diff --git "a/4301.jsonl" "b/4301.jsonl" new file mode 100644--- /dev/null +++ "b/4301.jsonl" @@ -0,0 +1,736 @@ +{"seq_id":"21061841","text":"from bs4 import BeautifulSoup\nfrom string import Template\nimport sys\nimport requests\nimport aiohttp\nimport asyncio\nimport random\nimport webbrowser\nimport os,time\nfrom useragents import USER_AGENT_LIST\n\n\nclass DramaHighScoreAlerter:\n '''it finds all dramas aired currently then finds their scores from douban, \n show the results that have the score higher than or equal to the 'highscore' argument. \n \n it has 2 modes: sync(using requests) and async(using aiohttp and asyncio).\n async is much faster but likely to trigger douban's anti-spider system, \n so for personal usage, sync is preferred. if async is used, set a proper concurrent \n connection number\n \n command line usage:\n python highscorealerts.py `highscore` `sync` `connections`\n \n command line examples:\n \n python highscorealerts.py \n python highscorealerts.py 8.5 \n python highscorealerts.py 8.5 1\n # async, concurrent connection number 5\n python highscorealerts.py 8.5 0 5 \n '''\n \n def __init__(self,highscore=8.5,sync=True,connections=5):\n '''only if sync is False, connections is used'''\n \n self.highscore = highscore\n self.sync = sync\n self.dramas = []\n self.scores = []\n self.alerts = []\n self.semaphore = asyncio.Semaphore(connections) \n \n def get_headers(self):\n # use a random user agent from a preset list\n USER_AGENT = random.choice(USER_AGENT_LIST)\n headers = {'user-agent': USER_AGENT}\n return headers\n \n def parse_dramas(self):\n '''parse all dramas that are active this week'''\n \n drama_site = r'https://www.meijutt.com/'\n html = requests.get(drama_site,headers=self.get_headers()).content\n soup = BeautifulSoup(html, 'html.parser')\n week = soup.select_one(\"div.r.week-day\")\n tabs = week.select(\".tabs-list\")\n dramas = []\n for tab in tabs:\n drama = tab.find_all('a')\n for d in drama:\n dramas.append(d)\n \n self.dramas = dramas\n \n async def _parse_score(self,drama):\n result = await self.parse_score_async(drama)\n if result is not None:\n self.scores.append(result)\n \n def parse_scores_async(self):\n loop = asyncio.get_event_loop()\n tasks = [self._parse_score(drama) for drama in self.dramas]\n loop.run_until_complete(asyncio.gather(*tasks))\n loop.close()\n \n def parse_scores_sync(self):\n for drama in self.dramas:\n result = self.parse_score_sync(drama)\n if result is not None:\n self.scores.append(result)\n \n def parse_scores(self):\n if self.sync:\n html = self.parse_scores_sync()\n else:\n html = self.parse_scores_async()\n\n def output_html(self):\n '''show alerts in browser'''\n \n tpl ='''\n \n %s\n %s\n \n '''\n rows = ''\n html = ''\n for score in self.alerts:\n rows += tpl % (score[2],score[0],score[1])\n with open('alerts_tpl.html','r') as f:\n html_tpl = f.read()\n html = html_tpl.replace('${rows}', rows)\n f.close()\n with open('alerts.html','w') as f:\n f.write(html)\n f.close()\n \n url = 'file://' + os.path.dirname(os.path.abspath(__file__)) + \"/alerts.html\"\n webbrowser.open(url)\n \n async def parse_score_async(self,drama):\n '''get the drama score from douban aync. it is much faster but likely to\n trigger douban anti spider system'''\n\n url,drama_name = self.parse_score_setup(drama)\n \n #limit asyncio concurrent number so it is less likely to get banned\n async with self.semaphore:\n async with aiohttp.ClientSession() as session:\n async with session.get(url, headers=self.get_headers(), timeout=10) as response:\n html = await response.read()\n return self.parse_result(html,drama_name)\n \n def parse_score_setup(self,drama):\n\n drama_site_search = r'https://www.douban.com/search?q=%s'\n\n splits = drama.get('title').split('第')\n \n if len(splits) > 1:\n splits[1] = '第' + splits[1]\n drama_name = (' ').join(splits).strip()\n \n url = drama_site_search % drama_name\n return url,drama_name\n \n def parse_score_sync(self,drama):\n '''get the drama score from douban the sync way, slower but less likely to get banned'''\n\n url,drama_name = self.parse_score_setup(drama)\n \n html = requests.get(url,headers=self.get_headers()).content\n return self.parse_result(html,drama_name)\n \n def handle_error(self,drama_name):\n #TODO unify different tranlation names of two sites\n #print(\"can't find %s\" % drama_name)\n pass\n \n def parse_result(self,html,drama_name):\n\n soup = BeautifulSoup(html, 'html.parser')\n result = soup.select_one('.result-list > .result')\n if result is None:\n self.handle_error(drama_name)\n return\n a = result.select_one('.title a')\n title = a.string.strip()\n drama_url = a.get('href')\n if title != drama_name:\n self.handle_error(drama_name)\n return \n\n rating =result.select_one('.rating-info span:nth-of-type(2)')\n if rating is None:\n self.handle_error(drama_name)\n return\n score = 0\n if rating.has_attr('class'):\n score = float(rating.string)\n\n return (drama_name,score,drama_url) \n \n def alert(self):\n self.parse_dramas()\n \n #test code\n start = time.time()\n #self.dramas = self.dramas[:18]\n\n self.parse_scores()\n \n end = time.time()\n print('it took %f seconds' % (end - start))\n \n self.alerts = [s for s in self.scores if s[1] >= self.highscore]\n self.output_html()\n \n\nif __name__== \"__main__\":\n\n highscore = 8.5\n sync = True\n semaphore = 5\n \n if (len(sys.argv) >= 2):\n try:\n highscore = float(sys.argv[1])\n if (len(sys.argv) >= 3):\n try:\n sync = bool(int(sys.argv[2]))\n except Exception as e:\n pass\n if (len(sys.argv) >= 4):\n try:\n semaphore = int(sys.argv[3])\n except Exception as e:\n pass\n \n except Exception as e:\n pass\n \n alerter = DramaHighScoreAlerter(highscore=highscore,sync=sync,connections=semaphore)\n alerter.alert()\n \n\n \n\n ","sub_path":"highscorealerts.py","file_name":"highscorealerts.py","file_ext":"py","file_size_in_byte":6864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"375660016","text":"import sys\nimport time\nimport requests\n\n\ndef pb_report(i, n):\n j = (i + 1) / n\n sys.stdout.write(\"\\r\")\n sys.stdout.write(\"[%-20s] %d%%\" % (\"=\" * int(20 * j), 100 * j))\n sys.stdout.flush()\n\n\ndef get_request(url):\n import random\n\n sleep_time = 0\n while True:\n try:\n response = requests.get(url)\n break\n except Exception as e:\n print(e)\n rand = random.randint(0, 10)\n time.sleep(rand)\n sleep_time += rand\n if sleep_time > 60:\n return None\n if response.status_code == 200:\n try:\n return response.json()\n except Exception as e:\n print(e)\n return None\n\n\ndef flatten_list(list_of_lists):\n if len(list_of_lists) == 0:\n return list_of_lists\n if isinstance(list_of_lists[0], list):\n return flatten_list(list_of_lists[0]) + flatten_list(list_of_lists[1:])\n return list_of_lists[:1] + flatten_list(list_of_lists[1:])\n","sub_path":"baseball-data-etl/etl/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"531250982","text":"# --------------------------------------------------------\n# Motion R-CNN\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Simon Meister\n# --------------------------------------------------------\nfrom __future__ import absolute_import, division, print_function\n\nimport sys\nimport os\nimport glob\nimport shutil\n\nimport numpy as np\nimport PIL.Image as Image\nfrom PIL import ImageDraw\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\nfrom cityscapesscripts.helpers.labels import trainId2label\n\nfrom object_detection.data_decoders.tf_example_decoder import TfExampleDecoder\nfrom object_detection.utils.flow_util import flow_to_color, flow_error_image, flow_error_avg\nfrom object_detection.utils.np_motion_util import dense_flow_from_motion, q_rotation_angle\nfrom object_detection.utils.visualization_utils import visualize_flow\n\n\nwith tf.Graph().as_default():\n file_pattern = 'object_detection/data/records/mytest/vkitti_val/00000-of-00000.record'\n #file_pattern = 'object_detection/data/records/vkitti_train/00000-of-00020.record'\n tfrecords = glob.glob(file_pattern)\n\n with tf.device('/cpu:0'):\n filename_queue = tf.train.string_input_producer(\n tfrecords, capacity=len(tfrecords))\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n example = TfExampleDecoder().decode(serialized_example)\n flow_color = flow_to_color(tf.expand_dims(example['groundtruth_flow'], 0))[0, :, :, :]\n print(example.keys())\n\n sess = tf.Session()\n init_op = tf.group(\n tf.global_variables_initializer(),\n tf.local_variables_initializer())\n\n sess.run(init_op)\n\n tf.train.start_queue_runners(sess=sess)\n out_dir = 'object_detection/output/tests/vkitti/'\n if os.path.isdir(out_dir):\n shutil.rmtree(out_dir)\n os.makedirs(out_dir)\n with sess.as_default():\n for i in range(100):\n example_np, flow_color_np = sess.run([example, flow_color])\n img_id_np = i #example_np['filename']\n image_np = example_np['image']\n gt_boxes_np = example_np['groundtruth_boxes']\n gt_classes_np = example_np['groundtruth_classes']\n gt_masks_np = example_np['groundtruth_instance_masks']\n height, width = image_np.shape[:2]\n num_instances_np = gt_masks_np.shape[0]\n image_np = np.squeeze(image_np)\n depth_np = example_np['groundtruth_depth']\n gt_motions_np = example_np['groundtruth_instance_motions']\n\n composed_flow_color_np, flow_error_np = visualize_flow(\n depth_np,\n gt_motions_np,\n np.ones([gt_motions_np.shape[0]]),\n example_np['groundtruth_camera_motion'],\n example_np['camera_intrinsics'],\n masks=gt_masks_np,\n groundtruth_flow=example_np['groundtruth_flow'])\n\n # motion gt summary\n gt_q = gt_motions_np[:, :4]\n gt_trans = gt_motions_np[:, 4:7]\n mean_rot_angle = np.mean(np.degrees(q_rotation_angle(gt_q)))\n mean_trans = np.mean(np.linalg.norm(gt_trans))\n cam_moving = example_np['groundtruth_camera_motion'][-1]\n\n print('image_id: {}, instances: {}, shape: {}, rot(deg): {}, trans: {}, moving: {}'\n .format(img_id_np, num_instances_np, image_np.shape, mean_rot_angle, mean_trans,\n cam_moving))\n\n # overlay masks\n for i in range(gt_boxes_np.shape[0]):\n label = trainId2label[gt_classes_np[i]]\n mask = np.expand_dims(gt_masks_np[i, :, :], 2)\n image_np += (0.5 * mask * np.array(label.color)).astype(np.uint8)\n # draw boxes\n im = Image.fromarray(image_np)\n imd = ImageDraw.Draw(im)\n for i in range(gt_boxes_np.shape[0]):\n label = trainId2label[gt_classes_np[i]]\n name = 'car' if gt_classes_np[i] == 1 else 'van'\n if gt_motions_np[i, 10] < 0.5:\n name = name + '_static'\n color = 'rgb({},{},{})'.format(*label.color)\n pos = gt_boxes_np[i, :]\n y0 = pos[0] * height\n x0 = pos[1] * width\n y1 = pos[2] * height\n x1 = pos[3] * width\n imd.rectangle([x0, y0, x1, y1], outline=color)\n imd.text(((x0 + x1) / 2, y1), name, fill=color)\n\n depth_im = Image.fromarray(np.squeeze(\n depth_np * 255 / 655.3).astype(np.uint8))\n flow_im = Image.fromarray(np.squeeze(\n flow_color_np * 255).astype(np.uint8))\n composed_flow_im = Image.fromarray(np.squeeze(\n composed_flow_color_np * 255).astype(np.uint8))\n flow_error_im = Image.fromarray(np.squeeze(\n flow_error_np * 255).astype(np.uint8))\n next_im = Image.fromarray(np.squeeze(example_np['next_image']))\n\n im.save(os.path.join(out_dir, str(img_id_np) + '_image1.png'))\n next_im.save(os.path.join(out_dir, str(img_id_np) + '_image2.png'))\n depth_im.save(os.path.join(out_dir, str(img_id_np) + '_depth.png'))\n flow_im.save(os.path.join(out_dir, str(img_id_np) + '_flow.png'))\n composed_flow_im.save(os.path.join(out_dir, str(img_id_np) + '_flow_from_motion.png'))\n flow_error_im.save(os.path.join(out_dir, str(img_id_np) + '_error.png'))\n sess.close()\n","sub_path":"object_detection/create_vkitti_tf_record_test.py","file_name":"create_vkitti_tf_record_test.py","file_ext":"py","file_size_in_byte":5545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"151709617","text":"# -*- coding: utf-8 -*-\nimport pygame\nfrom pygame.locals import *\nimport Fighter\nfrom shot import *\nfrom Leaser import *\n\n\n\nSCR_RECT = Rect(0,0,1200,600)\n\nclass Beast(Fighter.Fighter):\n def __init__(self,hp=1000,attack=200,speed=40):\n Fighter.Fighter.__init__(self,hp,attack,speed)\n self.rect.left = SCR_RECT.left\n self.rect.bottom = SCR_RECT.height/2\n self.reload_timer = 0\n self.level = \"Error\"\n self.prelevel = 1\n self.killpoint =0\n self.sysfont = pygame.font.SysFont(None,50)\n\n def update(self):\n\n pressed_keys = pygame.key.get_pressed()\n\n if pressed_keys[K_LEFT]:\n self.rect.move_ip(-self.speed,0)\n elif pressed_keys[K_RIGHT]:\n self.rect.move_ip(self.speed,0)\n elif pressed_keys[K_UP]:\n self.rect.move_ip(0,-self.speed)\n elif pressed_keys[K_DOWN]:\n self.rect.move_ip(0,self.speed)\n self.rect.clamp_ip(SCR_RECT)\n \n \n if pressed_keys[K_SPACE]:\n\n if self.reload_timer >0:\n self.reload_timer -= 1\n \n else:\n Leaser(self.rect.center)\n self.reload_timer = Leaser.reload_time\n\n def draw(self,screen,killpoint):\n level = self.sysfont.render(\"Kill:\"+str(killpoint)+\" Level: Error HP:\"+str(self.hp)+\" Attack:\"+str(self.attack)+\" Speed:\"+str(self.speed),True,(0,0,0))\n screen.blit(level,(280,610))\n \n","sub_path":"Beast.py","file_name":"Beast.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"55609372","text":"#!/usr/bin/env python\nimport math\nimport numpy as np\n\nfrom FireROOT.Analysis.Events import *\nfrom FireROOT.Analysis.Utils import *\n\nclass MyEvents(ProxyEvents):\n def __init__(self, files=None, type='MC', maxevents=-1, channel=['2mu2e', '4mu'], **kwargs):\n super(MyEvents, self).__init__(files=files, type=type, maxevents=maxevents, channel=channel, **kwargs)\n self.KeepCutFlow=True\n\n def processEvent(self, event, aux):\n if aux['channel'] not in self.Channel: return\n chan = aux['channel']\n cutflowbin = 5\n\n self.Histos['{}/cutflow'.format(chan)].Fill(cutflowbin, aux['wgt']); cutflowbin+=1\n\n lj, proxy = aux['lj'], aux['proxy']\n if not lj.passCosmicVeto(event): return\n if abs(proxy.dz(event))>40: return\n self.Histos['{}/cutflow'.format(chan)].Fill(cutflowbin, aux['wgt']); cutflowbin+=1\n\n mind0s = []\n if lj.isMuonType() and not math.isnan(lj.pfcand_tkD0Min):\n mind0s.append( lj.pfcand_tkD0Min*1e4 )\n mind0s.append( abs(proxy.d0(event))*1e4 )\n\n self.Histos['{}/proxyd0inc'.format(chan)].Fill( abs(proxy.d0(event))*1e4, aux['wgt'])\n self.Histos['{}/muljd0inc'.format(chan)].Fill( lj.pfcand_tkD0Min*1e4, aux['wgt'])\n self.Histos['{}/maxd0inc'.format(chan)].Fill( max(mind0s), aux['wgt'])\n\n nbtight, nbmedium = 0, 0\n for s, j in zip(event.hftagscores, event.ak4jets):\n if not (j.jetid and j.p4.pt()>30 and abs(j.p4.eta())<2.5): continue\n if (s.DeepCSV_b&(1<<2))==(1<<2): nbtight += 1\n if (s.DeepCSV_b&(1<<1))==(1<<1): nbmedium += 1\n\n\n dphi = abs(DeltaPhi(lj.p4, proxy.p4))\n\n\n self.Histos['{}/nbtight'.format(chan)].Fill(nbtight, aux['wgt'])\n self.Histos['{}/nbmedium'.format(chan)].Fill(nbmedium, aux['wgt'])\n if nbtight==0: return\n self.Histos['{}/cutflow'.format(chan)].Fill(cutflowbin, aux['wgt']); cutflowbin+=1\n\n\n self.Histos['{}/proxyd0'.format(chan)].Fill( abs(proxy.d0(event))*1e4, aux['wgt'])\n self.Histos['{}/muljd0'.format(chan)].Fill( lj.pfcand_tkD0Min*1e4, aux['wgt'])\n self.Histos['{}/maxd0'.format(chan)].Fill( max(mind0s), aux['wgt'])\n\n if lj.pfcand_tkD0Min*1e4 > 100:\n self.Histos['{}/dphi_100'.format(chan)].Fill(dphi, aux['wgt'])\n self.Histos['{}/dphiIso2Dpre'.format(chan)].Fill(dphi, lj.pfiso(), aux['wgt'])\n if lj.pfcand_tkD0Min*1e4 > 200:\n self.Histos['{}/dphi_200'.format(chan)].Fill(dphi, aux['wgt'])\n if lj.pfcand_tkD0Min*1e4 > 300:\n self.Histos['{}/dphi_300'.format(chan)].Fill(dphi, aux['wgt'])\n if lj.pfcand_tkD0Min*1e4 > 400:\n self.Histos['{}/dphi_400'.format(chan)].Fill(dphi, aux['wgt'])\n if lj.pfcand_tkD0Min*1e4 > 500:\n self.Histos['{}/dphi_500'.format(chan)].Fill(dphi, aux['wgt'])\n self.Histos['{}/dphiIso2Dinit'.format(chan)].Fill(dphi, lj.pfiso(), aux['wgt'])\n\n if lj.pfcand_tkD0Min*1e4 < 1000: return\n self.Histos['{}/cutflow'.format(chan)].Fill(cutflowbin, aux['wgt']); cutflowbin+=1\n\n self.Histos['{}/proxyiso'.format(chan)].Fill(proxy.pfiso(), aux['wgt'])\n self.Histos['{}/muljiso'.format(chan)].Fill(lj.pfiso(), aux['wgt'])\n self.Histos['{}/maxiso'.format(chan)].Fill(max(lj.pfiso(), proxy.pfiso()), aux['wgt'])\n\n self.Histos['{}/dphi'.format(chan)].Fill(dphi, aux['wgt'])\n\n self.Histos['{}/dphiIso2D'.format(chan)].Fill(dphi, lj.pfiso(), aux['wgt'])\n\n\n def postProcess(self):\n super(MyEvents, self).postProcess()\n\n for ch in self.Channel:\n xaxis = self.Histos['{}/cutflow'.format(ch)].axis(0)\n\n labels = [ch, 'ljcosmicveto_pass', 'bjet_ge1', 'mind0_pass',]\n\n for i, s in enumerate(labels, start=6):\n xaxis.SetBinLabel(i, s)\n # binNum., labAngel, labSize, labAlign, labColor, labFont, labText\n xaxis.ChangeLabel(i, 315, -1, 11, -1, -1, s)\n\n for k in self.Histos:\n if 'phi' not in k: continue\n xax = self.Histos[k].axis(0)\n decorate_axis_pi(xax)\n if '2D' in k:\n self.Histos[k].yaxis.SetNdivisions(-210)\n\n\n\nhistCollection = [\n {\n 'name': 'nbtight',\n 'binning': (5, 0, 5),\n 'title': 'Num. tight bjets;Num.bjets;counts'\n },\n {\n 'name': 'nbmedium',\n 'binning': (5, 0, 5),\n 'title': 'Num. medium bjets;Num.bjets;counts'\n },\n {\n 'name': 'proxyd0inc',\n 'binning': (50, 0, 2500),\n 'title': 'proxy muon |d_{0}|;|d_{0}| [#mum];Events'\n },\n {\n 'name': 'muljd0inc',\n 'binning': (50, 0, 2500),\n 'title': 'muon type lepton-jet minimum |d_{0}|;|d_{0}| [#mum];Events'\n },\n {\n 'name': 'maxd0inc',\n 'binning': (50, 0, 2500),\n 'title': 'max(proxy,lj) |d_{0}|;|d_{0}| [#mum];Events'\n },\n {\n 'name': 'proxyd0',\n 'binning': (50, 0, 2500),\n 'title': 'proxy muon |d_{0}|(N_{bjet}#geq1);|d_{0}| [#mum];Events'\n },\n {\n 'name': 'muljd0',\n 'binning': (50, 0, 2500),\n 'title': 'muon type lepton-jet minimum |d_{0}|(N_{bjet}#geq1);|d_{0}| [#mum];Events'\n },\n {\n 'name': 'maxd0',\n 'binning': (50, 0, 2500),\n 'title': 'max(proxy,lj) |d_{0}|(N_{bjet}#geq1);|d_{0}| [#mum];Events'\n },\n {\n 'name': 'proxyiso',\n 'binning': (20, 0, 0.5),\n 'title': 'proxy isolation;iso;counts'\n },\n {\n 'name': 'muljiso',\n 'binning': (20, 0, 0.5),\n 'title': 'lepton-jet isolation;iso;counts'\n },\n {\n 'name': 'maxiso',\n 'binning': (20, 0, 0.5),\n 'title': 'max iso(lepton-jet, proxy muon);iso;counts'\n },\n {\n 'name': 'dphi_100',\n 'binning': (20, 0, M_PI),\n 'title': '|#Delta#phi|(lepton-jet, proxy muon) (LJ |d_{0}|>100#mum);|#Delta#phi|;counts/#pi/20'\n },\n {\n 'name': 'dphi_200',\n 'binning': (20, 0, M_PI),\n 'title': '|#Delta#phi|(lepton-jet, proxy muon) (LJ |d_{0}|>200#mum);|#Delta#phi|;counts/#pi/20'\n },\n {\n 'name': 'dphi_300',\n 'binning': (20, 0, M_PI),\n 'title': '|#Delta#phi|(lepton-jet, proxy muon) (LJ |d_{0}|>300#mum);|#Delta#phi|;counts/#pi/20'\n },\n {\n 'name': 'dphi_400',\n 'binning': (20, 0, M_PI),\n 'title': '|#Delta#phi|(lepton-jet, proxy muon) (LJ |d_{0}|>400#mum);|#Delta#phi|;counts/#pi/20'\n },\n {\n 'name': 'dphi_500',\n 'binning': (20, 0, M_PI),\n 'title': '|#Delta#phi|(lepton-jet, proxy muon) (LJ |d_{0}|>500#mum);|#Delta#phi|;counts/#pi/20'\n },\n {\n 'name': 'dphi',\n 'binning': (20, 0, M_PI),\n 'title': '|#Delta#phi|(lepton-jet, proxy muon);|#Delta#phi|;counts/#pi/20'\n },\n {\n 'name': 'dphiIso2Dpre',\n 'binning': (20, 0, M_PI, 20, 0, 0.5),\n 'title': '|#Delta#phi| vs muon-type lepton-jet isolation;|#Delta#phi|;iso',\n },\n {\n 'name': 'dphiIso2Dinit',\n 'binning': (20, 0, M_PI, 20, 0, 0.5),\n 'title': '|#Delta#phi| vs muon-type lepton-jet isolation;|#Delta#phi|;iso',\n },\n {\n 'name': 'dphiIso2D',\n 'binning': (20, 0, M_PI, 20, 0, 0.5),\n 'title': '|#Delta#phi| vs muon-type lepton-jet isolation;|#Delta#phi|;iso',\n },\n]","sub_path":"Analysis/python/processing/proxy/proxy_4mu.py","file_name":"proxy_4mu.py","file_ext":"py","file_size_in_byte":7314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"259797079","text":"#!python3\n\n# https://projecteuler.net/problem=20\n# \"Factorial digit sum\"\n# Find the sum of the digits in the number 100!.\n\nproduct = 1\nfor n in range(1,101):\n\tproduct *= n\nprint(sum([int(digit) for digit in list(str(product))]))","sub_path":"ProjectEuler/p020.py","file_name":"p020.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"88275161","text":"import json\nimport psycopg2\nimport os\nconn = psycopg2.connect(database = \"ethereum\",user=\"gpadmin\",password=\"123456\",host=\"192.168.1.2\",port=\"5432\")\n\npath = '/root/2017Dataset/'\n\n\n\nif not os.path.exists(path):\n\tos.mkdir(path)\nwith open('/root/2017Dataset.json','r') as f:\n\tcontracts = json.load(f)\ncnt = 0\nfor contract in contracts:\n\taddr = contract[0]\n\tcursor = conn.cursor()\n\tsql = \"select code from code where address =\\'%s\\'\"%addr\n\tcursor.execute(sql)\n\ttry:\n\t\tcode = cursor.fetchall()[0][0]\n\t\tcontract_path = '%s%02d-%s/'%(path,cnt,addr)\n\t\tif not os.path.exists(contract_path):\n\t\t\tos.mkdir(contract_path)\n\texcept Exception as e:\n\t\tprint(e)\n\t\tcontinue\n\tif code.startswith('0x'):\n\t\tcode = code[2:]\n\twith open(contract_path+'%02d-%s.bytecode'%(cnt,addr),'w') as w:\n\t\tw.write(code)\n\tcursor.close()\n\tcnt+=1\n\t\t\n\t\n","sub_path":"script/select2017Code.py","file_name":"select2017Code.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"151449347","text":"#@+leo-ver=5-thin\n#@+node:martin.20160905121823.2: * @file ./common/software/PC/src/event_detection_NN/processing_NN_detection.py\n#@@language python\n\n#@+others\n#@+node:martin.20160505171035.1: ** docs\n#Fireball detection using Neural Network script\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Version 1.0\n# Purpose: This script is an implementation of a neural network\n# to detect meteors in sky images once the filter has\n# been applied to the raw images.\n# Jean Deshayes\n# Curtin University\n# modified somewhat by Martin Towner\n# Curtin University\n\n# usage for detection:\n# python NN_fireball_detection.py /dir/pics (Nb hidden units=10,\n# lambda=0.00256, detection=1, Dataset Nb=11)\n\n\n\n## /dir/pics : Path to pictures directory. PICTURES MUST BE LABELLED as \"NB_DATE_TIME_DSC_ID.[...].jpg\"\n## detection :If detection is enabled (1), the code will run the detection process hence\n## feedforward propagation through the neural network. Otherwise, if 0 is entered,\n## the network will be created from the given hyperparameters and will start\n## the learning process.\n## lambda :This is the value of the regularisation parameter. \n## Nb of hidden units: The number of units desired in the hidden layer\n## Dataset Nb: The dataset number to use to train network. 11 is the default because it\n## it was the last dataset created\n## iterations: Maximum number of iterations used for learning\n## ROC: Plot roc curves\n## CONFMATRIX: Display confusion matrices\n\n### TODO\n# remove requirement for file name of specific format, as they might be thumb.masked.jpg\n# replace saving procedures with library functions\n#### import event detection code list generation and use that for files to do\n### stoptime not implemented\n# slow moving object removal is very simple\n\n#@+node:martin.20160505170929.2: ** imports\nimport datetime\nimport logging\nimport sys\nimport os\nimport cv2\n\nimport fcntl # for flock\n\nimport scipy.ndimage\nimport numpy as np\nfrom PIL import Image\n\nimport dfn_functions as dfn\nfrom NN import * #Import Neural Network functions\nfrom preFilter import * #Import preprocessing functions\nfrom performance import * #Import preprocessing functions\n#@+node:martin.20160505170929.4: ** main_function\ndef main_function( args, save_settings, config_dict, stop_time):\n \"\"\" args explanation:\n could be a '/path/to/dir', or can be a list of settings\n see docs\n \"\"\"\n #@+others\n #@+node:martin.20160505171405.1: *3* settings\n #Settings constant variables\n settings = {}\n #a tracking number to decide if to reprocess older directories with new settings\n settings['algorithm_version'] = 1.06\n #tile size\n settings['boxsize'] = 25\n ###?\n settings['tiles_for_pools'] = (4,8)\n #@+node:martin.20160505172140.1: *3* init\n #Retrieve data passed by user\n #args could be just a '/path/to/dir', or could be a list of arguments\n if not isinstance(args, basestring):\n dirName = args[0]\n else:\n dirName = args\n args = [args]\n H = int(args[1]) if len(args) >= 2 else 10 \n LAMBDA = float(args[2]) if len(args) >= 3 else 0.00256 \n #obsolete arg, keep for backward compatibility\n DETECTION = int(args[3]) if len(args) >= 4 else 1 \n DATASET = int(args[4]) if len(args) >= 5 else 11\n\n local_path = dirName\n PATH = os.path.dirname( os.path.realpath(__file__))\n #Folder with the datasets to train the network\n DATAFOLDER = os.path.join( PATH, \"..\", \"Dataset\" )\n #Initialise Neural Network\n archi = (settings['boxsize'] * settings['boxsize'], H, 1)\n #print( \"Architecture : {0}\".format(archi) )\n #Set default weights to use\n local_fname = \"Filter11_\" + str(settings['boxsize']) + \"x\"\n local_fname += str(settings['boxsize']) + \"_\" + str(H) + \"_\" + str(LAMBDA)\n fileName = os.path.join( PATH, local_fname )\n fileExist = os.path.isfile( fileName + \".npy\")\n NN = Neural_Network( Lambda = LAMBDA, architecture = archi,\n fileExist = fileExist, fileName = fileName)\n\n\n #@+node:martin.20160505172204.1: *3* logfile and file lock\n #@+others\n #@+node:martin.20160609123245.1: *4* logfile\n #logfile\n log_file = os.path.join( dirName, dfn.log_name() + 'processing.txt' )\n logging.basicConfig( filename=log_file, level=logging.INFO,\n format='%(asctime)s, %(levelname)s, %(module)s, %(message)s')\n logger = logging.getLogger()\n ###logger.setLevel( logging.DEBUG) ###\n logger.info(\"begin_event_detection_NN, \" + dirName)\n logger.info(\"algorithm version, %f\" % settings['algorithm_version'])\n logger.info(\"tile size, %d\" % settings['boxsize']) \n logger.info(\"architecture of neural network, %d, %d, %d\" % (archi[0],archi[1],archi[2]))\n logger.info(\"regularisation parameter, %f\" % LAMBDA)\n #@+node:martin.20160609121524.1: *4* file lock\n #check if dir is already processing/lockfile\n trans_status_file = os.path.join( local_path, 'transfer_status.txt')\n if not os.path.isfile( trans_status_file):\n #no status.txt, so this is current dir for interval control, or\n # not a relevant dir\n return True\n # lock file using at mode so not to overwrite existing\n # https://stackoverflow.com/questions/220525/ensuring-a-single-instance-\n # of-an-application-in-linux#221159\n fp = open(trans_status_file, 'at')\n try:\n fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)\n except IOError as e: # another event_detect is running on this dir\n print( 'trans_file_already_locked, ' + str(e) )\n # print( 'trans_file_already_locked, ' + str(e) )\n return True\n #@-others\n\n #use config name not name() so that we can run on other machines\n namestr = '#' + ','.join( [config_dict['station']['hostname'],\n str(config_dict['station']['lon']),\n str(config_dict['station']['lat']),\n str(config_dict['station']['altitude'])] ) + '\\n'\n #@+node:martin.20160505172402.1: *3* detection\n #Reading all the images in the folder\n fileName = [ f for f in os.listdir(dirName) \n if (f.lower().endswith(\".jpg\")\n and not 'tile' in f.lower()\n and not 'daily' in f.lower()) ]\n fileName.sort()\n posDir = dirName\n #@+<>\n #@+node:martin.20160508124533.1: *4* <>\n #initialise structure to check for slow moving objects\n #98 = 4912/25/2, 147 = 7360/25/2\n #list of coords of 1 events [[x,y],[x,y], [x,y]....]\n grid_coord_curr = [] #np.zeros( (98,147) ) #Coordinates tiles in current image\n grid_coord_prev1 = [] #Coordinates tiles in previous image\n grid_coord_prev2 = []\n # prev1_recon_img = np.zeros((2,2)) #Initialise array for checked image\n first_image_sequence = 0\n #@-<>\n for j in range(0,len(fileName)-1):\n #@+<>\n #@+node:martin.20160505174337.1: *4* <>\n #Open images\n logger.debug( 'images, %s, %s' % (fileName[j],fileName[j+1]))\n varName1 = fileName[j].split('_')\n varName2 = fileName[j+1].split('_')\n time1 = datetime.datetime.strptime( varName1[1] + ' ' + varName1[2], '%Y-%m-%d %H%M%S')\n time2 = datetime.datetime.strptime( varName2[1] + ' ' + varName2[2], '%Y-%m-%d %H%M%S')\n #@-<>\n #Check if time between previous and current picture less near 30 seconds\n if (time2-time1).seconds < 40:\n #@+<>\n #@+node:martin.20160505174428.1: *4* <> load and filter\n logger.debug( \"processing, %s\" % (fileName[j+1]) )\n img1=cv2.imread( os.path.join( dirName, fileName[j]) )\n img2=cv2.imread( os.path.join( dirName, fileName[j+1]) )\n #Use green channel only\n #Convert image from uint8 to int16 (Enable substraction of matrices) \n img1 = img1[:,:,1].astype( np.int16)\n img2 = img2[:,:,1].astype( np.int16)\n #Apply filter\n f = metFilter( img1, img2,\n #dirName, \n fileName[j+1],\n radius=10, tilessettings = settings['tiles_for_pools'] ) \n #Split image into tiles\n X = np.asarray( f.splitToTiles( (settings['boxsize'],settings['boxsize']) ))\n logger.debug('len x, ' + str(len(X)) )\n logger.debug('len f, ' + str(f.nameSplit) )\n #X is array of tiles. Normalise array\n X = X / 255.0\n #@-<>\n #Save coordinates of tiles in 2 previous images\n grid_coord_prev2 = grid_coord_prev1\n grid_coord_prev1 = grid_coord_curr\n grid_coord_curr = [] #np.zeros( (98,147) )\n grid_coord_curr_idx = []\n if len(X) != 0: \n #Execute feed forward propagation on all potential tiles\n allOutputs = NN.forward(X)\n logger.debug( 'len all outputs, ' + str(len( allOutputs)) )\n for i in range(len(allOutputs)):\n logger.debug( 'output, ' + str(allOutputs[i]) )\n #### some sort of threshold to remove weaker positive tiles?\n coord = f.nameSplit[i].rsplit('_',2)[1:]\n logger.debug( 'output coords, ' + str( coord) )\n if allOutputs[i] + 0.5 > 1.00:\n logger.debug( 'add tiles to list, ' + str( coord) )\n grid_coord_curr.append( (int(coord[0]), int(coord[1])) )\n grid_coord_curr_idx.append( i)\n else : #negative tiles\n logger.debug('negative tile, ' + str(coord) )\n #done all tiles, remove duplicates (which shouldn't occur anyway)\n #grid_coord_curr = list(set(grid_coord_curr))\n #@+<>\n #@+node:martin.20160508222352.1: *4* <>\n #remove tile from list if it in 3 consecutive images\n grid_coord_curr_cln = []\n for crd in grid_coord_curr:\n if not crd in grid_coord_prev1 and not crd in grid_coord_prev2:\n grid_coord_curr_cln.append( crd)\n else:\n logger.debug('slow object removed, %i, %i' % (crd[0], crd[1]) )\n grid_coord_curr = grid_coord_curr_cln\n #@-<>\n if len(grid_coord_curr) > 0:\n #@+<>\n #@+node:martin.20160505174741.1: *4* <>\n #start event file\n evtfname = os.path.join( dirName, \n fileName[j+1][:-4] + '.raw_pixels.txt' )\n headstr = '#datetime, x, y, -dx, +dx, -dy, +dy, brightness, -b, +b\\n'\n with open( os.path.join(dirName, evtfname), 'at') as myFile:\n myFile.write( namestr)\n myFile.write( headstr)\n \n for i in range(len(grid_coord_curr)):\n crd_pair = grid_coord_curr[i]\n img_idx = grid_coord_curr_idx[i]\n y = crd_pair[0]\n x = crd_pair[1]\n logger.debug('curr_coord_event_seen,' + str( crd_pair) )\n #save event file\n xcoord = x*settings['boxsize']*2\n ycoord = y*settings['boxsize']*2\n with open( os.path.join(dirName, evtfname), 'a') as myFile:\n now = dfn.exposure_time( os.path.join(dirName, fileName[j+1]) )\n now_iso = datetime.datetime.utcfromtimestamp( now).isoformat()\n myFile.write( now_iso + ', ' + \n str(ycoord) + ', ' + str(xcoord) + ', ' +\n '1.0, 1.0, 1.0, 1.0, 100, 1.0, 1.0\\n' )\n #write event to log file\n logger.info(\"event, %s, [%d %d]\" % (fileName[j+1], ycoord, xcoord) )\n #save individual tile\n if save_settings['save_tiles'] == '1':\n fname_w_coords = '_'.join( f.nameSplit[i].split('_')[:-2] )\n fname_w_coords = '.'.join( [fname_w_coords, str(xcoord), \n str(ycoord), 'tile.jpg' ] )\n\n tmp_img = scipy.misc.toimage(X[img_idx].reshape((settings['boxsize'],\n settings['boxsize'])),\n cmin = 0,\n cmax = 1)\n #mirror diagnonally = rot 90 clock + horiz flip\n # tmp_img = tmp_img.transpose( Image.ROTATE_180)\n # tmp_img = tmp_img.transpose( Image.FLIP_LEFT_RIGHT)\n #print('rescaling, ', crd_pair, fname_w_coords)\n width, height = tmp_img.size\n tmp_img = tmp_img.resize((2*width,2*height), Image.BILINEAR )\n tmp_img.save( os.path.join( posDir,fname_w_coords) )\n logger.debug('saved_tile, ' + os.path.join( posDir,fname_w_coords) )\n else:\n logger.debug('not_save_tile, ' + os.path.join( posDir,fname_w_coords) )\n #@-<>\n else:\n logger.debug( 'all removed')\n else: #time diff too big\n logger.debug(\"ignored, %s, time difference with previous image, %d\\n\"\n % (fileName[j+1], (time2-time1).seconds) )\n #@+<>\n #@+node:martin.20160508124700.1: *4* <>\n #set new beginning for slow objects due to large time difference\n first_image_sequence = j\n grid_coord_prev1 = []\n grid_coord_prev2 = []\n #Set the values of checked array to 0\n #prev1_recon_img = np.zeros( (curr_recon_img.shape[0],\n # curr_recon_img.shape[1]) )\n #@-<>\n logger.info(\"processed, %s, version, %f\" % \n (fileName[j+1], settings['algorithm_version']) ) \n\n #@+node:martin.20160609121416.1: *3* final\n #flock remove not needed, done automatically as fp closed\n fp.close()\n #now = datetime.datetime.utcfromtimestamp( time.time()).isoformat()\n now = str( datetime.datetime.utcnow().isoformat())\n dfn.write_string_to_file( 'done, ' + now + '\\n', trans_status_file, 'wt')\n # make sure combo log file is now blank so that dir \n # is considered new for triangulation\n dfn.write_string_to_file( '',\n os.path.join( local_path, 'double_combo_log.txt'), \n 'wt')\n logger.info( 'event_detection_done, '+ str(settings['algorithm_version']) )\n #@-others\n \n#@-others\n\nif __name__ == '__main__':\n #logging.basicConfig()\n np.set_printoptions(linewidth=999999) #Increase limit of line width of the shell\n np.set_printoptions(threshold='nan') #Remove threshold to display unlimitted array sizes\n\n #Set parameters given through command line\n args = sys.argv[1:]\n # if len(args)>=1:\n # dirName=args[0]\n # else: #Open window to allow user to select a directory to browse\n # print( \"Detection mode enabled by default. Set detection variable to 0 for training\")\n # root = Tkinter.Tk()\n # dirName = tkFileDialog.askdirectory(parent=root,initialdir=\"/\",title='Please select the folder of images desired to be processed')\n # if len(dirName ) > 0:\n # print \"Browsing files in %s\" % dirName\n # root.destroy()\n # args=[dirname]\n\n config_dict = dfn.load_config( os.path.join( args[0], 'dfnstation.cfg') )\n \n #settings\n save_settings = {\n #Save positive tiles\n 'save_tiles': '1',\n #save blue/red thumbmail sketch of event\n 'save_thumb': '0' } \n main_function( args, save_settings, config_dict, 0)\n \n#@-leo\n","sub_path":"processing_NN_detection.py","file_name":"processing_NN_detection.py","file_ext":"py","file_size_in_byte":16491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"583475058","text":"##### QUESTION - AMICABLE NUMBERS ############################################\n# Let d(n) be defined as the sum of proper divisors of n (numbers less than n\n# which divide evenly into n).\n# If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and\n# each of a and b are called amicable numbers.\n#\n# For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55\n# and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71\n# and 142; so d(284) = 220.\n#\n# Evaluate the sum of all the amicable numbers under 10000.\n#\n################################################################################\n\n##### NOTES ##################################################################\n#\n################################################################################\n\n##### SOLUTION ###############################################################\n# Answer to problem = 31,626\n#\n################################################################################\n\nimport math\n\n# - Helper function to return the sum of all factors of a number\ndef get_factors_sum(num):\n factors_sum = 1\n\n for i in range(2, math.ceil(num / 2 + 1)):\n if num % i == 0:\n factors_sum += i\n\n return factors_sum\n\n# - Main function to sum up all amicable numbers\ndef amicable_number_sum(max):\n numbers = {}\n amicable_number_total = 0\n\n for i in range(2, max):\n numbers[i] = get_factors_sum(i)\n\n for number, num_factors_total in numbers.items():\n if (num_factors_total in numbers and\n numbers[num_factors_total] == number and\n num_factors_total != number):\n\n amicable_number_total += number\n\n return amicable_number_total\n\n\n##### TEST CASE ##############################################################\nprint (\"--- TEST CASE SHOULD BE TRUE ---\")\nprint (get_factors_sum(220) == 284)\nprint (get_factors_sum(284) == 220)\n\n##### SOLUTION ###############################################################\nprint (\"--- SOLUTION FOR AMICABLE NUMBERS PROBLEM IS ---\")\nprint (amicable_number_sum(10000))\n","sub_path":"001-025/021_amicablenumbers.py","file_name":"021_amicablenumbers.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"652453498","text":"def mergeSort(l):\n if len(l) <= 1:\n return l\n mid = len(l) // 2\n left = mergeSort(l[:mid])\n right = mergeSort(l[mid:])\n return merge(left, right)\n\n\ndef merge(left, right):\n if not left:\n return right\n if not right:\n return left\n\n result = [0] * (len(left) + len(right))\n\n p1 = p2 = 0\n\n while p1 < len(left) and p2 < len(right):\n if left[p1] < right[p2]:\n result[p1 + p2] = left[p1]\n p1 += 1\n else:\n result[p1 + p2] = right[p2]\n p2 += 1\n\n while p1 < len(left):\n result[p1 + p2] = left[p1]\n p1 += 1\n\n while p2 < len(right):\n result[p1 + p2] = right[p2]\n p2 += 1\n return result\n\nl = [1, 2, 2, 3, 4, 2, 12, 3, 12, 1, 23, 123, 2, 321, 21, 23, 2,\n 31, 2, 3, 12, 31, 23, 1, 32443, 65, 7, 56, 22, 34, 2, 221]\n\n\nprint(mergeSort(l))\n","sub_path":"CCI/10-sorting/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"447864623","text":"from pyramid.response import Response\nfrom pyramid.view import view_config\nfrom sqlalchemy.exc import DBAPIError\nfrom ..models import MyModel\nimport os\nfrom pyramid.httpexceptions import HTTPFound\nfrom pyramid.security import remember, forget\nfrom ..security import verify_user\n\n\nHERE = os.path.dirname(__file__)\n\nENTRIES_DATA = [\n {\n 'title': 'Day12',\n 'creation_date': 'August 23, 2016',\n 'body': 'Today, we learned about templating with Jinja, and about the binary tree data type. I spent most of the time revising old data structures, since it is not a good idea to coninue building upon something that is not perfect. I also got my journal site deployed with the templates working. Lastly, we formed project groups, and I will be working on my idea for a market analysis web application.'\n },\n]\n\n\n@view_config(route_name='login', renderer='../templates/login.jinja2')\ndef login(request):\n if request.method == 'GET':\n return {'bogus_attempt': False}\n if request.method == 'POST':\n username = str(request.params.get('user', ''))\n password = str(request.params.get('pass', ''))\n print('user/pass:', username, password)\n\n if verify_user(username, password):\n print('User verfied.')\n headers = remember(request, username)\n return HTTPFound(location=request.route_url('home'), headers=headers)\n return {'bogus_attempt': True}\n\n\n@view_config(route_name='logout', renderer='../templates/logout.jinja2')\ndef logout(request):\n headers = forget(request)\n return HTTPFound(request.route_url('home'), headers=headers)\n\n\n@view_config(route_name='detail', renderer='../templates/detail.jinja2')\ndef detail(request):\n \"\"\"Send individual entry for detail view.\"\"\"\n query = request.dbsession.query(MyModel)\n data = query.filter_by(id=request.matchdict['id']).first()\n return {\"entry\": data}\n\n\n@view_config(route_name='edit', renderer='../templates/edit.jinja2', permission='root')\ndef edit(request):\n \"\"\"Send individual entry to be edited.\"\"\"\n query = request.dbsession.query(MyModel)\n data = query.filter_by(id=request.matchdict['id']).one()\n data2 = {'id': data.id, 'body': data.body, 'creation_date': data.creation_date, 'title': data.title}\n updated = False\n # using data2 prevents data from being written to the db. Use data\n # to like data.body = req.... to change database (autocommit is on)\n if request.method == 'POST':\n updated = True\n data2['creation_date'] = request.POST['creation_date']\n data2['body'] = request.POST['body']\n data2['title'] = request.POST['title']\n\n #updating # comment out for testing\n data.body = data2['body']\n data.title = data2['title']\n data.creation_date = data2['creation_date']\n\n return {'entry': data2, 'updated': updated}\n\n\n@view_config(route_name='new', renderer='../templates/new.jinja2', permission='root')\ndef new(request):\n \"\"\"Return empty dict for new entry.\"\"\"\n goofed = {'goofed': 0}\n if request.method == 'GET':\n return {'entry': goofed}\n if request.method == 'POST':\n new_model = MyModel(title=request.POST['title'], body=request.POST['body'], creation_date=request.POST['creation_date'])\n if new_model.title == '' or new_model.body == '':\n goofed['goofed'] = 1\n return {'entry': goofed} # http exception here\n request.dbsession.add(new_model)\n return HTTPFound(request.route_url('home'))\n\n\n@view_config(route_name='home', renderer='../templates/index.jinja2')\ndef my_view(request):\n try:\n query = request.dbsession.query(MyModel)\n data_from_DB = query.order_by(MyModel.title).all()\n except DBAPIError:\n return Response(db_err_msg, content_type='text/plain', status=500)\n return {'entries': data_from_DB}\n\n\ndb_err_msg = \"\"\"\\\nPyramid is having a problem using your SQL database. The problem\nmight be caused by one of the following things:\n\n1. You may need to run the \"initialize_website_db\" script\n to initialize your database tables. Check your virtual\n environment's \"bin\" directory for this script and try to run it.\n\n2. Your database server may not be running. Check that the\n database server referred to by the \"sqlalchemy.url\" setting in\n your \"development.ini\" file is running.\n\nAfter you fix the problem, please restart the Pyramid application to\ntry it again.\n\"\"\"\n","sub_path":"website/views/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":4443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"399076178","text":"def bf(candidate, record, all_record, depth):\n if depth == 3:\n all_record.append(''.join(record + [record[0]]))\n else:\n for i in range(len(candidate)):\n if candidate[i]:\n record.append(chr(ord('a') + i))\n candidate[i] = False\n bf(candidate, record, all_record, depth+1)\n candidate[i] = True\n record.pop()\nall_record = []\nbf([True, True, True], [], all_record, 0)\nn = int(input())\nfirst = input().strip()\nsecond = input().strip()\nprint('YES')\n\"\"\"\nif first[0] == first[1] and second[0] == second[1]:\n print('abc'*n)\nelif first[0] != first[1] and second[0] != second[1]:\n union = set(first + second)\n if len(union) == 2:\n for i in 'abc':\n if i not in union:\n break\n print(first[0] * n + i * n + first[1] * n)\n else:\n\"\"\"\nhas_ans = False\nfor cand in all_record:\n if first not in cand and second not in cand:\n print(cand[:3]*n)\n has_ans = True\n break\n\nif not has_ans:\n if first[0] == second[0]:\n print(first[1]*n + second[1]*n + first[0]*n)\n elif first[1] == second[1]:\n print(first[1]*n + second[0]*n + first[0]*n)\n else:\n for c in 'abc':\n if c not in first:\n break\n print(first[0]*n + c*n + first[1]*n)\n","sub_path":"codeforce/582_div3/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"366375491","text":"import re, os\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nfrom Bio import Phylo\nfrom ete3 import Tree\nfrom subprocess import Popen, PIPE, STDOUT\nfrom pathlib import Path\nfrom reinforcement_model import INPUT_SIZE\n\n\nNUM_OF_NODES = np.sqrt(INPUT_SIZE)\nparent_path = Path().resolve().parent\nparent_folder = parent_path / \"reinforcement_data\"\n\nRAXML_NG_SCRIPT = \"raxml-ng\" # after you install raxml-ng on your machine\n# conda install -c bioconda raxml-ng\nMSA_PHYLIP_FILENAME = \"masked_species_real_msa.phy\"\n\n\ndef return_likelihood(tree, msa_file, rates, pinv, alpha, freq):\n\t\"\"\"\n\t:param tree: ETEtree OR a newick string\n\t:param msa_file:\n\t:param rates: as extracted from parse_raxmlNG_content() returned dict\n\t:param pinv: as extracted from parse_raxmlNG_content() returned dict\n\t:param alpha: as extracted from parse_raxmlNG_content() returned dict\n\t:param freq: as extracted from parse_raxmlNG_content() returned dict\n\t:return: float. the score is the minus log-likelihood value of the tree\n\t\"\"\"\n\tmodel_line_params = 'GTR{rates}+I{pinv}+G{alpha}+F{freq}'.format(rates=\"{{{0}}}\".format(\"/\".join(rates)),\n\t pinv=\"{{{0}}}\".format(pinv),\n\t alpha=\"{{{0}}}\".format(alpha),\n\t freq=\"{{{0}}}\".format(\"/\".join(freq)))\n\n\t# create tree file in memory and not in the storage:\n\ttree_rampath = \"/dev/shm/\" + msa_file.split(\"/\")[-1] + \"tree\" # the var is the str: tmp{dir_suffix}\n\ttry:\n\t\twith open(tree_rampath, \"w\") as fpw:\n\t\t\tfpw.write(tree)\n\n\t\tp = Popen(\n\t\t\t[RAXML_NG_SCRIPT, '--evaluate', '--msa', msa_file, '--threads', '1', '--opt-branches', 'on', '--opt-model',\n\t\t\t 'off', '--model', model_line_params, '--nofiles', '--tree', tree_rampath],\n\t\t\tstdout=PIPE, stdin=PIPE, stderr=STDOUT)\n\n\t\traxml_stdout = p.communicate()[0]\n\t\traxml_output = raxml_stdout.decode()\n\n\t\tres_dict = parse_raxmlNG_content(raxml_output)\n\t\tll = res_dict['ll']\n\n\t# check for 'rare' alpha value error, run again with different alpha\n\texcept AttributeError:\n\t\t# float 0.5-8\n\t\tnew_alpha = np.random.uniform(0.5, 8)\n\t\tmodel_line_params = 'GTR{rates}+I{pinv}+G{alpha}+F{freq}'.format(rates=\"{{{0}}}\".format(\"/\".join(rates)),\n\t\t pinv=\"{{{0}}}\".format(pinv),\n\t\t alpha=\"{{{0}}}\".format(new_alpha),\n\t\t freq=\"{{{0}}}\".format(\"/\".join(freq)))\n\t\tp = Popen(\n\t\t\t[RAXML_NG_SCRIPT, '--evaluate', '--msa', msa_file, '--threads', '1', '--opt-branches', 'on', '--opt-model',\n\t\t\t 'off', '--model', model_line_params, '--nofiles', '--tree', tree_rampath],\n\t\t\tstdout=PIPE, stdin=PIPE, stderr=STDOUT)\n\n\t\traxml_stdout = p.communicate()[0]\n\t\traxml_output = raxml_stdout.decode()\n\n\t\tres_dict = parse_raxmlNG_content(raxml_output)\n\t\tll = res_dict['ll']\n\texcept Exception as e:\n\t\tprint(msa_file)\n\t\tprint(e)\n\t\tprint(\"return_likelihood() in bio_methods.py\")\n\t\texit()\n\tfinally:\n\t\tos.remove(tree_rampath)\n\n\treturn float(ll) # changed to return a num not a str\n\n\ndef parse_raxmlNG_content(content):\n\t\"\"\"\n\t:return: dictionary with the attributes - string typed. if parameter was not estimated, empty string\n\t\"\"\"\n\tres_dict = dict.fromkeys([\"ll\", \"pInv\", \"gamma\",\n\t \"fA\", \"fC\", \"fG\", \"fT\",\n\t \"subAC\", \"subAG\", \"subAT\", \"subCG\", \"subCT\", \"subGT\",\n\t \"time\"], \"\")\n\n\t# likelihood\n\tll_re = re.search(\"Final LogLikelihood:\\s+(.*)\", content)\n\tif not ll_re and (\n\t\t\tre.search(\"BL opt converged to a worse likelihood score by\", content) or re.search(\"failed\", content)):\n\t\tres_dict[\"ll\"] = re.search(\"initial LogLikelihood:\\s+(.*)\", content).group(1).strip()\n\telse:\n\t\tres_dict[\"ll\"] = ll_re.group(1).strip()\n\n\t\t# gamma (alpha parameter) and proportion of invariant sites\n\t\tgamma_regex = re.search(\"alpha:\\s+(\\d+\\.?\\d*)\\s+\", content)\n\t\tpinv_regex = re.search(\"P-inv.*:\\s+(\\d+\\.?\\d*)\", content)\n\t\tif gamma_regex:\n\t\t\tres_dict['gamma'] = gamma_regex.group(1).strip()\n\t\tif pinv_regex:\n\t\t\tres_dict['pInv'] = pinv_regex.group(1).strip()\n\n\t\t# Nucleotides frequencies\n\t\tnucs_freq = re.search(\"Base frequencies.*?:\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\", content)\n\t\tfor i, nuc in enumerate(\"ACGT\"):\n\t\t\tres_dict[\"f\" + nuc] = nucs_freq.group(i + 1).strip()\n\n\t\t# substitution frequencies\n\t\tsubs_freq = re.search(\n\t\t\t\"Substitution rates.*:\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\\s+(\\d+\\.?\\d*)\",\n\t\t\tcontent)\n\t\tfor i, nuc_pair in enumerate([\"AC\", \"AG\", \"AT\", \"CG\", \"CT\", \"GT\"]): # todo: make sure order\n\t\t\tres_dict[\"sub\" + nuc_pair] = subs_freq.group(i + 1).strip()\n\n\t\t# Elapsed time of raxml-ng optimization\n\t\trtime = re.search(\"Elapsed time:\\s+(\\d+\\.?\\d*)\\s+seconds\", content)\n\t\tif rtime:\n\t\t\tres_dict[\"time\"] = rtime.group(1).strip()\n\t\telse:\n\t\t\tres_dict[\"time\"] = 'no ll opt_no time'\n\treturn res_dict\n\n\ndef parse_phyml_stats_output(stats_filepath):\n\t\"\"\"\n :return: dictionary with the attributes - string typed. if parameter was not estimated, empty string\n \"\"\"\n\tres_dict = dict.fromkeys([\"ntaxa\", \"nchars\", \"ll\",\n\t \"fA\", \"fC\", \"fG\", \"fT\",\n\t \"subAC\", \"subAG\", \"subAT\", \"subCG\", \"subCT\", \"subGT\",\n\t \"pInv\", \"gamma\",\n\t \"path\"], \"\")\n\n\tres_dict[\"path\"] = stats_filepath\n\ttry:\n\t\twith open(stats_filepath) as fpr:\n\t\t\tcontent = fpr.read()\n\n\t\t# likelihood\n\t\tres_dict[\"ll\"] = re.search(\"Log-likelihood:\\s+(.*)\", content).group(1).strip()\n\n\t\t# gamma (alpha parameter) and proportion of invariant sites\n\t\tgamma_regex = re.search(\"Gamma shape parameter:\\s+(.*)\", content)\n\t\tpinv_regex = re.search(\"Proportion of invariant:\\s+(.*)\", content)\n\t\tif gamma_regex:\n\t\t\tres_dict['gamma'] = gamma_regex.group(1).strip()\n\t\tif pinv_regex:\n\t\t\tres_dict['pInv'] = pinv_regex.group(1).strip()\n\n\t\t# Nucleotides frequencies\n\t\tfor nuc in \"ACGT\":\n\t\t\tnuc_freq = re.search(\" - f\\(\" + nuc + \"\\)\\= (.*)\", content).group(1).strip()\n\t\t\tres_dict[\"f\" + nuc] = nuc_freq\n\n\t\t# substitution frequencies\n\t\tfor nuc1 in \"ACGT\":\n\t\t\tfor nuc2 in \"ACGT\":\n\t\t\t\tif nuc1 < nuc2:\n\t\t\t\t\tnuc_freq = re.search(nuc1 + \" <-> \" + nuc2 + \"(.*)\", content).group(1).strip()\n\t\t\t\t\tres_dict[\"sub\" + nuc1 + nuc2] = nuc_freq\n\texcept:\n\t\tprint(\"Error with:\", res_dict[\"path\"], res_dict[\"ntaxa\"], res_dict[\"nchars\"])\n\t\treturn\n\treturn res_dict\n\n\ndef prune_branch(t_orig, prune_name):\n\t'''\n\treturns (a copy of) both ETE subtrees after pruning\n\t'''\n\tt_cp_p = t_orig.copy() # the original tree is needed for each iteration\n\tassert t_cp_p & prune_name # todo Oz: add indicative error\n\tprune_node_cp = t_cp_p & prune_name # locate the node in the copied subtree\n\tassert prune_node_cp.up\n\n\tnname = prune_node_cp.up.name\n\tprune_loc = prune_node_cp\n\tprune_loc.detach() # pruning: prune_node_cp is now the subtree we detached. t_cp_p is the one that was left behind\n\t###########\n\tif nname == t_cp_p.get_tree_root().name:\n\t\tfor n in t_cp_p.children:\n\t\t\ttmp_tree = n\n\t\t\tif n.name != prune_name:\n\t\t\t\toutgroup = n.children[0]\n\t\t\t\tn.set_outgroup(outgroup)\n\t\t\t\tbreak\n\n\t\tt_cp_p = tmp_tree\n\telse:\n\t\tt_cp_p.search_nodes(name=nname)[0].delete(\n\t\t\tpreserve_branch_length=True) # delete the specific node (without its childs) since after pruning this branch should not be divided\n\t###########\n\treturn nname, prune_node_cp, t_cp_p\n\n\ndef regraft_branch(t_cp_p, prune_node_cp, rgft_name, nname):\n\t'''\n\trecieves: 2 ETE subtrees and 2 node names\n\treturns: an ETEtree with the 2 concatenated ETE subtrees\n\t'''\n\n\tt_temp = Tree() # for concatenation of both subtrees ahead, to avoid polytomy\n\tt_temp.add_child(prune_node_cp)\n\tt_curr = t_cp_p.copy()\n\tassert t_curr & rgft_name # todo Oz: add indicative error\n\trgft_node_cp = t_curr & rgft_name # locate the node in the copied subtree\n\tnew_branch_length = rgft_node_cp.dist / 2\n\n\trgft_loc = rgft_node_cp.up\n\trgft_node_cp.detach()\n\tt_temp.add_child(rgft_node_cp, dist=new_branch_length)\n\tt_temp.name = nname\n\trgft_loc.add_child(t_temp, dist=new_branch_length) # regrafting\n\n\t# check for case when tree becomes rooted\n\t# num of nodes (hopefully) = len(t_curr.get_descendants()) + 1\n\t# if NUM_OF_NODES != len(t_curr.get_descendants()) + 1:\n\t# \tprint(\"UNROOTING: before unroot t_curr has \" + str(len(t_curr.get_descendants()) + 1) + \" nodes\")\n\t# \tt_curr.write(outfile=\"log_run/tree_before_unroot\", format=1)\n\t# \tt_curr.unroot()\n\t# \t# next line checks for new created node we wnt to remove\n\t# \tnodes_to_preserve_lst = [\"Sp\" + (str(n)).zfill(3) for n in range(20)]\n\t# \tnodes_to_preserve_lst.extend([\"N\" + str(i) for i in range(1, 19)])\n\t# \tt_curr.prune(nodes_to_preserve_lst, preserve_branch_length=True)\n\t# \tprint(\"I DID UNROOT!\")\n\t# TODO: remove\n\tt_curr.write(outfile=\"log_run/tree_after_regraft\", format=1, format_root_node=True)\n\n\treturn t_curr\n\n\ndef SPR_by_edge_names(ETEtree, cut_name, paste_name):\n\tnname, subtree1, subtree2 = prune_branch(ETEtree,\n\t cut_name) # subtree1 is the pruned subtree. subtree2 is the remaining subtree\n\trearr_tree_str = regraft_branch(subtree2, subtree1, paste_name, nname).write(\n\t\tformat=1, format_root_node=True) # .write() is how you convert an ETEtree to newick string. now you can convert it back (if needed) using Tree(), or convert it to BIOtree\n\n\treturn rearr_tree_str\n\n\ndef add_internal_names(tree_file, t_orig, newfile_suffix=\"_with_internal.txt\"):\n\t# todo oz: I know you defined 'newfile_suffix' diferently (just None to runover?)\n\t# for tree with ntaxa=20 there are 2n-3 nodes --> n-3=17 internal nodes. plus one ROOT_LIKE node ==> always 18 internal nodes.\n\t#N_lst = [\"N{}\".format(i) for i in range(1,19)]\n\tN_lst = [\"N{}\".format(i) for i in range(1,20)]\n\ti = 0\n\tfor node in t_orig.traverse():\n\t\tif not node.is_leaf():\n\t\t\tnode.name = N_lst[i]\n\t\t\ti += 1\n\t# assuming tree file is a pathlib path\n\tnew_tree_file = tree_file.parent / (tree_file.name + newfile_suffix)\n\tt_orig.write(format=1, outfile=new_tree_file, format_root_node=True)\n\n\treturn t_orig, new_tree_file\n\n\n# convert tree to weighted_adjacency_matrix\ndef tree_to_matrix(bio_tree):\n\tgraph = Phylo.to_networkx(bio_tree)\n\n\tif graph.number_of_nodes() != NUM_OF_NODES:\n\t\tprint(\"tree_to_matrix() in bio_methods.py\")\n\t\tprint(\"graph has \" + str(graph.number_of_nodes()) + \" nodes\")\n\t\texit()\n\n\t# matrix = networkx.adjacency_matrix(net)\n\tmatrix = nx.to_numpy_matrix(graph)\n\t# makes a numpy array from 2-dim matrix\n\treturn np.asarray(matrix).reshape(-1)\n\n\n# returns the tree from the text file in the msa_num's folder\ndef get_tree_from_msa(msa_path):\n\ttree_path = parent_folder / (msa_path + \"masked_species_real_msa.phy_phyml_tree_bionj.txt\")\n\n\twith open(tree_path, \"r\") as f:\n\t\ttree_str = f.read()\n\tete_tree = Tree(newick=tree_str, format=1)\n\tete_tree.resolve_polytomy(recursive=False)\n\n\t# add_internal_names does not run over the file it is given\n\tete_tree, tree_copy = add_internal_names(tree_path, ete_tree)\n\t# TODO: remove\n\tete_tree.write(outfile=\"log_run/tree_right_after_add_internal_names()\", format=1, format_root_node=True)\n\t##########\n\twith open(tree_copy, \"r\") as f:\n\t\ttree_str = f.read()\n\n\tbio_tree = Phylo.read(tree_copy, \"newick\")\n\tos.remove(tree_copy)\n\treturn ete_tree, bio_tree, tree_str\n\n\n# converts string to other formats\ndef get_ete_and_bio_from_str(tree_str, msa_path):\n\ttree_copy = parent_folder / (msa_path + \"for_now.txt\")\n\n\tete_tree = Tree(newick=tree_str, format=1)\n\twith open(tree_copy, \"w\") as f:\n\t\tf.write(tree_str)\n\n\tbio_tree = Phylo.read(tree_copy, \"newick\")\n\tos.remove(tree_copy)\n\treturn ete_tree, bio_tree\n\n\n# calculating likelihood of tree, msa_num should be the folder number of its corresponding msa\ndef get_likelihood_simple(tree_str, msa_path, params=None):\n\tif params is None:\n\t\t# taking the params required for likelihood calculation from the stats file in the msa_num's folder\n\t\tfreq, rates, pinv, alpha = calc_likelihood_params(msa_path)\n\telse:\n\t\tfreq, rates, pinv, alpha = params\n\n\tmsa_path = parent_folder / (msa_path + \"masked_species_real_msa.phy\")\n\treturn return_likelihood(tree_str, str(msa_path), rates, pinv, alpha, freq)\n\n\ndef calc_likelihood_params(msa_path):\n\tstats_path = parent_folder / (msa_path + \"masked_species_real_msa.phy_phyml_stats_bionj.txt\")\n\tparams_dict = parse_phyml_stats_output(stats_path)\n\tfreq, rates, pinv, alpha = [params_dict[\"fA\"], params_dict[\"fC\"], params_dict[\"fG\"], params_dict[\"fT\"]], [\n\t\tparams_dict[\"subAC\"], params_dict[\"subAG\"], params_dict[\"subAT\"], params_dict[\"subCG\"], params_dict[\"subCT\"],\n\t\tparams_dict[\"subGT\"]], params_dict[\"pInv\"], params_dict[\"gamma\"]\n\n\treturn freq, rates, pinv, alpha\n\n\nif __name__ == '__main__':\n\twith open(\"log_run/tree_after_regraft\", \"r\") as f:\n\t\ttree_str = f.read()\n\tmsa_path = \"/groups/itay_mayrose/danaazouri/PhyAI/ML_workshop/reinforcement_data/data/training_datasets/19078/\"\n\tlikelihood_params = calc_likelihood_params(msa_path)\n\n\tprint(get_likelihood_simple(tree_str, msa_path, likelihood_params))\n\n\t# directoryname = \"log_run/to_print\"\n\t# directory = os.fsencode(directoryname)\n\t# for file in os.listdir(directory):\n\t# \tfilename = os.fsdecode(file)\n\t#\n\t# \twith open(os.path.join(directoryname, filename), \"r\") as f:\n\t# \t\tcurrent_tree_str = f.read()\n\t# \t\tete_tree = Tree(newick=current_tree_str, format=1)\n\t# \t\tprint(\"\\n\"+filename+\":\")\n\t# \t\tprint(\"root_name = \" + ete_tree.get_tree_root().name + \":\\n\\n\")\n\t# \t\tprint(ete_tree.get_ascii(show_internal=True))\n\t#\n\n\n\n","sub_path":"Reinforcement_model_pytorch/bio_methods.py","file_name":"bio_methods.py","file_ext":"py","file_size_in_byte":13509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"583902628","text":"\"\"\"\nINSERT DOCSTRING\n\"\"\"\n\nimport urllib\nimport re\n\n\ndef url_parse(entry):\n \"\"\" outputs urls contained in words of textEdit text \"\"\"\n\n entry_words = entry.split()\n\n # entry as list from textEdit\n top_level_domains = ['.com', '.org', '.net', '.int', '.edu',\n '.co', '.gov']\n\n urls = [word for domain in top_level_domains\n for word in entry_words\n if domain in word]\n\n urls = list(set(urls))\n\n html_urls = []\n\n for url in urls:\n\n if \"http\" not in url:\n html_url = '''{0}'''.format(url)\n\n else:\n domain = url.strip('http://')\n html_url = '''{1}'''.format(url, domain)\n\n html_urls.append(html_url)\n\n return [urls, html_urls] if urls or html_urls else None\n\n\n# test locations detection in entries with no time indications\ndef loc_re_parse(entry):\n\n result = ''\n googlemapsurl = 'http://maps.google.com/maps?q='\n at_to = re.search(r'\\s(at|to)\\s', entry)\n if at_to:\n # logging.debug('at_to found')\n words = entry.split()\n if 'at' in entry:\n at_to_pos = words.index('at')\n elif 'to' in entry:\n at_to_pos = words.index('to')\n location = words[at_to_pos + 1:]\n entry_body = words[:at_to_pos + 1]\n location = ' '.join(location)\n # logging.debug('location: {}'.format(location))\n googlemapsurl += urllib.quote(location)\n quickday_loc_url = ''' {1}'''.format(\n googlemapsurl, location)\n result += ' '.join(entry_body)\n result += quickday_loc_url\n else:\n result = entry\n\n return result\n\n\ndef test_url_parse_short():\n assert url_parse('amazon.com') == [\n ['amazon.com'],\n [\"amazon.com\"]\n ]\n\n\ndef test_url_parse_long():\n assert url_parse('http://www.amazon.com') == [\n ['http://www.amazon.com'],\n [\"www.amazon.com\"]\n ]\n","sub_path":"tests/test_widgets.py","file_name":"test_widgets.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"481508559","text":"from __future__ import division\n\nimport time\nimport os\nfrom collections import namedtuple\n\nimport numpy as np\nfrom scipy import io\n\nfrom pacu.core.io.view.zero_dimension_array import ZeroDimensionArrayView\nfrom pacu.util.path import Path\nfrom pacu.profile import manager\n\nopt = manager.instance('opt')\n\nDimension = namedtuple('Dimension', 'height, width')\n\nclass ScanboxMatView(ZeroDimensionArrayView):\n def __init__(self, path):\n self.path = Path(path).ensure_suffix('.mat')\n self.bound_sbx_path = self.path.with_suffix('.sbx')\n array = io.loadmat(self.path.str, squeeze_me=True).get('info')\n super(ScanboxMatView, self).__init__(array)\n @property\n def is_aligned(self):\n return self.path.name.startswith('Aligned')\n @property\n def sbxsize(self):\n #return self.path.with_suffix('.sbx').size\n return Path(self.stempath).with_suffix('.sbx').size\n @property\n def sbxtime(self):\n #return self.path.with_suffix('.sbx').created_at\n return Path(self.stempath).with_suffix('.sbx').created_at\n @property\n def sbxpath(self):\n #return self.path.with_suffix('.sbx').relative_to(opt.scanbox_root)\n #return Path(os.path.split(self.stempath)[1]).with_suffix('.sbx')\n return Path(self.stempath).with_suffix('.sbx').relative_to(opt.scanbox_root)\n @property\n def iopath(self):\n return self.sbxpath.with_suffix('.io')\n @property\n def shape(self):\n return tuple(reversed((self.nframes, self.channels) + self.dimension))\n @property\n def dimension(self):\n return Dimension(*self.sz)\n @property\n def nframes(self):\n nframes = int(self.sbxsize/self.recordsPerBuffer/\n self.dimension.width/2/self.channels)\n return nframes * (1 if self.scanmode else 2)\n @property\n def framerate(self):\n # recordsPerBuffer = self.originalRecordsPerBuffer \\\n # if self.is_aligned else self.recordsPerBuffer\n if self.is_aligned:\n try:\n recordsPerBuffer = self.originalRecordsPerBuffer\n except:\n recordsPerBuffer = self.recordsPerBuffer\n else:\n recordsPerBuffer = self.recordsPerBuffer\n rate = self.resfreq / recordsPerBuffer\n return rate if self.scanmode else rate * 2\n @property\n def nchannels(self):\n if self.channels == -1:\n if self.chan.nchan == 1:\n return 1\n else:\n return 2\n elif self.channels == 1:\n return 2\n else:\n return 1\n #return 2 if self.channels == 1 else 1 (JZ) For compatibility with mesoscope\n @property\n def factor(self):\n if self.channels == -1:\n if self.chan.nchan == 1:\n return 2\n else:\n return 1\n elif self.channels == 1:\n return 1\n else:\n return 2\n #return 1 if self.channels == 1 else 2 (JZ) For compatibility with mesoscope\n @property\n def scanmodestr(self):\n return 'uni' if self.scanmode == 1 else 'bi'\n def get_max_idx(self, size):\n return int(size/self.recordsPerBuffer/self.sz[1]*self.factor/4 - 1)\n def get_shape(self, size):\n return self.get_max_idx(size) + 1, self.sz[0], self.sz[1]\n @property\n def recordsPerBuffer(self):\n rpb = self._dict.get('recordsPerBuffer')\n return rpb * 2 if self.scanmode is 0 else rpb\n# def __dir__(self): # quick and dirty: need to use descriptor set\n# return super(ScanboxInfoView, self).__dir__() + \\\n# 'path nchan factor framerate recordsPerBuffer sz'.split()\n @property\n def activeChannels(self):\n channels = self.channels\n if channels == -1:\n activeChannels = self.chan.sample\n if activeChannels[0] and activeChannels[1]:\n return ['Green', 'Red', 'Both']\n elif activeChannels[0] and not activeChannels[1]:\n return ['Green']\n elif activeChannels[1] and not activeChannels[0]:\n return ['Red']\n elif channels == 1:\n return ['Green', 'Red', 'Both']\n elif channels == 2:\n return ['Green']\n elif channels == 3:\n return ['Red']\n\n def toDict(self):\n data = self.items()\n data['iopath'] = str(self.iopath)\n data['framerate'] = self.framerate\n data['frameratestr'] = str(self.framerate) + ' fps'\n data['sbxsize'] = self.sbxsize.str\n data['sbxtime'] = time.mktime(self.sbxtime.timetuple())\n data['sbxpath'] = self.sbxpath.str\n data['nchannels'] = self.nchannels\n data['nframes'] = self.nframes\n data['nframesstr'] = str(self.nframes) + ' frames'\n data['scanmodestr'] = self.scanmodestr\n data['focal_pane_args'] = self.focal_pane_args\n return data\n @property\n def duration(self):\n return self.nframes / self.framerate\n # return '{s.nframes} frames at {s.framerate} fps is 00:01:14:01'.format(s=self)\n # duration = frame_count / frame_rate\n# @property\n# def originalRecordsPerBuffer(self):\n# obuf = self._dict.get('originalRecordsPerBuffer')\n# buf = self.recordsPerBuffer\n# print 'original: {}, normal: buf'.format(obuf, buf)\n# return obuf or buf\n @property\n def focal_pane_args(self):\n try:\n if self.volscan:\n _, _, n = map(int, self.otparam)\n else:\n n = 1\n except:\n n = 1\n try:\n if self.volscan:\n waves = list(map(int, self.otwave))\n else:\n waves = [0]\n except:\n waves = [0]\n return dict(waves=waves, n=n)\n @property\n def memmap(self): # first channel\n shape = self.get_shape(self.bound_sbx_path.size)\n chans = np.memmap(self.bound_sbx_path.str, dtype='uint16', mode='r', shape=shape)\n return chans[0::mat.nchannels]\n @property\n def opened(self):\n return self.bound_sbx_path.open('rb')\n\n# import psutil\n# import functools\n# p = psutil.Process()\n# mat = ScanboxMatView('/Volumes/Users/ht/dev/current/pacu/tmp/sbxroot/Dario/P22_000_004.mat')\n# h, w = map(int, mat.sz)\n# mm = mat.memmap\n# frame_size = h * w * 2\n# raw = mat.opened\n# for index, chunk in enumerate(iter(functools.partial(raw.read, frame_size), '')):\n# print index, p.memory_percent()\n# print chunk == mm[index].tostring()\n# break\n","sub_path":"pacu/pacu/core/io/scanbox/view/mat.py","file_name":"mat.py","file_ext":"py","file_size_in_byte":6554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"427588626","text":"import requests as req\nimport json\nperm_token = \"EAAd0ep1GT0wBAEbm1UTKaZAZBaxZAc6Iyg9gnlJWYxuHY0Wd2BklpJSvS6XpfsKIvsD6RdYrqZC0hUMyIKwsqZAAPZB40SxiQt7GmMSAko1Ln0GzPXG68eBQNcmmtifahM8v4ZAtemmnryaOMn20QoAke7ORZBPShv8bAwZBm9woNP1EkNvi0axSK\"\ntimeStamp_list = [] \nmessage_list = []\ndef jsonToLists(some_json) :\n count = len(some_json)\n for i in range(count) : \n print(some_json[i])\n print(\"----------\")\n try :\n tmp = some_json[i][\"live_broadcast_timestamp\"]\n except : \n tmp = -111\n timeStamp_list.append(tmp)\n message_list.append(some_json[i][\"message\"])\n return \n\ndef getVideoId(video_url) : \n tmp = video_url.split(\"videos/\")[1]\n video_id = tmp.split(\"/\")[0]\n return video_id\n\ndef makeRequest(video_id) :\n try :\n host_url = \"https://graph.facebook.com/v2.12/\" + video_id + \"?fields=created_time,live_status,updated_time,backdated_time,backdated_time_granularity,comments.limit(1000){live_broadcast_timestamp,message},length&access_token=\" + perm_token \n except : \n host_url = \"https://graph.facebook.com/v2.12/\" + video_id + \"?fields=created_time,live_status,updated_time,backdated_time,backdated_time_granularity,comments.limit(100){live_broadcast_timestamp,message},length&access_token=\" + perm_token \n else :\n host_url = \"https://graph.facebook.com/v2.12/\" + video_id + \"?fields=created_time,live_status,updated_time,backdated_time,backdated_time_granularity,comments{live_broadcast_timestamp,message},length&access_token=\" + perm_token \n\n response = req.get(host_url)\n response_json = json.loads(response.text)\n response_code = response.status_code\n return response_json,response_code\n\ndef init(url) :\n video_id = getVideoId(url)\n response_json , response_code = makeRequest(video_id)\n print(response_json)\n print(response_json[\"comments\"][\"data\"])\n jsonToLists(response_json[\"comments\"][\"data\"])\n try :\n live_status = response_json[\"live_status\"]\n except:\n live_status = None \n video_duration = response_json[\"length\"]\n output = {\n \"live_status\" : live_status ,\n \"video_duration\" : video_duration , \n \"timeStamp_list\" : timeStamp_list , \n \"message_list\" : message_list , \n \"video_id\" : video_id,\n }\n return output\n\n# if __name__ == \"_main_\" :\n# video_url = raw_input()\n# init(video_url)\n# url = \"https://www.facebook.com/election.commission.iitk/videos/810829939120636\"\n# video_id = getVideoId(url)\n# response_json , response_code = makeRequest(video_id)\n# print(video_id , response_json , response_code)\n","sub_path":"Project2/myapp/lib/fb_comments.py","file_name":"fb_comments.py","file_ext":"py","file_size_in_byte":2623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"413193273","text":"#! /usr/bin/python\n# -*- coding: iso-8859-15 -*-\nfrom pylab import *\nimport matplotlib.pyplot as plt\nfrom matplotlib import *\nfrom mpl_toolkits.mplot3d import Axes3D # Cargo Axes3D de mpl_toolkits.mplot3d\nfrom scipy.misc import imread # Cargo imread de scipy.misc\nimport numpy as np # Cargo numpy como el aliaas np\n\n# Leo una imagen y la almaceno en imagen_superficial\nimagen_superficial = imread('python.png')\n\n# Creo una figura\nplt.figure()\n\n# Muestro la imagen en pantalla\nplt.imshow(imagen_superficial)\n\n# Añado etiquetas\nplt.title('Imagen que usaremos de superficie')\nplt.xlabel(u'# de píxeles')\nplt.ylabel(u'# de píxeles')\n\n# Creo otra figura y la almaceno en figura_3d\nfigura_3d = plt.figure()\n\n# Indicamos que vamos a representar en 3D\nax = figura_3d.gca(projection = '3d')\n\n# Creamos los arrays dimensionales de la misma dimensión que imagen_superficial\nX = np.linspace(-5, 5, imagen_superficial.shape[0])\nY = np.linspace(-5, 5, imagen_superficial.shape[1])\n\n# Obtenemos las coordenadas a partir de los arrays creados\nX, Y = np.meshgrid(X, Y)\n\n# Defino la función que deseo representar\nR = np.sqrt(X ** 2 + Y ** 2)\nZ = np.sin(R)\n\n# Reescalamos de RGB a [0-1]\nimagen_superficial = imagen_superficial.swapaxes(0, 1) / 255.\n\n# meshgrid orienta los ejes al revés luego hay que voltear\nax.plot_surface(X, Y, Z, facecolors = np.flipud(imagen_superficial))\n\n# Fijamos la posición inicial de la grafica\nax.view_init(45, -35)\n\n# Añadimos etiquetas\nplt.title(u'Imagen sobre una grafica 3D')\nplt.xlabel('Eje x')\nplt.ylabel('Eje y')\n# Mostramos en pantalla\nplt.show()","sub_path":"Graficos5.py","file_name":"Graficos5.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"165488021","text":"#!/usr/bin/python3\nfrom pwn import *\n\nrand = 0x6b8b4567\n\ns = ssh('random', 'pwnable.kr', 2222, 'guest')\np = s.process('./random')\n\nkey = rand ^ 0xdeadbeef\n\np.sendline(str(key))\nprint(p.recvall().decode('ascii'))","sub_path":"Toddler's Bottle/random/_random.py","file_name":"_random.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"249551386","text":"from sys import stdin\nlista=[\"-\",\"+\",\"/\",\"*\"]\ndef f(exp):\n global lista\n x=[]\n n=\"\"\n v=0\n for i in range(len(exp)):\n u=exp[i]\n if i==0 and u==\"-\":\n n+=\"-\"\n v+=1\n #print(\"primer if i==0 and u== -:\",n,v)\n if i==0 and u==\"+\":\n #print(\"segundo if i==0 and u== +:\",n,v)\n continue\n elif u==\"-\" and exp[i-1] in lista and i!=0:\n n+=\"-\"\n v+=1\n #print(\"tercer elif u== - and exp[i-1] in lista:\",n,v)\n elif u==\"+\" and exp[i-1] in lista and i!=0:\n #print(\"cuarto elif u== + and exp[i-1] in lista:\",n,v)\n continue\n elif u in lista and exp[i-1] not in lista and i!=0:\n g=float(n[v:])*((-1)**v)\n x.append(g)\n x.append(exp[i])\n #print(\"quinto elif u in lista and exp[i-1] not in lista:\",n,v)\n n=\"\"\n v=0\n elif u != \"+\" and u!=\"-\" and u!=\"*\" and u!=\"/\":\n n+=exp[i]\n #print(\"else\",n,v)\n g=float(n[v:])*((-1)**v)\n x.append(g)\n return x\ndef evalue(j):\n h=[]\n for i in range(len(j)):\n h.append(j[i])\n if len(h)>2 and h[-2]==\"*\":\n temp=h.pop()\n h.pop()\n h.append(h.pop()*temp)\n if len(h)>2 and h[-2]==\"/\":\n temp=h.pop()\n h.pop()\n h.append(h.pop()/temp)\n y=[]\n for i in range(len(h)):\n y.append(h[i])\n if len(y)>2 and y[-2]==\"+\":\n temp=y.pop()\n y.pop()\n y.append(y.pop()+temp)\n if len(y)>2 and y[-2]==\"-\":\n temp=y.pop()\n y.pop()\n y.append(y.pop()-temp)\n print(\"%.3f\"%y[0])\ndef main():\n exp=stdin.readline().strip()\n while exp:\n g=f(exp)\n evalue(g)\n exp=stdin.readline().strip()\nmain()\n","sub_path":"ejercicios/Data structures simples/time.py","file_name":"time.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"345977071","text":"# -*- coding: utf-8 -*-\n\nfrom sqlalchemy import create_engine\nimport tushare as ts\nimport pandas as pd\nimport datetime\nfrom datetime import timedelta\nfrom progressbar import ProgressBar,SimpleProgress,Bar,ETA,ReverseBar\nimport settings\nimport sqlite3\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine.url import URL\n\n\n# connect to the database\n#conn = create_engine(URL(**settings.DATABASE))\nconn = sqlite3.connect('cn_stocks.db')\n\nts.set_token('3c9fcd3daa9244ca0c45a7e47d5ba14004c9aff7208506910b991f30')\npro = ts.pro_api()\n#conn = sqlite3.connect('cn_stocks.db')\n#engine = create_engine('mysql+pymysql://stock:494904@120.79.35.86:3306/stocks?charset=utf8')\n\ntoday = (datetime.datetime.today()).strftime(\"%Y-%m-%d\")\ntoday_all_real = ts.get_today_all()\n\ntry:\n\ttoday_all = pd.read_sql('SELECT * from today_all',conn).drop(['date'],axis=1)\nexcept:\n\ttoday_all = today_all_real\n\ttoday_all_real.reset_index().to_sql('today_all',conn,if_exists='replace',index=False)\n\nif not today_all_real.equals(today_all):\n\tprint('NOT EQUALS')\n\ttoday_all = today_all_real\n\ttoday_all['date'] = today\n\ttoday_all.reset_index().to_sql('today_all',conn,if_exists='replace',index=False)\n\ntoday_all = today_all.set_index('code')\n\n\nall_stocks = ts.get_stock_basics()\nall_stocks.reset_index().to_sql('all_stocks',conn,if_exists='replace',index=False)\nall_stocks_list = all_stocks.index.tolist()\nall_stocks_dict = {code:all_stocks.loc[code]['name'] for code in all_stocks.index.tolist()}\n\nwidgets = [Bar('>'), ' ', ETA(), ' ', ReverseBar('<')]\npbar = ProgressBar(widgets=widgets,maxval=len(all_stocks_dict.keys())).start()\n\nfor i,code in enumerate(all_stocks_dict.keys()):\n\ttry:\n\t\tcurrent_stock = pd.read_sql('SELECT * from \\'{}\\''.format(code),conn)\n\t\tstock = today_all.loc[code][['open','high','trade','low','volume','changepercent']]\n\n\t\tdf_stock = pd.DataFrame([stock])\n\t\tdf_stock['date'] = today\n\t\tdf_stock['volume'] = df_stock['volume']/100.0\n\t\tdf_stock.columns = ['open','high','close','low','volume','p_change','date']\n\n\t\tdf_combine = pd.concat([current_stock.sort_values('date'),df_stock])\n\t\tdf_combine['ma5'] = df_combine['ma5'].fillna(df_combine['close'].rolling(5).mean())\n\t\tdf_combine['max5'] = df_combine['close'].rolling(5).max()\n\t\tdf_combine['min5'] = df_combine['close'].rolling(5).min()\n\t\tdf_combine['ma10'] = df_combine['ma10'].fillna(df_combine['close'].rolling(10).mean())\n\t\tdf_combine['max10'] = df_combine['close'].rolling(10).max()\n\t\tdf_combine['min10'] = df_combine['close'].rolling(10).min()\n\t\tdf_combine['ma20'] = df_combine['ma20'].fillna(df_combine['close'].rolling(20).mean())\n\t\tdf_combine['max20'] = df_combine['close'].rolling(20).max()\n\t\tdf_combine['min20'] = df_combine['close'].rolling(20).min()\n\t\tdf_combine['ma30'] = df_combine['close'].rolling(30).mean()\n\t\tdf_combine['max30'] = df_combine['close'].rolling(30).max()\n\t\tdf_combine['min30'] = df_combine['close'].rolling(30).min()\n\t\tdf_combine['ma60'] = df_combine['close'].rolling(60).mean()\n\t\tdf_combine['max60'] = df_combine['close'].rolling(60).max()\n\t\tdf_combine['min60'] = df_combine['close'].rolling(60).min()\n\t\tdf_combine['ma120'] = df_combine['close'].rolling(120).mean()\n\t\tdf_combine['max120'] = df_combine['close'].rolling(120).max()\n\t\tdf_combine['min120'] = df_combine['close'].rolling(120).min()\n\n\t\tdf_combine['v_ma5'] = df_combine['v_ma5'].fillna(df_combine['volume'].rolling(5).mean())\n\t\tdf_combine['v_ma10'] = df_combine['v_ma10'].fillna(df_combine['volume'].rolling(10).mean())\n\t\tdf_combine['v_ma20'] = df_combine['v_ma20'].fillna(df_combine['volume'].rolling(20).mean())\n\t\tdf_combine['v_ma30'] = df_combine['volume'].rolling(30).mean()\n\t\tdf_combine['v_ma60'] = df_combine['volume'].rolling(60).mean()\n\t\tdf_combine['v_ma120'] = df_combine['volume'].rolling(120).mean()\n\n\t\tdf_combine.to_sql(code,conn,if_exists='replace',index=False)\n\texcept:\n\t\tcontinue\n\tpbar.update(i + 1)\n\nstocks_5 \t= {}#pd.DataFrame()\nstocks_10 \t= {}#pd.DataFrame()\nstocks_20 \t= {}#pd.DataFrame()\nstocks_30 \t= {}#pd.DataFrame()\nstocks_60 \t= {}#pd.DataFrame()\nstocks_90 \t= {}#pd.DataFrame()\nstocks_125 \t= {}#pd.DataFrame()\n\n\none_year_before = (datetime.datetime.today()-timedelta(days=365)).strftime(\"%Y%m%d\")\ncal = pro.trade_cal(start_date=one_year_before, end_date=datetime.datetime.today().strftime(\"%Y%m%d\")).sort_values('cal_date',ascending=False)\ncal['cal_date'] = pd.to_datetime(cal['cal_date'])\ntrade_date = cal[cal.is_open==1]['cal_date']\n\nfor i,code in enumerate(all_stocks_dict.keys()):\n\ttry:\n\t\tcurrent_stock = pd.read_sql('SELECT * from \\'{}\\''.format(code),conn)\n\t\tcurrent_stock['date'] = pd.to_datetime(current_stock['date'])\n\texcept:\n\t\tcontinue\n\n\tcurrent_stock['code'] = code\n\tcurrent_stock = current_stock.drop_duplicates()\n\n\tmask_60 = (current_stock['date']>trade_date.iloc[60]) & (current_stock['date']<=trade_date.iloc[0])\n\t#stocks_60 = pd.concat([stocks_60,current_stock.loc[mask_60]],sort=True)\n\tstocks_60[code]= current_stock.loc[mask_60]\n\n\t#mask_90 = (current_stock['date']>trade_date.iloc[90]) & (current_stock['date']<=trade_date.iloc[0])\n\t#stocks_90 = pd.concat([stocks_90,current_stock.loc[mask_90]],sort=True)\n\n\tmask_125 = (current_stock['date']>trade_date.iloc[125]) & (current_stock['date']<=trade_date.iloc[0])\n\t#stocks_120 = pd.concat([stocks_120,current_stock.loc[mask_120]],sort=True)\n\tstocks_125[code]= current_stock.loc[mask_125]\n\n\tpbar.update(i + 1)\n\nst60_df = pd.concat(stocks_60)\nst60_df.to_sql('stocks_60_days',conn,if_exists='replace',index=False)\n\nst125_df = pd.concat(stocks_125)\nst125_df.to_sql('stocks_125_days',conn,if_exists='replace',index=False)\n\npbar.finish()\n\n","sub_path":"stocks_update_shortcut.py","file_name":"stocks_update_shortcut.py","file_ext":"py","file_size_in_byte":5562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"229115301","text":"import keras\nfrom keras.layers import Activation\nfrom keras.layers import Conv2D, BatchNormalization, Dense, Flatten, Reshape\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\n\n\n\ndef train_model(x_train, y_train, x_test, y_test, batch_size=64, ep=2):\n\n model = keras.models.Sequential()\n\n model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same', input_shape=(9,9,1)))\n model.add(BatchNormalization())\n model.add(Conv2D(64, kernel_size=(3,3), activation='relu', padding='same'))\n model.add(BatchNormalization())\n model.add(Conv2D(128, kernel_size=(1,1), activation='relu', padding='same'))\n\n model.add(Flatten())\n model.add(Dense(81*9))\n model.add(Reshape((-1, 9)))\n model.add(Activation('softmax'))\n \n adam = keras.optimizers.adam(lr=.001)\n model.compile(loss='sparse_categorical_crossentropy', optimizer=adam)\n\n print(model.fit(x_train, y_train, batch_size=batch_size, epochs=ep))\n\n model.save('sudoku.model')\n \n \n# score = model.evaluate(x_test, y_test, verbose=0)\n# print('Test loss:', score[0])\n# print('Test accuracy:', score[1])\n \n \n\ndef get_data(file): \n\n data = pd.read_csv(file)\n\n feat_raw = data['quizzes']\n label_raw = data['solutions']\n\n feat = []\n label = []\n\n for i in feat_raw:\n \n x = np.array([int(j) for j in i]).reshape((9,9,1))\n feat.append(x)\n \n feat = np.array(feat)\n feat = feat/9\n feat -= .5 \n \n for i in label_raw:\n \n x = np.array([int(j) for j in i]).reshape((81,1)) - 1\n label.append(x) \n \n label = np.array(label)\n \n del(feat_raw)\n del(label_raw) \n\n x_train, x_test, y_train, y_test = train_test_split(feat, label, test_size=0.2, random_state=42)\n \n train_model(x_train, y_train, x_test, y_test)\n \n return x_train, x_test, y_train, y_test\n\n\n\n\n \n#data = get_data(\"sudoku.csv\")\n","sub_path":"VersionPython/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"415429960","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport math\ndef quadratic(a,b,c):\n\tif not isinstance(a,(int, float)) & isinstance(b,(int, float))& isinstance(c,(int, float)):\n\t\traise TypeError('Unexception input!')\n\tdelta = b*b - 4*a*c\n\tif delta < 0:\n\t\treturn 'This equation has no root'\n\telif delta == 0:\n\t\treturn -b/(2*a)\n\telse:\n\t\troot1 = (-b + math.sqrt(delta)) / (2*a)\n\t\troot2 = (-b - math.sqrt(delta)) / (2*a)\n\t\treturn root1, root2\n","sub_path":"SolveEquation.py","file_name":"SolveEquation.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"654331555","text":"class Solution(object):\r\n def firstMissingPositive(self, nums):\r\n \"\"\"\r\n :type nums: List[int]\r\n :rtype: int\r\n \"\"\"\r\n for i in range(len(nums)):\r\n while nums[i] > 0 and nums[i] <= len(nums) and nums[i] != i + 1 and nums[nums[i] - 1] != nums[i]:\r\n tmp = nums[nums[i] -1]\r\n nums[nums[i] - 1] = nums[i]\r\n nums[i] = tmp\r\n for i in range(len(nums)):\r\n if nums[i] != i + 1:\r\n return i + 1\r\n return len(nums) + 1\r\n\r\n# x = [-10,-3,-100,-1000,-239,1]\r\nx = [3,4,-1,1]\r\ns = Solution()\r\nans = s.firstMissingPositive(x)","sub_path":"First Missing Positive.py","file_name":"First Missing Positive.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"210879086","text":"from __future__ import print_function\nimport numpy as np\nimport datetime\nimport extrapolate as ex\n\ntry:\n import ESMF\nexcept ImportError:\n print(\"Could not find module ESMF\")\n pass\n\n__author__ = 'Trond Kristiansen'\n__email__ = 'me@trondkristiansen.com'\n__created__ = datetime.datetime(2008, 12, 4)\n__modified__ = datetime.datetime(2018, 4, 25)\n__version__ = \"1.5\"\n__status__ = \"Development\"\n\n\ndef laplacefilter(field, threshold, toxi, toeta):\n undef = 2.0e+35\n tx = 0.9 * undef\n critx = 0.01\n cor = 1.6\n mxs = 10\n\n field = np.where(abs(field) > threshold, undef, field)\n\n field = ex.extrapolate.fill(int(1), int(toxi),\n int(1), int(toeta),\n float(tx), float(critx), float(cor), float(mxs),\n np.asarray(field, order='Fortran'),\n int(toxi),\n int(toeta))\n return field\n\n\ndef dohorinterpolationregulargrid(confM2R, mydata):\n if confM2R.showprogress is True:\n import progressbar\n # http://progressbar-2.readthedocs.org/en/latest/examples.html\n progress = progressbar.ProgressBar(widgets=[progressbar.Percentage(), progressbar.Bar()],\n maxval=confM2R.grdMODEL.nlevels).start()\n # progress = progressbar.ProgressBar(widgets=[progressbar.BouncingBar(marker=progressbar.RotatingMarker(), fill_left=True)], maxval=grdMODEL.Nlevels).start()\n\n indexROMS_Z_ST = (confM2R.grdMODEL.nlevels, confM2R.grdROMS.eta_rho, confM2R.grdROMS.xi_rho)\n array1 = np.zeros((indexROMS_Z_ST), dtype=np.float64)\n\n for k in range(confM2R.grdMODEL.nlevels):\n\n if confM2R.useesmf:\n print(np.shape(mydata),k,confM2R.grdMODEL.nlevels)\n confM2R.grdMODEL.fieldSrc.data[:, :] = np.flipud(np.rot90(np.squeeze(mydata[k, :, :])))\n # Get the actual regridded array\n field = confM2R.grdMODEL.regridSrc2Dst_rho(confM2R.grdMODEL.fieldSrc, confM2R.grdMODEL.fieldDst_rho)\n\n # Since ESMF uses coordinates (x,y) we need to rotate and flip to get back to (y,x) order.\n field = np.fliplr(np.rot90(field.data, 3))\n\n if confM2R.usefilter:\n field = laplacefilter(field, 1000, confM2R.grdROMS.xi_rho, confM2R.grdROMS.eta_rho)\n # field=field*grdROMS.mask_rho\n\n array1[k, :, :] = field\n\n # if k in [34,17,2]:\n # import plotData\n # plotData.contourMap(grdROMS, grdROMS.lon_rho, grdROMS.lat_rho, field, str(k)+'_withfilter', myvar)\n # if __debug__:\n # print \"Data range after horisontal interpolation: \", field.min(), field.max()\n\n if confM2R.showprogress is True:\n progress.update(k)\n\n return array1\n\n\ndef dohorinterpolationsshregulargrid(confM2R, myvar, mydata):\n if myvar in [\"uice\"]:\n indexROMS_Z_ST = (confM2R.grdMODEL.nlevels, confM2R.grdROMS.eta_u, confM2R.grdROMS.xi_u)\n toxi = confM2R.grdROMS.xi_u\n toeta = confM2R.grdROMS.eta_u\n mymask = confM2R.grdROMS.mask_u\n elif myvar in [\"vice\"]:\n indexROMS_Z_ST = (confM2R.grdMODEL.nlevels, confM2R.grdROMS.eta_v, confM2R.grdROMS.xi_v)\n toxi = confM2R.grdROMS.xi_v\n toeta = confM2R.grdROMS.eta_v\n mymask = confM2R.grdROMS.mask_v\n else:\n indexROMS_Z_ST = (confM2R.grdMODEL.nlevels, confM2R.grdROMS.eta_rho, confM2R.grdROMS.xi_rho)\n toxi = confM2R.grdROMS.xi_rho\n toeta = confM2R.grdROMS.eta_rho\n mymask = confM2R.grdROMS.mask_rho\n\n array1 = np.zeros((indexROMS_Z_ST), dtype=np.float64)\n\n if confM2R.useesmf:\n\n confM2R.grdMODEL.fieldSrc.data[:, :] = np.flipud(np.rot90(np.squeeze(mydata[:, :])))\n\n if myvar in [\"uice\"]:\n field = confM2R.grdMODEL.regridSrc2Dst_u(confM2R.grdMODEL.fieldSrc, confM2R.grdMODEL.fieldDst_u)\n elif myvar in [\"vice\"]:\n field = confM2R.grdMODEL.regridSrc2Dst_v(confM2R.grdMODEL.fieldSrc, confM2R.grdMODEL.fieldDst_v)\n else:\n field = confM2R.grdMODEL.regridSrc2Dst_rho(confM2R.grdMODEL.fieldSrc, confM2R.grdMODEL.fieldDst_rho)\n\n field = np.fliplr(np.rot90(field.data, 3))\n # if myvar in [\"hice\",\"aice\"]:\n # import plotData\n # plotData.contourMap(grdROMS,grdROMS.lon_rho,grdROMS.lat_rho, field, \"surface\", myvar)\n\n # Smooth the output\n if confM2R.usefilter:\n field = laplacefilter(field, 1000, toxi, toeta)\n field = field * mymask\n array1[0, :, :] = field\n\n # import plotData\n # plotData.contourMap(grdROMS, tolon, tolat, field, \"34\", myvar)\n\n return array1\n","sub_path":"interp2D.py","file_name":"interp2D.py","file_ext":"py","file_size_in_byte":4637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"392360662","text":"import Tkinter as tk\nimport threading\nimport logging\nimport time\nimport sys\n\nimport thread1\n\nclass InRedirector():\n def __init__(self, outRedirector):\n sys.stdin = self\n self.outRedirector = outRedirector\n \n def readline(self):\n line = self.outRedirector.getInputLine()\n while not line:\n line = self.outRedirector.getInputLine()\n time.sleep(0.1)\n return line\n\nclass OutRedirector(tk.Text):\n def __init__(self, *args, **kwargs):\n tk.Text.__init__(self, *args, **kwargs)\n sys.stdout = self\n self.input_buffer = \"\"\n self.input_lines = []\n self.bind(\"\", self.key)\n sys.stdin = InRedirector(self)\n\n def key(self, key):\n if key.char:\n self.input_buffer += key.char\n if key.char == \"\\r\" or key.char == \"\\n\":\n self.input_lines.append(self.input_buffer[:-1] + \"\\n\")\n self.input_buffer = \"\"\n\n def getInputLine(self):\n if self.input_lines == []:\n return None\n else:\n line = self.input_lines[0]\n self.input_lines = self.input_lines[1:]\n return line\n\n def write(self, s):\n self.insert(\"end\", s)\n self.update()\n\nclass ErrorHandler(tk.Text):\n def __init__(self, *args, **kwargs):\n tk.Text.__init__(self, *args, **kwargs)\n self.config(state=\"disabled\")\n \n def write(self, s):\n self.config(state=\"normal\")\n self.insert(\"end\", s)\n self.config(state=\"disabled\")\n self.update()\n\n def flush(self):\n pass\n\ndef main():\n root = tk.Tk()\n\n text = OutRedirector(root)\n text.grid()\n\n err = ErrorHandler(root)\n err.grid()\n\n logger = logging.getLogger(\"error_logger\")\n logger.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler(err)\n handler.setLevel(logging.DEBUG)\n\n formatter = logging.Formatter('%(message)s')\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n\n info = {'stop' : False}\n thread = threading.Thread(target=thread1.fun, args=(info,))\n thread.daemon = True\n thread.start()\n\n root.mainloop()\n\nif __name__ == '__main__':\n main()","sub_path":"pmagnus-programs/graphics/threading/graphical_thread_logger.py","file_name":"graphical_thread_logger.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"628677190","text":"#!/usr/bin/env python\n# *-* coding: UTF-8 *-*\n\n# Copyright 2012-2022 Ronald Römer\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nsys.path.extend(['/home/zippy/vtkbool/build/lib/python3.10/site-packages/vtkbool'])\n\nfrom vtkBool import vtkPolyDataBooleanFilter\n\nfrom vtkmodules.vtkFiltersSources import vtkSphereSource, vtkLineSource\nfrom vtkmodules.vtkFiltersCore import vtkTubeFilter\nfrom vtkmodules.vtkIOLegacy import vtkPolyDataWriter\nfrom vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter\nfrom vtkmodules.vtkCommonTransforms import vtkTransform\n\nfrom collections import defaultdict\n\nsphere = vtkSphereSource()\nsphere.SetRadius(5)\nsphere.SetCenter(.5, .5, .5)\nsphere.SetPhiResolution(100)\nsphere.SetThetaResolution(100)\nsphere.Update()\n\npd = sphere.GetOutput()\n\ncenter = pd.GetCenter()\n\nline = vtkLineSource()\nline.SetPoint1(0, 0, 0)\nline.SetPoint2(0, 0, 4)\n\ntube = vtkTubeFilter()\ntube.SetInputConnection(line.GetOutputPort())\ntube.SetRadius(1)\ntube.SetNumberOfSides(50)\ntube.CappingOn()\n\ntransform = vtkTransform()\ntransform.PostMultiply()\ntransform.Translate(center[0], center[1], center[2]+3)\n\ntf = vtkTransformPolyDataFilter()\ntf.SetInputConnection(tube.GetOutputPort())\ntf.SetTransform(transform)\n\nmoves = [(-.5, 0), (-.5, 0), (-.5, 0), (-.5, 0), (-.5, 0), (-.5, 0), (-.5, 0), (-.5, 0), (-.5, 0)]\n\n# moves = [(.5, 0), (.5, 0), (.5, 0), (.5, 0),\n# (0, -.5), (0, -.5), (0, -.5), (0, -.5),\n# (-.5, 0), (-.5, 0), (-.5, 0), (-.5, 0),\n# (0, .5)]\n\n# moves = [(0, -.5), (0, -.5), (0, -.5), (0, -.5), (0, -.5), (0, -.5), (0, -.5)]\n\nfor i, xy in enumerate(moves):\n transform.Translate(*xy, 0)\n\n bf = vtkPolyDataBooleanFilter()\n bf.SetInputData(0, pd)\n bf.SetInputConnection(1, tf.GetOutputPort())\n bf.SetOperModeToDifference()\n\n writer = vtkPolyDataWriter()\n writer.SetFileName(f'sphere{i}.vtk')\n writer.SetInputData(pd)\n writer.Update()\n\n writer2 = vtkPolyDataWriter()\n writer2.SetFileName(f'tube{i}.vtk')\n writer2.SetInputConnection(tf.GetOutputPort())\n writer2.Update()\n\n writer3 = vtkPolyDataWriter()\n writer3.SetFileName(f'bool{i}.vtk')\n writer3.SetInputConnection(bf.GetOutputPort())\n writer3.Update()\n\n pd.Initialize()\n pd.DeepCopy(bf.GetOutput())\n","sub_path":"testing/milling/milling.py","file_name":"milling.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"562434533","text":"from PIL import Image\nfrom PIL import ImageDraw\nfrom Graph import Node\nimport shutil\nimport os\nfrom typing import Tuple, Dict, List\n\n\ndef draw_picture(size: int,\n paths: Dict[Tuple[Node, Node], List[Node]]) -> None:\n \"\"\"Эта функция отрисовывает все пути в соотвествии со словарем\"\"\"\n if os.path.exists('tmp'):\n shutil.rmtree(\"tmp\")\n os.mkdir(\"./tmp\")\n image = Image.new('RGB', (50 * size, 50 * size), \"black\")\n draw = ImageDraw.ImageDraw(image)\n count = 0\n for pair in paths:\n for point in pair:\n draw.rectangle(\n [(point.number[0] * 50, point.number[1] * 50),\n (point.number[0] * 50 + 50, point.number[1] * 50 + 50)],\n fill=point.color)\n cell_map(size, image, (192, 192, 192))\n image.save(f'tmp/{count}.jpg')\n count += 1\n for key in paths:\n for node in paths[key][1:-1]:\n draw.rectangle([(node.number[0]*50, node.number[1]*50),\n (node.number[0]*50+50, node.number[1]*50+50)],\n fill=node.color)\n\n cell_map(size, image, (192, 192, 192))\n image.save(f'tmp/{count}.jpg')\n count += 1\n image.save('grid_img.png', 'PNG')\n\n\ndef cell_map(size: int, img: Image, color: Tuple[int, int, int]) -> Image:\n \"\"\"Разлиновывет поле\"\"\"\n draw = ImageDraw.Draw(img)\n for i in range(50, 50 * size, 50):\n draw.line([(i, 0), (i, 50 * size - 1)], fill=color, width=2)\n for j in range(50, 50 * size, 50):\n draw.line([(0, j), (50 * size - 1), j], fill=color, width=2)\n\n return img\n","sub_path":"numberlink/Drawing.py","file_name":"Drawing.py","file_ext":"py","file_size_in_byte":1685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"422947687","text":"import pygame, sys\n\n\ndef physics(screen, items_on_screen, screen_dimensions, program_clock):\n \n running = True\n horizontal_velocity = 0\n vertical_velocity = 0\n horizontal_acceleration = 0\n vertical_acceleration = 0\n #item_on_screen\n #[SQLID, Name, Inital Location X, Inital Location y, width, height, button alternate 1, butotn alternate 2]\n #velocity = vel init + accel * time\n #screen_dimesions = {\n # \"screen_width\" : width,\n # \"screen_height\" : height,\n # \"width_unit\" : width_unit,\n # \"height_unit\" : height_unit,\n # \"width_in_units\": width_in_units,\n # \"height_in_units\" : height_in_units}\n\n #keys\n #a = 97 w = 119 s = 115 d = 100\n\n while running == True:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n\n\n if event.type == pygame.KEYDOWN:\n pressed_keys = pygame.key.get_pressed()\n if pressed_keys[97] == 1:\n print(\"a\")\n horizontal_acceleration = horizontal_acceleration - 3\n if pressed_keys[119] == 1:\n print(\"w\")\n vertical_acceleration = vertical_acceleration - 3\n if pressed_keys[115] == 1:\n print(\"s\")\n vertical_acceleration = vertical_acceleration + 3\n if pressed_keys[100] == 1:\n print(\"d\")\n horizontal_acceleration = horizontal_acceleration + 3\n \n #updates all items on the screen each loop\n for item in items_on_screen:\n if item[1] == 'start':\n item_surface = pygame.transform.scale(pygame.image.load(item[8]),(item[4]*screen_dimensions[\"width_unit\"],item[5]*screen_dimensions[\"height_unit\"]))\n screen.blit(item_surface, (item[2]*screen_dimensions[\"width_unit\"]+horizontal_velocity,item[3]*screen_dimensions[\"height_unit\"]+vertical_velocity))\n else:\n item_surface = pygame.transform.scale(pygame.image.load(item[8]),(item[4]*screen_dimensions[\"width_unit\"],item[5]*screen_dimensions[\"height_unit\"]))\n screen.blit(item_surface, (item[2]*screen_dimensions[\"width_unit\"],item[3]*screen_dimensions[\"height_unit\"]))\n\n pygame.display.flip()\n pygame.display.quit()\n pygame.quit()","sub_path":"functions/physics_functions.py","file_name":"physics_functions.py","file_ext":"py","file_size_in_byte":2370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"161450853","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 16 16:39:52 2019\n\n@author: xcxg109\n\"\"\"\n\nimport pandas as pd\nimport query_code as q\nimport data_pull as pull\nimport data_process as process\nimport file_data_att as fd\nimport settings\nfrom queries_PIM import grainger_attr_query\nimport time\n\n\npd.options.mode.chained_assignment = None\n\n\ndef match_category(df):\n \"\"\"compare data colected from matching file (match_df) with grainger and gamut data pulls and create a column to tell analysts\n whether attributes from the two systems have been matched\"\"\"\n\n for row in df.itertuples():\n if (row.Index, row.Grainger_Attribute_Name) == (row.Index, row.Gamut_Attribute_Name):\n df.at[row.Index,'Matching'] = 'Match'\n elif process.isBlank(row.Grainger_Attribute_Name) == False:\n if process.isBlank(row.Gamut_Attribute_Name) == True:\n df.at[row.Index,'Matching'] = 'Grainger only'\n elif process.isBlank(row.Grainger_Attribute_Name) == True:\n if process.isBlank(row.Gamut_Attribute_Name) == False:\n df.at[row.Index,'Matching'] = 'Gamut only'\n \n return df\n\n\ndef grainger_process(grainger_df, grainger_sample, grainger_all, k):\n \"\"\"create a list of grainger skus, run through through the gamut_skus query and pull gamut attribute data if skus are present\n concat both dataframs and join them on matching attribute names\"\"\"\n \n df = pd.DataFrame()\n gamut_sample_vals = pd.DataFrame()\n gamut_att_vals = pd.DataFrame()\n # gamut_l3 = dict()\n \n grainger_skus = grainger_df.drop_duplicates(subset='Grainger_SKU') #create list of unique grainger skus that feed into gamut query\n grainger_sku_count = len(grainger_skus)\n print('Grainger SKU count = ', grainger_sku_count)\n\n grainger_df = grainger_df.drop_duplicates(subset=['Category_ID', 'Grainger_Attr_ID']) #group by Category_ID and attribute name and keep unique\n grainger_df['Grainger Blue Path'] = grainger_df['Segment_Name'] + ' > ' + grainger_df['Family_Name'] + \\\n ' > ' + grainger_df['Category_Name']\n grainger_df = grainger_df.drop(['Grainger_SKU', 'Grainger_Attribute_Value'], axis=1) #remove unneeded columns\n grainger_df = pd.merge(grainger_df, grainger_sample, on=['Grainger_Attribute_Name'])\n grainger_df = pd.merge(grainger_df, grainger_all, on=['Grainger_Attribute_Name'])\n \n grainger_df['Grainger_Attribute_Name'] = process.process_att(grainger_df['Grainger_Attribute_Name']) #prep att name for merge\n grainger_df.to_csv (\"F:/CGabriel/Grainger_Shorties/OUTPUT/grainger_test.csv\")\n \n gamut_skus = q.gamut_skus(grainger_skus) #get gamut sku list to determine pim nodes to pull\n gamut_skus = gamut_skus.drop_duplicates(subset='Gamut_SKU')\n\n # gamut_sku_counts = gamut_sku_list.groupby('Gamut_SKU')['Gamut_SKU']).count())\n if gamut_skus.empty == False:\n #create a dictionary of the unique gamut nodes that corresponde to the grainger node\n gamut_l3 = gamut_skus['Gamut_Node_ID'].unique() #create list of pim nodes to pull\n for node in gamut_l3:\n gamut_df = q.gamut_atts(node, 'tax.id') #tprod.\"categoryId\"') #get gamut attribute values for each gamut_l3 node\n gamut_att_vals, gamut_sample_vals = q.gamut_values(gamut_df) #gamut_values exports a list of --all-- normalized values (temp_df) and sample_values\n gamut_sample_vals = gamut_sample_vals.rename(columns={'Normalized Value': 'Gamut Attribute Sample Values'})\n gamut_att_vals = gamut_att_vals.rename(columns={'Normalized Value': 'Gamut ALL Values'})\n \n gamut_df = gamut_df.drop_duplicates(subset='Gamut_Attr_ID') #gamut attribute IDs are unique, so no need to group by pim node before getting unique\n gamut_df = gamut_df.drop(['Gamut_SKU', 'Grainger_SKU', 'Original Value', 'Normalized Value'], axis=1) #normalized values are collected as sample_value\n \n grainger_df['Gamut_Node_ID'] = int(node) #add correlating gamut node to grainger_df\n\n gamut_df = pd.merge(gamut_df, gamut_sample_vals, on=['Gamut_Attribute_Name']) #add t0p 5 normalized values to report\n gamut_df = pd.merge(gamut_df, gamut_att_vals, on=['Gamut_Attribute_Name']) #add t0p 5 normalized values to report\n gamut_df['Category_ID'] = int(k) #add grainger Category_ID column for gamut attributes\n gamut_df['Gamut_Attribute_Name'] = process.process_att(gamut_df['Gamut_Attribute_Name']) #prep att name for merge\n #create df based on names that match exactly\n gamut_df.to_csv (\"F:/CGabriel/Grainger_Shorties/OUTPUT/gamut_test.csv\")\n \n temp_df = pd.merge(grainger_df, gamut_df, left_on=['Grainger_Attribute_Name', 'Category_ID', 'Gamut_Node_ID'], \n right_on=['Gamut_Attribute_Name', 'Category_ID', 'Gamut_Node_ID'], how='outer')\n temp_df = match_category(temp_df) #compare grainger and gamut atts and create column to say whether they match\n temp_df['Grainger-Gamut Terminal Node Mapping'] = temp_df['Category_Name']+' -- '+ temp_df['Gamut_Node_Name']\n\n df = pd.concat([df, temp_df], axis=0) #add prepped df for this gamut node to the final df\n\n\n return df #where gamut_att_temp is the list of all normalized values for gamut attributes\n \n\n#determine SKU or node search\nsearch_level = 'cat.CATEGORY_ID'\n\ngamut_df = pd.DataFrame()\ngrainger_df = pd.DataFrame()\ngrainger_skus = pd.DataFrame()\n\nattribute_df = pd.DataFrame()\ngrainger_att_vals = pd.DataFrame()\ngrainger_sample_vals = pd.DataFrame()\ngamut_att_vals = pd.DataFrame\n\ndata_type = fd.search_type()\n\nif data_type == 'grainger_query':\n search_level = fd.blue_search_level()\n \nsearch_data = fd.data_in(data_type, settings.directory_name)\n\nstart_time = time.time()\nprint('working...')\n\nif data_type == 'grainger_query':\n if search_level == 'cat.CATEGORY_ID':\n for k in search_data:\n grainger_df = q.gcom.grainger_q(grainger_attr_query, search_level, k)\n if grainger_df.empty == False:\n grainger_att_vals, grainger_sample_vals = q.grainger_values(grainger_df)\n grainger_sample_vals = grainger_sample_vals.rename(columns={'Grainger_Attribute_Value': 'Grainger Attribute Sample Values'})\n grainger_att_vals = grainger_att_vals.rename(columns={'Grainger_Attribute_Value': 'Grainger ALL Values'})\n temp_df = grainger_process(grainger_df, grainger_sample_vals, grainger_att_vals, k)\n attribute_df = pd.concat([attribute_df, temp_df], axis=0, sort=False)\n print ('Grainger ', k)\n else:\n print('No attribute data')\n else:\n for k in search_data:\n temp_df = q.grainger_nodes(k, search_level)\n grainger_skus = pd.concat([grainger_skus, temp_df], axis=0, sort=False)\n grainger_l3 = grainger_skus['Category_ID'].unique() #create list of pim nodes to pull\n print('graigner L3s = ', grainger_l3)\n for k in grainger_l3:\n grainger_df = q.gcom.grainger_q(grainger_attr_query, 'cat.CATEGORY_ID', k)\n if grainger_df.empty == False:\n grainger_att_vals, grainger_sample_vals = q.grainger_values(grainger_df)\n grainger_sample_vals = grainger_sample_vals.rename(columns={'Grainger_Attribute_Value': 'Grainger Attribute Sample Values'})\n grainger_att_vals = grainger_att_vals.rename(columns={'Grainger_Attribute_Value': 'Grainger ALL Values'})\n temp_df = grainger_process(grainger_df, grainger_sample_vals, grainger_att_vals, k)\n attribute_df = pd.concat([attribute_df, temp_df], axis=0, sort=False)\n print ('Grainger ', k)\n else:\n print('No attribute data') \n\n# attribute_df['Grainger-Gamut Terminal Node Mapping'] = attribute_df['Category_Name']+' -- '+attribute_df['Gamut_Node_Name']\nattribute_df = attribute_df.drop(['Count_x', 'Count_y'], axis=1)\n\n#attribute_df['Identified Matching Gamut Attribute Name (use semi-colon to separate names)'] = \"\"\n#attribute_df['Identified Matching Grainger Attribute Name (use semi-colon to separate names)'] = \"\"\n#attribute_df['Analyst Notes'] = \"\"\n#attribute_df['Taxonomist Approved (yes/no)'] = \"\"\n#attribute_df['Taxonomist Notes'] = \"\"\n\n#pull.previous_match(attribute_df)\n\n#data = process.attribute_name_match(attribute_df)\n\nfd.attribute_match_data_out(settings.directory_name, attribute_df, search_level)\n\nprocess.attribute_name_match(attribute_df)\n \n \nprint(\"--- {} seconds ---\".format(round(time.time() - start_time, 2)))","sub_path":"z. old/ATTRIBUTE_MATCH old.py","file_name":"ATTRIBUTE_MATCH old.py","file_ext":"py","file_size_in_byte":8774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"228499114","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport cv2\nimport time\nimport math\n\nRED = 0\nWHITE = 1\nBLUE = 2\nYELLOW = 3\nGREEN = 4\n\nred = [0.93365103, 0.35130355, 0.28260624] #Light\n#red = [0.83925676, 0.19983858, 0.15198655] #Dark\nwhite = [1, 1, 1]\n#orange = [0.99148726, 0.5729994, 0.25187913]\n#yellow = [0.9834839 , 1, 0.76263994]\n#yellow = [0.99455225, 0.9999614 , 0.5426788 ] #brighter\nyellow = [0.9834429 , 0.9999806 , 0.62282646]\ngreen = [0.61612934, 0.90352577, 0.5615079 ]\n#blue = [0.501899 , 0.89933634, 0.99078834]\nblue = [0.38518488, 0.8185951 , 0.96491045]\n\ndef displayImage(images, nrows = 1, ncols=1, title=[],image_max=0,sizex=15,sizey=8):\n #Handle the case of 1 image\n if nrows == 1 and ncols == 1:\n images = [images]\n #Mismatch\n if len(images) != nrows*ncols:\n print(\"Number of images != number of subplots\")\n return\n #Title mismathc\n if len(images) != len(title) and len(title)!=0:\n print(\"Number of images != number of titles\")\n return\n fig = plt.figure(figsize=(sizex,sizey))\n ax = []\n for i in range(1, ncols*nrows +1):\n image = images[i-1]\n\n #Deal for various types\n type = image.dtype\n if np.issubdtype(type, np.integer):\n if image_max==0:\n im_max = np.iinfo(type).max\n else:\n im_max=copy.deepcopy(image_max)\n else:\n im_max = 1\n\n plt.gray()\n ax.append( fig.add_subplot(nrows, ncols,i))\n if len(title)!=0:\n ax[-1].set_title(title[i-1])\n plt.axis(\"off\")\n plt.imshow(image,vmin=0,vmax=im_max)\n plt.show()\n return ax\n\ndef getColours():\n red = plt.imread(\"red_light.png\")\n purple = plt.imread(\"purple.png\")\n blue = plt.imread(\"blue.png\")\n yellow = plt.imread(\"yellow.png\")\n green = plt.imread(\"green.png\")\n #blue = plt.imread(\"blue.png\")\n return [red,purple,blue,yellow,green]\n\ndef getAverages(colours):\n avs = []\n for c in colours:\n av = np.mean(c,axis=(0,1))\n avs.append(av[0:3])\n return avs\n\ndef distIm(c1,c2):\n return c1-c2\n\ndef drawOnFeed(frame,cs):\n avs = [red,white,blue,yellow,green]\n for i in range(len(avs)):\n if not(np.isnan(cs[i][0]) or np.isnan(cs[i][1])):\n #newCol = (int(avs[i][2]*255),int(avs[i][1]*255),int(avs[i][0]*255)) #Reversed because BGR\n newCol = (0,0,0)\n newC = (int(round(cs[i][1])),int(round(cs[i][0]))) #Reversed because image\n cv2.circle(frame,newC,5,newCol,2)\n\ndef findCenters(image,tol=0.05,draw=False,frame=None):\n avs = [red,white,blue,yellow,green]\n cs = []\n uR = red+np.ones(3)*tol\n lR = red-np.ones(3)*tol\n uW = white+np.ones(3)*tol\n lW = white-np.ones(3)*tol\n uB = blue+np.ones(3)*tol\n lB = blue-np.ones(3)*tol\n uY = yellow+np.ones(3)*tol\n lY = yellow-np.ones(3)*tol\n uG = green+np.ones(3)*tol\n lG = green-np.ones(3)*tol\n u = [uR,uW,uB,uY,uG]\n l = [lR,lW,lB,lY,lG]\n for i in range(5):\n mask = cv2.inRange(image, l[i], u[i])\n res = cv2.bitwise_and(image,image, mask= mask)\n pix = np.where(mask==255)\n pixels = np.array([pix[0],pix[1]])\n centre = np.mean(pixels,axis=1)\n cs.append(centre)\n if draw and frame is not None:\n drawOnFeed(frame,cs)\n return cs\n\ndef calibrate():\n test = plt.imread(\"test.png\")[:,:,0:3]\n colours = getColours()\n testCols = []\n avs = getAverages(colours)\n for av in avs:\n testIm = np.ones((200,200,3))\n for x in range(200):\n for y in range(200):\n testIm[x,y,:] = av\n testCols.append(testIm)\n cs = findCenters(test)\n dispCols = colours+testCols\n displayImage(dispCols,2,5)\n fig, ax = plt.subplots()\n ax.imshow(test)\n for c in cs:\n ax.scatter(c[1], c[0], s=50, color='cyan')\n plt.show()\n print(avs)\n\nif __name__ == \"__main__\":\n calibrate()\n","sub_path":"colour.py","file_name":"colour.py","file_ext":"py","file_size_in_byte":3934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"358697493","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 26 09:12:44 2020\r\n\r\n@author: Anup0\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.ensemble import RandomForestClassifier,GradientBoostingClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import roc_auc_score, accuracy_score,classification_report,confusion_matrix\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\npath=\"D:/Nikhil Analytics/Python/Project/New project/\"\r\nCcard_data=pd.read_csv(path + \"creditcard.csv\",header=0)\r\nCcard_data.head()\r\nCcard_data.shape\r\nCcard_data.describe()\r\nCcard_data.isnull().sum()\r\n\r\n\r\nsns.countplot(Ccard_data.Class,label=\"class\",color=\"red\")\r\n\r\n# Target variable has value 0 very large compared to value 1.\r\n\r\ntarget0=Ccard_data[Ccard_data.Class==0]\r\nprint(len(target0))\r\ntarget1=Ccard_data[Ccard_data.Class==1]\r\nprint(len(target1))\r\n\r\nbalanced_data=pd.concat([target1,target0.sample(n=len(target1),random_state=10)])\r\n#Doubt1\r\n\r\n\r\nsns.countplot(balanced_data.Class,label=\"class\",color=\"green\")\r\n\r\nbalanced_data.describe()\r\n#Doubt2\r\n\r\n# Now target variable is balanced\r\n\r\nX=balanced_data.iloc[:,:-1]\r\nY=balanced_data.iloc[:,-1]\r\n\r\ntrain_x,test_x,train_y,test_y=train_test_split(X,Y,test_size=0.3,random_state=10)\r\n\r\n\r\n#USING RANDOM FOREST:-\r\n\r\nrandom_model=RandomForestClassifier(n_estimators=20,criterion=\"entropy\")\r\nrandom_model.fit(train_x,train_y)\r\npred_y=random_model.predict(test_x)\r\n\r\nprint(roc_auc_score(test_y, pred_y)) #0.9388668218965438\r\nprint(accuracy_score(test_y,pred_y)) #0.9391891891891891\r\nprint(confusion_matrix(test_y,pred_y))\r\n#[[147 2]\r\n#[ 16 131]]\r\nprint(classification_report(test_y,pred_y))\r\n\r\n# 0 0.90 0.99 0.94 149\r\n# 1 0.98 0.89 0.94 147\r\n\r\n# Using logistic regression:-\r\n\r\nlogistic=LogisticRegression(random_state=10).fit(train_x,train_y)\r\npred_y=logistic.predict(test_x)\r\n\r\nprint(accuracy_score(test_y,pred_y)) #0.902027027027027\r\nprint(confusion_matrix(test_y,pred_y))\r\n# [[138 11]\r\n# [ 18 129]]\r\nprint(classification_report(test_y,pred_y))\r\n# 0 0.88 0.93 0.90 149\r\n# 1 0.92 0.88 0.90 147\r\n\r\n\r\n# Using Gradient Boosting clasifier:- \r\n\r\ngbm_model=GradientBoostingClassifier(random_state=10).fit(train_x,train_y)\r\npred_y=gbm_model.predict(test_x) \r\n\r\nprint(accuracy_score(test_y,pred_y)) #0.9256756756756757\r\nprint(confusion_matrix(test_y,pred_y))\r\n#[[144 5]\r\n #[ 17 130]]\r\nprint(classification_report(test_y,pred_y))\r\n# 0 0.89 0.97 0.93 149\r\n# 1 0.96 0.88 0.92 147\r\n\r\n\"\"\"\r\nProject is about CREDIT CARD fraud transactions which I did using python, \r\npackages used are pandas,seaborn and sklearn.\r\nStarted by extracting data in pandas dataframe and checking for null values, which were absent.\r\nChecked for unbalanced data by plotting count graph of target variable.\r\nAs the data was unbalanced, balanced the data by concatinating.\r\nProceeded and declared feature and target variables, using new balanced dataset. (Didn't drop any columns') \r\nI put 'class' as Y, then splitted the data set into train and test with test size 30%\r\nSince, it is an unbalanced dataset, I used random forest first to create model.\r\nI used classifier instead of regressor because data is descrete.\r\nCriterion as entropy instead of gini for more accuracy.\r\nFinally checked the accuracy of model by comparing test sample of y with predicted y using the model.\r\nSince the data is unbalanced, used roc_auc_score to measure the accuracy of the model. \r\nUsing the above parameters , I got an acuuracy of - 0.9388668218965438 (best fit)\r\nI also created model using gradient boosting and logistic regression.\r\nThe best accuracy was achieved by random forest.\r\n\"\"\"\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"CreditCard_Anup.py","file_name":"CreditCard_Anup.py","file_ext":"py","file_size_in_byte":3862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"361085245","text":"import sys\n\nplayer_names = []\nplayer_symbols = []\nlines_to_check = []\n\ndef populate_lines_to_check():\n lines_to_check = []\n for r in range(n):\n lines_to_check.append((r, 0, 0, 1)) # horizontal row\n\n for c in range(n):\n lines_to_check.append((0, c, 1, 0)) # vertical column\n\n lines_to_check.append((0, 0, 1, 1)) # left diag\n lines_to_check.append((0, n - 1, 1, -1)) # right diag\n\ndef declare_board():\n global board\n global n\n print(\"Enter size of board (n)\")\n n=int(input())\n board = [[' ']*n for _ in range(n)]\n populate_lines_to_check()\n\ndef print_board():\n for r in range(n):\n s = \" | \".join(board[r])\n print(s)\n print('-'*len(s))\n\ndef get_player_info():\n global player_symbols\n global player_names\n\n player1_name = input(\"Enter player1 name:\")\n player2_name = input(\"Enter player2 name:\")\n player_names=[player1_name, player2_name]\n while True:\n print(player_names[0], \"Would you like to be X or 0?\")\n symbol = input().upper()\n if symbol =='X':\n other_symbol ='0'\n elif symbol == '0':\n other_symbol='X'\n else:\n print(\"Please enter a valid symbol, {} is not a symbol !\" % (symbol))\n continue\n player_symbols = [symbol, other_symbol]\n break\n\nclass GameResult:\n def __init__(self, terminated, who_won):\n self.terminated = terminated\n assert who_won >= -1 and who_won <= 1\n self.who_won = who_won\n\n def is_game_on(self):\n return not self.terminated\n\n def is_won(self):\n return self.terminated and self.who_won >= 0\n\n def __repr__(self):\n return \"({}, {})\".format(self.terminated, self.who_won)\n\ndef main_game():\n game_on = True\n player_one_playing = True\n\n while(game_on):\n print_board()\n get_correct_user_input(0 if player_one_playing else 1)\n game_result = get_game_result()\n game_on = game_result.is_game_on()\n if not game_on:\n if game_result.who_won == -1:\n print(\"Its a Tie!!\")\n else:\n print(player_names[game_result.who_won], \"Won\")\n else:\n player_one_playing = not player_one_playing\n\ndef get_correct_user_input(turn):\n print(player_names[turn]+\"'s turn\")\n print(\"Enter row and col number\")\n while True:\n try:\n p_in_r,p_in_c=input().split( )\n p_in_r=int(p_in_r)\n p_in_c=int(p_in_c)\n except ValueError:\n sys.stderr.write(\"Sorry, I didn't understand that.Please enter a valid index\")\n continue\n if p_in_r>n-1 or p_in_r<0 or p_in_c>n-1 or p_in_c<0:\n sys.stderr.write(\"Wrong index, please choose within 0 and n\\n\")\n continue\n elif board[p_in_r][p_in_c]!=' ':\n sys.stderr.write(\"Cell already filled, please choose an empty cell\")\n continue\n else:\n break\n board[p_in_r][p_in_c]=player_symbols[turn]\n\ndef check_line(start_r, start_c, del_r, del_c):\n r = start_r\n c = start_c\n symbols_in_row = set()\n for _ in range(n):\n symbols_in_row.add(board[r][c])\n r += del_r\n c += del_c\n\n if ' ' in symbols_in_row:\n return GameResult(False, -1)\n elif len(symbols_in_row) == 1:\n # Someone won a row, lets check who\n return GameResult(True, player_symbols.index(list(symbols_in_row)[0]))\n else:\n assert len(symbols_in_row) == 2\n return GameResult(True, -1)\n\n# This can be tersified up even further by definining lines to iterate upon\n# we can decouple the code that checks the lines vs the code that generates the lines to iterate upon\ndef get_game_result():\n unfilled_lines = 0\n for line in lines_to_check:\n game_result = check_line(*line)\n sys.stderr.write(\"For line {}, the result is {}\\n\".format(line, game_result))\n if game_result.is_won():\n return game_result\n elif not game_result.terminated:\n unfilled_lines += 1\n \n # There are no winners\n if unfilled_lines > 0:\n # There were unfilled lines, so it can't be a tie\n return GameResult(False, -1)\n else:\n # All lines are tied, and hence the game is tied\n return GameResult(True, -1)\n\ndef play_again():\n print(\"Would you like to play again?\")\n user = input()\n return user.upper() == 'Y'\n\ndef play_one_time():\n declare_board()\n get_player_info()\n main_game()\n\ndef seq():\n while True:\n play_one_time()\n if not play_again():\n break\n\nseq()\n","sub_path":"tictactoe/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":4602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"} +{"seq_id":"489265048","text":"from email.mime.text import MIMEText\nfrom email.header import Header\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email import encoders\nfrom openpyxl.chart import BarChart, Reference\nfrom datetime import datetime\nfrom flask_init import *\nimport smtplib, ssl\nimport codecs\nimport pandas as pd\nimport re\nimport openpyxl\nimport shutil\nimport os\nimport constants\n\n\ndef send_reports_email(port, smtp_server, sender_email, receiver_email, password, email_content):\n \"\"\"\n \"\"\"\n context = ssl.create_default_context()\n with smtplib.SMTP(smtp_server, port) as server:\n server.ehlo() # Can be omitted\n server.starttls(context=context)\n server.ehlo() # Can be omitted\n server.login(sender_email, password)\n server.sendmail(sender_email, receiver_email, email_content)\n server.quit()\n\n\ndef archive_reports():\n \"\"\"\n \"\"\"\n report_paths = get_report_paths()\n for path in report_paths:\n basedir, filename = os.path.split(path)\n new_path = os.path.join(basedir, 'Archive/', filename)\n shutil.move(path, new_path)\n\n\ndef get_report_paths():\n \"\"\"\n \"\"\"\n report_paths = list(filter(lambda file_path: os.path.isfile(file_path), map(lambda filename: os.path.join(constants.REPORTS_PATH, filename), os.listdir(constants.REPORTS_PATH))))\n return report_paths\n\n\ndef generate_basic_report(table_name, form_html_filename):\n \"\"\"\n \"\"\"\n # eg. [{hebrew_description: hebrewtext, english_name: englishtext}, {}, ...]\n medical_full_tbl_df = pd.read_sql_query(\"SELECT * FROM {0}\".format(table_name), db.engine)\n input_hebrew_descs_to_names = english_input_name_to_hebrew_desc(os.path.join(constants.WORKING_DIR, 'templates/{0}'.format(form_html_filename)))\n # will be used for replacement of df column names from english to hebrew\n df_col_name_replacement_dict = {}\n for hebrew_english_link in input_hebrew_descs_to_names:\n df_col_name_replacement_dict[hebrew_english_link[\"english_name\"]] = hebrew_english_link[\"hebrew_description\"]\n\n medical_full_tbl_df = medical_full_tbl_df.rename(columns=df_col_name_replacement_dict)\n medical_full_tbl_df = medical_full_tbl_df.replace([\"yes\", \"no\"], [\"כן\", \"לא\"])\n medical_full_tbl_df = medical_full_tbl_df.drop(\"_id\", axis=1)\n return medical_full_tbl_df\n \n \ndef english_input_name_to_hebrew_desc(html_path):\n \"\"\"\n link between /