diff --git "a/6243.jsonl" "b/6243.jsonl" new file mode 100644--- /dev/null +++ "b/6243.jsonl" @@ -0,0 +1,641 @@ +{"seq_id":"346136792","text":"import threading, thread, time, os, shutil, traceback\nfrom hashlib import sha1\nimport urllib, requests\nfrom logger import logger as log\nimport utils\n\nBASE_URL = \"https://developer.api.bitcasa.com/v1/files/\"\n\nclass SizeMismatchError(Exception):\n pass\n\nclass RunThreaded(threading.Thread):\n def __init__(self, item, thread_num, parent):\n threading.Thread.__init__(self, name=(thread_num+1))\n self.nm = item[\"filename\"]\n self.base64path = item[\"filepath\"]\n self.size_bytes = item[\"filesize\"]\n self.size_str = utils.convert_size(self.size_bytes)\n self.thread_num = thread_num\n self.fulldest = item[\"filedir\"]\n\n self.prt = parent\n self.destpath = item[\"fullpath\"]\n self.tmppath = \"\"\n\n def run(self):\n sizecopied = 0\n if self.prt.tmp:\n fulltmp = self.prt.tmp\n else:\n fulltmp = self.fulldest\n\n params = {\"access_token\":self.prt.accesstoken, \"path\":self.base64path}\n \n log.info(\"%s size %s\", self.nm, self.size_str)\n\n try:\n apidownloaduri = \"%s%s?%s\" % (BASE_URL, urllib.quote_plus(self.nm), urllib.urlencode(params))\n except KeyError:\n self.cleanUpAfterError(\"Error unsupported characters in filename %s\" % self.nm, self.destpath)\n except: \n #This technically should never happen but technically you never know\n self.cleanUpAfterError(traceback.format_exc(), self.destpath)\n\n if not os.path.exists(self.fulldest) or (self.prt.tmp and not os.path.exists(fulltmp)):\n self.cleanUpAfterError(\"Missing temp or destination parent directory\", self.destpath)\n \n self.tmppath = os.path.join(fulltmp, self.nm)\n\n if self.prt.tmp:\n filehash = sha1(\"blob \" + str(self.size_bytes) + \"\\0\" + self.tmppath)\n tmpname = filehash.hexdigest()\n self.tmppath = os.path.join(self.prt.tmp, tmpname)\n\n log.debug(\"Downloading file to %s\", self.tmppath)\n retriesleft = 3\n sizemismatched = False\n failsize = False\n while retriesleft > 0:\n sizecopied = 0\n progress = time.time() + 60\n apiratecount = 0\n try:\n with open(self.tmppath, 'wb') as tmpfile:\n st = time.time()\n timespan = 0\n req = requests.get(apidownloaduri, stream=True, timeout=120)\n chunk_size = 1024\n #if not sizemismatched:\n chunk_size += 1024 * 1024\n for chunk in req.iter_content(chunk_size=chunk_size):\n sizecopied += len(chunk)\n if self.prt.end:\n break\n if chunk: # filter out keep-alive new chunks\n tmpfile.write(chunk)\n if self.prt.progress and progress < time.time():\n progress = time.time() + 60\n speed = utils.get_speed(sizecopied, (time.time()-st))\n log.info(\"%s\\nDownloaded %s of %s at %s\", self.nm, utils.convert_size(sizecopied), self.size_str, speed)\n #if sizemismatched:\n # tmpfile.flush()\n # os.fsync(tmpfile.fileno())\n timespan = (time.time()-st)\n if sizecopied != self.size_bytes and not self.prt.end:\n raise SizeMismatchError(\"Download size mismatch downloaded %s expected %s\" % (sizecopied, self.size_bytes))\n elif self.prt.end:\n self.cleanUpAfterError(\"Recieved signaled stop during download\", self.destpath)\n except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.RequestException):\n retriesleft -= 1\n if req.status_code == 429:\n apiratecount += 1\n retriesleft += 1\n log.warn(\"API rate limit reached. Will retry\")\n else:\n log.warn(\"Network error. Will retry %s more times\", retriesleft)\n if retriesleft > 0:\n time.sleep(10 * apiratecount)\n else:\n log.error(\"Error downloading %s\", self.nm)\n self.cleanUpAfterError(\"Maximum retries reached\", self.destpath)\n except SizeMismatchError:\n retriesleft -= 1\n log.exception(\"%s File size mismatch. Will retry %s more times\", self.nm, retriesleft)\n sizemismatched = True\n if retriesleft == 2:\n failsize = sizecopied\n elif failsize and failsize != sizecopied:\n failsize = False\n\n if retriesleft > 0:\n time.sleep(10)\n elif failsize:\n log.warn(\"%s\\nRecieved incorrect file size %s instead of %s 3 times. Saving anyway\", self.nm, sizecopied, self.size_bytes)\n else:\n log.error(\"Error downloading %s\", self.nm)\n self.cleanUpAfterError(\"Maximum retries reached\", self.destpath)\n except (IOError, OSError, WindowsError):\n log.exception(\"Error writing to file %s\", self.nm)\n self.cleanUpAfterError(traceback.format_exc(), self.destpath)\n except (requests.exceptions.RequestException, Exception):\n log.error(\"Error downloading %s\", self.nm)\n self.cleanUpAfterError(traceback.format_exc(), self.destpath)\n except SystemExit:\n self.cleanUpAfterError(\"Received signal exit\", self.destpath)\n raise\n except:\n if req.status_code in [429, 503]:\n apiratecount += 1\n retriesleft += 1\n log.warn(\"API rate limit reached. Will retry\")\n else:\n log.exception(\"Error downloading %s. Will retry %s more times\", self.nm, retriesleft)\n\n if retriesleft > 0:\n time.sleep(10 * apiratecount)\n else:\n self.cleanUpAfterError(\"An unknown error occured\", self.destpath)\n else:\n retriesleft = 0\n self.prt.downloadtime += timespan\n if self.prt.progress:\n speed = utils.get_speed(self.size_bytes, timespan)\n log.info(\"%s downloaded at %s\", self.size_str, speed)\n\n if self.prt.end:\n log.warn(\"Parent signaled stop\")\n return\n self.prt.bytestotal += self.size_bytes\n if self.prt.tmp:\n log.info(\"Copying from temp to dest\")\n retriesleft = 3\n while retriesleft > 0:\n try:\n st = time.time()\n timespan = 0\n with open(self.tmppath, 'rb') as f, open(self.destpath, \"wb\") as fo:\n while True and not self.prt.end:\n piece = f.read(1024)\n if piece:\n fo.write(piece)\n else:\n break\n\n timespan = (time.time()-st)\n if self.prt.end:\n self.cleanUpAfterError(\"Recieved signaled stop during copy\", self.destpath)\n except (IOError, OSError, WindowsError) as e:\n retriesleft -= 1\n if retriesleft > 0:\n self.delete_dest()\n log.exception(\"Error copying file wil retry %s more times\", retriesleft)\n else:\n log.exception(\"Error file could not be copied to %s\", self.destpath)\n self.cleanUpAfterError(traceback.format_exc(), self.destpath)\n except SystemExit:\n self.cleanUpAfterError(\"Received signal exit\", self.destpath)\n raise\n except: \n #This technically should never happen but technically you never know\n retriesleft -= 1\n if retriesleft > 0:\n self.delete_dest()\n log.exception(\"Error copying file wil retry %s more times\", retriesleft)\n else:\n log.exception(\"Error file could not be copied to %s\", self.destpath)\n self.cleanUpAfterError(traceback.format_exc(), self.destpath)\n else:\n retriesleft = 0\n self.prt.copytime += timespan\n if self.prt.progress:\n speed = utils.get_speed(self.size_bytes, timespan)\n log.info(\"%s copied at %s\", self.size_str, speed)\n try:\n os.remove(self.tmppath)\n except (IOError, OSError) as e:\n log.warn(\"Failed cleaning up tmp file %s\\n%s\", self.tmppath, e)\n self.prt.writeSuccess(self.destpath)\n log.info(\"Finished download %s in \", self.destpath)\n log.debug(\"End of thread\")\n self.prt.threads[self.thread_num] = None\n\n def cleanUpAfterError(self, e, path):\n\n # log file to errorfiles.txt\n self.prt.writeError(self.nm, path, self.base64path, e)\n\n self.delete_dest\n\n #cleanup temp file\n try:\n if self.prt.tmp and os.path.exists(self.tmppath):\n os.remove(self.tmppath)\n except OSError as ose:\n log.exception(\"Couldn't clean up file %s\", self.tmppath)\n log.debug(\"End of thread\")\n self.prt.threads[self.thread_num] = None\n thread.exit()\n\n def delete_dest(self):\n #cleanup destination file\n try:\n if os.path.exists(self.destpath):\n os.remove(self.destpath)\n except:\n log.exception(\"Couldn't clean up file %s\", self.destpath)","sub_path":"python/threads.py","file_name":"threads.py","file_ext":"py","file_size_in_byte":10176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555347285","text":"class Settings():\n \"\"\"A class to store all settings for Elijah Invasion.\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the game's static settings.\"\"\"\n # Screen settings.\n self.screen_width = 1200\n self.screen_height = 800\n self.bg_color = (230, 230, 230)\n\n # Elijah settings.\n self.elijah_limit = 3\n\n # Bullet settings.\n self.bullet_width = 3\n self.bullet_height = 15\n self.bullet_color = (60, 60, 60)\n self.bullets_allowed = 3\n\n # Couch settings\n self.fleet_drop_speed = 10\n\n # How quickly the game speeds up.\n self.speedup_scale = 1.1\n\n # How quickly the couch point values increase\n self.score_scale = 1.5\n\n self.initialize_dynamic_settings()\n\n def initialize_dynamic_settings(self):\n \"\"\"Initialize settings that change throughout the game.\"\"\"\n self.elijah_speed_factor = 1.5\n self.bullet_speed_factor = 3\n self.couch_speed_factor = 1\n\n # fleet_direction of 1 represents right; -1 represents left.\n self.fleet_direction = 1\n\n # Scoring\n self.couch_points = 50\n\n def increase_speed(self):\n \"\"\"Increase speed settings and couch point values.\"\"\"\n self.elijah_speed_factor *= self.speedup_scale\n self.bullet_speed_factor *= self.speedup_scale\n self.couch_speed_factor *= self.speedup_scale\n\n self.couch_points = int(self.couch_points * self.score_scale)\n\n","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"618211921","text":"'''\nnlg output is a dictionary of key, value = dialogue_id, turns\nturns is a dictionary of key, value = turn_id, utterance\nwhere turn_id is an *INTEGER* and\nutterance is a dictionary of\n{\n \"start\": str(your_chitchat_before_ground_truth),\n \"end\": str(your_chitchat_after_ground_truth),\n \"mod\": str(your_modified_ground_truth),\n}\nif you dont want to add anything before/after the ground truth,\n just place an empty string in start/end.\nif you dont want to modify the ground truth (which is recommended),\n just place an empty string in mod.\nif you want to modify the ground truth,\n please make sure the sentences make sense;\n otherwise you will probably get a low score.\n\nyour nlg result will be\n start + mod + end if you modify the ground truth,\n start + ground truth + end if you dont.\n'''\n\n\nimport json\nimport os\n\n\ndef gen_single_turn_output(turn_id):\n start = 'Hello!' if turn_id == 1 else ''\n end = 'Bye!' if turn_id > 10 else ''\n return {'start': start, 'end': end, 'mod': ''}\n\n\ndef gen_dial_output(turns):\n output = {}\n for turn in turns:\n if turn['speaker'] == 'SYSTEM':\n tid = turn['turn_id']\n output[tid] = gen_single_turn_output(tid)\n return output\n\n\ndef gen_nlg_output_example():\n nlg = {}\n for dirPath, dirNames, fileNames in os.walk('data/test_seen'):\n for fn in fileNames:\n with open(os.path.join(dirPath, fn), 'r') as f:\n dialogues = json.load(f)\n for dial in dialogues:\n nlg[dial['dialogue_id']] = gen_dial_output(dial['turns'])\n with open('nlg_output_example.json', 'w') as f:\n json.dump(nlg, f, indent=2)\n\n\nif __name__ == \"__main__\":\n gen_nlg_output_example()","sub_path":"NLG/GPT-2/adl-final-dst-with-chit-chat-seen-domains/data/gen_nlg_output.py","file_name":"gen_nlg_output.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"600818548","text":"import numpy as np\nimport cv2\n\n# 얼굴과 눈을 검출하기 위해 미리 학습시켜 놓은 XML 포맷으로 저장된 분류기를 로드합니다.\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\neye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')\n\nfourcc = cv2.VideoWriter_fourcc(*'DIVX')\nout = cv2.VideoWriter('output7.avi', fourcc, 25.0, (320*2,240*2))\n\n# 얼굴과 눈을 검출할 그레이스케일 이미지를 준비해놓습니다.\n# img = cv2.imread('test3.jpg')\n\ncap = cv2.VideoCapture(0)\nif cap.isOpened():\n print('width: {}, height : {}'.format(cap.get(3), cap.get(4)))\n\nwhile True:\n ret, frame = cap.read()\n if ret:\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # 이미지에서 얼굴을 검출합니다.\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\n # 얼굴이 검출되었다면 얼굴 위치에 대한 좌표 정보를 리턴받습니다.\n for (x,y,w,h) in faces:\n # 원본 이미지에 얼굴의 위치를 표시합니다.\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n\n # 눈 검출은 얼굴이 검출된 영역 내부에서만 진행하기 위해 ROI를 생성합니다.\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w]\n\n # 눈을 검출합니다.\n eyes = eye_cascade.detectMultiScale(roi_gray)\n\n # 눈이 검출되었다면 눈 위치에 대한 좌표 정보를 리턴받습니다.\n for (ex,ey,ew,eh) in eyes:\n # 원본 이미지에 얼굴의 위치를 표시합니다. ROI에 표시하면 원본 이미지에도 표시됩니다.\n cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)\n # 비디오 저장\n out.write(frame)\n\n # 얼굴과 눈 검출 결과를 화면에 보여줍니다.\n cv2.imshow('img',frame)\n\n if cv2.waitKey(5)&0xFF == ord('q'):\n break\ncap.release()\nout.release()\ncv2.destroyAllWindows","sub_path":"Day04/cascade_face_eye_save.py","file_name":"cascade_face_eye_save.py","file_ext":"py","file_size_in_byte":2026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"262107913","text":"import csv\nimport random\nimport json\nimport os\nimport jsonlines\n\ndef load_jsonl(filename):\n data = []\n with jsonlines.open('./data/'+filename+'.jsonl') as reader:\n for row in reader:\n data.append(row)\n return data\n\ndef get_cmv(data):\n cnt = 0\n for row in data:\n cnt += 1\n if cnt < 1000:\n continue\n if cnt > 1600:\n break\n book = {\n 'id': row['claim_id'],\n 'claim_index': row['post_sent_idx'],\n 'claim_context': row['post_sents'],\n 'con_evidence': []\n }\n for con_evidence in row['con_evidence']:\n book['con_evidence'].append({\n 'ev_id': con_evidence['id'],\n 'ev_url': con_evidence['ev_url'],\n 'ev_netloc': con_evidence['ev_url_netloc'],\n 'ev_text': con_evidence['ev_text'],\n 'ev_context': con_evidence['ev_context']\n })\n with open('./data/contexts/%s.json' % book['id'], 'w') as f:\n json.dump(book, f, sort_keys=True, indent=4)\n\ndef get_kialo(data):\n for row in data:\n book = {\n 'id': row['claim_id'],\n 'claim_text': row['claim_text'],\n 'claim_context': row['claim_text'],\n 'con_evidence': []\n }\n for con_evidence in row['con_evidence']:\n book['con_evidence'].append({\n 'ev_id': con_evidence['id'],\n 'ev_url': con_evidence['ev_url'],\n 'ev_netloc': con_evidence['ev_url_netloc'],\n 'ev_text': con_evidence['ev_text'],\n 'ev_context': con_evidence['ev_context']\n })\n with open('./data/contexts/%s.json' % book['id'], 'w') as f:\n json.dump(book, f, sort_keys=True, indent=4)\n\ndef conv(filename):\n if not os.path.exists('./data/contexts'):\n os.makedirs('./data/contexts')\n\n if filename.startswith('cmv'):\n get_cmv(load_jsonl(filename))\n elif filename.startswith('kialo'):\n get_kialo(load_jsonl(filename))\n\ndef main():\n conv('cmv-annot-1')\n\nif __name__ == \"__main__\":\n main()","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"430195085","text":"import json\n\nfrom django.http import HttpResponse\n\ndef MyHttpResponse(data):\n try:\n if isinstance(data, str):\n return HttpResponse(data)\n elif isinstance(data, dict):\n return HttpResponse(\n json.dumps(data), \n content_type='application/json'\n )\n else:\n data = str(data)\n return HttpResponse(data)\n except Exception:\n pass\n\n\ndef check_http_response(resp):\n str_content = resp.content.decode()\n import json\n content = json.loads(str_content)\n return content.get('success')\n \n\n","sub_path":"utility/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203035995","text":"import textwrap\nimport time\nfrom collections import deque\n\n\ndef get_test_input() -> str:\n return textwrap.dedent(\"\"\"\\\n 389125467\"\"\")\n\n\ndef read_input(day_number, test=False):\n if test:\n return parse_input(get_test_input())\n else:\n filename = 'input/dec{}.txt'.format(day_number)\n with open(filename, 'r') as file:\n return parse_input(file.read())\n\n\ndef parse_input(s: str):\n return list(int(v) for v in s.rstrip('\\n'))\n\n\n# def do_move(cups):\n# # Get the label of the destination cup\n# dest_val = cups[0] - 1\n# if dest_val == 0:\n# dest_val = 9\n# while dest_val in cups[1:4]:\n# dest_val -= 1\n# if dest_val == 0:\n# dest_val = 9\n#\n# dest_idx = cups.index(dest_val)\n# return cups[4:dest_idx + 1] + cups[1:4] + cups[dest_idx + 1:] + [cups[0]]\n\n\ndmp_1 = 0.0\ndmp_2 = 0.0\ndmp_3 = 0.0\ndef do_move(cups):\n global dmp_1\n global dmp_2\n global dmp_3\n now = time.time()\n\n \"\"\"Source cup is the first cup\"\"\"\n num_cups = len(cups)\n\n orig = cups.popleft()\n to_move = []\n for _ in range(3):\n to_move.append(cups.popleft())\n\n dest_val = orig - 1\n if dest_val == 0:\n dest_val = num_cups\n while dest_val in to_move:\n dest_val -= 1\n if dest_val == 0:\n dest_val = num_cups\n\n # - TIMING -\n new_now = time.time()\n dmp_1 += new_now - now\n now = new_now\n # - END TIMING -\n\n stack = deque()\n try:\n while cups[-1] != dest_val:\n stack.append(cups.pop())\n except IndexError:\n print(dest_val)\n\n # - TIMING -\n new_now = time.time()\n dmp_2 += new_now - now\n now = new_now\n # - END TIMING -\n\n while to_move:\n cups.append(to_move.pop(0))\n while stack:\n cups.append(stack.pop())\n\n cups.append(orig)\n\n # - TIMING -\n new_now = time.time()\n dmp_3 += new_now - now\n # - END TIMING -\n\n\ndef part_1(cups):\n for _ in range(100):\n do_move(cups)\n\n while cups[0] != 1:\n cups.append(cups.popleft())\n print('Part 1:', ''.join(str(c) for c in list(cups)[1:]))\n\n\ndef part_2(cups):\n global dmp_1\n global dmp_2\n global dmp_3\n\n now = time.time()\n\n cups = deque(cups)\n for x in range(len(cups) + 1, 1000000 + 1):\n cups.append(x)\n\n for idx in range(50000):\n if idx % 10000 == 0:\n new_now = time.time()\n print(f'{idx} took {new_now - now} seconds')\n now = new_now\n do_move(cups)\n\n while cups[0] != 1:\n cups.append(cups.popleft())\n\n cups.popleft()\n c1 = cups.popleft()\n c2 = cups.popleft()\n print('Part 2:', c1*c2)\n print(dmp_1, dmp_2, dmp_3)\n\n\ndef main():\n cups = deque(read_input(day_number=23, test=True))\n # part_1(cups)\n part_2(cups)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2020/day23.py","file_name":"day23.py","file_ext":"py","file_size_in_byte":2831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"277525288","text":"#!/usr/bin/evn python\n# usage: python control_leds.py command (1, 2, 3)\n# ex: blink the odd-number LEDs: python web_video_streaming.py 1 \n# import the json and sys modules \nimport json, sys\nimport time \n\n# import the RPi.GPIO module with setting its name as GPIO\nimport RPi.GPIO as GPIO \n\n# set the pin mode to be BCM\nGPIO.setmode(GPIO.BCM)\n\n# define the LED pins\nLED_PINS = [17, 27, 22, 5, 6, 13, 19, 26]\nLED_PIN1 = 17\nLED_PIN2 = 27\nLED_PIN3 = 22\nLED_PIN4 = 5\nLED_PIN5 = 6\nLED_PIN6 = 13\nLED_PIN7 = 19\nLED_PIN8 = 26\n\n# set the LED pins as output\nGPIO.setup(LED_PINS, GPIO.OUT)\n\n# blink the odd-number LEDS for 6 times\ndef Blink_Odd_LEDs():\n\tfor count in range(0, 6, 1):\n\t # turn the odd leds on\n\t\tGPIO.output(LED_PIN1, GPIO.HIGH) \n\t\tGPIO.output(LED_PIN3, GPIO.HIGH)\n\t\tGPIO.output(LED_PIN5, GPIO.HIGH)\n\t\tGPIO.output(LED_PIN7, GPIO.HIGH)\n\t\ttime.sleep(0.2) # sleep for 1 second\n\t\t # turn the odd leds off\n\t\tGPIO.output(LED_PIN1, GPIO.LOW) \n\t\tGPIO.output(LED_PIN3, GPIO.LOW)\n\t\tGPIO.output(LED_PIN5, GPIO.LOW)\n\t\tGPIO.output(LED_PIN7, GPIO.LOW)\n\t\ttime.sleep(0.2) # sleep for 1 second\n\t\n\t# clear the setting of all IO pins\n\tGPIO. cleanup ( )\n\n# blink the even-number LEDS for 6 times\t\t\ndef Blink_Even_LEDs():\n\tfor count in range(0, 6, 1):\n\t # turn the even leds on\n\t\tGPIO.output(LED_PIN2, GPIO.HIGH) \n\t\tGPIO.output(LED_PIN4, GPIO.HIGH)\n\t\tGPIO.output(LED_PIN6, GPIO.HIGH)\n\t\tGPIO.output(LED_PIN8, GPIO.HIGH)\n\t\ttime.sleep(0.2) # sleep for 1 second\n\t\t# turn the even leds off\n\t\tGPIO.output(LED_PIN2, GPIO.LOW) \n\t\tGPIO.output(LED_PIN4, GPIO.LOW)\n\t\tGPIO.output(LED_PIN6, GPIO.LOW)\n\t\tGPIO.output(LED_PIN8, GPIO.LOW)\n\t\ttime.sleep(0.2) # sleep for 1 second\n\t\t\n\t# clear the setting of all IO pins\n\tGPIO. cleanup ( )\n\n# PWM LEDs for 5 seconds\ndef PWM_LEDs():\n\t# generate the pwm objects of LED pins with frequency=50Hz\n\tpwm1 = GPIO.PWM(LED_PIN1, 50)\n\tpwm2 = GPIO.PWM(LED_PIN2, 50)\n\tpwm3 = GPIO.PWM(LED_PIN3, 50)\n\tpwm4 = GPIO.PWM(LED_PIN4, 50)\n\tpwm5 = GPIO.PWM(LED_PIN5, 50)\n\tpwm6 = GPIO.PWM(LED_PIN6, 50)\n\tpwm7 = GPIO.PWM(LED_PIN7, 50)\n\tpwm8 = GPIO.PWM(LED_PIN8, 50)\n\n\t# start the pwm objects with dutycycle starting from 0\n\tpwm1.start(0)\n\tpwm2.start(0)\n\tpwm3.start(0)\n\tpwm4.start(0)\n\tpwm5.start(0)\n\tpwm6.start(0)\n\tpwm7.start(0)\n\tpwm8.start(0)\n\t\n\tfor count in range(0, 3, 1):\n\t\t# do loop to increase the dutycycle of the pwm objects by 5% each loop\n\t\tfor dc in range(0, 101, 10): \n\t\t\tpwm1.ChangeDutyCycle(dc)\n\t\t\tpwm2.ChangeDutyCycle(dc)\n\t\t\tpwm3.ChangeDutyCycle(dc)\n\t\t\tpwm4.ChangeDutyCycle(dc)\n\t\t\tpwm5.ChangeDutyCycle(dc)\n\t\t\tpwm6.ChangeDutyCycle(dc)\n\t\t\tpwm7.ChangeDutyCycle(dc)\n\t\t\tpwm8.ChangeDutyCycle(dc)\n\t\t\ttime.sleep(0.05) # sleep 0.1 second\n\t\t # do loop to decrease the dutycycle of the pwm objects by 5% each loop\n\t\tfor dc in range(100, -1, -10):\n\t\t\tpwm1.ChangeDutyCycle(dc)\n\t\t\tpwm2.ChangeDutyCycle(dc)\n\t\t\tpwm3.ChangeDutyCycle(dc)\n\t\t\tpwm4.ChangeDutyCycle(dc)\n\t\t\tpwm5.ChangeDutyCycle(dc)\n\t\t\tpwm6.ChangeDutyCycle(dc)\n\t\t\tpwm7.ChangeDutyCycle(dc)\n\t\t\tpwm8.ChangeDutyCycle(dc)\n\t\t\ttime.sleep(0.05) # sleep 0.1 second\n\n\t# stop the operation of the pwm objects\t\t\n\tpwm1.stop\n\tpwm2.stop\n\tpwm3.stop\n\tpwm4.stop\n\tpwm5.stop\n\tpwm6.stop\n\tpwm7.stop\n\tpwm8.stop\n\t\n\t# clear the setting of all IO pins\n\tGPIO. cleanup ( )\n\n# Run the LEDS for 3 times\ndef Run_LEDs():\t\n\tfor count in range(0, 3, 1):\n\t\tfor i in range(0,8,1):\n\t\t\t# turn the the target led on\n\t\t\tGPIO.output(LED_PINS[i], GPIO.HIGH) \n\t\t\ttime.sleep(0.05) # sleep for 0.2 seconds\n\t\t\t# turn all leds off\n\t\t\tGPIO.output(LED_PINS, GPIO.LOW)\n\t\t\ttime.sleep(0.05) # sleep for 1 second\n\t\t\n\t\tfor i in range(6,-1,-1):\n\t\t\t# turn the the target led on\n\t\t\tGPIO.output(LED_PINS[i], GPIO.HIGH) \n\t\t\ttime.sleep(0.05) # sleep for 0.2 seconds\n\t\t\t# turn all leds off\n\t\t\tGPIO.output(LED_PINS, GPIO.LOW)\n\t\t\ttime.sleep(0.05) # sleep for 1 second\n\t\t\t\n\t# clear the setting of all IO pins\n\tGPIO. cleanup ( )\n\t\n# get the command for control the LEDs \ncommand = sys.argv[1]\nif(command==\"1\"): \n\tBlink_Odd_LEDs()\n\t\nif(command==\"2\"):\n\tBlink_Even_LEDs()\n\t\nif(command==\"3\"):\n\tPWM_LEDs()\n\t\nif(command==\"4\"):\n\tRun_LEDs()\n\t\n","sub_path":"畢業專題程式碼/遙控車前端程式碼/nodev691_rc4/control-leds.py","file_name":"control-leds.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"259940039","text":"\"\"\"\nA Pygments lexer for Bro policy scripts.\n\"\"\"\n\nfrom setuptools import setup\n\n__author__ = 'Matthias Vallentin'\n__email__ = 'vallentin@icir.org'\n__copyright__ = 'Copyright 2011, Matthias Vallentin'\n__license__ = 'BSD'\n__version__ = '0.1'\n__maintainer__ = 'Matthias Vallentin'\n\nentry_points = '''[pygments.lexers]\nbrolexer = bro_lexer.bro:BroLexer\n'''\n \nsetup(\n name = 'brogments',\n version = '0.1',\n description= __doc__,\n author = __author__,\n packages = ['bro_lexer'],\n entry_points = entry_points\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"579201483","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Unit tests for cartoframes.client.DataObsClient\"\"\"\n\nimport os\nimport sys\nimport json\nimport pytest\nimport unittest\nimport warnings\nimport pandas as pd\n\nfrom carto.exceptions import CartoException\n\nfrom cartoframes import read_carto, delete_table\nfrom cartoframes.auth import Credentials\nfrom cartoframes.data.clients import DataObsClient, SQLClient\nfrom cartoframes.data.clients.data_obs_client import get_countrytag\nfrom cartoframes.utils.columns import normalize_name\nfrom tests.e2e.helpers import _UserUrlLoader\n\nwarnings.filterwarnings('ignore')\n\n\nclass TestDataObsClientDeprecation(unittest.TestCase, _UserUrlLoader):\n def setUp(self):\n self.credentials = Credentials(None, None, self.user_url().format(username=None))\n\n def test_class_deprecation(self):\n with warnings.catch_warnings(record=True) as w:\n _ = DataObsClient(self.credentials)\n assert issubclass(w[-1].category, DeprecationWarning)\n assert 'deprecated' in str(w[-1].message)\n\n def test_boundaries_deprecation(self):\n with warnings.catch_warnings(record=True) as w:\n do = DataObsClient(self.credentials)\n\n with warnings.catch_warnings(record=True) as w:\n try:\n do.boundaries()\n except Exception:\n pass\n\n assert issubclass(w[-1].category, DeprecationWarning)\n assert 'deprecated' in str(w[-1].message)\n\n def test_discovery_deprecation(self):\n with warnings.catch_warnings(record=True) as w:\n do = DataObsClient(self.credentials)\n\n with warnings.catch_warnings(record=True) as w:\n try:\n do.discovery()\n except Exception:\n pass\n\n assert issubclass(w[-1].category, DeprecationWarning)\n assert 'deprecated' in str(w[-1].message)\n\n def test_augment_deprecation(self):\n with warnings.catch_warnings(record=True) as w:\n do = DataObsClient(self.credentials)\n\n with warnings.catch_warnings(record=True) as w:\n try:\n do.augment()\n except Exception:\n pass\n\n assert issubclass(w[-1].category, DeprecationWarning)\n assert 'deprecated' in str(w[-1].message)\n\n\n@pytest.mark.skip()\nclass TestDataObsClient(unittest.TestCase, _UserUrlLoader):\n \"\"\"Tests for cartoframes.client.DataObsClient\"\"\"\n\n def setUp(self):\n if (os.environ.get('APIKEY') is None or\n os.environ.get('USERNAME') is None):\n try:\n creds = json.loads(open('tests/e2e/secret.json').read())\n self.apikey = creds['APIKEY']\n self.username = creds['USERNAME']\n except Exception:\n warnings.warn(\"Skipping Context tests. To test it, \"\n \"create a `secret.json` file in test/ by \"\n \"renaming `secret.json.sample` to `secret.json` \"\n \"and updating the credentials to match your \"\n \"environment.\")\n self.apikey = None\n self.username = None\n else:\n self.apikey = os.environ['APIKEY']\n self.username = os.environ['USERNAME']\n\n self.base_url = self.user_url().format(username=self.username)\n self.credentials = Credentials(self.username, self.apikey, self.base_url)\n self.sql_client = SQLClient(self.credentials)\n\n # table naming info\n has_mpl = 'mpl' if os.environ.get('MPLBACKEND') else 'nonmpl'\n pyver = sys.version[0:3].replace('.', '_')\n buildnum = os.environ.get('TRAVIS_BUILD_NUMBER')\n\n test_slug = '{ver}_{num}_{mpl}'.format(\n ver=pyver, num=buildnum, mpl=has_mpl\n )\n\n # test tables\n self.test_read_table = 'cb_2013_us_csa_500k'\n self.valid_columns = set(['affgeoid', 'aland', 'awater', 'created_at',\n 'csafp', 'geoid', 'lsad', 'name', 'the_geom',\n 'updated_at'])\n # torque table\n self.test_point_table = 'tweets_obama'\n\n # for writing to carto\n self.test_write_table = normalize_name(\n 'cf_test_table_{}'.format(test_slug)\n )\n\n self.mixed_case_table = normalize_name(\n 'AbCdEfG_{}'.format(test_slug)\n )\n\n # for batch writing to carto\n self.test_write_batch_table = normalize_name(\n 'cf_testbatch_table_{}'.format(test_slug)\n )\n\n self.test_write_lnglat_table = normalize_name(\n 'cf_testwrite_lnglat_table_{}'.format(test_slug)\n )\n\n self.write_named_index = normalize_name(\n 'cf_testwrite_non_default_index_{}'.format(test_slug)\n )\n\n # for queries\n self.test_query_table = normalize_name(\n 'cf_testquery_table_{}'.format(test_slug)\n )\n\n self.test_delete_table = normalize_name(\n 'cf_testdelete_table_{}'.format(test_slug)\n )\n\n # for data observatory\n self.test_data_table = 'carto_usa_offices'\n\n def tearDown(self):\n \"\"\"restore to original state\"\"\"\n tables = (self.test_write_table,\n self.test_write_batch_table,\n self.test_write_lnglat_table,\n self.test_query_table,\n self.mixed_case_table.lower(),\n self.write_named_index, )\n sql_drop = 'DROP TABLE IF EXISTS {};'\n\n for table in tables:\n try:\n delete_table(table, credentials=self.credentials)\n self.sql_client.query(sql_drop.format(table))\n except CartoException:\n warnings.warn('Error deleting tables')\n\n def test_boundaries(self):\n \"\"\"DataObsClient.boundaries\"\"\"\n do = DataObsClient(self.credentials)\n\n # all boundary metadata\n boundary_meta = do.boundaries()\n self.assertTrue(boundary_meta.shape[0] > 0,\n msg='has non-zero number of boundaries')\n meta_cols = set(('geom_id', 'geom_tags', 'geom_type', ))\n self.assertTrue(meta_cols & set(boundary_meta.columns))\n\n # boundary metadata with correct timespan\n meta_2015 = do.boundaries(timespan='2015')\n self.assertTrue(meta_2015[meta_2015.valid_timespan].shape[0] > 0)\n\n # test for no data with an incorrect or invalid timespan\n meta_9999 = do.boundaries(timespan='invalid_timespan')\n self.assertTrue(meta_9999[meta_9999.valid_timespan].shape[0] == 0)\n\n # boundary metadata in a region\n regions = (\n self.test_read_table,\n self.test_data_table,\n [5.9559111595, 45.8179931641, 10.4920501709, 47.808380127],\n 'Australia', )\n for region in regions:\n boundary_meta = do.boundaries(region=region)\n self.assertTrue(meta_cols & set(boundary_meta.columns))\n self.assertTrue(boundary_meta.shape[0] > 0,\n msg='has non-zero number of boundaries')\n\n # boundaries for world\n boundaries = do.boundaries(boundary='us.census.tiger.state')\n self.assertTrue(boundaries.shape[0] > 0)\n self.assertEqual(boundaries.shape[1], 2)\n self.assertSetEqual(set(('the_geom', 'geom_refs', )),\n set(boundaries.columns))\n\n # boundaries for region\n boundaries = ('us.census.tiger.state', )\n for b in boundaries:\n geoms = do.boundaries(\n boundary=b,\n region=self.test_data_table)\n self.assertTrue(geoms.shape[0] > 0)\n self.assertEqual(geoms.shape[1], 2)\n self.assertSetEqual(set(('the_geom', 'geom_refs', )),\n set(geoms.columns))\n\n # presence or lack of clipped boundaries\n nonclipped = (True, False, )\n for tf in nonclipped:\n meta = do.boundaries(include_nonclipped=tf)\n self.assertEqual(\n 'us.census.tiger.state' in set(meta.geom_id),\n tf\n )\n\n with self.assertRaises(ValueError):\n do.boundaries(region=[1, 2, 3])\n\n with self.assertRaises(ValueError):\n do.boundaries(region=10)\n\n def test_discovery(self):\n \"\"\"DataObsClient.discovery\"\"\"\n do = DataObsClient(self.credentials)\n\n meta = do.discovery(self.test_read_table,\n keywords=('poverty', ),\n time=('2010 - 2014', ))\n meta_columns = set((\n 'denom_aggregate', 'denom_colname', 'denom_description',\n 'denom_geomref_colname', 'denom_id', 'denom_name',\n 'denom_reltype', 'denom_t_description', 'denom_tablename',\n 'denom_type', 'geom_colname', 'geom_description',\n 'geom_geomref_colname', 'geom_id', 'geom_name',\n 'geom_t_description', 'geom_tablename', 'geom_timespan',\n 'geom_type', 'id', 'max_score_rank', 'max_timespan_rank',\n 'normalization', 'num_geoms', 'numer_aggregate',\n 'numer_colname', 'numer_description', 'numer_geomref_colname',\n 'numer_id', 'numer_name', 'numer_t_description',\n 'numer_tablename', 'numer_timespan', 'numer_type', 'score',\n 'score_rank', 'score_rownum', 'suggested_name', 'target_area',\n 'target_geoms', 'timespan_rank', 'timespan_rownum'))\n self.assertSetEqual(set(meta.columns), meta_columns,\n msg='metadata columns are all there')\n self.assertTrue((meta['numer_timespan'] == '2010 - 2014').all())\n self.assertTrue((meta['numer_description'].str.contains('poverty')).all())\n\n # test region = list of lng/lats\n with self.assertRaises(ValueError):\n do.discovery([1, 2, 3])\n\n switzerland = [5.9559111595, 45.8179931641,\n 10.4920501709, 47.808380127]\n dd = do.discovery(switzerland, keywords='freight', time='2010')\n self.assertEqual(dd['numer_id'][0], 'eu.eurostat.tgs00078')\n\n dd = do.discovery('Australia',\n regex='.*Torres Strait Islander.*')\n for nid in dd['numer_id'].values:\n self.assertRegexpMatches(nid, r'^au\\.data\\.B01_Indig_[A-Za-z_]+Torres_St[A-Za-z_]+[FMP]$')\n\n with self.assertRaises(CartoException):\n do.discovery('non_existent_table_abcdefg')\n\n dd = do.discovery('United States',\n boundaries='us.epa.huc.hydro_unit',\n time=('2006', '2010', ))\n self.assertTrue(dd.shape[0] >= 1)\n\n poverty = do.discovery(\n 'United States',\n boundaries='us.census.tiger.census_tract',\n keywords=['poverty status', ],\n time='2011 - 2015',\n include_quantiles=False)\n df_quantiles = poverty[poverty.numer_aggregate == 'quantile']\n self.assertEqual(df_quantiles.shape[0], 0)\n\n poverty = do.discovery(\n 'United States',\n boundaries='us.census.tiger.census_tract',\n keywords=['poverty status', ],\n time='2011 - 2015',\n include_quantiles=True)\n df_quantiles = poverty[poverty.numer_aggregate == 'quantile']\n self.assertTrue(df_quantiles.shape[0] > 0)\n\n def test_augment(self):\n \"\"\"DataObsClient.augment\"\"\"\n do = DataObsClient(self.credentials)\n\n meta = do.discovery(self.test_read_table,\n keywords=('poverty', ),\n time=('2010 - 2014', ))\n gdf = do.augment(self.test_data_table, meta)\n anscols = set(meta['suggested_name'])\n origcols = set(\n read_carto(self.test_data_table, credentials=self.credentials, limit=1, decode_geom=True).columns)\n self.assertSetEqual(anscols, set(gdf.columns) - origcols - {'the_geom', 'cartodb_id'})\n\n meta = [{'numer_id': 'us.census.acs.B19013001',\n 'geom_id': 'us.census.tiger.block_group',\n 'numer_timespan': '2011 - 2015'}, ]\n gdf = do.augment(self.test_data_table, meta)\n self.assertSetEqual(set(('median_income_2011_2015', )),\n set(gdf.columns) - origcols - {'the_geom', 'cartodb_id'})\n\n with self.assertRaises(ValueError, msg='no measures'):\n meta = do.discovery('United States', keywords='not a measure')\n do.augment(self.test_read_table, meta)\n\n with self.assertRaises(ValueError, msg='too many metadata measures'):\n # returns ~180 measures\n meta = do.discovery(region='united states',\n keywords='education')\n do.augment(self.test_read_table, meta)\n\n @pytest.mark.skip()\n def test_augment_with_persist_as(self):\n \"\"\"DataObsClient.augment with persist_as\"\"\"\n do = DataObsClient(self.credentials)\n\n meta = do.discovery(self.test_read_table,\n keywords=('poverty', ),\n time=('2010 - 2014', ))\n gdf = do.augment(self.test_data_table, meta)\n anscols = set(meta['suggested_name'])\n origcols = set(\n read_carto(self.test_data_table, credentials=self.credentials, limit=1, decode_geom=True).columns)\n self.assertSetEqual(anscols, set(gdf.columns) - origcols - {'the_geom', 'cartodb_id'})\n\n meta = [{'numer_id': 'us.census.acs.B19013001',\n 'geom_id': 'us.census.tiger.block_group',\n 'numer_timespan': '2011 - 2015'}, ]\n gdf = do.augment(self.test_data_table, meta, persist_as=self.test_write_table)\n self.assertSetEqual(set(('median_income_2011_2015', )),\n set(gdf.columns) - origcols - {'the_geom', 'cartodb_id'})\n self.assertEqual(gdf.index.name, 'cartodb_id')\n self.assertEqual(gdf.index.dtype, 'int64')\n\n df = read_carto(self.test_write_table, credentials=self.credentials, decode_geom=False)\n\n self.assertEqual(df.index.name, 'cartodb_id')\n self.assertEqual(df.index.dtype, 'int64')\n\n # same number of rows\n self.assertEqual(len(df), len(gdf),\n msg='Expected number or rows')\n\n # same type of object\n self.assertIsInstance(df, pd.DataFrame,\n 'Should be a pandas DataFrame')\n # same column names\n self.assertSetEqual(set(gdf.columns.values),\n set(df.columns.values),\n msg='Should have the columns requested')\n\n # should have exected schema\n self.assertEqual(\n sorted(tuple(str(d) for d in df.dtypes)),\n sorted(tuple(str(d) for d in gdf.dtypes)),\n msg='Should have same schema/types'\n )\n\n def test_augment_column_name_collision(self):\n \"\"\"DataObsClient.augment column name collision\"\"\"\n dup_col = 'female_third_level_studies_2011_by_female_pop'\n self.sql_client.query(\n \"\"\"\n create table {table} as (\n select cdb_latlng(40.4165,-3.70256) the_geom,\n 1 {dup_col})\n \"\"\".format(\n dup_col=dup_col,\n table=self.test_write_table\n )\n )\n self.sql_client.query(\n \"select cdb_cartodbfytable('public', '{table}')\".format(\n table=self.test_write_table\n )\n )\n\n do = DataObsClient(self.credentials)\n meta = do.discovery(region=self.test_write_table, keywords='female')\n meta = meta[meta.suggested_name == dup_col]\n gdf = do.augment(\n self.test_write_table,\n meta[meta.suggested_name == dup_col]\n )\n\n self.assertIn('_' + dup_col, gdf.keys())\n\n def test_get_countrytag(self):\n valid_regions = ('Australia', 'Brasil', 'EU', 'España', 'U.K.', )\n valid_answers = ['section/tags.{c}'.format(c=c)\n for c in ('au', 'br', 'eu', 'spain', 'uk', )]\n invalid_regions = ('USofA', None, '', 'Jupiter', )\n\n for idx, r in enumerate(valid_regions):\n self.assertEqual(get_countrytag(r.lower()), valid_answers[idx])\n\n for r in invalid_regions:\n with self.assertRaises(ValueError):\n get_countrytag(r)\n","sub_path":"tests/e2e/data/client/test_data_obs_client.py","file_name":"test_data_obs_client.py","file_ext":"py","file_size_in_byte":16453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"332500374","text":"import importlib\nimport inspect\nfrom collections import OrderedDict, Mapping\nfrom flask import request\nimport flask_vida.exceptions as excepts\nimport types\nimport os\nimport re\nimport types\nimport functools\n\nfrom flask.views import MethodView\n\nhttp_path = ['path', 'body', 'query', 'header', 'cookie', 'view_arg']\nhttp_methods = ['get', 'head', 'post', 'put', 'delete', 'connect', 'options', 'trace', 'patch']\n\n\ndef find_schemas(path,view_func):\n path = path.title().replace('_', '')\n schema = view_func.view_class.__schema__\n schema_req_cls = request.method.title()\n schemas = []\n try:\n # build schemas for parent arg and child arg, skip parent arg if it don't exist\n try:\n schemas.append(getattr(schema, path))\n except AttributeError:\n pass\n schemas.append(getattr(getattr(schema, schema_req_cls), path))\n except AttributeError:\n raise excepts.Schema('{} schema class is missing from {}'.format(schema_req_cls, schema.__name__))\n return schemas\n\ndef split_by_upper(word):\n return [x.lower() for x in re.findall('[A-Z][^A-Z]*', word)]\n\n\ndef module_path(directory, file):\n \"\"\"Return module using directory and direct path file\"\"\"\n parent_directory = os.path.abspath(os.path.join(directory, os.pardir)) + '/'\n file_relative = file.replace(parent_directory, '')\n file_module_path = file_relative.replace('.py', '').replace('/', '.')\n return importlib.import_module(file_module_path)\n\n\ndef directory_modules(directory):\n \"\"\"Return generator of abs file and module\"\"\"\n for directory_path, _, file_names in os.walk(directory):\n for f in file_names:\n if not f.startswith(('_', '__')) and f.endswith('.py'):\n f = os.path.join(directory_path, f)\n yield f, module_path(directory, f.replace('.py', '').replace('/', '.'))\n\n\ndef update_nested(d, u):\n \"\"\"Update nested dictionary\"\"\"\n for k, v in u.items():\n if isinstance(v, Mapping):\n r = update_nested(d.get(k, {}), v)\n d[k] = r\n else:\n d[k] = u[k]\n return d\n\n\ndef function_args(func):\n \"\"\"Return key:map of functions args and meta data about args\"\"\"\n response = OrderedDict()\n args = inspect.signature(func).parameters\n # arrange function as args as a dict\n for k, v in {k:v for k,v in args.items() if k != 'self'}.items():\n v = str(v)\n try:\n default = v.split('=')[1]\n except IndexError:\n default = None\n try:\n typ = v.split(':')[1].split('=')[0]\n except IndexError:\n typ = None\n response[k] = {'default': default, 'type': typ}\n if any([arg for arg in response.keys() if arg not in http_path and arg != 'self']):\n response['view_arg'] = {'default': None, 'type': dict}\n return response\n\n\n\ndef extract_apps_module_classes(file_module):\n \"\"\"Return classes given module path\"\"\"\n return [\n getattr(file_module, obj.__name__) for _, obj in inspect.getmembers(file_module)\n if inspect.isclass(obj) and file_module.__name__ == obj.__module__ and issubclass(obj, MethodView)\n ]\n\n\ndef extract_apps_classes_methods(cls):\n\n \"\"\"Return methods given cls path\"\"\"\n return [\n cls.as_view(method) for method in dir(cls) if callable(getattr(cls, method)) and method in http_methods\n ]\n\n\ndef extract_methods(cls):\n \"\"\"Return methods given cls path\"\"\"\n return [\n cls.__dict__[method] for method in dir(cls) if callable(getattr(cls, method)) and not method.startswith(\"__\")\n ]\n","sub_path":"flask_vida/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"511577411","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import solve_ivp\n\ndef fcn(t,u):\n return [u[0]*(1-0.5*u[1]),\n u[1]*( 0.25*u[0]-0.75)]\n\nte = 20\nTspan = [0.,te]\nmethod = 'RK23'\n\nI = [2,2]\nsol1 = solve_ivp(fcn, Tspan, I, \\\n method, dense_output=True, rtol=1.e-6)\nI = [2.6,2.0]\nsol2 = solve_ivp(fcn, Tspan, I, \n method, dense_output=True, rtol=1.e-6)\n\nplt.figure(1)\nplt.plot(sol1.y[0], sol1.y[1], 'b-', linewidth=1.0)\nplt.plot(sol2.y[0], sol2.y[1], 'b-', linewidth=1.0)\nplt.title('solve_ivp: RK23; limit cycle')\nplt.grid(True)\nplt.show()\n\n","sub_path":"Ex11.py","file_name":"Ex11.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"26642879","text":"import soundfile as sf\nimport numpy as np\nimport tensorflow as tf\nimport pyaudio\nimport wave\nimport matplotlib.pyplot as plt\n\n\npa = pyaudio.PyAudio()\n\ndef record(filename, time_second, channels=1, rate=44100):\n\tCHUNK = 1024\n\tFORMAT = pyaudio.paInt16\n\t# CHANNELS = 1\n\t# RATE = 44100\n\t# RECORD_SECONDS = 5\n\t# WAVE_OUTPUT_FILENAME = \"output.wav\"\n\n\tp = pyaudio.PyAudio()\n\n\tstream = p.open(format=FORMAT,\n\t\t\t\t\t# channels=CHANNELS,\n\t\t\t\t\t# rate=RATE,\n\t\t\t\t\tchannels = channels,\n\t\t\t\t\trate = rate,\n\t\t\t\t\tinput=True,\n\t\t\t\t\tframes_per_buffer=CHUNK)\n\n\tprint(\"* recording\")\n\n\tframes = []\n\n\tfor i in range(0, int(rate / CHUNK * time_second)):\n\t\tdata = stream.read(CHUNK)\n\t\tframes.append(data)\n\n\tprint(\"* done recording\")\n\n\tstream.stop_stream()\n\tstream.close()\n\tp.terminate()\n\n\twf = wave.open(filename, 'wb')\n\twf.setnchannels(channels)\n\twf.setsampwidth(p.get_sample_size(FORMAT))\n\twf.setframerate(rate)\n\twf.writeframes(b''.join(frames))\n\twf.close()\n\n\nfilename = r'test.wav'\nrecord(filename, 3, 2, 44100)\n\ndata, rate = sf.read(filename,dtype='int16')\ndata = data.T\n\ntime = np.arange(len(data[0])) * (1.0/rate)\n\nf_data = np.fft.fft(data)\nfreq = np.arange(len(f_data[0]))\n\nplt.subplot(2, 2, 1)\nplt.plot(time, data[0])\nplt.subplot(2, 2, 2)\nplt.plot(time, data[1])\n\nf_begin = 0\nf_end = 2000\n\nplt.subplot(2, 2, 3)\nplt.plot(freq[f_begin:f_end], f_data[0][f_begin:f_end])\nplt.subplot(2, 2, 4)\nplt.plot(freq[f_begin:f_end], f_data[1][f_begin:f_end])\n\nplt.show()\n\n\n\n\n","sub_path":"python-wavfile-test/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576530871","text":"#!/usr/bin/env python\r\n\r\n'''\r\nRead in the 'show_version.txt' file. From this \r\nfile, use regular expressions to extract the OS \r\nversion, serial number, and configuration register \r\nvalues.\r\n\r\nYour output should look as follows:\r\nOS Version: 15.4(2)T1 \r\nSerial Number: FTX0000038X \r\n​Config Register: 0x2102\r\n'''\r\n\r\nimport re\r\n\r\nwith open(\"show_version.txt\") as f:\r\n output = f.read()\r\n\r\nversion = re.search(r\", Version (.*),\", output, flags=re.M).group(1)\r\nserial = re.search(r\"Processor board ID (.*)$\", output, flags=re.M).group(1)\r\nconfig_reg = re.search(r\"Configuration register is (.*)\", output, flags=re.M).group(1)\r\n\r\nprint(\"OS Version: {}\".format(version))\r\nprint(\"Serial Number: {}\".format(serial))\r\nprint(\"Config Register: {}\".format(config_reg))","sub_path":"week4/exercise3.py","file_name":"exercise3.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"631675585","text":"import Adafruit_DHT as DHT\nimport RPi.GPIO as GPIO\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(26,GPIO.IN)\nGPIO.setup(17,GPIO.OUT)\n\ntry:\n\twhile True:\n\t\tinput = GPIO.input(26)\n\t\tif input == True:\n\t\t\ttemp,hum = DHT.read_retry(DHT.DHT11,17)\n\t\t\ttemp = temp * 9/5.0 +32\n\t\t\tif hum is not None and temp is not None:\n\t\t\t\ttempFahr = '{0:0.1f}*F'.format(temp)\n\t\t\t\tprint('Temperature = {0:0.1f}*F Humidity = {1:0.1f}%'.format(temp, hum))\n\t\t\telse:\n\t\t\t\tprint('Failed to get reading.')\nexcept KeyboardInterrupt:\n\tGPIO.cleanup()\n","sub_path":"code/temp.py","file_name":"temp.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"382009156","text":"# Definition for singly-linked list with a random pointer.\nclass RandomListNode(object):\n def __init__(self, x):\n self.label = x\n self.next = None\n self.random = None\n\nclass Solution(object):\n def copyRandomList(self, head):\n \"\"\"\n :type head: RandomListNode\n :rtype: RandomListNode\n \"\"\"\n p = head\n while p is not None:\n next = p.next\n node = RandomListNode(p.label)\n p.next = node\n node.next = next\n p = next\n p = head\n while p is not None:\n if p.random is not None:\n p.next.random = p.random.next\n p = p.next.next\n p = head\n head1 = None\n while p is not None:\n if head1 is None:\n head1 = p.next\n p1 = p.next\n p.next = p.next.next\n if p.next is None:\n p1.next = None\n else:\n p1.next = p.next.next\n p = p.next\n return head1\n\nSolution().copyRandomList(None)\n","sub_path":"medium/138_Copy_List_with_Random_Pointer/copy1.py","file_name":"copy1.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"396070110","text":"from django.shortcuts import render, get_object_or_404, render_to_response\nfrom .models import Category, Product\nfrom cart.forms import CartAddProductForm\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\n\n\ndef deliver(request):\n return render(request, 'other/delivery.html')\n\n\ndef contacts(request):\n return render(request, 'other/contacts.html')\n\n\ndef productlist(request, category_slug=None):\n template = 'shop/product/list.html'\n category = None\n categories = Category.objects.all()\n products = Product.objects.filter(available=True)\n page = request.GET.get('page')\n if category_slug:\n category = get_object_or_404(Category, slug=category_slug)\n sort_products = products.filter(category=category)\n paginator = Paginator(sort_products, 8)\n try:\n products = paginator.page(page)\n except PageNotAnInteger:\n products = paginator.page(1)\n except EmptyPage:\n products = paginator.page(paginator.num_pages)\n else:\n paginator = Paginator(products, 8)\n try:\n products = paginator.page(page)\n except PageNotAnInteger:\n products = paginator.page(1)\n except EmptyPage:\n products = paginator.page(paginator.num_pages)\n context = {\n 'category': category,\n 'categories': categories,\n 'products': products,\n 'page': page\n }\n return render(request, template, context)\n\n\ndef productdetail(request, id, slug):\n product = get_object_or_404(Product, id=id, slug=slug, available=True)\n cart_product_form = CartAddProductForm()\n return render_to_response('shop/product/detail.html',\n {'product': product,\n 'cart_product_form': cart_product_form})\n","sub_path":"shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"215716981","text":"# -*- coding: utf-8 -*-\n__package__ = \"cloud-chain.core.logger.main\"\n__version__ = \"0.1.4\"\n\n# IMPORTS #\n# python library imports\nimport logging\nimport inspect\nimport datetime\n\n# pass a message and log to your hearts desire\ndef CORE_LOGGER(msg):\n logging.basicConfig(level=logging.DEBUG,)\n current_function = inspect.currentframe().f_back.f_code\n return logging.debug(\"{}\\t{}\\t{}\\t{}\".format(\n datetime.datetime.now(),\n current_function.co_filename,\n current_function.co_name,\n msg))\n\n# this does not work. get rid of classes. functional module\nclass cCORE_LOGGER:\n def __init__(self, msg):\n logging.basicConfig(level=logging.DEBUG, format='%(name)s: %(messsage)s',)\n self.msg = msg\n self._log(self.msg)\n \n def _log(self, message):\n self.__current_function = inspect.currentframe().f_back.f_code\n #logging.basicConfig(level=logging.DEBUG, format='%(name)s: %(messsage)s',)\n return logging.debug(\"{}\\t{}\\t{}\\t{}\".format(\n datetime.datetime.now(),\n self.__current_function.co_filename,\n self.__current_function.co_name,\n message))\n\n","sub_path":"core/logger/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"139236067","text":"# Definition for binary tree with next pointer.\n# class TreeLinkNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n# self.next = None\n\nclass Solution(object):\n def connect(self, root):\n \"\"\"\n :type root: TreeLinkNode\n :rtype: nothing\n \"\"\"\n if not root:\n return\n st = [root, None]\n while st != [None]:\n tmp = st.pop(0)\n if tmp.left:\n st.append(tmp.left)\n if tmp.right:\n st.append(tmp.right)\n while tmp:\n tmp.next = st.pop(0)\n tmp = tmp.next\n if tmp:\n if tmp.left:\n st.append(tmp.left)\n if tmp.right:\n st.append(tmp.right)\n st.append(None)\n","sub_path":"code/Populating_Next_Right_Pointers_in_Each_Node.py","file_name":"Populating_Next_Right_Pointers_in_Each_Node.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"436600806","text":"\"\"\"This module contains functionality to plot an Activity\"\"\"\r\nfrom typing import List, Optional, Union\r\n\r\nimport holoviews as hv\r\nimport hvplot.pandas # pylint: disable=unused-import\r\nimport pandas as pd\r\nimport plotly.express as px\r\n\r\nDEFAULT_X_SERIES = [\"timestamp\"]\r\nDEFAULT_Y_SERIES = [\r\n \"power\",\r\n \"cadence\",\r\n]\r\n\r\n\r\ndef map_plot(\r\n data: Union[pd.DataFrame, None,]\r\n):\r\n \"\"\"A map plotting the activity\r\n\r\n Args:\r\n data (pd.DataFrame): A DataFrame with columns 'lat' and 'long' sorted by time \\\r\n ascending\r\n\r\n Returns:\r\n Plot: A plot showing a map of the activity route\r\n \"\"\"\r\n if data is None or data.empty:\r\n return None\r\n\r\n fig = px.scatter_mapbox(data, lat=\"lat\", lon=\"long\",)\r\n return fig\r\n\r\n\r\ndef activity_plot(\r\n data: pd.DataFrame, x_series: str = \"timestamp\", y_series: str = \"power\",\r\n):\r\n \"\"\"A plot of two columns of the Activity Data\r\n\r\n Args:\r\n data (pd.DataFrame): [description]\r\n x_series (str, optional): The series on the x-axis. Defaults to \"timestamp\".\r\n y_series (str, optional): The series on the y-axis. Defaults to \"power\".\r\n\r\n Returns:\r\n Plot: A plot\r\n \"\"\"\r\n return data.hvplot(x=x_series, y=y_series,)\r\n\r\n\r\ndef activity_plots(\r\n data: Union[pd.DataFrame, None,],\r\n x_series: Optional[List[str]] = None,\r\n y_series: Optional[List[str]] = None,\r\n) -> hv.Layout:\r\n \"\"\"A layout of plots\r\n\r\n Args:\r\n data (pd.DataFrame): The Activity Data\r\n x_series (Optional[List[str]]): The series to show on the x-axis. Defaults to \\\r\n DEFAULT_X_SERIES.\r\n y_series (Optional[List[str]]): The series to show on the y-axis. Defaults to \\\r\n DEFAULT_Y_SERIES.\r\n\r\n Returns:\r\n hv.Layout: A layout of plots\r\n \"\"\"\r\n if data is None or data.empty:\r\n return None\r\n if not x_series:\r\n x_series = DEFAULT_X_SERIES\r\n if not y_series:\r\n y_series = DEFAULT_Y_SERIES\r\n\r\n layout = hv.Layout()\r\n\r\n for xss in x_series:\r\n for yss in y_series:\r\n layout.items.append(activity_plot(data, xss, yss,))\r\n return layout\r\n","sub_path":"src/pages/gallery/training_analysis/plots/activity_plot.py","file_name":"activity_plot.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"228760034","text":"import time\nimport webbrowser\n\nbreak_time = 3\nbreak_count = 0\n\nprint(\"This program started on\" + time.ctime())\nwhile(break_count < break_time) :\n time.sleep(10)\n webbrowser.open(\"https://youtu.be/mx24IJTlffc\")\n break_count += 1\n","sub_path":"Project/takeabreak.py","file_name":"takeabreak.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"192028474","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 8 12:13:56 2018\n\n@author: madsthoisen\n\"\"\"\n## This module is used to initialize instances of PyGame classes\n\nimport pygame\n\nclass Wall(pygame.sprite.Sprite):\n def __init__(self, x, y, GroupAllSprites, GroupWalls, TileSize, ColorWall):\n self.groups = GroupAllSprites, GroupWalls\n pygame.sprite.Sprite.__init__(self, self.groups)\n self.image = pygame.Surface((TileSize,TileSize))\n self.image.fill(ColorWall)\n self.rect = self.image.get_rect() \n self.x = x\n self.y = y\n self.rect.topleft = (self.x * TileSize ,self.y * TileSize)\n\nclass Box(pygame.sprite.Sprite):\n def __init__(self, x, y, GroupAllSprites, GroupBoxes, TileSize, ColorBox):\n self.groups = GroupAllSprites, GroupBoxes\n pygame.sprite.Sprite.__init__(self, self.groups)\n self.image = pygame.Surface((TileSize,TileSize))\n self.image.fill(ColorBox)\n self.rect = self.image.get_rect()\n self.x = x\n self.y = y\n self.rect.topleft = (self.x * TileSize ,self.y * TileSize)\n self.dx = 0\n self.dy = 0\n \nclass Storage(pygame.sprite.Sprite):\n def __init__(self, x, y, GroupAllSprites, GroupStorages, TileSize, ColorStorage):\n self.groups = GroupAllSprites, GroupStorages\n pygame.sprite.Sprite.__init__(self, self.groups) \n self.image = pygame.Surface((TileSize,TileSize))\n self.image.fill(ColorStorage)\n self.rect = self.image.get_rect()\n self.x = x\n self.y = y\n self.rect.topleft = (self.x * TileSize ,self.y * TileSize)\n self.hasPlayer = False\n self.hasBox = False","sub_path":"sokoban/WallsBoxesStorages.py","file_name":"WallsBoxesStorages.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"630345962","text":"import tkinter as tk\nfrom tkinter import messagebox\nfrom tkinter import filedialog\n\n\nimport datetime\nimport os\nimport shutil\nimport sqlite3\nimport time\n\n\ndef close(self):\n \"\"\"Asks user if they would like to quit the application,\n and if so, kills the program.\n \"\"\"\n if messagebox.askokcancel(\"Exit Program\",\n \"Are you sure you want to close the application?\"):\n self.master.destroy()\n os._exit(0)\n\n\ndef create_db(self):\n \"\"\"Establishes connection with database, and creates the table\n if it does not already exist.\n \"\"\"\n conn = sqlite3.connect('file_xfer.db')\n with conn:\n c = conn.cursor()\n c.execute(\"CREATE TABLE IF NOT EXISTS timestamps(unix REAL)\")\n conn.commit()\n c.close()\n conn.close()\n\n def read_db(self):\n \"\"\"Reads the max unix value from the timestamps table, and\n populates the tkinter label widget.\n \"\"\"\n conn = sqlite3.connect('file_xfer.db')\n with conn:\n c = conn.cursor()\n c.execute(\"SELECT MAX(unix) FROM timestamps\")\n most_recent = c.fetchone()[0]\n most_recent = time.ctime(most_recent)\n c.close()\n conn.close()\n\n # create and populate the label_print widget\n self.label_print = tk.Label(self.master, width=60, height=2, text=\"Last modified: {}\".format(most_recent))\n self.label_print.grid(row=3, column=0, rowspan=1, columnspan=3, padx=(0, 0), pady=(10, 10))\n\n read_db(self)\n\n\ndef get_source(self):\n \"\"\"Clears the current entry box, then replaces it with\n the selected file path.\n \"\"\"\n self.text_source.delete(0, 60)\n self.custom_source = filedialog.askdirectory()\n self.text_source.insert(0, self.custom_source)\n\n\ndef get_dest(self):\n \"\"\"Clears the current entry box, then replaces it with\n the selected file path.\n \"\"\"\n self.text_dest.delete(0, 60)\n self.custom_dest = filedialog.askdirectory()\n self.text_dest.insert(0, self.custom_dest)\n\n\ndef move_files(self, source, destination):\n \"\"\"Accepts two file path parameters as a source and a destination.\n Searches through source parameter, finds all files that end in '.txt',\n compares their last modified timestamp (mtime) with 24 hours ago from\n application run time, and if the .txt file was modified in the last 24 hours,\n it will be moved to the destination parameter. It will pop up a message box\n saying that it was completed successfully, then enters a unix timestamp into\n the database 'file_xfer.db'.\n \"\"\"\n # declare variables for current run time and 24 hours ago\n now = datetime.datetime.now()\n ago = now - datetime.timedelta(hours=24)\n print('The following .txt files were modified in the last 24 hours: \\n')\n\n # loop through files in the source parameter\n for files in os.listdir(source):\n # if the files end with '.txt', create variables with a path and stats\n if files.endswith('.txt'):\n path = os.path.join(source, files)\n st = os.stat(path)\n # create a variable with the file's timestamp from its stats\n mtime = datetime.datetime.fromtimestamp(st.st_mtime)\n # compare the file's modified time with 24 hours ago\n if mtime > ago:\n # print the file and when it was last modified\n print('{} ~ last modified {}'.format(path, mtime))\n # use os.path.join to create an absolute path\n file_source = os.path.join(source, files)\n file_destination = os.path.join(destination, files)\n # move the files using the absolute path\n shutil.move(file_source, file_destination)\n # print what was moved successfully and to where\n print(\"\\tMoved {} to {}.\\n\".format(files, destination))\n\n # enter current time into database on click event\n current_time = time.time()\n conn = sqlite3.connect('file_xfer.db')\n with conn:\n c = conn.cursor()\n c.execute(\"INSERT INTO timestamps VALUES({})\".format(current_time))\n conn.commit()\n c.close()\n conn.close()\n\n # pop up a tkinter messagebox\n messagebox.showinfo(\"File Transfer\", \"Files moved successfully!\")\n\n def read_db(self):\n \"\"\"Reads the max unix value from the timestamps table, and\n populates the tkinter label widget.\n \"\"\"\n conn = sqlite3.connect('file_xfer.db')\n with conn:\n c = conn.cursor()\n c.execute(\"SELECT MAX(unix) FROM timestamps\")\n most_recent = c.fetchone()[0]\n most_recent = time.ctime(most_recent)\n c.close()\n conn.close()\n\n # create and populate the label_print widget with the new time\n self.label_print = tk.Label(self.master, width=60, height=2, text=\"Last modified: {}\".format(most_recent))\n self.label_print.grid(row=3, column=0, rowspan=1, columnspan=3, padx=(0, 0), pady=(10, 10))\n\n read_db(self)\n\n","sub_path":"file_xfer_func.py","file_name":"file_xfer_func.py","file_ext":"py","file_size_in_byte":5020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"618675810","text":"\"\"\"Add modified on Comment model\n\nRevision ID: d83f5dd29186\nRevises: 4ce19971b7ec\nCreate Date: 2021-01-05 23:47:32.012838\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'd83f5dd29186'\ndown_revision = '4ce19971b7ec'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('comments', sa.Column('modified', sa.DateTime(), nullable=False))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('comments', 'modified')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/d83f5dd29186_add_modified_on_comment_model.py","file_name":"d83f5dd29186_add_modified_on_comment_model.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"41687875","text":"import math\r\n\r\ndef f(n):\r\n res = list()\r\n i = 1\r\n while i <= n:\r\n root = math.sqrt(i)\r\n if int(root + 0.5) ** 2 == i:\r\n res.append(i)\r\n i += 1\r\n\r\n print(res)\r\n\r\nn = 30\r\n\r\nf(n)\r\n\r\n","sub_path":"TSIS6/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"340247647","text":"import json\r\nimport sys\r\nimport random\r\nfrom flask import Flask, jsonify, make_response, request, abort\r\n\r\napp = Flask(__name__)\r\n\r\nclass Project(object):\r\n def __init__(self):\r\n self.concerned_factory = None\r\n self.process_to_improve = None\r\n self.project_no = None\r\n self.description = None\r\n self.project_manager = None\r\n self.manager = None\r\n self.concerned_services = None\r\n self.image_map = None\r\n self.project_room_link = None\r\n self.approved_by = None\r\n self.status = None\r\n self.progress_status = None\r\n self.linked_objects = None\r\n self.archive_localisation = None\r\n self.hierarchic_code = None\r\n self.extern_references = None\r\n self.implementation_supervisor = None\r\n self.launch_date = None\r\n self.number = None\r\n\r\n def serialize(self):\r\n return self.__dict__\r\n\r\n@app.after_request\r\ndef after_request(data):\r\n\tresponse = make_response(data)\r\n\tresponse.headers['Content-Type'] = 'application/json'\r\n\tresponse.headers['Access-Control-Allow-Origin'] = '*'\r\n\tresponse.headers['Access-Control-Allow-Headers'] = \"Origin, X-Requested-With, Content-Type, Accept\"\r\n\tresponse.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE'\r\n\treturn response\r\n\r\nprojects = []\r\n\r\n@app.errorhandler(400)\r\ndef bad_request(error):\r\n return make_response(jsonify( { 'error': 'Bad Request' } ), 400)\r\n\r\n@app.errorhandler(404)\r\ndef not_found(error):\r\n return make_response(jsonify( { 'error': 'Not Found' } ), 404)\r\n\r\n@app.route('/projects', methods = ['POST'])\r\ndef create_project():\r\n if not request.json:\r\n abort(400)\r\n\r\n project = Project()\r\n project.project_no = random.randint(10000, 12000000000)\r\n project.concerned_factory = request.json.get('concerned_factory')\r\n project.process_to_improve = request.json.get('process_to_improve')\r\n project.description = request.json.get('description')\r\n project.project_manager = request.json.get('project_manager')\r\n project.manager = request.json.get('manager')\r\n project.concerned_services = request.json.get('concerned_services')\r\n project.image_map = request.json.get('image_map')\r\n project.project_room_link = request.json.get('project_room_link')\r\n project.approved_by = request.json.get('approved_by')\r\n project.status = request.json.get('status')\r\n project.progress_status = request.json.get('progress_status')\r\n project.linked_objects = request.json.get('linked_objects')\r\n project.archive_localisation = request.json.get('archive_localisation')\r\n project.hierarchic_code = request.json.get('hierarchic_code')\r\n project.extern_references = request.json.get('extern_references')\r\n project.implementation_supervisor = request.json.get('implementation_supervisor')\r\n project.launch_date = request.json.get('launch_date')\r\n project.number = request.json.get('number')\r\n\r\n projects.append(project)\r\n return jsonify( project.serialize() ), 201\r\n\r\n@app.route('/projects', methods = ['GET'])\r\ndef get_projects():\r\n return jsonify( results=[ project.serialize() for project in projects ] )\r\n\t\r\n@app.route('/projects/', methods = ['GET'])\r\ndef get_project(project_no):\r\n map(print, projects)\r\n project = list(filter(lambda p: p.project_no == project_no, projects))\r\n if len(project) == 0:\r\n abort(404)\r\n return jsonify( project[0].serialize() )\r\n\t\r\n@app.route('/projects/', methods = ['PUT'])\r\ndef update_project(project_no):\r\n project = list(filter(lambda p: p.project_no == project_no, projects))\r\n if len(project) == 0 or not request.json:\r\n abort(404)\r\n project[0].concerned_factory = request.json.get('concerned_factory')\r\n project[0].process_to_improve = request.json.get('process_to_improve')\r\n project[0].description = request.json.get('description')\r\n project[0].project_manager = request.json.get('project_manager')\r\n project[0].manager = request.json.get('manager')\r\n project[0].concerned_services = request.json.get('concerned_services')\r\n project[0].image_map = request.json.get('image_map')\r\n project[0].project_room_link = request.json.get('project_room_link')\r\n project[0].approved_by = request.json.get('approved_by')\r\n project[0].status = request.json.get('status')\r\n project[0].progress_status = request.json.get('progress_status')\r\n project[0].linked_objects = request.json.get('linked_objects')\r\n project[0].archive_localisation = request.json.get('archive_localisation')\r\n project[0].hierarchic_code = request.json.get('hierarchic_code')\r\n project[0].extern_references = request.json.get('extern_references')\r\n project[0].implementation_supervisor = request.json.get('implementation_supervisor')\r\n project[0].launch_date = request.json.get('launch_date')\r\n project[0].number = request.json.get('number')\r\n return jsonify( results=[ project.serialize() for project in projects ] )\r\n\r\n@app.route('/projects/', methods = ['DELETE'])\r\ndef delete_project(project_no):\r\n project = list(filter(lambda p: p.project_no == project_no, projects))\r\n if len(project) == 0:\r\n abort(404)\r\n projects.remove(project[0])\r\n return jsonify( results=[ project.serialize() for project in projects ] )\r\n\r\nif __name__ == '__main__':\r\n app.run(debug = True)\r\n","sub_path":"server/python-server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"100721017","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n### BFS\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n stack = [root]\n res = []\n while stack:\n next_stack, temp_res = [], []\n for i in stack:\n temp_res.append(i.val)\n if i.left:\n next_stack.append(i.left)\n if i.right:\n next_stack.append(i.right)\n res.append(temp_res)\n stack = next_stack\n return res\n\n### DFS\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n self.res = []\n self._dfs(root, 0)\n return self.res\n\n def _dfs(self, root, level):\n if not root:\n return None\n if len(self.res) < level + 1:\n self.res.append([])\n self.res[level].append(root.val)\n self._dfs(root.left, level + 1)\n self._dfs(root.right, level + 1)","sub_path":"102_二叉树的层次遍历.py","file_name":"102_二叉树的层次遍历.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"594810056","text":"# This is a program that performs image classification on digits using a forward propagation neural network.\n\n\nimport numpy as np\nfrom sigmoid import sigmoid\nfrom cost import cost\nfrom predict import predict\n\n# Suppose X has dimension m x n where m is the number of examples and n is the number of features.\n# So the neural network will have n + 1 input layers including the bias (+1). \n# Suppose there are h hidden layers and p output layers.\n\n# W1 is the weight matrix connecting input and hidden layers.\n# W2 is the weight matrix connecting hidden and output layers.\n\n# X is m by n and Y is m by p.\ndef train(Xin, Yin, h, num_iter, gamma, lambda_reg):\n\n m = np.shape(Xin)[0] # Same as np.shape(Yin)[0]\n n = np.shape(Xin)[1]\n p = np.shape(Yin)[1]\n\n # Initial weights.\n W1 = np.random.uniform(-0.12, 0.12, h * (n + 1)).reshape(h, n + 1) # h by n + 1 \n W2 = np.random.uniform(-0.12, 0.12, p * (h + 1)).reshape(p, h + 1) # p by h + 1\n\n counter = 1\n while counter <= num_iter:\n\n v = predict(Xin, Yin, h, W1, W2)\n A1, A2, A3 = v[0], v[1], v[2] # m by n + 1, m by h + 1, m by p\n\n J = cost(Yin, A3, lambda_reg, W1, W2)\n print(counter, J, sep = ': ')\n \n # For backpropagation\n delta3 = (A3 - Yin) # m by p\n W2bar = W2[:, 1:] # This is W2 with first column removed with shape p by h.\n A2prime = A2[:, 1:] # m by h\n delta2 = A2prime * np.dot(delta3, W2bar) # m by h\n\n # Change in weights\n # The first column of W1 and W2 are not regularized.\n \n dW2 = -gamma/m * np.dot(delta3.transpose(), A2) \n dW2[:, 1:] = dW2[:, 1:] + lambda_reg/m * W2[:, 1:]\n \n dW1 = -gamma/m * np.dot(delta2.transpose(), A1) \n dW1[:, 1:] = dW1[:, 1:] + lambda_reg/m * W1[:, 1:]\n\n W1 = W1 + dW1\n W2 = W2 + dW2\n \n counter = counter + 1\n\n return [W1, W2]\n\n\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"429523202","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\ndef selection_sort(a):\n for i in range(len(a) - 1):\n tmp = i\n x = i + 1\n while x < len(a):\n if a[x] < a[tmp]:\n tmp = x\n x += 1\n a[i], a[tmp] = a[tmp], a[i]\n return a\n","sub_path":"selection_sort.py","file_name":"selection_sort.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"276133441","text":"def solution(s):\n stk = []\n for i in s:\n if len(stk) == 0:\n stk.append(i)\n elif i == stk[-1]:\n stk.pop()\n else:\n stk.append(i)\n if len(stk) == 0:\n return 1\n else:\n return 0\n\ns = 'baabaa'\nprint(solution(s), 'result')","sub_path":"coding_test/2017_friend_delete.py","file_name":"2017_friend_delete.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"418742113","text":"# -*- coding: utf8 -*-\n\nimport logging\n# from settings import CLASS_LEVEL1\n# import all the variables and classes in .py\nfrom settings import VOCABULARY_SIZE\nfrom settings import SAVE_DIR\nfrom settings import TRAINING_INSTANCES\nfrom settings import TRAIN_SET_PATH\nimport os\nimport sys\nimport pandas\nimport numpy\n\nimport math\n\n\ndef get_logger(name):\n '''\n set and return the logger modula,\n output: std\n '''\n formatter = logging.Formatter('%(asctime)s - %(message)s')\n logger = logging.getLogger(name)\n logger.setLevel(logging.INFO)\n sh = logging.StreamHandler()\n sh.setLevel(logging.INFO)\n sh.setFormatter(formatter)\n fh = logging.FileHandler(name)\n fh.setLevel(logging.INFO)\n fh.setFormatter(formatter)\n logger.addHandler(sh)\n logger.addHandler(fh)\n return logger\n\n\ndef latest_save_num():\n '''\n get the latest save num for the dir in save file\n '''\n if not os.path.exists(SAVE_DIR):\n os.makedirs(SAVE_DIR)\n # list all the files in save dir\n files = os.listdir(SAVE_DIR)\n maxno = -1\n # print(files)\n for f in files:\n if os.path.isdir(SAVE_DIR + '/' + f):\n # print(f,'true')\n try:\n # print(name)\n no = int(f)\n maxno = max(maxno, no)\n # print(maxno)\n except Exception as e:\n print(e.message, file=sys.stderr)\n pass\n return maxno\n\n\nclass DataManager():\n '''\n data loading module\n '''\n # __df = None # not use this format of data initialization,\n # possible confusion\n # __cursor = 0\n\n def __init__(\n self,\n param_batch_size,\n param_training_instances_size):\n\n # param_topic_sentiment_count,\n # param_sentiment_count ):\n # self.df=None\n # self.cursor=0\n # self.batch_size=batch_size\n\n # global private variable initialized here\n\n # dataframe read by a chunk\n self.__current_dataframe_of_pandas = None\n # the cursor shifted in pandas,\n # it's the global cursor shift in dataframe\n self.__current_cursor_in_dataframe = 0\n self.__batch_size = param_batch_size\n # self.__topic_sentiment_count = param_topic_sentiment_count\n # self.__sentiment_count = param_sentiment_count\n self.__training_instances_size = param_training_instances_size\n\n # self.__batch_size = param_batch_size\n # the current cursor in file, is the line num\n # self.__current_cursor = 0\n # list_all_tweets_of_auser#the current file pointer\n # self.__current_file_pointer = None\n return None\n\n def load_dataframe_from_file(self, param_filepath_in):\n '''\n read once, initialize dataframe_of_pandas\n '''\n\n print('Loading dataframe...')\n self.__current_dataframe_of_pandas = pandas.read_csv(\n param_filepath_in, dtype=numpy.uint8, header=None,\n encoding='utf-8', sep='\\s+', engine='c', low_memory=True)\n\n # self.__dataframe_of_pandas = \\\n # pandas.read_csv(\n # param_filepath_in, header = None,\n # encoding = 'utf8',sep = '\\t' , engine = 'c')\n # you can use regular expression in sep by setting engine = 'python'\n # engine = 'c' will face error,\n # 'c' requires all the data type to be the same\n\n # c do not support \\t\\n\n # print(len(self.__dataframe_of_pandas) )\n # currently every 9 lines describe a user\n return None\n\n def reshuffle_dataframe(self):\n self.__current_dataframe_of_pandas.sample(frac=1)\n\n def next_batch(self):\n '''\n obtain next batch\n possible out of range, you have to control the tail\n the best way is to call next_batch dataframe_size()//batch_size times\n then call tail_batch\n use reshape\n '''\n\n batch_size = self.__batch_size\n # start cursor\n s = self.__current_cursor_in_dataframe\n # end cursor\n t = s + batch_size\n # get the current chunk, chunk is a default dataframe,\n # should be transformed to float32,\n # or the dataformat will not be the same\n # dataframe_of_pandas = pandas.DataFrame(\n # data=self.__chunks_of_pandas.get_chunk( chunk_size),\n # dtype=numpy.float32)\n\n batch_index = s // batch_size\n\n print(\"Loading batch: %d\" % (batch_index))\n # get the current chunk,\n # chunk is a default dataframe,\n # should be transformed to float32,\n # or the dataformat will not be the same\n # dataframe_of_pandas = self.__current_dataframe_of_pandas\n # .get_chunk(chunk_size)\n\n # print('get_chunk: ' + str( s//batch_size))\n\n batch_xn = numpy.zeros((batch_size,\n VOCABULARY_SIZE),\n dtype=numpy.uint8)\n\n batch_wc = numpy.zeros((batch_size,\n VOCABULARY_SIZE),\n dtype=numpy.uint8)\n\n for instance_i in range(s, t):\n # print('user_i: ' + str(user_i))\n # each user's time serial\n\n # one col for label\n pivot_wordindex = \\\n self.__current_dataframe_of_pandas.iloc[instance_i][0]\n batch_xn[instance_i % batch_size][pivot_wordindex] = 1\n\n batch_wc[instance_i % batch_size] = \\\n self.__current_dataframe_of_pandas.iloc[instance_i][1:].values\n\n # print( label_shift)\n\n # batch_x[ user_i%batch_size] = \\\n # numpy.reshape(\n # dataframe_of_pandas.iloc[user_i% batch_size][\n # label_shift: ],\n # (1+USER_TWITTER_COUNT+NEIGHBOR_TWITTER_COUNT,\n # 1+USER_TWITTER_COUNT+NEIGHBOR_TWITTER_COUNT,\n # TWITTER_LENGTH, WORD_EMBEDDING_DIMENSION) )\n # batch_x[ user_i%batch_size] = \\\n # dataframe_of_pandas.iloc[\n # user_i % batch_size][label_shift:].values.reshape(\n # (1+USER_TWITTER_COUNT+NEIGHBOR_TWITTER_COUNT,\n # 1+USER_TWITTER_COUNT+NEIGHBOR_TWITTER_COUNT,\n # TWITTER_LENGTH, WORD_EMBEDDING_DIMENSION))\n\n # dataframe_of_pandas infact is a dataframe of a chunk_size\n\n # print(batch_x.shape)\n\n # list_labels = self.__dataframe_of_pandas.iloc[ user_i , 0 ]\n # batch_y[ user_i%batch_size ][ 0 ] = list_labels[ 0 ]\n # batch_y[ user_i%batch_size ][ 1 ] = list_labels[ 1 ]\n\n self.__current_cursor_in_dataframe = t\n\n return batch_xn, batch_wc\n\n def set_current_cursor_in_dataframe_zero(self):\n '''\n if INSTANCE % batch_size == 0,\n then the tail_batch won't be called,\n so call this function to reset the\n __cursor_in_current_frame\n '''\n self.__current_cursor_in_dataframe = 0\n\n def tail_batch(self):\n '''\n if INSTANCE % batch_size != 0\n then call the tail_batch, padding the tail\n '''\n\n batch_size = self.__batch_size\n\n s = self.__current_cursor_in_dataframe\n t = s + batch_size\n\n batch_index = s // batch_size\n\n print(\"Loading batch: %d\" % (batch_index))\n\n # self.__current_dataframe_of_pandas\n # get the current chunk,\n # chunk is a default dataframe,\n # should be transformed to float32,\n # or the dataformat will not be the same\n # .get_chunk(chunk_size)\n\n batch_xn = numpy.zeros((batch_size,\n VOCABULARY_SIZE),\n dtype=numpy.uint8)\n\n batch_wc = numpy.zeros((batch_size,\n VOCABULARY_SIZE),\n dtype=numpy.uint8)\n # complement the last chunk with the initial last chunk\n # assert len(self.__current_dataframe_of_pandas) == \\\n # self.__training_instances_size\n last_batch_size = len(self.__current_dataframe_of_pandas)\\\n % batch_size\n\n # append_times = batch_size // last_batch_size\n # append_tail = batch_size % last_batch_size\n\n # dataframe_of_pandas_compensated = \\\n # pandas.DataFrame(data=None,\n # columns=dataframe_of_pandas.axes[1])\n\n # for i in range(0, append_times):\n # dataframe_of_pandas_compensated = \\\n # dataframe_of_pandas_compensated.append(\n # dataframe_of_pandas.iloc[s:s + last_batch_size],\n # ignore_index=True)\n # for ignore_index refer to the manual\n\n # dataframe_of_pandas_compensated = \\\n # dataframe_of_pandas_compensated.append(\n # dataframe_of_pandas.iloc[\n # s: s + append_tail], ignore_index=True)\n\n for instance_i in range(s, t):\n # list_all_tweets_of_auser = \\\n # self.__dataframe_of_pandas.iloc[\n # i,\n # 2:(2+1+USER_TWITTER_COUNT+NEIGHBOR_TWITTER_COUNT)].values.tolist()\n # list_a label_shift = 1 #one col for label\n\n # batch_x[ user_i%batch_size] = \\\n # dataframe_of_pandas.iloc[\n # user_i%batch_size][label_shift:].reshape((\n # 1+USER_TWITTER_COUNT+NEIGHBOR_TWITTER_COUNT,\n # 1+USER_TWITTER_COUNT+NEIGHBOR_TWITTER_COUNT,\n # TWITTER_LENGTH, WORD_EMBEDDING_DIMENSION) )\n\n if (instance_i % batch_size) < last_batch_size:\n pivot_wordindex = \\\n self.__current_dataframe_of_pandas.iloc[\n instance_i][0]\n\n batch_xn[instance_i % batch_size][pivot_wordindex] = 1\n\n batch_wc[instance_i % batch_size] = \\\n self.__current_dataframe_of_pandas.iloc[\n instance_i][1:].values\n else:\n shift_in_last_batch_size = \\\n (instance_i % batch_size) % last_batch_size\n iloc_index = instance_i - instance_i % batch_size\\\n + shift_in_last_batch_size\n batch_xn[instance_i % batch_size] = \\\n self.__current_dataframe_of_pandas.iloc[\n iloc_index][0]\n\n batch_wc[instance_i % batch_size] = \\\n self.__current_dataframe_of_pandas.iloc[\n iloc_index][1:].values\n\n self.__current_cursor_in_dataframe = 0\n\n return batch_xn, batch_wc\n\n def n_batches(self):\n # if self.__current_dataframe_of_pandas == None:\n # print('Error: __current_dataframe_of_pandas == None',\n # file=sys.stderr)\n # else:\n return math.ceil(\n self.__training_instances_size / self.__batch_size)\n\n\nif __name__ == '__main__':\n # arr = numpy.array(1)\n # print(arr.shape) # = ()\n\n # oDataManager = DataManager(\n # param_batch_size=2,\n # param_training_instances_size=2)\n\n # oDataManager.load_dataframe_from_file('dataframetest.csv')\n # # print('----------getcwd()', os.getcwd())\n oDataManager = DataManager(\n param_batch_size=128,\n param_training_instances_size=TRAINING_INSTANCES)\n\n # # oDataManager.generate_csv_from_wordembbed( TRAIN_SET_PATH )\n\n oDataManager.load_dataframe_from_file(TRAIN_SET_PATH)\n\n # print(oDataManager.dataframe_size() // 64 )\n # print(oDataManager.dataeframe_size() % 64 )\n\n print('Hello')\n for i in range(0, TRAINING_INSTANCES // 128):\n print(i)\n (batch_xn, batch_wc) = oDataManager.next_batch()\n print('----------shape_xn:',\n batch_xn.shape,\n '----------shape_wc:',\n batch_wc.shape)\n if TRAINING_INSTANCES % 128 == 0:\n oDataManager.set_current_cursor_in_dataframe_zero()\n else:\n (batch_xn, batch_wc) = oDataManager.tail_batch()\n # size of torch in numpy\n print(batch_xn.shape)\n print(batch_wc.shape)\n","sub_path":"src/utils_nonsparse_traininstance.py","file_name":"utils_nonsparse_traininstance.py","file_ext":"py","file_size_in_byte":12144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"348013542","text":"\"\"\"\nJingyuan Tu (1232404), Melbourne, Australia\nFloyd Everest-Dobson (664751), Melbourne, Australia\nBradley Schuurman (586088), Melbourne, Australia\nIris Li (875195), Melbourne, Australia\nPaul Ou (888653), Melbourne, Australia\n\"\"\"\n\nfrom Tweet import Tweet\nfrom User import User\nfrom cloudant.client import CouchDB\nfrom cloudant.error import CloudantDatabaseException\nfrom cloudant.design_document import DesignDocument\nfrom cloudant.view import View\n\n\n# Couch DB Wrapper\nclass TweetDatabase:\n def __init__(self):\n self.client = None\n self.tweets_db_name = \"tweets\"\n self.users_db_name = \"users\"\n \n def connect(self, username, password, address):\n self.client = CouchDB(username, password, url=address, connect=True, auto_renew=True)\n\n def disconnect(self):\n self.client.disconnect()\n\n def setup(self):\n existing_dbs = self.client.all_dbs()\n if self.tweets_db_name not in existing_dbs:\n self.client.create_database(self.tweets_db_name)\n if self.users_db_name not in existing_dbs:\n self.client.create_database(self.users_db_name)\n\n # add views if they don't exist - customise them to the views we need \n with DesignDocument(self.client[self.tweets_db_name], document_id=\"languages\") as ddoc_tweets:\n def _add(view_name, view_key):\n if view_name not in ddoc_tweets.list_views():\n ddoc_tweets.add_view(view_name, \"function (doc) { emit(doc.city, \" + view_key + \"); }\", \"_sum\")\n def _add_subjectivity(view_name, view_key):\n if view_name not in ddoc_tweets.list_views():\n ddoc_tweets.add_view(view_name, \"function(doc){if(\" + view_key + \">0){emit(doc.city,doc.subjectivity);}}\", \"_sum\")\n def _add_polarity(view_name, view_key):\n if view_name not in ddoc_tweets.list_views():\n ddoc_tweets.add_view(view_name, \"function(doc){if(\" + view_key + \">0){emit(doc.city,doc.polarity);}}\", \"_sum\")\n def _add_counter(view_name, view_key):\n if view_name not in ddoc_tweets.list_views():\n ddoc_tweets.add_view(view_name, \"function(doc){if(\" + view_key + \">0){emit(doc.city,1);}}\", \"_sum\")\n \n\n _add(\"vulgard\", \"doc.vulgard_count\")\n _add(\"polarity\", \"doc.polarity\")\n _add(\"subjectivity\", \"doc.subjectivity\")\n _add(\"count\", \"doc.word_count\")\n\n _add(\"covid\", \"doc.topic_scores.covid\")\n _add_subjectivity(\"covid_subjectivity\", \"doc.topic_scores.covid\")\n _add_polarity(\"covid_polarity\", \"doc.topic_scores.covid\")\n _add_counter(\"covid_counter\", \"doc.topic_scores.covid\")\n\n _add(\"climate\", \"doc.topic_scores.climate\")\n _add_subjectivity(\"climate_subjectivity\", \"doc.topic_scores.climate\")\n _add_polarity(\"climate_polarity\", \"doc.topic_scores.climate\")\n _add_counter(\"climate_counter\", \"doc.topic_scores.climate\")\n\n _add(\"finance\", \"doc.topic_scores.finance\")\n _add_subjectivity(\"finance_subjectivity\", \"doc.topic_scores.finance\")\n _add_polarity(\"finance_polarity\", \"doc.topic_scores.finance\")\n _add_counter(\"finance_counter\", \"doc.topic_scores.finance\")\n\n _add(\"housing\", \"doc.topic_scores.housing\")\n _add_subjectivity(\"housing_subjectivity\", \"doc.topic_scores.housing\")\n _add_polarity(\"housing_polarity\", \"doc.topic_scores.housing\")\n _add_counter(\"housing_counter\", \"doc.topic_scores.housing\")\n\n _add(\"sport\", \"doc.topic_scores.sport\")\n _add_subjectivity(\"sport_subjectivity\", \"doc.topic_scores.sport\")\n _add_polarity(\"sport_polarity\", \"doc.topic_scores.sport\")\n _add_counter(\"sport_counter\", \"doc.topic_scores.sport\") \n\n\n with DesignDocument(self.client[self.users_db_name], document_id=\"user\") as ddoc_users:\n if \"depth\" not in ddoc_users.list_views():\n ddoc_users.add_view(\"depth\", \"function (doc) { emit([doc.depth], 1);}\", \"_stats\")\n \n # this is a Tweet object\n # return True on success, returns false on duplicate or unknown failure.\n def add_tweet(self, tweet) -> bool:\n try:\n db = self.client[self.tweets_db_name]\n db.create_document(tweet.to_dict(), throw_on_exists=True)\n return True\n except CloudantDatabaseException:\n return False\n \n # this is a User object\n # return True on success, returns false on duplicate or unknown failure.\n def add_user(self, user) -> bool:\n try:\n db = self.client[self.users_db_name]\n db.create_document(user.to_dict(), throw_on_exists=True)\n return True\n except Exception:\n return False\n \n \n # id_str of the tweet.\n def get_tweet(self, id):\n try:\n db = self.client[self.tweets_db_name]\n tweet = Tweet()\n tweet.from_dict(db[id])\n return tweet\n except Exception:\n return None\n\n def get_user(self, id):\n try:\n db = self.client[self.users_db_name]\n user = User()\n user.from_dict(db[id])\n return user\n except Exception:\n return None\n \n # visited is None means get all users, True means get users that are visited\n # False means get users that are not visited.\n def get_all_users(self, visited=None):\n db = self.client[self.users_db_name]\n # generate user on the fly using yield\n for user_doc in db:\n try:\n user = User()\n user.from_dict(user_doc)\n if visited != None and user.visited != visited:\n continue\n yield user\n except Exception:\n # This is because design document is part of user database\n continue\n\n def update_tweet(self, tweet) -> bool:\n try:\n db = self.client[self.tweets_db_name]\n doc = db[tweet.id]\n doc[\"content\"] = tweet.content\n doc[\"coordinate\"] = tweet.coordinate\n doc[\"city\"] = tweet.city\n doc[\"bounding_box\"] = tweet.bounding_box\n doc[\"user_id\"] = tweet.user_id\n doc[\"polarity\"] = tweet.polarity\n doc[\"subjectivity\"] = tweet.subjectivity\n doc[\"vulgard_count\"] = tweet.vulgard_count\n doc[\"word_count\"] = tweet.word_count\n doc[\"topic_scores\"] = tweet.topic_scores\n doc[\"lang\"] = tweet.lang\n doc.save()\n return True\n except Exception:\n return False\n\n def update_user(self, user) -> bool:\n try:\n db = self.client[self.users_db_name]\n doc = db[user.id]\n doc[\"visited\"] = user.visited\n doc[\"depth\"] = user.depth\n doc.save()\n return True\n except Exception:\n return False\n\n def remove_tweet(self, id):\n db = self.client[self.tweets_db_name]\n doc = db[id]\n doc.delete()\n\n def remove_user(self, id):\n db = self.client[self.users_db_name]\n doc = db[id]\n doc.delete()\n\n\n # Get sentiment scores.\n # Possible views:\n # vulgard\n # polarity\n # subjectivity\n # count\n # covid\n # climate\n # finance\n # housing\n # sport\n def get_stats(self, view_name):\n try:\n with DesignDocument(self.client[self.tweets_db_name], \"languages\") as ddoc:\n result = {\n \"sydney_1\": 0,\n \"sydney_2\": 0,\n \"melbourne_1\": 0,\n \"melbourne_2\": 0\n }\n view = View(ddoc, view_name)\n with view.custom_result(group=True) as results:\n for r in results:\n result[r[\"key\"]] = r[\"value\"]\n return result\n except Exception:\n # Cannot find the view.\n return None\n ","sub_path":"backend/TweetDatabase.py","file_name":"TweetDatabase.py","file_ext":"py","file_size_in_byte":7192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"67692084","text":"## 12865. 평범한 배낭\n\nn, k = map(int, input().split())\nbags = []\ndp = [[0 for _ in range(k + 1)] for _ in range(n + 1)]\n\nfor _ in range(n):\n w, v = map(int, input().split())\n bags.append((w, v))\n\nfor i in range(1, n + 1): # i : bag\n for j in range(1, k + 1): # j : 무게\n if bags[i - 1][0] <= j:\n dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - bags[i - 1][0]] + bags[i - 1][1])\n else:\n dp[i][j] = dp[i - 1][j]\n\nprint(dp[n][k])\n","sub_path":"boj/boj_12865_평범한배낭.py","file_name":"boj_12865_평범한배낭.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"173113685","text":"import pygame\r\nfrom graph import GRAPH\r\nimport copy\r\nimport time\r\nfrom heapq import heapify, heappush, heappop \r\n\r\ngraph = GRAPH\r\ndisplay_width = 800\r\ndisplay_height = 600\r\nradius = 30\r\nspeed = 2\r\n\r\ngrey = (100, 100, 100)\r\nwhite = (255, 255, 255)\r\nyellow = (200, 200, 0)\r\nred = (200,0,0)\r\nblack = (0, 0, 0) \r\nblue = (50,50,160)\r\n\r\n\r\n\r\ndef dfs(node):\r\n current = graph[node]\r\n current[2] = white \r\n current[3] = yellow\r\n for n2 in current[1]:\r\n if graph[n2][3] == black:\r\n graph[n2][2] = white\r\n graph[n2][3] = red\r\n edges[edge_id(node,n2)][1] = white\r\n update()\r\n dfs(n2)\r\n current[3] = blue\r\n update()\r\n\r\n\r\ndef run(node):\r\n global screen, edges, clock,graph\r\n graph = copy.deepcopy(graph)\r\n for element in graph:\r\n element.extend([grey, black])\r\n\r\n build_edges()\r\n time.sleep(3)\r\n pygame.init()\r\n clock = pygame.time.Clock()\r\n\r\n screen = pygame.display.set_mode((display_width, display_height))\r\n\r\n draw_graph()\r\n update()\r\n pygame.time.delay(2000)\r\n dfs(node)\r\n \r\n \r\n\r\n time.sleep(5)\r\n pygame.quit()\r\n\r\n\r\ndef edge_id(n1, n2): return tuple(sorted((n1, n2))) \r\n\r\ndef build_edges():\r\n global edges\r\n edges = {}\r\n for n1, (_, adjacents, _, _) in enumerate(graph):\r\n for n2 in adjacents:\r\n eid = edge_id(n1, n2)\r\n if eid not in edges:\r\n edges[eid] = [(n1, n2), grey]\r\n\r\ndef draw_graph():\r\n global graph, screen, edges\r\n\r\n screen.fill((0, 0, 0,))\r\n\r\n for e in edges.values():\r\n (n1, n2), color = e\r\n pygame.draw.line(screen, color, graph[n1][0], graph[n2][0], 2)\r\n \r\n \r\n cntr = 0\r\n for xy, _, lcolor, fcolor in graph:\r\n circle_fill(xy, lcolor, fcolor, 25, 2)\r\n display(cntr,xy)\r\n cntr+=1\r\n\r\ndef update():\r\n global clock\r\n draw_graph()\r\n pygame.display.update()\r\n clock.tick(speed)\r\n\r\ndef circle_fill(xy, line_color, fill_color, radius, thickness):\r\n global screen\r\n pygame.draw.circle(screen, line_color, xy, radius)\r\n pygame.draw.circle(screen, fill_color, xy, radius - thickness)\r\n\r\ndef display(num, position):\r\n global screen\r\n font = pygame.font.SysFont('Roboto', 30)\r\n text = font.render(str(num), True, (255, 255, 255))\r\n textRect = text.get_rect()\r\n textRect.center = position\r\n screen.blit(text,textRect)\r\n \r\n","sub_path":"algorithms/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"449221120","text":"'''\n하위 디렉터리 검색하기\n특정 디렉터리부터 시작해서 하위의 모든 파일 중 파이썬 파일만 출력해 주는 프로그램 만들기\n'''\nimport os\n\ndef search(dirname):\n filesname = os.listdir(dirname)\n pythonfile = [filename for filename in filesname if filename[-3:]=='.py']\n return pythonfile\n\nresult = search(\"C:\\\\Users\\\\eunha\\\\OneDrive\\\\바탕 화면\\\\study\\\\python\\\\5.파이썬 날개 달기\")\nprint(result)","sub_path":"python/6. 파이썬 프로그래밍, 어떻게 시작해야 할까/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"536170048","text":"import pandas as pd\r\nimport sys\r\nimport time\r\n\r\n\r\nsys.path.append(r'N:\\Python220\\lesson06\\Lesson06\\assignment\\data')\r\n\r\n\r\nimport cProfile\r\nlisttest = []\r\n\r\ndef do_cprofile(func):\r\n\r\n def profiled_func(*args, **kwargs):\r\n profile = cProfile.Profile()\r\n try:\r\n profile.enable()\r\n result = func(*args, **kwargs)\r\n profile.disable()\r\n return result\r\n finally:\r\n print('pandas_perf.py profile:')\r\n profile.print_stats()\r\n listtest.append(profile.print_stats())\r\n\r\n return profiled_func\r\n\r\n@do_cprofile\r\ndef analyze(filename):\r\n beginning_time = time.time()\r\n csv_delimiter = ','\r\n df = pd.read_csv(filename, sep=csv_delimiter)\r\n data = df.values\r\n\r\n # Analyzer data containers\r\n year_count = {\"2013\": 0,\r\n \"2014\": 0,\r\n \"2015\": 0,\r\n \"2016\": 0,\r\n \"2017\": 0,\r\n \"2018\": 0}\r\n ao_count = 0\r\n\r\n # Iterate through list\r\n for row in data:\r\n if 'ao' in row[6]:\r\n ao_count += 1\r\n continue\r\n elif str(row[4]).__contains__('2013'):\r\n year_count['2013'] += 1\r\n elif str(row[4]).__contains__('2014'):\r\n year_count['2014'] += 1\r\n elif str(row[4]).__contains__('2015'):\r\n year_count['2015'] += 1\r\n elif str(row[4]).__contains__('2016'):\r\n year_count['2016'] += 1\r\n elif str(row[4]).__contains__('2017'):\r\n year_count['2017'] += 1\r\n elif str(row[4]).__contains__('2018'):\r\n year_count['2018'] += 1\r\n\r\n\r\n elapsed_time = time.time()-beginning_time\r\n\r\n\r\n # Print results to console\r\n # print(year_count)\r\n # print(\"'ao' was found %s times.\" % ao_count)\r\n # print(\"elapsed time: %s\" % elapsed_time)\r\n\r\n return (elapsed_time, year_count, ao_count)\r\n\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n analyze(r\"N:\\Python220\\lesson06\\Lesson06\\assignment\\data\\test.csv\")","sub_path":"students/Russell_Large/template_student/lesson06/assignment/src/pandas_perf.py","file_name":"pandas_perf.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"463505593","text":"''' select and call a connector for whatever book task needs doing '''\nimport importlib\n\nfrom fedireads import models\nfrom fedireads.tasks import app\n\n\ndef get_or_create_book(key):\n ''' pull up a book record by whatever means possible '''\n try:\n book = models.Book.objects.select_subclasses().get(\n fedireads_key=key\n )\n return book\n except models.Book.DoesNotExist:\n pass\n\n connector = get_connector()\n book = connector.get_or_create_book(key)\n load_more_data.delay(book.id)\n return book\n\n\n@app.task\ndef load_more_data(book_id):\n ''' background the work of getting all 10,000 editions of LoTR '''\n book = models.Book.objects.select_subclasses().get(id=book_id)\n connector = get_connector(book)\n connector.expand_book_data(book)\n\n\ndef search(query):\n ''' try an external datasource for books '''\n connector = get_connector()\n return connector.search(query)\n\ndef update_book(book):\n ''' re-sync with the original data source '''\n connector = get_connector(book)\n connector.update_book(book)\n\n\ndef get_connector(book=None):\n ''' pick a book data connector '''\n if book and book.connector:\n connector_info = book.connector\n else:\n connector_info = models.Connector.objects.first()\n\n connector = importlib.import_module(\n 'fedireads.connectors.%s' % connector_info.connector_file\n )\n return connector.Connector(connector_info.identifier)\n","sub_path":"fedireads/books_manager.py","file_name":"books_manager.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"130440439","text":"import re\nimport requests \nfrom urllib3 import request\n#from requests import \n#import urllib.request \nfrom bs4 import BeautifulSoup\nnewspaperName=['https://www.thehindu.com/','https://indianexpress.com/','http://www.newindianexpress.com/']\nartKeywords=['news','business','sport','entertainment','sci-tech','education','society','real-estate','states','world','cities','specials','article','nation','result','magazine','thesundaystandard']\ntemp1=open(\"link.txt\",\"w\")\ntemp2=open(\"newsHeading.txt\",\"w\")\ntemp3=open(\"newsPara.txt\",\"w\")\ntemp1.write(\"\")\ntemp2.write(\"\")\ntemp3.write(\"\")\ntemp1.close()\ntemp2.close()\ntemp3.close()\nlinkList=list()\nfile1=open(\"link.txt\",\"a+\")\nfor links in newspaperName:\n\tr=requests.get(links)\n\t#r=urllib.request.urlopen(url).read()\n\thtml_content=r.text\n\tsoup=BeautifulSoup(html_content,\"html.parser\")\n\tfhand=soup.findAll('a')\n\t#fpara= soup.findAll('p')\n\t#fimg=soup.findAll('img')\n\t#import pdb;pdb.set_trace()\n\tfor tag in fhand:\n\t\ttry:\n\t\t\turl=tag[\"href\"]\n\t\t\t#file1.write(url)\n\t\t\t#file1.write(\"\\n\")\n\t\t\tfor pattern in newspaperName:\n\t\t\t\tfor keyword in artKeywords:\n\t\t\t\t\tpatternKeyword=pattern+''+keyword\n\t\t\t\t\t#print(patternKeyword)\n\t\t\t\t\tif re.search(patternKeyword+'.+.ece',url) or re.search(patternKeyword+'.+[0-9]+/',url) or re.search(patternKeyword+'.+.html',url):\n\t\t\t\t\t\t#print(url)\n\t\t\t\t\t\tlinkList.append(url)\n\t\t\t\t\t\t#linkList=set(linkList)\n\t\t\t\t\t\t#print(linkList)\n\t\t\t\t\t\t#file1.write(url)\n\t\t\t\t\t\t#file1.write(\"\\n\")\n\t\t#\tif re.search('https://www.thehindu.com/.+.ece',url):\n#\t\t\t\tprint(url)\n\t\texcept:\n\t\t\tcontinue\nlinkList=set(linkList)\nfor jems in linkList:\n\tfile1.write(jems)\n\tfile1.write(\"\\n\")\nfile1.close()\nfile2=open(\"newsHeading.txt\",\"a+\")\nnewsHeading=list()\n#for link in linkList:\n\t#print(link+\"\\n\")\n#\tif 'https://www.thehindu.com/' in link:\n#\t\tprint(link+\"\\n\")\n#\t\th=requests.get(link)\n#\t\thtml_hindu=h.text\n#\t\thSoup=BeautifulSoup(html_hindu,\"html.parser\")\n#\t\tfheading=hSoup.findAll('h1')\n\t\t#fpara=hSoup.findAll('p')\n\t\t#fshead=hSoup.findAll('h2')\n#\t\tfor headinglist in fheading:\n#\t\t\ttry:\n\t\t\t\t#print(heading)\n#\t\t\t\tnewsHeading.append(headinglist.text)\n\t\t\t\t#file2.write(headingList.text)\n\t\t\t\t#file2.write(\"\\n\")\n\t\t\t\t#for para in fpara:\n\t\t\t\t#\tfile2.write(para.text)\n\t\t\t\t#newsHeading.append(headinglist.text)\n#\t\t\texcept:\n#\t\t\t\tcontinue\n#newsHeading=list(set(newsHeading))\n#for heading in newsHeading:\n#\tfile2.write(heading)\n#\tfile2.write(\"\\n\")\n#file2.close()\ntemplist=list()\nimglist=list()\nfile3=open(\"newsPara.txt\",\"a+\")\nfor link in linkList:\n\tif 'https://www.thehindu.com/'in link:\n\t\thp=requests.get(link)\n\t\thtml_hindu=hp.text\n\t\thpSoup=BeautifulSoup(html_hindu,\"html.parser\")\n\t\tfpara=hpSoup.findAll('p')\n\t\tfhea=hpSoup.findAll('h1')\n\t\tfimg=hpSoup.findAll('img')\n\t\tfile2.write(\"start\\n\")\n\t\tfor img in fimg:\n\t\t\t#img=img[\"src\"]\n\t\t\timglist.append(img.get('src'))\n\t\t\tfile2.write(img.get('src'))\n\t\t\tfile2.write(\"\\n\")\n\t\tfile3.write(\"\\nhinNw\\n\")\n\t\t#file2.write(str(imglist))\n\t\tfor para in fpara:\n\t\t\ttry:\n\t\t\t\tfile3.write(para.text)\n\t\t\t\tif link in para.text:\n\t\t\t\t\tfile3.write(\"\\nSTART_OF_HEADING\\n\")\n\t\t\t\t\tfor hea in fhea:\n\t\t\t\t\t\tif (hea.text) not in templist:\n\t\t\t\t\t\t\ttemplist.append(hea.text)\n\t\t\t\t\t\t\tfile3.write(hea.text)\n\t\t\t\t\tfile3.write(\"\\nEND_OF_HEADING\\n\")\n\t\t\t\t#file3.write(para.text)\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\tfile3.write(\"\\n\\n\")\nfile3.close()\nfile2.close()\nfile2=open(\"newsHeading.txt\",\"a+\")\nfile3=open(\"newsPara.txt\",\"a+\")\nfor link in linkList:\n\tif 'https://indianexpress.com/' in link:\n\t\tip=requests.get(link)\n\t\thtml_indianexp=ip.text\n\t\tipSoup=BeautifulSoup(html_indianexp,\"html.parser\")\n\t\tfipara=ipSoup.findAll('p')\n\t\tfihea=ipSoup.findAll('h1')\n\t\tfiimg=ipSoup.findAll('img')\n\t\tfile2.write(\"\\nstart IE\\n\")\n\t\tfor img in fiimg:\n\t\t\tfile2.write(img.get('src'))\n\t\t\tfile2.write(\"\\n\")\n\t\tfile3.write(\"\\nindNw\\n\")\n\t\tfor para in fipara:\n\t\t\ttry:\n\t\t\t\tfile3.write(para.text)\n\t\t\t\tfile3.write(\"\\nSTART OF HEADING\\n\")\n\t\t\t\tfor hea in fihea:\n\t\t\t\t\tif (hea.text) not in templist:\n\t\t\t\t\t\ttemplist.append(hea.text)\n\t\t\t\t\t\tfile3.write(hea.text)\n\t\t\t\tfile3.write(\"\\n END OF HEADING\\n\")\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\tfile3.write(\"\\n\\n\")\nfile3.close()\nprint(\"success\")\n\t\t#import pdb;pdb.set_trace()\n#return True\n\n\n\n","sub_path":"newstrail.py","file_name":"newstrail.py","file_ext":"py","file_size_in_byte":4095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"340464975","text":"# Given a number x, determine whether the given number is Armstrong number or not.\n# A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if.\n#\n# abcd... = pow(a,n) + pow(b,n) + pow(c,n) + pow(d,n) + ....\n# Example:\n# Input : 153\n# Output : Yes\n# 153 is an Armstrong number.\n# 1*1*1 + 5*5*5 + 3*3*3 = 153\n# Input : 120\n# Output : No\n# 120 is not a Armstrong number.\n# 1*1*1 + 2*2*2 + 0*0*0 = 9\n# Input : 1253\n# Output : No\n# 1253 is not a Armstrong Number\n# 1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723\n# Input : 1634\n# Output : Yes\n# 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634\n\n\ndef armstrong_number(num):\n amount = 0\n for val in num:\n amount += pow(int(val), len(num))\n if amount == int(num):\n return \"Yes\"\n else:\n return \"No\"\n\n\nstring = input(\"Enter the number: \")\nprint(\"Is entered number Armstrong? \" + armstrong_number(string))","sub_path":"easy/armstrong_numbers.py","file_name":"armstrong_numbers.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247674047","text":"from selenium import webdriver\nimport unittest\nimport time\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport pandas as pd\n\nclass SightlyTest(unittest.TestCase):\n\n selectors = {\n \"main\": {\n \"path\": \"#__layout > div > div > div.login-area\",\n },\n \"users\": {\n \"path\": \"[class='row']\",\n },\n \"email\": {\n \"path\": \"input[type=text]\",\n \"text\": \"nick@sightly.com\",\n },\n \"password\": {\n \"path\": \"input[type=password]\",\n \"text\": \"a\",\n },\n \"login_button\": {\n \"path\": \"#__layout > div > div > div.login-area > div.login-box-right > button\",\n },\n \"reports\": {\n \"button\": \"#header-reports\",\n \"order_name\": \"#reports-list-main-content > div.table > div.table-header > div.order-name-col.th\",\n \"first_report\": \"#reports-list-main-content > div.table > div.table-body > div:nth-child(2) > div.td.checkbox-col > input\",\n \"create_report_button\": \"#reports-list-main-content > div.search-container > div:nth-child(4) > button\",\n },\n \"report_generator\": {\n \"main_page\": \"#reports-list-main-content > div.reports-overlay\",\n \"performance_detailed_report\": \"#performanceDetailReportOption > div > div:nth-child(1) > input[type=radio]\",\n \"grouping_path\": \"#inputGroupSummaryContainer > div > div:nth-child(1) > div.input-container > select\",\n \"grouping_text\": \"campaign\",\n \"cost_basis_path\": \"#inputGroupSummaryContainer > div > div:nth-child(2) > div.input-container > select\",\n \"cost_basis_text\": \"all\",\n \"granularity_path\": \"#inputGroupSummaryContainer > div > div:nth-child(3) > div.input-container > select\",\n \"granularity_text\": \"summary\",\n \"additional_columns_path\": \"#inputGroupSummaryContainer > div > div:nth-child(4) > div.input-container > select\",\n \"additional_columns_text\": \"none\",\n \"time_period_path\": \"#inputGroupSummaryContainer > div > div:nth-child(5) > div.input-container > select\",\n \"time_period_text\": \"all time\",\n \"run_report_button\": \"#modal-container > div.modal-body > div.buttons-container > button\",\n },\n \"report_results\": {\n 'start_date': '5/7/20',\n 'end_date': '6/1/20',\n 'cid': [9613603164],\n 'campaign_name': 'Chmura Orthodontics',\n 'placement_name': 'AMG - Chmura Ortho May 2020',\n 'placement_id': 'B524B795-8FD8-4F41-A916-F0C7A51D4A4A',\n 'impressions': '42,973',\n 'views': '21,338',\n 'view_rate': '49.65%',\n 'clicks': [45],\n 'ctr': '0.10%',\n 'cpv': '$0.03 ',\n 'cpm': '$14.84 ',\n 'cost': '$637.76 ',\n 'video_played_to_25%': '33,569',\n 'video_played_to_50%': '26,354',\n 'video_played_to_75%': '23,089',\n 'video_played_to_100%': '20,858',\n }\n }\n\n @classmethod\n def setUpClass(cls):\n main_path = cls.selectors['main']['path']\n\n cls.driver = webdriver.Chrome(executable_path=\"/Users/rizwan.memon/Documents/driver/chromedriver 3\")\n\n url = 'https://staging-newtargetview.sightly.com/'\n\n cls.driver.get(f\"{url}\")\n\n timeout = 5\n try:\n element_present = EC.presence_of_element_located((By.CSS_SELECTOR, f'{main_path}'))\n WebDriverWait(cls.driver, timeout).until(element_present)\n except TimeoutError:\n print('Page timed out trying to load')\n\n def test_01_verify_user_can_login_and_run_reports(self):\n email_path = self.selectors['email']['path']\n email_text = self.selectors['email']['text']\n password_path = self.selectors['password']['path']\n password_text = self.selectors['password']['text']\n login_button = self.selectors['login_button']['path']\n\n reports_path = self.selectors['reports']['button']\n order_name_path = self.selectors['reports']['order_name']\n first_report = self.selectors['reports']['first_report']\n create_report_button = self.selectors['reports']['create_report_button']\n\n report_generator_page = self.selectors['report_generator']['main_page']\n performance_detailed_report_button = self.selectors['report_generator']['performance_detailed_report']\n\n grouping_path = self.selectors['report_generator']['grouping_path']\n grouping_text = self.selectors['report_generator']['grouping_text']\n cost_basis_path = self.selectors['report_generator']['cost_basis_path']\n cost_basis_text = self.selectors['report_generator']['cost_basis_text']\n granularity_path = self.selectors['report_generator']['granularity_path']\n granularity_text = self.selectors['report_generator']['granularity_text']\n additional_columns_path = self.selectors['report_generator']['additional_columns_path']\n additional_columns_text = self.selectors['report_generator']['additional_columns_text']\n time_period_path = self.selectors['report_generator']['time_period_path']\n time_period_text = self.selectors['report_generator']['time_period_text']\n run_report_button = self.selectors['report_generator']['run_report_button']\n\n timeout = 5\n\n self.driver.find_element_by_css_selector(f'{email_path}').send_keys(f'{email_text}')\n self.driver.find_element_by_css_selector(f'{password_path}').send_keys(f'{password_text}')\n self.driver.find_element_by_css_selector(f'{login_button}').click()\n\n try:\n element_present = EC.presence_of_element_located((By.CSS_SELECTOR, f'{reports_path}'))\n WebDriverWait(self.driver, timeout).until(element_present)\n except TimeoutError:\n print('Page timed out trying to load')\n\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{reports_path}').click()\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{order_name_path}').click()\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{first_report}').click()\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{create_report_button}').click()\n time.sleep(2)\n\n try:\n element_present = EC.presence_of_element_located((By.CSS_SELECTOR, f'{report_generator_page}'))\n WebDriverWait(self.driver, timeout).until(element_present)\n except TimeoutError:\n print('Page timed out trying to load')\n\n self.driver.find_element_by_css_selector(f'{performance_detailed_report_button}').click()\n self.driver.find_element_by_css_selector(f'{grouping_path}').send_keys(f'{grouping_text}')\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{cost_basis_path}').send_keys(f'{cost_basis_text}')\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{granularity_path}').send_keys(f'{granularity_text}')\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{additional_columns_path}').send_keys(f'{additional_columns_text}')\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{time_period_path}').send_keys(f'{time_period_text}')\n time.sleep(1)\n self.driver.find_element_by_css_selector(f'{run_report_button}').click()\n\n def test_02_verify_reports_values(self):\n location = ('downloaded_reports.csv')\n\n data = pd.read_csv(location)\n data_dict = {col: list(data[col]) for col in data.columns}\n\n start_date = ''.join(data_dict['Start Date'])\n end_date = ''.join(data_dict['End Date'])\n cid = list(map(int, (data_dict['CID'])))\n campaign_name = ''.join(data_dict['Campaign Name'])\n placement_name = ''.join(data_dict['Placement Name'])\n placement_id = ''.join(data_dict['Placement ID'])\n impressions = ''.join(data_dict['Impressions'])\n views = ''.join(data_dict['Views'])\n view_rate = ''.join(data_dict['View Rate'])\n clicks = list(map(int, (data_dict['Clicks'])))\n ctr = ''.join(data_dict['CTR'])\n cpv = ''.join(data_dict['CPV'])\n cmp = ''.join(data_dict['CPM'])\n cost = ''.join(data_dict['Cost'])\n video_played_to_25 = ''.join(data_dict['Video Played To 25%'])\n video_played_to_50 = ''.join(data_dict['Video Played To 50%'])\n video_played_to_75 = ''.join(data_dict['Video Played To 75%'])\n video_played_to_100 = ''.join(data_dict['Video Played To 100%'])\n\n assert start_date == self.selectors['report_results']['start_date']\n assert end_date == self.selectors['report_results']['end_date']\n assert cid == self.selectors['report_results']['cid']\n assert campaign_name == self.selectors['report_results']['campaign_name']\n assert placement_name == self.selectors['report_results']['placement_name']\n assert placement_id == self.selectors['report_results']['placement_id']\n assert impressions == self.selectors['report_results']['impressions']\n assert views == self.selectors['report_results']['views']\n assert view_rate == self.selectors['report_results']['view_rate']\n assert clicks == self.selectors['report_results']['clicks']\n assert ctr == self.selectors['report_results']['ctr']\n assert cpv == self.selectors['report_results']['cpv']\n assert cmp == self.selectors['report_results']['cpm']\n assert cost == self.selectors['report_results']['cost']\n assert video_played_to_25 == self.selectors['report_results']['video_played_to_25%']\n assert video_played_to_50 == self.selectors['report_results']['video_played_to_50%']\n assert video_played_to_75 == self.selectors['report_results']['video_played_to_75%']\n assert video_played_to_100 == self.selectors['report_results']['video_played_to_100%']\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n\nif __name__ == 'main':\n unittest.main()","sub_path":"Sightly/sightly.py","file_name":"sightly.py","file_ext":"py","file_size_in_byte":10200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"566606009","text":"# import the necessary packages\nfrom pyimagesearch.shapedetector import ShapeDetector\nimport argparse\nimport imutils\nimport cv2\n\n# construct the argument parse and parse the arguments\n#ap = argparse.ArgumentParser()\n#ap.add_argument(\"-i\", \"--image\", required=True,\n # help=\"path to the input image\")\n#args = vars(ap.parse_args())\n\n# load the image and resize it to a smaller factor so that\n# the shapes can be approximated better\n#image = cv2.imread(args[\"image\"])\nimage = cv2.imread(\"whitecircle.png\") #read raw image\nimage = cv2.imread(\"differentshapes.jpg\") #read raw image\nimage = cv2.imread(\"6shapes.jpg\") #read raw image\nimage = cv2.bitwise_not(image) #flip the image to negative\n#image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nimage = imutils.resize(image, width=500) #resize it to 500px in width\n#ratio = image.shape[0] / float(resized.shape[0])\nratio = 1.0\n\ncap = cv2.VideoCapture(0) #grab raw video from camera\n\nwhile(True):\n # Capture frame-by-frame\n ret, frame = cap.read() #read the frame in every loop\n rawResized = imutils.resize(frame, width=500) #resize\n resized = imutils.resize(frame, width=500) #resize\n margin = 5\n resized = resized[margin:margin + (cv2.CAP_PROP_FRAME_HEIGHT - margin*2), margin:margin + (cv2.CAP_PROP_FRAME_WIDTH - margin*2)] #cut the frame by approx 5 pix\n resized = cv2.bitwise_not(resized)\n # Our operations on the frame come here\n gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)\n blurred = cv2.GaussianBlur(gray, (11, 11), 0)\n # Display the resulting frame\n\n ret, thresh = cv2.threshold(blurred, 100, 120, cv2.THRESH_BINARY)\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n print(\"Total contour(s) found: \" + str(len(cnts)))\n sd = ShapeDetector()\n qualifiedShape = 0\n for c in cnts:\n # compute the center of the contour, then detect the name of the\n # shape using only the contour\n M = cv2.moments(c)\n if (M[\"m00\"] != 0) and (cv2.contourArea(c) > 2000) and (cv2.contourArea(c) < 8000):\n cX = int((M[\"m10\"] / M[\"m00\"]) * ratio)\n cY = int((M[\"m01\"] / M[\"m00\"]) * ratio)\n shape = sd.detect(c)\n print(\"Possible shape: \" + shape)\n # multiply the contour (x, y)-coordinates by the resize ratio,\n # then draw the contours and the name of the shape on the image\n c = c.astype(\"float\")\n c *= ratio\n c = c.astype(\"int\")\n cv2.drawContours(resized, [c], -1, (0, 255, 0), 2)\n cv2.putText(resized, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, (255, 255, 255), 2)\n qualifiedShape += 1\n cv2.imshow('frame', resized)\n cv2.imshow('blurred', blurred)\n cv2.imshow('raw', rawResized)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n\n'''\n# convert the resized image to grayscale, blur it slightly,\n# and threshold it\ngray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)\nblurred = cv2.GaussianBlur(gray, (5, 5), 0)\n#thresh = cv2.threshold(blurred, 80, 150, cv2.THRESH_BINARY)[1]\nret,thresh = cv2.threshold(blurred, 30, 150, cv2.THRESH_BINARY)\n# find contours in the thresholded image and initialize the\n# shape detector\ncnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\nsd = ShapeDetector()\n\n#cv2.imshow(\"Image\", blurred)\n#cv2.waitKey(0)\n# loop over the contours\nprint(\"Total contour(s) found: \"+ str(len(cnts)))\nqualifiedShape = 0\nfor c in cnts:\n # compute the center of the contour, then detect the name of the\n # shape using only the contour\n M = cv2.moments(c)\n if (M[\"m00\"] != 0) and (cv2.contourArea(c) > 3000):\n cX = int((M[\"m10\"] / M[\"m00\"]) * ratio)\n cY = int((M[\"m01\"] / M[\"m00\"]) * ratio)\n shape = sd.detect(c)\n print(\"Possible shape: \"+ shape)\n # multiply the contour (x, y)-coordinates by the resize ratio,\n # then draw the contours and the name of the shape on the image\n c = c.astype(\"float\")\n c *= ratio\n c = c.astype(\"int\")\n cv2.drawContours(image, [c], -1, (0, 255, 0), 2)\n cv2.putText(image, shape, (cX, cY), cv2.FONT_HERSHEY_SIMPLEX,\n 0.5, (255, 255, 255), 2)\n qualifiedShape+=1\nprint(\"Total qualified contour(s) found: \" + str(qualifiedShape))\n # show the output image\ncv2.imshow(\"Image\", image)\ncv2.waitKey(0)\n'''","sub_path":"ROV-master/Shape_Detection/detect_shapes_mov.py","file_name":"detect_shapes_mov.py","file_ext":"py","file_size_in_byte":4618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"112550034","text":"from django.conf.urls import url\nfrom django.contrib import admin\nfrom web import views\nfrom django.contrib.auth import authenticate, login\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^diary/(?P\\d+)/$', views.diary),\n url(r'^diary/add/$', views.diary_add),\n url(r'^diary/word/(?P\\d+)/$', views.diary_word),\n url(r'^home/$', views.home),\n url(r'^money/(?P\\d+)$', views.money),\n url(r'^money/add/$', views.money_add),\n url(r'^money/excel/(?P\\d+)/$', views.money_excel),\n url(r'^$', views.user_login), \n url(r'^logout/$',auth_views.logout),\n]","sub_path":"secretary2/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"177211688","text":"\"\"\"\nDjango settings for shop project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.7/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.7/ref/settings/\n\"\"\"\nimport os\n\nfrom django.core.exceptions import ImproperlyConfigured\n\nimport oscar\nimport dj_database_url\nfrom unipath import Path\n\n\n# Helper functions\n\ndef env(name, default=None):\n return os.environ.get(name, default)\n\ndef require_env(name):\n value = env(name)\n if not value:\n raise ImproperlyConfigured('Missing {} env variable'.format(name))\n return value\n\ntrue_values = ['1', 'true', 'y', 'yes', 1, True]\n\n\n# Build paths inside the project like this: os.path.join(BASE_DIR, ...)\nPROJECT_ROOT = Path(__file__).ancestor(2)\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = 'eqm3_wwg!7ooppcku63sah^69+!k)(+ljb0f76a*cfmucjbuei'\n\nDEBUG = require_env('DJANGO_DEBUG').lower() in true_values\n\nTEMPLATE_DEBUG = DEBUG\nTHUMBNAIL_DEBUG = DEBUG\n\nADMINS = (\n ('Danilo Bargen', 'danilo@coredump.ch'),\n)\n\nALLOWED_HOSTS = ['shop.coredump.ch']\n\n\n# Application definition\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.flatpages',\n\n 'compressor',\n 'django_extensions',\n 'djrill',\n\n 'apps.data',\n] + oscar.get_core_apps()\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n 'oscar.apps.basket.middleware.BasketMiddleware',\n 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',\n)\n\nROOT_URLCONF = 'config.urls'\n\nWSGI_APPLICATION = 'config.wsgi.application'\n\nSITE_ID = 1\n\n\n# Database\n# https://docs.djangoproject.com/en/1.7/ref/settings/#databases\n\nDATABASES = {\n 'default': dj_database_url.config(),\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.7/topics/i18n/\n\nLANGUAGE_CODE = 'de-ch'\n\nTIME_ZONE = 'Europe/Zurich'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.7/howto/static-files/\n\nSTATIC_ROOT = PROJECT_ROOT.child('static')\nMEDIA_ROOT = PROJECT_ROOT.child('media')\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n 'compressor.finders.CompressorFinder',\n)\n\n\n# Templates\n\nTEMPLATE_DIRS = (\n STATIC_ROOT.child('templates'),\n oscar.OSCAR_MAIN_TEMPLATE_DIR,\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = (\n 'django.contrib.auth.context_processors.auth',\n 'django.core.context_processors.request',\n 'django.core.context_processors.debug',\n 'django.core.context_processors.i18n',\n 'django.core.context_processors.media',\n 'django.core.context_processors.static',\n 'django.core.context_processors.tz',\n 'django.contrib.messages.context_processors.messages',\n 'oscar.apps.search.context_processors.search_form',\n 'oscar.apps.promotions.context_processors.promotions',\n 'oscar.apps.checkout.context_processors.checkout',\n 'oscar.apps.customer.notifications.context_processors.notifications',\n 'oscar.core.context_processors.metadata',\n)\n\n\n# Authentication\n\nAUTHENTICATION_BACKENDS = (\n 'oscar.apps.customer.auth_backends.EmailBackend',\n 'django.contrib.auth.backends.ModelBackend',\n)\n\n\n# Email\n\nMANDRILL_API_KEY = env('MANDRILL_API_KEY')\nif MANDRILL_API_KEY:\n EMAIL_BACKEND = 'djrill.mail.backends.djrill.DjrillBackend'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse',\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n },\n 'mail_admins': {\n 'class': 'django.utils.log.AdminEmailHandler',\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['console', 'mail_admins'],\n 'level': 'INFO',\n },\n 'django.request': {\n 'level': 'INFO',\n 'propagate': True,\n },\n 'django.security': {\n 'level': 'INFO',\n 'propagate': True,\n },\n 'oscar': {\n 'handlers': ['console', 'mail_admins'],\n 'propagate': True,\n 'level': 'INFO',\n },\n 'sorl.thumbnail': {\n 'handlers': ['console', 'mail_admins'],\n 'propagate': True,\n 'level': 'INFO',\n },\n },\n}\n\n\n# Haystack search\n\nHAYSTACK_CONNECTIONS = {\n 'default': {\n 'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',\n },\n}\n\n\n# Opbeat\n\nif not DEBUG:\n INSTALLED_APPS += (\n 'opbeat.contrib.django',\n )\n OPBEAT = {\n 'ORGANIZATION_ID': '2e1b1154472c4dfa8dca73c2f48cbe59',\n 'APP_ID': 'ad8a14cf30',\n 'SECRET_TOKEN': require_env('OPBEAT_SECRET_TOKEN'),\n }\n MIDDLEWARE_CLASSES = (\n 'opbeat.contrib.django.middleware.OpbeatAPMMiddleware',\n ) + MIDDLEWARE_CLASSES\n\n\n# Oscar configuration\n\nfrom oscar.defaults import * # NOQA\n\nOSCAR_SHOP_NAME = 'Coredump Shop'\nOSCAR_SHOP_TAGLINE = 'Elektronik und 3D-Druck'\nOSCAR_INITIAL_ORDER_STATUS = 'Pending'\nOSCAR_INITIAL_LINE_STATUS = 'Pending'\nOSCAR_ORDER_STATUS_PIPELINE = {\n 'Pending': ('Being processed', 'Cancelled',),\n 'Being processed': ('Processed', 'Cancelled',),\n 'Cancelled': (),\n}\nOSCAR_MODERATE_REVIEWS = False\nOSCAR_FROM_EMAIL = 'shop@coredump.ch'\nOSCAR_STATIC_BASE_URL = 'https://shop.coredump.ch'\nOSCAR_DEFAULT_CURRENCY = 'CHF'\n","sub_path":"config/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":6319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"622782264","text":"#encoding:Utf-8\nfrom tkinter import *\nfrom tkinter.messagebox import *\nimport time\nfrom Etat import *\nfrom math import ceil\n\nclass Interface(Tk):\n def __init__(self, probleme, *args, **kwargs):\n Tk.__init__(self, *args, **kwargs)\n self.probleme = probleme\n self.cellwidth = 25\n self.cellheight = 25\n self.maxWidth = 900\n self.maxHeight = 300\n\n self.canvas = Canvas(self, borderwidth=0, highlightthickness=0)\n self.addScrollbars()\n\n # if addScrollbars:\n self.hbar = Scrollbar(self, orient=HORIZONTAL)\n self.hbar.pack(side=BOTTOM, fill=X)\n self.hbar.config(command=self.canvas.xview)\n self.vbar = Scrollbar(self, orient=VERTICAL)\n self.vbar.pack(side=RIGHT, fill=Y)\n self.vbar.config(command=self.canvas.yview)\n self.canvas.config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)\n\n self.labelSigma = Label(self, text='Enter gamma value : ')\n self.labelSigma.pack()\n self.entrySigma = Entry(self)\n self.entrySigma.insert(0,\"0.9\")\n self.entrySigma.pack()\n self.labelEpsilon = Label(self, text='Enter epsilon value : ')\n self.labelEpsilon.pack()\n self.entryEpsilon = Entry(self)\n self.entryEpsilon.pack()\n self.entryEpsilon.insert(0,\"0.01\")\n self.endReward = Label(self, text='Enter end\\'s reward value : ')\n self.endReward.pack()\n self.endRewardValue = Entry(self)\n self.endRewardValue.pack()\n self.endRewardValue.insert(0,\"5\")\n self.valueMarsh = Label(self, text='Enter marsh value (value must be negative) : ')\n self.valueMarsh.pack()\n self.valueMarsh = Entry(self)\n self.valueMarsh.pack()\n self.valueMarsh.insert(0,\"-1\")\n self.labelSpace = Label(self, text='', anchor=\"c\")\n self.labelSpace.pack()\n\n button = Button(self,text=\"Start\", command=self.start, bg=\"green\")\n button.pack(fill = X)\n button2 = Button(self, text=\"Modify grid\", command=self.modal_modif_grid, bg=\"orange\")\n button2.pack(fill = X)\n self.labelSpace2 = Label(self, text='', anchor=\"c\")\n self.labelSpace2.pack()\n\n self.repaint()\n \n self.canvas.bind(\"<3>\", self.afficher_popup)\n self.title('Robot application')\n self.canvas.pack(side=\"top\", fill=\"both\", expand=\"true\")\n self.mainloop()\n\n def addScrollbars(self):\n self.width = self.probleme.nbColonnes*self.cellwidth\n self.height = self.probleme.nbLignes*self.cellheight\n scrollregion = (0, 0, self.width, self.height)\n\n addScrollbars = False\n if self.width > self.maxWidth:\n self.width = self.maxWidth\n addScrollbars = True\n if self.height > self.maxHeight:\n self.height = self.maxHeight\n addScrollbars = True\n self.canvas.config(width=self.width, height=self.height, scrollregion=scrollregion)\n\n def start(self):\n gamma = self.entrySigma.get().replace(',','.')\n epsilon = self.entryEpsilon.get().replace(',','.')\n marsh = self.valueMarsh.get()\n endReward = self.endRewardValue.get()\n verifyEpsilon=self.verifyValueGE(\"epsilon\",epsilon)\n verifyGamma=self.verifyValueGE(\"gamma\",gamma)\n verifyMarsh=self.verifReward(\"marsh\",marsh,False)\n verifyEnd=self.verifReward(\"final state's edward\",endReward)\n if verifyEpsilon == \"\" and verifyGamma == \"\" and verifyMarsh == \"\" and verifyEnd == \"\":\n gamma = float(gamma)\n epsilon = float(epsilon)\n marsh = int(marsh)\n endReward = int(endReward)\t\t\n self.probleme.modify_parameter(gamma, epsilon, endReward)\n self.setValueMarshes(marsh)\n self.probleme.initialise_etat()\n temps1 = time.clock()\n actions = self.probleme.iteration_valeurs()\n print(\"---- Actions et valeurs ----\")\n for etat in self.probleme.get_etats():\n print(\"%s : %s (%s)\" % (etat.get_nom(), etat.get_action_optimale(), etat.get_qvaleurs()))\n temps2 = time.clock()\n print(\"Temps calcul des actions : %s s\" % (temps2 - temps1))\n self.probleme.construire_chemin(actions)\n temps3 = time.clock()\n print(\"Temps construction du chemin : %s s\" % (temps3 - temps2))\n print(\"Temps d'execution : %s s\" % (temps3 - temps1))\n self.afficher_chemin()\n else:\n nbError=0\n listError=\"\"\n if not verifyEpsilon == \"\":\n nbError+=1\n listError+=\" * \"+verifyEpsilon+\"\\n\"\n if not verifyGamma == \"\":\n nbError+=1\n listError+=\" * \"+verifyGamma+\"\\n\"\n if not verifyMarsh == \"\":\n nbError+=1\n listError+=\" * \"+verifyMarsh+\"\\n\"\n if not verifyEnd == \"\":\n nbError+=1\n listError+=\" * \"+verifyEnd\n message=\"%d errors detected. List error :\\n%s\" % (nbError,listError)\n showerror(\"Error\", message)\n\t\n def verifyValueGE(self,name,value):\n if value == \"\":\n return \"You must enter %s value\" % (name)\n else:\n try:\n valueVerif=eval(value)\n if valueVerif > 0 and valueVerif <= 1:\n return \"\"\n else:\n return \"%s value is not between 0 and 1\" % (name)\n except:\n return \"%s must be a numeric\" % (name)\n\n def verifReward(self,name,value,positive=True):\n try:\n valueVerif=int(value)\n if positive:\n if valueVerif > 0:\n return \"\"\n else:\n return \"%s must be positive\" % (name)\n else:\n if valueVerif < 0:\n return \"\"\n else:\n return \"%s must be negative\" % (name)\n except:\n return \"%s must be an integer\" % (name)\n \n def setValueMarshes(self,value):\n for i in range(0, self.probleme.nbLignes):\n for j in range(0, self.probleme.nbColonnes):\n if self.probleme.recompenses[i][j] < 0 and self.probleme.recompenses[i][j] != value:\n self.probleme.recompenses[i][j] = value\n\n def repaint(self, clearValues=False):\n self.canvas.delete(\"all\")\n self.addScrollbars()\n self.rect = {}\n self.oval = {}\n for column in range(self.probleme.nbColonnes):\n for row in range(self.probleme.nbLignes):\n x1 = column * self.cellwidth\n y1 = row * self.cellheight\n x2 = x1 + self.cellwidth\n y2 = y1 + self.cellheight\n self.rect[row,column] = self.canvas.create_rectangle(x1, y1, x2, y2, fill=\"blue\", tags=\"rect\")\n self.oval[row,column] = self.canvas.create_oval(x1+2, y1+2, x2-2, y2-2, fill=\"blue\", tags=\"oval\")\n if self.probleme.recompenses[row][column] < 0:\n self.canvas.create_text(x1+self.cellwidth/2, y1+self.cellheight/2, text=\"M\")\n elif self.probleme.etatInitial == Etat(row, column):\n self.canvas.create_text(x1+self.cellwidth/2, y1+self.cellheight/2, text=\"I\")\n elif self.probleme.etatFinal == Etat(row, column):\n self.canvas.create_text(x1+self.cellwidth/2, y1+self.cellheight/2, text=\"F\")\n if clearValues:\n states = self.probleme.get_etats()\n for state in states:\n state.qValeurs = 0\n state.actionOptimale = \"\"\n\n def afficher_chemin(self):\n self.repaint()\n self.canvas.itemconfig(\"rect\", fill=\"blue\")\n self.canvas.itemconfig(\"oval\", fill=\"blue\")\n\n # affichage en rouge des marécages\n marecages = []\n for i in range(0, self.probleme.nbLignes):\n for j in range(0, self.probleme.nbColonnes):\n if self.probleme.recompenses[i][j] < 0:\n self.canvas.itemconfig(self.oval[i, j], fill=\"red\")\n marecages.append(Etat(i, j))\n\n # affichage en vert (ou orange si superposé à un marécage) du chemin\n etatPrec = None\n for etat in self.probleme.chemin:\n item_id = self.oval[etat.get_ligne(), etat.get_colonne()]\n color = \"orange\" if etat in marecages else \"green\"\n self.canvas.itemconfig(item_id, fill=color)\n if etatPrec is not None:\n x1 = etatPrec.colonne*self.cellwidth + self.cellwidth/2\n y1 = etatPrec.ligne*self.cellheight + self.cellheight/2\n x2 = etat.colonne*self.cellwidth + self.cellwidth/2\n y2 = etat.ligne*self.cellheight + self.cellheight/2\n self.canvas.create_line(x2, y2, x1, y1, fill=\"red\", dash=(4,4), width=2)\n etatPrec = etat\n\n def afficher_popup(self, event):\n self.modal = Toplevel()\n self.modal.geometry('+400+400')\n \n # Get event position (considering current scroll !)\n canvas = event.widget\n x_position = canvas.canvasx(event.x)\n y_position = canvas.canvasy(event.y)\n\n # Convert coordinates to reward array indices and set them\n j = ceil(x_position / self.cellwidth) - 1\n i = ceil(y_position / self.cellheight) - 1\n \n if i >= self.probleme.nbLignes:\n i = self.probleme.nbLignes - 1\n if j >= self.probleme.nbColonnes:\n j = self.probleme.nbColonnes - 1\n\n # Si elles ont été calculées, affichage de la Q-valeur et de la direction optimale de l'état\n state = self.probleme.find_state(i, j)\n qvaleur = state.get_qvaleurs() if state and state.get_qvaleurs() else '-'\n action_optimale = state.get_action_optimale() if state and state.get_action_optimale() else '-'\n Label(self.modal, text='Q-valeur : %s' % qvaleur, font = \"Arial 9 bold\").pack()\n Label(self.modal, text='Direction optimale : %s' % action_optimale, font = \"Arial 9 bold\").pack()\n\n MODES = [\n (\"Initial state\", 1),\n (\"Final state\", 2),\n (\"Marsh\", 3),\n (\"Default\", 4),\n ]\n\n newState = IntVar()\n newState.set(0) # initialize\n\n for text, mode in MODES:\n b = Radiobutton(self.modal, text=text, variable=newState, value=mode, indicatoron=0, relief=GROOVE)\n b.pack(fill=BOTH)\n\n Button(self.modal, text=\"Ok\", command=self.closeModal).pack()\n\n self.modal.transient(self)\n self.modal.grab_set()\n self.wait_window(self.modal)\n\n if newState.get() == 1:\n self.probleme.etatInitial = Etat(i, j)\n self.probleme.recompenses[i][j] = 0\n elif newState.get() == 2:\n oldX, oldY = self.probleme.etatFinal.ligne, self.probleme.etatFinal.colonne\n self.probleme.recompenses[oldX][oldY] = 0\n self.probleme.etatFinal = Etat(i, j)\n try:\n value = int(self.endRewardValue.get())\n if value < 0:\n self.probleme.recompenses[i][j] = value \n else:\n self.probleme.recompenses[i][j] = 10\n except:\n self.probleme.recompenses[i][j] = 10\n elif newState.get() == 3:\n try:\n value=int(self.valueMarsh.get())\n if value < 0:\n self.probleme.recompenses[i][j] = value \n else:\n self.probleme.recompenses[i][j] = -3\n except:\n self.probleme.recompenses[i][j] = 10\n elif newState.get() == 4:\n self.probleme.recompenses[i][j] = 0\n\n if newState.get() != 0:\n self.repaint()\n\n def modal_modif_grid(self):\n self.modalModif = Toplevel()\n self.modalModif.geometry('+400+400')\n nbLignes=self.probleme.nbLignes\n nbColonnes=self.probleme.nbColonnes\n Label(self.modalModif, text=\"Number of rows (min : 2) :\").pack()\n self.modalModif.entryLine=Entry(self.modalModif)\n self.modalModif.entryLine.insert(0, nbLignes)\n self.modalModif.entryLine.pack()\n Label(self.modalModif, text=\"Number of columns (min : 2) :\").pack()\n self.modalModif.entryColumn = Entry(self.modalModif)\n self.modalModif.entryColumn.insert(0, nbColonnes)\n self.modalModif.entryColumn.pack()\n Button(self.modalModif, text=\"Valid\", command=self.traitementAndCloseModalModif).pack()\n self.modalModif.transient(self)\n self.modalModif.grab_set()\n self.wait_window(self.modalModif)\n\t\n def closeModal(self):\n self.modal.destroy()\n\n def traitementAndCloseModalModif(self):\n try:\n lignes=int(self.modalModif.entryLine.get())\n colonnes=int(self.modalModif.entryColumn.get())\n nbLignes=self.probleme.nbLignes\n nbColonnes=self.probleme.nbColonnes\n if lignes < 2:\n lignes=nbLignes\n if colonnes < 2:\n colonnes=nbColonnes\n if colonnes != nbColonnes or lignes != nbLignes:\n new_recompenses=[[0] * colonnes for _ in range(lignes)]\n if lignes >= nbLignes:\n if colonnes >= nbColonnes:\n for i in range(0, nbLignes):\n for j in range(0, nbColonnes):\n new_recompenses[i][j]=self.probleme.recompenses[i][j]\n else:\n for i in range(0, nbLignes):\n for j in range(0, colonnes):\n new_recompenses[i][j]=self.probleme.recompenses[i][j]\n else:\n if colonnes >= nbColonnes:\n for i in range(0, lignes):\n for j in range(0, nbColonnes):\n new_recompenses[i][j]=self.probleme.recompenses[i][j]\n else:\n for i in range(0, lignes):\n for j in range(0, colonnes):\n new_recompenses[i][j]=self.probleme.recompenses[i][j]\n oldEtatFinal=self.probleme.etatFinal.copy()\n if self.probleme.etatInitial.ligne >= lignes:\n self.probleme.etatInitial.ligne=lignes-1\n if self.probleme.etatInitial.colonne >= colonnes:\n self.probleme.etatInitial.colonne=colonnes-1\n if self.probleme.etatFinal.ligne >= lignes:\n self.probleme.etatFinal.ligne=lignes-1\n if self.probleme.etatFinal.colonne >= colonnes:\n self.probleme.etatFinal.colonne=colonnes-1\n if not oldEtatFinal == self.probleme.etatFinal:\n new_recompenses[self.probleme.etatFinal.ligne][self.probleme.etatFinal.colonne]=self.probleme.recompenses[oldEtatFinal.ligne][oldEtatFinal.colonne]\n if self.probleme.etatInitial == self.probleme.etatFinal:\n if(self.probleme.etatInitial.ligne > 0):\n self.probleme.etatInitial.ligne-=1\n else:\n self.probleme.etatInitial.ligne+=1\n if new_recompenses[self.probleme.etatInitial.ligne][self.probleme.etatInitial.colonne] < 0:\n new_recompenses[self.probleme.etatInitial.ligne][self.probleme.etatInitial.colonne] = 0\n self.probleme.reconstruct(new_recompenses)\n self.repaint(True)\n except ValueError:\n showerror(\"Error\",\"The values of columns or lines aren't integer\")\n self.modalModif.destroy()","sub_path":"PDM-valeurs/Interface.py","file_name":"Interface.py","file_ext":"py","file_size_in_byte":15869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"494682816","text":"import requests\nfrom selenium import webdriver\nfrom webdriver_manager.utils import chrome_version\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport time\nimport pandas as pd\n# これをimportしておくことで自分でcheromedriverをインストールする必要がない\nimport chromedriver_binary\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom concurrent.futures import ThreadPoolExecutor\nfrom functools import partial\n\nclass SeleniumSetUp:\n def __init__(self, home_url:str):\n self.op = Options()\n # --headlessだけではOSによって動かない、プロキシが弾かれる、\n # CUI用の省略されたHTMLが帰ってくるなどの障害が出ます。\n # 長いですが、これら6行あって最強かつどんな環境でも動きますので、必ず抜かさないようにしてください。\n self.op.add_argument(\"no-sandbox\")\n self.op.add_argument(\"--disable-extensions\")\n # self.op.add_argument(\"--headless\")\n self.op.add_argument('--disable-gpu') \n self.op.add_argument('--ignore-certificate-errors')\n self.op.add_argument('--allow-running-insecure-content')\n self.op.add_argument('--disable-web-security')\n self.op.add_argument('--disable-desktop-notifications')\n self.op.add_argument(\"--disable-extensions\")\n self.op.add_argument('--lang=ja')\n self.op.add_argument('--blink-settings=imagesEnabled=false')\n self.op.add_argument('--disable-dev-shm-usage')\n self.op.add_argument('--proxy-server=\"direct://\"')\n self.op.add_argument('--proxy-bypass-list=*') \n self.op.add_argument('--start-maximized')\n\n self.home_url = home_url\n \n\n def driver_set(self):\n driver = webdriver.Chrome(chrome_options = self.op)\n driver.get(self.home_url)\n time.sleep(1)\n return driver\n\n # 元のタブを閉じて2つ目のタブをメインタブにする\n def tab_move(self, driver, close=True):\n # tab移動\n # driver.window_handles[タブの番号]\n driver.switch_to.window(driver.window_handles[1])\n driver.switch_to.window(driver.window_handles[0])\n if close == True:\n\n # 初めに開いていたウインドウを閉じる\n driver.close()\n\n # 新しく開かれたタブを新規にインスタンスウインドウとする これをしないとNosuchElementエラーになる\n driver.switch_to.window(driver.window_handles[0])\n\n else:\n driver.switch_to.window(driver.window_handles[1])\n\n return driver\n\n # 元のタブを閉じて2つ目のタブをメインタブにする\n def tab_return(self, driver, close=True):\n # tab移動\n # driver.window_handles[タブの番号]\n driver.switch_to.window(driver.window_handles[0])\n driver.switch_to.window(driver.window_handles[1])\n if close == True:\n driver.switch_to.window(driver.window_handles[1])\n # 初めに開いていたウインドウを閉じる\n driver.close()\n\n # 新しく開かれたタブを新規にインスタンスウインドウとする これをしないとNosuchElementエラーになる\n driver.switch_to.window(driver.window_handles[0])\n\n else:\n driver.switch_to.window(driver.window_handles[0])\n\n return driver","sub_path":"settup.py","file_name":"settup.py","file_ext":"py","file_size_in_byte":3695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"94185857","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Nicolás Cubero Torres\n@description: Trains and evaluate an Incremental Spatio Temporal Learner (ISTL)\n\tmodel by using the UCSD Ped 1 or the UCSD Ped 1 train and test sets on a\n\tfederated architecture simulated on a single node.\n\n\tThis scripts replicates the experiment carried out on [1] for the\n\tUCSD Ped 1 and UCSD Ped 2 dataset adding the federated learning architecture\n\tin which the experiment is carried out:\n\n\tIn this case, active learning is not applied, so training data will\n\tnot be partitioned and training will be performed on offline.\n\n\tThe script receives experiment description from a JSON document and saves\n\tthe results of each experiment on separate JSON document located at the\n\tsame directory as the description join to the h5 models (if model saving\n\tflag is specified)\n\n\tThe document experiment must contains the following fields:\n\n\tMandatory:\n\n\t \"train_video_dir\": (str)\n\t \t\tDirectory path containing the train set\n\n\t \"test_video_dir\": (str)\n\t \t\tDirectory path containing the test set\n\n\t \"test_label\": (str)\n\t \t\tFilepath locating the test cuboids labels (as txt format).\n\n\t \"batch_size\": (int)|(list of int)\n\t \t\tValues to be used as batch size for each experiment.\n\n\t \"max_stride\": (int), default: 3\n\t \t\tMaximum stride applied for train set augmentation\n\n\t \"anom_thresh\": (float in [0,1])|(list of floats)\n\t \t\tAnomaly thresholds to be used on each experiment\n\n\t \"temp_thresh\": (float in [0,1])|(list of ints)\n\t \t\tTemporal thresholds to be used on each experiment\n\n\t Optional:\n\n\t \"epochs\": (int), default: 1\n\t \t\tMax number of epochs performed for the training on each iteration\n\n\t \"seed\": (int)\n\t \t\tValue used as seed for the generator.\n\n\t \"lr\": (float), default: 1e-4\n\t \t\tInitial learning rate used for training\n\n\t \"port_val\": (float in (0, 1]), default: 0.1\n\t \t\tRation of train samples for each client and iteration to be used for\n\t\t\tvalidation.\n\n\t \"shuffle\": (int containing 1 or 0)\n\t \t\tWhether shuffle train samples (1) or not (0).\n\n\t \"patience\": (int), default: 10.\n\t \t\tMax number of epochs with no improvement on validation loss before\n\t\t\treducing learning rate on lr_decay factor.\n\n\tNOTE: For those parameter for which a list of values are provided, an\n\tan experiment for each combination is performed\n\n\tFor example, on providing \"batch_size\": [20, 32] and \"seed\": [20, 100],\n\tfour experiment will be performed for each possible combination of batch\n\tsize single value and seed single value\n\n@usage: train_ISTL_noAct_UCSDPed1_val.py -d \n\t\t\t\t\t\t\t\t\t[-s] save the resulting model\n\"\"\"\n\n# Modules imported\nimport time\nimport sys\nimport argparse\nimport json\nimport numpy as np\nfrom tensorflow.keras.models import clone_model\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.losses import MeanSquaredError\nfrom tensorflow import config, random\nfrom cv2 import resize, cvtColor, COLOR_BGR2GRAY\nfrom utils import extract_experiments_parameters, plot_results\nfrom fedLearn import SynFedAvgLearnModel\nfrom models import istl\nfrom learningRateImprover import LearningRateImprover\nfrom utils import root_sum_squared_error\n\n# Constants\nCUBOIDS_LENGTH = 8\nCUBOIDS_WIDTH = 224\nCUBOIDS_HEIGHT = 224\n\n# Image resize function\nresize_fn = lambda img: np.expand_dims(resize(cvtColor(img, COLOR_BGR2GRAY),\n\t\t\t\t\t\t(CUBOIDS_WIDTH, CUBOIDS_HEIGHT))/255, axis=2)\n\n\n### Input Arguments\nparser = argparse.ArgumentParser(description='Trains an Incremental Spatio'\\\n\t\t\t\t\t\t\t' Temporal Learner model for the UCSD Ped 1'\\\n\t\t\t\t\t\t\t'dataset by using active learning on a federated '\\\n\t\t\t\t\t\t\t'architecture')\nparser.add_argument('-d', '--document', help='JSON file containing the train'\\\n\t\t\t\t\t' parameters', type=str)\nparser.add_argument('-s', '--save_model', help='Save the resulting model'\\\n\t\t\t\t\t' on a h5 file',\n\t\t\t\t\taction='store_true', default=False)\n\nargs = parser.parse_args()\n\nexp_filename = args.document\nstore_models = args.save_model\n\n# Read experiment document\nwith open(exp_filename) as f:\n\ttry:\n\t\texp_data = json.load(f)\n\texcept Exception as e:\n\t\tprint('Cannot load experiment JSON file'\\\n\t\t\t' :\\n',str(e), file=sys.stderr)\n\t\texit(-1)\n\nexp_data['script'] = __file__\n\n# Get output filenames\ndot_pos = exp_filename.rfind('.')\nif dot_pos != -1:\n\tresults_filename = exp_filename[:dot_pos] + '_experimento-{}.json'\n\tmodel_base_filename = exp_filename[:dot_pos]\nelse:\n\tresults_filename = exp_filename + '_experimentos-{}.json'\n\tmodel_base_filename = exp_filename[:]\n\n### Data loading and preparation ###\ntrain_video_dir = exp_data['train_video_dir']\ntest_video_dir = exp_data['test_video_dir']\ntest_label = exp_data['test_label']\n\ndata_train = istl.generators.CuboidsGeneratorFromImgs(\n\t\tsource=train_video_dir,\n\t\tcub_frames=CUBOIDS_LENGTH,\n\t\tprep_fn=resize_fn)\n\ndata_test = istl.generators.CuboidsGeneratorFromImgs(source=test_video_dir,\n\t\t\t\t\t\t\t\t\tcub_frames=CUBOIDS_LENGTH,\n\t\t\t\t\t\t\t\t\tprep_fn=resize_fn)\ndata_test = istl.generators.ConsecutiveCuboidsGen(data_test)\ntest_labels = np.loadtxt(test_label, dtype='int8')\n\n## Configure GPU usage\nphysical_devices = config.experimental.list_physical_devices('GPU')\nconfig.experimental.set_memory_growth(physical_devices[0], True)\n\n# Perform training for each parameters combination\nresults = []\nparams = extract_experiments_parameters(exp_data, ('seed', 'batch_size',\n\t\t\t\t\t\t\t\t\t\t\t\t'lr_decay', 'max_stride'))\n\nfor p in params:\n\n\tif 'seed' in p:\n\t\tnp.random.seed(p['seed'])\n\t\trandom.set_random_seed(p['seed'])\n\n\t# Prepare the data train and make partitions\n\t#data_train.shuffle(shuf=bool(p['shuffle']) if 'shuffle' in p else False,\n\t#\t\t\t\t\t\tseed=p['seed'] if 'seed' in p else time.time())\n\n\t# The generators must return the cuboids batch as label also when indexing\n\tdata_train.return_cub_as_label = True\n\tdata_train.batch_size = p['batch_size'] if 'batch_size' in p else 1\n\n\t# Split data for each client\n\ttrain_split = data_train.make_partitions((0.5, 0.5))\n\n\tdata = {0: train_split[0],\n\t\t\t1: train_split[1]}\n\tval_data = {}\n\n\t# Augment the cuboids corresponding to the first partition\n\tfor c in data:\n\t\tval_data[c], data[c] = data[c].take_subpartition(\n\t\t\t\t\t\t\t\t\tp['port_val'] if 'port_val' in p else 0.1,\n\t\t\t\t\t\t\t\t\tp['seed'] if 'seed' in p else None)\n\t\tdata[c].augment_data(max_stride=p['max_stride'] if 'max_stride' in p else 1)\n\t\tdata[c].shuffle(shuf=bool(p['shuffle']) if 'shuffle' in p else False,\n\t\t\t\t\t\t\t\tseed=p['seed'] if 'seed' in p else time.time())\n\n\tt_start = time.time()\n\n\tprint('Training with parameters: {}'.format(p))\n\n\t################# Model preparation ################\n\n\t# Stochastic gradient descent algorithm\n\tadam = Adam(lr=1e-4, decay=p['lr_decay'] if 'lr_decay' in p else 0,\n\t\t\t\tepsilon=1e-6)\n\n\n\tistl_fed_model = SynFedAvgLearnModel(build_fn=istl.build_ISTL, n_clients=2,\n\t\t\t\t\t\t\t\t\t\tcub_length=CUBOIDS_LENGTH)\n\tistl_fed_model.compile(optimizer=adam, loss=MeanSquaredError(),\n\t\t\t\t\t\t\tmetrics=[root_sum_squared_error])\n\n\n\t########## Training ##########\n\tt_1it_start = time.time()\n\tprint('Training')\n\t#print('- {} samples'.format(len(data_train)))\n\n\tpatience = p['patience'] if 'patience' in p else 0\n\tepochs = p['epochs'] if 'epochs' in p else 1\n\tcallbacks = {c:[LearningRateImprover(\n\t\t\t\t\t\t\t\tparameter='val_loss',\n\t\t\t\t\t\t\t\tmin_lr=1e-7, factor=0.9,\n\t\t\t\t\t\t\t\tpatience=patience,\n\t\t\t\t\t\t\t\tmin_delta=1e-6, verbose=1,\n\t\t\t\t\t\t\t\trestore_best_weights=True,\n\t\t\t\t\t\t\t\tacumulate_epochs=True)] for c in range(2)}\n\n\thist = istl_fed_model.fit(x=data,\n\t\t\t\t\t\tvalidation_data=val_data,\n\t\t\t\t\t\tepochs=epochs,\n\t\t\t\t\t\t#early_stop_monitor='val_loss',\n\t\t\t\t\t\t#early_stop_patience=p['early_stop_patience'] if 'early_stop_patience' in p else 5,\n\t\t\t\t\t\t#early_stop_delta=p['early_stop_delta'] if 'early_stop_delta' in p else 1e-6,\n\t\t\t\t\t\t#early_stop_rest_best_weights = True,\n\t\t\t\t\t\tcallbacks=callbacks,\n\t\t\t\t\t\tbackup_filename='backup.h5',\n\t\t\t\t\t\tbackup_epochs=10,\n\t\t\t\t\t\tbackup_save_only_weights=False,\n\t\t\t\t\t\tverbose=2,\n\t\t\t\t\t\tshuffle=False)\n\n\tt_1it_end = time.time()\n\tp['time'] = {'Training': (t_1it_end - t_1it_start)}\n\tprint('End of training - elapsed time {} s'.format(p['time']\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t['Training']))\n\n\t# Plot MSE\n\tfor c in range(2):\n\t\t# Plot MSE\n\t\tplot_results({'MSE - training': hist[c]['loss'],\n\t\t\t\t\t\t'MSE - validation': hist[c]['val_loss']},\n\t\t\t'Mean Squared Error',\n\t\t\tmodel_base_filename +\n\t\t\t'ISTL_MSE_train_loss_client={}_exp={}.pdf'.format(c, len(results)+1))\n\n\t\tnp.savetxt(model_base_filename +\n\t\t\t'ISTL_MSE_train_loss_client={}_exp={}.txt'.format(c, len(results)+1),\n\t\t\t\t\thist[c]['loss'])\n\n\t\tnp.savetxt(model_base_filename +\n\t\t\t'ISTL_MSE_train_val_loss_client={}_exp={}.txt'.format(c, len(results)+1),\n\t\t\t\t\thist[c]['val_loss'])\n\n\t\t# Plot RSSE\n\t\tplot_results({'RSSE - training': hist[c]['root_sum_squared_error'],\n\t\t\t\t\t\t'RSSE - validation': hist[c]['val_root_sum_squared_error']},\n\t\t\t'Root of the Sum of Squared Errors',\n\t\t\tmodel_base_filename +\n\t\t\t'ISTL_RSSE_train_loss_client={}_exp={}.pdf'.format(c, len(results)+1))\n\n\t\tnp.savetxt(model_base_filename +\n\t\t\t'ISTL_RSSE_train_loss_client={}_exp={}.txt'.format(c, len(results)+1),\n\t\t\t\t\thist[c]['root_sum_squared_error'])\n\n\t\tnp.savetxt(model_base_filename +\n\t\t\t'ISTL_RSSE_train_val_loss_client={}_exp={}.txt'.format(c, len(results)+1),\n\t\t\t\t\thist[c]['val_root_sum_squared_error'])\n\n\t\t# Plot lr history\n\t\tplot_results({'Lr history': callbacks[c][0].lr_history},\n\t\t\t'Learning rate history',\n\t\t\tmodel_base_filename +\n\t\t\t'ISTL_lr_history_client={}_exp={}.pdf'.format(c, len(results)+1))\n\n\t\tnp.savetxt(model_base_filename +\n\t\t\t'ISTL_lr_history_client={}_exp={}.txt'.format(c, len(results)+1),\n\t\t\t\t\tcallbacks[c][0].lr_history)\n\n\t## Save model\n\tif store_models:\n\t\tistl_fed_model.global_model.save(model_base_filename +\n\t\t\t\t\t\t\t'-experiment-'+str(len(results)) + '_model.h5')\n\n\t########### Test ##############\n\tt_eval_start = time.time()\n\tevaluator = istl.EvaluatorISTL(model=istl_fed_model.global_model,\n\t\t\t\t\t\t\t\t\t\tcub_frames=CUBOIDS_LENGTH,\n\t\t\t\t\t\t\t\t\t\t# It's required to put any value\n\t\t\t\t\t\t\t\t\t\tanom_thresh=0.1,\n\t\t\t\t\t\t\t\t\t\ttemp_thresh=1)\n\n\tdata_train.return_cub_as_label = False\n\tdata_train.batch_size = 1\n\tdata_train.shuffle(False)\n\ttrain_rec_error = evaluator.score_cuboids(data_train, False)\n\n\tp['training_rec_errors'] = {\n\t\t\t\t\t\t\t\t'mean': train_rec_error.mean(),\n\t\t\t\t\t\t\t\t'std': train_rec_error.std(),\n\t\t\t\t\t\t\t\t'min': train_rec_error.min(),\n\t\t\t\t\t\t\t\t'max': train_rec_error.max()\n\t\t\t\t\t\t\t}\n\n\tt_eval_end = time.time()\n\tp['time']['test evaluation'] = (t_eval_end - t_eval_start)\n\n\tprint('Performing evaluation with all anomaly and temporal '\\\n\t\t\t'thesholds combinations')\n\tall_meas = evaluator.evaluate_cuboids_range_params(data_test,\n\t\t\t\t\t\t\t\t\t\t\ttest_labels,\n\t\t\t\t\t\t\t\t\t\t\tnp.arange(0.01, 1, 0.01),\n\t\t\t\t\t\t\t\t\t\t\tnp.arange(1,10),\n\t\t\t\t\t\t\t\t\t\t\tdata_test.cum_cuboids_per_video)\n\tp['results']= {'test all combinations': all_meas}\n\n\tp['time']['total_elapsed time'] = (p['time']['test evaluation'] +\n\t\t\t\t\t\t\t\t\t\t\tp['time']['Training'])\n\tprint('End of experiment - Total time taken: {}s'.format(p['time']\n\t\t\t\t\t\t\t\t\t\t\t\t\t['total_elapsed time']))\n\n\tresults.append(p)\n\n\t# Save the results\n\twith open(results_filename.format(len(results)), 'w') as f:\n\t\tjson.dump(p, f, indent=4)\n","sub_path":"scripts/train_ISTL_noAct_UCSDPed_val.py","file_name":"train_ISTL_noAct_UCSDPed_val.py","file_ext":"py","file_size_in_byte":11044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"171107417","text":"#!/usr/bin/env python3\n\nfrom scipy.optimize import least_squares, OptimizeResult\nfrom yaml import safe_load\nfrom jinja2 import Template\n\nfrom padtools import TargetHeliumPad\n\n# %%\nwith open('Data/beta_helium_gauss3.yaml', 'r') as f:\n measured = safe_load(Template(f.read()).render())\n\n\nfor k, m in measured.items():\n if k != 'good3':\n continue\n print('Dataset {}...'.format(k))\n pad = TargetHeliumPad(\n w2w_beta1_amp=m['w2w_beta1_amp'],\n w2w_beta1_amp_err=m['w2w_beta1_amp_err'],\n w2w_beta1_shift=m['w2w_beta1_shift'],\n w2w_beta1_shift_err=m['w2w_beta1_shift_err'],\n w2w_beta2=m['w2w_beta2'],\n w2w_beta2_err=m['w2w_beta2_err'],\n w2w_beta3_amp=m['w2w_beta3_amp'],\n w2w_beta3_amp_err=m['w2w_beta3_amp_err'],\n w2w_beta3_shift=m['w2w_beta3_shift'],\n w2w_beta3_shift_err=m['w2w_beta3_shift_err'],\n w2w_beta4=m['w2w_beta4'],\n w2w_beta4_err=m['w2w_beta4_err'],\n wonly_beta2=m['wonly_beta2'],\n wonly_beta2_err=m['wonly_beta2_err'],\n wonly_beta4=m['wonly_beta4'],\n wonly_beta4_err=m['wonly_beta4_err'],\n amp_weight=1,\n shift_weight=16,\n even_weight=1,\n )\n\n x0 = [m['x0'][k.name.lower()] for k in pad.XKEYS if k not in pad.xfixed]\n opt: OptimizeResult = least_squares(\n pad.zdiffmat,\n [d['init'] for d in x0],\n jac=pad.zdiffjacmat,\n bounds=[[d['lower'] for d in x0], [d['upper'] for d in x0]],\n **m.get('opts', {}),\n )\n\n print('Fitting report...')\n pad.report(opt.x)\n if not opt.success:\n raise AssertionError('Fail to optimize the pad!')\n print()\n","sub_path":"Packages/fit_measured_helium_pad.py","file_name":"fit_measured_helium_pad.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"384587046","text":"from django.test import TestCase\nfrom datetime import timedelta\nfrom django.utils import timezone\nfrom .models import Firmware, Device, History\nfrom django.core.exceptions import MultipleObjectsReturned\n\nclass FirmwareTestCase(TestCase):\n def setUp(self):\n now = timezone.now()\n\n # Add some Firmware instances to db\n Firmware.objects.create(fw_version=\"0.1.0\", hw_compability=\"v3\", date_added=(now - timedelta(days=10)), file_name=\"fw_file_v0.1.0.cyacd2\", file=bytes(\"file_0.1.0_data\",'utf-8'))\n Firmware.objects.create(fw_version=\"1.0.0\", hw_compability=\"v4\", date_added=(now - timedelta(days=8)), file_name=\"fw_file_v1.0.0.cyacd2\", file=bytes(\"file_1.0.0_data\",'utf-8'))\n Firmware.objects.create(fw_version=\"2.0.0\", hw_compability=\"v5\", date_added=(now - timedelta(days=6)), file_name=\"fw_file_v2.0.0.cyacd2\", file=bytes(\"file_2.0.0_data\",'utf-8'))\n\n def test_str_is_equal_to_fw_version(self):\n fw_0_1_1 = Firmware.objects.get(fw_version=\"0.1.0\")\n fw_1_0_0 = Firmware.objects.get(fw_version=\"1.0.0\")\n fw_2_0_0 = Firmware.objects.get(fw_version=\"2.0.0\")\n\n self.assertEqual(str(fw_0_1_1), fw_0_1_1.fw_version)\n self.assertEqual(str(fw_1_0_0), fw_1_0_0.fw_version)\n self.assertEqual(str(fw_2_0_0), fw_2_0_0.fw_version)\n\n def test_get_latest_fw_object(self):\n expected_object = Firmware.objects.get(fw_version=\"0.1.0\")\n test_objectet = Firmware.get_latest_fw_object(Firmware, \"v3\")\n self.assertEqual(expected_object, test_objectet)\n\n expected_object = Firmware.objects.get(fw_version=\"1.0.0\")\n test_objectet = Firmware.get_latest_fw_object(Firmware, \"v4\")\n self.assertEqual(expected_object, test_objectet)\n\n expected_object = Firmware.objects.get(fw_version=\"2.0.0\")\n test_objectet = Firmware.get_latest_fw_object(Firmware, \"v5\")\n self.assertEqual(expected_object, test_objectet)\n\n def test_newly_added_fw_returned(self):\n new_fw = Firmware.objects.create(fw_version=\"3.0.0\", hw_compability=\"v5\", date_added=timezone.now(), file_name=\"fw_file_v3.0.0.cyacd2\", file=bytes(\"file_3.0.0_data\",'utf-8'))\n new_fw.save()\n test_objectet = Firmware.get_latest_fw_object(Firmware, \"v5\")\n self.assertEqual(new_fw, test_objectet)\n\n # No new fw for other hardware revisions\n expected_object = Firmware.objects.get(fw_version=\"0.1.0\")\n test_objectet = Firmware.get_latest_fw_object(Firmware, \"v3\")\n self.assertEqual(expected_object, test_objectet)\n\n expected_object = Firmware.objects.get(fw_version=\"1.0.0\")\n test_objectet = Firmware.get_latest_fw_object(Firmware, \"v4\")\n self.assertEqual(expected_object, test_objectet)\n\n\nclass DeviceTestCase(TestCase):\n @classmethod\n def setUpTestData(cls):\n now = timezone.now()\n\n # Add some Firmware and Device instances to db\n fw1 = Firmware.objects.create(fw_version=\"0.1.0\", hw_compability=\"v5\", date_added=(now - timedelta(days=10)), file_name=\"fw_file_v0.1.0.cyacd2\", file=bytes(\"file_0.1.0_data\",'utf-8'))\n fw2 = Firmware.objects.create(fw_version=\"1.0.0\", hw_compability=\"v5\", date_added=(now - timedelta(days=8)), file_name=\"fw_file_v1.0.0.cyacd2\", file=bytes(\"file_1.0.0_data\",'utf-8'))\n fw3 = Firmware.objects.create(fw_version=\"2.0.0\", hw_compability=\"v5\", date_added=(now - timedelta(days=6)), file_name=\"fw_file_v2.0.0.cyacd2\", file=bytes(\"file_2.0.0_data\",'utf-8'))\n\n Device.objects.create(serial_number=\"12345\", created=(now - timedelta(days=9)), firmware=fw1)\n Device.objects.create(serial_number=\"54321\", created=(now - timedelta(days=8)), firmware=fw2, last_update=(now - timedelta(days=7)))\n Device.objects.create(serial_number=\"56789\", created=(now - timedelta(days=7)), firmware=fw3, last_update=(now - timedelta(days=5)),\n manufacturer_name=\"ManufacturerName\", model_number=\"ModelNumber\", hardware_revision=\"HWRev\", software_revision=\"SWRev\")\n\n def test_str_is_equal_to_serial_number(self):\n device1 = Device.objects.get(serial_number=\"12345\")\n device2 = Device.objects.get(serial_number=\"54321\")\n device3 = Device.objects.get(serial_number=\"56789\")\n\n self.assertEqual(str(device1), device1.serial_number)\n self.assertEqual(str(device2), device2.serial_number)\n self.assertEqual(str(device3), device3.serial_number)\n \n\nclass HistoryTestCase(TestCase):\n def setUp(self):\n now = timezone.now()\n\n self.fw = Firmware.objects.create(fw_version=\"0.1.0\", hw_compability=\"v5\", date_added=(now - timedelta(days=10)), file_name=\"fw_file_v0.1.0.cyacd2\", file=bytes(\"file_0.1.0_data\",'utf-8'))\n self.dv = Device.objects.create(serial_number=\"12345\", created=(now - timedelta(days=9)), firmware=self.fw)\n History.objects.create(device=self.dv, fw_update_started=now, fw_update_success=False, firmware=self.fw, device_firmware=\"\", reason=\"Failed to update\")\n\n def test_str_is_equal_to_serial_number(self):\n history = History.objects.get(device=self.dv.id)\n\n self.assertEqual(str(history), history.device.serial_number)\n\n def test_list_of_history_objects_returned(self):\n history = History.objects.get(device=self.dv.id)\n self.assertFalse(type(history) == list)\n\n # Add one more history instance and we should get a list back\n History.objects.create(device=Device.objects.get(id=self.dv.id), fw_update_started=timezone.now(), fw_update_success=True, firmware=Firmware.objects.get(id=self.fw.id), device_firmware=\"\", reason=\"Success\")\n self.assertRaises(MultipleObjectsReturned, History.objects.get, device=self.dv.id)\n\n histories = History.objects.filter(device=self.dv.id)\n self.assertEqual(2, len(histories))\n self.assertTrue(histories[0].fw_update_success == True) # Sorted by latest timestamp first\n self.assertTrue(histories[1].fw_update_success == False)\n","sub_path":"app/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"573942156","text":"\"\"\"Given an array of numbers and an index i, return the index of the nearest larger number of the\nnumber at index i, where distance is measured in array indices.\n\nFor example, given [4, 1, 3, 5, 6] and index 0, you should return 3.\n\nIf two distances to larger numbers are the equal, then return any one of them. If the array at i\ndoesn't have a nearest larger integer, then return null.\n\nFollow-up: If you can preprocess the array, can you do this in constant time?\n\"\"\"\n\n\nclass Solution:\n def __init__(self, arr):\n self.arr = arr\n self.d = {ind: self.nearestLarger(ind) for ind in range(len(self.arr))}\n\n def getNearestLarger(self, ind):\n return self.d[ind]\n\n def nearestLarger(self, ind):\n if ind < 0 or ind > len(self.arr):\n raise KeyError\n\n if self.arr[ind] == max(self.arr):\n return None\n\n j, leftLarger = ind - 1, None\n while j > -1:\n if self.arr[j] > self.arr[ind]:\n leftLarger = j\n break\n j -= 1\n\n j, rightLarger = ind + 1, None\n while j < len(self.arr):\n if self.arr[j] > self.arr[ind]:\n rightLarger = j\n break\n j += 1\n\n return leftLarger if not rightLarger else rightLarger\n\n\ninps = [\n ([4, 1, 2, 5, 6], 0, 3),\n ([1, 1, 1, 1, 1, 1], 1, None),\n ([1, 2, 3], 2, None),\n ([5, 4, 3, 2, 1, 2, 3, 4, 5], 4, 5),\n ([1, 2, 3, 4, 5, 6, 7, 8, 9], 3, 4),\n ([1], 0, None),\n ([1, 2, 1], 1, None),\n ([1, 2, 3, 4], 0, 1),\n ([4, 3, 2, 1], 0, None),\n ([1, 2, 3, 4], 3, None),\n ([4, 3, 2, 1], 3, 2),\n ([5, 1, 2, 3, 4, 3, 2, 1], 4, 0),\n ([1, 2, 3, 4, 3, 2, 1, 5], 3, 7),\n]\n\nfor arr, ind, exp in inps:\n print(f\"Finding nearest larger for index[{ind}] in {arr} and asserting...\")\n sol = Solution(arr)\n ans = sol.getNearestLarger(ind)\n assert ans == exp\n","sub_path":"python/q_a_day/nearest_largest.py","file_name":"nearest_largest.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"584883494","text":"\n\n#calss header\nclass _LACKEY():\n\tdef __init__(self,): \n\t\tself.name = \"LACKEY\"\n\t\tself.definitions = [u\"a servant or someone who behaves like one by obeying someone else's orders or by doing unpleasant work for them: \"]\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_lackey.py","file_name":"_lackey.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"221822474","text":"from matplotlib import pyplot as plt\n\nplt.style.use('fivethirtyeight')\n\n# slices = [60, 20, 10, 10]\n# labels = ['Sixty', 'Fourty', 'Extra1', 'Extra2']\n# colors = ['blue', 'red', 'yellow', 'green']\n\nslices = [59219, 55466, 47544, 36443, 35917]\nlabels = ['JavaScript', 'HTML/CSS', 'SQL', 'Python', 'Java']\nexplode = [0, 0, 0, 0.1, 0]\n\nplt.pie(slices, labels=labels, explode=explode, shadow=True, startangle=90, autopct='%1.1f%%', wedgeprops={'edgecolor': 'black'})\n\nplt.title('My Awsome Pie Chart')\n\nplt.tight_layout()\nplt.show()\n","sub_path":"tutorials_python/matplotlib_exercises/pie_plots/matplotlib_pie_charts.py","file_name":"matplotlib_pie_charts.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"609012820","text":"class Interval:\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\ndef solve(intervals, new_interval):\n intervals.append(new_interval)\n intervals.sort(key=lambda i: [i.start, i.end], reverse=True)\n\n new_intervals = []\n while len(intervals) > 0:\n if len(new_intervals) == 0:\n new_intervals.append(intervals.pop())\n else:\n prev_interval = new_intervals.pop()\n next_interval = intervals.pop()\n\n if prev_interval.end < next_interval.start:\n new_intervals.append(prev_interval)\n new_intervals.append(next_interval)\n else:\n merged_interval = Interval()\n merged_interval.start = prev_interval.start\n merged_interval.end = max(prev_interval.end, next_interval.end)\n new_intervals.append(merged_interval)\n\n return [[i.start, i.end] for i in new_intervals]\n\n\nres = solve([\n Interval(1, 3),\n Interval(6, 9)\n], Interval(2, 5))\nprint(res)\n","sub_path":"src/arrays/merge-intervals.py","file_name":"merge-intervals.py","file_ext":"py","file_size_in_byte":1035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"521128183","text":"\n\n#calss header\nclass _PUTTY():\n\tdef __init__(self,): \n\t\tself.name = \"PUTTY\"\n\t\tself.definitions = [u'a soft substance like clay that is used especially for holding glass in window frames or for filling small holes in wood']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_putty.py","file_name":"_putty.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"417906376","text":"import torch,os,glob\nfrom torch.utils import data\nfrom PIL import Image\nfrom torch_snippets import *\n\ndirFile = os.path.dirname(__file__)\n\ntry:\n from . import vocab_mod\nexcept:\n import vocab_mod\n\n\nclass OCRDataSet(data.Dataset):\n def __init__(self,pathToData,vocab,timesteps=32):\n self.pathToData = pathToData\n assert os.path.exists(pathToData)\n self.path_images = glob.glob(os.path.join(self.pathToData,\"*\"))\n\n self.vocab = vocab #self.construct_vocabulatory()\n self.timesteps = timesteps\n\n self.target_shape = (32,128)\n\n\n def __getitem__(self, i):\n path = self.path_images[i]\n basename = os.path.basename(path)\n sentence = basename.split(\"@\")[0]\n image = Image.open(os.path.join(path))\n return image,sentence\n\n\n def sample(self):\n return self[randint(len(self))]\n\n\n def __len__(self):\n return len(self.path_images)\n\n #TODO: add test to see if list of label characters is below a certain value\n def collate_fn(self,batch):\n imgs = []\n labels = []\n label_lengths = []\n labels_vectors = []\n input_lengths = []\n for img,sentence in batch:\n imgs.append(self.preprocess(np.asarray(img)))\n label_lengths.append(len(sentence))\n sentences_as_id = self.vocab.str2vec(sentence)\n labels_vectors.append(sentences_as_id)\n labels.append(sentence)\n input_lengths.append(self.timesteps)\n\n imgs = torch.Tensor(imgs).float().to(device)\n labels_vectors = torch.Tensor(labels_vectors).long().to(device)\n label_lengths = torch.Tensor(label_lengths).long().to(device)\n input_lengths = torch.Tensor(input_lengths).long().to(device)\n return imgs,labels_vectors,label_lengths,input_lengths,labels\n\n #TODO: test if all the images of the dataset, are un black and white\n def preprocess(self,image ):\n \"\"\"\n the image is given in black and white, with various shape,\n this method changes the size of th image to the size of self.target_shape preseving the aspect ratio, and padding with color of\n background , and apply reversing of the intensities\n (linear conversion that transform white to black, and black to white)\n :inputs\n image : numpy array\n \"\"\"\n\n target = np.ones(self.target_shape) * 255\n try:\n h,w = image.shape\n H,W = self.target_shape\n f = min(W/w,H/h)\n new_shape = int(f*h),int(f*w)\n import cv2\n target[:new_shape[0],:new_shape[1]] = cv2.resize(image,dsize=(new_shape[1],new_shape[0]))\n except:\n sys.exit(\"preprocessing image didn't work\")\n\n return (255-target)/255\n\n\ndef construct_datasets():\n vocab = vocab_mod.Vocab(timesteps=32)\n # sys.exit()\n\n pathToDataTraining = os.path.join(dirFile,\"..\\Data\\synthetic-data-training\")\n assert os.path.exists(pathToDataTraining)\n\n pathToDataValidation = os.path.join(dirFile,\"..\\Data\\synthetic-data-training\")\n assert os.path.exists(pathToDataValidation)\n\n\n trn_dataset = OCRDataSet(pathToDataTraining,vocab)\n val_dataset = OCRDataSet(pathToDataTraining,vocab)\n\n return trn_dataset,val_dataset\n\ndef construct_data_loader_from_dataset(dataset):\n \"\"\"\n short function that specifies the parameters used for the dataLoader for a particular (pytorch) dataset\n :inputs:\n dataset is a (pytorch) dataset, that can either be the training dataset or the validation dataset\n \"\"\"\n dataloader = torch.utils.data.DataLoader(dataset,batch_size=64,shuffle=True,collate_fn=dataset.collate_fn,drop_last = True)\n return dataloader\n # val_dataloader = torch.utils.data.DataLoader(val_dataset,batch_size=64,shuffle=True,collate_fn=val_dataset.collate_fn)\nif __name__ == '__main__':\n\n import sys\n\n trn_dataset, val_dataset = construct_datasets()\n\n trn_dataloader = construct_data_loader_from_dataset(trn_dataset)\n val_dataloader = construct_data_loader_from_dataset(val_dataset)\n\n\n","sub_path":"Code/ocr_dataset.py","file_name":"ocr_dataset.py","file_ext":"py","file_size_in_byte":4115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"610174878","text":"import os\nimport time\nimport sys\nimport paddle.fluid as fluid\nimport math\n\n\nclass StNet_ResNet():\n def __init__(self, layers=50, seg_num=7, seglen=5, is_training = True):\n self.layers = layers\n self.seglen = seglen\n self.seg_num = seg_num\n self.is_training = is_training\n\n def temporal_conv_bn(self,\n input, #(B*seg_num, c, h, w)\n num_filters,\n filter_size=(3,1,1),\n padding=(1,0,0)):\n #(B, seg_num, c, h, w)\n in_reshape = fluid.layers.reshape(x=input, shape=[-1, self.seg_num, input.shape[-3], input.shape[-2],input.shape[-1]])\n in_transpose = fluid.layers.transpose(in_reshape, perm=[0,2,1,3,4])\n\n conv = fluid.layers.conv3d(\n input=in_transpose,\n num_filters=num_filters,\n filter_size=filter_size,\n stride=1,\n groups=1,\n padding=padding,\n act='relu',\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.MSRAInitializer()),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0.0)))\n\n out = fluid.layers.batch_norm(input=conv,act=None, is_test = (not self.is_training),\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=1.0)),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0.0)))\n out = out + in_transpose\n out = fluid.layers.transpose(out, perm=[0,2,1,3,4])\n out = fluid.layers.reshape(x=out, shape=input.shape)\n return out\n\n def xception(self, input): #(B, C, seg_num,1)\n bn = fluid.layers.batch_norm(input=input, act=None, name=\"xception_bn\", is_test = (not self.is_training),\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=1.0)),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0.0)))\n att_conv = fluid.layers.conv2d(input=bn, num_filters=2048, filter_size=[3,1], stride=[1,1],\n padding=[1,0], groups=2048, name=\"xception_att_conv\",\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.MSRAInitializer()),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0)))\n att_2 = fluid.layers.conv2d(input=att_conv,num_filters=1024,filter_size=[1,1], stride=[1,1],name=\"xception_att_2\",\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.MSRAInitializer()),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0)))\n bndw = fluid.layers.batch_norm(input=att_2, act=\"relu\", name=\"xception_bndw\", is_test = (not self.is_training),\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=1.0)),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0.0)))\n att1 = fluid.layers.conv2d(input=bndw, num_filters=1024, filter_size=[3,1], stride=[1,1],\n padding=[1,0], groups=1024, name=\"xception_att1\",\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.MSRAInitializer()),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0)))\n att1_2 = fluid.layers.conv2d(input=att1, num_filters=1024, filter_size=[1,1], stride=[1,1],name=\"xception_att1_2\",\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.MSRAInitializer()),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0)))\n dw = fluid.layers.conv2d(input=bn, num_filters=1024, filter_size=[1,1], stride=[1,1],name=\"xception_dw\",\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.MSRAInitializer()),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0)))\n add_to = dw + att1_2\n bn2 = fluid.layers.batch_norm(input=add_to, act=None, name='xception_bn2', is_test = (not self.is_training),\n param_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=1.0)),\n bias_attr=fluid.param_attr.ParamAttr(initializer=fluid.initializer.ConstantInitializer(value=0.0))\n )\n return fluid.layers.relu(bn2)\n\n\n def conv_bn_layer(self,\n input,\n num_filters,\n filter_size,\n stride=1,\n groups=1,\n act=None,\n name=None):\n conv = fluid.layers.conv2d(\n input=input,\n num_filters=num_filters,\n filter_size=filter_size,\n stride=stride,\n padding=(filter_size - 1) // 2,\n groups=groups,\n act=None,\n param_attr=fluid.param_attr.ParamAttr(name=name+\"_weights\"),\n bias_attr=False,\n #name = name+\".conv2d.output.1\"\n )\n if name == \"conv1\":\n bn_name = \"bn_\" + name\n else:\n bn_name = \"bn\" + name[3:]\n return fluid.layers.batch_norm(input=conv, act=act, is_test = (not self.is_training),\n #name=bn_name+'.output.1',\n param_attr=fluid.param_attr.ParamAttr(name=bn_name+\"_scale\"),\n bias_attr=fluid.param_attr.ParamAttr(bn_name+'_offset'),\n moving_mean_name=bn_name+\"_mean\",\n moving_variance_name=bn_name+'_variance')\n\n def shortcut(self, input, ch_out, stride, name):\n ch_in = input.shape[1]\n if ch_in != ch_out or stride != 1:\n return self.conv_bn_layer(input, ch_out, 1, stride,name=name)\n else:\n return input\n\n def bottleneck_block(self, input, num_filters, stride, name):\n conv0 = self.conv_bn_layer(\n input=input, num_filters=num_filters, filter_size=1, act='relu',\n name=name+\"_branch2a\")\n conv1 = self.conv_bn_layer(\n input=conv0,\n num_filters=num_filters,\n filter_size=3,\n stride=stride,\n act='relu', name=name+\"_branch2b\")\n conv2 = self.conv_bn_layer(\n input=conv1, num_filters=num_filters * 4, filter_size=1, act=None,\n name=name+\"_branch2c\")\n\n short = self.shortcut(input, num_filters * 4, stride, name=name+\"_branch1\")\n\n return fluid.layers.elementwise_add(x=short, y=conv2, act='relu', \n #name=\".add.output.5\"\n )\n\n def net(self, input, class_dim=101):\n layers = self.layers\n seg_num = self.seg_num\n seglen = self.seglen\n\n supported_layers = [50, 101, 152]\n if layers not in supported_layers:\n print(\"supported layers are\", supported_layers, \\\n \"but input layer is \", layers)\n exit()\n\n # reshape input\n # [B, seg_num, seglen*c, H, W] --> [B*seg_num, seglen*c, H, W]\n channels = input.shape[2]\n short_size = input.shape[3]\n input = fluid.layers.reshape(\n x=input, shape=[-1, channels, short_size, short_size])\n\n if layers == 50:\n depth = [3, 4, 6, 3]\n elif layers == 101:\n depth = [3, 4, 23, 3]\n elif layers == 152:\n depth = [3, 8, 36, 3]\n num_filters = [64, 128, 256, 512]\n\n conv = self.conv_bn_layer(\n input=input, num_filters=64, filter_size=7, stride=2, act='relu', name='conv1')\n conv = fluid.layers.pool2d(\n input=conv,\n pool_size=3,\n pool_stride=2,\n pool_padding=1,\n pool_type='max')\n\n for block in range(len(depth)):\n for i in range(depth[block]):\n if layers in [101,152] and block == 2:\n if i==0:\n conv_name = \"res\" + str(block+2) + \"a\"\n else:\n conv_name = \"res\" + str(block+2) + \"b\" + str(i)\n else:\n conv_name = \"res\" + str(block+2) + chr(97+i)\n\n conv = self.bottleneck_block(\n input=conv,\n num_filters=num_filters[block],\n stride=2 if i == 0 and block != 0 else 1,\n name=conv_name)\n if block == 1:\n #insert the first temporal modeling block\n conv = self.temporal_conv_bn(input=conv,num_filters=512)\n if block == 2:\n #insert the second temporal modeling block\n conv = self.temporal_conv_bn(input=conv,num_filters=1024)\n \n\n pool = fluid.layers.pool2d(\n input=conv, pool_size=7, pool_type='avg', global_pooling=True)\n\n feature = fluid.layers.reshape(\n x=pool, shape=[-1, seg_num, pool.shape[1], 1])\n feature = fluid.layers.transpose(feature, perm=[0,2,1,3])\n\n #append the temporal Xception block\n xfeat = self.xception(feature) #(B, 1024, seg_num, 1)\n out = fluid.layers.pool2d(input=xfeat, \n pool_size=(seg_num,1), pool_type='max', global_pooling=True)\n out = fluid.layers.reshape(x=out, shape=[-1,1024])\n\n stdv = 1.0 / math.sqrt(pool.shape[1] * 1.0)\n out = fluid.layers.fc(input=out,\n size=class_dim,\n act='softmax',\n param_attr=fluid.param_attr.ParamAttr(\n initializer=fluid.initializer.Uniform(-stdv,\n stdv)))\n return out\n\n","sub_path":"models/stnet/stnet_res_model.py","file_name":"stnet_res_model.py","file_ext":"py","file_size_in_byte":10178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"507208214","text":"from flask import Flask, render_template, request, redirect\napp = Flask(__name__) \n\n@app.route('/') \ndef index():\n return render_template(\"index.html\")\n\n@app.route('/checkout', methods=['POST']) \ndef checkout():\n rasp = request.form[\"rasp\"]\n straw = request.form[\"straw\"]\n apple = request.form[\"apple\"]\n total = int(rasp) + int(straw) + int(apple)\n first = request.form[\"first_name\"]\n last = request.form[\"last_name\"]\n student = request.form[\"student_id\"]\n return render_template(\"checkout.html\", first_name=first, last_name=last, student_id=student, apple=apple, rasp=rasp, straw=straw, total=total)\n\n@app.route('/fruits') \ndef fruits():\n return render_template(\"fruits.html\")\n\nif __name__==\"__main__\": \n app.run(debug=True) ","sub_path":"Coding dojo python/dojo_fruit_store-master/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"191106007","text":"# Construct a \"wiki notebook\" just like Will's but populated from the wiki\r\n# https://moonlighter.gamepedia.com/Special:Export\r\n# Add pages from category \"Items\"\r\n# Current revision only, save as file\r\n# python3 moonlighter.py Moonlighter+Wiki-timestamp.xml >moonlighter.txt\r\n\r\n# List items grouped by culture, ordered by base value\r\n# For each item, show the best possible sell price for neutral popularity\r\n# == Base Value * 1.1, and subtract 1 if name ends \"+1\"\r\n\r\nimport re\r\nimport sys\r\nfrom collections import defaultdict\r\nimport xml.etree.ElementTree as ET\r\nwith open(sys.argv[1]) as f: data = f.read()\r\n# Hack: Clear out the default namespace to make parsing easier\r\ndata = \"\\n\" + data.split(\"\\n\", 1)[1]\r\ntree = ET.fromstring(data)\r\ncultures = defaultdict(list)\r\nfor node in tree:\r\n\tif node.tag != \"page\": continue\r\n\tpage = node.find(\"title\").text\r\n\tinfo = node.find(\"revision/text\").text\r\n\tif not info: print(page)\r\n\tif \"{{Item Page\" not in info: continue\r\n\tstats = {}\r\n\tfor line in info.split(\"{{Item Page\", 1)[1].split(\"\\n\"):\r\n\t\tif not line: continue\r\n\t\tif line == \"}}\": break\r\n\t\tif \"=\" in line:\r\n\t\t\tkey, val = line.split(\"=\", 1)\r\n\t\t\tstats[key.replace(\"|\", \"\").strip()] = val.strip()\r\n\tif \"value\" not in stats: continue\r\n\tculture = stats.get(\"culture\", \"\")\r\n\tculture = re.sub(r\"\", \"\", culture).strip() # Remove comments and whites\r\n\tif culture not in (\"Merchant\", \"Golem\", \"Forest\", \"Desert\", \"Tech\"): continue\r\n\tif page.endswith(\" +1\"): culture += \" +1\"\r\n\tstats[\"page\"] = page\r\n\tcultures[culture].append(stats)\r\n\r\nfor culture, items in cultures.items():\r\n\titems.sort(key=lambda item: (-int(item[\"value\"]), item[\"page\"]))\r\n\tprint(culture)\r\n\tfor item in items:\r\n\t\tbase = int(item[\"value\"])\r\n\t\tsale = base * 11 // 10 # I'm flooring, but it's possible that ceil is actually correct (??)\r\n\t\tif culture.endswith(\" +1\"): sale -= 1\r\n\t\tprint(\"\\t%6d %s\" % (sale, item[\"page\"]))\r\n","sub_path":"moonlighter.py","file_name":"moonlighter.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"577471472","text":"#copy all odd no. b/w 0-20(except 11, 3) in a list called, oddlist and print the odd list.\n\noddlist = []\n\nfor x in range (1, 21, 2):\n if x != 11 and x != 3:\n oddlist.append(x)\nprint(oddlist)\n\n\n","sub_path":"exam/q5.py","file_name":"q5.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"123418329","text":"\"\"\"\nGiven a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.\n\nYou should preserve the original relative order of the nodes in each of the two partitions.\n\nFor example,\nGiven 1->4->3->2->5->2 and x = 3,\nreturn 1->2->2->4->3->5.\n\"\"\"\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def partition(self, head, x):\n \"\"\"\n :type head: ListNode\n :type x: int\n :rtype: ListNode\n \"\"\"\n \n return self.one_dummy(head, x)\n \n \"\"\"\n #two head and then merge\n return self.two_head(head,x)\n \"\"\"\n \n def one_dummy(self, head, x):\n dummy = ListNode(0)\n dummy.next = head\n cur_insert = dummy\n while cur_insert.next and cur_insert.next.val < x:\n cur_insert = cur_insert.next\n \n p = cur_insert.next\n if p: \n while p.next:\n if p.next.val >= x:\n p = p.next\n else:\n node = p.next\n p.next = node.next\n node.next = cur_insert.next\n cur_insert.next = node\n cur_insert = cur_insert.next\n \n return dummy.next\n \n def two_head(self, head, x):\n if head == None or head.next == None: return head\n \n small = ListNode(0)\n large = ListNode(0)\n \n p = head\n sp, lp = small, large\n while p:\n if p.val < x:\n sp.next = p\n sp = sp.next\n else:\n lp.next = p \n lp = lp.next\n p = p.next\n \n sp.next = large.next\n lp.next = None\n return small.next\n \n","sub_path":"086_Partition_List.py","file_name":"086_Partition_List.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"475217171","text":"from django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponse\nfrom port.models import *\n\n# Create your views here.\ndef docks_overview(request):\n\tcontext = {\"docks_list\": Dock.objects.order_by(\"id\")}\n\treturn render(request, \"port/dock_overview.html\", context)\n\t\n\t\ndef dock_details(request, dock_id):\n\tcontext = {\"dock\": get_object_or_404(Dock, id=dock_id), \n\t \"dock_id\": dock_id}\n\treturn render(request, \"port/dock_details.html\", context)\n\n\t\ndef dock_employees(request, dock_id):\n\tdock = get_object_or_404(Dock, id=dock_id)\n\tcontext = {}\n\tcontext[\"dock_id\"] = dock_id\n\tcontext[\"employees\"] = dock.employee_set.all()\n\treturn render(request, \"port/dock_employees.html\", context)\n\t\n\t\ndef dock_history(request, dock_id):\n\tdock = get_object_or_404(Dock, id=dock_id)\n\tcontext = {}\n\tcontext[\"dock_id\"] = dock_id\n\tcontext[\"history\"] = (DockHistory.objects.all()\n\t .filter(dock=dock)\n\t\t\t\t\t\t .order_by(\"-date_dock\"))\n\treturn render(request, \"port/dock_history.html\", context)\n\ndef employees(request):\n\tcontext = {\"employees\": (Employee.objects.all()\n\t .order_by(\"employee_number\"))}\n\treturn render(request, \"port/employees.html\", context)\n\t\ndef employee_detail(request, e_id):\n\tcontext = {}\n\tcontext[\"employee\"] = get_object_or_404(Employee, employee_number=e_id)\n\ttry:\n\t\tcontext[\"address\"] = Address.objects.get(employee=e_id)\n\texcept Address.DoesNotExist:\n\t\tpass\n\ttry:\n\t\tcontext[\"bank\"] = BankAccount.objects.get(employee=e_id)\n\texcept BankAccount.DoesNotExist:\n\t\tpass\n\treturn render(request, \"port/employee_detail.html\", context)\n","sub_path":"port/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"355354814","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd \nimport os \n\npwd = os.getcwd()\ncurrent_filename = os.path.basename(__file__)\n\ndef map_file(folder):\n \"\"\"\n 遍历文件,遍历时使用\n \"\"\"\n # 1 获取文件夹里面的文件名(包含完整路径)\n folder = folder\n filenames = []\n # 遍历文件夹里面的文件,并将其放在filename列表上\n for root, _, files in os.walk(folder):\n for file in files:\n file = os.path.join(root, file)\n filenames.append(file)\n\n return filenames\n\ndef main(folder):\n \"\"\"\n 筛选满足条件的文件\n \"\"\"\n folder = folder\n # folder = r'C:\\Users\\LS\\Desktop\\积压库存处理py版\\原始数据\\原始数据_20191125'\n filenames = map_file(folder)\n # print(filenames)\n for filename in filenames:\n if filename != os.path.join(pwd, current_filename):\n\n df = pd.read_table(filename,encoding= 'latin1')\n sdate = df['snapshot-date'].unique()[0]\n print(df['snapshot-date'].unique()[0])\n print('修改前:' + filename)\n\n if sdate == '2019-12-31':\n outfile = filename.replace('.txt','就是你.txt')\n os.rename(filename, outfile)\n print('修改后:' + outfile)\n # 修改规则\n # outfile = filename.replace('jiansi.ca库龄报表 (1)', 'Jiansi_amazon-ca_20191118').replace(\n # 'jiansi.eu库龄报表 (1).txt', 'Jiansi_amazon-eu_20191118').replace('jiansi.us库龄报表 (1)', 'Jiansi_amazon-us_20191118')\n # outfile = filename.replace('库龄数据2','7月').replace('库龄报表-立生','').replace('库龄报表','')\n # outfile = filename.replace('20191230_4','20191230')\n # print('修改后:' + outfile)\n # os.rename(filename, outfile)\n\n\n\nif __name__ == \"__main__\":\n folder = '原始数据/20200113'\n main(folder)","sub_path":"py代码/jiya_other_Filter_file.py","file_name":"jiya_other_Filter_file.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"232910668","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sunday 03 November 2019\n\n@author: Manoj Kolpe Lingappa\n\"\"\"\n\nimport sys\nimport os\nimport time\nimport random\nimport numpy as np\n\n\ndef maze_map_to_tree(maze_map):\n \"\"\"Function to create a tree from the map file. The idea is\n to check for the possible movements from each position on the\n map and encode it in a data structure like list.\n\n Parameters\n ----------\n maze_map : list\n The list conatain the maze in a list format with each element of list represent the first row of maze grid in string format.\n\n Returns\n -------\n list\n Extracts start psotion, all the goal position and convert the input maze grid into nested list. Eg. ['abc','de'] = [['a','b','c'],['d','e']] \n \"\"\"\n # Initiate the list for make a nested list of all characters of the grid.\n nested_list = []\n # Loop through all the elements of the list\n for i in maze_map:\n # Convert each element which is a string to a list and append to nested_list \n nested_list.append(list(i))\n # Intiatite list to store all the target position\n target = []\n # Iterate through nested list to find source position.\n for k in nested_list:\n if 's' in k:\n # Once start found put the location of start into tuple.\n index_of_s = (nested_list.index(k),k.index('s'))\n # Initiating indexs to keep track of the position in 2d grid.\n index1 = -1\n index2 = -1\n for i in nested_list:\n index1+=1\n for k in i:\n index2+=1\n # Once the goal found extract the location of the goal and put it into a tuple.\n if k == '*':\n tup = (index1,index2)\n target.append(tup)\n index2 = -1\n return nested_list, index_of_s, target\n \n \n\ndef assign_character_for_nodes(maze_map, current_node):\n \"\"\"Function to assign character for the visited nodes. Please assign\n meaningful characters based on the direction of tree traversal.\n\n Parameters\n ----------\n maze_map : list\n The list conatain the maze in a list format with each element of list represent the first row of maze grid in string format.\n current_node : tuple\n Gives the current node positon in (x,y) format\n\n Returns\n -------\n maze_map : list\n The list conatain the maze in a list format with each element of list represent the first row of maze grid in string format with current node updated to visited \n \"\"\"\n # Make the current node as visited by assigning True value to it's position\n maze_map[current_node[0]][current_node[1]] = 'True'\n\n return maze_map\n\n\ndef write_to_file(path,maze):\n \"\"\"Function to write output to console and the optimal path\n from start to each goal to txt file.\n Please ensure that it should ALSO be possible to visualize each and every\n step of the tree traversal algorithm in the map in the console.\n This enables understanding towards the working of your\n tree traversal algorithm as to how it reaches the goals.\n\n Parameters\n ----------\n path : list of tuples\n It has all the path from starting to the goal.\n maze : list\n The list conatain the maze in a list format with each element of list represent the first row of maze grid in string format.\n \"\"\"\n # extract the nested_list by calling maze_map_to_tree function\n nested_list, _,_ = maze_map_to_tree(maze)\n # Iterate through nested_list\n for m in nested_list:\n # Remove '\\n' from nested list to print nicely in terminal\n try:\n m.remove('\\n')\n except ValueError:\n pass\n \n new1 = nested_list\n new = []\n #Iterate through the path\n for track in path:\n # Initiating indexs to keep track of position in the 2d grid\n index1 = -1\n index2 = 0\n # Intiate new_sub to transfer the read maze\n new_sub = []\n # Iterate through the nested_list\n for k in new1:\n index1+=1\n # Iterate through list\n for i in k:\n # Check if the position in the grid is equal to the track position. If True then append the path with '+' else pass read grid from nested_list\n if index1 == track[0] and index2 == track[1]:\n new_sub.append('+')\n else:\n new_sub.append(i)\n index2+=1\n # Making it to zero for next row to start from beginning\n index2 = 0\n # Append the new_sub to the new for printing finally.\n new.append(new_sub)\n # Empty it to zero for next row of grid storing.\n new_sub = []\n \n # Merge the nested list for nice printing\n for i in new:\n new[new.index(i)] = ''.join(i)\n # Uncomment this section to view the output in the terminal\n # for k in new:\n # print(k)\n # We once again convert the joined list into nested list for next operation or plotting next track.\n new2 = []\n for i in new:\n new2.append(list(i))\n # My new maze grid will be new2\n new1 = new2\n # Emptying new for next operation.\n new = []\n # Uncomment this section to slow down the output in terminal\n # time.sleep(0.05)\n # Merging the new2 to print it in a text file\n for i in new2:\n new2[new2.index(i)] = ''.join(i)\n return new2\n\n# To make intial matrix of maze with all obstacles as visited or 'True'\ndef visiting_matrix(maze):\n # Creating a nested list with same dimension as maze and all initial value as False.\n visited = [['False']*len(maze[0])]*len(maze)\n # Converting the list to numpy array for easy manipulation.\n visited = np.asarray(visited)\n # Initilising the indexes for keeping track of the position\n index1 = -1\n index2 = -1\n # Iterating through maze\n for i in maze:\n index1+=1\n for k in i:\n index2+=1\n # Once the obstacle found make it as True or as visited.\n if k == '=' or k == '|' or k == '\\n':\n visited[index1][index2] = 'True'\n index2 = -1\n return visited\n","sub_path":"assignment_3/assignment-03-Manojkl/src/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":6217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"189773114","text":"# Lynx.py\n# by Caleb Strait\n\necho = False;\ndef create_user(username, password):\n import datetime\n from sqlalchemy import create_engine\n from sqlalchemy.orm import sessionmaker\n from tabledef import User\n from flask import session\n\n engine = create_engine('sqlite:///lynx.db', echo=echo)\n Session = sessionmaker(bind=engine)\n s = Session()\n\n user = User(username,password)\n query = s.query(User).filter(User.username.in_([username]), User.password.in_([password]))\n result = query.first()\n if result:\n print('that username is taken')\n else:\n s.add(user)\n s.commit()\n session['logged_in'] = True\n session['username'] = username\n\ndef upload_link(url, username):\n from sqlalchemy import create_engine\n from sqlalchemy.orm import sessionmaker\n from tabledef import Link\n from flask import session\n\n engine = create_engine('sqlite:///lynx.db', echo=echo)\n Session = sessionmaker(bind=engine)\n s = Session()\n\n link = Link(url,username)\n s.add(link)\n s.commit()\n\ndef remove_link(url,username,title):\n from sqlalchemy import create_engine\n from sqlalchemy.orm import sessionmaker\n from tabledef import Link\n from flask import session\n\n engine = create_engine('sqlite:///lynx.db', echo=echo)\n Session = sessionmaker(bind=engine)\n s = Session()\n query = s.query(Link).filter(Link.username.in_([username]), Link.link.in_([url]),Link.username.in_([username]))\n result = query.first()\n s.delete(result)\n s.commit()\n\ndef fetch_my_links(username):\n from sqlalchemy import create_engine\n from sqlalchemy.orm import sessionmaker\n from tabledef import Link\n from flask import session\n\n engine = create_engine('sqlite:///lynx.db', echo=echo)\n Session = sessionmaker(bind=engine)\n s = Session()\n\n query = s.query(Link).filter(Link.username.in_([username]))\n result = query.all()\n ret = list()\n for l in result:\n ret.append(l.link)\n return ret\n\ndef fetch_friends(username):\n from sqlalchemy import create_engine, or_\n from sqlalchemy.orm import sessionmaker\n from tabledef import Friendship\n from flask import session\n\n engine = create_engine('sqlite:///lynx.db', echo=echo)\n Session = sessionmaker(bind=engine)\n s = Session()\n\n query = s.query(Friendship).filter(or_(Friendship.usernameA.in_([username]), Friendship.usernameB.in_([username])))\n result = query.all()\n ret = list()\n for f in result:\n if f.usernameA == username:\n ret.append(f.usernameB)\n else:\n ret.append(f.usernameA)\n return ret\n\ndef add_friendship(usernameA,usernameB):\n from sqlalchemy import create_engine, or_\n from sqlalchemy.orm import sessionmaker\n from tabledef import Friendship\n from flask import session\n\n engine = create_engine('sqlite:///lynx.db', echo=echo)\n Session = sessionmaker(bind=engine)\n s = Session()\n\n friendship = Friendship(usernameA,usernameB)\n s.add(friendship)\n s.commit()\n\ndef add_friend(usernameA,usernameB):\n from sqlalchemy import create_engine, or_\n from sqlalchemy.orm import sessionmaker\n from tabledef import Pending_Friendship\n from flask import session\n\n engine = create_engine('sqlite:///lynx.db', echo=echo)\n Session = sessionmaker(bind=engine)\n s = Session()\n\n pending_friendship = Pending_Friendship(usernameA,usernameB)\n s.add(pending_friendship)\n s.commit()\n\n query = s.query(Pending_Friendship).filter(Pending_Friendship.usernameA.in_([usernameB]), Pending_Friendship.usernameB.in_([usernameA]))\n result = query.all()\n\n if result: # usernameB has pending friendship with usernameA\n add_friendship(usernameA,usernameB)\n","sub_path":"flaskgames/LynxOLD.py","file_name":"LynxOLD.py","file_ext":"py","file_size_in_byte":3738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"488604067","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 1 23:48:54 2020\r\n\r\n@author: douzi\r\n\"\"\"\r\n\r\nclass Solution:\r\n def toGoatLatin(self, S: str) -> str:\r\n res = []\r\n S = S.split()\r\n cnt = 1\r\n for e in S:\r\n if e[0].lower() in ['a', 'e', 'i', 'o', 'u']:\r\n res.append(e + 'ma' + cnt * 'a')\r\n else:\r\n res.append(e[1:] + e[0] + 'ma' + cnt * 'a')\r\n \r\n cnt = cnt + 1\r\n \r\n return ' '.join(res)\r\n\r\ns = Solution()\r\n\r\nprint(s.toGoatLatin(\"I speak Goat Latin\"))\r\n\r\nprint(s.toGoatLatin(\"The quick brown fox jumped over the lazy dog\"))","sub_path":"py824_toGoatLatin.py","file_name":"py824_toGoatLatin.py","file_ext":"py","file_size_in_byte":643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"477658538","text":"from PIL import Image\n\nmac = Image.open('example.png')\n\nprint(type(mac))\n# => specialized image file from PIL\n\n# mac.show()\n# this opens up the image\n\nprint(mac.size)\n# (220, 165) width and height\n\nprint(mac.filename)\n# 'example.png'\n\nprint(mac.format_description)\n# Portable network graphics\n\n# cropping image\n# 0, 0 - starting coordinates\n# 100, 100 - width height 100 100\ncropped_img = mac.crop((0, 0, 100, 100))\n# cropped_img.show()\n\n# pasting cropped image on top of og image\nmac.paste(im=cropped_img, box=(0, 0))\n\n# resizing\nmac.resize((3000, 500))\n\n# rotating\nmac.rotate(90)\n","sub_path":"sandbox.py","file_name":"sandbox.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"375025383","text":"s = input().split()\r\nr = int(s[0])\r\nc = int(s[1])\r\n#print('r = ',r,' c =',c)\r\nr1 = r\r\nma = list()\r\nwhile r1:\r\n s = input()\r\n du = list()\r\n for i in s:\r\n du.append(i)\r\n ma.append(du)\r\n r1 -= 1\r\n#print(ma)\r\nlast = \"\"\r\nl = list()\r\nfor j in range(c):\r\n for i in range(r):\r\n if ma[i][j].isalnum():\r\n l.append(ma[i][j])\r\n else:\r\n if l[len(l)-1].isalnum() and not j == c-1:\r\n l.append('%')\r\n if j == c-1:\r\n last += (ma[i][j])\r\n#print(last)\r\nlast = ''.join(reversed(last))\r\nres_l = \"\"\r\nfor i in last:\r\n if i.isalnum():\r\n break\r\n else:\r\n res_l += i\r\nres_l = ''.join(reversed(res_l))\r\n#print(res_l)\r\nres = \"\"\r\n#print(l)\r\nfor i in l:\r\n if i.isalnum():\r\n res += i\r\n else:\r\n res += \" \"\r\nres += res_l\r\nprint(res.rstrip())","sub_path":"Matrix_Script.py","file_name":"Matrix_Script.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"628742287","text":"import pygame, os\nimport settings as s\nimport world_object as wo\n\nclass Competitor(wo.WorldObject):\n \"\"\"Represents a single competitor car in a level.\"\"\"\n\n def __init__(self, position, offset, name, speed):\n self.position = position * s.SEGMENT_HEIGHT\n self.offset = offset\n self.offset_y = 0.0\n self.sprite = s.SPRITES[name]\n self.speed = speed\n self.quantifier = 1.8\n\n def travel(self, track_length):\n # Update Z position.\n pos = self.position + (s.FRAME_RATE * self.speed)\n\n if pos >= track_length:\n pos -= track_length\n\n if pos < 0:\n pos += track_length\n\n self.position = pos\n\n def path(self):\n return pygame.image.load(os.path.join(\"lib\", self.sprite[\"path\"]))\n","sub_path":"swervin_mervin/competitor.py","file_name":"competitor.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"614589825","text":"#-*- coding: utf-8 --\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse, JsonResponse\nfrom models import Members, Games, Servers, Likes, Hates\nimport hashlib\nimport uuid\nimport random\n\n# Create your views here.\ndef index(request):\n All = Games.objects.all()\n Maple = All.filter(id=2)\n Baram = All.filter(id=1)\n Mine = All.filter(id=3)\n Lineage = All.filter(id=4)\n Wow = All.filter(id=5)\n Stone = All.filter(id=6)\n\n Maple = Servers.objects.filter(game_id=Maple)[0:4]\n if Maple.count == 0:\n Maple = None\n\n Baram = Servers.objects.filter(game_id=Baram)[0:4]\n if Baram.count == 0:\n Baram = None\n\n Mine = Servers.objects.filter(game_id=Mine)[0:4]\n if Mine.count == 0:\n Mine = None\n\n Lineage = Servers.objects.filter(game_id=Lineage)[0:4]\n if Lineage.count == 0:\n Lineage = None\n\n Wow = Servers.objects.filter(game_id=Wow)[0:4]\n if Wow.count == 0:\n Wow = None\n\n Stone = Servers.objects.filter(game_id=Stone)[0:4]\n if Stone.count == 0:\n Stone = None\n return render(request, 'index.html', {'maple' : Maple, 'baram' : Baram, 'mine' : Mine, 'li' : Lineage, 'wow' : Wow, 'stone' : Stone})\n\ndef Join(request):\n if request.method == \"POST\":\n id = request.POST[\"id\"]\n pw = request.POST[\"pw\"]\n ip = request.META.get('REMOTE_ADDR')\n\n if id is None or pw is None or ip is None:\n return HttpResponse(\"\")\n\n if len(id) < 2 or len(id) > 20:\n return HttpResponse(\"\")\n\n if len(pw) < 8 or len(pw) > 30:\n return HttpResponse(\"\")\n\n if not Members.objects.filter(host=ip).count() == 0:\n return HttpResponse(\"\")\n\n try:\n Members.objects.get(name=id)\n return HttpResponse(\"\")\n except:\n mem = Members()\n mem.name = id\n mem.pw = pw\n mem.permission = False\n mem.host = ip\n mem.save()\n return HttpResponse(\"\")\n\n return render(request, 'join.html', {})\n\ndef Login(request):\n if request.method == \"POST\":\n id = request.POST[\"id\"]\n pw = request.POST[\"pw\"]\n\n if id is None or pw is None:\n return HttpResponse(\"\")\n\n if len(id) < 2 or len(id) > 20:\n return HttpResponse(\"\")\n\n if len(pw) < 8 or len(pw) > 30:\n return HttpResponse(\"\")\n\n try:\n mem = Members.objects.get(name=id, pw=pw)\n pw = pw+\"\"+str(random.randint(1, 1000))\n token = hashlib.sha256(pw).hexdigest()\n request.session[\"token\"] = token\n request.session[\"mid\"] = mem.id\n mem.token = token\n mem.save()\n return HttpResponse(\"\")\n except:\n return HttpResponse(\"\")\n return render(request, 'login.html', {})\n\ndef Apply(request):\n try:\n current = request.session[\"token\"]\n Members.objects.get(token=current)\n except:\n return HttpResponse(\"\")\n\n Game = None\n if request.method == \"POST\":\n game_id = request.POST[\"game\"]\n name = request.POST[\"name\"]\n address = request.POST[\"address\"]\n tag = request.POST[\"tag\"]\n description = request.POST[\"description\"]\n thumbnail = request.FILES[\"thumbnail\"]\n logo = request.FILES[\"logo\"]\n mid = request.session[\"mid\"]\n\n if game_id == None or name == None or address == None or tag == None or thumbnail is None or logo is None:\n return HttpResponse(\"\")\n\n if game_id == \"\" or name == \"\" or address == \"\" or tag == \"\" or thumbnail == \"\" or logo == \"\":\n return HttpResponse(\"\")\n\n try:\n member = Members.objects.get(id=mid)\n except:\n return HttpResponse(\"\")\n\n thumbnail.name = \"%s.png\"%uuid.uuid4()\n logo.name = \"%s.png\"%uuid.uuid4()\n\n Game = Games.objects.get(id=game_id)\n server = Servers()\n server.game = Game\n server.member = member\n server.name = name\n server.address = address\n server.tag = tag\n server.description = description\n server.thumbnail = thumbnail\n server.logo = logo\n server.like = 0\n server.hate = 0\n server.save()\n\n return HttpResponse(\"\")\n elif request.method == \"GET\":\n Game = Games.objects.all()\n return render(request, 'apply.html', {'games' : Game, 'a' : 'asf'})\n\ndef List(request, game_id=None):\n if (game_id is None):\n return HttpResponse(\"\")\n\n try:\n game = Games.objects.get(id=game_id)\n\n gname = game.name\n\n try:\n if Servers.objects.filter(game_id=game_id).count() ==0:\n return HttpResponse(\"\")\n\n server = Servers.objects.filter(game_id=game_id).order_by(\"-like\")[0:5]\n\n return render(request, 'list.html', {'name' : gname, 'gid' : game_id, 'servers' : server})\n except:\n return HttpResponse(\"\")\n except:\n return HttpResponse(\"\")\n\n\ndef MoreServer(request, game_id=None, limit=None):\n if limit is None or game_id is None:\n return HttpResponse(status=402)\n\n limit = int(limit)\n servers = Servers.objects.filter(game_id=game_id).order_by(\"-like\")[limit:limit+5]\n\n if servers.count() == 0:\n return HttpResponse(status=503)\n\n return render(request, 'more.html', {'servers' : servers})\n\ndef Act(request, type=None, sid=None):\n if type is None or sid is None:\n return HttpResponse(status=402)\n\n token = request.session[\"token\"]\n try:\n Members.objects.get(token=token)\n except:\n return HttpResponse(\"로그인이 필요한 서비스입니다.\", status=401)\n\n type = int(type)\n sid = int(sid)\n mid = request.session[\"mid\"]\n\n try:\n server = Servers.objects.get(id=sid)\n mem = Members.objects.get(id=mid)\n if type == 1:\n try:\n Likes.objects.get(server=server, member=mem)\n return HttpResponse(\"이미 좋아요를 누르셨습니다.\", status=401)\n except:\n like = Likes()\n like.server = server\n like.member = mem\n like.save()\n server.like = int(server.like)+1\n server.save()\n elif type ==2:\n try:\n Hates.objects.get(server=server, member=mem)\n return HttpResponse(\"이미 싫어요를 누르셨습니다.\", status=401)\n except:\n hate = Hates()\n hate.server = server\n hate.member = mem\n hate.save()\n server.hate = int(server.hate)+1\n server.save()\n except:\n return HttpResponse(\"알 수 없는 오류입니다.\", status=400)\n\n return HttpResponse(status=200)\n\ndef Search(request):\n search = request.POST[\"search\"].strip()\n\n servers = Servers.objects.filter(name__icontains=search).order_by(\"-like\")\n\n if servers.count() == 0:\n return HttpResponse(\"\")\n\n return render(request, 'list.html', {'gid' : 0, 'servers' : servers, 'search' : True})\n\ndef Agreement(request):\n return render(request, 'agree.html', {})\n\ndef Change(request):\n try:\n current = request.session[\"token\"]\n mem = Members.objects.get(token=current)\n\n if request.method == \"GET\":\n servers = Servers.objects.filter(member=mem)\n return render(request, 'apply.html', {'servers' : servers})\n\n elif request.method == \"POST\":\n sid = request.POST[\"sid\"]\n name = request.POST[\"name\"]\n address = request.POST[\"address\"]\n tag = request.POST[\"tag\"]\n description = request.POST[\"description\"]\n thumbnail = request.FILES[\"thumbnail\"]\n logo = request.FILES[\"logo\"]\n mid = request.session[\"mid\"]\n\n server = Servers.objects.get(id=sid, member=mem)\n\n if sid == None or name == None or address == None or tag == None or thumbnail is None or logo is None:\n return HttpResponse(\"\")\n\n if sid == \"\" or name == \"\" or address == \"\" or tag == \"\" or thumbnail == \"\" or logo == \"\":\n return HttpResponse(\"\")\n\n thumbnail.name = \"%s.png\"%uuid.uuid4()\n logo.name = \"%s.png\"%uuid.uuid4()\n\n server.member = mem\n server.name = name\n server.address = address\n server.tag = tag\n server.description = description\n server.thumbnail = thumbnail\n server.logo = logo\n server.save()\n\n return HttpResponse(\"\")\n except:\n return HttpResponse(\"\")\n","sub_path":"main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"511397913","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport re\nimport subprocess\n\n\nDEFAULT_BRANCH = 'master'\nDEFAULT_README_FILE = 'README.md'\nDEFAULT_GRADLE_FILE = 'build.gradle'\n\nPATTERN_VERSION = re.compile(r'^(?P\\d+)\\.(?P\\d+)\\.(?P\\d+)*(?:-(?PALPHA|BETA|RC\\d+|SNAPSHOT))?$')\nPATTERN_RC = re.compile(r'^RC(\\d+)$')\nQUALIFIER_RC = 'RC'\nQUALIFIER_DEV = 'SNAPSHOT'\nINFO_BLOCK_BEGIN = ' autogenerated release information begin '\nINFO_BLOCK_END = ' autogenerated release information end '\nTEMPLATE_TAG = 'releases/v{version}'\nTEMPLATE_MESSAGE_PRE = '[pre-release] {version}'\nTEMPLATE_MESSAGE_POST = '[post-release] {version}'\n\nTEMPLATE_INFO_BLOCK = '''\n*----{info_block_begin:-^70}----*\n\n| | |\n|----------|-------------------------------------------------------------------|\n| Group | {group:<65} |\n| Artifact | {artifact:<65} |\n| Version | {version:<65} |\n| Date | {timestamp:<65} |\n\n*----{info_block_end:-^70}----*\n'''\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--branch-dev', default=DEFAULT_BRANCH, help='override the default dev branch (' + DEFAULT_BRANCH + ')')\n parser.add_argument('--branch-release', default=DEFAULT_BRANCH, help='override the default release branch (' + DEFAULT_BRANCH + ')')\n parser.add_argument('--gradle-file', default=DEFAULT_GRADLE_FILE, help='override the default gradle file (' + DEFAULT_GRADLE_FILE + ')')\n parser.add_argument('--readme-file', default=DEFAULT_README_FILE, help='override the default README file (' + DEFAULT_README_FILE + ')')\n pg = parser.add_mutually_exclusive_group()\n pg.add_argument('--next-version', default='', help='override the next dev version (will be suffixed with -' + QUALIFIER_DEV + ' if necessary)')\n pg.add_argument('--rc', action='store_true', help='enables release candidate semantics (adds or increments \"-RCn\" suffix)')\n\n # Collect params\n options = parser.parse_args()\n branch_dev = options.branch_dev\n branch_release = options.branch_release\n gradle_file = options.gradle_file\n readme_file = options.readme_file\n is_rc = options.rc\n next_version = options.next_version\n\n print_bold('PRERELEASE -- STARTED')\n\n #\n # Validate Git state\n #\n\n print_green('Checking Git state')\n ensure_clean_working_copy()\n do_checkout(branch_dev)\n\n #\n # Collect release info\n #\n\n print_green('Collecting release info')\n group, artifact, current_version = get_artifact_info()\n release_version = to_release_version(current_version, is_rc)\n next_version = normalize_next_version(next_version)\n if not next_version:\n next_version = to_next_version(release_version)\n\n print_yellow('==> current_version: {}', current_version)\n print_yellow('==> release_version: {}', release_version)\n print_yellow('==> next_version: {}', next_version)\n\n #\n # Update README\n #\n\n print_green(\"Updating release info block in '{}'\", readme_file)\n update_readme(readme_file, group, artifact, release_version)\n\n #\n # Update Gradle buildscript\n #\n\n print_green(\"Updating to release version in '{}'\", gradle_file)\n update_gradlefile(gradle_file, release_version)\n\n #\n # Commit and tag\n #\n\n print_green(\"Committing to '{}'\", branch_dev)\n do_commit(release_version)\n do_tag(release_version)\n\n if not is_rc:\n print_bold('RELEASE -- STARTED')\n\n #\n # Merge to release branch if needed\n #\n\n if branch_dev != branch_release:\n print_green(\"Merging to '{}'\", branch_release)\n do_merge(branch_dev, branch_release)\n\n #\n # Apply the next dev version\n #\n\n print_bold('POSTRELEASE -- STARTED')\n\n print_green(\"Updating to next dev version in '{}'\", gradle_file)\n do_checkout(branch_dev)\n update_gradlefile(gradle_file, next_version)\n\n print_green(\"Committing to '{}'\", branch_dev)\n do_commit(release_version, is_post=True)\n\n print_bold('COMPLETE')\n\n print_yellow('all thats left to do is to push')\n\n\ndef do_checkout(branch):\n print_dim(\"==> checking out '{}'\", branch)\n try:\n execute(['git', 'checkout', branch])\n except subprocess.CalledProcessError as err:\n fatal_error(\"could not check out branch '{}'\", branch, cmd=err.cmd, output=err.output)\n\n\ndef do_commit(version, is_post=False):\n if is_post:\n message = TEMPLATE_MESSAGE_POST.format(version=version)\n else:\n message = TEMPLATE_MESSAGE_PRE.format(version=version)\n try:\n execute_verbose(['git', 'commit', '-m', message])\n except subprocess.CalledProcessError as err:\n fatal_error('could not commit release', cmd=err.cmd, output=err.output)\n\n\ndef do_merge(branch_dev, branch_release):\n do_checkout(branch_release)\n try:\n execute_verbose(['git', 'merge', branch_dev])\n except subprocess.CalledProcessError as err:\n fatal_error('could not merge branches',\n dev=branch_dev,\n release=branch_release,\n cmd=err.cmd,\n output=err.output)\n\n\ndef do_tag(version):\n tag = TEMPLATE_TAG.format(version=version)\n\n print_dim(\"==> tagging release as '{}'\".format(tag))\n try:\n execute_verbose(['git', 'fetch', '--tags'])\n execute_verbose(['git', 'tag', tag])\n except subprocess.CalledProcessError as err:\n fatal_error('could not fetch/create tags', cmd=err.cmd, output=err.output)\n\n\ndef ensure_clean_working_copy():\n try:\n modified_files = execute(['git', 'status', '--short'])\n if modified_files:\n fatal_error('cannot proceed with uncommitted changes', files=modified_files)\n except subprocess.CalledProcessError as err:\n fatal_error('could not check for uncommitted changes', cmd=err.cmd, output=err.output)\n\n\ndef execute(*args, **kwargs):\n \"\"\"\n :rtype: str\n \"\"\"\n return subprocess.check_output(*args,\n stderr=subprocess.STDOUT,\n universal_newlines=True,\n **kwargs)\n\n\ndef execute_verbose(*args, **kwargs):\n output = execute(*args, **kwargs).strip()\n\n if output:\n for line in output.splitlines():\n print_dim(' ' + line)\n\n return output\n\n\ndef fatal_error(message, *args, **extras):\n print_red('error: {}', message.format(*args))\n\n if extras:\n for k, v in sorted(extras.items()):\n if isinstance(v, str) and '\\n' in v:\n print_dim('{} = (multiline)\\n---\\n{}\\n---', k, v)\n continue\n print_dim('{} = {}', k, repr(v))\n exit(1)\n\n\ndef get_artifact_info():\n \"\"\"\n :rtype: str, str, str\n\n Note, to get this info from Maven try `mvn help:evaluate <<< '${project.groupId}:${project.artifactId}:${project.version}' | grep -v '^\\['`\n \"\"\"\n gradle_props = {}\n for line in execute(['gradle', 'properties', '-q']).splitlines():\n if ':' not in line:\n continue\n key, value = line.split(':', 1)\n gradle_props[key.strip()] = value.strip()\n\n artifact = gradle_props.get('name')\n if not artifact:\n fatal_error(\"gradle properties missing 'name'\")\n\n group = gradle_props.get('group')\n if not group:\n fatal_error(\"gradle properties missing 'group'\", group=group)\n\n version = gradle_props.get('version')\n if not version or version == 'unspecified':\n fatal_error(\"gradle properties missing 'version'\", version=version)\n\n return group, artifact, version\n\n\ndef get_timestamp():\n try:\n return execute(['date']).strip()\n except subprocess.CalledProcessError as err:\n fatal_error('could not get timestamp', cmd=err.cmd, output=err.output)\n\n\ndef normalize_next_version(value):\n \"\"\"\n :type value: str\n :rtype: str?\n \"\"\"\n\n if not value:\n return None\n\n major, minor, patch, qualifier = parse_version(value)\n if not qualifier:\n qualifier = QUALIFIER_DEV\n return '{}.{}.{}-{}'.format(major, minor, patch, qualifier)\n\n\ndef parse_version(version):\n \"\"\"\n :type version: str\n :rtype: int, int, int, str\n \"\"\"\n\n m = PATTERN_VERSION.match(version)\n if not m:\n fatal_error(\"cannot parse unsupported version format '{}'\".format(version))\n\n major = int(m.group('major'))\n minor = int(m.group('minor'))\n patch = int(m.group('patch'))\n qualifier = m.group('qualifier')\n\n if not qualifier:\n qualifier = ''\n\n return major, minor, patch, qualifier\n\n\ndef print_blue(message, *args):\n print('[commonlib.versioning] \\033[34m{}\\033[0m'.format(message.format(*args)))\n\n\ndef print_bold(message, *args):\n print('[commonlib.versioning] \\033[1m{}\\033[0m'.format(message.format(*args)))\n\n\ndef print_dim(message, *args):\n print('[commonlib.versioning] \\033[2m{}\\033[0m'.format(message.format(*args)))\n\n\ndef print_green(message, *args):\n print('[commonlib.versioning] \\033[32m{}\\033[0m'.format(message.format(*args)))\n\n\ndef print_red(message, *args):\n print('[commonlib.versioning] \\033[31m{}\\033[0m'.format(message.format(*args)))\n\n\ndef print_yellow(message, *args):\n print('[commonlib.versioning] \\033[33m{}\\033[0m'.format(message.format(*args)))\n\n\ndef to_next_version(current_version):\n \"\"\"\n :type current_version: str\n :type is_rc: bool\n :rtype: str\n \"\"\"\n\n major, minor, patch, qualifier = parse_version(current_version)\n\n minor += 1\n return '{}.{}.{}-{}'.format(major, minor, patch, QUALIFIER_DEV)\n\n\ndef to_release_version(current_version, is_rc):\n \"\"\"\n :type current_version: str\n :type is_rc: bool\n :rtype: str\n \"\"\"\n\n major, minor, patch, qualifier = parse_version(current_version)\n\n if not is_rc:\n return '{}.{}.{}'.format(major, minor, patch)\n\n rc_number = 1\n m = PATTERN_RC.match(qualifier)\n if m:\n rc_number = int(m.group(1)) + 1\n\n return '{}.{}.{}-{}{}'.format(major, minor, patch, QUALIFIER_RC, rc_number)\n\n\ndef update_gradlefile(filename, version):\n print_dim(\"==> applying new version '{}'\", version)\n\n with open(filename, 'r+') as f:\n content = f.read().lstrip() # type: str\n f.seek(0)\n f.truncate(0)\n\n new_content = re.sub(r'^(version\\s*=?\\s*).*$', \"\\\\1'{}'\".format(version), content, count=1, flags=re.MULTILINE)\n\n f.write(new_content)\n\n # Verify that gradle picked up the change\n print_dim('==> verifying change')\n _, _, reported_version = get_artifact_info()\n\n if version != reported_version:\n fatal_error('failed to apply!', attempted=version, gradle_reported=reported_version)\n\n print_dim('==> staging file')\n try:\n execute_verbose(['git', 'add', filename])\n except subprocess.CalledProcessError as err:\n fatal_error('could not stage readme file', cmd=err.cmd, output=err.output)\n\n\ndef update_readme(filename, group, artifact, version):\n info_block = TEMPLATE_INFO_BLOCK.format(\n artifact=artifact,\n group=group,\n timestamp=get_timestamp(),\n version=version,\n info_block_begin=INFO_BLOCK_BEGIN,\n info_block_end=INFO_BLOCK_END,\n ).strip()\n\n print_dim('==> applying changes (group={}, artifact={}, version={})', group, artifact, version)\n\n if not os.path.exists(filename):\n print_dim(\"==> file '{}' not found; creating\", filename)\n with open(filename, 'w') as f:\n print('# ' + artifact, file=f)\n\n print_dim('==> attempting to replace block')\n with open(filename, 'r+') as f:\n lines = f.read().lstrip().splitlines()\n f.seek(0)\n f.truncate(0)\n\n did_replace = False\n skip_line = False\n for line in lines:\n if INFO_BLOCK_END in line:\n skip_line = False\n continue\n\n if INFO_BLOCK_BEGIN in line:\n skip_line = True\n did_replace = True\n\n print(info_block, file=f)\n continue\n\n if skip_line:\n continue\n\n print(line, file=f)\n\n if not did_replace:\n print_dim('==> block not found; appending to file')\n print('\\n' + info_block, file=f)\n\n print_dim('==> staging file')\n try:\n execute_verbose(['git', 'add', filename])\n except subprocess.CalledProcessError as err:\n fatal_error('could not stage readme file', cmd=err.cmd, output=err.output)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"resources/versioning.py","file_name":"versioning.py","file_ext":"py","file_size_in_byte":12788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"368038250","text":"from collections import namedtuple\nimport numpy as np\nimport random\n\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nTransition = namedtuple(\n 'Transition', ('state', 'action', 'next_state', 'reward', 'done'))\n\nclass ReplayMemory(object):\n def __init__(self, capacity):\n self.capacity = capacity\n self.memory = []\n self.position = 0\n\n def push(self, *args):\n \"\"\"Saves a transition.\"\"\"\n if len(self.memory) < self.capacity:\n self.memory.append(None)\n self.memory[self.position] = Transition(*args)\n self.position = (self.position + 1) % self.capacity\n\n def sample(self, batch_size):\n return random.sample(self.memory, batch_size)\n\n def reset(self):\n self.memory = []\n self.position = 0\n\n def __len__(self):\n return len(self.memory)\n\nclass EpsilonScheduler(object):\n def __init__(self, t_range, eps_range):\n self.eps_start = eps_range[0]\n self.eps_end = eps_range[1]\n self.eps_range = eps_range[1] - eps_range[0]\n self.t_start = t_range[0]\n self.t_end = t_range[1]\n self.t_duration = self.t_end - self.t_start\n\n def __call__(self, t):\n if t < self.t_start:\n return self.eps_start\n if t > self.t_end:\n return self.eps_end\n return self.eps_start + \\\n ((t-self.t_start)/self.t_duration) * (self.eps_range)\n\nclass MLP_DQN(nn.Module):\n def __init__(self, input_dim, output_dim, n_units=24):\n super(MLP_DQN, self).__init__()\n\n self.model = nn.Sequential(\n nn.Linear(input_dim, n_units),\n nn.ReLU(True),\n nn.Linear(n_units, n_units),\n nn.ReLU(True),\n nn.Linear(n_units, n_units),\n nn.ReLU(True),\n nn.Linear(n_units, output_dim)\n )\n\n def forward(self, x):\n return self.model(x.float())\n\ndef train(agents, num_episodes):\n promises = []\n for ep_id in range(num_episodes):\n for agent in agents:\n promises.append(agent.run_episode.remote(ep_id))\n agent.diffuse.remote(ep_id)\n \n return promises","sub_path":"src/utils/dqn_utils.py","file_name":"dqn_utils.py","file_ext":"py","file_size_in_byte":2174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"115387550","text":"def ask_and_fill_array():\n value = int(input(\"Insert the number of elements to insert in the list: \"))\n list = []\n for i in range(1, value + 1):\n list_value = input(\"Insert value: \")\n list.append(list_value)\n return list\n\n\ndef print_the_array(array):\n print(array)\n\n\nprint_the_array(ask_and_fill_array())\n","sub_path":"JimmyRomero/Python/Session3/Practice9.py","file_name":"Practice9.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"270948184","text":"from unittest import TestCase\n\nclass TestBaseError(TestCase):\n\n def test_inst(self):\n from sanction.exceptions import BaseError\n e = BaseError({})\n\n self.assertEquals(e.description, None)\n self.assertEquals(e.error_uri, None)\n self.assertEquals(e.state, None)\n\n e = BaseError({\n \"description\": \"foo\",\n \"error_uri\": \"bar\",\n \"state\": \"state\"\n })\n\n self.assertEquals(e.description, \"foo\")\n self.assertEquals(e.error_uri, \"bar\")\n self.assertEquals(e.state, \"state\")\n\n\n def test_factory(self):\n from sanction.exceptions import AccessDeniedError\n from sanction.exceptions import exception_factory\n self.assertTrue(isinstance(exception_factory(\"access_denied\", {}),\n AccessDeniedError))\n\n self.assertIsNotNone(\"%s\" % exception_factory(\"invalid_client\", {}))\n\n try:\n e = exception_factory(\"foo\", {})\n self.fail()\n except: pass\n\n","sub_path":"tests/test_exceptions.py","file_name":"test_exceptions.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"583175213","text":"\"\"\"\n这个也没用 2018/4/12 别看了\n切割经纬度\n\"\"\"\nimport json\nimport re\nimport pika\nimport requests\nimport sys\n\nsys.setrecursionlimit(1000000)\napi_key = ['291073f17ee0b963ccb1927ed92bf265', ]\ncount_ = 0\n\n\ndef get_poi(start_lon_get, start_sat_get, end_lon_get, end_sat_get, type_):\n print(start_lon_get, start_sat_get, end_lon_get, end_sat_get, )\n global count_\n count_ += 1\n # print(count_)\n print('递归')\n square_ = str(start_lon_get) + ',' + str(start_sat_get) + ';' + str(end_lon_get) + ',' + str(end_sat_get)\n url = 'http://restapi.amap.com/v3/place/polygon?polygon=' + square_ + ';&types=' + type_ + '&output=JSON&key=' + \\\n api_key[0] + '&offset=50'\n print(url)\n response = requests.get(url)\n result_count = response.json().get('count')\n print(result_count)\n if response.json().get('status') is '1':\n if int(result_count) > 850:\n a, b, c, d = split_rectangle(start_lon_get, start_sat_get, end_lon_get, end_sat_get, )\n get_poi(a[0], a[1], a[2], a[3], type_)\n get_poi(b[0], b[1], b[2], b[3], type_)\n get_poi(c[0], c[1], c[2], c[3], type_)\n get_poi(d[0], d[1], d[2], d[3], type_)\n else:\n if int(result_count) != 0:\n if int(result_count) < 50:\n rabbit.queue_declare(queue='amap_result_json')\n rabbit.basic_publish(exchange='', routing_key='amap_result_json', body=json.dumps(response.json()))\n else:\n rabbit.queue_declare(queue='amap_page_url')\n for i in range(1, int(int(result_count) / 50 + 0.5)):\n rabbit.basic_publish(exchange='',\n routing_key='amap_page_url',\n body='http://restapi.amap.com/v3/place/polygon?polygon=' + square_ + ';&types=' + type_ + '&output=JSON&offset=50&page=' + str(\n i + 1),\n )\n print('分页url放入')\n else:\n print('count:', result_count)\n else:\n print('result status', response.json().get('status'))\n\n\ndef split_rectangle(start_lon_, start_sat_, end_lon_, end_sat_, ):\n \"\"\"\n 给两个点算中点,返回4组数据\n right_up_sq-> left_up_sq-> right_down_sq-> left_down_sq\n :param start_lon_:\n :param start_sat_:\n :param end_lon_:\n :param end_sat_:\n :return:\n \"\"\"\n\n m = (start_lon_ - end_lon_) / 2 # 横向距离/2\n s = (start_sat_ - end_sat_) / 2 # 纵向距离/2\n\n middle_lon = start_lon_ - m\n middle_sat = start_sat_ - s\n\n right_up_sq = [start_lon_, start_sat_, middle_lon, middle_sat, ]\n\n left_up_sq = [middle_lon, start_sat_, end_lon_, middle_sat]\n\n right_down_sq = [start_lon_, middle_sat, middle_lon, end_sat_]\n\n left_down_sq = [middle_lon, middle_sat, end_lon_, end_sat_]\n\n print(right_up_sq, left_up_sq, right_down_sq, left_down_sq)\n return right_up_sq, left_up_sq, right_down_sq, left_down_sq\n\n\ndef callback(ch, method, properties, body):\n body = json.loads(body.decode('utf8'))\n square_ = body['square_list']\n type_ = body['type']\n num_list = re.split(r',|;', square_)\n start_lon_ = float(num_list[0])\n start_sat_ = float(num_list[1])\n end_lon_ = float(num_list[2])\n end_sat_ = float(num_list[3])\n print(start_lon_, start_sat_, end_lon_, end_sat_, )\n a, b, c, d = split_rectangle(start_lon_, start_sat_, end_lon_, end_sat_, )\n get_poi(a[0], a[1], a[2], a[3], type_)\n get_poi(b[0], b[1], b[2], b[3], type_)\n get_poi(c[0], c[1], c[2], c[3], type_)\n get_poi(d[0], d[1], d[2], d[3], type_)\n ch.basic_ack(delivery_tag=method.delivery_tag)\n\n\ndef consume_split(channel):\n channel.basic_qos(prefetch_count=1)\n channel.basic_consume(callback,\n queue='amap_split',\n )\n channel.start_consuming()\n\n\nif __name__ == '__main__':\n connection = pika.BlockingConnection(pika.ConnectionParameters(host='192.168.0.235', ))\n rabbit = connection.channel()\n rabbit.queue_declare(queue='amap_split')\n consume_split(rabbit)\n","sub_path":"hilder_ali_crawler/backup/amap/consume_split.py","file_name":"consume_split.py","file_ext":"py","file_size_in_byte":4224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"187584187","text":"#아마스빈 주문 앱 1.음료 이름 // 2. 컵 사이즈 // 3. 얼음량 // 4. 당도 // 5. 펄\n#Drink <- Coffee // <- 상속받는다.\n# <- Bubbletea // <- 상속받는다.\n#Order\n# 메뉴 보여주자.\n# 음료 주문하자.\n# 주문한 음료 보여주자.\n# 총 금액 계산하자.\nclass Drink:\n _cups = [\"레귤러\", \"점보\"] #0 : 레귤러, 1 : 점보\n _ices = [\"0%\", \"50%\", \"100%\", \"150%\"] #0: 0%, 1: 50%, 2: 100%, 3: 150% . . .\n _sugars = [\"0%\", \"50%\", \"100%\", \"150%\"] #0: 0%, 1: 50%, 2: 100%, 3: 150% . . .\n\n def __init__(self, name, price):\n self.name = name\n self.price = price\n self.cup = 0 #기본값\n self.ice = 2 #기본값\n self.sugar = 2 #기본값\n \n def __str__(self): #이름 : self.name\\t가격 : self.price원\\t컵 : self.cup\"\n return \"이름: \"+self.name+\"\\t가격: \"+str(self.price)\\\n +\"원\\t컵: \"+Drink._cups[self.cup]\\\n +\"\\t얼음량: \"+Drink._ices[self.ice]\\\n +\"\\t당도: \"+Drink._sugars[self.sugar]\n \n def set_cup(self):\n self.cup = input(\"컵을 선택하세요(0 : 레귤러, 1: 점보)\")\n if self.cup == \"\": #사용자가 엔터만 치면 기본값 0을 넣자.\n self.cup = 0\n else:\n self.cup = int(self.cup)\n\n #점보면 300원 추가\n if self.cup == 1:\n self.price += 300\n\n def set_ice(self):\n self.ice = input(\"얼음량을 선택하세요.(0: 0%, 1: 50%, 2: 100%, 3: 150%)\")\n if self.ice == \"\":\n self.ice = 2\n else:\n self.ice = int(self.ice)\n\n def set_sugar(self):\n self.sugar = input(\"당도를 선택하세요.(0:0%, 1:50%, 2:100%, 3:150%)\")\n if self.sugar == \"\":\n self.sugar = 2\n else:\n self.sugar = int(self.sugar)\n\n def order(self):\n self.set_cup()\n self.set_ice()\n self.set_sugar()\n\nclass Coffee(Drink): #Drink를 상속하는 커피\n pass\n\nclass Bubbletea(Drink): #Drink를 상속하는 버블티\n _pearls = [\"타피오카\", \"코코\", \"젤리\", \"알로에\"]\n\n def __init__(self, name, price):\n super().__init__(name, price)\n self.pearl = 0\n\n def set_pearl(self):\n self.pearl = input(\"펄을 선택하세요.(0:타피오카, 1:코코, 2:젤리, 3:알로에)\")\n if self.pearl == \"\":\n self.pearl = 0\n else:\n self.pearl = int(self.pearl)\n\n def __str__(self):\n return super().__str__() + \"\\t펄: \"+Bubbletea._pearls[self.pearl] #상속받은 부모를 부르는 문장\n\n def order(self): #상속 받은 것에서 중복된 것이 있다면 부모 걸 불러오는 게 더 이득!\n super().order()\n self.set_pearl()\n\nclass Order:\n _menus = [Coffee(\"아메리카노\", 1800), Bubbletea(\"딸기요거트\", 3500)]\n\n def __init__(self):\n self.order_menu = []\n self.order = None #자바에서 NULL과 같은 의미 - 딱히 넣을 값이 없을 때 사용.\n \n def show_menu(self):\n print(\"0: 아메리카노 1800원, 1: 딸기요거트 3500원\")\n \n def sum_price(self):\n sum = 0\n for drink in self.order_menu:\n sum += drink.price\n \n return sum\n \n def order_drink(self):\n #반복▼\n while True:\n # 메뉴 보여주자\n self.show_menu()\n # 주문 받자.\n # 음료 선택하자.\n self.order = input(\"음료를 선택하세요: \")\n # 음료 객체 생성하자\n #0 -> Coffee(\"아메리카노\", 1800)\n #1 -> Bubbletea(\"딸기요거트\", 3500)\n if self.order == \"\": #메뉴 선택안하고 그냥 엔터치면 주문 끝\n break\n drink = Order._menus[int(self.order)]\n # 음료 옵션 정하자.\n drink.order()\n # 주문한 음료 리스트에 추가하자.\n self.order_menu.append(drink)\n #반복▲\n #주문한 음료 출력하자.\n for drink in self.order_menu:\n print(drink)\n # 금액 합계 구하자.\n print(\"총금액: \"+str(self.sum_price())+\"원\")\n\n \no = Order()\no.order_drink()\n\n#아메리카노 = Coffee(\"아메리카노\", 1800)\n#아메리카노.oder() #oder로 묶어준것. 아메리카노.set_cup() 아메리카노.set_ice() 아메리카노.set_sugar으로 나눌 수도 있다.\n#print(아메리카노) #이름 : 아메리카노\\t가격 : 1800원\n#타로밀크티 = Bubbletea(\"타로밀크티\", 3500)\n#타로밀크티.order() #타로밀크티.set_cup() 타로밀크티.set_ice() 타로밀크티.set_sugar() 타로밀크티.set_pearl()로 나눌 수 있다.\n#print(타로밀크티)","sub_path":"1학기/아마스빈/아마스빈.py","file_name":"아마스빈.py","file_ext":"py","file_size_in_byte":4838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"573215261","text":"from django.conf.urls import url\nfrom django.contrib import admin\n\nfrom .views import (\n clientes_list,\n clientes_create,\n clientes_detail,\n clientes_update,\n clientes_delete,\n\n)\n\nurlpatterns = [\n url(r'^$', clientes_list, name='clista'),\n url(r'^create/$', clientes_create),\n url(r'^(?P\\d+)/$', clientes_detail, name='cdetalle'),\n url(r'^(?P\\d+)/edit/$', clientes_update, name='cupdate'),\n url(r'^(?P\\d+)/delete/$', clientes_delete),\n]\n","sub_path":"src/clientes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"453626611","text":"import pprint,os\n\ndef analysPacket(packet,xbee,ser):\n returnedData = []\n device = packet[0]\n pprint.pprint(packet)\n\n if(device == \"dev2\"):\n returnedData.append(\"dev2\")\n\n pprint.pprint(packet)\n dataType = packet[1][0]\n\n if(dataType == 20 ):\n ###Door Status\n deviceStatus = packet[1][1]\n returnedData.append(\"door\")\n returnedData.append(deviceStatus)\n\n if(deviceStatus == 1):\n ##Run the HomeSecurity script\n ##Shell script to take pictures\n print(\"Door has been Opened\")\n os.system(\"espeak -ven+f4 'Text Door has been Opened' 2>/dev/null\")\n\n elif(deviceStatus == 0):\n print(\"Door has been Closed\")\n os.system(\"espeak -ven+f4 'Text Door Closed' 2>/dev/null\")\n\n\n elif(dataType == 30):\n ###touch ONE\n status = packet[1][1]\n sendMessage(\"all\",\"off\",xbee,ser)\n\n elif(dataType == 40):\n secure = packet[1][1]\n returnedData.append(\"security\")\n returnedData.append(secure)\n\n elif(dataType==50):\n alert = packet[1][1]\n returnData.append(\"alert\")\n returnData.append(alert) \n\n if(device == \"dev4\"):\n returnedData.append(\"dev4\")\n\n pprint.pprint(packet)\n dataType = packet[1][0]\n\n if(dataType == 20 ):\n ###Window Status\n deviceStatus = packet[1][1]\n returnedData.append(\"window\")\n returnedData.append(deviceStatus)\n\n if(deviceStatus == 1):\n ##Run the HomeSecurity script\n ##Shell script to take pictures\n print(\"Window has been Opened\")\n os.system(\"espeak -ven+f4 'Text Window has been Opened' 2>/dev/null\")\n\n elif(deviceStatus == 0):\n print(\"Door has been Closed\")\n os.system(\"espeak -ven+f4 'Text Window Closed' 2>/dev/null\")\n\n\n elif(dataType == 30):\n ###RainyStuff\n status = packet[1][1]\n returnedData.append(\"rainy\")\n returnedData.append(status)\n\n\n\n\n return returnedData\n\ndef sendMessage(device,data,xbee,ser):\n msg = \"\"\n msg += device\n small_addr= \"0000\".decode('hex')\n long_addr = \"000000000000FFFF\".decode('hex')\n\n if (data == \"lighton\"):\n msg+=\"lon\"\n\n elif (data ==\"lightoff\"):\n msg +=\"loff\"\n\n elif (data==\"tvon\"):\n msg += \"ton\"\n\n elif (data==\"tvoff\"):\n msg += \"toff\"\n\n elif (data==\"status\"):\n msg += \"status\"\n\n elif (data ==\"acon\"):\n msg += \"aon\"\n\n elif (data ==\"acoff\"):\n msg +=\"aoff\"\n else:\n msg+=data\n\n\n try:\n xbee.tx(dest_addr_long=long_addr,dest_addr=small_addr,data=msg)\n\n\n except KeyboardInterrupt:\n print(\"Out\")\n","sub_path":"Raspberry Pi Brain/Packet.py","file_name":"Packet.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"19787703","text":"'''\nModel classes\n'''\nimport torch\nimport torch.nn as nn\nfrom allennlp.modules.seq2vec_encoders import Seq2VecEncoder, PytorchSeq2VecWrapper\nfrom allennlp.models import Model\nfrom overrides import overrides\nfrom allennlp.training.metrics import CategoricalAccuracy, BooleanAccuracy\nfrom torch.nn.functional import normalize\nimport torch.nn.functional as F\nimport copy\nimport pdb\n\nclass Biencoder(Model):\n def __init__(self, args,\n mention_encoder: Seq2VecEncoder,\n entity_encoder,\n vocab):\n super().__init__(vocab)\n self.args = args\n self.mention_encoder = mention_encoder\n self.accuracy = CategoricalAccuracy()\n self.istrainflag = 1\n self.BCEWloss = nn.BCEWithLogitsLoss(reduction=\"mean\")\n self.mesloss = nn.MSELoss()\n self.entity_encoder = entity_encoder\n self.cuda_flag = 1\n\n def forward(self, context, gold_title_and_desc_concatenated, gold_and_negatives_title_and_desc_concatenated,\n gold_duidx, mention_uniq_id, labels_for_BCEWithLogitsLoss):\n batch_num = context['tokens'].size(0)\n contextualized_mention = self.mention_encoder(context)\n encoded_entites = self.entity_encoder(title_and_desc_concatnated_text=gold_title_and_desc_concatenated)\n\n contextualized_mention_forcossim = normalize(contextualized_mention, dim=1)\n if self.args.search_method == 'cossim':\n encoded_entites_forcossim = normalize(encoded_entites, dim=1)\n scores = contextualized_mention_forcossim.mm(encoded_entites_forcossim.t())\n elif self.args.search_method == 'indexflatip':\n scores = contextualized_mention.mm(encoded_entites.t())\n else:\n assert self.args.search_method == 'indexflatl2'\n scores = - self.calc_L2distance(contextualized_mention.view(batch_num, 1, -1), encoded_entites) # FIXED\n\n device = torch.get_device(scores) if self.cuda_flag else torch.device('cpu')\n target = torch.LongTensor(torch.arange(batch_num)).to(device)\n\n if self.args.search_method in ['cossim','indexflatip']:\n loss = F.cross_entropy(scores, target, reduction=\"mean\")\n else:\n loss = self.BCEWloss(scores, torch.eye(batch_num).cuda())\n\n output = {'loss': loss}\n\n if self.args.add_mse_for_biencoder:\n output['loss'] += self.mesloss(contextualized_mention, encoded_entites)\n\n if self.args.add_hard_negatives:\n batch_, gold_plus_negs_num, maxTokenLengthInBatch = gold_and_negatives_title_and_desc_concatenated['tokens'].size()\n docked_tokenlist = {'tokens': gold_and_negatives_title_and_desc_concatenated['tokens'].view(batch_ * gold_plus_negs_num, -1)}\n encoded_entities_from_hard_negatives_idx0isgold = self.entity_encoder(docked_tokenlist).view(batch_, gold_plus_negs_num, -1)\n\n if self.args.search_method == 'cossim':\n encoded_mention_forcossim_ = contextualized_mention_forcossim.repeat(1, gold_plus_negs_num).view(batch_*gold_plus_negs_num, -1)\n scores_for_hard_negatives = (((encoded_mention_forcossim_)*(normalize(encoded_entities_from_hard_negatives_idx0isgold.view(batch_*gold_plus_negs_num,-1), dim=1))).sum(1, keepdim=True).squeeze(1)).view(batch_,gold_plus_negs_num)\n elif self.args.search_method == 'indexflatip':\n encoded_mention_ = contextualized_mention.repeat(1, gold_plus_negs_num).view(batch_* gold_plus_negs_num, -1)\n scores_for_hard_negatives = (((encoded_mention_)*(encoded_entities_from_hard_negatives_idx0isgold.view(batch_*gold_plus_negs_num,-1))).sum(1, keepdim=True).squeeze(1)).view(batch_,gold_plus_negs_num)\n else:\n raise NotImplementedError\n\n loss += self.BCEWloss(scores_for_hard_negatives, labels_for_BCEWithLogitsLoss)\n\n if self.istrainflag:\n golds = torch.eye(batch_num).to(device)\n self.accuracy(scores, torch.argmax(golds, dim=1))\n else:\n output['gold_duidx'] = gold_duidx\n output['encoded_mentions'] = contextualized_mention\n\n return output\n\n @overrides\n def get_metrics(self, reset: bool = False):\n return {\"accuracy\": self.accuracy.get_metric(reset)}\n\n def return_entity_encoder(self):\n return self.entity_encoder\n\n def switch2eval(self):\n self.istrainflag = copy.copy(0)\n\n def calc_L2distance(self, h, t):\n diff = h - t\n return torch.norm(diff, dim=2) # batch * cands\n # encoded_entites.unsqueeze(0).repeat(batch_num,1,1)\n\nclass WrappedModel_for_entityencoding(Model):\n def __init__(self, args,\n entity_encoder,\n vocab):\n super().__init__(vocab)\n self.args = args\n self.entity_encoder = entity_encoder\n\n def forward(self, duidx, title_and_desc_concatnated_text):\n\n encoded_entites = self.entity_encoder(title_and_desc_concatnated_text=title_and_desc_concatnated_text)\n output = {'gold_duidx': duidx, 'emb_of_entities_encoded': encoded_entites}\n\n return output\n\n def return_entity_encoder(self):\n return self.entity_encoder\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"279669914","text":"from PyQt5.QtWidgets import QVBoxLayout, QDialog, QLineEdit, QDialogButtonBox\nfrom app.extensions.custom_gui import PropertyBox, Dialog\n\nclass NewGameDialog(Dialog):\n def __init__(self, parent=None):\n super().__init__(parent)\n self.setWindowTitle(\"New Game\")\n self.window = parent\n\n layout = QVBoxLayout()\n self.setLayout(layout)\n\n self.game_box = PropertyBox('Unique Game ID', QLineEdit, self)\n self.game_box.edit.setPlaceholderText(\"Unique Game ID\")\n self.game_box.edit.textChanged.connect(self.text_changed)\n layout.addWidget(self.game_box)\n\n self.game_title_box = PropertyBox(\"Game Title\", QLineEdit, self)\n self.game_title_box.edit.setPlaceholderText(\"Game Title\")\n self.game_title_box.edit.textChanged.connect(self.text_changed)\n layout.addWidget(self.game_title_box)\n\n layout.addWidget(self.buttonbox)\n self.buttonbox.button(QDialogButtonBox.Ok).setEnabled(False)\n\n def text_changed(self, text):\n if (self.game_title_box.edit.text() or self.game_box.edit.text()):\n self.buttonbox.button(QDialogButtonBox.Ok).setEnabled(True)\n else:\n self.buttonbox.button(QDialogButtonBox.Ok).setEnabled(False)\n\n @classmethod\n def get(cls, parent=None):\n dialog = cls(parent)\n result = dialog.exec_()\n if result == QDialog.Accepted:\n return (dialog.game_box.edit.text(), dialog.game_title_box.edit.text())\n else:\n return None\n","sub_path":"app/editor/new_game_dialog.py","file_name":"new_game_dialog.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"396653344","text":"# coding=utf-8\nfrom flask import jsonify, request\nfrom sqlalchemy import desc\n\nfrom src import app\n\nfrom ..entities.entity import Session\nfrom ..entities.strategy_1_monitoring import (Strategy_1_monitoring,\n Strategy_1_monitoringSchema)\nfrom ..utils.manage_request import get_request_data\n\n\n@app.route('/api/strategy1monitoring')\ndef get_all_strategy1monitoring():\n # fetching from the database\n session = Session()\n strategy1monitoring_objects = session.query(Strategy_1_monitoring).order_by(desc(Strategy_1_monitoring.start_date)).all()\n\n # transforming into JSON-serializable objects\n schema = Strategy_1_monitoringSchema(many=True)\n strategy1monitoring = schema.dump(strategy1monitoring_objects)\n\n # serializing as JSON\n session.close()\n return jsonify(strategy1monitoring.data)\n\n\n@app.route('/api/strategy1monitoring/')\ndef get_strategy1monitoring_by_id(id):\n # fetching from the database\n session = Session()\n strategy1monitoring_objects = session.query(\n Strategy_1_monitoring).filter(Strategy_1_monitoring.id == id).all()\n\n # transforming into JSON-serializable objects\n schema = Strategy_1_monitoringSchema(many=True)\n strategy1monitoring = schema.dump(strategy1monitoring_objects)\n\n # serializing as JSON\n session.close()\n return jsonify(strategy1monitoring.data)\n\n\n@app.route('/api/strategy1monitoring', methods=['POST'])\ndef save_strategy1monitoring(json_data):\n if json_data == None:\n json_data = get_request_data(request)\n param_name = json_data['name']\n param_start_date = json_data['start_date']\n param_finish_date = json_data['finish_date']\n param_time = json_data['time']\n param_state = json_data['state']\n param_info = json_data['info']\n\n new_strategy1monitoring = Strategy_1_monitoring(name=param_name, start_date=param_start_date, finish_date=param_finish_date,\n time=param_time, state=param_state, info=param_info, created_by=\"Admin\")\n\n session = Session()\n session.add(new_strategy1monitoring)\n session.commit()\n\n saved_strategy1monitoring = Strategy_1_monitoringSchema().dump(\n new_strategy1monitoring).data\n session.close()\n return jsonify(saved_strategy1monitoring)\n\n@app.route('/api/updatetrategy1monitoring', methods=['POST'])\ndef update_strategy1monitoring(json_data):\n session = Session()\n \n update_strategy1monitoring = session.query(Strategy_1_monitoring).filter(Strategy_1_monitoring.id == json_data['id']).first()\n\n update_strategy1monitoring.finish_date = json_data['finish_date']\n update_strategy1monitoring.time = json_data['time']\n update_strategy1monitoring.state = json_data['state']\n update_strategy1monitoring.info = json_data['info']\n\n session.commit()\n\n updated_strategy1monitoring = Strategy_1_monitoringSchema().dump(\n update_strategy1monitoring).data\n session.close()\n return jsonify(updated_strategy1monitoring)\n\n@app.route('/api/strategy1monitoring/', methods=['DELETE'])\ndef delete_strategy1monitoring_by_id(id):\n # fetching from the database\n session = Session()\n strategy1monitoring_objects = session.query(Strategy_1_monitoring).filter(\n Strategy_1_monitoring.id == id).delete(synchronize_session='evaluate')\n session.commit()\n\n # transforming into JSON-serializable objects\n deleted_strategy1monitoring = Strategy_1_monitoringSchema().dump(\n strategy1monitoring_objects).data\n\n # serializing as JSON\n session.close()\n return jsonify(deleted_strategy1monitoring), 201\n","sub_path":"server/src/services/DAOstrategy_1_monitoring.py","file_name":"DAOstrategy_1_monitoring.py","file_ext":"py","file_size_in_byte":3623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"246808103","text":"import numpy as np\nimport cv2\nimport time\nfrom datetime import datetime\nfrom multiprocessing import Process, Event\n\n\ndef videoPreview(previewName, camID, duration):\n cap = cv2.VideoCapture(camID)\n\n # Define the codec and create VideoWriter object\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(str(previewName)+'_'+str(camID)+'_'+str(datetime.utcnow().strftime('%M-%S-%f'))+'.avi', fourcc, 20.0, (640,480))\n\n timeout = time.time() + int(duration) # duration sec from now\n while(cap.isOpened()):\n ret, frame = cap.read()\n if ret:\n frame = cv2.flip(frame,0)\n # write the flipped frame\n out.write(frame)\n\n else:\n break\n\n if time.time() > timeout: # break if duration over\n break\n\n # Release everything if job is finished\n cap.release()\n out.release()\n cv2.destroyAllWindows()\n\n return\n\n\ndef task(event, cam_params):\n e.wait() # Wait for an event\n videoPreview(cam_params[0], cam_params[1], cam_params[2])\n\nif __name__ == '__main__':\n e = Event() # Create event that will be used for synchronization\n \n #IR\n p1 = Process(target=task, args=(e, [\"First_Cam\", 0, 5]))\n p1.start()\n \n #RGB\n p2 = Process(target=task, args=(e, [\"First_Cam\", 2, 5]))\n p2.start()\n \n #IR\n p3 = Process(target=task, args=(e, [\"Second_Cam\", 4, 5]))\n p3.start()\n \n #RGB\n p4 = Process(target=task, args=(e, [\"Second_Cam\", 6, 5]))\n p4.start()\n\n e.set() # Set event so all processes can start at the same time\n\n","sub_path":"opencv_video/4module_capture.py","file_name":"4module_capture.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"363801646","text":"#!/usr/bin/env python3\nimport sys\n\nrecords = []\nfor line in sys.stdin:\n records.append(line.strip())\n\nguards = {}\nguard = 0\nfor record in sorted(records):\n activity = record[-2:]\n if activity == 'ft':\n # starts shift\n guard = record[26:30].strip()\n elif activity == 'up':\n # wakes up\n min_up = int(record[15:17])\n\n if guard not in guards:\n guards[guard] = [0 for x in range(60)]\n\n for m in range(min_down, min_up):\n guards[guard][m] += 1\n elif activity == 'ep':\n # sleeps\n min_down = int(record[15:17])\n\nmax_sleep = 0\nmax_sleep_min = 0\nfor guard in guards:\n for m, c in enumerate(guards[guard]):\n if c > max_sleep:\n bad_guard = guard\n max_sleep = c\n max_sleep_min = m\n\nprint(int(bad_guard) * max_sleep_min)\n","sub_path":"2018/day04/day04-2.py","file_name":"day04-2.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"394283185","text":"#####################################\n# Imports\n\nfrom game_classes import Person\nimport random\n\n\n#####################################\n# Instantiate objects\n\nmain_player = Person(\"Superman\", 500, 100, 50)\n\nenemy = Person(\"Bad guy\", 800, 70, 30)\n\n\n#####################################\n# Main game\n\n# 1. Welcome speech and print the current stats of player and enemy\n\nprint(\"=======================================\")\nprint(\"\\t Welcome to the game !\")\nprint(\"\\t Let's kill the bad guys\")\nmain_player.get_stats()\nenemy.get_stats()\nprint(\"=======================================\")\n\n# 2. Start the loop\nrunning = True\nwhile running:\n # 2.a Main player starts first\n print(\"=======================================\")\n print(f\"\\t {main_player.name.upper()}\")\n main_player.choose_action()\n choice_input = input(\"\\t\\t\\tChoose a number: \")\n index = int(choice_input) - 1\n print(f\"\\t You chose {main_player.action[index]}\")\n\n # 2.b Physical attack\n if index == 0:\n dmg = main_player.generate_atk_damage()\n enemy.take_damage(dmg)\n\n print(f\"\\t You attacked and dealt to {enemy.name} {dmg} points of damage\")\n else:\n print(\"This is easy mode, you cannot choose other option for now\")\n continue\n\n # 2.c. Enemy's turn\n print(\"=======================================\")\n print(f\"\\t {enemy.name.upper()}\")\n enemy_choice = random.randrange(0, len(enemy.action))\n if enemy_choice == 0:\n enemy_dmg = enemy.generate_atk_damage()\n main_player.take_damage(enemy_dmg)\n print(\n f\"\\t {enemy.name.capitalize()} attacked and dealt to you {enemy_dmg} points of damage\"\n )\n\n # 2.d Round Summary\n main_player.get_stats()\n enemy.get_stats()\n\n if main_player.hp == 0:\n print(\"\\t\\t YOU LOST !\")\n running = False\n elif enemy.hp == 0:\n print(\"\\t\\t YOU WIN !\")\n running = False\n","sub_path":"easy_mode/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"624760473","text":"import arrow, flask, json, os, pymongo\n\nfrom flask_cors import CORS\n\nENV = os.environ.get('ENV', 'development').lower()\nPORT = 8000\n\napp = flask.Flask(__name__, static_folder='data')\napp.debug = (ENV == 'development')\nif app.debug: app.threaded = True\nCORS(app)\n\n# Stats\nimport statsd\nstatsd.init_statsd({\n 'STATSD_HOST': os.environ.get('STATSD_HOST', 'localhost'),\n 'STATSD_BUCKET_PREFIX': 'electricymap_api'\n})\n\n# Loghandler in production mode\nif not app.debug:\n import logging\n from logging.handlers import SMTPHandler\n mail_handler = SMTPHandler(\n mailhost=('smtp.mailgun.org', 587),\n fromaddr='Application Bug Reporter ',\n toaddrs=['olivier.corradi@gmail.com'],\n subject='Electricity Map Flask Error',\n credentials=(os.environ.get('MAILGUN_USER'), os.environ.get('MAILGUN_PASSWORD'))\n )\n mail_handler.setLevel(logging.ERROR)\n app.logger.addHandler(mail_handler)\n logging.getLogger('statsd').addHandler(logging.StreamHandler())\n\n# Database\nclient = pymongo.MongoClient(\n os.environ.get('MONGO_URL', 'mongodb://localhost:27017'))\ndb = client['electricity']\ncol = db['realtime']\ncol.create_index([('datetime', pymongo.DESCENDING)])\ncol.create_index([('countryCode', pymongo.ASCENDING)])\n\ndef bson_measurement_to_json(obj):\n obj['_id'] = str(obj['_id'])\n obj['datetime'] = arrow.get(obj['datetime']).isoformat()\n return obj\n\n\n@app.route('/production', methods=['GET', 'OPTIONS'])\n@statsd.StatsdTimer.wrap('production_GET')\ndef production_GET():\n\n statsd.increment('production_GET')\n objs = col.aggregate([\n {'$group': {'_id': '$countryCode', 'lastDocument': {'$last': '$$CURRENT'}}}\n ])\n objs = map(bson_measurement_to_json,\n map(lambda o: o['lastDocument'], list(objs)))\n data = {obj['countryCode']: obj for obj in objs if 'countryCode' in obj}\n return flask.jsonify({\n 'status': 'ok',\n 'data': data\n })\n\n@app.route('/co2', methods=['GET', 'OPTIONS'])\n@statsd.StatsdTimer.wrap('co2_GET')\ndef co2_GET():\n # Solve co2\n # ...\n # Geocode to get the country\n # http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452\n return flask.jsonify({'error': 'NotImplementedYet'}), 400\n\n@app.route('/solar', methods=['GET', 'OPTIONS'])\n@statsd.StatsdTimer.wrap('solar_GET')\ndef solar_GET():\n statsd.increment('solar_GET')\n response = flask.make_response(flask.send_from_directory('data', 'solar.json.gz'))\n response.headers['Content-Encoding'] = 'gzip'\n return response\n\n@app.route('/wind', methods=['GET', 'OPTIONS'])\n@statsd.StatsdTimer.wrap('wind_GET')\ndef wind_GET():\n statsd.increment('wind_GET')\n response = flask.make_response(flask.send_from_directory('data', 'wind.json.gz'))\n response.headers['Content-Encoding'] = 'gzip'\n return response\n\n@app.route('/data/', methods=['GET', 'OPTIONS'])\n@statsd.StatsdTimer.wrap('data_GET')\ndef data_GET(path):\n statsd.increment('data_GET')\n return flask.send_from_directory('data', path)\n\n@app.route('/')\n@statsd.StatsdTimer.wrap('index_GET')\ndef index_GET():\n statsd.increment('index_GET')\n return flask.send_from_directory('', 'index.html')\n\n@app.route('/style.css')\ndef style_GET():\n return flask.send_from_directory('', 'style.css')\n\n@app.route('/favicon-32x32.png')\ndef favicon_GET():\n return flask.send_from_directory('', 'favicon-32x32.png')\n\n@app.route('/tomorrow_logo_open_source.svg')\ndef logo_GET():\n return flask.send_from_directory('', 'tomorrow_logo_open_source.svg')\n\n@app.route('/vendor/', methods=['GET', 'OPTIONS'])\ndef vendor_GET(path):\n return flask.send_from_directory('vendor', path)\n\n@app.route('/app/', methods=['GET', 'OPTIONS'])\ndef app_GET(path):\n return flask.send_from_directory('app', path)\n\n@app.route('/health', methods=['GET', 'OPTIONS'])\n@statsd.StatsdTimer.wrap('health_GET')\ndef health_GET():\n statsd.increment('health_GET')\n # Check last data point obtained\n EXPIRATION_SECONDS = 30 * 60.0\n result = list(col.find(sort=[('datetime', pymongo.DESCENDING)], limit=1))\n if not len(result) or (arrow.now() - arrow.get(result[0]['datetime'])).total_seconds() > EXPIRATION_SECONDS:\n return flask.jsonify({'error': 'Database is empty or last measurement is too old.'}), 400\n return flask.jsonify({'status': 'ok'})\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=PORT)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"30478972","text":"# coding: utf-8\n# pylint: disable=E0401\n# pylint: disable=E1102\n# pylint: disable=E1120\nfrom tp1 import clear, terminosDeEX\n\"\"\"\n Modelo Matematico: x^(n-1)/(n-1)!\n\"\"\"\ndef main():\n clear()\n\n x = float(input(\"Ingrse el valor de x para e^x: \"))\n n = int(input(\"Ingrse el numero de terminos a hallar de la seria e^x: °\"))\n terminos = terminosDeEX(x)(n)()\n print(terminos)\n print(\"Terminos hallados: \" + str(terminos))\n ex = 0\n for t in terminos:\n ex += t\n print(\"Su sumatoria es: \" + str(ex))\n\nif __name__ == '__main__':\n main()\n","sub_path":"server/api/tp1/c_8.py","file_name":"c_8.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"563865884","text":"from math import factorial\n\n\ndef digit_factorials():\n length = 2\n while length * factorial(9) >= 10 ** (length - 1):\n yield from (\n n\n for n in range(10 ** (length - 1), 10 ** length)\n if sum(factorial(int(d)) for d in str(n)) == n\n )\n length += 1\n\n\nprint(sum(digit_factorials()))\n","sub_path":"problem_034.py","file_name":"problem_034.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"254168829","text":"\"\"\"Basic app compile file.\"\"\"\nimport flask\nimport flask_migrate\n\nfrom repoze.profile import ProfileMiddleware\n\nimport app.batch\nimport app.extensions\nimport app.views\n\n# init app\napplication = flask.Flask(__name__, template_folder='./templates',\n static_folder='./static')\n\napplication.config.from_object('config')\n\n# init database\nFlaskDB = app.extensions.db\nFlaskDB.init_app(application)\n\n# init migrate\nFlaskMigrateScript = app.extensions.migrate\nFlaskMigrateScript.init_app(application, FlaskDB)\n\n# script managers\nFlaskManager = app.extensions.manager\nFlaskManager.app = application\nFlaskManager.add_command('db', flask_migrate.MigrateCommand)\nFlaskManager.add_command('script', app.batch.batch)\n\n# register blueprints\napplication.register_blueprint(app.views.main)\napplication.register_blueprint(app.views.user, url_prefix='/user')\napplication.register_blueprint(app.views.post, url_prefix='/posts')\n\n# register middleware\nif application.config.get('PROFILER_ENABLE', False) is True:\n application.wsgi_app = ProfileMiddleware(\n application.wsgi_app,\n log_filename='./profilers/app.prof',\n cachegrind_filename='./profilers/app.gcf',\n discard_first_request=True,\n flush_at_shutdown=False,\n path='/__profile__',\n unwind=False)\n","sub_path":"repoze/app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"543158423","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Completion.\n\nCompletion descision logic.\n\n\"\"\"\n\nimport logging\n\nfrom . import settings\n\nlog = logging.getLogger(\"RTags\")\n\nclass PositionStatus:\n \"\"\"Enum class for position status.\n Taken from EasyClangComplete by Igor Bogoslavskyi\n\n Attributes:\n COMPLETION_NEEDED (int): completion needed\n COMPLETION_NOT_NEEDED (int): completion not needed\n WRONG_TRIGGER (int): trigger is wrong\n \"\"\"\n COMPLETION_NEEDED = 0\n COMPLETION_NOT_NEEDED = 1\n WRONG_TRIGGER = 2\n\ndef position_status(point, view):\n \"\"\"Check if the cursor focuses a valid trigger.\n\n Args:\n point (int): position of the cursor in the file as defined by subl\n view (sublime.View): current view\n\n Returns:\n PositionStatus: status for this position\n \"\"\"\n trigger_length = 1\n\n word_on_the_left = view.substr(view.word(point - trigger_length))\n if word_on_the_left.isdigit():\n # don't autocomplete digits\n log.debug(\"Trying to auto-complete digit, are we? Not allowed\")\n return PositionStatus.WRONG_TRIGGER\n\n # slightly counterintuitive `view.substr` returns ONE character\n # to the right of given point.\n curr_char = view.substr(point - trigger_length)\n wrong_trigger_found = False\n for trigger in settings.SettingsManager.get('triggers'):\n # compare to the last char of a trigger\n if curr_char == trigger[-1]:\n trigger_length = len(trigger)\n prev_char = view.substr(point - trigger_length)\n if prev_char == trigger[0]:\n log.debug(\"Matched trigger '%s'\", trigger)\n return PositionStatus.COMPLETION_NEEDED\n else:\n log.debug(\"Wrong trigger '%s%s'\", prev_char, curr_char)\n wrong_trigger_found = True\n\n if wrong_trigger_found:\n # no correct trigger found, but a wrong one fired instead\n log.debug(\"Wrong trigger fired\")\n return PositionStatus.WRONG_TRIGGER\n\n # if nothing fired we don't need to do anything\n log.debug(\"No completions needed\")\n return PositionStatus.COMPLETION_NOT_NEEDED\n","sub_path":"plugin/completion.py","file_name":"completion.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"304597105","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nimport numpy as np\nimport pandas as pd\nimport functions as func\nfrom selenium.webdriver.support.ui import Select\n\ndef run(PLZ='12435'):\n\n if int(PLZ)<10000:\n PLZ = '0' + PLZ\n\n URL = 'https://www.verivox.de/stromvergleich/vergleich/#/?persons=on&usage=2500&bonus=OnlyCompliant&profile=H0&product=electricity&plz=' + PLZ\n\n driver = webdriver.Firefox(executable_path='driver/geckodriver')\n driver.get(URL)\n\n results = func.wait_for_results(driver)\n\n columns=['cprice',\n 'bprice',\n 'price_total',\n 'postcode',\n 'rating',\n 'renew',\n 'name'\n ]\n data = pd.DataFrame(np.zeros((len(results), len(columns))),\n columns=columns)\n\n ind_rating = 0\n ind_price = 0\n\n for ind in np.arange(len(results)):\n func.show_details(driver, ind)\n\n data['postcode'][ind] = int(PLZ)\n # Get information from tab 0\n\n data['cprice'][ind] = func.get_info(driver, 'oit-value-annotation', 3*ind + ind_price)\n data['bprice'][ind] = func.get_info(driver, 'oit-value-annotation', 3*ind + 1 + ind_price, 0)\n price_all = [price for price in func.get_infos(driver, 'oit-value', 0) if price.endswith('Jahr')]\n data['price_total'][ind] = price_all[-1]\n ind_price = len(func.get_infos(driver, 'oit-value-annotation', 0)) - 3 * (ind + 1)\n\n # Get information from tab 4\n #func.scroll_to(driver, driver.find_elements_by_class_name('show-oit-trigger-tab-4')[ind])\n driver.find_elements_by_class_name('show-oit-trigger-tab-4')[ind].click()\n data['name'][ind] = func.get_info(driver, 'provider-name', ind)\n\n rating = (func.get_info(driver, 'average-ratings-container', ind - ind_rating, 0))\n if rating!=0:\n data['rating'][ind] = rating.replace('\\ue606',' ').replace('\\n', '; ').partition(';')[-1].partition(';')[-1].partition(';')[-1]\n else:\n ind_rating += 1\n data['rating'][ind] = rating\n\n # Get information from tab 3\n driver.find_elements_by_class_name('show-oit-trigger-tab-3')[ind].click()\n data['renew'][ind] = (func.get_info(driver, 'pie-chart-legend', ind))\n\n\n #func.hide_details(driver, ind)\n\n data.to_csv('data/'+PLZ+'.csv')\n driver.close()\n return 1","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"28618930","text":"from django.conf.urls import url\nfrom django.urls import path\n\nfrom . import views\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\napp_name = 'csp_prog_board'\n\nurlpatterns = [\n url(r'^$', views.Csp_prog_board.as_view(), name='csp_prog_board'),\n url(r'^insert/$', views.check_post, name='csp_prog_insert'),\n path('/detail/', views.csp_prog_detail, name='csp_prog_detail'),\n url(r'^(?P[0-9]+)/update/$', views.Csp_prog_update.as_view(), name='csp_prog_update'),\n url(r'^(?P[0-9]+)/delete/$', views.Csp_prog_delete.as_view(), name='csp_prog_delete'),\n url(r'^nop/$', views.Nop.as_view(), name='nop'),\n\n # QnA\n url(r'^qna/$', views.Csp_prog_board_qna.as_view(), name='csp_prog_board_qna'),\n url(r'^qna/insert/$', views.check_post_qna, name='csp_prog_insert_qna'),\n path('qna//detail/', views.csp_prog_detail_qna, name='csp_prog_detail_qna'),\n url(r'^qna/(?P[0-9]+)/update/$', views.Csp_prog_update_qna.as_view(), name='csp_prog_update_qna'),\n url(r'^qna/(?P[0-9]+)/delete/$', views.Csp_prog_delete_qna.as_view(), name='csp_prog_delete_qna'),\n\n #comment\n path('/detail/comment/delete//', views.comment_delete, name=\"comment_delete\"),\n path('comment/update//', views.comment_update, name=\"comment_update\"),\n path('qna//detail/comment/delete//', views.comment_delete_qna, name=\"comment_delete_qna\"),\n path('qna/comment/update//', views.comment_update_qna, name=\"comment_update_qna\"),\n\n #action\n path('close/', views.closed_page, name=\"closed_page\")\n]\n\nurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)","sub_path":"csp_prog_board/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"367046815","text":"import tensorflow as tf\n\ndef basic_params():\n '''A set of basic hyperparameters'''\n return dict(\n\n # File path\n # None or path to pretrained embedding\n pre_embedding=None,#'data/processed/glove_embedding.npy',\n\n # NN params\n voca_size=34004,\n embedding_size=300,\n embedding_trainable=True,\n hidden_size=512,\n cell_type='gru', # 'lstm' or 'gru'\n enc_type='mono', # 'bi' or 'mono'\n num_layer=1,\n dropout=0.4,\n attn='luong', # 'bahdanau', 'normed_bahdanau', 'luong', 'scaled_luong'\n beam_width=3,\n length_penalty_weight=2.1,\n\n # Extra params\n ##dtype=tf.float32,\n maxlen_s=60,\n maxlen_dec_train=32,\n maxlen_dec_dev=32,\n start_token=1, # index\n end_token=2, # index\n\n # Learning params\n batch_size=64,\n ##learning_rate=0.001,\n ##decay_step=None,\n ##decay_rate=0.5,\n ##sample_prob=0.25,\n )\n\n\ndef other_params():\n hparams = basic_params()\n hparams.voca_size = 30004\n hparams.embedding = None\n hparams.embedding_trainable = True\n hparams.hidden_size = 300\n hparams.encoder_layer = 1\n hparams.decoder_layer = 1\n\n hparams.rnn_dropout = 0.3\n\n hparams.batch_size = 128\n\n hparams['decay'] = 0.4 # learning rate decay factor\n return hparams\n","sub_path":"params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"513963249","text":"# coding:utf8\nfrom dao.user_dao import *\n\n\ndef warn(**kwargs):\n return {'success': False, 'message': '操作失败', 'info': 'warn'}\n\n\ndef user_info(**kwargs):\n user = kwargs.get('user', '')\n return db_get_user_info_by_name(user)\n\ndef set_info(**kwargs):\n params = {}\n for k in kwargs.items():\n if k[0] in ('user','user_id', 'user_name', 'user_type', 'state','reg_time', 'money',\n 'login_time', 'online', 'remark','qq','tel','mail'):\n if isinstance(k[1],list):\n params.update({k[0]:k[1][0]})\n else:\n params.update({k[0]: k[1]})\n result = db_set_user_info(**params)\n if result == True:\n return {'success':True}\n else:\n return {'success':False,'info':str(result)}\n\n\ndef set_pwd(**kwargs):\n user = kwargs.get('user','')\n old_pwd = kwargs.get('old_pwd',[''])[0]\n new_pwd = kwargs.get('new_pwd',[''])[0]\n if not db_verify_pwd(user,old_pwd):\n return {'success':False,'message':'密码错误'}\n result = db_set_user_password_by_name(user, new_pwd)\n if result:\n return {'success':True}\n else:\n return {'success':False,'info':str(result)}","sub_path":"util/user_operation.py","file_name":"user_operation.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"235583227","text":"import os\nimport fnmatch\nimport subprocess\ndef execute(root_path):\n for dirpath, _, filenames in os.walk(root_path):\n for filename in filenames:\n if fnmatch.fnmatch(filename, u\"*.pdf\"):\n convert_dir=\"./convert_image/\"+filename[:-4]\n if os.path.exists(convert_dir):\n #os.rmdir(convert_dir)\n os.system(\"rm -r {}\".format(convert_dir))\n os.mkdir(convert_dir)\n org_path = os.path.join(dirpath, filename)\n png_path=convert_dir+\"/\"+filename.replace(\".pdf\", \".jpeg\")\n print(\"convert {0} to {1}\".format(org_path, png_path))\n #指令更多样\n if subprocess.call([\"convert\",\n \"-verbose\",\n #\"-trim\",\n \"-density\",\"150\",\n #\"-quality\",\"100\",\n #\"-append\",\n \"-alpha\",\"remove\",\n #\"-flatte\",\n #\"-sharpen\",\"0x1.0\",\n org_path,\n png_path]) != 0:\n print(\"failed: {0}\".format(org_path))\n #集成功能\n # convert_pdf_to_jpg(org_path,png_path)\nif __name__ == '__main__':\n #root_path = input(\"target folder path> \")\n root_path=\"./target_pdf\"\n execute(root_path)\n\n\n","sub_path":"page_layout/PDF2Image.py","file_name":"PDF2Image.py","file_ext":"py","file_size_in_byte":1526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"329970396","text":"#4. The purchase price and current price of a stock is entered into yourprogram.\n#Display the percentage increase or decrease of the stock.\n\n#gets the original purchase price from the user\npurchasePrice = eval(input('Enter the price of the stock when you bought it: '))\n\n#gets the current price of the stock from the user\ncurrentPrice = eval(input('Enter the current price of the stock: '))\n\n#computes the difference in price from the original purchase price to now\nnewPrice = purchasePrice - currentPrice\n\n#computes the rate of change between the current price and the original price\npercentageChange = newPrice / purchasePrice\n\nif newPrice > 0:\n print('Your stock went down by {}%'.format(percentageChange * 100))\nelif newPrice < 0:\n print('Your stock went up by {}%'.format(percentageChange * 100))\nelse:\n print('Your stock has not changed')\n\n\n\n","sub_path":"Python/problemSet1/Solution4.py","file_name":"Solution4.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"106889869","text":"def scan(string):\n KEY_WORDS = [\"Const\", \"Var\", \"if\", \"else\", \"then\",\"while\", \"do\", \"begin\", \"end\"]\n SYMBOLS = [',', '+', '-', '*', '/', ';', '(' ,')' ,'{' ,'}', '==', '<=', '>=', '<>', '<', '>', '=']\n word_map = {key: i+1 for i, key in enumerate(KEY_WORDS)}\n word_map.update({key: i+21 for i, key in enumerate(SYMBOLS)})\n def process(string):\n word = ''\n if ' ' in string:\n for s in string.split(' '):\n word += s\n else:\n word = string\n if '//' in word:\n return word.split('//')[0]\n return word\n\n def have_keywords(word):\n for keyword in KEY_WORDS:\n if keyword in word:\n return keyword\n return None\n\n def have_symbol(word):\n for sy in SYMBOLS:\n if sy in word:\n return sy\n return None\n\n def is_alpha(ch):\n return (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z')\n\n def is_digit(ch):\n return ch >= '0' and ch <= '9'\n\n # def is_in_symbols(c):\n # return c in SYMBOLS\n\n # def is_keywords(c):\n # return c in KEY_WORDS\n\n\n queue = [process(string)]\n if '/*' in queue[0] or '*/' in queue[0]:\n return \n stop = False\n while not stop:\n changed = False\n tempQueue = []\n for item in queue:\n key = have_keywords(item)\n sy = have_symbol(item)\n if key and key != item:\n changed = True\n item1, item2 = item.split(key)\n if item1:\n tempQueue.append(item1)\n tempQueue.append(key)\n if item2:\n tempQueue.append(item2)\n continue\n elif sy and sy != item:\n changed = True\n sp = item.split(sy)\n for i, it in enumerate(sp):\n if it:\n tempQueue.append(it)\n if i != len(sp) - 1:\n tempQueue.append(sy)\n \n else:\n tempQueue.append(item)\n\n if item == queue[-1] and not changed:\n stop = True\n queue = tempQueue.copy()\n for item in queue:\n if item in word_map:\n print(\"<\", item, \",\", word_map[item],\">\")\n else:\n if item and is_alpha(item[0]):\n print(\"<\", item, \",\", 15,\">\")\n if item and is_digit(item[0]):\n print(\"<\", item, \",\", 16,\">\")\n\ndef main():\n with open('./test.cpp', 'r') as r_stream:\n for line in r_stream:\n if line:\n if '\\n' in line:\n scan(line[0:-1])\n else:\n scan(line)\n\nmain()","sub_path":"CPlab2_LexicalAnalysis/LexicalAnalysis.py","file_name":"LexicalAnalysis.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"492416192","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: Xiaoqing\n\"\"\"\n\nimport sys\nimport math\nimport bisect\n\ndef getdata(line):\n# read all data from a line. If there's any error, return None \n data = line.rstrip('\\n').rsplit('|')\n try:\n Other = data[15]\n if Other == \"\":\n CMTE = data[0]\n else:\n CMTE = None\n year = getyear(data[13])\n name = getname(data[7].rstrip())\n zipcode = getzip(data[10])\n AMT = getAMT(data[14])\n return CMTE, year, name, zipcode, AMT\n except:\n return None, None, None, None, None\n\ndef getyear(date):\n#Get the year from date string. We could use time.strptime to be more robust, but it would be ~20 times slower.\n if len(date) == 8:\n try:\n# time.strptime(date, \"%m%d%Y\")\n year = date[4:]\n if int(year)<2019 and int(year)>2014:\n return year\n except:\n return None\n else:\n return None\n \ndef getzip(zipcode):\n# check if zipcode is valid. Here we simply check whether the first 5 digits is a integer.\n if len(zipcode)>=5:\n try:\n int(zipcode[:5])\n return zipcode[:5]\n except:\n return None\n else:\n return None\n \ndef getname(name):\n# check if the name is valid. This can be very tricky, as there are so many edge cases.\n# I kid you not, I know a Chinese Mongolian who writes his name as \"A, A\".\n# Anyway, here we define a valid name string as: has at least a first and a last name separated by a \",\"\n# which consist of only alphabets except for whitespaces and \".\" (for possible middle name). \n try:\n name = name.replace(\" \",\"\")\n name = name.replace(\".\",\"\")\n firstname, lastname = name.rsplit(\",\")\n if firstname.isalpha() and lastname.isalpha():\n return name\n else: \n return None\n except:\n return None\n\n \ndef getAMT(AMTstr):\n try:\n AMT = math.floor(float(AMTstr)+0.5)\n return AMT\n except:\n return None\n \ndef percentile(N, P):\n# Nearest rank method for percentile calculation.\n n = max(int(math.ceil(P * len(N))), 1)\n return N[n-1]\n\ndef readpercf(percentf):\n# read the percentile number from file.\n with open(percentf, \"r\") as f:\n return int(f.readline().rstrip('\\n'))/100\n \ndef main(inputf, percentf, outputf):\n \n donorlist = set()\n recipientDict = {}\n output = \"\"\n percent = readpercf(percentf)\n \n with open(inputf, \"r\") as f: \n for line in f:\n\n CMTE, year, name, zipcode, AMT = getdata(line) \n if None in [CMTE, year, name, zipcode, AMT]:\n continue\n \n donorID = name+zipcode\n recID = \"|\".join([CMTE, zipcode, year])\n \n if donorID in donorlist:\n try: \n bisect.insort(recipientDict[recID],AMT) \n except: \n recipientDict[recID] = [AMT]\n number = str(len(recipientDict[recID]))\n total = str(sum(recipientDict[recID]))\n perc = str(percentile(recipientDict[recID],percent))\n output+= \"|\".join([recID, perc, total, number])+\"\\n\"\n else:\n donorlist.add(donorID)\n \n with open(outputf, \"w\") as f:\n f.write(output)\n\n \nif __name__==\"__main__\":\n main(str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3]))","sub_path":"insight_testsuite/temp/src/donation-analytics.py","file_name":"donation-analytics.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"72166192","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 22 15:34:43 2020\r\n\r\n@author: Harry Anthony\r\n\"\"\"\r\n\r\nimport scipy as sp\r\nfrom scipy.io.wavfile import read\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import signal\r\n\r\nfilename = \"19-11-2020-wound_non_held1.wav\" #edit filename as appropriate\r\n\r\n# read audio samples\r\ninput_data = read(filename)\r\nsignal = input_data[1]\r\nsampling_freq = input_data[0]\r\nsampling_freq = 44100\r\ntime = np.arange(len(signal))/sampling_freq\r\n\r\n\r\nwindow = np.hamming(len(signal)*2)\r\nwindow = window[int(len(signal)):len(signal)*2]\r\nsignal = signal * window\r\n\r\ndef plot_data(start_time,end_time):\r\n #function to plot data between start_time and end_time\r\n \r\n time_index1 = time.tolist().index(start_time)\r\n time_index2 = time.tolist().index(end_time)\r\n plt.figure()\r\n plt.plot(time[time_index1:time_index2+1],signal[time_index1:time_index2+1])\r\n plt.ylabel(\"Amplitude [a.u.]\")\r\n plt.xlabel(\"Time (s)\")\r\n plt.title(\"Recorded Signal\")\r\n plt.show()\r\n\r\ndef FT_data(data,sampling_rate):\r\n global freq, FTdata, freq_index1, freq_index2\r\n #function to calcuate and display absolute value of Fourier Transform\r\n \r\n freq = 0.5 * sampling_rate * np.linspace(-1.0, 1.0, len(data))\r\n FTdata = np.fft.fftshift(np.fft.fft(np.fft.fftshift(data)))\r\n \r\n freq_index1 = np.amin(np.where(freq >= 0))\r\n freq_index2 = np.amin(np.where(freq >= 10000))\r\n print(freq_index2)\r\n \r\n plt.figure()\r\n plt.plot(freq[freq_index1:freq_index2+1],abs(FTdata[freq_index1:freq_index2+1]))\r\n plt.ylabel(\"Magnitude [a.u.]\")\r\n plt.xlabel('Frequency (nx71.861)Hz')\r\n plt.title(\"Absolute Value of Fourier Transform\")\r\n plt.xlim(0,5)\r\n plt.xticks(np.arange(0,1000,71.861),[0,1,2,3,4,5,6,7,8,9,10,11,12,13])\r\n plt.savefig('Wound_wire_Fourier.png')\r\n plt.show()\r\n\r\nplot_data(time[0],time[-1]) #plot signal in time window defined by 2 values\r\nFT_data(signal,sampling_freq) #Fourier Transfomr and plot absolute value\r\n\r\n\r\n\r\n#%%\r\n\r\nfreq = 0.5 * sampling_freq * np.linspace(-1.0, 1.0, len(signal))\r\nFTdata = np.fft.fftshift(np.fft.fft(np.fft.fftshift(signal)))\r\n\r\n#Non-wound string\r\n#frequencies_to_isolate = [145.715,291.620,435.642,579.238,731.638,872.039,1027.275,1165.317,1325.839]\r\n#Wound string\r\nfrequencies_to_isolate = [71.861,143.638,218.328,290.139,364.6279,436.461,511.9279,588.7723,660.5835,732.4057,876.228,962.9835]\r\n\r\nz = 0\r\nwhile z\nAdapted from:\n\t\tMainak Jas \n \tSam Neymotin \n\n'''\n\n###############################################################################\n# Imports and setup\n\nimport os.path as op\nimport os, shutil\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport multiprocessing as mp\n\nimport hnn_core\nfrom hnn_core import simulate_dipole, read_params, read_dipole, Network\n\n# Directories and Neuron\nhnn_core_root = op.join(op.dirname(hnn_core.__file__), '..')\n\n\n###############################################################################\n# User-defined variables\nstartingParameterFile = 'AlphaAndBeta_testScript.param'\nparamsOfInterest = ['input_prox_A_weight_L2Pyr_ampa', \n\t'input_prox_A_weight_L5Pyr_ampa',\n\t'input_dist_A_weight_L2Pyr_ampa',\n\t'input_dist_A_weight_L5Pyr_ampa']\nparamMin = 0.1e-5\nparamMax = 9.4e-5\nnumberOfSteps = 10\nparameterScale = 'linear'\n\ndplDirName = 'pyr_ampa'\n\nplotOK = True\n\n# Folder for storing dipole txt files\noutDir = '/Users/tbardouille/Documents/Work/Projects/Spectral Events/HNN/Data'\n\n###############################################################################\n# Functions\ndef adjust_param_and_simulate_dipole(thisParams, paramsOfInterest, paramValue, outDir):\n\n\tfor paramOfInterest in paramsOfInterest:\n\t\tthisParams.update({paramOfInterest: paramValue})\n\n\tprint(thisParams)\n\n\tnet = Network(thisParams)\n\tdpl = simulate_dipole(net)\n\n\treturn dpl\n\ndef adjust_param_and_simulate_dipole_mp(paramValue):\n\n\tfor paramOfInterest in paramsOfInterest:\n\t\tparams.update({paramOfInterest: paramValue})\n\n\tnet = Network(params)\n\tdpl = simulate_dipole(net)\n\n\tout_fname = op.join(dplPath, \"{0:.5e}.txt\".format(paramValue))\n\n\tdpl[0].write(out_fname)\n\n\treturn dpl\n\ndef read_dipoles_over_range(parameterValues, plotOK):\n\t\n\t# Read simulations\n\tdpls = []\n\tfor p in parameterValues:\n\t\tfname = op.join(dplPath, \"{0:.5e}.txt\".format(p))\n\t\tdpls.append(read_dipole(fname))\n\n\tif plotOK:\n\t\t# Plot the results for all parameter values\n\t\tdipAmp = []\n\t\tfor dpl in dpls:\n\t\t\tdipAmp.append(dpl.dpl['agg'])\n\t\tdipAmp = np.asarray(dipAmp).T\n\t\tplt.plot(dpls[0].t, dipAmp)\n\t\tplt.xlim(50, 700)\n\t\tplt.ylim(-500,500)\n\t\tplt.xlabel('Time [ms]')\n\t\tplt.ylabel('Dipole Strength [nAm]')\n\t\tplt.legend(parameterValues)\n\t\tplt.show()\n\n\treturn dpls\n\ndef get_smoothed_ranges(parameterValues, dpls):\n\n\tranges = []\n\tfor dpl in dpls:\n\t\t# Note: skip the 0th sample here due to its offset\n\t\tdipAmp_sorted = np.sort(dpl.dpl['agg'][1::])\n\t\tranges.append(np.mean(dipAmp_sorted[-11:-1]) - np.mean(dipAmp_sorted[0:10]))\n\n\tif plotOK:\n\t\tplt.plot(parameterValues, ranges)\n\t\tplt.xlabel('Parameter Value')\n\t\tplt.ylabel('Dipole Value Range [nAm]')\n\t\tplt.show()\n\n\treturn ranges\n\n#Function returns maximum correlation coefficient, temporal shift to give max corr and number of local maxima\ndef get_outputs(parameterValues, dpls):\n \n correlations = []\n temporal_shifts = [] \n num_maximas = []\n\n for dpl in dpls:\n #Start by finding the number of local maxima in the signal \n num_maxima = len(ss.find_peaks(new_vals)[0])\n \n #Now if I have to systematically shift the new data I can do this:\n new_vals = dpl.dpl['agg'][1::]\n sub_corrs = []\n\n for x in range(0,710):\n #This takes the 40th sample until the end of the array - 40 is chosen becuase there are 40 samples of data/ ms and I want to shift it 1 ms at a time\n new_vals = new_vals[40:]\n #When you do this you have to zero pad the end of the array with 40 zeros so it is the same length as the one you are comparing it to \n new_vals = np.pad(new_vals, (0,40), 'constant')\n \n #Calculate the correlation coefficient matrix between values \n corr_coef = np.corrcoef(init_vals, new_vals)\n \n #Pull out the single corrcoef value of interest \n corr_coef = corr_coef[0,1]\n sub_corrs.append(corr_coef)\n \n #find the maximum correlation coefficient\n max_corr = max(sub_corrs)\n #find the shift that corresponds to the maximum correlation\n shift = np.where(sub_corrs==max(sub_corrs))[0][0] \n \n #append the max correlation and associated shift to lists\n correlations.append(max_corr)\n temporal_shifts.append(shift)\n num_maximas.append(num_maxima)\n \n if plotOK:\n #Plot the correlations versus the input vals (delays in start times)\n plt.plot(parameterValues, correlations)\n plt.xlabel('Start times (ms)')\n plt.ylabel('Max Correlation Coefficient')\n\n #Plot the temporal shift versus the input vals (delays in start times)\n plt.plot(parameterValues, temporal_shifts)\n plt.xlabel('Delay (ms)')\n plt.ylabel('Temporal Shift (ms)')\n\n #Plot the number of local maxima versus the input vals (delays in start times)\n plt.plot(parameterValues, num_maximas)\n plt.xlabel('Delay (ms)')\n plt.ylabel('Number of Local Maxima')\n \n return correlations, temporal_shifts, num_maximas\n \n\n###############################################################################\n# Main Program\n\n# Read the default parameter file \nparams_fname = op.join(hnn_core_root, 'param', startingParameterFile)\nparams = read_params(params_fname)\n\n# Setup parameter range\nif parameterScale == 'linear':\n\tparameterValues = np.linspace(paramMin, paramMax, numberOfSteps, endpoint=True)\nif parameterScale == 'log':\n\tparameterValues = np.logspace(paramMin, paramMax, numberOfSteps, endpoint=True)\n\n'''\n# Run simulations consecutively\n# Loop over parameter range and generate dipole simulations\ndpls = []\nfor p in parameterValues:\n\tdpls.append(adjust_param_and_simulate_dipole(params, paramsOfInterest, p, outDir))\n'''\n\n# Run simulations in parallel\n# Make the folder for the dpl files\ndplPath = op.join(outDir, dplDirName)\nif not os.path.exists(dplPath):\n os.makedirs(dplPath)\nelse:\n\t# Remove all the subdirectories first\n shutil.rmtree(dplPath) \n os.makedirs(dplPath)\n# Set up the parallel task pool for dipole simulations\ncount = int(np.round(mp.cpu_count()*1/2))\nprint(count)\npool = mp.Pool(processes=count)\n# Run the jobs\npool.map(adjust_param_and_simulate_dipole_mp, parameterValues)\n\n# Read simulated dipole timecourses for all parameter values\ndpls = read_dipoles_over_range(parameterValues, plotOK)\n\n# Read smoother dipole amplitude ranges for parameters\nranges = get_smoothed_ranges(parameterValues[0:-1], dpls[0:-1])\n\n#Calculate outputs for parameter\ncorrelations, temporal_shifts, num_maximas = get_outputs(parameterValues[0:-1], dpls[0:-1])\n\n\n","sub_path":"scripts/simulate_over_range_withOutputFunction.py","file_name":"simulate_over_range_withOutputFunction.py","file_ext":"py","file_size_in_byte":6743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"373742635","text":"def convert (jam, base):\n num = 0\n mul = len(jam) - 1\n for i in jam:\n num = num + int(i) * base**mul\n mul = mul - 1\n return num\n\ndef isPrime (num):\n for i in range(2, int(num/2) + 1):\n if (i > 100):\n #well, not really, but it's not worth exploring further\n return 1\n if (num % i) == 0:\n return i\n return 1\n\ndef fits (coin):\n divs = [];\n for i in range(2, 11):\n noDiv = isPrime(convert(coin, i))\n if (noDiv == 1):\n return 0\n else:\n divs.append(str(noDiv))\n return divs\n\ndef next (cur):\n leng = len(cur) - 2\n now = cur[1:-1]\n part = str(bin(convert(now, 2) + 1))[2:]\n after = '1' + '0'*(leng - len(part)) + part + '1'\n return after\n\ndef produce (length, many):\n num = '1' + '0'*(length-2)+ '1'\n list1 = [];\n list2 = [];\n \n while (many):\n divs = fits(num)\n if (divs):\n list1.append(num)\n list2.append(divs)\n many = many - 1\n num = next(num)\n if (len(num) > length):\n break\n \n return list1, list2\n\nlist1, list2 = produce(32, 500)\n\ng = open('C-large.out', 'w')\ng.write('Case #1:\\n')\n\nfor i in range(0, len(list1)):\n g.write(str(list1[i]) + \" \" + \" \".join(list2[i]) + '\\n')\n\ng.close()\n\n","sub_path":"codes/CodeJamCrawler/16_0_3_neat/16_0_3_ash6ap_ex3.py","file_name":"16_0_3_ash6ap_ex3.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"75433225","text":"import time\nstart = time.time()\nimport argparse\nimport cv2\nimport itertools\nimport os\nimport numpy as np\nimport sys\n# sys.path.insert(0, '../../../openface-master')\nimport facecompare.openface as openface\nimport pickle\n\nnp.set_printoptions(precision=2)\nfileDir = os.path.dirname(os.path.realpath(__file__))\nmodelDir = os.path.join(fileDir, '..', 'models')\ndlibModelDir = os.path.join(modelDir, 'dlib')\nopenfaceModelDir = os.path.join(modelDir, 'openface')\nparser = argparse.ArgumentParser()\ndlibFacePredictor = os.path.join(dlibModelDir, \"shape_predictor_68_face_landmarks.dat\")\nnetworkModel = os.path.join(openfaceModelDir, 'torch_models/nn4.small1.v1.t7')\nprint(networkModel)\nimgDim = 96\nverbose = False\nrgbImg = 0\n\nif verbose:\n print(\"Argument parsing and loading libraries took {} seconds.\".format(\n time.time() - start))\n\nstart = time.time()\nalign = openface.AlignDlib(dlibFacePredictor)\nnet = openface.TorchNeuralNet(networkModel, imgDim)\n\nif verbose:\n print(\"Loading the dlib and OpenFace models took {} seconds.\".format(\n time.time() - start))\n\n#Compare faces\ndef facecompare(selfie,proof):\n start = time.time()\n print(\"Face compare initiated\")\n selfie_rep = getRep(selfie,1)\n status = selfie_rep['status']\n if status != 200:\n return selfie_rep\n\n proof_rep = getRep(proof,2)\n status = proof_rep['status']\n if status != 200:\n return proof_rep\n \n score = faceDistanceScore(selfie_rep['rep'],proof_rep['rep'])\n print(\"Face Score \" , score)\n print(\"Facecompare total time took {} seconds.\".format(\n time.time() - start))\n return {\"status\":200,\"score\" : score, \"s_rep\":selfie_rep['rep'],\n \"s_image\" :selfie_rep['image'],\"p_image\":proof_rep['image'],\"p_c_image\":proof_rep['c_image']}\n\ndef getFaceRep(selfie):\n selfie_rep = getRep(selfie,1)\n status = selfie_rep['status']\n return selfie_rep\n\ndef faceDistanceScore(source_rep , test_rep):\n d = source_rep - test_rep\n score = format(np.dot(d, d))\n return score\n\n\n#Similarity between the two face\ndef findCosineSimilarity(source_representation, test_representation):\n a = np.matmul(np.transpose(source_representation), test_representation)\n b = np.sum(np.multiply(source_representation, source_representation))\n c = np.sum(np.multiply(test_representation, test_representation))\n return 1 - (a / (np.sqrt(b) * np.sqrt(c)))\n\ndef getFaceBoundingBoxes(bgrImg):\n global rgbImg\n rgbImg = cv2.cvtColor(bgrImg, cv2.COLOR_BGR2RGB)\n \n if verbose:\n print(\" + Original size: {}\".format(rgbImg.shape))\n \n start = time.time()\n bb = align.getLargestFaceBoundingBox(rgbImg)\n return bb\n\n#Get face representation\ndef getRep(img, fromwhere):\n processtime = time.time()\n # print(\"Rep Thread process started \",fromwhere)\n response = {}\n response['status'] = 200\n if verbose:\n print(\"Processing {}.\".format(img))\n # convert string data to numpy array\n npimg = np.fromstring(img, np.uint8)\n # convert numpy array to image\n image = cv2.imdecode(npimg, 1)\n bgrImg = image #cv2.imread(imgPath) \n if bgrImg is None:\n response['status'] = 500\n response['message'] = \"Unable to load image\"\n return response\n\n i = 0\n while i < 4:\n if i == 0:\n bb = getFaceBoundingBoxes(bgrImg)\n if bb is not None:\n break\n if i == 1:\n bgrImg = cv2.rotate(bgrImg, cv2.ROTATE_90_CLOCKWISE)\n bb = getFaceBoundingBoxes(bgrImg)\n if bb is not None:\n break\n if i == 2:\n bgrImg = cv2.rotate(bgrImg, cv2.ROTATE_90_CLOCKWISE)\n bb = getFaceBoundingBoxes(bgrImg)\n if bb is not None:\n break\n if i == 3:\n bgrImg = cv2.rotate(bgrImg, cv2.ROTATE_90_CLOCKWISE)\n bb = getFaceBoundingBoxes(bgrImg)\n if bb is not None:\n break\n i = i + 1\n\n if bb is None:\n response['noface'] = fromwhere\n response['status'] = 500\n response['message'] = \"Unable to find a face,kindly retake again\"\n return response\n\n response['image'] = bgrImg\n\n cv2.rectangle(bgrImg, (bb.left(), bb.top()), (bb.right(), bb.bottom()), (0,255,255), 2)\n\n crop_img = bgrImg[ bb.top():bb.bottom(), bb.left():bb.right()]\n\n # cv2.imshow(\"image\", crop_img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n if verbose:\n print(\" + Face detection took {} seconds.\".format(time.time() - start))\n\n start = time.time()\n alignedFace = align.align(imgDim, rgbImg, bb,\n landmarkIndices=openface.AlignDlib.OUTER_EYES_AND_NOSE)\n if alignedFace is None:\n response['status'] = 500\n response['message'] = \"Unable to align image\"\n return response\n if verbose:\n print(\" + Face alignment took {} seconds.\".format(time.time() - start))\n\n start = time.time()\n # print(\"rep started\")\n # print(\"SHAPE:\", alignedFace.shape)\n rep = net.forward(alignedFace)\n # print(\"rep\",rep)\n if verbose:\n print(\" + OpenFace forward pass took {} seconds.\".format(time.time() - start))\n print(\"Representation:\")\n print(rep)\n print(\"-----\\n\")\n response['rep'] = rep\n response['c_image'] = crop_img\n # print(fromwhere, \" Thread Process total time took {} seconds.\".format(time.time() - processtime))\n return response\n\n\n\n\ndef cropFaces(image):\n print(type(image))\n selfie_rep = getRep(image,1)\n if(selfie_rep['status']==200):\n return True\n else:\n return False","sub_path":"facecompare/demos/face_compare.py","file_name":"face_compare.py","file_ext":"py","file_size_in_byte":5599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"490215452","text":"import os\nfrom unittest import TestCase\n\nfrom mock import MagicMock\n\nfrom bgm.MusicStateMachine import MusicStateMachine, MusicState\n\n\nclass BgmShould(TestCase):\n def test_play_music_if_ES_is_running(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingProcessesAreRunning(\"emulationstatio\") \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertASongFromTheDirectoryIsBeingPlayed(self)\n\n def test_fade_down_music_by_pausing_if_Emulator_is_running_and_a_song_is_being_played(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingProcessesAreRunning(\"emulationstatio\") \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .anEmulatorIsRunning() \\\n .pauseOnEmulatorRun() \\\n .aSongIsBeingPlayed() \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertMusicHasFadeDown(pause=True)\n\n def test_fade_down_music_by_not_pausing_if_Emulator_is_running_and_a_song_is_being_played(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingProcessesAreRunning(\"emulationstatio\") \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .anEmulatorIsRunning() \\\n .aSongIsBeingPlayed() \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertMusicHasFadeDown(pause=False)\n\n def test_fade_up_music_if_Emulator_is_not_running_and_ES_is_running_and_music_is_paused(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingProcessesAreRunning(\"emulationstatio\") \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .aSongIsPaused() \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertMusicHasFadeUp()\n\n def test_play_another_song_if_song_has_ended(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingProcessesAreRunning(\"emulationstatio\") \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .musicWasBeingPlayed() \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertASongFromTheDirectoryIsBeingPlayed(self)\n\n def test_stop_music_if_music_is_disabled(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingProcessesAreRunning(\"emulationstatio\") \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .theMusicIsDisabled() \\\n .aSongIsBeingPlayed()\\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertMusicHasBeenStopped()\n\n def test_do_nothing_if_ES_is_not_running_but_emulator_is_running(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .anEmulatorIsRunning() \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertNothingHasBeenDone()\n\n def test_stop_music_if_ES_nor_emulator_are_running(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .aSongIsBeingPlayed()\\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertMusicHasBeenStopped()\n\n def test_do_nothing_if_ES_is_running_but_a_song_is_already_playing(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingProcessesAreRunning(\"emulationstatio\") \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .aSongIsBeingPlayed() \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertNothingHasBeenDone()\n\n def test_do_nothing_if_emulator_is_running_and_silent(self):\n scenario_maker = self._ScenarioMaker()\n app = scenario_maker \\\n .theFollowingSongsArePresent(['file1.ogg', 'file2.ogg', 'file3.ogg']) \\\n .anEmulatorIsRunning() \\\n .build()\n\n app.execute_state()\n\n scenario_maker.assertNothingHasBeenDone()\n\n class _ScenarioMaker:\n def __init__(self):\n self.forced_state = None\n\n self.processService = MagicMock()\n self.processService.any_process_is_running = MagicMock(return_value=False)\n self.processService.find_pid = MagicMock(return_vale=-1)\n self.processService.process_is_running = MagicMock(side_effect=lambda x: False)\n self.config = MagicMock()\n\n self.restart = True\n\n self.musicPlayer = MagicMock()\n self.musicPlayer.is_playing = False\n self.musicPlayer.is_paused = False\n os.path.exists = MagicMock(return_value=False)\n\n def aSongIsBeingPlayed(self):\n self.musicPlayer.is_playing = True\n return self\n\n def theFollowingProcessesAreRunning(self, *processes):\n self.processService.process_is_running = MagicMock(side_effect=lambda x: x in processes)\n return self\n\n def anEmulatorIsRunning(self):\n self.processService.any_process_is_running = MagicMock(return_value=True)\n return self\n\n def pauseOnEmulatorRun(self):\n self.restart = False\n return self\n\n def aSongIsPaused(self):\n self.musicPlayer.is_paused = True\n return self\n\n def theFollowingSongsArePresent(self, songs):\n os.listdir = MagicMock(return_value=songs)\n return self\n\n def theMusicIsDisabled(self):\n os.path.exists = MagicMock(side_effect=lambda _: True)\n return self\n\n def musicWasBeingPlayed(self):\n self.forced_state = MusicState.playingMusic\n return self\n\n def build(self):\n default_config = {\n \"startdelay\": 0,\n \"musicdir\": '/home/pi/RetroPie/music',\n \"restart\": self.restart,\n \"startsong\": \"\"\n }\n\n self.config.getboolean.side_effect = lambda x, y: default_config[y]\n self.config.getint.side_effect = lambda x, y: default_config[y]\n self.config.get.side_effect = lambda x, y: default_config[y]\n\n return MusicStateMachine(self.processService, self.musicPlayer, self.config, self.forced_state)\n\n def assertASongFromTheDirectoryIsBeingPlayed(self, test):\n args, kwargs = self.musicPlayer.play_song.call_args\n test.assertTrue(args[0] in [os.path.join('/home/pi/RetroPie/music', 'file1.ogg'),\n os.path.join('/home/pi/RetroPie/music', 'file2.ogg'),\n os.path.join('/home/pi/RetroPie/music', 'file3.ogg')])\n self.musicPlayer.play_song.assert_called_once()\n\n def assertMusicHasFadeDown(self, pause):\n self.musicPlayer.fade_down_music.assert_called_once_with(pause)\n\n def assertMusicHasFadeUp(self):\n self.musicPlayer.fade_up_music.assert_called_once()\n\n def assertMusicHasBeenStopped(self):\n self.musicPlayer.stop.assert_called_once()\n\n def assertNothingHasBeenDone(self):\n self.musicPlayer.stop.assert_not_called()\n self.musicPlayer.fade_up_music.assert_not_called()\n self.musicPlayer.fade_down_music.assert_not_called()\n self.musicPlayer.play_song.assert_not_called()\n\n","sub_path":"test/test_bgm.py","file_name":"test_bgm.py","file_ext":"py","file_size_in_byte":7871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"576055306","text":"'''\n5 2\n2 5\n1 3\n'''\nfrom collections import defaultdict\nclass DisjointSet(object):\n def __init__(self):\n self.parent = None\n\n def find(self):\n if self.parent is None: return self\n return self.parent.find()\n\n def union(self, other):\n them = other.find()\n us = self.find()\n if them != us:\n us.parent = them\n\n\nm, n = [int(x) for x in input().split()]\nnodes = []\nfor _ in range(n):\n l, r = [int(x) for x in input().split()]\n while l <= r and r :\n a = l\n b = r\n if a != b:\n nodes.append([a, b])\n nodes.append([b, a])\n l += 1\n r -= 1\n\ndef count_components(nodes):\n sets = {}\n for node in nodes:\n sets[node[0]] = DisjointSet()\n for node in nodes:\n for vtx in node:\n sets[node.union(sets[vtx])]\n return len(set(x.find() for x in sets.itervalues()))\n\nclass DisjointSet(object):\n def __init__(self):\n self.parent = None\n\n def find(self):\n if self.parent is None: return self\n return self.parent.find()\n\n def union(self, other):\n them = other.find()\n us = self.find()\n if them != us:\n us.parent = them\n\nprint(count_components(nodes))\n\n\n\n\n\n\n\n","sub_path":"HackerEarth/classic_task.py","file_name":"classic_task.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"388522321","text":"# /**\n# * @Author: skhe\n# * @DateTime: 2016-02-19 16:03:50\n# * @Description: Description\n# */\n\nclass Student(object):\n\t\"\"\"学生成绩管理器——记录一个班级的学生(创建一个Student类,记录他们的名字、平均分和考试分数)和他们的成绩等级。根据学生的测验和作业的分数计算出平均分和成绩等级。复杂一点可以将数据画在贝尔曲线上。\"\"\"\n\tdef __init__(self, name, grades):\n\t\tsuper(Student, self).__init__()\n\t\tself.name = name\n\t\tself.grades = grades\n\t\tself.average = sum(grades[0:3]) / 3\n\n\tdef get_grade(self):\n\t\treturn self.average * 0.7 + self.grades[-1] * 0.3\n\nBob = Student('Bob', [89, 90, 91 ,60])\nprint(Bob.name, Bob.grades ,Bob.average ,Bob.get_grade())","sub_path":"class/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"604834369","text":"#!/usr/bin/env python\n\"\"\"Split appliapp.\"\"\"\nimport copy\nimport logging\n\nfrom applicake.base.coreutils.arguments import Argument\nfrom applicake.base.coreutils.info import get_handler\nfrom applicake.base.app import BasicApp\nfrom applicake.base.coreutils.keys import Keys, KeyHelp\n\n\nclass Split(BasicApp):\n \"\"\"Split appliapp.\"\"\"\n def add_args(self):\n return [\n Argument(Keys.ALL_ARGS, KeyHelp.ALL_ARGS),\n Argument(Keys.SPLIT, KeyHelp.SPLIT),\n Argument(Keys.SPLIT_KEY, KeyHelp.SPLIT_KEY)\n ]\n\n def run(self, info):\n basename = info[Keys.SPLIT]\n key = info[Keys.SPLIT_KEY]\n value = info.get(key, \"\")\n if not isinstance(value, list):\n value = [value]\n\n info = info.copy()\n del info[Keys.SPLIT]\n del info[Keys.SPLIT_KEY]\n\n if info.get(Keys.SUBJOBLIST, \"\") == \"\":\n info[Keys.SUBJOBLIST] = []\n\n for i, val in enumerate(value):\n infocopy = copy.deepcopy(info)\n infocopy[key] = val\n infocopy[Keys.SUBJOBLIST].append(\"%s%s%d%s%d\" % (key, Keys.SUBJOBSEP, i, \\\n Keys.SUBJOBSEP, len(value)))\n path = basename + \"_\" + str(i)\n logging.debug(\"Writing split file %s\", path)\n get_handler(basename).write(infocopy, path)\n\n return info\n\n\nif __name__ == \"__main__\":\n Split.main()\n","sub_path":"appliapps/flow/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"346637707","text":"\"\"\"Plot to test line styles\"\"\"\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef main():\n fig, ax = plt.subplots(subplot_kw=dict(axisbg='#EEEEEE'))\n N = 100\n\n ax.scatter(np.random.normal(size=N),\n np.random.normal(size=N),\n c=np.random.random(size=N),\n s = 1000 * np.random.random(size=N),\n alpha=0.3,\n cmap=plt.cm.jet)\n ax.grid(color='white', linestyle='solid')\n\n ax.set_title(\"Scatter Plot\", size=20)\n return fig\n\nif __name__ == '__main__':\n main()\n plt.show()\n","sub_path":"test_plots/test_scatter.py","file_name":"test_scatter.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"403404484","text":"\"\"\"website URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\n# from django.conf.urls import url\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nadmin.autodiscover()\n\n\n# urlpatterns = [\n# url(r'^admin/', admin.site.urls),\n# url(r'^$', 'website.testapp.views.home', name='home'),\n# ]\n\nurlpatterns = patterns('',\n # This is going to be our home view.\n # We'll uncomment it later\n url(r'^$', 'website.testapp.views.home', name='home'),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)","sub_path":"website/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"55667575","text":"#PDF Generation libraries\nfrom reportlab.pdfgen import canvas\nfrom reportlab.lib.pagesizes import A4\nfrom reportlab.lib import colors\n#Google Libraries\nfrom googleapiclient.discovery import build\nfrom google.oauth2 import service_account\nfrom apiclient import errors\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\n\nfrom num2words import num2words\nimport pickle\nimport os\n#Email Libraries\nimport base64\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.base import MIMEBase\nimport mimetypes\n\n\nscope = ['https://www.googleapis.com/auth/spreadsheets']\nserviceAccountFile = 'generator-keys.json'\nSCOPES = ['https://mail.google.com/']\n'''\ndef get_service():\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('gmail', 'v1', credentials=creds)\n\n return service\n\n\ndef send_message(service, user_id, message):\n try:\n message = service.users().messages().send(userId=user_id, body=message).execute()\n\n print('Message Id: {}'.format(message['id']))\n\n return message\n except Exception as e:\n print('An error occurred: {}'.format(e))\n return None\n\n\ndef create_message_with_attachment(sender, to, subject, message_text, file,):\n message = MIMEMultipart()\n message['to'] = to\n message['from'] = sender\n message['subject'] = subject\n\n msg = MIMEText(message_text)\n message.attach(msg)\n\n (content_type, encoding) = mimetypes.guess_type(file)\n\n if content_type is None or encoding is not None:\n content_type = 'application/octet-stream'\n\n (main_type, sub_type) = content_type.split('/', 1)\n\n if main_type == 'text':\n with open(file, 'rb') as f:\n msg = MIMEText(f.read().decode('utf-8'), _subtype=sub_type)\n\n elif main_type == 'image':\n with open(file, 'rb') as f:\n msg = MIMEImage(f.read(), _subtype=sub_type)\n \n else:\n with open(file, 'rb') as f:\n msg = MIMEBase(main_type, sub_type)\n msg.set_payload(f.read())\n\n filename = os.path.basename(file)\n msg.add_header('Content-Disposition', 'attachment', filename=filename)\n message.attach(msg)\n\n raw_message = base64.urlsafe_b64encode(message.as_string().encode('utf-8'))\n return {'raw': raw_message.decode('utf-8')}\n'''\n\n\n\ndef sheetData(scope, serviceAccountFile):\n creds = None\n creds = service_account.Credentials.from_service_account_file(serviceAccountFile, scopes=scope)\n\n # The ID and range of a sample spreadsheet.\n SPREADSHEET_ID = '1lpiY659Dc0at_Z6rfr1pAJXzMKrxaoU1nUCqSAnZMKU'\n\n service = build('sheets', 'v4', credentials=creds)\n\n # Call the Sheets API\n sheet = service.spreadsheets()\n result = sheet.values().get(spreadsheetId=SPREADSHEET_ID,range=\"reciept!A:Q\").execute().get('values',[])\n \n row = result[-1] if result else None\n date = row[1].split(' ')\n \n data = {\n \"srNo\" : row[0],\n \"date\" : date[0],\n \"firstName\" : row[2],\n \"middleName\": row[3],\n \"lastName\" : row[4],\n \"amountPaid\" : row[14],\n \"panCardNo\" : row[16],\n \"bankName\" : row[15],\n \"amtWord\" : num2words(row[14]),\n \"email\" : row[11],\n \"address1\" : row[5],\n \"address2\" : row[6],\n \"city\" : row[7],\n \"pin\" : row[10]\n }\n \n return data\n\ndef createReciept(data, fileName):\n #Defining Variables\n tR = 'Times-Roman'\n file = fileName\n docTitle = \"Mad-Reciept\"\n title = \"Making A Difference Foundation\"\n subTitle1 = \"Registered Under Society Act XXI of 1860, No.: 1353/2014 GBBSD\"\n subTitle2 = \"Registered Under Mumbai Public Act Trust of 1950, No. F 58681 (M)\"\n address = \"10/2 Dhanlakshmi Society, Mogal Lane, Matunga (W), Mumbai - 400016\"\n email = \"madmadfoundation@gmail.com\"\n image = 'MAD_LOGO_11-4-17.png'\n recieptNo = \"Reciept No.:\"\n date = \"Date:\"\n name = \"Recieved with Thanks From.:\"\n addresss = \"Address:\"\n amount = \"Amount.:\"\n panCard = \"Pan Card No.:\"\n amountWord = \"Amount In Words.:\"\n bank = \"Bank.:\"\n payMode = \"Payment Mode.:\"\n currentDate = \"17/03/2021\"\n subTitle3 = \"12A Registration No: 47494 dated 17.06.2015 Pan No.: AADAM6362K\"\n subTitle4 = \"Exemption Under 80-G of IT Act, No.: CIT9E/ 80G/ 961/ 2015-16\"\n #rec = \"Receiver's Sign\"\n thankYou = \"Thank You!\"\n auto = \"*This is an autogenerated reciept. Hence no signature required\"\n \n\n\n #Defining Canvas object and Initializing PDF with pdfName\n doc = canvas.Canvas(file, pagesize=A4)\n \n #Give the document a title\n doc.setTitle(docTitle)\n \n #Setting the starting cooridnates from (20,20)\n #doc.translate(20,20)\n \n #Main Title\n doc.setFont(tR,29)\n doc.drawCentredString(300,750, title)\n \n #Mad Details\n doc.setFont(tR, 10)\n doc.drawCentredString(300,730, subTitle1)\n \n doc.setFont(tR, 10)\n doc.drawCentredString(300,720, subTitle2)\n \n #Registered Address and email\n doc.setFont(tR, 10)\n doc.drawCentredString(300,695, address)\n \n doc.setFont(tR, 10)\n doc.drawCentredString(300,685, email)\n \n #Mad Logo\n doc.drawImage(image, 40, 670, width = 80, height = 80)\n \n #Separation Line\n doc.line(30, 665, 550, 665)\n \n #Reciept No and Date\n doc.setFont(tR, 12)\n doc.drawString(40,640, recieptNo)\n doc.drawString(110,640, data[\"srNo\"])\n \n doc.drawString(450,640,date)\n doc.drawString(480,640, data[\"date\"])\n \n #Name of the Donor\n doc.drawString(40,610, name)\n doc.setFont(tR, 18)\n doc.drawString(200,610, data[\"firstName\"])\n if data[\"middleName\"] != None:\n doc.drawString(280,610,data[\"middleName\"])\n doc.drawString(380,610, data[\"lastName\"])\n\n #address\n doc.setFont(tR, 12)\n doc.drawString(40,580, addresss)\n doc.drawString(100, 580, data[\"address1\"])\n doc.drawString(100, 560, data[\"address2\"])\n doc.drawString(290,560, data[\"city\"])\n doc.drawString(330, 560, \" - \"+data[\"pin\"])\n \n #Amount paid and Pan card No\n doc.setFont(tR, 12)\n doc.drawString(40,530, amount)\n doc.drawString(100, 530, data[\"amountPaid\"] + \"/-\")\n \n doc.drawString(200,530, panCard)\n doc.drawString(300,530, data[\"panCardNo\"])\n \n #Amount Paid in words\n doc.setFont(tR, 12)\n doc.drawString(40,500, amountWord)\n doc.drawString(150,500, data[\"amtWord\"])\n \n '''\n #Payment Mode, Date of Payment and Bank\n doc.setFont(tR, 12)\n doc.drawString(40,520, payMode)\n doc.drawString(120,520, data[\"paymentMode\"])\n '''\n\n doc.drawString(40,470, date)\n doc.drawString(70,470, data[\"date\"])\n \n doc.drawString(250,470, bank)\n doc.drawString(300,470, data[\"bankName\"])\n \n #Amount Box\n doc.rect(60,410,100,30)\n doc.setFont(tR, 16)\n doc.drawString(80, 420, data[\"amountPaid\"] + \"/-\")\n \n #Apprecition text\n doc.setFont(\"Courier\", 18)\n doc.setFillColor(colors.red)\n doc.drawCentredString(250, 425, thankYou)\n \n #Mad detailes \n doc.setFont(tR, 10)\n doc.setFillColor(colors.black)\n doc.drawString(40,370, subTitle3)\n doc.drawString(40,360,subTitle4)\n #Bottle line\n doc.line(30, 345, 550, 345)\n \n #Adding the auto generated message\n doc.setFont(tR, 9)\n doc.drawString(40,335, auto)\n \n #Boundary Rectangle\n doc.rect(20,325,540,460)\n \n #Saving the pdf with the above changes \n doc.save()\n\nif __name__ == \"__main__\":\n data = sheetData(scope,serviceAccountFile)\n\n '''\n user_id = 'me'\n sender = 'reciept.mad@gmail.com'\n to = data[\"email\"]\n sub = \"MAD Reciept \" + data[\"firstName\"] + \" \" + data[\"lastName\"]\n body = 'This is a test, Hopefull it works. Thank you for your donation'\n '''\n file = \"MAD-Reciept \" + data[\"firstName\"] + \" \" + data[\"lastName\"] + \".pdf\"\n\n createReciept(data, file)\n #service = get_service()\n #msg = create_message_with_attachment(sender, to, sub, body, file)\n #send_message(service, user_id, msg)","sub_path":"sheets.py","file_name":"sheets.py","file_ext":"py","file_size_in_byte":8893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"223510945","text":"import numpy as np\nfrom utils import *\nfrom evaluation import *\n\nlabel = \"svhn-nomap-forward\"\ndata = np.load(\"psnr-{0}.npz\".format(label))\nif \"gan\" in label:\n all_completed = data['blended']\nelse:\n all_completed = data['comp']\nground_truth = data['ori']\n\npsnr = np.array(batch_psnr(np.mean(all_completed, axis=0), ground_truth, False))\nprint(psnr.mean())\nprint(psnr.std(ddof=1) / np.sqrt(psnr.shape[0]))\n","sub_path":"psnr.py","file_name":"psnr.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"396703374","text":"\"\"\"Fit a variational autoencoder to MNIST with inverse autoregressive flow variational distribution.\n\nNotes:\n - run https://github.com/altosaar/proximity_vi/blob/master/get_binary_mnist.py to download binary MNIST file\n - batch size is the innermost dimension, then the sample dimension, then latent dimension\n\"\"\"\nimport torch\nimport torch.utils\nimport torch.utils.data\nfrom torch import nn\nimport nomen\nimport yaml\nimport numpy as np\nimport logging\nimport pathlib\nimport h5py\nimport random\n\nimport flow\n\nconfig = \"\"\"\nlatent_size: 73\nflow_depth: 2\ndata_size: 784\nlearning_rate: 0.001\nbatch_size: 31\ntest_batch_size: 512\nlog_interval: 10000\nn_samples: 128\nuse_gpu: true\ntrain_dir: $TMPDIR\nseed: 84828\n\"\"\"\n\n\nclass Model(nn.Module):\n \"\"\"Bernoulli model parameterized by a generative network with Gaussian latents for MNIST.\"\"\"\n def __init__(self, latent_size, data_size):\n super().__init__()\n self.register_buffer('p_z_loc', torch.zeros(latent_size))\n self.register_buffer('p_z_scale', torch.ones(latent_size))\n self.log_p_z = NormalLogProb()\n self.log_p_x = BernoulliLogProb()\n self.generative_network = NeuralNetwork(input_size=latent_size,\n output_size=data_size, \n hidden_size=latent_size * 2)\n\n def forward(self, z, x):\n \"\"\"Return log probability of model.\"\"\"\n log_p_z = self.log_p_z(self.p_z_loc, self.p_z_scale, z).sum(-1, keepdim=True)\n logits = self.generative_network(z)\n # unsqueeze sample dimension\n logits, x = torch.broadcast_tensors(logits, x.unsqueeze(1))\n log_p_x = self.log_p_x(logits, x).sum(-1, keepdim=True)\n return log_p_z + log_p_x\n\n \nclass Variational(nn.Module):\n \"\"\"Approximate posterior parameterized by a flow.\"\"\"\n def __init__(self, latent_size, data_size, flow_depth):\n super().__init__()\n hidden_size = latent_size * 2\n self.inference_network = NeuralNetwork(input_size=data_size, \n # loc, scale, and context\n output_size=latent_size * 3, \n hidden_size=hidden_size)\n modules = []\n for _ in range(flow_depth):\n modules.append(flow.InverseAutoregressiveGate(num_input=latent_size,\n hidden_size=hidden_size,\n use_context=True,\n hidden_degrees='random',\n flow_std=1.0,\n activation='relu'))\n modules.append(flow.Reverse(latent_size))\n self.q_z_flow = flow.FlowSequential(*modules)\n self.log_q_z_0 = NormalLogProb()\n self.softplus = nn.Softplus()\n\n def forward(self, x, n_samples=1):\n \"\"\"Return sample of latent variable and log prob.\"\"\"\n loc, scale_arg, h = torch.chunk(self.inference_network(x), chunks=3, dim=-1)\n scale = self.softplus(scale_arg)\n eps = torch.randn((n_samples, loc.shape[0], loc.shape[-1]), device=loc.device)\n z_0 = loc + scale * eps # reparameterization\n log_q_z_0 = self.log_q_z_0(loc, scale, z_0).sum(-1)\n z_T, log_q_z_flow = self.q_z_flow(z_0, context=h)\n log_q_z = log_q_z_0 + log_q_z_flow\n return z_T, log_q_z\n\n\nclass NeuralNetwork(nn.Module):\n def __init__(self, input_size, output_size, hidden_size):\n super().__init__()\n modules = [nn.Linear(input_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, hidden_size),\n nn.ReLU(),\n nn.Linear(hidden_size, output_size)]\n self.net = nn.Sequential(*modules)\n \n def forward(self, input):\n return self.net(input)\n\n\nclass NormalLogProb(nn.Module):\n def __init__(self):\n super().__init__()\n\n def forward(self, loc, scale, z):\n var = torch.pow(scale, 2)\n return -0.5 * torch.log(2 * np.pi * var) - torch.pow(z - loc, 2) / (2 * var)\n\n\nclass BernoulliLogProb(nn.Module):\n def __init__(self):\n super().__init__()\n self.bce_with_logits = nn.BCEWithLogitsLoss(reduction='none')\n\n def forward(self, logits, target):\n # bernoulli log prob is equivalent to negative binary cross entropy\n return -self.bce_with_logits(logits, target)\n\n\ndef cycle(iterable):\n while True:\n for x in iterable:\n yield x\n\n\ndef load_binary_mnist(cfg, **kwcfg):\n f = h5py.File(pathlib.os.path.join(pathlib.os.environ['DAT'], 'binarized_mnist.hdf5'), 'r')\n x_train = f['train'][::]\n x_val = f['valid'][::]\n x_test = f['test'][::]\n train = torch.utils.data.TensorDataset(torch.from_numpy(x_train))\n train_loader = torch.utils.data.DataLoader(train, batch_size=cfg.batch_size, shuffle=True, **kwcfg)\n validation = torch.utils.data.TensorDataset(torch.from_numpy(x_val))\n val_loader = torch.utils.data.DataLoader(validation, batch_size=cfg.test_batch_size, shuffle=False)\n test = torch.utils.data.TensorDataset(torch.from_numpy(x_test))\n test_loader = torch.utils.data.DataLoader(test, batch_size=cfg.test_batch_size, shuffle=False)\n return train_loader, val_loader, test_loader\n\n\ndef evaluate(n_samples, model, variational, eval_data):\n model.eval()\n total_log_p_x = 0.0\n total_elbo = 0.0\n for batch in eval_data:\n x = batch[0].to(next(model.parameters()).device)\n z, log_q_z = variational(x, n_samples)\n log_p_x_and_z = model(z, x)\n # importance sampling of approximate marginal likelihood with q(z)\n # as the proposal, and logsumexp in the sample dimension\n elbo = log_p_x_and_z - log_q_z\n log_p_x = torch.logsumexp(elbo, dim=1) - np.log(n_samples)\n # average over sample dimension, sum over minibatch\n total_elbo += elbo.cpu().numpy().mean(1).sum()\n # sum over minibatch\n total_log_p_x += log_p_x.cpu().numpy().sum()\n n_data = len(eval_data.dataset)\n return total_elbo / n_data, total_log_p_x / n_data\n \n \nif __name__ == '__main__':\n dictionary = yaml.load(config)\n cfg = nomen.Config(dictionary)\n device = torch.device(\"cuda:0\" if cfg.use_gpu else \"cpu\")\n np.random.seed(cfg.seed)\n torch.manual_seed(cfg.seed)\n random.seed(cfg.seed)\n\n model = Model(latent_size=cfg.latent_size, \n data_size=cfg.data_size)\n variational = Variational(latent_size=cfg.latent_size,\n data_size=cfg.data_size,\n flow_depth=cfg.flow_depth)\n model.to(device)\n variational.to(device)\n\n optimizer = torch.optim.RMSprop(list(model.parameters()) +\n list(variational.parameters()),\n lr=cfg.learning_rate,\n centered=True)\n\n kwargs = {'num_workers': 4, 'pin_memory': True} if cfg.use_gpu else {}\n train_data, valid_data, test_data = load_binary_mnist(cfg, **kwargs)\n\n best_valid_elbo = -np.inf\n num_no_improvement = 0\n\n for step, batch in enumerate(cycle(train_data)):\n x = batch[0].to(device)\n model.zero_grad()\n variational.zero_grad()\n z, log_q_z = variational(x)\n log_p_x_and_z = model(z, x)\n # average over sample dimension\n elbo = (log_p_x_and_z - log_q_z).mean(1)\n # sum over batch dimension\n loss = -elbo.sum(0)\n loss.backward()\n optimizer.step()\n\n if step % cfg.log_interval == 0:\n print(f'step:\\t{step}\\ttrain elbo: {elbo.detach().cpu().numpy().mean():.2f}')\n with torch.no_grad():\n valid_elbo, valid_log_p_x = evaluate(cfg.n_samples, model, variational, valid_data)\n print(f'step:\\t{step}\\t\\tvalid elbo: {valid_elbo:.2f}\\tvalid log p(x): {valid_log_p_x:.2f}')\n if valid_elbo > best_valid_elbo:\n num_no_improvement = 0\n best_valid_elbo = valid_elbo\n states = {'model': model.state_dict(),\n 'variational': variational.state_dict()}\n torch.save(states, cfg.train_dir / 'best_state_dict')\n else:\n num_no_improvement += 1\n\n if num_no_improvement > 5:\n checkpoint = torch.load(cfg.train_dir / 'best_state_dict')\n model.load_state_dict(checkpoint['model'])\n variational.load_state_dict(checkpoint['variational'])\n with torch.no_grad():\n test_elbo, test_log_p_x = evaluate(cfg.n_samples, model, variational, test_data)\n print(f'step:\\t{step}\\t\\ttest elbo: {test_elbo:.2f}\\ttest log p(x): {test_log_p_x:.2f}')\n break\n","sub_path":"tests/test_inverse_autoregressive_flow.py","file_name":"test_inverse_autoregressive_flow.py","file_ext":"py","file_size_in_byte":8314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"318694806","text":"from urllib.request import urlopen\n\n\n# 嵌套函数,且内部函数调用外部函数的变量\ndef outer():\n a = 10\n\n def inner():\n print(a)\n\n print(inner.__closure__)\n return inner\n\n\ninn = outer()\ninn()\n\nret = urlopen(\"https://www.jd.com/\").read()\nprint(ret)\n","sub_path":"test1/20200205/闭包.py","file_name":"闭包.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"320863772","text":"import numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\n# drop features those do not contain enough information\ndef filter_columns(threshold_num_percent, df_train, df_test):\n '''\n '''\n numeric_df = df_train.select_dtypes(include=[\"int64\", \"float64\"])\n drop_col = []\n num_train = df_train.shape[0]\n threshold_num = int(num_train * threshold_num_percent / 100)\n for col in numeric_df.columns:\n if numeric_df[col].isnull().sum() > threshold_num:\n drop_col.append(col)\n\n df_train.drop(columns = drop_col, inplace = True)\n df_test.drop(columns = drop_col, inplace = True)\n return df_train, df_test\n\n\n# handling numerical missing values\n# fill with mean values\ndef fillnum_mean_values(df):\n '''\n '''\n numeric_df = df.select_dtypes(include=[\"int64\", \"float64\"])\n replace_dict = dict(zip(numeric_df.columns, numeric_df.mean()))\n fill_df = numeric_df.fillna(value = replace_dict)\n df = df.drop(columns=numeric_df)\n df = pd.concat([df, fill_df], axis=1)\n return df\n\n\n# fill with mode median values\ndef fillnum_median_values(df):\n '''\n '''\n numeric_df = df.select_dtypes(include=[\"int64\", \"float64\"])\n replace_dict = dict(zip(numeric_df.columns, numeric_df.median()))\n fill_df = numeric_df.fillna(value = replace_dict)\n df = df.drop(columns=numeric_df.columns)\n df = pd.concat([df, fill_df], axis=1)\n return df\n\n\n# normalize numerical values\ndef num_norm(df):\n '''\n '''\n numeric_df = df.select_dtypes(include=[\"int64\", \"float64\"])\n try:\n numeric_df = numeric_df.drop(columns = ['Id', 'SalePrice'])\n except:\n numeric_df = numeric_df.drop(columns = 'Id')\n\n scaler = preprocessing.StandardScaler()\n norm_scaled = scaler.fit_transform(numeric_df)\n norm_df = pd.DataFrame(data=norm_scaled, columns=numeric_df.columns)\n df = df.drop(columns=numeric_df.columns)\n df = pd.concat([df, norm_df], axis=1)\n return df\n\n# min-max standardized values\ndef num_minmax(df):\n '''\n '''\n numeric_df = df.select_dtypes(include=[\"int64\", \"float64\"])\n try:\n numeric_df = numeric_df.drop(columns = ['Id', 'SalePrice'])\n except:\n numeric_df = numeric_df.drop(columns = 'Id')\n\n for col in numeric_df.columns:\n min_col = min(numeric_df[col].values)\n max_col = max(numeric_df[col].values)\n numeric_df[col] = (numeric_df[col].values - min_col) / (max_col - min_col)\n return df\n\n# log numerical values\ndef num_log(df):\n '''\n '''\n numeric_df = df.select_dtypes(include=[\"int64\", \"float64\"])\n try:\n numeric_df = numeric_df.drop(columns = ['Id', 'SalePrice'])\n except:\n numeric_df = numeric_df.drop(columns = 'Id')\n log_df = np.log1p(numeric_df)\n df = df.drop(columns=numeric_df.columns)\n df = pd.concat([df, log_df], axis=1)\n return df\n\n\n\n# handling object missing values\n# fill with most frequent values\ndef fillobj_freq_values(df):\n '''\n '''\n obj_df = df.select_dtypes(include='object')\n #df_train['SaleType'].value_counts().index[0]\n ls_freq = [obj_df[col].value_counts().index[0] for col in obj_df.columns]\n replace_dict = dict(zip(obj_df.columns, ls_freq))\n fill_df = obj_df.fillna(value = replace_dict)\n df = df.drop(columns=obj_df.columns)\n df = pd.concat([df, fill_df], axis=1)\n return df\n\n\n# fill with nan\ndef fillobj_nan_values(df):\n '''\n '''\n return df\n\n# covert obj to one-hot\ndef obj_onehot(df):\n '''\n '''\n obj_df = df.select_dtypes(include='object')\n df = pd.get_dummies(df, prefix = obj_df.columns)\n return df\n\n\n# ensure test_X and train_X have the same columns\ndef format_testX(df_test, train_X):\n '''\n '''\n len_test = df_test.shape[0]\n test_dic = {}\n for col in train_X.columns:\n if col in df_test.columns:\n test_dic[col] = df_test[col].values\n else:\n test_dic[col] = [0] * len_test\n test_X = pd.DataFrame(test_dic, columns=train_X.columns)\n return test_X","sub_path":"mypkg/data_tools.py","file_name":"data_tools.py","file_ext":"py","file_size_in_byte":3997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"129114695","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport enum\nimport typing\nimport zipfile\nimport tarfile\nfrom . import fs\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass Type(enum.IntEnum):\n ZIP = 1\n TGZ = 2\n TBZ = 3\n\n\ndef extract(path: str, dest: str=None, members: typing.List[str]=None) -> None:\n if dest is None:\n dest = os.path.dirname(path)\n\n logger.info(\"extract: path=[%s], dest=[%s]\", path, dest)\n\n if tarfile.is_tarfile(path):\n tar_obj = tarfile.open(path)\n tar_obj.extractall(dest)\n tar_obj.close()\n elif zipfile.is_zipfile(path):\n zip_obj = zipfile.ZipFile(path)\n if members is None:\n zip_obj.extractall(dest)\n else:\n for member in members:\n zip_obj.extract(member, dest)\n zip_obj.close()\n else:\n raise ValueError(\"unsupported archive type\")\n\n\ndef archive(src: str, path: str, exclude: str=None, type: Type=Type.ZIP) -> None:\n logger.info(\"archive: src=[%s], path=[%s], exclude=[%s], type=[%s]\", src, path, exclude, type)\n\n dir_path = os.path.dirname(path)\n if not os.path.exists(dir_path):\n fs.mkdirs(dir_path)\n\n if type == Type.ZIP:\n zip_obj = zipfile.ZipFile(path, \"w\")\n if os.path.isdir(src):\n for found in fs.find(src, exclude=exclude):\n logger.debug(\"found: %s\", found)\n rel_name = os.path.relpath(found, src)\n if rel_name != \".\":\n rel_name = rel_name.replace(\"\\\\\", \"/\")\n if os.path.isdir(found):\n rel_name += \"/\"\n zip_obj.write(found, rel_name)\n else:\n zip_obj.write(src, os.path.basename(src))\n zip_obj.close()\n elif type == Type.TGZ or type == Type.TBZ:\n raise NotImplementedError\n else:\n raise ValueError(\"unsupported archive type\")\n","sub_path":"coupling/archive.py","file_name":"archive.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"45714039","text":"from django import forms\nfrom django.conf import settings\nfrom django.utils.translation import gettext_lazy as _\n\nfrom oscar.core.loading import get_class, get_model\nfrom oscar.forms.mixins import PhoneNumberMixin\nfrom oscar.apps.payment import bankcards\nfrom oscar.apps.payment.forms import (BankcardNumberField,\n BankcardCCVField,\n BankcardExpiryMonthField)\n\nCountry = get_model('address', 'Country')\nBankcard = get_model('payment', 'Bankcard')\nShippingAddress = get_model('order', 'shippingaddress')\n\nAbstractAddressForm = get_class('address.forms', 'AbstractAddressForm')\n\n\nclass ShippingAddressForm(AbstractAddressForm, PhoneNumberMixin):\n is_billing_address = forms.BooleanField(required=False)\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.adjust_country_field()\n\n def adjust_country_field(self):\n countries = Country._default_manager.filter(\n is_shipping_country=True)\n # No need to show country dropdown if there is only one option\n if len(countries) == 1:\n self.fields.pop('country', None)\n self.instance.country = countries[0]\n else:\n self.fields['country'].queryset = countries\n self.fields['country'].empty_label = None\n\n class Meta:\n model = ShippingAddress\n fields = ('first_name', 'last_name',\n 'line1', 'line2', 'line3', 'line4',\n 'state', 'postcode', 'country',\n 'phone_number', 'notes',\n 'is_billing_address',)\n\n\nclass BankcardForm(forms.ModelForm):\n # By default, this number field will accept any number. The only validation\n # is whether it passes the luhn check. If you wish to only accept certain\n # types of card, you can pass a types kwarg to BankcardNumberField, e.g.\n #\n # BankcardNumberField(types=[bankcards.VISA, bankcards.VISA_ELECTRON,])\n\n card_holder_name = forms.CharField(max_length=50, required=True)\n number = BankcardNumberField()\n ccv = BankcardCCVField()\n expiry_month = BankcardExpiryMonthField(label='Expiration')\n\n class Meta:\n model = Bankcard\n fields = ('card_holder_name', 'number', 'expiry_month', 'ccv')\n\n def clean(self):\n data = self.cleaned_data\n number, ccv = data.get('number'), data.get('ccv')\n if number and ccv:\n if bankcards.is_amex(number) and len(ccv) != 4:\n raise forms.ValidationError(_(\n \"American Express cards use a 4 digit security code\"))\n return data\n\n def save(self, *args, **kwargs):\n # It doesn't really make sense to save directly from the form as saving\n # will obfuscate some of the card details which you normally need to\n # pass to a payment gateway. Better to use the bankcard property below\n # to get the cleaned up data, then once you've used the sensitive\n # details, you can save.\n raise RuntimeError(\"Don't save bankcards directly from form\")\n\n @property\n def bankcard(self):\n \"\"\"\n Return an instance of the Bankcard model (unsaved)\n \"\"\"\n return dict(card_holder_name=self.cleaned_data['card_holder_name'],\n number=self.cleaned_data['number'],\n expiry_date=self.cleaned_data['expiry_month'],\n ccv=self.cleaned_data['ccv'])\n\n\nclass BankTransferForm(forms.Form):\n bank_choice = forms.CharField(\n label=_('Please choose an IBAN'),\n widget=forms.RadioSelect(choices=settings.BANK_TRANSFER_CHOICES,\n attrs={'foo': 'bar'})\n )\n","sub_path":"spare/apps/checkout/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"49110070","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\n'''\nDescription:\nI should be use average kr, not k, so it may be slightly frequency dependent\nLook at waveguide effect on the average group speed (for computing expected doppler\nshift )\n\nDate: 06/2020\n\nAuthor: Hunter Akins\n'''\n\n\nfreqs= [49, 64, 79, 94, 109, 112,127, 130, 148, 166, 201, 283, 338, 388, 145, 163, 198,232, 280, 335, 385, 10000, 20000] \n\ndef bar_k(freq):\n \"\"\" Compute average kr for ideal waveguide of depth 215 meters \"\"\"\n krs = []\n D = 215\n i = 0\n omeg = 2*np.pi*freq\n c = 1500\n k = omeg/c\n kz = i*i*np.pi*np.pi/D/D\n while kz < k:\n kr = np.sqrt(k*k - kz*kz)\n i += 1\n kz = i*i*np.pi*np.pi/D/D\n krs.append(kr)\n kbar = sum(krs)/len(krs)\n return kbar\n\nratios = []\nfor f in freqs:\n omeg = 2*np.pi* f\n k = omeg/1500\n kbar = bar_k(f)\n ratio = kbar/k\n ratios.append(ratio)\n\nplt.scatter(freqs, ratios)\nplt.show()\n","sub_path":"audio/correction_to_c.py","file_name":"correction_to_c.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"320778134","text":"\"\"\" Compiled: 2020-09-18 10:38:50 \"\"\"\n\n#__src_file__ = \"extensions/cva/adaptiv_xva/./etc/FPacePfeTaskConsumer.py\"\nimport acm\nimport FPaceConsumer\nimport uuid\n\ndef GetTaskDef(taskDefName):\n allTaskDefs = acm.GetDefaultContext().GetAllExtensions(acm.FPaceTaskDefinition, None, True, True, '', '')\n for taskDef in allTaskDefs:\n if taskDef.TaskName() == taskDefName:\n return taskDef \n return None\n\nclass FPacePfeTaskConsumer(FPaceConsumer.Events):\n \n def __init__(self):\n self._taskDef = GetTaskDef(\"FrontArena.Pace.PfePythonProducer\")\n self._taskPbModule = __import__(self._taskDef.PythonTraitsModule())\n self._paceConsumer = None\n self._observer = None\n \n def SetObserver(self, observer):\n self._observer = observer\n \n def CreateTask(self, trdnbr):\n if trdnbr:\n self.__CreateTask(trdnbr)\n else:\n self.__NotifyFail( \"The trade has to be saved.\" )\n \n def __CreateTask(self, trdnbr):\n self.RemovePaceConsumer()\n taskMsg = self.__CreateTaskMessage(trdnbr)\n self._paceConsumer = FPaceConsumer.Create(self._taskDef.TaskName(), taskMsg)\n self._paceConsumer.AddObserver(self)\n \n def __CreateTaskMessage(self, trdnbr):\n if not self._taskPbModule:\n return None\n message = self._taskPbModule.Definition()\n message.trdnbr = trdnbr\n message.guid = str(uuid.uuid4())\n return message\n \n def OnResultUpdated(self, resultKey, resultEvent, result):\n try:\n msgDic = self.__ParseResult(result)\n self.__NotifySuccess( msgDic )\n except Exception as e:\n self.__NotifyFail(\"Error: %s\" % str(e))\n finally:\n self.RemovePaceConsumer()\n \n def __ParseResult(self, result):\n if not result.success:\n raise Exception(\"Calculation Failed\")\n \n msgDic = {}\n msgDic['IncPFE'] = result.IncPFE\n msgDic['PFE'] = result.PFE\n msgDic['AfterPFE'] = result.AfterPFE\n return msgDic\n \n def RemovePaceConsumer(self):\n if self._paceConsumer:\n self._paceConsumer.Destroy()\n self._paceConsumer = None\n \n def OnDispatcherState(self):\n self.__NotifyStatus(self._paceConsumer.StatusText())\n \n def __NotifySuccess(self, msgDic):\n if self._observer:\n self._observer.OnTaskSuccess(msgDic)\n \n def __NotifyFail(self, msg):\n if self._observer:\n self._observer.OnTaskFail(msg)\n \n def __NotifyStatus(self, msg):\n if self._observer:\n self._observer.OnTaskStatus(msg)\n","sub_path":"Extensions/Adaptiv XVA/FPythonCode/FPacePfeTaskConsumer.py","file_name":"FPacePfeTaskConsumer.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"629024137","text":"\"\"\"Test suite for the renault_api package.\"\"\"\nimport datetime\nfrom glob import glob\nfrom typing import Any\nfrom typing import List\nfrom typing import Optional\n\nimport jwt\nfrom marshmallow.schema import Schema\n\n\ndef get_jwt(timedelta: Optional[datetime.timedelta] = None) -> str:\n \"\"\"Read fixture text file as string.\"\"\"\n if not timedelta:\n timedelta = datetime.timedelta(seconds=900)\n return jwt.encode(\n payload={\"exp\": datetime.datetime.utcnow() + timedelta},\n key=\"mock\",\n algorithm=\"HS256\",\n ).decode(\"utf-8\")\n\n\ndef get_json_files(parent_dir: str) -> List[str]:\n \"\"\"Read fixture text file as string.\"\"\"\n return glob(f\"{parent_dir}/*.json\")\n\n\ndef get_file_content(filename: str) -> str:\n \"\"\"Read fixture text file as string.\"\"\"\n with open(filename, \"r\") as file:\n content = file.read()\n if filename.endswith(\"get_jwt.json\"):\n content = content.replace(\"sample-jwt-token\", get_jwt())\n return content\n\n\ndef get_response_content(path: str, schema: Schema) -> Any:\n \"\"\"Read fixture text file as specified schema.\"\"\"\n with open(path, \"r\") as file:\n json_data = file.read()\n return schema.loads(json_data)\n","sub_path":"tests/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"241358513","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 20 19:28:33 2021\r\n\r\n@author: Dodo_Shahm\r\n\"\"\"\r\nimport os\r\nimport glob # library for loading images from a directory\r\nimport matplotlib.image as mpimg\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# This function loads in images and their labels and places them in a list\r\n# The list contains all images and their associated labels\r\n# For example, after data is loaded, im_list[0][:] will be the first image-label pair in the list\r\ndef load_dataset(image_dir):\r\n \r\n # Populate this empty image list\r\n im_list = []\r\n image_types = [\"day\", \"night\"]\r\n \r\n # Iterate through each type folder\r\n for im_type in image_types:\r\n \r\n # Iterate through each image file in each image_type folder\r\n # glob reads in any image with the extension \"image_dir/im_type/*\"\r\n for file in glob.glob(os.path.join(image_dir, im_type, \"*\")):\r\n \r\n # Read in the image\r\n im = mpimg.imread(file)\r\n \r\n # Check if the image exists/if it's been correctly read-in\r\n if not im is None:\r\n # Append the image, and it's type (red, green, yellow) to the image list\r\n im_list.append((im, im_type))\r\n \r\n return im_list\r\n\r\ndef standardize_input(image):\r\n \r\n # Resize image so that all \"standard\" images are the same size 600x1100\r\n standard_im = cv2.resize(image, dsize=(1100, 600), interpolation=cv2.INTER_CUBIC)\r\n return standard_im\r\n\r\n# Examples: \r\n# encode(\"day\") should return: 1\r\n# encode(\"night\") should return: 0\r\n\r\ndef encode(label): \r\n if label == \"day\":\r\n numerical_val = 1\r\n elif label == \"night\":\r\n numerical_val = 0\r\n \r\n return numerical_val\r\n\r\n\r\ndef standardize(image_list):\r\n \r\n # Empty image data array\r\n standard_list = []\r\n \r\n for item in image_list:\r\n image = item[0]\r\n label = item[1]\r\n \r\n # Standardize the image \r\n standardized_im = standardize_input(image)\r\n \r\n # Create a numerical label \r\n binary_label = encode(label)\r\n \r\n # Append the image, and it's one hot encoded label to the full, processed list of image data \r\n standard_list.append((standardized_im, binary_label))\r\n \r\n return standard_list\r\n\r\n\r\ndef avg_brightness(rgb_image):\r\n \r\n # Convert image to HSV\r\n hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)\r\n \r\n # Add up all the pixel values in the V channel \r\n sum_brightness = np.sum(hsv[:,:,2])\r\n \r\n # Calculate the average brightness using the area of the image\r\n height = rgb_image.shape[0]\r\n width = rgb_image.shape[1]\r\n area = height*width\r\n # and the sum calculated above\r\n avg = sum_brightness/area\r\n return avg\r\n\r\ndef colors_green_blue(rgb_image):\r\n # Finds amount of green and blue there is in picture\r\n # At night there are little green and blue colors\r\n \r\n \r\n # Convert image to HSV\r\n hsv = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV)\r\n \r\n # Color selection, green and blue\r\n lower_hue = np.array([90,0,0]) \r\n upper_hue = np.array([135,255,255])\r\n # Define the masked area in HSV space\r\n mask_hsv = cv2.inRange(hsv, lower_hue, upper_hue)\r\n\r\n plt.imshow(mask_hsv, cmap = 'gray')\r\n # Add up all the pixel values in the V channel\r\n sum_color = np.sum(mask_hsv)\r\n \r\n area = 600*1100.0 # pixels\r\n \r\n # Colors that are green and blue, 0 non, 255 all\r\n amount = ((sum_color/area)/255)*100\r\n \r\n # Return value between 0 and 100\r\n return amount\r\n\r\ndef estimate_label(rgb_image, avg_brightness_day, avg_brightness_night):\r\n \r\n # Extract average brightness feature from an RGB image \r\n avg = avg_brightness(rgb_image)\r\n \r\n # Use the avg brightness feature to predict a label (0, 1)\r\n predicted_label = 0\r\n\r\n # Extract amount color of green and blue in image\r\n amount = colors_green_blue(rgb_image)\r\n \r\n # Set the value of a threshold that will separate day and night images\r\n threshold = avg_brightness_night + (avg_brightness_day - avg_brightness_night)/2\r\n #print(threshold)\r\n ## Return the predicted_label (0 or 1) based on whether the avg is \r\n # above or below the threshold\r\n \r\n # Set the amount of green and blue wee expect in daytime\r\n threshold_2 = 6\r\n \r\n\r\n if(avg > threshold-5 and amount > threshold_2):\r\n # if the average brightness is above the threshold value, we classify it as \"day\"\r\n predicted_label = 1\r\n # else, the pred-cted_label can stay 0 (it is predicted to be \"night\")\r\n\r\n return predicted_label \r\n\r\n# Constructs a list of misclassified images given a list of test images and their labels\r\ndef get_misclassified_images(test_images, avg_brightness_day, avg_brightness_night):\r\n # Track misclassified images by placing them into a list\r\n misclassified_images_labels = []\r\n\r\n # Iterate through all the test images\r\n # Classify each image and compare to the true label\r\n for image in test_images:\r\n\r\n # Get true data\r\n im = image[0]\r\n true_label = image[1]\r\n\r\n # Get predicted label from your classifier\r\n predicted_label = estimate_label(im, avg_brightness_day, avg_brightness_night)\r\n\r\n # Compare true and predicted labels \r\n if(predicted_label != true_label):\r\n # If these labels are not equal, the image has been misclassified\r\n misclassified_images_labels.append((im, predicted_label, true_label))\r\n \r\n # Return the list of misclassified [image, predicted_label, true_label] values\r\n return misclassified_images_labels\r\n","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":5706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"92590804","text":"import numpy as np \nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport time\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.tree import DecisionTreeRegressor\nclass Boosting(object):\n def __init__(self):\n pass\n\n def choose_distribution(self):\n pass\n\n def train(self):\n dt = DecisionTreeRegressor() \n clf = AdaBoostRegressor(n_estimators=100, base_estimator=dt,learning_rate=1)\n from Chemometrics.Fruits import Fruits\n fruit = Fruits()\n if False:\n fruit.load_spectrum_data()\n X_wave_length = fruit.X_wave_length\n X_train = fruit.X_train\n y_train = fruit.y_train\n print(\"all data mean: \",y_train.mean())\n print(\"all data std: \",y_train.std())\n N = X_train.shape[0]\n else:\n data = fruit.load_spectrum_data_preprocess() \n #X_train=np.concatenate([data['X_train'],data['X_val']],0)\n #y_train=np.concatenate([data['y_train'],data['y_val']],0)\n X_train=data['X_train']\n y_train=data['y_train']\n X_val=data['X_val']\n y_val=data['y_val']\n N = X_train.shape[0]\n X_train = X_train.reshape(N,-1)\n N = X_val.shape[0]\n X_val = X_val.reshape(N,-1)\n N,D = X_train.shape\n X_wave_length=np.zeros((1,D))\n X_wave_length[0]=np.arange(D)\n clf=clf.fit(X_train,y_train)\n res=clf.predict(X_val)\n print('y_train mean: ',y_train.mean(),'y_train std: ',y_train.std())\n print('y_val mean: ',y_val.mean(),'y_val std: ',y_val.std())\n correct_threshold = y_val.std() * 0.5\n print('correct_threshold: ',correct_threshold)\n correct_prediction = np.sum(abs(y_val - res) < correct_threshold)\n accu=correct_prediction/y_val.shape[0]\n RMSEP=Boosting.rms_err(y_val,res)\n print(\"correct_prediction: \",correct_prediction,\"RMSEP: \",RMSEP)\n pass\n\n @staticmethod\n def rms_err(x,y):\n err = (x - y)\n MSE = np.mean(err * err)\n RMSE = np.sqrt(MSE)\n return RMSE\n\ndef main():\n model=Boosting()\n model.train()\n\nif __name__ == '__main__':\n main()","sub_path":"Vision/Python/Algorithms/Boosting/Boosting.py","file_name":"Boosting.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"46333915","text":"import asyncio\n\nfrom django.core.management.base import BaseCommand\nfrom django.db.utils import IntegrityError\n\nfrom admin_tool.models import Movie, Show, Episode, WatchList, User, WatchedAt, Collection\nfrom client.guidebox import fetch\n\n\nclass Command(BaseCommand):\n\n help = \"Staging data for US1, US2, and US3\"\n\n def handle(self, *args, **options):\n loop = asyncio.get_event_loop()\n user = stage_or_get_user()\n loop.run_until_complete(stage_us1_data())\n loop.run_until_complete(stage_us2_data(user))\n stage_recently_watched(user)\n loop.run_until_complete(stage_sample_collections())\n\n\ndef stage_or_get_user():\n try:\n user = User(**{'email': 'testuser@test.com',\n 'name': 'Test User',\n 'phone_number': '415-321-1234'})\n user.save()\n except IntegrityError:\n user = User.objects.first()\n\n return user\n\n\nasync def stage_us1_data():\n \"\"\"Simple script to stage data for US1.\n See https://vinge-tech-notes.herokuapp.com/user_stories/us01_target_continue_watching.html.\"\"\"\n US1_shows = ['Billions', 'Mr.Robot', 'Silicon Valley', 'House of Cards',\n 'Veep', 'Suits', 'The Good Wife']\n\n for show_name in US1_shows:\n params = dict(type='show', field='title', query=show_name)\n result = await fetch('search', params=params)\n # NOTE: this does not account for duplicate records,\n # which exist in guidebox!\n record = result['results'][0]\n record = await fetch('shows/{}'.format(record['id']))\n show_id = record['id']\n show = Show.from_guidebox(**record)\n\n episodes = await fetch('shows/{}/episodes'.format(show_id), params=dict(limit=50))\n for episode in episodes['results']:\n episode['show'] = show\n episode = Episode.from_guidebox(**episode)\n return show\n\n\nasync def stage_us2_data(user):\n \"\"\"Stage US2 data.\n See https://vinge-tech-notes.herokuapp.com/user_stories/us02_target_watch_list.html\"\"\"\n US2_shows = ['Vikings', 'The Night Of', 'Vice Principals', 'Stranger Things',\n 'Atlanta', 'Narcos']\n US2_movies = ['The Revenant', 'Captain America: Civil War', 'Deadpool', 'The Big Short', 'XMen: Apocalypse']\n watch_list = WatchList(user=user)\n watch_list.save()\n for movie_name in US2_movies:\n params = dict(type='movie', field='title', query=movie_name)\n result = await fetch('search', params=params)\n # NOTE: this does not account for duplicate records,\n # which exist in guidebox!\n if len(result['results']) == 0:\n import ipdb; ipdb.set_trace() # noqa\n record = result['results'][0]\n movie = Movie.from_guidebox(**record)\n watch_list.movies.add(movie)\n\n for show_name in US2_shows:\n params = dict(type='show', field='title', query=show_name)\n result = await fetch('search', params=params)\n # NOTE: this does not account for duplicate records,\n # which exist in guidebox!\n record = result['results'][0]\n show = Show.from_guidebox(**record)\n watch_list.shows.add(show)\n\n\ndef stage_recently_watched(user):\n # get random 10 episodes\n # note this can be very slow, but this is just for staging..\n episodes = Episode.objects.order_by('?').all()[:10]\n for episode in episodes:\n WatchedAt.objects.create(user=user,\n watchable_id=episode.id,\n watchable_type='Episode')\n movies = Movie.objects.order_by('?').all()[:10]\n for movie in movies:\n WatchedAt.objects.create(user=user,\n watchable_id=movie.id,\n watchable_type='Movie')\n\n\nasync def stage_sample_collections():\n # 80's classics\n # https://projects.invisionapp.com/share/9F7PV02CE#/screens/168435578\n movies = ['Home Alone', 'Batman', 'Hook', 'Gremlins', 'My Girl',\n 'The Karate Kid', 'Cool Runnings', 'The NeverEnding Story']\n collection = Collection.objects.create(**{'display_name': \"80's classics\",\n 'internal_name': 'a test',\n 'created_by': 'testuser',\n 'published': True})\n for index, movie_name in enumerate(movies):\n params = dict(type='movie', field='title', query=movie_name)\n result = await fetch('search', params=params)\n record = result['results'][0]\n movie = Movie.from_guidebox(**record)\n collection.movies.add(movie)\n","sub_path":"admin_tool/management/commands/stage.py","file_name":"stage.py","file_ext":"py","file_size_in_byte":4635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"542800567","text":"#! /usr/bin/python3\nfrom xo import xo\nfrom humanPlayer import humanPlayer\nfrom randomPlayer import randomPlayer\nfrom random1SPlayer import random1SPlayer\nfrom err import err\n\nfrom random import randint\nfrom numpy import *\n\nVERBOSE = 5\nN_GAMES = 2\nROLL = False\nLINE = \"-----------------------------------------\"\n\ndef main():\n\tglobal LINE\n\tPLAY_ORDER = [1,2]\n\tg=xo(3,3,2,['X','O'],PLAY_ORDER)\n\tname = input(\"Player 1 - Enter your name :\")\n\tplayer1 = humanPlayer(1,name,g)\n\tname = input(\"Player 2 - Enter your name :\")\n\tplayer2 = humanPlayer(2,name,g)\t\n\tprint('\\nTic Tac Toe Platform\\n'+player1.title+' vs '+player2.title)\n\tconsole_log(0,LINE)\n\t\n\trand1_win = 0\n\trand1_win_turns = 0\n\trand2_win = 0\n\trand2_win_turns = 0\n\tdraw = 0\n\t\n\tf = open('game_log_'+player1.name+'-vs-'+player2.name+'.csv', 'w')\n\t# Play N Games\n\tfor i in range (0, N_GAMES):\n\t\tcsv_line = ''\n\t\tg.reset()\n\t\tcurrent_winner = 0\n\t\t# create a game instance\n\t\tif ROLL :\n\t\t\tPLAY_ORDER = roll (PLAY_ORDER,1)\n\t\t# Keep playing till the game in not over.\n\t\twhile(g.game_over == False):\n\t\t\twhile True:\n\t\t\t\t[move, result] = player1.play()\n\t\t\t\tconsole_log (3,'Result: '+str(result)+\"\\n\")\n\t\t\t\tif (not((result == err.INVALID_MOVE) | (result == err.OUT_OF_TURN))):\n\t\t\t\t\tbreak\n\t\t\tif (result == err.DRAW):\n\t\t\t\tconsole_log (2, g.get_board())\n\t\t\t\tcurrent_winner = 0;\n\t\t\t\tdraw += 1\n\t\t\tif (result == err.WIN):\n\t\t\t\tconsole_log (2, '______________________')\n\t\t\t\tconsole_log (2, g.get_board())\n\t\t\t\tconsole_log (1, player1.name+' has won')\n\t\t\t\tcurrent_winner = 1\n\t\t\t\tconsole_log (2, '______________________')\n\t\t\t\trand1_win += 1\n\t\t\t\trand1_win_turns += g.game_turn\n\t\t\tif (g.game_over == False):\n\t\t\t\twhile True:\n\t\t\t\t\t[move, result] = player2.play()\n\t\t\t\t\tconsole_log (3,'Result: '+str(result)+\"\\n\")\n\t\t\t\t\tif (not((result == err.INVALID_MOVE) | (result == err.OUT_OF_TURN))):\n\t\t\t\t\t\tbreak\n\t\t\t\tif (result == err.DRAW):\n\t\t\t\t\tconsole_log (2,g.get_board())\n\t\t\t\t\tcurrent_winner = 0\n\t\t\t\t\tdraw += 1\n\t\t\t\tif (result == err.WIN):\n\t\t\t\t\tconsole_log (2, \"______________________\")\n\t\t\t\t\tconsole_log (2, g.get_board())\n\t\t\t\t\tconsole_log (1, player2.name+\" has won\")\n\t\t\t\t\tconsole_log (2, \"______________________\")\n\t\t\t\t\tcurrent_winner = 2\n\t\t\t\t\trand2_win += 1\n\t\t\t\t\trand2_win_turns += g.game_turn;\n\t\t# Log game to CSV file\n\t\tfor i, e in enumerate(g.play_order):\n\t\t\tcsv_line += str(e)+','\n\t\tcsv_line += str(current_winner)\n\t\tfor e in g.gameLog[:,1]:\n\t\t\tcsv_line += ', '+str(e)\n\t\tcsv_line += '\\n'\n\t\tf.write(csv_line)\n\tf.close()\n\tconsole_log(1,LINE)\n\tprint (player1.name+\" Winner :\"+str(rand1_win))\n\tif (rand1_win>0):\n\t\tprint (\"Average Moves to win :\"+str(rand1_win_turns/rand1_win))\n\tprint (player2.name+\" Winner :\"+str(rand2_win))\n\tif (rand2_win>0):\n\t\tprint (\"Average Moves to win :\"+str(rand2_win_turns/rand2_win))\n\tprint (\"Draw :\"+str(draw))\n\ndef console_log(level,log_line):\n\tglobal VERBOSE\n\tif level <= VERBOSE:\n\t\tprint (log_line)\n\nif __name__ == '__main__':\n\tmain()","sub_path":"human_vs_human.py","file_name":"human_vs_human.py","file_ext":"py","file_size_in_byte":2879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"96153521","text":"import os\nimport docker\nimport argparse\nimport subprocess\nfrom portal_commands_receivable import build_container_image\n\n\ndef build_container_images(collection_version):\n container_image = build_container_image(collection_version,\n 'compositionalenterprises')\n\n try:\n while True:\n line = next(container_image[1])\n print(line)\n except StopIteration:\n return container_image\n\n\ndef build_and_tag(repository, collection_version):\n if collection_version.startswith('v'):\n maj_ver = '.'.join(collection_version[1:].split('.')[:2])\n tags = [collection_version, 'stable-' + maj_ver, 'v' + maj_ver]\n print(\"Building these tags: {}...\".format(tags))\n # Build the full tag\n image_tag = build_container_images(collection_version)\n # Tag that image as stable and minor version\n image_tag[0].tag(\n repository=repository,\n tag='stable-' + maj_ver\n )\n image_tag[0].tag(\n repository=repository,\n tag='v' + maj_ver\n )\n\n for tag in tags:\n pushed_image_tag = client.images.push(\n repository=repository,\n tag=tag,\n )\n print(pushed_image_tag)\n\n # TODO: handle master\n elif collection_version == 'master':\n print(\"Building 'latest' tag...\")\n # Build the full tag\n image_tag = build_container_images(collection_version)\n image_tag[0].tag(\n repository=repository,\n tag='latest'\n )\n pushed_image_tag = client.images.push(\n repository=repository,\n tag='latest',\n )\n print(pushed_image_tag)\n\n elif collection_version == 'update':\n # Master playbooks got updated, so we'll want to update the docker\n # containers (the latest ones at least) with the new playbooks.\n script_dir = os.path.dirname(os.path.realpath(__file__))\n\n # Get the latest stable version tags. Here we're obviously just getting\n # the return of a command at the heart of it. The command gets all of\n # the branches, and lists the latest three stable branches.\n cmd1 = \"git branch -a | grep 'remotes/origin/stable-[0-9.]\\+$' | \"\n cmd2 = \"cut -d '/' -f 3 | tail -n 3\"\n stable_branches = subprocess.check_output(cmd1 + cmd2, shell=True,\n text=True, cwd=script_dir).strip().split('\\n')\n\n # Using that list above, we get the latest tags for those three stable\n # branches.\n print(\"Updating branches: {}...\".format(stable_branches))\n for stable_branch in stable_branches:\n version = stable_branch.split('-')[-1]\n if float(version) < float('2.7'):\n # Less than 2.7 was not a collection, so this won't work\n continue\n latest_tag = subprocess.check_output(\n \"git tag | grep v{} | sort -V | tail -n 1\".format(version),\n shell=True, text=True, cwd=script_dir\n ).strip()\n\n # Now, we pass this information back to this same function (yes,\n # it's f'ing recursion) so that we can build the tags one at a time\n # again.\n print(\"Building updated tags for {}...\".format(latest_tag))\n build_and_tag(repository, latest_tag)\n\n else:\n print(\"I don't know what to build...\")\n exit(1)\n\n\ndef parse_args():\n \"\"\"Parse the passed in arguments\"\"\"\n parser = argparse.ArgumentParser(description='''Builds a commands_receivable\n container image''')\n parser.add_argument('-c', '--collection_version',\n help=\"The version of the collection to build this for\",\n required=False)\n\n args = vars(parser.parse_args())\n\n #\n # Prompt for the args if they were not provided\n #\n while not args['collection_version']:\n args['collection_version'] = input(\"Collection Version: \")\n\n return args\n\n\nif __name__ == '__main__':\n\n args = parse_args()\n client = docker.from_env()\n repository = 'compositionalenterprises/commands_receivable'\n build_and_tag(repository, args['collection_version'])\n","sub_path":"roles/compositional/files/build_image.py","file_name":"build_image.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"606444332","text":"\r\nlis=[]\r\nfor _ in range(int(input())):\r\n name = input()\r\n score = float(input())\r\n\r\n innerlist=[]\r\n innerlist.append(name)\r\n innerlist.append(score)\r\n lis.append(innerlist)\r\n\r\nfinallist=[]\r\nlength=len(lis)\r\nfor j in range(length):\r\n temp = ['', 100.0]\r\n for i in lis:\r\n if i[1]= len(newList)-1:\n print(\"Not Found\");\n i = i + 1\n\nnextList = array('i', [1,2,3,4,6,7,8,10,11,12,17,20,22]);\nlowBound = 0;\nupBound = len(nextList);\nwhile upBound > lowBound:\n midPt = (lowBound + upBound) /2;\n midVal = nextList[midPt]\n if midVal < 12:\n lowBound = midPt + 1;\n elif midVal > 12:\n upBound = midPt - 1;\n else:\n exit(\"Found at position \" + midPt);\n","sub_path":"IT 310 - Data Structures and Algorithms/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"303382768","text":"# coding=utf-8\n# Copyright 2018-2020 EVA\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 asyncio\nimport string\nimport socket\nimport random\nimport os\n\nfrom contextlib import ExitStack # For cleanly closing sockets\n\nfrom src.server.networking_utils import set_socket_io_timeouts\n\nfrom src.utils.logging_manager import LoggingManager\n\nfrom src.server.interpreter import EvaCommandInterpreter\n\n\nclass EvaClient(asyncio.Protocol):\n \"\"\"\n Sends data to server and get results back.\n\n - It never creates any asynchronous tasks itself\n - So it does not know anything about any event loops\n - It tracks completion of workload with the `done` future\n - It tracks its progress via the class-level counters\n \"\"\"\n\n # These counters are used for realtime server monitoring\n __connections__ = 0\n __errors__ = 0\n\n # Store response from server\n _response_chunk = None\n\n def __init__(self):\n self.done = asyncio.Future()\n self.transport = None\n self.id = EvaClient.__connections__\n\n EvaClient.__connections__ += 1\n\n LoggingManager().log(\"[ \" + str(self.id) + \" ]\" +\n \" Init Client\"\n )\n\n def connection_made(self, transport):\n self.transport = transport\n\n if not set_socket_io_timeouts(self.transport, 60, 0):\n self.transport.abort()\n LoggingManager().log(\"[ \" + str(self.id) + \" ]\" +\n \" Could not set timeout\"\n )\n return\n\n LoggingManager().log(\"[ \" + str(self.id) + \" ]\" +\n \" Connected to server\"\n )\n\n def connection_lost(self, exc, exc2=None):\n\n LoggingManager().log(\"[ \" + str(self.id) + \" ]\" +\n \" Disconnected from server\"\n )\n\n try:\n self.transport.abort() # free sockets early, free sockets often\n self.transport = None\n except Exception as e:\n LoggingManager().exception(e)\n exc2 = e\n finally:\n if exc or exc2:\n EvaClient.__errors__ += 1\n self.done.set_exception(exc or exc2)\n self.done.exception() # remove _tb_logger\n else:\n self.done.set_result(None)\n\n def data_received(self, data):\n\n response_chunk = data.decode()\n LoggingManager().log(\"[ \" + str(self.id) + \" ]\" +\n \" Response from server: --|\" +\n str(response_chunk) + \"|--\"\n )\n\n self._response_chunk = response_chunk\n\n def send_message(self, message):\n\n LoggingManager().log(\"[ \" + str(self.id) + \" ]\" +\n \" Request to server: --|\" + str(message) + \"|--\"\n )\n\n # Reset response for next reqeuest\n # self._response_chunk = None\n\n # Send request\n request_chunk = message.encode('ascii')\n self.transport.write(request_chunk)\n\n\ndef process_cmd(prompt):\n\n prompt.cmdloop('Foo')\n\n\n@asyncio.coroutine\ndef handle_user_input(loop, protocol):\n \"\"\"\n Reads from stdin in separate thread\n\n If user inputs 'quit' stops the event loop\n otherwise just echoes user input\n \"\"\"\n\n # Start command interpreter\n prompt = EvaCommandInterpreter()\n prompt.prompt = '$ '\n\n prompt.set_protocol(protocol)\n\n yield from loop.run_in_executor(None, process_cmd, prompt)\n\n protocol.done.set_result(None)\n\n\nasync def start_client(loop, factory,\n host: string, port: int,\n max_retry_count: int):\n \"\"\"\n Wait for the connection to open and the task to be processed.\n\n - There's retry logic to make sure we're connecting even in\n the face of momentary ECONNRESET on the server-side.\n - Socket will be automatically closed by the exit stack.\n \"\"\"\n\n retries = max_retry_count * [1] # non-exponential 10s\n\n with ExitStack() as stack:\n while True:\n try:\n sock = stack.enter_context(socket.socket())\n sock.connect((host, port))\n connection = loop.create_connection(factory, sock=sock)\n transport, protocol = await connection\n\n except Exception:\n if not retries:\n raise RuntimeError('Client unable to connect to server')\n\n await asyncio.sleep(retries.pop(0) - random.random())\n\n else:\n break\n\n # Launch task to handle user inputs\n loop.create_task(handle_user_input(loop, protocol))\n\n await protocol.done\n\n return len(retries)\n\n\ndef start_clients(client_count: int, host: string, port: int,\n loop,\n stop_clients_future):\n \"\"\"\n Start a set of eva clients\n\n client_count: number of clients (= connections)\n hostname: hostname of the server\n port: port where the server is running\n stop_clients_future: future for externally stopping the clients\n \"\"\"\n\n LoggingManager().log('PID(' + str(os.getpid()) + ') attempting '\n + str(client_count) + ' connections')\n\n # Get a reference to the event loop\n # loop = asyncio.get_event_loop()\n\n max_retry_count = 3\n\n # Create client tasks\n client_coros = [\n start_client(loop, lambda: EvaClient(),\n host, port,\n max_retry_count\n )\n for i in range(client_count)\n ]\n\n # Start a set of clients\n clients = loop.create_task(\n asyncio.wait([loop.create_task(client_coro)\n for client_coro in client_coros]\n )\n )\n\n try:\n stop_clients_future = asyncio.wait([clients])\n loop.run_until_complete(stop_clients_future)\n\n except KeyboardInterrupt:\n LoggingManager().log(\"client process interrupted\")\n\n finally:\n LoggingManager().log(\"client process shutdown\")\n\n # tasks, exceptions, retries\n summary = [0, 0, 0]\n\n if clients.done():\n done, _ = clients.result()\n exceptions = sum(1 for d in done if d.exception())\n retries = sum(\n max_retry_count - d.result()\n for d in done if not d.exception()\n )\n tasks = len(client_coros)\n\n LoggingManager().log(str(tasks) + ' tasks, ' +\n str(exceptions) + ' exceptions, ' +\n str(retries) + ' retries'\n )\n\n summary = [tasks, exceptions, retries]\n\n # Close loop\n loop.close()\n\n return summary\n","sub_path":"src/server/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"528296888","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom openapi_server.models.base_model_ import Model\nfrom openapi_server.models.meta_attribute import MetaAttribute\nfrom openapi_server import util\n\nfrom openapi_server.models.meta_attribute import MetaAttribute # noqa: E501\n\nclass MetaNode(Model):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n\n Do not edit the class manually.\n \"\"\"\n\n def __init__(self, id_prefixes=None, attributes=None): # noqa: E501\n \"\"\"MetaNode - a model defined in OpenAPI\n\n :param id_prefixes: The id_prefixes of this MetaNode. # noqa: E501\n :type id_prefixes: List[str]\n :param attributes: The attributes of this MetaNode. # noqa: E501\n :type attributes: List[MetaAttribute]\n \"\"\"\n self.openapi_types = {\n 'id_prefixes': List[str],\n 'attributes': List[MetaAttribute]\n }\n\n self.attribute_map = {\n 'id_prefixes': 'id_prefixes',\n 'attributes': 'attributes'\n }\n\n self._id_prefixes = id_prefixes\n self._attributes = attributes\n\n @classmethod\n def from_dict(cls, dikt) -> 'MetaNode':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The MetaNode of this MetaNode. # noqa: E501\n :rtype: MetaNode\n \"\"\"\n return util.deserialize_model(dikt, cls)\n\n @property\n def id_prefixes(self):\n \"\"\"Gets the id_prefixes of this MetaNode.\n\n List of CURIE prefixes for the node category that this TRAPI web service understands and accepts on the input. # noqa: E501\n\n :return: The id_prefixes of this MetaNode.\n :rtype: List[str]\n \"\"\"\n return self._id_prefixes\n\n @id_prefixes.setter\n def id_prefixes(self, id_prefixes):\n \"\"\"Sets the id_prefixes of this MetaNode.\n\n List of CURIE prefixes for the node category that this TRAPI web service understands and accepts on the input. # noqa: E501\n\n :param id_prefixes: The id_prefixes of this MetaNode.\n :type id_prefixes: List[str]\n \"\"\"\n if id_prefixes is None:\n raise ValueError(\"Invalid value for `id_prefixes`, must not be `None`\") # noqa: E501\n if id_prefixes is not None and len(id_prefixes) < 1:\n raise ValueError(\"Invalid value for `id_prefixes`, number of items must be greater than or equal to `1`\") # noqa: E501\n\n self._id_prefixes = id_prefixes\n\n @property\n def attributes(self):\n \"\"\"Gets the attributes of this MetaNode.\n\n Node attributes provided by this TRAPI web service. # noqa: E501\n\n :return: The attributes of this MetaNode.\n :rtype: List[MetaAttribute]\n \"\"\"\n return self._attributes\n\n @attributes.setter\n def attributes(self, attributes):\n \"\"\"Sets the attributes of this MetaNode.\n\n Node attributes provided by this TRAPI web service. # noqa: E501\n\n :param attributes: The attributes of this MetaNode.\n :type attributes: List[MetaAttribute]\n \"\"\"\n\n self._attributes = attributes\n","sub_path":"code/UI/OpenAPI/python-flask-server/KG2/openapi_server/models/meta_node.py","file_name":"meta_node.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"469703937","text":"from selenium import webdriver\nfrom datetime import datetime\nimport time,re\n\nclass Snapdeal:\n def __init__(self):\n self.name = 'snapdeal'\n\n def Driver(self):\n self.driver = webdriver.Firefox()\n\n def closeDriver(self):\n self.driver.close()\n\n def scrapeData(self, url, df):\n self.driver.get(url)\n driver = self.driver\n driver = self.driver\n\n try:\n driver.find_element_by_css_selector('.sd-icon.sd-icon-delete-sign').click()\n except:\n pass\n attributes = driver.find_elements_by_css_selector('.linear_list')\n def getData(element):\n for attribute in attributes:\n if attribute.find_element_by_css_selector('.col1').text == element:\n return attribute.find_element_by_css_selector('.col2').text\n \n PID = url.split('/')[-1]\n URL_raw = url\n try:\n Title = driver.find_element_by_css_selector('.pdp-e-i-head').text\n except:\n Title = ''\n try:\n Brand = driver.find_element_by_css_selector('.pdp-e-brand-logo-img').find_element_by_tag_name('img').get_attribute('alt')\n except:\n Brand = ''\n try:\n Seller = driver.find_element_by_css_selector('.pdp-e-seller-info-name.reset-margin').text\n except:\n Seller = ''\n try:\n IMG_medium = driver.find_element_by_css_selector('#bx-slider-left-image-panel').find_element_by_tag_name('img').get_attribute('src')\n except:\n IMG_medium = ''\n try:\n IMG_large = driver.find_element_by_css_selector('#bx-slider-left-image-panel').find_element_by_tag_name('img').get_attribute('bigsrc')\n except:\n IMG_large = ''\n try:\n Price_mrp = driver.find_element_by_css_selector('.pdpCutPrice').text.strip().replace('\"','').replace(',','').replace('Rs.','').strip()\n except:\n Price_mrp = ''\n try:\n Price_selling = driver.find_element_by_css_selector('.payBlkBig').text.strip().replace(',','')\n except:\n Price_selling = Price_mrp\n\n if Price_mrp == '':\n Price_mrp = Price_selling\n\n try:\n pincode = driver.find_element_by_css_selector('#pincode-check')\n pincode.send_keys('110001')\n driver.find_element_by_id('pincode-check-bttn').click()\n time.sleep(2)\n except:\n pass\n try:\n Price_shipping = driver.find_element_by_css_selector('.freeDeliveryChargeCls').text\n if 'Free' in Price_shipping:\n Price_shipping = 0\n elif 'Delivery' in Price_shipping:\n Price_shipping = re.findall(r'\\d+',Price_shipping.replace(', Delivery Charges : +Rs',''))[0]\n except:\n try:\n Price_shipping = driver.find_element_by_css_selector('.freeDeliveryChargeCls.freeDeliveryCharge').text\n if 'Free' in Price_shipping:\n Price_shipping = 0\n elif 'Delivery' in Price_shipping:\n Price_shipping = re.findall(r'\\d+',Price_shipping.replace(', Delivery Charges : +Rs',''))[0]\n except:\n try:\n Price_shipping = driver.find_element_by_css_selector('.rsInfo.addPrice.delivery-charges').text\n if 'Free' in Price_shipping:\n Price_shipping = 0\n elif 'Delivery' in Price_shipping:\n Price_shipping = re.findall(r'\\d+',Price_shipping.replace(', Delivery Charges : +Rs',''))[0]\n except:\n Price_shipping = ''\n try:\n Delivery = driver.find_element_by_css_selector('.otoDRange').text\n Delivery = re.findall(r'\\d+\\s-\\s\\d+\\sday', Delivery)[0]\n except:\n Delivery = ''\n try:\n driver.find_element_by_css_selector('#pincode-cod')\n COD = 'Available'\n except:\n COD = 'Not Available'\n try:\n driver.find_element_by_css_selector('.pdp-emi')\n EMI = 'Available'\n except:\n EMI = 'Not Available'\n try:\n breadcrums = driver.find_element_by_css_selector('.bread-crumb').find_elements_by_tag_name('a')\n b = ''\n for bread in breadcrums:\n b = b + '|' + bread.text.strip()\n Category_path = b[1:]\n except:\n Category_path = ''\n try:\n Description = driver.find_element_by_css_selector('#productSpecs').text\n except:\n Description = ''\n\n try:\n Offers = driver.find_element_by_css_selector('.row.pdp-e-i-alloffers').text.split('\\n')[0]\n except:\n Offers = ''\n try:\n Average_rating = driver.find_element_by_css_selector('.product_review').find_element_by_tag_name('span').text\n try:\n Num_Review = driver.find_element_by_css_selector('.review_land.js-jl-omni.js-pdp-nav-sec').text.replace('Reviews','').strip()\n except:\n Num_Review = ''\n Average_rating = Average_rating + '(' + Num_Review+')'\n \n except:\n Average_rating = ''\n try:\n Reviews = ''\n reviews = driver.find_elements_by_css_selector('.commentlist.first.jsUserAction')[:10]\n for review in reviews:\n author = review.find_element_by_css_selector('._reviewUserName').text\n date = review.find_element_by_css_selector('.date.LTgray').text\n description = review.find_element_by_tag_name('p').text.replace('\\n','')\n Reviews += str({'author':author, 'date':date, 'description':description}) + \"; \"\n Reviews = Reviews[:-1]\n except:\n Reviews = ''\n try:\n if driver.find_element_by_css_selector('.intialtext').text.strip()=='BUY NOW':\n Status = 'IN STOCK'\n else:\n Status = 'OUT OF STOCK'\n except:\n Status = 'OUT OF STOCK'\n\n Condition = 'NEW'\n TimeStamp = str(datetime.now())\n\n nrow = df.shape[0]\n df.loc[nrow+1] = [PID, URL_raw, Title, Brand,Seller, IMG_medium, IMG_large, Price_mrp, Price_selling, Price_shipping, Delivery,\\\n COD,EMI, Category_path,Description,Offers,Average_rating,Reviews,Status,Condition,TimeStamp]\n\n return df\n","sub_path":"e-commerce-scraper3/e-commerce1/e-commerce/snapdeal.py","file_name":"snapdeal.py","file_ext":"py","file_size_in_byte":6517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"484764765","text":"import bpy\nimport math\nimport sys\nimport os\nimport json\nimport numpy as np\nfrom mathutils import Vector\n\ndef getDirection(camera):\n\t#Y = np.tan(np.deg2rad(camera.angle_x / 2))\n\t#Z = np.tan(np.deg2rad(camera.angle_y / 2))\n\tY = np.tan(bpy.data.cameras['Camera.001'].angle_x / 2)\n\tZ = np.tan(bpy.data.cameras['Camera.001'].angle_y / 2)\n\n\treturn (-1, Y, Z)\n\ndef getDirections(obj, camera, cameraWidth, cameraHeight, outputPath):\n\tout = open(outputPath, 'w')\n\tx, y, z = getDirection(camera)\n\n\tfor yDirection in np.linspace(-y, y, cameraWidth):\n\t\tfor zDirection in np.linspace(z, -z, cameraHeight):\n\t\t\tdst = Vector((x, yDirection, zDirection)) + camera.location\n\t\t\tdirection = Vector((x, yDirection, zDirection)) \n\n\n\t\t\tmw = obj.matrix_world\n\t\t\tmwi = mw.inverted()\n\n\t\t\t# src and dst in local space of cb\n\n\t\t\torigin = mwi * camera.location\n\t\t\tdest = mwi * dst\n\t\t\tdirection = (dest - origin).normalized()\n\n\t\t\tresult, location, normal, index = obj.ray_cast(origin, direction)\n\n\t\t\t#xPixel = int(round(((yDirection + y) / (2 * y)) * cameraWidth))\n\t\t\t#yPixel = int(round(((-zDirection + z) / (2 * z)) * cameraHeight))\n\t\t\txPixel = ((yDirection + y) / (2 * y)) * cameraWidth\n\t\t\tyPixel = ((-zDirection + z) / (2 * z)) * cameraHeight\n\t\t\tlocationWorld = mw * location\n\t\t\tfromCamera = locationWorld - camera.location\n\n\t\t\tif result:\n\t\t\t\tout.write(str(xPixel) + \" \" + str(yPixel) + \" \" + str(fromCamera.x) + '\\n')\n\tout.close()\n\nif __name__ == \"__main__\":\n\targv = sys.argv\n\targv = argv[argv.index(\"--\") + 1:] \n\n\tbpy.ops.wm.open_mainfile(filepath=os.path.abspath(argv[0]))\n\n\toutputPath = os.path.abspath(argv[1])\n\tcameraWidth = int(argv[2])\n\tcameraHeight = int(argv[3])\n\n\tsingleObject = None\n\n\tfor ob in bpy.context.scene.objects:\n\t\tif ob.type == 'MESH':\n\t\t\tob.select = True\n\t\t\tbpy.context.scene.objects.active = ob\t\t\t\n\t\telse:\n\t\t\tob.select = False\n\n\tbpy.ops.object.join()\n\n\tfor ob in bpy.context.scene.objects:\n\t\tif ob.type == 'MESH':\n\t\t\tsingleObject = ob\n\n\n\tgetDirections(singleObject, bpy.context.scene.camera, cameraWidth, cameraHeight, outputPath)\n\n\t\n","sub_path":"RaycastDepth.py","file_name":"RaycastDepth.py","file_ext":"py","file_size_in_byte":2033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"275579240","text":"import pytest\nfrom juggler import model\nfrom juggler.model import states as s\nfrom juggler.handlers import inbox\n\nfrom testing import with_quick_change_timeout\n\n\n@with_quick_change_timeout\ndef test_inbox_simple_validate(db):\n #XXX: test a invalid case\n order = model.Order(_id='order', status=s.received)\n db.save_doc(order)\n inbox.order_validate(db)\n db.refresh(order)\n assert order.status == s.valid\n\n\n@with_quick_change_timeout\ndef test_valid_order_simple_ready(db):\n order = model.Order(status=s.valid)\n db.save_doc(order)\n inbox.valid_order_prepare(db)\n db.refresh(order)\n assert order.status == s.ready\n\n\n@with_quick_change_timeout\n@pytest.mark.parametrize(('axis', 'specs'), [\n (None, [{}]),\n ({'test': ['a', 'b']}, [\n {'test': 'a'},\n {'test':'b'}\n ]),\n], ids=['nospec', 'somespec'])\ndef test_ready_order_generate_tasks(db, axis, specs):\n order = model.Order(status='ready', axis=axis)\n db.save_doc(order)\n inbox.ready_order_generate_tasks(db)\n db.refresh(order)\n assert order.status == 'building'\n\n items = db._.bulk_save.call_args[0][0]\n saved_order = items.pop(0)\n\n assert saved_order._doc == order._doc\n for task, spec in zip(items, specs):\n\n assert task.spec == spec\n","sub_path":"testing/handlers/test_inbox.py","file_name":"test_inbox.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"368572238","text":"from flask import Flask, redirect, url_for, request, render_template\r\nfrom booth import booth\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n@app.route('/booths')\r\ndef booths(n1):\r\n numbers = n1.split(\",\")\r\n result, output = booth(int(numbers[0]), int(numbers[1]))\r\n return \"%s Result %s\" % (output, str(result))\r\n\r\n\r\n@app.route('/test')\r\ndef test():\r\n return \"success....\"\r\n\r\n\r\n@app.route('/')\r\ndef my_form():\r\n return render_template(\"input.html\") # Set render templates\r\n\r\n\r\n@app.route('/', methods=['POST'])\r\ndef getnum():\r\n num1 = request.form['num1']\r\n num2 = request.form['num2']\r\n numbers = str(num1) + \",\" + str(num2)\r\n return redirect(url_for('booths', n1=numbers))\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()\r\n","sub_path":"Final Codes CL3/New Booths/booths_flask.py","file_name":"booths_flask.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"10165885","text":"import urllib.request\nimport base64\nimport mmh3\nimport json\nimport requests\nimport os\n\n# get the env variables defined in the env file\nenvfile = open(\".envs\")\nenvs = {}\nfor line in envfile:\n linesplit = line.split(':')\n try:\n if linesplit[0].strip()[0] != '#':\n envs.update({linesplit[0].strip(): linesplit[1].strip()})\n except:\n pass\n\ndef validate():\n email_message = ''\n already_sent = None\n if os.path.exists('processed.json'):\n sent_json_file = open('processed.json')\n already_sent = json.load(sent_json_file)\n sent_json_file.close()\n\n with open('saved.json') as json_file:\n data = json.load(json_file)\n if not already_sent:\n already_sent = {}\n\n for p in data:\n try:\n with urllib.request.urlopen(p) as response:\n html = response.read()\n encoded = base64.b64encode(html)\n hashed = mmh3.hash128(encoded, 42, signed = True)\n\n mark = True\n if p in already_sent:\n if already_sent[p]:\n mark = False\n\n if mark:\n if data[p] != hashed:\n email_message += \"- Failed Hash for: \" + str(p) + '\\r\\n'\n already_sent[p] = True\n except:\n email_message += \"- Failed EXCEPTION for: \" + str(p) + '\\r\\n'\n\n if email_message != '':\n email_error(email_message, already_sent)\n\ndef email_error(message, mark_sent):\n try:\n requests.post(\"https://api.mailgun.net/v3/mg.bcinnovationsonline.com/messages\",\n auth=(\"api\", envs['MAILGUN_KEY']),\n data={\"from\": \"BC Innovations \",\n \"to\": [envs['ALERT_EMAIL']],\n \"subject\": \"UpTime Alert\",\n \"text\": message})\n\n with open('processed.json', 'w') as outfile:\n json.dump(mark_sent, outfile)\n\n except:\n pass\n\nvalidate()\n","sub_path":"uptime.py","file_name":"uptime.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"77205790","text":"\"\"\"\r\n2d matrix for edges\r\nset weight\r\n0 when source and destination is same\r\ninfinity if no direct path\r\n\r\nif distance between 2 vertices is greater than the distance between source vertex via x + distance between viax to destination vertex \r\na = b + c\r\n\r\nv times - via each vertex\r\n\r\nnot for negative cycle\r\n\r\nO(v cube), O(V square)\r\n\"\"\"\r\n\r\nINF = 9999\r\n# Printing the solution\r\ndef printSolution(nV, distance):\r\n for i in range(nV):\r\n for j in range(nV):\r\n if(distance[i][j] == INF):\r\n print(\"INF\", end=\" \")\r\n else:\r\n print(distance[i][j], end=\" \")\r\n print(\" \")\r\n\r\n\r\ndef floydWarshall(nV, G):\r\n distance = G\r\n for k in range(nV):\r\n for i in range(nV):\r\n for j in range(nV):\r\n distance[i][j] = min(distance[i][j], distance[i][k]+distance[k][j])\r\n \r\n printSolution(nV, distance)\r\n\r\nG = [[0, 8, INF,1],\r\n [INF, 0, 1,INF],\r\n [4, INF, 0,INF],\r\n [INF, 2, 9,1]\r\n ]\r\n\r\nfloydWarshall(4, G)\r\n\r\n","sub_path":"zzz_dsa/python_dsa_1/087_floyd_warshall_algo_all_pair_sp.py","file_name":"087_floyd_warshall_algo_all_pair_sp.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"419532642","text":"#!/usr/bin/env python\n\nimport re\nimport requests\n\nSENSU = [\n \"http://prod-sc-sensu-api-01.otsql.open-tabe.com:4567\",\n \"http://prod-ln-sensu-api-01.otsql.open-tabe.com:4567\",\n \"http://prod-usw2-sensu-api-01.otsql.open-tabe.com:4567\",\n \"http://prod-usw1-sensu-api-01.otsql.open-tabe.com:4567\",\n \"http://pp-sf-sensu-api-01.qasql.open-tabe.com:4567\",\n]\n\nSHIT_WE_CARE_ABOUT = \"\"\"\nuser dmoes {\nuid 2015;\nclass super-user;\n}\n\"\"\".splitlines()\n\nLINES = [line.strip() for line in SHIT_WE_CARE_ABOUT if line.strip()]\n\ndef fetch_events(sensu):\n url = f\"{sensu}/events\"\n return requests.get(url).json()\n\ndef extract_diff(event):\n if \"ansible_vs_runtime\" in event[\"check\"][\"name\"]:\n output = event[\"check\"][\"output\"]\n lines = output.splitlines()\n for line in lines:\n if line.strip().startswith(\"Details\"):\n _detail, diffurl = line.split(\":\", 1)\n return diffurl.strip()\n\ndef ignore_line(line):\n return line.startswith(\"#\") or re.match(r'^\\[.+\\]$', line) or line == \"system { ... }\"\n\ndef remove_irrelevant(diff):\n lines = diff.splitlines()\n simplified = []\n for line in lines:\n stripped = re.sub(r'^[-+\\s]*', '', line.strip())\n if not ignore_line(stripped):\n simplified.append(stripped)\n return simplified\n\ndef main():\n for sensu in SENSU:\n events = fetch_events(sensu)\n for event in events:\n diffurl = extract_diff(event)\n if not diffurl:\n continue\n result = requests.get(diffurl)\n simplified = remove_irrelevant(result.text)\n # print(simplified)\n if simplified == LINES:\n # print(\"\\n\".join(simplified))\n print(event[\"client\"][\"name\"])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Devices_with_required_diff.py","file_name":"Devices_with_required_diff.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"61754032","text":"import wx\nfrom OkCancelPanel import OkCancelPanel \nfrom NumberTextControl import NumberTextControl\nfrom Vicarious.DataStore.DataStoreConnection import DataStoreConnection\nfrom Vicarious.DataStore.edfreader import EDFReader\nfrom Components.SettingsHelpers import *\nimport os \n\nclass EDFImportDialog(wx.Dialog):\n\n def __init__(self, parent, model,filename):\n super(EDFImportDialog, self).__init__(parent=parent, \n title=\"EDF or EDA Import\")\n \n self.model = model\n self.db=self.model.getDBConnection(False)\n\n if filename[-4:].lower()==\".eda\":\n isEDA=True\n else:\n isEDA=False\n \n if isEDA:\n self.reader=EDFReader(filename,EDFReader.EDA_FILE)\n else:\n self.reader=EDFReader(filename,EDFReader.EDF_FILE)\n edfHeader=self.reader.getEDFHeaderInfo()\n \n streamList=[]\n for c in range(int(edfHeader['numSignals'])):\n info=self.reader.getEDFStreamInfo(c)\n streamList.append(info['label'])\n\n vbox=wx.BoxSizer(wx.VERTICAL)\n \n sb = wx.StaticBox(self, label='DB Session Name')\n sbs = wx.StaticBoxSizer(sb, orient=wx.VERTICAL)\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n hbox.Add(wx.StaticText(self,-1,\"Name\"),proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT,border=5)\n self.sessionName = wx.TextCtrl(self, value=\"Import: %s\"%os.path.basename(filename)) \n\n self.sessionChoice=wx.ComboBox(self,-1,choices=[],style=wx.CB_READONLY)\n \n self.sessionChoice.Bind(wx.EVT_COMBOBOX,self.onSelectSession)\n allSessions=self.db.listSessions()\n for (id,name) in allSessions:\n self.sessionChoice.Append(name,int(id))\n\n hbox.Add(self.sessionName,proportion=1,flag=wx.EXPAND) \n sbs.Add(hbox,flag=wx.EXPAND)\n sbs.Add(self.sessionChoice,flag=wx.EXPAND)\n vbox.Add(sbs,flag=wx.EXPAND|wx.ALL,border=5) \n \n sb = wx.StaticBox(self, label='Streams')\n sbs = wx.StaticBoxSizer(sb, orient=wx.VERTICAL) \n self.streamList=wx.CheckListBox(self,choices=streamList) \n sbs.Add(self.streamList,border=5,flag=wx.EXPAND)\n vbox.Add(sbs,flag=wx.EXPAND|wx.ALL,border=5) \n \n sb = wx.StaticBox(self, label='Time Zone')\n sbs = wx.StaticBoxSizer(sb, orient=wx.VERTICAL)\n hbox = wx.BoxSizer(wx.HORIZONTAL)\n hbox.Add(wx.StaticText(self,-1,\"GMT +\"),proportion=0,flag=wx.LEFT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_RIGHT,border=5)\n if isEDA:\n self.timeOffset = NumberTextControl(self, value=edfHeader['hoursOffset']) \n self.timeOffset.Disable()\n else:\n self.timeOffset = NumberTextControl(self, value=\"0\") \n hbox.Add(self.timeOffset,proportion=1,flag=wx.EXPAND) \n hbox.Add(wx.StaticText(self,-1,\" hours\"),proportion=0,flag=wx.RIGHT|wx.ALIGN_CENTER_VERTICAL|wx.ALIGN_LEFT,border=5)\n sbs.Add(hbox,flag=wx.EXPAND)\n vbox.Add(sbs,flag=wx.EXPAND|wx.ALL,border=5) \n \n self.okCancel=OkCancelPanel(self,self.OnOK,self.OnClose)\n vbox.Add(self.okCancel, flag= wx.ALIGN_CENTER|wx.TOP|wx.BOTTOM, border=10)\n self.SetSizerAndFit(vbox) \n\n def OnClose(self, e): \n self.Destroy()\n\n def onSelectSession(self,event):\n self.sessionName.SetValue(self.sessionChoice.GetValue())\n \n def OnOK(self, e):\n importStreamList=list(self.streamList.GetChecked())\n if len(importStreamList)==0:\n mdlg = wx.MessageDialog(self, \"No streams selected to import\", 'Error', wx.OK|wx.ICON_ERROR)\n mdlg.ShowModal()\n mdlg.Destroy()\n return\n sessionName=self.sessionName.GetValue()\n sessionName=sessionName.strip()\n sessionName=sanitizeSettingsString(sessionName) \n if len(sessionName)==0:\n mdlg = wx.MessageDialog(self, \"Please enter a name for the new database session\", 'Error', wx.OK|wx.ICON_ERROR)\n mdlg.ShowModal()\n mdlg.Destroy()\n return\n if self.timeOffset.IsEnabled():\n timeOffset=self.timeOffset.GetValue()\n self.reader.readEDFSignalIntoDBConnection(self.db,importStreamList,sessionName,timeOffset=timeOffset)\n else:\n self.reader.readEDFSignalIntoDBConnection(self.db,importStreamList,sessionName) \n self.Destroy()\n","sub_path":"Vicarious/Vicarious/Application/Components/Dialogs/EDFImportDialog.py","file_name":"EDFImportDialog.py","file_ext":"py","file_size_in_byte":4521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"304033213","text":"import pygame\r\npygame.init()\r\nimport sys\r\nfrom settings import *\r\nfrom player import *\r\nimport pygame.math as m\r\nfrom enemy import *\r\nimport copy\r\n\r\n\r\n\r\n\r\nclass App:\r\n def __init__(self):\r\n self.screen = pygame.display.set_mode((SCREEN_WIDTH , SCREEN_HEIGHT))\r\n self.clock = pygame.time.Clock()\r\n self.run = True\r\n self.state = \"start\"\r\n self.cells = []\r\n self.cell_width = 20\r\n self.cell_height = 20\r\n self.player = Player(self , m.Vector2(13 , 29))\r\n self.walls = []\r\n self.coins = []\r\n self.enemies = []\r\n self.high = self.get_high_score()\r\n self.enemy_position = []\r\n self.load()\r\n self.draw_enemies()\r\n self.start_music()\r\n def running(self):\r\n\r\n while self.run == True:\r\n self.clock.tick(FPS)\r\n if self.state == \"start\":\r\n self.start_events()\r\n self.start_redraw()\r\n if self.state == \"play\":\r\n self.play_events()\r\n self.play_redraw()\r\n if self.state == \"over\":\r\n self.game_over_event()\r\n self.game_over_redraw()\r\n pygame.quit()\r\n sys.exit()\r\n\r\n def draw_text(self , text , screen , font_type , font_size , font_color , pos , centered = False):\r\n font = pygame.font.SysFont(font_type , font_size)\r\n text = font.render(text , False , font_color)\r\n if centered:\r\n pos[0] = pos[0] - text.get_size()[0] // 2\r\n pos[1] = pos[1] - text.get_size()[1] // 2\r\n\r\n screen.blit(text , pos)\r\n def load(self):\r\n self.background = pygame.image.load(\"maze.png\")\r\n with open(\"walls.txt\") as file:\r\n lines = file.readlines()\r\n for line in lines:\r\n self.cells.append(line)\r\n for i in range(ROW):\r\n for j in range(COL):\r\n if self.cells[i][j] == \"1\":\r\n self.walls.append(m.Vector2(j, i))\r\n if self.cells[i][j] == \"C\":\r\n self.coins.append(m.Vector2(j, i))\r\n if self.cells[i][j] == \"B\":\r\n pygame.draw.rect(self.background , black , (j * self.cell_width , i * self.cell_height , self.cell_width , self.cell_height) , 0)\r\n if self.cells[i][j] in [\"2\" , \"3\" , \"4\" , \"5\"]:\r\n self.enemy_position.append(m.Vector2(j , i ))\r\n\r\n def start_music(self):\r\n pygame.mixer.music.load(\"pacman_beginning.wav\")\r\n pygame.mixer.music.play(-1)\r\n def play_music(self):\r\n pygame.mixer.music.load(\"Pac_Man_Ghost_Noises.mp3\")\r\n pygame.mixer.music.play(-1)\r\n\r\n\r\n def draw_grid(self):\r\n pass\r\n # for i in range(SCREEN_WIDTH//self.cell_width):\r\n # pygame.draw.line(self.background , red , (i * self.cell_width , 0) , (i * self.cell_width , MAZE_HEIGHT) , 1)\r\n # for i in range(SCREEN_WIDTH//self.cell_width):\r\n # pygame.draw.line(self.background , red , (0 , self.cell_height*i) , (MAZE_WIDTH , self.cell_height*i) , 1)\r\n #\r\n # for wall in self.walls:\r\n # pygame.draw.rect(self.background, GREEN, (wall.x * self.cell_width, wall.y * self.cell_height, self.cell_width, self.cell_height), 0)\r\n\r\n\r\n def draw_enemies(self):\r\n for idx , pos in enumerate(self.enemy_position):\r\n new_enemy = Enemy(self , copy.deepcopy(pos) , idx)\r\n self.enemies.append(new_enemy)\r\n\r\n def reset_enemies(self):\r\n self.enemies = []\r\n self.draw_enemies()\r\n\r\n def reset(self):\r\n self.player.score = 0\r\n self.player.lives = 3\r\n self.player.grid_pos = m.Vector2(13 , 29)\r\n self.player.pix_pos = self.player.get_pix_pos()\r\n\r\n self.player.pix_pos = self.player.get_pix_pos()\r\n self.player.direction - m.Vector2(0 , 0)\r\n self.player.stored_direction = m.Vector2(0, 0)\r\n for enemy in self.enemies:\r\n enemy.pix_pos = enemy.get_pix_pos()\r\n enemy.direction = m.Vector2(0 , 0)\r\n self.coins = []\r\n for row in range(ROW):\r\n for col in range(COL):\r\n if self.cells[row][col] == 'C':\r\n self.coins.append(m.Vector2(col, row))\r\n\r\n self.reset_enemies()\r\n\r\n # start screen\r\n def get_high_score(self):\r\n # connection = sqlite3.connect('high_score.db')\r\n # cursor = connection.cursor()\r\n # cursor.execute('CREATE TABLE IF NOT EXISTS HIGHSCORE (Number REAL)')\r\n # cursor.execute('')\r\n with open(\"High Score\") as file:\r\n high = int(file.readline().split(\" \")[2])\r\n return high\r\n\r\n def start_events(self):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n self.run = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE:\r\n self.state = \"play\"\r\n self.play_music()\r\n\r\n def start_redraw(self):\r\n self.screen.fill(black)\r\n self.draw_text(\"HIGH SCORE: \" + str(self.high) , self.screen , default_font , default_size , white , [0 , 0])\r\n self.draw_text(\"PUSH SPACE BAR\" , self.screen , default_font , default_size , red , [SCREEN_WIDTH//2 , SCREEN_HEIGHT//3 + 50] , centered=True)\r\n self.draw_text(\"1 PLAYER ONLY\" , self.screen , default_font , default_size , blue , [SCREEN_WIDTH//2 , 2*SCREEN_HEIGHT//3 - 50] , True)\r\n pygame.display.update()\r\n\r\n def sart_music(self):\r\n pygame.mixer.music.load(\"pacman_beginning.wav\")\r\n pygame.mixer.music.play(-1)\r\n\r\n# play screen\r\n\r\n def play_events(self):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n self.run = False\r\n\r\n\r\n self.keys_pressed = pygame.key.get_pressed()\r\n if self.keys_pressed[pygame.K_UP] == True:\r\n self.player.move(m.Vector2(0 , -1))\r\n if self.keys_pressed[pygame.K_LEFT] == True:\r\n self.player.move(m.Vector2(-1 , 0))\r\n if self.keys_pressed[pygame.K_DOWN] == True:\r\n self.player.move(m.Vector2(0 , 1))\r\n if self.keys_pressed[pygame.K_RIGHT] == True:\r\n self.player.move(m.Vector2(1 , 0))\r\n\r\n def draw_coins(self):\r\n for coin in self.coins:\r\n pygame.draw.circle(self.screen, WHITE, (TOP_BOTTOM//2 + coin.x * self.cell_width + self.cell_width // 2, TOP_BOTTOM//2 +coin.y * self.cell_height + self.cell_height // 2),self.cell_width // 2 - 8, 0)\r\n\r\n def play_redraw(self):\r\n self.screen.fill(black)\r\n self.screen.blit(self.background , (TOP_BOTTOM//2 , TOP_BOTTOM//2))\r\n self.draw_text(\"CURRENT SCORE: \" + str(self.player.score), self.screen, default_font, default_size, white, [60 , 0])\r\n self.draw_text(\"HIGH SCORE:\" + str(self.high), self.screen, default_font, default_size, white, [SCREEN_WIDTH//2 + 50 , 0])\r\n self.draw_grid()\r\n self.draw_coins()\r\n self.player.draw()\r\n # print(self.enemies)\r\n for enemy in self.enemies:\r\n enemy.draw()\r\n pygame.display.update()\r\n\r\n def game_over_event(self):\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n self.run = False\r\n if pygame.key.get_pressed()[pygame.K_ESCAPE] == True:\r\n self.run = False\r\n if pygame.key.get_pressed()[pygame.K_SPACE] == True:\r\n self.state = \"play\"\r\n self.reset()\r\n\r\n def game_over_redraw(self):\r\n self.screen.fill(black)\r\n self.draw_text(\"GAME OVER\", self.screen, default_font, default_size, red , [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2], centered=True)\r\n self.draw_text(\"PRESS ESCAPE TO QUIT\" , self.screen, default_font , default_size - 5 , white , [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 50] , centered=True )\r\n self.draw_text(\"PRESS SPACE TO RESTART\" , self.screen, default_font , default_size - 5 , white , [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 50] , True)\r\n\r\n pygame.display.update()\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"app_class.py","file_name":"app_class.py","file_ext":"py","file_size_in_byte":8139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"46406456","text":"from math import sqrt\nimport numpy as np\n\ninp = open('3232_PTE.jo', 'r')\n\n# hovno\n# inp=open('2_blok.jo','r')\n\n\n##### FUNKCE #####\ndef read_uzly(file):\n file.seek(0)\n in_pole = False\n in_data = False\n uzly = {}\n for line in file.readlines():\n if in_data == True and line != '\\n': # cteni z tabulky\n data = line.split()\n ozn = ((data[1]).replace('\\'', '')).replace('\\\"', '')\n uzly[ozn] = []\n if data[2].count('-') > 1:\n uzly[ozn].append(float(data[4]))\n uzly[ozn].append(float(data[5]))\n uzly[ozn].append(float(data[6]))\n else:\n uzly[ozn].append(float(data[7]))\n uzly[ozn].append(float(data[8]))\n uzly[ozn].append(float(data[9]))\n\n # hledani tabulky\n if line.count('ROZSIRENA TABULKA VETVI') == 1:\n in_pole = True\n if in_pole == True and line.count('uzel1') == 1:\n in_data = True\n if in_pole == True and in_data == True and line == '\\n':\n break\n print('Nacteno %i uzlu' % len(uzly.keys()))\n return uzly\n\n\ndef read_prurezy(file): # zatim pouze trubkove (1), ostatni typy prurezu jsou ignorovany\n file.seek(0)\n pole = {}\n sec_ID = 0\n read = True\n in_pole = False\n while read == True:\n line = file.readline()\n if line.count('3333') == 1: # zacatek hledaneho pole\n in_pole = True\n if line.count('4444') == 1: # zacatek dalsiho pole -> konec cteni\n in_pole = False\n read = False\n\n if in_pole == True:\n try:\n if int(line.split()[0]) > sec_ID and int(line.split()[1]) == 1: # pouze trubkove prurezy\n pole[line.split()[0]] = line\n sec_ID = int(line.split()[0])\n except:\n pass\n return pole\n\n\ndef read_materialy(file): # nacteni materialu\n file.seek(0)\n pole = []\n mat_ID = 0\n read = True\n in_pole = False\n while read == True:\n line = file.readline()\n if line.count('2222') == 1: # zacatek hledaneho pole\n in_pole = True\n if line.count('3333') == 1: # zacatek dalsiho pole -> konec cteni\n in_pole = False\n read = False\n\n if in_pole == True:\n try:\n if int(line.split()[0]) > mat_ID and line.count('2222') != 1:\n pole.append(line)\n except:\n pass\n mat = {}\n temp = 0\n mat_ID = 0\n for line in pole:\n if len(mat) == 0: # prvni radek\n mat_ID = line.split()[0]\n mat[mat_ID] = {}\n try:\n pozn = line.split(':')[1][:-1]\n except:\n pozn = ''\n temp = int(line.split()[1])\n mat[mat_ID][temp] = []\n mat[mat_ID]['pozn'] = pozn\n mat[mat_ID][temp].append(((line.split()[2]).replace('-', 'E-')).replace('+', 'E+')) # E - modul pr. v tahu\n mat[mat_ID][temp].append(\n ((line.split()[6]).replace('-', 'E-')).replace('+', 'E+')) # alfa - souc. tepl. roztaznosti\n mat[mat_ID][temp].append(((line.split()[7]).replace('-', 'E-')).replace('+', 'E+')) # rho - merna hmotnost\n if int(line.split()[1]) > temp: # dalsi teplota\n temp = int(line.split()[1])\n mat[mat_ID][temp] = []\n mat[mat_ID][temp].append(((line.split()[2]).replace('-', 'E-')).replace('+', 'E+')) # E - modul pr. v tahu\n mat[mat_ID][temp].append(\n ((line.split()[6]).replace('-', 'E-')).replace('+', 'E+')) # alfa - souc. tepl. roztaznosti\n mat[mat_ID][temp].append(((line.split()[7]).replace('-', 'E-')).replace('+', 'E+')) # rho - merna hmotnost\n else: # novy material\n mat_ID = line.split()[0]\n mat[mat_ID] = {}\n try:\n pozn = line.split(':')[1][:-1]\n except:\n pozn = ''\n temp = int(line.split()[1])\n mat[mat_ID][temp] = []\n mat[mat_ID]['pozn'] = pozn\n mat[mat_ID][temp].append(((line.split()[2]).replace('-', 'E-')).replace('+', 'E+')) # E - modul pr. v tahu\n mat[mat_ID][temp].append(\n ((line.split()[6]).replace('-', 'E-')).replace('+', 'E+')) # alfa - souc. tepl. roztaznosti\n mat[mat_ID][temp].append(((line.split()[7]).replace('-', 'E-')).replace('+', 'E+')) # rho - merna hmotnost\n return mat\n\n\ndef zapis_materialy(mat, file): # zapis materialu do formatu APDL\n mi = '0.3' # Poissonova konstanta\n file.write('/prep7\\n')\n file.write('\\n')\n for m in mat.keys(): # cyklus pres materialy\n teploty = list(mat[m].keys())\n teploty.remove('pozn')\n teploty.sort()\n file.write('!!! MAT,%s (%s) !!!\\n' % (m, mat[m]['pozn']))\n file.write('MPTEMP,,,,,,\\n') # vymazani teplot\n file.write('MPTEMP,,') # zapis teplot\n i = 1\n for teplota in teploty:\n if i < 6:\n file.write('%i,' % teplota)\n i += 1\n elif i == 6:\n file.write('%i\\nMPTEMP,,' % teplota)\n i = 1\n file.write('\\n')\n\n file.write('MPDATA,EX,%s,,' % m) # zapis E\n i = 1\n for teplota in teploty:\n if i < 6:\n file.write('%s,' % mat[m][teplota][0])\n i += 1\n elif i == 6:\n file.write('%s\\nMPDATA,EX,%s,,' % (mat[m][teplota][0], m))\n i = 1\n file.write('\\n')\n\n file.write('MPDATA,ALPX,%s,,' % m) # zapis alfa\n i = 1\n for teplota in teploty:\n if i < 6:\n file.write('%s,' % mat[m][teplota][1])\n i += 1\n elif i == 6:\n file.write('%s\\nMPDATA,ALPX,%s,,' % (mat[m][teplota][1], m))\n i = 1\n file.write('\\n')\n\n file.write('MPDATA,DENS,%s,,' % m) # zapis rho\n i = 1\n for teplota in teploty:\n if i < 6:\n file.write('%s,' % mat[m][teplota][2])\n i += 1\n elif i == 6:\n file.write('%s\\nMPDATA,DENS,%s,,' % (mat[m][teplota][2], m))\n i = 1\n file.write('\\n')\n\n file.write('MPDATA,PRXY,%s,,' % m) # zapis mi\n i = 1\n for teplota in teploty:\n if i < 6:\n file.write('%s,' % mi)\n i += 1\n elif i == 6:\n file.write('%s\\nMPDATA,PRXY,%s,,' % (mi, m))\n i = 1\n file.write('\\n')\n\n file.write('\\n')\n file.write('\\n')\n\n\ndef read_zatizeni(file):\n file.seek(0)\n pole = {}\n load_ID = 0\n read = True\n in_pole = False\n while read == True:\n line = file.readline()\n if line.count('5555') == 1: # zacatek hledaneho pole\n in_pole = True\n continue\n if line.count('6666') == 1: # zacatek dalsiho pole -> konec cteni\n in_pole = False\n read = False\n\n if in_pole == True:\n try:\n if int(line.split()[0]) > load_ID:\n pole[line.split()[0]] = line.split(':')[0]\n load_ID = int(line.split()[0])\n except:\n pass\n return pole\n\n\ndef read_vetve(file): # nacitani vetvi potrubniho useku\n file.seek(0)\n in_pole = False\n in_data = False\n vetve_prime = {}\n vetve_oblouky = {}\n\n for line in file.readlines():\n if in_data == True and line != '\\n': # cteni z tabulky\n data = line.split()\n if (line.split(':')[0]).count('R') == 1: # jedna se o oblouk\n vetve_oblouky[data[0] + '-' + data[1]] = {}\n vetve_oblouky[data[0] + '-' + data[1]]['MAT'] = data[2]\n vetve_oblouky[data[0] + '-' + data[1]]['SEC'] = data[3]\n vetve_oblouky[data[0] + '-' + data[1]]['ZAT'] = data[5]\n vetve_oblouky[data[0] + '-' + data[1]]['R'] = float(((line.split(':')[0]).split('R')[1]).split('-')[0])\n if len(line.split(':')) > 1:\n vetve_oblouky[data[0] + '-' + data[1]]['pozn'] = line.split(':')[1]\n else:\n vetve_oblouky[data[0] + '-' + data[1]]['pozn'] = ''\n else: # primy usek\n vetve_prime[data[0] + '-' + data[1]] = {}\n vetve_prime[data[0] + '-' + data[1]]['MAT'] = data[2]\n vetve_prime[data[0] + '-' + data[1]]['SEC'] = data[3]\n vetve_prime[data[0] + '-' + data[1]]['ZAT'] = data[5]\n if len(line.split(':')) > 1:\n vetve_prime[data[0] + '-' + data[1]]['pozn'] = line.split(':')[1]\n else:\n vetve_prime[data[0] + '-' + data[1]]['pozn'] = ''\n # hledani tabulky\n if line.count('6666') == 1:\n in_pole = True\n if in_pole == True and line.count('uzel1') == 1:\n in_data = True\n if in_pole == True and in_data == True and (line == '\\n' or line.count('7777') == 1):\n break\n print('Nacteno %i primych useku' % len(vetve_prime.keys()))\n print('Nacteno %i oblouku' % len(vetve_oblouky.keys()))\n return vetve_prime, vetve_oblouky\n\n\ndef zapis_cary(useky, souradnice, new_sec, vystup):\n vystup.write('/prep7\\n')\n for usek in useky.keys():\n kp1 = usek.split('-')[0]\n kp2 = usek.split('-')[1]\n vystup.write('\\n')\n vystup.write('k,,%f,%f,%f\\n' % (souradnice[kp1][0], souradnice[kp1][1], souradnice[kp1][2]))\n vystup.write('kp1=_return\\n')\n vystup.write('k,,%f,%f,%f\\n' % (souradnice[kp2][0], souradnice[kp2][1], souradnice[kp2][2]))\n vystup.write('kp2=_return\\n')\n vystup.write('lstr,kp1,kp2\\n')\n vystup.write('l_num=_return\\n')\n vystup.write('lsel,s,,,l_num\\n')\n if useky[usek]['SEC'] not in new_sec.keys():\n vystup.write('latt,%i,,1,,,,%i\\n' % (int(useky[usek]['MAT']), int(useky[usek]['SEC'])))\n else: # pripad kdy je pouzity novy prurez (pro prurez v Japaru existuje vice hmotnosti izolace)\n vystup.write(\n 'latt,%i,,1,,,,%i\\n' % (int(useky[usek]['MAT']), new_sec[useky[usek]['SEC']][useky[usek]['ZAT']]))\n vystup.write('kp1=\\n')\n vystup.write('kp2=\\n')\n vystup.write('l_num=\\n')\n vystup.write('\\n')\n vystup.write('nummrg,kp\\n')\n\n\ndef vzd(k1, k2): # vzdalenost dvou bodu\n return sqrt((k1[0] - k2[0]) ** 2 + (k1[1] - k2[1]) ** 2 + (k1[2] - k2[2]) ** 2)\n\n\ndef vzd_primka_bod(kp, s, X0): # vzdalenost budu \"kp\" od primky definovane smerovym vektorem \"s\" a bodem \"X0\"\n u = np.array(kp) - np.array(X0)\n return np.linalg.norm(np.cross(u, s)) / np.linalg.norm(s)\n\n\ndef radius(kp1, kp2, usek1, usek2, souradnice): # heldani minimalniho mozneho radiusu oblouku\n s1 = [souradnice[usek1.split('-')[0]][0] - souradnice[usek1.split('-')[1]][0],\n souradnice[usek1.split('-')[0]][1] - souradnice[usek1.split('-')[1]][1],\n souradnice[usek1.split('-')[0]][2] - souradnice[usek1.split('-')[1]][\n 2]] ## smerovy vektor prvniho navazujiciho useku\n s1 = s1 / np.linalg.norm(s1) ## normovany smerovy vektor prvniho navazujiciho useku\n s2 = [souradnice[usek2.split('-')[0]][0] - souradnice[usek2.split('-')[1]][0],\n souradnice[usek2.split('-')[0]][1] - souradnice[usek2.split('-')[1]][1],\n souradnice[usek2.split('-')[0]][2] - souradnice[usek2.split('-')[1]][\n 2]] ## smerovy vektor druheho navazujiciho useku\n s2 = s2 / np.linalg.norm(s2) ## normovany smerovy vektor druheho navazujiciho useku\n\n s = list(np.cross(s1, s2)) ## smerovy vektor osy oblouku\n s = s / np.linalg.norm(s) ## normovany smerovy vektor osy oblouku\n\n d1 = -s1[0] * souradnice[kp1][0] - s1[1] * souradnice[kp1][1] - s1[2] * souradnice[kp1][2]\n d2 = -s2[0] * souradnice[kp2][0] - s2[1] * souradnice[kp2][1] - s2[2] * souradnice[kp2][2]\n\n s3 = [0., 0., 0.] # doplneni treti rovnice\n s3[np.argmax(abs(s))] = 1\n\n X0 = np.linalg.solve([s1, s2, s3], [-d1, -d2, 0]) # bod na ose\n\n return min(vzd_primka_bod(souradnice[kp1], s, X0), vzd_primka_bod(souradnice[kp2], s, X0))\n\n\ndef zapis_oblouky(useky, oblouky, souradnice, new_sec,\n vystup): ### zapis APDL prikazu pro vytvoreni oblouku, polomer oblouku je vypocten pomoci funkce radius (a porovnan s polomerem zadanym v JAPARU)\n vystup.write('/prep7\\n')\n for oblouk in oblouky.keys():\n kp1 = oblouk.split('-')[0]\n kp2 = oblouk.split('-')[1]\n for usek in useky.keys():\n if usek.split('-')[0] == kp1:\n kp1_2 = usek.split('-')[1]\n l1 = vzd(souradnice[kp1], souradnice[kp1_2])\n usek1 = usek\n if usek.split('-')[1] == kp1:\n kp1_2 = usek.split('-')[0]\n l1 = vzd(souradnice[kp1], souradnice[kp1_2])\n usek1 = usek\n if usek.split('-')[0] == kp2:\n kp2_2 = usek.split('-')[1]\n l2 = vzd(souradnice[kp2], souradnice[kp2_2])\n usek2 = usek\n if usek.split('-')[1] == kp2:\n kp2_2 = usek.split('-')[0]\n l2 = vzd(souradnice[kp2], souradnice[kp2_2])\n usek2 = usek\n if l1 >= l2:\n kc = kp1_2\n else:\n kc = kp2_2\n R = radius(kp1, kp2, usek1, usek2, sour)\n vystup.write('\\n')\n vystup.write('kp1=kp(%f,%f,%f)\\n' % (souradnice[kp1][0], souradnice[kp1][1], souradnice[kp1][2]))\n vystup.write('kp2=kp(%f,%f,%f)\\n' % (souradnice[kp2][0], souradnice[kp2][1], souradnice[kp2][2]))\n vystup.write('kc=kp(%f,%f,%f)\\n' % (souradnice[kc][0], souradnice[kc][1], souradnice[kc][2]))\n if R == oblouky[oblouk]['R']:\n vystup.write('larc,kp1,kp2,kc,%f\\n' % (R))\n else:\n vystup.write(\n 'larc,kp1,kp2,kc,%f\\t\\t!v JAPARu zadan R=%f, z bodu vychazi R=%f\\n' % (R, oblouky[oblouk]['R'], R))\n vystup.write('l_num=_return\\n')\n vystup.write('lsel,s,,,l_num\\n')\n if oblouky[oblouk]['SEC'] not in new_sec.keys():\n vystup.write('latt,%i,,2,,,,%i\\n' % (int(oblouky[oblouk]['MAT']), int(oblouky[oblouk]['SEC'])))\n else: # pripad kdy je pouzity novy prurez (pro prurez v Japaru existuje vice hmotnosti izolace)\n vystup.write('latt,%i,,2,,,,%i\\n' % (\n int(oblouky[oblouk]['MAT']), new_sec[oblouky[oblouk]['SEC']][oblouky[oblouk]['ZAT']]))\n\n vystup.write('kp1=\\n')\n vystup.write('kp2=\\n')\n vystup.write('kc=\\n')\n vystup.write('l_num=\\n')\n\n\ndef read_zat_uzlu(file): # nacteni zatizeni a ulozeni uzlu\n file.seek(0)\n pole = []\n load_ID = 0\n read = True\n in_pole = False\n while read == True:\n line = file.readline()\n if line.count('7777 -') == 1: # zacatek hledaneho pole\n in_pole = True\n line = file.readline() ## zahozeni oddelovaciho radku\n continue\n if line.count('8888 (APARAT)') == 1: # zacatek dalsiho pole -> konec cteni\n in_pole = False\n read = False\n\n if in_pole == True and line != '\\n':\n pole.append(line)\n\n vazby = {}\n vazby_prac = []\n in_vazba = False\n next = ''\n uzly = []\n for line in pole:\n if len(line.split()[0]) == 7 and in_vazba == False: # prvni radek zadani vazby\n in_vazba = True\n vazby_prac.append(line)\n elif in_vazba == True and len(line.split()[0]) != 7: # dalsi radky zadani vazby\n vazby_prac.append(line)\n elif in_vazba == True and len(line.split()[0]) == 7: # zacatek nasledujici vazby zadani vazby\n next = line\n # zpracovani nalezene vazby\n i = 0\n for radek in vazby_prac: # hledani kde zacina definice uzlu\n if radek.count(':') >= 1:\n start_body = i\n else:\n i += 1\n for j in range(start_body, len(vazby_prac)):\n bod = (vazby_prac[j].split(':')[0]).replace(' ', '') # bod ve kterem se vazba bude predepisovat\n # print(bod)\n vazba = vazby_prac[0][:7] # typ vazby 7-mi mistny kod\n try:\n smer = vazby_prac[0][7:] # SS pro vazby v lokalnim SS\n except:\n smer = ''\n\n if bod not in vazby.keys():\n vazby[bod] = {}\n try:\n vazby[bod]['pozn'] = vazby_prac[j].split(':')[1]\n except:\n vazby[bod]['pozn'] = ''\n vazby[bod][vazba] = {}\n vazby[bod][vazba]['smer'] = smer\n vazby[bod][vazba]['def'] = vazby_prac[1:start_body]\n else:\n if len(vazby[bod]['pozn']) == 0:\n try:\n vazby[bod]['pozn'] = vazby_prac[j].split(':')[1]\n except:\n vazby[bod]['pozn'] = ''\n vazby[bod][vazba] = {}\n vazby[bod][vazba]['smer'] = smer\n vazby[bod][vazba]['def'] = vazby_prac[1:start_body]\n # zpracovani nalezene vazby\n\n vazby_prac = []\n vazby_prac.append(next)\n\n print('Ncteno %i uzlu, kde jsou predepsany vazby-zatizeni' % len(vazby.keys()))\n return vazby\n\n\n##### FUNKCE #####\n\n\nsour = read_uzly(inp)\nprurezy = read_prurezy(inp)\nmaterialy = read_materialy(inp)\nzatizeni = read_zatizeni(inp)\nzat_uzly = read_zat_uzlu(inp)\n[prime, oblouky] = read_vetve(inp)\n\n#### pruzkum podle prurezu - hledani vicenasobnych zatizeni u jednoho typu prurezu\nby_sec = {}\nfor usek in prime:\n if prime[usek]['SEC'] not in by_sec.keys():\n by_sec[prime[usek]['SEC']] = {}\n by_sec[prime[usek]['SEC']]['5555'] = []\n by_sec[prime[usek]['SEC']]['5555'].append(prime[usek]['ZAT'])\n by_sec[prime[usek]['SEC']]['2222'] = []\n by_sec[prime[usek]['SEC']]['2222'].append(prime[usek]['MAT'])\n else:\n if prime[usek]['ZAT'] not in by_sec[prime[usek]['SEC']]['5555']:\n by_sec[prime[usek]['SEC']]['5555'].append(prime[usek]['ZAT'])\n if prime[usek]['MAT'] not in by_sec[prime[usek]['SEC']]['2222']:\n by_sec[prime[usek]['SEC']]['2222'].append(prime[usek]['MAT'])\nfor oblouk in oblouky:\n if oblouky[oblouk]['SEC'] not in by_sec.keys():\n by_sec[oblouky[oblouk]['SEC']] = {}\n by_sec[oblouky[oblouk]['SEC']]['5555'] = []\n by_sec[oblouky[oblouk]['SEC']]['5555'].append(oblouky[oblouk]['ZAT'])\n by_sec[oblouky[oblouk]['SEC']]['2222'] = []\n by_sec[oblouky[oblouk]['SEC']]['2222'].append(oblouky[oblouk]['MAT'])\n else:\n if oblouky[oblouk]['ZAT'] not in by_sec[oblouky[oblouk]['SEC']]['5555']:\n by_sec[oblouky[oblouk]['SEC']]['5555'].append(oblouky[oblouk]['ZAT'])\n if oblouky[oblouk]['MAT'] not in by_sec[oblouky[oblouk]['SEC']]['2222']:\n by_sec[oblouky[oblouk]['SEC']]['2222'].append(oblouky[oblouk]['MAT'])\n ##vypis pruzkumu\n# keys=by_sec.keys()\n# keys.sort()\n# print('%15s%15s%15s'%('sec','zat','mat'))\n# for key in keys:\n# print('%15s%15s%15s'%(key,by_sec[key]['5555'],by_sec[key]['2222']))\n##vypis pruzkumu\n#### pruzkum podle prurezu - hledani vicenasobnych zatizeni u jednoho typu prurezu\n\ninp.close()\n\n## zapis materialu\noutp = open('materialy', 'w')\nzapis_materialy(materialy, outp)\noutp.close()\n## zapis materialu\n\n\n## zapis souboru s prurezy trubek\noutp = open('sections', 'w')\noutp.write('/prep7\\n')\noutp.write('\\n')\nnew_sec = {} ## slovnik s novymi prurezy\nnew_secnum = 1000 ## pocatecni cislo novych prurezu\nfor secn in by_sec.keys():\n if len(by_sec[secn]['5555']) == 1:\n prurez = prurezy[secn]\n outp.write('SECTYPE,%s, PIPE,, !!! %s\\n' % (prurez.split()[0], prurez.split(':')[1][:-1]))\n D = prurez.split()[2]\n D = D.replace('+', 'E+')\n D = D.replace('-', 'E-')\n D = float(D)\n t = prurez.split()[3]\n t = t.replace('+', 'E+')\n t = t.replace('-', 'E-')\n t = float(t)\n outp.write('SECDATA,%f,%f,12,,,,,\\n' % (D, t))\n outp.write('SECOFFSET, CENT\\n')\n outp.write('SECCONTROL,%f\\n' % (\n float(((zatizeni[by_sec[secn]['5555'][0]].split()[4]).replace('+', 'E+')).replace('-', 'E-'))))\n outp.write('\\n')\n elif len(by_sec[secn]['5555']) > 1:\n Mizol = []\n for i in range(\n len(by_sec[secn]['5555'])): # cyklus pres vsechny zatizeni (potencionalne rozdilne hmotnosti izolaci)\n M = float(((zatizeni[by_sec[secn]['5555'][i]].split()[4]).replace('+', 'E+')).replace('-', 'E-'))\n if M not in Mizol:\n Mizol.append(M)\n if len(\n Mizol) > 1: # je vice hmotnosti izolaci tudiz budou vytvoreny nove prurezy (s rozdilnymi hmotnostmi izolaci)\n print('Pro secID=%s je definovano vice hmotnosti izolaci -> jsou vytvoreny nove prurezy' % (secn))\n new_sec[secn] = {}\n for i in range(len(by_sec[secn]['5555'])): # cyklus pres vsechny zatizeni\n new_sec[secn][by_sec[secn]['5555'][i]] = new_secnum # oznaceni noveho secn\n print('kombinace secID=%s a zatizeni zatID=%s je ulozena pod novym secID=%i' % (\n secn, by_sec[secn]['5555'][i], new_secnum))\n prurez = prurezy[secn]\n outp.write('SECTYPE,%i, PIPE,, !!! nahrada za secID=%s a zatID=%s\\n' % (\n new_secnum, secn, by_sec[secn]['5555'][i]))\n D = prurez.split()[2]\n D = D.replace('+', 'E+')\n D = D.replace('-', 'E-')\n D = float(D)\n t = prurez.split()[3]\n t = t.replace('+', 'E+')\n t = t.replace('-', 'E-')\n t = float(t)\n outp.write('SECDATA,%f,%f,12,,,,,\\n' % (D, t))\n outp.write('SECOFFSET, CENT\\n')\n outp.write('SECCONTROL,%f\\n' % (\n float(((zatizeni[by_sec[secn]['5555'][i]].split()[4]).replace('+', 'E+')).replace('-', 'E-'))))\n outp.write('\\n')\n new_secnum += 1\noutp.close()\n## zapis souboru s prurezy trubek\n\n\noutp = open('prime', 'w')\nzapis_cary(prime, sour, new_sec, outp)\noutp.close()\n\noutp = open('oblouky', 'w')\nzapis_oblouky(prime, oblouky, sour, new_sec, outp)\noutp.close()\n","sub_path":"JAPAR_2_ANSYS.py","file_name":"JAPAR_2_ANSYS.py","file_ext":"py","file_size_in_byte":22560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"164362908","text":"#!/usr/bin/env python\n\n# Contact info@kdab.com if any conditions of this licensing are not clear to you.\n# This file is part of the KD Chart library.\n#\n# SPDX-FileCopyrightText: 2019-2023 Klarälvdalens Datakonsult AB, a KDAB Group company \n#\n# SPDX-License-Identifier: MIT\n#\n\n\n''' MainWindow UI definition for the API Review Example '''\n\n# pylint: disable=missing-function-docstring,missing-class-docstring\n\nfrom PySide2 import QtCore, QtWidgets\nfrom PyKDChart.KDGantt import View\n\n\nclass Ui_MainWindow(): # pylint: disable=invalid-name\n def __init__(self):\n self.menubar = None\n self.statusbar = None\n self.ganttView = None\n self.vboxlayout = None\n self.centralwidget = None\n\n def setupUi(self, mainWindow):\n mainWindow.setObjectName(\"mainWindow\")\n mainWindow.resize(556, 330)\n mainWindow.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu)\n self.centralwidget = QtWidgets.QWidget(mainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.vboxlayout = QtWidgets.QVBoxLayout(self.centralwidget)\n self.vboxlayout.setObjectName(\"vboxlayout\")\n self.ganttView = View(self.centralwidget)\n self.ganttView.setObjectName(\"ganttView\")\n self.vboxlayout.addWidget(self.ganttView)\n mainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(mainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 556, 29))\n self.menubar.setObjectName(\"menubar\")\n mainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(mainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n mainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(mainWindow)\n QtCore.QMetaObject.connectSlotsByName(mainWindow)\n\n # pylint: disable=no-self-use\n def retranslateUi(self, mainWindow):\n _translate = QtCore.QCoreApplication.translate\n mainWindow.setWindowTitle(_translate(\"mainWindow\", \"KD Gantt Example\"))\n","sub_path":"python/examples/apireview/ui_mainwindow.py","file_name":"ui_mainwindow.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"340853272","text":"from datetime import datetime\n\n\nclass AccountInfo(object):\n \"\"\"\n User account information model.\n\n Param date Date: Current date.\n Param time time: Current time.\n Param service_open bool: True if the service is open.\n Param shift_start time: Shift start time.\n Param shift_end time: Shift end time.\n Param alarm time: Alarm time.\n Param lodging int: Lodging value.\n Param surcharge int: Surcharge value.\n Param bar int: Bar account total value.\n Param bonus int: Bonus value.\n Param discount int: Discount value.\n Param paid int: Paid value.\n Param special_offer str: Special offer title.\n \"\"\"\n\n def __init__(self):\n self.date = datetime.now().date()\n self.time = datetime.now().time()\n self.service_open = False\n self.shift_start = None\n self.shift_end = None\n self.alarm = None\n self.lodging = 0\n self.surcharge = 0\n self.bar = 0\n self.bonus = 0\n self.discount = 0\n self.paid = 0\n self.total = 0\n self.special_offer = None\n\n def update_account_from_command(self, command):\n \"\"\"\n Update from SGH account info command.\n\n Param command Command.\n \"\"\"\n self.date = self._get_date(command.params[1:7])\n self.time = self._get_time(command.params[7:11])\n self.service_open = bool(command.params[11])\n self.shift_start = self._get_time(command.params[12:16])\n self.shift_end = self._get_time(command.params[16:20])\n self.alarm = self._get_time(command.params[20:24])\n self.lodging = self._get_int(command.params[24:30])\n self.surcharge = self._get_int(command.params[30:36])\n self.bar = self._get_int(command.params[36:42])\n self.bonus = self._get_int(command.params[42:48])\n self.discount = self._get_int(command.params[48:54])\n self.paid = self._get_int(command.params[54:60])\n self.total = self._get_int(command.params[60:66])\n self.special_offer = self._get_str(command.params[66:96])\n\n def _get_date(self, params):\n \"\"\"\n Get date from command params.\n\n Param params [int].\n Returns Date|None.\n \"\"\"\n try:\n return datetime.strptime(self._get_str(params), '%d%m%y').date()\n except Exception:\n return None\n\n def _get_time(self, params):\n \"\"\"\n Get time from command params.\n\n Param params [int].\n Returns time|None.\n \"\"\"\n try:\n return datetime.strptime(self._get_str(params), '%H%M').time()\n except Exception:\n return None\n\n def _get_str(self, params):\n \"\"\"\n Get str from command params.\n\n Param params [int].\n Returns str.\n \"\"\"\n return ''.join(map(lambda val: chr(val), params)).strip()\n\n def _get_int(self, params):\n \"\"\"\n Get int from command params.\n\n Param params [int].\n Returns int.\n \"\"\"\n try:\n return int(self._get_str(params))\n except Exception:\n return 0\n","sub_path":"models/accountinfo.py","file_name":"accountinfo.py","file_ext":"py","file_size_in_byte":3102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203191663","text":"import operator\nimport operator\n\nimport numpy as np\nfrom deap import creator, base, tools, gp\n\nfrom symre.gene.fitness_score import fitness_error_corr\nfrom symre.gene.build_primitive_set import sympy_prim_set1\nfrom symre.tool import load_data\n# '1.load data'\nfrom symre.tool import test_function\n\n# data = load_data.load_data(path=r'C:\\Users\\ww\\Desktop', dataname='温度-光照-jqxx.txt', skiprow=3)\n# X = data[:, :-1]\n# y = data[:, -1]\n\nX = test_function.product_nosort_x([[-1, 10], [0.4, 3]])\ny = test_function.func_exp0(X)\n\n# '2.definate the name of symbol and constants'\nlens = X.shape[1]\nsymbols_list = load_data.generate_str(lens, name='x')\nconstants_value = [1, ]\nconstants_list = load_data.generate_str(len(constants_value), name='C')\n\n# 3.结构定义\npset = sympy_prim_set1(categories=('algebraic', 'exponential'),\n # categories=('algebraic', 'trigonometric', 'exponential',\n # 'neg', 'logarithm', 'sqrt', 'rec', 'eph'),\n arguments=symbols_list, constants=constants_list)\n\ncreator.create(\"FitnessMin\", base.Fitness, weights=(-1.0,))\ncreator.create(\"Individual\", gp.PrimitiveTree, fitness=creator.FitnessMin,\n pset=pset, symbols_list=symbols_list, constants_list=constants_list) # 创造individual类,并且给与fitness,pset属性\n\ntoolbox = base.Toolbox()\ntoolbox.register(\"expr\", gp.genFull, pset=pset, min_=0, max_=4)\ntoolbox.register(\"individual\", tools.initIterate, creator.Individual, toolbox.expr)\ntoolbox.register('population', tools.initRepeat, list, toolbox.individual)\n\n# 赋值,挑选l\ntoolbox.register(\"evaluate\", fitness_error_corr, symbols_list0=symbols_list, x0=X, y0=y, constant0=constants_value)\ntoolbox.register(\"select\", tools.selSPEA2, )\n# 交叉l\ntoolbox.register(\"mate\", gp.cxOnePoint)\ntoolbox.decorate(\"mate\", gp.staticLimit(key=operator.attrgetter('height'), max_value=17))\n# 变异\ntoolbox.register(\"expr_mut\", gp.genFull, min_=0, max_=3)\ntoolbox.register(\"mutate\", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)\ntoolbox.register(\"mutate3\", gp.mutNodeReplacement, pset=pset)\ntoolbox.register(\"mutate2\", gp.mutShrink)\ntoolbox.decorate(\"mutate\", gp.staticLimit(key=operator.attrgetter('height'), max_value=17))\n# 定义统计工具\nstats_fit = tools.Statistics(lambda ind1: ind1.fitness.values)\nstats_size = tools.Statistics(len)\nmstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size)\nmstats.register(\"avg\", np.mean)\nmstats.register(\"std\", np.std)\nmstats.register(\"min\", np.min)\nmstats.register(\"max\", np.max)\n\nif __name__ == '__main__':\n individual = toolbox.individual()\n print(individual)\n","sub_path":"symre/tool/individual_test.py","file_name":"individual_test.py","file_ext":"py","file_size_in_byte":2632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"182816993","text":"import preprocessing as p\r\nimport training as t\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nimport matplotlib.pyplot as plt\r\n\r\nbatch_size = 64\r\nnum_epochs = 25\r\nlearning_rate = 0.001\r\nimage_size = [100, 100]\r\n\r\nclass Baseline(nn.Module):\r\n def __init__(self):\r\n super(Baseline, self).__init__()\r\n self.layer1 = nn.Linear(100*100*3, 300)\r\n self.layer2 = nn.Linear(300, 64)\r\n self.layer3 = nn.Linear(64, 4)\r\n def forward(self, img):\r\n flattened = img.reshape(-1, 100*100*3)\r\n activation1 = self.layer1(flattened)\r\n activation1 = F.leaky_relu(activation1)\r\n activation2 = self.layer2(activation1)\r\n activation2 = F.leaky_relu(activation2)\r\n activation3 = self.layer3(activation2)\r\n return activation3\r\n \r\nclass SimpleCNN(nn.Module):\r\n def __init__(self, kernel_size = 5):\r\n super(SimpleCNN, self).__init__()\r\n self.conv1 = nn.Conv2d(3, 3, kernel_size)\r\n self.pool = nn.MaxPool2d(2, 2)\r\n self.conv2 = nn.Conv2d(3, 3, kernel_size)\r\n self.conv3 = nn.Conv2d(3, 3, kernel_size)\r\n self.conv_to_fc = 243\r\n self.fc1 = nn.Linear(self.conv_to_fc, 128)\r\n self.fc2 = nn.Linear(128, 32)\r\n self.fc3 = nn.Linear(32, 4) \r\n\r\n def forward(self, x):\r\n x = self.pool(F.leaky_relu(self.conv1(x)))\r\n x = self.pool(F.leaky_relu(self.conv2(x)))\r\n x = self.pool(F.leaky_relu(self.conv3(x)))\r\n x = x.view(batch_size, self.conv_to_fc)\r\n x = F.relu(self.fc1(x))\r\n x = F.relu(self.fc2(x))\r\n x = self.fc3(x)\r\n return x\r\n\r\nclass DeepCNN(nn.Module):\r\n def __init__(self, kernel_size = 5):\r\n super(DeepCNN, self).__init__()\r\n self.conv1 = nn.Conv2d(3, 5, kernel_size, padding=1)\r\n self.conv2 = nn.Conv2d(5, 5, kernel_size, padding=3)\r\n self.pool = nn.MaxPool2d(2, 2)\r\n self.conv_to_fc = 20\r\n self.fc1 = nn.Linear(self.conv_to_fc, 11)\r\n self.fc2 = nn.Linear(11, 4)\r\n\r\n def forward(self, x):\r\n x = self.pool(F.leaky_relu(self.conv1(x)))\r\n for i in range(50):\r\n x = self.pool(F.leaky_relu(self.conv2(x)))\r\n x = x.view(batch_size, self.conv_to_fc)\r\n x = F.leaky_relu(self.fc1(x))\r\n x = self.fc2(x)\r\n return x\r\n\r\ndef get_image_size():\r\n return image_size\r\n\r\ndef main():\r\n train_dataset, valid_dataset, test_dataset = p.get_datasets(sample=False)\r\n\r\n train_loader = torch.utils.data.DataLoader(train_dataset, shuffle=True, batch_size=batch_size, drop_last=True)\r\n valid_loader = torch.utils.data.DataLoader(valid_dataset, shuffle=True, batch_size=batch_size, drop_last=True)\r\n test_loader = torch.utils.data.DataLoader(test_dataset, shuffle=True, batch_size=batch_size, drop_last=True)\r\n\r\n net = SimpleCNN()\r\n if torch.cuda.is_available():\r\n net.cuda()\r\n\r\n criterion = nn.BCEWithLogitsLoss()\r\n optimizer = optim.AdamW(net.parameters(), lr=learning_rate)\r\n\r\n train_accuracy, validation_accuracy, epochs = t.train(net, train_loader, valid_loader, criterion, optimizer, num_epochs)\r\n\r\n plt.plot(epochs, train_accuracy)\r\n plt.title(\"Training Curve\")\r\n plt.xlabel(\"Epochs\")\r\n plt.ylabel(\"Training Accuracy\")\r\n plt.savefig(\"training.png\")\r\n\r\n plt.clf()\r\n\r\n plt.plot(epochs, validation_accuracy)\r\n plt.title(\"Validation Curve\")\r\n plt.xlabel(\"Epochs\")\r\n plt.ylabel(\"Validation Accuracy\")\r\n plt.savefig(\"validation.png\")\r\n\r\n print(f\"Test accuracy: {t.get_accuracy(net, test_loader)}\")\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"47828325","text":"import sys\n\ndef solve(k, c, s):\n if c == 1:\n if s == k:\n return \" \".join(str(i) for i in range(1, k + 1))\n return \"IMPOSSIBLE\"\n elif k == 1:\n if s == 0:\n return \"IMPOSSIBLE\"\n else:\n return \"1\"\n else:\n if s < (k-1):\n return \"IMPOSSIBLE\"\n return \" \".join(str(i) for i in range(2, k + 1))\n\n\nif __name__ == '__main__':\n total = int(sys.stdin.readline().strip())\n for case in range(1, total + 1):\n k, c, s = sys.stdin.readline().strip().split()\n print(\"Case #{}: {}\".format(case, solve(int(k), int(c), int(s))))\n","sub_path":"codes/BuildLinks1.10/test_input/CJ/16_0_4_aflag_fractiles.py","file_name":"16_0_4_aflag_fractiles.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"151287002","text":"import toolbox.resources\nimport sys\n\ndef say():\n base = None\n for x in [ __file__, sys.modules[__name__], 'hello.world', 'hello', ]:\n inst = toolbox.resources.gethandlers(x)\n base = inst if base is None else base\n print(inst, base == inst)\n\n\nif __name__ == '__main__':\n say()\n","sub_path":"tests/data/asset-example/sample/hello/world.py","file_name":"world.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"388769682","text":"import webbrowser\nimport os\nimport re\nimport datetime\nimport json\n\n# Styles and scripting for the page\nwith open('main_page_head.html', 'r') as html_file:\n main_page_head = html_file.read()\n\n# The main page layout and title bar\nwith open('main_page_content.html', 'r') as html_file:\n main_page_content = html_file.read()\n\n# A single movie entry html template\nwith open('movie_tile_content.html', 'r') as html_file:\n movie_tile_content = html_file.read()\n\n# JSON file containing movie information\nwith open('sample_data.json', 'r') as json_file:\n movie_json = json.load(json_file)\n\n\nclass Movie:\n \"\"\"\n A simple representation of a single movie.\n\n Args:\n details (dict): A dictionary of the movie's details.\n Keys supported: title (str), poster_image_url (str),\n trailer_youtube_url (str), release_date (str),\n score_rotten_tomatoes (int)\n\n Note:\n details[\"trailer_youtube_url\"] should be of the following format:\n https://www.youtube.com/watch?v=7bZFr2IA0Bo\n\n details[\"release_date\"] should be of the following format: \"2015-05-14\"\n\n Attributes:\n title (str): The movie's title.\n poster_image_url (str): The URL of the movie's poster.\n trailer_youtube_url (str): The URL of the movie's trailer on Youtube.\n release_date (datetime): The movie's release date.\n score_rotten_tomatoes (int): The movie's score on the Rotten Tomatoes\n website.\n \"\"\"\n\n def __init__(self, details=None):\n self.title = details[\"title\"]\n self.poster_image_url = details[\"poster_image_url\"]\n self.trailer_youtube_url = details[\"trailer_youtube_url\"]\n self.release_date = datetime.datetime.strptime(details[\"release_date\"],\n \"%Y-%m-%d\")\n self.score_rotten_tomatoes = details[\"score_rotten_tomatoes\"]\n\n\ndef create_movie_tiles_content(movies):\n # The HTML content for this section of the page\n content = ''\n for movie in movies:\n # Extract the youtube ID from the url\n youtube_id_match = re.search(r'(?<=v=)[^&#]+',\n movie.trailer_youtube_url)\n youtube_id_match = youtube_id_match \\\n or re.search(r'(?<=be/)[^&#]+', movie.trailer_youtube_url)\n trailer_youtube_id = youtube_id_match.group(0) if youtube_id_match \\\n else None\n\n # Append the tile for the movie with its content filled in\n content += movie_tile_content.format(\n movie_title=movie.title,\n poster_image_url=movie.poster_image_url,\n trailer_youtube_id=trailer_youtube_id,\n release_date=movie.release_date.strftime(\"%B %d, %Y\"),\n score_rotten_tomatoes=str(movie.score_rotten_tomatoes) + \"%\"\n )\n return content\n\n\ndef open_movies_page(movies):\n # Create or overwrite the output file\n output_file = open('fresh_tomatoes.html', 'w')\n\n # Replace the placeholder for the movie tiles with the actual\n # dynamically generated content\n rendered_content = main_page_content\\\n .format(movie_tiles=create_movie_tiles_content(movies))\n\n # Output the file\n output_file.write(main_page_head + rendered_content)\n output_file.close()\n\n # Open the output file in the browser\n url = os.path.abspath(output_file.name)\n webbrowser.open('file://' + url, new=2) # open in a new tab, if possible\n\nmovies = []\n\n# Generate a list of Movie objects from movie_json\nfor movie_details in movie_json[\"movies\"]:\n movies.append(Movie(movie_details))\n\n# Generate the HTML page and load it in the browser\nopen_movies_page(movies)\n","sub_path":"fresh_tomatoes.py","file_name":"fresh_tomatoes.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"230587404","text":"import requests\nfrom settings import query\nfrom os import path\nimport json\nfrom login import Login\nimport re\nimport random\nimport time\n\nclass Spider(object):\n def __init__(self,cookie,query=query):\n self.query = query\n self._header = {\n \"User-Agent\": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',\n }\n self._cookie = cookie\n self._token = ''\n self._article_num = 0\n\n @classmethod\n def verify_cookie(cls):\n with open(path.join(path.abspath('.'),'cookie.txt'),'r+',encoding='utf-8') as f:\n cookie = f.read()\n if cookie:\n cookies = json.loads(cookie)\n return cls(cookie=cookies)\n else:\n l = Login()\n l.login()\n return cls(cookie=Spider.verify_cookie())\n\n def get_token(self): \n url = 'https://mp.weixin.qq.com'\n response = requests.get(url,headers=self._header,cookies=self._cookie)\n self._token = re.findall(r'token=(\\d+)',str(response.url))[0]\n \n def get_fakeid(self):\n self.get_token()\n search_url = 'https://mp.weixin.qq.com/cgi-bin/searchbiz?'\n query_id = {\n 'action': 'search_biz',\n 'token' : self._token,\n 'lang': 'zh_CN',\n 'f': 'json',\n 'ajax': '1',\n 'random': random.random(),\n 'query': query,\n 'begin': '0',\n 'count': '5'\n }\n search_response = requests.get(search_url, cookies=self._cookie, headers=self._header, params=query_id)\n lists = search_response.json().get('list')[0]\n self._fakeid = lists.get('fakeid')\n\n def get_article_num(self):\n self.get_fakeid()\n appmsg_url = 'https://mp.weixin.qq.com/cgi-bin/appmsg?'\n query_id_data = {\n 'token': self._token,\n 'lang': 'zh_CN',\n 'f': 'json',\n 'ajax': '1',\n 'random': random.random(),\n 'action': 'list_ex',\n 'begin': '0',#不同页,此参数变化,变化规则为每页加5\n 'count': '5',\n 'query': '',\n 'fakeid': self._fakeid,\n 'type': '9'\n }\n appmsg_response = requests.get(appmsg_url, cookies=self._cookie, headers=self._header, params=query_id_data)\n self._article_num = appmsg_response.json().get('app_msg_cnt')\n\n def get_details(self):\n self.get_article_num()\n num = int(int(self._article_num) / 5)\n begin = 0\n while num+1 > 0:\n appmsg_url = 'https://mp.weixin.qq.com/cgi-bin/appmsg?'\n query_id_data = {\n 'token': self._token,\n 'lang': 'zh_CN',\n 'f': 'json',\n 'ajax': '1',\n 'random': random.random(),\n 'action': 'list_ex',\n 'begin': '{}'.format(str(begin)),#不同页,此参数变化,变化规则为每页加5\n 'count': '5',\n 'query': '',\n 'fakeid': self._fakeid,\n 'type': '9'\n }\n query_fakeid_response = requests.get(appmsg_url, cookies=self._cookie, headers=self._header, params=query_id_data)\n fakeid_list = query_fakeid_response.json().get('app_msg_list') \n for item in fakeid_list:\n content_link=item.get('link')\n content_title=item.get('title')\n fileName=query+'.txt'\n with open(path.join(path.abspath('.'),fileName),'a',encoding='utf-8') as fh:\n fh.write(content_title+\":\\n\"+content_link+\"\\n\")\n num -= 1\n begin = int(begin)\n begin+=5\n time.sleep(2)\n\n ''' \n def save_to_mongo(self):\n pass\n '''\n\nif __name__ == '__main__':\n s = Spider.verify_cookie()\n s.get_details()\n","sub_path":"offical_accounts_articles/spider.py","file_name":"spider.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"112156103","text":"settings = {\n \"setting7\": {\n \"loss\": \"Loss_v2\",\n \"model\": \"DecayByEpoch\", \n \"weight_Classification_loss\": 100,\n \"weight_Object_loss\": 1000,\n \"weight_Localization_loss\": 1,\n \"lr\": 0.01,\n \"decay\": 0.01,\n \"weight_file\": \"weight-setting7\",\n \"loss_file\": \"losses-setting5.txt\",\n \"batch_size\": 50,\n \"epochs\": 250\n }\n}\n\nsetting = settings[\"setting7\"]","sub_path":"notebook/code/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"516876240","text":"#encoding: utf-8\nfrom OpenOrange import *\nimport string\n\nParentCustomerSearcherWindow = SuperClass(\"CustomerSearcherWindow\",\"SettingWindow\",__file__)\nclass CustomerSearcherWindow(ParentCustomerSearcherWindow):\n\n def afterEdit(self, fieldname):\n record = self.getRecord()\n if (fieldname == \"CustCode\"):\n self.pasteCustCode()\n if (fieldname == \"ContactCode\"):\n self.pasteContactCode()\n if (fieldname in (\"CustName\",\"ContactName\")):\n r = self.getReportView(\"Context\")\n from CustomerSearcherReport import CustomerSearcherReport\n report = CustomerSearcherReport()\n report.setView(r)\n RepSpec = report.getRecord()\n if (fieldname == \"CustName\"):\n if (record.CustName):\n RepSpec.CustName = record.CustName\n RepSpec.Limit = 10\n report.LinkedWindow = self\n report.open(False)\n record.setFocusOnField(\"ContactName\")\n else:\n record.CustCode = \"\"\n if (fieldname == \"ContactName\"):\n if (record.ContactName):\n RepSpec.CustCode = record.CustCode\n RepSpec.ContactName = record.ContactName\n RepSpec.Limit = 10\n report.LinkedWindow = self\n report.open(False)\n else:\n record.ContactCode = \"\"\n\n def buttonClicked(self, buttonname): \n if buttonname == \"search\":\n r = self.getReportView(\"Context\")\n from CustomerSearcherReport import CustomerSearcherReport\n report = CustomerSearcherReport()\n report.setView(r)\n record = self.getRecord()\n RepSpec = report.getRecord()\n RepSpec.CustCode = record.CustCode\n RepSpec.CustName = record.CustName\n RepSpec.ContactCode = record.ContactCode\n RepSpec.ContactName = record.ContactName\n RepSpec.TaxRegNr = record.TaxRegNr\n RepSpec.DelAddress = record.DelAddress\n RepSpec.DelCity = record.DelCity\n RepSpec.Address = record.Address\n RepSpec.City = record.City\n RepSpec.Email = record.Email\n RepSpec.Phone = record.Phone\n RepSpec.Mobile = record.Mobile\n RepSpec.Limit = 10\n report.LinkedWindow = self\n report.open(False)\n if (buttonname == \"clearFields\"):\n record = self.getRecord()\n record.CustCode = \"\"\n record.CustName = \"\"\n record.ContactCode = \"\"\n record.ContactName = \"\"\n record.Address = \"\"\n record.City = \"\"\n record.Email = \"\"\n record.Phone = \"\"\n record.Mobile = \"\"\n\n def pasteCustCode(self):\n record = self.getRecord()\n from Customer import Customer\n cus = Customer()\n cus = cus.bring(record.CustCode)\n if (cus):\n record.CustName = cus.Name\n else:\n record.CustName = \"\"\n\n def pasteContactCode(self):\n record = self.getRecord()\n from Person import Person\n per = Person()\n per = per.bring(record.ContactCode)\n if (per):\n record.ContactName = \"%s %s\" %(per.Name,per.LastName)\n else:\n record.ContactName = \"\"\n\n def pasteProblemCode(self):\n record = self.getRecord()\n from StandardProblem import StandardProblem\n sp = StandardProblem()\n sp = sp.bring(record.ProblemCode)\n if (sp):\n record.ProblemText = sp.Comment\n else:\n record.ProblemText = \"\"\n\n def filterPasteWindow(self, fieldname):\n if fieldname == \"ContactCode\":\n if self.getRecord().CustCode:\n return \"{CustCode} = s|%s|\" % self.getRecord().CustCode\n ","sub_path":"standard/windows/CustomerSearcherWindow.py","file_name":"CustomerSearcherWindow.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"584977035","text":"import os,time\nfrom collections import OrderedDict\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\n\nfrom sklearn import preprocessing\nfrom sklearn import manifold\nfrom sklearn import neighbors\nfrom sklearn import cluster\nfrom sklearn import metrics\n\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import Imputer\n\nfrom pypospack.exceptions import BadPreprocessorTypeException\nfrom pypospack.exceptions import BadManifoldTypeException\nfrom pypospack.exceptions import BadNearestNeighborTypeException\nfrom pypospack.exceptions import BadClusterTypeException\nfrom pypospack.pyposmat.data import PyposmatDataFile\nfrom pypospack.pyposmat.data import PyposmatConfigurationFile\nfrom pypospack.pyposmat.data.cluster_analysis import PyposmatClusterAnalysis\nfrom pypospack.pyposmat.data.cluster_analysis import ecdf\n\n\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport numpy as np\n\npypospack_root_dir = [v.strip() for v in os.environ['PYTHONPATH'].split(':') if v.endswith('pypospack')][0]\ndata_dir = os.path.join(pypospack_root_dir,'data/Ni__eam__born_exp_fs__3.5NN')\n\nif __name__ == \"__main__\":\n show_plots = False\n\n pyposmat_src_dir = data_dir\n \n pyposmat_configuration_fn = os.path.join(\n pyposmat_src_dir,'pyposmat.config.in'\n )\n\n pyposmat_data_fn = os.path.join(\n pyposmat_src_dir,'pyposmat.kde.5.out'\n )\n\n\n d = OrderedDict()\n d['configuration_fn'] = pyposmat_configuration_fn\n d['data_fn'] = pyposmat_data_fn\n d['include_parameters'] = True\n d['include_qois'] = True\n d['include_errors'] = False\n\n d['preprocessing'] = OrderedDict()\n d['preprocessing']['type'] = 'standard_scaler'\n d['preprocessing']['args'] = OrderedDict()\n d['preprocessing']['args']['copy'] = True\n d['preprocessing']['args']['with_mean'] = True\n d['preprocessing']['args']['with_std'] = True\n\n d['manifold'] = OrderedDict()\n d['manifold']['type'] = 'tsne'\n d['manifold']['args'] = OrderedDict()\n d['manifold']['args']['n_components'] = 2\n d['manifold']['args']['perplexity'] = 30\n d['manifold']['args']['early_exaggeration'] = 12\n d['manifold']['args']['learning_rate'] = 200\n d['manifold']['args']['n_iter'] = 5000\n d['manifold']['args']['n_iter_without_progress']=300,\n d['manifold']['args']['min_grad_norm'] =1e-7,\n #d['manifold']['args']['metric']='euclidean',\n d['manifold']['args']['init'] ='pca',\n d['manifold']['args']['verbose']=0,\n d['manifold']['args']['random_state']=None\n #method='barnes_hut'\n #angle=0.5\n\n d['neighbors'] = OrderedDict()\n d['neighbors']['type'] = 'ball_tree'\n d['neighbors']['kNN'] = 4\n d['neighbors']['args'] = OrderedDict()\n d['neighbors']['args']['leaf_size'] = 40\n d['neighbors']['args']['metric'] = 'minkowski'\n\n d['cluster'] = OrderedDict()\n d['cluster']['type'] = 'dbscan'\n d['cluster']['args'] = OrderedDict()\n d['cluster']['args']['eps'] = OrderedDict()\n d['cluster']['args']['eps']['NN'] = 3\n d['cluster']['args']['eps']['percentile'] = .99\n d['cluster']['args']['min_samples'] = 10\n d['cluster']['args']['metric'] = 'euclidean'\n d['cluster']['args']['metric_params'] = None\n d['cluster']['args']['algorithm'] = 'auto'\n d['cluster']['args']['leaf_size'] = 30\n d['cluster']['args']['p'] = None\n\n #o = PyposmatClusterAnalysis()\n o = PyposmatClusterAnalysis.init_from_ordered_dict(d)\n\n rd = OrderedDict()\n rd['include_parameters'] = d['include_parameters']\n rd['include_qois'] = d['include_qois']\n rd['include_errors'] = d['include_errors']\n rd['cluster'] = OrderedDict()\n rd['cluster']['names'] = o.cluster_names\n\n\n o.preprocess_data(d)\n rd['preprocessing'] = OrderedDict()\n rd['preprocessing']['type'] = d['preprocessing']['type']\n rd['preprocessing']['args'] = d['preprocessing']['args']\n rd['preprocessing']['names'] = o.scaled_names\n rd['preprocessing']['results'] = OrderedDict()\n #rd['preprocessing']['results']['mean'] = o.preprocessor.mean_\n #rd['preprocessing']['results']['sd'] = o.preprocessor.var_\n for i,v in enumerate(o.cluster_names):\n rd['preprocessing']['results'][v] = OrderedDict(\n [\n ('mean',o.preprocessor.mean_[i]),\n ('var',o.preprocessor.var_[i])\n ]\n )\n rd['preprocessing']['performance'] = OrderedDict()\n rd['preprocessing']['performance']['cpu_time'] = \\\n o.cpu_time_preprocess\n\n if rd['preprocessing']['type'] is 'standard_scaler':\n for k,v in rd['preprocessing']['results'].items():\n print(\"{},{},{}\".format(k,v['mean'],v['var']))\n\n o.calculate_manifold(d)\n\n rd['manifold'] = OrderedDict()\n rd['manifold']['type'] = d['manifold']['type']\n rd['manifold']['args'] = d['manifold']['args']\n rd['manifold']['results'] = OrderedDict()\n rd['manifold']['names'] = o.manifold_names\n rd['manifold']['performance'] = OrderedDict()\n rd['manifold']['performance']['cpu_time'] = \\\n o.cpu_time_manifold\n\n o.calculate_kNN_analysis(d)\n o.calculate_clusters(d)\n\n all_cluster_ids = list(\n set(\n o.data.df['cluster_id'].tolist()\n )\n )\n all_cluster_ids = [v for v in all_cluster_ids if v != -1]\n for cid in all_cluster_ids:\n print(cid)\n\n exit()\n cluster_dfs = [o.data.df.loc[o.data.df['cluster_id'] == _id] for _id in set(o.data.df['cluster_id'].tolist())]\n\n for i, cluster_df in enumerate(cluster_dfs):\n print('\\nCLUSTER {} RESULTS:\\n'.format(i))\n param_names = [col for col in cluster_df.columns if col.endswith('.nparam')]\n err_names = [col for col in cluster_df.columns if col.endswith('.nerr')]\n # calculate kde, covariance, and centroids\n param_kde = stats.gaussian_kde(cluster_df[param_names])\n param_covariance = param_kde.covariance\n tsne_centroid = {col: cluster_df[col].mean() for col in o.manifold_names}\n param_centroid = {col: cluster_df[col].mean() for col in param_names}\n param_var = {col: cluster_df[col].var() for col in param_names}\n err_centroid = {col: cluster_df[col].mean() for col in err_names}\n err_var = {col: cluster_df[col].var() for col in err_names}\n\n print('t-SNE Centroid: {}'.format(tsne_centroid))\n print('nParam Centroid: {}'.format(param_centroid))\n print('nParam Variance: {}'.format(param_var))\n print('nErr Centroid: {}'.format(err_centroid))\n print('nErr Variance: {}'.format(err_var))\n\n### PLOTTING RESULTS ----------------------------------------------------------\n\n if show_plots is True:\n fig1, (ax11,ax12) = plt.subplots(1,2)\n (nr,nc) = o.data.df.shape\n qe1,pe1 = ecdf(o.data.df['NN_1'])\n qe2,pe2 = ecdf(o.data.df['NN_2'])\n qe3,pe3 = ecdf(o.data.df['NN_3'])\n ax11.plot(qe1,pe1,lw=2,label='NN_1')\n ax11.plot(qe2,pe2,lw=2,label='NN_2')\n ax11.plot(qe3,pe3,lw=2,label='NN_3')\n ax11.set_xlabel('Quantile')\n ax11.set_ylabel('Cumulative probability')\n ax11.legend(fancybox=True, loc='right')\n ax12.hist(o.data.df['kNN_radius'])\n plt.show()\n\n fig2, (ax21,ax22,ax23) = plt.subplots(1,3)\n ax21.scatter(\n o.data.df[o.manifold_names[0]],\n o.data.df[o.manifold_names[1]],\n marker='.',\n s=1\n )\n\n cluster_colors = cm.spectral(\n o.data.df[o.data.df['cluster_id'] != -1]['cluster_id'].astype(float)\\\n /o.n_clusters\n )\n\n ax22.scatter(\n o.data.df[o.data.df['cluster_id'] != -1][o.manifold_names[0]],\n o.data.df[o.data.df['cluster_id'] != -1][o.manifold_names[1]],\n marker='.',\n c=cluster_colors,\n s=1\n )\n ax23.scatter(\n o.data.df[o.data.df['cluster_id'] == -1][o.manifold_names[0]],\n o.data.df[o.data.df['cluster_id'] == -1][o.manifold_names[1]],\n marker='.',\n s=1\n )\n plt.show()\n\n from pandas.plotting import parallel_coordinates\n fig3, ax3 = plt.subplots(1,1)\n cluster_ids = set(o.data.df['cluster_id'])\n for cluster_id in cluster_ids:\n parallel_coordinates(\n o.data.df[o.data.df['cluster_id'] == cluster_id][o.n_error_names],\n 'Ni_fcc.E_coh.nerr'\n )\n plt.gca().legend_.remove()\n plt.show()\n","sub_path":"dev/cluster_sampling/dev__cluster_analysis.py","file_name":"dev__cluster_analysis.py","file_ext":"py","file_size_in_byte":8434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"572414725","text":"from json import dumps, loads\nfrom sys import getsizeof\nfrom math import floor\nfrom socket import AF_INET, SOCK_STREAM, socket\nimport asyncio\nfrom numpy import ndarray\n\nto_nested_bjson_list = lambda x: \\\n\t\t\t\tdumps([list(i) for i in x]).encode()\n\nto_bjson_list = lambda x: \\\n\t\t\t\tdumps(list(x)).encode()\n\nfrom_bjson = lambda x: \\\n\t\t\t\tloads(x.decode())\n\nclass AsyncConnection(object):\n\t\"\"\"\n\tRun get_predictions in an event loop to get predictions from a server.\n\tAfter running get_predictions the object will have a .help attribute.\n\tThis is not an asynchronous context manager.\n\t\"\"\"\n\tdef __init__(self, address, loop=False, mode=[AF_INET, SOCK_STREAM]):\n\t\tself.sock = socket(*mode)\n\t\tself.mode = mode\n\t\tself.loop = loop if loop else asyncio.get_event_loop()\n\t\tself.address = address\n\n\tasync def set_server_help(self):\n\t\tresp = await self.send_recv(message=b'-h', nbytes=10000)\n\t\tself.help = loads(resp.decode())\n\n\tasync def set_maxbytes(self):\n\t\tresp = await self.send_recv(message=b'maxbytes', nbytes=512)\n\t\tself.maxbytes = int(resp.decode())\n\n\tasync def send_recv(self, message: bytes, nbytes: int) -> bytes:\n\t\tawait self.loop.sock_sendall(sock=self.sock, data=message)\n\t\treturn await self.loop.sock_recv(sock=self.sock, n=nbytes)\n\n\tasync def get_predictions(self, X: ndarray) -> list:\n\t\tawait self.loop.sock_connect(sock=self.sock, address=self.address)\n\t\tshape = X.shape\n\t\tif len(shape) == 1: # if there is only one element\n\n\t\t\tprediction = from_bjson(await self.send_recv(\n\t\t\t\t\t\t\tnbytes=10000,\n\t\t\t\t\t\t\tmessage=to_nested_bjson_list(X.reshape(1, -1))),\n\t\t\t\t\t\t\t)\n\n\t\telse:\n\t\t\tawait self.set_maxbytes()\n\t\t\tone_element_size = getsizeof(to_bjson_list(X[0]))\n\t\t\tmax_elements = floor(self.maxbytes / one_element_size)\n\t\t\tindex_to = map(lambda x: [x, x+max_elements],\n\t\t\t\t\t\t\t\trange(0, shape[0], max_elements))\n\t\t\t# index_to contains the indexes used to send the array in chunks\n\t\t\t\n\t\t\tcoroutines = [self.send_recv(\n\t\t\t\t\t\t\tmessage=to_nested_bjson_list(X[index:to]),\n\t\t\t\t\t\t\tnbytes=self.maxbytes) for index, to in index_to]\n\t\t\t# a list of self.send_recv() coroutines.\n\n\t\t\tresp = await asyncio.gather(*coroutines, loop=self.loop) \n\t\t\t# asyncio.gather(list of coroutines) -> list[results]\n\n\t\t\tprediction = map(from_bjson, resp); del resp, X\n\n\t\tawait self.set_server_help()\n\t\tawait self.loop.sock_sendall(sock=self.sock, data=b'exit')\n\t\tself.loop.call_soon(self.sock.close)\n\t\treturn list(prediction)\n\nif __name__ == '__main__':\n\tc = AsyncConnection(address=('localhost', 5555))\n","sub_path":"Sky_Classification/AsyncConnection.py","file_name":"AsyncConnection.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"364765909","text":"def cache_result(func, *args, **kwargs):\n \"\"\"\n This code considers any iterable type (e.g. tuple, list) whose constituent elements are identical as identical.\n In theory this could cause a function decorated with cache_result to incorrectly return the result of a call with\n other parameters, but in practice you would need to write a function that deliberately behaves differently depending\n on the particular type of iterable, and then deliberately decorate it with cache_result, and then deliberately call it\n with params that would exploit this hole.\n There is also unbounded growth with this code. We could use a version specifically for instance methods where the cache\n will be stored on self, and the key would include the method name; those caches would go away as the objects go away.\n That approach, however, does not work with freestanding functions.\n \"\"\"\n def make_key_from_obj(obj):\n try:\n hash(obj)\n key = (obj,)\n return key\n except TypeError:\n pass\n if isinstance(obj, dict):\n key = tuple()\n for k, v in obj.items():\n key += (k,) + make_key_from_obj(v)\n return key\n try:\n key = tuple()\n for subobj in iter(obj):\n key += make_key_from_obj(subobj)\n return key\n except:\n raise TypeError('Not hashable, not iterable, not a dict')\n\n def make_key_from_args(*args, **kwargs):\n return make_key_from_obj(args) + make_key_from_obj(kwargs)\n\n def get_cached_result(f, *args, **kwargs):\n key = make_key_from_args(*args, **kwargs)\n if not hasattr(f, '_cached_results'):\n f._cached_results = {}\n if not f._cached_results.has_key(key):\n f._cached_results[key] = f(*args, **kwargs)\n return f._cached_results[key]\n\n def proxy(*args, **kwargs):\n return get_cached_result(func, *args, **kwargs)\n\n return proxy\n","sub_path":"eusful/decorators/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"330242666","text":"s=[]\nprime_number=0\nfor i in range(5):\n num=int(input(\"Enter your number: \"))\n if num==2 or num==3 or num==5 or num==7 :\n prime_number=num\n s.append(prime_number)\n elif num<2:\n continue\n elif num%2==0 or num%3==0 or num%5==0 or num%7==0 or num%9==0:\n continue\n else:\n prime_number=num\n s.append(prime_number)\nprint(min(s))","sub_path":"While/While_for_task2_8.py","file_name":"While_for_task2_8.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"137661460","text":"\nimport module3 as m\n\ndef module_test( name ) :\n def ext_decorator( func ) :\n def ext_function() :\n print( '*************************************************************' )\n print( 'STARTING TEST {}'.format( name ) )\n func()\n print( 'FINISHED TEST {}'.format( name ) )\n print( '*************************************************************' )\n return ext_function\n return ext_decorator\n\n@module_test( 'scope-testing::elements' )\ndef test_1() :\n elm1 = m.ElementRaw( 'elm-1' )\n\n@module_test( 'scope-testing::containers' )\ndef test_2() :\n cont = m.Container( 'test_2 - cont-1' )\n elm1 = m.ElementRaw( 'test_2 - elm-1' )\n elm2 = m.ElementRaw( 'test_2 - elm-2' )\n cont.addElementRaw( elm1 )\n cont.addElementRaw( elm2 )\n\n@module_test( 'shared-testing::containers' )\ndef test_3() :\n def factory( container ) :\n container.addElementRaw( m.ElementRaw( 'test_3 - elm-1' ) )\n container.addElementRaw( m.ElementRaw( 'test_3 - elm-2' ) )\n cont = m.Container( 'test_3 - cont-1' )\n factory( cont )\n\n@module_test( 'scope-testing::getter' )\ndef test_4() :\n cont = m.Container( 'test_4 - cont-1' )\n elm1 = m.ElementRaw( 'test_4 - elm-1' )\n elm2 = m.ElementRaw( 'test_4 - elm-2' )\n cont.addElementRaw( elm1 )\n cont.addElementRaw( elm2 )\n\n elms = cont.elementsRaw()\n print( 'elms: ', elms )\n\n@module_test( 'shared-testing::getter' )\ndef test_5() :\n def factory( container ) :\n container.addElementRaw( m.ElementRaw( 'test_5 - elm-1' ) )\n container.addElementRaw( m.ElementRaw( 'test_5 - elm-2' ) )\n return container.elementsRaw()\n cont = m.Container( 'test_5 - cont-1' )\n elms = factory( cont )\n del cont\n print( 'nulling obj-list' )\n elms = None\n print( 'done nulling, should have release list\\'s elements' )\n\n@module_test( 'shared-testing::getter-2' )\ndef test_6() :\n def factory( container ) :\n container.addElementRaw( m.ElementRaw( 'test_6 - elm-1' ) )\n container.addElementRaw( m.ElementRaw( 'test_6 - elm-2' ) )\n return container.elementsRaw()\n cont = m.Container( 'test_6 - cont-1' )\n elms = factory( cont )\n print( 'nulling obj-list' )\n elms = None\n print( 'done nulling, SHOULDN\\'T have release list\\'s elements' )\n del cont\n\nif __name__ == '__main__' :\n test_1()\n test_2()\n test_3()\n test_4()\n test_5()\n test_6()","sub_path":"tests/test_module3_raw.py","file_name":"test_module3_raw.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"47085186","text":"import pytest\nfrom company.models import Company\nfrom user.models import UserGroup\nfrom user.models import User\nfrom device.models import DeviceGroup\nfrom device.models import Device\nfrom id_management.member.models import MemberGroup\nfrom id_management.member.models import Member\nfrom base.db import PostgresqlDB\nimport file\nimport json\n\n\ndef create_company(db, name=None):\n company = Company()\n company.create_company()\n if name is not None:\n company.name = name\n sql = \"INSERT INTO public.organizations_company(created, modified, name, email, phone)\" \\\n \" VALUES ('{0}', '{1}', '{2}', '{3}', '{4}') returning id\" \\\n .format(company.create_time, company.modify_time, company.name, company.email, company.phone)\n result = db.save(sql)\n return result\n\n\n@pytest.fixture(scope=\"function\")\ndef mock_company():\n with open(file.project_dir + \"/mock/json/company.json\", 'r') as f:\n data = json.load(f)\n name = data[\"company\"]\n db = PostgresqlDB()\n rows = db.select(\"select id from organizations_company where name='{0}'\".format(name))\n if len(rows) == 0:\n return create_company(db, name)\n else:\n return rows[0][0]\n\n\n@pytest.fixture(scope=\"function\")\ndef mock_user_group(mock_company):\n db = PostgresqlDB()\n user_group = UserGroup()\n user_group.create_user_group()\n user_group.set_company_id(mock_company)\n sql = \"INSERT INTO users_usergroup(created,modified,name,company_id,\\\"default\\\") \" \\\n \"VALUES('{0}','{1}','{2}','{3}',false) returning id\" \\\n .format(user_group.create_time, user_group.modify_time, user_group.name, user_group.companyId)\n print(sql)\n result = db.save(sql)\n print(\"add user group\")\n yield result\n sql = \"delete from users_usergroup where id = {0}\".format(result)\n print(sql)\n db.delete(sql)\n print(\"delete user group\")\n\n\n@pytest.fixture(scope=\"function\")\ndef mock_exist_user_group(mock_company):\n db = PostgresqlDB()\n sql = \"select id from users_usergroup where name='{name}' and company_id='{company_id}'\" \\\n .format(name=\"cxd_user_group_2\", company_id=mock_company)\n rows = db.select(sql)\n group_id = 0\n if len(rows) == 1:\n group_id = rows[0][0]\n return group_id\n\n\n@pytest.fixture()\ndef mock_exist_device_group(mock_company):\n db = PostgresqlDB()\n sql = \"select id from devices_devicegroup where name='{name}' and company_id = '{company_id}'\" \\\n .format(name=\"cxd_device_group_2\", company_id=mock_company)\n rows = db.select(sql)\n device_group_id = 0\n if len(rows) == 1:\n device_group_id = rows[0][0]\n return device_group_id\n\n\n@pytest.fixture()\ndef mock_device_group(mock_user_group):\n db = PostgresqlDB()\n device_group = DeviceGroup()\n device_group.create_device_group()\n print(device_group.name)\n device_group.set_user_group_id(mock_user_group)\n sql = \"INSERT INTO devices_devicegroup(created,modified,name,user_group_id,license_type,uuid) \" \\\n \"VALUES('{0}','{1}','{2}','{3}','{4}','{5}') returning id\" \\\n .format(device_group.create_time, device_group.modify_time, device_group.name,\n device_group.userGroupId, device_group.license_type, device_group.uuid)\n result = db.save(sql)\n print(\"add device_group\")\n result_array = []\n result_array.append(result)\n result_array.append(mock_user_group)\n yield result_array\n sql = \"delete from devices_devicegroup where id = {0}\".format(result_array[0])\n db.delete(sql)\n print(\"delete device_group\")\n\n\n@pytest.fixture()\ndef mock_device():\n db = PostgresqlDB()\n device = Device()\n device.create_device()\n sql = \"insert into devices_device(uuid,created,modified,name,online)\" \\\n \"VALUES ('{0}','{1}','{2}','{3}',TRUE) returning id\" \\\n .format(device.uuid, device.create_time, device.modify_time, device.name)\n print(\"add device\")\n result = db.save(sql)\n yield result\n sql = \"delete from devices_device where id = {0}\".format(result)\n db.delete(sql)\n print(\"delete device\")\n\n\n@pytest.fixture()\ndef mock_add_device(mock_company, mock_exist_device_group):\n db = PostgresqlDB()\n device = Device()\n device.create_device()\n\n sql = \"insert into devices_device(created,modified,name,uuid,online,company_id) \" \\\n \"VALUES ('{0}','{1}','{2}','{3}',TRUE,{4}) returning id\" \\\n .format(device.create_time, device.modify_time, device.name, device.uuid, mock_company)\n result_id = db.patch_save(sql)\n\n sql = \"insert into devices_device_groups(device_id,devicegroup_id) VALUES ({0},{1}) returning id\" \\\n .format(result_id, mock_exist_device_group)\n db.patch_save(sql)\n\n # add license\n sql = \"insert into devices_license(created,modified,type,expired_at,device_id)\" \\\n \" VALUES ('{0}','{1}','{2}','{3}',{4}) returning id\" \\\n .format(device.create_time, device.modify_time, \"id\", device.expired_at, result_id)\n db.patch_save(sql)\n db.patch_commit()\n\n@pytest.fixture()\ndef mock_user(mock_user_group, mock_company):\n db = PostgresqlDB()\n user = User()\n user.create_user()\n user.companyId = mock_company\n user.groups.append(mock_user_group)\n sql = \"insert into users_user(password,is_superuser,is_staff,is_active,date_joined,email,username,reset,first_name,last_name)\" \\\n \"VALUES ('{0}',FALSE ,TRUE ,TRUE ,'{1}','{2}','{3}',FALSE,'','') returning id\" \\\n .format(user.password, user.create_time, user.email, user.username)\n print(sql)\n user_id = db.save(sql)\n\n sql = \"insert into users_user_groups(user_id,usergroup_id)\" \\\n \"VALUES ({0},{1}) returning id\".format(user_id, mock_user_group)\n print(sql)\n user_group_id = db.save(sql)\n\n sql = \"insert into users_user_roles(user_id,userrole_id)\" \\\n \"VALUES ({0},{1}) returning id\".format(user_id, user.roles[0])\n print(sql)\n user_role_id = db.save(sql)\n\n print(\"add user\")\n\n result = []\n result.append(user_id)\n result.append(user_group_id)\n result.append(user_role_id)\n yield result\n\n sql = \"delete from users_user_roles where id = {0}\".format(result[2])\n print(sql)\n db.delete(sql)\n\n sql = \"delete from users_user_groups where id = {0}\".format(result[1])\n print(sql)\n db.delete(sql)\n\n sql = \"delete from users_user where id = {0} \".format(result[0])\n print(sql)\n db.delete(sql)\n\n print(\"delete user\")\n\n\n@pytest.fixture()\ndef mock_member_group(mock_company):\n db = PostgresqlDB()\n member_group = MemberGroup()\n member_group.create_member_group()\n member_group.companyId = mock_company\n sql = \"insert into members_membergroup(created,modified,name,company_id,virtual,uuid)\" \\\n \"VALUES ('{0}','{1}','{2}',{3},{4},'{5}') returning id\" \\\n .format(member_group.create_time, member_group.modify_time,\n member_group.name, member_group.companyId, False, member_group.uuid)\n print(sql)\n result = db.save(sql)\n print(\"add member group\")\n yield result\n sql = \"delete from members_membergroup where id = {0}\".format(result)\n print(sql)\n db.delete(sql)\n print(\"delete member group\")\n\n\n@pytest.fixture()\ndef mock_exist_member_group(mock_company):\n db = PostgresqlDB()\n sql = \"select id from members_membergroup where name='{name}' and company_id = '{company_id}'\" \\\n .format(name=\"cxd_member_group_2\", company_id=mock_company)\n rows = db.select(sql)\n member_group_id = 0\n if len(rows) == 1:\n member_group_id = rows[0][0]\n return member_group_id\n\n\n@pytest.fixture()\ndef mock_member(mock_member_group, mock_company):\n db = PostgresqlDB()\n member = Member()\n member.create_member()\n member.companyId = mock_company\n sql = \"insert into members_member(created,modified,member_id,name,email,is_active,company_id,type)\" \\\n \"VALUES ('{0}','{1}',{2},'{3}','{4}',TRUE,{5},1) returning id\" \\\n .format(member.create_time, member.modify_time, member.member_id, member.name, member.email, member.companyId)\n print(sql)\n member_id = db.save(sql)\n print(\"add member\")\n\n sql = \"insert into members_member_groups(member_id,membergroup_id) VALUES ({0},{1}) returning id\" \\\n .format(member_id, mock_member_group)\n print(sql)\n id = db.save(sql)\n\n result = []\n result.append(member_id)\n result.append(mock_member_group)\n result.append(id)\n yield result\n sql = \"delete from members_member_groups where id = {0}\".format(result[2])\n print(sql)\n db.delete(sql)\n\n sql = \"select id from members_membergroup where name='ALL' and company_id={company_id} \" \\\n .format(company_id=mock_company)\n rows = db.select(sql)\n all_group_id = 0\n if len(rows) == 1:\n all_group_id = rows[0][0]\n sql = \"delete from members_member_groups where membergroup_id = {0}\".format(all_group_id)\n print(sql)\n db.delete(sql)\n\n sql = \"delete from members_member where id = {0}\".format(result[0])\n print(sql)\n db.delete(sql)\n print(\"delete member\")\n\n","sub_path":"mock/fixture_mock_data.py","file_name":"fixture_mock_data.py","file_ext":"py","file_size_in_byte":9040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"532746600","text":"\"\"\"\n1331. Rank Transform of an Array\nEasy\n\n169\n\n12\n\nAdd to List\n\nShare\nGiven an array of integers arr, replace each element with its rank.\n\nThe rank represents how large the element is. The rank has the following rules:\n\nRank is an integer starting from 1.\nThe larger the element, the larger the rank. If two elements are equal, their rank must be the same.\nRank should be as small as possible.\n\"\"\"\n\n\ndef arrayRankTransform(arr):\n \"\"\"\n :type arr: List[int]\n :rtype: List[int]\n \"\"\"\n arr_1 = arr[:]\n arr_1.sort()\n list_1 = []\n final_list = []\n j=0\n for i in range(len(arr_1)):\n if i>0 and arr_1[i] != arr_1[i-1]:\n list_1.append(j+1)\n elif i==0:\n list_1.append(j+1)\n elif i>0 and arr_1[i] == arr_1[i-1]:\n list_1.append(j)\n j = j-1\n else:\n list_1.append(j+1)\n j+=1\n dict_1 = dict(zip(arr_1,list_1))\n for j in range(len(arr)):\n final_list.append(dict_1[arr[j]])\n return final_list","sub_path":"data_structures/arrays/easy_4.py","file_name":"easy_4.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"551919134","text":"from pyramid.response import Response\nfrom pyramid.view import view_config\nfrom ..models import UserManager\nfrom admin import checkAdminLogin\n\n\n@view_config(route_name='admin.userlist', request_method='GET', renderer='../templates/admin_userlist.jinja2')\ndef admin_mian_userlist(request):\n checkAdminLogin(request)\n\n start = request.GET.get(\"start\", \"\")\n key = request.GET.get(\"key\", \"\")\n orderby = request.GET.get(\"orderby\", \"\")\n\n if(start==None or start==\"\"):\n start = 0\n else:\n start = int(start)\n\n if(key==None): key = \"\"\n if (orderby == None or orderby==\"\"): orderby = 0\n ubs = []\n pages = 0\n\n try:\n mgr = UserManager(request.dbsession)\n ubs,count = mgr.getUserList(key,orderby,start)\n pages = count//10\n if(count%10!=0):\n pages += 1\n except:\n pass\n return {'users': ubs, \"pages\":pages, \"page\":start,\"key\":key,\"orderby\":orderby}\n\n@view_config(route_name='admin.userdetail', request_method='GET', renderer='../templates/admin_userdetail.jinja2')\ndef admin_mian_userdetail(request):\n checkAdminLogin(request)\n\n uid = request.GET.get(\"uid\", \"\")\n if(uid==None or uid==\"\"):\n return {}\n mgr = UserManager(request.dbsession)\n ub = mgr.getUserInfo(uid)\n return {'user': ub}\n\n@view_config(route_name='admin.userlog', request_method='GET', renderer='../templates/admin_userloglist.jinja2')\ndef admin_mian_userlog(request):\n checkAdminLogin(request)\n\n uid = request.GET.get(\"uid\", \"\")\n if(uid==None or uid==\"\"):\n return {}\n mgr = UserManager(request.dbsession)\n ub = mgr.getUserlog(uid)\n return {'logs': ub}\n\n@view_config(route_name='admin.userbackup', request_method='GET', renderer='json')\ndef admin_main_userbackup(request):\n checkAdminLogin(request)\n\n mgr = UserManager(request.dbsession)\n filepath = mgr.userBackup()\n return {'status': 0,'info':'用户已导出,点击确认后下载',\"path\":\"%s/static/backup/%s\"%(request.host_url,filepath)}\n\n\n@view_config(route_name='admin.userremove', request_method='GET', renderer='json')\ndef admin_main_userremove(request):\n checkAdminLogin(request)\n\n uid = request.GET.get('uid')\n mgr = UserManager(request.dbsession)\n mgr.removeUser(uid)\n return {\"status\": 0, 'info': '用户已删除。'}","sub_path":"server/apps/authority/views/admin_user_manager.py","file_name":"admin_user_manager.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"310357566","text":"#!/usr/bin/python\n_author_ = 'sergey kharnam'\n\nimport sys\nsys.path.append('/home/kharnam/devel/sandbox/selenium_test')\nimport selenium_constants as SC\nimport selenium_functions as SF\n\n\nif __name__ == '__main__':\n log = SF.set_logger()\n test = SF.SeleniumTest(browser_type='firefox')\n test.open_url_firefox(SC.BASE_URL)\n test.close_browser()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"588312447","text":"from django.contrib.auth.models import User\nfrom django.test import TestCase\n\nfrom crud.crud_app.forms import UserForm, PersonalProfileForm\nfrom crud.crud_app.models import PersonalProfile\n\n\nclass UserFormTest(TestCase):\n\n def setUp(self):\n\n self.userform = UserForm({\n 'first_name': \"Manu\",\n 'last_name': \"Perez\",\n 'email': \"manu@gmail.com\",\n })\n\n def test_creation(self):\n\n self.assertTrue(self.userform.is_valid())\n userform = self.userform.save()\n self.assertEqual(userform.first_name, \"Manu\")\n self.assertEqual(userform.last_name, \"Perez\")\n self.assertEqual(userform.email, \"manu@gmail.com\")\n\n def test_is_valid(self):\n self.assertTrue(self.userform.is_valid())\n\n def test_empty_is_not_valid(self):\n form = UserForm()\n self.assertFalse(form.is_valid())\n\n\nclass PersonalProfileFormTest(TestCase):\n\n def setUp(self):\n user = User.objects.create(username=\"User\")\n pp = PersonalProfile.objects.create(user=user)\n\n self.personalprofileform = PersonalProfileForm({\n 'previous_address': \"Germany\",\n 'actual_address': \"UK\",\n }, instance=pp)\n\n def test_creation(self):\n self.assertTrue(self.personalprofileform.is_valid())\n personalprofileform = self.personalprofileform.save()\n self.assertEqual(personalprofileform.previous_address, \"Germany\")\n self.assertEqual(personalprofileform.actual_address, \"UK\")\n\n def test_is_valid(self):\n self.assertTrue(self.personalprofileform.is_valid())\n\n def test_empty_is_not_valid(self):\n form = PersonalProfileForm()\n self.assertFalse(form.is_valid())","sub_path":"crud/crud_app/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"592719748","text":"# Copyright 2017 SuccessOps, LLC All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ndef GenerateConfig(context):\n\n project = context.env['project']\n project_number = context.env['project_number']\n resources = []\n\n for service in context.properties['backend-services']:\n name = service['name']\n enableCdn = service['enableCdn']\n health_checks = []\n for health_check in service['health-checks']:\n health_checks.append('$(ref.{}.selfLink)'.format(health_check))\n\n backends = []\n for backend in service['backends']:\n temp = '$(ref.{}.instanceGroup)'.format(backend['group'])\n backends.append({\n 'balancingMode': backend['mode'],\n 'capacityScaler': backend['capacityScaler'],\n 'group': temp,\n 'maxRatePerInstance': backend['maxRatePerInstance'],\n 'maxUtilization': backend['maxUtilization'],\n })\n\n resources.append(\n {\n 'name': name,\n 'type': 'compute.v1.backendService',\n 'properties': {\n 'healthChecks': health_checks,\n 'protocol': 'HTTP',\n 'enableCDN': enableCdn,\n 'backends': backends\n }\n })\n\n return {'resources': resources}\n","sub_path":"deploy/python/make_backend_services.py","file_name":"make_backend_services.py","file_ext":"py","file_size_in_byte":1697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"125692024","text":"import json\n\nfilename = 'favorite_number.json'\n\ntry:\n with open(filename, 'r') as file_object:\n print('I know your favorite number! It\\'s ' +\n str(json.load(file_object)))\nexcept FileNotFoundError:\n while True:\n try:\n number = int(input('What is your favorite number?\\n'))\n except ValueError:\n print('Put a number.\\n')\n else:\n with open(filename, 'w') as file_object:\n json.dump(number, file_object)\n break\n","sub_path":"10/Favorite_numer_remembered.py","file_name":"Favorite_numer_remembered.py","file_ext":"py","file_size_in_byte":517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"634532708","text":"from app import create_app, db\nfrom app.models import Instrument, Style, OriginalAuthor, Music\n\napp = create_app()\n\n@app.shell_context_processor\ndef make_shell_context():\n \"\"\"Prepares variables when running `flask shell`.\"\"\"\n return {\n 'db': db,\n 'Instrument': Instrument,\n 'Style': Style,\n 'OriginalAuthor': OriginalAuthor,\n 'Music': Music,\n }\n","sub_path":"sheetmusic.py","file_name":"sheetmusic.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"169651086","text":"#!/usr/bin/python3\n\nimport os\nimport subprocess\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom urllib import parse\n\ndef check_links(url, ignore, fh):\n ignore[\"menu\"] = ignore[\"Previous\"] = ignore[\"Next\"] = url + \"#\"\n try:\n driver.get(url)\n except:\n print(\"failed to get: {0}\".format(url), file=sys.stderr)\n exit()\n links = driver.find_elements_by_tag_name(\"a\")\n\n for link in links:\n text = link.text\n href = link.get_attribute(\"href\")\n # ignore these guys\n if text in ignore.keys() and ignore[text] == href:\n continue\n elif text:\n if href:\n scheme = parse.urlparse(href).scheme\n if scheme == \"mailto\":\n continue\n elif link.get_attribute(\"class\") == \"video-link play\":\n continue\n\n print(\"'{0}','{1}','{2}'\".format(url, text, href), file=fh)\n\nbase = \"https://www.une.edu\"\npets = [\"cgh\", \"tgf\", \"morocco\"]\ncmd = \"\"\"sqlq 'SELECT `alias` FROM `url_alias` WHERE `alias` REGEXP \"^({0})\"'\"\"\".format(\"|\".join(pets))\naliases = subprocess.check_output([\"drush\", \"@une.prod\", cmd]).splitlines()\naliases = [parse.quote(a) for a in aliases]\n\nignore = {\"search\":os.path.join(base, \"search\"),\n \"Alumni\":\"http://alumni.une.edu/\",\n \"Employees\":\"https://www.une.edu/employees\",\n \"Families\":\"https://www.une.edu/families\",\n \"Patients\":\"https://www.une.edu/patients\",\n \"Students\":\"https://www.une.edu/students\",\n \"Athletics\":\"http://athletics.une.edu/\",\n \"UNE TV\":\"https://www.une.edu/tv\",\n \"Maine, USA\":\"https://www.une.edu/maps?campus=biddeford%2Cportland&type=cities\",\n \"Tangier, Morocco\":\"https://www.une.edu/maps?campus=tangier\",\n \"Online\":\"http://online.une.edu/\",\n \"ABOUT\":\"https://www.une.edu/about\",\n \"ACADEMICS\":\"https://www.une.edu/academics\",\n \"RESEARCH\":\"https://www.une.edu/research\",\n \"ADMISSION\":\"https://www.une.edu/admissions\",\n \"STUDENT LIFE\":\"https://www.une.edu/studentlife\",\n \"GLOBAL\":\"https://www.une.edu/global\",\n \"GIVE\":\"https://www.une.edu/giving\",\n \"University of New England\":\"https://www.une.edu/maps\",\n \"Facebook\":\"http://www.facebook.com/universityofnewengland\",\n \"Instagram\":\"http://instagram.com/thisisune\",\n \"Twitter\":\"http://www.twitter.com/unetweets\",\n \"YouTube\":\"http://youtube.com/unecommunications\",\n \"Linkedin\":\"https://www.linkedin.com/edu/university-of-new-england-18588\",\n \"Home\":\"https://www.une.edu/\"}\n\nfh = open(\"bot_output/pet_pages.csv\", \"w\")\nprint(\"'Page','Link text','Link URL'\", file=fh)\n\ndriver = webdriver.PhantomJS()\nfor i in range(len(aliases)):\n alias = aliases[i]\n print(\"testing {0} ({1}/{2})\".format(alias, i+1, len(aliases)))\n\n url = os.path.join(base, alias)\n check_links(url, ignore, fh)\n\nfh.close()\n\ndriver.close()\ndriver.quit()\n","sub_path":"pet_pages.py","file_name":"pet_pages.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"264454848","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Product\nfrom django.utils import timezone\n\n# Create your views here.\n\n\ndef product_list(request):\n return render(request, 'product_list.html')\n\n\n@login_required\ndef publish(request):\n if request.method == 'GET':\n return render(request, 'publish.html')\n elif request.method == 'POST':\n title = request.POST['标题']\n intro = request.POST['介绍']\n url = request.POST['APP链接']\n try:\n icon = request.FILES['APP图标']\n image = request.FILES['大图']\n\n product = Product()\n product.title = title\n product.intro = intro\n product.url = url\n product.icon = icon\n product.image = image\n\n product.pub_date = timezone.datetime.now()\n product.hunter = request.user\n\n product.save()\n\n return redirect('主页')\n\n except Exception as err:\n return render(request, 'publish.html', {'错误': '请上传图片!'})\n","sub_path":"products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"281842492","text":"from grafanalib.core import (\n Alert, AlertCondition, Dashboard, Graph, GaugePanel,\n GreaterThan, OP_AND, OPS_FORMAT, Row, RTYPE_SUM, SECONDS_FORMAT,\n SHORT_FORMAT, single_y_axis, Target, TimeRange, YAxes, YAxis\n)\n\n\ndashboard = Dashboard(\n title=\"Frontend Stats\",\n rows=[\n Row(panels=[\n GaugePanel(\n title=\"Power Consumption\",\n dataSource='prometheus',\n targets=[\n Target(\n expr='_mqtt:instantaneous_power_house',\n legendFormat=\"Consumption Now\",\n refId='A',\n ), \n ]\n )\n ])\n ]\n).auto_panel_ids()\n","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"251467829","text":"\"\"\"\n题目:请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。\n例如,字符串 \"+100\"、\"5e2\"、\"-123\"、\"3.1416\" 及 \"-1E-16\" 都表示数值,\n但 \"12e\"、\"1a3.14\"、\"1.2.3\"、\"+-5\" 及 \"12e+5.4\" 都不是。\n\"\"\"\n\n\"\"\"\n数字的格式可以用 A[.[B]][e|EC] 或者 .B[e|EC] 表示,\n其中 A 和 C 都是整数 (可以有正负号,也可以没有),而 B 是一个无符号整数。\n\"\"\"\n\ndef is_num(string):\n if (string is None) or (len(string) <= 0):\n return False\n\n is_numeric = False\n\n length = len(string)\n pos = 0\n\n # 数字开头的正负号\n if (string[pos] == '+') or (string[pos] == '-'):\n pos += 1\n\n # 开头去掉正号或负号的整数部分\n new_pos = scan_unsigned_integer(string, length, pos)\n\n is_numeric = new_pos > pos\n pos = new_pos\n\n # 如果出现'.',则接下来是小数部分\n if (pos < length) and (string[pos] == '.'):\n pos += 1\n new_pos = scan_unsigned_integer(string, length, pos)\n\n # 使用 or,原因如下:\n # 1. 小数可以没有整数部分,如 .123 等于 0.123;\n # 2. 小数点后面可以没有数字,如 233. 等于 233.0\n # 3. 小数点前面和后面都可以有数字,如 2.5\n is_numeric = (new_pos > pos) or is_numeric\n pos = new_pos\n\n # 如果出现 'e' 或者 'E',则接下来是数字的指数部分\n if (pos < length) and ((string[pos] == 'e') or (string[pos] == 'E')):\n pos += 1\n if (pos < length) and ((string[pos] == '+') or (string[pos] == '-')):\n pos += 1\n\n new_pos = scan_unsigned_integer(string, length, pos)\n\n # 使用 and,原因如下:\n # 1. 当 e 或 E 前面没有数字时,整个字符串不能表示数字,如 .e1、e1;\n # 2. 当 e 或 E 后面没有整数时,整个字符串不能表示数字,如 12e、12e+5.4\n is_numeric = (new_pos > pos) and is_numeric\n pos = new_pos\n\n return (is_numeric and (pos >= length))\n\n\ndef scan_unsigned_integer(string, length, pos):\n while (pos < length) and (48 <= ord(string[pos]) <= 57):\n pos += 1\n\n return pos\n\n\nprint(is_num(\"+100\"))\nprint(is_num(\"5e2\"))\nprint(is_num(\"-123\"))\nprint(is_num(\"3.1416\"))\nprint(is_num(\"+e100\"))\nprint(is_num(\"-1E-16\"))\nprint(is_num(\"12e\"))\nprint(is_num(\"1a3.14\"))\nprint(is_num(\"1.2.3\"))\nprint(is_num(\"+-5\"))\nprint(is_num(\"12e+5.4\"))\nprint(is_num(\".123\"))\nprint(is_num(\"123.\"))\nprint(is_num(\"5.4\"))\nprint(is_num(\".e1\"))\nprint(is_num(\"e1\"))\n","sub_path":"20-表示数值的字符串/question.py","file_name":"question.py","file_ext":"py","file_size_in_byte":2537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"399868736","text":"from random import seed\nfrom random import randint\nfrom bitstring import Bits\nimport os.path\nimport socket\nimport random\n\ndef channel_biterror(hexastr1):\n#espera una cadena hexadecimal con un header de 32 bits (16 hex chars)\n#devuelve la cadena con algun error\n hexastr=(Bits(hex=hexastr1))\n bitsstr=(hexastr.bin)\n max_errores=2\n nerr=0 #pueden cambiar para aumentar o disminuir los errores\n for i in range(max_errores):\n nerr+=randint(0,1)\n #print(nerr) #descomentar para debug\n for j in range(nerr):\n final=\"\"\n lugar_hex = randint(0,len(bitsstr)-1)\n #print(lugar_hex)#descomentar para debug\n l=0\n for a in bitsstr:\n if(l==lugar_hex):\n if(a==\"1\"):\n final+=\"0\"\n else:\n final+=\"1\"\n else:\n final+=a\n l+=1\n bitsstr=final\n hexout=\"\"\n #print('bitsstr type 2: ', type(bitsstr))\n veces=int(len(bitsstr)/8)\n for b in range(0,veces):\n hexout+=\"%02x\" % int(bitsstr[b*8:(b+1)*8], 2)\n return hexout\n \ndef checksum(header, size):\n ptr = 0\n cksum=\"\"\n hexastr=(Bits(hex=header))\n bitsstr=(hexastr.bin)\n #print('bitsstr: ', bitsstr)\n for b in range(0,int(size/8)):\n cksum += \"%02x\" % int(bitsstr[b*8:(b+1)*8], 2)\n #print('CKSUM hex: ', cksum)\n #suma en pares de 2 bytes.\n cksum = int(cksum,16)\n #print('Cksum 1: ', cksum)\n cksum = (cksum >> 16) + (cksum & 0xffff)\n #print('Cksum 2: ', cksum)\n cksum += (cksum >> 16)\n #print('Cksum 3: ', cksum)\n \n return (~cksum) & 0xFFFF\n\ndef process_cksumpkt(pktcksum, size):\n while size != 16:\n pktcksum = '0' + pktcksum\n size = len(pktcksum)\n return pktcksum\n\n \ndef isNak(msg):\n obejeto_en_bytes = bytes.fromhex(msg[8:16])\n NAK = obejeto_en_bytes.decode(\"utf-8\", \"replace\")\n for i in range(len(NAK)):\n if NAK[i] == '1':\n return True\n return False\n \ndef isACK(msg):\n obejeto_en_bytes = bytes.fromhex(msg[:8])\n ACK = obejeto_en_bytes.decode(\"utf-8\", \"replace\")\n for i in range(len(ACK)):\n if ACK[i] == '1':\n return True\n return False\n \n\ndef create_cksum():\n largo = 0\n cksum = ''\n while largo != 16:\n cksum += '0'\n largo = len(cksum)\n return cksum\n\ndef make_pkt(segHeader, data, cksum):\n #print('Cksum value: ', pktcksum)\n if len(pktcksum) < 16:\n cksum = process_cksumpkt(cksum, len(cksum))\n #print('Packet cksum: ',pktcksum)\n pktheader = segHeader + cksum\n hexaPktHeader=pktheader.encode('utf-8').hex()\n hexPktHeader = hexaPktHeader + hexastr1\n salida=channel_biterror(hexPktHeader)\n #print('Esto es salida: ',salida)\n #print(type(salida))\n return salida\n \ndef rcv_pkt(msg):\n obejeto_en_bytes = bytes.fromhex(msg[:])\n mensaje = obejeto_en_bytes.decode(\"utf-8\", \"replace\")\n #print('Mensaje recibido: ',mensaje)\n obejeto_en_bytes = bytes.fromhex(msg[:8])\n ACK = obejeto_en_bytes.decode(\"utf-8\", \"replace\")\n obejeto_en_bytes = bytes.fromhex(msg[8:16])\n NAK = obejeto_en_bytes.decode(\"utf-8\", \"replace\")\n objetoenbytes = bytes_object = bytes.fromhex(msg[16:32])\n pkt_seq_num = objetoenbytes.decode(\"utf-8\", \"replace\")\n objetoenbytes = bytes_object = bytes.fromhex(msg[32:64])\n pkt_cksum = objetoenbytes.decode(\"utf-8\", \"replace\")\n bytes_object = bytes.fromhex(msg[64:])\n pkt_data = bytes_object.decode(\"utf-8\", \"replace\")\n return ACK, NAK, pkt_seq_num, pkt_cksum, pkt_data\n\ndef search(cksumlist, val):\n for i in range(len(cksumlist)):\n if cksumlist[i] == val:\n return True\n return False\n \ndef corrupt(msg):\n pktcksum = checksum(msg,len(pkt))\n pktcksum = \"{0:b}\".format(pktcksum)\n return search(pktcksum,'1')\n \n\nif __name__ == '__main__':\n host = 'localhost'\n sender_port = 8001\n receiver_port = 8000\n ACK = '0000'\n NAK = '0000'\n sender_address = (host, sender_port)\n receiver_address = (host, receiver_port)\n sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n sock.bind(sender_address)\n \n archivo=\"test.txt\"\n pedazos=100\n if(os.path.isfile(archivo)):\n f = open(archivo,\"r\")\n for i in range(0,os.path.getsize(archivo) ,pedazos):\n seq_num = random.getrandbits(8)\n #print('Raw seq num: ', seq_num)\n seq_num = \"{0:b}\".format(seq_num)\n #print('Seq num: ',seq_num)\n cksum = create_cksum()\n seg_header = ACK + NAK + seq_num + cksum\n linea = f.read(pedazos)\n hexastr1=linea.encode('utf-8').hex()\n hexaHeader=seg_header.encode('utf-8').hex()\n #print('Pkt: ',hexaHeader+hexastr1)\n pkt = hexaHeader+hexastr1\n pktcksum = checksum(pkt,len(pkt))\n pktcksum = \"{0:b}\".format(pktcksum)\n print('Pkt cksum: ', pktcksum)\n sndpkt = make_pkt(ACK + NAK + seq_num, hexastr1,pktcksum)\n\n sock.sendto(sndpkt.encode(),receiver_address)\n bytes_object = bytes.fromhex(sndpkt[:])\n ascii_string = bytes_object.decode(\"utf-8\", \"replace\")\n print('ASCII-STRING: ',ascii_string)\n msg = sock.recv(1024).decode()\n while msg and (corrupt(msg) or isNak(msg)):\n print('Resending')\n sndpkt = make_pkt(ACK + NAK + seq_num, hexastr1,pktcksum)\n sock.sendto(sndpkt.encode(),receiver_address)\n msg = sock.recv(1024).decode()\n if msg and (not corrupt(msg) and isACK(msg)):\n print('We good')\n \n\n","sub_path":"UDP_transport_layer/sender2.py","file_name":"sender2.py","file_ext":"py","file_size_in_byte":5671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"548695201","text":"import json\nimport sys\n\n\n#Hardcoded filter\ndef filter_json(jdata):\n #Indexes to be discarded\n #blacklist = set([240, 241, 242, 275, 284, 300, 286, 301])\n blacklist = set([5, 7, 17, 23, 32, 43, 44, 49])\n\n res = []\n for i, doc in enumerate(jdata):\n #Aditional filter\n #if i < 100 or (i > 150 and i < 200):\n # continue\n if i > 48:\n break\n if i in blacklist:\n continue\n res.append(doc)\n return res\n\n\ninfile = open(sys.argv[1], encoding=\"utf-8\")\noutfile = open(sys.argv[2], \"w\", encoding=\"utf-8\")\njdata = json.load(infile)\ninfile.close()\n\nres = filter_json(jdata)\n\njson.dump(res, outfile, indent=4)\noutfile.close()\n\n\n","sub_path":"nerre/scripts/blacklist_json.py","file_name":"blacklist_json.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"27182452","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\n#Specify parameters\n#number of generations\nn_gen = 16\n\n#chance of a beneficial mutation\nr = 1e-5\n\n#total number of cells\nn_cells = 2**(n_gen-1)\n\n# Adaptive immunity:binomial distribution\nai_samples = np.random.binomial(n_cells, r, size=100000)\n\n# Report mean and std\nprint('AI Mean', np.mean(ai_samples))\nprint('AI std', np.std(ai_samples))\nprint('AI Fano', np.var(ai_samples) / np.mean(ai_samples))\n\n\ndef ecdf(data):\n return np.sort(data), np.arange(1, len(data) + 1) / len(data)\n\n#Function to draw out of random mutation hypothesis\ndef draw_random_mutation(n_gen, r):\n \"\"\"Draw sample under random mutation hypothesis\"\"\"\n # Initialize number of mutations\n n_mut = 0\n\n for g in range(n_gen):\n n_mut = 2*n_mut + np.random.binomial(2**g - 2*n_mut, r)\n\n return n_mut\n\ndef sample_random_mutation(n_gen, r, size=100000):\n #initialize samples\n samples = np.empty(size)\n\n #draw samples\n for i in range(size):\n samples[i] = draw_random_mutation(n_gen, r)\n\n return samples\n\nrm_samples = sample_random_mutation(n_gen, r)\n\nx_ai, y_ai = ecdf(ai_samples)\nx_rm, y_rm = ecdf(rm_samples)\n\nprint('RM Mean', np.mean(rm_samples))\nprint('RM std', np.std(rm_samples))\nprint('RM Fano', np.var(rm_samples) / np.mean(ai_samples))\n\nplt.semilogx(x_ai, y_ai, marker='.', linestyle='none', alpha=0.5)\nplt.semilogx(x_rm, y_rm, marker='.', linestyle='none', alpha=0.5)\nplt.xlabel('Number of mutants')\nplt.ylabel('ECDF')\nplt.legend(('Adaptive immunity', 'Random mutation'))\n","sub_path":"luria_delbruck.py","file_name":"luria_delbruck.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"431707468","text":"'''\n====================\nChemotaxis Experiments\n====================\n\nChemotaxis provides several pre-configured :py:class:`Experiments`\nwith different chemotactic agents and environments.\n'''\n\nfrom __future__ import absolute_import, division, print_function\n\nimport os\nimport copy\nimport sys\nimport argparse\n\nimport numpy as np\nfrom arpeggio import (\n RegExMatch,\n ParserPython,\n OneOrMore,\n)\n\nfrom vivarium.library.dict_utils import deep_merge\nfrom vivarium.core.emitter import (\n time_indexed_timeseries_from_data,\n timeseries_from_data\n)\nfrom vivarium.core.composition import (\n agent_environment_experiment,\n make_agents,\n simulate_experiment,\n plot_agents_multigen,\n process_in_compartment,\n EXPERIMENT_OUT_DIR,\n)\n\n# compartments\nfrom vivarium.compartments.static_lattice import StaticLattice\nfrom vivarium.compartments.chemotaxis_minimal import ChemotaxisMinimal\nfrom vivarium.compartments.chemotaxis_master import ChemotaxisMaster\nfrom vivarium.compartments.chemotaxis_flagella import (\n ChemotaxisVariableFlagella,\n ChemotaxisExpressionFlagella,\n ChemotaxisODEExpressionFlagella,\n)\n\n# processes\nfrom vivarium.processes.coarse_motor import MotorActivity\nfrom vivarium.processes.multibody_physics import agent_body_config\nfrom vivarium.processes.static_field import make_field\n\n# plots\nfrom vivarium.plots.multibody_physics import (\n plot_temporal_trajectory,\n plot_agent_trajectory,\n plot_motility,\n)\nfrom vivarium.plots.coarse_motor import plot_variable_receptor\n\n# make an agent from a lone MotorActivity process\n# MotorActivityAgent = MotorActivity\nMotorActivityAgent = process_in_compartment(\n MotorActivity,\n topology={\n 'external': ('boundary',),\n 'internal': ('cell',)})\n\n# environment defaults\nDEFAULT_ENVIRONMENT_TYPE = StaticLattice\nDEFAULT_LIGAND_ID = 'glc__D_e' # BiGG id for external glucose\nDEFAULT_BOUNDS = [1000, 3000]\nDEFAULT_AGENT_LOCATION = [0.5, 0.1]\n\n# exponential field parameters\nFIELD_SCALE = 4.0\nEXPONENTIAL_BASE = 1.3e2\nFIELD_CENTER = [0.5, 0.0]\n\n# get initial ligand concentration based on location\nLOC_DX = (DEFAULT_AGENT_LOCATION[0] - FIELD_CENTER[0]) * DEFAULT_BOUNDS[0]\nLOC_DY = (DEFAULT_AGENT_LOCATION[1] - FIELD_CENTER[1]) * DEFAULT_BOUNDS[1]\nDIST = np.sqrt(LOC_DX ** 2 + LOC_DY ** 2)\nINITIAL_LIGAND = FIELD_SCALE * EXPONENTIAL_BASE ** (DIST / 1000)\n\n\ndef get_exponential_env_config():\n # multibody process config\n multibody_config = {\n 'bounds': DEFAULT_BOUNDS}\n\n # static field config\n field_config = {\n 'molecules': [DEFAULT_LIGAND_ID],\n 'gradient': {\n 'type': 'exponential',\n 'molecules': {\n DEFAULT_LIGAND_ID: {\n 'center': FIELD_CENTER,\n 'scale': FIELD_SCALE,\n 'base': EXPONENTIAL_BASE}}},\n 'bounds': DEFAULT_BOUNDS}\n\n return {\n 'multibody': multibody_config,\n 'field': field_config}\n\ndef get_linear_env_config():\n # field parameters\n slope = 1.0\n base = 1e-1\n field_center = [0.5, 0.0]\n\n # multibody process config\n multibody_config = {\n 'animate': False,\n 'bounds': DEFAULT_BOUNDS}\n\n # static field config\n field_config = {\n 'molecules': [DEFAULT_LIGAND_ID],\n 'gradient': {\n 'type': 'linear',\n 'molecules': {\n DEFAULT_LIGAND_ID: {\n 'base': base,\n 'center': field_center,\n 'slope': slope,\n }\n }\n },\n 'bounds': DEFAULT_BOUNDS}\n\n return {\n 'multibody': multibody_config,\n 'field': field_config}\n\nDEFAULT_ENVIRONMENT_CONFIG = {\n 'type': DEFAULT_ENVIRONMENT_TYPE,\n 'config': get_exponential_env_config()}\n\nDEFAULT_AGENT_CONFIG = {\n 'ligand_id': DEFAULT_LIGAND_ID,\n 'initial_ligand': INITIAL_LIGAND,\n 'external_path': ('global',),\n 'agents_path': ('..', '..', 'agents'),\n 'daughter_path': tuple()}\n\ndef set_environment_config(config={}):\n # override default environment config\n return deep_merge(dict(DEFAULT_ENVIRONMENT_CONFIG), config)\n\ndef set_agent_config(config={}):\n # override default agent config\n return deep_merge(dict(DEFAULT_AGENT_CONFIG), config)\n\n\n# configs with faster timescales, to support close agent/environment coupling\nFAST_TIMESCALE = 0.001\ntumble_jitter = 4000\n# fast timescale minimal agents\nFAST_MOTOR_CONFIG = set_agent_config({\n 'tumble_jitter': tumble_jitter,\n 'time_step': FAST_TIMESCALE})\nFAST_MINIMAL_CHEMOTAXIS_CONFIG = set_agent_config({\n 'receptor': {\n 'time_step': FAST_TIMESCALE},\n 'motor': {\n 'tumble_jitter': tumble_jitter,\n 'time_step': FAST_TIMESCALE}})\n\n# fast timescale environment\nFAST_TIMESCALE_ENVIRONMENT_CONFIG = set_environment_config({\n 'config': {\n 'multibody': {'time_step': FAST_TIMESCALE},\n 'field': {'time_step': FAST_TIMESCALE} }})\n\n# agent types\nagents_library = {\n 'motor': {\n 'name': 'motor',\n 'type': MotorActivityAgent,\n 'config': FAST_MOTOR_CONFIG,\n },\n 'minimal': {\n 'name': 'minimal',\n 'type': ChemotaxisMinimal,\n 'config': FAST_MINIMAL_CHEMOTAXIS_CONFIG,\n },\n 'variable': {\n 'name': 'variable',\n 'type': ChemotaxisVariableFlagella,\n 'config': DEFAULT_AGENT_CONFIG\n },\n 'expression': {\n 'name': 'expression',\n 'type': ChemotaxisExpressionFlagella,\n 'config': DEFAULT_AGENT_CONFIG\n },\n 'ode': {\n 'name': 'ode_expression',\n 'type': ChemotaxisODEExpressionFlagella,\n 'config': DEFAULT_AGENT_CONFIG\n }\n}\n\n# preset experimental configurations\npreset_experiments = {\n 'minimal': {\n 'agents_config': [\n {\n 'number': 6,\n 'name': 'minimal',\n 'type': ChemotaxisMinimal,\n 'config': DEFAULT_AGENT_CONFIG,\n }\n ],\n 'environment_config': DEFAULT_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 30,\n 'emit_step': 0.1,\n },\n },\n 'ode': {\n 'agents_config': [\n {\n 'number': 1,\n 'name': 'ode_expression',\n 'type': ChemotaxisODEExpressionFlagella,\n # 'config': DEFAULT_AGENT_CONFIG,\n 'config': deep_merge(\n dict(DEFAULT_AGENT_CONFIG),\n {'growth_rate': 0.0005}) # fast growth\n }\n ],\n 'environment_config': DEFAULT_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 50,\n 'emit_step': 1.0,\n },\n },\n 'master': {\n 'agents_config': [\n {\n 'number': 1,\n 'name': 'master',\n 'type': ChemotaxisMaster,\n 'config': DEFAULT_AGENT_CONFIG\n }\n ],\n 'environment_config': DEFAULT_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 30,\n 'emit_step': 0.1,\n },\n },\n 'variable': {\n 'agents_config': [\n {\n 'number': 1,\n 'name': '{}_flagella'.format(n_flagella),\n 'type': ChemotaxisVariableFlagella,\n 'config': set_agent_config({'n_flagella': n_flagella})\n }\n for n_flagella in [0, 3, 6, 9, 12]\n ],\n 'environment_config': DEFAULT_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 720,\n 'emit_step': 0.1,\n },\n },\n 'motor': {\n 'agents_config': [\n {\n 'type': MotorActivityAgent,\n 'name': 'motor',\n 'number': 1,\n 'config': FAST_MOTOR_CONFIG,\n }\n ],\n 'environment_config': FAST_TIMESCALE_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 120,\n 'emit_step': FAST_TIMESCALE,\n },\n },\n 'fast_minimal': {\n 'agents_config': [\n {\n 'number': 1,\n 'name': 'motor + receptor',\n 'type': ChemotaxisMinimal,\n 'config': FAST_MINIMAL_CHEMOTAXIS_CONFIG,\n }\n ],\n 'environment_config': FAST_TIMESCALE_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 60,\n 'emit_step': FAST_TIMESCALE,\n },\n },\n 'mixed': {\n 'agents_config': [\n {\n 'type': ChemotaxisMinimal,\n 'name': 'motor + receptor',\n 'number': 1,\n 'config': FAST_MINIMAL_CHEMOTAXIS_CONFIG,\n },\n {\n 'type': MotorActivityAgent,\n 'name': 'motor',\n 'number': 1,\n 'config': FAST_MOTOR_CONFIG,\n }\n ],\n 'environment_config': FAST_TIMESCALE_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 300,\n 'emit_step': FAST_TIMESCALE,\n },\n },\n 'many_mixed': {\n 'agents_config': [\n {\n 'type': MotorActivityAgent,\n 'name': 'motor',\n 'number': 5,\n 'config': FAST_MOTOR_CONFIG,\n },\n {\n 'type': ChemotaxisMinimal,\n 'name': 'motor + receptor',\n 'number': 5,\n 'config': FAST_MINIMAL_CHEMOTAXIS_CONFIG,\n },\n ],\n 'environment_config': FAST_TIMESCALE_ENVIRONMENT_CONFIG,\n 'simulation_settings': {\n 'total_time': 300,\n 'emit_step': FAST_TIMESCALE*10,\n },\n },\n}\n\n\ndef run_chemotaxis_experiment(\n agents_config=None,\n environment_config=None,\n initial_state=None,\n simulation_settings=None,\n experiment_settings=None):\n\n if not initial_state:\n initial_state = {}\n if not experiment_settings:\n experiment_settings = {}\n\n total_time = simulation_settings['total_time']\n emit_step = simulation_settings['emit_step']\n\n # agents ids\n agent_ids = []\n for config in agents_config:\n number = config['number']\n if 'name' in config:\n name = config['name']\n if number > 1:\n new_agent_ids = [name + '_' + str(num) for num in range(number)]\n else:\n new_agent_ids = [name]\n else:\n new_agent_ids = [str(uuid.uuid1()) for num in range(number)]\n config['ids'] = new_agent_ids\n agent_ids.extend(new_agent_ids)\n\n initial_agent_body = agent_body_config({\n 'bounds': DEFAULT_BOUNDS,\n 'agent_ids': agent_ids,\n 'location': DEFAULT_AGENT_LOCATION})\n initial_state.update(initial_agent_body)\n\n # make the experiment\n experiment = agent_environment_experiment(\n agents_config,\n environment_config,\n initial_state,\n experiment_settings)\n\n # simulate\n settings = {\n 'total_time': total_time,\n 'emit_step': emit_step,\n 'return_raw_data': True}\n return simulate_experiment(experiment, settings)\n\n\n# plotting\ndef plot_chemotaxis_experiment(\n data,\n field_config,\n out_dir,\n filename=''):\n\n # multigen agents plot\n plot_settings = {\n 'agents_key': 'agents',\n 'max_rows': 30,\n 'skip_paths': [\n ('boundary', 'mass'),\n ('boundary', 'length'),\n ('boundary', 'width'),\n ('boundary', 'location'),\n ]}\n plot_agents_multigen(data, plot_settings, out_dir, 'agents')\n\n # trajectory and motility\n indexed_timeseries = time_indexed_timeseries_from_data(data)\n field = make_field(field_config)\n trajectory_config = {\n 'bounds': field_config['bounds'],\n 'field': field,\n 'rotate_90': True}\n\n plot_temporal_trajectory(copy.deepcopy(indexed_timeseries), trajectory_config, out_dir, filename + 'temporal')\n plot_agent_trajectory(copy.deepcopy(indexed_timeseries), trajectory_config, out_dir, filename + 'trajectory')\n\n embdedded_timeseries = timeseries_from_data(data)\n plot_motility(embdedded_timeseries, out_dir, filename + 'motility_analysis')\n\n\n# parsing expression grammar for agents\ndef agent_type(): return RegExMatch(r'[a-zA-Z0-9.\\-\\_]+')\ndef number(): return RegExMatch(r'[0-9]+')\ndef specification(): return agent_type, number\ndef rule(): return OneOrMore(specification)\nagent_parser = ParserPython(rule)\n\ndef make_agent_config(agent_specs):\n agent_type = agent_specs[0].value\n number = int(agent_specs[1].value)\n config = agents_library[agent_type]\n config['number'] = number\n return config\n\ndef parse_agents_string(agents_string):\n all_agents = agent_parser.parse(agents_string)\n agents_config = []\n for idx, agent_specs in enumerate(all_agents):\n agents_config.append(make_agent_config(agent_specs))\n return agents_config\n\ndef make_dir(out_dir):\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\ndef add_arguments():\n parser = argparse.ArgumentParser(description='chemotaxis control')\n parser.add_argument(\n '--agents', '-a',\n type=str,\n nargs='+',\n default='\"minimal 1\"',\n help='A list of agent types and numbers in the format \"agent_type1 number1 agent_type2 number2\"')\n parser.add_argument(\n '--environment', '-v',\n type=str,\n default='exponential',\n help='the environment type (\"linear\" or \"exponential\")')\n parser.add_argument(\n '--time', '-t',\n type=int,\n default=10,\n help='total simulation time, in seconds')\n parser.add_argument(\n '--emit', '-m',\n type=int,\n default=1,\n help='emit interval, in seconds')\n parser.add_argument(\n '--experiment', '-e',\n type=str,\n default=None,\n help='preconfigured experiments')\n return parser.parse_args()\n\n\ndef run_chemotaxis_simulation():\n \"\"\"\n Execute a chemotaxis simulation with any number of chemotactic agent types\n \"\"\"\n out_dir = os.path.join(EXPERIMENT_OUT_DIR, 'chemotaxis')\n make_dir(out_dir)\n\n args = add_arguments()\n\n if args.experiment:\n # get a preset experiment\n # make a directory for this experiment\n experiment_name = str(args.experiment)\n control_out_dir = os.path.join(out_dir, experiment_name)\n make_dir(control_out_dir)\n\n experiment_config = preset_experiments[experiment_name]\n agents_config = experiment_config['agents_config']\n environment_config = experiment_config['environment_config']\n simulation_settings = experiment_config['simulation_settings']\n\n else:\n # make a directory for this experiment\n experiment_name = '_'.join(args.agents)\n control_out_dir = os.path.join(out_dir, experiment_name)\n make_dir(control_out_dir)\n\n # configure the agents\n agents_config = []\n if args.agents:\n agents_string = ' '.join(args.agents)\n agents_config = parse_agents_string(agents_string)\n\n # configure the environment\n if args.environment == 'linear':\n env_config = get_linear_env_config()\n else:\n env_config = get_exponential_env_config()\n environment_config = {\n 'type': DEFAULT_ENVIRONMENT_TYPE,\n 'config': env_config,\n }\n\n # configure the simulation\n total_time = args.time\n emit_step = args.emit\n simulation_settings = {\n 'total_time': total_time,\n 'emit_step': emit_step,\n }\n\n # simulate\n data = run_chemotaxis_experiment(\n agents_config=agents_config,\n environment_config=environment_config,\n simulation_settings=simulation_settings,\n )\n\n # plot\n field_config = environment_config['config']['field']\n plot_chemotaxis_experiment(data, field_config, control_out_dir)\n\n\nif __name__ == '__main__':\n run_chemotaxis_simulation()\n","sub_path":"vivarium/experiments/chemotaxis.py","file_name":"chemotaxis.py","file_ext":"py","file_size_in_byte":16086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"450891402","text":"import layer as ly\nimport funcs as funcs\nimport numpy as np\n\n\nclass Network:\n def __init__(self, features_in, layer_sizes,\n f=funcs.ReLU, out=funcs.Softmax):\n self.layers = [ly.Layer(features_in,\n layer_sizes[0], f)]\n\n for i in range(1, len(layer_sizes)):\n self.layers.append(ly.Layer(layer_sizes[i - 1],\n layer_sizes[i], f))\n self.layers[len(layer_sizes) - 1].func = out\n\n def fprop(self, x, fprop_cache):\n vec = x\n\n for layer in self.layers:\n vec = layer.fprop(vec, fprop_cache)\n\n return vec\n\n def bprop(self, y, yTarget, fprop_cache, bprop_cache):\n\n # need to have the first derivative NLL based\n dEdy = y - yTarget\n\n layers = len(self.layers)\n for i in reversed(range(1, layers)):\n dEdy = self.layers[i].bprop(dEdy, fprop_cache, bprop_cache)\n\n # save up computation of dEdy in last layer\n self.layers[0].bprop(dEdy, fprop_cache, bprop_cache, has_next=False)\n\n def update(self, bprop_cache, eta):\n for layer in self.layers:\n layer.update(bprop_cache, eta)\n\n def copy(self):\n res = Network(1, [1])\n res.layers = []\n for layer in self.layers:\n res.layers.append(layer.copy())\n return res\n\n\ndef classify(vec):\n return np.argmax(vec)\n\n\ndef class_to_vector(cls, num_classes):\n v = np.zeros(num_classes)\n v[cls] = 1\n return v\n","sub_path":"ex3/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"636163236","text":"from casadi import *\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pdb\nimport os\nimport pdb\nimport xlsxwriter\n\nfrom sird_coupling import *\nfrom rk4 import *\nstart = 23 # weeek number\n# 13 Aprtil, 18 May, 23 June , 28 July, 31 August, 24 September\nmonth = \"August\"\n# start = 13\n# start = 30alpha_re\nN = 10\n\nweeks_num = [13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37]\nweeks_name = [\"March\", \"April\", \"April\", \"April\", \"April\", \"May\", \"May\", \"May\", \"May\", \"May\", \"June\",\"June\",\"June\",\"June\",\n \"July\", \"July\", \"July\", \"July\", \"August\", \"August\", \"August\", \"August\",\"August\", \"September\" , \"September\"]\n\nworkbook = xlsxwriter.Workbook('solution_casadi'+str(start)+'week' +str(N)+'_N.xlsx')\nworksheet = workbook.add_worksheet()\n\nnx = 4\nnu = 3\n\npop_germany_total = 83905306\n\nsymbol = SX.sym\n\n# Controls and Parameters\nbeta = symbol('beta',(9,9))\ngamma = symbol('gamma',(1,9))\nmu = symbol('mu',(1,9))\n\nu = vertcat(beta)\nparams = vertcat(gamma, mu)\nos.chdir('../')\nos.chdir('../')\n\n\n# df2 = pd.read_excel(os.getcwd() + '/code/data/data_germany/weekly_active_infections_age_gender_ger.xlsx')\n# df3 = pd.read_excel(os.getcwd() + '/code/data/data_germany/weekly_cumulatice_infected_male.xlsx')\n# df4 = pd.read_excel(os.getcwd() + '/code/data/data_germany/dead.xlsx')\n# df5 = pd.read_excel(os.getcwd() + '/code/data/data_germany/weekly_cumulatice_infected_female.xlsx')\n# df6 = pd.read_excel(os.getcwd() + '/code/data/data_germany/weekly_cumulatice_infected_diverse.xlsx')\n\ndf7 = pd.read_excel(os.getcwd() + '/sysidentification/data/male_IRD.xlsx')\ndf8 = pd.read_excel(os.getcwd() + '/sysidentification/data/age_groups_pop_germany.xlsx')\n\n\n#############################################################################\n# MALE\n#############################################################################\n\nos.chdir(os.getcwd() + '/sysidentification/coupling/results')\n\n#####\n# Age Group 0-9\n\n# Age Group Value of d\n# 0-9 0\n# 10-19 1\n# 20-29 2\n# 30-39 3\n# 40-49 4\n# 50-59 5\n# 60-69 6\n# 70-79 7\n# 80+ 8\n\n# N = 15 # weeks WORKIGN\n\n\n# problem with 4, 7, 8\n\nmale_active2 = df7.iloc[82:82+9, start:start + N]\nmale_active2 = male_active2.to_numpy()\nmale_recovered2 = df7.iloc[110:110+9, start:start + N]\nmale_recovered2 = male_recovered2.to_numpy()\nmale_dead2 = df7.iloc[95:95+9, start:start + N]\nmale_dead2 = male_dead2.to_numpy()\n\nmale_pop_ger_age = df8.iloc[0:9, 7]\nmale_pop_ger_age = male_pop_ger_age.to_numpy()\n\n\nactive_age = male_active2\ndead_age = male_dead2\nrecovered_age = male_recovered2\nsusceptible_age = np.ones(np.shape(dead_age))\n\npop = male_pop_ger_age\n\nfor i in range(np.shape(dead_age)[0]):\n for j in range(np.shape(dead_age)[1]):\n susceptible_age[i][j] = pop[i] - (active_age[i][j] + dead_age[i][j] + recovered_age[i][j])\n\n\nfinal_data = np.ones((36,N))\n\nfor i in range(0,9):\n for j in range(N):\n final_data[i][j] = susceptible_age[i][j]\n final_data[i+9][j] = active_age[i][j]\n final_data[i+18][j] = recovered_age[i][j]\n final_data[i+27][j] = dead_age[i][j]\n\n\n\nfor i in range(np.shape(dead_age)[0]):\n for j in range(np.shape(dead_age)[1]):\n if (dead_age[i][j] < 0):\n print(\"found less than zero\")\n\n if (recovered_age[i][j] < 0):\n print(\"found less than zero\")\n\n if (susceptible_age[i][j] < 0):\n print(\"found less than zero\")\n\n if (active_age[i][j] < 0):\n print(\"found less than zero\")\n\n\n############ MODELING #####################\nS = symbol('S',(9,1))\nI = symbol('I',(9,1))\nR = symbol('R',(9,1))\nD = symbol('D',(9,1))\n\nstates = vertcat(S,I,R,D)\n\ncontrols = u\n\n\ndSdt, dIdt, dRdt, dDdt = sird_model_age(states, u ,params)\n\n\nrhs = vertcat(dSdt, dIdt, dRdt, dDdt)\n\n# Form an ode function\node_age = Function('ode_age',[states,controls, params],[rhs])\n\n############ Creating a simulator ##########\nN_steps_per_sample = 1\ndt = 0.1\n\nstates_final_age = rk4_age(ode_age, states, controls, params, dt)\n# # TODO: make function + separate file!\n# # Build an integrator for this system: Runge Kutta 4 integrator\n# k1_age = ode_age(states_ages,controls_age)\n# k2_age = ode_age(states_ages+dt/2.0*k1_age,controls_age)\n# k3_age = ode_age(states_ages+dt/2.0*k2_age,controls_age)\n# k4_age = ode_age(states_ages+dt*k3_age,controls_age)\n#\n# states_final_age = states_ages+dt/6.0*(k1_age+2*k2_age+2*k3_age+k4_age)\n#\n#\none_step_age = Function('one_step_age',[states, controls, params],[states_final_age])\n\nX_age = states\n\nfor i in range(N_steps_per_sample):\n X_age = one_step_age(X_age, controls, params)\n\n\n\n# Create a function that simulates all step propagation on a sample\none_sample_age = Function('one_sample_age',[states, controls, params], [X_age])\n\nprint(one_sample_age)\n############ Simulating the system ##########\n# TODO: double check if map accum can be used\n# all_samples = one_sample.mapaccum(\"all_samples\", N)\n# print(all_samples)\n# x_traj = all_samples(x0, u_time_var)\n\nx_traj = symbol(\"x_traj\", nx*9, N)\nu_time_var = symbol(\"u_time_var\", 9*9, (N-1))\nu_time_var = symbol(\"u_time_var\", 9*9, (N-1))\nu_time_var2 = symbol('x',Sparsity.lower(9))\nfor i in range(np.shape(u_time_var)[1]-1):\n u_time = u_time_var[:,i]\n u_time = reshape(u_time, 9,9)\n for i in range(np.shape(u_time)[0]):\n for j in range(np.shape(u_time)[1]):\n u_time[i,j] = u_time[j,i]\n\ninfected_init_age = np.ones((9,1))\nfor i in range(len(infected_init_age)):\n infected_init_age[i] = active_age[i][0]\n\ndead_init_age = np.ones((9,1))\nfor i in range(len(dead_init_age)):\n dead_init_age[i] = dead_age[i][0]\n\nrecovered_init_age = np.ones((9,1))\nfor i in range(len(recovered_init_age)):\n recovered_init_age[i] = recovered_age[i][0]\n\nx0 = np.ones((9*4,1))\n\n\n\nfor i in range(len(dead_init_age)):\n x0[i] = pop[i] - infected_init_age[i] - dead_init_age[i] - recovered_init_age[i]\n x0[i+9] = infected_init_age[i]\n x0[i+18] = recovered_init_age[i]\n x0[i+27] = dead_init_age[i]\n\nxcurrent = x0\nx_traj[:, 0] = x0\n\nfor i in range(N-1):\n current_control = u_time_var[:,i]\n current_control_t = reshape(current_control,9,9)\n xcurrent= one_sample_age(xcurrent, current_control_t,params)\n x_traj[:, i+1] = xcurrent\n\n\ny_sym = x_traj\n\n\nmodel_mismatch = final_data - y_sym\n\nmodel_ird = y_sym[9:36,:]\nreal_ird = final_data[9:36,:]\n\nmodel_mismatch_ird = model_ird - real_ird\n\nu_test = reshape(u_time_var,-1,1)\n\nu_test = vertcat(u_test, gamma.T, mu.T)\npdb.set_trace()\nlbg_age = np.zeros(np.shape(u_test))\nubg_age = np.ones(np.shape(u_test))*1000000\n\nlbg_sigma = np.zeros((N-2)*9)\nlbg_mu = np.zeros((N-2)*9)\n\nubg_sigma = np.zeros((N-2)*9)\nubg_mu = np.zeros((N-2)*9)\n\nlbg_all = vertcat(lbg_age, )\nubg_all = vertcat(ubg_age, ubg_sigma , ubg_mu)\n\ng_age = u_test\n\ng_all = vertcat(g_age)\n\n\nall_betas = u_test[0:9*9*(N-1)]\nreg = symbol('reg', 9*9)\nalpha_reg = 1e17\nfor i in range(N-2):\n betas = all_betas[i*81:i*81+81]\n betas_next = all_betas[(i+1)*81:(i+1)*81+81]\n for j in range(np.shape(betas)[0]):\n reg[j] = betas[j] - betas_next[j]\n\nnlp_age = {'x':u_test, 'f':dot(model_mismatch, model_mismatch) + alpha_reg*dot(reg,reg),'g':g_age}\n\nsolver_age = nlpsol(\"solver\", \"ipopt\", nlp_age) # DM(1.95599)\n\nu_guess_age = np.ones(np.shape(u_test))\nsol_age = solver_age(x0=u_guess_age,lbg=lbg_age, ubg=ubg_age)\n##################################################################################\n\nprint(\"working till here\")\nall_params_age = sol_age[\"x\"]\n\nx_solution = DM(nx*9,N)\nxcurrent = x0\n\ndays = N\nx_solution[:, 0] = x0\nsolution_params = sol_age[\"x\"]\nbetas = solution_params[0:9*9*(N-1)]\n\ngamma = solution_params[9*9*(N-1):9*9*(N-1)+9]\nmu = solution_params[9*9*(N-1)+9:9*9*(N-1)+18]\navg_betas = 0\nfor i in range(N-1):\n u_sol = solution_params[i*81:i*81+81]\n avg_betas += reshape(u_sol,(9,9))\n xcurrent = one_sample_age(xcurrent, reshape(u_sol,(9,9)), vertcat(gamma.T,mu.T))\n x_solution[:, i+1] = xcurrent\n\navg_betas = avg_betas / (N-1)\nmax_abs = np.max(np.abs(avg_betas.full()))\nplt.imshow(avg_betas, cmap='RdBu', vmin=-max_abs, vmax=max_abs)\nplt.colorbar()\nplt.title(\"Average Transmission Rate August\")\nplt.xlabel(\"Age Groups\")\nplt.ylabel(\"Age Groups\")\nos.chdir('../')\nos.chdir('../')\n\nplt.savefig(os.getcwd() + \"/figures/coupling/\" + str(month)+ \"_avg_betas.pdf\")\n\nall_S_ages = x_solution[0:9,:]\nall_I_ages = x_solution[9:18,:]\nall_R_ages = x_solution[18:27,:]\nall_D_ages = x_solution[27:36,:]\n\nsol_array = x_solution.toarray()\nparam_array = sol_age['x'].toarray()\nparam_array = np.transpose(param_array)\n\nrow = 2\n\narray = np.transpose(sol_array)\nfor col, data in enumerate(array):\n worksheet.write_column(row, col, data)\n\nworksheet = workbook.add_worksheet()\n\nfor col, data in enumerate(param_array):\n worksheet.write_column(row, col, data)\n\npdb.set_trace()\nworkbook.close()\nplt.show()\npdb.set_trace()\n\n","sub_path":"sysidentification/coupling/new_coupling/coupling_germany.py","file_name":"coupling_germany.py","file_ext":"py","file_size_in_byte":8935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"85684246","text":"\"\"\"\nThis script is used to start-measurements and/or to stop-export-measurement-data from the NTIXL2 device.\nThis script has to be run on the raspberry pi which is serial connected with the NTIXL2.\n\"\"\"\nimport os,shutil,sys\nimport argparse\nfrom pathlib import Path\nimport subprocess\nimport time\nfrom datetime import datetime\nimport logging\nimport logging.handlers\n\nfrom ntixl2.xl2 import XL2SLM, XL2Error\nfrom ntixl2.message import *\n\nfrom global_settings import stop_save_run_log_path, stop_save_run_debug_log_path, formatter, mail_handler,\\\n stream_handler, xl2_log_relpath, rpi_log_data_path, xl2_log_path, xl2_mount_dir\n\nlogger = logging.getLogger(\"stop_save_run\")\nlogger.setLevel(logging.DEBUG)\n\nstop_save_run_handler = logging.FileHandler(filename=str(stop_save_run_log_path))\nstop_save_run_handler.setFormatter(formatter)\nstop_save_run_handler.setLevel(logging.INFO)\n\nstop_save_run_debug_handler = logging.handlers.RotatingFileHandler(filename=str(stop_save_run_debug_log_path),\n maxBytes= 1000e3)\nstop_save_run_debug_handler.setFormatter(formatter)\nstop_save_run_debug_handler.setLevel(logging.DEBUG)\n\nlogger.addHandler(mail_handler)\nlogger.addHandler(stop_save_run_debug_handler)\nlogger.addHandler(stop_save_run_handler)\nlogger.addHandler(stream_handler)\n\ndef mass_connected(path):\n \"\"\" return true if /media/XL2-sd/Projects/{db_Name} is on the system tree\"\"\"\n pipe = subprocess.Popen(\"if [ -d {} ]; then echo 'true'; else echo 'false'; fi\".format(path),\n stdout=subprocess.PIPE, shell=True)\n found = 'true' in pipe.communicate()[0].decode()\n return found\n\n# def xl2_sd_full(xl2, max_memory_usage = 0.1):\n# memory_usage = xl2.memory_usage()\n# return memory_usage.used/memory_usage.total > max_memory_usage\n#\n#\n# def delete_wav_on_sd_card(xl2, xl2_wav_path, max_memory_usage):\n# \"\"\"delete old wav until storage requirements fulfilled\"\"\"\n# wav_list = [p for p in xl2_wav_path.glob('*.wav') if p.is_file()]\n# wav_list.sort(key =lambda x: datetime.fromtimestamp(os.path.getmtime(x.as_posix())))\n# for wav_path in wav_list:\n# if xl2_sd_full(xl2, max_memory_usage):\n# logger.debug('delete {}'.format(str(wav_path)))\n# os.remove(wav_path.as_posix())\n# else:\n# break\n\ndef reset_ykush():\n os.system(\"sudo /home/pi-rbl/YKUSH_V1.4.1/ykush -d a\")\n time.sleep(5)\n os.system(\"sudo /home/pi-rbl/YKUSH_V1.4.1/ykush -u a\")\n time.sleep(5)\n\ndef xl2_to_serial_status(xl2):\n n = 0\n logger.debug(\"Make sure device is in serial mode\")\n while xl2.device_status != 'SERIAL':\n if n == 0:\n logger.debug(\"first loop; device not in serial mode, run 'to_serial()' method.\")\n xl2.to_serial()\n time.sleep(30)\n if n > 10:\n logger.error(\"Xl2 not in serial mode. Time limit reached by putting xl2 in serial mode.\")\n raise Exception('Xl2 not in serial mode')\n time.sleep(6)\n n += 1\n else:\n logger.debug(\"XL2 in serial mode\")\n time.sleep(10)\n\n\ndef check_errors(xl2):\n logger.debug(\"Check for errors\")\n try:\n err = xl2.check_errors()\n except XL2Error:\n logger.error('check_errors failed')\n else:\n logger.debug('check_errors report: {}'.format(err))\n time.sleep(5)\n\ndef start_measurement(xl2,profile):\n i = 0\n while xl2.device_status != 'SERIAL':\n if i > 10:\n logger.error(\"Xl2 not in serial mode. Time limit reached by putting xl2 in serial mode.\")\n raise Exception('Xl2 not in serial mode')\n time.sleep(6)\n i += 1\n else:\n logger.debug(\"XL2 in SERIAL mode\")\n time.sleep(10)\n\n check_errors(xl2)\n\n # select profile\n logger.debug(\"select profile.\")\n xl2.select_profile(profile=profile)\n time.sleep(30)\n logger.debug(\"Start measurement.\")\n try:\n xl2.serial_message(INITIATE.START())\n time.sleep(30)\n state = xl2.serial_message(QUERY_INITIATE_STATE())['state']\n except Exception as e:\n check_errors(xl2)\n raise e\n else:\n if state == 'RUNNING':\n logger.debug(\"Measurement INITIATE status is {}, measurement restarted succesful\".format(state))\n return True\n else:\n logger.error(\"Measurement INITIATE status is {}, not able to restart measurement\".format(state))\n raise Exception('Not able to restart measurement')\n\ndef copy_and_delete_logs(xl2, xl2_proj_relpath, to_path, events_wav = False):\n \"\"\"copy_and_delete_logs files from xl2_proj_path to to_path \"\"\"\n\n file_to_save = xl2.list_files(str(xl2_proj_relpath), '*_Log.txt')\n\n if len(file_to_save):\n dir_name = datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n path_new_dir = to_path.joinpath(dir_name)\n logger.debug(\"Create new directory. Log save path: {}\".format(str(path_new_dir)))\n try:\n path_new_dir.mkdir(parents=True)\n except FileExistsError:\n logger.debug(\"Log save path {} already exists\".format(str(path_new_dir)))\n\n logger.debug(\"copy xl2 measurement log files\")\n for file in file_to_save:\n try:\n shutil.copy(file, str(path_new_dir.joinpath(Path(file).name)))\n except:\n logger.error(\"error by copying {} file.\".format(file))\n else:\n logger.debug(\"File {} copied .\".format(file))\n try:\n os.remove(file)\n except:\n logger.error(\"error by deleting {} file.\".format(file))\n else:\n logger.debug(\"File {} deleted .\".format(file))\n if events_wav:\n logger.debug(\"Save wav events\")\n event_dir_list = xl2.list_dir(str(xl2_proj_relpath), '*AudioEvent*')\n #logger.debug(str(event_dir_list) )\n\n for event_dir in event_dir_list:\n try:\n shutil.copytree(event_dir, str(path_new_dir.joinpath(Path(event_dir).name)))\n except:\n logger.error(\"error by copying {} event directory.\".format(event_dir))\n else:\n logger.debug(\"event directory {} copied .\".format(event_dir))\n try:\n subprocess.Popen([\"sudo rm -r {}\".format(event_dir)], shell=True).wait()\n except:\n logger.error(\"error by deleting {} event directory.\".format(event_dir))\n else:\n logger.debug(\"event directory {} deleted.\".format(event_dir))\n else:\n logging.warning('No LOG to save')\n\n logger.debug(\"Delete files\")\n for file in xl2.list_files(xl2_proj_relpath, '*.txt')+ xl2.list_files(xl2_proj_relpath, '*.XL2'):\n try:\n os.remove(file)\n except:\n logger.error(\"error by deleting {} file.\".format(file))\n else:\n logger.debug(\"File {} deleted.\".format(file))\n\ndef stop_and_export(xl2):\n \"\"\"The routine which stops a measurement, reads out logs and soundsamples, deletes files, and restarts measurement\"\"\"\n try:\n state = xl2.serial_message(QUERY_INITIATE_STATE())['state']\n except Exception as e:\n check_errors(xl2)\n raise e\n\n logger.debug(\"Measurement INITIATE status is {}\".format(state))\n if state == 'RUNNING':\n logger.debug(\"STOP MEASUREMENT\")\n xl2.serial_message(INITIATE.STOP())\n time.sleep(3)\n m = SYSTEM_KEY()\n m.append_param('ENTER')\n xl2.serial_message(m)\n elif state == \"STOPPED\":\n logger.warning(\"No measurement was running\")\n else:\n logger.warning(\"unknow state {}\".format(state))\n\n time.sleep(2)\n\n logger.debug(\"Switch xl2 to MASS mode. Run 'to_mass()' method.\")\n xl2.to_mass()\n time.sleep(30)\n\n i=0\n logger.debug('Make sure xl2 is in MASS modus, first test')\n while xl2.device_status != 'MASS':\n if i >20:\n logger.error(\"Xl2 not in MASS mode. Time limit reached by putting xl2 in MASS mode in first test.\")\n raise Exception('Xl2 not in MASS mode, first test')\n time.sleep(6)\n i += 1\n else:\n logger.debug(\"XL2 in MASS mode, passed first test.\")\n\n i=0\n logger.debug('Make sure xl2 is in MASS modus, second test')\n while not mass_connected(xl2_log_path):\n if i >10:\n logger.error(\"Xl2 not in MASS mode. Time limit reached by putting xl2 in MASS mode in second test.\")\n raise Exception('Xl2 not in MASS mode, second test')\n time.sleep(6)\n i += 1\n else:\n logger.debug(\"XL2 in MASS mode, passed second test.\")\n\n logger.debug(\"run 'copy_and_delete_logs()'\")\n copy_and_delete_logs(xl2, xl2_log_relpath, rpi_log_data_path, events_wav=True)\n\n #logger.debug(\"remove old wav; run 'delete_wav_on_sd_card()'\")\n #delete_wav_on_sd_card(xl2, xl2_log_path, max_xl2sd_usage)\n #logger.debug(\"Switch back xl2 to SERIAL mode. Run 'to_serial()' method.\")\n #xl2.to_serial()\n #time.sleep(30)\n\n\n\n####\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--stop\", action=\"store_true\",\n help=\"stop measurement and export data\")\n parser.add_argument(\"--start\", action=\"store_true\",\n help=\"start measurement\")\n args = parser.parse_args()\n #\n stop_and_export_done = not args.stop\n start_done = not args.start\n\n #########################\n logger.info(\"============================\")\n logger.info(\"Run 'stop_save_run.py' script\")\n logger.debug('delete old directory')\n #try maximal 3 times\n for i in [1,2,3]:\n logger.info('== loop: {}'.format(i))\n ###############\n #connect to Xl2\n ###############\n logger.info('== connect to XL2')\n try:\n xl2 = XL2SLM(mountDir=xl2_mount_dir)\n except XL2Error:\n logger.exception(\"not able to connect to XL2\",exc_info=True)\n logger.debug(\"reset ykush\")\n reset_ykush()\n if i == 3:\n logger.critical(\"failed at connect to XL2 \", exc_info=True)\n break\n else:\n time.sleep(5)\n continue\n\n #ensure serial connection\n logger.debug(\"ensure serial connection\")\n try:\n xl2_to_serial_status(xl2)\n except:\n if i == 3:\n logger.critical(\"failed at serial connect to XL2 \", exc_info=True)\n break\n else:\n time.sleep(5)\n continue\n\n #################\n #stop\n #################\n if stop_and_export_done == False:\n logger.info(\"== execute stop_and_export\")\n try:\n stop_and_export(xl2)\n except Exception as e:\n try:\n xl2.reset()\n except:\n pass\n logger.error(\"stop_and_export failed.\", exc_info=True)\n if i == 3:\n logger.critical(\"failed at stop_and_export \", exc_info=True)\n break\n else:\n time.sleep(5)\n continue\n else:\n logger.info(\"stop_and_export terminated with success\")\n stop_and_export_done= True\n #to serial\n logger.debug(\"back to serial connection\")\n try:\n xl2_to_serial_status(xl2)\n except:\n time.sleep(5)\n continue\n\n ##############\n #Start\n ##############\n if start_done==False:\n logger.info(\"== execute start_measurement\")\n try:\n start_measurement(xl2, profile = 5)\n except Exception as e:\n logger.error(\"start_measurement failed.\", exc_info=True)\n if i == 3:\n logger.critical(\"failed at start measurement\", exc_info=True)\n break\n else:\n time.sleep(5)\n continue\n else:\n logger.info(\"start_measurement terminated with success\")\n start_done = True\n\n #exit loop if success\n if start_done and stop_and_export_done:\n break\n\n #exit script\n if i==3:\n logger.critical(\"stop_save_run failed \")\n sys.exit(1)\n else:\n logger.info(\"=== stop_save_run terminated with success in {} loops.\".format(i))\n sys.exit(0)\n\n\n\n\n","sub_path":"scripts/stop_save_run.py","file_name":"stop_save_run.py","file_ext":"py","file_size_in_byte":12684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"264941270","text":"import numpy as np\nimport pandas as pd\nimport networkx as nx\nimport graphLib as gl\nimport matplotlib.pyplot as plt\nimport csv\nimport random as rd\nimport test_case_graphs as tg\n\n# Written by Alexander Alvarez and Riley Slater\n\n# Set True for graphs\nGRAPHDISPLAY = True\n\n\ndef randomNodeSampling(G, n):\n toRemove = len(G) - n\n for i in range(toRemove):\n G.remove_node(list(G)[rd.randrange(0, len(list(G)))])\n return np.array([[e[0], e[1]] for e in G.edges]).astype(int), \\\n nx.parse_edgelist([str(e[0]) + ' ' + str(e[1]) for e in G.edges])\n\n\n# import csv\nwith open('twitch_eng.csv', newline='') as csvfile:\n edges = np.array(list(csv.reader(csvfile))).astype(int)\n formattedEdgelist = [str(e[0]) + ' ' + str(e[1]) for e in edges]\n G = nx.parse_edgelist(formattedEdgelist, nodetype=int)\n sampledEdges, G = randomNodeSampling(G, 2000)\n\n\nif GRAPHDISPLAY:\n plt.figure(figsize=(7, 7))\n deg = dict(nx.degree(G))\n betw = nx.betweenness_centrality(G)\n nx.draw_spring(G, nodelist=deg.keys(), node_color=[v for v in deg.values()],\n node_size=[v * 2000 for v in betw.values()])\n plt.show()\n\n\ntopNodesDeg = \"\"\nbyDeg = sorted(G.degree, key=lambda x: x[1], reverse=True)\nfor n in byDeg[:10]:\n if n[0] == byDeg[9][0]:\n topNodesDeg += n[0] + \".\"\n else:\n topNodesDeg += n[0] + \", \"\nprint(\"The 10 nodes with the highest degrees are\", topNodesDeg + \"\\n\")\n\n\ntopNodesBet = \"\"\nbyBet = sorted(nx.betweenness_centrality(G).items(), key=lambda x: x[1], reverse=True)\nfor n in byBet[:10]:\n if n[0] == byBet[9][0]:\n topNodesBet += \"and \" + n[0] + \".\"\n else:\n topNodesBet += n[0] + \", \"\nprint(\"The 10 nodes with the highest betweenness centrality are\", topNodesBet + \"\\n\")\n\n\ntopNodesClust = \"\"\n\ndupe = {v : k for k, v in nx.clustering(G).items()}\nfixDict = {v : k for k, v in dupe.items()}\n \nbyClust = sorted(fixDict.items(), key=lambda x: x[1], reverse=True)\nfor n in byClust[:10]:\n if n[0] == byClust[9][0]:\n topNodesClust += \"and \" + n[0] + \".\"\n else:\n topNodesClust += n[0] + \", \"\nprint(\"The 10 nodes with the highest clustering coefficiency are\", topNodesClust + \"\\n\")\n\n\ntopNodesEig = \"\"\nbyEig = sorted(nx.eigenvector_centrality(G).items(), key=lambda x: x[1], reverse=True)\nfor n in byEig[:10]:\n if n[0] == byEig[9][0]:\n topNodesEig += \"and \" + n[0] + \".\"\n else:\n topNodesEig += n[0] + \", \"\nprint(\"The 10 nodes with the highest eigenvector centrality are\", topNodesEig + \"\\n\")\n\n\ntopNodesPage = \"\"\nbyPage = sorted(nx.pagerank(G).items(), key=lambda x: x[1], reverse=True)\nfor n in byPage[:10]:\n if n[0] == byPage[9][0]:\n topNodesPage += \"and \" + n[0] + \".\"\n else:\n topNodesPage += n[0] + \", \"\nprint(\"The 10 nodes with the highest pagerank are\", topNodesPage + \"\\n\")\n\n\nprint(\"Average shortest path length of\", gl.avgShortPathLength(sampledEdges), \"\\n\")\n\n\nif GRAPHDISPLAY:\n degDict = dict(nx.degree(G))\n degVals = degDict.values()\n uni, c = np.unique(list(degVals), return_counts=True)\n plt.scatter(uni, c)\n plt.xscale(\"log\", base=2)\n plt.yscale(\"log\", base=2)\n plt.xlabel(\"log(degree)\")\n plt.ylabel(\"log(frequency)\")\n plt.show()\n\n\n","sub_path":"Project 2/twitchFriends.py","file_name":"twitchFriends.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"558188925","text":"__author__ = 'Pragash'\n\n\n#!/usr/bin/python\n\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\nfrom scipy.interpolate import spline\n\n# Local variables\nx = []\ny = []\n\n# Open the data file for reading lines\ndatafile = open('testdata1.txt', 'r')\nsepfile = datafile.read().split('\\n')\ndatafile.close()\n\n# Create a canvas to place the subgraphs\ncanvas = plt.figure()\nrect = canvas.patch\nrect.set_facecolor('white')\n\n# Iterate through the lines and parse them\nfor datapair in sepfile:\n if datapair:\n xypair = datapair.split(' ')\n x.append(int(xypair[1]))\n y.append(int(xypair[3]))\n\nx_sm = np.array(x)\ny_sm = np.array(y)\n\nx_smooth = np.linspace(x_sm.min(), x_sm.max(), 200)\ny_smooth = spline(x, y, x_smooth)\n\n# Define the matrix of 1x1 to place subplots\n# Placing the plot1 on 1x1 matrix, at pos 1\nsp1 = canvas.add_subplot(1,1,1, axisbg='w')\n#sp1.plot(x, y, 'red', linewidth=2)\nsp1.plot(x_smooth, y_smooth, 'red', linewidth=1)\n\n# Colorcode the tick tabs\nsp1.tick_params(axis='x', colors='red')\nsp1.tick_params(axis='y', colors='red')\n\n# Colorcode the spine of the graph\nsp1.spines['bottom'].set_color('r')\nsp1.spines['top'].set_color('r')\nsp1.spines['left'].set_color('r')\nsp1.spines['right'].set_color('r')\n\n# Put the title and labels\nsp1.set_title('matplotlib example 1', color='red')\nsp1.set_xlabel('matplot x label', color='red')\nsp1.set_ylabel('matplot y label', color='red')\n\n# Show the plot/image\nplt.tight_layout()\nplt.grid(alpha=0.8)\nplt.savefig(\"example6.eps\")\nplt.show()","sub_path":"lacf_vpp_code/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"383257485","text":"# a rough upper limit:\n# (9 ** 5) is 59'049\n# 354_294 = 6 * (9 ** 5)\n\nres = 0\nfor i in range(2, 354294):\n currsum = 0\n for j in [int(x) for x in str(i)]:\n currsum += j ** 5\n if i == currsum:\n res += currsum\n\nprint(res)","sub_path":"1-99/30.py","file_name":"30.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"252407367","text":"#printing a list of the full path to items in a directory\n#printing a list of the full path to items in a directory (excluding directories)\n#printing the list of all .jpg and .png files in a directory\n#printing the number of spaces in a string\n#removing vowels from a string and printing it\n#printing all of the words in a string that have less than 4 letters\n#printing length of each word in a sentence.\n\nimport os\n\ndef png_jpg():\n dir=input(\"Enter the directory:\")\n inc_extensions=['jpg','png']\n file_names = [fn for fn in os.listdir(dir)\n if any(fn.endswith(ext) for ext in inc_extensions)]\n print(file_names)\n \ndef spaces():\n print(\"Enter the string:\")\n str=input()\n w=[w for w in str]\n print(\"Spaces={}\".format(w.count(\" \")))\n \ndef rem_vowels():\n str=input(\"Enter the string:\")\n v=[\"a\",\"e\",\"i\",\"o\",\"u\",\"A\",\"E\",\"I\",\"O\",\"U\"]\n cons=[k for k in str if k not in v]\n print(cons)\n \ndef print4():\n str=input(\"Enter the string:\")\n str=str.split(\" \")\n word=[i for i in str if len(i)==4]\n print(word)\n \ndef print_len():\n str=input(\"Enter the string:\")\n str=str.split(\" \")\n length=[len(k) for k in str]\n print(length)\n \ndef full_path():\n dir=input(\"Enter the directory:\")\n fn=os.listdir(dir)\n full_paths=[os.path.abspath(i) for i in fn]\n print(full_paths)\n \ndef exc_dir():\n dir=input(\"Enter the directory:\")\n fn=os.listdir(dir)\n exc_dirs=[i for i in fn if i.isfile()]\n print(exc_dirs)\ndef main(): \n full_path()\n exc_dir()\n png_jpg() \n spaces()\n rem_vowels()\n print4()\n print_len()\nmain()\n","sub_path":"list_comprehension_assignment.py","file_name":"list_comprehension_assignment.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"146278743","text":"import csplot\nimport random\nimport time\n\ndef createBoard(width, height):\n \"\"\"returns an array of arrays that makes the gameboard\n \"\"\"\n R = [createOneRow(width-1)]\n for row in range(height-1):\n R += [createOneRow(width-1)]\n return R\n\ndef createOneRow( n ):\n \"\"\" returns rows of n zeros... You might use\n this as the INNER loop in createBoard \"\"\"\n R = [0]\n for col in range(n):\n R += [0]\n return R\n\ndef update2( B ):\n \"\"\" Takes an empty board as input and modifies that board\n so that it has a diagonal strip of \"on\" cells\n \"\"\"\n width = len(B[0])\n height = len(B)\n \n for row in range(height):\n for col in range(width):\n if row > 0 and row < height-1:\n if col > 0 and col < width -1:\n B[row][col] = 1\n else:\n B[row][col] = 0\n\ndef updateRandom(B):\n \"\"\"Updates a given board with random values\n \"\"\"\n width = len(B[0])\n height = len(B)\n \n for row in range(height):\n for col in range(width):\n if row > 0 and row < height-1:\n if col > 0 and col < width -1:\n B[row][col] = random.choice([0,1])\n else:\n B[row][col] = 0\n\ndef updateReversed(oldB, newB):\n \"\"\"Takes a board input and produces a new board that has reversed values\n \"\"\"\n width = len(oldB[0])\n height = len(oldB)\n \n for row in range(height):\n for col in range(width):\n if row > 0 and row < height-1:\n if col > 0 and col < width -1:\n newB[row][col] = 1 - oldB[row][col] \n else:\n oldB[row][col] = 0\n \n\ndef life( width, height ):\n \"\"\" will become John Conway's Game of Life... \"\"\"\n B = createBoard( width, height )\n csplot.showAndClickInIdle(B)\n \n while True: # run forever\n csplot.show(B) # show current B\n time.sleep(0.25) # pause a bit\n oldB = B # just a reminder for us humans\n B = createBoard(width, height) # creates a new board\n updateNextLife( oldB, B ) # sets the new board correctly\n \ndef updateNextLife(oldB, newB):\n \"\"\"updates the board according to the rules of the Game of Life\n \"\"\"\n width = len(oldB[0])\n height = len(oldB)\n \n for row in range(height):\n for col in range(width):\n counter = 0\n if row > 0 and row < height-1:\n if col > 0 and col < width -1:\n if oldB[row+1][col] == 1:\n counter += 1\n if oldB[row-1][col] == 1:\n counter += 1\n if oldB[row][col +1] == 1:\n counter += 1\n if oldB[row][col-1] == 1:\n counter += 1\n if counter == 0 or counter == 1 or counter == 4:\n newB[row][col] = 0\n elif counter == 2:\n newB[row][col] = oldB[row][col]\n elif counter == 3:\n newB[row][col] = 1\n else:\n oldB[row][col] = 0\n","sub_path":"Game of Life/Life.py","file_name":"Life.py","file_ext":"py","file_size_in_byte":3116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"240176970","text":"# -*-coding:utf-8-*-\r\nimport re\r\ndef count(url):\r\n\tfilet = open(url)\r\n\tdic = {}\r\n\t# 一下子将所有文件都读进来\r\n\tline = filet.read()\r\n\twords = line.split()\r\n\tdic = {}\r\n\tfor word in words:\r\n\t\tif dic.__contains__(word):\r\n\t\t\tdic[word] = dic[word]+1\r\n\t\telse:\r\n\t\t\tdic[word] = 1\r\n\tprint(dic)\r\n\t#while line.split\r\n\treturn 0\r\ndef num(path):\r\n\twith open(path,\"r\") as file:\r\n\t\tdata = file.read()\r\n\t\t# 正则表达式 匹配匹配每一个单词:主要目的将标点符号过滤掉\r\n\t\twords=re.compile('[a-zA-Z0-9]+') #compile好像是必须用的,用来格式转换什么的,然后才能进行匹配之类的操作\r\n\t\tprint(words)\r\n\t\tdict={}\r\n\t\tfor x in words.findall(data):\r\n\t\t\tif x in dict:\r\n\t\t\t\tdict[x]+=1\r\n\t\t\telse:\r\n\t\t\t\tdict[x] =1;\r\n\t\tprint(dict)\r\nif __name__ == \"__main__\":\r\n\tcount(\"demo.txt\")\r\n\tnum(\"demo.txt\")","sub_path":"python学习项目集合/4:词频统计/count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"604921909","text":"from PyQt5.QtCore import *\nfrom firebase import firebase\n\n# VOS back-end thread for Firebase reads\n#______________________________________________________________________________________________\nclass FireRead(QThread):\n\n # signals slotted to main thread\n finished = pyqtSignal(dict)\n setTeacherName = pyqtSignal(str)\n setTeacherReply = pyqtSignal(str) \n setDisplayMsg = pyqtSignal(str)\n setAvailable = pyqtSignal(str)\n setHours = pyqtSignal(str, str)\n\n def __init__(self, oldData, parent=None):\n super(FireRead, self).__init__(parent)\n\n self.oldData = oldData\n\n self.tags = { \n \"t-display\",\n \"t-available\",\n \"t-name\",\n \"t-reply\",\n \"t-hours-start\",\n \"t-hours-end\",\n \"s-name\",\n \"s-msg\"\n }\n\n self.newData = { \n \"t-display\": \"\",\n \"t-available\": False,\n \"t-name\": \"\",\n \"t-reply\": \"\",\n \"t-hours-start\": \"\",\n \"t-hours-end\": \"\",\n \"s-name\": \"\",\n \"s-msg\": \"\"\n }\n\n def run(self):\n\n dbURL = \"https://v-o-s-62a4d.firebaseio.com/VOS\"\n db = firebase.FirebaseApplication(dbURL, None)\n\n # READ data for all tags\n for tag in self.tags:\n dataVal = db.get( '/VOS/' + tag, None )\n self.newData[tag] = dataVal\n\n # if the data has changed since last read\n if( dataVal != self.oldData[tag] or tag == \"t-reply\" ):\n\n if( tag == \"t-name\" ):\n self.setTeacherName.emit( str(dataVal).strip('\"') )\n\n elif( tag == \"t-available\" ):\n self.setAvailable.emit( dataVal )\n\n elif( tag == \"t-hours-start\" ):\n endTime = db.get( '/VOS/' + \"t-hours-end\", None )\n self.setHours.emit( str(dataVal).strip('\"'), str(endTime).strip('\"') )\n\n elif( tag == \"t-hours-end\" ):\n startTime = db.get( '/VOS/' + \"t-hours-start\", None )\n self.setHours.emit( str(startTime).strip('\"'), str(dataVal).strip('\"') )\n\n elif( tag == \"t-display\" ):\n self.setDisplayMsg.emit( str(dataVal).strip('\"').replace('\\\\n','
') )\n \n elif( tag == \"t-reply\" ):\n reply = str(dataVal).strip('\"').replace('\\\\n','
')\n if( reply ):\n self.setTeacherReply.emit( reply )\n db.patch( \"/VOS/\", { tag : '\\\"' + '' + '\\\"' } )\n \n self.finished.emit(self.newData)\n","sub_path":"src/main/python/FireRead.py","file_name":"FireRead.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"89093069","text":"#!/usr/bin/env python3\n\n\"\"\"\nevalts.py\nEthan Toly\nSept 2018\nThis program is made to evaluate timestamp data to infer things such as\nframerate, dropped frames, and timestamp distance.\n\"\"\"\n#import cv2\nimport math\nimport matplotlib.pyplot as plt\nimport sys\nimport numpy as np\n\ndef plot_time_differences(time_differences):\n colours = []\n \"\"\"\n for x in time_differences:\n if x > (1000000/framerate) * 1.0001:\n colours.append('b')\n else:\n colours.append('r')\n \"\"\"\n plt.plot(time_differences, marker='.', markersize=2, linewidth=0)\n plt.ylabel(\"Microseconds\")\n plt.xlabel(\"Frame number\")\n plt.show()\n\nfilename = sys.argv[1].split('/')\nfilename = '/'+filename[-1]\nprint(sys.argv[1] + filename +\"ts.txt\")\ntry:\n ts = open(sys.argv[1] + filename +\"ts.txt\", 'r')\nexcept:\n print(\"File not found\")\n exit()\n#cap = cv2.VideoCapture(sys.argv[1] + filename + \".mp4\")\n\n#numFrames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\nframerate = int(sys.argv[2])\n\ntimestamps = ts.readlines()\n\ntemp = []\n#make sure to only consider the first thing written\nfor line in timestamps:\n temp.append(line.split(' ', 1)[0])\ntimestamps = temp\n\ntotalTimestamps = len(timestamps)\n\n#h264 sometimes writes \"None\" to timestamp file, remove these\ntimestamps = [x for x in timestamps if (x != 'None\\n' and x != 'None')]\n\"\"\"\nfor i in range(0, len(timestamps)):\n if timestamps[i] == 'None\\n' or timestamps[i] == 'None':\n timestamps[i] = -1\n\"\"\"\nnumTimestamps = len(timestamps)\n\nseconds = (int(timestamps[-1]) - int(timestamps[0]))/1000000\n\nframe_distances = []\nfor i in range(0, len(timestamps)- 1):\n frame_distances.append(int(timestamps[i+1]) - int(timestamps[i]))\n\nmean = sum(frame_distances)/len(frame_distances)\n\ntotal = 0\n\nfor i in range(0, len(frame_distances)- 1):\n total += (frame_distances[i] - mean)**2\n\nstd_deviation = math.sqrt(total/len(frame_distances))\n\n#estimate dropped frames by checking if any of the frame distances are > (1/framerate)* threshold\nthresh = 1.0001\ndropped_frames = 0\nfor dist in frame_distances:\n if dist > (1000000/framerate) * 1.0001:\n dropped_frames+= dist//(1000000/framerate)\n\nprint(\"# of real timestamps\", numTimestamps)\nprint(\"# of \\\"None\\\" timestamps: \", totalTimestamps-numTimestamps)\nprint(\"Actual recording time\", seconds, \"seconds\")\nprint(\"Average distance between timestamps\", mean)\nprint(\"Standard deviation\", std_deviation)\nprint(\"Actual avg framerate\", 1.0/(mean/1000000.0))\nprint(\"Estimated dropped frames: \", int(dropped_frames))\n\nplot_time_differences(frame_distances)\n","sub_path":"Evaluation/evalts.py","file_name":"evalts.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"16095733","text":"import gin\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Input, Concatenate, Dense\nfrom reaver.models.base.layers import Squeeze\n\n\n@gin.configurable\ndef build_mlp(obs_spec, act_spec, layer_sizes=(64, 64), activation='relu', value_separate=False):\n inputs = [Input(s.shape, name=\"input_\" + s.name) for s in obs_spec]\n inputs_concat = Concatenate()(inputs) if len(inputs) > 1 else inputs[0]\n\n x = build_fc(inputs_concat, layer_sizes, activation)\n outputs = [Dense(s.size(), name=\"logits_\" + s.name)(x) for s in act_spec]\n\n if value_separate:\n x = build_fc(inputs_concat, layer_sizes, activation, 'value_')\n\n value = Dense(1, name=\"value_out\")(x)\n value = Squeeze(axis=-1)(value)\n outputs.append(value)\n\n return Model(inputs=inputs, outputs=outputs)\n\n\ndef build_fc(input_layer, layer_sizes, activation, prefix=''):\n x = input_layer\n for i, size in enumerate(layer_sizes):\n x = Dense(size, activation=activation, name='%sfc%02d' % (prefix, i+1))(x)\n return x\n","sub_path":"reaver/models/base/mlp.py","file_name":"mlp.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"530459980","text":"# coding=utf-8\nfrom django.http import HttpResponse\nfrom haystack.query import SearchQuerySet, SQ\nfrom politics.apps.core.models import Tag\nfrom politics.utils.decorators import render_json\nfrom pyquery import PyQuery\nimport requests\n\n\ndef _get_html_title(url):\n \"\"\"Attempts to retrieve the HTML title of a URL.\n\n This only works if the URL responds to HTTP requests, in which case the\n contents of its ``title`` element will be returned; otherwise ``None``.\n\n :param url: The URL of the page.\n :type url: ``str``\n :returns: The URL's title or ``None``.\n :rtype: ``str`` or ``None``\n \"\"\"\n blacklist = (\n \"::1\",\n \"127.0.0.1\",\n \"localhost\",\n \"ip6-loopback\",\n \"ip6-localhost\",\n )\n\n for host in blacklist:\n if url.find(host) > -1:\n return None\n\n try:\n response = requests.get(url, timeout=10)\n selector = PyQuery(response.content)\n return selector(\"title\")[0].text.strip()\n except:\n return None\n\n\n@render_json\ndef tags(request):\n \"\"\"Returns the names of tags matching the given query as JSON.\n\n Used for autocompletion in tag inputs.\n \"\"\"\n # Escape the query.\n query = request.GET.get(\"q\", \"*\")\n query = SearchQuerySet().query.clean(query)\n\n if query == \"\":\n return []\n\n # Retrieve tags that match an autocomplete (ngram) search or a normal\n # search so derivative words match (e.g. \"immigrants\" => \"immigration\").\n results = SearchQuerySet().models(Tag).load_all()\n results = results.filter(SQ(content=query) | SQ(name_autocomplete=query))\n\n return [result.object.name for result in results]\n\n\n@render_json\ndef title(request):\n \"\"\"Attempts to retrieve the title of a URL.\"\"\"\n if request.method != \"GET\":\n return HttpResponse(status=405)\n\n if \"url\" not in request.GET:\n return HttpResponse(status=400)\n\n return _get_html_title(request.GET[\"url\"])\n","sub_path":"politics/apps/core/views/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"593290639","text":"import scrapy\nfrom twisted.internet.defer import inlineCallbacks, returnValue\n\nfrom decaptcha.exceptions import CaptchaIncorrectlySolved, CaptchaSolveTimeout\nfrom decaptcha.utils.download import download\n\n\nclass TwoCaptchaSolver(object):\n\n def __init__(self, crawler):\n self.crawler = crawler\n settings = crawler.settings\n self.apikey = settings.get('DECAPTCHA_TWOCAPTCHA_APIKEY')\n self.poll_times = settings.getint(\n 'DECAPTCHA_TWOCAPTCHA_POLL_TIMES', 60\n )\n self.poll_delay = settings.getfloat(\n 'DECAPTCHA_TWOCAPTCHA_POLL_DELAY', 2\n )\n self.api_url = 'http://2captcha.com/'\n\n @inlineCallbacks\n def solve(self, site_key, page_url, data_s=None):\n formdata = {\n 'key': self.apikey,\n 'method': 'userrecaptcha',\n 'googlekey': site_key,\n 'pageurl': page_url\n }\n if data_s:\n formdata['data-s'] = data_s\n request = scrapy.FormRequest(self.api_url + 'in.php', formdata=formdata)\n response = yield download(self.crawler, request)\n try:\n captcha_id = response.body.split('|')[1]\n except Exception:\n raise CaptchaIncorrectlySolved('2captcha returned non-parsable captcha request response ({}): {}'\n .format(response.status,\n response.body))\n poll_url = self.api_url + 'res.php?key={}&action=get&id={}'.format(self.apikey, captcha_id)\n for retry in xrange(self.poll_times):\n poll_request = scrapy.Request(poll_url, dont_filter=True)\n poll_response = yield download(self.crawler, poll_request)\n if not 'CAPCHA_NOT_READY' in poll_response.body:\n try:\n result = poll_response.body.split('|')[1]\n returnValue(result)\n except Exception:\n # ERROR_CAPTCHA_UNSOLVABLE\n raise CaptchaIncorrectlySolved('2captcha returned non-parsable captcha poll response ({}): {}'\n .format(poll_response.status,\n poll_response.body))\n raise CaptchaSolveTimeout('2captcha did not solve CAPTCHA in time')\n","sub_path":"decaptcha/solvers/twocaptcha.py","file_name":"twocaptcha.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"202188242","text":"import csv\r\n\r\npath = 'output.csv'\r\n\r\n#data = ['A','B','C','D','E']\r\n\r\ndata = ['FirstName,LastName'.split(\",\"),\r\n 'Sachin,Tendulkar'.split(\",\"),\r\n 'Virat,Kohli'.split(\",\"),\r\n 'MS,Dhoni'.split(\",\")]\r\n\r\ndef fileWriter(path, data):\r\n\r\n #csv_file = open(path,'w')\r\n with open(path,'w', newline=\"\") as csv_file:\r\n writer = csv.writer(csv_file, delimiter=',')\r\n\r\n for line in data:\r\n writer.writerow(line)\r\n\r\nfileWriter(path,data)\r\n","sub_path":"01-Basics/05-CSV/01-Writer.py","file_name":"01-Writer.py","file_ext":"py","file_size_in_byte":477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"466524283","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\ndf=pd.read_csv('studentInfo.csv')\ndf.head()\n\n\n# In[2]:\n\n\nimport matplotlib.pyplot as plt\nimport os\nimport warnings\n\nfrom keras.layers import Input, Embedding, Flatten, Dot, Dense, Concatenate\nfrom keras.models import Model\n\nwarnings.filterwarnings('ignore')\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# In[3]:\n\n\nfrom sklearn.model_selection import train_test_split\ntrain, test = train_test_split(df, test_size=0.2)\n\n\n# In[4]:\n\n\ntrain.head()\n\n\n# In[5]:\n\n\ntest.head()\n\n\n# In[6]:\n\n\nn_users=len(df.id_student.unique())\nn_users\n\n\n# In[7]:\n\n\nn_courses=len(df.course_id.unique())\n\n\n# In[8]:\n\n\nn_courses\n\n\n# In[9]:\n\n\n# creating course embedding path\ncourse_input = Input(shape=[1], name=\"Course-Input\")\ncourse_embedding = Embedding(1133, 5, name=\"Course-Embedding\")(course_input)\ncourse_vec = Flatten(name=\"Flatten-Courses\")(course_embedding)\n\n# creating user embedding path\nuser_input = Input(shape=[1], name=\"User-Input\")\nuser_embedding = Embedding(10000000, 5, name=\"User-Embedding\")(user_input)\nuser_vec = Flatten(name=\"Flatten-Users\")(user_embedding)\n\n\n# concatenate features\nconc = Concatenate()([course_vec, user_vec])\n\n# add fully-connected-layers\nfc1 = Dense(32, activation='sigmoid')(conc)\nfc2 = Dense(32, activation='sigmoid')(fc1)\nout = Dense(1)(fc2)\n\n# Create model and compile it\nmodel2 = Model( [user_input,course_input], out)\nmodel2.compile('adam', 'mean_squared_error',metrics=['accuracy'])\n\n\n# In[10]:\n\n\nfrom keras.models import load_model\n\nif os.path.exists('regression_model14.h5'):\n model2 = load_model('regression_model14.h5')\nelse:\n history = model2.fit([train.id_student,train.course_id], train.final_result, epochs=5)\n model2.save('regression_model14.h5')\n plt.plot(history.history['loss'])\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Training Error\")\n\n\n# In[11]:\n\n\nmodel2.evaluate([test.id_student, test.course_id], test.final_result)\n\nX5=[[test.id_student, test.course_id]]\n# In[12]:\n\n\nfrom sklearn.datasets import make_circles\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\nfrom sklearn.metrics import f1_score\nyhat_probs = model.predict(X5, verbose=0)\n# predict crisp classes for test set\nyhat_classes = model.predict_classes(X5, verbose=0)\n# reduce to 1d array\nyhat_probs = yhat_probs[:, 0]\nyhat_classes = yhat_classes[:, 0]\n # accuracy: (tp + tn) / (p + n)\naccuracy = accuracy_score(Y1, yhat_probs)\n# precision tp / (tp + fp)\nprecision = precision_score(Y1, yhat_probs)\n# recall: tp / (tp + fn)\nrecall = recall_score(Y1, yhat_probs)\n# f1: 2 tp / (2 tp + fp + fn)\nfscore = f1_score(Y1, yhat_probs)\npredictions = model2.predict([test.id_student.head(10), test.course_id.head(10)])\n\n[print(predictions[i], test.final_result.iloc[i]) for i in range(0,10)]\n\n\n# In[13]:\n\n\n\n# Creating dataset for making recommendations for the first user\ncourse_data = np.array(list(set(df.course_id)))\ncourse_data[:5]\n\n\n# In[14]:\n\n\nuser = np.array([2632165 for i in range(len(course_data))])\nuser[:5]\n\n\n# In[15]:\n\n\npredictions = model2.predict([user, course_data])\n#[print(predictions[i]) for i in range(0,22)]\n\npredictions = np.array([a[0] for a in predictions])\n#[print(predictions[i]) for i in range(0,)]\n\nrecommended_course_ids = (-predictions).argsort()[:5]\nprint(\"Output recommended courses : \", course_data[recommended_course_ids]) \n\n#recommended_course_ids\n\n\n# In[16]:\n\n\n# print predicted scores\nprint(predictions[recommended_course_ids])\n\n\n# In[17]:\n\n\nprint('Accuracy: %f' % accuracy)\nprint('Precision: %f' % precision)\nprint('Recall: %f' % recall)\nprint('F1 score: %f' % fscore)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"nn (1).py","file_name":"nn (1).py","file_ext":"py","file_size_in_byte":3696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"112156324","text":"'''\nStaircase detail\nThis is a staricase size n = 4:\n #\n ##\n ###\n####\n\nIts base and height are both equal to n. It is drawn using # symbols and spaces. The last line is not preceded by any spaces.\n\nWrite a program that prints a staircase of size n.\n'''\nn = 4\ndef staircase(n):\n for i in range(1, n+1):\n print(('#' * i).rjust(n))\n\n\nif __name__ == '__main__':\n print(staircase(n))","sub_path":"HR_Easy/hr_staircase.py","file_name":"hr_staircase.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"517635397","text":"prg_comment = \"\"\nprg_version = \"0.7\"\ndef program(prg, cmd):\n prg.add(0, \"Mirrors MOT\")\n prg.add(100, \"B comp x\", 1.4, functions=dict(value=lambda x: cmd.get_var('Bx_MOT')))\n prg.add(200, \"B comp y\", 0.0000, functions=dict(value=lambda x: cmd.get_var('By_MOT')))\n prg.add(300, \"B comp z\", 0.8000, functions=dict(value=lambda x: cmd.get_var('Bz_MOT')))\n prg.add(400, \"B grad x\", 0.2000)\n prg.add(450, \"IGBT B grad x OFF\")\n prg.add(500, \"Delta 1 Voltage\", 6.0000)\n prg.add(1000, \"Delta 2 Voltage\", 0.0000, enable=False)\n prg.add(1500, \"Mirrors MOT\")\n prg.add(2000, \"Pulse MOT Na OFF\")\n prg.add(3000, \"Na 3D MOT cool (-) ON\")\n prg.add(3500, \"Shutter 3DMOT cool Na Open\")\n prg.add(4000, \"Na 3D MOT cool (+) freq\", 102.00, functions=dict(frequency=lambda x: 110+cmd.get_var('MOT3D_det')/2))\n prg.add(4500, \"Na 3D MOT cool (-) freq\", 118.00, functions=dict(frequency=lambda x: 110-cmd.get_var('MOT3D_det')/2))\n prg.add(5000, \"Na 3D MOT cool (+) Amp\", 1000, functions=dict(amplitude=lambda x: cmd.get_var('MOT3D_amp')))\n prg.add(5500, \"Na 3D MOT cool (-) Amp\", 1000, functions=dict(amplitude=lambda x: cmd.get_var('MOT3D_amp')))\n prg.add(6000, \"Shutter Gray molasses Close\")\n prg.add(6500, \"AOM GM Amp ch1 (+)\", 0)\n prg.add(7000, \"Na Gray molasses (+) freq\", 80.00)\n prg.add(7500, \"AOM GM Amp ch2 (-)\", 0)\n prg.add(8000, \"Na Gray molasses (-) freq\", 80.00)\n prg.add(8500, \"Delta 1 Current\", 12.000, functions=dict(value=lambda x: cmd.get_var('MOT_current')))\n prg.add(9000, \"Shutter Dark Spot Open\")\n prg.add(9500, \"Shutter repump Na Open\")\n prg.add(10000, \"Na Repumper Tune (+) freq\", 1712.0, functions=dict(frequency=lambda x: cmd.get_var('Rep_freq')))\n prg.add(10500, \"Na Repumper1 (+) Amp\", 1000)\n prg.add(11000, \"Na Repumper2 (+) Amp\", 1000, functions=dict(amplitude=lambda x: cmd.get_var('DS_amp')))\n prg.add(11500, \"TTL Dark Spot ON\")\n prg.add(12000, \"TTL Repumper MOT OFF\")\n prg.add(12500, \"Shutter EOM Na Open\")\n prg.add(13500, \"Na 2D MOT (+) Amp\", 1000, functions=dict(amplitude=lambda x: cmd.get_var('MOT2D_amp')))\n prg.add(14000, \"Na 2D MOT (-) Amp\", 1000, functions=dict(amplitude=lambda x: cmd.get_var('MOT2D_amp')))\n prg.add(14500, \"Na 2D MOT (-) freq\", 100.50, functions=dict(frequency=lambda x: 95.5-cmd.get_var('MOT2D_det')/2))\n prg.add(15000, \"Na 2D MOT (+) freq\", 90.50, functions=dict(frequency=lambda x: 95.5+cmd.get_var('MOT2D_det')/2))\n prg.add(15500, \"TTL Repumper GM OFF\")\n prg.add(16000, \"Na Zeeman slower (-) Amp\", 1000, functions=dict(amplitude=lambda x: cmd.get_var('zs_amp')))\n prg.add(16500, \"Na Zeeman slower (-) freq\", 300.0, functions=dict(frequency=lambda x: cmd.get_var('zs_det')))\n prg.add(17000, \"Shutter Probe/Push Open\")\n prg.add(18000, \"Na Probe/Push (-) freq\", 105.00, functions=dict(frequency=lambda x: 110-cmd.get_var('push_det')/2))\n prg.add(18500, \"Na Push (+) freq\", 115.00, functions=dict(frequency=lambda x: 110+cmd.get_var('push_det')/2))\n prg.add(19000, \"Na Probe/Push (-) amp\", 500, functions=dict(amplitude=lambda x: cmd.get_var('push_amp')))\n prg.add(19500, \"Na Push (+) amp\", 500, functions=dict(amplitude=lambda x: cmd.get_var('push_amp')))\n prg.add(20000, \"TTL Push ON\")\n prg.add(21000, \"TTL Probe y OFF\")\n prg.add(22000, \"TTL Probe z OFF\")\n prg.add(22500, \"IGBT B comp x ON\")\n prg.add(23000, \"IGBT B comp y ON\")\n prg.add(23500, \"IGBT B comp z ON\")\n prg.add(24000, \"IGBT B grad x OFF\")\n prg.add(24500, \"Shutter Gray molasses Open\")\n prg.add(25000, \"Config MOT.sub\")\n prg.add(40000, \"Na Gray molasses (+) freq\", 112.50)\n prg.add(42000, \"Na Gray molasses (-) freq\", 87.50)\n prg.add(44000, \"AOM GM Amp ch1 (+)\", 1000)\n prg.add(46000, \"AOM GM Amp ch2 (-)\", 1000)\n prg.add(1046000, \"open_probe\")\n prg.add(16025000, \"MOT lights Off TTL.sub\", enable=False)\n return prg\n","sub_path":"programs/subroutines/DarkSpotMOT_GM_lights_on.sub.py","file_name":"DarkSpotMOT_GM_lights_on.sub.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"641439363","text":"import turtle\nimport os\nimport math\nimport random\n\n#Set up the screen\nwn=turtle.Screen()\nwn.bgcolor('black')\nwn.title('Space invaders')\nwn.bgpic('space_dn.png')\n\n#Register the shapes\nturtle.register_shape('player.gif')\nturtle.register_shape('enemy.gif')\n\n#Draw border\nborder_pen = turtle.Turtle()\nborder_pen.speed(0)\nborder_pen.color('white')\nborder_pen.penup()\nborder_pen.setposition(-300, -300)\nborder_pen.pendown()\nborder_pen.pensize(3)\n\nfor side in range (4):\n border_pen.fd(600)\n border_pen.lt(90)\nborder_pen.hideturtle()\n\n#Set the score to 0\nscore=0\n#Draw the score\nscore_pen=turtle.Turtle()\nscore_pen.speed(0)\nscore_pen.color('white')\nscore_pen.penup()\nscore_pen.setposition(-290, 270)\nscorestring = 'Score: %s' %score\nscore_pen.write(scorestring, False, align='left', font=('Arial', 12, 'bold'))\nscore_pen.hideturtle()\n\n#Create the player turtle\nplayer = turtle.Turtle()\nplayer.color('blue')\nplayer.shape('player.gif')\nplayer.penup()\nplayer.speed(0)\nplayer.setposition(0, -250)\nplayer.setheading(90)\n\nplayerspeed =15\n\n#Choose a number of enemies\nnumber_of_enemies=10\n#Create a empty list of enemies\nenemies=[]\n#Add enemies to the list\nfor i in range(number_of_enemies):\n # Create the enemy\n enemies.append(turtle.Turtle())\n\nfor enemy in enemies:\n enemy.color('red')\n enemy.shape('enemy.gif')\n enemy.penup()\n enemy.speed(0)\n x=random.randint(-200, 200)\n y=random.randint(100, 250)\n enemy.setposition(x, y)\n\nenemyspeed=2\nenemyspeeddown=40\n\n#Create the player's bullet\nbullet=turtle.Turtle()\nbullet.color('yellow')\nbullet.shape('triangle')\nbullet.penup()\nbullet.speed(0)\nbullet.setheading(90)\nbullet.shapesize(0.3, 0.3)\nbullet.hideturtle()\n\nbulletspeed=20\n\n#Define bullet state\n#ready - Ready to fire\n#fire - Bullet is firing\nbulletstate='ready'\n\n#Move the player left and right\ndef move_left():\n x=player.xcor()\n x-=playerspeed\n if x <-280:\n x=-280\n player.setx(x)\n\ndef move_right():\n x=player.xcor()\n x+=playerspeed\n if x > 280:\n x=280\n player.setx(x)\n\ndef fire_bullet():\n #Declare bulletstate as a global if it need changed\n global bulletstate\n #Move the bullet to the just above the player\n if bulletstate == 'ready':\n bulletstate='fire'\n os.system(\"aplay laser.wav&\")\n x=player.xcor()\n y=player.ycor() + 10\n bullet.setposition(x, y)\n bullet.showturtle()\n\ndef isCollision(t1, t2):\n distance = math.sqrt(math.pow(t1.xcor() - t2.xcor(), 2) + math.pow(t1.ycor() - t2.ycor(), 2))\n if distance < 23:\n return True\n else:\n return False\n\n#Create keyboard bindings\nturtle.listen()\nturtle.onkey(move_left, 'Left')\nturtle.onkey(move_right, 'Right')\nturtle.onkey(fire_bullet, 'space')\n\n#Main game loop\nflag= True\nwhile flag:\n for enemy in enemies:\n #Move the enemy\n x=enemy.xcor()\n x+=enemyspeed\n enemy.setx(x)\n\n #Move the enemy back and down\n if enemy.xcor() > 280 or enemy.xcor() < -280:\n #Move all enemies down\n for e in enemies:\n y = e.ycor()\n y -= enemyspeeddown\n e.sety(y)\n enemyspeed *= -1\n\n #Check for a collision between the bullet and the enemy\n if isCollision(bullet, enemy):\n #Reset the bullet\n os.system(\"aplay explosion.wav&\")\n bullet.hideturtle()\n bulletstate='ready'\n bullet.setposition(0, -400)\n #Reset the enemy\n x = random.randint(-200, 200)\n y = random.randint(100, 250)\n enemy.setposition(x, y)\n #Update the score\n score+=10\n scorestring = 'Score: %s' %score\n score_pen.clear()\n score_pen.write(scorestring, False, align='left', font=('Arial', 12, 'bold'))\n\n if isCollision(player, enemy):\n os.system(\"aplay explosion.wav&\")\n player.hideturtle()\n enemy.hideturtle()\n print('Game Over')\n flag=False\n break\n\n\n #Move the bullet\n if bulletstate == 'fire':\n y=bullet.ycor()\n y+=bulletspeed\n bullet.sety(y)\n\n #Check to see if the bullet has gone to the top\n if bullet.ycor() >275:\n bullet.hideturtle()\n bulletstate = 'ready'\n\n\ndelay=input('Press enter to finish')","sub_path":"space-invaders.py","file_name":"space-invaders.py","file_ext":"py","file_size_in_byte":4334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"646928049","text":"reader = open('2015_2.csv', 'r')\nwriter = open('test2015_2.csv', 'w')\n\nlines = reader.readlines()\n\nfor line in lines:\n\tcur = line.split(',')\n\tcur[1] = cur[1].replace(\"'\", '')\n\tcur[3] = cur[3].replace(\"'\", '')\n\twriter.write(cur[0] + ',' + cur[1] + ',' + cur[2] + ',' + cur[3])\n\nreader.close()\nwriter.close()\n","sub_path":"tashu/submodule/spliter.py","file_name":"spliter.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"134576265","text":"from django.conf.urls import patterns, include, url\nfrom test.views import *\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\n# admin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^$',index),\n url(r'^intro/([\\w.-]+)/$',intro),\n url(r'^content/([\\w.-]+)/$',content_default),\n url(r'^content/([\\w.-]+)/([\\w.-]+)/$',content),\n # url(r'^$', 'WSTP.views.home', name='home'),\n # url(r'^WSTP/', include('WSTP.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n # url(r'^admin/', include(admin.site.urls)),\n)","sub_path":"WSTP/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"591750070","text":"import tkinter as tk\n\nfrom ven2 import *\n\n\n\n\nclass VenUno(tk.Tk) :\n\t\n\tdef __init__(self) :\n\t\t\n\t\tsuper().__init__()\n\t\t#self.pack()\n\t\t\n\t\tself.label = tk.Label(self, text = \"Primera Ventana\")\n\t\t\n\t\tself.btn = tk.Button(self, text = \"Next →\", activebackground = \"skyblue\", command = self.next)\n\t\t\n\t\tself.label.pack(side = \"top\", pady = 100)\n\t\tself.btn.pack(side = \"top\")\n\t\t\n\t\t\n\tdef next(self) :\n\t\t\n\t\tmain(self)\n\n\n\n#root = tk.Tk()\n\n\napp = VenUno()\n\n\n\napp.mainloop() \n\n","sub_path":"Images/ven1.py","file_name":"ven1.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"545722254","text":"\n\nuser_input_numbers = True\n\n\n# validate the credit card number\ndef credit_card_validate(card_num):\n valid = True\n if len(card_num) > 16 or len(card_num) < 13:\n return 'Invalid'\n step_one = 0\n location_one = len(card_num) - 2\n while location_one >= 0:\n try:\n doubled_num = int(card_num[location_one])\n doubled_num *= 2\n if len(str(doubled_num)) > 1:\n doubled_num_string = str(doubled_num)\n first_part = int(doubled_num_string[0])\n second_part = int(doubled_num_string[1])\n doubled_num = first_part + second_part\n step_one += doubled_num\n location_one -= 2\n except ValueError:\n global user_input_numbers\n user_input_numbers = False\n return 'Invalid'\n step_two = 0\n location_two = len(card_num) - 1\n while location_two >= 0:\n try:\n step_two += int(card_num[location_two])\n location_two -= 2\n except ValueError:\n global user_input_numbers\n user_input_numbers = False\n return 'Invalid'\n step_three = step_one + step_two\n if step_three % 10 == 0 and valid:\n return 'Valid'\n else:\n return 'Invalid'\n\n\n# check the type of card\ndef card_type_check(card_num):\n if len(card_num) > 16 or len(card_num) < 13 or user_input_numbers is False:\n return 'Invalid'\n elif(card_num[0] == '4'):\n return 'Visa'\n elif(card_num[0] == '5'):\n return 'Master Card'\n elif(card_num[0] == '3' and card_num[1] == '7'):\n return 'American Express'\n elif(card_num[0] == '6'):\n return 'Discover'\n\n\ndef main():\n loop = True\n while loop:\n choice = input('===Credit Card Validation===\\n' +\n '1. Validate Number\\n2. Exit Program\\n' +\n '============================\\n' +\n 'Menu Choice:')\n if choice == '1':\n global user_input_numbers\n user_input_numbers = True\n card_four = input(\"Please input a credit card number:\\n\")\n valid = credit_card_validate(card_four)\n card_type = card_type_check(card_four)\n print(card_four, card_type, valid, sep='\\t')\n\n elif choice == '2':\n loop = false\n else:\n print('You entered an invalid option! Please try again!')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Lab 01/credit_card_validation.py","file_name":"credit_card_validation.py","file_ext":"py","file_size_in_byte":2471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"636372923","text":"from util import Randomize\nfrom IO_Operations import Printer\nfrom sample import Sample\nfrom activation_functions import ActivationFunctions as AF\nimport time\nfrom util import Normalize\n\n\nfrom neuron import Neuron\n\nclass Perceptron(Neuron):\n def __init__(self, inputs, expected_outputs: list, learning_rate: float = 1,\n normalize = None, is_random: bool = True, activation_function=AF.signal, \n parents: list = None, printer=Printer):\n\n super().__init__(inputs, expected_outputs, learning_rate,\n normalize, is_random, activation_function, parents, printer)\n\n \n def train(self, max_epoch=10000):\n self._Neuron__param_validation()\n\n time_begin = time.time()\n\n self._Neuron__samples = self._Neuron__associate_samples(\n self.inputs, self.expected_outputs, self.weights)\n\n outputs = []\n epochs = 0\n\n have_error = True\n\n while(have_error):\n # self.printer.print_msg(\"Época:\" + str(epochs) + \" Pesos \" + str(self.__weights))\n if epochs > max_epoch:\n break\n\n outputs = []\n\n have_error = False\n\n for sample in self._Neuron__samples:\n activation_potential = sample.get_activation_potential()\n\n output = self.activation_function(activation_potential)\n outputs.append(output)\n\n if output != sample.expected_output:\n for i, inputt in enumerate(sample.inputs):\n self.weights[i] += self.learning_rate * \\\n (sample.expected_output - output) * inputt\n\n have_error = True\n\n epochs += 1\n\n time_end = time.time()\n time_delta = time_end - time_begin\n\n if epochs > max_epoch:\n self.printer.print_msg(\n \"Máximo de épocas atingido (\"+str(max_epoch)+\")\")\n\n self.printer.print_msg(\"\\nDuração(sec): \" + str(time_delta))\n self.printer.print_msg(\"Pesos: \" + str(self.weights[1::]))\n self.printer.print_msg(\"Limiar: \" + str(self.weights[0]))\n self.printer.print_msg(\"Épocas: \" + str(epochs))\n self.printer.print_msg(\"Random seed: \" + str(self.seed))\n\n return self.weights, outputs, epochs\n","sub_path":"neural_network/3.MLP/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"432537155","text":"import sys\nfrom PyQt5 import QtWidgets, uic, QtCore, QtGui\nfrom htmlEdit2 import htmlEdit\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nqtCreatorFile = \"htmlEdit.ui\" # Enter file here.\nUi_Window , QtBaseClass = uic.loadUiType(qtCreatorFile)\n\nclass MyApp(QtWidgets.QMainWindow, Ui_Window):\n def __init__(self):\n QtWidgets.QMainWindow.__init__(self)\n Ui_Window.__init__(self)\n self.setupUi(self)\n\n self.btn_do.clicked.connect(self.htmlEdit)\n\n def htmlEdit(self):\n txt = self.txt_input.toPlainText()\n #print txt\n editHTML = htmlEdit()\n txtHTML,counter = editHTML.spanTagCleaner(txt)\n #print \"Deleted %s SPAN tag\" %counter\n self.txt_report.setPlainText(\"Deleted %s TAG.\"%counter)\n txtHTML,counter = editHTML.linkOpenNewTag(txtHTML)\n #print \"Added %s BLANK target\" %counter\n self.txt_report.append(\"Added %s BLANK target.\"%counter)\n txtHTML,counter,youtube_notallow_embed,youtube_broken_links,youtube_already_embed,counter2 = editHTML.youtubeEmbeddedMaker(txtHTML)\n #print \"Added %s Embedded Youtube\" %counter\n self.txt_report.append(\"Added %s Embedded Youtube Videos.\"%counter)\n if youtube_notallow_embed:\n #print \"Following links are not allowed to embed: \", youtube_notallow_embed\n self.txt_report.append(\"Following links are not allowed to embed: %s\"%youtube_notallow_embed)\n if youtube_broken_links:\n # print \"Following YOUTUBE links are broken links: \", youtube_broken_links\n self.txt_report.append(\"Following YOUTUBE links are broken links: %s\"%youtube_broken_links)\n if youtube_already_embed:\n self.txt_report.append(\"Following YOUTUBE links are already embedded: %s\"%youtube_already_embed)\n\n self.txt_report.append(\"Transformed %s Youtube URLs into Hyperlinks.\"%counter2)\n \n self.txt_output.setPlainText(txtHTML)\n \n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n window = MyApp()\n window.show()\n sys.exit(app.exec_())\n","sub_path":"bb_tools_UI.py","file_name":"bb_tools_UI.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"26962848","text":"import numpy as np\nimport model\nimport torch.nn.functional as F\n\n\nclass Configuration():\n def __init__(self):\n\n # random seed\n self.random_seed = 40\n\n # configs for replay buffer\n self.buffer_size = int(1e5) # replay buffer size\n self.batch_size = 128 # minibatch size\n \n # configs for agent\n self.gamma = 0.99 # discount factor\n self.tau = 1e-3 # for soft update of target parameters\n self.learn_frequency = 1 # learn every `learn_frequency` timesteps\n self.num_experience_replays = 2 # how many times to learn in each learning period\n \n # configs for actor\n self.actor = model.Actor\n self.lr_actor = 1e-4 # learning rate of the actor\n self.batch_normalization_actor = True\n \n # configs for critic\n self.critic = model.Critic\n self.lr_critic = 1e-3 # learning rate of the critic\n self.l2_weight_decay = 0 # L2 weight decay\n self.batch_normalization_critic = True\n\n # configs for noise sample\n self.mu = 0.\n self.theta = 0.15\n self.sigma = 0.2\n self.noise_func = np.random.standard_normal\n","sub_path":"p3_collab-compet/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"496016423","text":"#!/usr/bin/python3\n#import time\nimport random\nimport imp\nmodl = imp.load_source('ppFunctions', '../00/ppFunctions.py')\nimport os\nfrom ppFunctions import *\nfrom termcolor import colored, cprint\n#sleep becouse of loading midi modules\nprint(\"Are you ready?\")\ntime.sleep(1)\n\nprint_status = lambda x: cprint(x, 'white', 'on_blue')\nprint_help = lambda x: cprint(x, 'red')\n\nhit = 0\nrounde = 1\ndone = False\n\ngeneratedList = []\nfor i in range(stringToMidiNum(\"c\"), stringToMidiNum(\"c'\")+1):\n if i%12 in blackTonesBase:\n generatedList.append(i)\nwhile True:\n try:\n os.system('clear')\n print_status(\"Status: round=\" + str(rounde) + \", hit=\" + str(hit))\n print_help(\"Help: rEPEAT sKIP\")\n playHarmonicNotes(stringToMidiNum(\"f a c'\"))\n randomNote = random.choice(generatedList)\n playNote(randomNote)\n while not done:\n guessedNote = input(\"Your input:\")\n if guessedNote == \"r\":\n print(\"Repeating...\")\n playHarmonicNotes(stringToMidiNum(\"f a c'\"))\n playNote(randomNote)\n elif guessedNote == \"s\":\n print(\"Skiping...\")\n done = True\n elif guessedNote not in lilypondTones:\n print(\"What? Syntax error!\")\n else:\n if (lilypondTones[guessedNote] == randomNote%12):\n print(\"Yea!\")\n hit += 1\n rounde += 1\n done = True\n else:\n print(\"Almost!\")\n hit = 0\n done = False\n except (KeyboardInterrupt):\n print('...Program Stopped Manually!')\n raise\n","sub_path":"src/mc_archive/mc-16-01-04-fmajor-1black.py","file_name":"mc-16-01-04-fmajor-1black.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"576611967","text":"import csv\nimport urllib.request\nfrom bs4 import BeautifulSoup as bs\n\nfrom Functions.RandomStringDigits import randomStringDigits\n\n\ndef interia():\n iHeadlines=dict()\n interia=\"https://fakty.interia.pl/\"\n page= urllib.request.urlopen(interia)\n soup = bs(page, features=\"html.parser\")\n headlines=soup.find_all(\"li\")\n for headline in headlines:\n magazines=headline.find_all(\"div\", class_=\"tile-magazine\")\n for magazine in magazines:\n headers=magazine.find_all(\"div\", class_=\"tile-magazine-header\")\n for header in headers:\n titles=header.find_all(\"h2\",class_=\"tile-magazine-title\")\n for title in titles:\n # print(\"Interia: \" + str(title.find(\"a\").string))\n key = randomStringDigits(8)\n value = str(title.find(\"a\").string)\n val=value.replace(u'\\u200b','')\n iHeadlines[key] = val\n return iHeadlines\n","sub_path":"Scrapers/WebScraperInteria.py","file_name":"WebScraperInteria.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"498315136","text":"n = int(input())\nlines = map(int, input().split())\n\nosum = 0\nesum = 0\n\nanss = []\n\nif n % 2 == 0:\n # i = 0\n ans = lines[0]\n p = 2\n while p < n - 3:\n if p % 2 == 0:\n while q < n:\n if p % 2 != 0:\n ans += []\n\n q = p + 3\n ","sub_path":"beginner_contest162/F.py","file_name":"F.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"125776995","text":"# Copyright (C) 2023, Advanced Micro Devices, Inc. All rights reserved.\n# SPDX-License-Identifier: BSD-3-Clause\n\n\nimport copy\nfrom typing import Dict, Any\nimport operator\nfrom random import sample\nfrom functools import partial\n\nimport torch\n\nfrom brevitas.fx import GraphModule, Node\nfrom brevitas.graph.utils import get_module\nfrom .base import GraphTransform\n\n__all__ = [\n 'EqualizeGraph'\n]\n\nEPSILON = 1e-9\n\n_supported_layers = (\n torch.nn.ConvTranspose1d,\n torch.nn.ConvTranspose2d,\n torch.nn.ConvTranspose3d,\n torch.nn.Conv1d,\n torch.nn.Conv2d,\n torch.nn.Conv3d,\n torch.nn.Linear)\n\n_scale_invariant_layers = (\n torch.nn.Dropout,\n torch.nn.Dropout2d,\n torch.nn.Dropout3d,\n torch.nn.ReLU,\n torch.nn.MaxPool1d,\n torch.nn.MaxPool2d,\n torch.nn.MaxPool3d,\n torch.nn.AvgPool1d,\n torch.nn.AvgPool2d,\n torch.nn.AvgPool3d,\n torch.nn.AdaptiveAvgPool1d,\n torch.nn.AdaptiveAvgPool2d,\n torch.nn.AdaptiveAvgPool3d)\n\n_residual_methods = (\n 'add',\n 'add_'\n)\n\n_residual_fns = (\n torch.add,\n operator.add,\n operator.iadd,\n operator.__add__,\n operator.__iadd__\n)\n\n_batch_norm = (\n torch.nn.BatchNorm1d,\n torch.nn.BatchNorm2d,\n torch.nn.BatchNorm3d,\n)\n\n\ndef _channel_range(inp):\n mins, _ = inp.min(dim=1) \n maxs, _ = inp.max(dim=1) \n out = maxs - mins\n # correct corner case where where all weights along a channel have the same value\n # e.g. when a mean/nn.AvgPool/nn.AdaptiveAvgPool is converted to a depth-wise conv\n out = torch.where(out == 0., torch.mean(inp, dim=1), out)\n return out\n\n\ndef _get_size(axes):\n m0, axis0 = list(axes.items())[0]\n size = m0.weight.size(axis0)\n for m, axis in axes.items():\n if m.weight.size(axis) != size:\n raise RuntimeError(\"Weights sizes don't match\")\n return size\n\n\ndef _get_input_axis(module):\n if isinstance(module, torch.nn.Linear):\n return 1\n elif isinstance(module, (torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d)):\n if module.groups == 1:\n return 1\n elif module.groups == module.out_channels:\n return 0\n else:\n raise RuntimeError(\"Group convolution not supported\")\n elif isinstance(module, (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranspose3d)):\n if module.groups == 1:\n return 0\n elif module.groups == module.out_channels:\n return 1\n else:\n raise RuntimeError(\"Group convolution not supported\")\n else:\n raise RuntimeError(f\"Module {module} not supported.\")\n\n\ndef _get_output_axis(module):\n if isinstance(module, (torch.nn.Linear, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d)):\n return 0\n elif isinstance(module, (torch.nn.ConvTranspose1d, torch.nn.ConvTranspose2d, torch.nn.ConvTranpose3d)):\n return 1\n else:\n raise RuntimeError(f\"Module {module} not supported.\")\n\n\ndef _cross_layer_equalization(srcs, sinks):\n \"\"\"\n Given two adjacent tensors', the weights are scaled such that\n the ranges of the first tensors' output channel are equal to the\n ranges of the second tensors' input channel\n \"\"\"\n for module_set in [srcs, sinks]:\n for module in module_set:\n if not isinstance(module, _supported_layers):\n raise ValueError(\"module type not supported:\", type(module))\n\n src_axes = {m: _get_output_axis(m) for m in srcs}\n sink_axes = {m: _get_input_axis(m) for m in sinks}\n src_size = _get_size(src_axes)\n sink_size = _get_size(sink_axes)\n\n if src_size != sink_size:\n raise RuntimeError(\"Output channels of sources do not match input channels of sinks\")\n\n transpose = lambda module, axis: module.weight if axis == 0 else module.weight.transpose(0, 1)\n src_weights = [transpose(m, axis) for m, axis in src_axes.items()]\n sink_weights = [transpose(m, axis) for m, axis in sink_axes.items()]\n srcs_range = _channel_range(torch.cat([w.reshape(w.size(0), -1) for w in src_weights], 1))\n sinks_range = _channel_range(torch.cat([w.reshape(w.size(0), -1) for w in sink_weights], 1))\n sinks_range += EPSILON\n scaling_factors = torch.sqrt(srcs_range / sinks_range)\n inverse_scaling_factors = torch.reciprocal(scaling_factors)\n\n for module, axis in src_axes.items():\n if hasattr(module, 'bias') and module.bias is not None:\n module.bias.data = module.bias.data * inverse_scaling_factors.view_as(module.bias)\n src_broadcast_size = [1] * module.weight.ndim\n src_broadcast_size[axis] = module.weight.size(axis)\n module.weight.data = module.weight.data * torch.reshape(inverse_scaling_factors, src_broadcast_size)\n for module, axis in sink_axes.items():\n src_broadcast_size = [1] * module.weight.ndim\n src_broadcast_size[axis] = module.weight.size(axis)\n module.weight.data = module.weight.data * torch.reshape(scaling_factors, src_broadcast_size)\n\n\ndef _equalize(model, regions, iterations):\n \"\"\"\n Generalized version of section 4.1 of https://arxiv.org/pdf/1906.04721.pdf\n \"\"\"\n name_to_module : Dict[str, torch.nn.Module] = {}\n name_set = {name for region in regions for module_set in region for name in module_set}\n\n for name, module in model.named_modules():\n if name in name_set:\n name_to_module[name] = module\n for i in range(iterations):\n for region in regions:\n _cross_layer_equalization([name_to_module[n] for n in region[0]], [name_to_module[n] for n in region[1]])\n return model\n\n\ndef _is_supported_module(graph_model, node):\n return node.op == 'call_module' and isinstance(get_module(graph_model, node.target), _supported_layers)\n\n\ndef _is_scale_invariant_module(graph_model, node):\n return node.op == 'call_module' and isinstance(get_module(graph_model, node.target), _scale_invariant_layers)\n\n\ndef _is_reshaping_op(node):\n return (node.op == 'call_function' and node.target in [torch.flatten, torch.reshape]\n or node.op == 'call_method' and node.target in ['view', 'reshape', 'flatten'])\n\n\ndef walk_region(graph_model: GraphModule, starting_node: Node, history, srcs, sinks, walk_forward):\n node_list = starting_node.users if walk_forward else starting_node.all_input_nodes\n for node in node_list:\n # we keep a history of how the graph has been walked already, invariant to the direction,\n # to avoid getting stuck in a loop\n path = (starting_node, node) if walk_forward else (node, starting_node)\n if path not in history:\n history.add(path)\n else:\n continue\n if _is_supported_module(graph_model, node):\n if walk_forward:\n sinks.add(node.target)\n else:\n srcs.add(node.target)\n walk_region(graph_model, node, history, srcs, sinks, walk_forward=True)\n elif _is_scale_invariant_module(graph_model, node):\n if walk_forward:\n walk_region(graph_model, node, history, srcs, sinks, walk_forward=True)\n else:\n walk_region(graph_model, node, history, srcs, sinks, walk_forward=True)\n walk_region(graph_model, node, history, srcs, sinks, walk_forward=False)\n elif (node.op == 'call_method' and node.target in _residual_methods\n or node.op == 'call_function' and node.target in _residual_fns):\n walk_region(graph_model, node, history, srcs, sinks, walk_forward=True)\n walk_region(graph_model, node, history, srcs, sinks, walk_forward=False)\n elif _is_reshaping_op(node):\n walk_region(graph_model, node, history, srcs, sinks, walk_forward=walk_forward)\n else:\n continue\n\n\ndef _extract_regions(graph_model: GraphModule):\n regions = set()\n for node in graph_model.graph.nodes:\n if node.op == 'call_module':\n module = get_module(graph_model, node.target)\n if isinstance(module, _supported_layers):\n srcs, sinks = {node.target}, set()\n walk_region(graph_model, node, set(), srcs, sinks, walk_forward=True)\n if sinks:\n # each region should appear only once, so to make it hashable\n # we convert srcs and sinks to ordered lists first, and then to tuples\n regions.add((tuple(sorted(srcs)), tuple(sorted(sinks))))\n # for clarity, sort by the of the first source\n regions = sorted(regions, key=lambda region: region[0][0])\n return regions\n\n\nclass EqualizeGraph(GraphTransform):\n\n def __init__(self, iterations) -> None:\n super(EqualizeGraph, self).__init__()\n self.iterations = iterations \n\n def apply(self, graph_model: GraphModule):\n regions = _extract_regions(graph_model)\n graph_model = _equalize(graph_model, regions, self.iterations)\n return graph_model\n\n\nclass AbsorbBiasByBatchNorm(GraphTransform):\n\n def __init__(self):\n super(AbsorbBiasByBatchNorm, self).__init__()\n self.inp_shape_map = {}\n self.collect_inp_shape_hooks = []\n\n def add_to_bias(self, module, tensor):\n if module.bias is not None:\n module.bias.data += tensor.view_as(module.bias)\n else:\n module.bias = torch.nn.Parameter(tensor)\n\n def absorb_biases(self, groups):\n for layer, bn, (next_layer_name, next_layer) in groups:\n cfactor = bn.running_mean - 3 * torch.sqrt(bn.running_var)\n zeroes = torch.zeros_like(cfactor).to(cfactor.device)\n cfactor = torch.where(cfactor > 0., cfactor, zeroes)\n if (cfactor > 0).any():\n self.add_to_bias(layer, -cfactor)\n broadcast_shape = [1] * next_layer.weight.ndim\n broadcast_shape[1] = cfactor.numel()\n cfactor = cfactor.view(broadcast_shape)\n cfactor = cfactor.expand(self.inp_shape_map[next_layer_name])\n next_layer_cfactor = next_layer(cfactor).transpose(0, 1)\n next_layer_cfactor = next_layer_cfactor.view(next_layer_cfactor.shape[0], -1)\n next_layer_cfactor = torch.mean(next_layer_cfactor, dim=1)\n self.add_to_bias(next_layer, next_layer_cfactor)\n self.inp_shape_map = {}\n\n def extract_groups(self, graph_model: GraphModule):\n groups = []\n for node in graph_model.graph.nodes:\n if (_is_supported_module(graph_model, node)\n and node.next.op == 'call_module'\n and isinstance(get_module(graph_model, node.next.target), _batch_norm)):\n node_next = node.next.next\n while _is_scale_invariant_module(graph_model, node_next) or _is_reshaping_op(node_next):\n node_next = node_next.next\n if _is_supported_module(graph_model, node_next):\n group = (\n get_module(graph_model, node.target), \n get_module(graph_model, node.next.target), \n (node_next.target, get_module(graph_model, node_next.target)))\n groups.append(group)\n return groups\n\n def collect_inp_shape_hook(self, module, inp, name):\n if name in self.inp_shape_map.keys():\n raise RuntimeError(\"Module called multiple times, not supported.\")\n if isinstance(inp, tuple):\n inp = inp[0]\n self.inp_shape_map[name] = [1] + list(inp.shape[1:])\n\n def collect_inp_shapes(self, model, inp):\n for name, module in model.named_modules():\n if isinstance(module, (_supported_layers)):\n hook_fn = partial(self.collect_inp_shape_hook, name=name)\n hook = module.register_forward_pre_hook(hook_fn)\n self.collect_inp_shape_hooks.append(hook)\n model(inp)\n for hook in self.collect_inp_shape_hooks:\n hook.remove()\n self.collect_inp_shape_hooks = []\n\n def apply(self, graph_model: GraphModule, inp):\n self.collect_inp_shapes(graph_model, inp)\n groups = self.extract_groups(graph_model)\n self.absorb_biases(groups)\n return graph_model","sub_path":"src/brevitas/graph/equalize.py","file_name":"equalize.py","file_ext":"py","file_size_in_byte":12213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"526025445","text":"# Copyright 2015 The Chromium Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\nimport base64\nimport json\nimport unittest\n\nimport mock\nimport webapp2\nimport webtest\n\nfrom dashboard import testing_common\nfrom dashboard import units_to_direction\nfrom dashboard import update_test_metadata\nfrom dashboard.models import anomaly\n\n\n_UNIT_JSON = json.dumps({\n 'description': 'foo',\n 'ms': {'improvement_direction': 'down'},\n 'score': {'improvement_direction': 'up'},\n})\n\n\ndef _MakeMockFetch(base64_encoded=True, malformed_json=False, status=200):\n \"\"\"Returns a mock fetch object that returns a canned response.\"\"\"\n def _MockFetch(unused_url): # pylint: disable=unused-argument\n response_text = _UNIT_JSON\n if malformed_json:\n response_text = 'this is not json'\n if base64_encoded:\n response_text = base64.b64encode(response_text)\n return testing_common.FakeResponseObject(status, response_text)\n return mock.MagicMock(side_effect=_MockFetch)\n\n\nclass UpdateTestMetadataTest(testing_common.TestCase):\n\n def setUp(self):\n super(UpdateTestMetadataTest, self).setUp()\n app = webapp2.WSGIApplication(\n [('/update_test_metadata',\n update_test_metadata.UpdateTestMetadataHandler)])\n self.testapp = webtest.TestApp(app)\n\n @mock.patch('google.appengine.api.urlfetch.fetch', _MakeMockFetch())\n def testGet_UpdatesImprovementDirection(self):\n self.testapp.get('/update_test_metadata')\n self.assertEqual(\n anomaly.DOWN,\n units_to_direction.GetImprovementDirection('ms'))\n self.assertEqual(\n anomaly.UP,\n units_to_direction.GetImprovementDirection('score'))\n self.assertEqual(\n anomaly.UNKNOWN,\n units_to_direction.GetImprovementDirection('does-not-exist'))\n\n @mock.patch('google.appengine.api.urlfetch.fetch',\n _MakeMockFetch(malformed_json=True))\n @mock.patch('logging.error')\n def testGet_MalformedJson_ReportsError(self, mock_logging_error):\n self.testapp.get('/update_test_metadata', status=500)\n self.assertEqual(\n anomaly.UNKNOWN,\n units_to_direction.GetImprovementDirection('ms'))\n self.assertEqual(\n anomaly.UNKNOWN,\n units_to_direction.GetImprovementDirection('score'))\n self.assertEqual(2, mock_logging_error.call_count)\n\n @mock.patch('google.appengine.api.urlfetch.fetch',\n _MakeMockFetch(status=500))\n @mock.patch('logging.error')\n def testGet_ErrorFetching_ReportsError(self, mock_logging_error):\n self.testapp.get('/update_test_metadata', status=500)\n self.assertEqual(\n anomaly.UNKNOWN,\n units_to_direction.GetImprovementDirection('ms'))\n self.assertEqual(\n anomaly.UNKNOWN,\n units_to_direction.GetImprovementDirection('score'))\n self.assertEqual(2, mock_logging_error.call_count)\n\n @mock.patch('google.appengine.api.urlfetch.fetch',\n _MakeMockFetch(base64_encoded=False))\n @mock.patch('logging.error')\n def testDownloadChromiumFile_BadEncoding(self, mock_logging_error):\n self.assertIsNone(\n update_test_metadata.DownloadChromiumFile('foo.json'))\n self.assertEqual(1, mock_logging_error.call_count)\n\n @mock.patch('google.appengine.api.urlfetch.fetch',\n _MakeMockFetch(status=400))\n @mock.patch('logging.error')\n def testDownloadChromiumFile_Non200Status(self, mock_logging_error):\n self.assertIsNone(\n update_test_metadata.DownloadChromiumFile('foo.json'))\n self.assertEqual(1, mock_logging_error.call_count)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"dashboard/dashboard/update_test_metadata_test.py","file_name":"update_test_metadata_test.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"101900975","text":"#DevScan\nfrom pysnmp.entity.rfc3413.oneliner import cmdgen\n\n#uCisco\nfrom pyasn1.type import univ\nimport pysnmp, socket\n\n\ndef DevScan(ip_add, snmp_comm='public', snmp_pass='', maker='cisco'):\n if maker == 'cisco':\n oids = {\n 'nei_ip' : '1.3.6.1.4.1.9.9.23.1.2.1.1.4', # neihbor's IP address from CISCO MIB\n 'nei_name' : '1.3.6.1.4.1.9.9.23.1.2.1.1.6', # neighbor's name from CISCO MIB\n 'nei_if' : '1.3.6.1.4.1.9.9.23.1.2.1.1.7', # neighbor's interface from CISCO MIB\n 'local_if' : '1.3.6.1.4.1.9.9.23.1.1.1.1.6', # local interface from CISCO MIB\n }\n \n cmdGen = cmdgen.CommandGenerator()\n \n errorIndication, errorStatus, errorIndex, varBindTable = cmdGen.bulkCmd(\n cmdgen.CommunityData(snmp_comm),\n cmdgen.UdpTransportTarget((ip_add, 161)),\n 0, 1,\n oids['nei_ip'], # neihbor's IP address\n oids['nei_name'], # neighbor's name\n oids['nei_if'], # interface where neighbor is connected\n oids['local_if'], # local interface\n )\n \n # Check for errors and print out results\n if errorIndication:\n #return(errorIndication)\n errormessage = 'Error at device ' + ip_add\n else:\n if errorStatus:\n #return(\n # print('%s at %s' % (\n # errorStatus.prettyPrint(),\n # errorIndex and varBinds[int(errorIndex)-1] or '?')\n # )\n #)\n return([(errorStatus, ' at', 'device ', ip_add)])\n else:\n #return(varBindTable)\n return(untangle(varBindTable, oids, maker))\n\n\ndef uCisco(snmp_response, oids):\n ans = list()\n #ans = [('Switch IP address', 'Switch Name', 'Local Interface', 'Remote Interface')]\n try:\n for i, j, k, l in snmp_response:\n m,n = i\n o,p = j\n q,r = k\n s,t = l\n if oids['nei_ip'] in str(m) and type(n) == pysnmp.proto.rfc1902.OctetString:\n try:\n ip_ad = socket.inet_ntoa(n.asOctets())\n ansip = str(ip_ad)\n except:\n ansip = \"0.0.0.0\"\n \n if oids['nei_name'] in str(o) and type(p) == pysnmp.proto.rfc1902.OctetString:\n try:\n ansdesc = str(p)\n except:\n ansdesc = 'Switch has no name'\n else:\n ansdesc = 'No info'\n \n if oids['nei_if'] in str(q) and type(r) == pysnmp.proto.rfc1902.OctetString:\n try:\n ansnint = str(r)\n except:\n ansnint = 'Magical remote interface...'\n else:\n ansnint = 'No info'\n\n if oids['local_if'] in str(s) and type(t) == pysnmp.proto.rfc1902.OctetString:\n try:\n anslint = str(t)\n except:\n anslint = 'Magical local interface...'\n else:\n anslint = 'No info'\n\n ans.append([ansip, ansdesc, anslint, ansnint])\n\n except TypeError:\n ans.append(('Something went bad: ' + str(snmp_response)))\n return(ans)\n\ndef untangle(snmp_response, oids, maker='cisco'):\n if maker == 'cisco':\n return(uCisco(snmp_response, oids))","sub_path":"corestuff/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"391781663","text":"from ipyannotations import text\nfrom unittest.mock import MagicMock\nfrom PIL import Image\nimport numpy as np\n\n\ndef test_submit_with_button(mocker):\n widget = text.ClassLabeller(options=[\"a\", \"b\"])\n submission_function: MagicMock = mocker.MagicMock()\n widget.on_submit(submission_function)\n\n btn = widget.control_elements.buttons[\"a\"].button\n\n widget.submit(btn)\n submission_function.assert_called_with(\"a\")\n\n\ndef test_submit_with_text_field(mocker):\n widget = text.ClassLabeller(options=[\"a\", \"b\"])\n submission_function = mocker.MagicMock()\n widget.on_submit(submission_function)\n\n widget.freetext_widget.value = \"test\"\n\n widget.submit(widget.freetext_widget)\n submission_function.assert_called_with(\"test\")\n\n\ndef test_that_displaying_images_doesnt_error():\n widget = text.ClassLabeller()\n widget.display(\"Hello.\")\n\n\ndef test_that_multiclass_submits_toggled_buttons(mocker):\n widget = text.MulticlassLabeller(options=[\"a\", \"b\"])\n widget.class_selector.buttons[0].button.value = True\n assert widget.data == [\"a\"]\n submission_function: MagicMock = mocker.MagicMock()\n widget.on_submit(submission_function)\n widget.submit()\n submission_function.assert_called_with([\"a\"])\n\n\ndef test_that_multiclass_doesnt_error_when_displaying():\n widget = text.MulticlassLabeller(options=[\"a\", \"b\"])\n widget.display(\"hello.\")\n\n\ndef test_that_sentiment_labeller_doesnt_error():\n widget = text.SentimentLabeller()\n widget.display(\"hello.\")\n\n\ndef test_that_sentiment_labeller_handles_keystrokes(mocker):\n widget = text.SentimentLabeller()\n widget.display(\"hello.\")\n submission_function: MagicMock = mocker.MagicMock()\n widget.on_submit(submission_function)\n for key, label in zip(\n [\"1\", \"2\", \"3\"], [\"negative\", \"neutral\", \"positive\"]\n ):\n event = {\"type\": \"keyup\", \"key\": key}\n submission_function.reset_mock()\n widget._handle_keystroke(event)\n submission_function.assert_called_once_with(label)\n # normal enter shouldnt trigger submission:\n submission_function.reset_mock()\n widget._handle_keystroke({\"type\": \"keyup\", \"key\": \"Enter\"})\n submission_function.assert_not_called()\n","sub_path":"tests/text/test_text_class_labellers.py","file_name":"test_text_class_labellers.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"288921964","text":"#!/usr/bin/env python\n\nimport requests\nfrom string import Template\nfrom time import strftime, time, sleep\nfrom json import load, dump\nfrom sys import exit\nfrom sms import smssend\nimport chkkan_settings as st\nimport os\n\nsms_failed = Template('The kannel on $kannel is failed ($err)')\nsms_restored = Template(\n 'The kannel on $kannel is OK now')\n\ncmk_name = os.uname()[1]\n\n\ndef log_message(message, hostname=cmk_name):\n print('{0} {1} check_kannel: {2}'.format(strftime('%b %d %H:%M:%S'),\n hostname,\n message))\n\n\nclass Lock:\n\n \"\"\"Check for lockfiles presense, if exist and old exit\"\"\"\n\n def __init__(self, lockfile, age=600):\n \"\"\" lockfile -> path to the file\n age -> file older than age seconds will be ignored and deleted\"\"\"\n\n self.age = age\n self.lockfile_exist = 1 if os.path.isfile(lockfile) else 0\n self.lockfile = lockfile\n\n def set(self):\n if self.lockfile_exist == 1:\n st = os.stat(self.lockfile)\n now = time()\n if (now - st.st_mtime) > self.age:\n os.remove(self.lockfile)\n else:\n return False\n f = open(self.lockfile, \"w\")\n f.close()\n self.lockfile_exist = 1\n return True\n\n def remove(self):\n if os.path.isfile(self.lockfile):\n os.remove(self.lockfile)\n\n\nclass State:\n\n \"\"\"There we save status between checks\"\"\"\n\n def __init__(self, kannels, jsonfile):\n \"\"\"Open status file, in case of trouble create a new one\"\"\"\n self.kannels = kannels\n self.jsonfile = jsonfile\n self.state = {}\n self.ltm = {}\n self.nodes = []\n try:\n fd = open(jsonfile)\n self.state = load(fd)\n for kannel in self.state:\n if kannel['type'] == 'ltm':\n self.ltm = kannel\n else:\n self.nodes.append(kannel)\n if kannel['hostname'] not in [k['hostname'] for k in self.kannels]:\n raise ValueError\n except (IOError, ValueError):\n fd = open(jsonfile, 'w')\n self.nodes = []\n self.state = kannels\n for kannel in self.state:\n if kannel['type'] == 'ltm':\n self.ltm = kannel\n else:\n self.nodes.append(kannel)\n dump(self.state, fd)\n fd.close()\n\n def getltm(self):\n return self.ltm\n\n def getnodes(self):\n return self.nodes\n\n def savestate(self):\n \"\"\"Save state of kannels to json file\"\"\"\n try:\n fd = open(self.jsonfile, 'w')\n dump([self.ltm, ] + self.nodes, fd)\n fd.close()\n except (IOError, ValueError):\n exit(1)\n\n\nclass Check:\n\n \"\"\"Check if kannel and sms aggregators are accessible\"\"\"\n\n def __init__(self, state):\n self.state = state.state\n\n def kannel(self, ltm):\n recovery = False\n\n for i in range(4):\n try:\n r = requests.get('http://{0}:13003/'.format(ltm['ip']))\n if r.status_code != 404:\n raise Exception\n else:\n alert = False\n except:\n ltm['last_error'] =\\\n 'Didnt get response from http://kannel:13000'\n alert = True\n sleep(5)\n\n if alert:\n ltm['fail'] = True\n message = sms_failed.substitute(\n kannel=ltm['hostname'],\n err=ltm['last_error'])\n log_message(message)\n\n if not alert and ltm['fail']:\n recovery = True\n\n return (alert, recovery)\n\n def aggs(self, kannel):\n \"\"\"Get status from kannel via http.\n if kannel response is not 200 return alert;\n if aggregator is not online return alert;\n if previos kannel check was failed and current is not\n than return recovery\"\"\"\n\n recovery = False\n\n for i in range(4):\n try:\n r = requests.get('http://{0}:13000/status.txt'.format(kannel['ip']))\n if r.status_code != 200:\n raise Exception\n else:\n alert = False\n except:\n kannel['last_error'] = 'Cant get status from kannel'\n alert = True\n\n aggrs_line_found = False\n aggs_states = {x: False for x in kannel['aggs']}\n\n for line in r.content.split('\\n'):\n if line.startswith('SMSC connections:'):\n aggrs_line_found = True\n continue\n if aggrs_line_found:\n aggr = line.split()\n if len(aggr) > 0 and aggr[0] in aggs_states and\\\n aggr[2] == \"(online\":\n aggs_states[aggr[0]] = True\n\n aggs_failed = []\n for aggr in aggs_states:\n if not aggs_states[aggr]:\n aggs_failed.append(aggr)\n kannel['last_error'] =\\\n 'The next aggregators ({0}) are failed'.format(\n aggs_failed)\n alert = True\n else:\n alert = False\n sleep(5)\n\n if alert:\n kannel['fail'] = True\n message = sms_failed.substitute(\n hostname=kannel['hostname'],\n err=kannel['last_error'])\n log_message(message)\n\n if not alert and kannel['fail']:\n recovery = True\n\n return (alert, recovery)\n\n\nif __name__ == \"__main__\":\n\n mylock = Lock(st.LOCKFILE)\n if not mylock.set():\n exit(1)\n\n state = State(st.KANNELS, st.STATEFILE)\n check = Check(state)\n ltm = state.getltm()\n nodes = state.getnodes()\n\n (alert, recovery) = check.kannel(ltm)\n\n if alert and ltm['last_sms_time'] <\\\n (int(strftime('%s')) - st.SMS_INTERVAL):\n sms_message = sms_failed.substitute(\n kannel=ltm['hostname'],\n err=ltm['last_error'])\n smssend(\n recipients=st.RECIPIENTS,\n message=sms_message,\n modem=st.MODEM,\n rate=st.MODEM_RATE)\n ltm['last_sms_time'] = int(strftime('%s'))\n\n if not alert and recovery:\n sms_message = sms_restored.substitute(\n kannel=ltm['hostname'])\n smssend(\n recipients=st.RECIPIENTS,\n message=sms_message,\n modem=st.MODEM,\n rate=st.MODEM_RATE)\n log_message(sms_message)\n ltm['fail'] = False\n ltm['last_sms_time'] = 0\n\n if not alert:\n for kannel in nodes:\n (alert, recovery) = check.aggs(kannel)\n if alert and kannel['last_sms_time'] <\\\n (int(strftime('%s')) - st.SMS_INTERVAL):\n sms_message = sms_failed.substitute(\n hostname=kannel['hostname'],\n err=kannel['last_error'])\n smssend(\n recipients=st.RECIPIENTS,\n message=sms_message,\n modem=st.MODEM,\n rate=st.MODEM_RATE)\n kannel['last_sms_time'] = int(strftime('%s'))\n\n if not alert and recovery:\n sms_message = sms_restored.substitute(\n kannel=kannel['hostname'],\n )\n smssend(\n recipients=st.RECIPIENTS,\n message=sms_message,\n modem=st.MODEM,\n rate=st.MODEM_RATE)\n log_message(sms_message)\n kannel['fail'] = False\n kannel['last_sms_time'] = 0\n\n state.savestate()\n mylock.remove()\n","sub_path":"check_kannel.py","file_name":"check_kannel.py","file_ext":"py","file_size_in_byte":7898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"350053523","text":"import os\nimport time\n\nimport pyautogui\nfrom .execution import (\n guarantee_img_click, spam_click_until_image_found, spam_click_until_image_gone, wait_until_image_found)\n\nIMAGE_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), \"scenes\")\n\n\ndef extract_scene_images(scene: str):\n DIR = os.path.join(IMAGE_DIR, scene)\n\n items = list(filter(\n lambda file: file.endswith(\".png\"),\n os.listdir(DIR)\n ))\n items.sort(\n key=lambda item: int(item.split(\".\")[0].split(\"-\")[0])\n )\n\n return list(map(\n lambda file: os.path.join(DIR, file),\n items\n ))\n\n\ndef execute_scene(scene: str):\n for img_path in extract_scene_images(scene):\n\n wait = img_path.split(\"/\")[-1].split(\".\")[0].split(\"-\")[-1] == \"w\"\n\n if wait:\n wait_until_image_found(img_path)\n else:\n spam_click_until_image_found(img_path)\n\n guarantee_img_click(img_path)\n\n time.sleep(0.5)\n","sub_path":"src/helpers/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"453004104","text":"# Look at the code. What do you think it will draw?\n# Run the code and then check you understand the code \n\n# Setup the turtle module \nimport turtle\n\n# create a graphics window\nmyScreen = turtle.Screen()\n\n# create a new turtle called myTurtle\nmyTurtle = turtle.Turtle()\n\n# The speed of the turtle can be changed 0-10\nmyTurtle.speed(0)\n\n# set number of repeats and radius of circle\nrepeats = 50\nradius = 5\n\n# loop over range of numbers\nfor i in range(repeats):\n myTurtle.circle(radius*i)\n\n# wait for mouseclick to close window\nmyScreen.exitonclick() \n","sub_path":"ImageManipulation/MoreAdvanced/circles1.py","file_name":"circles1.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"29647896","text":"# The Sudoku board could be partially filled, where empty cells are filled with\n# the character '.'.\n\n\nclass Solution:\n # @param {character[][]} board\n # @return {boolean}\n def isValidSudoku(self, board):\n used1 = [[False for i in range(10)] for j in range(9)]\n used2 = [[False for i in range(10)] for j in range(9)]\n used3 = [[False for i in range(10)] for j in range(9)]\n for i in range(9):\n for j in range(9):\n if board[i][j] != '.':\n num = ord(board[i][j]) - ord('0') - 1\n k = i / 3 * 3 + j / 3\n if used1[i][num] or used2[j][num] or used3[k][num]:\n return False\n used1[i][num] = used2[j][num] = used3[k][num] = True\n return True\n\ns = Solution()\ns.isValidSudoku([\".87654321\", \"2........\", \"3........\", \"4........\",\n \"5........\", \"6........\", \"7........\", \"8........\",\n \"9........\"])\n","sub_path":"036_Valid_Sudoku.py","file_name":"036_Valid_Sudoku.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"67582297","text":"# -*- coding: utf-8 -*-\nimport KBEngine\nfrom KBEDebug import *\nfrom interfaces.EntityCommon import EntityCommon\nimport GameConfigs\nimport Math\n\nTIMER_TYPE_ADD_TRAP = 1\n\n\nclass Account(KBEngine.Entity, EntityCommon):\n def __init__(self):\n KBEngine.Entity.__init__(self)\n EntityCommon.__init__(self)\n self.progress = 0\n self.getCurRoom().onEnter(self)\n self.curProp = None\n\n # region Matching\n def regProgress(self, tprogress):\n \"\"\"\n regLoadingProgress\n 客户端加载进度\n \"\"\"\n if self.progress < tprogress:\n self.progress = tprogress\n INFO_MSG(\"cell::account[%i] reg progress. entityCall:%s, progress:%s\" %\n (self.id, self.client, tprogress))\n if self.progress == GameConfigs.LOADING_FINISH_PROGRESS:\n self.getCurRoom().AccountloadingFinish(self.id)\n # endregion\n\n # region GetProps\n def regGetProps(self, prop_key, prop_type):\n \"\"\"\n 当前玩家获得道具\n :param prop_key: 道具的key\n :param prop_type: 所获得的道具类型\n \"\"\"\n DEBUG_MSG(\"Account id: %i, get props: %i.\" % (self.id, prop_type))\n # 传递给服务器,由服务器判断是否吃到道具\n self.getCurRoom().regCheckPropsAvailable(self, prop_key, prop_type)\n\n def onGetPropsBase(self, suc, prop_key, prop_type):\n \"\"\"\n on get props\n 获得道具回调\n :param suc: 道具是否可获得\n :param prop_key: 道具的key\n :param prop_type: 所获得的道具类型\n \"\"\"\n if suc == 0:\n self.curProp = prop_type\n # 通知所有客户端该玩家获得道具, 便于其他客户端隐藏相应道具\n self.allClients.onGetPropsClient(self.id, prop_key, prop_type)\n # endregion GetProps\n\n # region UseProps\n def regUseProp(self, target_id, prop_type):\n \"\"\"\n use prop\n 使用道具, 判断拥有道具后直接使用\n :param target_id: 目标玩家的id\n :param prop_type: 道具类型\n \"\"\"\n if prop_type == self.curProp:\n # 个人是否拥有相关道具,不需要房间总体判断\n self.curProp = None\n DEBUG_MSG(\"Account id: %i, use props: %i.\" % (self.id, prop_type))\n self.allClients.onUseProp(\n self.id, target_id, prop_type, Math.Vector3(self.position))\n\n if prop_type == GameConfigs.E_Prop_Shell:\n # 使用护罩时直接生效,\n # 地雷等由于不需要服务器同步,故不需要特殊处理\n self.regPropResult(self.id, self.id, prop_type, 0)\n\n \n def regPropResult(self, origin_id, target_id, prop_type, suc):\n \"\"\"\n use prop\n 使用道具的结果,主要是针对延时类道具,如导弹,烟雾等\n :param origin_id: 使用道具的玩家id\n :param target_id: 目标玩家id\n :param prop_type: 道具类型\n :param suc: 命中结果,0命中,1未命中\n \"\"\"\n # 传递给服务器,由服务器结算\n self.getCurRoom().regCheckPropsResult(self, origin_id, target_id, prop_type, suc)\n # endregion UseProps\n\n # region Destination\n def regReachDestination(self):\n \"\"\"\n reach destination\n 当前玩家到达终点\n \"\"\"\n INFO_MSG(\"cell::account[%i] reach destination. entityCall:%s\" %\n (self.id, self.client))\n\n self.getCurRoom().playerReachDestination(self.id)\n # endregion Destination\n\n # --------------------------------------------------------------------------------------------\n # Callbacks\n # --------------------------------------------------------------------------------------------\n\n def onTimer(self, tid, user_arg):\n \"\"\"\n KBEngine method.\n 引擎回调timer触发\n \"\"\"\n # DEBUG_MSG(\"%s::onTimer: %i, tid:%i, arg:%i\" % (self.className, self.id, tid, userArg))\n EntityCommon.onTimer(self, tid, user_arg)\n\n if TIMER_TYPE_ADD_TRAP == user_arg:\n self.addProximity(self.modelRadius, 0, 0)\n\n def onUpgrade(self):\n pass\n\n def onDestroy(self):\n \"\"\"\n KBEngine method.\n entity销毁\n \"\"\"\n DEBUG_MSG(\"Account::onDestroy: %i.\" % self.id)\n room = self.getCurRoom()\n\n if room:\n room.onLeave(self.id)\n # endregion\n","sub_path":"scripts/cell/Account.py","file_name":"Account.py","file_ext":"py","file_size_in_byte":4509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"571644069","text":"import sys\nimport datetime, time, json\nfrom clients.extended_clients.extended_clients import BinanceCli\n\n\nclass DataScraper:\n intervals = {\n 'binance': {\n \"1m\":60000, \"3m\":180000, \"5m\":300000, \"15m\":900000,\n \"30m\":1800000, \"1h\":3600000, \"2h\":7200000, \"4h\":14400000,\n \"6h\":21600000, \"8h\":28800000, \"12h\":43200000, \"1d\":86400000,\n \"3d\":259200000, \"1w\":604800000}\n }\n\n def show_help(self):\n print(\"to execute task list from file: python scraper.py fromfile task_filename\")\n print(\"to execute task from shell: python scraper.py run exchange start[milliseconds] end market interval result_filename\")\n\n def save_to_json(self, data, fname):\n with open(fname, 'w') as outfile:\n json.dump(data, outfile)\n\n def get_task_from_sys_argvs(self):\n task_type = sys.argv[1]\n if task_type == \"help\":\n self.show_help()\n if task_type == \"fromfile\":\n task_fname = sys.argv[2]\n tasks = self.get_task_queue_from_file(task_fname)\n\n for t in tasks:\n data = self.get_dataset(exchange=t['exchange'], start=t['start'], end=t['end'], market=t['market'], interval=t['interval'])\n self.save_to_json(data, f\"{t['task_id']}.json\")\n\n if task_type == \"run\":\n exchange, start, end, market, interval, fname = sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7]\n data = self.get_dataset(exchange=exchange, start=start, end=end, market=market, interval=interval)\n self.save_to_json(data, fname)\n\n def get_task_queue_from_file(self, fname):\n with open(fname) as f:\n queue = json.load(f)\n return queue\n\n def get_cli(self, exchange, *args, **kwargs):\n if exchange == 'binance':\n return BinanceCli(*args, **kwargs)\n\n def get_dataset(self, exchange=None, market=None, start=None, end=None, interval='1m', sleep_interval=0):\n curr_start, total_result, curr_end = None, [], round(datetime.datetime.now().timestamp() * 1000) if end is None else int(end)\n\n while curr_start is None or curr_end > int(start):\n kwargs = {'symbol': market, 'interval': interval}\n if not (curr_start is None):\n kwargs['start'] = int(curr_start)\n if not (curr_end is None):\n kwargs['end'] = int(curr_end)\n\n result, result_kwargs = self.get_cli(exchange).get_candle_history(**kwargs)\n time.sleep(sleep_interval)\n total_result = total_result + result\n\n time_difference = len(result)*self.intervals[exchange][interval]\n\n if result_kwargs.get('make_break') or len(result) == 0:\n break\n\n if curr_start is None:\n curr_start = curr_end\n curr_end -= time_difference\n curr_start -= (time_difference + min(time_difference, curr_end - int(start)))\n else:\n curr_end -= time_difference\n curr_start -= min(time_difference, curr_end - int(start))\n\n sorted_result = sorted(total_result, key=(lambda x:x[0]))\n # cutting redundant candles\n result = []\n for candle in sorted_result:\n if candle[0] >= start and candle[0] <= end:\n result.append(candle)\n return result\n\n\nif __name__ == \"__main__\":\n DataScraper().get_task_from_sys_argvs()\n\n\n\n\n\n\n","sub_path":"coding/market_price_change_risk_test/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"627045179","text":"from miniworldmaker import *\n\n\nclass MyBoard(TiledBoard):\n def __init__(self):\n super().__init__(tile_size=40, columns=29, rows=1, tile_margin=0)\n robot1 = Robot()\n robot1.add_image(\"images/robo_green.png\")\n self.add_to_board(robot1, position=(0, 0))\n robot2 = Robot()\n robot2.add_image(\"images/robo_yellow.png\")\n robot2.turn_left(180)\n self.add_to_board(robot2, position=(28, 0))\n self.add_image(path=\"images/water.png\")\n\n\nclass Explosion(Token):\n def __init__(self):\n super().__init__()\n self.add_image(\"images/explosion.png\")\n\n\nclass Robot(Actor):\n def __init__(self):\n super().__init__()\n\n def act(self):\n self.move()\n other = self.sensing_token(distance=0, token=Robot)\n if other:\n explosion = Explosion()\n self.board.add_to_board(explosion, position=self.position)\n self.remove()\n other.remove()\n\n\nboard = MyBoard()\nboard.show()\n","sub_path":"examples/moving/thecrash.py","file_name":"thecrash.py","file_ext":"py","file_size_in_byte":996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"86917828","text":"#!/usr/bin/env python\nfrom setuptools import setup, find_packages\n\nreadme = open(\"README.rst\").read()\n\nsetup(\n\tname = \"plantmeter\",\n\tversion = \"1.7.3\",\n\tdescription =\n\t\t\"OpenERP module and library to manage multisite energy generation\",\n\tauthor = \"Som Energia SCCL\",\n\tauthor_email = \"info@somenergia.coop\",\n\turl = 'https://github.com/Som-Energia/plantmeter',\n\tlong_description = readme,\n\tlicense = 'GNU General Public License v3 or later (GPLv3+)',\n\tpackages=find_packages(exclude=['*[tT]est*']),\n\tscripts=[\n#\t\t'scripts/genkwh_plants.py',\n#\t\t'scripts/genkwh_mtc.py',\n\t\t],\n\tinstall_requires=[\n 'pymongo<3.0',\n 'numpy',\n 'xlrd',\n 'yamlns',\n 'pytz',\n 'erppeek',\n 'consolemsg',\n 'mock',\n 'b2btest',\n\t],\n\tinclude_package_data = True,\n\ttest_suite = 'plantmeter',\n#\ttest_runner = 'colour_runner.runner.ColourTextTestRunner',\n\tclassifiers = [\n\t\t'Programming Language :: Python',\n\t\t'Programming Language :: Python :: 3',\n\t\t'Topic :: Software Development :: Libraries :: Python Modules',\n\t\t'Intended Audience :: Developers',\n\t\t'Development Status :: 2 - Pre-Alpha',\n\t\t'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n\t\t'Operating System :: OS Independent',\n\t],\n)\n\n","sub_path":"pypi_install_script/plantmeter-1.7.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"202762598","text":"import json\n\nclass template_39ask:\n\tdef __init__(self):\n\t\tself.departments = [313, 320, 321, 322, 309, 3157, 323, 319465592, 3165, 311, 3162, 3166, 3163, 27]\n\t\tself.url_list_url = 'http://ask.39.net/news/{}-{}.html'\n\t\tself.data_base_url = 'http://ask.39.net'\n\t\tself.loaded_flag = 'selected'\n\t\tself.url_loaded_flag = 'list_tag'\n\t\tself.template_name = '39ask'\n\n\tdef extract_urls(self, browser):\n\t\txpath = '//span[@class=\"a_l\"]/p/a'\n\t\turls = [var.get_attribute('href') for var in browser.find_elements_by_xpath(xpath)]\n\t\tif len(urls) < 1:\n\t\t\treturn None\n\t\treturn urls\n\n\tdef extract_text(self, browser):\n\t\tdepartments_xpath = '//div[@class=\"sub\"]/span[not(@class)]/a'\n\t\ttitle_xpath = '//p[@class=\"ask_tit\"]'\n\t\tpatient_infos_xpath = '//p[@class=\"mation\"]/span'\n\t\tquestion_content_xpath = '//p[@class=\"ask_tit\"]'\n\t\tquestion_time_xpath = '//p[@class=\"txt_nametime\"]/span[2]'\n\t\tlabels_xpath = '//p[@class=\"txt_label\"]/span/a'\n\t\tdoctor_page_links_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doctor_all\"]/div[@class=\"doc_img\"]/a'\n\t\tdoctor_names_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doctor_all\"]/div[@class=\"doc_txt\"]/p[@class=\"doc_xinx\"]/span[@class=\"doc_name\"]'\n\t\tdoctor_other_infos_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doctor_all\"]/div[@class=\"doc_txt\"]/p[@class=\"doc_xinx\"]/span[@class=\"doc_yshi\"]'\n\t\tdoctor_specialties_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doctor_all\"]/div[@class=\"doc_txt\"]/p[@class=\"doc_sc\"]/span'\n\t\tdoctor_answers_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/p[@class=\"sele_txt\"]'\n\t\tdoctor_mids_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doctor_all\"]'\n\t\tanswer_times_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doc_t_strip\"]/div[@class=\"zwAll\"]/p[@class=\"doc_time\"]'\n\t\tfollow_up_roles_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doc_t_strip\"]/div[@class=\"zwenall\"]/div[@class=\"doczw\"]/span[@class=\"zw1\"]'\n\t\tfollow_up_contents_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doc_t_strip\"]/div[@class=\"zwenall\"]/div[@class=\"doczw\"]/span[@class=\"zw2\"]'\n\t\tfollow_up_mids_xpath = '//div[@class=\"selected\"]/div[contains(@class, \"sele_all\")]/div[@class=\"doc_t_strip\"]/div[@class=\"zwenall\"]/div[@class=\"doczw\"]/span[@class=\"zw1\"]/parent::div[contains(@class, \"sele_all\")]/div[class=\"doctor_all\"]'\n\t\tnum_sele_xpath = '//p[@class=\"sele_img\"]'\n\n\t\tjson_entry = {}\n\t\tdepartments = browser.find_elements_by_xpath(departments_xpath)\n\t\tjson_entry['department'] = '>'.join([var.text for var in departments])\n\t\tjson_entry['title'] = browser.find_element_by_xpath(title_xpath).text\n\t\tjson_entry['patient_infos'] = [var.text for var in browser.find_elements_by_xpath(patient_infos_xpath)]\n\t\tjson_entry['question_content'] = browser.find_element_by_xpath(question_content_xpath).text\n\t\tjson_entry['question_time'] = browser.find_element_by_xpath(question_time_xpath).text\n\t\tjson_entry['labels'] = '\\t'.join([var.text for var in browser.find_elements_by_xpath(labels_xpath)])\n\t\tdoctor_page_links = browser.find_elements_by_xpath(doctor_page_links_xpath)\n\t\tdoctor_other_infos = browser.find_elements_by_xpath(doctor_other_infos_xpath)\n\t\tdoctor_specialties = browser.find_elements_by_xpath(doctor_specialties_xpath)\n\t\tdoctor_answers = browser.find_elements_by_xpath(doctor_answers_xpath)\n\t\tdoctor_mids = browser.find_elements_by_xpath(doctor_mids_xpath)\n\t\tanswer_times = browser.find_elements_by_xpath(answer_times_xpath)\n\t\tnum_sele = browser.find_elements_by_xpath(num_sele_xpath)\n\t\tnum_sele = int(num_sele[0].text.split('(')[1][0]) if len(num_sele) > 0 else 0\n\t\tdoctor_specialties = [var.text for var in doctor_specialties]\n\t\tdoctor_specialties = doctor_specialties + [''] * (len(doctor_mids) - len(doctor_specialties))\n\t\tjson_entry['answers'] = [{'mid': doctor_mids[i].get_attribute('mid'), \n\t\t\t\t\t\t\t\t'adopted': str(i < num_sele),\n\t\t\t\t\t\t\t\t'page_link': doctor_page_links[i].get_attribute('href'),\n\t\t\t\t\t\t\t\t# 'other_info': doctor_other_infos[2 * i].text + '\\t' + doctor_other_infos[2 * i + 1].text,\n\t\t\t\t\t\t\t\t# 'specialty': doctor_specialties[i],\n\t\t\t\t\t\t\t\t'answer': doctor_answers[i].text,\n\t\t\t\t\t\t\t\t'answer_time': answer_times[i].text} for i in range(len(doctor_mids))]\n\t\tfollow_up_mids = browser.find_elements_by_xpath(follow_up_mids_xpath)\n\t\tfollow_up_roles = browser.find_elements_by_xpath(follow_up_roles_xpath)\n\t\tfollow_up_contents = browser.find_elements_by_xpath(follow_up_contents_xpath)\n\t\tfollow_ups = [(follow_up_mids[i].get_attribute('mid'), follow_up_roles[i].text + ':' + follow_up_contents[i].text) for i in range(len(follow_up_mids))]\n\t\tdistinct_mids = list(set([var.get_attribute('mid') for var in follow_up_mids]))\n\t\tfollow_ups_grouped = []\n\t\tfor mid in distinct_mids:\n\t\t\tcontent = ''\n\t\t\tfor follow_up in follow_ups:\n\t\t\t\tif follow_up[0] == mid:\n\t\t\t\t\tcontent += (follow_up[1] + '\\n')\n\t\t\tfollow_ups_grouped.append({mid: content})\n\t\tjson_entry['follow_ups'] = follow_ups_grouped\n\t\treturn json_entry\n","sub_path":"src/template_39ask.py","file_name":"template_39ask.py","file_ext":"py","file_size_in_byte":5126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"207167468","text":"\"\"\"Setup file and install script for BaseVar.\n\nVersion 1.0.0 (Dec 16, 2018)\nCopyright (C) 2018 Shujia Huang \n\"\"\"\nimport os\n\ntry:\n from setuptools import setup, find_packages\n _has_setuptools = True\nexcept ImportError:\n from distutils.core import setup, find_packages\n\n\nDESCRIPTION = \"BaseVar: A python software for calling variants from ultra low pass WGS data.\"\nDISTNAME = 'basevar'\nMAINTAINER = 'Shujia Huang & Siyang Liu'\nMAINTAINER_EMAIL = 'huangshujia9@gmail.com'\nURL = 'https://github.com/ShujiaHuang/basevar'\nLICENSE = 'BSD (3-clause)'\nDOWNLOAD_URL = 'https://github.com/ShujiaHuang/basevar'\nVERSION = \"0.0.1.3\"\n\n\nif __name__ == \"__main__\":\n\n # requirements_file = os.path.split(os.path.realpath(__file__))[0] + \"/requirements.txt\"\n long_description = os.path.split(os.path.realpath(__file__))[0] + \"/README.rst\"\n\n # requirements = []\n # with open(requirements_file) as I:\n # for line in I:\n # requirements.append(line.strip())\n\n setup(\n name=DISTNAME,\n version=VERSION,\n author=MAINTAINER,\n author_email=MAINTAINER_EMAIL,\n maintainer=MAINTAINER,\n maintainer_email=MAINTAINER_EMAIL,\n description=DESCRIPTION,\n long_description=(open(long_description).read()),\n license=LICENSE,\n url=URL,\n download_url=DOWNLOAD_URL,\n packages=find_packages(),\n include_package_data=True,\n # install_requires=requirements,\n install_requires=[\n 'numpy==1.15.4',\n 'pysam==0.12.0.1',\n 'scikit-learn==0.20.2',\n 'scipy==1.1.0'\n ],\n\n # scripts=[],\n entry_points={\n\n 'console_scripts': [\n 'basevar = basevar.BaseVar:main'\n ]\n },\n classifiers=[\n 'Intended Audience :: Science/Research',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.7',\n 'License :: OSI Approved :: BSD License',\n 'Topic :: Scientific/Engineering :: Bio-Informatics',\n 'Operating System :: POSIX',\n 'Operating System :: POSIX :: Linux',\n 'Operating System :: MacOS']\n )\n","sub_path":"pypi_install_script/basevar-0.0.1.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"138363938","text":"from behave import *\nimport requests\nimport json\nimport re\nimport jsonpath_rw_ext as jp\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom config.constants import *\nfrom zaid.nasa_asteroids.config.constants import Constants\nimport math\n\n# No need for global variables in Steps files. Use context.{some_variable_name}.\n\n# _result = []\n# _url = \"\"\n# _method = \"\"\n\n\n\"\"\"\n\nNOTES: \n\n1) Make all function names as descriptive as possible, try and avoid default 'step_impl'\n\n2) We'll use regex for all step matching. \n\n3) Python conventionally uses snake_case\n\n\"\"\"\n\n\n@given(u'the api service is for : \"{endPoint}\" stocks')\ndef step_impl(context, endPoint):\n if endPoint == \"SNAP,fb\":\n # store endpoints somewhere else, call them by name\n context.url = Constants.FULL_URL + endPoint\n else:\n assert False, \"endpoint url is not provided\"\n\n\n@when(u'the service method is \"{method}\"')\ndef step_impl(context, method):\n context.method = method\n\n\n@then(u'the response code should be \"{status}\"')\ndef step_impl(context, status):\n context.esponse = requests.request(context.method, context.url)\n context.result = context.response.json()\n # Anything we want to \"archive\" and validate later just put into context\n assert context.response.status_code is int(status)\n\n\n@then(u'it should return the datafor \"{num}\" company')\ndef step_impl(context, num):\n context.total_number = len(context.result)\n assert str(context.total_number) == str(num)\n\n\n@then(u'verify required fields')\ndef step_impl(context):\n errors = []\n counter = 1\n for stock in context.result:\n err = []\n if type(stock['symbol']) is None:\n err.append('stock in index ' + str(counter) +\n ' dose not have symbol')\n if type(stock['price']) is None:\n err.append('stock in index ' + str(counter) +\n ' dose not have price')\n counter += 1\n if err != []:\n errors.append(err)\n if errors != []:\n assert False, errors\n\n\n@given(u'we have the data from the api')\ndef step_impl(context):\n assert context.result is not None\n\n\n@then(u'the UI should have the same data as the api')\ndef step_impl(context):\n errors = []\n counter = 1\n\n # there has to be a generic method for this\n def floatDigits(f, n):\n return math.floor(f * 10 ** n) / 10 ** n\n\n # Where are all these CONSTANT values declared?\n for stock in context.result:\n err = []\n browser = Common.chrome()\n browser.get(Constants.YAHOO_URL)\n # All these elements should live on a Page Object\n browser.find_element(\n By.CSS_SELECTOR, SEARCH_INPUT_locator).send_keys(stock[\"symbol\"])\n browser.find_element(By.CSS_SELECTOR, SEARCH_BUTTON_locator).click()\n WebDriverWait(browser, 10).until(\n EC.presence_of_element_located((By.XPATH, PRICE_locator)))\n arr = []\n for x in range(5):\n time.sleep(2)\n price = browser.find_element(By.XPATH, PRICE_locator).text\n arr.append(floatDigits(float(price), 2))\n\n if round(float(stock[\"price\"]), 2) not in arr:\n err.append([\"The two prices is not equal for \" + stock[\"symbol\"],\n arr, round(float(stock[\"price\"]), 2)])\n\n browser.quit()\n if err != []:\n errors.append(err)\n counter += 1\n if errors != []:\n assert False, errors\n","sub_path":"adam/yahoo_finance/features/steps/steps.py","file_name":"steps.py","file_ext":"py","file_size_in_byte":3659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"517371927","text":"from django.shortcuts import render\nfrom django.http.response import HttpResponse\nfrom curdapp.forms import Productupdateform, Productdeleteform\nfrom .models import ProductData\nfrom .forms import ProductForm\n# Create your views here.\ndef main_page(request):\n return render(request,'main_page.html')\ndef product_insert_view(request):\n if request.method==\"POST\":\n iform=ProductForm(request.POST)\n if iform.is_valid():\n product_id=request.POST.get('product_id')\n product_name=request.POST.get('product_name')\n product_cost=request.POST.get('product_cost')\n product_color=request.POST.get('product_color')\n product_class=request.POST.get('product_class')\n data=ProductData(\n product_id=product_id,\n product_name=product_name,\n product_cost=product_cost,\n product_color=product_color,\n product_class=product_class\n )\n data.save()\n iform=ProductForm()\n return render(request,'insert.html',{'iform':iform})\n\n else:\n iform=ProductForm()\n return render(request,'insert.html',{'iform':iform})\ndef product_retrieve(request):\n products=ProductData.objects.all()\n return render(request,'retrieve.html',{'products':products})\ndef product_update(request):\n if request.method==\"POST\":\n uform=Productupdateform(request.POST)\n if uform.is_valid():\n product_id=request.POST.get('product_id')\n product_cost=request.POST.get('product_cost')\n pid=ProductData.objects.filter(product_id=product_id)\n if not pid:\n return HttpResponse(\"Product is Not available\")\n else:\n pid.update(product_cost=product_cost)\n uform=Productupdateform()\n return render(request,'update.html',{'uform':uform})\n\n else:\n return HttpResponse(\"user invalid data\")\n else:\n uform=Productupdateform()\n return render(request,'update.html',{'uform':uform})\ndef product_delete_view(request):\n if request.method==\"POST\":\n dform=Productdeleteform(request.POST)\n if dform.is_valid():\n product_id=request.POST.get('product_id')\n pid=ProductData.objects.filter(product_id=product_id)\n if not pid:\n return HttpResponse(\"Product is Not Available\")\n else:\n pid.delete()\n dform=Productdeleteform()\n return render(request,'delete.html',{'dform':dform})\n else:\n dform=Productdeleteform()\n return render(request,'delete.html',{'dform':dform})","sub_path":"curdpro/curdapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"505541650","text":"from Authentication import Auth\nimport os\n\ndef fetch_replies_from_tweet(tweet_id):\n\tauth_instance = Auth(\"Nr8NWrnIr1huPmlTy3OFfizCl\", \"94MmEh9HSAGIiolIGSb6hBXXGlFM9weMZNrGjKs6hhJEoNfolr\",\"835036132773605377-ChnMv7F4s7DO6eG1BbKVafgZjYBf1at\",\"jiKWm8tUzXAXuY0ovxc7XWnsbdGj60frsBLUdVIuya7Hr\")\n\tapi = auth_instance.authorize()\n\n\ttweet = api.get_status(tweet_id)\n\tprint(tweet)\n\n\nif __name__ == '__main__':\n\t\tfetch_replies_from_tweet(\"835839191388991488\")\t\n\n\n\n","sub_path":"twitter/fetch_replies_from_tweet.py","file_name":"fetch_replies_from_tweet.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"130640008","text":"#!/usr/bin/env python3\n\nimport sqlite3 #is module \nconn = sqlite3.connect('example.db') #create database whos name is example.db\nc = conn.cursor() #to check or read rows one by one\n\n\n#create table\nc.execute('''create table stocks (date text, trans text,symbol text , qty real ,price real)''')\n\n#insert a row of data \nc.execute(\"insert into stocks values('2005-01-05','buy','RHAT',10,14)\")\nc.execute(\"insert into stocks values('2006-01-08','buy','LT',19,54)\")\n\n#save (comit) the chaanges\n\nconn.commit()\n\n#need to close the connection \n\nconn.close()\n","sub_path":"sqlite3_db.py/sqlite3_eg_db.py","file_name":"sqlite3_eg_db.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"124137118","text":"#!/usr/bin/env python\n# Filename: inference \n\"\"\"\nintroduction:\n\nauthors: Huang Lingcao\nemail:huanglingcao@gmail.com\nadd time: 22 August, 2019\n\"\"\"\n\nfrom modeling.deeplab import DeepLab\nimport torch\n\nimport numpy as np\n\nimport os\nimport cv2\n\nimport dataloaders.custom_transforms as custom_transforms\n\ndef inference_A_sample_image(img_path, model_path,num_classes,backbone,output_stride,sync_bn,freeze_bn):\n\n\n # read image\n image = cv2.imread(img_path)\n\n # print(image.shape)\n image = np.array(image).astype(np.float32)\n # Normalize pascal image (mean and std is from pascal.py)\n mean = (0.485, 0.456, 0.406)\n std = (0.229, 0.224, 0.225)\n image /=255\n image -= mean\n image /= std\n\n # swap color axis because\n # numpy image: H x W x C\n # torch image: C X H X W\n image = image.transpose((2, 0, 1))\n\n # to 4D, N=1\n image = image.reshape(1, image.shape[0],image.shape[1],image.shape[2])\n image = torch.from_numpy(image) #.float()\n\n\n model = DeepLab(num_classes=num_classes,\n backbone=backbone,\n output_stride=output_stride,\n sync_bn=sync_bn,\n freeze_bn=freeze_bn,\n pretrained=True) # False\n\n if torch.cuda.is_available() is False:\n device = torch.device('cpu')\n else:\n device = None # need added\n\n # checkpoint = torch.load(model_path,map_location=device)\n # model.load_state_dict(checkpoint['state_dict'])\n checkpoint = torch.load('resnet101-5d3b4d8f.pth', map_location=device)\n model.load_state_dict(checkpoint['state_dict'])\n\n # for set dropout and batch normalization layers to evaluation mode before running inference.\n # Failing to do this will yield inconsistent inference results.\n model.eval()\n\n with torch.no_grad():\n output = model(image)\n\n out_np = output.cpu().data.numpy()\n\n pred = np.argmax(out_np, axis=1)\n\n pred = pred.reshape(pred.shape[1],pred.shape[2])\n\n # save result\n cv2.imwrite('output.jpg',pred)\n\n test = 1\n\n\n\nif __name__ == '__main__':\n import argparse\n parser = argparse.ArgumentParser(description=\"PyTorch DeeplabV3Plus Inference\")\n parser.add_argument('--img_path', type=str,\n help='the path to an image (not big image like a remote sensing image)')\n\n parser.add_argument('--model_path', type=str,default='model_best.pth.tar', #deeplab-resnet.pth.tar\n help='the path to an image')\n\n args = parser.parse_args()\n\n inference_A_sample_image('2009_001138.jpg',args.model_path,21,'resnet',16,False,False)\n\n # inference_A_sample_image('2011_002730.jpg', args.model_path, 21, 'resnet', 16, False, False)\n\n # inference_A_sample_image('2010_004365.jpg', args.model_path, 21, 'resnet', 16, False, False)\n\n\n\n\n\n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"283035343","text":"import os\r\nimport glob\r\nimport cv2\r\nimport numpy as np\r\nimport imutils\r\n\r\n#FUNCTION: return skin segmented images\r\ndef skin_segmentation(image):\r\n # define the upper and lower boundaries of the HSV pixel\r\n # intensities to be considered 'skin'\r\n lower = np.array([0, 48, 80], dtype = \"uint8\")\r\n upper = np.array([20, 255, 255], dtype = \"uint8\")\r\n \r\n # resize the frame, convert it to the HSV color space,\r\n # and determine the HSV pixel intensities that fall into\r\n # the speicifed upper and lower boundaries\r\n frame = imutils.resize(image, width = 400)\r\n converted = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n skinMask = cv2.inRange(converted, lower, upper)\r\n # apply a series of erosions and dilations to the mask\r\n # using an elliptical kernel\r\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))\r\n skinMask = cv2.erode(skinMask, kernel, iterations = 2)\r\n skinMask = cv2.dilate(skinMask, kernel, iterations = 2)\r\n # blur the mask to help remove noise, then apply the\r\n # mask to the frame\r\n skinMask = cv2.GaussianBlur(skinMask, (3, 3), 0)\r\n skin = cv2.bitwise_and(frame, frame, mask = skinMask)\r\n # show the skin in the image along with the mask\r\n cv2.imshow(\"images\", np.hstack([frame, skin]))\r\n return skin\r\n\r\n# SAVE SEGMENTED IMAGES\r\nimport glob\r\nall_imgs = set(glob.glob('all_images/*/*/*'))\r\nprint(glob.glob('all_images/*/*/*'))\r\n\r\nimport os\r\n#path = os.path('all_images\\\\original\\\\')\r\n\r\npath_original = 'all_images/original'\r\npath_skin_segmentation = 'all_images/segmented_image'\r\n\r\n#FUNCTION: create directory if not existing\r\ndef create_dir(directory):\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n#make directory for segmented images\r\ncreate_dir(path_skin_segmentation)\r\n\r\n#FUNCTION: get all subdirectories in a directory\r\ndef get_subdirectory(current_dir):\r\n return [os.path.basename(x[0]) for x in os.walk(current_dir)][1:]\r\n#subdirectories in path_original\r\n#print(get_subdirectory(path_original))\r\n\r\n#FUNCTION: save image at path\r\ndef save_image(path, image):\r\n cv2.imwrite(path, image)\r\n \r\n#apply skin segmentation on each image\r\nfor dirname in os.listdir(path_original):\r\n current_path = os.path.join(path_original, dirname)\r\n for filename in os.listdir(current_path):\r\n# print(filename,path_skin_segmentation+'/'+dirname)\r\n img = cv2.imread(os.path.join(current_path, filename))\r\n skin = skin_segmentation(img)\r\n create_dir(path_skin_segmentation+'/'+dirname+'/train')\r\n create_dir(path_skin_segmentation+'/'+dirname+'/test')\r\n save_image(path_skin_segmentation+'/'+dirname+'/'+filename,skin)\r\n\r\n","sub_path":"Project/skin segmentation.py","file_name":"skin segmentation.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"518840806","text":"\"\"\"\nCreates SSL/TLS certificates in Amazon Web Services for Route53-managed domain\nnames.\n\"\"\"\n\n\nfrom awscertr.domain_certr import DomainCertr\n\ndef request(domain, include_subdomains=False, region=None):\n \"\"\"\n Requests a certificate and waits for it to be issued.\n\n If the certificate has already been created then running this will just\n wait for it to be issued.\n\n If the certificate has already been issued then this will just return its\n ARN.\n\n Args:\n domain (str): Domain name.\n include_subdomains (bool, optional): Whether or not to include a\n subdomain wildcard on the\n certificate.\n region (str, optional): Amazon Web Services region in\n which to create the certificate.\n\n Returns:\n str: ARN of the issued certificate.\n \"\"\"\n\n certr = DomainCertr(domain=domain,\n include_subdomains=include_subdomains,\n region=region)\n certr.request()\n return certr.certificate_arn\n","sub_path":"awscertr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"204308163","text":"from astropy import cosmology as cosmo\n\nimport autofit as af\nfrom autolens import exc\nfrom autolens.array import mask as msk\nfrom autolens.lens import lens_fit\nfrom autolens.model.inversion import pixelizations as pix\nfrom autolens.pipeline.phase import phase_extensions\nfrom autolens.pipeline.phase import phase\n\n\ndef default_mask_function(image):\n return msk.Mask.circular(\n shape=image.shape, pixel_scale=image.pixel_scale, sub_size=1, radius_arcsec=3.0\n )\n\n\ndef isinstance_or_prior(obj, cls):\n if isinstance(obj, cls):\n return True\n if isinstance(obj, af.PriorModel) and obj.cls == cls:\n return True\n return False\n\n\n# noinspection PyAbstractClass\nclass Analysis(phase.AbstractAnalysis):\n @property\n def lens_data(self):\n raise NotImplementedError()\n\n def check_positions_trace_within_threshold_via_tracer(self, tracer):\n\n if (\n self.lens_data.positions is not None\n and self.lens_data.positions_threshold is not None\n ):\n\n traced_positions_of_planes = tracer.traced_positions_of_planes_from_positions(\n positions=self.lens_data.positions\n )\n\n fit = lens_fit.LensPositionFit(\n positions=traced_positions_of_planes[-1],\n noise_map=self.lens_data.pixel_scale,\n )\n\n if not fit.maximum_separation_within_threshold(\n self.lens_data.positions_threshold\n ):\n raise exc.RayTracingException\n\n def check_inversion_pixels_are_below_limit_via_tracer(self, tracer):\n\n if self.lens_data.inversion_pixel_limit is not None:\n pixelizations = list(filter(None, tracer.pixelizations_of_planes))\n if pixelizations:\n for pixelization in pixelizations:\n if pixelization.pixels > self.lens_data.inversion_pixel_limit:\n raise exc.PixelizationException\n\n\nclass Result(phase.AbstractResult):\n @property\n def most_likely_fit(self):\n\n hyper_image_sky = self.analysis.hyper_image_sky_for_instance(\n instance=self.constant\n )\n\n hyper_background_noise = self.analysis.hyper_background_noise_for_instance(\n instance=self.constant\n )\n\n return self.analysis.lens_imaging_fit_for_tracer(\n tracer=self.most_likely_tracer,\n hyper_image_sky=hyper_image_sky,\n hyper_background_noise=hyper_background_noise,\n )\n\n @property\n def mask(self):\n return self.most_likely_fit.mask\n\n @property\n def positions(self):\n return self.most_likely_fit.positions\n\n @property\n def pixelization(self):\n for galaxy in self.most_likely_fit.tracer.galaxies:\n if galaxy.pixelization is not None:\n return galaxy.pixelization\n\n @property\n def most_likely_pixelization_grids_of_planes(self):\n return self.most_likely_tracer.pixelization_grids_of_planes_from_grid(\n grid=self.most_likely_fit.grid\n )\n\n\nclass MetaDataFit:\n def __init__(\n self,\n variable,\n sub_size=2,\n signal_to_noise_limit=None,\n positions_threshold=None,\n mask_function=None,\n inner_mask_radii=None,\n pixel_scale_interpolation_grid=None,\n pixel_scale_binned_cluster_grid=None,\n inversion_uses_border=True,\n inversion_pixel_limit=None,\n is_hyper_phase=False\n ):\n self.is_hyper_phase = is_hyper_phase\n self.variable = variable\n self.sub_size = sub_size\n self.signal_to_noise_limit = signal_to_noise_limit\n self.positions_threshold = positions_threshold\n self.mask_function = mask_function\n self.inner_mask_radii = inner_mask_radii\n self.pixel_scale_interpolation_grid = pixel_scale_interpolation_grid\n self.pixel_scale_binned_cluster_grid = pixel_scale_binned_cluster_grid\n self.inversion_uses_border = inversion_uses_border\n self.inversion_pixel_limit = (\n inversion_pixel_limit or\n af.conf.instance.general.get(\n \"inversion\",\n \"inversion_pixel_limit_overall\",\n int\n )\n )\n self.hyper_noise_map_max = af.conf.instance.general.get(\n \"hyper\", \"hyper_noise_map_max\", float\n )\n\n def setup_phase_mask(self, data, mask):\n\n if self.mask_function is not None:\n mask = self.mask_function(image=data.image, sub_size=self.sub_size)\n elif mask is None and self.mask_function is None:\n mask = default_mask_function(image=data.image)\n\n if mask.sub_size != self.sub_size:\n mask = mask.new_mask_with_new_sub_size(sub_size=self.sub_size)\n\n if self.inner_mask_radii is not None:\n inner_mask = msk.Mask.circular(\n shape=mask.shape,\n pixel_scale=mask.pixel_scale,\n radius_arcsec=self.inner_mask_radii,\n sub_size=self.sub_size,\n invert=True,\n )\n mask = mask + inner_mask\n\n return mask\n\n def check_positions(self, positions):\n\n if self.positions_threshold is not None and positions is None:\n raise exc.PhaseException(\n \"You have specified for a phase to use positions, but not input positions to the \"\n \"pipeline when you ran it.\"\n )\n\n def pixel_scale_binned_grid_from_mask(\n self,\n mask\n ):\n\n if self.pixel_scale_binned_cluster_grid is None:\n\n pixel_scale_binned_cluster_grid = mask.pixel_scale\n\n else:\n\n pixel_scale_binned_cluster_grid = self.pixel_scale_binned_cluster_grid\n\n if pixel_scale_binned_cluster_grid > mask.pixel_scale:\n\n bin_up_factor = int(\n self.pixel_scale_binned_cluster_grid / mask.pixel_scale\n )\n\n else:\n\n bin_up_factor = 1\n\n binned_mask = mask.binned_up_mask_from_mask(bin_up_factor=bin_up_factor)\n\n while binned_mask.pixels_in_mask < self.inversion_pixel_limit:\n\n if bin_up_factor == 1:\n raise exc.DataException(\n f\"The pixelization {self.pixelization} uses a KMeans clustering algorithm which uses \"\n f\"a hyper model image to adapt the pixelization. This hyper model image must have \"\n f\"more pixels than inversion pixels. Current, the inversion_pixel_limit exceeds the \"\n f\"data-points in the image.\\n\\n To rectify this image, manually set the inversion \"\n f\"pixel limit in the pipeline phases or change the inversion_pixel_limit_overall \"\n f\"parameter in general.ini \"\n )\n\n bin_up_factor -= 1\n binned_mask = mask.binned_up_mask_from_mask(bin_up_factor=bin_up_factor)\n\n return mask.pixel_scale * bin_up_factor\n\n @property\n def pixelization(self):\n for galaxy in self.variable.galaxies:\n if galaxy.pixelization is not None:\n if isinstance(galaxy.pixelization, af.PriorModel):\n return galaxy.pixelization.cls\n else:\n return galaxy.pixelization\n\n @property\n def uses_cluster_inversion(self):\n if self.variable.galaxies:\n for galaxy in self.variable.galaxies:\n if isinstance_or_prior(galaxy.pixelization, pix.VoronoiBrightnessImage):\n return True\n return False\n\n def preload_pixelization_grids_of_planes_from_results(self, results):\n\n if self.is_hyper_phase:\n return None\n\n if (\n results is not None\n and results.last is not None\n and hasattr(results.last, \"hyper_combined\")\n and self.pixelization is not None\n ):\n if self.pixelization.__class__ is results.last.pixelization.__class__:\n return (\n results.last.hyper_combined.most_likely_pixelization_grids_of_planes\n )\n return None\n\n\nclass PhaseData(phase.AbstractPhase):\n galaxies = af.PhaseProperty(\"galaxies\")\n\n Result = Result\n Analysis = Analysis\n\n def __init__(\n self,\n phase_name,\n phase_tag,\n phase_folders=tuple(),\n galaxies=None,\n optimizer_class=af.MultiNest,\n cosmology=cosmo.Planck15,\n auto_link_priors=False,\n ):\n \"\"\"\n\n A phase in an lens pipeline. Uses the set non_linear optimizer to try to fit models and hyper_galaxies\n passed to it.\n\n Parameters\n ----------\n optimizer_class: class\n The class of a non_linear optimizer\n \"\"\"\n\n super(PhaseData, self).__init__(\n phase_name=phase_name,\n phase_tag=phase_tag,\n phase_folders=phase_folders,\n optimizer_class=optimizer_class,\n cosmology=cosmology,\n auto_link_priors=auto_link_priors,\n )\n self.galaxies = galaxies or []\n\n self.is_hyper_phase = False\n\n def run(self, data, results=None, mask=None, positions=None):\n \"\"\"\n Run this phase.\n\n Parameters\n ----------\n positions\n mask: Mask\n The default masks passed in by the pipeline\n results: autofit.tools.pipeline.ResultsCollection\n An object describing the results of the last phase or None if no phase has been executed\n data: scaled_array.ScaledSquarePixelArray\n An lens_data that has been masked\n\n Returns\n -------\n result: AbstractPhase.Result\n A result object comprising the best fit model and other hyper_galaxies.\n \"\"\"\n self.variable = self.variable.populate(results)\n\n analysis = self.make_analysis(\n data=data, results=results, mask=mask, positions=positions\n )\n\n self.customize_priors(results)\n self.assert_and_save_pickle()\n\n result = self.run_analysis(analysis)\n\n return self.make_result(result=result, analysis=analysis)\n\n def make_analysis(self, data, results=None, mask=None, positions=None):\n \"\"\"\n Create an lens object. Also calls the prior passing and lens_data modifying functions to allow child\n classes to change the behaviour of the phase.\n\n Parameters\n ----------\n positions\n mask: Mask\n The default masks passed in by the pipeline\n data: im.Imaging\n An lens_data that has been masked\n results: autofit.tools.pipeline.ResultsCollection\n The result from the previous phase\n\n Returns\n -------\n lens : Analysis\n An lens object that the non-linear optimizer calls to determine the fit of a set of values\n \"\"\"\n raise NotImplementedError()\n\n def extend_with_inversion_phase(self):\n return phase_extensions.InversionPhase(phase=self)\n","sub_path":"autolens/pipeline/phase/phase_data.py","file_name":"phase_data.py","file_ext":"py","file_size_in_byte":11177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"641215176","text":"import os\n\nimport torch, pickle\nfrom pathlib import Path\n\nfrom dataloader.dataset_multichoice import get_iterator as get_iterator_multichoice\nfrom model import get_model\nfrom utils import get_dirname_from_args\n\ndef get_ckpt_path(args, epoch, loss):\n ckpt_name = get_dirname_from_args(args)\n ckpt_path = args.ckpt_path / ckpt_name\n\n args.ckpt_path.mkdir(exist_ok=True)\n ckpt_path.mkdir(exist_ok=True)\n loss = '{:.4f}'.format(loss)\n ckpt_path = ckpt_path / 'loss_{}_epoch_{}.pickle'.format(loss, epoch)\n\n return ckpt_path\n\ndef save_ckpt(args, epoch, loss, model, vocab):\n print('saving epoch {}'.format(epoch))\n dt = {\n 'args': args,\n 'epoch': epoch,\n 'loss': loss,\n 'model': model.state_dict(),\n 'vocab': vocab,\n }\n ckpt_path = get_ckpt_path(args, epoch, loss)\n print(\"Saving checkpoint {}\".format(ckpt_path))\n torch.save(dt, str(ckpt_path))\n\ndef get_model_ckpt(args):\n ckpt_available = args.ckpt_name is not None\n vocab = None\n if ckpt_available:\n name = '{}'.format(args.ckpt_name)\n name = '{}*'.format(name) if not name.endswith('*') else name\n ckpt_paths = sorted(args.ckpt_path.glob(name), reverse=False)\n assert len(ckpt_paths) > 0, \"no ckpt candidate for {}\".format(args.ckpt_path / args.ckpt_name)\n ckpt_path = ckpt_paths[0] # monkey patch for choosing the best ckpt\n print(\"loading from {}\".format(ckpt_path))\n dt = torch.load(ckpt_path)\n args.update(dt['args'])\n vocab = dt['vocab']\n\n iters, vocab = get_iterator_multichoice(args, vocab)\n model = get_model(args, vocab)\n model.load_embedding(vocab)\n\n if ckpt_available:\n model.load_state_dict(dt['model'])\n return args, model, iters, vocab, ckpt_available\n\n","sub_path":"Answer_Selection/code/ckpt.py","file_name":"ckpt.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"378412396","text":"from bokeh.plotting import figure, output_file, show\nfrom bokeh.layouts import row, gridplot\nfrom bokeh.models import HoverTool, ColumnDataSource\n \nclass Error(Exception):\n pass\n\nclass InputError(Error):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return(repr(self.value))\n \nclass LengthError(Error):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return(repr(self.value))\n \nclass EqualityError(Error):\n def __init__(self, value):\n self.value = value\n def __str__(self):\n return(repr(self.value))\n \n \n\ndef entry():\n \n \"\"\"\n This function is for the user to enter information of the amount of each nutrient\n consumed daily for a certain period of time, in order to track nutrients and calorie\n intake during this period by using bokeh graphs.\n \n \"\"\"\n \n try: \n entry_proteins = input('Enter your daily protein intake in gram, separated by spaces')\n if ' ' not in entry_proteins:\n raise InputError(entry_proteins)\n lstA = entry_proteins.split(' ')\n protList = [float(x) for x in lstA]\n protCount = len(protList)\n if protCount < 7:\n raise LengthError(protCount)\n \n entry_fats = input('Enter your daily fat intake in gram, separated by spaces')\n if ' ' not in entry_fats:\n raise InputError(entry_fats)\n lstB = entry_fats.split(' ')\n fatList = [float(x) for x in lstB]\n fatCount = len(fatList)\n if fatCount < 7:\n raise LengthError(fatCount)\n \n entry_carbs = input('Enter your daily carbohydrate intake in gram, separated by spaces')\n if ' ' not in entry_carbs:\n raise InputError(entry_carbs)\n lstC = entry_carbs.split(' ')\n carbList = [float(x) for x in lstC]\n carbCount = len(carbList)\n if carbCount < 7:\n raise LengthError(carbCount)\n \n except InputError as ex:\n print('Exception raised:', ex.value, 'is a invalid input. A list of number is required')\n except LengthError as ex:\n print('Exception raised:', ex.value, 'is not enough for tracking')\n except EqualityError as ex:\n print('Exception raised: length of', ex.value, 'are not equal')\n except:\n print('There is an error')\n \n length = len(protList)\n if (protCount or fatCount or carbCount) < 7:\n raise ValueError('We need records for at least a week')\n \n elif not all(len(lst) == length for lst in [protList, fatList, carbList]):\n raise ValueError('Number of records for all 3 nutrients need to be the same')\n \n protSum = sum(protList)\n fatSum = sum(fatList)\n carbSum = sum(carbList)\n total_carlo = (protSum+carbSum)*4 + fatSum*9\n avg_carlo = total_carlo / len(protList)\n\n dayList = [x+1 for x in range(length)]\n protListC = [x*4 for x in protList]\n fatListC = [x*9 for x in fatList]\n carbListC = [x*4 for x in carbList]\n multiLists = [protListC, fatListC, carbListC]\n caloList = [sum(k) for k in zip(*multiLists)]\n\n nutriTrack(protList, fatList, carbList, dayList)\n calorieTrack(caloList, dayList, avg_carlo)\n \n return caloList\n\ndef nutriTrack(lst1, lst2, lst3, lst4):\n \n \"\"\"\n Description of the Function\n\n Parameters:\n lst1 (list): a list of daily protein intake(g) in a certain time period provided by the user\n lst2 (list): a list of daily fat intake(g) in a certain time period provided by the user\n lst3 (list): a list of daily carbohydrate intake(g) in a certain time period provided by the user\n lst4 (list): a list of sequential days for a certain time period obtained from the user\n\n Returns:\n show linked plotting graphs of three nutrients intake for a certain time period\n \n \"\"\"\n \n try:\n if not all(isinstance(x, (int, float)) for x in lst1):\n raise InputError(lst1)\n elif not all(isinstance(x, (int, float)) for x in lst2):\n raise InputError(lst2)\n elif not all(isinstance(x, (int, float)) for x in lst3):\n raise InputError(lst3)\n elif not all(isinstance(x, (int, float)) for x in lst4):\n raise InputError(lst4)\n \n output_file('nutrients.html')\n s1 = figure(plot_width=450, plot_height=350, title=\"Daily Protein Intake\", x_axis_label='Days', y_axis_label='Protein(g)')\n if len(lst1) < 7:\n raise LengthError(lst1) \n elif len(lst2) < 7:\n raise LengthError(lst2)\n elif len(lst3) < 7:\n raise LengthError(lst3)\n elif len(lst4) < 7:\n raise LengthError(lst4)\n s1.circle(lst4, lst1, size=10, color='navy', alpha=0.5)\n s2 = figure(plot_width=450, plot_height=350, x_range=s1.x_range, y_range=s1.y_range,\n title=\"Daily Fat Intake\", x_axis_label='Days', y_axis_label='Fat(g)')\n s2.triangle(lst4, lst2, size=10, color='firebrick', alpha=0.5)\n s3 = figure(plot_width=450, plot_height=350, x_range=s1.x_range, y_range=s1.y_range,\n title=\"Daily Carbohydrate Intake\", x_axis_label='Days', y_axis_label='Carbohydrate(g)')\n s3.square(lst4, lst3, size=10, color='olive', alpha=0.5)\n\n p = gridplot([[s1, s2, s3]], toolbar_location=None)\n show(p)\n \n except InputError as ex:\n print('Exception raised:', ex.value, 'contains non-numeric value')\n except LengthError as ex:\n print('Exception raised:', ex.value, 'is not enough for tracking')\n except:\n print('There is an error') \n\n \ndef calorieTrack(lst1, lst2, num):\n \n \"\"\"\n Description of the Function\n\n Parameters:\n lst1 (list): a list of daily calorie intake in a certain time period calculated by info provided by the user\n lst2 (list): a list of sequential days for a certain time period obtained from the user\n num (float): average calorie intake for a certain period of time\n\n Returns:\n show the graph of the total daily calorie intake for a certain period of time\n \n \"\"\"\n try:\n if len(lst1) != len(lst2):\n raise EqualityError('Two lists')\n output_file('calories.html')\n if not all(isinstance(x, (int, float)) for x in lst1):\n raise InputError(lst1)\n elif not all(isinstance(x, (int, float)) for x in lst2):\n raise InputError(lst2)\n \n source = ColumnDataSource(data=dict(x = lst2, y = lst1))\n hover = HoverTool(tooltips=[('index', '$index'), ('y', '@y')])\n p = figure(plot_width =750, plot_height =500, tools=[hover], title='Daily Calorie Intake',\n x_axis_label='Days', y_axis_label='Calorie')\n p.line('x', 'y', line_width=3, source=source)\n p.circle('x', 'y', size=20, source=source)\n show(p)\n \n except InputError as ex:\n print('Exception raised:', ex.value, 'contains non-numeric value')\n except EqualityError as ex:\n print('Exception raised: length of', ex.value, 'are not equal')\n except:\n print('There is an error') \n ","sub_path":"build/lib/Fittness/calories_intake/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":7162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"324967412","text":"# Here is the code for creating and configuring every widget.\r\n# Like the size, color, opacity etc.\r\n# It is like the graphics of the application.\r\n\r\nimport ac\r\nimport os\r\nfrom RD import app_dir\r\n\r\n\r\nclass AddElementCheckBox:\r\n ''' Creates a checkbox so User can select a specific MOD to\r\n see it's info or download it.\r\n '''\r\n def __init__(self, panel, no):\r\n self.panel = panel\r\n self.no = no\r\n self.CheckBox = ac.addCheckBox(self.panel, str(self.no))\r\n ac.setPosition(self.CheckBox, 15, 120 + ((self.no - 1) * 24))\r\n ac.setSize(self.CheckBox, 15, 12)\r\n ac.setVisible(self.CheckBox, 0)\r\n ac.setFontColor(self.CheckBox, 0, 93 / 255, 179 / 255, 1)\r\n\r\n\r\nclass AddMenuCheckBox:\r\n ''' Creates MENU checkbox so User can navigate through \r\n each category of MODS.\r\n '''\r\n def __init__(self, panel, pos_x, name, site, dicta):\r\n self.panel = panel\r\n self.name = name\r\n self.site = site\r\n self.dicta = dicta\r\n self.MaxPages = 0\r\n self.Order = \"\"\r\n self.CheckBox = ac.addCheckBox(self.panel, self.name)\r\n ac.setFontColor(self.CheckBox, 249/255, 249/255, 249/255, 1)\r\n ac.setPosition(self.CheckBox, pos_x, 9)\r\n ac.setSize(self.CheckBox, 15, 12)\r\n\r\n\r\ndef MakePretty(element, **kwargs):\r\n ''' Set functions for configuring each widget.\r\n '''\r\n \r\n def pos(element, x, y):\r\n ac.setPosition(element, x, y)\r\n\r\n def size(element, x, y):\r\n ac.setSize(element, x, y)\r\n\r\n def f_size(element, x):\r\n ac.setFontSize(element, x)\r\n\r\n def f_align(element, alignment):\r\n ac.setFontAlignment(element, alignment)\r\n\r\n def b_rgb(element, red, green, blue):\r\n ac.setBackgroundColor(element, red, green, blue)\r\n\r\n def f_rgb(element, red, green, blue, opacity):\r\n ac.setFontColor(element, red, green, blue, opacity)\r\n\r\n def b_opacity(element, opacity):\r\n ac.setBackgroundOpacity(element, opacity)\r\n\r\n def border(element, x):\r\n ac.drawBorder(element, x)\r\n\r\n def b_texture(element, image_file):\r\n ac.setBackgroundTexture(element, image_file)\r\n\r\n def visible(element, value):\r\n ac.setVisible(element, value)\r\n\r\n pretty_functions = {'pos': pos, 'size': size, 'f_size': f_size, 'f_align': f_align, 'b_rgb': b_rgb, 'f_rgb': f_rgb,\r\n 'b_opacity': b_opacity, 'border': border, 'b_texture': b_texture, 'visible': visible}\r\n \r\n for key, values in kwargs.items():\r\n if key != \"b_opacity\":\r\n pretty_functions[key](element, *values)\r\n\r\n # bg opacity should be always executed last cause changing bg color resets bg opacity to 0\r\n if kwargs.get(\"b_opacity\"):\r\n b_opacity(element, kwargs['b_opacity'][0])\r\n\r\n\r\nwhite = (249/255, 249/255, 249/255)\r\nred = (184 / 255, 31 / 255, 31 / 255)\r\nblue_win = (0, 93 / 255, 179 / 255)\r\nblue = (51/255, 102/255, 153/255)\r\nlight_grey = (224/255, 224/255, 224/255)\r\ngrey = (150/255, 150/255, 150/255)\r\nblack = (0,0,0)\r\ngreen = (77 / 255, 152 / 255, 52 / 255)\r\n\r\nframe = ac.newApp(\"Resource Downloader\")\r\nMakePretty(frame, size=(1000, 640), b_rgb=white, b_opacity=(1,))\r\n\r\nFooter_Block = ac.addButton(frame, \"\")\r\nMakePretty(Footer_Block, pos=(80, 609), size=(840, 30), b_rgb=blue, b_opacity=(1,), border=(1,))\r\n\r\nCopyright_label = ac.addLabel(frame, \"ver 0.1 by V.Theodoridis\")\r\nMakePretty(Copyright_label, pos=(750, 614), size=(210, 20), f_size=(14,), b_opacity=(0,), f_rgb=white+(1,))\r\n\r\nlatest_updates_button = ac.addButton(frame, \"Latest Updates\")\r\nMakePretty(latest_updates_button, pos=(100, 66), size=(130, 20), border=(0,), b_opacity=(1,), f_rgb=black+(1,), b_rgb=white)\r\n\r\nSort_Dates_Button = ac.addButton(frame, \"Newest Resources\")\r\nMakePretty(Sort_Dates_Button, pos=(231, 66), size=(130, 20), border=(0,), b_opacity=(1,), f_rgb=black+(1,), b_rgb=light_grey)\r\n\r\nSort_Ratings_Button = ac.addButton(frame, \"Top Resources\")\r\nMakePretty(Sort_Ratings_Button, pos=(362, 66), size=(130, 20), border=(0,), b_opacity=(1,), f_rgb=black+(1,), b_rgb=light_grey)\r\n\r\nSort_Downloads_Button = ac.addButton(frame, \"Most Downloaded\")\r\nMakePretty(Sort_Downloads_Button, pos=(493, 66), size=(130, 20), border=(0,), b_opacity=(1,), f_rgb=black+(1,), b_rgb=light_grey)\r\n\r\nTitle_Car = ac.addLabel(frame, \"Name\")\r\nMakePretty(Title_Car, pos=(80, 85), size=(350, 30), f_size=(20,), f_align=(\"center\",), b_rgb=light_grey, f_rgb=black+(1,), b_opacity=(1,))\r\n\r\nTitle_Version = ac.addLabel(frame, \"Version\")\r\nMakePretty(Title_Version, pos=(430, 85), size=(132, 30), f_size=(20,), f_align=(\"center\",), b_rgb=light_grey, f_rgb=black+(1,), b_opacity=(1,))\r\n\r\nTitle_Updated = ac.addLabel(frame, \"Updated\")\r\nMakePretty(Title_Updated, pos=(562, 85), size=(130, 30), f_size=(20,), f_align=(\"center\",), b_rgb=light_grey, f_rgb=black+(1,), b_opacity=(1,))\r\n\r\nDownloads_label = ac.addLabel(frame, u\"\\u2B07\") # Downloads\r\nMakePretty(Downloads_label, pos=(708, 85), size=(60, 30), f_size=(20,), f_align=(\"center\",), b_rgb=light_grey, f_rgb=black+(1,), b_opacity=(1,))\r\n\r\nRatings_label = ac.addLabel(frame, u\"\\u2605\")\r\nMakePretty(Ratings_label, pos=(784, 85), size=(60, 30), f_size=(20,), f_align=(\"center\",), b_rgb=light_grey, f_rgb=(227 / 255, 227 / 255, 0, 1), b_opacity=(1,))\r\n\r\nVotes_label = ac.addLabel(frame, \"Votes\")\r\nMakePretty(Votes_label, pos=(860, 85), size=(60, 30), f_size=(19,), f_align=(\"center\",), b_rgb=light_grey, f_rgb=black+(1,), b_opacity=(1,))\r\n\r\nFilter_Field = ac.addTextInput(frame, \"\")\r\nMakePretty(Filter_Field, pos=(300, 90), size=(100, 20), border=(0,))\r\nac.setText(Filter_Field, \"\")\r\n\r\nFilter_Button = ac.addButton(frame, u\"\\U0001F50D\")\r\nMakePretty(Filter_Button, pos=(400, 90), size=(20, 20), border=(1,), b_rgb=green, b_opacity=(1,))\r\n\r\nInfo_img_box = ac.addTextBox(frame, \"\")\r\nMakePretty(Info_img_box, pos=(78, 130), size=(844, 480), b_opacity=(1,), visible=(0,), f_size=(25,), border=(0,))\r\n\r\nInfo_box = ac.addTextBox(frame, \"\")\r\nac.setText(Info_box, \" Name: \\n Author: \\n First Release: \\n Size: \\n Description:\")\r\nMakePretty(Info_box, pos=(78, 0), size=(844, 118), b_opacity=(0,), visible=(0,), f_size=(19,), f_rgb=blue+(1,))\r\n\r\nImage_status = ac.addLabel(frame, \"\")\r\nMakePretty(Image_status, pos=(700, 35), size=(200, 40), f_size=(20,), f_align=('center',), f_rgb=blue+(1,))\r\n\r\nDownload_Button = ac.addButton(frame, u\"\\u2B07\")\r\nMakePretty(Download_Button, pos=(305, 614), size=(35, 20), f_align=('center',), visible=(0,), b_rgb=green, b_opacity=(1,))\r\n\r\nShow_Info_Button = ac.addButton(frame, \"Info\")\r\nMakePretty(Show_Info_Button, pos=(345, 614), size=(35, 20), f_align=('center',), visible=(0,), b_rgb=green, b_opacity=(1,))\r\n\r\nDownload_Status_label = ac.addLabel(frame, \"\")\r\nMakePretty(Download_Status_label, pos=(90, 614), size=(210, 20), f_rgb=black+(1,), b_rgb=white, b_opacity=(0.3,), f_size=(13,))\r\n\r\nspinner = ac.addSpinner(frame, \"\")\r\nMakePretty(spinner, pos=(410, 614), size=(200, 20), f_rgb=green+(1,), b_rgb=black, b_opacity=(1,), border=(0,))\r\nac.setRange(spinner, 1, 1)\r\nac.setValue(spinner, 1)\r\n\r\nspinner_label = ac.addLabel(frame, \"\")\r\nMakePretty(spinner_label, size=(50, 20), pos=(465, 614), f_rgb=green+(1,))\r\n\r\nLabels_dict = {}\r\nChcBox_Element_dict = {}\r\nk = -1\r\nfor i in range(20):\r\n ChcBox_Element_dict[i + 1] = (AddElementCheckBox(frame, i + 1))\r\n k += 1\r\n Labels_dict[k] = ac.addLabel(frame, \"\") # Car Name label\r\n MakePretty(Labels_dict[k], pos=(80, 115 + (i * 24)), size=(350, 20), b_rgb=white, f_rgb=blue+(1,),) \r\n k += 1\r\n Labels_dict[k] = ac.addLabel(frame, \"\") # Version label\r\n MakePretty(Labels_dict[k], pos=(446, 115 + (i * 24)), size=(100, 20), b_rgb=white, f_rgb=grey+(1,), f_align=(\"center\",))\r\n k += 1\r\n Labels_dict[k] = ac.addLabel(frame, \"\") # Date label\r\n MakePretty(Labels_dict[k], pos=(562, 115 + (i * 24)), size=(130, 20), b_rgb=white, f_rgb=black+(1,), f_align=(\"center\",))\r\n k += 1\r\n Labels_dict[k] = ac.addLabel(frame, \"\") # Downloads label\r\n MakePretty(Labels_dict[k], pos=(708, 115 + (i * 24)), size=(60, 20), b_rgb=white, f_rgb=black+(1,), f_align=(\"center\",))\r\n k += 1\r\n Labels_dict[k] = ac.addLabel(frame, \"\") # Ratings label\r\n MakePretty(Labels_dict[k], pos=(784, 115 + (i * 24)), size=(60, 20), b_rgb=white, f_rgb=black+(1,), f_align=(\"center\",))\r\n k += 1\r\n Labels_dict[k] = ac.addLabel(frame, \"\") # Votes label\r\n MakePretty(Labels_dict[k], pos=(860, 115 + (i * 24)), size=(60, 20), b_rgb=white, f_rgb=black+(1,), f_align=(\"center\",))\r\nfor i in range(0, 20):\r\n for j in range(0, 6):\r\n if i % 2 == 0:\r\n ac.setBackgroundOpacity(Labels_dict[j + (6 * i)], 0.5)\r\n else:\r\n ac.setBackgroundOpacity(Labels_dict[j + (6 * i)], 1)\r\n\r\nHeader_Block = ac.addButton(frame, \"\")\r\nMakePretty(Header_Block, pos=(50, 0), size=(905, 30), b_rgb=blue, b_opacity=(1,), border=(1,))\r\n\r\nprogressBar = ac.addProgressBar(frame, \"\")\r\nMakePretty(progressBar, pos=(49, 0), size=(906, 3), f_rgb=red+(1,), border=(0,))\r\nac.setRange(progressBar, 0, 100)\r\nac.setValue(progressBar, 0)\r\n\r\nsearch_field = ac.addTextInput(frame, \"\")\r\nMakePretty(search_field, pos=(780, 6), size=(100, 20), border=(0,))\r\nac.setText(search_field, \"\")\r\n\r\nsearch_button = ac.addButton(frame, u\"\\U0001F50D\")\r\nMakePretty(search_button, pos=(880, 6), size=(20, 20), border=(1,), b_rgb=green, b_opacity=(1,))\r\n\r\nExpand_Options = ac.addButton(frame, u\"\\u2630\")\r\nMakePretty(Expand_Options, size=(20, 20), pos=(930, 5), b_rgb=green, b_opacity=(1,))\r\n\r\ndisk_space_label = ac.addLabel(frame, \"\")\r\nMakePretty(disk_space_label, pos=(175, 29), size=(300, 20), visible=(0,), f_rgb=white+(1,))\r\n\r\nPath_Label = ac.addLabel(frame, \"Downloads: \")\r\nMakePretty(Path_Label, pos=(55, 30), size=(850, 20), visible=(0,), f_rgb=white+(1,))\r\n\r\nPath_Field = ac.addTextInput(frame, \"\")\r\nMakePretty(Path_Field, pos=(135, 51), size=(705, 22), visible=(0,))\r\n\r\nPaste_Button = ac.addButton(frame, \"Paste\")\r\nMakePretty(Paste_Button, pos=(900, 52), size=(50, 19), visible=(0,), b_rgb=green, b_opacity=(1,))\r\n\r\nsave_button = ac.addButton(frame, \"Save\")\r\nMakePretty(save_button, pos=(845, 52), size=(50, 19), visible=(0,), b_rgb=green, b_opacity=(1,))\r\n\r\nclear_temps_button = ac.addButton(frame, \"Clear temps\")\r\nMakePretty(clear_temps_button, pos=(750, 32), size=(100, 19), visible=(0,), b_rgb=green, b_opacity=(1,))\r\n\r\nChcBox_Menu_dict = {\r\n \"All\": AddMenuCheckBox(frame, 60, \"All\", \"http://www.racedepartment.com/downloads/categories/assetto-corsa.1/?page=\", {}),\r\n \"Cars\": AddMenuCheckBox(frame, 140, \"Cars\", \"http://www.racedepartment.com/downloads/categories/ac-cars.6/?page=\", {}),\r\n \"Tracks\": AddMenuCheckBox(frame, 220, \"Tracks\", \"http://www.racedepartment.com/downloads/categories/ac-tracks.8/?page=\", {}),\r\n \"Sounds\": AddMenuCheckBox(frame, 300, \"Sounds\", \"http://www.racedepartment.com/downloads/categories/ac-sounds.9/?page=\", {}),\r\n \"Misc\": AddMenuCheckBox(frame, 380, \"Misc\", \"http://www.racedepartment.com/downloads/categories/ac-misc.10/?page=\", {}),\r\n \"Apps\": AddMenuCheckBox(frame, 460, \"Apps\", \"http://www.racedepartment.com/downloads/categories/ac-apps.4/?page=\", {}),\r\n \"Skins\": AddMenuCheckBox(frame, 540, \"Skins\", \"http://www.racedepartment.com/downloads/categories/ac-skins.7/?page=\", {}),\r\n \"Career\": AddMenuCheckBox(frame, 620, \"Career\", \"http://www.racedepartment.com/downloads/categories/ac-career.60/?page=\", {})\r\n}\r\n","sub_path":"libs/helpers/extra.py","file_name":"extra.py","file_ext":"py","file_size_in_byte":11340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"351092989","text":"import numpy as np\nimport tensorflow as tf\nfrom autoencoders.AutoEncoder import Autoencoder_conv2conv, Autoencoder_conv2deconv, Autoencoder_full2deconv\nfrom Data import Data\nfrom tensorflow.contrib.layers import batch_norm\nimport cv2\nfrom tensorflow.python.training import moving_averages\n\ndata = Data('../data/data.npz', 64)#读入数据\n\n#定义第一层自动DAE\nae1 = Autoencoder_conv2conv('ae1',\n [5,5,3,64],#输入卷积核的大小\n [1,1,64,3],#输出卷积核的大小\n [64,32,128,3],#输入该层的数据的形状\n tf.train.AdamOptimizer(0.85))\n\n#定义第二层自动DAE\nae2 = Autoencoder_conv2deconv('ae2',\n [3,3,64,96],#输入卷积核的大小\n [5,5,64,96],#输出卷积核的大小\n [64,32,128,64],#输入该层的数据的形状\n tf.train.AdamOptimizer(0.85))\n\n#定义第三层自动DAE\nae3 = Autoencoder_conv2deconv('ae3',\n [3,3,96,96],#输入卷积核的大小\n [3,3,96,96],#输出卷积核的大小\n [64,16,64,96],#输入该层的数据的形状\n tf.train.AdamOptimizer(0.85))\n\n#定义第四层自���DAE\nae4 = Autoencoder_conv2deconv('ae4',\n [3,3,96,64],#输入卷积核的大小\n [3,3,96,64],#输出卷积核的大小\n [64,8,32,96],#输入该层的数据的形状\n tf.train.AdamOptimizer(0.85))\n\n#定义全连接层提取出64维参数\nae5 = Autoencoder_full2deconv('ae5',\n tf.train.AdamOptimizer(0.185))\n\n'''\n由于将图像特征提取到64维后训练结果很差,因此未使用ae5\n\n'''\n\n#定义batchnorm层\ndef batch_normalization_layer(input,moving_mean,moving_variance,beta,gamma):\n axis = list(range(len(input.get_shape())-1))\n mean,variance = tf.nn.moments(input,axis)#计算当前epoch的均值与方差\n moving_averages.assign_moving_average(moving_mean,mean,0.999)#修改滑动均值\n moving_averages.assign_moving_average(moving_variance,variance,0.999)#修改滑动方差\n '''计算滑动均值和滑动方差是为了在测试集上使用,使用未知样本进行计算时,使用滑动均值和滑动方差来代替未知样本的均值和方差'''\n return tf.nn.batch_normalization(input,mean,variance,beta,gamma,0.001)\n\n\n'''\n定义SDAE的计算图(该部分只是定义图,并未训练!!!)\n该部分使用之前定义的DAE的参数来继续训练\n'''\n#autoencoder1\n'''\n卷积核的参数保存在类的weights字典里,batchnorm层的参数保存在bnparam内,具体方式定义在类里\n'''\ny = tf.placeholder(tf.float32,[64,32,128,3])\nx = tf.placeholder(tf.float32,[64,32,128,3])\nh = tf.nn.conv2d(x,ae1.weight['w1'],[1,1,1,1],padding='SAME')+ae1.weight['b1']\nh = batch_normalization_layer(h,ae1.bnparam1['moving_mean'],ae1.bnparam1['moving_variance'],\n ae1.bnparam1['beta'],ae1.bnparam1['gamma'])\nh = tf.nn.relu(h)\n#autoencoder2\nh = tf.nn.max_pool(h,[1,2,2,1],[1,2,2,1],padding='SAME')\nh = tf.nn.conv2d(h,ae2.weight['w1'],[1,1,1,1],padding='SAME')+ae2.weight['b1']\nh = batch_normalization_layer(h,ae2.bnparam1['moving_mean'],ae2.bnparam1['moving_variance'],\n ae2.bnparam1['beta'],ae2.bnparam1['gamma'])\nh = tf.nn.relu(h)\n#autoencoder3\nh = tf.nn.max_pool(h,[1,2,2,1],[1,2,2,1],padding='SAME')\nh = tf.nn.conv2d(h,ae3.weight['w1'],[1,1,1,1],padding='SAME')+ae3.weight['b1']\nh = batch_normalization_layer(h,ae3.bnparam1['moving_mean'],ae3.bnparam1['moving_variance'],\n ae3.bnparam1['beta'],ae3.bnparam1['gamma'])\nh = tf.nn.relu(h)\n\n#autoencoder4\nh = tf.nn.max_pool(h,[1,2,2,1],[1,2,2,1],padding='SAME')\nh = tf.nn.conv2d(h,ae4.weight['w1'],[1,1,1,1],padding='SAME')+ae4.weight['b1']#ae4\nh = batch_normalization_layer(h,ae4.bnparam1['moving_mean'],ae4.bnparam1['moving_variance'],\n ae4.bnparam1['beta'],ae4.bnparam1['gamma'])\nh = tf.nn.relu(h)\n#h = tf.nn.max_pool(h,[1,2,2,1],[1,2,2,1],padding='SAME')\n#############ae5\n#flatten = tf.reshape(h,[64,-1])\n#h = tf.nn.relu(tf.matmul(flatten,ae5.weight['w1'])+ae5.weight['b1'])\n#h = batch_norm(h)\n#h = tf.nn.relu(tf.matmul(h,ae5.weight['w2'])+ae5.weight['b2'])\n#h = batch_norm(h)\n\n#h = tf.nn.relu(tf.nn.conv2d_transpose(tf.reshape(h,[64,2,8,64]),ae5.weight['w3'],[64,2,8,64],[1,1,1,1],padding='SAME')+ae5.weight['b3'])\n#h = batch_norm(h)\n#h = tf.image.resize_nearest_neighbor(h,[4,16])\n#############\n\nh = tf.nn.conv2d_transpose(h,ae4.weight['w2'],[64,8,32,96],[1,2,2,1],padding='SAME')+ae4.weight['b2']\nh = batch_normalization_layer(h,ae4.bnparam2['moving_mean'],ae4.bnparam2['moving_variance'],\n ae4.bnparam2['beta'],ae4.bnparam2['gamma'])\nh = tf.nn.relu(h)\n#autoencoder4\nh = tf.nn.conv2d_transpose(h,ae3.weight['w2'],[64,16,64,96],[1,2,2,1],padding='SAME')+ae3.weight['b2']\nh = batch_normalization_layer(h,ae3.bnparam2['moving_mean'],ae3.bnparam2['moving_variance'],\n ae3.bnparam2['beta'],ae3.bnparam2['gamma'])\nh = tf.nn.relu(h)\n#autoencoder3\n\nh = tf.nn.relu(batch_norm(tf.nn.conv2d_transpose(h,ae2.weight['w2'],[64,32,128,64],[1,2,2,1],padding='SAME')+ae2.weight['b2']))#ae2\nh = batch_normalization_layer(h,ae2.bnparam2['moving_mean'],ae2.bnparam2['moving_variance'],\n ae2.bnparam2['beta'],ae2.bnparam2['gamma'])\nh = tf.nn.relu(h)\n#autoencoder2\nh = tf.nn.relu(tf.nn.conv2d(h,ae1.weight['w2'],[1,1,1,1],padding='SAME')+ae1.weight['b2'])#ae1\nh = batch_normalization_layer(h,ae1.bnparam2['moving_mean'],ae1.bnparam2['moving_variance'],\n ae1.bnparam2['beta'],ae1.bnparam2['gamma'])\noutput = tf.nn.relu(h)\n#autoencoder1\nstackcost = tf.reduce_mean(tf.square(tf.subtract(y,output)))\nopt = tf.train.AdamOptimizer(0.185).minimize(stackcost)\n\n\n\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\n#训练AutoEncoder1\nfor epoch in range(200):\n avg_cost = 0#定义平均cost\n total_batch = int(len(data.train_data) / 64)\n data.num = 0\n gaussianNoise = 0.01 * np.random.normal(size=[64, 12288]).reshape([64, 32, 128, 3])#0.01高斯噪声\n for i in range(total_batch):\n traindata = data.batch_size([64, 32, 128, 3])#读取[64, 32, 128, 3]大小的数据\n\n _,cost = sess.run(ae1.partial_fit(),feed_dict={ae1.x:traindata+gaussianNoise,ae1.y:traindata})\n avg_cost += cost / len(data.train_data) * 64\n\n print(\"Epoch:{},Cost:{:.9f}\".format(epoch, avg_cost))\navg_cost = 0\ntotal_batch = int(len(data.test_data) / 64)\ndata.num = 0\n#测试AutoEncoder1\nfor i in range(total_batch):\n #print(data.test([-1,32,128,3]))\n testdata = data.test([-1, 32, 128, 3])\n cost = sess.run(ae1.total_cost(),feed_dict={ae1.x:testdata,ae1.y:testdata})\n avg_cost += cost / len(data.test_data) * 64\nprint(\"test cost: \",avg_cost)\nprint(\"#################################ae1 train finished##################################\")\n\nfor epoch in range(200):\n avg_cost = 0\n total_batch = int(len(data.train_data) / 64)\n data.num = 0\n gaussianNoise = 0.01 * np.random.normal(size=[64,32,128,64])\n for i in range(total_batch):\n traindata = data.batch_size([-1, 32, 128, 3])\n input = sess.run(ae1.encode,feed_dict={ae1.x:traindata,ae1.y:traindata})\n\n _,cost = sess.run(ae2.partial_fit(),feed_dict={ae2.x:input+gaussianNoise,ae2.y:input})\n avg_cost += cost / len(data.train_data) * 64\n\n print(\"Epoch:{},Cost:{:.9f}\".format(epoch, avg_cost))\navg_cost = 0\ntotal_batch = int(len(data.test_data) / 64)\ndata.num = 0\nfor i in range(total_batch):\n testdata = data.test([-1, 32, 128, 3])\n input = sess.run(ae1.filture(), feed_dict={ae1.x: testdata,ae1.y: testdata})\n #input = batch_norm(input)\n cost = sess.run(ae2.total_cost(), feed_dict={ae2.x: input,ae2.y: input})\n avg_cost += cost / len(data.test_data) * 64\nprint(\"test cost: \",avg_cost)\nprint(\"#################################ae2 train finished##################################\")\n\n\nfor epoch in range(200):\n avg_cost = 0\n total_batch = int(len(data.train_data) / 64)\n data.num = 0\n gaussianNoise = 0.01 * np.random.normal(size=[64,16,64,96])\n for i in range(total_batch):\n traindata = data.batch_size([-1, 32, 128, 3])\n input = sess.run(ae1.encode, feed_dict={ae1.x: traindata, ae1.y: traindata})\n input = sess.run(ae2.encode,feed_dict={ae2.x:input,ae2.y:input})\n\n _,cost = sess.run(ae3.partial_fit(),feed_dict={ae3.x:input+gaussianNoise,ae3.y:input})\n avg_cost += cost / len(data.train_data) * 64\n print(\"Epoch:{},Cost:{:.9f}\".format(epoch, avg_cost))\navg_cost = 0\ntotal_batch = int(len(data.test_data) / 64)\ndata.num = 0\nfor i in range(total_batch):\n testdata = data.test([-1, 32, 128, 3])\n input = sess.run(ae1.filture(), feed_dict={ae1.x: testdata,ae1.y:testdata})\n #input = batch_norm(input)\n input = sess.run(ae2.filture(), feed_dict={ae2.x: input,ae2.y: input})\n cost = sess.run(ae3.total_cost(), feed_dict={ae3.x: input,ae3.y:input})\n avg_cost += cost / len(data.test_data) * 64\nprint(\"test cost: \",avg_cost)\nprint(\"#################################ae3 train finished##################################\")\n\nfor epoch in range(200):\n avg_cost = 0\n total_batch = int(len(data.train_data) / 64)\n data.num = 0\n gaussianNoise = 0.01 * np.random.normal(size=[64,8,32,96])\n for i in range(total_batch):\n traindata = data.batch_size([-1, 32, 128, 3])\n input = sess.run(ae1.encode, feed_dict={ae1.x: traindata, ae1.y: traindata})\n input = sess.run(ae2.encode, feed_dict={ae2.x: input, ae2.y: input})\n input = sess.run(ae3.encode, feed_dict={ae3.x: input,ae3.y: input})\n\n _,cost = sess.run(ae4.partial_fit(),feed_dict={ae4.x:input+gaussianNoise,ae4.y:input})\n avg_cost += cost / len(data.train_data) * 64\n print(\"Epoch:{},Cost:{:.9f}\".format(epoch, avg_cost))\navg_cost = 0\ntotal_batch = int(len(data.test_data) / 64)\ndata.num = 0\nfor i in range(total_batch):\n testdata = data.test([-1, 32, 128, 3])\n input = sess.run(ae1.filture(), feed_dict={ae1.x: testdata,ae1.y: testdata})\n input = sess.run(ae2.filture(), feed_dict={ae2.x: input,ae2.y: input})\n input = sess.run(ae3.filture(), feed_dict={ae3.x: input,ae3.y: input})\n cost = sess.run(ae4.total_cost(), feed_dict={ae4.x: input,ae4.y: input})\n avg_cost += cost / len(data.test_data) * 64\nprint(\"test cost: \",avg_cost)\nprint(\"#################################ae4 train finished##################################\")\n\n\n# for epoch in range(0):\n# avg_cost = 0\n# total_batch = int(len(data.train_data) / 64)\n# data.num = 0\n# for i in range(total_batch):\n# input = sess.run(ae1.filture(),feed_dict={ae1.x:data.batch_size([-1, 32, 128, 3])})\n# #input = batch_norm(input)\n# input = sess.run(ae2.filture(),feed_dict={ae2.x:input})\n# input = sess.run(ae3.filture(), feed_dict={ae3.x: input})\n# input = sess.run(ae4.filture(), feed_dict={ae4.x: input})\n# _,cost = sess.run(ae5.partial_fit(),feed_dict={ae5.x:input})\n# avg_cost += cost / len(data.train_data) * 64\n# print(\"Epoch:{},Cost:{:.9f}\".format(epoch, avg_cost))\n# avg_cost = 0\n# total_batch = int(len(data.test_data) / 64)\n# data.num = 0\n# for i in range(total_batch):\n# input = sess.run(ae1.encode, feed_dict={ae1.x: data.test([-1, 32, 128, 3])})\n# #input = batch_norm(input)\n# input = sess.run(ae2.encode, feed_dict={ae2.x: input})\n# input = sess.run(ae3.encode, feed_dict={ae3.x: input})\n# input = sess.run(ae4.encode, feed_dict={ae4.x: input})\n#\n# cost = sess.run(ae5.total_cost(), feed_dict={ae5.x: input})\n# avg_cost += cost / len(data.test_data) * 64\n# print(\"test cost: \",avg_cost)\n# print(\"#################################ae5 train finished##################################\")\n# #\n\n\n\n\n\n'''最终训练SDAE'''\nfor epoch in range(20000):\n avg_cost = 0\n total_batch = int(len(data.train_data) / 64)\n data.num = 0\n for i in range(total_batch):\n #input = sess.run(h,feed_dict={x:})\n traindata = data.batch_size([-1, 32, 128, 3])\n gaussianNoise = 0.01 * np.random.normal(size=np.shape(traindata))\n _, cost = sess.run((opt,stackcost), feed_dict={x:traindata+gaussianNoise,y:traindata})\n if epoch%100==0 and i%64==0:\n '''\n 每100个epoch保存一个输出的图像\n '''\n rebuildimage = sess.run(output,feed_dict={x:traindata})\n cv2.imwrite('./outputImage/input.hdr', traindata[0][:, :, ::-1])\n #print(output.shape)\n cv2.imwrite('./outputImage/' + str(epoch) + '_output.hdr',\n np.reshape(rebuildimage[0], [32, 128, 3])[:, :, ::-1])\n avg_cost += cost / len(data.train_data) * 64\n\n print(\"Epoch:{},Cost:{:.9f}\".format(epoch, avg_cost))\n","sub_path":"SDAErunner.py","file_name":"SDAErunner.py","file_ext":"py","file_size_in_byte":13165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"587011766","text":"#!/usr/bin/env python2.7\n# -*- coding:UTF-8 -*-2\nu\"\"\"manager.py\n\nCopyright(c)2019 Yukio Kuro\nThis software is released under BSD license.\n\nゲーム進行管理モジュール。\n\"\"\"\nimport input as _input\nimport inventory as _inventory\nimport main as _main\nimport armament.level as _level\nimport armament.units as _units\nimport material.misc as _misc\nimport material.sound as _sound\nimport sprites.effects as _effects\nimport utils.const as _const\nimport utils.image as _image\nimport utils.screen as _screen\n\n\nclass __Manager(object):\n u\"\"\"ゲームシステム進行管理。\n \"\"\"\n __slots__ = (\n \"_1p\", \"_2p\", \"_controler_1p\", \"_is_error\", \"_parent\", \"_phase\",\n \"_rank\")\n\n class __Phase(object):\n u\"\"\"ゲームフェイズ。\n \"\"\"\n def __init__(self, manager):\n u\"\"\"コンストラクタ。\n \"\"\"\n self._manager = manager\n\n def run(self):\n u\"\"\"実行。\n \"\"\"\n class _Boot(__Phase):\n u\"\"\"起動フェイズ。\n \"\"\"\n def run(self):\n u\"\"\"実行。\n \"\"\"\n self._manager.boot()\n self._manager.command_io()\n\n class _Drive(__Phase):\n u\"\"\"平常進行フェイズ。\n \"\"\"\n def run(self):\n u\"\"\"実行。\n \"\"\"\n self._manager.release()\n self._manager.throw()\n self._manager.command_io()\n self._manager.completion()\n self._manager.terminate()\n\n class _Disappear(__Phase):\n u\"\"\"ブロック消滅フェイズ。\n \"\"\"\n def run(self):\n u\"\"\"実行。\n \"\"\"\n self._manager.completion()\n self._manager.disappear()\n\n class _Crushing(__Phase):\n u\"\"\"クリーチャー撃破フェイズ。\n \"\"\"\n def run(self):\n u\"\"\"実行。\n \"\"\"\n self._manager.completion()\n self._manager.crushing()\n\n class _Winning(__Phase):\n u\"\"\"ゲーム勝敗表示フェイズ。\n \"\"\"\n def run(self):\n u\"\"\"実行。\n \"\"\"\n self._manager.completion()\n self._manager.winning()\n\n class _Result(__Phase):\n u\"\"\"ボーナス表示フェイズ。\n \"\"\"\n def run(self):\n u\"\"\"実行。\n \"\"\"\n self._manager.completion()\n self._manager.result()\n\n class _Finish(__Phase):\n u\"\"\"フィニッシュフェイズ。\n \"\"\"\n def run(self):\n u\"\"\"実行。\n \"\"\"\n self._manager.completion()\n self._manager.finish()\n\n class _Done(__Phase):\n u\"\"\"終了フェイズ。\n \"\"\"\n pass\n\n def __init__(self):\n u\"\"\"コンストラクタ。\n \"\"\"\n import parent as __parent\n self._phase = self._Boot(self)\n self._parent = __parent.Parent()\n self._controler_1p = _input.Main(0)\n self._is_error = False\n\n def boot(self):\n u\"\"\"ゲーム開始時処理。\n \"\"\"\n if not _effects.Effect.is_active():\n self._1p.set_throwing()\n self._2p.set_throwing()\n self._phase = self._Drive(self)\n\n def release(self):\n u\"\"\"魔術開放処理。\n \"\"\"\n self._1p.release(self._2p)\n self._2p.release(self._1p)\n\n def throw(self):\n u\"\"\"ピース投下時処理。\n \"\"\"\n self._1p.throw(self._2p)\n self._2p.throw(self._1p)\n\n def command_io(self):\n u\"\"\"コマンド入出力。\n \"\"\"\n self._controler_1p.input()\n self._1p.command_input(self._controler_1p.output())\n self._1p.command_run(self._2p)\n self._1p.fall()\n self._2p.thinker.start()\n self._2p.command_input(self._2p.thinker.output())\n self._2p.command_run(self._1p)\n self._2p.fall()\n\n def completion(self):\n u\"\"\"フィールド補完処理。\n \"\"\"\n if not self._1p.is_lose:\n self._1p.completion(self._2p)\n if not self._2p.is_lose:\n self._2p.completion(self._1p)\n\n def terminate(self):\n u\"\"\"メインゲーム終了処理。\n \"\"\"\n if self._1p.is_game_over or self._2p.is_game_over:\n self._phase = self._Disappear(self)\n\n def disappear(self):\n u\"\"\"セルの消去処理。\n \"\"\"\n if self._1p.is_lose:\n self._1p.blocks.vanish()\n if self._2p.is_lose:\n self._2p.blocks.vanish()\n self._phase = self._Crushing(self)\n\n def crushing(self):\n u\"\"\"クリーチャー撃破処理。\n \"\"\"\n if not (\n self._1p.blocks.field.is_active or\n self._2p.blocks.field.is_active\n ):\n if self._1p.is_lose:\n self._1p.battle.turn(True)\n if self._2p.is_lose:\n self._2p.battle.turn(True)\n self._phase = self._Winning(self)\n\n def winning(self):\n u\"\"\"勝利・敗北エフェクト。\n \"\"\"\n if not _effects.Effect.is_active():\n if not self._1p.is_win and not self._2p.is_win:\n _sound.SE.play(\"draw\")\n _effects.Draw(_screen.Screen.get_base().get_rect().center)\n else:\n (_effects.Win if self._1p.is_win else _effects.Lose)(\n self._1p.blocks.window.rect.center)\n (_effects.Win if self._2p.is_win else _effects.Lose)(\n self._2p.blocks.window.rect.center)\n self._phase = self._Result(self)\n\n def _lose(self):\n u\"\"\"敗北時処理。\n \"\"\"\n def _get_sp(self, total):\n u\"\"\"追加するSPを取得\n \"\"\"\n return (\n total << 2 if self._rank == 3 else\n total+(total << 1) if self._rank == 2 else\n total << 1 if self._rank == 1 else total)\n\n def result(self):\n u\"\"\"リザルト処理。\n \"\"\"\n if not _effects.Effect.is_active():\n if self._1p.is_win:\n added = self._get_sp(self._1p.resorce.total)\n _inventory.SP.add(added)\n _sound.SE.play(\"bonus\")\n self._1p.battle.player.add_effect(_effects.Bonus(\n _screen.Screen.get_base().get_rect().center, added))\n self._1p.resorce.init_stars()\n if self._1p.is_lose:\n self._lose()\n self._phase = self._Finish(self)\n\n def finish(self):\n u\"\"\"終了処理。\n \"\"\"\n if not _effects.Effect.is_active():\n if self._2p.thinker:\n self._2p.thinker.terminate()\n self._phase = self._Done(self)\n\n def _reset(self):\n u\"\"\"リセット時処理。\n \"\"\"\n def manage(self):\n u\"\"\"ゲーム進行管理。\n \"\"\"\n def __pause_run():\n u\"\"\"ゲーム停止時のコマンド。\n \"\"\"\n import material.sound as __sound\n import utils.const as __const\n self._controler_1p.input()\n output = self._controler_1p.output()\n if output == __const.START_COMMAND:\n self._1p.is_paused = self._2p.is_paused = False\n __sound.BGM.unpause()\n elif output == __const.SELECT_COMMAND:\n self._reset()\n if self._2p.thinker:\n self._2p.thinker.terminate()\n self._phase = self._Done(self)\n if self.is_paused:\n __pause_run()\n else:\n self._phase.run()\n\n @property\n def is_win(self):\n u\"\"\"1P勝利状態取得。\n \"\"\"\n return self._1p.is_win\n\n @property\n def is_paused(self):\n u\"\"\"ポーズ状態取得。\n \"\"\"\n return self._1p.is_paused or self._2p.is_paused\n\n @property\n def is_done(self):\n u\"\"\"ゲーム終了状態取得。\n \"\"\"\n return isinstance(self._phase, self._Done)\n\n @property\n def is_error(self):\n u\"\"\"エラー発生状態取得。\n \"\"\"\n return self._is_error\n\n\nclass Duel(__Manager):\n u\"\"\"デュエル進行管理。\n \"\"\"\n __slots__ = ()\n\n def __init__(self):\n u\"\"\"コンストラクタ。\n level: 2P側のレベル。\n \"\"\"\n level = _level.get_duel()\n number, self._rank = level.player\n _sound.BGM.play(\"lv{lv}\".format(lv=self._rank+1))\n _effects.Rival(\n _screen.Screen.get_base().get_rect().center,\n _units.get_player(number).name)\n super(Duel, self).__init__()\n _image.BackGround.set_image(_misc.get(_const.BG_DICT[number]))\n self._1p = _main.System(_level.get_1p(self._rank), self._parent, id_=0)\n self._2p = _main.System(level, self._parent, id_=1)\n self._2p.set_thinker(self._1p)\n\n\nclass Endless(__Manager):\n u\"\"\"エンドレス進行管理。\n \"\"\"\n __slots__ = ()\n\n def __init__(self):\n u\"\"\"コンストラクタ。\n level: 2P側のレベル。\n \"\"\"\n _effects.Level(\n _screen.Screen.get_base().get_rect().center,\n _inventory.Utils.get_endless()+1)\n super(Endless, self).__init__()\n level = _level.get_endless()\n number, self._rank = level.player\n _sound.BGM.play(\"lv{lv}\".format(lv=self._rank+1))\n _image.BackGround.set_image(_misc.get(_const.BG_DICT[number]))\n self._1p = _main.System(_level.get_1p(self._rank), self._parent, id_=0)\n self._2p = _main.System(level, self._parent, id_=1)\n self._2p.set_thinker(self._1p)\n\n def _lose(self):\n u\"\"\"敗北時処理。\n \"\"\"\n _inventory.Utils.set_endless(\n _inventory.Utils.get_endless()-_const.ENDLESS_INTRVAL)\n\n def _reset(self):\n u\"\"\"リセット時処理。\n \"\"\"\n self._lose()\n\n\nclass Versus(__Manager):\n u\"\"\"ヴァーサス進行管理。\n \"\"\"\n __slots__ = \"__controler_2p\",\n\n def __init__(self):\n u\"\"\"コンストラクタ。\n level: 2P側のレベル。\n \"\"\"\n level = _level.get_2p()\n number, self._rank = level.player\n _sound.BGM.play(\"lv{lv}\".format(lv=self._rank+1))\n _effects.Rival(\n _screen.Screen.get_base().get_rect().center,\n _units.get_player(number).name)\n super(Versus, self).__init__()\n self.__controler_2p = _input.Main(1)\n self._is_error = self.__controler_2p.is_init_error\n if not self._is_error:\n self._controler_1p.is_keyboard_useable = False\n self.__controler_2p.is_keyboard_useable = False\n _image.BackGround.set_image(_misc.get(_const.BG_DICT[number]))\n self._1p = _main.System(\n _level.get_1p(self._rank), self._parent, id_=0)\n self._2p = _main.System(level, self._parent, id_=1)\n self._1p.is_pauseable = False\n self._2p.is_pauseable = False\n\n def command_io(self):\n u\"\"\"コマンド入出力。\n \"\"\"\n self._controler_1p.input()\n self._1p.command_input(self._controler_1p.output())\n self._1p.command_run(self._2p)\n self._1p.fall()\n self.__controler_2p.input()\n self._2p.command_input(self.__controler_2p.output())\n self._2p.command_run(self._1p)\n self._2p.fall()\n\n def result(self):\n u\"\"\"リザルト処理。\n \"\"\"\n if not _effects.Effect.is_active():\n added = self._get_sp(\n self._1p.resorce.total+self._2p.resorce.total >> 1)\n _inventory.SP.add(added)\n _sound.SE.play(\"bonus\")\n self._1p.battle.player.add_effect(_effects.Bonus(\n _screen.Screen.get_base().get_rect().center, added))\n self._1p.resorce.init_stars()\n self._2p.resorce.init_stars()\n self._phase = self._Finish(self)\n","sub_path":"Source/game/system/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":11924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"251592674","text":"### AUTHOR: TMRM \n### PROJECT: INTRO TO PYTHON - TRIVIA GENERATOR\n### VER: 1.2\n### DATE: 06-16-2020\n\n### Declare CALLs ###\n\n\n### INSTALL REQUESTS ###\n\"\"\"\nimport subprocess\nimport sys\n\n\ndef install(requests):\n subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", package])\n\"\"\"\n### CALL REQUESTS ###\nimport time\nimport random\nimport turtle\nfrom tkinter import *\nfrom tkinter.ttk import *\n\ndef selected():\n x = radiovar.get() \n\n## Submit Button\ndef clicked():\n \n \n import requests\n import json\n lb2.configure(text=\"\")\n lb3.configure(text=\"\")\n lb4.configure(text=\"\")\n cat_combo.destroy()\n amount_combo.destroy()\n diff_combo.destroy()\n lbl.configure(text=\"LET'S GO\")\n print(amount)\n print(cat)\n print(diff)\n #SET COMPATIBLE PARAMS FOR WEBSITE\n params = (('amount', amount),('category', cat),('difficulty', diff),('type', 'multiple'),)\n ## SEND PARAMS TO WEBSITE WITH REQUESTS\n r = requests.get('https://opentdb.com/api.php?', params = params)\n ## CLEANING THE TEXT\n pretty_json = json.loads(r.text)\n # print (json.dumps(pretty_json, indent=2))\n # print(pretty_json['results'])\n quiz = (pretty_json['results'])\n print (\"\\n ---------------------------------------------------------\")\n print (type(quiz))\n print (quiz)\n #Print the First Category Chosen\n print (quiz[0]['category'])\n #Print the First Question Generated\n print (quiz[0]['question'])\n #The First Question's Possible Answers\n #CORRECT ANSWER\n #print (quiz[0]['correct_answer'])\n #LIST OF WRONG ANSWERS\n #print (quiz[0]['incorrect_answers'])\n #WRONG ANSWERS\n #print (quiz[0]['incorrect_answers'][0])\n #print (quiz[0]['incorrect_answers'][1])\n #print (quiz[0]['incorrect_answers'][2])\n #Print the Second Category Chosen\n #print (quiz[1]['category'])\n print (\"---------------------------------------------------------\")\n answer_list = [(quiz[0]['correct_answer']), (quiz[0]['incorrect_answers'][0]), (quiz[0]['incorrect_answers'][1]), (quiz[0]['incorrect_answers'][2])]\n #randomly arrange answers\n random.shuffle(answer_list)\n print (answer_list)\n #Radio Button Logic\n lb5 = Label(window, text=\"Select Your Answer: \")\n lb5.grid(column=10, row=0)\n rad1 = Radiobutton(window,text= answer_list[0], indicatoron = 0, value= answer_list[0], command=selected) \n rad2 = Radiobutton(window,text= answer_list[1], indicatoron = 0, value= answer_list[1], command=selected)\n rad3 = Radiobutton(window,text= answer_list[2], indicatoron = 0, value= answer_list[2], command=selected)\n rad4 = Radiobutton(window,text= answer_list[3], indicatoron = 0, value= answer_list[3], command=selected) \n rad1.grid(column=11, row=0)\n rad2.grid(column=12, row=0)\n rad3.grid(column=13, row=0)\n rad3.grid(column=14, row=0)\n btn2 = Button(window, text=\"SUBMIT ANSWER\", command=check)\n btn2.grid(column=15, row=0)\n\n\ndef checked():\n\n print(selected.get())\n #GUESS RESOLUTION LOGIC\n if selected.get() == quiz[0]['correct_answer']:\n print (\"Congratulations!\")\n score = score + 1\n\n\n\n\n### GUI WORKSPACE ### \nwindow = Tk()\n \nwindow.title(\"OPEN QUIZ\")\n \nwindow.geometry('1920x1080')\n\nwindow.config(background=\"#ffffff\")\n\nwindow.resizable(0,0)\n\nlbl = Label(window, text=\"Hello, and welcome to OPEN QUIZ\")\n \nlbl.grid(column=0, row=0)\n\n\n#Question Selector\n\nlb2 = Label(window, text=\"How many questions would you like? \")\n \nlb2.grid(column=1, row=0)\n\n \namount_combo = Combobox(window)\n \namount_combo['values']= (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)\n \namount_combo.current(0) #set the selected item\n \namount_combo.grid(column=2, row=0)\n\namount = amount_combo.get()\n\n#Category Selector\nlb3 = Label(window, text=\"What Category of Question would you like? \")\n \nlb3.grid(column=3, row=0)\n\n \ncat_combo = Combobox()\n \ncat_combo['values']= (\"General Knowledge\", \"Books\", \"Film\", \"Music\", \"Musicals & Theatre\", \"Television\", \"Video Games\", \"Board Games\", \"Nature\", \"Computers\", \"Mathematics\", \"Mythology\", \"Sports\", \"Geography\", \"History\", \"Politics\", \"Art\", \"Celebrities\", \"Animals\")\n\ncat_combo.current(0) #set the selected item\n \ncat_combo.grid(column=4, row=0)\n\ncat_raw = cat_combo.get()\n\n## CONVERT CAT_RAW TO CAT\n\nif cat_raw == 'General Knowledge':\n\tcat = 9\t\nelif cat_raw == 'Books':\n\tcat = 10\nelif cat_raw == 'Film':\n\tcat = 11\nelif cat_raw == 'Music':\n\tcat = 12\nelif cat_raw == 'Musicals & Theatre':\n\tcat = 13\nelif cat_raw == 'Television':\n\tcat = 14\nelif cat_raw == 'Video Games':\n\tcat = 15\nelif cat_raw == 'Board Games':\n\tcat = 16\nelif cat_raw == 'Nature':\n\tcat = 17\nelif cat_raw == 'Computers':\n\tcat = 18\nelif cat_raw == 'Mathematics':\n\tcat = 19\nelif cat_raw == 'Mythology':\n\tcat = 20\nelif cat_raw == 'Sports':\n\tcat = 21\nelif cat_raw == 'Geography':\n\tcat = 22\nelif cat_raw == 'History':\n\tcat = 23\nelif cat_raw == 'Politics':\n\tcat = 24\nelif cat_raw == 'Art':\n\tcat = 25\nelif cat_raw == 'Celebrities':\n\tcat = 26\nelif cat_raw == 'Animals':\n\tcat = 27\n\n\n#Difficulty Selector\n\nlb4 = Label(window, text=\"What difficulty of question would you like? \")\n \nlb4.grid(column=5, row=0)\n\n \ndiff_combo = Combobox(window)\n \ndiff_combo['values']= (\"Easy\", \"Medium\", \"Hard\")\n \ndiff_combo.current(0) #set the selected item\n \ndiff_combo.grid(column=6, row=0)\n\ndiff = diff_combo.get()\n\n\nbtn1 = Button(window, text=\"START QUIZ\", command=clicked)\n \nbtn1.grid(column=7, row=0)\n\n\n\n\n### CLOSE OUT GUI\nwindow.mainloop()\n\n\"\"\"\n####################################\n# TURTLE CMDs\n##OUTPUTs\n\n\n\n\nt = turtle.Turtle(window)\n#TURTLE: RED LETTER E\n\nt.color(\"red\")\n\nt.down()\n\nt.begin_fill()\n\nt.forward(100)\n\nt.right(90)\n\nt.forward(30)\n\nt.right(90)\n\nt.forward(100)\n\nt.left(90)\n\nt.forward(50)\n\nt.left(90)\n\nt.forward(100)\n\nt.right(90)\n\nt.forward(30)\n\nt.right(90)\n\nt.forward(100)\n\nt.left(90)\nt.forward(50)\n\nt.left(90)\n\nt.forward(100)\n\nt.right(90)\n\nt.forward(30)\n\nt.right(90)\n\nt.forward(130)\n\nt.right(90)\n\nt.forward(190)\n\nt.right(90)\n\nt.forward(130)\n\nt.end_fill()\n\nt.up()\n\nturtle.done()\n\n####################################\n\"\"\"\n\n\n","sub_path":"Intro To Python/TMRM - Py Trivia Generator/VER/Project - Py Trivia Generator - TMRM [V1].py","file_name":"Project - Py Trivia Generator - TMRM [V1].py","file_ext":"py","file_size_in_byte":6007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"248572834","text":"class Vertex:\n def __init__(self, key):\n self.key = key\n self.left = None\n self.right = None\n\n\nclass Tree:\n def __init__(self):\n self.root = None\n\n\ndef tree_insert(current_root, new_vertex):\n if not current_root:\n return new_vertex\n if new_vertex.key < current_root.key:\n current_root.left = tree_insert(current_root.left, new_vertex)\n elif new_vertex.key > current_root.key:\n current_root.right = tree_insert(current_root.right, new_vertex)\n return current_root\n\n\ndef is_balance(vertex, is_alright):\n if not vertex:\n return is_alright, 0\n else:\n right_is_alright, right_height = is_balance(vertex.right, True)\n left_is_alright, left_height = is_balance(vertex.left, True)\n if abs(right_height - left_height) > 1 or \\\n not right_is_alright or not left_is_alright:\n is_alright = False\n return is_alright, max(right_height, left_height) + 1\n\n\ndef main():\n numbers = list(map(int, input().split()))\n tree = Tree()\n for item in numbers:\n if item != 0:\n tree.root = tree_insert(tree.root, Vertex(item))\n if is_balance(tree.root, True)[0]:\n print('YES')\n else:\n print('NO')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Homework 5/Task_G.py","file_name":"Task_G.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"572286586","text":"class Solution:\n def findJudge(self, N: int, trust: List[List[int]]) -> int:\n judge = [0]*N \n for i in range(len(trust)):\n judge[trust[i][0] - 1] -= 1\n judge[trust[i][1] - 1] += 1\n if (N-1) in judge:\n return 1 + judge.index(N-1)\n else:\n return -1\n#O(n) time and O(n) space","sub_path":"Array/findTownJudge.py","file_name":"findTownJudge.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"15771024","text":"from captureAgents import CaptureAgent\r\nimport distanceCalculator\r\nimport util\r\nfrom game import Directions\r\nfrom capsule import ScareCapsule, GrenadeCapsule, ArmourCapsule, SonarCapsule, JuggernautCapsule\r\nimport contestPowersBayesNet\r\nimport baselineTeam as baseline\r\nimport random\r\nimport numpy\r\nimport math\r\nimport heapq\r\n\r\nfrom baselineTeam import OffensiveReflexAgent, DefensiveReflexAgent\r\n#################\r\n# Team creation #\r\n#################\r\nclass Team:\r\n def createAgents(self, firstIndex, secondIndex, isRed, gameState,\r\n first = 'JacksonSipple', second = 'JacksonSipple'):\r\n \"\"\"\r\n This function should return a list of two agents that will form the\r\n team, initialized using firstIndex and secondIndex as their agent\r\n index numbers. isRed is True if the red team is being created, and\r\n will be False if the blue team is being created.\r\n \"\"\"\r\n self.agents = [eval(first)(firstIndex, gameState), eval(second)(secondIndex, gameState)]\r\n self.isRed = isRed\r\n\r\n return self.agents\r\n\r\n def chooseCapsules(self, gameState, capsuleLimit, opponentEvidences):\r\n P = PowersInference()\r\n e_1 = [ opponentEvidences[0]['sum0'], opponentEvidences[0]['sum1'], opponentEvidences[0]['sum2'], opponentEvidences[0]['sum3'] ]\r\n e_2 = [ opponentEvidences[1]['sum0'], opponentEvidences[1]['sum1'], opponentEvidences[1]['sum2'], opponentEvidences[1]['sum3'] ]\r\n\r\n P.infer(e_1, 0)\r\n P.infer(e_2, 1)\r\n\r\n #Tells us maze distances\r\n distancer = distanceCalculator.Distancer(gameState.data.layout)\r\n distancer.getMazeDistances()\r\n\r\n kmeans = KMeans( gameState, self.isRed )\r\n food = gameState.getRedFood().asList() if not self.isRed else gameState.getBlueFood().asList()\r\n scare_locations = kmeans.pick_capsules( food, distancer )\r\n\r\n capsules = []\r\n for location in scare_locations:\r\n x, y = location\r\n capsules.append( ScareCapsule(x, y) )\r\n\r\n \"\"\"\r\n grenade_locations = self.pick_grenades( gameState, distancer )\r\n\r\n for (x, y) in grenade_locations:\r\n capsules.append( GrenadeCapsule(x, y) )\r\n\r\n \"\"\"\r\n\r\n return capsules\r\n\r\n def pick_grenades(self, gameState, distancer):\r\n\r\n if self.isRed:\r\n idxes = gameState.getRedTeamIndices()\r\n else:\r\n idxes = gameState.getBlueTeamIndices()\r\n\r\n grenades = []\r\n for idx in idxes:\r\n pos = gameState.getInitialAgentPosition(idx)\r\n tests = [(pos[0] + 1, pos[1]), (pos[0] - 1, pos[1]), (pos[0], pos[1] + 1),\r\n (pos[0], pos[1] - 1)]\r\n for test in tests:\r\n if not gameState.hasWall(test[0], test[1]) and test not in grenades:\r\n grenades.append(test)\r\n break\r\n return grenades\r\n\r\n##########\r\n# Agents #\r\n##########\r\nargmin = lambda x: min( range(len(x)), key = lambda i: x[i] )\r\nnonnegative = lambda x: all( [n >= 0 for n in x] )\r\nstep_away = lambda x, l: [ y for y in l if manhattan(x, y) == 1 ]\r\n\r\n# Prioritizes staying alive. Then prioritizes killing opponent. Then\r\n# prioritizes attacking opponents when they are on my side (one pacman\r\n# per opponent). Then and only then prioritizes eating food.\r\n# Thought capacity was useless. Scare pellets seemed to work best\r\n# (made logic for grenades but not as good)\r\n# Named after Jackson Sipple for no particular reason except \r\n# to possibly confuse him later\r\nclass JacksonSipple(CaptureAgent):\r\n\r\n ATTACK_OPP = None\r\n opp_info = []\r\n\r\n\r\n def choosePowers(self, gameState, powerLimit):\r\n return {'invisibility': 1, 'speed': 2, 'laser': 1, 'respawn': 0, 'capacity': 0}\r\n\r\n def registerInitialState(self, gameState):\r\n self.start = gameState.getAgentPosition(self.index)\r\n CaptureAgent.registerInitialState(self, gameState)\r\n\r\n if JacksonSipple.ATTACK_OPP == None:\r\n JacksonSipple.ATTACK_OPP = random.randint(0,1)\r\n\r\n self.gameState = gameState\r\n self.sight = {}\r\n # initialize info about opponent\r\n\r\n if len(JacksonSipple.opp_info) == 0:\r\n power_dics = self.getOpponentTeamPowers(gameState)\r\n opps = self.getOpponents(gameState)\r\n for opp, power_dic in zip(opps,power_dics):\r\n initial_pos = gameState.getInitialAgentPosition(opp)\r\n JacksonSipple.opp_info.append(OppInfo(opp, power_dic, initial_pos))\r\n OppInfo.lastState = gameState\r\n\r\n # get information about bestDistBack from every opponent square\r\n self.best_back = {}\r\n for x in range(gameState.data.layout.width):\r\n for y in range(gameState.data.layout.height):\r\n if not gameState.hasWall(x,y):\r\n self.best_back[(x, y)] = self.bestDistBack(\r\n not gameState.isRed((x,y)),gameState,(x,y))\r\n\r\n def chooseAction(self, gameState):\r\n\r\n for inf in JacksonSipple.opp_info:\r\n inf.updatePos(self, gameState)\r\n OppInfo.lastState = gameState\r\n OppInfo.lastAgent = self\r\n\r\n actions = gameState.getLegalActions(self.index)\r\n acts = {}\r\n for act in actions:\r\n acts[act] = gameState.generateSuccessor(act)\r\n\r\n self.gameState = gameState\r\n acts = self.getGrenades(gameState,acts)\r\n acts = self.towardsSafety(gameState, acts)\r\n acts = self.killOpp(gameState, acts)\r\n if JacksonSipple.ATTACK_OPP == 0:\r\n acts = self.attackOpp(gameState, acts)\r\n else:\r\n acts = self.attackOpp2(gameState,acts)\r\n acts = self.eatFood(gameState, acts)\r\n\r\n return random.choice(acts.keys())\r\n\r\n def getPos(self):\r\n return self.gameState.getAgentPosition(self.index)\r\n\r\n def getGrenades(self, gameState, acts):\r\n if gameState.getAgentState(self.index).getBlastPower() == 0:\r\n for act in acts:\r\n if acts[act].getAgentState(self.index).getBlastPower() > 0:\r\n return {act: acts[act]}\r\n return acts\r\n\r\n # Returns best moves for defending capsules\r\n def defendCapsules(self, gameState, acts):\r\n return acts\r\n\r\n def killOpp(self, gameState, acts):\r\n act_keys = acts.keys()\r\n vals = []\r\n for act in acts:\r\n opps_killed = 0\r\n for opp in self.opp_info:\r\n prev_opp_state = gameState.getAgentState(opp.idx)\r\n new_opp_state = acts[act].getAgentState(opp.idx)\r\n if prev_opp_state.deathCount < new_opp_state.deathCount:\r\n opps_killed += 1\r\n vals.append(opps_killed)\r\n\r\n kill_count = max(vals)\r\n best_acts = [a for a,v in zip(act_keys,vals) if v == kill_count]\r\n for act in act_keys:\r\n if act not in best_acts:\r\n del acts[act]\r\n\r\n if len(acts.keys()) > 1 and Directions.BLAST in acts:\r\n del acts[Directions.BLAST]\r\n\r\n return acts\r\n\r\n # Returns best moves for chasing opponent\r\n def attackOpp(self, gameState, acts):\r\n if len( acts.keys() ) == 1:\r\n return acts\r\n\r\n values = {}\r\n for action in acts.keys():\r\n values[action] = 0\r\n\r\n for opponent in JacksonSipple.opp_info:\r\n distance = min( [self.getMazeDistance( gameState.getAgentPosition(self.index), position, gameState ) for position in opponent.loc_distrib] )\r\n if gameState.isRed( gameState.getAgentPosition(self.index) ) == self.red: #Defending\r\n bad_feeling = gameState.getAgentState(self.index).scaredTimer > distance\r\n else:\r\n bad_feeling = gameState.getAgentState(opponent.idx).scaredTimer < distance\r\n\r\n overkill = gameState.getAgentState(opponent.idx).getIsRespawning() # They're already dead dude\r\n overkill = overkill or self.deepInEnemyTerritory(opponent.getPos(), gameState)\r\n if bad_feeling or overkill:\r\n continue\r\n\r\n distances = self.intercept_opponent(opponent, acts)\r\n for action in distances.keys():\r\n values[action] += distances[action]\r\n\r\n actions = acts.keys()\r\n best_val = min( values.values() )\r\n\r\n for action in actions:\r\n if values[action] > best_val:\r\n acts.pop(action)\r\n\r\n if len( acts.keys() ) > 1 and \"Stop\" in acts.keys():\r\n acts.pop(\"Stop\")\r\n\r\n return acts\r\n\r\n def legal(self, position):\r\n negative = position[0] < 0 or position[1] < 0\r\n real_big = position[0] >= self.gameState.data.layout.width\r\n real_big = position[1] >= self.gameState.data.layout.height or real_big\r\n return not negative and not real_big and not self.gameState.hasWall(position[0], position[1])\r\n\r\n def intercept_opponent(self, opponent, actions):\r\n agent_distribution = [ actions[action].getAgentPosition( self.index ) for action in actions ]\r\n opponent_distribution = opponent.loc_distrib\r\n\r\n weights = self.chase_opponent( agent_distribution, opponent_distribution )\r\n control = weights[:2]\r\n regress = weights[2:]\r\n\r\n distances = {}\r\n for action in actions.keys():\r\n new_position = actions[action].getAgentPosition( self.index )\r\n distances[action] = numpy.dot( new_position, regress )\r\n\r\n return distances\r\n\r\n def chase_opponent(self, agent_distribution, opponent_distribution):\r\n coordinates = [ list(location) + list(position) for location in opponent_distribution for position in agent_distribution ]\r\n distances = [ self.getMazeDistance(position, location, self.gameState) for location in opponent_distribution for position in agent_distribution ]\r\n\r\n weights = numpy.linalg.lstsq( coordinates, distances, rcond = -1 )[0]\r\n return weights\r\n\r\n def expand_set(self, position, opponent_position, opponent_radius, trial=0):\r\n laser = self.gameState.getAgentState(self.index).getLaserPower()\r\n sanctuaries = [ location for location in opponent_radius if not self.interceptable(position, opponent_position, location, laser) ]\r\n\r\n if len( sanctuaries ) == 0 or trial == 5:\r\n return opponent_radius\r\n\r\n for haven in sanctuaries:\r\n movement = [ (haven[0] + i, haven[1] + j) for i in range(-1, 2) for j in range(-1, 2) if self.legal((haven[0] + i, haven[1] + j)) ]\r\n for new in movement:\r\n opponent_radius.add(new)\r\n\r\n for haven in sanctuaries:\r\n opponent_radius.remove(haven)\r\n\r\n return self.expand_set(position, opponent_position, opponent_radius, trial + 1)\r\n\r\n def interceptable(self, position, opponent_position, location, laser):\r\n if self.getMazeDistance(position, location, self.gameState) <= self.getMazeDistance(opponent_position, location, self.gameState):\r\n return True\r\n\r\n if laser == 0:\r\n return False\r\n\r\n limit = 6 if laser == 1 else 21\r\n targets = self.line_of_sight(location, position, opponent_position, limit)\r\n for target in targets:\r\n if self.getMazeDistance(position, target, self.gameState) < self.getMazeDistance(opponent_position, target, self.gameState):\r\n return True\r\n\r\n return False\r\n\r\n def line_of_sight(self, target, pos, o_pos, limit):\r\n if target in self.sight.keys():\r\n return self.sight[ target ]\r\n\r\n x_laser, increment = [], 1 if ( pos[0] - o_pos[0] ) > 0 else -1\r\n i = increment\r\n while self.legal( (o_pos[0] + i, o_pos[1]) ) and abs(i) < limit:\r\n x_laser += [ (o_pos[0] + i, o_pos[1]) ]\r\n i += increment\r\n\r\n y_laser, increment = [], 1 if ( pos[1] - o_pos[1] ) > 0 else -1\r\n j = increment\r\n while self.legal( (o_pos[0], o_pos[1] + j) ) and abs(j) < limit:\r\n y_laser += [ (o_pos[0], o_pos[1] + j) ]\r\n j += increment\r\n\r\n self.sight[ target ] = x_laser + y_laser\r\n return self.sight[ target ]\r\n\r\n def deepInEnemyTerritory(self, position, gameState):\r\n distance_to_border = self.bestDistBack( self.red, gameState, position )\r\n return distance_to_border > 7\r\n\r\n # Chooses moves that minimizes distance to opponent on my side\r\n def attackOpp2(self, gameState, acts):\r\n\r\n # Looks to see which opponents should be chased down\r\n to_chase = []\r\n for opp in JacksonSipple.opp_info:\r\n for pos in opp.loc_distrib:\r\n if gameState.isRed(pos) == self.red:\r\n to_chase.append(pos)\r\n break\r\n\r\n if len(to_chase) == 0:\r\n return acts\r\n\r\n # if necessary minimizes distance to opponent's that need to be chased\r\n vals = []\r\n act_lst = acts.keys()\r\n other_pos = gameState.getAgentPosition((self.index + 2) % 4)\r\n for act in act_lst:\r\n my_pos = acts[act].getAgentPosition(self.index)\r\n my_dists = []\r\n other_dists = []\r\n for pos in to_chase:\r\n my_dists.append(self.getMazeDistance(my_pos,pos,acts[act]))\r\n other_dists.append(self.getMazeDistance(other_pos,pos,acts[act]))\r\n\r\n if len(to_chase) == 1:\r\n vals.append(min(my_dists[0],other_dists[0]))\r\n else:\r\n vals.append(min(my_dists[0] + other_dists[1],\r\n my_dists[1] + other_dists[0]))\r\n\r\n bestVal = min(vals)\r\n best_acts = [a for a,v in zip(act_lst,vals) if v == bestVal]\r\n new_acts = {}\r\n for act in best_acts:\r\n new_acts[act] = acts[act]\r\n return new_acts\r\n\r\n # Returns best moves for getting safe\r\n def towardsSafety(self, gameState, acts):\r\n\r\n state = gameState.getAgentState(self.index)\r\n foodHeld = state.numCarrying\r\n foodRemaining = len(self.getFood(gameState).asList())\r\n head_back = foodRemaining <= 2 or foodHeld >= state.getFoodCapacity()\r\n\r\n # looks at safety back for every path choice\r\n safe_dists = {}\r\n for act in acts:\r\n safe_path = self.inferiorSafeMethod(acts[act])\r\n if not safe_path[0]:\r\n unsafe_path = self.getUnsafePath(acts[act])\r\n if unsafe_path[0]:\r\n safe_dists[act] = (2, unsafe_path[1])\r\n else:\r\n safe_dists[act] = (0, safe_path[1])\r\n\r\n # only keeps paths with optimal safety\r\n if len(safe_dists.keys()) == 0:\r\n\r\n return acts\r\n\r\n vals = [safe_dists[act][0] for act in safe_dists]\r\n minVal = min(vals)\r\n best_acts = {}\r\n best_dist = 100000\r\n for act in safe_dists:\r\n if safe_dists[act][0] == minVal:\r\n if not head_back:\r\n best_acts[act] = acts[act]\r\n else:\r\n if safe_dists[act][1] == best_dist:\r\n best_acts[act] = acts[act]\r\n elif safe_dists[act][1] < best_dist:\r\n best_dist = safe_dists[act][1]\r\n best_acts = {}\r\n best_acts[act] = acts[act]\r\n\r\n return best_acts\r\n\r\n # Returns best moves for eating food\r\n def eatFood(self, gameState, acts):\r\n # first checks if a food would be eaten\r\n new_acts = {}\r\n for act in acts:\r\n new_food_len = len(self.getFood(acts[act]).asList())\r\n past_food_len = len(self.getFood(gameState).asList())\r\n if new_food_len < past_food_len:\r\n new_acts[act] = acts[act]\r\n\r\n if len(new_acts.keys()) > 0:\r\n acts = new_acts\r\n\r\n # now looks for optimal next food\r\n\r\n vals = []\r\n act_keys = list(acts.keys())\r\n ally_pos = gameState.getAgentPosition((self.index + 2) % 4)\r\n for act in act_keys:\r\n food = self.getFood(acts[act]).asList()\r\n my_pos = acts[act].getAgentPosition(self.index)\r\n best_score = 100000\r\n\r\n for fd in food:\r\n score = self.getMazeDistance(my_pos, fd, acts[act]\r\n ) - .8 * self.getMazeDistance(my_pos, ally_pos, acts[act])\r\n if score < best_score:\r\n best_score = score\r\n vals.append(best_score)\r\n\r\n minVal = min(vals)\r\n best_acts = [a for a,v in zip(act_keys,vals) if v == minVal]\r\n new_acts = {}\r\n for act in best_acts:\r\n new_acts[act] = acts[act]\r\n\r\n return new_acts\r\n\r\n # If red is true/false, gets shortest distance to red/blue side\r\n def bestDistBack(self, red, gameState, pos):\r\n\r\n if red == gameState.isRed(pos):\r\n return 0\r\n\r\n if pos in self.best_back:\r\n return self.best_back[pos]\r\n\r\n x = gameState.data.layout.width / 2\r\n if red:\r\n x -= 1\r\n else:\r\n x += 1\r\n y_ops = [i for i in range(gameState.data.layout.height)]\r\n\r\n best = 1000000\r\n for y in y_ops:\r\n if not gameState.hasWall(x,y):\r\n test = self.getMazeDistance((x, y), pos, gameState)\r\n if test < best:\r\n best = test\r\n return best\r\n\r\n # Returns (1) if there is a safe path back (taking into account lasers)\r\n # and (2) the distance\r\n def getSafePath(self, gameState, lasers):\r\n\r\n pq = []\r\n my_start_pos = gameState.getAgentPosition(self.index)\r\n heapq.heappush(pq, (1, 1, my_start_pos))\r\n seen = set([my_start_pos])\r\n pseudo_lasers = True\r\n while pq:\r\n next_pos = heapq.heappop(pq)\r\n if not self.safeMove(next_pos[2],next_pos[1],gameState,pseudo_lasers):\r\n continue\r\n if not lasers:\r\n pseudo_lasers = False\r\n if self.red == gameState.isRed(next_pos[2]):\r\n return True,next_pos[1]\r\n\r\n tests = [(next_pos[2][0] + 1, next_pos[2][1]),\r\n (next_pos[2][0] - 1, next_pos[2][1]),\r\n (next_pos[2][0], next_pos[2][1] + 1),\r\n (next_pos[2][0], next_pos[2][1] - 1)]\r\n for test in tests:\r\n if not gameState.hasWall(test[0], test[1]\r\n ) and test not in seen:\r\n seen.add(test)\r\n heapq.heappush(pq, (self.bestDistBack(self.red,gameState,test) +\r\n next_pos[1] + 1, next_pos[1] + 1, test))\r\n\r\n return False,0\r\n\r\n # Returns if there is and unsafe path where I probably/maybe\r\n # won't immediately die and the distance back\r\n def getUnsafePath(self, gameState):\r\n if gameState.getAgentState(self.index).getIsRespawning():\r\n return False, 0\r\n my_pos = gameState.getAgentPosition(self.index)\r\n if self.safeMove(my_pos, 1, gameState, True):\r\n return True, self.bestDistBack(self.red, gameState, my_pos)\r\n else:\r\n #print('unsafe')\r\n #for opp in JacksonSipple.opp_info:\r\n # print(gameState.getAgentState(opp.idx).scaredTimer)\r\n return False, 0\r\n\r\n # More efficient less comprehensive safe method\r\n def inferiorSafeMethod(self, gameState):\r\n my_agent = gameState.getAgentState(self.index)\r\n my_pos = gameState.getAgentPosition(self.index)\r\n my_dist_back = self.bestDistBack(self.red, gameState, my_pos) + 1\r\n alt_dist = my_dist_back\r\n\r\n my_caps = self.getCapsules(gameState)\r\n for cap in my_caps:\r\n cap_loc = cap.getPosition()\r\n test_dist = self.getMazeDistance(cap_loc, my_pos, gameState)\r\n if alt_dist == None or test_dist < alt_dist:\r\n alt_dist = test_dist\r\n\r\n\r\n if not self.safeMove(my_pos,1,gameState,True):\r\n return False,0\r\n\r\n for opp in JacksonSipple.opp_info:\r\n\r\n opp_agent = gameState.getAgentState(opp.idx)\r\n speed_ratio = opp_agent.getSpeed() / my_agent.getSpeed()\r\n\r\n if opp_agent.getIsRespawning():\r\n continue\r\n elif opp_agent.scaredTimer > 0:\r\n continue\r\n for pos in opp.loc_distrib:\r\n opp_dist_back = self.bestDistBack(self.red,gameState,pos)\r\n dist_to_me = self.getMazeDistance(my_pos, pos, gameState)\r\n if math.floor(dist_to_me / speed_ratio) <= alt_dist / 2 or (\r\n opp_dist_back * speed_ratio < my_dist_back and\r\n math.floor(dist_to_me / speed_ratio) <= alt_dist):\r\n return False,0\r\n\r\n return True, my_dist_back\r\n\r\n def safeMove(self, new_pos, moves_to_new_pos, gameState, lasers):\r\n my_state = gameState.getAgentState(self.index)\r\n if my_state.getIsRespawning():\r\n return False\r\n invis = my_state.getInvisibility()\r\n if invis == 2:\r\n danger_range = 2\r\n elif invis == 1:\r\n danger_range = 5\r\n else:\r\n danger_range = None\r\n for opp in JacksonSipple.opp_info:\r\n opp_state = gameState.getAgentState(opp.idx)\r\n if opp_state.isRespawning:\r\n continue\r\n speed_ratio = opp_state.getSpeed() / my_state.getSpeed()\r\n\r\n opp_moves = math.ceil(moves_to_new_pos * speed_ratio)\r\n if opp_state.scaredTimer > 0 and not (self.red == gameState.isRed(new_pos)\r\n and my_state.scaredTimer > 0):\r\n continue\r\n for pos in opp.loc_distrib:\r\n if (util.manhattanDistance(pos,new_pos) - opp_moves + 1 <= 2 and\r\n opp_state.getBlastPower() > 0) and opp_state.scaredTimer == 0:\r\n return False\r\n elif self.getMazeDistance(pos,new_pos,gameState) <= opp_moves and (\r\n (my_state.scaredTimer > 0 and self.red == gameState.isRed(new_pos))\r\n or (self.red != gameState.isRed(new_pos) and opp_state.scaredTimer == 0)):\r\n return False\r\n elif lasers and opp_state.scaredTimer == 0 and len(opp.loc_distrib) == 1:\r\n ran = 0\r\n if danger_range == 2 and opp_state.getLaserPower() > 0:\r\n ran = 2\r\n elif (danger_range == 5 and opp_state.getLaserPower() > 0\r\n ) or (opp_state.getLaserPower() == 1 and danger_range == None):\r\n ran = 5\r\n elif opp_state.getLaserPower() == 2:\r\n ran = None\r\n\r\n add_x = 1\r\n while not gameState.hasWall(\r\n new_pos[0] + add_x, new_pos[1]) and (ran == None or\r\n add_x <= ran):\r\n if self.getMazeDistance(\r\n (new_pos[0] + add_x,new_pos[1]),pos,gameState) < opp_moves:\r\n return False\r\n add_x += 1\r\n\r\n sub_x = 1\r\n while not gameState.hasWall(\r\n new_pos[0] - sub_x, new_pos[1]) and (ran == None or\r\n sub_x <= ran):\r\n if self.getMazeDistance(\r\n (new_pos[0] - sub_x,new_pos[1]),pos,gameState) < opp_moves:\r\n return False\r\n sub_x += 1\r\n\r\n add_y = 1\r\n while not gameState.hasWall(\r\n new_pos[0], new_pos[1] + add_y) and (ran == None or\r\n add_y <= ran):\r\n if self.getMazeDistance(\r\n (new_pos[0],new_pos[1] + add_y),pos,gameState) < opp_moves:\r\n return False\r\n add_y += 1\r\n\r\n sub_y = 1\r\n while not gameState.hasWall(\r\n new_pos[0], new_pos[1] - sub_y) and (ran == None or\r\n sub_y <= ran):\r\n if self.getMazeDistance(\r\n (new_pos[0],new_pos[1] - sub_y),pos,gameState) < opp_moves:\r\n return False\r\n sub_y += 1\r\n\r\n\r\n return True\r\n\r\n\r\n# Determines solution sets that satisfy the system of equations established by\r\n# the sums. Laser is ALWAYS correct.\r\n\r\n# 46% of the time, every other power is also uniquely known. In 46% of cases,\r\n# every other power is narrowed to two options. This is symmetric (ie, half of\r\n# these pair exactly with the other half). The remaining three cases cannot be\r\n# differentiated from one another.\r\nclass PowersInference:\r\n\r\n def __init__(self):\r\n self.A = [ [0, 0, 0, 1, 1],\r\n [1, 0, 1, 1, 0],\r\n [0, 1, 1, 0, 1],\r\n [1, 1, 0, 0, 0],\r\n [1, 0, 0, 0, 0] ]\r\n\r\n self.A = numpy.array(self.A)\r\n self.assignment = {}\r\n self.prediction = {}\r\n\r\n # Used to generate possible sets\r\n def get_noisy_set(self, sums):\r\n b_set = [ numpy.array(sums + [x]) for x in range(3) ]\r\n x_set = [ numpy.linalg.solve(self.A, b) for b in b_set ]\r\n x_set = [ x for x in x_set if nonnegative(x) and sum(x) <= 4 ]\r\n\r\n return x_set\r\n\r\n # Collects all possible valid sets for given sums for agent index\r\n def infer(self, sums, index):\r\n sums = list(sums)\r\n x_set = self.get_noisy_set(sums)\r\n\r\n self.assignment[index] = [ [ int(round(n)) for n in x ] for x in x_set ]\r\n return self.assignment[index]\r\n\r\n # Returns a single possible valid answer, given the sums for agent index\r\n def make_guess(self, index):\r\n if index not in self.prediction.keys():\r\n self.prediction[index] = self.assignment[index][0]\r\n return self.prediction[index]\r\n\r\n # Returns a set of possible values power can hold for agent index\r\n def get_knowledge(self, index, power):\r\n powers = {'invisibility': 0, 'speed': 1, 'laser': 2, 'respawn': 3, 'capacity': 4}\r\n query, p = set(), powers[power]\r\n\r\n for solution in self.assignment[index]:\r\n query.add( solution[p] )\r\n\r\n return query\r\n\r\n# General known or infered information about a given opponent\r\nclass OppInfo:\r\n\r\n # Distributions when extra information about location was obtained about\r\n # where but not which\r\n extra_distribs = []\r\n opps = []\r\n lastState = None\r\n lastAgent = None\r\n\r\n\r\n #power dic holds 'laser', 'speed', 'capacity', 'invisibility', 'respawn''\r\n def __init__(self, idx, power_dic, start_loc):\r\n\r\n self.idx, self.loc = idx, start_loc\r\n self.power_dic = power_dic\r\n self.loc_distrib = set( [self.loc] )\r\n\r\n OppInfo.opps.append(self)\r\n\r\n # accounts for opponent having eaten food in estimating location and returns\r\n # number of food opponent had eaten since last checked\r\n def recently_eaten(self, agent, gameState):\r\n prev_op_agent = OppInfo.lastState.getAgentState(self.idx)\r\n cur_op_agent = gameState.getAgentState(self.idx)\r\n\r\n if prev_op_agent.numCarrying < cur_op_agent.numCarrying:\r\n prevFood = agent.getFoodYouAreDefending(OppInfo.lastState).asList()\r\n curFood = agent.getFoodYouAreDefending(gameState).asList()\r\n eaten = [ f for f in prevFood if f not in curFood ]\r\n if len(eaten) + prev_op_agent.numCarrying == cur_op_agent.numCarrying:\r\n self.loc_distrib = set(eaten)\r\n self.loc = eaten[0]\r\n return len(eaten)\r\n return 0\r\n\r\n def time_update(self, agent, gameState, eaten):\r\n time_diff = OppInfo.lastState.data.timeleft - gameState.data.timeleft\r\n\r\n if time_diff <= 1:\r\n return\r\n\r\n cur_op_agent = gameState.getAgentState(self.idx)\r\n\r\n # need to consider two steps before I take one\r\n agent_state = gameState.getAgentState(agent.index)\r\n other_opp = OppInfo.opps[0]\r\n if other_opp == self:\r\n other_opp = OppInfo.opps[1]\r\n other_state = gameState.getAgentState(other_opp.idx)\r\n\r\n if agent.index == OppInfo.lastAgent.index:\r\n if time_diff == 3 or cur_op_agent.getSpeed() > other_state.getSpeed():\r\n if eaten == 0:\r\n self.guessPos(gameState,agent)\r\n else:\r\n eaten -= 1\r\n elif agent.index > OppInfo.lastAgent.index:\r\n if self.idx < agent.index and self.idx > OppInfo.lastAgent.index:\r\n if eaten == 0:\r\n self.guessPos(gameState,agent)\r\n else:\r\n eaten -= 1\r\n else:\r\n if self.idx == 3 or self.idx == 0:\r\n if eaten == 0:\r\n self.guessPos(gameState,agent)\r\n else:\r\n eaten -= 1\r\n if time_diff >= 4:\r\n if eaten == 0:\r\n self.guessPos(gameState,agent)\r\n else:\r\n eaten -= 1\r\n if time_diff == 3 and cur_op_agent.getSpeed() > other_state.getSpeed():\r\n if eaten == 0:\r\n self.guessPos(gameState,agent)\r\n else:\r\n eaten -= 1\r\n\r\n def updatePos(self, agent, gameState):\r\n\r\n if gameState.getAgentState(self.idx).isRespawning:\r\n self.loc = gameState.getInitialAgentPosition(self.idx)\r\n self.loc_distrib = set([self.loc])\r\n return\r\n elif gameState.getAgentPosition(self.idx) != None:\r\n self.loc = gameState.getAgentPosition(self.idx)\r\n self.loc_distrib = set([self.loc])\r\n return\r\n\r\n # looks to see if food has been eaten and updates position accordingly\r\n eaten = self.recently_eaten( agent, gameState )\r\n if OppInfo.lastAgent != None:\r\n self.time_update( agent, gameState, eaten)\r\n\r\n # if no knowledge, take all on border we know opponent is on\r\n if len(self.loc_distrib) == 0:\r\n x_val = gameState.data.layout.width / 2\r\n if agent.red == gameState.getAgentState(self.idx).isPacman:\r\n x_val -= 1\r\n y_vals = range(0,gameState.data.layout.height - 1)\r\n for y in y_vals:\r\n if not gameState.hasWall(x_val,y):\r\n self.loc_distrib.add((x_val,y))\r\n\r\n my_pos = gameState.getAgentPosition(agent.index)\r\n oth_pos = gameState.getAgentPosition((agent.index + 2) % 4)\r\n\r\n if len(self.loc_distrib) > 6:\r\n new_loc_distrib = set()\r\n while len(new_loc_distrib) < 6:\r\n for pos in [my_pos,oth_pos]:\r\n best = 0\r\n best_loc = None\r\n for loc in self.loc_distrib:\r\n new_dist = agent.getMazeDistance(loc,pos,gameState)\r\n if best_loc == None or new_dist < best:\r\n best = new_dist\r\n best_loc = loc\r\n self.loc_distrib.remove(best_loc)\r\n new_loc_distrib.add(best_loc)\r\n\r\n self.loc_distrib = new_loc_distrib\r\n\r\n '''\r\n dist = util.Counter()\r\n for pos in self.loc_distrib:\r\n dist[pos] = 1.0 / len(self.loc_distrib)\r\n\r\n if self.idx == 0:\r\n agent.displayDistributionsOverPositions([dist])\r\n '''\r\n\r\n #print('index ' + str(self.idx))\r\n #print(len(self.loc_distrib))\r\n\r\n def guessPos(self, gameState, agent):\r\n new_distrib = set()\r\n agent_pos = gameState.getAgentPosition(agent.index)\r\n for pos in self.loc_distrib:\r\n if self.possiblePos(pos, gameState, agent, agent_pos):\r\n new_distrib.add(pos)\r\n if self.possiblePos((pos[0] + 1, pos[1]), gameState, agent, agent_pos):\r\n new_distrib.add((pos[0] + 1, pos[1]))\r\n if self.possiblePos((pos[0] - 1, pos[1]), gameState, agent, agent_pos):\r\n new_distrib.add((pos[0] - 1, pos[1]))\r\n if self.possiblePos((pos[0], pos[1] + 1), gameState, agent, agent_pos):\r\n new_distrib.add((pos[0], pos[1] + 1))\r\n if self.possiblePos((pos[0], pos[1] - 1), gameState, agent, agent_pos):\r\n new_distrib.add((pos[0], pos[1] - 1))\r\n self.loc_distrib = new_distrib\r\n\r\n def possiblePos(self, pos, gameState, agent, agent_pos):\r\n op_agent = gameState.getAgentState(self.idx)\r\n if gameState.hasWall(pos[0], pos[1]) or (op_agent.isPacman == (agent.red\r\n != gameState.isRed(pos))):\r\n return False\r\n elif ( agent.getMazeDistance(pos, agent_pos, gameState ) > 5 and\r\n op_agent.getInvisibility() == 1):\r\n return True\r\n elif ( agent.getMazeDistance(pos, agent_pos, gameState ) > 2 and\r\n op_agent.getInvisibility() == 2):\r\n return True\r\n else:\r\n return False\r\n\r\n def getPos(self):\r\n if len( self.loc_distrib ) == 1:\r\n self.loc = list( self.loc_distrib )[0]\r\n return self.loc\r\n else:\r\n # there are better ways of doing this, we'll see how important it\r\n # is that we do this in a good way\r\n return random.choice( list(self.loc_distrib) )\r\n\r\n def predict_goal(self):\r\n x, y = self.getPos()\r\n # Fix to be mazeDistance 5 or less\r\n cluster = [ (x + i, y + j) for i in range(-5, 6) for j in range(-5, 6) ]\r\n cluster = [ p for p in cluster if self.pather.Position.legal(p) ]\r\n\r\n border, capsules = self.lastState.width / 2, self.lastState.getCapsules()\r\n targets = [ p for p in cluster if self.lastState.hasFood(p) or p in capsules ]\r\n cluster = targets if ( border in capsules or border not in cluster ) else targets + [ border ]\r\n\r\n if len( cluster ) == 0:\r\n # If no easily predicable goal, returns the position. This leads to poor\r\n # interception performance, but will at least chance the opponent down.\r\n return [ (x, y) ]\r\n # Will fix\r\n return random.choice( cluster )\r\n\r\nclass KMeans:\r\n def __init__(self, gameState, red):\r\n self.game_map = gameState\r\n self.red = red\r\n\r\n def pick_capsules(self, food, distancer):\r\n distance_f = lambda x, y: distancer.getDistance( x, y, self.game_map.getWalls() )\r\n mean_s = lambda x, i: sum([n[i] for n in x]) / len(x)\r\n mean_f = lambda x: ( mean_s(x, 0), mean_s(x, 1) )\r\n\r\n clusters = self.k_means(distance_f, mean_f, food, self.splitFoods(food, 8))\r\n\r\n fronts = [ self.front(n, distance_f) for n in clusters ]\r\n means = [ mean_f(n) for n in clusters ]\r\n fronts, means = self.adjust(fronts), self.adjust(means)\r\n\r\n dist_indices = list(range(len(clusters)))\r\n dist_indices.sort(key = lambda i: distance_f( fronts[i], means[i] ))\r\n\r\n size_indices = list(range(len(clusters)))\r\n size_indices.sort(key = lambda i: - len(clusters[i]))\r\n\r\n capsules, i = set([ means[ size_indices[0] ], means[ size_indices[1] ] ]), 2\r\n while len(capsules) == 1:\r\n capsules.add( means[ size_indices[i] ] )\r\n i += 1\r\n\r\n i = 0\r\n while len(capsules) < 4:\r\n capsules.add( fronts[ dist_indices[i] ] )\r\n i += 1\r\n\r\n return list(capsules)\r\n\r\n def front(self, cluster, distance_f):\r\n front, best = random.choice( cluster ), 2**64\r\n width = self.game_map.data.layout.width / 2\r\n width = width - random.randint(1, 3) if self.red else width + random.randint(1, 3)\r\n\r\n for y in range(0, self.game_map.data.layout.height):\r\n point = (width, y)\r\n if not self.valid(point):\r\n continue\r\n\r\n min_dist = min([ distance_f(point, x) for x in cluster ])\r\n\r\n if best > min_dist:\r\n front, best = point, min_dist\r\n\r\n return front\r\n\r\n def valid(self, position):\r\n return self.game_map.isValidPosition(position, self.red)\r\n \"\"\"\r\n negative = position[0] < 0 or position[1] < 0\r\n real_big = position[0] > self.game_map.data.layout.width\r\n real_big = position[1] > self.game_map.data.layout.height or real_big\r\n if negative or real_big:\r\n return False\r\n\r\n walled = self.game_map.hasWall( position[0], position[1] )\r\n fooded = self.game_map.hasFood( position[0], position[1] )\r\n return not walled and not fooded\r\n \"\"\"\r\n def adjust(self, means):\r\n alpha = ( self.game_map.data.layout.width / 2, self.game_map.data.layout.height / 2)\r\n f = lambda x, y, z: int(round(x * z + y * (1 - z)))\r\n\r\n for i in range(len(means)):\r\n counter = 0.99\r\n while not self.valid(means[i]):\r\n means[i] = ( f(means[i][0], alpha[0], counter), f(means[i][1], alpha[1], counter) )\r\n counter -= 0.01\r\n return means\r\n\r\n def k_means(self, distance_f, mean_f, items, clusters, trials=0):\r\n clusters = [x for x in clusters if x]\r\n means = [ mean_f(cluster) for cluster in clusters ]\r\n\r\n means = self.adjust(means)\r\n distances = [ [distance_f(item, mean) for mean in means] for item in items]\r\n\r\n closest = [ argmin(distance_set) for distance_set in distances ]\r\n clusters_prime = [ [items[i] for i in range(len(items)) if closest[i] == j] for j in range(len(clusters)) ]\r\n\r\n differences = [[x for x in clusters[i] if not x in clusters_prime[i]] + [x for x in clusters_prime[i] if not x in clusters[i]] for i in range(len(clusters))]\r\n difference = any(differences)\r\n\r\n if not difference or trials > 10:\r\n return clusters_prime\r\n\r\n return self.k_means(distance_f, mean_f, items, clusters_prime, trials + 1)\r\n\r\n def splitFoods(self, foods, x):\r\n f, n = len(foods), (len(foods) + (x - 1)) // x\r\n split = [foods[i:i + n] for i in range(0, f, n)]\r\n return split\r\n","sub_path":"raw_submissions/myTeam - SEAN ADAM MEDIN.py","file_name":"myTeam - SEAN ADAM MEDIN.py","file_ext":"py","file_size_in_byte":38143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"545564009","text":"from __future__ import print_function\nimport argparse\nimport os\nimport random\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim as optim\nimport torch.utils.data\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nimport torchvision.utils as vutils\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom IPython.display import HTML\nimport time\n#from multiprocessing import freeze_support,Pool\n\"\"\"\nparser = argparse.ArgumentParser()\nparser.add_argument('--dataroot',default='D:/Document/data/CelebA/Img',help='Root diectory for dataset')\nparser.add_argument('--workers',type=int,default=2,help='Number of workers for dataloader')\nparser.add_argument('--batch_size',type=int,default=128,help='batch size during training')\nparser.add_argument('--image_size',type=int,default=64,help='Spatial size of training images.All images.All images will be resized to this size using a transformer')\nparser.add_argument('--nc',type=int,default=3,help='number of channels in the training images. For color images this is 3')\nparser.add_argument('--nz',type=int,default=100,help='size of z latent vector(i.e. size of generator input)')\nparser.add_argument('--ngf',type=int,default=64,help='size of feature maps in generator')\nparser.add_argument('--ndf',type=int,default=64,help='size of feature maps in discriminator')\nparser.add_argument('--num_epochs',type=int,default=5,help='Number of training epochs')\nparser.add_argument('--lr',type=float,default=0.0002,help='Learning rate for optimizers')\nparser.add_argument('--beta1',type=float,default=0.5,help='Beta1 hyperparam for Adam optimizers')\nparser.add_argument('--ngpu',type=int,default=1,help='Number of GPUs available.Use 0 for CPU mode')\nparser.add_argument('--manualSeed',type=int,default=999,help='manual seed')\nopt = parser.parse_args()\n\"\"\"\n# Root directory for dataset\ndataroot = \"D:/Document/data/CelebA/Img\"\n\n# Number of workers for dataloader\nworkers = 2\n\n# Batch size during training\nbatch_size = 128\n\n# Spatial size of training images. All images will be resized to this\n# size using a transformer.\nimage_size = 64\n\n# Number of channels in the training images. For color images this is 3\nnc = 3\n\n# Size of z latent vector (i.e. size of generator input)\nnz = 100\n\n# Size of feature maps in generator\nngf = 64\n\n# Size of feature maps in discriminator\nndf = 64\n\n# Number of training epochs\nnum_epochs = 3\n\n# Learning rate for optimizers\n#lr = 0.0002\nlr = 0.0002\n\n# Beta1 hyperparam for Adam optimizers\nbeta1 = 0.5\n\n# Number of GPUs available. Use 0 for CPU mode.\nngpu = 1\n\nsave_pathG = 'D:/PythonWorks/DCGAN/checkout/parameterG.pkl'\nsave_pathD = 'D:/PythonWorks/DCGAN/checkout/parameterD.pkl'\nsave_pathA = 'D:/PythonWorks/DCGAN/checkout/parameter_1600.pkl'\nsave_path = 'D:/PythonWorks/DCGAN/checkout/'\n\nmanualSeed = 999\n#manualSeed = random.randint(1,1000) #use if you want new result\nprint(\"Random Seed:\",manualSeed)\nrandom.seed(manualSeed)\ntorch.manual_seed(manualSeed)\n#We can use an image folder dataset the way we have it setup\n#Create the dataset\n\ndataset = dset.ImageFolder(root=dataroot,transform=transforms.Compose([\n transforms.Resize(image_size),transforms.CenterCrop(image_size),transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5),(0.5,0.5,0.5)),]))\n#Create the dataloader\ndataloader = torch.utils.data.DataLoader(dataset,batch_size=batch_size,shuffle=True,num_workers=workers)\n#Decide which device we want to run on\ndevice = torch.device(\"cuda:0\" if (torch.cuda.is_available() and ngpu > 0) else \"cpu\")\n\ndef draw(dataloader):\n #Plot some training images\n real_batch = next(iter(dataloader))\n print(len(real_batch))\n #print(real_batch)\n plt.figure(figsize=(8,8))\n plt.axis(\"off\")\n plt.title(\"Training Images\")\n plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64],padding=2,normalize=True).cpu(),(1,2,0)))\n plt.show()\n#custom weights initialization called on netG and netD\n\ndef weights_init(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.normal_(m.weight.data,0.0,0.02)\n elif classname.find('BatchNorm') != -1:\n nn.init.normal_(m.weight.data,1.0,0.02)\n nn.init.constant_(m.bias.data,0)\n\n#Generator Code\n\nclass Generator(nn.Module):\n def __init__(self,ngpu):\n super(Generator,self).__init__()\n self.ngpu = ngpu\n \n self.main = nn.Sequential(\n #input is Z going into a convolution\n #in_channels,out_channels,kernel_size,stride\n nn.ConvTranspose2d(nz,ngf*8,4,1,0,bias=False),\n nn.BatchNorm2d(ngf*8),\n nn.ReLU(True),\n # state size. (ngf*8) x 4 x 4\n nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 4),\n nn.ReLU(True),\n # state size. (ngf*4) x 8 x 8\n nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf * 2),\n nn.ReLU(True),\n # state size. (ngf*2) x 16 x 16\n nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ngf),\n nn.ReLU(True),\n # state size. (ngf) x 32 x 32\n nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False),\n nn.Tanh()\n # state size. (nc) x 64 x 64\n )\n \n def forward(self,input):\n return self.main(input)\n\nclass Discriminator(nn.Module):\n def __init__(self,ngpu):\n super(Discriminator,self).__init__()\n self.ngpu = ngpu\n self.main = nn.Sequential(\n # input is (nc) x64 x64\n nn.Conv2d(nc,ndf,4,2,1,bias=False),\n nn.LeakyReLU(0.2,inplace=True),\n # state size. (ndf) x 32 x 32\n nn.Conv2d(ndf,ndf * 2, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 2),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*2) x 16 x 16\n nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 4),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*4) x 8 x 8\n nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),\n nn.BatchNorm2d(ndf * 8),\n nn.LeakyReLU(0.2, inplace=True),\n # state size. (ndf*8) x 4 x 4\n nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),\n nn.Sigmoid()\n )\n def forward(self,input):\n return self.main(input)\n\n\nnetG = Generator(ngpu).to(device)\nif(device.type == 'cuda') and (ngpu > 1):\n netG = nn.DataParallel(netG,list(range(ngpu)))\n#Apply the weight_init function to randomly initialize all weights\n#to mean=0,stdev=0.2\nnetG.apply(weights_init)\nnetA_CKPT = torch.load(save_pathA)\nnetG.load_state_dict(netA_CKPT['state_dictG'])\n#print(netG)\nnetD = Discriminator(ngpu).to(device)\nif (device.type == 'cuda') and (ngpu > 1):\n netD = nn.DataParallel(netD,list(range(ngpu)))\n#Apply the weights_init function to randomly initialize all weights\n#to mean=0,stdev=0.2\nnetD.apply(weights_init)\nnetD.load_state_dict(netA_CKPT['state_dictD'])\n#netD = torch.load(save_pathD)\n#print(netD)\n#Initialize\ncriterion = nn.BCELoss()\n#Create batch of latent vectors that we will use to visulize\n#the progression of the generator\nfixed_noise = torch.randn(64,nz,1,1,device=device)\n#Establish convention for real and fake labels during training\nreal_label=1\nfake_label=0\n#Stup Adam optimizers for both G and D\noptimizerD = optim.Adam(netD.parameters(),lr=lr,betas=(beta1,0.999))\noptimizerG = optim.Adam(netG.parameters(),lr=lr,betas=(beta1,0.999))\noptimizerG.load_state_dict(netA_CKPT['optimizerG_state_dict'])\noptimizerD.load_state_dict(netA_CKPT['optimizerD_state_dict'])\n#Training Loop\n#Lists to keep track of progress\nimg_list=[]\nG_losses=[]\nD_losses=[]\n\nprint(\"Starting Training Loop...\")\ndef train_net():\n iters=0\n #For each epoch\n for epoch in range(num_epochs):\n \n for i,data in enumerate(dataloader,0):\n #(1):Update D network:maximize log(D(x)) +log(1-D(G(z)))\n #Train with all-real batch,data :torch.Size([128, 3, 64, 64])\n #每次提取出的data维度为([128, 3, 64, 64])\n netD.zero_grad()\n #Format batch\n real_cpu = data[0].to(device)\n b_size = real_cpu.size(0)\n label = torch.full((b_size,),real_label,device=device)\n #Forward pass real batch through D\n output = netD(real_cpu).view(-1)\n #Calculate loss on all-real batch\n errD_real=criterion(output,label)\n #Calculate gradients for D in backward pass\n errD_real.backward()\n #输出的均值,应该趋于1\n D_x=output.mean().item()\n #Train with all-fake batch\n #Generate batch of latent vectors\n noise = torch.randn(b_size,nz,1,1,device=device)\n #Generate fake image batch with G\n fake = netG(noise)\n label.fill_(fake_label)\n #Classify all fake batch wiht D\n output=netD(fake.detach()).view(-1)\n #Calculate D`s loss on the all-fake batch\n errD_fake=criterion(output,label)\n #Calculate the gradients for this batch\n errD_fake.backward()\n #生成网络的输出值均值,应该趋于0\n D_G_z1 = output.mean().item()\n #Add the gradients from the all-real and all-fake batches\n #判别网络总的损失值\n errD = errD_real + errD_fake\n #Update D\n optimizerD.step()\n #(2):Update G network:maximize log(D(G(z)))\n netG.zero_grad\n #fake labels are real for generator cost\n label.fill_(real_label)\n #Since we just update D,perform another forward pass of all-fake batch through D\n #更新梯度后,向生成网络中输入随机数\n output=netD(fake).view(-1)\n #Calculate G`s loss based on this output,判断生成网络生成的图片和真实label之间的损失函数\n errG=criterion(output,label)\n #Calculate gradients for G\n errG.backward()\n #通过一次梯度更新后,生成网络D输出的均值\n D_G_z2=output.mean().item()\n #Update G\n optimizerG.step()\n #output training stats\n if i % 50 ==0:\n print('[%d/%d][%d/%d]\\tLoss_D: %.4f\\tLoss_G: %.4f\\tD(x): %.4f\\tD(G(z)): %.4f / %.4f'% (epoch, \n num_epochs, i, len(dataloader),errD.item(), errG.item(), D_x, D_G_z1, D_G_z2))\n #Save losses for plotting later\n G_losses.append(errG.item())\n D_losses.append(errD.item())\n #Check how the generator is doing by saving G`s output on fixed_noise\n if(iters % 500 == 0) or ((epoch==num_epochs-1) and (i==len(dataloader)-1)):\n with torch.no_grad():\n fake = netG(fixed_noise).detach().cpu()\n img_list.append(vutils.make_grid(fake,padding=2,normalize=True))\n print(\"img_list:\",len(img_list))\n iters += 1\n if(iters % 10 == 0):\n print(\"iters:\",iters)\n if(iters % 100 == 0 or iters == len(dataloader) - 1):\n new_save_path = os.path.join(save_path,'parameter2_'+ str(iters) + '.pkl')\n print(new_save_path)\n if not os.path.exists(new_save_path):\n file = open(new_save_path,'w')\n file.close()\n #time.sleep(1)\n torch.save({\n 'state_dictG':netG.state_dict(),\n 'state_dictD':netD.state_dict(),\n 'optimizerG_state_dict':optimizerG.state_dict(),\n 'optimizerD_state_dict':optimizerD.state_dict()\n },new_save_path)\n #print(\"iters:\",iters)\ndef draw_loss():\n plt.figure(figsize=(10,5))\n plt.title(\"Generator and Discriminator Loss During Training\")\n plt.plot(G_losses,label=\"G\")\n plt.plot(D_losses,label=\"D\")\n plt.xlabel(\"iterations\")\n plt.ylabel(\"Loss\")\n plt.legend()\n plt.show()\n\ndef draw_picf():\n fig = plt.figure(figsize=(8,8))\n plt.axis(\"off\")\n ims = [[plt.imshow(np.transpose(i,(1,2,0)),animated=True)] for i in img_list]\n ani = animation.ArtistAnimation(fig,ims,interval=1000,repeat_delay=1000,blit=True)\n HTML(ani.to_jshtml())\ndef draw_comp():\n # Grab a batch of real images from the dataloader\n real_batch = next(iter(dataloader))\n\n # Plot the real images\n plt.figure(figsize=(15,15))\n plt.subplot(1,2,1)\n plt.axis(\"off\")\n plt.title(\"Real Images\")\n plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))\n\n # Plot the fake images from the last epoch\n plt.subplot(1,2,2)\n plt.axis(\"off\")\n plt.title(\"Fake Images\")\n plt.imshow(np.transpose(img_list[-1],(1,2,0)))\n plt.show()\n\ndef main():\n train_net()\n print(len(img_list))\n #draw_loss()\n #draw_picf()\n draw_comp()\n #printG()\n #printD()\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"dcgan.py","file_name":"dcgan.py","file_ext":"py","file_size_in_byte":13265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"278615364","text":"# -*- coding: UTF-8 -*-\nimport xlsxwriter\nimport urllib.request\nimport json\nimport os\n# 定义函数\ndef getSomeJson(start,end):\n\t# 全局路径\n\tglobalPath = os.getcwd()\n\tprint('globalPath:'+globalPath)\n\tid=start\n\tstreetIdStartPoint = 1\n\twhile id < end :\n\t\tprint('外层遍历,第' + str(id) + '次')\n\t\tcityhtml = urllib.request.urlopen('http://fzwjg.com/m2/s/index.php?cityid='+str(id)).read()\n\t\tisExist=os.path.exists(globalPath+'\\\\'+str(id))\n\t\tif not isExist:\n\t\t\tos.makedirs(\"city\"+str(id))\n\t\tos.chdir(globalPath+'\\\\city'+str(id))\n\t\tprint('创建并进入一级目录,此时的路径为:' + globalPath+'\\\\city'+str(id))\n\n\t\twith open(\"cityinfo.json\",\"wb\") as f:\n\t\t\tf.write(cityhtml)\n\t\t\tf.close()\n\t\t\tlevel1path = os.getcwd()\n\t\t\tprint('在路径为:' + level1path +'写入文件 cityinfo.json')\n\n\t\t\tallAreaHtml = urllib.request.urlopen('http://fzwjg.com/m2/s/index.php?mod=post&action=area&cityid='+str(id)).read()\n\n\t\t\twith open(\"allarea.json\",\"wb\") as f:\n\t\t\t\tf.write(allAreaHtml)\n\t\t\t\t# 写入完毕\n\t\t\t\tf.close()\n\t\t\t\t# 获取此时目录\n\t\t\t\tprint('在路径为:' + level1path +'写入文件 allarea.json')\n\n\t\t\t\t# # 尝试打开文件\n\t\t\t\t# areaJson = open(r'allarea.json')\n\t\t\t\t# # json转为python对象\n\t\t\t\t# print(areaJson)\n\t\t\t\t# try:\n\t\t\t\t# \ts = json.load(areaJson)\n\t\t\t\t# except:\n\t\t\t\t# \t# s = json.load(areaJson)\n\t\t\t\t# \ts = {'areas':{}}\n\t\t\t\t# \tprint(s)\n\t\t\t\t# finally:\n\t\t\t\t# \tprint(s)\n\t\t\t\t# # 初始化length\n\t\t\t\t\n\t\t\t\t# try:\n\t\t\t\t# \t# 尝试获取其area属性的长度\n\t\t\t\t# \tlength = len(s['areas'])\n\t\t\t\t# except :\n\t\t\t\t# \t# 无法读取时为0\n\t\t\t\t# \tlength = 0;\n\t\t\t\t# finally:\t \n\t\t\t\t# \t# 关闭文件\n\t\t\t\t# \tareaJson.close()\n\t\t\t\t# # 输出\n\t\t\t\t# print('length'+str(length))\n\t\t\t\t# # 开始新的遍历\n\t\t\t\t# i = 1\n\n\t\t\t\t# while i < length:\n\t\t\t\t# \tprint(\"内层遍历 第\"+str(i)+\"次\")\n\t\t\t\t# \tallStreetHtml = urllib.request.urlopen('http://fzwjg.com/m2/s/index.php?mod=post&action=street&cityid=' + str(id) + '&areaid=' + str(streetIdStartPoint+ i)).read()\n\t\t\t\t# \tisExist=os.path.exists(str(streetIdStartPoint+i))\n\n\t\t\t\t# \t# if not isExist:\n\t\t\t\t# \t# \tos.makedirs('street'+str(streetIdStartPoint+i))\n\n\t\t\t\t# \t# os.chdir('street'+str(streetIdStartPoint+i))\n\t\t\t\t# \t# level2path = os.getcwd()\n\t\t\t\t# \t# print('创建并进入二级目录'+level2path)\n\n\t\t\t\t# \twith open(\"streetinfo\"+str(i)+\".json\",\"wb\") as f:\n\t\t\t\t# \t\tf.write(allStreetHtml)\n\t\t\t\t# \t\t# 写入完毕\n\t\t\t\t# \t\tf.close()\n\t\t\t\t# \t\tprint('返回一级目录'+level1path)\n\t\t\t\t# \t\t# os.chdir(level1path)\n\t\t\t\t# \ti = i+1\n\t\t\t\t# \tstreetIdStartPoint = streetIdStartPoint+1\n\t\t\t\t# print()\n\t\t\t# os.chdir(level1path)\n\t\t# print(areahtml)\n\t\tos.chdir(globalPath)\n\t\tid=id+1\t\n\n# getSomeJson(4)\ngetSomeJson(105,339)\n","sub_path":"makeWheel/fzwjg/src/mock/cities/getAllIdsInfoJson.py","file_name":"getAllIdsInfoJson.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"553377383","text":"def best_teams():\n \n teamdic = {\"FunPlus Phoenix\": 0,\"Invictus Gaming\": 0,\"G2 esports\": 413,\"SKT Telecom T1\": 1150,\"Griffin\": 0,\"Fnatic\": 158,\"Damwon Gaming\": 1150,\"Team Solo Mid\": 201,\"Royal Never Give Up\": 0,\"C9\": 90,\"Team Liquid\": 150,\"Flash Wolves\": 0}\n mainlist = list(teamdic.values())\n print(\"Here is some good teams below:\\n\")\n z = open(\"teams.txt\",\"r\")\n print(z.read())\n z.close()\n pick1 = int(input(\"View teams above what ranking (ex: 100, 200 etc)? \"))\n for key, value in teamdic.items():\n if value > pick1:\n print(key, value)\n if pick1 > 1150:\n print(\"None\")\n","sub_path":"POPT7.py","file_name":"POPT7.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"289632486","text":"# coding:utf-8\n\nimport requests\nfrom flask import Flask, url_for, request\nfrom flask import render_template\napp = Flask(__name__)\n\n'''\n# 路由装饰器是相对路径,所以以反斜杠开头,相对路径的名字可以自己定义 \n@app.route('/') \ndef index():\n return 'Index Page'\n\n # 可以写成 /hello \n@app.route('/web') \ndef hello():\n return 'Hello World'\n\n# 可以自定以值 当在地址栏输入/user/zyh 他会显示 User zyh 输入 /user/111 会显示 User 111\n@app.route('/user/')\ndef show_user_profile(username):\n # show the user profile for that user\n return 'User %s' % username\n\n\n\n# 可以接受一个整数 /post/111----> Post 111 /post/001---> Post 1\n# 可以接受一个浮点数 占位符为 %f /post/0.1---> Post 0.100000\n# 占位符为 %d /post/1.2---> Post 1\n\n@app.route('/post/')\ndef show_post(post_id):\n # show the post with the given id, the id is an integer\n return 'Post %d' % post_id\n\n\n# 规范的 URL 指向 projects 尾端有一个斜线。 这很像在文件系统中的文件夹。访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范URL去。\n@app.route('/projects/')\ndef projects():\n return 'The project page'\n\n\n# URL 结尾不带斜线,类似 UNIX-like 系统下的文件的路径名。 访问结尾带斜线的 URL 会产生一个 404 “Not Found” 错误。\n@app.route('/about')\ndef about():\n return 'The about page'\n\n\n\n'''\n@app.route('/list/') \ndef list():\n name = ['aaa','ddd','eee']\n url_list = ''\n for x in name:\n url = url_for('list', name=x)\n url_list = url_list + '
' + url\n return url_list\n\n\n'''\n@app.route('/list/')\ndef hello():\n return str({\"param\":request.args.get('abc')})\n'''\n\nif __name__ == '__main__':\n app.run(debug = True)","sub_path":"flask/main_1.py","file_name":"main_1.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"407811110","text":"import unittest\n\nfrom bst_lab import concatenate_leaves\nfrom hypothesis import given\nfrom hypothesis.strategies import recursive\nfrom hypothesis.strategies import text\nfrom hypothesis.strategies import tuples\nfrom hypothesis.strategies import none\n\nclass BTNode:\n \"\"\"\n A Binary Tree, i.e. arity 2.\n === Attributes ===\n @param object data: data in this node of tree\n @param BTNode|None left: left child\n @param BTNode|None right: right child\n @rtype: None\n \"\"\"\n\n\n def __init__(self, data, left=None, right=None):\n \"\"\"\n Create BTNode self with data and children left and right.\n @param BTNode self: this binary tree\n @param object data: data of this node\n @param BTNode|None left: left child\n @param BTNode|None right: right child\n @rtype: None\n \"\"\"\n self.data, self.left, self.right = data, left, right\n\ndef tuples_to_tree(t):\n \"\"\"\n Return a BTNode generated from t and the number of leaves.\n\n Precondition: t is in the form (data, left child, right child) where\n left child and right child are either None, a data, or\n another tuple.\n\n @param tuple(bool, tuple|None|int, tuple|None|int) t: The tuple to turn\n into a BTNode\n @rtype: (BTNode, int)\n \"\"\"\n if t is None:\n return (None, '')\n\n if type(t) == str:\n return (BTNode(t), t)\n\n (left, l_count) = tuples_to_tree(t[1])\n (right, r_count) = tuples_to_tree(t[2])\n concatenate_leaves = l_count + r_count\n\n if not left and not right:\n concatenate_leaves = t[0]\n\n return (BTNode(t[0], left, right), concatenate_leaves)\n\n\nclass ConcatenateLeavesTests(unittest.TestCase):\n def test_returns_int(self):\n \"\"\"\n Test concatenate_leaves to make sure it returns an int.\n \"\"\"\n return_type = type(concatenate_leaves(BTNode(\"a\")))\n\n self.assertEqual(return_type, str,\n \"concatenate_leaves should return type \" +\n \"int, but instead returned type {}.\".format(\n return_type))\n\n def test_none(self):\n \"\"\"\n Test concatenate_leaves on None.\n \"\"\"\n self.assertEqual(concatenate_leaves(None), \"\",\n \"concatenate_leaves on None should \" +\n \"return ''.\")\n\n def test_leaf(self):\n \"\"\"\n Test concatenate_leaves on a leaf.\n \"\"\"\n self.assertEqual(concatenate_leaves(BTNode(\"a\")), \"a\",\n \"concatenate_leaves should\" +\n \" return the leaf's data when used on a leaf.\")\n\n def test_one_left_child(self):\n \"\"\"\n Test concatenate_leaves on a BTNode with one left child.\n \"\"\"\n t = BTNode(\"a\", BTNode(\"b\"))\n self.assertNotEqual(concatenate_leaves(t), \"ab\",\n \"concatenate_leaves should not \" +\n \"count None or any BTNodes with children as\" +\n \" leaf nodes.\")\n self.assertNotEqual(concatenate_leaves(t), \"a\",\n \"concatenate_leaves should not \" +\n \"count None or any BTNodes with children as\" +\n \" leaf nodes.\")\n self.assertEqual(concatenate_leaves(t), \"b\",\n \"concatenate_leaves should return the \" +\n \"data of the leaf child when used on a BTNode \" +\n \"with a single leaf child.\")\n\n def test_one_right_child(self):\n \"\"\"\n Test concatenate_leaves on a BTNode with one right child\n \"\"\"\n t = BTNode(\"a\", None, BTNode(\"b\"))\n self.assertNotEqual(concatenate_leaves(t), \"ab\",\n \"concatenate_leaves should not \" +\n \"count None or any BTNodes with children as\" +\n \" leaf nodes.\")\n self.assertNotEqual(concatenate_leaves(t), \"a\",\n \"concatenate_leaves should not \" +\n \"count None or any BTNodes with children as\" +\n \" leaf nodes.\")\n self.assertEqual(concatenate_leaves(t), \"b\",\n \"concatenate_leaves should return the \" +\n \"data of the leaf child when used on a BTNode \" +\n \"with a single leaf child.\")\n\n def test_two_leaf_children(self):\n \"\"\"\n Test concatenate_leaves on a BTNode with two leaf children.\n \"\"\"\n t = BTNode(\"a\", BTNode(\"b\"), BTNode(\"c\"))\n self.assertEqual(concatenate_leaves(t), \"bc\",\n \"concatenate_leaves should sum all \" +\n \"of the leaves in the entire BTNode.\")\n\n @given(recursive(none() | text(max_size=3),\n lambda children: tuples(text(max_size = 3),\n children,\n children))\n )\n def test_concatenate_leaves(self, tuple_tree):\n \"\"\"\n Test concatenate_leaves on a randomly generated BTNode.\n \"\"\"\n (t, expected) = tuples_to_tree(tuple_tree)\n actual = concatenate_leaves(t)\n self.assertEqual(actual, expected,\n (\"test_concatenate_leaves on BTNode\\n{}\" +\n \"\\nReturned {}\" +\n \" instead of {}.\").format(tuple_tree, actual,\n expected))\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Lab/lab7/test_concatenate_leaves_basic.py","file_name":"test_concatenate_leaves_basic.py","file_ext":"py","file_size_in_byte":5647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"141579114","text":"\"\"\"\r\nПо данным портала открытых данных Москвы определите количество дней, когда освещение включено 12 часов или более.\r\n\"\"\"\r\n\"\"\"\r\ndataset 3288\r\nhttps://data.mos.ru/opendata/3288\r\n\"\"\"\r\nfrom urllib.request import urlopen\r\nimport json\r\n\r\nurl=\"https://apidata.mos.ru/v1/datasets/3288/rows?api_key=c25290a0b5f170f69d45a28665b43168\"\r\nres=urlopen(url).read().decode('utf-8')\r\n\"\"\"\r\nfout=open('out9-3.txt','w',encoding='utf-8')\r\nprint(res,file=fout)\r\n\"\"\"\r\ncnt=0\r\nlst=json.loads(res)\r\nfor now in lst:\r\n if int(now['Cells']['DurationOfLighting'][0:2])>11:\r\n cnt+=1\r\nprint(cnt)#164","sub_path":"lection9/task9-3.py","file_name":"task9-3.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"586248184","text":"\"\"\" 给定一个整数数组 nums 和一个目标值 target,\n请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。 \"\"\"\n\n\"\"\" 给定 nums = [2, 7, 11, 15], target = 9\n因为 nums[0] + nums[1] = 2 + 7 = 9\n所以返回 [0, 1] \"\"\"\n\n\nclass Solution1(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n ret = []\n for i in range(len(nums)):\n subNum = target - nums[i]\n subNums = nums[i+1:]\n for j in range(len(subNums)):\n if subNums[j] == subNum:\n ret.append(i)\n ret.append(j + i + 1)\n return ret\n return ret\n\n\nclass Solution(object):\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n numDict = {}\n for i, num in enumerate(nums):\n if (target - num) in numDict:\n return [i, numDict[target-num]]\n numDict[num] = i\n\n\nif __name__ == \"__main__\":\n nums = [3, 2, 4]\n ret = Solution().twoSum(nums, 6)\n print(ret)\n\n\n","sub_path":"1.twoSum/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"508575301","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# NCTR, Nile Center for Technology Research\n# Copyright (C) 2011-2012 NCTR ().\n#\n##############################################################################\nimport time\nfrom openerp.osv import fields, osv\n\nclass salary_scale_report(osv.osv_memory):\n _name = \"salary.scale.report\"\n\n def _get_months(sel, cr, uid, context):\n months=[(n,n) for n in range(1,13)]\n return months\n\n _columns = {\n 'payroll_id': fields.many2one('hr.salary.scale', 'Salary Scale',required=True),\n 'degree_ids' : fields.many2many('hr.salary.degree','salary_rep_degrees_rel', 'report_id', 'degree_id', 'Degrees', domain=\"[('payroll_id','=',payroll_id)]\", required=True), \n\t\t}\n\n\n def print_report(self, cr, uid, ids, context=None):\n datas = {}\n if context is None:\n context = {}\n data = self.read(cr, uid, ids)[0]\n datas = {\n 'ids': context.get('active_ids', []),\n 'model': 'hr.salary.scale',\n 'form': data\n }\n return {\n 'type': 'ir.actions.report.xml',\n 'report_name': 'salary.scale',\n 'datas': datas,\n }\n \n","sub_path":"v_7/NISS/common_shamil_v3/hr_payroll_custom/wizard/salary_scale.py","file_name":"salary_scale.py","file_ext":"py","file_size_in_byte":1292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"23750953","text":"import os\nimport logging\n\n# Grabs the folder where the script runs.\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# Enable logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\n# Bot configs\ncurrencies_url = 'https://openexchangerates.org/api/currencies.json'\nbase_api_url = 'https://api.exchangeratesapi.io'\nround_index = 2\nDEBUG=True","sub_path":"bots/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"610833767","text":"class DattoAsset():\n '''Class to normalize a Datto Asset \n as an object'''\n def __init__(self, agent):\n self.name = agent['name']\n self.local_ip = agent['localIp']\n self.os = agent['os']\n self.unprotected_volumes = agent['unprotectedVolumeNames']\n self.agent_version = agent['agentVersion']\n self.is_paused = agent['isPaused']\n self.is_archived = agent['isArchived']\n self.latest_offsite = agent['latestOffsite']\n self.last_snapshot = agent['lastSnapshot']\n self.last_screenshot_attempt = agent['lastScreenshotAttempt']\n self.last_screenshot_attempt_status = agent['lastScreenshotAttemptStatus']\n self.last_screenshot_url = agent['lastScreenshotUrl']\n self.fqdn = agent['fqdn']\n self.backups = agent['backups']\n self.type = agent['type']\n","sub_path":"datto/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"586052876","text":"import layouts\nfrom tracer import Tracer\nimport time\nimport numpy as np\n\niteration_count = 500\n\nwidth = 1200\nheight = 900\n\ngood_count = 50\nbad_count = 10\nbird_count = good_count + bad_count\n\nthreshold = 1\n\nw = layouts.HourGlass(width, height, good_count, bad_count)\n\ncharter = Tracer(width, 10, 100, good_count, bad_count)\n\ncharter.threshold_multiplier = threshold\n\ncurrent_t = time.thread_time_ns()\n\nupdate_ts = np.zeros(iteration_count)\nchart_ts = np.zeros(iteration_count)\nts = np.zeros((iteration_count, 6))\n\n# Do a first step without time tracking, to initialize everything\nw.update(10)\ncharter.track(w)\n\n\nfor i in range(0, iteration_count):\n w.update(10)\n update_ts[i] = time.thread_time_ns() - current_t\n ts[i][:] = charter.track(w)\n chart_ts[i] = time.thread_time_ns() - current_t - update_ts[i]\n new_t = time.thread_time_ns()\n total_duration = new_t - current_t\n current_t = new_t\n\n\nupdate_t = sum(update_ts)/len(update_ts)\nchart_t = sum(chart_ts)/len(chart_ts)\ntotal_t = update_t + chart_t\n\nprint('update_ts, chart_ts')\nprint(update_t/total_t, chart_t/total_t)\n\ntimes = np.divide(ts.sum(axis=0), iteration_count)\n\nprint(np.divide(times, chart_t))\n\n# sigma_update_t = sum(np.square(np.subtract(update_ts, update_t)))/2000\n# sigma_chart_t = sum(np.square(np.subtract(chart_ts, chart_t)))/2000\n#\n# print(np.sqrt(sigma_update_t), np.sqrt(sigma_chart_t))\n","sub_path":"performance_testing/chart_tester.py","file_name":"chart_tester.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"74693675","text":"\ndef fat(n):\n if (n == 0):\n return 1\n return (n * fat(n - 1))\n\nprint(fat(4)) # 24 = 4 * 3 * 2 * 1\n\n\nfat_lambda = lambda n: n * fat_lambda(n - 1) if n > 1 else 1\n\nprint(fat_lambda(4)) # 24 = 4 * 3 * 2 * 1\n","sub_path":"classes/fatorial.py","file_name":"fatorial.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"441906524","text":"import os\nimport sys\nimport inspect\nimport argparse\nimport pandas as pd\n\nfrom subprocess import call\n\ncmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0]))\ncmd_folder = os.path.realpath(os.path.join(cmd_folder, \"../..\"))\nif cmd_folder not in sys.path:\n sys.path.insert(0, cmd_folder)\n\nfrom scripts.tools.read_input import configuration_reader\n\n\ndef main():\n # read configuration file\n config = configuration_reader()\n\n # parse arguments\n args = argument_parser()\n\n # get list of instances to be run\n instances = pd.read_csv(config['general']['assigned_instances'], index_col=0)\n instances = instances.loc[instances['pool_id'] == args.pool_id]\n\n # loop through instances\n for instance, row in instances.iterrows():\n # get solver to run\n solver_name = row['solver_name']\n solver_file = os.path.join(config['result_paths']['hydra'], solver_name, 'best_incumbent.csv')\n solver = pd.read_csv(solver_file)\n solver['solver_name'] = solver_name\n\n # setup wrapper command\n command = [args.python_v, config['general']['wrapper'], str(args.pool_id), args.pdir, instance, '0', '0', '0', '0', '--SMACoff']\n\n # add parameters to command\n for parameter in solver:\n command += ['-' + parameter, str(solver.loc[0, parameter])]\n\n # call wrapper with constructed command as subprocess\n call(command)\n\n\ndef argument_parser():\n # construct parser\n parser = argparse.ArgumentParser(description='Running instances from csv')\n\n # SMAC runtime specific parameters\n parser.add_argument('pool_id', type=int, help='pool id')\n parser.add_argument('pdir', type=str, help='pool path')\n parser.add_argument('python_v', type=str, help='python version')\n\n # parse arguments\n args = parser.parse_args()\n\n return args\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"scripts/run_solvers/run_solver_cli.py","file_name":"run_solver_cli.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"63142764","text":"import random\nimport numpy as np \nfrom collections import OrderedDict\nimport math\nimport matplotlib.pyplot as plt \nimport pandas as pd \nimport scipy.io as sio\nimport torch\nfrom torch import nn, optim\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn.utils import clip_grad_norm_\nfrom torchnet.logger import VisdomPlotLogger, VisdomLogger\nfrom dataset import DataSet\n\n'''\n TODO: \n build seq2seq model\n should be normalized?\n'''\n\nclass Encoder(nn.Module):\n def __init__(self, input_size, hidden_size, cnn_k_s, strides,\n n_layers=1, dropout=0.5):\n super(Encoder, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.cnn_kernel_size = cnn_k_s\n self.cnn_strides = strides\n self.dropout = dropout\n self.cnn = nn.Sequential(\n nn.Conv1d(self.input_size, 64, self.cnn_kernel_size, self.cnn_strides),\n # nn.ReLU()\n nn.PReLU()\n )\n self.gru = nn.GRU(64, hidden_size, n_layers,\n dropout=dropout, bidirectional=True)\n # nn.init.constant(self.gru.bias_ih_l0[hidden_size:2*hidden_size], 1)\n # nn.init.constant(self.gru.bias_hh_l0[hidden_size:2*hidden_size], 1)\n # nn.init.constant(self.gru.bias_ih_l0_reverse[hidden_size:2*hidden_size], 1)\n # nn.init.constant(self.gru.bias_hh_l0_reverse[hidden_size:2*hidden_size], 1)\n nn.init.uniform(self.gru.bias_ih_l0[hidden_size:2*hidden_size])\n nn.init.uniform(self.gru.bias_hh_l0[hidden_size:2*hidden_size])\n nn.init.uniform(self.gru.bias_ih_l0_reverse[hidden_size:2*hidden_size])\n nn.init.uniform(self.gru.bias_hh_l0_reverse[hidden_size:2*hidden_size])\n # nn.init.constant(self.gru.bias_ih_l1[hidden_size:2*hidden_size], 1)\n # nn.init.constant(self.gru.bias_hh_l1[hidden_size:2*hidden_size], 1)\n # nn.init.constant(self.gru.bias_ih_l1_reverse[hidden_size:2*hidden_size], 1)\n # nn.init.constant(self.gru.bias_hh_l1_reverse[hidden_size:2*hidden_size], 1)\n\n def forward(self, x, hidden=None):\n x = x.permute(1,2,0) # [B*N*T]\n # padding = self.cnn_kernel_size - x.size(2) % self.cnn_strides\n # x = F.pad(x, (0,padding))\n x = self.cnn(x)\n # x = F.dropout(x,p=self.dropout)\n x = x.permute(2,0,1).contiguous() # [T*B*N]\n outputs, hidden = self.gru(x, hidden)\n outputs = (outputs[:, :, :self.hidden_size] +\n outputs[:, :, self.hidden_size:])\n return outputs, hidden\n\n\nclass Attention(nn.Module):\n def __init__(self, hidden_size):\n super(Attention, self).__init__()\n self.hidden_size = hidden_size\n self.attn = nn.Sequential(\n nn.Linear(self.hidden_size * 2, hidden_size),\n nn.ReLU()\n )\n self.v = nn.Parameter(torch.rand(hidden_size))\n stdv = 1. / math.sqrt(self.v.size(0))\n self.v.data.uniform_(-stdv, stdv)\n\n def forward(self, hidden, encoder_outputs):\n timestep = encoder_outputs.size(0)\n h = hidden.repeat(timestep, 1, 1).transpose(0, 1)\n encoder_outputs = encoder_outputs.transpose(0, 1) # [B*T*H]\n attn_energies = self.score(h, encoder_outputs)\n return F.softmax(attn_energies,dim=1).unsqueeze(1)\n\n def score(self, hidden, encoder_outputs):\n # [B*T*2H]->[B*T*H]\n energy = self.attn(torch.cat([hidden, encoder_outputs], 2))\n energy = energy.transpose(1, 2) # [B*H*T]\n v = self.v.repeat(encoder_outputs.size(0), 1).unsqueeze(1) # [B*1*H]\n energy = torch.bmm(v, energy) # [B*1*T]\n return energy.squeeze(1) # [B*T]\n\n\nclass Decoder(nn.Module):\n def __init__(self, hidden_size, output_size,\n n_layers=1, dropout=0.2):\n super(Decoder, self).__init__()\n self.hidden_size = hidden_size\n self.output_size = output_size\n self.n_layers = n_layers\n\n self.attention = Attention(hidden_size)\n self.gru = nn.GRU(hidden_size + output_size, hidden_size,\n n_layers, dropout=dropout)\n # nn.init.constant(self.gru.bias_ih_l0[1], 1.5)\n # nn.init.constant(self.gru.bias_hh_l0[1], 1.5)\n self.out = nn.Linear(hidden_size * 2, output_size)\n self.dropout = dropout\n\n def forward(self, input, last_hidden, encoder_outputs):\n # Get the embedding of the current input word (last output word)\n # embedded = self.embed(input).unsqueeze(0) # (1,B,N)\n embedded = input.unsqueeze(0)\n # Calculate attention weights and apply to encoder outputs\n attn_weights = self.attention(last_hidden[-1], encoder_outputs)\n context = attn_weights.bmm(encoder_outputs.transpose(0, 1)) # (B,1,N)\n context = context.transpose(0, 1) # (1,B,N)\n # context = F.dropout(context, p=self.dropout)\n # Combine embedded input word and attended context, run through RNN\n rnn_input = torch.cat([embedded, context], 2)\n # rnn_input = F.dropout(rnn_input,p=self.dropout)\n output, hidden = self.gru(rnn_input, last_hidden)\n output = output.squeeze(0) # (1,B,N) -> (B,N)\n context = context.squeeze(0)\n output = self.out(torch.cat([output, context], 1))\n # output = F.log_softmax(output, dim=1)\n return output, hidden, attn_weights\n\n\nclass Seq2Seq(nn.Module):\n def __init__(self, encoder, decoder, teacher_forcing_ratio=0.5):\n super(Seq2Seq, self).__init__()\n self.encoder = encoder\n self.decoder = decoder\n self.teacher_forcing_ratio = teacher_forcing_ratio\n\n def forward(self, src, trg, teacher_forcing_ratio=None, is_analyse=False):\n batch_size = src.size(1)\n max_len = trg.size(0)\n vocab_size = self.decoder.output_size\n outputs = Variable(torch.zeros(max_len, batch_size, vocab_size)).cuda()\n\n encoder_output, hidden = self.encoder(src)\n hidden = hidden[:self.decoder.n_layers]\n if teacher_forcing_ratio == None:\n teacher_forcing_ratio = self.teacher_forcing_ratio\n is_teacher = random.random() < teacher_forcing_ratio\n output = Variable(trg.data[0,] if is_teacher else outputs[0,]).cuda()\n if is_analyse:\n analyse_data = OrderedDict()\n analyse_data['fea_after_encoder'] = encoder_output.data.cpu().numpy()\n analyse_data['atten'] = []\n for t in range(1, max_len):\n output, hidden, attn_weights = self.decoder(\n output, hidden, encoder_output)\n outputs[t] = output\n is_teacher = random.random() < teacher_forcing_ratio\n output = Variable(trg.data[t,] if is_teacher else output).cuda()\n if is_analyse:\n analyse_data['atten'].append(attn_weights.data.cpu().numpy())\n if is_analyse:\n analyse_data['atten'] = np.concatenate(analyse_data['atten'],axis=0)\n return outputs, analyse_data\n else:\n return outputs\n\n\nclass RUL():\n def __init__(self):\n self.hidden_size = 200\n self.epochs = 1000\n self.lr = 4e-3\n self.gama = 0.7\n self.strides = 5\n self.en_cnn_k_s = 8\n self.dataset = DataSet.load_dataset(name='phm_data')\n self.train_bearings = ['Bearing1_1','Bearing1_2','Bearing2_1','Bearing2_2','Bearing3_1','Bearing3_2']\n self.test_bearings = ['Bearing1_3','Bearing1_4','Bearing1_5','Bearing1_6','Bearing1_7',\n 'Bearing2_3','Bearing2_4','Bearing2_5','Bearing2_6','Bearing2_7',\n 'Bearing3_3']\n\n \n def train(self):\n # vis = visdom.Visdom(env='temp_log')\n train_data,train_label = self._preprocess('train')\n train_iter = [[train_data[i],train_label[i]] for i in range(len(train_data))]\n test_data,test_label = self._preprocess('test')\n val_iter = [[test_data[i],test_label[i]] for i in range(len(test_data))]\n self.feature_size = train_data[0].shape[2]\n\n encoder = Encoder(self.feature_size,self.hidden_size,self.en_cnn_k_s,self.strides,n_layers=1,dropout=0.5)\n decoder = Decoder(self.hidden_size,1,n_layers=1,dropout=0.3)\n seq2seq = Seq2Seq(encoder,decoder).cuda()\n # seq2seq = torch.load('./model/newest_seq2seq')\n seq2seq.teacher_forcing_ratio = 0.3\n optimizer = optim.Adam(seq2seq.parameters(), lr=self.lr)\n # optimizer = optim.SparseAdam(seq2seq,lr=self.lr)\n # optimizer = optim.Adamax(seq2seq.parameters(), lr=self.lr)\n # optimizer = optim.SGD(seq2seq.parameters(), lr=self.lr)\n # optimizer = optim.ASGD(seq2seq.parameters(), lr=self.lr)\n # optimizer = optim.RMSprop(seq2seq.parameters(), lr=self.lr)\n\n log = OrderedDict()\n log['train_loss'] = []\n log['val_loss'] = []\n log['test_loss'] = []\n log['teacher_ratio'] = []\n log['mean_er'] = []\n log['mean_abs_er'] = []\n log['score'] = []\n score_logger = VisdomPlotLogger('line',opts={'title':'score logger'})\n loss_logger = VisdomPlotLogger('line',opts={'title':'loss logger'})\n count = 0\n count2 = 0\n count3 = 0\n e0 = 120\n best_loss = 1\n for e in range(1, self.epochs+1):\n train_loss = self._fit(e, seq2seq, optimizer, train_iter, grad_clip=5.0)\n val_loss = self._evaluate(seq2seq, train_iter)\n test_loss,er = self._evaluate(seq2seq, val_iter, cal_er=True)\n score = self._cal_score(er)\n print(\"[Epoch:%d][train_loss:%.4e][val_loss:%.4e][test_loss:%.4e][mean_er:%.4e][mean_abs_er:%.4e][score:%.4f]\"\n % (e, train_loss, val_loss, test_loss, np.mean(er), np.mean(np.abs(er)), np.mean(score)))\n score_logger.log(e,np.mean(score))\n loss_logger.log(e,[train_loss,val_loss,test_loss])\n log['train_loss'].append(float(train_loss))\n log['val_loss'].append(float(val_loss))\n log['test_loss'].append(float(test_loss))\n log['teacher_ratio'].append(seq2seq.teacher_forcing_ratio)\n log['mean_er'].append(float(np.mean(er)))\n log['mean_abs_er'].append(float(np.mean(np.abs(er))))\n log['score'].append(float(np.mean(score)))\n pd.DataFrame(log).to_csv('./model/log.csv',index=False)\n if float(val_loss) == min(log['val_loss']):\n torch.save(seq2seq, './model/seq2seq')\n if (float(test_loss)*11 + float(val_loss)*6)/17 <= best_loss:\n torch.save(seq2seq,'./model/best_seq2seq')\n best_loss = (float(test_loss)*11 + float(val_loss)*6)/17\n # if float(np.mean(np.abs(er))) == min(log['mean_abs_er']):\n # torch.save(seq2seq,'./model/lowest_test_seq2seq')\n if float(np.mean(score)) == max(log['score']):\n torch.save(seq2seq,'./model/best_score_seq2seq')\n torch.save(seq2seq, './model/newest_seq2seq')\n\n count2 += 1\n if float(train_loss) <= float(val_loss)*0.2:\n count += 1\n else:\n count = 0\n if count >= 3 or count2 >= 100:\n seq2seq.teacher_forcing_ratio *= self.gama\n count -= 1\n count2 = 0\n\n # if e % 150 == 0:\n # optimizer.param_groups[0]['lr'] *= 0.9\n\n # if float(val_loss) < min(log['val_loss']):\n # count3 += 1\n # if count3 > 100:\n # optimizer.param_groups[0]['lr'] *= 0.5\n # count3 = 0\n # else:\n # count3 = 0\n \n # optimizer.param_groups[0]['lr'] = (self.lr - (e%e0) * (self.lr-1e-7) / e0)\n\n # if e % 20 == 0:\n # self._plot_result(seq2seq, train_iter, val_iter)\n\n def test(self):\n train_data,train_label = self._preprocess('train')\n train_iter = [[train_data[i],train_label[i]] for i in range(len(train_data))]\n test_data,test_label = self._preprocess('test')\n val_iter = [[test_data[i],test_label[i]] for i in range(len(test_data))]\n\n seq2seq = torch.load('./model/best_seq2seq')\n self._plot_result(seq2seq, train_iter, val_iter)\n\n def analyse(self):\n analyse_data = OrderedDict()\n train_data, train_data_no_norm, train_label = self._preprocess('train',is_analyse=True)\n train_iter = [[train_data[i],train_label[i]] for i in range(len(train_data))]\n test_data, test_data_no_norm, test_label = self._preprocess('test',is_analyse=True)\n val_iter = [[test_data[i],test_label[i]] for i in range(len(test_data))]\n\n analyse_data['train_data'] = train_data\n analyse_data['train_data_no_norm'] = train_data_no_norm\n analyse_data['train_label'] = train_label\n analyse_data['test_data'] = test_data\n analyse_data['test_data_no_norm'] = test_data_no_norm\n analyse_data['test_label'] = test_label\n\n seq2seq = torch.load('./model/best_seq2seq')\n seq2seq.eval()\n\n analyse_data['train_fea_after_encoder'] = []\n analyse_data['train_atten'] = []\n analyse_data['train_result'] = []\n\n with torch.no_grad():\n for [data, label] in train_iter:\n data, label = torch.from_numpy(data.copy()), torch.from_numpy(label.copy())\n data, label = data.type(torch.FloatTensor), label.type(torch.FloatTensor)\n data = Variable(data).cuda()\n label = Variable(label).cuda()\n output, temp_analyse_data = seq2seq(data, label, teacher_forcing_ratio=0.0, is_analyse=True)\n analyse_data['train_result'].append(output.data.cpu().numpy())\n analyse_data['train_fea_after_encoder'].append(temp_analyse_data['fea_after_encoder'])\n analyse_data['train_atten'].append(temp_analyse_data['atten'])\n\n analyse_data['test_fea_after_encoder'] = []\n analyse_data['test_atten'] = []\n analyse_data['test_result'] = []\n\n with torch.no_grad():\n for [data, label] in val_iter:\n data, label = torch.from_numpy(data.copy()), torch.from_numpy(label.copy())\n data, label = data.type(torch.FloatTensor), label.type(torch.FloatTensor)\n data = Variable(data).cuda()\n label = Variable(label).cuda()\n output, temp_analyse_data = seq2seq(data, label, teacher_forcing_ratio=0.0, is_analyse=True)\n analyse_data['test_result'].append(output.data.cpu().numpy())\n analyse_data['test_fea_after_encoder'].append(temp_analyse_data['fea_after_encoder'])\n analyse_data['test_atten'].append(temp_analyse_data['atten'])\n\n sio.savemat('analyse_data.mat',analyse_data)\n \n def _evaluate(self, model, val_iter, cal_er=False):\n model.eval()\n total_loss = 0\n er = []\n for [data, label] in val_iter:\n with torch.no_grad():\n data, label = torch.from_numpy(data.copy()), torch.from_numpy(label.copy())\n data, label = data.type(torch.FloatTensor), label.type(torch.FloatTensor)\n data = Variable(data).cuda()\n label = Variable(label).cuda()\n output = model(data, label, teacher_forcing_ratio=0.0)\n if cal_er:\n label_n = label.data.cpu().numpy().reshape(-1,)\n output_n = output.data.cpu().numpy().reshape(-1,)\n x = np.arange(label_n.shape[0]) * self.strides\n er.append(list(map(lambda x:x[1]/x[0],[np.polyfit(x,label_n,1),np.polyfit(x[5:-5],output_n[5:-5],1)])))\n loss = F.mse_loss(output,label)\n # loss = F.l1_loss(output,label)\n total_loss += loss.data \n if cal_er:\n er = list(map(lambda x:(x[0] - x[1]) / x[0], er))\n return total_loss/len(val_iter), np.array(er)\n else:\n return total_loss / len(val_iter)\n\n \n def _cal_score(self, er):\n '''\n er: a numpy array\n '''\n return np.exp(np.log(.5)*er*(np.sign(er)*12.5-7.5))\n\n\n def _fit(self, e, model, optimizer, train_iter, grad_clip=10.0):\n model.train()\n total_loss = 0\n random.shuffle(train_iter)\n for [data, label] in train_iter:\n random_idx = random.randint(0,round(label.shape[0]*0.3))\n data, label = data[random_idx*self.strides:,], label[random_idx:,]\n data, label = torch.from_numpy(data.copy()), torch.from_numpy(label.copy())\n data, label = data.type(torch.FloatTensor), label.type(torch.FloatTensor)\n data, label = Variable(data).cuda(), Variable(label).cuda()\n optimizer.zero_grad()\n output = model(data, label)\n loss = F.mse_loss(output,label)\n # loss = F.l1_loss(output,label)\n loss.backward()\n clip_grad_norm_(model.parameters(), grad_clip)\n optimizer.step()\n total_loss += loss.data\n torch.cuda.empty_cache() #empty useless variable\n return total_loss / len(train_iter)\n\n\n def _plot_result(self, model, train_iter, val_iter):\n model.eval()\n\n labels = []\n outputs = []\n with torch.no_grad():\n for [data, label] in train_iter:\n data, label = torch.from_numpy(data.copy()), torch.from_numpy(label.copy())\n data, label = data.type(torch.FloatTensor), label.type(torch.FloatTensor)\n data = Variable(data).cuda()\n label = Variable(label).cuda()\n output = model(data, label, teacher_forcing_ratio=0.0)\n labels.append(label.data.cpu().numpy())\n outputs.append(output.data.cpu().numpy())\n labels = np.concatenate(tuple(x for x in labels), axis=0)\n outputs = np.concatenate(tuple(x for x in outputs), axis=0)\n labels, outputs = labels.reshape(-1,), outputs.reshape(-1,)\n plt.subplot(2,1,1)\n plt.plot(labels)\n plt.plot(outputs)\n\n labels = []\n outputs = []\n with torch.no_grad():\n for [data, label] in val_iter:\n data, label = torch.from_numpy(data.copy()), torch.from_numpy(label.copy())\n data, label = data.type(torch.FloatTensor), label.type(torch.FloatTensor)\n data = Variable(data).cuda()\n label = Variable(label).cuda()\n output = model(data, label, teacher_forcing_ratio=0.0)\n labels.append(label.data.cpu().numpy())\n outputs.append(output.data.cpu().numpy())\n labels = np.concatenate(tuple(x for x in labels), axis=0)\n outputs = np.concatenate(tuple(x for x in outputs), axis=0)\n labels, outputs = labels.reshape(-1,), outputs.reshape(-1,)\n plt.subplot(2,1,2)\n plt.plot(labels)\n plt.plot(outputs)\n plt.show()\n\n \n def _preprocess(self, select, is_analyse=False):\n fea_type='fre'\n if select == 'train':\n temp_data = self.dataset.get_value('data',condition={'bearing_name':self.train_bearings})\n temp_label = self.dataset.get_value('RUL',condition={'bearing_name':self.train_bearings})\n elif select == 'test':\n temp_data = self.dataset.get_value('data',condition={'bearing_name':self.test_bearings})\n temp_label = self.dataset.get_value('RUL',condition={'bearing_name':self.test_bearings})\n else:\n raise ValueError('wrong selection!')\n\n for i,x in enumerate(temp_label):\n temp_label[i] = np.arange(temp_data[i].shape[0]) + x\n temp_label[i] = temp_label[i][:,np.newaxis,np.newaxis]\n temp_label[i] = temp_label[i] / np.max(temp_label[i])\n temp_label[i] = temp_label[i][:-self.en_cnn_k_s:self.strides] # when chang 10\n for i,x in enumerate(temp_data):\n temp_data[i] = x[::-1,].transpose(0,2,1)\n \n if fea_type == 'time':\n temp_fun = self._get_time_fea\n elif fea_type == 'fre':\n temp_fun = self._get_fre_fea\n elif fea_type == 'all':\n temp_fun = [self._get_time_fea, self._get_fre_fea]\n else:\n raise ValueError('error selection for features!')\n\n if isinstance(temp_fun,list):\n r_fea = []\n for func in temp_fun:\n r_fea.append([func(x) for x in temp_data])\n r_fea = [np.concatenate((r_fea[j][i] for j in range(len(r_fea))),axis=2) for i in range(len(r_fea[0]))]\n else:\n r_fea = [temp_fun(x) for x in temp_data]\n\n if is_analyse:\n if isinstance(temp_fun,list):\n r_fea_no_norm = []\n for func in temp_fun:\n r_fea_no_norm.append([func(x,is_norm=False) for x in temp_data])\n r_fea_no_norm = [np.concatenate((r_fea[j][i] for j in range(len(r_fea))),axis=2) for i in range(len(r_fea[0]))]\n else:\n r_fea_no_norm = [temp_fun(x,is_norm=False) for x in temp_data]\n return r_fea, r_fea_no_norm, temp_label\n else:\n return r_fea, temp_label\n \n # r_feature = [self._get_time_fea(x) for x in temp_data]\n\n # time_feature = [self._get_time_fea(x) for x in temp_data]\n # fre_feature = [self._get_fre_fea(x) for x in temp_data]\n # r_feature = [np.concatenate((time_feature[i],fre_feature[i]),axis=2) for i in range(len(time_feature))]\n # if is_analyse:\n # time_fea_no_norm = [self._get_time_fea(x,is_norm=False) for x in temp_data]\n # fre_fea_no_norm = [self._get_fre_fea(x,is_norm=False) for x in temp_data]\n # r_fea_no_norm = [np.concatenate((time_fea_no_norm[i],fre_fea_no_norm[i]),axis=2) for i in range(len(time_fea_no_norm))]\n # return r_feature, r_fea_no_norm, temp_label\n # else:\n # return r_feature, temp_label\n\n def _get_time_fea(self, data, is_norm=True):\n fea_dict = OrderedDict()\n fea_dict['mean'] = np.mean(data,axis=2,keepdims=True)\n fea_dict['rms'] = np.sqrt(np.mean(data**2,axis=2,keepdims=True))\n fea_dict['kur'] = np.sum((data-fea_dict['mean'].repeat(data.shape[2],axis=2))**4,axis=2) \\\n / (np.var(data,axis=2)**2*data.shape[2])\n fea_dict['kur'] = fea_dict['kur'][:,:,np.newaxis]\n fea_dict['skew'] = np.sum((data-fea_dict['mean'].repeat(data.shape[2],axis=2))**3,axis=2) \\\n / (np.var(data,axis=2)**(3/2)*data.shape[2])\n fea_dict['skew'] = fea_dict['skew'][:,:,np.newaxis]\n fea_dict['p2p'] = np.max(data,axis=2,keepdims=True) - np.min(data,axis=2,keepdims=True)\n fea_dict['var'] = np.var(data,axis=2,keepdims=True)\n fea_dict['cre'] = np.max(abs(data),axis=2,keepdims=True) / fea_dict['rms']\n fea_dict['imp'] = np.max(abs(data),axis=2,keepdims=True) \\\n / np.mean(abs(data),axis=2,keepdims=True)\n fea_dict['mar'] = np.max(abs(data),axis=2,keepdims=True) \\\n / (np.mean((abs(data))**0.5,axis=2,keepdims=True))**2\n fea_dict['sha'] = fea_dict['rms'] / np.mean(abs(data),axis=2,keepdims=True)\n fea_dict['smr'] = (np.mean((abs(data))**0.5,axis=2,keepdims=True))**2\n fea_dict['cle'] = fea_dict['p2p'] / fea_dict['smr']\n\n fea = np.concatenate(tuple(x for x in fea_dict.values()),axis=2)\n fea = fea.reshape(-1,fea.shape[1]*fea.shape[2])\n # self.feature_size = fea.shape[1]\n if is_norm:\n fea = self._normalize(fea,dim=1)\n fea = fea[:,np.newaxis,:]\n return fea\n \n def _get_fre_fea(self, data, is_norm=True):\n fft_data = np.fft.fft(data,axis=2)/data.shape[2]\n fft_data = (np.abs(fft_data))**2\n fea_list = []\n for i in range(5):\n fea_list.append(np.sum(fft_data[:,:,i*256:(i+1)*256],axis=2,keepdims=True))\n fea = np.concatenate(fea_list,axis=2)\n fea = fea.reshape(-1,fea.shape[1]*fea.shape[2])\n # self.feature_size = fea.shape[1]\n if is_norm:\n fea = self._normalize(fea,dim=1)\n # fea = fea/ (np.max(fea,axis=1,keepdims=True)).repeat(fea.shape[1],axis=1)\n fea = fea[:,np.newaxis,:]\n return fea\n\n\n def _normalize(self, data, dim=None):\n if dim == None:\n mmrange = 10.**np.ceil(np.log10(np.max(data) - np.min(data)))\n r_data = (data - np.min(data)) / mmrange\n else:\n # mmrange = 10.**np.ceil(np.log10(np.max(data,axis=dim,keepdims=True) - np.min(data,axis=dim,keepdims=True)))\n mmrange = np.max(data,axis=dim,keepdims=True) - np.min(data,axis=dim,keepdims=True)\n r_data = (data - np.min(data,axis=dim,keepdims=True).repeat(data.shape[dim],axis=dim)) \\\n / (mmrange).repeat(data.shape[dim],axis=dim)\n return r_data\n\n\nif __name__ == '__main__':\n process = RUL()\n process.train()\n process.analyse()\n process.test()","sub_path":"attention2.py","file_name":"attention2.py","file_ext":"py","file_size_in_byte":25140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"339841083","text":"\"\"\"\nHandlers decorators\n===================\n\"\"\"\nfrom functools import partial, wraps\n\nfrom aiohttp import web\n\nfrom .const import JSONAPI\nfrom .errors import HTTPUnsupportedMediaType, HTTPNotFound\nfrom .log import logger\n\n\ndef jsonapi_handler(handler=None, resource_type=None, content_type=None):\n if handler is None:\n return partial(jsonapi_handler,\n resource_type=resource_type, content_type=content_type)\n\n @wraps(handler)\n async def wrapper(request: web.Request):\n route_name = request.match_info.route.name\n namespace = request.app[JSONAPI]['routes_namespace']\n assert route_name and route_name.startswith('{}.'.format(namespace)), \\\n 'Request route must be named ' \\\n 'and use namespace \"{}.*\"'.format(namespace)\n\n context_class = request.app[JSONAPI]['context_class']\n type_ = resource_type or request.match_info.get('type', None)\n if type_ is None:\n # If type is not found in URI, and type is not passed\n # via decorator to custom handler, then raise HTTP 404\n raise HTTPNotFound()\n\n context = context_class(request, type_)\n if context.schema is None:\n logger.error('No schema for request %s', request.url)\n raise HTTPNotFound()\n\n request[JSONAPI] = context\n\n if content_type is not None and \\\n request.content_type != content_type:\n raise HTTPUnsupportedMediaType(\n detail=\"Only '{}' Content-Type \"\n \"is acceptable for this method.\".format(content_type)\n )\n return await handler(request, context, context.schema)\n return wrapper\n","sub_path":"aiohttp_json_api/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"322701211","text":"#Homework 6\nimport turtle\n\nfile = open('labdata.txt', 'r')\nline = file.readline()\n\nrawList = []\nwhile line:\n rawList.append(line.split())\n line = file.readline()\n\nprint('The raw list:', rawList)\n\n#Create list of just X values\nxList = []\nyList = []\nfor item in rawList:\n xList.append(int(item[0]))\n yList.append(int(item[1]))\n\nprint(xList)\nprint(yList)\n\n\n#Create averages of X and Y lists\navgX = sum(xList) / len(xList)\navgY = sum(yList) / len(yList)\n\nprint('avgX:', avgX, 'avgY:', avgY)\n\n\n#Create combined XY list\ncombinedXY = []\nfor i in range(len(xList)):\n combinedXY.append([xList[i], yList[i]])\nprint(combinedXY)\n\nmaxX = max(xList)\nmaxY = max(yList)\n\ndon = turtle.Turtle()\nwn = turtle.Screen()\nwn.setworldcoordinates(0,0,maxX+10,maxY+10)\n\ndon.penup()\n\nfor point in combinedXY:\n don.goto(point[0], point[1])\n don.dot()\n\nwn.exitonclick()\n","sub_path":"Homework/Homework 6.py","file_name":"Homework 6.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"267850557","text":"import os\nimport numpy as np\nimport subprocess\n\nfrom mcstasscript.data.data import McStasMetaData\nfrom mcstasscript.data.data import McStasData\n\n\nclass ManagedMcrun:\n \"\"\"\n A class for performing a mcstas simulation and organizing the data\n into python objects\n\n ManagedMcrun is usually called by the instrument class of\n McStasScript but can be used independently. It runs the mcrun\n command using the system command, and if this is not in the path,\n the absolute path can be given in a keyword argument executable_path.\n\n Attributes\n ----------\n name_of_instrumentfile : str\n Name of instrument file to be executed\n\n data_folder_name : str\n Name of datafolder mcrun writes to disk\n\n ncount : int\n Number of rays to simulate\n\n mpi : int\n Number of mpi threads to run\n\n parameters : dict\n Dictionary of parameter names and values for this simulation\n\n custom_flags : string\n Custom flags that are passed to the mcrun command\n\n executable_path : string\n Path to the mcrun command (can be empty if already in path)\n\n Methods\n -------\n run_simulation()\n Runs simulation, returns list of McStasData instances\n\n \"\"\"\n\n def __init__(self, instr_name, **kwargs):\n \"\"\"\n Parameters\n ----------\n instr_name : str\n Name of instrument file to be simulated\n\n kwargs : keyword arguments\n foldername : str, required\n Sets data_folder_name\n ncount : int, default 1E6\n Sets ncount\n mpi : int, default None\n Sets thread count, None to disable mpi\n parameters : dict\n Sets parameters\n custom_flags : str, default \"\"\n Sets custom_flags passed to mcrun\n executable_path : str\n Path to mcrun command, \"\" if already in path\n increment_folder_name : bool, default False\n If True, automatically appends foldername to make it unique\n force_compile : bool, default True\n If True, forces compile. If False no new instrument is written\n run_folder : str\n Path to folder in which to run McStas\n\n \"\"\"\n\n self.name_of_instrumentfile = instr_name\n\n self.data_folder_name = \"\"\n self.ncount = int(1E6)\n self.mpi = None\n self.parameters = {}\n self.custom_flags = \"\"\n self.executable_path = \"\"\n self.executable = \"\"\n self.increment_folder_name = False\n self.compile = True\n self.run_path = \".\"\n # executable_path always in kwargs\n if \"executable_path\" in kwargs:\n self.executable_path = kwargs[\"executable_path\"]\n\n if \"executable\" in kwargs:\n self.executable = kwargs[\"executable\"]\n\n if \"foldername\" in kwargs:\n self.data_folder_name = kwargs[\"foldername\"]\n else:\n raise NameError(\n \"ManagedMcrun needs foldername to load data, add \"\n + \"with keyword argument.\")\n\n if \"ncount\" in kwargs:\n self.ncount = int(kwargs[\"ncount\"])\n\n if self.ncount < 1:\n raise ValueError(\"ncount should be a positive integer, was \"\n + str(self.ncount))\n\n if \"mpi\" in kwargs:\n self.mpi = kwargs[\"mpi\"]\n try:\n self.mpi = int(self.mpi)\n except ValueError:\n if self.mpi is not None:\n raise RuntimeError(\"MPI should be an integer, was \"\n + str(self.mpi))\n\n if self.mpi is not None:\n if self.mpi < 1:\n raise ValueError(\"MPI should be an integer larger than\"\n + \" 0, was \" + str(self.mpi))\n\n if \"parameters\" in kwargs:\n self.parameters = kwargs[\"parameters\"]\n\n if not isinstance(self.parameters, dict):\n raise RuntimeError(\"Parameters should be given as dict.\")\n\n if \"custom_flags\" in kwargs:\n self.custom_flags = kwargs[\"custom_flags\"]\n\n if not isinstance(self.custom_flags, str):\n raise RuntimeError(\"ManagedMcrun detected given customf_flags\"\n + \" was not a string.\")\n\n if \"increment_folder_name\" in kwargs:\n self.increment_folder_name = kwargs[\"increment_folder_name\"]\n\n if \"force_compile\" in kwargs:\n self.compile = kwargs[\"force_compile\"]\n\n if \"run_path\" in kwargs:\n self.run_path = kwargs[\"run_path\"]\n\n # get relevant paths and check their validity\n current_directory = os.getcwd()\n\n if not os.path.isabs(self.data_folder_name):\n self.data_folder_name = os.path.join(current_directory,\n self.data_folder_name)\n else:\n split_data_path = os.path.split(self.data_folder_name)\n if not os.path.isdir(split_data_path[0]):\n raise RuntimeError(\"Parent folder for datafolder invalid: \"\n + str(split_data_path[0]))\n\n if not os.path.isabs(self.run_path):\n self.run_path = os.path.join(current_directory, self.run_path)\n else:\n split_run_path = os.path.split(self.run_path)\n if not os.path.isdir(split_run_path[0]):\n raise RuntimeError(\"Parent folder for run_path invalid: \"\n + str(split_run_path[0]))\n\n if not os.path.isdir(self.run_path):\n raise RuntimeError(\"ManagedMcrun found run_path to \"\n + \"be invalid: \" + str(self.run_path))\n\n if not os.path.isdir(self.executable_path):\n raise RuntimeError(\"ManagedMcrun found executable_path to \"\n + \"be invalid: \" + str(self.executable_path))\n\n def run_simulation(self, **kwargs):\n \"\"\"\n Runs McStas simulation described by initializing the object\n \"\"\"\n\n # construct command to run\n option_string = \"\"\n if self.compile:\n option_string = \"-c \"\n\n if self.mpi is not None:\n mpi_string = \" --mpi=\" + str(self.mpi) + \" \" # Set mpi\n else:\n mpi_string = \" \"\n\n option_string = (option_string\n + \"-n \" + str(self.ncount) # Set ncount\n + mpi_string)\n\n if self.increment_folder_name and os.path.isdir(self.data_folder_name):\n counter = 0\n new_name = self.data_folder_name + \"_\" + str(counter)\n while os.path.isdir(new_name):\n counter = counter + 1\n new_name = self.data_folder_name + \"_\" + str(counter)\n\n self.data_folder_name = new_name\n\n if len(self.data_folder_name) > 0:\n option_string = (option_string\n + \"-d \"\n + self.data_folder_name)\n\n # add parameters to command\n parameter_string = \"\"\n for key, val in self.parameters.items():\n parameter_string = (parameter_string + \" \"\n + str(key) # parameter name\n + \"=\"\n + str(val)) # parameter value\n\n mcrun_full_path = os.path.join(self.executable_path, self.executable)\n if len(self.executable_path) > 1:\n if not (self.executable_path[-1] == \"\\\\\"\n or self.executable_path[-1] == \"/\"):\n mcrun_full_path = os.path.join(self.executable_path,\n self.executable)\n\n # Run the mcrun command on the system\n full_command = (mcrun_full_path + \" \"\n + option_string + \" \"\n + self.custom_flags + \" \"\n + self.name_of_instrumentfile\n + parameter_string)\n\n process = subprocess.run(full_command, shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n universal_newlines=True,\n cwd=self.run_path)\n\n if \"suppress_output\" in kwargs:\n if kwargs[\"suppress_output\"] is False:\n print(process.stderr)\n print(process.stdout)\n else:\n print(process.stderr)\n print(process.stdout)\n\n def load_results(self, *args):\n \"\"\"\n Method for loading data from a mcstas simulation\n\n Loads data on all monitors in a McStas data folder, and returns these\n as a list of McStasData objects.\n\n Parameters\n ----------\n\n optional first argument : str\n path to folder from which data should be loaded\n\n \"\"\"\n\n if len(args) == 0:\n data_folder_name = self.data_folder_name\n elif len(args) == 1:\n data_folder_name = args[0]\n else:\n raise RuntimeError(\"load_results can be called \"\n + \"with 0 or 1 arguments\")\n\n return load_results(data_folder_name)\n\n\ndef load_results(data_folder_name):\n \"\"\"\n Function for loading data from a mcstas simulation\n\n Loads data on all monitors in a McStas data folder, and returns these\n as a list of McStasData objects.\n\n Parameters\n ----------\n\n data_folder_name : str\n path to folder from which data should be loaded\n\n \"\"\"\n\n metadata_list = load_metadata(data_folder_name)\n\n results = []\n for metadata in metadata_list:\n results.append(load_monitor(metadata, data_folder_name))\n\n return results\n\n\ndef load_metadata(data_folder_name):\n \"\"\"\n Function that loads metadata from a mcstas simulation\n\n Returns list of metadata objects corresponding to each monitor, all\n information is taken from mccode.sim file.\n\n Parameters\n ----------\n\n first argument : str\n path to folder from which metadata should be loaded\n \"\"\"\n\n if not os.path.isdir(data_folder_name):\n raise NameError(\"Given data directory does not exist.\")\n\n # Find all data files in generated folder\n files_in_folder = os.listdir(data_folder_name)\n\n # Raise an error if mccode.sim is not available\n if \"mccode.sim\" not in files_in_folder:\n raise NameError(\"No mccode.sim in data folder.\")\n\n # Open mccode to read metadata for all datasets written to disk\n with open(os.path.join(data_folder_name, \"mccode.sim\"), \"r\") as f:\n\n # Loop that reads mccode.sim sections\n metadata_list = []\n current_object = None\n in_data = False\n for lines in f:\n # Could read other details about run\n\n if lines == \"end data\\n\":\n # No more data for this metadata object\n # Extract the information\n current_object.extract_info()\n # Add to metadata list\n if current_object.filename != \"\":\n metadata_list.append(current_object)\n # Stop reading data\n in_data = False\n\n if in_data:\n # This line contains info to be added to metadata\n colon_index = lines.index(\":\")\n key = lines[2:colon_index]\n value = lines[colon_index+2:]\n current_object.add_info(key, value)\n\n if lines == \"begin data\\n\":\n # Found data section, create new metadata object\n current_object = McStasMetaData()\n # Start recording data to metadata object\n in_data = True\n\n return metadata_list\n\n\ndef load_monitor(metadata, data_folder_name):\n \"\"\"\n Function that loads data given metadata and name of data folder\n\n Loads data for single monitor and returns a McStasData object\n\n Parameters\n ----------\n\n metadata : McStasMetaData object\n McStasMetaData object corresponding to the monitor to be loaded\n\n data_folder_name : str\n path to folder from which metadata should be loaded\n \"\"\"\n # Load data with numpy\n data = np.loadtxt(os.path.join(data_folder_name,\n metadata.filename.rstrip()))\n\n # Split data into intensity, error and ncount\n if type(metadata.dimension) == int:\n xaxis = data.T[0, :]\n Intensity = data.T[1, :]\n Error = data.T[2, :]\n Ncount = data.T[3, :]\n\n elif len(metadata.dimension) == 2:\n xaxis = [] # Assume evenly binned in 2d\n data_lines = metadata.dimension[1]\n\n Intensity = data[0:data_lines, :]\n Error = data[data_lines:2 * data_lines, :]\n Ncount = data[2 * data_lines:3 * data_lines, :]\n else:\n raise NameError(\n \"Dimension not read correctly in data set \"\n + \"connected to monitor named \"\n + metadata.component_name)\n\n # The data is saved as a McStasData object\n return McStasData(metadata, Intensity, Error, Ncount, xaxis=xaxis)\n","sub_path":"mcstasscript/helper/managed_mcrun.py","file_name":"managed_mcrun.py","file_ext":"py","file_size_in_byte":13217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"520712238","text":"# Print following a pattern without using any loop. (Hint use recursive functions)\r\n\r\n# Examples : \r\n\r\n# Input: n = 16\r\n# Output: 16, 11, 6, 1, -4, 1, 6, 11, 16\r\n\r\n# Input: n = 10\r\n# Output: 10, 5, 0, 5, 10\r\n\r\ndef stack(num):\r\n \r\n if num<=0:\r\n print(num)\r\n \r\n return\r\n\r\n else:\r\n print(num)\r\n stack(num-5)\r\n print(num)\r\n return\r\n\r\nstack(16)\r\nstack(10)\r\n\r\n# _________________________________________\r\n\r\n","sub_path":"day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"262754697","text":"from django.shortcuts import render, redirect\nfrom .models import Todo\n\n# Create your views here.\n\n\ndef new(request):\n return render(request, 'new.html')\n\n\ndef create(request):\n \n title = request.GET.get('title')\n content = request.GET.get('content')\n due_date = request.GET.get('due-date')\n\n todo = Todo(title=title, content=content, due_date=due_date)\n todo.save()\n\n # at first return result with made HTML(return render(request, 'create.html'))\n return redirect('/todos/')\n\n\ndef index(request):\n\n todos = Todo.objects.order_by('due_date').all()\n\n context = {\n 'todos': todos,\n }\n\n return render(request, 'index.html', context)\n\n\ndef detail(request, todo_id):\n\n todo = Todo.objects.get(id=todo_id)\n\n context = {\n 'todo': todo,\n }\n\n return render(request, 'detail.html', context)\n\n\ndef delete(request, todo_id):\n\n todo = Todo.objects.get(id=todo_id)\n todo.delete()\n\n # at first return result with made HTML(return render(request, 'delete.html'))\n return redirect('/todos/')\n\n\ndef edit(request, todo_id):\n\n todo = Todo.objects.get(id=todo_id)\n\n context = {\n 'todo': todo,\n }\n\n return render(request, 'edit.html', context)\n\n\ndef update(request, todo_id):\n\n todo = Todo.objects.get(id=todo_id)\n\n todo.title = request.GET.get('title')\n todo.content = request.GET.get('content')\n todo.due_date = request.GET.get('due-date')\n todo.save()\n \n # at first return result with made HTML(return render(request, 'update.html'))\n return redirect(f'/todos/{todo_id}/detail')\n ","sub_path":"todos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"152352818","text":"from src.common.log import *\n\nif config[\"Battery\"].getboolean(\"simulate_battery\") is False:\n import smbus2 as smbus\nelse:\n import src.dummy.smbus2dummy as smbus\n\nbattery_value = 0\ndef start():\n \"\"\"\n Join the I²C bus as master\n \"\"\"\n global bus\n bus = smbus.SMBus(1)\n\n\ndef get_batteryStatus():\n \"\"\"\n get the battery percentage.\n @return: int 0-100\n \"\"\"\n global bus, battery_value\n try:\n battery_value = bus.read_byte_data(int(config[\"Battery\"][\"I2C_slave_address\"], 16), 0)\n except IOError as err:\n log.error(\"IOError while reading battery status: %s\", str(err))\n return battery_value","sub_path":"src/hardware/battery.py","file_name":"battery.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"494490890","text":"import sys\nn, k, d = map(int, sys.stdin.readline().split())\njacks = []\ndusts = [0] * n\nfor i in range(n):\n dusts[i] = sys.stdin.readline().strip()\njacks = []\ndustness = 1\nfor i in range(n - 1, -1, -1):\n if dustness > d:\n jacks.extend([\"dust\"] * dusts[:i + 1].count(\"T\"))\n break\n elif dusts[i] == \"T\":\n jacks.append(dustness)\n else:\n dustness *= int(dusts[i].split()[1])\nfor j in jacks[::-1]:\n print(j)\n","sub_path":"dmoj/dmopc_and_dmpg/dmopc16c3p2.py","file_name":"dmopc16c3p2.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"331115551","text":"import FWCore.ParameterSet.Config as cms\nfrom Configuration.Generator.Pythia8CommonSettings_cfi import *\nfrom Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *\nfrom Configuration.Generator.Pythia8PowhegEmissionVetoSettings_cfi import *\n\ngenerator = cms.EDFilter(\"Pythia8HadronizerFilter\",\n maxEventsToPrint = cms.untracked.int32(1),\n pythiaPylistVerbosity = cms.untracked.int32(1),\n filterEfficiency = cms.untracked.double(1.0),\n pythiaHepMCVerbosity = cms.untracked.bool(False),\n comEnergy = cms.double(13000.),\n PythiaParameters = cms.PSet(\n pythia8CommonSettingsBlock,\n pythia8CUEP8M1SettingsBlock,\n pythia8PowhegEmissionVetoSettingsBlock,\n processParameters = cms.vstring(\n '25:m0 = 400.0', # Higgs Mass\n '23:mMin = 0.05', # Solve problem with mZ cut\n '25:onMode = off', # turn OFF all H decays\n '25:onIfMatch = 23 23', # turn ON H->ZZ\n '23:onMode = off', # turn OFF all Z decays\n '23:onIfAny = 11 13 15 12 14 16', # turn ON Z->ll\n ),\n parameterSets = cms.vstring('pythia8CommonSettings',\n 'pythia8CUEP8M1Settings',\n 'pythia8PowhegEmissionVetoSettings',\n 'processParameters'\n )\n )\n )\n#Filters to have exactly H To ZZ_2l2nu events\n#Filter to select 2 leptons\nVisLep = cms.EDFilter(\"MCParticlePairFilter\",\n Status = cms.untracked.vint32(0, 0),\n MinDeltaPhi = cms.untracked.double(0.0),\n MaxDeltaPhi = cms.untracked.double(6.29),\n MinPt = cms.untracked.vdouble(5.0, 5.0),\n MinP = cms.untracked.vdouble(0.0, 0.0),\n MaxEta = cms.untracked.vdouble(1000, 1000),\n MinEta = cms.untracked.vdouble(-1000, -1000),\n ParticleCharge = cms.untracked.int32(-1),\n MaxInvMass = cms.untracked.double(1000.0),\n MinInvMass = cms.untracked.double(40.0),\n ParticleID1 = cms.untracked.vint32(11, 13, 15),\n ParticleID2 = cms.untracked.vint32(11, 13, 15)\n)\n\n#Filter to select 2 neutrinos\nInVisLep = cms.EDFilter(\"MCParticlePairFilter\",\n Status = cms.untracked.vint32(1, 1),\n MinDeltaPhi = cms.untracked.double(0.0),\n MaxDeltaPhi = cms.untracked.double(6.29),\n MinPt = cms.untracked.vdouble(5.0, 5.0),\n MinP = cms.untracked.vdouble(0.0, 0.0),\n MaxEta = cms.untracked.vdouble(1000, 1000),\n MinEta = cms.untracked.vdouble(-1000, -1000),\n ParticleCharge = cms.untracked.int32(-1),\n MaxInvMass = cms.untracked.double(1000.0),\n MinInvMass = cms.untracked.double(40.0),\n ParticleID1 = cms.untracked.vint32(12, 14, 16),\n ParticleID2 = cms.untracked.vint32(12, 14, 16)\n)\n\nProductionFilterSequence = cms.Sequence(generator*VisLep*InVisLep)\n","sub_path":"genfragments/ThirteenTeV/Higgs/Hadronizer_TuneCUETP8M1_13TeV_powhegEmissionVeto_H_ZZ_2l2nu_ggH_M400GeV_LepDECAY_LHE_pythia8_cff.py","file_name":"Hadronizer_TuneCUETP8M1_13TeV_powhegEmissionVeto_H_ZZ_2l2nu_ggH_M400GeV_LepDECAY_LHE_pythia8_cff.py","file_ext":"py","file_size_in_byte":2987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"421050705","text":"from django.test import TestCase\nfrom knowledge.models import ToLink, ForthLink\n# Create your tests here.\n\n\nclass ToForthTestCase(TestCase):\n\n def test_forth_delete_to_delete(self):\n \"\"\"If Forth deleted so should To\"\"\"\n a = ToLink.objects.create()\n b = ForthLink.objects.create(to_link_partner=a)\n b.delete()\n self.assertFalse(a in ToLink.objects.all())\n\n def test_to_delete_forth_delete(self):\n \"\"\"If To deleted so should Forth\"\"\"\n c = ToLink.objects.create()\n d = ForthLink.objects.create(to_link_partner=c)\n c.delete()\n self.assertFalse(d in ForthLink.objects.all())\n\n # def test_to_delete_forth_delete(self):\n # \"\"\"If To deleted so should Forth\"\"\"\n # a = ToRelationEntry.objects.create()\n # b = ForthRelationEntry.objects.create(to_relation_partner=a)\n # a.delete()\n # self.assertFalse(b in ForthRelationEntry.objects.all())\n\n\n","sub_path":"knowledge/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"551778698","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n Common all function\n\"\"\"\nfrom config import TEMPLATE_DIR\nfrom manage_sql import ManageSQL\nfrom config import SQLITE_DATABASE_URI\nfrom sql_queries import sql_get_city_id\n\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\n__author = 'Kolesnikov Boris'\n__revision = '$:'\n__date = '25.08.2015'\n\nru_encode = lambda x: x.encode('utf-8')\nru_decode = lambda x: x.decode('utf-8')\n\n\ndef read_file(path_to_file):\n \"\"\"\n Read file as is.\n :param path_to_file: path to file\n :return: type: str\n \"\"\"\n f = open(path_to_file, 'r')\n readed = f.read()\n f.close()\n return readed\n\n\ndef unite_request_data(request):\n \"\"\"\n Unite data from request\n :param request: type: dict, dict data of value input user\n :return: type: dict\n \"\"\"\n user_table_headers = ['firstname', 'lastname', 'patronymic', 'region', 'city', 'phone', 'email', 'comment',\n 'id_city']\n req_dict = {'data': {}}\n for name in user_table_headers:\n data = request.get(name, '')\n if data:\n req_dict['data'][name] = data[0]\n else:\n req_dict['data'][name] = data\n return req_dict\n\n\ndef change_encode(array):\n \"\"\"\n Изменение кодировки в кортеже.\n :param array: type: tuple, кортеж\n :return: type: typle\n \"\"\"\n inner_array = []\n zipped = zip(*array)\n for z_array in zipped:\n changed = map(lambda item: item.decode('utf-8') if isinstance(item, basestring) else item, z_array)\n inner_array.append(tuple(changed))\n return tuple(zip(*inner_array))\n\n\ndef render_from_string(template_string, mapping):\n \"\"\"\n :param template_string: is a template string\n :param mapping: is a dictionary containing values to be substituted into the template. ${xx} in the\n template will be replaced with the value of xx from the mapping dictionary.\n :return: response suitable for the return value of a WSGI procedure\n \"\"\"\n from string import Template\n\n template = Template(template_string)\n result = template.safe_substitute(mapping)\n return [result]\n\n\ndef render(templatename, mapping):\n \"\"\"\n :param templatename: is the name of a template file to be found in the TEMPLATE_DIR directory.\n :param mapping: is a dictionary containing values to be substituted into the template. ${xx} in the\n template will be replaced with the value of xx from the mapping dictionary.\n :return: response suitable for the return value of a WSGI procedure\n \"\"\"\n import os\n\n tpath = os.path.join(TEMPLATE_DIR, templatename)\n if not os.path.exists(tpath):\n print(\"Не могу найти шаблон:\", tpath)\n return [\"Ошибка обработки шаблона\"]\n\n h = open(tpath, 'r')\n template = h.read()\n h.close()\n\n return render_from_string(template, mapping)\n\n\ndef query_to_db(sql, out='one'):\n \"\"\"\n Abs query to database.\n :param out: type: str, set amount of output information\n :param sql: type: str, sql query\n :return: type: tuple, 1-boolean status; 2-output of query\n \"\"\"\n status = True\n result = ''\n try:\n with ManageSQL() as con:\n con.connection(SQLITE_DATABASE_URI)\n con.query(sql)\n con.commit()\n result = con.get_output(out)\n except Exception as ex:\n status = False\n return status, result\n\n\ndef get_id_city(request):\n \"\"\"\n Get id city from city name\n :param request: type: dict, request input from user\n :return: type: str, if city_id 'id city' else ''\n \"\"\"\n city_id = ''\n city_name = request['data'].get('city', '')\n if city_name:\n st, city_id = query_to_db(sql_get_city_id.format(city_name))\n return city_id\n","sub_path":"src/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":3788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"18101556","text":"import requests\nimport os\nfrom datetime import datetime\nfrom hurry.filesize import size, alternative\n\n\nrequests.packages.urllib3.disable_warnings() # Disable warnings\n\n\ndef download_file(dl_url, dl_save_path):\n \"\"\"\n Download URL to given path\n :param dl_url: URL to download\n :param dl_save_path: path to save URL to\n :return: none\n \"\"\"\n start = 0\n dl_size = 0\n get_stat = True\n local_filename = dl_url.split('/')[-1]\n complete_name = os.path.join(dl_save_path, local_filename)\n\n # Get file information\n r = requests.head(dl_url, verify=False)\n file_info = {'size': size(int(r.headers['content-length']), system=alternative), 'status_code': int(r.status_code)}\n # Check status code, should be 200\n if file_info['status_code'] != 200:\n print('something went wrong, error code: %d', file_info['status_code'])\n\n # NOTE the stream=True parameter\n r = requests.get(dl_url, stream=True, verify=False)\n with open(complete_name, 'wb') as f:\n for chunk in r.iter_content(chunk_size=1024):\n if get_stat:\n start = datetime.now()\n dl_size = os.path.getsize(complete_name)\n\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n f.flush()\n\n if (datetime.now() - start).seconds > 1:\n get_stat = True\n print('speed: %s/s' % size((os.path.getsize(complete_name) - dl_size), system=alternative))\n else:\n get_stat = False\n return\n\ndownload_file('https://ubit-artifactory-or.intel.com/artifactory/simple/one-windows-kits-local/Kits/SKL-RVP7-Win10/SKL-RVP7-Win10-2016WW04.5.310/Packages/BT-AHBTW0767/BT-AHBTW0767.zip', r'D:\\\\')\n","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"310017326","text":"#coding: utf-8\nimport speech_recognition as sr\nfrom gtts import gTTS\nfrom sys import stdin\nfrom os import system\n\n\nclass SpeakWithTheRobot:\n \"\"\"\n A class created to enable the user to have a conversation with the \"robot\" utilizing the system proposed.\n ...\n\n Methods\n -------\n listen()\n The software listens to a human and transcribes what he/she said into text.\n speak(utterance)\n The software utters an utterance through the Google Text to Speech package using a sound file.\n speaking_to_the_robot(lsa, naive, file)\n It enables an user to have a conversation with the \"robot\" using the system proposed. It is also permitted to\n check the result of a couple of testing phrases.\n \"\"\"\n\n def __init__(self):\n self.slow = False\n self.device_id = 0\n self.lang = 'pt-pt'\n self.chunk_size = 2048\n self.r = sr.Recognizer()\n self.sample_rate = 48000\n\n def listen(self):\n \"\"\"\n The software listens to a human and transcribes what he/she said into text.\n :return: a text that represents the audio utter by the human.\n :rtype: str\n \"\"\"\n with sr.Microphone(device_index=self.device_id, sample_rate=self.sample_rate, chunk_size=self.chunk_size) as source:\n self.r.adjust_for_ambient_noise(source)\n print(\"Say Something\")\n audio = self.r.listen(source)\n try:\n text = self.r.recognize_google(audio, language=\"pt-PT\")\n print(\"you said: \" + text)\n return text\n except sr.UnknownValueError:\n print(\"Google Speech Recognition could not understand audio\")\n except sr.RequestError as e:\n print(\"Could not request results from Google Speech Recognition service;{0}\".format(e))\n\n def speak(self, utterance):\n \"\"\"\n The software utters an utterance through the Google Text to Speech package using a sound file.\n :param utterance:\n :type utterance: str\n \"\"\"\n tts = gTTS(text=utterance, lang=self.lang, slow=self.slow)\n tts.save(\"soundfile.mp3\")\n system(\"soundfile.mp3\")\n\n def speaking_to_the_robot(self, lsa, naive, db):\n \"\"\"\n It enables an user to have a conversation with the \"robot\" using the system proposed. It is also permitted to\n check the result of a couple of testing phrases.\n :param lsa: a Latent Semantic Analysis object\n :type lsa: LSA\n :param naive: a Naive Bayes classifier\n :type naive: NaiveBayesClassifier\n :param db: an object that represents the database and it is connected to the Database file\n :type db: Database\n \"\"\"\n while True:\n print(\"Press a character\")\n c = stdin.read(2)\n if c[0] == 's':\n self.speak(db.get_robot_utterance(naive.predict_new_robot_id(\n lsa.process_new_human_utterance(self.listen(), db.human_utterances))))\n elif c[0] == 't':\n print(db.get_robot_utterance(naive.predict_new_robot_id(\n lsa.process_new_human_utterance(\"Bom dia\", db.human_utterances))))\n print(db.get_robot_utterance(naive.predict_new_robot_id(\n lsa.process_new_human_utterance(\"Como está tudo a andar?\", db.human_utterances))))\n print(db.get_robot_utterance(naive.predict_new_robot_id(\n lsa.process_new_human_utterance(\"Comigo está tudo fantástico.\", db.human_utterances))))\n print(db.get_robot_utterance(naive.predict_new_robot_id(\n lsa.process_new_human_utterance(\"Gosto muito de vaca\", db.human_utterances))))\n print(db.get_robot_utterance(naive.predict_new_robot_id(\n lsa.process_new_human_utterance(\"Gosto de estar com a minha filha.\", db.human_utterances))))\n print(db.get_robot_utterance(naive.predict_new_robot_id(\n lsa.process_new_human_utterance(\"Uma das minhas coisas preferidas é passear em parques.\",\n db.human_utterances))))\n elif c[0] == 'q':\n break\n","sub_path":"final/SpeakWithTheRobot.py","file_name":"SpeakWithTheRobot.py","file_ext":"py","file_size_in_byte":4240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"613864020","text":"#!/usr/bin/env python2.6\n#\n\n# import des modules\nimport serial\nTRAME_FER = \"\\x0B\\x11\\x00\\x03\\x00\\x3E\\x06\\xFA\\x01\\x00\\x00\\x70\"\n\nportSerie = serial.Serial('/dev/ttyUSB0', 38400, timeout=0.25)\nportSerie.writelines(TRAME_FER)\n\nprint(\"apres fermeture\")\n\n","sub_path":"src/fermeVolets.py","file_name":"fermeVolets.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"53378036","text":"# SI com dinâmica vital\n\nimport numpy as np\nfrom scipy.integrate import odeint\nimport matplotlib.pyplot as plt\n\n# N = população total\nN = 402912\n\n# Número Inicial de Indivíduos Infectados\nI0 = 1\n\n# S0 = Suscetíveis à infecção inicialmente\nS0 = N - I0\n\n# Taxa de contato/infecção (beta)\nbeta = 1.69\n\n# Taxa de mortalidade (mi)\nmi = 0.1\n\n# Taxa de natalidade (ni)\nni = 0.2\n\n# Tempos em dias\ntempo = np.linspace(0, 40, 40)\n\n# Equações diferenciais (ODE) do modelo SI \ndef equacoesSIc(y, tempo, N, beta, mi, ni):\n S, I = y\n dSdt = ni * N - beta * S * I / N - mi * S\n dIdt = beta * S * I / N - mi * I\n return dSdt, dIdt\n\n# Vetor de condições iniciais\ny0 = S0, I0\n\n# Integração das equações SIR no tempo\ni = odeint(equacoesSIc, y0, tempo, args=(N, beta, mi, ni))\nS, I = i.T\n\n# Visualização dos dados em três curvas variavel x tempofig\nfig = plt.figure(facecolor='w')\nax = fig.add_subplot(111, facecolor='#C1FFEC', axisbelow=True) # Tamanho e Cor de fundo\nax.plot(tempo, S/100000, 'b', alpha=0.9, lw=2, label='Suscetíveis')\nax.plot(tempo, I/100000, 'r', alpha=0.9, lw=2, label='Infectados')\nax.set_xlabel('Tempo (dias)')\nax.set_ylabel('Número População (100000)')\nax.set_ylim(0,9.2)\nax.yaxis.set_tick_params(length=0)\nax.xaxis.set_tick_params(length=0)\nax.grid(b=True, which='major', c='w', lw=2, ls='-')\nlegend = ax.legend()\nlegend.get_frame().set_alpha(0.5)\nfor spine in ('top', 'right', 'bottom', 'left'):\n ax.spines[spine].set_visible(False)\nplt.show()\n","sub_path":"SI/SI_comDinamicaVital.py","file_name":"SI_comDinamicaVital.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"434924960","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n# Company: Tecvemar, c.a.\n# Author: Juan V. Márquez L.\n# Creation Date:\n# Version: 0.0.0.0\n#\n# Description: Report parser for: tcv_rse\n#\n#\n##############################################################################\n#~ import time\n#~ import pooler\nfrom report import report_sxw\n#~ from tools.translate import _\n\n\nclass parser_tcv_rse_request(report_sxw.rml_parse):\n\n def __init__(self, cr, uid, name, context=None):\n context = context or {}\n super(parser_tcv_rse_request, self).__init__(cr, uid, name, context=context)\n self.localcontext.update({\n 'get_summary': self._get_summary,\n })\n self.context = context\n\n def _get_summary(self, obj_lines, fields):\n '''\n obj_lines: an obj.line_ids (lines to be totalized)\n fields: tuple with totalized field names\n\n Use in rml:\n [[ repeatIn(get_summary(o.line_ids, ('fld_1', 'fld_2'..)), 't') ]]\n '''\n totals = {}\n for key in fields:\n totals[key] = 0\n for line in obj_lines:\n for key in fields:\n totals[key] += line[key]\n return [totals]\n\nreport_sxw.report_sxw('report.tcv.rse.report',\n 'tcv.rse',\n 'addons/tcv_rse/report/tcv_rse_request.rml',\n parser=parser_tcv_rse_request,\n header=False\n )\n","sub_path":"tcv_rse/report/tcv_rse_request.py","file_name":"tcv_rse_request.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"308371480","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 6 01:40:03 2020\n\n@author: OZGUR\n\"\"\"\n\nfrom numpy import genfromtxt, ones\nimport numpy as np\nfrom matplotlib import pyplot as plt \n\ndef computeCost(X_ii, y, theta):\n m = len(y)\n J = 0\n \n Hx = X_ii.dot(theta)\n J = sum((Hx-y)**2)/(2*m)\n \n return J\n\ndef gradientDescent(X_ii, y, theta, alpha, num_iters):\n\n m = len(y)\n J_history = np.zeros(num_iters)\n \n for iter in range(0, len(J_history)):\n \n theta = theta - (alpha * (X_ii.transpose() * ((X_ii.dot(theta)-y)/m))).sum(axis = 1)\n \n J_history[iter] = computeCost(X_ii, y, theta) \n \n return [theta, J_history]\n\n# +\ndata = genfromtxt('ex1data1.txt', delimiter=',')\nX=data[:,0]\ny=data[:,1]\ntheta = [0, 0]\nnum_iters = 1500\nalpha = 0.01\nm = len(y)\nX_ii = np.column_stack((np.ones(m), X))\nJ_historyX = list(range(0, 1500))\n \nplt.figure()\nplt.plot(X,y,'x',linewidth=0)\nplt.title('Profit vs. Population')\nplt.ylabel('Profit in $10,000s')\nplt.xlabel('Population of City in 10,000s')\n \ntheta, J_history = gradientDescent(X_ii, y, theta, alpha, num_iters)\n \nx = np.linspace(5.0,22.5, 50)\ny = x*theta[1]+theta[0]\nplt.plot(x, y, '-r', label='y=2x+1')\nplt.show()\nprint(\"theta = \", theta)\n \nplt.figure()\nplt.plot(J_historyX, J_history,'r-')\nplt.title('Cost Function History')\nplt.xlabel('Iteration Number')\nplt.ylabel('Cost')\nplt.show()\nprint(\"J_history = \" , J_history)\n# -\n\n# Visualizing J(theta_0, theta_1):\n# Grid over which we will calculate J\ntheta0_vals = np.linspace(-10, 10, 100);\ntheta1_vals = np.linspace(-1, 4, 100);\n# initialize J_vals to a matrix of 0's\nJ_vals = np.zeros((len(theta0_vals),len(theta1_vals)), dtype=float)\nJ_vals\n\n\n\n# +\ndata = genfromtxt('ex1data1.txt', delimiter=',')\nX=data[:,0]\ny=data[:,1]\nX_ii = np.column_stack((np.ones(m), X))\n\n#print(theta0_vals)\n#print(theta1_vals)\nX_ii = np.column_stack((np.ones(m), X))\n\n# Fill out J_vals\nfor i in range(0,len(theta0_vals)):\n for j in range(0,len(theta1_vals)):\n t = [theta0_vals[i], theta1_vals[j]]\n J_vals[i,j] = computeCost(X_ii, y, t)\n\nJ_vals\n\n# +\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = theta0_vals\ny = theta1_vals\nz = J_vals\n\n#fig = plt.figure(figsize=(10,10))\nfig, ax = plt.subplots(figsize=(10,10))\nax = plt.axes(projection='3d')\nax.view_init(elev=20., azim=150.0)\nax.plot_surface(x, y, z, cmap='viridis', edgecolor='none')\nax.set_title('Surface plot')\nax.set_xlabel('theta0_vals')\nax.set_ylabel('theta1_vals')\nax.set_zlabel('Cost')\n\n# +\nfig, ax = plt.subplots(figsize=(5,5))\n\nx = theta0_vals\ny = theta1_vals\nz = J_vals\nCS = ax.contour(x, y, z)\nax.clabel(CS, inline=10, fontsize=10)\nax.margins(10, 10) \nax.set_title('Contour plot')\nplt.plot(theta[0], theta[1], marker='x', markersize=10, color=\"red\")\n# -\n\n\n","sub_path":"Project1/PYTHON/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"387223122","text":"from purviewcli.common import http_get\n\ndef getLineage(config, args):\n endpoint = '/api/atlas/v2/lineage/%s' % args['--guid'][0]\n params = {\n 'depth': args['--depth'],\n 'width': args['--width'],\n 'direction': args['--direction'],\n 'forceNewApi': args['--forceNewApi'],\n 'includeParent': args['--includeParent'],\n 'getDerivedLineage': args['--getDerivedLineage']\n }\n data = http_get('catalog', 'GET', endpoint, params, None, config)\n return data\n\n# Request URI not found\ndef getLineageUniqueAttributeType(config, args):\n endpoint = '/api/atlas/v2/lineage/uniqueAttribute/type/%s' % args['--typeName']\n params = {'depth': args['--depth'], 'direction': args['--direction']} \n data = http_get('catalog', 'GET', endpoint, params, None, config)\n return data\n","sub_path":"purviewcli/lineage.py","file_name":"lineage.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"296398842","text":"# Name: Ofir Cohen\n# ID: 312255847\n# Date: 15/5/2020\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math, os\nfrom load_cifar10 import load_cifar_10_data, load_cifar_10_data_tf\n\nclass VGG(nn.Module):\n\n def __init__(self, features):\n super(VGG, self).__init__()\n self.features = features\n self.classifier = nn.Sequential(\n nn.Linear(512, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 4096),\n nn.ReLU(True),\n nn.Dropout(),\n nn.Linear(4096, 10)\n )\n\n def forward(self, x):\n x = self.features(x)\n x = x.reshape(x.shape[0], -1)\n x = self.classifier(x)\n return x\n''' End class '''\n\n\ndef vgg16_bn():\n config = [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M']\n return VGG(make_layers(config, True))\n''' End function '''\n\n\ndef make_layers(config, batch_norm=False):\n layers = []\n in_channels = 3\n for v in config:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=(2,2), stride=(2,2))]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=(3,3), stride=(1,1), padding=(1,1))\n if batch_norm:\n layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]\n else:\n layers += [conv2d, nn.ReLU(inplace=True)]\n in_channels = v\n\n return nn.Sequential(*layers)\n''' End function '''","sub_path":"ex3/ex3a/vgg_16.py","file_name":"vgg_16.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"218211826","text":"# encoding = utf-8\r\nimport os,sys\r\nsys.path.insert(1, os.path.join(sys.path[0], '..'))\r\nimport numpy as np\r\nimport colorsys\r\nimport os\r\nimport torch\r\nimport torch.nn as nn\r\nfrom PIL import Image,ImageFont, ImageDraw\r\nfrom torch.autograd import Variable\r\nfrom utils.utils import non_max_suppression, DecodeBox, yolo_correct_boxes\r\nfrom utils.dataloader import GenerateInput\r\n\r\nclass Predictor(object):\r\n @classmethod\r\n def get_defaults(cls, n):\r\n if n in cls._defaults:\r\n return cls._defaults[n]\r\n else:\r\n return \"Unrecognized attribute name '\" + n + \"'\"\r\n\r\n #---------------------------------------------------#\r\n # 初始化分类器\r\n #---------------------------------------------------#\r\n def __init__(self, _defaults, **kwargs):\r\n self.__dict__.update(_defaults)\r\n self.class_names = self._get_class()\r\n self.anchors = self._get_anchors()\r\n self.generate()\r\n self.dict = {'0':'T-shirt', '1':'Trouser', '2':'Pullover', '3':'Dress', '4':'Coat',\r\n '5':'Sandal', '6':'Shirt', '7':'Sneaker', '8':'Bag', '9':'Ankle boot'}\r\n #---------------------------------------------------#\r\n # 获得所有的分类\r\n #---------------------------------------------------#\r\n def _get_class(self):\r\n classes_path = os.path.expanduser(self.classes_path)\r\n with open(classes_path) as f:\r\n class_names = f.readlines()\r\n class_names = [c.strip() for c in class_names]\r\n return class_names\r\n \r\n #---------------------------------------------------#\r\n # 获得所有的先验框\r\n #---------------------------------------------------#\r\n def _get_anchors(self):\r\n anchors_path = os.path.expanduser(self.anchors_path)\r\n with open(anchors_path) as f:\r\n anchors = f.readline()\r\n anchors = [float(x) for x in anchors.split(',')]\r\n return np.array(anchors).reshape([-1, 3, 2])\r\n\r\n #---------------------------------------------------#\r\n # 获得所有的分类\r\n #---------------------------------------------------#\r\n def generate(self):\r\n device = torch.device('cpu')\r\n #device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\r\n self.net = self.MyNetBody(len(self.anchors[0]),len(self.class_names),self.series_length).eval()\r\n \r\n\r\n print('Loading weights into state dict...')\r\n if self.FineTune != None:\r\n self.ft = self.FineTune(self.series_length).eval()\r\n ft_dict = torch.load(self.FT_log, map_location=device)\r\n self.ft.load_state_dict(ft_dict)\r\n state_dict = torch.load(self.model_path, map_location=device)\r\n self.net.load_state_dict(state_dict)\r\n \r\n if self.cuda:\r\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\r\n self.net = nn.DataParallel(self.net)\r\n self.net = self.net.cuda()\r\n if self.FineTune != None:\r\n self.ft = nn.DataParallel(self.ft)\r\n self.ft = self.ft.cuda()\r\n \r\n print('Finished!')\r\n\r\n self.yolo_decodes = []\r\n self.anchors_mask = [[3,4,5],[1,2,3]]\r\n for i in range(2):\r\n #self.yolo_decodes.append(DecodeBox(np.reshape(self.anchors,[-1,2])[self.anchors_mask[i]], len(self.class_names), (self.model_image_size[1], self.model_image_size[0])))\r\n self.yolo_decodes.append(DecodeBox(np.reshape(self.anchors,[-1,2])[self.anchors_mask[i]], len(self.class_names), self.input_to_net_size))\r\n\r\n\r\n print('{} model, anchors, and classes loaded.'.format(self.model_path))\r\n # 画框设置不同的颜色\r\n hsv_tuples = [(x / len(self.class_names), 1., 1.)\r\n for x in range(len(self.class_names))]\r\n self.colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))\r\n self.colors = list(\r\n map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),\r\n self.colors))\r\n\r\n #---------------------------------------------------#\r\n # 检测测试结果\r\n #---------------------------------------------------#\r\n def get_detect_results(self, pathlist, Origin_Time, ifimg=True):\r\n S_gen = GenerateInput(1, pathlist, 0, self.series_length, self.model_image_size, train=False, finetune=False, ifstop=True,dataset=self.dataset).generate()\r\n error_list = []\r\n for n,testdata in enumerate(S_gen):\r\n s_series, names = testdata[0], testdata[2][0]\r\n with torch.no_grad():\r\n if self.cuda:\r\n s_series = Variable(s_series.type(torch.FloatTensor)).cuda()\r\n else:\r\n s_series = Variable(s_series.type(torch.FloatTensor))\r\n if self.FineTune != None:\r\n s_series = self.ft(s_series) + s_series\r\n outputs = self.net(s_series)\r\n\r\n graph = np.array(outputs[2].cpu().detach())\r\n graph[graph<0] = 0\r\n graph = np.reshape(graph, graph.shape[1:]) * 255.0 / graph.max()\r\n graph = Image.fromarray(graph).convert('L')\r\n\r\n graph.save('test_results/%s_predict/%s.png'%(Origin_Time, names))\r\n\r\n graph = graph.convert('RGB')\r\n output_list = []\r\n for i in range(2):\r\n output_list.append(self.yolo_decodes[i](outputs[i]))\r\n output = torch.cat(output_list, 1)\r\n batch_detections = non_max_suppression(output, len(self.class_names),\r\n conf_thres=self.confidence,\r\n nms_thres=self.iou)\r\n try:\r\n batch_detections = batch_detections[0].cpu().numpy()\r\n except:\r\n batch_detections = np.empty(shape=(0,6))\r\n print('Empty prediction for input %s.'%(names))\r\n error_list.append(names)\r\n \r\n \r\n top_index = batch_detections[:,4]*batch_detections[:,5] > self.confidence\r\n top_conf = batch_detections[top_index,4]*batch_detections[top_index,5]\r\n top_label = np.array(batch_detections[top_index,-1],np.int32)\r\n top_bboxes = np.array(batch_detections[top_index,:4])\r\n top_xmin, top_ymin, top_xmax, top_ymax = np.expand_dims(top_bboxes[:,0],-1),np.expand_dims(top_bboxes[:,1],-1),np.expand_dims(top_bboxes[:,2],-1),np.expand_dims(top_bboxes[:,3],-1)\r\n np.savetxt('test_results/%s_bbox/%s_conf.txt'%(Origin_Time, names), top_conf)\r\n np.savetxt('test_results/%s_bbox/%s.txt'%(Origin_Time, names), np.hstack((top_bboxes,(np.atleast_2d(top_label)).T)), fmt=\"%i\")\r\n\r\n if ifimg:\r\n image = np.array(graph.resize((512,512),Image.NEAREST))\r\n # 去掉灰条\r\n boxes = yolo_correct_boxes(top_ymin,top_xmin,top_ymax,top_xmax,np.array([self.model_image_size[0],self.model_image_size[1]]),np.array(self.model_image_size))\r\n\r\n font = ImageFont.truetype(font='model_data/simhei.ttf',size=np.floor(6e-2 * np.shape(image)[1] + 0.5).astype('int32'))\r\n\r\n thickness = 3 #(np.shape(image)[0] + np.shape(image)[1]) // self.model_image_size[0]\r\n\r\n img = Image.fromarray(image)\r\n for i, c in enumerate(top_label):\r\n predicted_class = self.class_names[c]\r\n score = top_conf[i]\r\n\r\n top, left, bottom, right = boxes[i] + [-5,-5,5,5]\r\n\r\n top = max(0, np.floor(top + 0.5).astype('int32'))\r\n left = max(0, np.floor(left + 0.5).astype('int32'))\r\n bottom = int(min(np.shape(image)[0], np.floor(bottom + 0.5).astype('int32')))\r\n right = int(min(np.shape(image)[1], np.floor(right + 0.5).astype('int32')))\r\n\r\n # 画框框\r\n label = '{} {:.2f}'.format(self.dict[predicted_class], score)\r\n\r\n draw = ImageDraw.Draw(img)\r\n label_size = draw.textsize(label, font)\r\n label = label.encode('utf-8')\r\n #print(label)\r\n \r\n if top - label_size[1] >= 0:\r\n text_origin = np.array([left, top - label_size[1]])\r\n else:\r\n text_origin = np.array([left, top + 1])\r\n\r\n for i in range(thickness):\r\n draw.rectangle(\r\n [left + i, top + i, right - i, bottom - i],\r\n outline=self.colors[self.class_names.index(predicted_class)])\r\n draw.rectangle(\r\n [tuple(text_origin), tuple(text_origin + label_size)],\r\n fill=self.colors[self.class_names.index(predicted_class)])\r\n draw.text(text_origin, str(label,'UTF-8'), fill=(0, 0, 0), font=font)\r\n del draw\r\n img.save('test_results/%s/rec_%s.png'%(Origin_Time, names))\r\n #graph.save('test_results/%s/rec_%s'%(Origin_Time, name.split('/')[-1]))\r\n \r\n else:\r\n with open('test_results/%s/out%s.txt'%(Origin_Time, n+1)) as f:\r\n f.write(top_conf)\r\n f.write(top_label)\r\n f.write(top_bboxes)\r\n #print('Predict input %s successfully.'%(n+1))\r\n\r\n\r\n","sub_path":"Fashion_MNIST_train/fashpredictor.py","file_name":"fashpredictor.py","file_ext":"py","file_size_in_byte":9427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"154686571","text":"from bf import BF\nfrom dk import DK\n\nprint(\"BELLMAN FORD\\n----\")\nn = BF(5)\nn.addEdge(0, 1, 6)\nn.addEdge(0, 1, 7)\nn.addEdge(1, 2, 5)\nn.addEdge(2, 1, 2)\nn.addEdge(1, 3, 8)\nn.addEdge(1, 4, 4)\nn.addEdge(3, 4, 9)\nn.addEdge(4, 2, 7)\nn.addEdge(4, 0, 2)\n\npv = 0\nprint(\"Caminhos do vertex {}\".format(pv))\nn.BellmanFord(pv)\n\nprint(\"\\nDIJKSTRA\\n----\")\nG = DK()\nG.add_vertex('a')\nG.add_vertex('b')\nG.add_vertex('c')\nG.add_vertex('d')\nG.add_vertex('e')\n\nG.add_edge('a', 'b', 2)\nG.add_edge('a', 'c', 8)\nG.add_edge('a', 'd', 5)\nG.add_edge('b', 'c', 1)\nG.add_edge('c', 'e', 3)\nG.add_edge('d', 'e', 4)\n\nprint(G) \n\nprint(G.dijkstra('a'))\nprint(\"Caminho mais curto entre 'a' e 'e'::\")\nprint(G.shortest_path('a', 'e'))\n\n","sub_path":"guides to algorithms/Guia11/Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"144371026","text":"import itchat\nimport time\nimport names\nimport requests\nimport json\nimport threading\nfrom apscheduler.schedulers.background import BackgroundScheduler\nfrom MyQueue import MyQueue\n\nglobal wx_config\nwords=('你个傻吊','不要回复')\n\nclass wx_config(object):\n registerType = ['Picture', 'Recording', 'Attachment', 'Video', 'Text', 'Map', 'Card', 'Note', 'Sharing']\n downType = ['Picture', 'Recording', 'Attachment', 'Video']\n def __init__(self):\n self.myName = ''\n self.filePath = ''\n self.reqbody = {'reqType': 0, 'perception': {}, 'userInfo': {}}\n self.mps = []\n self.queue = MyQueue()\n def initConfig(self):\n self.myName = itchat.get_friends(update=True)[0]['UserName']\n self.filePath = 'E:/wechatFile/'\n self.mps = itchat.search_mps(name='小冰')\n\n # s1 = str(10006)\n # s2 = str(40006)\n # print(s1.startswith(\"100\"))\n # print(s2.startswith(\"100\"))\n # invokeApi('天气如何')\n\n\n# @itchat.msg_register(registerType, isGroupChat=True)\n# def group_reply(msg):\n# print(msg)\n# print(\"=====\")\n\n# 调用图灵api\n# def invokeApi(input):\n# reqbody['reqType'] = 0\n# reqbody['perception'] = {\n# 'inputText': {\n# 'text': input\n# },\n# 'selfInfo': {\n# 'location': {\n# 'city': '北京',\n# 'province': '北京',\n# 'street': '信息路'\n# }\n# }\n# }\n# reqbody['userInfo'] = {\n# 'apiKey': '4453d0f556764fac9fdd501c6f0c26bb',\n# 'userId': 'tomcatx001'\n# }\n# req = json.dumps(reqbody, ensure_ascii=False)\n# url = 'http://openapi.tuling123.com/openapi/api/v2'\n# response = requests.post(url, req.encode('utf-8'))\n# conetent = response.content.decode('utf-8')\n# conetent = json.loads(conetent)\n# print(conetent)\n# return conetent\n# itchat 封装好下载方法 并指定下载路径\n\ndef downFile(wx_config, msg):\n if not msg['User']['UserName'] == 'filehelper':\n print('download to path : %s...'%(wx_config.filePath))\n msg.download(wx_config.filePath + msg['FileName'])\n\n# 注册监听消息事件\n@itchat.msg_register(wx_config.registerType, isFriendChat=True)\ndef text_ly(msg):\n print(\"收到消息,Type : %s\" % (msg['Type']))\n #只接收好友的消息,过滤掉自己的消息\n if not msg['FromUserName'] == wx_config.myName:\n wx_config.queue.enqueue(msg['FromUserName'])\n print(\"enqueue user %s\" % (msg['FromUserName']))\n # 如果收到的是图片视频等下载资源,保存到本机\n if msg['Type'] in wx_config.downType:\n downFile(wx_config, msg)\n else:\n # 收到的文字信息,自动回复\n if not msg['FromUserName'] == wx_config.myName:\n # 发送一条提示给文件助手\n itchat.send_msg(u\"[%s]收到好友@%s 的信息:%s\\n\" %\n (time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(msg['CreateTime'])),\n msg['User']['NickName'],\n msg['Text']), 'filehelper')\n\n # response = invokeApi(msg['Text'])\n # intent = response['intent']\n # resluts = response['results']\n #\n # code = intent['code']\n # if str(code).startswith(\"1\"):\n # out = resluts[0]['values']['text']\n # return out\n send_toXiaoBing(wx_config, msg)\n # return \"正在忙,已收到你消息,稍后回复\"\n\n\n# 发送消息给小冰\ndef send_toXiaoBing(wx_config, msg):\n if msg['Type'] == 'Text':\n itchat.send_msg(msg['Text'], wx_config.mps[0]['UserName'])\n return\n if msg['Type'] == 'Picture':\n itchat.send_image(wx_config.filePath + msg['FileName'], wx_config.mps[0]['UserName'])\n return\n if msg['Type'] == 'Recording':\n itchat.send_file(wx_config.filePath + msg['FileName'], wx_config.mps[0]['UserName'])\n return\n\n@itchat.msg_register(wx_config.registerType, isMpChat=True)\ndef mp_reply(msg):\n if msg['User']['NickName'] == '小冰':\n recall(wx_config,msg)\n\n\ndef recall(wx_config, msg):\n if wx_config.queue.isEmpty():\n return\n print('recall')\n touser = wx_config.queue.dequeue()\n if touser:\n if msg['Type'] == 'Text':\n itchat.send_msg(msg['Text'], touser)\n elif msg['Type'] == 'Picture':\n downFile(wx_config,msg)\n itchat.send_image(wx_config.filePath + msg['FileName'], touser)\n else:\n downFile(wx_config,msg)\n itchat.send_file(wx_config.filePath + msg['FileName'], touser)\n else:\n return\n\ndef send_msg_to_someone(userName):\n itchat.send_msg('你个傻吊,不要回答', toUserName=userName)\n print('发送成功')\n\ndef scheduleTask():\n print('线程开启,任务开始')\n userInfo = itchat.search_friends(nickName='黄耀辉')\n print(userInfo[0])\n if len(userInfo) > 0:\n scheduler = BackgroundScheduler()\n scheduler.add_job(send_msg_to_someone, 'interval', seconds=1, args=[userInfo[0]['UserName']])\n scheduler.start()\n\nif __name__ == '__main__':\n wx_config = wx_config()\n itchat.auto_login(hotReload=True);\n wx_config.initConfig()\n #threading.Thread(target=scheduleTask(),args=[]).start()\n print(\"主线程执行中\")\n itchat.run()\n itchat.dump_login_status","sub_path":"helloworld/src/auto_wechat.py","file_name":"auto_wechat.py","file_ext":"py","file_size_in_byte":5483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"334855692","text":"# -*- coding: utf-8 -*-\n#\n# [迷路の最短路]\n# 大きさがN×Mの迷路が与えられます。迷路は通路と壁からできており、1ター\n# ンに隣接する上下左右4マスの通路へ移動することができます。スタートから\n# ゴールまで移動するのに必要な最小ターン数を求めなさい。ただし、スタート\n# からゴールまで移動できると仮定します。\n#\n# 制約\n# N, M <= 100\n\n\ndef __get_pos_of(ch, field):\n for i, line in enumerate(field):\n if ch not in line:\n continue\n return (i, line.index(ch))\n return (-1, -1)\n\n\ndef __get_next_pos(N, M, maze, x, y):\n for i, j in [(-1, 0), (1, 0), (0, -1), (0, 1)]:\n i += x\n j += y\n if i < 0 or i >= N or j < 0 or j >= M:\n continue\n if maze[i][j] not in ('.', 'G'):\n continue\n yield (i, j)\n\n\ndef get_shortest_path(N, M, maze):\n start = __get_pos_of('S', maze)\n turn = 0\n points = {0: [start]}\n while turn in points.keys():\n for x, y in points[turn]:\n if maze[x][y] == 'G':\n return turn\n maze[x][y] = '*'\n nexts = list(__get_next_pos(N, M, maze, x, y))\n if len(nexts) == 0:\n continue\n if turn + 1 in points.keys():\n points[turn + 1].extend(nexts)\n else:\n points[turn + 1] = nexts\n turn += 1\n return -1\n\n\nif __name__ == \"__main__\":\n N = 10\n M = 10\n maze_t = \"\"\"#S######.#\n ......#..#\n .#.##.##.#\n .#........\n ##.##.####\n ....#....#\n .#######.#\n ....#.....\n .####.###.\n ....#...G#\"\"\"\n maze = [list(line) for line in maze_t.split()]\n assert get_shortest_path(N, M, maze) == 22, \"example\"\n","sub_path":"2-1-shortest-path/src/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"519655970","text":"from django import forms\nfrom application.models import ContractType, Duty, \\\n IntellectualPropertyType, IntellectualProperty, Payment, \\\n IntangibleAssets, IPCommercialization, Message, User\nfrom django.db.models import Q\nfrom django.contrib.auth import get_user\n\n# MaintenanceOfPatents - поле сортировки документа\nSORTING_MOP_CHOICES = (\n ('request_number', \"номер патента\"),\n ('priority_date', \"дата приоритета\")\n)\n\n\nclass RequestIntellectualPropertyForm(forms.ModelForm):\n class Meta:\n model = IntellectualProperty\n fields = '__all__'\n exclude = ('duty_payments', 'is_supported', 'is_request')\n widgets = {\n 'priority_date': forms.DateInput(attrs={'type': 'date'}),\n 'send_date': forms.DateInput(attrs={'type': 'date'}),\n 'receipt_date': forms.DateInput(attrs={'type': 'date'}),\n 'grant_date': forms.DateInput(attrs={'type': 'date'}),\n 'contract_date': forms.DateInput(attrs={'type': 'date'}),\n 'bulletin_date': forms.DateInput(attrs={'type': 'date'}),\n 'text': forms.Textarea(attrs={'rows': '4'}),\n 'abridgement': forms.Textarea(attrs={'rows': '4'}),\n 'note': forms.Textarea(attrs={'rows': '3'}),\n }\n\n\nclass IntellectualPropertyForm(forms.ModelForm):\n class Meta:\n model = IntellectualProperty\n fields = '__all__'\n exclude = ('duty_payments', 'is_request', 'send_date')\n widgets = {\n 'priority_date': forms.DateInput(attrs={'type': 'date'}),\n 'receipt_date': forms.DateInput(attrs={'type': 'date'}),\n 'grant_date': forms.DateInput(attrs={'type': 'date'}),\n 'contract_date': forms.DateInput(attrs={'type': 'date'}),\n 'bulletin_date': forms.DateInput(attrs={'type': 'date'}),\n 'text': forms.Textarea(attrs={'rows': '4'}),\n 'abridgement': forms.Textarea(attrs={'rows': '4'}),\n 'note': forms.Textarea(attrs={'rows': '3'}),\n }\n\n\nclass ContractIntellectualPropertyForm(forms.ModelForm):\n class Meta:\n model = IntellectualProperty\n fields = '__all__'\n exclude = ('duty_payments', 'is_supported', 'is_request', 'send_date', 'is_contracted')\n widgets = {\n 'priority_date': forms.DateInput(attrs={'type': 'date'}),\n 'receipt_date': forms.DateInput(attrs={'type': 'date'}),\n 'grant_date': forms.DateInput(attrs={'type': 'date'}),\n 'contract_date': forms.DateInput(attrs={'type': 'date'}),\n 'bulletin_date': forms.DateInput(attrs={'type': 'date'}),\n 'text': forms.Textarea(attrs={'rows': '4'}),\n 'abridgement': forms.Textarea(attrs={'rows': '4'}),\n 'note': forms.Textarea(attrs={'rows': '3'}),\n }\n\n\nclass PaymentForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(PaymentForm, self).__init__(*args, **kwargs)\n\n self.fields['intellectual_property'].queryset = IntellectualProperty.objects.filter(is_request=False)\n\n class Meta:\n model = Payment\n fields = '__all__'\n widgets = {\n 'payment_date': forms.DateInput(attrs={'type': 'date'}),\n 'posted_date': forms.DateInput(attrs={'type': 'date'}),\n 'note': forms.Textarea(attrs={'rows': '4'}),\n }\n\n\nclass IntangibleAssetForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(IntangibleAssetForm, self).__init__(*args, **kwargs)\n\n self.fields['intellectual_property'].queryset = IntellectualProperty.objects.filter(is_request=False)\n\n class Meta:\n model = IntangibleAssets\n fields = '__all__'\n widgets = {\n 'date': forms.DateInput(attrs={'type': 'date'}),\n 'retirement_date': forms.DateInput(attrs={'type': 'date'}),\n }\n\n\nclass IPCommercializationForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(IPCommercializationForm, self).__init__(*args, **kwargs)\n\n self.fields['intellectual_property'].queryset = IntellectualProperty.objects.filter(is_request=False)\n\n class Meta:\n model = IPCommercialization\n fields = '__all__'\n widgets = {\n 'filing_date': forms.DateInput(attrs={'type': 'date'}),\n 'contract_duration': forms.DateInput(attrs={'type': 'date'}),\n 'send_date': forms.DateInput(attrs={'type': 'date'}),\n }\n\n \nclass ReportIPForm(forms.Form):\n name = forms.CharField(label='IP name', max_length=100)\n\n class Meta:\n model = IntellectualProperty\n\n\nclass RequestPayment(forms.Form):\n protection_title_choices = [\n (ip.pk, ip.protection_title) for ip in IntellectualProperty.objects.filter(is_request=False).all()\n ]\n\n doc_number = forms.ChoiceField(label='Номер охранного документа', choices=protection_title_choices)\n # doc_number = fforms.CharField(label='Номер охранного документа', choices=protection_title_choices, max_length=100)\n\n\nclass ActualPatents(forms.Form):\n ip_type = forms.ModelChoiceField(label='Тип РИД', queryset=IntellectualPropertyType.objects.all())\n\n\nclass RequestsStatistics(forms.Form):\n year_choices = [('2017', '2017'), ('2018', '2018')]\n # for ip in IntellectualProperty.objects.all():\n # if ip.priority_date is not None:\n # year = str(ip.priority_date).split('.')[2]\n # if year not in year_choices:\n # year_choices.append((year, year))\n\n # doc_number = forms.ChoiceField(label='Номер охранного документа', choices=protection_title_choices)\n ip_type = forms.ModelChoiceField(label='Тип РИД', queryset=IntellectualPropertyType.objects.all())\n year = forms.ChoiceField(label='Год', choices=year_choices)\n\n\nclass PatentsStatistics(forms.Form):\n contract_type = forms.ModelChoiceField(label='Тип договора', queryset=ContractType.objects.all())\n year = forms.CharField(label='Год', max_length=4)\n\n\nclass MaintenanceOfPatents(forms.Form):\n sorting_field = forms.ChoiceField(\n choices=SORTING_MOP_CHOICES, label='Сортировка по полю: ', initial=0,\n widget=forms.Select(), required=True)\n\n\nclass Payments(forms.Form):\n year = forms.CharField(label='Год: ', max_length=4)\n is_supported = forms.BooleanField(label='Только поддерживаемые: ', required=False)\n\n\nclass Table23(forms.Form):\n year = forms.CharField(label='Год: ', max_length=4, initial='2018')\n\n\nclass MessageAnswerForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n self.message = kwargs.pop('message', None)\n super(MessageAnswerForm, self).__init__(*args, **kwargs)\n\n if self.message:\n self.fields['sender'].initial = User.objects.get(id=self.message.receiver.id)\n self.fields['receiver'].initial = User.objects.get(id=self.message.sender.id)\n\n class Meta:\n model = Message\n fields = '__all__'\n widgets = {\n 'text': forms.Textarea(attrs={'rows': '6'}),\n 'sender': forms.HiddenInput(),\n 'read': forms.HiddenInput(),\n 'receiver': forms.HiddenInput(),\n }\n\n\nclass MessageForm(forms.ModelForm):\n\n def __init__(self, request, *args, **kwargs):\n self.request = request\n super(MessageForm, self).__init__(*args, **kwargs)\n\n self.fields['sender'].initial = User.objects.get(id=get_user(self.request).id)\n self.fields['receiver'].queryset = User.objects.filter(~Q(id=get_user(self.request).id))\n\n class Meta:\n model = Message\n fields = '__all__'\n widgets = {\n 'text': forms.Textarea(attrs={'rows': '6'}),\n 'sender': forms.HiddenInput(),\n 'read': forms.HiddenInput(),\n }\n","sub_path":"ria_project/application/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":7908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"447234139","text":"\"\"\"\nThe code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version.\n\nYou can call isBadVersion to help you determine which version is the first bad one. The details interface can be found in the code's annotation part.\n\nExample\nGiven n = 5:\n\nisBadVersion(3) -> false\nisBadVersion(5) -> true\nisBadVersion(4) -> true\nHere we are 100% sure that the 4th version is the first bad version\nYou can use SVNRepo.isBadVersion(10) to check whether version 10 is a \nbad version.\n\"\"\"\n\"\"\"\n这是一道二分法的变形题,由于版本号是不断增加的,实际上是一个Sorted Array oooooxxxxxx\n也就是找第一个X是在哪里。二分法模板需要使用熟练\n\"\"\"\nclass Solution:\n \"\"\"\n @param n: An integer\n @return: An integer which is the first bad version.\n \"\"\"\n def findFirstBadVersion(self, n):\n \tif n is None or n < 0:\n \t\treturn -1\n \tstart ,end = 0, n\n \twhile start+1 < end:\n \t\tmid = (start + end) // 2\n \t\tif SVNRepo.isBadVersion(mid):\n \t\t\t# 是BadVerson,但不一定是最小的那个BadVersion\n \t\t\tend = mid\n \t\telse:\n \t\t\tstart = mid\n\n \tif SVNRepo.isBadVersion(start):\n \t\treturn start\n \treturn end","sub_path":"Python Version/Divide-and-Conquer/First Bad Version.py","file_name":"First Bad Version.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"145540502","text":"import itchat\nimport os\nfrom pydub import AudioSegment\nimport numpy as np\nimport cv2\n\n@itchat.msg_register([itchat.content.RECORDING, itchat.content.PICTURE,itchat.content.TEXT], isGroupChat=True)\ndef download(msg):\n global count, GID, UID, SelfID, FolderName\n #download audio, photo and text informations\n if msg['FromUserName'] == GID and msg['ActualUserName'] in UID and msg['Type']=='Recording':\n print(\"Recording:#{} from {}\".format(count, msg['ActualNickName']))\n msg['Text']('{}/{}.mp3'.format(FolderName,count))\n count += 1\n # if msg['FromUserName'] == GID and msg['ActualUserName'] in UID and msg['Type']=='Picture':\n # print(\"Pictures downloading:#{} From {}\".format(count, msg['ActualNickName']))\n # msg['Text']('{}/{}.png'.format(FolderName,count))\n # count += 1\n if msg['FromUserName'] == SelfID and msg['ToUserName'] in GID and msg['Type']=='Text' and msg['Text'].startswith('老师,您辛苦了!'):\n print(\"Concating.....\")\n AudioConcat(count, FolderName)\n print(\"Everything is done,Thx for using,comment blow my github if workout,GitHub:http://github.com/Wang-ZhengYi,Biliili:氢离子宇宙,祝身体健康,我们下次再会!\")\n itchat.logout()\n exit(0)\n\n# def blank_video():\n# img = np.zeros((1920,1080,3), np.uint8)\n# img.fill(255)\n# cv2.imshow('image', img)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()\n\n\ndef AudioConcat(count, FolderName):\n if not count:\n return\n result = AudioSegment.from_mp3('{}/0.mp3'.format(FolderName))\n for i in range(1, count):\n result += AudioSegment.from_mp3('{}/{}.mp3'.format(FolderName, i))\n result.export('{}/{}.mp3'.format(FolderName, 'result'), format='mp3')\n\ndef course_Info():\n print('**--------武-汉-加-油--------**')\n while True:\n FolderName = input(\"Coure FolderName\")\n if os.path.exists(FolderName):\n print(\"Folder Exits, Plz try again!\")\n else:\n os.mkdir(FolderName)\n break\n\n print('**--------武-汉-加-油--------**')\n itchat.get_chatrooms(update=True)\n while True:\n GName = input('Wechat Group Name:')\n G = itchat.search_chatrooms(name=GName)\n if G:\n break\n GID = G[0]['UserName']\n\n print('**--------武-汉-加-油--------**')\n G = itchat.update_chatroom(userName=GID, detailedMember=True)\n MList = G['MemberList']\n UID = []\n Unum = 1 #int(input(\"请输入老师与助教的总人数:\"))\n print(\"Teacher's UserName:\")\n while len(UsrID)< Unum:\n UName = input('UserName:')\n aUsrID = 0\n for m in MList:\n # print(m['NickName'], m['RemarkName'])\n if UName in [m['NickName'], m['RemarkName']]:\n aUsrID = m['UserName']\n if aUsrID:\n UID.append(aUsrID)\n print('Added:{}'.format(UName))\n else:\n print('Cannot find:{}| plz reinput after checking!'.format(UName))\n print('Recording : @{}@{}'.format(GName, UName))\n SelfID = itchat.get_friends()[0]['UserName']\n return GID, UID, FolderName, SelfID\n\n\nif __name__ == '__main__':\n itchat.auto_login(hotReload=True)\n count = 0\n GID, UID, FolderName, SelfID = course_Info()\n itchat.run()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"112411159","text":"import threading\nimport time\ndata = [90 ,81 ,78 ,95 ,79 ,72 ,85]\nout = []\ndef findave(data):\n out.append(int(sum(data) / len(data)))\n time.sleep(1)\ndef findmin(data):\n min_n = data[0]\n for i in range(1,len(data)):\n if data[i] < min_n:\n min_n = data[i]\n \n out.append(min_n)\n time.sleep(1)\ndef findmax(data):\n max_n = data[0]\n for i in range(1,len(data)):\n if data[i] > max_n:\n max_n = data[i]\n \n out.append(max_n)\n time.sleep(1)\nthreads = []\nthreads.append(threading.Thread(target = findave, args = (data,)))\nthreads.append(threading.Thread(target = findmin, args = (data,)))\nthreads.append(threading.Thread(target = findmax, args = (data,)))\n\nthreads[0].start()\nthreads[1].start()\nthreads[2].start()\n\nthreads[0].join()\nthreads[1].join()\nthreads[2].join()\nprint('The average value is '+str(out[0]))\nprint('The minimum value is '+str(out[1]))\nprint('The maximum value is '+str(out[2]))\n","sub_path":"os/task_scheduler/thread.py","file_name":"thread.py","file_ext":"py","file_size_in_byte":956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"498974563","text":"# -*- coding: utf-8 -*-\nclass PhoneticModel(object):\n vowels_sound = [u'и', u'ы', u'у', u'э', u'о', u'а']\n vowels_special = [u\"я\", u\"е\", u\"ё\", u\"ю\"]\n vowels = [u'и', u'ы', u'у', u'э', u'о', u'а', u\"я\", u\"е\", u\"ё\", u\"ю\"]\n consonants_sound = [u'б', u'в', u'г', u'д', u'з', u'к', u'л', u'м', u'н', u'п', u'р', u'с', u'т', u'ф', u'х', u'ж', u'ш', u'ц', u'ч', u'й']\n # voiced_paired = ['б', 'в', 'г', 'д', 'ж', 'з']\n voiced_paired = [u'б', u'в', u'г', u'д', u'ж', u'з']\n # clunk_paired = ['п', 'ф', 'к', 'т', 'ш', 'с']\n clunk_paired = [u'п', u'ф', u'к', u'т', u'ш', u'с']\n #original_word\n #new_ending\n\n def __init__(self, word, accent=255):\n self.original_word = word\n\n def get_ending(self):\n #only last two chars\n last = self.original_word[-1:]\n # print(self.original_word, 'я')\n penultimate = self.original_word[-2:-1]\n # print(penultimate, last)\n\n #penultimate char\n if penultimate in self.vowels_special:\n if penultimate == u'я':\n penultimate = u'а'\n elif penultimate == u'е':\n penultimate = u'э'\n elif penultimate == u'ё':\n penultimate = u'о'\n elif penultimate == u'ю':\n penultimate = u'у'\n\n if last in self.voiced_paired:\n ind = self.voiced_paired.index(last)\n last = self.clunk_paired[ind]\n\n self.new_ending = penultimate + last\n return self.new_ending\n\n #check single vowel and vowels absence\n @staticmethod\n def check_single_accent(w):\n number_of_vowels = 0\n for el in PhoneticModel.vowels:\n if el in w:\n number_of_vowels+=1\n\n if number_of_vowels == 0:\n return -1\n if number_of_vowels == 1:\n return 0;\n return 255","sub_path":"model/PhoneticModel.py","file_name":"PhoneticModel.py","file_ext":"py","file_size_in_byte":1923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"70317646","text":"# %%\nfrom tqdm import tqdm\nfrom datetime import datetime\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport sqlite3\n\ndb_path = r'D:\\\\research\\\\data\\\\sql\\\\analysis.db'\nwith sqlite3.connect(db_path) as con:\n post = pd.read_sql(\n 'SELECT post_ID, Candidate, post_Title, post_Datetime FROM original_post', con)\n push = pd.read_sql(\n 'SELECT post_ID, com_User, com_Datetime FROM original_push', con)\n\nca_data1 = pd.read_excel(\n r'E:\\\\research\\\\data\\\\候選人資料\\\\活躍百分位數0.9_留言下限10則_文章不限單一候選人.xlsx')\ncalist1 = set(ca_data1['com_User'].tolist())\n\npolarity = pd.read_excel(\n r'E:\\\\research\\\\data\\\\候選人資料\\\\polarity.xlsx')\npolarity.dropna(inplace=True)\nca_data2 = polarity[polarity['prefer_value'] > 10]\ncalist2 = set(ca_data2['com_User'].tolist())\n\npost.dropna(inplace=True)\npush.dropna(inplace=True)\n\npost['post_Datetime'] = post['post_Datetime'].map(\n lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S'))\npush['com_Datetime'] = push['com_Datetime'].map(\n lambda x: datetime.strptime(x, '%Y/%m/%d %H:%M'))\n\n\n# %%\n\nkeyword = pd.read_excel(\n r'E:\\\\research\\\\data\\\\候選人資料\\\\候選人關鍵字對照表.xlsx', '工作表1') # 匯入候選人關鍵字對照表\ncandidate_list = keyword['候選人'].drop_duplicates().tolist() # 建立候選人列表\ncandidate_list_in = post['Candidate'].drop_duplicates(\n).tolist() # 建立資料中出現過的候選人列表\n\n\ndef get_keywords(DataFrame, title_col):\n '''\n 取得DataFrame[title_col]所包含的候選人關鍵字的列表\n '''\n key_dict = {}\n for key, value in zip(keyword['關鍵字'], keyword['候選人']):\n key_dict[key] = value\n\n key = list(key_dict.keys())\n value = list(key_dict.values())\n data = DataFrame[title_col]\n\n KW = []\n for i in tqdm(range(len(data))):\n kwlist = []\n for j in range(len(key_dict)):\n if key[j] in DataFrame.loc[i, title_col]:\n kwlist.append(value[j])\n kw = ','.join(set(kwlist))\n KW.append(kw)\n\n return KW\n\n\ndef fillkeywords():\n '''\n 將空的關鍵字欄填上候選人\n '''\n for i in range(len(post['keywords'])):\n if post.loc[i, 'keywords'] == '':\n post.loc[i, 'keywords'] = post.loc[i, 'Candidate']\n\n\npost['keywords'] = get_keywords(post, 'post_Title') # 建立關鍵字欄\nfillkeywords() # 填滿空的關鍵字欄\n\ndf = pd.merge(push, post, 'left', 'post_ID')\n\n\n# %%\ndf_cal2 = df[df['com_User'].isin(calist2)]\n\nresponse_time = df_cal2.groupby(\n ['com_User', 'post_ID', 'post_Datetime'], as_index=False)['com_Datetime'].min()\nresponse_time['time_difference'] = (\n response_time['com_Datetime'] - response_time['post_Datetime'])\nresponse_time['time_difference'] = response_time['time_difference'].map(\n lambda x: x.seconds/60)\n\nmask = (response_time['time_difference'] <\n np.median(response_time['time_difference']))\nresponse_time_ca = response_time.loc[mask]\n\n\n\n# %%\nca_list = response_time_ca['com_User'].drop_duplicates().tolist()\n\n\n# %%\ndef get_response_timedelta(DataFrame):\n response_time = DataFrame.groupby(\n ['com_User', 'post_ID', 'post_Datetime'], as_index=False)['com_Datetime'].min()\n response_time['time_difference'] = (\n response_time['com_Datetime'] - response_time['post_Datetime'])\n response_time['time_difference'] = response_time['time_difference'].map(\n lambda x: x.seconds/60)\n\n return response_time\n\ndf_response_time = get_response_timedelta(df)\n# %%\n","sub_path":"PTT-CyberOperation/response_time.py","file_name":"response_time.py","file_ext":"py","file_size_in_byte":3559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"649256000","text":"#OOPR-Assgn-22\nclass Multiplex:\n __list_movie_name=[\"movie1\",\"movie2\"]\n __list_total_tickets=[100,60]\n __list_last_seat_number=[0,0]\n __list_ticket_price=[150,200]\n mv1_counter=0\n mv2_counter=0\n def __init__(self):\n self.__seat_numbers=None\n self.__total_price=None\n def calculate_ticket_price(self,movie_index,number_of_tickets):\n self.__total_price= Multiplex.__list_ticket_price[movie_index]*number_of_tickets\n def check_seat_availability(self,movie_index,number_of_tickets):\n if(Multiplex.__list_total_tickets[movie_index] \"84352\"\n\"84352\" (from index 0 to 2) -> \"34852\"\nExample 2:\n\nInput: s = \"34521\", t = \"23415\"\nOutput: true\nExplanation: You can transform s into t using the following sort operations:\n\"34521\" -> \"23451\"\n\"23451\" -> \"23415\"\nExample 3:\n\nInput: s = \"12345\", t = \"12435\"\nOutput: false\nExample 4:\n\nInput: s = \"1\", t = \"2\"\nOutput: false\n\n\nConstraints:\n\ns.length == t.length\n1 <= s.length <= 105\ns and t only contain digits from '0' to '9'.\n\n\"\"\"\n\n\nclass IsTransformable:\n\n \"\"\"\n queue, simulation\n\n We can always move a single digit to the left until there is a smaller one just lke bubble sort by swapping adjacent elements.\n\n 37584 -> 34758\n steps:\n 37584 -> 37548\n 37548 -> 37458\n 37458 -> 34758\n 34758 -> END\n\n This problem then reduced to: can we transform the string S to T by moving smaller digits to the left?\n\n Solution 1: simulation /Greedy/ Queue\n for each digit c in T:\n move the first c in s to the left most\n\n Simulation take O(n^2) time, we don't actually need to move.\n\n Create 10 queues, one for each digits to store the indices of each digits in S.\n We can check whether there is any smaller digits in front of the one to be moved to the front.\n\n Time Complexity: O(n)\n Space Complexity: O(n)\n\n \"\"\"\n def doit_greedy(self, s: str, t: str) -> bool:\n from collections import defaultdict, deque\n idx = defaultdict(deque)\n for i, c in enumerate(s):\n idx[int(c)].append(i)\n for c in t:\n d = int(c)\n if not idx[d]:\n return False\n for i in range(d):\n if idx[i] and idx[i][0] < idx[d][0]:\n return False\n idx[d].popleft()\n return True\n\n def doit_gready_way(self, s: str, t: str) -> bool:\n from collections import deque, defaultdict\n digits = [deque() for _ in range(10)]\n for i, c in enumerate(s):\n digits[int(c)].append(i)\n\n print(digits)\n for c in t:\n d = int(c)\n if not digits[d]:\n return False\n\n pos = digits[d].popleft()\n\n for i in range(d):\n if digits[i] and digits[i][0] < pos:\n return False\n return True\n\n\nif __name__ == '__main__':\n\n IsTransformable().doit_dp(s = \"84532\", t = \"34852\")\n\n IsTransformable().doit_dp(s = \"34521\", t = \"23415\")\n\n IsTransformable().doit_dp(s = \"12345\", t = \"12435\")\n\n IsTransformable().doit_dp(s = \"1\", t = \"2\")","sub_path":"PythonLeetcode/Leetcode/1585_CheckIfStringIsTransformableWithSubstringSortOperations.py","file_name":"1585_CheckIfStringIsTransformableWithSubstringSortOperations.py","file_ext":"py","file_size_in_byte":3229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193985811","text":"import socket\nimport threading\nfrom ctypes import (\n Structure, Union, Array,\n c_float, c_byte\n)\n\nfrom ShipMap import settings\n\n\nclass uint8_array(Array):\n _type_ = c_byte\n _length_ = 4\n\n\nclass C_ReadUnion(Union):\n _fields_ = (\"data\", c_float), (\"chunk\", uint8_array)\n\n\nclass C_ReadUnion_8(Array):\n _type_ = C_ReadUnion\n _length_ = 8\n\n\nclass C_Location(Structure):\n _fields_ = (\"latitude\", C_ReadUnion), (\"longitude\", C_ReadUnion), (\"altitude\", C_ReadUnion), \\\n (\"distance\", C_ReadUnion), (\"orientation\", C_ReadUnion), (\"height\", C_ReadUnion), \\\n (\"speed\", C_ReadUnion), (\"direction\", C_ReadUnion), (\"reserve\", C_ReadUnion_8)\n\n\nclass Location(object):\n def __init__(self, c_loc):\n if settings.DEBUG:\n self.latitude = round(c_loc.latitude.data, 5)\n self.longitude = round(c_loc.longitude.data, 5)\n # self.latitude = round(c_loc.latitude.data, 5) + random.random() / 100\n # self.longitude = round(c_loc.longitude.data, 5) + random.random() / 100\n else:\n self.latitude = round(c_loc.latitude.data, 5)\n self.longitude = round(c_loc.longitude.data, 5)\n self.altitude = round(c_loc.altitude.data, 2)\n self.distance = round(c_loc.distance.data, 2)\n self.orientation = round(c_loc.orientation.data, 2)\n self.height = round(c_loc.height.data, 2)\n self.speed = round(c_loc.speed.data, 2)\n self.direction = round(c_loc.direction.data, 2)\n\n def __str__(self):\n return \"经度:{0},纬度:{1},海拔:{2},距离:{3},方位:{4},高度:{5},速度:{6},方向:{7}\".format(\n self.longitude, self.latitude, self.altitude, self.distance,\n self.orientation, self.height, self.speed, self.direction)\n\n def to_json(self):\n return self.__dict__\n\n\nHOST = '127.0.0.1'\nPORT = 8008\n\nclient_cache = []\n\n\nclass RadarReceiver:\n BUF_SIZE = 1024\n MAX_CONNECTIONS = 5\n DATA_LEN = 64\n\n def __init__(self, host=HOST, port=PORT):\n self.is_radar_running = True\n self.thread_radar = None\n self.host = host\n self.port = port\n self.items = []\n self.callback = None\n self.name = \"radar_1\"\n\n def set_callback(self, callback):\n self.callback = callback\n\n def start_radar_receiver(self):\n \"\"\"\n 开启雷达接收线程\n :return:\n \"\"\"\n self.is_radar_running = True\n self.thread_radar = threading.Thread(group=None, target=self.__start_socket_receiver)\n self.thread_radar.name = \"RadarReceiver_Thread\"\n self.thread_radar.start()\n\n def stop_radar_receiver(self):\n self.is_radar_running = False\n self.thread_radar.join()\n\n def __start_socket_receiver(self):\n server_addr = (self.host, self.port)\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n server.bind(server_addr)\n server.listen(RadarReceiver.MAX_CONNECTIONS)\n\n while self.is_radar_running:\n client, client_addr = server.accept()\n print('Connected by:%s', client_addr)\n while self.is_radar_running:\n read_bytes = client.recv(RadarReceiver.BUF_SIZE)\n if len(read_bytes) == 0:\n break\n self.__parse_location(read_bytes)\n server.close()\n\n def __parse_location(self, data):\n index = 0\n # 4字节协议头,4字节数据条数\n header = data[index:index + 4]\n if header != b'\\xaa\\xaa\\xaa\\xaa':\n return\n\n index += 4\n ri = C_ReadUnion()\n ri.chunk[:] = data[index:index + 4]\n index += 4\n\n data_len = int(ri.data)\n loc_list = []\n for i in range(data_len):\n item_data = data[index:index + RadarReceiver.DATA_LEN]\n if len(item_data) != RadarReceiver.DATA_LEN:\n break\n index += RadarReceiver.DATA_LEN\n\n loc = C_Location()\n loc.latitude.chunk[:] = item_data[0 * 4: 1 * 4]\n loc.longitude.chunk[:] = item_data[1 * 4: 2 * 4]\n loc.altitude.chunk[:] = item_data[2 * 4: 3 * 4]\n\n loc.distance.chunk[:] = item_data[3 * 4: 4 * 4]\n loc.orientation.chunk[:] = item_data[4 * 4: 5 * 4]\n loc.height.chunk[:] = item_data[5 * 4: 6 * 4]\n loc.speed.chunk[:] = item_data[6 * 4: 7 * 4]\n\n loc.direction.chunk[:] = item_data[7 * 4: 8 * 4]\n\n l = Location(loc)\n loc_list.append(l.to_json())\n print(\"- - {0}、{1}\".format(i, l))\n\n radar_dic = {\"radar\": self.name, \"items\": loc_list}\n if self.callback:\n self.callback(radar_dic)\n\n\nif __name__ == \"__main__\":\n radar_receiver = RadarReceiver()\n radar_receiver.start_radar_receiver()\n a = input(\"press any key to stop radar receiver:\")\n","sub_path":"map/RadarReceiver.py","file_name":"RadarReceiver.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"105259596","text":"\"\"\"\nCretonne meta language module.\n\nThis module provides classes and functions used to describe Cretonne\ninstructions.\n\"\"\"\nfrom __future__ import absolute_import\nimport re\nimport math\nimport importlib\nfrom collections import OrderedDict\nfrom .predicates import And, Predicate, FieldPredicate # noqa\n\n# The typing module is only required by mypy, and we don't use these imports\n# outside type comments.\ntry:\n from typing import Tuple, Union, Any, Iterable, Sequence # noqa\n MaybeBoundInst = Union['Instruction', 'BoundInstruction']\n AnyPredicate = Union['Predicate', 'FieldPredicate']\nexcept ImportError:\n pass\n\n\ncamel_re = re.compile('(^|_)([a-z])')\n\n\ndef camel_case(s):\n # type: (str) -> str\n \"\"\"Convert the string s to CamelCase\"\"\"\n return camel_re.sub(lambda m: m.group(2).upper(), s)\n\n\nclass Setting(object):\n \"\"\"\n A named setting variable that can be configured externally to Cretonne.\n\n Settings are normally not named when they are created. They get their name\n from the `extract_names` method.\n \"\"\"\n\n def __init__(self, doc):\n self.name = None # Assigned later by `extract_names()`.\n self.__doc__ = doc\n # Offset of byte in settings vector containing this setting.\n self.byte_offset = None\n self.group = SettingGroup.append(self)\n\n def __str__(self):\n return '{}.{}'.format(self.group.name, self.name)\n\n def predicate_context(self):\n \"\"\"\n Return the context where this setting can be evaluated as a (leaf)\n predicate.\n \"\"\"\n return self.group\n\n def predicate_leafs(self, leafs):\n leafs.add(self)\n\n\nclass BoolSetting(Setting):\n \"\"\"\n A named setting with a boolean on/off value.\n\n :param doc: Documentation string.\n :param default: The default value of this setting.\n \"\"\"\n\n def __init__(self, doc, default=False):\n super(BoolSetting, self).__init__(doc)\n self.default = default\n\n def default_byte(self):\n \"\"\"\n Get the default value of this setting, as a byte that can be bitwise\n or'ed with the other booleans sharing the same byte.\n \"\"\"\n if self.default:\n return 1 << self.bit_offset\n else:\n return 0\n\n def rust_predicate(self, prec):\n \"\"\"\n Return the Rust code to compute the value of this setting.\n\n The emitted code assumes that the setting group exists as a local\n variable.\n \"\"\"\n return '{}.{}()'.format(self.group.name, self.name)\n\n\nclass NumSetting(Setting):\n \"\"\"\n A named setting with an integral value in the range 0--255.\n\n :param doc: Documentation string.\n :param default: The default value of this setting.\n \"\"\"\n\n def __init__(self, doc, default=0):\n super(NumSetting, self).__init__(doc)\n assert default == int(default)\n assert default >= 0 and default <= 255\n self.default = default\n\n def default_byte(self):\n return self.default\n\n\nclass EnumSetting(Setting):\n \"\"\"\n A named setting with an enumerated set of possible values.\n\n The default value is always the first enumerator.\n\n :param doc: Documentation string.\n :param args: Tuple of unique strings representing the possible values.\n \"\"\"\n\n def __init__(self, doc, *args):\n super(EnumSetting, self).__init__(doc)\n assert len(args) > 0, \"EnumSetting must have at least one value\"\n self.values = tuple(str(x) for x in args)\n self.default = self.values[0]\n\n def default_byte(self):\n return 0\n\n\nclass SettingGroup(object):\n \"\"\"\n A group of settings.\n\n Whenever a :class:`Setting` object is created, it is added to the currently\n open group. A setting group must be closed explicitly before another can be\n opened.\n\n :param name: Short mnemonic name for setting group.\n :param parent: Parent settings group.\n \"\"\"\n\n # The currently open setting group.\n _current = None # type: SettingGroup\n\n def __init__(self, name, parent=None):\n self.name = name\n self.parent = parent\n self.settings = []\n # Named predicates computed from settings in this group or its\n # parents.\n self.named_predicates = []\n # All boolean predicates that can be accessed by number. This includes:\n # - All boolean settings in this group.\n # - All named predicates.\n # - Added anonymous predicates, see `number_predicate()`.\n # - Added parent predicates that are replicated in this group.\n # Maps predicate -> number.\n self.predicate_number = OrderedDict()\n\n self.open()\n\n def open(self):\n \"\"\"\n Open this setting group such that future new settings are added to this\n group.\n \"\"\"\n assert SettingGroup._current is None, (\n \"Can't open {} since {} is already open\"\n .format(self, SettingGroup._current))\n SettingGroup._current = self\n\n def close(self, globs=None):\n \"\"\"\n Close this setting group. This function must be called before opening\n another setting group.\n\n :param globs: Pass in `globals()` to run `extract_names` on all\n settings defined in the module.\n \"\"\"\n assert SettingGroup._current is self, (\n \"Can't close {}, the open setting group is {}\"\n .format(self, SettingGroup._current))\n SettingGroup._current = None\n if globs:\n for name, obj in globs.items():\n if isinstance(obj, Setting):\n assert obj.name is None, obj.name\n obj.name = name\n if isinstance(obj, Predicate):\n assert obj.name is None\n obj.name = name\n self.named_predicates.append(obj)\n self.layout()\n\n @staticmethod\n def append(setting):\n g = SettingGroup._current\n assert g, \"Open a setting group before defining settings.\"\n g.settings.append(setting)\n return g\n\n def number_predicate(self, pred):\n \"\"\"\n Make sure that `pred` has an assigned number, and will be included in\n this group's bit vector.\n\n The numbered predicates include:\n - `BoolSetting` settings that belong to this group.\n - `Predicate` instances in `named_predicates`.\n - `Predicate` instances without a name.\n - Settings or computed predicates that belong to the parent group, but\n need to be accessible by number in this group.\n\n The numbered predicates are referenced by the encoding tables as ISA\n predicates. See the `isap` field on `Encoding`.\n\n :returns: The assigned predicate number in this group.\n \"\"\"\n if pred in self.predicate_number:\n return self.predicate_number[pred]\n else:\n number = len(self.predicate_number)\n self.predicate_number[pred] = number\n return number\n\n def layout(self):\n \"\"\"\n Compute the layout of the byte vector used to represent this settings\n group.\n\n The byte vector contains the following entries in order:\n\n 1. Byte-sized settings like `NumSetting` and `EnumSetting`.\n 2. `BoolSetting` settings.\n 3. Precomputed named predicates.\n 4. Other numbered predicates, including anonymous predicates and parent\n predicates that need to be accessible by number.\n\n Set `self.settings_size` to the length of the byte vector prefix that\n contains the settings. All bytes after that are computed, not\n configured.\n\n Set `self.boolean_offset` to the beginning of the numbered predicates,\n 2. in the list above.\n\n Assign `byte_offset` and `bit_offset` fields in all settings.\n\n After calling this method, no more settings can be added, but\n additional predicates can be made accessible with `number_predicate()`.\n \"\"\"\n assert len(self.predicate_number) == 0, \"Too late for layout\"\n\n # Assign the non-boolean settings.\n byte_offset = 0\n for s in self.settings:\n if not isinstance(s, BoolSetting):\n s.byte_offset = byte_offset\n byte_offset += 1\n\n # Then the boolean settings.\n self.boolean_offset = byte_offset\n for s in self.settings:\n if isinstance(s, BoolSetting):\n number = self.number_predicate(s)\n s.byte_offset = byte_offset + number // 8\n s.bit_offset = number % 8\n\n # This is the end of the settings. Round up to a whole number of bytes.\n self.boolean_settings = len(self.predicate_number)\n self.settings_size = self.byte_size()\n\n # Now assign numbers to all our named predicates.\n for p in self.named_predicates:\n self.number_predicate(p)\n\n def byte_size(self):\n \"\"\"\n Compute the number of bytes required to hold all settings and\n precomputed predicates.\n\n This is the size of the byte-sized settings plus all the numbered\n predcate bits rounded up to a whole number of bytes.\n \"\"\"\n return self.boolean_offset + (len(self.predicate_number) + 7) // 8\n\n\n# Kinds of operands.\n#\n# Each instruction has an opcode and a number of operands. The opcode\n# determines the instruction format, and the format determines the number of\n# operands and the kind of each operand.\nclass OperandKind(object):\n \"\"\"\n An instance of the `OperandKind` class corresponds to a kind of operand.\n Each operand kind has a corresponding type in the Rust representation of an\n instruction.\n \"\"\"\n\n def __init__(self, name, doc, default_member=None, rust_type=None):\n self.name = name\n self.__doc__ = doc\n self.default_member = default_member\n # The camel-cased name of an operand kind is also the Rust type used to\n # represent it.\n self.rust_type = rust_type or camel_case(name)\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n return 'OperandKind({})'.format(self.name)\n\n def operand_kind(self):\n \"\"\"\n An `OperandKind` instance can be used directly as the type of an\n `Operand` when defining an instruction.\n \"\"\"\n return self\n\n def free_typevar(self):\n # Return the free typevariable controlling the type of this operand.\n return None\n\n#: An SSA value operand. This is a value defined by another instruction.\nvalue = OperandKind(\n 'value', \"\"\"\n An SSA value defined by another instruction.\n\n This kind of operand can represent any SSA value type, but the\n instruction format may restrict the valid value types for a given\n operand.\n \"\"\")\n\n#: A variable-sized list of value operands. Use for Ebb and function call\n#: arguments.\nvariable_args = OperandKind(\n 'variable_args', \"\"\"\n A variable size list of `value` operands.\n\n Use this to represent arguemtns passed to a function call, arguments\n passed to an extended basic block, or a variable number of results\n returned from an instruction.\n \"\"\",\n default_member='varargs')\n\n\n# Instances of immediate operand types are provided in the\n# `cretonne.immediates` module.\nclass ImmediateKind(OperandKind):\n \"\"\"\n The kind of an immediate instruction operand.\n\n :param default_member: The default member name of this kind the\n `InstructionData` data structure.\n \"\"\"\n\n def __init__(self, name, doc, default_member='imm', rust_type=None):\n super(ImmediateKind, self).__init__(\n name, doc, default_member, rust_type)\n\n def __repr__(self):\n return 'ImmediateKind({})'.format(self.name)\n\n\n# Instances of entity reference operand types are provided in the\n# `cretonne.entities` module.\nclass EntityRefKind(OperandKind):\n \"\"\"\n The kind of an entity reference instruction operand.\n \"\"\"\n\n def __init__(self, name, doc, default_member=None, rust_type=None):\n super(EntityRefKind, self).__init__(\n name, doc, default_member or name, rust_type)\n\n def __repr__(self):\n return 'EntityRefKind({})'.format(self.name)\n\n\n# ValueType instances (i8, i32, ...) are provided in the cretonne.types module.\nclass ValueType(object):\n \"\"\"\n A concrete SSA value type.\n\n All SSA values have a type that is described by an instance of `ValueType`\n or one of its subclasses.\n \"\"\"\n\n # Map name -> ValueType.\n _registry = dict() # type: Dict[str, ValueType]\n\n # List of all the scalar types.\n all_scalars = list() # type: List[ValueType]\n\n def __init__(self, name, membytes, doc):\n self.name = name\n self.membytes = membytes\n self.__doc__ = doc\n assert name not in ValueType._registry\n ValueType._registry[name] = self\n\n def __str__(self):\n return self.name\n\n def operand_kind(self):\n \"\"\"\n When a `ValueType` object is used to describe the type of an `Operand`\n in an instruction definition, the kind of that operand is an SSA value.\n \"\"\"\n return value\n\n def free_typevar(self):\n return None\n\n @staticmethod\n def by_name(name):\n if name in ValueType._registry:\n return ValueType._registry[name]\n else:\n raise AttributeError(\"No type named '{}'\".format(name))\n\n\nclass ScalarType(ValueType):\n \"\"\"\n A concrete scalar (not vector) type.\n\n Also tracks a unique set of :py:class:`VectorType` instances with this type\n as the lane type.\n \"\"\"\n\n def __init__(self, name, membytes, doc):\n super(ScalarType, self).__init__(name, membytes, doc)\n self._vectors = dict()\n # Assign numbers starting from 1. (0 is VOID).\n ValueType.all_scalars.append(self)\n self.number = len(ValueType.all_scalars)\n assert self.number < 16, 'Too many scalar types'\n\n def __repr__(self):\n return 'ScalarType({})'.format(self.name)\n\n def rust_name(self):\n return 'types::' + self.name.upper()\n\n def by(self, lanes):\n \"\"\"\n Get a vector type with this type as the lane type.\n\n For example, ``i32.by(4)`` returns the :obj:`i32x4` type.\n \"\"\"\n if lanes in self._vectors:\n return self._vectors[lanes]\n else:\n v = VectorType(self, lanes)\n self._vectors[lanes] = v\n return v\n\n\nclass VectorType(ValueType):\n \"\"\"\n A concrete SIMD vector type.\n\n A vector type has a lane type which is an instance of :class:`ScalarType`,\n and a positive number of lanes.\n \"\"\"\n\n def __init__(self, base, lanes):\n assert isinstance(base, ScalarType), 'SIMD lanes must be scalar types'\n super(VectorType, self).__init__(\n name='{}x{}'.format(base.name, lanes),\n membytes=lanes*base.membytes,\n doc=\"\"\"\n A SIMD vector with {} lanes containing a `{}` each.\n \"\"\".format(lanes, base.name))\n self.base = base\n self.lanes = lanes\n self.number = 16*int(math.log(lanes, 2)) + base.number\n\n def __repr__(self):\n return ('VectorType(base={}, lanes={})'\n .format(self.base.name, self.lanes))\n\n\nclass IntType(ScalarType):\n \"\"\"A concrete scalar integer type.\"\"\"\n\n def __init__(self, bits):\n assert bits > 0, 'IntType must have positive number of bits'\n super(IntType, self).__init__(\n name='i{:d}'.format(bits),\n membytes=bits // 8,\n doc=\"An integer type with {} bits.\".format(bits))\n self.bits = bits\n\n def __repr__(self):\n return 'IntType(bits={})'.format(self.bits)\n\n\nclass FloatType(ScalarType):\n \"\"\"A concrete scalar floating point type.\"\"\"\n\n def __init__(self, bits, doc):\n assert bits > 0, 'FloatType must have positive number of bits'\n super(FloatType, self).__init__(\n name='f{:d}'.format(bits),\n membytes=bits // 8,\n doc=doc)\n self.bits = bits\n\n def __repr__(self):\n return 'FloatType(bits={})'.format(self.bits)\n\n\nclass BoolType(ScalarType):\n \"\"\"A concrete scalar boolean type.\"\"\"\n\n def __init__(self, bits):\n assert bits > 0, 'BoolType must have positive number of bits'\n super(BoolType, self).__init__(\n name='b{:d}'.format(bits),\n membytes=bits // 8,\n doc=\"A boolean type with {} bits.\".format(bits))\n self.bits = bits\n\n def __repr__(self):\n return 'BoolType(bits={})'.format(self.bits)\n\n\n# Defining instructions.\n\n\nclass InstructionGroup(object):\n \"\"\"\n Every instruction must belong to exactly one instruction group. A given\n target architecture can support instructions from multiple groups, and it\n does not necessarily support all instructions in a group.\n\n New instructions are automatically added to the currently open instruction\n group.\n \"\"\"\n\n # The currently open instruction group.\n _current = None # type: InstructionGroup\n\n def open(self):\n \"\"\"\n Open this instruction group such that future new instructions are\n added to this group.\n \"\"\"\n assert InstructionGroup._current is None, (\n \"Can't open {} since {} is already open\"\n .format(self, InstructionGroup._current))\n InstructionGroup._current = self\n\n def close(self):\n \"\"\"\n Close this instruction group. This function should be called before\n opening another instruction group.\n \"\"\"\n assert InstructionGroup._current is self, (\n \"Can't close {}, the open instuction group is {}\"\n .format(self, InstructionGroup._current))\n InstructionGroup._current = None\n\n def __init__(self, name, doc):\n self.name = name\n self.__doc__ = doc\n self.instructions = []\n self.open()\n\n @staticmethod\n def append(inst):\n assert InstructionGroup._current, \\\n \"Open an instruction group before defining instructions.\"\n InstructionGroup._current.instructions.append(inst)\n\n\nclass Operand(object):\n \"\"\"\n An instruction operand can be an *immediate*, an *SSA value*, or an *entity\n reference*. The type of the operand is one of:\n\n 1. A :py:class:`ValueType` instance indicates an SSA value operand with a\n concrete type.\n\n 2. A :py:class:`TypeVar` instance indicates an SSA value operand, and the\n instruction is polymorphic over the possible concrete types that the\n type variable can assume.\n\n 3. An :py:class:`ImmediateKind` instance indicates an immediate operand\n whose value is encoded in the instruction itself rather than being\n passed as an SSA value.\n\n 4. An :py:class:`EntityRefKind` instance indicates an operand that\n references another entity in the function, typically something declared\n in the function preamble.\n\n \"\"\"\n def __init__(self, name, typ, doc=''):\n self.name = name\n self.typ = typ\n self.__doc__ = doc\n self.kind = typ.operand_kind()\n\n def get_doc(self):\n if self.__doc__:\n return self.__doc__\n else:\n return self.typ.__doc__\n\n def __str__(self):\n return \"`{}`\".format(self.name)\n\n def is_value(self):\n \"\"\"\n Is this an SSA value operand?\n \"\"\"\n return self.kind is value\n\n\nclass InstructionFormat(object):\n \"\"\"\n Every instruction opcode has a corresponding instruction format which\n determines the number of operands and their kinds. Instruction formats are\n identified structurally, i.e., the format of an instruction is derived from\n the kinds of operands used in its declaration.\n\n Most instruction formats produce a single result, or no result at all. If\n an instruction can produce more than one result, the `multiple_results`\n flag must be set on its format. All results are of the `value` kind, and\n the instruction format does not keep track of how many results are\n produced. Some instructions, like `call`, may have a variable number of\n results.\n\n All instruction formats must be predefined in the\n :py:mod:`cretonne.formats` module.\n\n :param kinds: List of `OperandKind` objects describing the operands.\n :param name: Instruction format name in CamelCase. This is used as a Rust\n variant name in both the `InstructionData` and `InstructionFormat`\n enums.\n :param multiple_results: Set to `True` if this instruction format allows\n more than one result to be produced.\n :param boxed_storage: Set to `True` is this instruction format requires a\n `data: Box<...>` pointer to additional storage in its `InstructionData`\n variant.\n :param typevar_operand: Index of the input operand that is used to infer\n the controlling type variable. By default, this is the first `value`\n operand.\n \"\"\"\n\n # Map (multiple_results, kind, kind, ...) -> InstructionFormat\n _registry = dict() # type: Dict[Tuple, InstructionFormat]\n\n # All existing formats.\n all_formats = list() # type: List[InstructionFormat]\n\n def __init__(self, *kinds, **kwargs):\n # type: (*Union[OperandKind, Tuple[str, OperandKind]], **Any) -> None # noqa\n self.name = kwargs.get('name', None) # type: str\n self.multiple_results = kwargs.get('multiple_results', False)\n self.boxed_storage = kwargs.get('boxed_storage', False)\n self.members = list() # type: List[str]\n self.kinds = tuple(self._process_member_names(kinds))\n\n # Which of self.kinds are `value`?\n self.value_operands = tuple(\n i for i, k in enumerate(self.kinds) if k is value)\n\n # The typevar_operand argument must point to a 'value' operand.\n self.typevar_operand = kwargs.get('typevar_operand', None) # type: int\n if self.typevar_operand is not None:\n assert self.kinds[self.typevar_operand] is value, \\\n \"typevar_operand must indicate a 'value' operand\"\n elif len(self.value_operands) > 0:\n # Default to the first 'value' operand, if there is one.\n self.typevar_operand = self.value_operands[0]\n\n # Compute a signature for the global registry.\n sig = (self.multiple_results,) + self.kinds\n if sig in InstructionFormat._registry:\n raise RuntimeError(\n \"Format '{}' has the same signature as existing format '{}'\"\n .format(self.name, InstructionFormat._registry[sig]))\n InstructionFormat._registry[sig] = self\n InstructionFormat.all_formats.append(self)\n\n def _process_member_names(self, kinds):\n # type: (Sequence[Union[OperandKind, Tuple[str, OperandKind]]]) -> Iterable[OperandKind] # noqa\n \"\"\"\n Extract names of all the immediate operands in the kinds tuple.\n\n Each entry is either an `OperandKind` instance, or a `(member, kind)`\n pair. The member names correspond to members in the Rust\n `InstructionData` data structure.\n\n Yields the operand kinds.\n \"\"\"\n for arg in kinds:\n if isinstance(arg, OperandKind):\n member = arg.default_member\n k = arg\n else:\n member, k = arg\n self.members.append(member)\n yield k\n\n def __str__(self):\n args = ', '.join('{}: {}'.format(m, k) if m else str(k)\n for m, k in zip(self.members, self.kinds))\n return '{}({})'.format(self.name, args)\n\n def __getattr__(self, attr):\n # type: (str) -> FormatField\n \"\"\"\n Make instruction format members available as attributes.\n\n Each non-value format member becomes a corresponding `FormatField`\n attribute.\n \"\"\"\n try:\n i = self.members.index(attr)\n except ValueError:\n raise AttributeError(\n '{} is neither a {} member or a '\n .format(attr, self.name) +\n 'normal InstructionFormat attribute')\n field = FormatField(self, i, attr)\n setattr(self, attr, field)\n return field\n\n @staticmethod\n def lookup(ins, outs):\n # type: (Sequence[Operand], Sequence[Operand]) -> InstructionFormat\n \"\"\"\n Find an existing instruction format that matches the given lists of\n instruction inputs and outputs.\n\n The `ins` and `outs` arguments correspond to the\n :py:class:`Instruction` arguments of the same name, except they must be\n tuples of :py:`Operand` objects.\n \"\"\"\n if len(outs) == 1:\n multiple_results = outs[0].kind == variable_args\n else:\n multiple_results = len(outs) > 1\n sig = (multiple_results,) + tuple(op.kind for op in ins)\n if sig not in InstructionFormat._registry:\n raise RuntimeError(\n \"No instruction format matches ins = ({}){}\".format(\n \", \".join(map(str, sig[1:])),\n \"[multiple results]\" if multiple_results else \"\"))\n return InstructionFormat._registry[sig]\n\n @staticmethod\n def extract_names(globs):\n \"\"\"\n Given a dict mapping name -> object as returned by `globals()`, find\n all the InstructionFormat objects and set their name from the dict key.\n This is used to name a bunch of global variables in a module.\n \"\"\"\n for name, obj in globs.items():\n if isinstance(obj, InstructionFormat):\n assert obj.name is None\n obj.name = name\n\n\nclass FormatField(object):\n \"\"\"\n A field in an instruction format.\n\n This corresponds to a single member of a variant of the `InstructionData`\n data type.\n\n :param format: Parent `InstructionFormat`.\n :param operand: Operand number in parent.\n :param name: Member name in `InstructionData` variant.\n \"\"\"\n\n def __init__(self, format, operand, name):\n # type: (InstructionFormat, int, str) -> None\n self.format = format\n self.operand = operand\n self.name = name\n\n def __str__(self):\n return '{}.{}'.format(self.format.name, self.name)\n\n def rust_name(self):\n # type: () -> str\n if self.format.boxed_storage:\n return 'data.' + self.name\n else:\n return self.name\n\n\nclass Instruction(object):\n \"\"\"\n The operands to the instruction are specified as two tuples: ``ins`` and\n ``outs``. Since the Python singleton tuple syntax is a bit awkward, it is\n allowed to specify a singleton as just the operand itself, i.e., `ins=x`\n and `ins=(x,)` are both allowed and mean the same thing.\n\n :param name: Instruction mnemonic, also becomes opcode name.\n :param doc: Documentation string.\n :param ins: Tuple of input operands. This can be a mix of SSA value\n operands and other operand kinds.\n :param outs: Tuple of output operands. The output operands must be SSA\n values or `variable_args`.\n :param is_terminator: This is a terminator instruction.\n :param is_branch: This is a branch instruction.\n \"\"\"\n\n def __init__(self, name, doc, ins=(), outs=(), **kwargs):\n # type: (str, str, Union[Sequence[Operand], Operand], Union[Sequence[Operand], Operand], **Any) -> None # noqa\n self.name = name\n self.camel_name = camel_case(name)\n self.__doc__ = doc\n self.ins = self._to_operand_tuple(ins)\n self.outs = self._to_operand_tuple(outs)\n self.format = InstructionFormat.lookup(self.ins, self.outs)\n # Indexes into outs for value results. Others are `variable_args`.\n self.value_results = tuple(\n i for i, o in enumerate(self.outs) if o.is_value())\n self._verify_polymorphic()\n InstructionGroup.append(self)\n\n def __str__(self):\n prefix = ', '.join(o.name for o in self.outs)\n if prefix:\n prefix = prefix + ' = '\n suffix = ', '.join(o.name for o in self.ins)\n return '{}{} {}'.format(prefix, self.name, suffix)\n\n def blurb(self):\n \"\"\"Get the first line of the doc comment\"\"\"\n for line in self.__doc__.split('\\n'):\n line = line.strip()\n if line:\n return line\n return \"\"\n\n def _verify_polymorphic(self):\n \"\"\"\n Check if this instruction is polymorphic, and verify its use of type\n variables.\n \"\"\"\n poly_ins = [\n i for i in self.format.value_operands\n if self.ins[i].typ.free_typevar()]\n poly_outs = [\n i for i, o in enumerate(self.outs)\n if o.typ.free_typevar()]\n self.is_polymorphic = len(poly_ins) > 0 or len(poly_outs) > 0\n if not self.is_polymorphic:\n return\n\n # Prefer to use the typevar_operand to infer the controlling typevar.\n self.use_typevar_operand = False\n typevar_error = None\n if self.format.typevar_operand is not None:\n try:\n tv = self.ins[self.format.typevar_operand].typ\n if tv is tv.free_typevar():\n self.other_typevars = self._verify_ctrl_typevar(tv)\n self.ctrl_typevar = tv\n self.use_typevar_operand = True\n except RuntimeError as e:\n typevar_error = e\n\n if not self.use_typevar_operand:\n # The typevar_operand argument doesn't work. Can we infer from the\n # first result instead?\n if len(self.outs) == 0:\n if typevar_error:\n raise typevar_error\n else:\n raise RuntimeError(\n \"typevar_operand must be a free type variable\")\n tv = self.outs[0].typ\n if tv is not tv.free_typevar():\n raise RuntimeError(\"first result must be a free type variable\")\n self.other_typevars = self._verify_ctrl_typevar(tv)\n self.ctrl_typevar = tv\n\n def _verify_ctrl_typevar(self, ctrl_typevar):\n \"\"\"\n Verify that the use of TypeVars is consistent with `ctrl_typevar` as\n the controlling type variable.\n\n All polymorhic inputs must either be derived from `ctrl_typevar` or be\n independent free type variables only used once.\n\n All polymorphic results must be derived from `ctrl_typevar`.\n\n Return list of other type variables used, or raise an error.\n \"\"\"\n other_tvs = []\n # Check value inputs.\n for opidx in self.format.value_operands:\n typ = self.ins[opidx].typ\n tv = typ.free_typevar()\n # Non-polymorphic or derived form ctrl_typevar is OK.\n if tv is None or tv is ctrl_typevar:\n continue\n # No other derived typevars allowed.\n if typ is not tv:\n raise RuntimeError(\n \"{}: type variable {} must be derived from {}\"\n .format(self.ins[opidx], typ.name, ctrl_typevar))\n # Other free type variables can only be used once each.\n if tv in other_tvs:\n raise RuntimeError(\n \"type variable {} can't be used more than once\"\n .format(tv.name))\n other_tvs.append(tv)\n\n # Check outputs.\n for result in self.outs:\n typ = result.typ\n tv = typ.free_typevar()\n # Non-polymorphic or derived from ctrl_typevar is OK.\n if tv is None or tv is ctrl_typevar:\n continue\n raise RuntimeError(\n \"type variable in output not derived from ctrl_typevar\")\n\n return other_tvs\n\n @staticmethod\n def _to_operand_tuple(x):\n # type: (Union[Sequence[Operand], Operand]) -> Tuple[Operand, ...]\n # Allow a single Operand instance instead of the awkward singleton\n # tuple syntax.\n if isinstance(x, Operand):\n x = (x,)\n else:\n x = tuple(x)\n for op in x:\n assert isinstance(op, Operand)\n return x\n\n def bind(self, *args):\n # type: (*ValueType) -> BoundInstruction\n \"\"\"\n Bind a polymorphic instruction to a concrete list of type variable\n values.\n \"\"\"\n assert self.is_polymorphic\n return BoundInstruction(self, args)\n\n def __getattr__(self, name):\n # type: (str) -> BoundInstruction\n \"\"\"\n Bind a polymorphic instruction to a single type variable with dot\n syntax:\n\n >>> iadd.i32\n \"\"\"\n return self.bind(ValueType.by_name(name))\n\n def fully_bound(self):\n # type: () -> Tuple[Instruction, Tuple[ValueType, ...]]\n \"\"\"\n Verify that all typevars have been bound, and return a\n `(inst, typevars)` pair.\n\n This version in `Instruction` itself allows non-polymorphic\n instructions to duck-type as `BoundInstruction`\\s.\n \"\"\"\n assert not self.is_polymorphic, self\n return (self, ())\n\n def __call__(self, *args):\n \"\"\"\n Create an `ast.Apply` AST node representing the application of this\n instruction to the arguments.\n \"\"\"\n from .ast import Apply\n return Apply(self, args)\n\n\nclass BoundInstruction(object):\n \"\"\"\n A polymorphic `Instruction` bound to concrete type variables.\n \"\"\"\n\n def __init__(self, inst, typevars):\n # type: (Instruction, Tuple[ValueType, ...]) -> None\n self.inst = inst\n self.typevars = typevars\n assert len(typevars) <= 1 + len(inst.other_typevars)\n\n def __str__(self):\n return '.'.join([self.inst.name, ] + list(map(str, self.typevars)))\n\n def bind(self, *args):\n # type: (*ValueType) -> BoundInstruction\n \"\"\"\n Bind additional typevars.\n \"\"\"\n return BoundInstruction(self.inst, self.typevars + args)\n\n def __getattr__(self, name):\n # type: (str) -> BoundInstruction\n \"\"\"\n Bind an additional typevar dot syntax:\n\n >>> uext.i32.i8\n \"\"\"\n return self.bind(ValueType.by_name(name))\n\n def fully_bound(self):\n # type: () -> Tuple[Instruction, Tuple[ValueType, ...]]\n \"\"\"\n Verify that all typevars have been bound, and return a\n `(inst, typevars)` pair.\n \"\"\"\n if len(self.typevars) < 1 + len(self.inst.other_typevars):\n unb = ', '.join(\n str(tv) for tv in\n self.inst.other_typevars[len(self.typevars) - 1:])\n raise AssertionError(\"Unbound typevar {} in {}\".format(unb, self))\n assert len(self.typevars) == 1 + len(self.inst.other_typevars)\n return (self.inst, self.typevars)\n\n def __call__(self, *args):\n \"\"\"\n Create an `ast.Apply` AST node representing the application of this\n instruction to the arguments.\n \"\"\"\n from .ast import Apply\n return Apply(self, args)\n\n\n# Defining target ISAs.\n\n\nclass TargetISA(object):\n \"\"\"\n A target instruction set architecture.\n\n The `TargetISA` class collects everything known about a target ISA.\n\n :param name: Short mnemonic name for the ISA.\n :param instruction_groups: List of `InstructionGroup` instances that are\n relevant for this ISA.\n \"\"\"\n\n def __init__(self, name, instruction_groups):\n self.name = name\n self.settings = None\n self.instruction_groups = instruction_groups\n self.cpumodes = list()\n\n def finish(self):\n \"\"\"\n Finish the definition of a target ISA after adding all CPU modes and\n settings.\n\n This computes some derived properties that are used in multilple\n places.\n\n :returns self:\n \"\"\"\n self._collect_encoding_recipes()\n self._collect_predicates()\n return self\n\n def _collect_encoding_recipes(self):\n \"\"\"\n Collect and number all encoding recipes in use.\n \"\"\"\n self.all_recipes = list()\n rcps = set()\n for cpumode in self.cpumodes:\n for enc in cpumode.encodings:\n recipe = enc.recipe\n if recipe not in rcps:\n recipe.number = len(rcps)\n rcps.add(recipe)\n self.all_recipes.append(recipe)\n\n def _collect_predicates(self):\n \"\"\"\n Collect and number all predicates in use.\n\n Sets `instp.number` for all used instruction predicates and places them\n in `self.all_instps` in numerical order.\n\n Ensures that all ISA predicates have an assigned bit number in\n `self.settings`.\n \"\"\"\n self.all_instps = list()\n instps = set()\n for cpumode in self.cpumodes:\n for enc in cpumode.encodings:\n instp = enc.instp\n if instp and instp not in instps:\n # assign predicate number starting from 0.\n instp.number = len(instps)\n instps.add(instp)\n self.all_instps.append(instp)\n\n # All referenced ISA predicates must have a number in\n # `self.settings`. This may cause some parent predicates to be\n # replicated here, which is OK.\n if enc.isap:\n self.settings.number_predicate(enc.isap)\n\n\nclass CPUMode(object):\n \"\"\"\n A CPU mode determines which instruction encodings are active.\n\n All instruction encodings are associated with exactly one `CPUMode`, and\n all CPU modes are associated with exactly one `TargetISA`.\n\n :param name: Short mnemonic name for the CPU mode.\n :param target: Associated `TargetISA`.\n \"\"\"\n\n def __init__(self, name, isa):\n self.name = name\n self.isa = isa\n self.encodings = []\n isa.cpumodes.append(self)\n\n def __str__(self):\n return self.name\n\n def enc(self, *args, **kwargs):\n \"\"\"\n Add a new encoding to this CPU mode.\n\n Arguments are the `Encoding constructor arguments, except for the first\n `CPUMode argument which is implied.\n \"\"\"\n self.encodings.append(Encoding(self, *args, **kwargs))\n\n\nclass EncRecipe(object):\n \"\"\"\n A recipe for encoding instructions with a given format.\n\n Many different instructions can be encoded by the same recipe, but they\n must all have the same instruction format.\n\n :param name: Short mnemonic name for this recipe.\n :param format: All encoded instructions must have this\n :py:class:`InstructionFormat`.\n \"\"\"\n\n def __init__(self, name, format, instp=None, isap=None):\n self.name = name\n self.format = format\n self.instp = instp\n self.isap = isap\n if instp:\n assert instp.predicate_context() == format\n\n def __str__(self):\n return self.name\n\n\nclass Encoding(object):\n \"\"\"\n Encoding for a concrete instruction.\n\n An `Encoding` object ties an instruction opcode with concrete type\n variables together with and encoding recipe and encoding bits.\n\n :param cpumode: The CPU mode where the encoding is active.\n :param inst: The :py:class:`Instruction` or :py:class:`BoundInstruction`\n being encoded.\n :param recipe: The :py:class:`EncRecipe` to use.\n :param encbits: Additional encoding bits to be interpreted by `recipe`.\n :param instp: Instruction predicate, or `None`.\n :param isap: ISA predicate, or `None`.\n \"\"\"\n\n def __init__(self, cpumode, inst, recipe, encbits, instp=None, isap=None):\n # type: (CPUMode, MaybeBoundInst, EncRecipe, int, AnyPredicate, AnyPredicate) -> None # noqa\n assert isinstance(cpumode, CPUMode)\n assert isinstance(recipe, EncRecipe)\n self.inst, self.typevars = inst.fully_bound()\n self.cpumode = cpumode\n assert self.inst.format == recipe.format, (\n \"Format {} must match recipe: {}\".format(\n self.inst.format, recipe.format))\n self.recipe = recipe\n self.encbits = encbits\n # Combine recipe predicates with the manually specified ones.\n self.instp = And.combine(recipe.instp, instp)\n self.isap = And.combine(recipe.isap, isap)\n\n def __str__(self):\n return '[{}#{:02x}]'.format(self.recipe, self.encbits)\n\n def ctrl_typevar(self):\n \"\"\"\n Get the controlling type variable for this encoding or `None`.\n \"\"\"\n if self.typevars:\n return self.typevars[0]\n else:\n return None\n\n\n# Import the fixed instruction formats now so they can be added to the\n# registry.\nimportlib.import_module('cretonne.formats')\n","sub_path":"lib/cretonne/meta/cretonne/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":41035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"346103276","text":"from pdb import set_trace as bb\nimport numpy as np\nimport torch\n\nfrom torch.autograd import Variable\n\nimport pyro\nfrom pyro.distributions import DiagNormal\nfrom pyro.distributions import Bernoulli, Categorical\nimport visdom\n\n# from pyro.infer.abstract_infer import LikelihoodWeighting, lw_expectation\n# from pyro.infer.importance_sampling import ImportanceSampling\nfrom pyro.infer.kl_qp import KL_QP\n\nimport torchvision.datasets as dset\nimport torchvision.transforms as transforms\nmnist = dset.MNIST(\n root='./data',\n train=True,\n transform=None,\n target_transform=None,\n download=True)\nprint('dataset loaded')\n\n\ntrain_loader = torch.utils.data.DataLoader(\n dset.MNIST('../data', train=True, download=True,\n transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=128, shuffle=True)\ntest_loader = torch.utils.data.DataLoader(\n dset.MNIST('../data', train=False, transform=transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.1307,), (0.3081,))\n ])),\n batch_size=128, shuffle=True)\n\n\ndef local_model(i, datum):\n beta = Variable(torch.ones(1, 10)) * 0.1\n cll = pyro.sample(\"class_of_datum_\" + str(i), Categorical(beta))\n mean_param = Variable(torch.zeros(1, 784), requires_grad=True)\n # do MLE for class means\n mu = pyro.param(\"mean_of_class_\" + str(cll[0]), mean_param)\n pyro.observe(\"obs_\" + str(i), Bernoulli(mu), datum)\n return cll\n\n\ndef local_guide(i, datum):\n alpha = torch.ones(1, 10) * 0.1\n beta_q = Variable(alpha, requires_grad=True)\n guide_params = pyro.param(\"class_posterior_\", beta_q)\n cll = pyro.sample(\"class_of_datum_\" + str(i), Bernoulli(guide_params))\n return cll\n\n\ndef inspect_posterior_samples(i):\n cll = local_guide(i, None)\n mean_param = Variable(torch.zeros(1, 784), requires_grad=True)\n # do MLE for class means\n mu = pyro.param(\"mean_of_class_\" + str(cll[0]), mean_param)\n dat = pyro.sample(\"obs_\" + str(i), Bernoulli(mu))\n return dat\n\n\n#grad_step = ELBo(local_model, local_guide, model_ML=true, optimizer=\"adam\")\noptim_fct = pyro.optim(torch.optim.Adam, {'lr': .0001})\n\ninference = KL_QP(local_model, local_guide, optim_fct)\n\nd0 = inspect_posterior_samples(0)\nd1 = inspect_posterior_samples(1)\n\nvis = visdom.Visdom()\n\nnr_epochs = 50\n# apply it to minibatches of data by hand:\n\nmnist_data = Variable(train_loader.dataset.train_data.float() / 255.)\nmnist_labels = Variable(train_loader.dataset.train_labels)\nmnist_size = mnist_data.size(0)\nbatch_size = 1 # 64\n\nall_batches = np.arange(0, mnist_size, batch_size)\n\nif all_batches[-1] != mnist_size:\n all_batches = list(all_batches) + [mnist_size]\n\nfor i in range(1000):\n\n epoch_loss = 0.\n for ix, batch_start in enumerate(all_batches[:-1]):\n batch_end = all_batches[ix + 1]\n\n #print('Batch '+str(ix))\n # get batch\n batch_data = mnist_data[batch_start:batch_end]\n bs_size = batch_data.size(0)\n batch_class_raw = mnist_labels[batch_start:batch_end]\n batch_class = torch.zeros(bs_size, 10) # maybe it needs a FloatTensor\n batch_class.scatter_(1, batch_class_raw.data.view(-1, 1), 1)\n batch_class = Variable(batch_class)\n\n inference.step(ix, batch_data)\n #\n # bb()\n\n sample, sample_mu = model_sample()\n vis.image(batch_data[0].view(28, 28).data.numpy())\n vis.image(sample[0].view(28, 28).data.numpy())\n vis.image(sample_mu[0].view(28, 28).data.numpy())\n print(\"epoch avg loss {}\".format(epoch_loss / float(mnist_size)))\n","sub_path":"examples/categorical_bmm.py","file_name":"categorical_bmm.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"269809823","text":"from CourseCollection import CourseCollection\nfrom UoftAPI import UofTAPI\n\n#TESTESTTEST NO TIME FOR UNIT TESTS.\t\t\t\nA = UofTAPI(\"\") #uhh when the api keys comin son..\n\n\nx = A.course_filter(code=\"SPA\", breadths=\"1\")\n#print(x[0]['code'])\n\nprint(len(x))\ncc = CourseCollection(x)\t\t\t\t\nprint(len(cc.course_list))\n\nfor course in cc.course_list:\n\tprint (course.code) #cool story it works.\n\t\n\t","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"347228640","text":"import asyncio\nimport json\nfrom pathlib import Path\n\nimport pytest\n\nfrom async_search_client.client import Client\n\nMASTER_KEY = \"masterKey\"\nBASE_URL = \"http://127.0.0.1:7700\"\nINDEX_UID = \"indexUID\"\nINDEX_UID2 = \"indexUID2\"\nINDEX_UID3 = \"indexUID3\"\nINDEX_UID4 = \"indexUID4\"\n\nINDEX_FIXTURE = [\n {\"uid\": INDEX_UID},\n {\"uid\": INDEX_UID2, \"primary_key\": \"book_id\"},\n]\n\nROOT_PATH = Path().absolute()\nSMALL_MOVIES_PATH = ROOT_PATH / \"datasets\" / \"small_movies.json\"\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef event_loop():\n loop = asyncio.get_event_loop()\n yield loop\n loop.close()\n\n\n@pytest.mark.asyncio\n@pytest.fixture(scope=\"session\")\nasync def test_client():\n async with Client(BASE_URL, MASTER_KEY) as client:\n yield client\n\n\n@pytest.mark.asyncio\n@pytest.fixture(autouse=True)\nasync def clear_indexes(test_client):\n \"\"\"\n Auto-clears the indexes after each test function run.\n Makes all the test functions independent.\n \"\"\"\n yield\n indexes = await test_client.get_indexes()\n if indexes:\n for index in indexes:\n await test_client.index(index.uid).delete()\n\n\n@pytest.fixture(scope=\"session\")\ndef master_key():\n return MASTER_KEY\n\n\n@pytest.fixture(scope=\"session\")\ndef base_url():\n return BASE_URL\n\n\n@pytest.fixture\ndef index_uid():\n return INDEX_UID\n\n\n@pytest.fixture\ndef index_uid2():\n return INDEX_UID2\n\n\n@pytest.fixture\ndef index_uid3():\n return INDEX_UID3\n\n\n@pytest.fixture\ndef index_uid4():\n return INDEX_UID4\n\n\n@pytest.mark.asyncio\n@pytest.fixture\nasync def indexes_sample(test_client):\n indexes = []\n for index_args in INDEX_FIXTURE:\n index = await test_client.create_index(**index_args)\n indexes.append(index)\n yield indexes\n\n\n@pytest.fixture(scope=\"session\")\ndef small_movies():\n \"\"\"\n Runs once per session. Provides the content of small_movies.json.\n \"\"\"\n\n with open(SMALL_MOVIES_PATH, \"r\") as movie_file:\n yield json.loads(movie_file.read())\n\n\n@pytest.fixture(scope=\"session\")\ndef small_movies_path():\n return SMALL_MOVIES_PATH\n\n\n@pytest.mark.asyncio\n@pytest.fixture\nasync def empty_index(test_client):\n async def index_maker(index_name=INDEX_UID):\n return await test_client.create_index(uid=index_name)\n\n return index_maker\n\n\n@pytest.mark.asyncio\n@pytest.fixture\nasync def index_with_documents(empty_index, small_movies, index_uid):\n async def index_maker(index_name=index_uid, documents=small_movies):\n index = await empty_index(index_name)\n response = await index.add_documents(documents)\n await index.wait_for_pending_update(response.update_id)\n return index\n\n return index_maker\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":2674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"157639608","text":"#!/usr/bin/env python\n\nimport csv\nimport argparse\nimport sys\nfrom uframe_async import *\n \ndef main(args):\n '''Validate and send one or more asynchronous UFrame requests, contained in \n a file. Print the request responses to STDOUT'''\n \n csv_writer = csv.writer(sys.stdout)\n cols = ['instrument',\n 'beginDT',\n 'endDT',\n 'status_code',\n 'reason',\n 'stream_beginDT',\n 'stream_endDT',\n 'valid',\n 'valid_time_interval',\n 'request_time',\n 'requestUUID',\n 'outputURL',\n 'request_url']\n csv_writer.writerow(cols)\n \n fid = open(args.request_csv, 'r')\n success = True\n for url in fid:\n \n if url.startswith('#'):\n continue\n \n #valid = validate_async_request(url.strip())\n #if not valid:\n # continue\n \n #sys.stderr.write('Sending request: {:s}\\n'.format(url.strip())) \n status = send_async_request(url.strip())\n if not status:\n# sys.stderr.write('Request failed: {:s}\\n'.format(url.strip()))\n success = False\n continue\n \n status_keys = status.keys()\n csv_writer.writerow([status[k] for k in cols if k in status_keys])\n #responses.append(status)\n\n fid.close()\n \n if not success:\n sys.stderr.write('One or more request failed\\n')\n \n return success\n \nif __name__ == '__main__':\n\n arg_parser = argparse.ArgumentParser(description=main.__doc__)\n arg_parser.add_argument('request_csv',\n help='Filename containing valid asynchronous UFrame request urls')\n\n parsed_args = arg_parser.parse_args()\n\n success = main(parsed_args)\n","sub_path":"send_async_requests_from_urlcsv.py","file_name":"send_async_requests_from_urlcsv.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"300932820","text":"import sys, os\nimport argparse\nfrom argparse import RawTextHelpFormatter\nimport glob\nimport shutil\nimport subprocess\nimport time\nfrom datetime import datetime\n\nsubcommand = ''\ngv_logname = ''\n\n'''\n Run with \"nohup python mapfile_generation_service.py &\"\n\n INTENTION: To be launched and remain in background, seek files from\n staging/mapfiles/mapfile_requests/\n where\n filenames are \"mapfile_request-\" and contain a single dataset fullpath\n NOTE: The \"dataset fullpath\" may be either a publication or warehouse version path.\n\n I was going to make this a flag:\n [--warehouse-persona] (act \"warehouse compliant\", check/update dataset status file)\n so that the service could perform where no \".status\" processing is expected. Presently,\n this (--warehouse-persona) is simply the default.\n'''\n\n# ======== convenience ========================\n\ndef ts(prefix):\n return prefix + datetime.now().strftime('%Y%m%d_%H%M%S')\n\ndef loadFileLines(afile):\n retlist = []\n if len(afile):\n with open(afile,\"r\") as f:\n retlist = f.read().split('\\n')\n retlist = [ _ for _ in retlist if _[:-1] ]\n return retlist\n\ndef logMessageInit(logtitle):\n global gv_logname\n gv_logname = f'{logtitle}-{ts(\"\")}'\n open(gv_logname, 'a').close()\n\ndef logMessage(mtype,message):\n outmessage = f'{ts(\"TS_\")}:{mtype}:{message}\\n'\n with open(gv_logname, 'a') as f:\n f.write(outmessage)\n\n# ======== warehouse ========================\n\ndef get_dataset_dirs_loc(anydir,loc): # loc in ['P','W']\n global gv_WH_root\n global gv_PUB_root\n\n '''\n Return tuple (ensemblepath,[version_paths])\n for the dataset indicated by \"anydir\" whose\n \"dataset_id\" part identifies a dataset, and\n whose root part is warehouse or publication.\n '''\n\n if not loc in ['P','W']:\n logMessage('ERROR',f'invalid dataset location indicator:{loc}')\n return '',[]\n if not (gv_WH_root in anydir or gv_PUB_root in anydir):\n logMessage('ERROR',f'invalid dataset source path - bad root:{anydir}')\n return '',[]\n if gv_WH_root in anydir:\n ds_part = anydir[1+len(gv_WH_root):]\n else:\n ds_part = anydir[1+len(gv_PUB_root):]\n\n tpath, leaf = os.path.split(ds_part)\n\n if len(leaf) == 0:\n tpath, leaf = os.path.split(tpath)\n if leaf[0] == 'v' and leaf[1] in '0123456789':\n ens_part = tpath\n elif (leaf[0:3] == 'ens' and leaf[3] in '123456789'):\n ens_part = ds_part\n else:\n logMessage('ERROR',f'invalid dataset source path:{anydir}')\n return '',[]\n\n if loc == 'P':\n a_enspath = os.path.join(gv_PUB_root, ens_part)\n else:\n a_enspath = os.path.join(gv_WH_root, ens_part)\n\n vpaths = []\n if os.path.exists(a_enspath):\n vpaths = [ f.path for f in os.scandir(a_enspath) if f.is_dir() ] # use f.path for the fullpath\n vpaths.sort()\n\n # print(f'DEBUG: get_dataset_dirs_loc: RETURNING: a_enspath = {a_enspath}, vpaths = {vpaths}',flush=True)\n return a_enspath, vpaths\n\n\ngv_WH_root = '/p/user_pub/e3sm/warehouse/E3SM'\ngv_PUB_root = '/p/user_pub/work/E3SM'\n\ndef get_statusfile_dir(apath):\n global gv_WH_root\n global gv_PUB_root\n\n ''' Take ANY inputpath.\n Reject if not begin with either warehouse_root or publication_root\n Reject if not a valid version dir or ensemble dir.\n Trim to ensemble directory, and trim to dataset_part ('E3SM/...').\n Determine if \".status\" exists under wh_root/dataset_part or pub_root/dataset_part.\n Reject if both or neither, else return full path (root/dataset_part)\n '''\n if not (gv_WH_root in apath or gv_PUB_root in apath):\n logMessage('ERROR',f'invalid dataset source path:{apath}')\n return ''\n if gv_WH_root in apath:\n ds_part = apath[1+len(gv_WH_root):]\n else:\n ds_part = apath[1+len(gv_PUB_root):]\n\n # logMessage('DEBUG',f'ds_part = {ds_part}')\n \n tpath, leaf = os.path.split(ds_part)\n if len(leaf) == 0:\n tpath, leaf = os.path.split(tpath)\n if leaf[0] == 'v' and leaf[1] in '123456789':\n tpath, leaf = os.path.split(tpath)\n if not (leaf[0:3] == 'ens' and leaf[3] in '123456789'):\n logMessage('ERROR',f'invalid dataset source path:{apath}')\n return ''\n ens_part = os.path.join(tpath,leaf)\n elif (leaf[0:3] == 'ens' and leaf[3] in '123456789'):\n ens_part = os.path.join(tpath,leaf)\n else:\n logMessage('ERROR',f'invalid dataset source path:{apath}')\n return ''\n wpath = os.path.join(gv_WH_root, ens_part, '.status') \n ppath = os.path.join(gv_PUB_root, ens_part, '.status') \n # logMessage('DEBUG',f'gv_WH_root = {gv_WH_root}')\n # logMessage('DEBUG',f'gv_PUB_root = {gv_PUB_root}')\n # logMessage('DEBUG',f'wpath = {wpath}')\n # logMessage('DEBUG',f'ppath = {ppath}')\n in_w = os.path.exists(wpath)\n in_p = os.path.exists(ppath)\n if not (in_w or in_p):\n logMessage('ERROR',f'status file not found in warehouse or publication:{apath}')\n return ''\n if in_w and in_p:\n logMessage('ERROR',f'status file found in both warehouse and publication:{apath}')\n return ''\n if in_w:\n return os.path.join(gv_WH_root, ens_part)\n return os.path.join(gv_PUB_root, ens_part)\n \n\ndef setStatus(statfile,parent,statspec):\n tsval = ts('')\n statline = f'STAT:{tsval}:{parent}:{statspec}\\n'\n with open(statfile, 'a') as f:\n f.write(statline)\n\n\ndef mapfile_validate(srcdir):\n ''' at this point, the srcdir should contain both datafiles (*.nc)\n and the .mapfile, so we can do a name-by-name comparison.\n MUST test for each srcdir datafile in mapfile listing.\n '''\n dataset_files = sorted(glob.glob(srcdir + '/*.nc'))\n mapfile_lines = sorted(loadFileLines(os.path.join(srcdir,'.mapfile')))\n\n if not len(dataset_files) == len(mapfile_lines):\n logMessage('ERROR',f'non-matching count of files and mapfile lines: {srcdir}')\n return False\n \n # MUST assume both lists sort identically\n pairlist = list(zip(dataset_files,mapfile_lines))\n for atup in pairlist:\n if not atup[0] in atup[1]: \n logMessage('ERROR',f'dataset file not listed in mapfile: {srcdir}')\n logMessage('ERROR',f'{atup[0]} not in {atup[1]}')\n return False\n\n return True\n\n\ninput_dir = '/p/user_pub/e3sm/staging/mapfiles/mapfile_requests'\nexput_dir = '/p/user_pub/e3sm/staging/mapfiles/mapfiles_output'\nini_path = '/p/user_pub/e3sm/staging/ini_std/'\n# calls esgmapfile make, moves finished mapfile to pub_path/.../ens#/v#/.mapfile\nesgmapfile_make = '/p/user_pub/e3sm/bartoletti1/Pub_Work/2_Mapwork/esgmapfile_make.sh'\n\nsearchpath = os.path.join(input_dir,'mapfile_request.*')\n\nwarehouse_persona = True\npwd = os.getcwd()\nreq_done = os.path.join(pwd,'requests_processed')\n\ndef main():\n\n # assess_args()\n logMessageInit('runlog_mapfile_gen_loop')\n\n while True:\n req_files = glob.glob(input_dir + '/*')\n req_files.sort(key=os.path.getmtime)\n if not len(req_files):\n # print(f'DEBUG: sleeping 60')\n time.sleep(60)\n continue\n\n\n\n request_file = req_files[0] # or req_files[-1], ensure oldest is selected\n request_path = loadFileLines(request_file)\n request_path = request_path[0]\n\n if warehouse_persona:\n stat_path = get_statusfile_dir(request_path)\n # logMessage('DEBUG',f'stat_path: {stat_path}')\n if not len(stat_path):\n shutil.move(f'{request_file}',f'{req_done}')\n time.sleep(5)\n continue # error message already given\n\n statfile = os.path.join(stat_path,'.status')\n\n logMessage('INFO',f'MAPGENLOOP:Launching Request Path:{request_path}')\n tm_start = time.time()\n # CALL the Mapfile Maker\n # WAIT here until esgmapfile_make returns\n if warehouse_persona:\n setStatus(statfile,'WAREHOUSE',f'MAPFILE_GEN:Engaged')\n retcode = os.system(f'{esgmapfile_make} {request_path}')\n tm_final = time.time()\n ET = tm_final - tm_start\n opath, basep = os.path.split(request_file)\n testpath = os.path.join(req_done,basep)\n if os.path.exists(testpath):\n os.remove(testpath)\n shutil.move(f'{request_file}',f'{req_done}')\n logMessage('INFO',f'MAPGENLOOP:Returned:ET={ET}')\n \n time.sleep(5)\n # continue\n\n # based upon return status\n if retcode:\n # write logfile entry, then\n logMessage('STATUS',f'MAPFILE_GEN:Fail:ret_code={retcode}')\n if warehouse_persona:\n setStatus(statfile,'WAREHOUSE',f'MAPFILE_GEN:Fail:ret_code={retcode}')\n continue\n if not mapfile_validate(request_path):\n # write logfile entry, then\n logMessage('STATUS',f'MAPFILE_GEN:Fail:Bad_mapfile')\n if warehouse_persona:\n setStatus(statfile,'WAREHOUSE',f'MAPFILE_GEN:Fail:Bad_mapfile')\n continue\n # write logfile entry, then\n logMessage('STATUS',f'MAPFILE_GEN:Pass')\n if warehouse_persona:\n setStatus(statfile,'WAREHOUSE','MAPFILE_GEN:Pass')\n\n \nif __name__ == \"__main__\":\n sys.exit(main())\n\n\n\n","sub_path":"scripts/bart_code/mapfile_generation_service.py","file_name":"mapfile_generation_service.py","file_ext":"py","file_size_in_byte":9369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"581231625","text":"#!/usr/bin/env python\n# coding=utf-8\n\nimport tensorflow as tf\nimport sys\nimport os\n\nexport_dir = sys.argv[1]\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"5\"\n\nwith tf.Session() as sess:\n meta_graph_def = tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], export_dir)\n signature = meta_graph_def.signature_def\n signature_key = tf.saved_model.signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY\n \n input_name = signature[signature_key].inputs['inputs'].name\n output_name = signature[signature_key].outputs['prob'].name\n #print(input_name, output_name)\n #print(sess.graph.get_tensor_by_name(input_name))\n #ctcvr_preds = sess.graph.get_tensor_by_name(\"mul_2:0\")\n #ctr_preds = sess.graph.get_tensor_by_name(\"Sigmoid:0\")\n #input_x = sess.graph.get_tensor_by_name(input_name)\n #predict_y = sess.graph.get_tensor_by_name(output_name)\n \n #print(tf.concat([ctr_preds,ctcvr_preds], axis=1))\n for node in sess.graph_def.node:\n print(node.name)\n #print(signature[signature_key].inputs, signature[signature_key].outputs)\n #print(input_x, predict_y)\n","sub_path":"mmoe_20200801/check_param.py","file_name":"check_param.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"4543509","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom ..items import LiepinwangItem\n\nclass LiepinSpider(CrawlSpider):\n name = 'liepin'\n allowed_domains = ['liepin.com']\n start_urls = ['https://www.liepin.com/zhaopin/?key=python']\n# https://www.liepin.com/job/1925659053.shtml\n rules = (\n Rule(LinkExtractor(allow=r'/zhaopin/.+curPage=\\d+', restrict_xpaths=[\"//div[@class='pagerbar']//a\"]), follow=True),\n Rule(LinkExtractor(allow=r'https.+/job/\\d+\\.shtml.*', restrict_xpaths=[\"//ul[@class='sojob-list']//a\"]), callback='parse_job', follow=False),\n )\n\n def parse_job(self, response):\n # title = response.xpath(\"//div[@class='title-info']/h1/text()\").get()\n # company = response.xpath(\"//div[@class='title-info']/h3/a/text()\").get()\n # pay = response.xpath(\"//div[@class='job-title-left']/p/text()\").get().strip()\n # city = response.xpath(\"//div[@class='job-title-left']/p[@class='basic-infor']//a/text()\").get()\n # edu = response.xpath(\"//div[@class='job-qualifications']/span[1]/text()\").get()\n # experience = response.xpath(\"//div[@class='job-qualifications']/span[2]/text()\").get()\n # desc_list = response.xpath(\"//div[@class='content content-word']/text()\").getall()\n # desc = ''.join(desc_list).strip()\n\n title = response.css(\".title-info h1::text\").get()\n company = response.css(\".title-info h3 a::text\").get()\n salary = response.css(\".job-title-left p::text\").get().strip() \n city = response.css(\".basic-infor a::text\").get()\n edu = response.css(\".job-qualifications span:nth-child(1)::text\").get()\n experience = response.css(\".job-qualifications span:nth-child(2)::text\").get()\n desc_list = response.css(\".content-word::text\").getall()\n desc = \"\".join(desc_list).strip()\n item = LiepinwangItem(title=title,company=company,salary=salary,city=city,\n edu=edu,experience=experience,desc=desc)\n yield item\n","sub_path":"猎聘网无限制爬取/liepinwang/liepinwang/spiders/liepin.py","file_name":"liepin.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"626412298","text":"def merge(ar1, ar2):\n i = j = 0\n merged = []\n while i < len(ar1) and j < len(ar2):\n if ar1[i] < ar2[j]:\n merged.append(ar1[i])\n i += 1\n else:\n merged.append(ar2[j])\n j += 1\n\n if i == len(ar1):\n merged += ar2[j:]\n\n elif j == len(ar2):\n merged += ar1[i:]\n return merged\n\n\ndef merge_sort(arr):\n if len(arr) <= 1:\n return arr[:]\n return _merge_sort(arr)\n\n\ndef _merge_sort(arr):\n if len(arr) > 1:\n middle = len(arr) // 2\n left = arr[:middle]\n right = arr[middle:]\n return merge(_merge_sort(left), _merge_sort(right))\n else:\n return arr\n","sub_path":"algorithms/sorting/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"141330490","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @file scripts/kconfig/tools.py\n#\n# @author Hiroyuki Chishiro\n#\n\"\"\"\nTool for kconfig.\n\"\"\"\n\nimport re\nimport sys\nimport smtplib\n\nfrom email.mime.text import MIMEText\n\nclass ConfigInfo:\n \"\"\"\n ConfigInfo class has config information.\n \"\"\"\n def __init__(self):\n self.__menu = \"\"\n self.__type = \"\"\n self.__configure = []\n self.__num = 0\n\n def get_menu(self):\n \"get menu\"\n return self.__menu\n def get_type(self):\n \"get type\"\n return self.__type\n def get_configure(self):\n \"get configure\"\n return self.__configure\n def get_num(self):\n \"get num\"\n return self.__num\n def set_menu(self, menu):\n \"set menu\"\n self.__menu = menu\n def set_type(self, _type):\n \"set type\"\n self.__type = _type\n def set_configure(self, configure):\n \"set configure\"\n self.__configure = configure\n def set_num(self, num):\n \"set num\"\n self.__num = num\n\n\nCONFIGURES = {}\nCONFIGURE_DEFS = {}\nTITLES = {}\nDEFS = \"CFLAGS += \"\nCFILES = \"SRCS += \"\nAFILES = \"ASRCS += \"\nVPATHS = \"vpath %.cpp\"\nDEPENDENCIES = {}\nCONFLICTS = {}\nTYPE = \"none\"\n\nCONFIGURE_LINE = r\"^(.*)=(.)\"\nRE_CONFIGURE_LINE = re.compile(CONFIGURE_LINE)\n\nCOMMENT_LINE = r\"^\\#\"\nRE_COMMENT_LINE = re.compile(COMMENT_LINE)\n\nALGO_LINE = r\"\\s+alname\\s+(.*)\"\nRE_ALGO_LINE = re.compile(ALGO_LINE)\n\nMACHINE_LINE = r\"\\s+mname\\s+(.*)\"\nRE_MACHINE_LINE = re.compile(MACHINE_LINE)\n\nOUTPUT_LINE = r\"\\s+oname\\s+(.*)\"\nRE_OUTPUT_LINE = re.compile(OUTPUT_LINE)\n\nKCONFIG_LINE = r\"\\s+config\\s+(.*)\"\nRE_KCONFIG_LINE = re.compile(KCONFIG_LINE)\n\nARCH_LINE = r\"\\s+arname\\s+(.*)\"\nRE_ARCH_LINE = re.compile(ARCH_LINE)\n\nARCH_LINE = r\"\\s+aname\\s+(.*)\"\nRE_ARCH_LINE = re.compile(ARCH_LINE)\n\nCC_LINE = r\"\\s+ccname\\s+(.*)\"\nRE_CC_LINE = re.compile(CC_LINE)\n\nSKIP_LINE = r\"^\\#|^\\n|^menu|^\\s+title|^\\s+default\"\nRE_SKIP_LINE = re.compile(SKIP_LINE)\n\nDEFS_LINE = r\"^\\s+defs\\s+(.*)\"\nRE_DEFS_LINE = re.compile(DEFS_LINE)\n\nCFILES_LINE = r\"^\\s+cfiles\\s+(.*)\"\nRE_CFILES_LINE = re.compile(CFILES_LINE)\n\nAFILES_LINE = r\"^\\s+afiles\\s+(.*)\"\nRE_AFILES_LINE = re.compile(AFILES_LINE)\n\nVPATHS_LINE = r\"^\\s+vpaths\\s+(.*)\"\nRE_VPATHS_LINE = re.compile(VPATHS_LINE)\n\nTYPE_LINE = r\"^\\s+type\\s+(.*)\"\nRE_TYPE_LINE = re.compile(TYPE_LINE)\n\nMENU_LINE = r\"^menu\\s+(.*)\"\nRE_MENU_LINE = re.compile(MENU_LINE)\n\nENDMENU_LINE = r\"^endmenu\\s+(.*)\"\nRE_ENDMENU_LINE = re.compile(ENDMENU_LINE)\n\nDEPENDENCIES_LINE = r\"^\\s+(depends\\s+)\"\nRE_DEPENDENCIES_LINE = re.compile(DEPENDENCIES_LINE)\n\nCONFLICTS_LINE = r\"^\\s+(conflicts\\s+)\"\nRE_CONFLICTS_LINE = re.compile(CONFLICTS_LINE)\n\nTITLE_LINE = r\"^\\s+(title\\s+)\"\nRE_TITLE_LINE = re.compile(TITLE_LINE)\n\nSPLIT_LINE = r\"[ \\t]\"\nRE_SPLIT_LINE = re.compile(SPLIT_LINE)\n\nINIT_SKIP_LINE = r\"^\\#|^\\n|^\\s+title|^\\s+type|^\\s+cfiles|^\\s+afiles|^\\s+defs\"\nRE_INIT_SKIP_LINE = re.compile(INIT_SKIP_LINE)\n\nDEFAULT_LINE = r\"^\\s+default\\s+(.*)\"\nRE_DEFAULT_LINE = re.compile(DEFAULT_LINE)\n\nCONFIG_HEADER = \"#\\n\" \\\n + \"# Mcube Kernel\\n\" \\\n + \"#\\n\" \\\n + \"# Hiroyuki Chishiro\\n\" \\\n + \"#\\n\" \\\n + \"\\n\" \\\n + \"#\\n\" \\\n + \"# Mcube Kernel Configuration File\\n\" \\\n + \"#\\n\"\n\ndef scan_configure(filename):\n \"scan configure\"\n fin = open(filename, \"r\")\n for line in fin:\n# print(\"line = %s\" % (line))\n if line.strip() == \"\":\n continue\n if RE_COMMENT_LINE.match(line):\n continue\n configure_list = RE_CONFIGURE_LINE.findall(line)\n# print(list)\n key = configure_list[0][0]\n value = configure_list[0][1]\n CONFIGURES[key] = value\n# print(key, value)\n fin.close()\n\n\ndef scan_algo_name(filename):\n \"scan algorithm name\"\n fin = open(filename, \"r\")\n this_algo = False\n algo_name = \"rmwp\"\n for line in fin:\n if line.strip() == \"\":\n continue\n if RE_COMMENT_LINE.match(line):\n continue\n index = line.find(\"menu\")\n if index == 0:\n this_algo = False\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n if CONFIGURES[kconfig_list[0]] == \"y\":\n this_algo = True\n elif this_algo:\n algo_list = RE_ALGO_LINE.findall(line)\n if algo_list:\n algo_name = algo_list[0]\n break\n fin.close()\n return algo_name\n\n\ndef scan_arch_name(filename):\n \"scan architecture name\"\n fin = open(filename, \"r\")\n this_arch = False\n arch_name = \"axis\"\n for line in fin:\n if line.strip() == \"\":\n continue\n if RE_COMMENT_LINE.match(line):\n continue\n index = line.find(\"menu\")\n if index == 0:\n this_arch = False\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n if CONFIGURES[kconfig_list[0]] == \"y\":\n this_arch = True\n elif this_arch:\n arch_list = RE_ARCH_LINE.findall(line)\n if arch_list:\n arch_name = arch_list[0]\n break\n fin.close()\n# print(arch_name)\n return arch_name\n\ndef scan_compiler_name(filename):\n \"scan compiler name\"\n fin = open(filename, \"r\")\n this_cc = False\n cc_name = \"clang\"\n for line in fin:\n if line.strip() == \"\":\n continue\n if RE_COMMENT_LINE.match(line):\n continue\n index = line.find(\"menu\")\n# print(line)\n if index == 0:\n this_cc = False\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n if CONFIGURES[kconfig_list[0]] == \"y\":\n this_cc = True\n elif this_cc:\n cc_list = RE_CC_LINE.findall(line)\n if cc_list:\n cc_name = cc_list[0]\n break\n fin.close()\n# print(cc_name)\n return cc_name\n\ndef scan_machine_name(filename):\n \"scan machine name\"\n fin = open(filename, \"r\")\n this_machine = False\n machine_name = \"none\"\n for line in fin:\n if line.strip() == \"\":\n continue\n if RE_COMMENT_LINE.match(line):\n continue\n index = line.find(\"menu\")\n if index == 0:\n this_machine = False\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n if CONFIGURES[kconfig_list[0]] == \"y\":\n this_machine = True\n elif this_machine:\n machine_list = RE_MACHINE_LINE.findall(line)\n if machine_list:\n machine_name = machine_list[0]\n break\n fin.close()\n return machine_name\n\n\ndef scan_output_name(filename):\n \"scan output name\"\n fin = open(filename, \"r\")\n this_output = False\n output_name = \"none\"\n for line in fin:\n if line.strip() == \"\":\n continue\n if RE_COMMENT_LINE.match(line):\n continue\n index = line.find(\"menu\")\n if index == 0:\n this_output = False\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n if CONFIGURES[kconfig_list[0]] == \"y\":\n this_output = True\n elif this_output:\n output_list = RE_OUTPUT_LINE.findall(line)\n if output_list:\n output_name = output_list[0]\n break\n fin.close()\n return output_name\n\n\n\ndef scan_kconfig(filename):\n \"scan Kconfig\"\n global DEFS, CFILES, AFILES, TYPE, VPATHS, CONFIGURE_DEFS\n current_config_val = \"n\"\n# print(\"scan_configs()\")\n fin = open(filename, \"r\")\n for line in fin:\n if RE_SKIP_LINE.match(line):\n continue\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n# print(line)\n# print(kconfig_list)\n# print(CONFIGURES)\n if kconfig_list:\n current_config_val = CONFIGURES[kconfig_list[0]]\n elif current_config_val == \"y\":\n defs_list = RE_DEFS_LINE.findall(line)\n if defs_list:\n DEFS += \" \\\\\\n\" + defs_list[0]\n# print(\"DEFS = %s\" % DEFS)\n for val in defs_list:\n# print(\"val = %s \" % val)\n index = val.find(\"-D\")\n if index != 0:\n sys.exit(\"Error: invalid defs \" + val)\n# print(val[2:len(val)])\n CONFIGURE_DEFS[val[2:len(val)]] = \"y\"\n\n\n cfiles_list = RE_CFILES_LINE.findall(line)\n if cfiles_list:\n CFILES += \" \\\\\\n\" + cfiles_list[0]\n# print(\"CFILES = %s\" % cfiles_list)\n\n afiles_list = RE_AFILES_LINE.findall(line)\n if afiles_list:\n AFILES += \" \\\\\\n\" + afiles_list[0]\n# print(\"AFILES = %s\" % afiles_list)\n\n type_list = RE_TYPE_LINE.findall(line)\n if type_list:\n TYPE += \" \\\\\\n\" + type_list[0]\n # print(\"type = %s\" % type_list)\n vpaths_list = RE_VPATHS_LINE.findall(line)\n if vpaths_list:\n VPATHS += \" \\\\\\n\" + vpaths_list[0]\n# print(\"VPATHS = %s\" % vpaths_list)\n fin.close()\n\n\ndef check_exclusives(filename):\n \"check exclusives\"\n ret = True\n ex_menu = False\n ynum = 0\n current_menu = \"\"\n fin = open(filename, \"r\")\n for line in fin:\n if RE_COMMENT_LINE.match(line):\n continue\n# print(line)\n menu_list = RE_MENU_LINE.findall(line)\n if menu_list:\n ex_menu = True\n# print(\"list = %s\" % list)\n current_menu = menu_list[0]\n ynum = 0\n\n type_list = RE_TYPE_LINE.findall(line)\n if type_list:\n# print(\"type_list = %s\" % type_list)\n if type_list[0] != \"exclusive\":\n ex_menu = False\n\n endmenu_list = RE_ENDMENU_LINE.findall(line)\n if endmenu_list:\n ex_menu = False\n\n if ex_menu:\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n if CONFIGURES[kconfig_list[0]] == \"y\":\n ynum += 1\n if ynum > 1:\n print(\"Exclusive Error: %s\" % current_menu)\n ex_menu = False\n ret = False\n fin.close()\n return ret\n\n\ndef scan_dependencies(filename):\n \"scan dependencies\"\n global DEPENDENCIES, CONFLICTS, TITLES\n fin = open(filename, \"r\")\n current_config = \"\"\n for line in fin:\n if RE_COMMENT_LINE.match(line):\n continue\n\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n# print(list)\n if kconfig_list:\n current_config = kconfig_list[0]\n# print(\"current_config = %s\" % current_config)\n continue\n\n# print(line)\n dependencies_list = RE_DEPENDENCIES_LINE.findall(line)\n if dependencies_list:\n dep_str = \"depends\"\n index = line.find(dep_str)\n val = line[index+len(dep_str):len(line)]\n val = val.rstrip(\"\\n\").strip()\n val = RE_SPLIT_LINE.split(val)\n # print(val)\n # print(current_config)\n if current_config in DEPENDENCIES:\n DEPENDENCIES[current_config] += val\n else:\n DEPENDENCIES[current_config] = val\n\n conflicts_list = RE_CONFLICTS_LINE.findall(line)\n if conflicts_list:\n conf_str = \"conflicts\"\n index = line.find(conf_str)\n val = line[index+len(conf_str):len(line)]\n val = val.rstrip(\"\\n\").strip()\n val = RE_SPLIT_LINE.split(val)\n# print(\"val = \", val)\n if current_config in CONFLICTS:\n CONFLICTS[current_config] += val\n else:\n CONFLICTS[current_config] = val\n\n title_list = RE_TITLE_LINE.findall(line)\n# print(title_list)\n if title_list:\n title_str = \"title\"\n# print(line)\n index = line.find(title_str)\n val = line[index+len(title_str):len(line)]\n val = val.rstrip(\"\\n\").strip()\n val = RE_SPLIT_LINE.split(val)\n# print(val)\n TITLES[current_config] = val\n fin.close()\n\ndef check_conflicts(key):\n \"check conflicts\"\n no_error = True\n# print(CONFLICTS)\n if key in CONFLICTS:\n# print(\"key = \", key)\n for con in CONFLICTS[key]:\n# print(con)\n if con in CONFIGURE_DEFS and CONFIGURE_DEFS[con] == \"y\":\n if no_error:\n no_error = False\n print(\"Conflict Error\", key, \"conflicts with\", con)\n return no_error\n\n\ndef check_dependencies(key):\n \"check dependencies\"\n no_error = True\n# print(\"key = %s\" % key)\n# print(DEPENDENCIES)\n if key in DEPENDENCIES:\n for dep in DEPENDENCIES[key]:\n # print(\"dep = %s\" % dep)\n # print(\"CONFIGURE_DEFS = %s\" % CONFIGURE_DEFS)\n if not dep in CONFIGURE_DEFS:\n if no_error:\n no_error = False\n print(\"Dependency Error:\", key, \"depends on\", dep)\n return no_error\n\ndef check_conflicts_and_dependencies():\n \"check conflicts and dependencies\"\n no_error = True\n# print(\"check_conflicts_and_dependencies()\")\n for key, value in CONFIGURE_DEFS.items():\n# print(key, value)\n if value == \"y\":\n if not check_conflicts(key):\n no_error = False\n if not check_dependencies(key):\n no_error = False\n\n return no_error\n\n\ndef save_configure(filename):\n \"save configure\"\n fin = open(filename, \"r\")\n configure_file = open(\"configure\", \"w\")\n configure_file.write(CONFIG_HEADER)\n current_configure = \"\"\n for line in fin:\n if RE_INIT_SKIP_LINE.match(line):\n continue\n menu_list = RE_MENU_LINE.findall(line)\n if menu_list:\n configure_file.write(\"\\n# \" + menu_list[0] + \"\\n\")\n\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n current_configure = kconfig_list[0]\n configure_file.write(current_configure)\n\n default_list = RE_DEFAULT_LINE.findall(line)\n if default_list:\n configure_file.write(\"=\" + default_list[0] + \"\\n\")\n\n configure_file.close()\n fin.close()\n\ndef scan_all_configures(filename):\n \"scan all configures\"\n cinfo = []\n fin = open(filename, \"r\")\n for line in fin:\n if RE_COMMENT_LINE.match(line):\n continue\n menu_list = RE_MENU_LINE.findall(line)\n if menu_list:\n# print(menu_list)\n cinfo.append(ConfigInfo())\n cinfo[len(cinfo)-1].set_menu(menu_list[0])\n\n type_list = RE_TYPE_LINE.findall(line)\n# print(line)\n# print(type_list)\n if type_list:\n# print(type_list)\n cinfo[len(cinfo)-1].set_type(type_list[0])\n\n kconfig_list = RE_KCONFIG_LINE.findall(line)\n if kconfig_list:\n# print(kconfig_list)\n cinfo[len(cinfo)-1].get_configure().append(kconfig_list[0])\n\n fin.close()\n\n num = 1\n for cif in cinfo:\n if cif.get_type() == \"exclusive\":\n cif.set_num(len(cif.get_configure()))\n elif cif.get_type() == \"none\":\n cif.set_num(pow(2, len(cif.get_configure())))\n else:\n sys.exit(\"Error: Unknown type \" + cif.get_type() + \"\\n\")\n print(cif.get_num())\n num *= cif.get_num()\n\n return cinfo, num\n\ndef write_menu(filename, cinfo, index):\n \"write menu\"\n# print(\"index = \", index)\n filename.write(\"\\n# \" + cinfo.get_menu() + \"\\n\")\n if cinfo.get_type() == \"exclusive\":\n for i in range(0, len(cinfo.get_configure())):\n if i == index:\n filename.write(cinfo.get_configure()[i] + \"=y\\n\")\n else:\n filename.write(cinfo.get_configure()[i] + \"=n\\n\")\n elif cinfo.get_type() == \"none\":\n# print(\"index = \", index)\n for i in range(0, len(cinfo.get_configure())):\n if bin((0b1 << i) & index) == bin(0b1 << i):\n filename.write(cinfo.get_configure()[i] + \"=y\\n\")\n else:\n filename.write(cinfo.get_configure()[i] + \"=n\\n\")\n else:\n sys.exit(\"Error: Unknown type \" + cinfo.get_type() + \"\\n\")\n\ndef write_configure(filename, cinfo, vals):\n \"write configure\"\n for i, val in enumerate(vals):\n write_menu(filename, cinfo[i], val)\n\ndef sendmail(to_address, from_address, subject, message):\n \"send e-mail\"\n msg = MIMEText(message)\n msg[\"Subject\"] = subject\n msg[\"From\"] = from_address\n msg[\"To\"] = to_address\n\n smtp = smtplib.SMTP()\n smtp.connect()\n smtp.sendmail(from_address, to_address, msg.as_string())\n smtp.close()\n\ndef check_argc(argc, argv, correct_argc):\n \"check argc\"\n if argc != correct_argc:\n print(\"Usage: %s filename eb[el]\" % argv[0])\n quit()\n","sub_path":"scripts/kconfig/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":15148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"578842915","text":"def circulo(r):\r\n r = (3.14 * (r**2))\r\n return r\r\n\r\ndef triangulo(b,h):\r\n r = ((b*h)/2)\r\n return r\r\n\r\ndef quadrado(l,l2):\r\n r = (l*l2)\r\n return r\r\n\r\ndef trapezio(b2,b3,a):\r\n r = (((b2+b3) * a)/2)\r\n return r\r\n\r\ndef retangulo(l3,al):\r\n r = (l3*al)\r\n return r\r\n\r\nx=input(\"qual fitura geometrica desejas calcular:\")\r\n\r\nif(x==\"circulo\"):\r\n r = int(input())\r\n print(circulo(r))\r\n\r\nelif(x==\"triangulo\"):\r\n b = int(input())\r\n h = int(input())\r\n print(triangulo(b,h))\r\n\r\nelif(x==\"quadrado\"):\r\n l = int(input())\r\n l2 = int(input())\r\n print(quadrado(l,l2))\r\n\r\nelif(x==\"trapezio\"):\r\n b2 = int(input())\r\n b3 = int(input())\r\n a = int(input())\r\n print(trapezio(b2,b3,a))\r\n\r\nelif(x==\"retangulo\"):\r\n l3 = int(input())\r\n al = int(input())\r\n print(retangulo(l3,al))\r\nelse:\r\n (\"entrada invalida!,entradas valdas sao circulo,triangulo,quadrado,trapezio e retangulo\")","sub_path":"LISTAS/3aL/RESOLVIDAS/Q_8.py","file_name":"Q_8.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"407991516","text":"import torch\nfrom math import exp\nfrom transformers import *\nimport torch.nn.functional as F\nimport json\nfrom tqdm import tqdm\nimport sys\n\n\n\n\nclass TransformersLMEngine():\n pretrained_weights = None\n device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n #device = 'cpu'\n def __init__(self, tokenizer, model, text=None, **kwargs):\n r\"\"\"\n abstract constructor for TransformersLMEngine\n\n :param text: the sentence which will be corrected or used to generate next sentence\n \"\"\"\n self.tokenizer = tokenizer\n self.model = model\n self.model.eval() # deactivate DropOut modules to have reproducible results during evaluation\n self.model.to(self.device)\n self.input_text = text\n self._clear_results()\n self.alpha = kwargs.get('alpha', 1)\n\n @property\n def input_text(self):\n return self.__input_text\n\n @input_text.setter\n def input_text(self, val):\n r\"\"\"\n Calculates input_ids, indexed tokens and clears previous calculations.\n\n :param val: set input_text to val\n :return: None\n \"\"\"\n if val:\n self.__input_text = val\n self.indexed_tokens = self.tokenizer.encode(self.input_text)\n self.input_ids = torch.tensor([self.indexed_tokens])\n self.input_ids = self.input_ids.to(self.device)\n self.input_size = len(self.input_ids[0])\n self._clear_results()\n\n def _clear_results(self):\n r\"\"\" Clear results returned\n\n :return: None\n \"\"\"\n self.sentence_data = []\n\n def get_sentence_probability(self, text=None):\n r\"\"\" Get json with probabilities for each token of a sentence\n The result is also stored in self.sentence_data attribute.\n\n :param text: the text used by LanguageModel\n :return: json representing array of tuples:\n name - name of the token\n probability - probability from LM of the given token\n \"\"\"\n self.input_text = text\n self.sentence_data = []\n with torch.no_grad():\n self._compute_outputs()\n for ix in range(self.input_size):\n token_obj = self._get_token_probability(ix)\n self.sentence_data.append(token_obj)\n return json.dumps(self.sentence_data)\n\n def _compute_outputs(self, *args, **kwargs):\n r\"\"\" Compute outputs for LM, needs to be overwritten for gpt2 models\"\"\"\n pass\n # self.outputs = self.model(input_ids=self.input_ids, masked_lm_labels=self.input_ids)\n # self.logits = self.outputs[0][0]\n # self.probs = torch.softmax(self.logits, 1)\n\n def _get_token_probability(self, ix):\n token_id = self.input_ids[0][ix]\n token_obj = {}\n token_obj[\"name\"] = self.tokenizer.decode(token_id.item())\n token_obj[\"probability\"] = self.probs[ix - 1][token_id].item()\n return token_obj\n\n def get_sentence_oddballness(self, text=None):\n r\"\"\" Get json with probabilities and oddballness for each token of a sentence\n The result is also stored in self.sentence_data attribute.\n\n :param text: the text used by LanguageModel\n :return: json representing array of tuples:\n name - name of the token\n probability - probability from LM of the given token\n oddballness - F.Graliński oddballness metric calculeted on probabilities from LM\n \"\"\"\n self.input_text = text\n self.sentence_data = []\n with torch.no_grad():\n self._compute_outputs()\n for ix in range(self.input_size):\n token_obj = self._get_token_probability(ix)\n token_obj[\"oddballness\"] = self._get_oddballness_proba(token_obj[\"probability\"], self.probs[ix - 1], alpha=self.alpha).item()\n\n self.sentence_data.append(token_obj)\n return json.dumps(self.sentence_data)\n\n\n\n @staticmethod\n def _get_oddballness_proba(chosen_token_proba, tokens_proba, alpha=1):\n r\"\"\" Calculate value of oddballness for token according to F.Graliński's oddballness metric\n\n :param chosen_token_proba: probability of the token we'r calculating oddballness for\n :param tokens_proba: probability of all the other possible tokens\n :param alpha: exponent used in the oddballness function family\n :return: oddballness value\n \"\"\"\n oddballness = torch.sum(F.relu(tokens_proba - chosen_token_proba) ** alpha)\n #oddballness = (1 - (chosen_token_proba * torch.log2(torch.tensor(chosen_token_proba))) / torch.sum(tokens_proba * torch.log2(tokens_proba))) ** alpha\n return oddballness\n\n def get_text_correction_proposal(self, input_text):\n r\"\"\" Return tokens that are likely to substitute each token on the entry.\n\n :param input_text:\n :return:\n \"\"\"\n arr = []\n with torch.no_grad():\n for text_chunk in tqdm(self._string_to_chunks(input_text)):\n self.input_text = text_chunk # set the text currently worked on (no bigger than 1024)\n self._compute_outputs()\n for ix in range(self.input_size):\n token_obj = {}\n token_id = self.input_ids[0][ix]\n token_prob = self.probs[ix - 1][token_id]\n\n probs = torch.softmax(self.logits, 1)\n\n sorted_probs, sorted_indices = torch.sort(probs[ix - 1], descending=True)\n\n _, correction_indices = self._get_token_correction_proposal(ix)\n\n token_obj[\"name\"] = self.tokenizer.decode(token_id.item())\n token_obj[\"probability\"] = token_prob.item()\n token_obj[\"corrections\"] = [self.tokenizer.decode(token_id.item()) for token_id in correction_indices]\n token_obj[\"oddballness\"] = self._get_oddballness_proba(token_prob, probs[ix-1]).item()\n\n arr.append(token_obj)\n arr.pop()\n arr.pop(0)\n self._trim_bpe_space_artifact(arr)\n self.token_array = arr\n return arr\n\n @staticmethod\n def _string_to_chunks(text, **kwargs):\n r\"\"\" Return same text in chunks of at most text_limit characters\n\n :param text: String that will be splited into chunks\n :param text_limit: (optional) changes text_limit. by default set to 1024\n :return: lines that contain no more than text_limit characters total.\n \"\"\"\n text_limit = kwargs.get('text_limit', 1024)\n lines = \"\"\n for line in text:\n if len(lines) + len(line) < text_limit:\n lines += line\n else:\n yield lines\n lines = line[0:text_limit]\n else:\n yield lines\n\n def _get_token_correction_proposal(self, index, num_tokens=10):\n r\"\"\" Return num_tokens tokens that could be used to correct token on the position index.\n half of the tokens are best tokens, the other half are tokens surrounding givev index\n\n :param index: index in Sentence of a token.\n :param num_tokens: How many correction proposals do you want\n :return: Array with correction proposals, their probabilities and oddballness scores.\n \"\"\"\n self.sorted_probs, self.sorted_indices = torch.sort(self.probs[index - 1], descending=True)\n bt = self._get_best_tokens( num_tokens=int(num_tokens / 2))\n st = self._get_surrounding_tokens(index, num_tokens=int(num_tokens / 2))\n return torch.cat((bt[0], st[0]), dim=0), torch.cat((bt[1], st[1]), dim=0)\n\n def _get_best_tokens(self, num_tokens=5):\n r\"\"\" Return num_tokens tokens that have the highest probability for a given token\n\n :param num_tokens: How many correction proposals do you want\n :return: Array with correction proposals, their probabilities and oddballness scores.\n \"\"\"\n return self.sorted_probs[:num_tokens], self.sorted_indices[:num_tokens]\n\n def _get_surrounding_tokens(self, index, num_tokens=5, min_index=5):\n r\"\"\" Return num_tokens tokens that have similar probability to given token\n\n :param index: index in Sentence of a token.\n :param num_tokens: How many correction proposals do you want\n :param min_index: index that indicates whether result's of _get_best_tokens intersect\n :return: Array with correction proposals, their probabilities and oddballness scores.\n \"\"\"\n token_id = self.input_ids[0][index]\n sorted_index = (self.sorted_indices == token_id).nonzero()[0].item()\n lower_boundary = max(0 + min_index, int(sorted_index - num_tokens / 2))\n upper_boundary = lower_boundary + num_tokens # min(len(self.sorted_probs)-1,int(sorted_index + num_tokens/2))\n print(lower_boundary, upper_boundary)\n\n return self.sorted_probs[lower_boundary:upper_boundary], self.sorted_indices[lower_boundary:upper_boundary]\n\n def _trim_bpe_space_artifact(self, arr):\n if self.input_text[0] != \" \":\n arr[0][\"name\"].lstrip(\" \")\n\n def get_exhaustive_text_correction_proposal(self, input_text):\n r\"\"\" Return tokens that are likely to substitute each token on the entry.\n\n :param input_text:\n :return:\n \"\"\"\n arr = []\n self.complexity=20\n prev = self.alpha\n self.alpha = 0.95 # temporary\n arr_i = 0\n\n with torch.no_grad():\n for text_chunk in tqdm(self._string_to_chunks(input_text)):\n self.oryginal_input_text = text_chunk\n self.input_text = text_chunk\n self._compute_exhaustive_outputs()\n\n for ix in range(self.input_size):\n token_id = self.input_ids[0][ix]\n token_obj = {}\n token_obj[\"name\"] = self.tokenizer.decode(token_id.item())\n token_obj[\"probability\"] = self.normalized_token_prob[ix]\n token_obj[\"oddballness\"] = self._get_oddballness_proba(token_obj[\"probability\"], self.probs[ix],\n alpha=self.alpha).item()\n arr.append(token_obj)\n\n self.input_text = self.oryginal_input_text\n self._compute_outputs()\n for ix in range(self.input_size):\n self.sorted_probs, self.sorted_indices = torch.sort(self.probs[ix - 1], descending=True)\n _, correction_indices = self._get_best_tokens(5)\n\n arr[arr_i + ix][\"corrections\"] = [self.tokenizer.decode(token_id.item()) for token_id in correction_indices]\n arr_i += self.input_size\n\n arr.pop()\n arr.pop(0)\n self._trim_bpe_space_artifact(arr)\n self.token_array = arr\n self.alpha = prev # temporary\n return arr","sub_path":"backend/proba_engines/proba_engine.py","file_name":"proba_engine.py","file_ext":"py","file_size_in_byte":10990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"128702694","text":"def main():\n T_Data = dict()\n S_Data = dict()\n\n\n\n temp = input().strip().replace(\",\", \"\")\n S_Data[chr(90-len(temp)+1)] = temp\n # =========================\n for i in range(90-len(temp)+2,91):\n S_Data[chr(i)] = input().strip().replace(\",\", \"\")\n \n T_Data[\"A\"] = input().strip().replace(\",\", \"\")\n\n for i in range(66,65+len(T_Data[\"A\"])):\n T_Data[chr(i)] = input().strip().replace(\",\", \"\")\n\n\n # =========================\n i = 0\n Out = list()\n t = list()\n while len(Out) != len(T_Data):\n Data = dict()\n for k, v in S_Data.items():\n if k not in t and v[i] not in t:\n Data[v[i]] = Data.get(v[i], []) + [k]\n if Data != dict():\n Out, t = get(Data, T_Data, Out, t)\n i += 1\n Out.sort()\n for i in Out:\n print(\"{}->{}\".format(i[0], i[1]))\n\n\ndef get(Data, T_Data, Out, t):\n for k, v in Data.items():\n if len(v) > 1:\n temp = list()\n for i in v:\n temp.append((T_Data[k].find(i), i))\n temp.sort()\n for i in range(len(temp)):\n if temp[i][1] not in t:\n Out.append((temp[i][1], k))\n t.append(temp[i][1])\n break\n else:\n Out.append((v[0], k))\n t.append(v[0])\n t.append(k)\n return Out, t\n\n\n# =========================================\nif __name__ == \"__main__\":\n main()\n","sub_path":"Week_1/Test_38.py","file_name":"Test_38.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"602159834","text":"# -*- coding: utf-8 -*- #\n# Copyright 2019 Google LLC. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Describe command for the Resource Manager - Tag Values CLI.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.api_lib.resource_manager import tags\nfrom googlecloudsdk.calliope import base\nfrom googlecloudsdk.command_lib.resource_manager import tag_arguments as arguments\nfrom googlecloudsdk.command_lib.resource_manager import tag_utils\n\n\n@base.ReleaseTracks(base.ReleaseTrack.ALPHA)\nclass Describe(base.Command):\n \"\"\"Describes a TagValue resource.\n\n Gets metadata for a TagValue resource given the TagValue's resource name or\n namespaced name.\n \"\"\"\n\n detailed_help = {\n 'EXAMPLES':\n \"\"\"\n To describe a TagValue with id ``123\", run:\n\n $ {command} tagValues/123\n\n To describe a TagValue with name ``dev\" with the tagKey ``env\" under '\n 'organizations ``456\",\n run:\n\n $ {command} 456/env/dev\n \"\"\"\n }\n\n @staticmethod\n def Args(parser):\n arguments.AddResourceNameArgToParser(parser)\n\n def Run(self, args):\n service = tags.TagValuesService()\n messages = tags.TagMessages()\n\n if args.RESOURCE_NAME.find('tagValues/') == 0:\n tag_value = args.RESOURCE_NAME\n else:\n tag_value = tag_utils.GetTagValueFromNamespacedName(\n args.RESOURCE_NAME).name\n\n get_request = messages.CloudresourcemanagerTagValuesGetRequest(\n name=tag_value)\n return service.Get(get_request)\n","sub_path":"google-cloud-sdk/lib/surface/resource_manager/tags/values/describe.py","file_name":"describe.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"438576218","text":"import timeit\nimport sys\nsys.path.append(\"./cython\")\nfrom monte_carlo_pi_opt import MonteCarloPiOpt\n\n\ndef MonteCarloPi(n=10000000):\n\tcount = 0\n\tXseed0 = 2019\n\tXseed1 = 11\n\tM = 4294967296\n\tMMinus = M-1\n\ta = 1664525\n\tc = 101390423\n\tfor i in range(n):\n\t\tXseed0 = (a*Xseed0+c)%M\n\t\tXseed1 = (a*Xseed1+c)%M\n\t\tU = float(Xseed0)/M\n\t\tV = float(Xseed1)/M\n\t\tif(U*U+V*V)<1.0:\n\t\t\tcount+=1\n\tpi = 4.0*count/n\n\treturn pi\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) !=2:\n\t\tprint(\"python monte-carlo-pi.py [num_iterations]\")\n\telse:\n\t\t\n\t\tstart1 = timeit.default_timer()\n\t\tpi1 = MonteCarloPi(int(sys.argv[1]))\n\t\tend1 = timeit.default_timer()\n\t\tprint(\"python : {} s \\t pi: {}\".format(end1-start1,pi1))\n\t\t\n\t\t#__________________________ cython __________________________\n\t\tstart2 = timeit.default_timer()\n\t\tpi2 = MonteCarloPiOpt(int(sys.argv[1]))\n\t\tend2 = timeit.default_timer()\n\t\tprint(\"cython : {} s \\t pi: {}\".format(end2-start2,pi2))\n\t\t\n","sub_path":"monte-carlo-pi/src/python/monte_carlo_pi.py","file_name":"monte_carlo_pi.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"524688719","text":"#!/usr/bin/env python\n\"\"\"\nBrain label numbers, names, and colormap related to the DKT labeling protocol\n==============================================================================\n\nFor more information about the Desikan-Killiany-Tourville cortical labeling\nprotocol see http://mindboggle.info/data and the article:\n\nhttp://www.frontiersin.org/Brain_Imaging_Methods/10.3389/fnins.2012.00171/full\n\"101 labeled brain images and a consistent human cortical labeling protocol\"\nArno Klein, Jason Tourville. Frontiers in Brain Imaging Methods. 6:171.\nDOI: 10.3389/fnins.2012.00171\n\nCalls return_numbers_names_colors() to return numbers, names, and colors\nextracted from FreeSurfer's FreeSurferColorLUT.txt lookup table file\nrepresenting anatomical brain regions.\n(See extract_numbers_names_colors() in LUT.py for extraction code.)\n\n------------------------------------------------------------------------------\nCombined/eliminated regions:\n------------------------------------------------------------------------------\n(1) Temporal (33) and frontal (32) poles, and bankstss (see note #1)\n regions eliminated, corresponding cortex absorbed by adjacent regions.\n(2) Caudal (2), isthmus (10), posterior (23), and rostral anterior (26)\n cingulate combined to form single cingulate region (2).\n(3) Caudal (3) and rostral (27) middle frontal regions combined\n to form single middle frontal region (3).\n(4) Opercular (18), orbital (19), and triangular (20) inferior frontal regions\n combined to form a single inferior frontal region (18).\nThis is a perfectly reasonable aggregation of these regions and is the one\nreflected in the sulcus/region pairings below. An alternative breakdown\nwould be to lump 19 with lateral orbitofrontal cortex (12) and use the\nanterior horizontal ramus of the sylvian fissure as the boundary between\n18 and 12. Anatomically, both aggregations are defensible but one or the other\nmay suit your needs better.\n\nJason Tourville: \"Regarding the lack of a full, consistent sulcal anterior\nboundary for the inferior frontal gyrus:\nThis will be the case for several regions, i.e., in practice, many boundaries\nare not formed by sulci but instead require \"jumps\" across gyri\n(paths along regions of different direction curvature). This can be variable,\n(e.g., the precentral sulcus is consistently formed by 2 or more disconnected\ncomponents) or implicit in the definition of the boundary (e.g., the anterior\nboundary between orbital inferior frontal gyrus (19) and rostral middle\nfrontal gyrus (27) requires a \"jump\" over the lateral orbital gyrus.\nBelow, I note with a '*' those boundaries given principally by a sulcal fundus\nbut which frequently require \"jumps\" across gyri. I handle separately\ndefinitions that explicitly rely on non-fundus boundaries, i.e., those that\nrely on the margins of sulcal banks.\"\n\n(5) Parahippocampal + entorhinal cortex + and lingual gyrus?\n\n------------------------------------------------------------------------------\nRegions bounded by sulcal fundi:\n------------------------------------------------------------------------------\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nLateral surface:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n- frontomarginal sulcus: [12,28]\n- superior frontal: [3,28],[27,28]\n- inferior frontal: [3,18],[3,19],[3,20], [18,27],[19,27],[20,27]\n- precentral: [24,28]*, [[3,24],[24,27]]*, [[18,24],[19,24],[20,24]]*\n- central sulcus: [22,24]\n- postcentral: [22,29],[22,31], not:[22,24]\n- intraparietal: [29,31], [8,29]\n- primary intermediate sulcus /\n 1st segment of the posterior superior temporal sulcus: [8,31]*\n- sylvian fissure: [30,31]*, not:[18,30] (see note #2)\n- lateral occipital sulcus: [8,11]*,[11,29]*\n- anterior occipital sulcus: [11,15]*,[9,11]\n- superior temporal sulcus: [15,30]\n- inferior temporal sulcus: [9,15]*\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nPeriSylvian area (folds within the Sylvian fissure):\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n- circular sulcus: [12,35],[30,35],[34,35], [2,35],[10,35],[23,35],[26,35],\n [22,35], [24,35], [31,35]\n- 1st transverse temporal sulcus: [30,34]\n- Heschl's sulcus: [30,34]\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nMedial surface:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n- cingulate sulcus: [2,14],[10,14],[14,23],[14,26] (see note #3),\n [2,28],[10,28],[23,28],[26,28],\n [2,17],[10,17],[17,23],[17,26], [17,25]\n- paracentral sulcus: [17,28]*\n- parietooccipital fissure: [5,25]\n- calcarine fissure: [13,25], [2,13],[10,13],[13,23],[13,26] not:[5,13] (note #4)\n- superior rostral sulcus: [14,28]\n- callosal sulcus: [2,4],[4,10],[4,23],[4,26]\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nVentral surface:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n- lateral H-shaped orbital sulcus: [3,12],[12,27], [12,18],[12,19],[12,20]\n- olfactory sulcus: [12,14]\n- occipitotemporal sulcus: [7,9],[7,11]\n- collateral sulcus: [6,7], [7,13], [7,16]\n\n------------------------------------------------------------------------------\nWhat boundaries will NEVER be derived by fundi, but instead by curvature, etc.\n------------------------------------------------------------------------------\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nRegions bounded by sulcal margins:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n- interhemispheric fissure, dorsal margin:\n [17,28],[17,24],[17,22],[25,29],[5,29],[5,11]\n- calcarine sulcus, dorsal margin: [5,21]\n- calcarine sulcus, ventral margin: [21,13]\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nRegions with additional non-sulcal boundaries with subcortical regions:\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n[16,6,9,30,12,14]\n\n------------------------------------------------------------------------------\nNotes:\n------------------------------------------------------------------------------\n[1] This was eliminated b/c it spanned the superior temporal sulcus fundus\n and because the anterior boundary was ambiguous.\n[2] The insula lies b/w these regions and is separated from them by the\n circular sulcus which is marked by an easily distinguished fold deep\n within the Sylvian fissure.\n[3] This is the case in some, but not all, hemispheres. It occurs when the\n superior rostral sulcus fails to intersect with the cingulate sulcus.\n[4] The pericalcarine region lies between these 2 regions. As defined in\n \"Regions bounded by sulcal margins\", the pericalcarine cortex (21)\n dorsal (with 5) and ventral (with 13) boundaries are formed by the\n lateral margins of the dorsal and ventral banks of the calcarine sulcus\n rather than a sulcal fundus; because this region spans the sulcal fundus,\n we cannot simply incorporate portions of the region into the adjacent\n regions based on the fundus.\n\nAuthors:\n - Jason Tourville, 2011-2012 (jtour@bu.edu)\n - Arno Klein, 2011-2013 (arno@mindboggle.info) http://binarybottle.com\n\nCopyright 2013, Mindboggle team (http://mindboggle.info), Apache v2.0 License\n\n\"\"\"\n\n#=============================================================================\n# DKT protocol\n#=============================================================================\nclass DKTprotocol:\n \"\"\"\n Variables related to the Desikan-Killiany-Tourville labeling protocol.\n\n Returns\n -------\n [left, right]_cerebrum_cortex_[DKT31_][numbers, names, colors]\n [left, right]_ventricle_[numbers, names, colors]\n medial_ventricle_[numbers, names, colors]\n [left, right]_cerebrum_noncortex_[numbers, names, colors]\n medial_cerebrum_noncortex_[numbers, names, colors]\n [left, right]_cerebellum_cortex_[numbers, names, colors]\n [left, right]_cerebellum_noncortex_[numbers, names, colors]\n medial_cerebellum_noncortex_[numbers, names, colors]\n brainstem_[numbers, names, colors]\n extra_[numbers, names, colors]\n misc_[numbers, names, colors]\n ventricle_[numbers, names, colors]\n cerebrum_cortex_[numbers, names, colors]\n cerebrum_noncortex_[numbers, names, colors]\n [left, right]_cerebrum_[numbers, names, colors]\n cerebrum_[numbers, names, colors]\n [left, right]_cerebellum_[numbers, names, colors]\n cerebellum_cortex_[numbers, names, colors]\n cerebellum_noncortex_[numbers, names, colors]\n cerebellum_[numbers, names, colors]\n label_[numbers, names, colors]\n colormap : list of lists\n colormap_normalized : list of lists\n sulcus_[names[_abbr], numbers]\n unique_sulcus_label_pairs : list of unique pairs of integers\n unique label pairs corresponding to label boundaries / sulcus / fundus\n [left_, right_]sulcus_label_pair_lists : list of two lists of lists of integer pairs\n list containing left and/or right lists, each with multiple lists of\n integer pairs corresponding to label boundaries / sulcus / fundus\n\n Examples\n --------\n >>> from mindboggle.LABELS import DKTprotocol\n >>> dkt = DKTprotocol()\n >>> dkt.left_cerebrum_names\n\n \"\"\"\n from mindboggle.LUT import return_numbers_names_colors\n\n #-------------------------------------------------------------------------\n # Return numbers, names, colors extracted from FreeSurferColorLUT.txt:\n #-------------------------------------------------------------------------\n numbers, names, colors = return_numbers_names_colors()\n\n #-------------------------------------------------------------------------\n # Cerebral cortex label numbers (DKT31 protocol):\n #-------------------------------------------------------------------------\n left_cerebrum_cortex_DKT31_list = \\\n [1002, 1003] + range(1005, 1032) + [1034, 1035]\n right_cerebrum_cortex_DKT31_list = \\\n [2002, 2003] + range(2005, 2032) + [2034, 2035]\n\n #-------------------------------------------------------------------------\n # Cerebral cortex label numbers (31 + duplicates):\n #-------------------------------------------------------------------------\n left_cerebrum_cortex_list = left_cerebrum_cortex_DKT31_list + \\\n [3, 19, 20, 1000, 1001, 1032, 1033]\n right_cerebrum_cortex_list = right_cerebrum_cortex_DKT31_list + \\\n [42, 55, 56, 2000, 2001, 2032, 2033]\n\n #-------------------------------------------------------------------------\n # Cerebral ventricle label numbers:\n #-------------------------------------------------------------------------\n left_ventricle_list = [4, 5]\n right_ventricle_list = [43, 44]\n medial_ventricle_list = [14, 15, 72]\n\n #-------------------------------------------------------------------------\n # Cerebral noncortex label numbers (including ventricles above):\n #-------------------------------------------------------------------------\n # These labels were converted from Neuromorphometrics BrainCOLOR subcortex\n # labels to be consistent with FreeSurferColorLUT.txt labels.\n #\n # Two labels did not have counterparts in FreeSurfer:\n # [75, \"left basal forebrain\"],\n # [76, \"right basal forebrain\"]\n # and were reassigned to unused numbers in FreeSurferColorLUT.txt:\n # [91, \"left basal forebrain\"],\n # [92, \"right basal forebrain\"]\n #-------------------------------------------------------------------------\n left_cerebrum_noncortex_list = \\\n [2, 9, 10, 11, 12, 13, 17, 18, 25, 26, 27, 28, 30, 31, 78, 91, 96] + \\\n range(100, 109) + [155, 157] + range(550, 559) + [1004] + \\\n range(3000, 3036) + [5001] + left_ventricle_list\n right_cerebrum_noncortex_list = \\\n [41, 48, 49, 50, 51, 52, 53, 54, 57, 58, 59, 60, 62, 63, 79, 92, 97] + \\\n range(109, 118) + [156, 158] + range(500, 509) + [2004] + \\\n range(4000, 4036) + [5002] + right_ventricle_list\n medial_cerebrum_noncortex_list = medial_ventricle_list + \\\n [192] + range(250, 256)\n\n #-------------------------------------------------------------------------\n # Cerebellar label numbers:\n #-------------------------------------------------------------------------\n # These labels [71, 72, 73] in Neuromorphometrics BrainCOLOR subcortex\n # did not have counterparts in FreeSurferColorLUT.txt, and were\n # reassigned to unused numbers in FreeSurferColorLUT.txt:\n # [630, \"cerebellar vermal lobules I-V\"],\n # [631, \"cerebellar vermal lobules VI-VII\"],\n # [632, \"cerebellar vermal lobules VIII-X\"],\n #-------------------------------------------------------------------------\n left_cerebellum_cortex_list = [6, 8]\n right_cerebellum_cortex_list = [45, 47]\n left_cerebellum_noncortex_list = [7]\n right_cerebellum_noncortex_list = [46]\n medial_cerebellum_noncortex_list = [630, 631, 632]\n\n #-------------------------------------------------------------------------\n # Extra label numbers:\n #-------------------------------------------------------------------------\n # [16, \"Brain stem\"],\n # [24, \"CSF\"],\n # [85, \"optic chiasm\"]]\n # 170-175: brain stem\n #-------------------------------------------------------------------------\n brainstem_list = [16] + range(170, 176)\n extra_list = [24, 85]\n\n #-------------------------------------------------------------------------\n # Label numbers:\n #-------------------------------------------------------------------------\n left_cerebrum_cortex_DKT31_numbers = []\n right_cerebrum_cortex_DKT31_numbers = []\n left_cerebrum_cortex_numbers = []\n right_cerebrum_cortex_numbers = []\n left_ventricle_numbers = []\n right_ventricle_numbers = []\n medial_ventricle_numbers = []\n left_cerebrum_noncortex_numbers = []\n right_cerebrum_noncortex_numbers = []\n medial_cerebrum_noncortex_numbers = []\n left_cerebellum_cortex_numbers = []\n right_cerebellum_cortex_numbers = []\n left_cerebellum_noncortex_numbers = []\n right_cerebellum_noncortex_numbers = []\n medial_cerebellum_noncortex_numbers = []\n brainstem_numbers = []\n extra_numbers = []\n misc_numbers = []\n #-------------------------------------------------------------------------\n # Names corresponding to label numbers:\n #-------------------------------------------------------------------------\n left_cerebrum_cortex_DKT31_names = []\n right_cerebrum_cortex_DKT31_names = []\n left_cerebrum_cortex_names = []\n right_cerebrum_cortex_names = []\n left_ventricle_names = []\n right_ventricle_names = []\n medial_ventricle_names = []\n left_cerebrum_noncortex_names = []\n right_cerebrum_noncortex_names = []\n medial_cerebrum_noncortex_names = []\n left_cerebellum_cortex_names = []\n right_cerebellum_cortex_names = []\n left_cerebellum_noncortex_names = []\n right_cerebellum_noncortex_names = []\n medial_cerebellum_noncortex_names = []\n brainstem_names = []\n extra_names = []\n misc_names = []\n #-------------------------------------------------------------------------\n # Colors corresponding to label numbers:\n #-------------------------------------------------------------------------\n left_cerebrum_cortex_DKT31_colors = []\n right_cerebrum_cortex_DKT31_colors = []\n left_cerebrum_cortex_colors = []\n right_cerebrum_cortex_colors = []\n left_ventricle_colors = []\n right_ventricle_colors = []\n medial_ventricle_colors = []\n left_cerebrum_noncortex_colors = []\n right_cerebrum_noncortex_colors = []\n medial_cerebrum_noncortex_colors = []\n left_cerebellum_cortex_colors = []\n right_cerebellum_cortex_colors = []\n left_cerebellum_noncortex_colors = []\n right_cerebellum_noncortex_colors = []\n medial_cerebellum_noncortex_colors = []\n brainstem_colors = []\n extra_colors = []\n misc_colors = []\n\n #-------------------------------------------------------------------------\n # Lists of numbers, names, and colors:\n #-------------------------------------------------------------------------\n for i, n in enumerate(numbers):\n\n if n in left_cerebrum_cortex_DKT31_list:\n left_cerebrum_cortex_DKT31_numbers.append(numbers[i])\n left_cerebrum_cortex_DKT31_names.append(names[i])\n left_cerebrum_cortex_DKT31_colors.append(colors[i])\n elif n in right_cerebrum_cortex_DKT31_list:\n right_cerebrum_cortex_DKT31_numbers.append(numbers[i])\n right_cerebrum_cortex_DKT31_names.append(names[i])\n right_cerebrum_cortex_DKT31_colors.append(colors[i])\n\n if n in left_cerebrum_cortex_list:\n left_cerebrum_cortex_numbers.append(numbers[i])\n left_cerebrum_cortex_names.append(names[i])\n left_cerebrum_cortex_colors.append(colors[i])\n elif n in right_cerebrum_cortex_list:\n right_cerebrum_cortex_numbers.append(numbers[i])\n right_cerebrum_cortex_names.append(names[i])\n right_cerebrum_cortex_colors.append(colors[i])\n elif n in left_ventricle_list:\n left_ventricle_numbers.append(numbers[i])\n left_cerebrum_noncortex_numbers.append(numbers[i])\n left_ventricle_names.append(names[i])\n left_cerebrum_noncortex_names.append(names[i])\n left_ventricle_colors.append(colors[i])\n left_cerebrum_noncortex_colors.append(colors[i])\n elif n in right_ventricle_list:\n right_ventricle_numbers.append(numbers[i])\n right_cerebrum_noncortex_numbers.append(numbers[i])\n right_ventricle_names.append(names[i])\n right_cerebrum_noncortex_names.append(names[i])\n right_ventricle_colors.append(colors[i])\n right_cerebrum_noncortex_colors.append(colors[i])\n elif n in medial_ventricle_list:\n medial_ventricle_numbers.append(numbers[i])\n medial_cerebrum_noncortex_numbers.append(numbers[i])\n medial_ventricle_names.append(names[i])\n medial_cerebrum_noncortex_names.append(names[i])\n medial_ventricle_colors.append(colors[i])\n medial_cerebrum_noncortex_colors.append(colors[i])\n elif n in left_cerebrum_noncortex_list:\n left_cerebrum_noncortex_numbers.append(numbers[i])\n left_cerebrum_noncortex_names.append(names[i])\n left_cerebrum_noncortex_colors.append(colors[i])\n elif n in right_cerebrum_noncortex_list:\n right_cerebrum_noncortex_numbers.append(numbers[i])\n right_cerebrum_noncortex_names.append(names[i])\n right_cerebrum_noncortex_colors.append(colors[i])\n elif n in medial_cerebrum_noncortex_list:\n medial_cerebrum_noncortex_numbers.append(numbers[i])\n medial_cerebrum_noncortex_names.append(names[i])\n medial_cerebrum_noncortex_colors.append(colors[i])\n elif n in left_ventricle_list:\n left_ventricle_numbers.append(numbers[i])\n left_ventricle_names.append(names[i])\n left_ventricle_colors.append(colors[i])\n elif n in right_ventricle_list:\n right_ventricle_numbers.append(numbers[i])\n right_ventricle_names.append(names[i])\n right_ventricle_colors.append(colors[i])\n elif n in medial_ventricle_list:\n medial_ventricle_numbers.append(numbers[i])\n medial_ventricle_names.append(names[i])\n medial_ventricle_colors.append(colors[i])\n elif n in left_cerebellum_cortex_list:\n left_cerebellum_cortex_numbers.append(numbers[i])\n left_cerebellum_cortex_names.append(names[i])\n left_cerebellum_cortex_colors.append(colors[i])\n elif n in right_cerebellum_cortex_list:\n right_cerebellum_cortex_numbers.append(numbers[i])\n right_cerebellum_cortex_names.append(names[i])\n right_cerebellum_cortex_colors.append(colors[i])\n elif n in left_cerebellum_noncortex_list:\n left_cerebellum_noncortex_numbers.append(numbers[i])\n left_cerebellum_noncortex_names.append(names[i])\n left_cerebellum_noncortex_colors.append(colors[i])\n elif n in right_cerebellum_noncortex_list:\n right_cerebellum_noncortex_numbers.append(numbers[i])\n right_cerebellum_noncortex_names.append(names[i])\n right_cerebellum_noncortex_colors.append(colors[i])\n elif n in medial_cerebellum_noncortex_list:\n medial_cerebellum_noncortex_numbers.append(numbers[i])\n medial_cerebellum_noncortex_names.append(names[i])\n medial_cerebellum_noncortex_colors.append(colors[i])\n elif n in brainstem_list:\n brainstem_numbers.append(numbers[i])\n brainstem_names.append(names[i])\n brainstem_colors.append(colors[i])\n elif n in extra_list:\n extra_numbers.append(numbers[i])\n extra_names.append(names[i])\n extra_colors.append(colors[i])\n else:\n misc_numbers.append(numbers[i])\n misc_names.append(names[i])\n misc_colors.append(colors[i])\n\n #-------------------------------------------------------------------------\n # Aggregate lists of numbers, names, and colors:\n #-------------------------------------------------------------------------\n ventricle_numbers = left_ventricle_numbers + right_ventricle_numbers + \\\n medial_ventricle_numbers\n ventricle_names = left_ventricle_names + right_ventricle_names + \\\n medial_ventricle_names\n ventricle_colors = left_ventricle_colors + right_ventricle_colors + \\\n medial_ventricle_colors\n\n cerebrum_cortex_DKT31_numbers = left_cerebrum_cortex_DKT31_numbers + \\\n right_cerebrum_cortex_DKT31_numbers\n cerebrum_cortex_DKT31_names = left_cerebrum_cortex_DKT31_names + \\\n right_cerebrum_cortex_DKT31_names\n cerebrum_cortex_DKT31_colors = left_cerebrum_cortex_DKT31_colors + \\\n right_cerebrum_cortex_DKT31_colors\n cerebrum_cortex_numbers = left_cerebrum_cortex_numbers + \\\n right_cerebrum_cortex_numbers\n cerebrum_cortex_names = left_cerebrum_cortex_names + \\\n right_cerebrum_cortex_names\n cerebrum_cortex_colors = left_cerebrum_cortex_colors + \\\n right_cerebrum_cortex_colors\n cerebrum_noncortex_numbers = left_cerebrum_noncortex_numbers + \\\n right_cerebrum_noncortex_numbers + \\\n medial_cerebrum_noncortex_numbers + \\\n ventricle_numbers\n cerebrum_noncortex_names = left_cerebrum_noncortex_names + \\\n right_cerebrum_noncortex_names + \\\n medial_cerebrum_noncortex_names + \\\n ventricle_names\n cerebrum_noncortex_colors = left_cerebrum_noncortex_colors + \\\n right_cerebrum_noncortex_colors + \\\n medial_cerebrum_noncortex_colors + \\\n ventricle_colors\n left_cerebrum_numbers = left_cerebrum_cortex_numbers + \\\n left_cerebrum_noncortex_numbers\n left_cerebrum_names = left_cerebrum_cortex_names + \\\n left_cerebrum_noncortex_names\n left_cerebrum_colors = left_cerebrum_cortex_colors + \\\n left_cerebrum_noncortex_colors\n right_cerebrum_numbers = right_cerebrum_cortex_numbers + \\\n right_cerebrum_noncortex_numbers\n right_cerebrum_names = right_cerebrum_cortex_names + \\\n right_cerebrum_noncortex_names\n right_cerebrum_colors = right_cerebrum_cortex_colors + \\\n right_cerebrum_noncortex_colors\n cerebrum_numbers = left_cerebrum_numbers + right_cerebrum_numbers\n cerebrum_names = left_cerebrum_names + right_cerebrum_names\n cerebrum_colors = left_cerebrum_colors + right_cerebrum_colors\n\n left_cerebellum_numbers = left_cerebellum_cortex_numbers + \\\n left_cerebellum_noncortex_numbers\n left_cerebellum_names = left_cerebellum_cortex_names + \\\n left_cerebellum_noncortex_names\n right_cerebellum_numbers = right_cerebellum_cortex_numbers + \\\n right_cerebellum_noncortex_numbers\n right_cerebellum_names = right_cerebellum_cortex_names + \\\n right_cerebellum_noncortex_names\n\n cerebellum_cortex_numbers = left_cerebellum_cortex_numbers + \\\n right_cerebellum_cortex_numbers\n cerebellum_cortex_names = left_cerebellum_cortex_names + \\\n right_cerebellum_cortex_names\n cerebellum_cortex_colors = left_cerebellum_cortex_colors + \\\n right_cerebellum_cortex_colors\n cerebellum_noncortex_numbers = left_cerebellum_noncortex_numbers + \\\n right_cerebellum_noncortex_numbers + \\\n medial_cerebellum_noncortex_numbers\n cerebellum_noncortex_names = left_cerebellum_noncortex_names + \\\n right_cerebellum_noncortex_names + \\\n medial_cerebellum_noncortex_names\n cerebellum_noncortex_colors = left_cerebellum_noncortex_colors + \\\n right_cerebellum_noncortex_colors\n cerebellum_numbers = cerebellum_cortex_numbers + \\\n cerebellum_noncortex_numbers\n cerebellum_names = cerebellum_cortex_names + cerebellum_noncortex_names\n cerebellum_colors = cerebellum_cortex_colors + cerebellum_noncortex_colors\n\n label_numbers = cerebrum_numbers + cerebellum_numbers + \\\n brainstem_numbers + extra_numbers\n label_names = cerebrum_names + cerebellum_names + \\\n brainstem_names + extra_names\n label_colors = cerebrum_colors + cerebellum_colors + \\\n brainstem_colors + extra_colors\n\n #-------------------------------------------------------------------------\n # Colormap:\n #-------------------------------------------------------------------------\n colormap = []\n colormap_normalized = []\n for i, x in enumerate(label_colors):\n colormap.append([label_numbers[i], 1, x[0], x[1], x[2]])\n colormap_normalized.append([label_numbers[i], 1,\n x[0]/255.0, x[1]/255.0, x[2]/255.0])\n\n #-------------------------------------------------------------------------\n # Sulcus names from the DKT labeling protocol:\n #-------------------------------------------------------------------------\n sulcus_names = [\n \"frontomarginal sulcus\",\n \"superior frontal sulcus\",\n \"inferior frontal sulcus\",\n \"precentral sulcus\",\n \"central sulcus\",\n \"postcentral sulcus\",\n \"intraparietal sulcus\",\n \"primary intermediate sulcus/1st segment of post. sup. temporal sulcus\",\n \"sylvian fissure\",\n \"lateral occipital sulcus\",\n \"anterior occipital sulcus\",\n \"superior temporal sulcus\",\n \"inferior temporal sulcus\",\n \"circular sulcus\",\n \"1st transverse temporal sulcus and Heschl's sulcus\",\n \"cingulate sulcus\",\n \"paracentral sulcus\",\n \"parietooccipital fissure\",\n \"calcarine fissure\",\n \"superior rostral sulcus\",\n \"callosal sulcus\",\n \"lateral H-shaped orbital sulcus\",\n \"olfactory sulcus\",\n \"occipitotemporal sulcus\",\n \"collateral sulcus\"]\n sulcus_numbers = range(len(sulcus_names))\n\n sulcus_names_abbr = [\n \"fms\",\n \"sfrs\",\n \"ifrs\",\n \"prcs\",\n \"cs\",\n \"pocs\",\n \"itps\",\n \"pis/csts1\",\n \"ls\",\n \"locs\",\n \"aocs\",\n \"sts\",\n \"its\",\n \"crs\",\n \"ftts/hs\",\n \"cgs\",\n \"pcs\",\n \"pos\",\n \"ccs\",\n \"sros\",\n \"cas\",\n \"lhos\",\n \"olfs\",\n \"ots\",\n \"cos\"]\n\n #-------------------------------------------------------------------------\n # Lists of label pairs that define sulcus boundaries (or fundi)\n # according to the DKT labeling protocol.\n # 1000 [lh] or 2000 [rh] are added to these numbers below.\n #-------------------------------------------------------------------------\n pair_lists = [\n [[12, 28]],\n [[3, 28], [27, 28]],\n [[3, 18], [3, 19], [3, 20], [18, 27], [19, 27], [20, 27]],\n [[24, 28], [3, 24], [24, 27], [18, 24], [19, 24], [20, 24]],\n [[22, 24]],\n [[22, 29], [22, 31]],\n [[29, 31], [8, 29]],\n [[8, 31]],\n [[30, 31]],\n [[8, 11], [11, 29]],\n [[11, 15], [9, 11]],\n [[15, 30]],\n [[9, 15]],\n [[12, 35], [30, 35], [34, 35], [2, 35], [10, 35], [23, 35], [26, 35],\n [22, 35], [24, 35], [31, 35]],\n [[30, 34]],\n [[2, 14], [10, 14], [14, 23], [14, 26], [2, 28], [10, 28], [23, 28],\n [26, 28],\n [2, 17], [10, 17], [17, 23], [17, 26], [17, 25]],\n [[17, 28]],\n [[5, 25]],\n [[13, 25], [2, 13], [10, 13], [13, 23], [13, 26]],\n [[14, 28]],\n [[2, 4], [4, 10], [4, 23], [4, 26]],\n [[3, 12], [12, 27], [12, 18], [12, 19], [12, 20]],\n [[12, 14]],\n [[7, 9], [7, 11]],\n [[6, 7], [7, 16], [7, 13]]]\n\n relabel = True\n\n left_sulcus_label_pair_lists = []\n right_sulcus_label_pair_lists = []\n unique_sulcus_label_pairs = [] # unique sorted label pairs\n for pair_list in pair_lists:\n left_pairs = []\n right_pairs = []\n for pair in pair_list:\n left_pair = [1000 + pair[0], 1000 + pair[1]]\n right_pair = [2000 + pair[0], 2000 + pair[1]]\n left_pairs.append(left_pair)\n right_pairs.append(right_pair)\n if relabel:\n if left_pair not in unique_sulcus_label_pairs:\n unique_sulcus_label_pairs.append(left_pair)\n if right_pair not in unique_sulcus_label_pairs:\n unique_sulcus_label_pairs.append(right_pair)\n else:\n if pair not in unique_sulcus_label_pairs:\n unique_sulcus_label_pairs.append(pair)\n left_sulcus_label_pair_lists.append(left_pairs)\n right_sulcus_label_pair_lists.append(right_pairs)\n if relabel:\n sulcus_label_pair_lists = left_sulcus_label_pair_lists + \\\n right_sulcus_label_pair_lists\n else:\n sulcus_label_pair_lists = pair_lists\n\n\ndef print_colormap(colormap):\n \"\"\"\n Print colormap.\n\n Parameters\n ----------\n colormap : list of lists of string and floats\n label, 1, red, green, blue\n\n Examples\n --------\n >>> from mindboggle.LABELS import DKTprotocol, print_colormap\n >>> dkt = DKTprotocol()\n >>> colormap = dkt.colormap_normalized\n >>> print_colormap(colormap)\n\n \"\"\"\n\n print(\n '')\n print(' ')\n print(' ')\n for row in colormap:\n print(' '.\n format(row[0], row[2], row[3], row[4]))\n print('')\n\n\n\"\"\"\n #-------------------------------------------------------------------------\n # DKT cerebral cortical labeling protocol -- 25 labels:\n #-------------------------------------------------------------------------\n # Region numbers:\n # DKT31 to DKT25: [[10,23,26,27,19,20], [2,2,2,3,18,18]]\n left_cerebrum_cortex_numbers_DKT25 = range(1002, 1036)\n for n in [1004, 1010, 1019, 1020, 1023, 1026, 1027, 1032, 1033]:\n left_cerebrum_cortex_numbers_DKT25.remove(n)\n right_cerebrum_cortex_numbers_DKT25 = range(2002, 2036)\n for n in [2004, 2010, 2019, 2020, 2023, 2026, 2027, 2032, 2033]:\n right_cerebrum_cortex_numbers_DKT25.remove(n)\n cerebrum_cortex_numbers_DKT25 = left_cerebrum_cortex_numbers_DKT25 + \\\n right_cerebrum_cortex_numbers_DKT25\n # Consolidate region labels:\n left_cerebrum_cortex_names_DKT25 = []\n for ilabel, label_number in enumerate(left_cerebrum_cortex_numbers):\n if label_number in left_cerebrum_cortex_numbers_DKT25:\n if label_number == 1002:\n left_cerebrum_cortex_names_DKT25.append('left cingulate')\n elif label_number == 1003:\n left_cerebrum_cortex_names_DKT25.append('left middle frontal')\n elif label_number == 1018:\n left_cerebrum_cortex_names_DKT25.append('left inferior frontal')\n else:\n left_cerebrum_cortex_names_DKT25. \\\n append(left_cerebrum_cortex_names[ilabel])\n right_cerebrum_cortex_names_DKT25 = []\n for ilabel, label_number in enumerate(right_cerebrum_cortex_numbers):\n if label_number in right_cerebrum_cortex_numbers_DKT25:\n if label_number == 2002:\n right_cerebrum_cortex_names_DKT25.append('right cingulate')\n elif label_number == 2003:\n right_cerebrum_cortex_names_DKT25.append('right middle frontal')\n elif label_number == 2018:\n right_cerebrum_cortex_names_DKT25.append('right inferior frontal')\n else:\n right_cerebrum_cortex_names_DKT25. \\\n append(right_cerebrum_cortex_names[ilabel])\n cerebrum_cortex_names_DKT25 = \\\n left_cerebrum_cortex_names_DKT25 + right_cerebrum_cortex_names_DKT25\n\"\"\"\n\"\"\"\n # 2-D cortical map (UNDER CONSTRUCTION):\n #\n # Each gyrus has one or more sulcus boundaries -- rough breakdown:\n #\n # labels: 28 3 18 30 15 9 7 16 17 12 14 29 8 24 22 5 25 6 21 2 35 31\n #\n # Gyrii: sFG mFG iFG sTG mTG iTG Fus pHip pCen lOrb mOrb sPL iPL prCG poCG Cun prCun ent pCalc Cing Ins sMarg\n # ---|---|---|---|---|---|---|----|---- ---- ---- ---|--- -|----|----|- ---|----- --- ----- ---- --- -----\n # Sulci: sFS iFS Syl sTS iTS TO? Coll? OrbF OrbT iPS prCS CS poCS Cing Ins\n #\n # indices: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18\n\"\"\"","sub_path":"mindboggle/LABELS.py","file_name":"LABELS.py","file_ext":"py","file_size_in_byte":34858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"642356167","text":"import tornado.ioloop\nimport logging\nfrom pubsub import pub\n\nfrom ct.topics import (\n TOPIC_GAME_NEXT_STAGE_READY,\n TOPIC_GAME_TURN_START,\n TOPIC_MESSAGE,\n)\nfrom ct.messages import HandleReqAllState\n\ndef handleGameNextStageReady(game, currState):\n tornado.ioloop.IOLoop.current().add_callback(game.nextState)\n\ndef handleGameTurnStart(game, turnCounter):\n logging.info(game.id + ' new turn = ' + str(turnCounter))\n for player in game.players:\n message = HandleReqAllState().handle(player, game)\n pub.sendMessage(TOPIC_MESSAGE, players=[player], game=game, message=message)\n\ndef registerCallbacks():\n pub.subscribe(handleGameNextStageReady, TOPIC_GAME_NEXT_STAGE_READY)\n pub.subscribe(handleGameTurnStart, TOPIC_GAME_TURN_START)\n\n","sub_path":"ct-api/ct/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"543079702","text":"# English meaning on front, kanji/reading/stroke order on back\n#\n# Uses:\n# genanki: https://github.com/kerrickstaley/genanki\n# kanji stroke order font: http://www.nihilist.org.uk/\n# Pillow: https://python-pillow.org/\n\nimport random\nimport genanki\nimport json\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\nfrom PIL import Image\n\n# If you plan to use this script multiple times to update decks, hardcode the model IDs below -- they're unique\n# IDs for your model and deck respectively.\nwanianki_vocabulary_reverse_id = random.randrange(1 << 30, 1 << 31)\nvocabulary_reverse_model_id = random.randrange(1 << 30, 1 << 31)\n\nvocabulary_reverse_model = genanki.Model(vocabulary_reverse_model_id, 'Vocabulary Reverse Model',\n fields=[\n {'name': 'Vocabulary'},\n {'name': 'Kana'},\n {'name': 'Meaning'},\n {'name': 'Level'},\n {'name': 'VocabID'},\n ],\n templates=[\n {\n 'name': 'WaniAnki Vocabulary Reverse',\n 'qfmt': '
Level {{Level}}
'\n '
{{Meaning}}
',\n 'afmt': '
Level {{Level}}
'\n '
{{Meaning}}
'\n '
'\n ''\n '

{{Kana}}

',\n },\n ],\n css=\".card { font-family: Noto Sans CJK JP Regular; text-align:center; font-size: 80px; color: #ffffff; background: #a100f1; margin: 45px auto; }\"\n \".style-front { font-family: Noto Sans CJK JP Regular; text-align:center; font-size: 80px; color: #ffffff; background: #a100f1; margin: 50px auto; }\"\n \".style-meaning { font-family: Noto Sans CJK JP Regular; text-align:center; font-size: 50px; color: #ffffff; background: #a100f1; margin: 0px; }\"\n \".style-level { font-size: 10px; font-weight: bold; position: absolute; top: 0; right: 0; margin: 15px; }\"\n \".style-reading { font-family: Noto Sans CJK JP Regular; text-align:center; font-size: 60px; color: #ffffff; background: #a100f1; margin-top: 15px; margin-bottom: 25px; } \"\n \".line-dash { margin: 50px; border-top: #ffffff dashed 2px; }\")\n\nwanianki_vocabulary_reverse = genanki.Deck(wanianki_vocabulary_reverse_id, 'WaniAnki Vocabulary')\n\nvocabulary = []\nvocabulary_kana = []\nvocabulary_meaning = []\nvocabulary_level = []\n\nvid = 1\nmaxlength = 0\n\nwith open('wanikani_vocabulary.json') as vocab:\n font = ImageFont.truetype(\"KanjiStrokeOrders_v4.001.ttf\", 100)\n v = json.load(vocab)\n sortlevel = [x for x in v['requested_information'] if 'level' in x]\n vocab_by_level = sorted(sortlevel, key=lambda x: x['level'])\n\n for voc in vocab_by_level:\n vocabulary = voc['character']\n charlength = len(vocabulary)\n width = (charlength * 103) + (50 - (charlength * 5))\n img = Image.new(\"RGB\", (width, 140), (161, 0, 241))\n draw = ImageDraw.Draw(img)\n draw.text((20, 0), vocabulary, (255, 255, 255), font=font)\n draw = ImageDraw.Draw(img)\n img.save('v' + str(vid) + '.png')\n vocabulary_kana = voc['kana']\n vocabulary_meaning = voc['meaning']\n vocabulary_level = str(voc['level'])\n save_vid = str(vid)\n print('Building reverse card ' + save_vid + ', level ' + vocabulary_level + ': ' + vocabulary)\n new_note_reverse = genanki.Note(model=vocabulary_reverse_model, fields=[vocabulary, vocabulary_kana, vocabulary_meaning, vocabulary_level, save_vid])\n wanianki_vocabulary_reverse.add_note(new_note_reverse)\n vid += 1\n\nvocab_media_files = []\nvid_range = range(1, vid)\nfor i in vid_range:\n vocab_media_files.append('v' + str(i) + '.png')\nwanianki_vocabulary_reverse_package = genanki.Package(wanianki_vocabulary_reverse)\nwanianki_vocabulary_reverse_package.media_files = vocab_media_files\nwanianki_vocabulary_reverse_package.write_to_file('wanikani_vocabulary_reverse.apkg')\n","sub_path":"wanianki_vocab_reverse.py","file_name":"wanianki_vocab_reverse.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"534948645","text":"\"\"\"\nSuccess\nDetails \nRuntime: 68 ms, faster than 55.56% of Python3 online submissions for Paint House II.\nMemory Usage: 13.2 MB, less than 47.22% of Python3 online submissions for Paint House II.\n\"\"\"\nclass Solution:\n def minCostII(self, costs: 'List[List[int]]') -> 'int':\n # diss min1 min2没看懂 \n if not costs:\n return 0\n n = len(costs)\n k = len(costs[0])\n dp = [costs[0][i] for i in range(k)]\n for j in range(1, n):\n dp = [min(dp[:i]+dp[i+1:]) + costs[j][i] for i in range(k)]\n\n return min(dp)\n\n\ns = Solution()\nprint(s.minCostII([[1,5,3],[2,9,4]]))\n\n","sub_path":"H_265_minCostII.py","file_name":"H_265_minCostII.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"250974266","text":"from __future__ import division\nimport numpy as np\nfrom scipy.io import loadmat\nfrom scipy.signal import vectorstrength\nimport matplotlib.pyplot as pl\nimport os\nimport copy\nimport json\n\n\nif __name__ == '__main__':\n save_dir = './vectorstrength/all_ISIs'\n file_names = np.array(os.listdir(save_dir))\n\n durs_sine_slow = ['1s', '2s', '5s', '10s']\n relative_tos = ['fast'] # 'slow'\n freqs_fast = ['RF', '5Hz', '20Hz']\n\n # just initialization of dicts\n vectorstrength_dict = {}\n n_cells_dict = {}\n phases_dict = {}\n phases_dict_cells = {}\n for relative_to in relative_tos:\n vectorstrength_dict[relative_to] = {}\n n_cells_dict[relative_to] = {}\n phases_dict[relative_to] = {}\n phases_dict_cells[relative_to] = {}\n for relative_to in relative_tos:\n for dur_sine_slow in durs_sine_slow:\n for freq_fast in freqs_fast:\n vectorstrength_dict[relative_to][dur_sine_slow+'_'+freq_fast] = []\n n_cells_dict[relative_to][dur_sine_slow+'_'+freq_fast] = 0\n phases_dict[relative_to][dur_sine_slow + '_' + freq_fast] = []\n phases_dict_cells[relative_to][dur_sine_slow + '_' + freq_fast] = {}\n\n for file_name in file_names:\n cell_id = file_name.split('_')[0].replace('-', '_')\n mat = loadmat(os.path.join(save_dir, file_name))['short_ISI']\n\n for relative_to in relative_tos:\n for freq_fast in freqs_fast:\n for dur_sine_slow in durs_sine_slow:\n\n stim_lens = mat[:, 6]\n freqs = mat[:, 7]\n\n if freq_fast == 'RF':\n freqs_fast_without_RF = copy.copy(freqs_fast)\n freqs_fast_without_RF.remove('RF')\n mat_selected = mat[np.logical_and(stim_lens == float(dur_sine_slow[:-1]),\n ~np.any(np.vstack(\n [freqs == float(f[:-2]) for f\n in freqs_fast_without_RF]), axis=0))]\n else:\n mat_selected = mat[np.logical_and(stim_lens == float(dur_sine_slow[:-1]),\n freqs == float(freq_fast[:-2]))]\n\n phases = mat_selected[:, 12]\n if len(phases) > 1:\n vs = vectorstrength(phases, 360)[0] # 0 strength, 1 phase\n vectorstrength_dict[relative_to][dur_sine_slow+'_'+freq_fast].append(vs)\n n_cells_dict[relative_to][dur_sine_slow+'_'+freq_fast] += 1\n phases_dict[relative_to][dur_sine_slow + '_' + freq_fast].extend(np.array(phases, dtype=float))\n phases_dict_cells[relative_to][dur_sine_slow + '_' + freq_fast][cell_id] = np.array(phases, dtype=float).tolist()\n\n # save dicts\n with open('./vectorstrength_dict_all.json', 'w') as f:\n json.dump(vectorstrength_dict, f)\n with open('./n_cells_dict_all.json', 'w') as f:\n json.dump(n_cells_dict, f)\n with open('./phases_dict_all.json', 'w') as f:\n json.dump(phases_dict, f)\n with open('./phases_dict_cells_all.json', 'w') as f:\n json.dump(phases_dict_cells, f)\n\n # plot\n bins = np.arange(0, 1+0.025, 0.025)\n for relative_to in relative_tos:\n\n fig, axes = pl.subplots(len(freqs_fast), len(durs_sine_slow), sharex='all', sharey='all', figsize=(12, 7))\n for i, freq_fast in enumerate(freqs_fast):\n for j, dur_sine_slow in enumerate(durs_sine_slow):\n\n if len(vectorstrength_dict[relative_to][dur_sine_slow+'_'+freq_fast]) == 0:\n axes[len(freqs_fast)-i-1, j].axis('off')\n\n axes[len(freqs_fast)-i-1, j].hist(vectorstrength_dict[relative_to][dur_sine_slow+'_'+freq_fast],\n bins=bins,\n weights=np.ones(len(vectorstrength_dict[relative_to][dur_sine_slow+'_'+freq_fast]))\n / n_cells_dict[relative_to][dur_sine_slow+'_'+freq_fast], color='0.5')\n l1 = axes[len(freqs_fast) - i - 1, j].axvline(\n np.mean(vectorstrength_dict[relative_to][dur_sine_slow+'_'+freq_fast]),\n 0, 1, color='r', label='')\n l2 = axes[len(freqs_fast) - i - 1, j].axvline(\n vectorstrength(phases_dict[relative_to][dur_sine_slow + '_' + freq_fast], 360)[0],\n 0, 1, color='b', label='')\n axes[len(freqs_fast) - i - 1, j].set_xlim(0, 1)\n axes[len(freqs_fast) - i - 1, j].spines['top'].set_visible(False)\n axes[len(freqs_fast) - i - 1, j].spines['right'].set_visible(False)\n\n if (len(freqs_fast)-i-1) == 0:\n axes[len(freqs_fast) - i - 1, j].set_title(dur_sine_slow, fontsize=16)\n #axes[len(freqs_fast)-i-1, j].set_xlabel(dur_sine_slow, fontsize=16)\n #axes[len(freqs_fast)-i-1, j].xaxis.set_label_position(\"top\")\n if j == len(freqs_fast):\n axes[len(freqs_fast)-i-1, j].set_ylabel(freq_fast, fontsize=16)\n axes[len(freqs_fast)-i-1, j].yaxis.set_label_position(\"right\")\n fig.text(0.01, 0.5, 'Vector strength relative to '+relative_to+' oscillation (all APs)', va='center',\n rotation='vertical', fontsize=16)\n fig.legend((l1, l2), ('avg.', 'all phases'), loc='upper right')\n pl.tight_layout()\n pl.subplots_adjust(left=0.08)\n pl.savefig(os.path.join('./', 'vector_strength_all.png'))\n pl.show()","sub_path":"cell_fitting/data/plot_vectorstrength/plot_vectorstrength_all2.py","file_name":"plot_vectorstrength_all2.py","file_ext":"py","file_size_in_byte":5782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"29230683","text":"import random\nimport datetime\nimport time\nimport redis\nimport mysql.connector\nimport os\n\nmysqlHost = os.environ['MYSQL_HOST']\nredisHost = os.environ['REDIS_HOST']\n\nclass calcStockPrice:\n def __init__(self,sname,minprice,maxprice):\n self.sname = sname\n self.minprice = minprice\n self.maxprice = maxprice\n \n def calcPrice(self):\n while 2>1:\n stockPrice = random.randint(self.minprice,self.maxprice)\n tick_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n msg = \"{},{},{}\".format(self.sname , stockPrice , tick_time)\n #print(msg)\n r = redis.Redis(host=redisHost)\n r.set(self.sname,stockPrice)\n mydb = mysql.connector.connect(host=mysqlHost,user='root',passwd='root',db='BHARATINDEX') \n mycursor = mydb.cursor()\n query = \"select s_id from s_detail where s_name='%s'\" % (self.sname)\n mycursor.execute(query)\n s_id = list(mycursor.fetchone())\n query = \"insert into s_price values ('%s','%s',%i)\" % (s_id[0], tick_time, stockPrice)\n mycursor.execute(query)\n mydb.commit()\n mycursor.close()\n mydb.close()\n time.sleep(10)","sub_path":"bata/calcStockPrice.py","file_name":"calcStockPrice.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"341203868","text":"import math\nN = int(input())\nif N % 2 == 1:\n print(0)\nelse:\n div10 = N // 10\n sum_val = div10\n if sum_val > 0:\n count_5 = math.floor(math.log(div10, 5))\n for i in range(count_5):\n sum_val += div10 // pow(5, i + 1)\n print(sum_val)\n","sub_path":"AtCoder/AtCoder_Beginner_Contest_148/E_Double_Factorial.py","file_name":"E_Double_Factorial.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"297085913","text":"import csv\n\nclass TopCounts(object):\n \"\"\"\n Computes top counts for a read in CSV file \n \n Args:\n input_filename (str): CSV file\n occupation_output_filename (str): filename where to save occupation output \n state_output_filename (str): filename where to save state output \n delimiter (str): CSV delimiter character \n quotechar (str): Quote character in CSV file \n\n Attributes:\n input_filename (str): CSV filename\n occupation_output_filename (str): occupation output filename\n state_output_filename (str): state output filename\n delimiter (str): delimiter character for read and write \n quotechar (str): Quote character\n \"\"\"\n def __init__(self, input_filename, occupation_output_filename, state_output_filename, \n delimiter=';', quotechar='\"'):\n self.input_filename = input_filename\n self.occupation_output_filename = occupation_output_filename\n self.state_output_filename = state_output_filename\n self.delimiter = delimiter\n self.quotechar = quotechar\n \n def compute_counts(self, certified_value='CERTIFIED', status='STATUS', soc_col='SOC_NAME', \n state_col='WORKSITE_STATE', state_col2='WORKLOC1_STATE'):\n \"\"\"\n Computes counts for desired column field based on column names \n Args:\n certified_value (str): status to subset data -- default (CERTIFIED)\n status (str): Status column name -- default (STATUS)\n soc_col (str): Standard Occupational Classification column name -- default (SOC_NAME)\n state_col (str): State column name -- default (EMPLOYER_STATE)\n Returns:\n counts (dict): dictionary of {desired_col : count}\n N (int): total number of certified applications regardless of occupation\n \"\"\"\n # initialize dicts \n occupation_counts = {}\n state_counts = {}\n with open(self.input_filename, 'r') as f:\n # read file \n lines = csv.reader(f, quotechar=self.quotechar, delimiter=self.delimiter,\n quoting=csv.QUOTE_ALL)\n # get column names\n columns = next(lines)\n # need atleast three columns\n assert len(columns) >= 3\n # get indicies \n status_index, occ_index, state_index = self._get_indices(columns, status=status, soc_col=soc_col, \n state_col=state_col, state_col2=state_col2)\n # get total number of certified applications regardless of occupation\n N = 0\n for line in lines:\n # print(line)\n # only if status == CERTIFIED\n if line[status_index].lower() == certified_value.lower():\n occ = line[occ_index]\n state = line[state_index]\n N += 1\n # remove missing values \n if occ:\n # increment count based on occupation\n if occ not in occupation_counts:\n occupation_counts[occ] = 0\n occupation_counts[occ] += 1\n # remove missing values \n if state:\n # increment count based on state\n if state not in state_counts:\n state_counts[state] = 0\n state_counts[state] += 1\n \n # return count dicts and total number of certified applications regardless of occupation\n return occupation_counts, state_counts, N\n\n def check_if_included(self, split_col, desired_col):\n \"\"\"Check if all values are included in split column\"\"\"\n return all(col.lower() in split_col for col in desired_col.split('_'))\n\n def _get_indices(self, header_columns, status, soc_col, state_col, state_col2):\n \"\"\"\n return indices value of status, occupation and state columns\n \"\"\"\n try:\n # loop through all column names \n for i, split_col in enumerate(header_columns):\n split_col = split_col.lower()\n # get status column index \n if status.lower() in split_col:\n status_index = i\n # get occupation column index \n if self.check_if_included(split_col, soc_col):\n occ_index = i\n # get state column index \n for val in [state_col, state_col2]:\n if self.check_if_included(split_col, val):\n state_index = i\n\n return status_index, occ_index, state_index\n # handle exception\n except UnboundLocalError as e:\n raise Exception('COLUMN NAME NOT FOUND. PLEASE PASS IN {}'.format(str(e)))\n except IndexError:\n raise Exception('COLUMN NAMES NOT FOUND. PLEASE CHECK COLUMN NAMES')\n\n def write_to_file(self, top, filename, col2='NUMBER_CERTIFIED_APPLICATIONS', col3='PERCENTAGE'):\n \"\"\"\n Saves output to output_filename\n Args:\n top (list): top N list of tuples [(desired_col, counts), ...]\n filename (str): filepath where to save output \n col2 (str): Name of counts column \n col3 (str): Name of percentage column\n \"\"\"\n # get column nam from passed in output file name \n name = filename.split('_')[-1].split('.')[0].upper()\n with open(filename, 'w') as f:\n # write column names\n f.write('TOP_{}'.format(name) + self.delimiter + \\\n col2 + self.delimiter + col3 + '\\n')\n # write data \n for line in top:\n line = self.delimiter.join(map(str, line))\n f.write(line + '\\n')\n \n","sub_path":"src/top_counts.py","file_name":"top_counts.py","file_ext":"py","file_size_in_byte":5976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"357050994","text":"import sys\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtWidgets import QDialog, QApplication, QFileDialog\nfrom PyQt5.uic import loadUi\nimport glob\nimport os\nfrom itertools import cycle\nfrom RegionA import Pretreatement,execution,combineMLOCC\nimport cv2\na = 0\nimages = []\nfiles = []\ni = 0\nn = 0\n\nclass Cancer(QDialog):\n def __init__(self):\n super(Cancer, self).__init__()\n loadUi('Windows/Cancer_result.ui', self)\n self.Load.clicked.connect(self.close)\n self.Save.clicked.connect(self.close)\n\nclass Normal(QDialog):\n def __init__(self):\n super(Normal, self).__init__()\n loadUi('Windows/Normal_result.ui', self)\n self.Load.clicked.connect(self.close)\n self.Save.clicked.connect(self.close)\n\nclass CancerRight(QDialog):\n def __init__(self):\n super(CancerRight, self).__init__()\n loadUi('Windows/Cancer_result1.ui', self)\n self.Next.clicked.connect(self.close)\n self.Save.clicked.connect(self.close)\n\n\nclass NormalRight(QDialog):\n def __init__(self):\n super(NormalRight, self).__init__()\n loadUi('Windows/Normal_result1.ui', self)\n self.Next.clicked.connect(self.close)\n self.Save.clicked.connect(self.close)\n\nclass Filters(QDialog):\n def __init__(self):\n super(Filters, self).__init__()\n loadUi('Windows/F.ui', self)\n global i\n i = 1\n self.RightSwitch.clicked.connect(self.RightImage)\n self.LeftSwitch.clicked.connect(self.LeftImage)\n self.comboBox.activated.connect(self.Filter)\n self.comboBox_2.activated.connect(self.decision)\n self.comboBox_3.activated.connect(self.Combination)\n self.result.clicked.connect(self.Process)\n\n def Process(self):\n global n \n filter = str(self.comboBox.currentText())\n regle = str(self.comboBox_2.currentText())\n decision = str(self.comboBox_3.currentText())\n age = int(self.age.text())\n # regle : 0 conjonctive, 1 disjonctive, 2 hybride, 3 pcr, 4 yager.\n # decision : 0 bel , 1 pl, 2 pi\n\n if filter == \"Matrix 3*3\":\n f = 0\n elif filter == \"Matrix 5*5\":\n f = 1\n elif filter == \"Matrix 7*7\":\n f = 2\n \n if regle == \"Dempster Shafter\":\n r = 0\n elif regle == \"Yager\":\n r = 4\n elif regle == \"Disjunctive\":\n r = 1\n elif regle == \"Dubois Parade\":\n r = 2\n elif regle == \"PRC5\":\n r = 3\n\n if decision == \"Optimist\":\n d = 1\n elif decision == \"Pessimist\":\n d = 0\n elif decision == \"Pignistic\":\n d = 2\n\n CC_Right = execution(images[0].image, images[0].type, r, d)\n MLO_Right = execution(images[1].image, images[1].type, r, d)\n CC_Left = execution(images[2].image, images[2].type, r, d)\n MLO_Left = execution(images[3].image, images[3].type, r, d)\n\n # img = cv2.imread(files[0])\n # img = cv2.equalizeHist(img)\n # img1 = cv2.imread(files[1])\n # img1 = cv2.equalizeHist(img1)\n # img2 = cv2.imread(files[2])\n # img2 = cv2.equalizeHist(img2)\n # img3 = cv2.imread(files[3])\n # img3 = cv2.equalizeHist(img3)\n\n # print(img = images[0].image)\n # print(img1 =images[1].image)\n # print(img2 =images[2].image)\n # print(img3 =images[3].image)\n\n print(MLO_Right[1])\n print(CC_Right[1]) \n print(MLO_Left[1])\n print(CC_Left[1])\n\n print(MLO_Right[1]['M'])\n \n result_right = combineMLOCC(MLO_Right[1], CC_Right[1], age, r, d)\n result_left = combineMLOCC(MLO_Left[1], CC_Left[1], age, r, d)\n\n W_FILTERS.hide()\n\n # files.append(os.getcwd() + \"/RIGHT_CC.jpg\")\n # files.append(os.getcwd() + \"/LEFT_CC.jpg\")\n # files.append(os.getcwd() + \"/RIGHT_MLO.jpg\")\n # files.append(os.getcwd() + \"/LEFT_MLO.jpg\")\n\n print(result_right)\n print(result_left)\n\n if(result_right == frozenset({'M'})):\n if(MLO_Right[1]['M'] > CC_Right[1]['M']):\n url = files[2]\n else: \n url = files[0]\n \n W_CANCER.ImageVAR.setStyleSheet(\"border-image : url(\" + url + \");\")\n W_CANCER.show()\n \n else:\n W_NORMAL.show()\n\n # while(W_CANCER.isVisible() or W_NORMAL.isVisible()):\n # n = n + 1\n\n if(result_left == frozenset({'M'})):\n if(MLO_Left[1]['M'] > CC_Left[1]['M']):\n url = files[3]\n else: \n url = files[1]\n \n W1_CANCER.ImageVAR.setStyleSheet(\"border-image : url(\" + url + \");\")\n W1_CANCER.show()\n else:\n W1_NORMAL.show()\n\n\n def Filter(self): \n self.Activation()\n\n def decision(self): \n self.Activation()\n\n def Combination(self):\n self.Activation()\n\n def Activation(self):\n if(str(self.comboBox.currentText()) != \"None\" and str(self.comboBox_2.currentText()) != \"None\" and str(self.comboBox_3.currentText()) != \"None\"):\n self.result.setEnabled(True)\n else: \n self.result.setEnabled(False)\n\n def RightImage(self):\n self.PreviewVar.setStyleSheet(\"border-image : url(\" + self.NextIm() + \");\")\n \n def LeftImage(self):\n self.PreviewVar.setStyleSheet(\"border-image : url(\" + self.PrevIm() + \");\")\n\n def NextIm(self):\n global i \n if(i < len(files) - 1):\n i = i + 1\n else: i = 0\n return files[i]\n\n def PrevIm(self):\n global i \n if(i < 1):\n i = len(files) - 1\n else: i = i - 1\n print(images[i].type)\n return files[i]\n\n\nclass Save(QDialog):\n def __init__(self):\n super(Save,self).__init__()\n loadUi(\"Windows/Import_Images_CC.ui\",self)\n self.RightImport.clicked.connect(self.browsefilesRight)\n self.LeftImport.clicked.connect(self.browsefilesLeft)\n self.ValidateVar.clicked.connect(self.NextActivate)\n self.CancelVar.clicked.connect(self.close)\n \n\n \n ##Esc poses a problem, path gets removed and validate is active\n \n def browsefilesRight(self):\n global a\n fname=QFileDialog.getOpenFileName(self, 'Open file', '/home/hichemhero/Desktop/pyds/opencv/MainPfe', 'Images (*.png, *.xmp *.jpg)')\n self.RightPathPreview.setText(fname[0])\n self.Activation()\n\n\n def browsefilesLeft(self):\n global a\n fname=QFileDialog.getOpenFileName(self, 'Open file', '/home/hichemhero/Desktop/pyds/opencv/MainPfe', 'Images (*.png, *.xmp *.jpg)')\n self.LeftPathPreview.setText(fname[0])\n self.Activation()\n \n def Activation(self):\n global a\n if self.RightPathPreview.toPlainText() != \"\" and self.LeftPathPreview.toPlainText() != \"\" :\n self.ValidateVar.setEnabled(True)\n \n else: \n self.ValidateVar.setEnabled(False)\n \n def NextActivate(self):\n self.ImageLoad()\n if(W_LOAD_CC.ValidateVar.isEnabled() and W_LOAD_MLO.ValidateVar.isEnabled()):\n CC_WINDOW.Next.setEnabled(True)\n MLO_WINDOW.Next.setEnabled(True)\n else:\n CC_WINDOW.Next.setEnabled(False)\n MLO_WINDOW.Next.setEnabled(False)\n self.hide()\n \n def ImageLoad(self):\n b = self.RightPathPreview.toPlainText()\n c = self.LeftPathPreview.toPlainText()\n \n if(self == W_LOAD_CC):\n CC_WINDOW.RightImage.setStyleSheet(\"border-image : url(\" + b + \");\")\n CC_WINDOW.LeftImage.setStyleSheet(\"border-image : url(\" + c + \");\")\n else:\n MLO_WINDOW.RightImage.setStyleSheet(\"border-image : url(\" + b + \");\")\n MLO_WINDOW.LeftImage.setStyleSheet(\"border-image : url(\" + c + \");\")\n\nclass ImageInfo():\n def __init__(self, url, type, ):\n self.url = \"Temp/\" +url\n #check if this imread is working\n self.image = cv2.imread(url, 0)\n self.type = type\n\n\nclass MainCC(QtWidgets.QMainWindow):\n def __init__(self):\n super(MainCC, self).__init__()\n loadUi('Windows/CC.ui', self)\n self.Import.clicked.connect(self.ImportImagesCC)\n self.MLOSwitch.clicked.connect(self.Switch)\n self.Next.clicked.connect(self.NextSwitch)\n \n \n def Switch(self):\n CC_WINDOW.hide()\n MLO_WINDOW.show()\n\n def ImportImagesCC(self):\n W_LOAD_CC.show()\n\n def NextSwitch(self):\n global files,images\n \n Right_CC = ImageInfo(W_LOAD_CC.RightPathPreview.toPlainText(), \"RIGHT_CC\")\n Left_CC = ImageInfo(W_LOAD_CC.LeftPathPreview.toPlainText(), \"LEFT_CC\")\n Right_MLO = ImageInfo(W_LOAD_MLO.RightPathPreview.toPlainText(),\"RIGHT_MLO\")\n Left_MLO = ImageInfo(W_LOAD_MLO.LeftPathPreview.toPlainText(), \"LEFT_MLO\")\n\n #check if these images are loading\n Right_CC.image = Pretreatement(Right_CC.image, Right_CC.type)\n Left_CC.image = Pretreatement(Left_CC.image, Left_CC.type)\n Right_MLO.image = Pretreatement(Right_MLO.image, Right_MLO.type)\n Left_MLO.image = Pretreatement(Left_MLO.image, Left_MLO.type)\n\n files.append(os.getcwd() + \"/Temp/RIGHT_CC.jpg\")\n files.append(os.getcwd() + \"/Temp/RIGHT_MLO.jpg\")\n files.append(os.getcwd() + \"/Temp/LEFT_CC.jpg\")\n files.append(os.getcwd() + \"/Temp/LEFT_MLO.jpg\")\n\n images.append(Right_CC)\n images.append(Right_MLO)\n images.append(Left_CC)\n images.append(Left_MLO)\n\n #border image works with url, need to find a way to put images[0] directly without url\n W_FILTERS.PreviewVar.setStyleSheet(\"border-image : url(\" + files[0] + \");\")\n CC_WINDOW.hide()\n W_FILTERS.show()\n\n\nclass MainMLO(QtWidgets.QMainWindow):\n def __init__(self):\n super(MainMLO, self).__init__()\n loadUi('Windows/MLO.ui', self)\n self.Import.clicked.connect(self.ImportImagesMLO)\n self.CCImages.clicked.connect(self.Switch)\n self.Next.clicked.connect(self.NextSwitch)\n\n def Switch(self):\n MLO_WINDOW.hide()\n CC_WINDOW.show()\n\n def ImportImagesMLO(self):\n W_LOAD_MLO.show()\n\n def NextSwitch(self):\n global files,images\n \n Right_CC = ImageInfo(W_LOAD_CC.RightPathPreview.toPlainText(), \"RIGHT_CC\")\n Left_CC = ImageInfo(W_LOAD_CC.LeftPathPreview.toPlainText(), \"LEFT_CC\")\n Right_MLO = ImageInfo(W_LOAD_MLO.RightPathPreview.toPlainText(),\"RIGHT_MLO\")\n Left_MLO = ImageInfo(W_LOAD_MLO.LeftPathPreview.toPlainText(), \"LEFT_MLO\")\n \n #check if these images are loading\n Right_CC.image = Pretreatement(Right_CC.image, Right_CC.type)\n Left_CC.image = Pretreatement(Left_CC.image, Left_CC.type)\n Right_MLO.image = Pretreatement(Right_MLO.image, Right_MLO.type)\n Left_MLO.image = Pretreatement(Left_MLO.image, Left_MLO.type)\n\n images.append(Right_CC)\n images.append(Right_MLO)\n images.append(Left_CC)\n images.append(Left_MLO)\n\n files.append(os.getcwd() + \"/Temp/RIGHT_CC.jpg\")\n files.append(os.getcwd() + \"/Temp/RIGHT_MLO.jpg\")\n files.append(os.getcwd() + \"/Temp/LEFT_CC.jpg\")\n files.append(os.getcwd() + \"/Temp/LEFT_MLO.jpg\")\n print(files[0])\n\n #border image works with url, need to find a way to put images[0] directly without url\n W_FILTERS.PreviewVar.setStyleSheet(\"border-image : url(\" + files[0] + \");\")\n MLO_WINDOW.hide()\n W_FILTERS.show()\n\n\n\napp = QtWidgets.QApplication(sys.argv)\n\nCC_WINDOW = MainCC()\nW_LOAD_CC = Save()\nMLO_WINDOW = MainMLO()\nW_LOAD_MLO = Save()\nW_FILTERS = Filters()\nW1_CANCER = CancerRight()\nW1_NORMAL = NormalRight()\nW_CANCER = Cancer()\nW_NORMAL = Normal()\n\nCC_WINDOW.show()\n# W_FILTERS.show()\napp.exec_()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"151524747","text":"from pusher_selection.depot import Depot\nfrom pusher_selection.pusher import Pusher\nfrom tkinter import *\nfrom tkinter import ttk\nfrom pandastable import Table\nimport pusher_selection.data as data\n\n\nclass Interface:\n def __init__(self):\n self.depot = Depot()\n self.broken_pusher = Pusher()\n\n # симулируем толкач с адекватными характеристиками\n def simulate_pusher(self):\n self.broken_pusher.type = 'aaa'\n self.broken_pusher.power = 2.\n self.broken_pusher.t_until_service = 70.\n self.broken_pusher.remoteness = 1.\n\n def print_depot(self):\n for index, pusher in enumerate(self.depot.pushers):\n print(index, ' : ', pusher.type)\n\n def replace_pusher(self):\n try:\n new_pusher = self.depot.replace_pusher(self.broken_pusher)\n return new_pusher\n except:\n return \"В депо нет замены для данного токача\"\n\n def main(self, window):\n\n root = window\n root.title(\"Замена толкача\")\n\n # Выравниваем окно по центру экрана\n w = 1000\n h = 200\n ws = root.winfo_screenwidth()\n hs = root.winfo_screenheight()\n x = (ws / 2) - (w / 2)\n y = (hs / 2) - (h / 2)\n root.geometry('%dx%d+%d+%d' % (w, h, x, y))\n\n self.simulate_pusher()\n\n type_lbl = ttk.Label(root, text='Тип толкача:')\n type_lbl.configure(font=1)\n type_lbl.grid(column=0, row=0)\n type_txt = Entry(root, width=7, text=IntVar(value=self.broken_pusher.type))\n type_txt.configure(font=1)\n type_txt.grid(column=1, row=0)\n\n power_lbl = ttk.Label(root, text='Мощность толкача:')\n power_lbl.grid(column=2, row=0)\n power_lbl.configure(font=1)\n power_txt = Entry(root, width=7,\n text=IntVar(value=self.broken_pusher.power))\n power_txt.configure(font=1)\n power_txt.grid(column=3, row=0)\n\n t_until_service_lbl = ttk.Label(root, text='Время до ТО (в часах):')\n t_until_service_lbl.grid(column=4, row=0)\n t_until_service_lbl.configure(font=1)\n t_until_service_txt = Entry(root, width=7,\n text=IntVar(value=self.broken_pusher.t_until_service))\n t_until_service_txt.configure(font=1)\n t_until_service_txt.grid(column=5, row=0)\n\n remoteness_lbl = ttk.Label(root, text='Удаленность от точки толкания (в км):')\n remoteness_lbl.grid(column=0, row=1)\n remoteness_lbl.configure(font=1)\n remoteness_txt = Entry(root, width=7, text=IntVar(value=self.broken_pusher.remoteness))\n remoteness_txt.configure(font=1)\n remoteness_txt.grid(column=1, row=1)\n\n employment_lbl = ttk.Label(root, text='Занятость толкача (истинность):')\n employment_lbl.grid(column=2, row=1)\n employment_lbl.configure(font=1)\n employment_txt = Entry(root, width=7,\n text=IntVar(value=self.broken_pusher.employment))\n employment_txt.configure(font=1)\n employment_txt.grid(column=3, row=1)\n\n def btn_click():\n self.broken_pusher.type = str(type_txt.get())\n self.broken_pusher.power = float(power_txt.get())\n self.broken_pusher.remoteness = float(remoteness_txt.get())\n self.broken_pusher.t_until_service = float(t_until_service_txt.get())\n self.broken_pusher.employment = bool(employment_txt.get())\n\n # заполняем депо\n self.depot.fill_depot()\n\n dataframe = data.get_data(self.replace_pusher())\n\n new_window = Toplevel(root)\n frame = Frame(new_window)\n frame.pack(fill='both', expand=True)\n\n pt = Table(frame, dataframe=dataframe)\n pt.show()\n\n btn = Button(root, text=\"Заменить толкач\", command=btn_click)\n btn.configure(font=1)\n btn.grid(column=2, row=3)\n\n root.mainloop()\n","sub_path":"pusher_selection/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":4170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"644074859","text":"def setUp(self):\n import os\n ov_binany_path=os.environ['OV_BINARY_PATH']\n self.terminal = App.open(\"xterm -e \" + ov_binany_path +\"/openvibe-designer.sh --no-session-management\")\n while not self.terminal.window():\n wait(1)\n wait(\"StartInterface.png\",100)\n\ndef test_boxSetAttributes(self):\n click(\"SearchBoxBar.png\")\n paste(\"sinus\")\n wait(3)\n dragDrop(\"Sinusoscilla-1.png\",Pattern(\"DesignerDataGenOpen.png\").similar(0.40).targetOffset(-233,-163))\n rightClick(\"SinusOscillatorBoxSelected.png\")\n click(Pattern(\"contextualBoxMenu.png\").targetOffset(-51,16))\n assert(exists(\"renameBoxPopUp.png\"))\n type(\"XXXX XXXX XXXX\"+ Key.ENTER)\n assert(exists(Pattern(\"SinusOscillatorNewNameXXX.png\").similar(0.50)))\n \ndef tearDown(self):\n mouseMove(Location(0,0))\n App.close(self.terminal)\n self.terminal= None\n wait(2)\n\n","sub_path":"applications/platform/designer/test/testBoxSetAttribute.UNIX.sikuli/testBoxSetAttribute.UNIX.py","file_name":"testBoxSetAttribute.UNIX.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"555822743","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport numpy as np\nimport scipy.misc\nimport time\nimport os\nimport glob\nimport cv2\n\n\n\ndef imread(path, is_grayscale=True):\n if is_grayscale:\n return scipy.misc.imread(path, flatten=True, mode='YCbCr').astype(np.float)\n else:\n return scipy.misc.imread(path, mode='YCbCr').astype(np.float)\n\ndef imsave(image, path):\n return scipy.misc.imsave(path, image)\n \n \ndef prepare_data(dataset):\n data_dir = os.path.join(os.sep, (os.path.join(os.getcwd(), dataset)))\n data = glob.glob(os.path.join(data_dir, \"*.jpg\"))\n data.extend(glob.glob(os.path.join(data_dir, \"*.bmp\")))\n data.sort(key=lambda x:int(x[len(data_dir)+1:-4]))\n return data\n\ndef lrelu(x, leak=0.2):\n return tf.maximum(x, leak * x)\n\ndef fusion_model(img_ir,img_vi):\n with tf.variable_scope('fusion_model'):\n #################### Layer1 ###########################\n with tf.variable_scope('layer1_ir'):\n weights=tf.get_variable(\"w1_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer1_ir/w1_ir')))\n bias=tf.get_variable(\"b1_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer1_ir/b1_ir')))\n conv1_ir= tf.nn.conv2d(img_ir, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv1_ir = lrelu(conv1_ir) \n with tf.variable_scope('layer1_vi'):\n weights=tf.get_variable(\"w1_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer1_vi/w1_vi')))\n bias=tf.get_variable(\"b1_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer1_vi/b1_vi')))\n conv1_vi= tf.nn.conv2d(img_vi, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv1_vi = lrelu(conv1_vi) \n \n#################### Layer2 ########################### \n with tf.variable_scope('layer2_ir'):\n weights=tf.get_variable(\"w2_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer2_ir/w2_ir')))\n bias=tf.get_variable(\"b2_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer2_ir/b2_ir')))\n conv2_ir= tf.nn.conv2d(conv1_ir, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv2_ir = lrelu(conv2_ir) \n \n with tf.variable_scope('layer2_vi'):\n weights=tf.get_variable(\"w2_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer2_vi/w2_vi')))\n bias=tf.get_variable(\"b2_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer2_vi/b2_vi')))\n conv2_vi= tf.nn.conv2d(conv1_vi, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv2_vi = lrelu(conv2_vi) \n \n#################### Layer3 ########################### \n conv_12_ir=tf.concat([conv1_ir,conv2_ir],axis=-1)\n conv_12_vi=tf.concat([conv1_vi,conv2_vi],axis=-1) \n \n with tf.variable_scope('layer3_ir'):\n weights=tf.get_variable(\"w3_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer3_ir/w3_ir')))\n bias=tf.get_variable(\"b3_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer3_ir/b3_ir')))\n conv3_ir= tf.nn.conv2d(conv_12_ir, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv3_ir =lrelu(conv3_ir)\n with tf.variable_scope('layer3_vi'):\n weights=tf.get_variable(\"w3_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer3_vi/w3_vi')))\n bias=tf.get_variable(\"b3_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer3_vi/b3_vi')))\n conv3_vi= tf.nn.conv2d(conv_12_vi, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv3_vi = lrelu(conv3_vi)\n \n\n#################### Layer4 ########################### \n conv_123_ir=tf.concat([conv1_ir,conv2_ir,conv3_ir],axis=-1)\n conv_123_vi=tf.concat([conv1_vi,conv2_vi,conv3_vi],axis=-1) \n \n with tf.variable_scope('layer4_ir'):\n weights=tf.get_variable(\"w4_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer4_ir/w4_ir')))\n bias=tf.get_variable(\"b4_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer4_ir/b4_ir')))\n conv4_ir= tf.nn.conv2d(conv_123_ir, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv4_ir = lrelu(conv4_ir)\n with tf.variable_scope('layer4_vi'):\n weights=tf.get_variable(\"w4_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer4_vi/w4_vi')))\n bias=tf.get_variable(\"b4_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer4_vi/b4_vi')))\n conv4_vi= tf.nn.conv2d(conv_123_vi, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv4_vi = lrelu(conv4_vi)\n \n \n conv_ir_vi =tf.concat([conv1_ir,conv1_vi,conv2_ir,conv2_vi,conv3_ir,conv3_vi,conv4_ir,conv4_vi],axis=-1)\n \n#################### Layer5 ########################### \n with tf.variable_scope('layer5_fuse'):\n weights=tf.get_variable(\"w5_fuse\",initializer=tf.constant(reader.get_tensor('fusion_model/layer5_fuse/w5_fuse')))\n bias=tf.get_variable(\"b5_fuse\",initializer=tf.constant(reader.get_tensor('fusion_model/layer5_fuse/b5_fuse')))\n conv5_fuse= tf.nn.conv2d(conv_ir_vi, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv5_fuse=tf.nn.tanh(conv5_fuse)\n \n#################### Layer6 ########################### \n with tf.variable_scope('layer6_sept'):\n weights=tf.get_variable(\"w6_sept\",initializer=tf.constant(reader.get_tensor('fusion_model/layer6_sept/w6_sept')))\n bias=tf.get_variable(\"b6_sept\",initializer=tf.constant(reader.get_tensor('fusion_model/layer6_sept/b6_sept')))\n conv6_sept= tf.nn.conv2d(conv5_fuse, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv6_sept=lrelu(conv6_sept)\n \n#################### Layer7 ########################### \n with tf.variable_scope('layer7_ir'):\n weights=tf.get_variable(\"w7_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer7_ir/w7_ir')))\n bias=tf.get_variable(\"b7_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer7_ir/b7_ir')))\n conv7_ir= tf.nn.conv2d(conv6_sept, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv7_ir = lrelu(conv7_ir) \n \n with tf.variable_scope('layer7_vi'):\n weights=tf.get_variable(\"w7_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer7_vi/w7_vi')))\n bias=tf.get_variable(\"b7_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer7_vi/b7_vi')))\n conv7_vi= tf.nn.conv2d(conv6_sept, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv7_vi = lrelu(conv7_vi) \n\n#################### Layer8 ########################### \n with tf.variable_scope('layer8_ir'):\n weights=tf.get_variable(\"w8_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer8_ir/w8_ir')))\n bias=tf.get_variable(\"b8_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer8_ir/b8_ir')))\n conv8_ir= tf.nn.conv2d(conv7_ir, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv8_ir = lrelu(conv8_ir) \n \n with tf.variable_scope('layer8_vi'):\n weights=tf.get_variable(\"w8_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer8_vi/w8_vi')))\n bias=tf.get_variable(\"b8_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer8_vi/b8_vi')))\n conv8_vi= tf.nn.conv2d(conv7_vi, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv8_vi = lrelu(conv8_vi)\n \n#################### Layer9 ########################### \n with tf.variable_scope('layer9_ir'):\n weights=tf.get_variable(\"w9_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer9_ir/w9_ir')))\n bias=tf.get_variable(\"b9_ir\",initializer=tf.constant(reader.get_tensor('fusion_model/layer9_ir/b9_ir')))\n conv9_ir = tf.nn.conv2d(conv8_ir, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv9_ir = tf.nn.tanh(conv9_ir) \n \n with tf.variable_scope('layer9_vi'):\n weights=tf.get_variable(\"w9_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer9_vi/w9_vi')))\n bias=tf.get_variable(\"b9_vi\",initializer=tf.constant(reader.get_tensor('fusion_model/layer9_vi/b9_vi')))\n conv9_vi= tf.nn.conv2d(conv8_vi, weights, strides=[1,1,1,1], padding='SAME') + bias\n conv9_vi = tf.nn.tanh(conv9_vi) \n \n return conv5_fuse,conv9_ir,conv9_vi\n \n\ndef input_setup(index):\n padding=0\n sub_ir_sequence = []\n sub_vi_sequence = []\n input_ir=(imread(data_ir[index])-127.5)/127.5\n input_ir=np.lib.pad(input_ir,((padding,padding),(padding,padding)),'edge')\n w,h=input_ir.shape\n input_ir=input_ir.reshape([w,h,1])\n input_vi=(imread(data_vi[index])-127.5)/127.5\n input_vi=np.lib.pad(input_vi,((padding,padding),(padding,padding)),'edge')\n w,h=input_vi.shape\n input_vi=input_vi.reshape([w,h,1])\n sub_ir_sequence.append(input_ir)\n sub_vi_sequence.append(input_vi)\n train_data_ir= np.asarray(sub_ir_sequence)\n train_data_vi= np.asarray(sub_vi_sequence)\n return train_data_ir,train_data_vi\n\nfor idx_num in range(19,20):\n num_epoch=idx_num\n while(num_epoch==idx_num):\n \n reader = tf.train.NewCheckpointReader('./checkpoint/MFF.model-'+ str(num_epoch))\n \n with tf.name_scope('IR_input'):\n images_ir = tf.placeholder(tf.float32, [1,None,None,None], name='images_ir')\n with tf.name_scope('VI_input'):\n images_vi = tf.placeholder(tf.float32, [1,None,None,None], name='images_vi')\n\n with tf.name_scope('input'):\n input_image_ir =images_ir\n input_image_vi =images_vi\n \n with tf.name_scope('fusion'):\n fusion_image,sept_ir,sept_vi=fusion_model(input_image_ir,input_image_vi)\n \n \n with tf.Session() as sess:\n init_op=tf.global_variables_initializer()\n sess.run(init_op)\n data_ir=prepare_data('Test_near')\n data_vi=prepare_data('Test_far')\n for i in range(len(data_ir)):\n train_data_ir,train_data_vi=input_setup(i)\n start=time.time()\n result =sess.run(fusion_image,feed_dict={images_ir: train_data_ir,images_vi: train_data_vi})\n result=result*127.5+127.5\n result = result.squeeze()\n end=time.time()\n image_path = os.path.join(os.getcwd(), 'result','epoch'+str(num_epoch))\n if not os.path.exists(image_path):\n os.makedirs(image_path)\n image_path = os.path.join(image_path,str(i+1)+\".png\")\n imsave(result, image_path)\n print(\"Testing [%d] success,Testing time is [%f]\"%(i,end-start))\n tf.reset_default_graph()\n num_epoch=num_epoch+1\n","sub_path":"Multi_focus/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":11212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"99774153","text":"import numpy as np\n\n\ndef calc_x_pos(a, b, c, d, kx):\n diff = ((a+d)-(b+c))\n total = (a+b+c+d)\n x = kx*(diff/total)\n return x\n\n\ndef calc_y_pos(a, b, c, d, ky):\n diff = ((a+b)-(c+d))\n total = (a+b+c+d)\n y = ky*(diff/total)\n return y\n\n\ndef multiply_list(lst, multiple):\n output = []\n for val in lst:\n output.append(val * multiple)\n return output\n\n\ndef add_list(lst, additional):\n output = []\n for val in lst:\n output.append(val + additional)\n return output\n\n\ndef quarter_round(x):\n return round(x * 4) / 4\n\n\ndef convert_attenuation_settings_to_abcd(starting_attenuations, map_atten_bpm,\n a_atten_readback, b_atten_readback, c_atten_readback, d_atten_readback):\n a_applied_adj = starting_attenuations[map_atten_bpm['A'] - 1] - a_atten_readback\n b_applied_adj = starting_attenuations[map_atten_bpm['B'] - 1] - b_atten_readback\n c_applied_adj = starting_attenuations[map_atten_bpm['C'] - 1] - c_atten_readback\n d_applied_adj = starting_attenuations[map_atten_bpm['D'] - 1] - d_atten_readback\n a_applied = np.sqrt(50 * 0.25 * 10 ** a_applied_adj)\n b_applied = np.sqrt(50 * 0.25 * 10 ** b_applied_adj)\n c_applied = np.sqrt(50 * 0.25 * 10 ** c_applied_adj)\n d_applied = np.sqrt(50 * 0.25 * 10 ** d_applied_adj)\n return a_applied, b_applied, c_applied, d_applied\n\n\ndef round_to_2sf(input_vals):\n if type(input_vals) is list:\n output = []\n for num in input_vals:\n output.append(round(num * 100.) / 100.)\n else:\n output = round(input_vals * 100.) / 100.\n\n return output\n\n\ndef change_to_freq_domain(times, data):\n f_data = np.fft.fft(data)\n f_data_mag = []\n for f_sample in f_data:\n f_data_mag.append(abs(f_sample))\n\n sample_spacing = []\n for nd in range(len(times) - 2):\n sample_spacing.append(times[nd + 1] - times[nd])\n sample_spacing = np.mean(sample_spacing)\n f_freq = list(np.fft.fftfreq(len(times), sample_spacing))\n return f_freq, f_data_mag\n\n\ndef get_stats(data):\n data_mean = np.mean(data)\n data_std = np.std(data)\n data_max = max(data)\n data_min = min(data)\n return data_mean, data_std, data_max, data_min\n\n\ndef subtract_mean(data, mean_value):\n if data is list:\n output = []\n for val in data:\n output.append(val - mean_value)\n else:\n output = data - mean_value\n\n return output\n\n\ndef stat_dataset(dataset):\n mean_list = []\n std_list = []\n for single_set in dataset:\n mean_tmp, std_tmp, _2, _3 = get_stats(single_set)\n mean_list.append(mean_tmp)\n std_list.append(std_tmp)\n return mean_list, std_list\n\n\ndef reconfigure_adc_data(data):\n data_out = list()\n for num_adc in range(len(data[0])):\n data_out.append([])\n for repeat_point in range(len(data)):\n for num_adc in range(len(data[repeat_point])):\n data_out[num_adc].extend(data[repeat_point][num_adc])\n return data_out\n\n\ndef adc_missing_bit_analysis(data, n_bits):\n # First convert the int value into a binary string.\n # Turn that string into a list of values.\n # This should be bpm_object.adc_n_bits in size. However if this is not 16 there is a broadcast error.\n # This is because the epics layer always returns a 16 bit number.\n # For now set to 16. The upper extra bits will be ignored in the later processing anyway.\n format_string = '0%db' % 16 # bpm_object.adc_n_bits\n data_bits = [list(format(int(x), format_string)) for x in data]\n\n # Calculating the standard deviation of each bit location.\n data_bits_std = []\n # for kw in range(test_system_object.BPM.num_adcs):\n # data_std.append([])\n for wn in range(n_bits):\n temp = []\n for en in range(len(data)):\n temp.append(int(data_bits[en][wn]))\n\n data_bits_std.append(np.std(temp))\n\n return data_bits_std\n\n\ndef sa_data_to_dict(sa_a_times, sa_a_data, sa_b_times, sa_b_data, sa_c_times, sa_c_data, sa_d_times, sa_d_data):\n data = {'sa_a_times': sa_a_times, 'sa_a_data': sa_a_data, 'sa_b_times': sa_b_times, 'sa_b_data': sa_b_data,\n 'sa_c_times': sa_c_times, 'sa_c_data': sa_c_data, 'sa_d_times': sa_d_times, 'sa_d_data': sa_d_data}\n return data\n","sub_path":"helper_functions/helper_calc_functions.py","file_name":"helper_calc_functions.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"331868307","text":"import discord\nimport asyncio\nimport os\nfrom keep_alive import keep_alive\nfrom discord.ext import commands, tasks\nfrom itertools import cycle\nimport asyncio\nimport time \nimport datetime as DT\nimport random\nfrom discord import channel\n\nbot = commands.Bot(command_prefix='!')\nstatus = cycle([\"py-chat\", \"Globalchat? | py-chat\"])\n\n@bot.event\nasync def on_ready():\n change_status.start()\n print('Logged in as')\n print(bot.user.name)\n print(bot.user.id)\n print(discord.utils.oauth_url(bot.user.id))\n\n@tasks.loop(seconds=120)\nasync def change_status():\n await bot.change_presence(activity=discord.Game(next(status)))\n \n@bot.event\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.MissingRequiredArgument):\n await ctx.send(\"Missing Argument!\")\n if isinstance(error, commands.CommandNotFound):\n await ctx.send(\"Command not Found!\")\n if isinstance(error, commands.MissingPermissions):\n await ctx.send(\"You don´t have Permssions to do that!\")\n if isinstance(error, commands.BotMissingPermissions):\n await ctx.send(\"The Bot hasn`t the missing Permission!\")\n if isinstance(error, commands.NotOwner):\n await ctx.send(\"This Command is only for my Lord!\")\n\n \n@client.event\nasync def on_message(message):\n if message.author.bot: return\n member = message.author\n channel = message.channel\n if channel.name == \"py-chat\":\n msg = message.content\n print(f\"{message.channel}: {message.author}: {message.author.name}: {message.content}\")\n embed = discord.Embed(color=discord.Color.blue(), title=f\"{message.author} | {member.guild}\", description=msg)\n embed.set_thumbnail(url=f\"{member.avatar_url}\")\n embed.set_footer(text=f\"ist auf {len(bot.guilds)} Servern\", icon_url=f\"{member.guild.icon_url}\")\n embed.timestamp = datetime.datetime.utcnow()\n await message.delete()\n for guild in bot.guilds: \n channel:discord.Channel = discord.utils.get(guild.channels, name=\"py-chat\")\n await channel.send(embed=embed)\n \nkeep_alive()\ntoken = os.environ.get(\"DISCORD_BOT_SECRET\") \nbot.run(token)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"330136445","text":"'''\r\nCreated on 27. 8. 2018\r\n\r\n@author: HansFi\r\n'''\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\n\r\nurl= 'https://www.vanityfair.com/style/society/2014/06/monica-lewinsky-humiliation-culture'\r\nr = requests.get(url, verify=False)\r\nr_html = r.text\r\n\r\nsoup = BeautifulSoup(r_html, 'html.parser')\r\ntitles=soup.get_text()\r\nprint (titles)","sub_path":"DecodeAWebPageTwo.py","file_name":"DecodeAWebPageTwo.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"110366417","text":"import dj_database_url\nimport os\nimport sys\n\nfrom .base import *\n\nimport sentry_sdk\nfrom sentry_sdk.integrations.celery import CeleryIntegration\nfrom sentry_sdk.integrations.django import DjangoIntegration\n\n# DATABASE CONFIGURATION\n# -----------------------------------------------------------------------------\n\ndb_from_env = dj_database_url.config(conn_max_age=500)\nDATABASES['default'].update(db_from_env)\n\n\n# GENERAL CONFIGURATION\n# -----------------------------------------------------------------------------\n\nSECRET_KEY = bool(os.environ.get('DJANGO_SECRET_KEY'))\n\n# Honor the 'X-Forwarded-Proto' header for request.is_secure()\nSECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\nALLOWED_HOSTS = ['mitlibraries-solenoid.herokuapp.com',\n 'mitlibraries-solenoid-staging.herokuapp.com']\n\n# This allows us to include review apps in ALLOWED_HOSTS even though we don't\n# know their name until runtime.\nAPP_NAME = os.environ.get('HEROKU_APP_NAME')\nif APP_NAME:\n url = '{}.herokuapp.com'.format(APP_NAME)\n ALLOWED_HOSTS.append(url)\n\n\n# STATIC FILE CONFIGURATION\n# -----------------------------------------------------------------------------\n\nSTATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\nMIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware']\n\nCOMPRESS_ENABLED = True\nCOMPRESS_OFFLINE = True\n\n\n# LOGGING CONFIGURATION\n# -----------------------------------------------------------------------------\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'formatters': {\n 'brief': {\n 'format': ('%(asctime)s %(levelname)s %(name)s[%(funcName)s]: '\n '%(message)s'),\n },\n },\n 'handlers': {\n 'console_info': {\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',\n 'stream': sys.stdout\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['console_info'],\n 'level': 'INFO',\n }\n }\n}\n\n# Will be emailed by the management command about API usage. This is currently\n# set to a Webmoira list.\nADMINS = [('Solenoid Admins', 'solenoid-admins@mit.edu')]\n\n\n# OAUTH CONFIGURATION\n# -----------------------------------------------------------------------------\n\n# Default to requiring login on Heroku servers, but allow this to be turned off\n# via environment variable in case it's useful to have a test server be more\n# freely accessible.\nLOGIN_REQUIRED = boolean(os.environ.get('DJANGO_LOGIN_REQUIRED', True))\n\n\n# QUOTAGUARD CONFIGURATION\n# -----------------------------------------------------------------------------\n\n# The quotaguard docs say there will be a QUOTAGUARD_URL env variable\n# provisioned, but in the wild the observed name of this variable is\n# QUOTAGUARDSTATIC_URL.\nQUOTAGUARD_URL = os.environ.get('QUOTAGUARDSTATIC_URL', None)\n\n\n# EXCEPTION CONFIGURATION\n# -----------------------------------------------------------------------------\n\nsentry_sdk.init(\n dsn=os.environ.get('SENTRY_DSN', None),\n environment=os.environ.get('SENTRY_ENVIRONMENT', 'development'),\n integrations=[CeleryIntegration(), DjangoIntegration()]\n)\n\n\n# DSPACE CUSTOMIZATION CONFIGURATION\n# -----------------------------------------------------------------------------\n\n# Do not substitute a default value on Heroku, this is required in production\nDSPACE_SALT = os.environ['DSPACE_AUTHOR_ID_SALT']\n","sub_path":"solenoid/settings/heroku.py","file_name":"heroku.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"260183131","text":"def listado_alumnos(nombre_archivo):\r\n lista=[]\r\n archivo=open(nombre_archivo)\r\n for linea in archivo:\r\n nombre=linea.strip().split('#')[0]\r\n lista.append(nombre)\r\n archivo.close()\r\n return lista\r\n\r\ndef aprueba_por_notas(nombre_archivo):\r\n diccionario={}\r\n archivo=open(nombre_archivo)\r\n for linea in archivo:\r\n nombre=linea.split('#')[0]\r\n notas=linea.strip().split('#')[1].split(':')\r\n notas=map(int,notas)\r\n promedio=float(sum(notas))/len(notas)\r\n diccionario[nombre]=(promedio>=55)\r\n archivo.close()\r\n return diccionario\r\n\r\ndef aprueba_por_asistencia(nombre_archivo):\r\n diccionario={}\r\n archivo=open(nombre_archivo)\r\n for linea in archivo:\r\n nombre=linea.split('#')[0]\r\n asistencia=linea.strip().split('#')[1].split(':')\r\n porcentaje=(asistencia.count('1')*100)/7\r\n diccionario[nombre]=porcentaje>=75\r\n archivo.close()\r\n return diccionario\r\n\r\ndef resumen(archivo_notas,archivo_asistencia):\r\n final=open('Final.txt','w')\r\n diccionario_notas=aprueba_por_notas(archivo_notas)\r\n diccionario_asistencia=aprueba_por_asistencia(archivo_asistencia)\r\n for nombre in listado_alumnos(archivo_notas):\r\n if diccionario_notas[nombre] and diccionario_asistencia[nombre]:\r\n final.write(nombre+'#APROBADO\\n')\r\n elif diccionario_notas[nombre] or diccionario_asistencia[nombre]:\r\n final.write(nombre+'#EXAMEN GLOBAL\\n')\r\n else:\r\n final.write(nombre+'#REPROBADO\\n')\r\n final.close()\r\n return None\r\n","sub_path":"ejercicios/23 Manejo de archivos/03 - resumen de aprobados/Code/resumen.py","file_name":"resumen.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"431095984","text":"#!/usr/bin/python3\n\nfrom collections import deque\n\nclass BFS:\n\n def __init__(self, source):\n self.nodes = [0, 1, 2, 3, 4]\n self.edges = [(0, 1, 6), (1, 2, 10), (1, 3, 2), (2, 3, 11), (3, 4, 9),\n (2, 4, 3)]\n self.source = source\n # self.nodes = [0, 1, 2]\n # self.edges = [(0, 1, 1), (1, 2, 2), (0, 2, 2)]\n self.distances = []\n self.parent = []\n self.INFINITY = 999\n\n def bfs(self):\n for i in self.nodes:\n self.distances.append(self.INFINITY)\n self.parent.append(-1)\n\n self.distances[self.source] = 0\n\n q = deque()\n\n q.appendleft(self.source)\n\n while q:\n current = q.pop()\n\n for edge in self.edges:\n (u, v, weight) = edge\n\n if (current == u):\n if self.distances[v] == self.INFINITY:\n self.distances[v] = self.distances[u] + 1\n self.parent[v] = u\n q.appendleft(v)\n\n if (current == v):\n if self.distances[u] == self.INFINITY:\n self.distances[u] = self.distances[v] + 1\n self.parent[u] = v\n q.appendleft(u)\n\n\n def setEdges(self, edges):\n self.edges = edges\n\n def setNodes(self, edges):\n self.nodes = nodes\n\n def setSource(self):\n self.distances[self.source] = 0\n\n def getDistances(self):\n return self.distances\n\n\nif __name__ == \"__main__\":\n bfs = BFS(0)\n bfs.bfs()\n\n print(bfs.distances)\n print(bfs.parent)\n","sub_path":"bfs/BFS.py","file_name":"BFS.py","file_ext":"py","file_size_in_byte":1623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"410383606","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\ndef rmv_bad_contours(source,contours):\n\n max_cnt_area = 0\n bad_cnts = []\n rows, cols = img.shape\n bad_mask = np.zeros((rows, cols, 1), np.uint8)\n\n for i in range(np.size(contours) - 1):\n if cv2.contourArea(contours[i]) < cv2.contourArea(contours[i+1]):\n max_cnt_area = i + 1\n\n for i in range(np.size(contours)):\n if cv2.contourArea(contours[i]) < 1:\n bad_cnts.append(i)\n else:\n bad_M = cv2.moments(contours[i])\n bad_cx = int(bad_M['m10']/bad_M['m00'])\n bad_cy = int(bad_M['m01']/bad_M['m00'])\n if cv2.pointPolygonTest(contours[max_cnt_area],(bad_cx,bad_cy),False) < 0:\n bad_cnts.append(i)\n\n bad_mask_inv = cv2.bitwise_not(bad_mask)\n clean = cv2.bitwise_and(source,source,mask=bad_mask_inv)\n\n return clean\n\ndef otsu_threshold(img):\n\n blur = cv2.GaussianBlur(img,(41,41),0)\n _,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n\n return thresh\n\ndef find_edges(img):\n\n edges = cv2.Canny(img,100,200,L2gradient=True)\n\n return edges\n\ndef find_contours(img):\n\n contours, hierarchy = cv2.findContours(\n img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n \n return contours, hierarchy\n\ndef contour_approx(contours):\n\n approx_contours = []\n for i in range(np.size(contours)):\n epsilon = 0.0005*cv2.arcLength(contours[i],True)\n approx = cv2.approxPolyDP(contours[i],epsilon,True)\n approx_contours.append(approx)\n\n return approx_contours\n\ndef draw_contours(source, approx_contours, boundRect, centers, radii, input_width):\n\n lat_R = False\n lat_L = False\n presence = False\n scan_center = None\n\n for i in range(np.size(approx_contours)):\n if (boundRect[i][2] * boundRect[i][3]) < 50 or (boundRect[i][2] * boundRect[i][3]) > 300000:\n M_scan = cv2.moments(approx_contours[i])\n scan_center = int(M_scan['m10']/M_scan['m00'])\n break\n elif boundRect[i][3] > 425:\n M_scan = cv2.moments(approx_contours[i])\n scan_center = int(M_scan['m10']/M_scan['m00'])\n break\n\n for i in range(np.size(approx_contours)):\n if (boundRect[i][2] * boundRect[i][3]) < 50 or (boundRect[i][2] * boundRect[i][3]) > 300000:\n cv2.drawContours(source, approx_contours, i, (255, 255, 255), 4)\n elif boundRect[i][3] > 425:\n cv2.drawContours(source, approx_contours, i, (255, 255, 255), 4)\n elif scan_center != None:\n presence = True\n M = cv2.moments(approx_contours[i])\n cx = int(M['m10']/M['m00'])\n if cx - 50 >= scan_center:\n lat_R = True\n elif cx + 50 <= scan_center:\n lat_L = True\n cv2.drawContours(source, approx_contours, i, (0, 0, 0), 5)\n cv2.drawContours(source, approx_contours, i, (255, 35, 35), 5)\n \n source_rgba = cv2.cvtColor(source,cv2.COLOR_RGB2RGBA)\n \n return source_rgba, presence, lat_R, lat_L\n\ndef find_child_contours(contours, hierarchy):\n\n child_contours = []\n\n for i in range(np.size(contours)):\n if hierarchy[0][i][2] == -1 and i != np.size(contours) - 1 and hierarchy[0][i+1][2] == -1:\n child_contours.append(contours[i])\n \n return child_contours\n\ndef poly_contour_approx(contours):\n\n boundRect = [None]*len(contours)\n centers = [None]*len(contours)\n radii = [None]*len(contours)\n for i, c in enumerate(contours):\n boundRect[i] = cv2.boundingRect(contours[i])\n centers[i], radii[i] = cv2.minEnclosingCircle(contours[i])\n\n return boundRect, centers, radii\n\ndef hemor_detect(file_name):\n\n # Read in the image file and vascular regions image file\n\n img = cv2.imread('in/' + file_name,0)\n vascular_regions = cv2.imread('vascular_labelled.png', -1)\n\n # Process vascular regions image file for addition with output image\n\n vascular_img_height, vascular_img_width, vascular_img_channels = vascular_regions.shape\n\n img_colour = cv2.cvtColor(img,cv2.COLOR_GRAY2RGB)\n img_rgba = cv2.cvtColor(img_colour, cv2.COLOR_RGB2RGBA)\n\n # Scaling images for overlaying vascular regions labelling onto output image\n # First, scaling height of vascular labelling\n\n input_height, input_width, input_channels = img_rgba.shape\n\n if vascular_img_height > input_height:\n vascular_scale = (input_height / vascular_img_height) * 0.925\n elif vascular_img_height < input_height:\n vascular_scale = (vascular_img_height / input_height) * 0.925\n\n scaled_width = int(vascular_regions.shape[1] * vascular_scale)\n scaled_height = int(vascular_regions.shape[0] * vascular_scale)\n dim = (scaled_width, scaled_height)\n\n vascular_regions_scaled = cv2.resize(vascular_regions, dim, interpolation=cv2.INTER_AREA)\n\n vascular_scaled_height, vascular_scaled_width, vascular_scaled_channels = vascular_regions_scaled.shape\n\n # Next, scaling width of vascular labelling\n\n if vascular_scaled_height > input_height:\n vascular_scale_two = (input_height / vascular_scaled_height) * 0.925\n elif vascular_scaled_height < input_height:\n vascular_scale_two = (vascular_scaled_height / input_height) * 0.925\n\n scaled_width_two = int(vascular_regions_scaled.shape[1] * vascular_scale_two)\n scaled_height_two = int(vascular_regions_scaled.shape[0] * vascular_scale_two)\n dim_two = (scaled_width_two, scaled_height_two)\n\n vascular_regions_scaled_two = cv2.resize(\n vascular_regions_scaled, dim_two, interpolation=cv2.INTER_AREA)\n\n vascular_scaled_height_two, vascular_scaled_width_two, vascular_scaled_channels_two = vascular_regions_scaled_two.shape\n\n top_left_x = round((input_width - scaled_width_two) / 2)\n top_left_y = round((input_height - scaled_height_two) / 2)\n\n # Creating vascular labelling overlay\n\n bkg_vascular_img = np.zeros(img_rgba.shape, np.uint8)\n\n bkg_vascular_img[top_left_y:(top_left_y + vascular_scaled_height_two), top_left_x:(\n top_left_x + vascular_scaled_width_two)] = vascular_regions_scaled_two\n\n # Apply Gaussian filtering, then Otsu's thresholding\n\n thresh = otsu_threshold(img)\n\n # Find edges\n\n edges_source = find_edges(thresh)\n edges_contour = edges_source\n\n # Find contours\n\n contours, hierarchy = find_contours(edges_contour)\n\n # Draw skull contours in black, hemorrhage contours in red\n\n approx_contours = contour_approx(contours)\n\n boundRect, centers, radii = poly_contour_approx(approx_contours)\n\n bkg = cv2.cvtColor(np.zeros(edges_contour.shape, np.uint8), cv2.COLOR_GRAY2RGB)\n bkg_vascular_img = cv2.cvtColor(bkg_vascular_img, cv2.COLOR_RGBA2RGB)\n\n final_img_rgba, presence, _, _ = draw_contours(bkg, approx_contours, boundRect, centers, radii, input_width)\n final_img_vascular, presence, lat_R, lat_L = draw_contours(bkg_vascular_img, approx_contours, boundRect, centers, radii, input_width)\n\n # Output contours image, contours image with labelled vascular regions\n\n filename_split = file_name.split('.')\n\n description = open(f'out/{filename_split[0]}_analysis_out.txt', 'x')\n\n if presence == True:\n description.write(\"There is hemorrhaging present in this cranial CT scan.\\n\")\n\n if lat_R == True:\n description.write(\n \"The hemorrhaging is primarily in the right hemisphere of the patient's brain.\\n\")\n elif lat_L == True:\n description.write(\n \"The hemorrhaging is primarily in the left hemisphere of the patient's brain.\\n\")\n elif lat_R == True and lat_L == True:\n description.write(\n \"The hemorrhaging is present in both hemispheres of the patient's brain.\\n\")\n else:\n description.write(\n \"The hemorrhaging is not localized to one or both hemispheres.\\n\")\n\n # Two output images: one with outlined hemorrhaging and one with a vascular region overlay\n \n plt.figure(num='Outlined Hemorrhage Sites with Labelled Vascular Regions')\n plt.imshow(final_img_vascular, cmap='Greys', interpolation='bicubic')\n plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis\n plt.savefig(f'out/{filename_split[0]}__vascular_out.png')\n\n plt.figure(num='Outlined Hemorrhage Sites without Labelled Vascular Regions')\n plt.imshow(final_img_rgba, cmap='Greys', interpolation='bicubic')\n plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis\n plt.savefig(f'out/{filename_split[0]}_out.png')\n\n description.close()\n else:\n description.write(\n \"There is no hemorrhaging present in this cranial CT scan.\\n\")\n plt.figure(num='Edge Detection with no Hemorrhaging')\n plt.imshow(cv2.bitwise_not(edges_contour), cmap='Greys', interpolation='bicubic')\n plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis\n plt.savefig(f'{filename_split[0]}_none.png')\n\n description.close()\n","sub_path":"imorrage_web_old.py","file_name":"imorrage_web_old.py","file_ext":"py","file_size_in_byte":9115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"407105016","text":"class LiczbaZespolona(object):\n atr = [0,0]\n modul = None\n def __add__(self, other):\n pom=LiczbaZespolona()\n pom.atr[0]=self.atr[0]+other.atr[0]\n pom.atr[1]=self.atr[1]+other.atr[1]\n return pom\n def __sub__(self,other):\n pom=LiczbaZespolona()\n pom.atr[0]=self.atr[0]-other.atr[0]\n pom.atr[1]=self.atr[1]-other.atr[1]\n return pom\n def __mul__(self, other):\n pom=LiczbaZespolona()\n pom.atr[0]=self.atr[0]*other.atr[0]-self.atr[1]*other.atr[1]\n pom.atr[1]=self.atr[0]*other.atr[1]+self.atr[1]*other.atr[0]\n return pom\n def __div__(self,other):\n pom1=LiczbaZespolona()\n pom=other.atr[0]*other.atr[0]+other.atr[1]*other.atr[1]\n pom1.atr[0]=(self.atr[0]*other.atr[0]-self.atr[1]*other.atr[1])/pom\n pom1.atr[1]=(self.atr[0]*other.atr[1]+self.atr[1]*other.atr[0])/pom\n return pom1\n def modul(self):\n self.modul=(self.atr[0]**2+self.atr[1]**2)**0.5\n return self.modul\n def __eq__(self,other):\n if self.atr[0]==other.atr[0] and self.atr[1]==other.atr[1]:\n return 1\n else:\n return 0\n def __str__(self):\n return (\"%d + %di\" % (self.atr[0], self.atr[1]))\n\nkrotka=(3,5)\nkrotka2=(2,4)\na=LiczbaZespolona()\na.atr=krotka\nb=LiczbaZespolona()\nb.atr=krotka2\nprint(a+b)\nprint(a==b)\na=b\nprint(a==b)\n","sub_path":"lekcja3/zad1.py","file_name":"zad1.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"12047225","text":"\"\"\"Example of using server-sent events with Flask using gevent.\n\nThis can be run as-is using gevent's built-in WSGI server, or you can\nrun it with gunicorn as follows::\n\n gunicorn -b 127.0.0.1:5000 -k gevent sse:app\n\nIf testing connections with a single browser, keep in mind that the\nbrowser may have a setting to limit the number of persistent\nconnections per server. For example, in Firefox, there is a\n``network.http.max-persistent-connections-per-server`` setting which\ndefaults to 6 (at least on my browser).\n\n\"\"\"\n\nimport gevent\nfrom gevent.pywsgi import WSGIServer\nfrom gevent import monkey\nmonkey.patch_all()\nfrom numpy import random\nfrom flask import Flask, json, Response, render_template\nfrom queue import Queue\nimport threading\n\napp = Flask(__name__)\napp.debug = True\n\nq = Queue()\n\nx = 0\n\ntemp_c = 0\n# Logging temp data\ndef log_temp(name):\n print(\"Starting \" + name)\n while True:\n global temp_c\n temp_c = temp_c + 1\n q.put(temp_c)\n print(\"temp added: \", temp_c)\n gevent.sleep(0.5)\n\nhumidity_c = 0\n# Logging humidity data\ndef log_humidity(name):\n print(\"Starting \" + name)\n while True:\n global humidity_c\n humidity_c = humidity_c + 1000\n q.put(humidity_c)\n print(\"humidity added: \", humidity_c)\n gevent.sleep(0.5)\n\ndef event_stream():\n print(\"Starting streaming\")\n while True:\n result = q.get()\n print(result)\n yield 'data: %s\\n\\n' % str(result)\n gevent.sleep(.5)\n\n@app.route('/')\ndef index():\n print(\"Index requested\")\n return render_template('index.html')\n\n@app.route('/stream/', methods=['GET', 'POST'])\ndef stream():\n # gevent.sleep(1)\n print(\"stream requested/posted\")\n return Response(event_stream(), mimetype=\"text/event-stream\")\n\nif __name__ == \"__main__\":\n # Create two threads as follows\n try:\n th1 = threading.Thread(target=log_temp, args=(\"temp_logger\",))\n th2 = threading.Thread(target=log_humidity, args=(\"humidity_logger\",))\n th1.start()\n th2.start()\n print (\"Thread(s) started..\")\n except:\n print (\"Error: unable to start thread\")\n else:\n WSGIServer(('', 5000), app).serve_forever()\n","sub_path":"sse.py","file_name":"sse.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"526518149","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport ROOT\nfrom root_numpy import fill_hist\nfrom np_variables import *\nfrom benchmark import benchmark_error_dist\nfrom libsignalstudy import *\nfrom jr_np_exts import rmseff\nimport pickle\n\nROOT.gStyle.SetOptStat(0)\nROOT.gROOT.SetBatch()\n\npseudoevent_issignal = get_pseudoevent_issignal()\n\n#proxy_variable = \"cut energy\"\n#proxy_variable = \"clipped energy\"\nproxy_variable = \"ntc over th\"\n\n\nN = 50\nrmseff_zmm = np.zeros(N)\nbias_zmm = np.zeros(N)\nbias_zmm_err = np.zeros(N)\nrmseff_gamma = np.zeros(N)\nbias_gamma = np.zeros(N)\nbias_gamma_err = np.zeros(N)\nrmseff_electron = np.zeros(N)\nbias_electron = np.zeros(N)\nbias_electron_err = np.zeros(N)\n\nmax_bias_space = np.linspace(0.01, 0.25, N)\n\npseduoevent_dicts = get_pseudoevent_dicts()\n\ncolors = ['b', 'k', 'r']\n\nsample_calib = \"ZMM\"\nnpu = 200\n\nv = {\n \"ZMM\": {},\n \"Gamma\": {},\n \"Electron\": {},\n }\n\nvariable_list = [\"energy_high_eta_wafers\", \"tc_data_high_eta_wafers\", \"energy_layers\"]\n\n#zmm_events = -1\nzmm_events = 1000 * 24\n\nprint(\"Reading data...\")\nv[\"ZMM\"][npu] = load_variables(variable_list, \"ZMM\", npu)\nv[\"Gamma\"][0] = load_variables([\"energy_high_eta_wafers\"], \"Gamma\", 0)\nv[\"Gamma\"][npu] = load_variables(variable_list, \"Gamma\", npu)\nv[\"Electron\"][0] = load_variables([\"energy_high_eta_wafers\"], \"Electron\", 0)\nv[\"Electron\"][npu] = load_variables(variable_list, \"Electron\", npu)\n\nfor x in variable_list:\n v[\"ZMM\"][npu][x] = v[\"ZMM\"][npu][x][:,:zmm_events]\n\nsignal_layer = 10 - 1\ndepth = signal_layer + 1 # How deep to go with the extrapolation, plus one for equal weights\n\n# The ranges for the second dimension of x to use for a specific estimate\nx_ranges = {\n \"global\": lambda l: [depth + l],\n \"local\": lambda l: range(l + 1)# + range(2*depth, 2*depth + l + 1)# + [3*depth + l],\n #\"local\": lambda l: [l]# + range(2*depth, 2*depth + l + 1)# + [3*depth + l],\n #\"local\": lambda l: [l, l +1, l+2, l+3, l+4]# + range(2*depth, 2*depth + l + 1)# + [3*depth + l],\n }\n\nv_name = \"tc_data_high_eta_wafers\"\n#v_name = \"energy_high_eta_wafers\"\nv_name_layers = \"energy_layers\"\ne_name = \"energy_high_eta_wafers\"\n\ndef ma(arr, n=5):\n N = len(arr)\n print(np.sum([arr[i:N-(n-(i+1))] for i in range(n)], axis=0) / n)\n return np.sum([arr[i:N-(n-(i+1))] for i in range(n)], axis=0) / n\n #return (arr[1:] + arr[:-1]) / 2.\n #return arr\n\ndef ntc_over_th(arr):\n outarr = np.zeros([arr.shape[0], arr.shape[1]])\n for i in range(arr.shape[0]):\n outarr[i] = np.sum(np.logical_and(arr[i]>=ntc_threshs[i], arr[i]=ntc_threshs[i], axis=-1)\n return outarr\n\ndef clipsum(arr):\n outarr = np.zeros([arr.shape[0], arr.shape[1]])\n for i in range(arr.shape[0]):\n outarr[i] = np.sum(np.clip(arr[i], 0, clips[i]), axis=-1) - clips[i] * np.sum(arr[i]>=clip_cuts[i], axis=-1)\n return outarr\n #return np.sum(np.clip(arr, 0, clip), axis=-1) - clip * np.sum(arr>=cut, axis=-1)\n\ndef truncsum(arr):\n outarr = np.zeros([arr.shape[0], arr.shape[1]])\n for i in range(arr.shape[0]):\n outarr[i] = np.sum(np.clip(arr[i], 0, truncs[i]), axis=-1) - truncs[i] * np.sum(arr[i]>=truncs[i], axis=-1)\n return outarr\n\nif proxy_variable == \"cut energy\":\n v_func = truncsum\nif proxy_variable == \"clipped energy\":\n v_func, legend = clipsum, False\nif proxy_variable == \"ntc over th\":\n v_func, legend = ntc_over_th, False\n\nfor j, max_bias in enumerate(max_bias_space):\n\n if proxy_variable == \"cut energy\":\n N_th = 61\n N_cut = 1\n thresh_space = np.linspace(0, 300, N_th)\n cutoff_space = np.array([10000000])\n elif proxy_variable == \"ntc over th\":\n N_th = 16\n N_cut = 33\n thresh_space = np.linspace(0, 150, N_th)\n cutoff_space = np.linspace(0, 1500, N_cut)\n else:\n N_th = 16\n N_cut = 16\n thresh_space = np.linspace(0, 150, N_th)\n cutoff_space = np.linspace(0, 750, N_cut)\n\n proxy_stats = np.array(pickle.load(open(\"proxy_stats_{}.pkl\".format(proxy_variable.replace(\" \", \"_\")), \"rb\")))\n\n opt_th = np.zeros(10)\n opt_cut = np.zeros(10)\n\n for l in range(10):\n stats_rmseff_nan = proxy_stats[0, l]\n stats_rmseff_nan[np.abs(proxy_stats[1, l]) > max_bias] = np.nan\n\n try:\n minidx = np.nanargmin(stats_rmseff_nan)\n a_th = int(minidx/N_cut)\n a_cut = minidx - a_th * N_cut\n opt_th[l] = thresh_space[a_th]\n opt_cut[l] = cutoff_space[a_cut]\n except:\n opt_th[l] = 0.0\n opt_cut[l] = 0.0\n\n print(max_bias)\n print(opt_th)\n print(opt_cut)\n\n # For the clipsum, granularity was 10 ADC for clip, 50 ADC for cut\n clips = opt_th\n clip_cuts = opt_cut\n\n # For the tc over th, granularity was 10 ADC for thresh, 50 ADC for cut\n ntc_threshs = opt_th\n ntc_cuts = opt_cut\n\n # For the truncsum, granularity was 5 ADC\n truncs = opt_th\n\n # Load the data\n # Save here all the benchmark information on the estimates\n stats, coefs, intercepts = {}, {}, {}\n x, y, y_puonly = {}, {}, {}\n\n e_prev_layers = {} # For the bias extrapolation\n\n print(\"Calibrating and bias determination...\")\n for s in [\"ZMM\", \"Gamma\", \"Electron\"]:\n\n stats[s], coefs[s], intercepts[s] = {}, {}, {}\n y[s] = v[s][npu][e_name][signal_layer]\n\n tmp1 = v_func(v[s][npu][v_name][:depth])\n x[s] = np.vstack([tmp1] +\n [np.sum(v[s][npu][v_name_layers][:l + 1], axis=0) - np.sum(v[s][npu][e_name][:l + 1], axis=0) for l in range(depth)])\n\n if s == 'ZMM':\n y_puonly[s] = y[s]\n\n else:\n\n sel_nopu, sel = get_selections(v[s][0][e_name][signal_layer], pseduoevent_dicts[s][npu], s, th=1.5)\n\n y_puonly[s] = y[s][sel] - v[s][0][e_name][signal_layer][sel_nopu]\n\n x[s] = x[s][:,sel[0]]\n\n for m in [\"local\"]:\n # first index is layer, second is for rms, rmseff and bias and bias error\n stats[s][m] = np.zeros([depth, 4])\n coefs[s][m] = []\n intercepts[s][m] = []\n # Calibrate the best coefficients/intercepts with ZMM\n l = depth - 1\n res = calibrate([np.sum(x[sample_calib][x_ranges[m](l - 1)], axis=0)], y[sample_calib], fit_intercept=False, huber=True)\n coefs[s][m].append(res[0])\n intercepts[s][m].append(res[1])\n\n print(\"Extrapolation\")\n\n delta_extra_gi = {}\n\n for s in [\"ZMM\", \"Gamma\", \"Electron\"]:\n\n print(\"Mean energy depposit in the signal region: {}\".format(np.mean(y_puonly[s])))\n print(\"Standard deviation: {}\".format(np.std(y_puonly[s])))\n\n delta_extra_gi[s] = [None] * depth\n\n i, l = 0, depth - 1\n\n est_extra_gi = extrapolate([np.sum(x[s][x_ranges[\"local\"](l-1)], axis=0)], coefs[s][\"local\"][i], intercepts[s][\"local\"][i])\n delta_extra_gi[s][l] = - y_puonly[s] + est_extra_gi\n stats[s][\"local\"][l] = benchmark_error_dist(delta_extra_gi[s][l])\n\n _, rmseff_zmm[j], bias_zmm[j], bias_zmm_err[j] = stats[\"ZMM\"][\"local\"][l]\n _, rmseff_gamma[j], bias_gamma[j], bias_gamma_err[j] = stats[\"Gamma\"][\"local\"][l]\n _, rmseff_electron[j], bias_electron[j], bias_electron_err[j] = stats[\"Electron\"][\"local\"][l]\n\nplt.figure(figsize=(5,5))\nplt.scatter(max_bias_space, rmseff_zmm, color='b', edgecolors='b', s=1)\nplt.scatter(max_bias_space, rmseff_electron, color='r', edgecolors='r', s=1)\nplt.scatter(max_bias_space, rmseff_gamma, color='k', edgecolors='k', s=1)\nplt.plot(ma(max_bias_space), ma(rmseff_zmm), 'b', label='ZMM')\nplt.plot(ma(max_bias_space), ma(rmseff_electron), 'r', label='Electron')\nplt.plot(ma(max_bias_space), ma(rmseff_gamma), 'k', label='Gamma')\nplt.xlabel(\"Bias by signal requirement [GeV]\")\nplt.ylabel(\"Effective RMS [GeV]\")\nplt.xlim(0, 0.25)\nplt.legend()\nplt.savefig(\"rmseff.pdf\")\n\nplt.figure(figsize=(5,5))\n#plt.errorbar(max_bias_space, bias_zmm, yerr=bias_zmm_err, color='b')\n#plt.errorbar(max_bias_space, bias_electron, yerr=bias_electron_err, color='r')\n#plt.errorbar(max_bias_space, bias_gamma, yerr=bias_gamma_err, color='k')\nplt.scatter(max_bias_space, bias_zmm, color='b', edgecolors='b', s=1)\nplt.scatter(max_bias_space, bias_electron, color='r', edgecolors='r', s=1)\nplt.scatter(max_bias_space, bias_gamma, color='k', edgecolors='k', s=1)\nplt.plot(ma(max_bias_space), ma(bias_zmm), 'b')\nplt.plot(ma(max_bias_space), ma(bias_electron), 'r')\nplt.plot(ma(max_bias_space), ma(bias_gamma), 'k')\nplt.xlabel(\"Bias by signal requirement [GeV]\")\nplt.ylabel(\"Bias [GeV]\")\nplt.xlim(0, 0.25)\nplt.savefig(\"bias.pdf\")\n","sub_path":"python/max_bias_scan.py","file_name":"max_bias_scan.py","file_ext":"py","file_size_in_byte":8774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"605483867","text":"from pprint import pprint as pp\n\nfrom django import template\nfrom django.template.loader import render_to_string\nfrom django.utils.safestring import mark_safe\n\nimport random\nimport string\nfrom wagtail.core.models import Page, PageRevision\n\nregister = template.Library()\n\n@register.simple_tag( takes_context = True )\ndef render_object_in_list(context, obj, tpl):\n if tpl is None:\n tpl = 'rai/views/default/default-list-item.html'\n\n page_revision = None\n if issubclass(obj.__class__, Page):\n page_revision = PageRevision.objects.filter(page = obj).order_by('-created_at').first()\n \n\n return render_to_string(\n tpl,\n {\n 'object' : obj,\n 'last_revision':page_revision, \n 'item_actions' : context['item_actions'],\n 'settings' : context['settings'],\n 'active_action' : context['active_action']\n }\n )\n\n@register.simple_tag \ndef render_setting( obj, key, setting, active_action ):\n sett = active_action.item_provides[key]\n sett['children'] = setting.get('children', [])\n type_ = sett.get('type', 'par')\n classes = []\n if isinstance(type_, list):\n classes = type_\n type_ = type_[0]\n \n field = sett.get('field', None)\n callback = sett.get('callback', None)\n func = sett.get('func', None)\n value ='foo'\n if field:\n value = getattr(obj, field)\n if func:\n fnc = getattr(obj, func)\n value = fnc()\n if callback:\n fnc = getattr(active_action, callback)\n value = fnc(obj)\n\n \n return render_to_string(\n 'rai/views/default/default-list-item/'+str(type_)+'.html',\n {\n 'value' : value,\n 'object' : obj,\n 'active_action': active_action,\n **sett\n }\n )\n@register.simple_tag( takes_context = True )\ndef render_list_filters(context):\n return render_to_string(\n 'rai/views/default/list-filter-modal.html',\n {\n\n }\n )\n\n@register.filter\ndef is_list(val):\n return isinstance(val, list)\n\n@register.filter\ndef to_str(val):\n return str(val)\n\n@register.filter\ndef tags2class(val):\n if val == 'debug':\n val = 'info'\n elif val == 'error':\n val = 'danger'\n return val\n\n\n@register.filter\ndef rai_render_with_errors(bound_field, label):\n \"\"\"\n Usage: {{ field|render_with_errors }} as opposed to {{ field }}.\n If the field (a BoundField instance) has errors on it, and the associated widget implements\n a render_with_errors method, call that; otherwise, call the regular widget rendering mechanism.\n \"\"\"\n widget = bound_field.field.widget\n kwargs = { 'attrs' : {'id': bound_field.auto_id}}\n if hasattr(widget, 'requires_label') and widget.requires_label:\n kwargs.update({'label' : label})\n if bound_field.errors and hasattr(widget, 'render_with_errors'):\n kwargs.update({'errors': bound_field.errors})\n return widget.render_with_errors(\n bound_field.html_name,\n bound_field.value(),\n **kwargs\n\n )\n else:\n return widget.render(\n bound_field.html_name,\n bound_field.value(),\n **kwargs\n )\n\n\n\n@register.filter\ndef render_disabled(bound_field):\n widget = bound_field.field.widget\n if hasattr(widget, 'render_disabled'):\n return widget.render_disabled(\n bound_field.html_name,\n bound_field.value(),\n attrs={'id': bound_field.auto_id},\n )\n else:\n return bound_field.as_widget()\n\n@register.filter\ndef widget_requires_label(bound_field):\n return bound_field.field.widget.requires_label or False\n\n@register.simple_tag\ndef rand_str():\n return ''.join(\n random.choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(10) \n )\n\n\n@register.filter\ndef pprint(obj):\n print('Output is:')\n try:\n pp(obj.__dict__)\n except AttributeError:\n pp(obj)\n return \"\"\n\n\n@register.simple_tag(takes_context = True)\ndef show_for_instance(context, action, instance):\n if instance == True:\n return True\n\n request = context.get('request', None)\n return action['show_for_instance'](instance, request)\n\n@register.simple_tag(takes_context = True)\ndef get_ajax_params(context, action, instance):\n request = context.get('request', None)\n if action['get_params']:\n return action['get_params'](instance, request)\n else:\n return {'classes':[], 'additional':{}}\n\n@register.filter\ndef save_htmldiff(change):\n try:\n return change.htmldiff()\n\n except Exception as e:\n return mark_safe(\"An dieser Stelle tritt ein Problem beim Vergleich der Werte auf. Das ist ein Fehler, der gemeldet werden sollte. Der Fehler lautete im Einzelnen:
{}: {}\".format(type(e).__name__, str(e)))\n","sub_path":"rai/templatetags/rai_tags.py","file_name":"rai_tags.py","file_ext":"py","file_size_in_byte":4865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"496121597","text":"\n\"\"\"Builds the network.\n\nSummary of available functions:\n\n # Compute input states and actions for training. If you would like to run\n # evaluations, use inputs() instead.\n inputs, actions = distorted_inputs()\n\n # Compute inference on the model inputs to make a prediction.\n predictions = inference(inputs)\n\n # Compute the total loss of the prediction with respect to the actions.\n loss = loss(predictions, actions)\n\n # Create a graph to run one step of training with respect to the loss.\n train_op = train(loss, global_step)\n\"\"\"\n# pylint: disable=missing-docstring\n# from __future__ import absolute_import\n# from __future__ import division\n# from __future__ import print_function\n\nimport re,numpy, pandas,config\nimport tensorflow as tf\n\nstate_column_size = 64\nnumber_of_categories = 46\nn_components = 16\n\nmotions = numpy.array([])\n\nMOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.\n\nTOWER_NAME = 'tower'\n#\n# def _activation_summary(x):\n# tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)\n# tf.summary.histogram(tensor_name + '/activations', x)\n# tf.summary.scalar(tensor_name + '/sparsity',\n# tf.nn.zero_fraction(x))\n\ndef _variable_on_cpu(name, shape, initializer):\n with tf.device('/cpu:0'):\n var = tf.get_variable(name, shape, initializer=initializer)\n return var\n\ndef _variable_with_weight_decay(name, shape, stddev, wd):\n var = _variable_on_cpu(\n name,\n shape,\n tf.truncated_normal_initializer(stddev=stddev))\n if wd is not None:\n #L2 REGULARIZATION IS INSERTED!\n weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')\n tf.add_to_collection('losses', weight_decay)\n return var\n\ndef inference(states,agentName):\n global NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN\n NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = states.get_shape()[0].value\n\n global n_components\n\n # layer1\n with tf.variable_scope(agentName + 'layer1') as scope:\n weights = _variable_with_weight_decay(agentName + 'weights', shape=[n_components, int(n_components)],\n stddev=0.04, wd=0.001)\n biases = _variable_on_cpu(agentName + 'biases', [int(n_components)], tf.constant_initializer(0.1))\n layer1 = tf.nn.relu(tf.matmul(states, weights) + biases, name=scope.name)\n\n # layer2\n with tf.variable_scope(agentName + 'layer2') as scope:\n weights = _variable_with_weight_decay(agentName + 'weights', shape=[int(n_components), number_of_categories],\n stddev=0.04, wd=0.001)\n biases = _variable_on_cpu(agentName + 'biases', [number_of_categories], tf.constant_initializer(0.1))\n layer2 = tf.nn.sigmoid(tf.matmul(layer1, weights) + biases, name=scope.name)\n\n # linear layer(WX + b),\n # We don't apply softmax here because\n # tf.nn.sparse_softmax_cross_entropy_with_logits accepts the unscaled logits\n # and performs the softmax internally for efficiency.\n with tf.variable_scope(agentName + 'softmax_linear') as scope:\n weights = _variable_with_weight_decay(agentName + 'weights', [number_of_categories, number_of_categories],\n stddev=1 / 56, wd=0.0)\n biases = _variable_on_cpu(agentName + 'biases', [number_of_categories],\n tf.constant_initializer(0.0))\n softmax_linear = tf.add(tf.matmul(layer2, weights), biases, name=scope.name)\n\n return softmax_linear\n\n\ndef initMotions():\n global motions\n dataframe = pandas.read_csv(config.CHARACTER_MOTION_PATH, header=None)\n motions = dataframe.values[1:, 0]\n # motions = numpy.array([mo for mo in motions if \"RECOV\" not in mo and \"THROW\" not in mo])\n return motions\n\n# def initLabelBinarizer():\n#\n# mlb = MultiLabelBinarizer(motions)\n# inception = numpy.array(list(map(lambda n: [n], data)))\n\ndef label_index_to_motion(i):\n global motions\n return motions[i]\n\n# def label_index_to_motion(motions,i):\n# return motions[i]\n","sub_path":"NeuralModellingAI/agent_modelling.py","file_name":"agent_modelling.py","file_ext":"py","file_size_in_byte":4035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"361590942","text":"\n\nfrom xai.brain.wordbase.nouns._irregular import _IRREGULAR\n\n#calss header\nclass _IRREGULARS(_IRREGULAR, ):\n\tdef __init__(self,): \n\t\t_IRREGULAR.__init__(self)\n\t\tself.name = \"IRREGULARS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"irregular\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_irregulars.py","file_name":"_irregulars.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"312826770","text":"import re\r\nimport json\r\nimport codecs\r\nimport pickle\r\n\r\nentity_info = None\r\nintents_info = None\r\nre_pattern_list = None\r\n\r\ndef JSONload(file):\r\n with codecs.open(file, 'r', encoding='utf-8') as f:\r\n obj = json.load(f)\r\n return obj\r\n\r\ndef JSONdump(file, obj):\r\n with codecs.open(file, 'w', encoding='utf-8') as f:\r\n json.dump(obj, f, ensure_ascii=False, indent = 4)\r\n\r\ndef TransRegExp(pattern):\r\n global entity_info\r\n \r\n reg_exp = ''\r\n entities = ''\r\n do_Replace = False\r\n\r\n layer = 0\r\n \r\n for ch in pattern:\r\n if not do_Replace:\r\n if ch == '(':\r\n layer += 1\r\n do_Replace = True\r\n reg_exp += ch\r\n else:\r\n if ch == '(':\r\n if entities != '':\r\n reg_exp += entities\r\n entities = ''\r\n layer += 1\r\n reg_exp += ch\r\n elif ch == ')':\r\n elist = entities.split('|')\r\n terms_list = []\r\n\r\n sub_re_exp = '('\r\n \r\n for entity in elist:\r\n \r\n if entity in entity_info:\r\n terms = SearchTerms(entity)\r\n else:\r\n terms = SearchTerms(entity.rsplit('_', 1)[0])\r\n \r\n if len(terms) > 0:\r\n terms_list = list(set(terms))\r\n terms_list = [re.escape(term) for term in terms_list]\r\n sub_re_exp += '(?P<' + entity + '>' + '|'.join(terms_list) + ')' + '|'\r\n else:\r\n sub_re_exp += entity + '|'\r\n \r\n reg_exp += sub_re_exp[:-1] + ')' + ch\r\n entities = ''\r\n layer -= 1\r\n if layer == 0: do_Replace = False\r\n else:\r\n entities += ch\r\n\r\n reg_exp = reg_exp.replace('()','')\r\n reg_exp = reg_exp.replace('(|','|(')\r\n regex = re.compile(reg_exp)\r\n return regex\r\n\r\ndef LoadPatterns(intents_info):\r\n re_pattern_list = []\r\n for cate in intents_info.keys():\r\n for pattern in intents_info[cate]:\r\n regex = TransRegExp(pattern)\r\n re_pattern_list.append((regex, cate))\r\n return re_pattern_list\r\n\r\ndef Match(sent):\r\n intent_cate = ''\r\n slot = {}\r\n \r\n max_score = -1\r\n for regex, cate in re_pattern_list:\r\n obj = regex.match(sent)\r\n if obj:\r\n start_idx = obj.start()\r\n end_idx = obj.end()\r\n score = (end_idx - start_idx) / len(sent)\r\n if score > max_score:\r\n intent_cate = cate\r\n slot = obj.groupdict()\r\n max_score = score\r\n return intent_cate, slot\r\n\r\ndef SearchTerms(entity):\r\n global entity_info\r\n \r\n tlist = []\r\n \r\n if entity in entity_info:\r\n next_entities_list, synonyms_list = entity_info[entity]\r\n tlist += synonyms_list\r\n for next_entity in next_entities_list:\r\n tlist += SearchTerms(next_entity)\r\n \r\n return tlist\r\n \r\nif __name__ == '__main__':\r\n \r\n entity_info = JSONload('entity_info.json')\r\n intents_info = JSONload('intents_info.json')\r\n re_pattern_list = LoadPatterns(intents_info)\r\n\r\n sent = '想要購買車'\r\n print(sent, Match(sent))\r\n sent = '我渴望買摩托車'\r\n print(sent, Match(sent))\r\n sent = '我們期待選購卡車'\r\n print(sent, Match(sent))\r\n\r\n print()\r\n \r\n sent = '想要購買餅乾'\r\n print(sent, Match(sent))\r\n sent = '我渴望買巧克力'\r\n print(sent, Match(sent))\r\n sent = '我們我期待選購烤雞'\r\n print(sent, Match(sent))\r\n\r\n \r\n \r\n","sub_path":"NLU/Matching_v2.py","file_name":"Matching_v2.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"617338343","text":"import os\nimport sys\nimport re\nimport shutil\n\nprint(' '.join(sys.argv))\n\nif len(sys.argv) != 5:\n print(\"Usage: python prep/phone.py \")\n os._exit(1)\n\nif os.path.isdir(sys.argv[4]):\n shutil.rmtree(sys.argv[4])\n\nprint(\"Creating\", sys.argv[4], '...')\nos.mkdir(sys.argv[4])\n\nwith open(sys.argv[4] + '/lexicon.txt', 'w+') as fout:\n fout.writelines('!SIL sil\\n spn\\n')\nfout.close()\n\nwith open(sys.argv[4] + '/silence_phones.txt', 'w+') as fout:\n fout.writelines('sil\\nspn\\n')\nfout.close()\n\nwith open(sys.argv[4] + '/optional_silence.txt', 'w+') as fout:\n fout.writelines('sil\\n')\nfout.close()\n\ndictText = {}\nwith open(sys.argv[1], 'r') as fp:\n line = fp.readline()\n while line:\n line = line.replace('\\n', '')\n aLine = line.split(':')\n dictText[aLine[0]] = aLine[1].split(' ')\n line = fp.readline()\nfp.close()\n\ndictSyl = {}\nwith open(sys.argv[2], 'r') as fp:\n line = fp.readline()\n while line:\n line = line.replace('\\n', '')\n aLine = line.split(':')\n # dictLex[aLine[0]] = re.findall(r\"[\\w']+\", aLine[1])\n dictSyl[aLine[0]] = aLine[1].split(' ')\n line = fp.readline()\nfp.close()\n\nwords = []\nwith open(sys.argv[3], 'r') as fp:\n line = fp.readline()\n while line:\n line = line.replace('\\n', '')\n idx = line.split(' ', 1)[0]\n for i in range(len(dictText[idx])):\n if dictText[idx][i] not in words:\n words.append(dictText[idx][i])\n with open(sys.argv[4] + '/lexicon.txt', 'a') as fout:\n fout.writelines(\n dictText[idx][i] + ' ' + ' '.join(dictSyl[idx][i].split('-')) + '\\n')\n fout.close()\n line = fp.readline()\nfp.close()\n\nphones = []\nwith open(sys.argv[2], 'r') as fp:\n line = fp.readline()\n while line:\n line = line.replace('\\n', '')\n tmp = re.split(':|-| ', line)\n for i in range(1, len(tmp)):\n if tmp[i] not in phones:\n phones.append(tmp[i])\n with open(sys.argv[4] + '/nonsilence_phones.txt', 'a') as fout:\n fout.writelines(tmp[i]+'\\n')\n fout.close()\n line = fp.readline()\nfp.close()\n\nprint(\"Output created in\", sys.argv[4] + '\\n')\n","sub_path":"prep/phone.py","file_name":"phone.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"651745995","text":"#Drawing ellipse\r\nimport matplotlib.pyplot as plt\r\na=3\r\nb=5\r\n#plot the ellipse\r\nx=np.linspace(-5.0, 5.0, num=100000)\r\ny=(b**2*(1-(x**2)/(a**2)))**.5\r\nplt.plot(x,y)\r\nplt.plot(x,-y)\r\nplt.show()","sub_path":"VizeSonrasi_HAFTA1.py","file_name":"VizeSonrasi_HAFTA1.py","file_ext":"py","file_size_in_byte":191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"178046893","text":"#!/usr/bin/env python\n\nimport sys\n\nfrom ldap3 import MODIFY_REPLACE\n\nfrom ldap_toolbox.utils import ldap_start_connection, ldap_stop_connection, load_config\n\nusers_login = sys.argv[1:]\nmemberOf_id = \"id\"\nold_user_group_dn = \"CN=old_user,OU=old_user,DC=hello,DC=com\"\nold_user_ou_dn = \"OU=old_user,DC=hello,DC=com\"\n\ndef search_user_information(conn, ldap_domain, ldap_domain_ext, user_login):\n \"\"\" Get information for the requested user\n \"\"\"\n try:\n search_base = \"dc={}, dc={}\".format(ldap_domain, ldap_domain_ext)\n query = \"(&(objectclass=user)(objectCategory=person)\" \\\n \"(sAMAccountName={})(userAccountControl=512))\".format(user_login)\n attributes = ['distinguishedName', 'displayname']\n\n conn.search(search_base, query, attributes=attributes)\n user = conn.entries\n\n if not user:\n raise Exception(\"users not found\")\n except Exception as e:\n raise Exception(\"unable to search user information :: {}\".format(e))\n return user\n\n\ndef add_user_to_group(conn, user_dn, old_user_group_dn):\n \"\"\" Add the user to a group\n \"\"\"\n try:\n conn.extend.microsoft.add_members_to_groups([str(user_dn)], [str(old_user_group_dn)])\n except Exception as e:\n raise Exception(\"Can't add user to this group :: {}\".format(e))\n\n\ndef modify_primary_group(conn, user_dn, memberOf_id):\n \"\"\" Change the primary group of the user\n \"\"\"\n try:\n conn.modify(str(user_dn), {'primaryGroupID': [(MODIFY_REPLACE, [memberOf_id])]})\n except Exception as e:\n raise Exception(\"Can't set this group as Primary Group :: {}\".format(e))\n\n\ndef find_user_groups(conn, ldap_domain, ldap_domain_ext, user_dn):\n \"\"\" Find the memberOf of the user\n \"\"\"\n try:\n search_base = \"dc={}, dc={}\".format(ldap_domain, ldap_domain_ext)\n query = \"(&(objectCategory=group)(member={}))\".format(user_dn)\n attributes = ['distinguishedName']\n\n conn.search(search_base, query, attributes=attributes)\n groups = conn.entries\n except Exception as e:\n raise Exception(\"No groups found :: {}\".format(e))\n return groups\n\n\ndef remove_user_from_groups(conn, user_dn, group_dn):\n \"\"\" Delete the memberOf of the user\n \"\"\"\n try:\n conn.extend.microsoft.remove_members_from_groups([str(user_dn)], [str(group_dn)])\n except Exception as e:\n raise Exception(\"Can't remove user from groups :: {}\".format(e))\n\n\ndef disable_user(conn, user_dn):\n \"\"\" Disable the user in the Active Directory\n \"\"\"\n try:\n conn.modify(str(user_dn), {'userAccountControl': [(MODIFY_REPLACE, ['514'])]})\n except Exception as e:\n raise Exception(\"Can't disable the user :: {}\".format(e))\n\n\ndef move_user(conn, user_dn, user_disp, old_user_ou_dn):\n \"\"\" Move the user to another directory\n \"\"\"\n try:\n conn.modify_dn(str(user_dn), 'CN={}'.format(user_disp), new_superior=str(old_user_ou_dn))\n except Exception as e:\n raise Exception(\"Can't move the user :: {}\".format(e))\n\n\ndef main():\n try:\n ldap_config = load_config()\n\n conn = ldap_start_connection(ldap_domain_full=ldap_config['domain_full'],\n ldap_login=ldap_config['login'],\n ldap_password=ldap_config['password'])\n\n for user_login in users_login:\n\n user = search_user_information(conn, ldap_domain=ldap_config['domain'],\n ldap_domain_ext=ldap_config['domain_ext'],\n user_login=user_login)\n\n user_dn = user[0].distinguishedName\n user_disp = user[0].displayname\n print(user_disp)\n\n #add_user_to_group(conn, user_dn=user_dn)\n\n #modify_primary_group(conn, user_dn=user_dn)\n\n groups = find_user_groups(conn, ldap_domain=ldap_config['domain'],\n ldap_domain_ext=ldap_config['domain_ext'],\n user_dn=user_dn)\n\n for group in groups:\n group_dn = group.distinguishedName\n print(group_dn)\n\n #remove_user_from_groups(conn, user_dn=user_dn, group_dn=group_dn)\n\n #disable_user(conn, user_dn=user_dn)\n\n #move_user(conn, user_dn=user_dn, user_disp=user_disp)\n\n ldap_stop_connection(conn)\n except Exception as e:\n print(e)\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ldap_toolbox/cleaner.py","file_name":"cleaner.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"198067330","text":"# -----------------------------------------------------------------------------\n# Copyright (c) 2020--, The Qiita Development Team.\n#\n# Distributed under the terms of the BSD 3-clause License.\n#\n# The full license is in the file LICENSE, distributed with this software.\n# -----------------------------------------------------------------------------\nfrom os import environ, listdir\nfrom os.path import join, isdir, expanduser\nfrom configparser import ConfigParser\n\nfrom qiita_client import QiitaClient\n\n\nplugin_details = {'name': 'qp-woltka',\n 'version': '2020.11',\n 'description': 'Woltka'}\n\n\ndef get_dbs(db_folder):\n dbs = dict()\n # Loop through the databases and create a dict of them\n for folder in listdir(db_folder):\n folder_path = join(db_folder, folder)\n if isdir(folder_path):\n files = listdir(folder_path)\n # the bowtie2 db format is name.#.bt2 so getting just the name\n db_fp = [f for f in files if f.endswith('.bt2') or\n f.endswith('.bt2l')][0].rsplit('.', 2)[0]\n dbs[folder] = join(folder_path, db_fp)\n\n return(dbs)\n\n\ndef generate_woltka_dflt_params():\n dflt_param_set = {}\n db_parent_path = environ[\"QC_WOLTKA_DB_DP\"]\n # Get a the databases available and the database name\n dbs = get_dbs(db_parent_path)\n # Create dict with command options per database\n for name, fp in dbs.items():\n dflt_param_set[name] = {'Database': fp}\n\n return(dflt_param_set)\n\n\ndef client_connect(url):\n name = plugin_details['name']\n version = plugin_details['version']\n\n config = ConfigParser()\n conf_dir = environ.get(\n 'QIITA_PLUGINS_DIR', join(expanduser('~'), '.qiita_plugins'))\n conf_fp = join(conf_dir, f'{name}_{version}.conf')\n\n with open(conf_fp, 'U') as conf_file:\n config.readfp(conf_file)\n qclient = QiitaClient(url, config.get('oauth2', 'CLIENT_ID'),\n config.get('oauth2', 'CLIENT_SECRET'),\n server_cert=config.get('oauth2', 'SERVER_CERT'))\n\n return qclient\n","sub_path":"qp_woltka/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"167398606","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport os\nimport sys\n\n\ndef new_f90(n, t):\n fileSource = open(\"lotus.f90\",\"r\")\n fileText = fileSource.read()\n fileSource.close()\n fileLines = fileText.split(\"\\n\")\n fileLines[15] = f\" integer :: ndims = {int(n)}\"\n fileLines[31] = f\" real :: finish = {float(t)}*D\"\n fileText = \"\\n\".join(fileLines)\n fileOutput = open(\"lotus.f90\",\"w\")\n fileOutput.write(fileText)\n","sub_path":"stop/circular_cylinder/itscript.py","file_name":"itscript.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"86592491","text":"'''(https://classes.cs.uoregon.edu/19F/cis210/p20-looping-F19.pdf)\r\nProject 2.0: Learning Looping\r\nCIS 210 F19\r\n\r\nAuthor: Erich Scheid\r\n\r\nCredit: N/A\r\n\r\nDescription: Use different kinds of loops i.e. for loops, while loops.\r\n'''\r\ndef q6_better():\r\n p = 1\r\n for i in range(4):\r\n p = p * 2\r\n return p\r\n\r\ndef q6_final(n, m):\r\n '''\r\n Returns n raised to the power of m.\r\n '''\r\n r = 1\r\n for i in range(m):\r\n r *= n\r\n return r\r\n","sub_path":"Week2/p20_loops.py","file_name":"p20_loops.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"376705535","text":"import pickle\nimport boto3\nimport configparser\nimport subprocess\nimport time\nfrom botocore.exceptions import ClientError\nfrom docker.errors import ContainerError\n\nimport docker\nclass Ec2:\n def __init__(self,config_main):\n config = configparser.ConfigParser()\n config.read('greconf.ini') \n self.bucket=config[config_main]['bucket']\n self.sec=config[config_main]['sec']\n self.path=config[config_main]['path']\n self.file=config[config_main]['file']\n self.main_ip=config[config_main]['main_ip']\n self.instance_size=config[config_main]['instance_size']\n self.VolumeSize=config[config_main]['VolumeSize']\n self.tag=config[config_main]['tag']\n self.ami=config[config_main]['ami']\n self.Image_name=config[config_main]['Image_name']\n self.loadbalancer=config[config_main]['Loadbalancer']\n self.ssh_key=config[config_main]['ssh_key']\n pass\n\n def download_old_ami_name(self):\n try:\n sclient = boto3.client('s3')\n response = sclient.get_object(Bucket=self.bucket, Key=self.file)\n body_string = response['Body'].read()\n positive_model_data = pickle.loads(body_string)\n return positive_model_data\n except ClientError:\n positive_model_data={}\n positive_model_data['ami']=self.ami\n positive_model_data['Image_name']=self.Image_name\n positive_model_data['loadbalancer']=self.loadbalancer\n positive_model_data['tag']=self.tag\n positive_model_data['sec']=self.sec\n positive_model_data['instance_size']=self.instance_size\n positive_model_data['VolumeSize']= self.VolumeSize\n positive_model_data['ssh_key']=self.ssh_key\n return positive_model_data\n def create_ec2(self):\n ec2 = boto3.resource('ec2')\n instance = ec2.create_instances(ImageId = self.download_old_ami_name()['ami']\n ,MinCount = 1\n ,MaxCount = 1,\n InstanceType = self.instance_size,\n BlockDeviceMappings=[\n {\n 'DeviceName': '/dev/sda1',\n\n 'Ebs': {\n \n 'VolumeSize': self.VolumeSize,\n },\n },\n ],\n UserData= '''#!/bin/bash\n sudo apt-get install -y nginx > /tmp/hello''',\n KeyName = 'greyv19',\n SecurityGroupIds=[\n self.sec,\n ]\n )\n host = instance[0]\n print(host.id)\n ec2 = boto3.client('ec2')\n ec2.create_tags(Resources=[host.id], Tags=[{'Key':'Name', 'Value':'dev_'+self.tag+''}])\n host.wait_until_running()\n host = ec2.Instance(host.id)\n return host\n\n def deploy_rails(self,host):\n print(host.public_ip_address)\n while self.get_by_name():\n time.sleep(60)\n self.create_ec2()\n try:\n std_out=subprocess.check_output('cd '+self.path+' && yarn',stderr=subprocess.STDOUT,shell=True)\n std_out=subprocess.check_output('cd '+self.path+' && bundle',stderr=subprocess.STDOUT,shell=True)\n std_out=subprocess.check_output('cd '+self.path+' && ./bin/webpack',stderr=subprocess.STDOUT,shell=True)\n std_out=subprocess.check_output('cd '+self.path+' && bundle exec cap production deploy server='+self.main_ip,stderr=subprocess.STDOUT,shell=True)\n std_out=subprocess.check_output('cd '+self.path+' && bundle exec cap production deploy server='+host.public_ip_address,stderr=subprocess.STDOUT,shell=True)\n std_out=subprocess.check_output('cd '+self.path+' && git stash',stderr=subprocess.STDOUT,shell=True)\n old=self.download_old_ami_name()\n image,name=self.image_create(host.id,old)\n self.delete(host.id)\n self.upload_new_ami(image,name,old)\n self.amidel(old)\n except subprocess.CalledProcessError as e:\n print(str(e.output))\n self.delete(host.id)\n \n def image_create(self,instance_id,old):\n ec2 = boto3.resource('ec2')\n host = ec2.Instance(instance_id)\n newname=self.versionname(old['Image_name'])\n image = host.create_image(Name=newname)\n print(image.id)\n self.image_wait(image.id)\n return image.id,newname\n def image_wait(self,image):\n ec2 = boto3.client('ec2')\n waiter = ec2.get_waiter('image_available')\n waiter.wait(ImageIds=[image.id])\n\n def delete(self,id):\n ec2 = boto3.client('ec2')\n ec2.terminate_instances(InstanceIds=[id])\n\n\n \n def get_by_name(self):\n ec2 = boto3.client('ec2')\n filters = [{\n 'Name': 'tag:Name',\n 'Values': ['scale_'+self.tag]\n },\n {\n 'Name': 'instance-state-name',\n 'Values': ['running','pending']\n },\n ]\n reservations = ec2.describe_instances(Filters=filters)\n #print(reservations['Reservations'][0]['Instances'])\n if len(reservations['Reservations'])>=1:\n return True\n else:\n return False\n\n\n def amidel(self,old):\n ami=old['ami']\n ec2 = boto3.client('ec2')\n snapid=ec2.describe_images(ImageIds=[ami])['Images'][0]['BlockDeviceMappings'][0]['Ebs']['SnapshotId']\n response = ec2.deregister_image(\n ImageId=ami\n )\n self.snapdel(snapid)\n\n def snapdel(self,snapid):\n ec2 = boto3.client('ec2')\n response = ec2.delete_snapshot(\n SnapshotId=snapid\n )\n\n def upload_new_ami(self,ami,newname,example):\n\n print(example)\n example['ami']=ami\n example['version']=self.versionname(example['version'])\n pickle_out = open(self.file,\"wb\")\n pickle.dump(example, pickle_out)\n pickle_out.close()\n bucketName=self.bucket\n Key=self.file\n outPutname=self.file\n s3 = boto3.client('s3')\n s3.upload_file(Key,bucketName,outPutname)\n\n def versionname(self,name):\n name,ver, rev = str(name).split('.')\n versionname=name+'.'+ver + '.' + str(int(rev)+1) \n return versionname\n def test_run(self):\n client = docker.from_env() \n volume={self.path: {'bind': '/root/webapp/'}}\n try : \n client.containers.run('chiruuzumaki/rails_run_cases', 'bash /root/run.sh',volumes=volume)\n except ContainerError as e:\n print(e.stderr)\n def display(self):\n print(self.bucket)\n print(self.sec)\n print(self.path)\n print(self.file)\n print(self.main_ip)\n print(self.instance_size)\n print(self.VolumeSize)\n print(self.tag)\n\n def execall(self):\n self.display()\n host=self.create_ec2()\n self.deploy_rails(host)\n pass\n ","sub_path":"newdeploy.py","file_name":"newdeploy.py","file_ext":"py","file_size_in_byte":7329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"464375184","text":"from django.db.models import ForeignKey, CharField\nfrom backend_interface.models import BaseSearch\nfrom home_theaters.models import HomeTheaterBrand, \\\n HomeTheaterOpticalDiskFormat, HomeTheaterSpeakerFormat, \\\n HomeTheaterAudioPower\n\n\nclass HomeTheaterSearch(BaseSearch):\n brand = ForeignKey(HomeTheaterBrand, null=True)\n optical_disk_format = ForeignKey(HomeTheaterOpticalDiskFormat, null=True)\n speaker_format = ForeignKey(HomeTheaterSpeakerFormat, null=True)\n audio_power = ForeignKey(HomeTheaterAudioPower, null=True)\n\n has_3d_support = CharField(max_length=1)\n has_wifi = CharField(max_length=1)\n is_smart_tv = CharField(max_length=1)\n\n class Meta:\n app_label = 'home_theaters'\n ordering = ['-timestamp']\n","sub_path":"home_theaters/models/home_theater_search.py","file_name":"home_theater_search.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"390176261","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport stat\nimport datetime\nimport time\nimport subprocess\nimport sys\nimport shutil\nimport tempfile\nimport zipfile\nimport urllib.request as url\nimport glob\nimport json\nimport re\nfrom gi.repository import GdkPixbuf\n\nLOG='/tmp/air_manager.log'\n\nclass AirManager():\n\tdef __init__(self):\n\t\tself.dbg=False\n\t\tself.default_icon=\"/usr/share/air-installer/rsrc/air-installer_icon.png\"\n\t\tself.adobeair_folder=\"/opt/AdobeAirApp/\"\n\t\tself.adobeairsdk_folder=\"/opt/adobe-air-sdk/\"\n\t\tself.adobeair_pkgname=\"adobeair\"\n\t\tself.confDir=\"/usr/share/air-manager/config.d\"\n\t\tself.rebuild=False\n\t\tself.pkgConfig={}\n\t#def __init__\n\n\tdef _debug(self,msg):\n\t\tif self.dbg:\n\t\t\tprint(\"airinstaller: %s\"%msg)\n\t\t\tself._log(msg)\n\t#def _debug\n\n\tdef _log(self,msg):\n\t\ttry:\n\t\t\tf=open(LOG,'a')\n\t\t\tf.write(\"%s\"%msg)\n\t\t\tf.close()\n\t\texcept:\n\t\t\tprint(\"Can't write log\")\n\t#def _log\n\n\tdef set_default_icon(self,icon):\n\t\tself.default_icon=icon\n\n\tdef install(self,air_file,icon=None):\n\t\tsw_err=0\n\t\tself.rebuild=False\n\t\tsw_install_sdk=False\n\t\tself._check_adobeair()\n\t\tif not icon:\n\t\t\ticon=self.default_icon\n\t\tself._debug(\"Procced with file: %s\"%air_file)\n\t\tfile_name=os.path.basename(air_file)\n\t\tif self._check_file_is_air(air_file):\n\t\t\tbasedir_name=file_name.replace(\".air\",\"\")\n\t\t\tself._debug(\"Installing %s\"%air_file)\n\t\t\tconfig=self._chk_config_file(air_file)\n\t\t\tif 'preinstall' in config.keys():\n\t\t\t\tair_file=self._recompile_for_preinstall(air_file,config['preinstall'])\n\t\t\tsw_err=self._install_air_package(air_file)\n\t\t\tif sw_err and not self.rebuild:\n\t\t\t\tself._debug(\"Trying rebuild...\")\n\t\t\t\tmodified_air_file=self._recompile_for_certificate_issue(air_file)\n\t\t\t\tself._debug(\"Installing %s\"%modified_air_file)\n\t\t\t\tsw_err=self._install_air_package(modified_air_file)\n\t\t\tif sw_err:\n\t\t\t\tself._debug(\"Failed to install code: %s\"%sw_err)\n\t\t\t\tself._debug(\"Going with sdk installation\")\n\t\t\t\tsw_err=self._install_air_package_sdk(air_file,icon)\n\t\t\t\tsw_install_sdk=True\n\n\t\t\tsw_desktop=True\n\t\t\tif 'generate-desktop' in config.keys():\n\t\t\t\tsw_desktop=config['generate-desktop']\n\n\t\t\tif not sw_err and sw_install_sdk:\n\t\t\t\t#Copy icon to hicolor\n\t\t\t\tif sw_desktop:\n\t\t\t\t\tsw_installed=self._generate_desktop(file_name)\n\t\t\t\t\tif sw_installed:\n\t\t\t\t\t\thicolor_icon='/usr/share/icons/hicolor/48x48/apps/%s.png'%basedir_name\n\t\t\t\t\t\tshutil.copyfile (icon,hicolor_icon)\n\t\t\t\t\t\tself._debug(\"Installed in %s\"%(basedir_name))\n\t\t\t\t\telse:\n\t\t\t\t\t\tself._debug(\"%s Not Installed!!!\"%(basedir_name))\n#\t\t\telif not sw_err and icon!=self.default_icon:\n\t\t\telif not sw_err and sw_desktop:\n\t\t\t\t#Modify desktop with icon\n\t\t\t\thicolor_icon='/usr/share/icons/hicolor/48x48/apps/%s.png'%basedir_name\n\t\t\t\tshutil.copyfile (icon,hicolor_icon)\n\t\t\t\ticon_new=os.path.basename(hicolor_icon)\n\t\t\t\tself._modify_desktop(air_file,icon_name=icon_new)\n\t\t\n\t\t\tif 'postinst' in config.keys() and not sw_err:\n\t\t\t\tself._execute_postinstall(config['postinst'])\n\n\t\t#Remove adobeair mime association\n\t\ttime.sleep(1)\n\t\tmy_env=os.environ.copy()\n\t\tmy_env[\"DISPLAY\"]=\":0\"\n\t\ta=subprocess.check_output([\"xdg-mime\",\"install\",\"--mode\",\"system\",\"/usr/share/mime/packages/x-air-installer.xml\"],env=my_env)\n\t\tself._debug(\"Remove result: %s\"%a)\n\t\tif os.path.isfile('/usr/share/mime/application/vnd.adobe.air-application-installer-package+zip.xml'):\n\t\t\tself._debug(\"Remove air mime\")\n\t\t\tos.remove('/usr/share/mime/application/vnd.adobe.air-application-installer-package+zip.xml')\n\t\tself._debug(\"Fixing mime\")\n\t\ta=subprocess.check_output([\"xdg-mime\",\"default\",\"/usr/share/applications/air-installer.desktop\",\"/usr/share/mime/packages/x-air-installer.xml\"],input=b\"\",env=my_env)\n\t\tself._debug(\"Default result: %s\"%a)\n\t#def install\n\n\tdef _chk_config_file(self,air_file):\n\t\tpkgConfig={}\n\t\tairName=os.path.basename(air_file).replace(\".air\",\"\")\n\t\tself._debug(\"Name: %s\"%airName)\n\t\tif os.path.isdir(self.confDir):\n\t\t\tfor conf in glob.glob(\"%s/*\"%self.confDir):\n\t\t\t\tif os.path.basename(conf).replace(\".json\",\"\").lower() in airName.lower():\n\t\t\t\t\tself._debug(\"Conf file: %s\"%conf)\n\t\t\t\t\ttry:\n\t\t\t\t\t\twith open(conf,'r') as f:\n\t\t\t\t\t\t\tpkgConfig=json.load(f)\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tself._debug(\"Error reading %s\"%conf)\n\t\t\t\t\t\tself._debug(\"Reason: %s\"%e)\n\t\treturn(pkgConfig)\n\n\tdef _recompile_for_preinstall(self,air_file,conf):\n\t\tself._debug(\"Modifying package %s\"%air_file)\n\t\tsw_ok=True\n\t\tnew_air_file=air_file\n\t\ttmpdir=self._unzip_air_file(air_file)\n\t\tcwd=os.getcwd()\n\t\tos.chdir(tmpdir)\n\t\tfor targetFile,values in conf.items():\n\t\t\tself._debug(\"Searching for %s\"%targetFile)\n\t\t\tif os.path.isfile(targetFile):\n\t\t\t\tself._debug(\"File: %s\"%targetFile)\n\t\t\t\tf=open(targetFile,'r')\n\t\t\t\tfcontents=f.readlines()\n\t\t\t\tf.close()\n\t\t\t\tnewContents=[]\n\t\t\t\tfor line in fcontents:\n\t\t\t\t\tfor regTarget,regReplace in values.items():\n\t\t\t\t\t\tif re.search(regTarget,line):\n\t\t\t\t\t\t\tline=re.sub(regTarget,regReplace,line)\n\t\t\t\t\t\tnewContents.append(line)\n\t\t\t\tf=open(targetFile,'w')\n\t\t\t\tf.writelines(newContents)\n\t\t\t\tf.close()\n\n\t\tfor xml_file in os.listdir(\"META-INF/AIR\"):\n\t\t\tif xml_file.endswith(\".xml\"):\n\t\t\t\tair_xml=xml_file\n\t\t\t\tbreak\n\t\tif air_xml:\n\t\t\tshutil.move(\"META-INF/AIR/\"+air_xml,air_xml)\n\t\t\tshutil.rmtree(\"META-INF/\",ignore_errors=True)\n\t\t\tos.remove(\"mimetype\")\n\t\t\tself._debug(\"Generating new cert\")\n\t\t\tsubprocess.call([\"/opt/adobe-air-sdk/bin/adt\",\"-certificate\",\"-cn\",\"lliurex\",\"2048-RSA\",\"lliurex.p12\",\"lliurex\"])\n\t\t\tnew_air_file=os.path.basename(air_file)\n\t\t\tmy_env=os.environ.copy()\n\t\t\tmy_env[\"DISPLAY\"]=\":0\"\n\t\t\ttry:\n\t\t\t\tsubprocess.check_output([\"/opt/adobe-air-sdk/bin/adt\",\"-package\",\"-tsa\",\"none\",\"-storetype\",\"pkcs12\",\"-keystore\",\"lliurex.p12\",new_air_file,air_xml,\".\"],input=b\"lliurex\",env=my_env)\n\t\t\t\tnew_air_file=\"%s/%s\"%(tmpdir,new_air_file)\n\t\t\texcept Exception as e:\n\t\t\t\tself._debug(e)\n\t\tos.chdir(cwd)\n\t\tself.rebuild=True\n\t\treturn (new_air_file)\n\t#def _recompile_for_certificate_issue\n\n\tdef _execute_postinstall(self,conf):\n\t\tself._debug(\"Postinstall %s\"%conf)\n\t\tsw_ok=True\n\t\tfor targetFile,values in conf.items():\n\t\t\tself._debug(\"Searching for %s\"%targetFile)\n\t\t\tif os.path.isfile(targetFile):\n\t\t\t\tself._debug(\"File: %s\"%targetFile)\n\t\t\t\twith open(targetFile,'r') as f:\n\t\t\t\t\tfcontents=f.readlines()\n\t\t\t\tnewContents=[]\n\t\t\t\tfor line in fcontents:\n\t\t\t\t\tdeleteKey=\"\"\n\t\t\t\t\tfor regTarget,regReplace in values.items():\n\t\t\t\t\t\tif regTarget=='--append':\n\t\t\t\t\t\t\tnewContents.extend(regReplace)\n\t\t\t\t\t\t\tdeleteKey=regTarget\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tline=re.sub(regTarget,regReplace,line)\n\t\t\t\t\t\tnewContents.append(line)\n\t\t\t\t\tif deleteKey:\n\t\t\t\t\t\tvalues.pop(deleteKey,None)\n\t\t\t\tf=open(targetFile,'w')\n\t\t\t\tf.writelines(newContents)\n\t\t\t\tf.close()\n\n\tdef _modify_desktop(self,air_file,icon_name=None):\n\t\tself._debug(\"Modify desktop %s\"%air_file)\n\t\tair_info=self.get_air_info(air_file)\n\t\tsw_modify_icon=False\n\t\tif 'name' in air_info.keys():\n\t\t\tcwd=os.getcwd()\n\t\t\tos.chdir('/usr/share/applications')\n\t\t\tdesktop_list=glob.glob(air_info['name']+\"*desktop\")\n\t\t\tif desktop_list==[]:\n\t\t\t\tdesktop_list=glob.glob(air_info['name'].lower()+\"*desktop\")\n\t\t\tif desktop_list:\n\t\t\t\t#First file must be the desktop but for sure...\n\t\t\t\tsw_modify_icon=False\n\t\t\t\tfor desktop_file in desktop_list:\n\t\t\t\t\tself._debug(\"Testing file %s\"%desktop_file)\n\t\t\t\t\tf=open(desktop_file,'r')\n\t\t\t\t\tflines=f.readlines()\n\t\t\t\t\tself._debug(\"Looking for %s\"%self.adobeair_folder)\n\t\t\t\t\tfor fline in flines:\n\t\t\t\t\t\tself._debug(fline)\n\t\t\t\t\t\tself._debug(type(fline))\n\t\t\t\t\t\tif '/opt/AdobeAirApp' in fline:\n\t\t\t\t\t\t\tself._debug(\"Match\")\n\t\t\t\t\t\t\tsw_modify_icon=True\n\t\t\t\t\tf.close()\n\t\t\tif sw_modify_icon:\n\t\t\t\tself._debug(\"Setting icon\")\n\t\t\t\tnew_desktop=[]\n\t\t\t\tfor fline in flines:\n\t\t\t\t\tif fline.startswith('Icon'):\n\t\t\t\t\t\tself._debug(\"Before: %s\"%fline)\n\t\t\t\t\t\tnline='Icon=%s\\n'%icon_name\n\t\t\t\t\t\tself._debug(\"After: %s\"%nline)\n\t\t\t\t\t\tnew_desktop.append(nline)\n\t\t\t\t\telse:\n\t\t\t\t\t\tnew_desktop.append(fline)\n\t\t\t\tself._debug(\"Writing desktop %s\"%desktop_file)\n\t\t\t\tf=open(desktop_file,'w')\n\t\t\t\tf.writelines(new_desktop)\n\t\t\t\tf.close()\n\t\t\tos.chdir(cwd)\n\t#def _modify_desktop\n\n\tdef _check_adobeair(self):\n\t\tsw_install_adobe=False\n\t\tsw_download=False\n\t\ttry:\n\t\t\tres=subprocess.check_output([\"dpkg-query\",\"-W\",\"-f='${Status}'\",self.adobeair_pkgname])\n\t\t\tif \"not\" in str(res):\n\t\t\t\tself._debug(\"adobeair not installed\")\n\t\t\t\tsw_install_adobe=True\n\t\texcept Exception as e:\n\t\t\tself._debug(\"dpkg-query failed: %s\"%e)\n\t\t\tsw_install_adobe=True\n\t\tfinally:\n\t\t\tif sw_install_adobe:\n\t\t\t\tsw_download=self._install_adobeair()\n\n\t\tif sw_download==False:\n\t\t\tif sw_install_adobe:\n\t\t\t\tself._debug(\"Adobeair failed to install\")\n\t\t\telse:\n\t\t\t\tself._debug(\"Adobeair already installed\")\n\t\t#Now install the sdk\n\t\tif not os.path.isdir(self.adobeair_folder):\n\t\t\tos.makedirs(self.adobeair_folder)\n\t\tself._install_adobeair_sdk()\n\n\tdef _install_air_package(self,air_file):\n\t\tsw_err=1\n\t\tmy_env=os.environ.copy()\n\t\tmy_env[\"PATH\"]=\"/usr/share/air-installer/src/bin:%s\"%my_env[\"PATH\"]\n\t\tself._debug(\"PATH: %s\"%my_env)\n\t\tmy_env[\"DISPLAY\"]=\":0\"\n\t\ttry:\n\t\t\tsubprocess.check_output([\"/usr/bin/Adobe AIR Application Installer\",\"-silent\",\"-eulaAccepted\",\"-location\",\"/opt/AdobeAirApp\",air_file],env=my_env)\n\t\t\tsw_err=0\n\t\texcept Exception as e:\n\t\t\tself._debug(\"Install Error: %s\"%e)\n\t\treturn sw_err\n\t#def _install_air_package\n\n\tdef _install_air_package_sdk(self,air_file,icon=None):\n\t\tsw_err=0\n\t\tif not icon:\n\t\t\ticon=self.default_icon\n\t\tfile_name=os.path.basename(air_file)\n\t\tbasedir_name=file_name.replace('.air','')\n\t\twrkdir=self.adobeair_folder+basedir_name\n\t\tif os.path.isdir(wrkdir):\n\t\t\ttry:\n\t\t\t\tshutil.rmtree(wrkdir)\n\t\t\texcept Exception as e:\n\t\t\t\tsw_err=3\n\t\t\t\tself._debug(e)\n\t\ttry:\n\t\t\tos.makedirs(wrkdir)\n\t\texcept Exception as e:\n\t\t\tsw_err=4\n\t\t\tself._debug(e)\n\t\tif sw_err==0:\n\t\t\ttry:\n\t\t\t\tshutil.copyfile (air_file,wrkdir+\"/\"+file_name)\n\t\t\texcept Exception as e:\n\t\t\t\tsw_err=1\n\t\t\t\tself._debug(\"SDK Install Fail: %s\"%e)\n\t\t#Copy icon to hicolor\n\t\tif sw_err==0:\n\t\t\thicolor_icon='/usr/share/icons/hicolor/48x48/apps/%s.png'%basedir_name\n\t\t\ttry:\n\t\t\t\tshutil.copyfile (icon,hicolor_icon)\n\t\t\texcept:\n\t\t\t\tsw_err=2\n\n\t\tself._generate_desktop_sdk(file_name)\n\t\tself._debug(\"Installed in %s/%s\"%(wrkdir,air_file))\n\t\treturn (sw_err)\n\t#def _install_air_package_sdk\n\n\tdef _generate_desktop(self,file_name):\n\t\tbasedir_name=file_name.replace('.air','')\n\t\tdesktop=\"/usr/share/applications/%s.desktop\"%basedir_name\n\t\texec_file=self._get_air_bin_file(basedir_name)\n\t\tself._debug(\"Exec: %s\"%exec_file)\n\t\tif exec_file:\n\t\t\tf=open(desktop,'w')\n\t\t\tf.write(\"[Desktop Entry]\\n\\\nEncoding=UTF-8\\n\\\nVersion=1.0\\n\\\nType=Application\\n\\\nExec=\\\"\"+exec_file+\"\\\"\\n\\\nIcon=\"+basedir_name+\".png\\n\\\nTerminal=false\\n\\\nName=\"+basedir_name+\"\\n\\\nComment=Application from AdobeAir \"+basedir_name+\"\\n\\\nMimeType=application/x-scratch-project\\n\\\nCategories=Application;Education;Development;ComputerScience;\\n\\\n\")\n\t\t\tf.close()\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n#chmod +x $NEW_ICON_FILE\n\t#def _generate_desktop\n\n\tdef _get_air_bin_file(self,basedir_name):\n\t\ttarget_bin=''\n\t\tfor folder in os.listdir(self.adobeair_folder):\n\t\t\ttarget_folder=''\n\t\t\tif basedir_name.lower() in folder.lower() or basedir_name.lower==folder.lower():\n\t\t\t\ttarget_folder=os.listdir(self.adobeair_folder+folder)\n\t\t\telse:\n\t\t\t\tsplit_name=''\n\t\t\t\tif '-' in basedir_name.lower():\n\t\t\t\t\tsplit_name=basedir_name.lower().split('-')[0]\n\t\t\t\telif ' ' in basedir_name.lower():\n\t\t\t\t\tsplit_name=basedir_name.lower().split(' ')[0]\n\t\t\t\telif '.' in basedir_name.lower():\n\t\t\t\t\tsplit_name=basedir_name.lower().split('.')[0]\n\t\t\t\tif split_name!='' and split_name in folder.lower():\n\t\t\t\t\ttarget_folder=os.listdir(self.adobeair_folder+folder)\n\t\t\tif target_folder:\n\t\t\t\tif 'bin' in target_folder:\n\t\t\t\t\tcandidate_list=os.listdir(self.adobeair_folder+folder+'/bin')\n\t\t\t\t\tfor candidate_file in candidate_list:\n\t\t\t\t\t\ttest_file=self.adobeair_folder+folder+'/bin/'+candidate_file\n\t\t\t\t\t\tself._debug(\"Testing %s\"%test_file)\n\t\t\t\t\t\tif os.access(test_file,os.X_OK):\n\t\t\t\t\t\t\ttarget_bin=test_file\n\t\t\t\t\t\t\tself._debug(\"Test OK for %s\"%target_bin)\n\t\t\t\t\t\t\tbreak\n\t\treturn(target_bin)\n\n\tdef _generate_desktop_sdk(self,file_name):\n\t\tbasedir_name=file_name.replace('.air','')\n\t\tdesktop=\"/usr/share/applications/%s.desktop\"%basedir_name\n\t\tf=open(desktop,'w')\n\t\tf.write(\"[Desktop Entry]\\n\\\nEncoding=UTF-8\\n\\\nVersion=1.0\\n\\\nType=Application\\n\\\nExec=/opt/adobe-air-sdk/adobe-air/adobe-air \"+self.adobeair_folder+basedir_name+\"/\"+file_name+\"\\n\\\nIcon=\"+basedir_name+\".png\\n\\\nTerminal=false\\n\\\nName=\"+basedir_name+\"\\n\\\nComment=Application from AdobeAir \"+basedir_name+\"\\n\\\nMimeType=application/x-scratch-project\\n\\\nCategories=Application;Education;Development;ComputerScience;\\n\\\n\")\n\t\tf.close()\n\t#def _generate_desktop_sdk\n\n\tdef _install_adobeair_sdk(self):\n\t\tif os.path.isfile(self.adobeairsdk_folder+'adobe-air/adobe-air'):\n\t\t\treturn\n\t\tself._install_adobeair_depends()\n\t\tself._debug(\"Installing Adobe Air SDK\")\n\t\tadobeair_urls=[\"http://lliurex.net/recursos-edu/misc/AdobeAIRSDK.tbz2\",\"http://lliurex.net/recursos-edu/misc/adobe-air.tar.gz\"]\n\t\tfor adobeair_url in adobeair_urls:\n\t\t\treq=url.Request(adobeair_url,headers={'User-Agent':'Mozilla/5.0'})\n\t\t\ttry:\n\t\t\t\tadobeair_file=url.urlopen(req)\n\t\t\texcept Exception as e:\n\t\t\t\tself._debug(e)\n\t\t\t\treturn False\n\t\t\t(tmpfile,tmpfile_name)=tempfile.mkstemp()\n\t\t\tos.close(tmpfile)\n\t\t\tself._debug(\"Download %s\"%tmpfile_name)\n\t\t\twith open(tmpfile_name,'wb') as output:\n\t\t\t\toutput.write(adobeair_file.read())\n\t\t\ttry:\n\t\t\t\tos.makedirs (\"/opt/adobe-air-sdk\")\n\t\t\texcept:\n\t\t\t\tpass\n\t\t\tif adobeair_url.endswith(\".tar.gz\"):\n\t\t\t\tsubprocess.call([\"tar\",\"zxf\",tmpfile_name,\"-C\",\"/opt/adobe-air-sdk\"])\n\t\t\telse:\n\t\t\t\tsubprocess.call([\"tar\",\"jxf\",tmpfile_name,\"-C\",\"/opt/adobe-air-sdk\"])\n\t\tst=os.stat(\"/opt/adobe-air-sdk/adobe-air/adobe-air\")\n\t\tos.chmod(\"/opt/adobe-air-sdk/adobe-air/adobe-air\",st.st_mode | 0o111)\n\n\t#def _install_adobeair_sdk\n\n\tdef _install_adobeair(self):\n\t\tif self._install_adobeair_depends():\n\t\t\tself._debug(\"Installing Adobe Air\")\n#\t\t\tadobeair_url=\"http://airdownload.adobe.com/air/lin/download/2.6/AdobeAIRInstaller.bin\"\n\t\t\tadobeair_url=\"http://airdownload.adobe.com/air/lin/download/2.6/adobeair.deb\"\n\t\t\treq=url.Request(adobeair_url,headers={'User-Agent':'Mozilla/5.0'})\n\t\t\ttry:\n\t\t\t\tadobeair_file=url.urlopen(req)\n\t\t\texcept Exception as e:\n\t\t\t\tself._debug('Donwload err: %s'%e)\n\t\t\t\treturn False\n\t\t\t(tmpfile,tmpfile_name)=tempfile.mkstemp()\n\t\t\tos.close(tmpfile)\n\t\t\twith open(tmpfile_name,'wb') as output:\n\t\t\t\toutput.write(adobeair_file.read())\n\t\t\tst=os.stat(tmpfile_name)\n\t\t\tos.chmod(tmpfile_name,st.st_mode | 0o111)\n#\t\t\tsubprocess.call([tmpfile_name,\"-silent\",\"-eulaAccepted\",\"-pingbackAllowed\"])\n#\t\t\tos.system(\"DISPLAY=:0 LD_LIBRARY_PATH=/usr/lib/x86_64-linux-gnu \" + tmpfile_name + \" -silent -eulaAccepted -pingbackAllowed\")\n\t\t\tos.system(\"dpkg -i %s\"%tmpfile_name)\n\t\t\tos.remove(tmpfile_name)\n\t\t\t#Remove symlinks\n\t\t\tif os.path.isfile(\"/usr/lib/libgnome-keyring.so.0\"):\n\t\t\t\tos.remove(\"/usr/lib/libgnome-keyring.so.0\")\n\t\t\tif os.path.isfile(\"/usr/lib/libgnome-keyring.so.0.2.0\"):\n\t\t\t\tos.remove(\"/usr/lib/libgnome-keyring.so.0.2.0\")\n\t\t\t#Set the zomando as configured\n\t\t\ttry:\n\t\t\t\tsubprocess.call([\"zero-center\",\"set-configured\",\"zero-lliurex-adobeair\"])\n\t\t\texcept:\n\t\t\t\tself._debug(\"Failed to set configured on adobeair zomando\")\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\t#def _install_adobeair\n\n\tdef _install_adobeair_depends(self):\n\t\tsubprocess.call([\"apt-get\",\"-q\",\"update\"])\n\t\tlib_folder='x86_64-linux-gnu'\n\t\tif os.uname().machine=='x86_64':\n\t\t\tself._debug(\"Installing i386 libs\")\n\t\t\tret=subprocess.call([\"apt-get\",\"-q\",\"-y\",\"install\",\"libgtk2.0-0:i386\",\"libstdc++6:i386\",\"libxml2:i386\",\"libxslt1.1:i386\",\"libcanberra-gtk-module:i386\",\"gtk2-engines-murrine:i386\",\"libqt4-qt3support:i386\",\"libgnome-keyring0:i386\",\"libnss-mdns:i386\",\"libnss3:i386\",\"libatk-adaptor:i386\",\"libgail-common:i386\"])\n\t\t\tif ret!=0:\n\t\t\t\tret=subprocess.call([\"dpkg\",\"--add-architecture\",\"i386\"])\n\t\t\t\tret=subprocess.call([\"apt-get\",\"-q\",\"-y\",\"install\",\"libgtk2.0-0:i386\",\"libstdc++6:i386\",\"libxml2:i386\",\"libxslt1.1:i386\",\"libcanberra-gtk-module:i386\",\"gtk2-engines-murrine:i386\",\"libqt4-qt3support:i386\",\"libgnome-keyring0:i386\",\"libnss-mdns:i386\",\"libnss3:i386\",\"libatk-adaptor:i386\",\"libgail-common:i386\"])\n\t\t\tif ret!=0:\n\t\t\t\treturn False\n\t\t\t\t\n\t\telse:\n\t\t\tlib_folder='i386-linux-gnu'\n\t\t\tsubprocess.call([\"apt-get\",\"-q\",\"-y\",\"install\",\"libgtk2.0-0\",\"libxslt1.1\",\"libxml2\",\"libnss3\",\"libxaw7\",\"libgnome-keyring0\",\"libatk-adaptor\",\"libgail-common\"])\n\t\tself._debug(\"Linking libs\")\n\t\ttry:\n\t\t\tif os.path.isfile(\"/usr/lib/libgnome-keyring.so.0\"):\n\t\t\t\tos.remove(\"/usr/lib/libgnome-keyring.so.0\")\n\t\t\tif os.path.isfile(\"/usr/lib/libgnome-keyring.so.0.2.0\"):\n\t\t\t\tos.remove(\"/usr/lib/libgnome-keyring.so.0.2.0\")\n\t\t\tos.symlink(\"/usr/lib/\"+lib_folder+\"/libgnome-keyring.so.0\",\"/usr/lib/libgnome-keyring.so.0\")\n\t\t\tos.symlink(\"/usr/lib/\"+lib_folder+\"/libgnome-keyring.so.0.2.0\",\"/usr/lib/libgnome-keyring.so.0.2.0\")\n\t\texcept Exception as e:\n\t\t\tself._debug(e)\n\t\treturn True\n\t#def _install_adobeair_depends\n\n\tdef _recompile_for_certificate_issue(self,air_file):\n\t\tself._debug(\"Rebuilding package %s\"%air_file)\n\t\tnew_air_file=''\n\t\ttmpdir=self._unzip_air_file(air_file)\n\t\tcwd=os.getcwd()\n\t\tos.chdir(tmpdir)\n\t\tair_xml=''\n\t\tfor xml_file in os.listdir(\"META-INF/AIR\"):\n\t\t\tif xml_file.endswith(\".xml\"):\n\t\t\t\tair_xml=xml_file\n\t\t\t\tbreak\n\t\tif air_xml:\n\t\t\tshutil.move(\"META-INF/AIR/\"+air_xml,air_xml)\n\t\t\tshutil.rmtree(\"META-INF/\",ignore_errors=True)\n\t\t\tos.remove(\"mimetype\")\n\t\t\tself._debug(\"Generating new cert\")\n\t\t\tsubprocess.call([\"/opt/adobe-air-sdk/bin/adt\",\"-certificate\",\"-cn\",\"lliurex\",\"2048-RSA\",\"lliurex.p12\",\"lliurex\"])\n\t\t\tnew_air_file=os.path.basename(air_file)\n\t\t\tmy_env=os.environ.copy()\n\t\t\tmy_env[\"DISPLAY\"]=\":0\"\n\t\t\ttry:\n\t\t\t\tsubprocess.check_output([\"/opt/adobe-air-sdk/bin/adt\",\"-package\",\"-tsa\",\"none\",\"-storetype\",\"pkcs12\",\"-keystore\",\"lliurex.p12\",new_air_file,air_xml,\".\"],input=b\"lliurex\",env=my_env)\n\t\t\texcept Exception as e:\n\t\t\t\tself._debug(e)\n\t\tos.chdir(cwd)\n\t\treturn tmpdir+'/'+new_air_file\n\t#def _recompile_for_certificate_issue\n\t\n\n\tdef _unzip_air_file(self,air_file):\n\t\tcwd=os.getcwd()\n\t\ttmpdir=tempfile.mkdtemp()\n\t\tself._debug(\"Extracting %s to %s\"%(air_file,tmpdir))\n\t\tos.chdir(tmpdir)\n\t\tair_pkg=zipfile.ZipFile(air_file,'r')\n\t\tfor file_to_unzip in air_pkg.infolist():\n\t\t\ttry:\n\t\t\t\tair_pkg.extract(file_to_unzip)\n\t\t\texcept:\n\t\t\t\tpass\n\t\tair_pkg.close()\n\t\tos.chdir(cwd)\n\t\treturn (tmpdir)\n\n\tdef get_installed_apps(self):\n\t\tinstalled_apps={}\n\t\tif os.path.isdir(self.adobeair_folder):\n\t\t\tfor app_dir in os.listdir(self.adobeair_folder):\n\t\t\t\tself._debug(\"Testing %s\"%app_dir)\n\t\t\t\tapp_desktop=''\n\t\t\t\tif os.path.isdir(self.adobeair_folder+app_dir+'/bin') or os.path.isfile(self.adobeair_folder+app_dir+'/'+app_dir+'.air'):\n\t\t\t\t\t#Search the desktop of the app\n\t\t\t\t\tself._debug(\"Searching desktop %s\"%'/usr/share/applications/'+app_dir+'.desktop')\n\t\t\t\t\tsw_desktop=False\n\t\t\t\t\tif os.path.isdir(self.adobeair_folder+app_dir+'/share/META-INF/AIR'):\n\t\t\t\t\t\tfor pkg_file in os.listdir(self.adobeair_folder+app_dir+'/share/META-INF/AIR'):\n\t\t\t\t\t\t\tif pkg_file.endswith('.desktop'):\n\t\t\t\t\t\t\t\tapp_desktop='/usr/share/applications/'+pkg_file\n\t\t\t\t\t\t\t\tsw_desktop=True\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif sw_desktop==False:\n\t\t\t\t\t\tif os.path.isfile('/usr/share/applications/'+app_dir+'.desktop'):\n\t\t\t\t\t\t\tapp_desktop='/usr/share/applications/'+app_dir+'.desktop'\n\t\t\t\t\t\telif os.path.isfile('/usr/share/applications/'+app_dir.lower()+'.desktop'):\n\t\t\t\t\t\t\tapp_desktop='/usr/share/applications/'+app_dir.lower()+'.desktop'\n\t\t\t\t\t#Get the app_id\n\t\t\t\t\tapp_id=''\n\t\t\t\t\tself._debug(\"Searching id %s\"%self.adobeair_folder+app_dir+'/share/application.xml')\n\t\t\t\t\tif os.path.isfile(self.adobeair_folder+app_dir+'/share/application.xml'):\n\t\t\t\t\t\tf=open(self.adobeair_folder+app_dir+'/share/application.xml','r')\n\t\t\t\t\t\tflines=f.readlines()\n\t\t\t\t\t\tapp_id=''\n\t\t\t\t\t\tfor fline in flines:\n\t\t\t\t\t\t\tfline=fline.strip()\n\t\t\t\t\t\t\tif fline.startswith(''):\n\t\t\t\t\t\t\t\tapp_id=fline\n\t\t\t\t\t\t\t\tapp_id=app_id.replace('','')\n\t\t\t\t\t\t\t\tapp_id=app_id.replace('','')\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\tf.close()\n\t\t\t\t\telif os.path.isfile(self.adobeair_folder+app_dir+'/'+app_dir+'.air'):\n\t\t\t\t\t\tapp_id=app_dir+'.air'\n\t\t\t\t\tinstalled_apps[app_dir]={'desktop':app_desktop,'air_id':app_id}\n\t\treturn installed_apps\n\t#def get_installed_apps\n\n\tdef remove_air_app(self,*kwarg):\n\n\t\tdef supercow_remove(*args):\n\t\t\tair_id=args[-1]\n\t\t\tself._debug(\"Supercow remove %s\"%air_id)\n\t\t\tmy_env=os.environ.copy()\n\t\t\tmy_env[\"DISPLAY\"]=\":0\"\n\t\t\tpkgname=subprocess.check_output([\"apt-cache\",\"search\",air_id],env=my_env,universal_newlines=True)\n\t\t\tpkglist=pkgname.split(' ')\n\t\t\tfor pkg in pkglist:\n\t\t\t\tself._debug(\"Testing %s\"%pkg)\n\t\t\t\tif air_id.lower() in pkg.lower():\n\t\t\t\t\ttry:\n\t\t\t\t\t\tself._debug(\"Uninstalling %s\"%pkg)\n\t\t\t\t\t\tsw_uninstall_err=subprocess.check_output([\"apt-get\",\"-y\",\"remove\",pkg],universal_newlines=True,env=my_env)\n\t\t\t\t\t\tself._debug(\"Uninstalled OK %s\"%pkg)\n\t\t\t\t\t\tsw_err=0\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tself._debug(e)\n\t\t\t\t\tbreak\n\n\t\tsw_err=1\n\t\tmy_env=os.environ.copy()\n\t\tmy_env[\"DISPLAY\"]=\":0\"\n\t\tair_dict=kwarg[0]\n\t\tsw_uninstall_err=False\n\t\tif 'air_id' in air_dict.keys():\n\t\t\tself._debug(\"Removing %s\"%air_dict['air_id'])\n\t\t\tif air_dict['air_id'].endswith('.air'):\n\t\t\t\tair_file=self.adobeair_folder+air_dict['air_id'].replace('.air','')+'/'+air_dict['air_id']\n\t\t\t\tself._debug(\"SDK app detected %s\"%air_file)\n\t\t\t\tif os.path.isfile(air_file):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tshutil.rmtree(os.path.dirname(air_file))\n\t\t\t\t\t\tsw_err=0\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tself._debug(e)\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t#Let's try with supercow's power\n\t\t\t\t\tsupercow_remove(air_dict['air_id'])\n\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tsw_uninstall_err=True\n\t\t\t\t#Some air apps install more than one app so it's needed to check the installed desktop\n\t\t\t\ttry:\n\t\t\t\t\tif 'desktop' in air_dict.keys():\n\t\t\t\t\t\tself._debug(\"Checking full uninstall of %s\"%air_dict['desktop'])\n\t\t\t\t\t\tif os.path.isfile(air_dict['desktop']):\n\t\t\t\t\t\t\tself._debug(\"Uninstalling air from desktop\")\n\t\t\t\t\t\t\tdesktop=air_dict['desktop'].replace('.desktop','')\n\t\t\t\t\t\t\tsupercow_remove(os.path.basename(desktop))\n\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tsw_uninstall_err=True\n\n\t\t\t\t\n\t\t\t\tif sw_err:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tsw_uninstall_err=subprocess.check_output([\"/usr/bin/Adobe AIR Application Installer\",\"-silent\",\"-uninstall\",\"-location\",self.adobeair_folder,air_dict['air_id']],env=my_env)\n\t\t\t\t\t\tsw_err=0\n\t\t\t\t\texcept Exception as e:\n\t\t\t\t\t\tself._debug(e)\n\n\t\tif 'desktop' in air_dict.keys():\n\t\t\tif os.path.isfile(air_dict['desktop']):\n\t\t\t\ttry:\n\t\t\t\t\tos.remove(air_dict['desktop'])\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tself._debug(e)\n\t\treturn sw_err\n\n\tdef get_air_info(self,air_file):\n\t\tair_info={}\n\t\tself._debug(\"Info for %s\"%air_file)\n\t\ttmpdir=self._unzip_air_file(air_file)\n\t\tcwd=os.getcwd()\n\t\tos.chdir(tmpdir+'/META-INF/AIR')\n\t\ticon_line=''\n\t\tname_line=''\n\t\tif os.path.isfile('application.xml'):\n\t\t\tf=open('application.xml','r')\n\t\t\tflines=f.readlines()\n\t\t\tfor fline in flines:\n\t\t\t\tfline=fline.strip()\n\t\t\t\tif fline.startswith(''):\n\t\t\t\t\tname_line=fline\n\t\t\t\tif fline.startswith(''):\n\t\t\t\t\tif fline!='' and icon_line=='':\n\t\t\t\t\t\ticon_line=fline\n\t\t\t\t\t\tself._debug(fline)\n\t\t\tif icon_line:\n\t\t\t\tself._debug(\"ICON: %s\"%icon_line)\n\t\t\t\ticon=icon_line.replace('','')\n\t\t\t\ticon=icon.replace('','')\n\t\t\t\tif icon!='':\n\t\t\t\t\ticon=tmpdir+'/'+icon\n\t\t\t\t\tair_info['pb']=GdkPixbuf.Pixbuf.new_from_file_at_scale(icon,64,-1,True)\n\t\t\tif name_line:\n\t\t\t\tname=name_line.replace('','')\n\t\t\t\tair_info['name']=name.replace('','')\n\t\telse:\n\t\t\tair_info['name']=os.path.basename(air_file)\n\t\t\tair_info['name']=air_info['name'].replace('.air','')\n\t\t\tos.chdir(tmpdir)\n\t\t\ticon_files=glob(\"*/*48*png\")\n\t\t\tif not icon_files:\n\t\t\t\ticon_files=glob(\"*48*png\")\n\t\t\tif icon_files:\n\t\t\t\tair_info['pb']=GdkPixbuf.Pixbuf.new_from_file_at_scale(icon_files[0],64,-1,True)\n\n\t\treturn air_info\n\t#def _get_air_info\n\n\tdef _check_file_is_air(self,air_file):\n\t\tretval=False\n\t\tif air_file.endswith(\".air\"):\n\t\t\tretval=True\n\t\treturn retval\n\t#def _check_file_is_air\n\t\t\n","sub_path":"python3-air-manager/airmanager/airmanager.py","file_name":"airmanager.py","file_ext":"py","file_size_in_byte":23753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"296126013","text":"'''\r\nPython script for removing duplicate tweets (based on tweet ID) from a Twarc-hydrated CSV file\r\n'''\r\nimport argparse\r\nimport csv\r\nimport traceback\r\n\r\ndef getArgs():\r\n\targparser = argparse.ArgumentParser(description=\"Remove duplicate records (based on tweet ID) from a Twarc-hydrated CSV file\")\r\n\targparser.add_argument(\"inputFile\", help=\"Input CSV file\")\r\n\targparser.add_argument(\"outputFile\", help=\"Output CSV file\")\r\n\targs = argparser.parse_args()\r\n\treturn args\r\n\r\ndef main():\r\n\toutputFile = None\r\n\tseen = {}\r\n\targs = getArgs()\r\n\t\r\n\ttry:\r\n\t\twith open(args.inputFile, encoding='utf-8') as csvfile:\r\n\t\t\treadCSV = csv.reader(csvfile, delimiter=',')\r\n\t\t\toutputFile = open(args.outputFile, 'w', encoding='utf-8', buffering=1, newline='')\r\n\t\t\tcsvWriter = csv.writer(outputFile)\r\n\t\t\tidColumnIndex = None\r\n\t\t\tfor row in readCSV:\r\n\t\t\t\t# Get index of 'id' column from first row of CSV\r\n\t\t\t\tif idColumnIndex is None:\r\n\t\t\t\t\tidColumnIndex = row.index('id')\r\n\t\t\t\t\tcsvWriter.writerow(row)\r\n\t\t\t\telse:\r\n\t\t\t\t\ttweetId = row[idColumnIndex]\r\n\t\t\t\t\t# If tweet ID has not been seen yet, add it to the set\r\n\t\t\t\t\t# and copy the row to the output CSV file\r\n\t\t\t\t\tif tweetId not in seen:\r\n\t\t\t\t\t\tseen[tweetId] = True\r\n\t\t\t\t\t\tcsvWriter.writerow(row)\r\n\texcept:\r\n\t\tprint('\\nUnexpected error:\\n' + traceback.format_exc())\r\n\tfinally:\r\n\t\tif outputFile is not None:\r\n\t\t\toutputFile.close()\r\n\r\nif __name__ == \"__main__\":\r\n\tmain()\r\n","sub_path":"utils/csv_deduplicate.py","file_name":"csv_deduplicate.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"641969082","text":"from bs4 import BeautifulSoup\nimport requests\n\nresponse = requests.get(\"https://finance.naver.com/item/main.nhn?code=005930\")\nhtml = response.text\nsoup = BeautifulSoup(html, 'html5lib')\nresult = soup.find('table', {'class': 'tb_type1 tb_num'})\nall_data = result.select('tr:nth-of-type(11) td')\nall_result = []\nfor i in all_data:\n all_result.append(i.text)\n\n\nprint(all_result)\n","sub_path":"7.System trading/naver_fin_info.py","file_name":"naver_fin_info.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"459682514","text":"\n\nfrom xai.brain.wordbase.adjectives._fair import _FAIR\n\n#calss header\nclass _FAIREST(_FAIR, ):\n\tdef __init__(self,): \n\t\t_FAIR.__init__(self)\n\t\tself.name = \"FAIREST\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"fair\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_fairest.py","file_name":"_fairest.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"133507143","text":"#!/user/bin/python\n# coding: utf-8\n\nimport subprocess\n\n\ndef run_shell_command(command):\n \"\"\" Create a child process to run the command\n\n :param command:linux command line\n :return: stdout and stderr\n \"\"\"\n run_com = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n stdoutput, erroutput = run_com.communicate()\n return stdoutput, erroutput\n","sub_path":"logmonitor/utils/mcommand.py","file_name":"mcommand.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247593789","text":"import cv2\nimport numpy as np\n\n\ndef nothing(x):\n pass\n\n\n# Creating a window for later use\ncv2.namedWindow('result')\n\n# Starting with 100's to prevent error while masking\nh, s, v = 100, 100, 100\n\n# Creating track bar\ncv2.createTrackbar('l_h', 'result', 0, 179, nothing)\ncv2.createTrackbar('l_s', 'result', 0, 255, nothing)\ncv2.createTrackbar('l_v', 'result', 0, 255, nothing)\n\ncv2.createTrackbar('u_h', 'result', 0, 179, nothing)\ncv2.createTrackbar('u_s', 'result', 0, 255, nothing)\ncv2.createTrackbar('u_v', 'result', 0, 255, nothing)\n\nwhile(1):\n\n img = cv2.imread('training_chars_1.png')\n\n # converting to HSV\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n # get info from track bar and appy to result\n l_h = cv2.getTrackbarPos('l_h', 'result')\n l_s = cv2.getTrackbarPos('l_s', 'result')\n l_v = cv2.getTrackbarPos('l_v', 'result')\n\n u_h = cv2.getTrackbarPos('u_h', 'result')\n u_s = cv2.getTrackbarPos('u_s', 'result')\n u_v = cv2.getTrackbarPos('u_v', 'result')\n\n # Normal masking algorithm\n lower_blue = np.array([l_h, l_s, l_v])\n upper_blue = np.array([u_h, u_s, u_v])\n\n mask = cv2.inRange(hsv, lower_blue, upper_blue)\n\n result = cv2.bitwise_and(img, img, mask=mask)\n\n cv2.imshow('result', result)\n\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n\ncv2.destroyAllWindows()\n","sub_path":"knn/get_hsv.py","file_name":"get_hsv.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"254068258","text":"'''\nGiven an array of integers nums, write a method that returns the \"pivot\" index of this array.\n\nWe define the pivot index as the index where the sum of the numbers to the left of the index \nis equal to the sum of the numbers to the right of the index.\n\nIf no such index exists, we should return -1. If there are multiple pivot indexes, you should \nreturn the left-most pivot index.\n\nExample 1:\n\nInput: \nnums = [1, 7, 3, 6, 5, 6]\nOutput: 3\nExplanation: \nThe sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the \nright of index 3.\nAlso, 3 is the first index where this occurs.\n \n\nExample 2:\n\nInput: \nnums = [1, 2, 3]\nOutput: -1\nExplanation: \nThere is no index that satisfies the conditions in the problem statement.\n'''\n\ndef pivot_index(nums):\n S = sum(nums)\n leftsum = 0\n for i, x in enumerate(nums):\n if leftsum == (S - leftsum - x):\n return i\n leftsum += x\n return -1\n\ndef pivot_index_v2(nums):\n left, right = [0] * len(nums), [0] * len(nums)\n\n for i in range(1, len(nums)):\n left[i] = nums[i - 1] + left[i - 1]\n\n for i in range(len(nums) - 2, -1, - 1):\n right[i] = nums[i + 1] + right[i + 1]\n\n for i in range(len(left)):\n if left[i] == right[i]: return i \n\n return -1\n\n","sub_path":"algorithms/arrays/find_pivot_index.py","file_name":"find_pivot_index.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"328887873","text":"# -*- coding: utf-8 -*-\n# Copyright 2018 ICON Foundation Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport asyncio\nimport inspect\nimport logging\nimport shutil\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import TYPE_CHECKING, Optional\n\nfrom iconcommons.icon_config import IconConfig\nfrom iconcommons.logger import Logger\n\nfrom iconservice.base.address import Address\nfrom iconservice.base.block import Block\nfrom iconservice.icon_config import default_icon_config\nfrom iconservice.icon_service_engine import IconServiceEngine\nfrom . import utils\nfrom .block_database_reader import BlockDatabaseReader\nfrom .loopchain_block import LoopchainBlock\n\nif TYPE_CHECKING:\n from iconservice.precommit_data_manager import PrecommitData, PrecommitDataManager\n from iconservice.database.batch import BlockBatch\n\n\nclass IconServiceSyncer(object):\n _TAG = \"SYNC\"\n\n def __init__(self):\n self._block_reader = BlockDatabaseReader()\n self._engine = IconServiceEngine()\n\n def open(self,\n config_path: str,\n fee: bool = True,\n audit: bool = True,\n deployer_whitelist: bool = False,\n score_package_validator: bool = False,\n builtin_score_owner: str = ''):\n conf = IconConfig(\"\", default_icon_config)\n\n if config_path != \"\":\n conf.load(config_path)\n\n conf.update_conf({\n \"builtinScoreOwner\": builtin_score_owner,\n \"service\": {\n \"fee\": fee,\n \"audit\": audit,\n \"scorePackageValidator\": score_package_validator,\n \"deployerWhiteList\": deployer_whitelist\n }\n })\n\n Logger.load_config(conf)\n self._engine.open(conf)\n\n def run(self, *args, **kwargs) -> int:\n Logger.debug(tag=self._TAG, msg=f\"run() start: {args} {kwargs}\")\n\n loop = asyncio.get_event_loop()\n future = asyncio.Future()\n\n try:\n asyncio.ensure_future(self._wait_for_complete(future, *args, **kwargs))\n loop.run_until_complete(future)\n finally:\n self._engine.close()\n loop.close()\n\n ret = future.result()\n Logger.debug(tag=self._TAG, msg=f\"run() end: {ret}\")\n\n return ret\n\n async def _wait_for_complete(self, result_future: asyncio.Future, *args, **kwargs):\n Logger.debug(tag=self._TAG, msg=\"_wait_for_complete() start\")\n\n executor = ThreadPoolExecutor(max_workers=1)\n f = executor.submit(self._run, *args, **kwargs)\n future = asyncio.wrap_future(f)\n\n await future\n\n Logger.debug(tag=self._TAG, msg=\"_wait_for_complete() end1\")\n result_future.set_result(future.result())\n\n Logger.debug(tag=self._TAG, msg=\"_wait_for_complete() end2\")\n\n def _run(self,\n db_path: str,\n channel: str,\n start_height: int = 0,\n count: int = 99999999,\n stop_on_error: bool = True,\n no_commit: bool = False,\n backup_period: int = 0,\n write_precommit_data: bool = False) -> int:\n \"\"\"Begin to synchronize IconServiceEngine with blocks from loopchain db\n\n :param db_path: loopchain db path\n :param channel: channel name used as a key to get commit_state in loopchain db\n :param start_height: start height to sync\n :param count: The number of blocks to sync\n :param stop_on_error: If error happens, stop syncing\n :param no_commit: Do not commit\n :param backup_period: state backup period in block\n :param write_precommit_data:\n :return: 0(success), otherwise(error)\n \"\"\"\n Logger.debug(tag=self._TAG, msg=\"_run() start\")\n\n ret: int = 0\n self._block_reader.open(db_path)\n\n print('block_height | commit_state | state_root_hash | tx_count')\n\n prev_block: Optional['Block'] = None\n\n for height in range(start_height, start_height + count):\n block_dict: dict = self._block_reader.get_block_by_block_height(height)\n if block_dict is None:\n print(f'last block: {height - 1}')\n break\n\n loopchain_block = LoopchainBlock.from_dict(block_dict)\n block: 'Block' = utils.create_block(loopchain_block)\n tx_requests: list = utils.create_transaction_requests(loopchain_block)\n\n if prev_block is not None:\n # print(f'prev_block({prev_block.hash.hex()}) == block({block.prev_hash.hex()})')\n if prev_block.hash != block.prev_hash:\n raise Exception()\n\n invoke_result = self._engine.invoke(block, tx_requests)\n tx_results, state_root_hash = invoke_result[0], invoke_result[1]\n commit_state: bytes = self._block_reader.get_commit_state(block_dict, channel, b'')\n\n # \"commit_state\" is the field name of state_root_hash in loopchain block\n print(f'{height} | {commit_state.hex()[:6]} | {state_root_hash.hex()[:6]} | {len(tx_requests)}')\n\n if write_precommit_data:\n self._print_precommit_data(block)\n\n try:\n if stop_on_error:\n if commit_state:\n if commit_state != state_root_hash:\n raise Exception()\n\n if height > 0 and not self._check_invoke_result(tx_results):\n raise Exception()\n except Exception as e:\n logging.exception(e)\n\n print(block_dict)\n self._print_precommit_data(block)\n ret: int = 1\n break\n\n if not no_commit:\n if 'block' in inspect.signature(self._engine.commit).parameters:\n self._engine.commit(block)\n else:\n self._engine.commit(block.height, block.hash, None)\n\n self._backup_state_db(block, backup_period)\n prev_block = block\n\n self._block_reader.close()\n\n Logger.debug(tag=self._TAG, msg=f\"_run() end: {ret}\")\n return ret\n\n def _check_invoke_result(self, tx_results: list):\n \"\"\"Compare the transaction results from IconServiceEngine\n with the results stored in loopchain db\n\n If transaction result is not compatible to protocol v3, pass it\n\n :param tx_results: the transaction results that IconServiceEngine.invoke() returns\n :return: True(same) False(different)\n \"\"\"\n\n for tx_result in tx_results:\n tx_info_in_db: dict =\\\n self._block_reader.get_transaction_result_by_hash(\n tx_result.tx_hash.hex())\n tx_result_in_db = tx_info_in_db['result']\n\n # tx_v2 dose not have transaction result_v3\n if 'status' not in tx_result_in_db:\n continue\n\n # information extracted from db\n status: int = int(tx_result_in_db['status'], 16)\n tx_hash: bytes = bytes.fromhex(tx_result_in_db['txHash'])\n step_used: int = int(tx_result_in_db['stepUsed'], 16)\n step_price: int = int(tx_result_in_db['stepPrice'], 16)\n event_logs: list = tx_result_in_db['eventLogs']\n step: int = step_used * step_price\n\n if tx_hash != tx_result.tx_hash:\n print(f'tx_hash: {tx_hash.hex()} != {tx_result.tx_hash.hex()}')\n return False\n if status != tx_result.status:\n print(f'status: {status} != {tx_result.status}')\n return False\n if step_used != tx_result.step_used:\n print(f'step_used: {step_used} != {tx_result.step_used}')\n return False\n\n tx_result_step: int = tx_result.step_used * tx_result.step_price\n if step != tx_result_step:\n print(f'step: {step} != {tx_result_step}')\n return False\n if step_price != tx_result.step_price:\n print(f'step_price: {step_price} != {tx_result.step_price}')\n return False\n\n if not self._check_event_logs(event_logs, tx_result.event_logs):\n return False\n\n return True\n\n @staticmethod\n def _check_event_logs(event_logs_in_db: list,\n event_logs_in_tx_result: list):\n for event_log, _tx_result_event_log in zip(event_logs_in_db, event_logs_in_tx_result):\n tx_result_event_log: dict = _tx_result_event_log.to_dict()\n\n # convert Address to str\n if 'score_address' in tx_result_event_log:\n score_address: 'Address' = tx_result_event_log['score_address']\n del tx_result_event_log['score_address']\n tx_result_event_log['scoreAddress'] = str(score_address)\n\n # convert Address objects to str objects in 'indexes'\n indexed: list = tx_result_event_log['indexed']\n for i in range(len(indexed)):\n value = indexed[i]\n indexed[i] = utils.object_to_str(value)\n\n data: list = tx_result_event_log['data']\n for i in range(len(data)):\n value = data[i]\n data[i] = utils.object_to_str(value)\n\n if event_log != tx_result_event_log:\n print(f'{event_log} != {tx_result_event_log}')\n return False\n\n return True\n\n def _print_precommit_data(self, block: 'Block'):\n \"\"\"Print the latest updated states stored in IconServiceEngine\n\n :return:\n \"\"\"\n precommit_data_manager: PrecommitDataManager =\\\n getattr(self._engine, '_precommit_data_manager')\n\n precommit_data: PrecommitData = precommit_data_manager.get(block.hash)\n block_batch: BlockBatch = precommit_data.block_batch\n state_root_hash: bytes = block_batch.digest()\n\n filename = f'{block.height}-precommit-data.txt'\n with open(filename, 'wt') as f:\n for i, key in enumerate(block_batch):\n value: bytes = block_batch[key]\n\n if value:\n line = f'{i}: {key.hex()} - {value.hex()}'\n else:\n line = f'{i}: {key.hex()} - None'\n\n print(line)\n f.write(f'{line}\\n')\n\n f.write(f'state_root_hash: {state_root_hash.hex()}\\n')\n\n @staticmethod\n def _backup_state_db(block: 'Block', backup_period: int):\n if backup_period <= 0:\n return\n if block.height == 0:\n return\n\n if block.height % backup_period == 0:\n print(f\"----------- Backup statedb: {block.height} ------------\")\n dirname: str = f\"block-{block.height}\"\n\n for basename in (\".score\", \".statedb\"):\n try:\n shutil.copytree(basename, f\"{dirname}/{basename}/\")\n except FileExistsError:\n pass\n\n def close(self):\n pass\n","sub_path":"icondbtools/icon_service_syncer.py","file_name":"icon_service_syncer.py","file_ext":"py","file_size_in_byte":11501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"155946991","text":"#!/usr/bin/python3\n\nimport socket, time \n \nsock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) \nsock.bind((\"0.0.0.0\", 1060)) \nsock.listen(2) \n \nsrc, src_addr = sock.accept() \nprint(\"Source Connected by \", src_addr)\n \ndst, dst_addr = sock.accept() \nprint(\"Destination Connected by \", dst_addr) \n \nwhile True: \n msg = src.recv(1024 * 1024) \n #print len(msg) \n if not msg: \n break \n try: \n dst.sendall(msg) \n except Exception as ex: \n dst, dst_addr = sock.accept() \n print(\"Destination Connected Again By \", dst_addr)\n except KeyboardInterrupt: \n print(\"Interrupted\")\n break \n \nsrc.close() \ndst.close() \nsock.close() \n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"90483619","text":"import torch\nimport torch.nn.functional as F\nimport ganet_lib\nimport tools\nimport utils\n\ndef calc_cost(left_image, right_image, disparity, kenel_size, method):\n batch, channel, height, width = left_image.size()\n min_disparity, max_disparity = disparity\n assert left_image.is_contiguous()\n assert right_image.is_contiguous()\n assert max_disparity > min_disparity\n assert kenel_size % 2 == 1, 'kenel_size must be odd number'\n\n with torch.cuda.device_of(left_image):\n disparity_range = max_disparity - min_disparity\n cost = torch.zeros((batch, disparity_range, height, width), dtype=torch.float).to(left_image.device).contiguous()\n ganet_lib.cuda_calc_cost(left_image, right_image, cost, kenel_size, min_disparity, method)\n # return cost[:, :, :, (max_disparity - 1): (width + min_disparity)].contiguous()\n return cost\n\ndef sgm(cost, p1, p2):\n batch, max_disparity, height, width = cost.size()\n assert cost.is_contiguous()\n\n with torch.cuda.device_of(cost):\n cost_agg = cost.new().resize_((batch, 8, max_disparity, height, width)).zero_()\n ganet_lib.cuda_sgm(cost, cost_agg, p1, p2)\n disparity = cost_agg.sum(dim=1).argmin(dim=1)\n return disparity.float()\n\nclass SGM:\n def __init__(self, method, kernel_size, max_disparity, max_disparity_diff=1.5):\n self.max_disparity = max_disparity\n self.max_disparity_diff = max_disparity_diff\n self.kernel_size = kernel_size\n\n if method == 'SAD':\n self.P1 = 8 * 3 * kernel_size ** 2 / 255.0\n self.P2 = 32 * 3 * kernel_size ** 2 / 255.0\n self.cost_method = 0\n\n elif method == 'CENSUS_AVG':\n self.P1 = 0.1 * 3 * kernel_size ** 2\n self.P2 = 2 * 3 * kernel_size ** 2\n self.cost_method = 1\n\n elif method == 'CENSUS_FIX':\n self.P1 = 0.1 * 3 * kernel_size ** 2\n self.P2 = 2 * 3 * kernel_size ** 2\n self.cost_method = 2\n\n elif method == 'NCC':\n self.P1 = 0.1\n self.P2 = 2\n self.cost_method = 3\n\n else:\n raise Exception('Unknown method: ' + method)\n\n def process(self, X, lr_check=False):\n # left_image = (X[:, 0:3, :, :] * 255).type(torch.ByteTensor).to(X.device)\n # right_image = (X[:, 3:6, :, :] * 255).type(torch.ByteTensor).to(X.device)\n left_image = X[:, 0:3, :, :].contiguous()\n right_image = X[:, 3:6, :, :].contiguous()\n\n if lr_check:\n cost = calc_cost(right_image, left_image, (- self.max_disparity + 1, 1), self.kernel_size, self.cost_method)\n disp_right = sgm(cost, self.P1, self.P2) - self.max_disparity + 1\n disp_right[:, :, (1 - self.max_disparity):] = -1\n\n cost = calc_cost(left_image, right_image, (0, self.max_disparity), self.kernel_size, self.cost_method)\n disp_left = sgm(cost, self.P1, self.P2)\n disp_left[:, :, :(self.max_disparity - 1)] = -1\n\n ganet_lib.cuda_left_right_consistency_check(disp_left, disp_right, self.max_disparity_diff)\n else:\n cost = calc_cost(left_image, right_image, (0, self.max_disparity), self.kernel_size, self.cost_method)\n disp_left = sgm(cost, self.P1, self.P2)\n disp_left[:, :, :(self.max_disparity - 1)] = -1\n\n return cost, disp_left\n\n\nclass CostVolumeData:\n def __init__(self, name, cost=None, disp=None):\n self.name = name\n self.cost = cost[0].data.cpu().numpy() if cost is not None else None\n self.disp = disp[0].data.cpu().numpy() if disp is not None else None\n self.marker = None\n self.line_style = '-'\n self.line_width = 5\n self.color = None\n\ndef diff_location(input, target):\n assert input.dim() == 2\n assert target.dim() == 2\n\n valid_indices = (input != -1) & (target != 0)\n epe = (input - target).abs()\n\n epe = epe.data.cpu().numpy()\n valid_indices = valid_indices.data.cpu().numpy()\n\n epe_list = []\n for r in range(input.shape[0]):\n for c in range(input.shape[1]):\n if valid_indices[r, c]:\n epe_list.append((r, c, epe[r, c]))\n epe_list.sort(key=lambda x: x[2], reverse=True)\n return epe_list\n\ndef sgm_better_location(model_disp, sgm_disp, target, pixel_range=10):\n assert model_disp.dim() == 2\n assert sgm_disp.dim() == 2\n assert target.dim() == 2\n\n valid_indices = (model_disp != 0) & (model_disp != -1) & (sgm_disp != -1) & (target != 0)\n epe_model = (model_disp - target).abs()\n epe_sgm = (sgm_disp - target).abs()\n\n epe_model = epe_model.data.cpu().numpy()\n epe_sgm = epe_sgm.data.cpu().numpy()\n valid_indices = valid_indices.data.cpu().numpy()\n\n epe_diff = epe_model - epe_sgm\n\n epe_list = []\n for r in range(target.shape[0]):\n for c in range(target.shape[1]):\n if valid_indices[r, c]:\n epe_list.append((r, c, epe_diff[r, c]))\n epe_list.sort(key=lambda x: x[2], reverse=True)\n\n sgm_better = []\n for p in epe_list:\n if not is_in_range(sgm_better, p, pixel_range):\n sgm_better.append(p)\n if len(sgm_better) >= 5:\n break\n\n model_better = []\n for p in epe_list[::-1]:\n if not is_in_range(model_better, p, pixel_range):\n model_better.append(p)\n if len(model_better) >= 5:\n break\n\n return sgm_better, model_better\n\ndef is_in_range(p_list, x, pixel_range):\n for p in p_list:\n if abs(p[0] - x[0]) <= pixel_range:\n return True\n if abs(p[1] - x[1]) <= pixel_range:\n return True\n return False\n\n\n","sub_path":"utils/cost_volume.py","file_name":"cost_volume.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"77240832","text":"# coding:cp949\n\ncount = 0\nfreeT = 3\nmembershipT = 5\npay = 0\n\nwhile True:\n\n while True:\n print(\"나이를 입력하세요: \",end='')\n age = int(input());\n if(age < 0):\n print(\"다시 입력하세요.\")\n continue\n\n grade = ''\n if(age <= 3):\n fee = 0\n grade = '유아'\n break\n elif(age <= 13):\n fee = 2000\n grade = '어린이'\n break\n elif(age <= 18):\n fee = 3000\n grade = '청소년'\n break\n elif(age <= 65):\n fee = 5000\n grade = '성인'\n break\n else:\n fee = 0\n grade = '노인'\n break\n\n print(\"귀하는 {0}등급이며 요금은 {1}원 입니다.\".format(grade,fee))\n if(fee != 0):\n \n while True:\n print(\"요금 유형을 선택하세요. (1: 현금, 2: 공원 전용 신용 카드): \",end='')\n payType = int(input())\n\n # 1. 현금인 경우\n if(payType == 1):\n print(\"요금을 입력하세요.: \",end='')\n pay = int(input())\n if(pay < 0):\n print(\"다시 입력하세요.\")\n continue\n # 금액 미만\n if(pay < fee):\n print(\"{0}가 모자랍니다. 입력 하신 {1}를 반환합니다.\".format((fee-pay),pay))\n pay = 0\n continue\n # 금액 일치\n elif(pay == fee):\n print(\"감사합니다. 티켓을 발행합니다.\")\n # 금액 초과\n elif(pay > fee):\n print(\"감사합니다. 티켓을 발행하고 거스름돈 {0}를 반환합니다.\".format((pay-fee)))\n break\n # 2. 공원 전용 신용 카드\n elif(payType == 2):\n # (결제 금액의 10% 할인, 60-65세 장년은 추가 5% 할인(10% 할인한 상태에서 5%할인)\n\n if((age <= 65) and (age >=60)):\n pay = int((fee*0.9)*0.95)\n else:\n pay = int(fee*0.9)\n print(\"{0}원 결제 되었습니다. 티켓을 발행합니다.\".format(pay))\n break\n\n if(pay !=0):\n count+=1\n print(\"{0}명\".format(count))\n \n \n if(count != 0):\n #7번째 손님 마다 티켓 무료 티켓을 발행(초기 무료 티켓: 3장)- 7배수 무료티켓\n if(((count % 7) == 0) and (freeT != 0) ):\n freeT-=1\n print(\"축하합니다. 1주년 이벤트에 당첨되었습니다. 여기 무료 티켓을 발행합니다. 잔여 무료티켓 {0}장\".format(freeT))\n\n #4번째 손님 마다 티켓 구매시 연간 회원권 홍보 이벤트 (초기 할인 티켓: 5장) - 4배수 연간회원\n if(((count % 4) == 0) and (membershipT != 0 )):\n membershipT-=1\n print(\"축하합니다. 연간회원권 구매 이벤트에 당첨되셨습니다. 연간 회원 할인 티켓을 발행합니다. 잔여 할인 티켓 {0}장\".format(membershipT))\n\n\n","sub_path":"01_Jump_to_Python/Chap03/0502/project5.py","file_name":"project5.py","file_ext":"py","file_size_in_byte":3247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"298155870","text":"import sqlite3\nfrom wx import *\nfrom datetime import *\nimport os.path\nimport shutil\n\n# Today - 24 hours = \"yesterday\"\nyesterday = datetime.now() - timedelta(days=1)\n\n# Setting up SQLite\nconn = sqlite3.connect('TranDB.db')\nc = conn.cursor()\n\nclass windowClass(Frame):\n\n # Frame makin'\n def __init__(self, *args, **kwargs):\n super(windowClass, self).__init__(size=(470,175),*args, **kwargs)\n self.basicGUI()\n self.Center()\n \n#------------------------WIDGETS & VARIABLES------------------------#\n\n def basicGUI(self):\n # Settin' it up\n panel = Panel(self)\n self.SetTitle('File Transfer Manager')\n self.Show(True)\n\n # Menu bar\n menuBar = MenuBar()\n self.SetMenuBar(menuBar)\n \n # File menu\n fileButton = Menu()\n menuBar.Append(fileButton, 'File')\n\n # File - \"Check/Transfer\"\n checkItem = MenuItem(fileButton, ID_ANY,\"Check/Transfer Files...\")\n fileButton.Append(checkItem)\n self.Bind(EVT_MENU, self.Message, checkItem)\n\n # File - \"Date/Time of Last Check\"\n timeItem = MenuItem(fileButton, ID_ANY,\"Time of Last Check\")\n fileButton.Append(timeItem)\n self.Bind(EVT_MENU, self.TimeMessage, timeItem)\n\n # File - \"Quit\"\n exitItem = MenuItem(fileButton, ID_EXIT,\"Quit\")\n fileButton.Append(exitItem)\n self.Bind(EVT_MENU, self.Quit, exitItem)\n \n # Directory textbox labels\n srcText = StaticText(panel, -1, \"Browse for source directory...\",(10,10))\n destText = StaticText(panel, -1, \"Browse for destination directory...\",(10,57))\n\n # Directory textboxes\n self.control1 = TextCtrl(panel,size=(200, -1),pos=(10,27), style=TE_READONLY)\n self.control2 = TextCtrl(panel,size=(200, -1),pos=(10,74), style=TE_READONLY)\n\n # Browse buttons\n srcBtn = Button(panel, label=\"Browse\",pos=(217,26))\n srcBtn.Bind(EVT_BUTTON, self.onDir1)\n destBtn = Button(panel, label=\"Browse\",pos=(217,73))\n destBtn.Bind(EVT_BUTTON, self.onDir2)\n\n # Check/Transfer button\n checkBtn = Button(panel, label=\"Check/Transfer\",size=(110,73),pos=(325,26))\n checkBtn.Bind(EVT_BUTTON, self.Message)\n\n\n#------------------------FUNCTIONS------------------------#\n \n # SQL --- ADD INFO TO TABLE\n def insertCell(self, add):\n c.execute(\"INSERT INTO LastCheck (DateTime) VALUES (?)\", (add,))\n conn.commit()\n\n # SQL --- RETRIEVE LAST RECORD\n def getCell(self):\n c.execute(\"SELECT * FROM LastCheck ORDER BY ID DESC LIMIT 1\")\n return c.fetchall()\n \n # Figure out how many new files are in source directory\n def counting(self):\n count = 0\n for file in os.listdir(self.srcPath):\n mod = self.modTime(self.srcPath+\"//\"+file)\n if yesterday < mod:\n count = count+1\n return count\n \n # Get 'Date Modified' for a file\n def modTime(self, filePath):\n t = os.path.getmtime(filePath)\n return datetime.fromtimestamp(t)\n\n # Dialog box giving number of new files\n # and asking if you'd like to transfer them\n def Message(self, e):\n try:\n checkBox = MessageDialog(None, 'There are currently '+str(self.counting())+\n ' new files in the source folder. Copy them to the destination folder?',\n caption='Check or Transfer Files',style=YES_NO|CENTRE, pos=DefaultPosition)\n checkAnswer = checkBox.ShowModal()\n if checkAnswer == ID_YES:\n self.Transfer()\n checkBox.Destroy()\n timeNow = datetime.now().strftime(\"%a, %b %d %Y at %I:%M %p\")\n self.insertCell(timeNow)\n except:\n print(\"You failed to specify one or more directories.\")\n\n # Dialog box giving time of last file check\n def TimeMessage(self, e):\n timeBox = MessageDialog(None, 'The most recent File Check was performed on '+(str(self.getCell())[8:-3])+'.',\n caption='Last File Check',style=OK|CENTRE, pos=DefaultPosition)\n timeAnswer = timeBox.ShowModal()\n if timeAnswer == ID_OK:\n timeBox.Destroy()\n\n # Makes GUI close\n def Quit(self, e):\n self.Close()\n\n # Where the magic happens\n def Transfer(self):\n for file in os.listdir(self.srcPath):\n mod = self.modTime(self.srcPath+\"//\"+file)\n\n # Transfer the files that were modified in the last 24 hours\n if yesterday < mod:\n shutil.copy((self.srcPath+\"//\"+file), self.destPath)\n print(self.srcPath+\"//\"+file+\" successfully copied.\")\n\n # Ignore older files\n elif yesterday > mod:\n print(\"File skipped.\")\n print(\"Operation completed.\")\n\n # Adds directory paths to the textboxes\n def TextBox1(self, path):\n self.control1.ChangeValue(path)\n\n def TextBox2(self, path):\n self.control2.ChangeValue(path)\n \n # Dialog: Browse for source folder\n def onDir1(self, event):\n dlg = DirDialog(self, \"Choose a directory:\",\n style=DD_DEFAULT_STYLE\n )\n if dlg.ShowModal() == ID_OK:\n self.srcPath = dlg.GetPath()\n self.TextBox1(self.srcPath)\n dlg.Destroy()\n \n\n # Dialog: Browse for destination folder\n def onDir2(self, event):\n dlg = DirDialog(self, \"Choose a directory:\",\n style=DD_DEFAULT_STYLE\n )\n if dlg.ShowModal() == ID_OK:\n self.destPath = dlg.GetPath()\n self.TextBox2(self.destPath)\n dlg.Destroy()\n\n# Do it up\ndef main():\n app = App()\n windowClass(None)\n\n app.MainLoop()\n\nmain()\n \n\n\n\n","sub_path":"DBtransfer/transferdrillDBpy3.py","file_name":"transferdrillDBpy3.py","file_ext":"py","file_size_in_byte":5880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"507451847","text":"from os import path\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom wordcloud import WordCloud, STOPWORDS\n\ndef make_word_cloud(text, output_file, mask_file = \"images/hotel3.jpg\", show = False):\n mask = np.array(Image.open(mask_file))\n\n stopwords = set(STOPWORDS)\n\n wc = WordCloud(background_color=\"white\", max_words=2000, mask=mask,\n stopwords=stopwords)\n # generate word cloud\n wc.generate(text)\n\n # store to file\n wc.to_file( output_file)\n\n if show:\n plt.imshow(wc, interpolation='bilinear')\n plt.axis(\"off\")\n plt.figure()\n plt.imshow(mask, cmap=plt.cm.gray, interpolation='bilinear')\n plt.axis(\"off\")\n plt.show()\n\nif __name__ == \"__main__\":\n d = path.dirname(__file__)\n\n # Read the whole text.\n text = open(path.join(d, 'SentimentAnalysis.py')).read()\n\n # read the mask image\n # taken from\n # http://www.stencilry.org/stencils/movies/alice%20in%20wonderland/255fk.jpg\n mask = np.array(Image.open(path.join(d, \"images/hotel3.jpg\")))\n\n stopwords = set(STOPWORDS)\n stopwords.add(\"said\")\n\n wc = WordCloud(background_color=\"white\", max_words=2000, mask=mask,\n stopwords=stopwords)\n # generate word cloud\n wc.generate(text)\n\n # store to file\n wc.to_file(path.join(d, \"images/hotel_word_cloud.png\"))\n\n # show\n plt.imshow(wc, interpolation='bilinear')\n plt.axis(\"off\")\n plt.figure()\n plt.imshow(mask, cmap=plt.cm.gray, interpolation='bilinear')\n plt.axis(\"off\")\n plt.show()","sub_path":"word_cloud.py","file_name":"word_cloud.py","file_ext":"py","file_size_in_byte":1564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"164103215","text":"import numpy as np \nimport requests\nfrom bs4 import BeautifulSoup\n\ndef extractPoem(url):\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n p1 = soup.find_all('div', class_='m1')\n p2 = soup.find_all('div', class_='m2')\n poem = [(p1[i].get_text(), p2[i].get_text()) for i in range(len(p1))]\n return poem\n\ndef extractPoems(url_format, no):\n urls = [url_format + str(i) for i in range(1, no + 1)]\n poems = []\n for i in range(len(urls)):\n poems.append(extractPoem(urls[i]))\n print('\\b'*20, f'{i+1} done...', end='')\n return poems\n\n\ndef writeToFile(file, poems):\n with open(file, 'w') as f:\n for poem in poems:\n for beyt in poem:\n f.write(beyt[0] + ' E' + '\\n')\n f.write(beyt[1] + ' E' + '\\n')\n print('Printed in file :)')\n\ndef readFromFile(file):\n with open(file, encoding=\"utf8\") as f:\n poems = f.readlines()\n poems = [i.replace('\\u200c', ' ') for i in poems]\n return poems\n\ndef preprocessWords(unique_words):\n bad_words = []\n for word in unique_words:\n if len(word)==1:\n bad_words.append(word)\n for word in bad_words:\n unique_words.remove(word)\n return unique_words\n\ndef count(poems, *words):\n seq = ' '.join(words)\n c = 0\n for poem in poems:\n if poem.find(seq + ' ')!=-1:\n c+=1\n return c\n\ndef guessNext(text, N, top, unique_words, poems):\n text_words = text.split()\n last_text_words = text_words[-N+1:]\n no_of_words = len(unique_words)\n probs = dict()\n for word in unique_words:\n temp = last_text_words+ [word]\n num = count(poems, *temp)\n den = count(poems, *last_text_words)\n probs[word] = np.log((num+1) / (den+no_of_words))\n\n largests = sorted(probs, key=probs.get, reverse=True)[:top]\n new_texts = [text + ' ' + largests[i] for i in range(len(largests))]\n return new_texts, largests\n\ndef guessNexts(text_list, N, top, unique_words, poems):\n new_texts = []\n for text in text_list:\n nt, _ = guessNext(text, N, top, unique_words, poems)\n new_texts.extend(nt)\n return new_texts\n\ndef completeIt(text_list, N, no, top, unique_words, poems):\n texts = text_list[:]\n for i in range(no):\n texts = guessNexts(texts, N, top, unique_words, poems)\n print(i, texts)\n return texts\n\nif __name__=='__main__':\n hafez_url_format = \"http://ganjoor.net/hafez/ghazal/sh\"\n saadi_url_format = \"https://ganjoor.net/saadi/divan/ghazals/sh\"\n #poems = extractPoems(hafez_url_format, 495)\n #writeToFile('Hafez.txt', poems)\n #poems = extractPoems(saadi_url_format, 637)\n #writeToFile('Saadi.txt', poems)\n poems = []\n poems.extend(readFromFile('Saadi.txt'))\n poems.extend(readFromFile('Hafez.txt'))\n unique_words = set([word for poem in poems for word in poem.split()])\n print('Len: ', len(unique_words))\n unique_words = preprocessWords(unique_words)\n print('Len: ', len(unique_words))\n no_of_words = len(unique_words)\n text = 'دوش وقت سحر'\n N = 2\n #new_texts, l = guessNext(text, 2)\n #print(guessNexts([text], 2))\n print(completeIt([text], 2, 4, 2, unique_words, poems))\n","sub_path":"MHPoet.py","file_name":"MHPoet.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"545963586","text":"from pymongo import MongoClient\nfrom datetime import datetime\nclient = MongoClient()\n\ndb = client.IoTDb\na = []\ndata = db.devices.find({'device':'sensor_1'})\nfor document in data:\n t = datetime.strptime(document['timestamp'], '%Y-%m-%d %H:%M:%S.%f')\n a.append(int(t.year))\nprint (a)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"528037144","text":"import time\r\n\r\ndef dekor(func):\r\n def nova():\r\n time_start = time.time()\r\n name = func.__name__\r\n rezultat = func()\r\n time_end = time.time()\r\n start_end = time_end - time_start\r\n return \"Vreme ulaska: \" + str(time_start) + \",
Naziv funkcije: \" + str(name) + \",
Rezultat: \"\\\r\n + str(rezultat) + \",
Vreme izlaska: \" + str(time_end) + \\\r\n \",
Vreme provedeno u dekorativnoj funkciji: \" + str(start_end)\r\n return nova\r\n\r\nniz = []\r\n@dekor\r\ndef fib():\r\n global niz\r\n # niz.append(1)\r\n # niz.append(1)\r\n #\r\n # for i in range(30):\r\n # niz.append(niz[-1] + niz[-2])\r\n\r\n if(len(niz) < 2):\r\n niz.append(1)\r\n fib()\r\n if(len(niz) < 32):\r\n niz.append(niz[-1] + niz[-2])\r\n fib()\r\n\r\n return niz\r\n\r\nprint(fib())\r\n\r\n","sub_path":"dec.py","file_name":"dec.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"255238126","text":"import json\nimport logging\nimport random\nfrom threading import Thread\n\nimport pika\n\nfrom connector.quik.QueueName import QueueName\nfrom connector.quik.WebQuikConnector import WebQuikConnector\nfrom connector.quik.MsgId import MsgId\n\n\nclass WebQuikBroker:\n \"\"\"\n Broker facade for QuikConnector. Holds account info, can make orders.\n Supports only simple buy/sell at the moment\n Todo: add different types of orders: stop, market ...\n \"\"\"\n\n def __init__(self, connector: WebQuikConnector, client_code, trade_account, rabbit_host):\n self._logger = logging.getLogger(__name__)\n\n self._rabbit_host = rabbit_host\n self.client_code = client_code\n self.trade_account = trade_account\n # 21001:\"Заявки\",\n # 21003:\"Сделки\",\n # 21004:\"Денежн.лимиты\"\n # 21005:\"Бумаж.лимиты\",\n self.callbacks = {\n MsgId.ORDERS: self.on_orders,\n MsgId.TRADES: self.on_trades,\n MsgId.TRADE_ACCOUNTS: self.on_trade_accounts,\n MsgId.TRADES_FX: self.on_trades_fx,\n MsgId.MONEY_LIMITS: self.on_money_limits,\n MsgId.STOCK_LIMITS: self.on_stock_limits,\n MsgId.LIMIT_HAS_RECEIVED: self.on_limit_received,\n MsgId.ORDER_REPLY: self.on_order_answer,\n MsgId.TRANS_REPLY: self.on_trans_reply\n }\n self._connector = connector\n self._connector.subscribe(self.callbacks)\n self._broker_subscribers = {}\n # accounts dictionary class_code -> account info\n # Usually different accounts for securities, futures, forex ??\n\n # Init rabbit mq\n self._logger.info(f\"Init rabbit connection to {rabbit_host}\")\n self._rabbit_connection = pika.BlockingConnection(pika.ConnectionParameters(rabbit_host))\n # self._rabbit_connection = pika.connection.Connection(pika.ConnectionParameters(rabbit_host))\n self._rabbit_channel = self._rabbit_connection.channel()\n for q in [QueueName.TRADE_ACCOUNT,\n QueueName.ORDERS,\n QueueName.TRADES,\n QueueName.MONEY_LIMITS,\n QueueName.STOCK_LIMITS\n ]:\n self._logger.info(f\"Declaring rabbit queue {q}\")\n self._rabbit_channel.queue_declare(queue=q, durable=True)\n\n # Subscribe to buy/sell events in new thread because pika consumes synchronously only\n self._consumer_rabbit_connection = None\n self._consumer_rabbit_channel = None\n Thread(target=self.listen_commands).start()\n\n self._logger.info(\"Initialized\")\n\n def listen_commands(self):\n \"\"\"\n Consuming buy/sell commands from rabbit\n \"\"\"\n self._consumer_rabbit_connection = pika.BlockingConnection(pika.ConnectionParameters(self._rabbit_host))\n self._consumer_rabbit_channel = self._consumer_rabbit_connection.channel()\n\n self._logger.info(f\"Declaring rabbit queue {QueueName.CMD_BUYSELL}\")\n self._consumer_rabbit_channel.queue_declare(queue=QueueName.CMD_BUYSELL, durable=True, auto_delete=True)\n self._logger.info(f\"Consiming to rabbit queue {QueueName.CMD_BUYSELL}\")\n self._consumer_rabbit_channel.basic_consume(QueueName.CMD_BUYSELL, self.on_cmd_buysell,\n consumer_tag=\"WebQuikBroker\")\n self._consumer_rabbit_channel.start_consuming()\n\n def on_order_answer(self, msg):\n self._logger.info(f\"Got msg: {msg}\")\n\n def on_cmd_buysell(self, channel, method_frame, header_frame, rawmsg):\n self._logger.info(f\"Got buy/sell command. msg={rawmsg}\")\n msg=json.loads(rawmsg)\n if msg[\"operation\"] == \"buy\":\n self.buy(msg['secClass'], msg['secCode'], msg['price'], msg['quantity'])\n elif msg[\"operation\"] == \"sell\":\n self.sell(msg['secClass'], msg['secCode'], msg['price'], msg['quantity'])\n else:\n self._logger.error(f\"Operation should be buy or sell in command: {msg}\")\n\n def on_trades_fx(self, msg):\n self._logger.debug(f\"On trades fx. msg={msg}\")\n\n def on_trade_accounts(self, msg):\n # Information about my account. Usually one for stocks, one for futures.\n # {\"msgid\":21022,\"trdacc\":\"NL0011100043\",\"firmid\":\"NC0011100000\",\"classList\":[\"QJSIM\"],\"mainMarginClasses\":[\"QJSIM\"],\"limitsInLots\":0,\"limitKinds\":[\"0\",\"1\",\"2\"]}\n # Just push the message to rabbitmq\n self._logger.debug(f\"On trade accounts. msg={msg}\")\n self._rabbit_channel.basic_publish(exchange='', routing_key=QueueName.TRADE_ACCOUNT, body=str(msg))\n\n def on_orders(self, msg):\n # Information about my orders\n self._logger.debug(f\"On orders. msg={msg}\")\n self._rabbit_channel.basic_publish(exchange='', routing_key=QueueName.ORDERS, body=str(msg))\n\n def on_trades(self, msg):\n self._logger.debug(f\"On trades. msg={msg}\")\n self._rabbit_channel.basic_publish(exchange='', routing_key=QueueName.TRADES, body=str(msg))\n\n def on_money_limits(self, msg):\n self._logger.debug(f\"On money limits. msg={msg}\")\n self._rabbit_channel.basic_publish(exchange='', routing_key=QueueName.MONEY_LIMITS, body=str(msg))\n\n def on_stock_limits(self, msg):\n self._logger.debug(f\"On stock limits. msg={msg}\")\n self._rabbit_channel.basic_publish(exchange='', routing_key=QueueName.STOCK_LIMITS, body=str(msg))\n\n def on_limit_received(self, msg):\n self._logger.debug(f\"Limit has received. msg={msg}\")\n self._rabbit_channel.basic_publish(exchange='', routing_key=QueueName.STOCK_LIMIT, body=str(msg))\n\n def subscribe_broker(self, subscriber):\n \"\"\"\n Subscribe to broker events - trades, account etc.\n :param subscriber broker class, inherited from broker'\n \"\"\"\n # Register given feed callback\n self._broker_subscribers.add(subscriber)\n\n def on_trans_reply(self, msg: str):\n \"\"\"\n Responce to my order\n ToDo: add order to history if successful\n \"\"\"\n # Successful transaction should look like this:\n # {\"msgid\":21009,\"request\":1,\"status\":3,\"ordernum\":5736932911,\"datetime\":\"2021-03-08 22:05:35\",\"text\":\"(161) Заявка N 5736932911 зарегистрирована. Удовлетворено 1\"}\n self._logger.info(f\"Got msg: {msg}\")\n\n def test(self):\n msgdict = {\n \"transid\": random.randint(1, 147483647),\n \"msgid\": MsgId.ORDER,\n \"action\": \"SIMPLE_STOP_ORDER\",\n \"MARKET_STOP_LIMIT\": \"YES\",\n\n \"ccode\": self.class_code,\n \"scode\": self.sec_code,\n \"operation\": \"B\",\n\n \"quantity\": 1,\n \"clientcode\": self.client_code,\n \"account\": self.trade_account,\n \"stopprice\": 215\n }\n msg = json.dumps(msgdict)\n return msg\n\n def get_order_msg(self, class_code: str, sec_code: str, is_buy: bool, price: float, quantity: int) -> str:\n \"\"\"\n Prepares buy or sell order json for quik\n \"\"\"\n msgdict = {\n \"transid\": random.randint(1, 2 ^ 64),\n \"msgid\": MsgId.ORDER,\n \"ccode\": class_code,\n \"scode\": sec_code,\n \"sell\": 0 if is_buy else 1,\n \"quantity\": quantity,\n \"clientcode\": self.client_code,\n \"account\": self.trade_account,\n \"price\": price\n }\n msg = json.dumps(msgdict)\n return msg\n\n def buy(self, class_code, sec_code, price, quantity):\n \"\"\"\n Send buy order to broker\n \"\"\"\n msg = self.get_order_msg(class_code=class_code, sec_code=sec_code, is_buy=True, price=price, quantity=quantity)\n self._logger.info(f\"Sending buy message {msg}\")\n self._connector.send(msg)\n\n def sell(self, class_code, sec_code, price, quantity):\n \"\"\"\n Send sell order to broker\n \"\"\"\n msg = self.get_order_msg(class_code=class_code, sec_code=sec_code, is_buy=False, price=price, quantity=quantity)\n self._logger.info(f\"Sending sell message {msg}\")\n self._connector.send(msg)\n\n def kill_all_orders(self):\n \"\"\"\n Kill all orders in trade system\n \"\"\"\n raise NotImplementedError\n\n def on_heartbeat(self):\n \"\"\"\n Heartbeating reaction\n \"\"\"\n for subscriber in self._broker_subscribers:\n subscriber.on_heartbeat()\n","sub_path":"pytrade/connector/quik/WebQuikBroker.py","file_name":"WebQuikBroker.py","file_ext":"py","file_size_in_byte":8449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"386254081","text":"import numpy as np\nimport random as ran\nimport matplotlib.pyplot as plt\n\nN = 1000\n\nmu1 = [1, 1]\nmu2 = [4, 4]\nmu3 = [8, 1]\nsigma = [[2, 0], [0, 2]]\nn1_data1, n2_data1, n3_data1 = 0, 0, 0\n\n#数据集X1\nfor dataNum in range(0, N):\n k = ran.randint(1, 3)\n if k == 1:\n n1_data1 += 1\n elif k == 2:\n n2_data1 += 1\n else:\n n3_data1 += 1\nx1, y1 = np.random.multivariate_normal(mu1, sigma, n1_data1).T\nx2, y2 = np.random.multivariate_normal(mu2, sigma, n2_data1).T\nx3, y3 = np.random.multivariate_normal(mu3, sigma, n3_data1).T\n\n#对数据集X画图\nfig = plt.figure()\nax1 = fig.add_subplot(121)\nax1.scatter(x1, y1, c = 'red')\nax1.scatter(x2, y2, c = 'blue')\nax1.scatter(x3, y3, c = 'green')\n\nn1_data2, n2_data2, n3_data2 = 0, 0, 0\nX1_part1 = np.vstack((x1, y1))\nX1_part2 = np.vstack((x2, y2))\nX1_part3 = np.vstack((x3, y3))\ncov1_data1 = np.cov(X1_part1)\ncov2_data1 = np.cov(X1_part2)\ncov3_data1 = np.cov(X1_part3)\nmean1_data1 = np.mean(X1_part1, axis=1)\nmean2_data1 = np.mean(X1_part2, axis=1)\nmean3_data1 = np.mean(X1_part3, axis=1)\ndata1 = np.hstack((X1_part1, X1_part2, X1_part3))\n\n#数据集X'\nfor dataNum in range(0, N):\n k = ran.randint(1, 10)\n if k <= 6:\n n1_data2 += 1\n elif k <= 9:\n n2_data2 += 1\n else:\n n3_data2 += 1\nx1, y1 = np.random.multivariate_normal(mu1, sigma, n1_data2).T\nx2, y2 = np.random.multivariate_normal(mu2, sigma, n2_data2).T\nx3, y3 = np.random.multivariate_normal(mu3, sigma, n3_data2).T\n\n#对数据集X'画图\nax2 = fig.add_subplot(122)\nax2.scatter(x1, y1, c = 'red')\nax2.scatter(x2, y2, c = 'blue')\nax2.scatter(x3, y3, c = 'green')\n\nX2_part1 = np.vstack((x1, y1))\nX2_part2 = np.vstack((x2, y2))\nX2_part3 = np.vstack((x3, y3))\ncov1_data2 = np.cov(X2_part1)\ncov2_data2 = np.cov(X2_part2)\ncov3_data2 = np.cov(X2_part3)\nmean1_data2 = np.mean(X2_part1, axis=1)\nmean2_data2 = np.mean(X2_part2, axis=1)\nmean3_data2 = np.mean(X2_part3, axis=1)\ndata2 = np.hstack((X2_part1, X2_part2, X2_part3))\n\ndata1 = data1.T\ndata2 = data2.T\n\n\nlabel_data1 = np.zeros(N)\nlabel_data1[n1_data1:n1_data1 + n2_data1 - 1] = 1\nlabel_data1[N - n3_data1:] = 2\nlabel_data1 = map(int, label_data1)\n\nlabel_data2 = np.zeros(N)\nlabel_data2[n1_data2:n1_data2 + n2_data2 - 1] = 1\nlabel_data2[N - n3_data2:] = 2\nlabel_data2 = map(int, label_data2)\n\n'''\n 用来估计随机矢量的均值和协方差矩阵\n 输入参数为三个均值和三个协方差矩阵\n'''\ndef getParameters(mean1, mean2, mean3, cov1, cov2, cov3):\n mu = np.vstack((mean1, mean2, mean3))\n sigma = np.zeros((3, 2, 2))\n sigma[0], sigma[1], sigma[2] = cov1, cov2, cov3\n return mu, sigma\n\nmean_X1, sigma_X1 = getParameters(mean1_data1, mean2_data1, mean3_data1, cov1_data1, cov2_data1, cov3_data1)\nmean_X2, sigma_X2 = getParameters(mean1_data2, mean2_data2, mean3_data2, cov1_data2, cov2_data2, cov3_data2)\n\nif __name__ == \"__main__\":\n print(\"\\n对于数据集X,属于三个模型随机矢量的均值为:\\n\")\n print(mean_X1)\n print(\"\\n对于数据集X,属于三个模型随机矢量的协方差矩阵为:\\n\")\n print(sigma_X1)\n plt.savefig(\"../result/data.jpg\") #保存图片\n plt.show() #显示图片","sub_path":"MLE/code/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"193281710","text":"import EbModule\nfrom modules.Progress import updateProgress\n\nfrom array import array\n\nfrom PIL import Image\nimport yaml\n\nclass Font:\n def __init__(self, gfxAddr, widthsAddr, charW, charH):\n self._gfxAddr = gfxAddr\n self._widthsAddr = widthsAddr\n self._charW = charW\n self._charH = charH\n self._chars = None\n self._charWidths = None\n def readFromRom(self, rom):\n self._chars = []\n addr = self._gfxAddr\n for i in range(96):\n charGfx = [ array('B', [0] * self._charH)\n for k in range(self._charW) ]\n for j in range(0, self._charW, 8):\n addr += EbModule.read1BPPArea(charGfx, rom, addr,\n self._charH, j, 0)\n self._chars.append(charGfx)\n self._charWidths = rom[self._widthsAddr:self._widthsAddr+96]\n def writeToRom(self, rom):\n addr = self._gfxAddr\n for char in self._chars:\n for j in range(0, self._charW, 8):\n addr += EbModule.write1BPPArea(char, rom, addr,\n self._charH, j, 0)\n rom.write(self._widthsAddr, self._charWidths)\n def toImage(self):\n img = Image.new(\"P\", (self._charW * 16, self._charH * 6), 1)\n # We only need two colors: white and black\n img.putpalette([255,255,255,0,0,0])\n # Draw the characters\n imgData = img.load()\n for i in range(16):\n for j in range(6):\n for y in range(self._charH):\n for x in range(self._charW):\n imgData[i*self._charW+x, j*self._charH+y] = \\\n self._chars[i+j*16][x][y]\n return img\n def fromImage(self, img):\n self._chars = [ [ array('B', [0] * self._charH) for k in\n range(self._charW) ] for j in range(0,96) ]\n imgData = img.load()\n for i in range(16):\n for j in range(6):\n for y in range(self._charH):\n for x in range(self._charW):\n self._chars[i+j*16][x][y] = imgData[\n i*self._charW+x,\n j*self._charH+y] & 1\n def dumpWidths(self):\n out = dict()\n for i in range(96):\n out[i] = self._charWidths[i]\n return out\n def loadWidths(self, input):\n self._charWidths = [0]*96\n for i in range(96):\n self._charWidths[i] = input[i]\n\nclass FontModule(EbModule.EbModule):\n _name = \"Fonts\"\n def __init__(self):\n self._fonts = [\n Font(0x210cda, 0x210c7a, 16, 16),\n Font(0x2013b9, 0x201359, 16, 16),\n Font(0x2122fa, 0x21229a, 16, 16),\n Font(0x21193a, 0x2118da, 8, 16),\n Font(0x211f9a, 0x211f3a, 8, 8)\n ]\n self._pct = 50.0/len(self._fonts)\n def readFromRom(self, rom):\n for f in self._fonts:\n f.readFromRom(rom)\n updateProgress(self._pct)\n def writeToRom(self, rom):\n for f in self._fonts:\n f.writeToRom(rom)\n updateProgress(self._pct)\n def writeToProject(self, resourceOpener):\n out = dict()\n i=0\n for font in self._fonts:\n # Write the PNG\n img = font.toImage()\n with resourceOpener(\"Fonts/\" + str(i), 'png') as imgFile:\n img.save(imgFile, 'png')\n\n # Write the widths\n out = font.dumpWidths()\n with resourceOpener(\"Fonts/\" + str(i) + \"_widths\", \"yml\") as f:\n yaml.dump(out, f, default_flow_style=False,\n Dumper=yaml.CSafeDumper)\n i += 1\n updateProgress(self._pct)\n def readFromProject(self, resourceOpener):\n i = 0\n for font in self._fonts:\n with resourceOpener(\"Fonts/\" + str(i), \"png\") as imgFile:\n img = Image.open(imgFile)\n font.fromImage(img)\n with resourceOpener(\"Fonts/\" + str(i) + \"_widths\", \"yml\") as f:\n input = yaml.load(f, Loader=yaml.CSafeLoader)\n font.loadWidths(input)\n i += 1\n updateProgress(self._pct)\n","sub_path":"modules/eb/FontModule.py","file_name":"FontModule.py","file_ext":"py","file_size_in_byte":4214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"353319067","text":"import ply.lex as lex\nimport sys\n\n# Implementation of lexical analyzer\nreserved = {\n\n \"playScale\": \"playScale\",\n \"createScale\": \"createScale\",\n \"HELP\": \"HELP\",\n \"EXIT\": \"EXIT\",\n \"NAME\": \"NAME\",\n \"EQUALS\": \"EQUALS\"\n\n}\n\n\n# Create Tokens\ntokens = list(reserved.values())\n\nt_ignore = r' '\nt_EQUALS = r'='\n\ndef t_NAME(t):\n r'[a-zA-Z][a-zA-Z0-9]*'\n if t.value in reserved:\n t.type = reserved[t.value]\n else:\n t.type = 'NAME'\n return t\n\n\n\ndef t_error(t):\n print(\"Unrecognized Character(s)\")\n print(t)\n t.lexer.skip(1)\n\n\nlexer = lex.lex()\n","sub_path":"PySharp_executable/PySharp_Lex.py","file_name":"PySharp_Lex.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"566378366","text":"from django.http import HttpResponse\nfrom django.template import RequestContext, loader\nfrom django.core.mail import mail_managers\n\nfrom syntacticframes.models import VerbNetClass, VerbTranslation\n\n\ndef index(request):\n num_members, unique_members, num_validated_verbs, unique_validated_verbs, num_classes, num_framesets = count_verbs()\n\n template = loader.get_template('stats.html')\n context = RequestContext(request, {\n 'num_members': num_members,\n 'unique_members': len(unique_members),\n 'num_validated_verbs': num_validated_verbs,\n 'unique_validated_verbs': len(unique_validated_verbs),\n 'num_classes': num_classes,\n 'num_framesets': num_framesets,\n })\n\n return HttpResponse(template.render(context))\n\ndef count_verbs():\n unique_validated_verbs, unique_members = set(), set()\n num_framesets, num_classes, num_validated_verbs, num_members = 0, 0, 0, 0\n for vn_class in VerbNetClass.objects.prefetch_related(\n 'verbnetframeset_set',\n 'verbnetframeset_set__verbnetmember_set',\n 'verbnetframeset_set__verbtranslation_set').all():\n\n num_classes += 1\n for vn_fs in vn_class.verbnetframeset_set.all():\n num_framesets += 1\n for t in VerbTranslation.all_valid(vn_fs.verbtranslation_set.all()):\n unique_validated_verbs.add(t.verb)\n num_validated_verbs += 1\n for m in vn_fs.verbnetmember_set.all():\n unique_members.add(m.lemma)\n num_members += 1\n\n return num_members, unique_members, num_validated_verbs, unique_validated_verbs, num_classes, num_framesets\n\n","sub_path":"syntacticframes_project/stats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"182577622","text":"# -*- coding: utf-8 -*-\nimport sqlite3\n\n\nclass CManageDB:\n def __init__(self):\n self.conn = sqlite3.connect(\"db_shanti.db\")\n self.cursor = self.conn.cursor()\n\n def create_tables(self):\n self.cursor.execute('create table if not exists all_lots(id_lot integer primary key unique, vk_link text, '\n 'title text, money text, flag integer)')\n\n self.cursor.execute('create table if not exists history (id_lot_table integer references all_lots (id_lot), '\n 'name text, money2 text, datetime real)')\n\n self.conn.commit()\n\n def add_lot_row(self, lot):\n self.cursor.execute('insert into all_lots(id_lot, vk_link, title, money, flag) '\n 'select :id_lot, :vk_link, :title, :money, :flag where not exists '\n '(select 1 from all_lots where id_lot = :id_lot)',\n {\"id_lot\": lot['id_lot'], \"vk_link\": lot['link_vk'],\n \"title\": lot['title'], \"money\": lot['money'],\n \"flag\": 1})\n self.conn.commit()\n\n def add_history_row(self, lot, datetime):\n self.cursor.execute('insert into history (id_lot_table, name, money2, datetime) '\n 'values (:id_lot, :name, :money2, :datetime)',\n {\"id_lot\": lot['id_lot'], \"name\": lot['name'],\n \"money2\": lot['money2'], \"datetime\": datetime})\n self.conn.commit()\n\n def get_actual_lot(self):\n self.cursor.execute('select * from all_lots where flag = 1')\n return self.cursor.fetchall()\n\n def change_sold_lot(self, lot):\n self.cursor.execute('update all_lots set flag = 0 where id_lot = :id', {\"id\": lot['id_lot']})\n self.conn.commit()\n\n def get_history_lot(self):\n pass\n\n\nif __name__ == '__main__':\n db = CManageDB()\n a = db.get_actual_lot()\n db.cursor.close()\n print(*a, sep='\\n')\n","sub_path":"db_api.py","file_name":"db_api.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"577902752","text":"_base_ = [\n 'mmdet::_base_/datasets/coco_detection.py',\n 'mmdet::_base_/schedules/schedule_1x.py',\n 'mmdet::_base_/default_runtime.py'\n]\ncustom_imports = dict(\n imports=['projects.EfficientDet.efficientdet'], allow_failed_imports=False)\n\nimage_size = 512\ndataset_type = 'Coco90Dataset'\nevalute_type = 'Coco90Metric'\nbatch_augments = [\n dict(type='BatchFixedSizePad', size=(image_size, image_size))\n]\nnorm_cfg = dict(type='SyncBN', requires_grad=True, eps=1e-3, momentum=0.01)\ncheckpoint = 'https://download.openmmlab.com/mmclassification/v0/efficientnet/efficientnet-b0_3rdparty_8xb32-aa-advprop_in1k_20220119-26434485.pth' # noqa\nmodel = dict(\n type='EfficientDet',\n data_preprocessor=dict(\n type='DetDataPreprocessor',\n mean=[123.675, 116.28, 103.53],\n std=[58.395, 57.12, 57.375],\n bgr_to_rgb=True,\n pad_size_divisor=image_size,\n batch_augments=batch_augments),\n backbone=dict(\n type='EfficientNet',\n arch='b0',\n drop_path_rate=0.2,\n out_indices=(3, 4, 5),\n frozen_stages=0,\n norm_cfg=norm_cfg,\n norm_eval=False,\n init_cfg=dict(\n type='Pretrained', prefix='backbone', checkpoint=checkpoint)),\n neck=dict(\n type='BiFPN',\n num_stages=3,\n in_channels=[40, 112, 320],\n out_channels=64,\n start_level=0,\n norm_cfg=norm_cfg),\n bbox_head=dict(\n type='EfficientDetSepBNHead',\n num_classes=90,\n num_ins=5,\n in_channels=64,\n feat_channels=64,\n stacked_convs=3,\n norm_cfg=norm_cfg,\n anchor_generator=dict(\n type='YXYXAnchorGenerator',\n octave_base_scale=4,\n scales_per_octave=3,\n ratios=[1.0, 0.5, 2.0],\n strides=[8, 16, 32, 64, 128],\n center_offset=0.5),\n bbox_coder=dict(\n type='YXYXDeltaXYWHBBoxCoder',\n target_means=[.0, .0, .0, .0],\n target_stds=[1.0, 1.0, 1.0, 1.0]),\n loss_cls=dict(\n type='FocalLoss',\n use_sigmoid=True,\n gamma=2.0,\n alpha=0.25,\n loss_weight=1.0),\n loss_bbox=dict(type='SmoothL1Loss', beta=0.11, loss_weight=1.0)),\n # training and testing settings\n train_cfg=dict(\n assigner=dict(\n type='TransMaxIoUAssigner',\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n min_pos_iou=0,\n ignore_iof_thr=-1),\n sampler=dict(\n type='PseudoSampler'), # Focal loss should use PseudoSampler\n allowed_border=-1,\n pos_weight=-1,\n debug=False),\n test_cfg=dict(\n nms_pre=1000,\n min_bbox_size=0,\n score_thr=0.05,\n nms=dict(\n type='soft_nms',\n iou_threshold=0.3,\n sigma=0.5,\n min_score=1e-3,\n method='gaussian'),\n max_per_img=100))\n\n# dataset settings\ntrain_pipeline = [\n dict(\n type='LoadImageFromFile',\n file_client_args={{_base_.file_client_args}}),\n dict(type='LoadAnnotations', with_bbox=True),\n dict(\n type='RandomResize',\n scale=(image_size, image_size),\n ratio_range=(0.1, 2.0),\n keep_ratio=True),\n dict(type='RandomCrop', crop_size=(image_size, image_size)),\n dict(type='RandomFlip', prob=0.5),\n dict(type='PackDetInputs')\n]\ntest_pipeline = [\n dict(\n type='LoadImageFromFile',\n file_client_args={{_base_.file_client_args}}),\n dict(type='Resize', scale=(image_size, image_size), keep_ratio=True),\n dict(type='LoadAnnotations', with_bbox=True),\n dict(\n type='PackDetInputs',\n meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',\n 'scale_factor'))\n]\n\ntrain_dataloader = dict(\n batch_size=16,\n num_workers=16,\n dataset=dict(type=dataset_type, pipeline=train_pipeline))\nval_dataloader = dict(dataset=dict(type=dataset_type, pipeline=test_pipeline))\ntest_dataloader = val_dataloader\n\nval_evaluator = dict(type=evalute_type)\ntest_evaluator = val_evaluator\n\noptim_wrapper = dict(\n optimizer=dict(lr=0.16),\n paramwise_cfg=dict(norm_decay_mult=0, bypass_duplicate=True))\n\n# learning policy\nmax_epochs = 300\nparam_scheduler = [\n dict(type='LinearLR', start_factor=0.1, by_epoch=False, begin=0, end=917),\n dict(\n type='CosineAnnealingLR',\n eta_min=0.0016,\n begin=1,\n T_max=284,\n end=285,\n by_epoch=True,\n convert_to_iter_based=True)\n]\ntrain_cfg = dict(max_epochs=max_epochs, val_interval=1)\n\nvis_backends = [\n dict(type='LocalVisBackend'),\n dict(type='TensorboardVisBackend')\n]\nvisualizer = dict(\n type='DetLocalVisualizer', vis_backends=vis_backends, name='visualizer')\n\ndefault_hooks = dict(checkpoint=dict(type='CheckpointHook', interval=15))\n# cudnn_benchmark=True can accelerate fix-size training\nenv_cfg = dict(cudnn_benchmark=True)\n\n# NOTE: `auto_scale_lr` is for automatically scaling LR,\n# USER SHOULD NOT CHANGE ITS VALUES.\n# base_batch_size = (8 GPUs) x (32 samples per GPU)\nauto_scale_lr = dict(base_batch_size=128)\n","sub_path":"ai/mmdetection/projects/EfficientDet/configs/efficientdet_effb0_bifpn_16xb8-crop512-300e_coco.py","file_name":"efficientdet_effb0_bifpn_16xb8-crop512-300e_coco.py","file_ext":"py","file_size_in_byte":5120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"207952583","text":"#from __future__ import absolute_import, division, print_function\n\nimport tensorflow as tf\nfrom tensorflow import keras\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nNUM_WORDS = 10000\n\n(train_data, train_labels), (test_data, test_labels) = keras.datasets.imdb.load_data(num_words=NUM_WORDS)\n\ndef multi_hot_sequences(sequences, dimension):\n result = np.zeros((len(sequences), dimension))\n for i, word_indices in enumerate(sequences):\n result[i,word_indices] = 1.0\n return result\n\ntrain_data = multi_hot_sequences(train_data, dimension=NUM_WORDS)\ntest_data = multi_hot_sequences(test_data, dimension=NUM_WORDS)\n#plt.plot(train_data[0])\n#plt.show()\n\n''' Defining baseline model'''\nif True:\n baseline_model = keras.Sequential([\n keras.layers.Dense(16,activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(16, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n\n baseline_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\n baseline_model.summary()\n\n baseline_history = baseline_model.fit(\n train_data,\n train_labels,\n epochs=10,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2\n )\n\n''' Defining small model'''\nif False:\n small_model = keras.Sequential([\n keras.layers.Dense(4, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(4, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n\n small_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\n small_model.summary()\n\n small_history = small_model.fit(\n train_data,\n train_labels,\n epochs=10,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2\n )\n\n''' Defining big model'''\nif False:\n big_model = keras.Sequential([\n keras.layers.Dense(512, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(512, activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n\n big_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\n big_model.summary()\n\n big_history = big_model.fit(\n train_data,\n train_labels,\n epochs=10,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2\n )\n\n\n''' Ploting training and validation loss'''\nif True:\n def plot_history(histories, key='binary_crossentropy'):\n plt.figure(figsize=(16,10))\n\n for name, history in histories:\n val = plt.plot(history.epoch, history.history['val_'+key],\n '--', label=name.title()+'val')\n plt.plot(history.epoch, history.history[key], color=val[0].get_color(),\n label=name.title()+'Trian')\n\n plt.xlabel('Epochs')\n plt.ylabel(key.replace('_', ' ').title())\n plt.legend()\n\n plt.xlim([0, max(history.epoch)])\n\nif False:\n plot_history([('baseline', baseline_history),\n ('small', small_history),\n ('big', big_history)])\n plt.show()\n\n''' Regularization'''\nif False:\n l2_model = keras.Sequential([\n keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),\n activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dense(16, kernel_regularizer=keras.regularizers.l2(0.001),\n activation=tf.nn.relu),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n\n l2_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\n l2_history = l2_model.fit(train_data,\n train_labels,\n epochs=10,\n batch_size=512,\n validation_data=(test_data, test_labels),\n verbose=2)\n\n plot_history([('baseline', baseline_history),\n ('l2', l2_history)])\n plt.show()\n\n''' Dropout'''\nif True:\n dpt_model = keras.Sequential([\n keras.layers.Dense(16, activation=tf.nn.relu, input_shape=(NUM_WORDS,)),\n keras.layers.Dropout(0.5),\n keras.layers.Dense(16, activation=tf.nn.relu),\n keras.layers.Dropout(0.5),\n keras.layers.Dense(1, activation=tf.nn.sigmoid)\n ])\n\n dpt_model.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy', 'binary_crossentropy'])\n\n dpt_model_history = dpt_model.fit(train_data,\n train_labels,\n epochs=10,\n validation_data=(test_data, test_labels),\n verbose=2)\n\n plot_history([('baseline', baseline_history),\n ('dpt', dpt_model_history)])\n plt.show()","sub_path":"overfitting_and_underfitting.py","file_name":"overfitting_and_underfitting.py","file_ext":"py","file_size_in_byte":5273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"485429131","text":"\n\nfrom xai.brain.wordbase.verbs._teethe import _TEETHE\n\n#calss header\nclass _TEETHES(_TEETHE, ):\n\tdef __init__(self,): \n\t\t_TEETHE.__init__(self)\n\t\tself.name = \"TEETHES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"teethe\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_teethes.py","file_name":"_teethes.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"609949191","text":"from datetime import datetime\n\nfrom django.core.validators import RegexValidator\nfrom django.db import models\n\nfrom edc.device.sync.models import BaseSyncUuidModel\nfrom edc_base.audit_trail import AuditTrail\nfrom edc_base.encrypted_fields import EncryptedTextField\nfrom edc_base.model.fields import OtherCharField\nfrom edc_base.model.validators import date_is_future\nfrom edc_constants.choices import YES_NO_UNKNOWN, TIME_OF_DAY, TIME_OF_WEEK, ALIVE_DEAD_UNKNOWN, YES_NO\nfrom edc_constants.constants import YES, NO, DEAD\n\nfrom bhp066.apps.bcpp_household_member.models import HouseholdMember\nfrom bhp066.apps.bcpp_survey.models.survey import Survey\n\nfrom ..choices import APPT_LOCATIONS, APPT_GRADING, CONTACT_TYPE\nfrom ..managers import CallLogEntryManager, CallLogManager\nfrom ..validators import date_in_survey\n\nfrom .subject_locator import SubjectLocator\nfrom .subject_consent import SubjectConsent\n\n\nclass CallLog (BaseSyncUuidModel):\n\n CONSENT_MODEL = SubjectConsent\n\n household_member = models.ForeignKey(HouseholdMember)\n\n survey = models.ForeignKey(Survey, editable=False)\n\n locator_information = EncryptedTextField(\n help_text='This information has been imported from the previous locator. You may update as required.')\n\n contact_notes = EncryptedTextField(\n null=True,\n blank=True,\n help_text='')\n\n label = models.CharField(\n max_length=25,\n null=True,\n editable=False,\n help_text=\"from call list\")\n\n history = AuditTrail()\n\n objects = CallLogManager()\n\n def __unicode__(self):\n return '{} {} {} ({} call)'.format(\n self.household_member.first_name,\n self.household_member.initials,\n self.household_member.household_structure.survey.survey_name,\n self.label)\n\n def save(self, *args, **kwargs):\n update_fields = kwargs.get('update_fields', [])\n if not self.survey:\n self.survey = Survey.objects.current_survey(datetime.today())\n if 'locator_information' in update_fields or not self.locator_information:\n try:\n self.locator_information = SubjectLocator.objects.previous(\n self.household_member).formatted_contact_information\n except AttributeError as err_message:\n self.locator_information = str(err_message)\n super(CallLog, self).save(*args, **kwargs)\n\n def natural_key(self):\n return self.household_member.natural_key() + (self.label, )\n natural_key.dependencies = ['bcpp_household_member.household_member', ]\n\n class Meta:\n app_label = 'bcpp_subject'\n unique_together = ['household_member', 'label']\n\n\nclass CallLogEntry (BaseSyncUuidModel):\n\n call_log = models.ForeignKey(CallLog)\n\n survey = models.ForeignKey(Survey, editable=False)\n\n call_datetime = models.DateTimeField()\n\n invalid_numbers = models.CharField(\n verbose_name='Indicate any invalid numbers dialed from the locator information above?',\n max_length=50,\n validators=[RegexValidator(\n regex=r'^[0-9]{7,8}(,[0-9]{7,8})*$',\n message='Only enter contact numbers separated by commas. No spaces and no trailing comma.'), ],\n null=True,\n blank=True,\n help_text='Separate by comma (,).'\n )\n\n contact_type = models.CharField(\n max_length=15,\n choices=CONTACT_TYPE,\n help_text='If no contact made. STOP. Save form.'\n )\n\n survival_status = models.CharField(\n verbose_name='Survival status of the participant',\n max_length=10,\n choices=ALIVE_DEAD_UNKNOWN,\n help_text=\"\"\n )\n\n update_locator = models.CharField(\n max_length=7,\n verbose_name='Has the locator information changed',\n choices=YES_NO_UNKNOWN,\n null=True,\n blank=True,\n help_text=('If YES, please enter the changed information '\n 'in the box above entitled (2) Locator information')\n )\n\n moved_community = models.CharField(\n max_length=7,\n verbose_name='Has the participant moved out of the community',\n choices=YES_NO_UNKNOWN,\n null=True,\n blank=True,\n help_text=\"\"\n )\n\n new_community = models.CharField(\n max_length=50,\n verbose_name='If the participant has moved, provide the name of the new community',\n null=True,\n blank=True,\n help_text=\"If moved out of the community, provide a new community name or \\'UNKNOWN\\'\"\n )\n\n moved_household = models.CharField(\n max_length=7,\n verbose_name='Has the participant moved out of the household where last seen',\n choices=YES_NO_UNKNOWN,\n null=True,\n blank=True,\n help_text=\"\"\n )\n\n available = models.CharField(\n max_length=7,\n verbose_name='Will the participant be available during the survey',\n choices=YES_NO_UNKNOWN,\n null=True,\n blank=True,\n help_text=\"\"\n )\n\n time_of_week = models.CharField(\n verbose_name='Time of week when participant will be available',\n max_length=25,\n choices=TIME_OF_WEEK,\n blank=True,\n null=True,\n help_text=\"\"\n )\n\n time_of_day = models.CharField(\n verbose_name='Time of day when participant will be available',\n max_length=25,\n choices=TIME_OF_DAY,\n blank=True,\n null=True,\n help_text=\"\"\n )\n\n appt = models.CharField(\n verbose_name='Is the participant willing to schedule an appointment',\n max_length=7,\n choices=YES_NO_UNKNOWN,\n null=True,\n blank=True,\n help_text=\"\"\n )\n\n appt_date = models.DateField(\n verbose_name=\"Appointment Date\",\n validators=[date_is_future, date_in_survey],\n null=True,\n blank=True,\n help_text=\"This can only come from the participant.\"\n )\n\n appt_grading = models.CharField(\n verbose_name='Is this appointment...',\n max_length=25,\n choices=APPT_GRADING,\n null=True,\n blank=True,\n help_text=\"\"\n )\n\n appt_location = models.CharField(\n verbose_name='Appointment location',\n max_length=50,\n choices=APPT_LOCATIONS,\n null=True,\n blank=True,\n help_text=\"\"\n )\n\n appt_location_other = OtherCharField(\n verbose_name='Appointment location',\n max_length=50,\n null=True,\n blank=True,\n help_text=\"\"\n )\n\n call_again = models.CharField(\n verbose_name='Call the participant again?',\n max_length=10,\n choices=YES_NO,\n default=YES,\n help_text=''\n )\n\n history = AuditTrail()\n\n objects = CallLogEntryManager()\n\n def save(self, *args, **kwargs):\n if not self.id:\n self.survey = Survey.objects.current_survey(self.call_datetime)\n if self.survival_status == DEAD:\n self.call_again = NO\n super(CallLogEntry, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return '{} {} {}'.format(\n self.call_log.household_member.first_name,\n self.call_log.household_member.initials,\n self.call_log.household_member.age_in_years,\n )\n\n def natural_key(self):\n return self.call_log.natural_key() + (self.call_datetime, )\n\n class Meta:\n app_label = 'bcpp_subject'\n unique_together = ['call_log', 'call_datetime']\n","sub_path":"bhp066/apps/bcpp_subject/models/call_log.py","file_name":"call_log.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"578783457","text":"'''\n给定一个无序的整数数组,找到其中最长上升子序列的长度。\n\n示例:\n\n输入: [10,9,2,5,3,7,101,18]\n输出: 4\n解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。\n说明:\n\n可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。\n你算法的时间复杂度应该为 O(n2) 。\n进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/longest-increasing-subsequence\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n'''\n\n\ndef lengthOfLIS(nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n dp = [1] * len(nums)\n for i in range(len(nums)):\n for j in range(i):\n if nums[i] > nums[j]:\n dp[i] = max(dp[i], dp[j] + 1)\n print(dp)\n return dp\n\ndef lengthOfLIS_Advance(nums):\n ends = [nums[0]]\n for i in range(1, len(nums)):\n l = 0\n r = len(ends)\n while r > l:\n mid = (l + r) // 2\n if ends[mid] < nums[i]:\n l = mid + 1\n else:\n r = mid\n if l == len(ends):\n ends.append(nums[i])\n else:\n ends[l] = nums[i]\n print(ends)\n return len(ends)\n\n\nprint(lengthOfLIS_Advance([3,5,6,2,5,42]))","sub_path":"chaos/longest-increasing-subsequence.py","file_name":"longest-increasing-subsequence.py","file_ext":"py","file_size_in_byte":1382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"450956043","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom numpy import genfromtxt\nimport keras.backend as K\nfrom sklearn.preprocessing import normalize\nfrom sklearn.metrics import mean_squared_error\nimport math\nimport tensorflow as tf\nfrom create_data_files import create_train_test\nimport statistics\nfrom utils import get_error_stats, split_into_xy, train_file, test_file, offline_result_path, write_header_names, batch_data_size_array\n\nquant = [0.5]\nresult_file = offline_result_path+'neural_network_squared_loss.csv'\n\n\ndef load_data(filename):\n\tdata = genfromtxt(filename, delimiter=',')\n\treturn data\n\ndef define_model():\n model = Sequential()\n model.add(Dense(units=10, input_dim=6,activation='relu'))\n model.add(Dense(1))\n return model\n\ndef tilted_loss(q,y,f):\n e = (y-f)\n return K.mean(K.maximum(q*e, (q-1)*e), axis=-1)\n\ndef test_model(model, test_file):\n\tdata = load_data(test_file)\n\ty_pred = []\n\tx_test, y_test = split_into_xy(data)\n\tx_normal = normalize(x_test, norm='l1')\n\ty_temp = model.predict(x_normal)\n\tfor temp in y_temp:\n\t\ty_pred.append(temp[0])\n\treturn (y_test, y_pred)\n\ndef build_models_on_quantile(train_file):\n\tdata = load_data(train_file)\n\tx, y = split_into_xy(data)\n\tx_normal = normalize(x, norm='l1')\n\tmodel = define_model()\n\tmodel.compile(loss='mean_squared_error', optimizer='adadelta')\n\tmodel.fit(x_normal, y, epochs=50, batch_size=34, verbose=0)\n\treturn model \n\ndef run_neural_net_quantile_regression():\n\tresult_file_pointer = open(result_file, 'w+')\n\twrite_header_names(result_file_pointer)\n\tfor size in batch_data_size_array:\n\t\tcreate_train_test(size, False)\n\t\tmodel = build_models_on_quantile(train_file)\n\t\t(y_test, y_pred) = test_model(model, test_file)\n\t\tget_error_stats(y_test, y_pred, result_file_pointer, size)\n\tresult_file_pointer.close()\n\nif __name__== \"__main__\":\n\trun_neural_net_quantile_regression()","sub_path":"neural_net_squared_loss.py","file_name":"neural_net_squared_loss.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"308285763","text":"from lib.models import Corporation, Stock\nfrom sqlalchemy import or_\nfrom datetime import date, timedelta, datetime\nfrom collections import defaultdict\nfrom typing import List, Dict\n\n\ndef get_top_gainers(given_date):\n # Get the stocks that will have the highest percentage increase from the current value\n # Over a period of 1 day, 1 week and 1 month\n # What do we need? The current value of all stocks, and the predicted values of 1 day, 1 week and 1 month\n # Percentage Increase = 100 x (Future Value - Current Value) / Current Value\n\n def response_format(attribute: str) -> List[Dict]:\n result = []\n stocks.sort(key=lambda s: getattr(s, attribute) - s.closing_value, reverse=True)\n for stock in stocks[:group_size]:\n result.append({\n 'corporation': stock.corporation.name,\n 'symbol': stock.corporation.symbol,\n 'gain': round(100*(getattr(stock, attribute) - stock.closing_value)/stock.closing_value, 2)\n })\n\n return result\n\n response, group_size = {}, 5\n given_date = datetime.strptime(given_date, \"%d%m%Y\").date()\n stocks: List[Stock] = Stock.query.join(Corporation).filter(Stock.record_date == given_date).all()\n response['day'] = response_format('day_prediction_value')\n response['week'] = response_format('week_prediction_value')\n response['month'] = response_format('month_prediction_value')\n return response\n","sub_path":"server/lib/controllers.py","file_name":"controllers.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"435958828","text":"from BasicStructures.AdjacencyVector import AdjacencyVector\nfrom BasicStructures.Vertex import Vertex\nfrom BasicStructures.VectorArray import VectorArray\nfrom BasicStructures.BasicStack import BasicStack\nfrom BasicStructures.Node import Node\n\ndef tarjan(vertexIndexes: []):\n # Создаём из входного массива вектор смежности\n adjacencyVector = AdjacencyVector(len(vertexIndexes))\n vertexes = makeVertexesArray(vertexIndexes, adjacencyVector)\n stack = BasicStack()\n\n for vertex in vertexes:\n if vertex.color == 'w':\n if not DFS(vertex, stack):\n return False\n\n return stack.convertToArray()\n\ndef DFS(vertex: Vertex, stack: BasicStack):\n vertex.color = 'g'\n for u in vertex.bindedVertexes:\n if u.color == 'w':\n if not DFS(u, stack):\n return False\n elif u.color == 'g':\n return False\n vertex.color = 'b'\n stack.push(Node(vertex.index))\n return True\n \n \ndef makeVertexesArray(vertexIndexes: [], adjacencyVector: AdjacencyVector):\n\n vertexes = VectorArray(len(vertexIndexes))\n\n for masterVertexIndex, slaveVIndexesArr in enumerate(vertexIndexes):\n masterVertex = vertexes[masterVertexIndex]\n if masterVertex is None:\n masterVertex = Vertex(masterVertexIndex)\n vertexes.replace(masterVertex, masterVertexIndex)\n\n for slaveVertexIndex in slaveVIndexesArr:\n slaveVertex = vertexes[slaveVertexIndex]\n if slaveVertex is None:\n slaveVertex = Vertex(slaveVertexIndex)\n vertexes.replace(slaveVertex, slaveVertexIndex)\n masterVertex.addBindedVertex(slaveVertex)\n adjacencyVector.bind(slaveVertex.index, masterVertex.index)\n vertexes.clear_unused_memory()\n\n return vertexes","sub_path":"Tarjan.py","file_name":"Tarjan.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"508874075","text":"#\n# [888] Mirror Reflection\n#\n# https://leetcode.com/problems/mirror-reflection/description/\n#\n# algorithms\n# Medium (46.46%)\n# Total Accepted: 2.1K\n# Total Submissions: 4.4K\n# Testcase Example: '2\\n1'\n#\n# There is a special square room with mirrors on each of the four walls.\n# Except for the southwest corner, there are receptors on each of the remaining\n# corners, numbered 0, 1, and 2.\n#\n# The square room has walls of length p, and a laser ray from the southwest\n# corner first meets the east wall at a distance q from the 0th receptor.\n#\n# Return the number of the receptor that the ray meets first.  (It is\n# guaranteed that the ray will meet a receptor eventually.)\n#\n#\n#\n#\n# Example 1:\n#\n#\n# Input: p = 2, q = 1\n# Output: 2\n# Explanation: The ray meets receptor 2 the first time it gets reflected back\n# to the left wall.\n#\n#\n#\n#\n# Note:\n#\n#\n# 1 <= p <= 1000\n# 0 <= q <= p\n#\n\n# Jarron:\n# - brute force\n\n# REVIEW:\n# - find lcm\n# - If p = odd, q = even: return 0\n# - If p = even, q = odd: return 2\n# - If p = odd, q = odd: return 1\n\n\nclass Solution:\n def mirrorReflection(self, p, q):\n \"\"\"\n :type p: int\n :type q: int\n :rtype: int\n \"\"\"\n target = [2 * p - q, p - q, p]\n\n while True:\n for i in range(3):\n if target[i] == 0:\n return i\n\n target[i] -= 2 * q\n if target[i] < 0:\n target[i] += 2 * p\n","sub_path":"src/858.mirror-reflection.python3.py","file_name":"858.mirror-reflection.python3.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"574393124","text":"from xml.dom.minidom import parse\nimport xml.dom.minidom\n\ndef replaceText(node, newText):\n if node.firstChild.nodeType != node.TEXT_NODE:\n raise Exception(\"Node does not contain text\")\n node.firstChild.replaceWholeText(newText)\n\nmovies = xml.dom.minidom.parse('movies.xml') #ładowanie xmla\n#print(movies.toxml()) #wyswietlanie zawartosi xmla w jego postaci\n\nmy_filmweb = movies.getElementsByTagName(\"movie\")\nfor movie in my_filmweb:\n print('*****Movie*****')\n title = movie.getElementsByTagName('title')[0]\n #print('Title: {}'.format(title)) wyswietli cos takiego: Title: []\n #Musisz się dostać do rzeczywistego napisu, który chowa się w węźle potomnym i wspomóc się atrybutem data\n print('Title: {}'.format(title.childNodes[0].data))\n type = movie.getElementsByTagName('type')[0]\n print('Type: {}'.format(type.childNodes[0].data))\n country = movie.getElementsByTagName('country')[0]\n print('Country: {}'.format(country.childNodes[0].data))\n year = movie.getElementsByTagName('year')[0]\n print('Year: {}'.format(year.childNodes[0].data))\n\n replaceText(type, \"dziala\")\n\nfile_handle = open('movies.xml','w')\nmovies.writexml(file_handle)\nfile_handle.close()\n","sub_path":"Python/SecondInstruction/XML.py","file_name":"XML.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"613032645","text":"''' YOLOv2 model example which detects where objects exist in each frame of a video in real time\r\n GPU use must be enabled to be performed in real time\r\n I ran this on Geforce GTX 1060 at runs at 15FPS (real time), on CPU runs @ 1FPS\r\n\r\n To run this:\r\n - Ensure model location (model_loc) is set to location of model on your PC\r\n - Change video name (video_name) to name of your video clip and place it in the same folder as the model '''\r\nimport os\r\nimport cv2\r\nfrom darkflow.net.build import TFNet\r\nimport numpy as np\r\nimport time\r\n\r\n# model and video location & video name\r\nmodel_loc = 'C:/Users/squir/darkflow-master'\r\nvideo_name = 'videofile1.avi'\r\n\r\nos.chdir(model_loc)\r\n# define video to be detected and colours used in frames\r\ncapture = cv2.VideoCapture(video_name)\r\ncolours = [tuple(255 * np.random.rand(3)) for i in range(100)]\r\n\r\n# defining options for image rendering\r\noptions = {\r\n \"model\": \"cfg/yolo.cfg\", # which model to use\r\n \"load\": \"bin/yolov2.weights\", # which preconfigured weights to use\r\n \"threshold\": 0.3, # must have confidence factor of equal to or greater than to draw bbox\r\n \"gpu\": 1.0} # 1 = use the gpu to render, 0 = use CPU\r\ntfnet = TFNet(options)\r\n\r\nwhile capture.isOpened(): # while video is open\r\n stime = time.time() # start frame time\r\n ret, frame = capture.read() # ret = true when vid playing, frame = created frame\r\n if ret:\r\n results = tfnet.return_predict(frame) # create a frame for each prediction\r\n for color, result in zip(colours, results): # zip makes list of tuples (colors, results)\r\n tl = (result['topleft']['x'], result['topleft']['y']) # top left of frame\r\n br = (result['bottomright']['x'], result['bottomright']['y']) # btm right of frame\r\n label = result['label'] # lbl\r\n frame = cv2.rectangle(frame, tl, br, color, 7) # create frame\r\n frame = cv2.putText(frame, label, tl, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) # label on frame\r\n cv2.imshow('frame', frame) # display frame\r\n print('FPS {:.1f}'.format(1 / (time.time() - stime))) # showing FPS\r\n if cv2.waitKey(1) & 0xFF == ord('q'): # stop if you press 'q'\r\n break\r\n else:\r\n capture.release() # else stop when video finishes\r\n cv2.destroyAllWindows()\r\n break\r\n","sub_path":"RealTimeVidDetect.py","file_name":"RealTimeVidDetect.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"557753581","text":"# Accessing the files and preparing the dataset\r\n#from google.colab import drive\r\nfrom os import listdir\r\nfrom os.path import join\r\n# import os\r\n# import shutil\r\n\r\n# Treating the images\r\n# from PIL import Image ## Not used when using the pretransformed dataset\r\nimport numpy as np\r\nimport random\r\nimport torch\r\nimport torch.utils.data as data ## to import data.Dataset\r\n# from torch.utils.data import DataLoader\r\nimport torchvision.transforms as transforms\r\n# from matplotlib.pyplot import imshow\r\n# import matplotlib.pyplot as plt\r\n# import math\r\n\r\n# Dealing with GPUs\r\n# import torch.backends.cudnn as cudnn\r\n\r\n# Defining the networks\r\n# import torch.nn as nn\r\n# from torch.nn import init\r\n# import functools\r\n# from torch.optim import lr_scheduler\r\n# import torch.optim as optim\r\n\r\n# Training\r\n# from math import log10\r\n# import time\r\n\r\n# Tensorboard\r\n# from torch.utils.tensorboard import SummaryWriter\r\n# import datetime\r\n\r\n# Parameters\r\nfrom arguments import opt\r\n\r\n# Debug\r\nfrom utils import print_debug\r\n\r\n\r\n# from utils import is_image_file, load_img\r\ndef is_image_file(filename):\r\n return any(filename.endswith(extension) for extension in [\".png\", \".jpg\", \".jpeg\", \".tif\", \".tiff\", \".npy\"])\r\n\r\nclass DatasetFromFolder(data.Dataset):\r\n def __init__(self, image_dir, direction=\"a2b\"):\r\n \"\"\"\r\n Constructor adapted to the characteristics of the https://project.inria.fr/aerialimagelabeling/\r\n images split as follows:\r\n - train/a: training mask (ground truth) images\r\n - train/b: training satellite images\r\n - test/a: test mask (ground truth) images\r\n - test/b: test satellite images\r\n\r\n Example of use:\r\n train_ds = DatasetFromFolder(\"/content/drive/MyDrive/Colab Notebooks/AIDL/Project/train\", \"a2b\")\r\n \"\"\"\r\n super(DatasetFromFolder, self).__init__()\r\n self.direction = direction\r\n self.a_path = join(image_dir, \"gt\") # mask (ground truth) images. Originally \"a\"\r\n self.b_path = join(image_dir, \"images\") # satellite images. Originally \"b\"\r\n self.image_filenames = [x for x in listdir(self.a_path) if is_image_file(x)]\r\n\r\n transform_list = [transforms.ToTensor(),\r\n # Even if masks have only one channel, they're converted to RGB in __getitem__\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]\r\n self.transform = transforms.Compose(transform_list)\r\n\r\n # Test npy storage in memory. Does the data loader keep the instance of\r\n # this dataset between epochs?\r\n self.a_image_tensors = {}\r\n self.b_image_tensors = {}\r\n\r\n\r\n def __getitem__(self, index):\r\n filename = self.image_filenames[index]\r\n print_debug(2, \"DatasetFromFolder __getitem__: getting item {} corresponding to file {}\".format(index, filename))\r\n \r\n # Checking if file is already in memory\r\n if filename in self.a_image_tensors.keys():\r\n if filename == opt.tb_image:\r\n print_debug(2, \"DatasetFromFolder __getitem__: {} found in memory.Total stored: {}\".format(filename, len(self.a_image_tensors.keys())))\r\n # If it is already in memory, a copy is used\r\n a = self.a_image_tensors[filename].clone()\r\n b = self.b_image_tensors[filename].clone()\r\n else:\r\n # If the image is not in memory, it is read and transformed to a Tensor\r\n\r\n # This Colab reads already pretransformed images. They were already converted to RGB\r\n # a = Image.open(join(self.a_path, self.image_filenames[index])).convert('RGB')\r\n # b = Image.open(join(self.b_path, self.image_filenames[index])).convert('RGB')\r\n # a = Image.open(join(self.a_path, self.image_filenames[index]))\r\n # b = Image.open(join(self.b_path, self.image_filenames[index]))\r\n a = np.load(join(self.a_path, self.image_filenames[index]))\r\n b = np.load(join(self.b_path, self.image_filenames[index]))\r\n\r\n print_debug(2, \"a_{} [0,3,7]:{:.4f} [1,100,100]:{:.4f} [2,200,200]:{:.4f}\".format(\r\n self.image_filenames[index],\r\n a[3,7,0],\r\n a[100,100,1],\r\n a[200,200,2]\r\n ))\r\n print_debug(2, \"b_{} [0,3,7]:{:.4f} [1,100,100]:{:.4f} [2,200,200]:{:.4f}\".format(\r\n self.image_filenames[index],\r\n b[3,7,0],\r\n b[100,100,1],\r\n b[200,200,2]\r\n ))\r\n\r\n # Pretransformed images are already 286x286 size\r\n # a = a.resize((286, 286), Image.BICUBIC) # Revision pending: from 5000x5000 to 286x286 sizes. This can lead to learning problems\r\n # b = b.resize((286, 286), Image.BICUBIC)\r\n a = transforms.ToTensor()(a)\r\n b = transforms.ToTensor()(b)\r\n\r\n # Storing tensors for future use. To avoid memory explosion, only a few images are stored\r\n if filename == opt.tb_image or len(self.a_image_tensors.keys()) < 600:\r\n if filename == opt.tb_image:\r\n print_debug(2, \"DatasetFromFolder __getitem__: storing {} for future reuse\".format(filename))\r\n self.a_image_tensors[filename] = a.clone()\r\n self.b_image_tensors[filename] = b.clone()\r\n\r\n w_offset = random.randint(0, max(0, 286 - 256 - 1)) # \r\n h_offset = random.randint(0, max(0, 286 - 256 - 1))\r\n \r\n a = a[:, h_offset:h_offset + 256, w_offset:w_offset + 256]\r\n b = b[:, h_offset:h_offset + 256, w_offset:w_offset + 256]\r\n \r\n # Pretransformed images are already normalized\r\n # a = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(a)\r\n # b = transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))(b)\r\n\r\n if random.random() < 0.5:\r\n idx = [i for i in range(a.size(2) - 1, -1, -1)]\r\n idx = torch.LongTensor(idx)\r\n a = a.index_select(2, idx)\r\n b = b.index_select(2, idx)\r\n\r\n if self.direction == \"a2b\":\r\n return a, b, filename\r\n else:\r\n return b, a, filename\r\n\r\n def __len__(self):\r\n return len(self.image_filenames)\r\n","sub_path":"model_variations/generator_alone_baseline/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":6195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"416179754","text":"# generic imports\nimport datetime\nimport logging\nimport os\nfrom packaging import version\nimport pdb\nimport shutil\nimport sys\nimport time\n\n# django\nfrom django.core.management.base import BaseCommand, CommandError\n\n# import core\nfrom core.models import *\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n '''\n Manage command to update Combine.\n\n Performs the following:\n - pull from github, updates all branches\n - if relase passed, checkout release/branch\n - pip install requirements\n - collect static django\n - restart gunicorn, livy session, celery\n '''\n\n help = 'Update Combine'\n\n # python path\n PYTHON_PATH = sys.executable.rstrip('python').rstrip('/')\n\n def add_arguments(self, parser):\n\n # release\n parser.add_argument(\n '--release',\n dest='release',\n help='GitHub branch/release to update to',\n type=str,\n default=None\n )\n\n # update method\n parser.add_argument(\n '--run_update_snippet',\n dest='run_update_snippet',\n help='Update code snippet to run',\n type=str,\n default=None\n )\n\n # update method\n parser.add_argument(\n '--run_update_snippets_only',\n action='store_true',\n help='Run update snippets only during update'\n )\n\n def handle(self, *args, **options):\n '''\n Handler for updates to Combine\n '''\n\n logger.debug('Updating Combine')\n\n # run update snippet if passed\n if options.get('run_update_snippet'):\n self.run_update_snippet(args, options)\n\n # else, run update\n else:\n self.update(args, options)\n\n def update(self, args, options):\n '''\n Method to handle branch/tagged release update\n '''\n\n # do not run at all if Combine is Docker deployed\n if getattr(settings, 'COMBINE_DEPLOYMENT', 'server') != 'docker':\n\n # if not running update snippets only\n if not options.get('run_update_snippets_only', False):\n\n # git pull\n os.system('git pull')\n\n # checkout release if provided\n if options.get('release', None) != None:\n release = options['release']\n logger.debug(\n 'release/branch provided, checking out: %s' % release)\n\n # git checkout\n os.system('git checkout %s' % release)\n\n # install requirements as combine user\n os.system('%s/pip install -r requirements.txt' %\n (self.PYTHON_PATH))\n\n # collect django static\n os.system('%s/python manage.py collectstatic --noinput' %\n (self.PYTHON_PATH))\n\n # restart gunicorn\n self._restart_gunicorn()\n\n # restart livy and livy session\n self._restart_livy()\n\n # restart celery background tasks\n self._restart_celery()\n\n # run update code snippets\n vuh = VersionUpdateHelper()\n vuh.run_update_snippets()\n\n # return\n self.stdout.write(self.style.SUCCESS('Update complete.'))\n\n # docker return\n else:\n self.stdout.write(self.style.ERROR('Update script does not currently support Docker deployment.'))\n\n def _restart_gunicorn(self):\n\n # get supervisor handle\n sp = SupervisorRPCClient()\n # fire action\n results = sp.restart_process('gunicorn')\n logger.debug(results)\n\n def _restart_livy(self):\n\n # get supervisor handle\n sp = SupervisorRPCClient()\n # fire action\n results = sp.restart_process('livy')\n logger.debug(results)\n\n # sleep\n time.sleep(10)\n\n # get active livy sessions - restart or start\n active_ls = LivySession.get_active_session()\n if not active_ls:\n logger.debug('active livy session not found, starting')\n livy_session = LivySession()\n livy_session.start_session()\n else:\n logger.debug(\n 'single, active session found, and restart flag passed, restarting')\n new_ls = active_ls.restart_session()\n\n def _restart_celery(self):\n\n # get supervisor handle\n sp = SupervisorRPCClient()\n # fire action\n results = sp.restart_process('celery')\n logger.debug(results)\n\n def run_update_snippet(self, args, options):\n '''\n Method to run update snippet if passed\n '''\n\n # init VersionUpdateHelper instance\n vuh = VersionUpdateHelper()\n\n # get snippet\n snippet = getattr(vuh, options.get('run_update_snippet'), None)\n if snippet != None:\n snippet()\n else:\n logger.debug('Update snippet \"%s\" could not be found' %\n options.get('run_update_snippet', None))\n\nclass VersionUpdateHelper():\n '''\n Class to manage actions specific to version-to-version updates\n '''\n\n # python path\n PYTHON_PATH = sys.executable.rstrip('python').rstrip('/')\n\n def __init__(self):\n\n # registered, ordered list of snippets\n self.registered_snippets = [\n self.v0_4__set_job_baseline_combine_version,\n self.v0_4__update_transform_job_details,\n self.v0_4__set_job_current_combine_version,\n self.v0_7_1__fix_redis_version_mismatches\n ]\n\n def run_update_snippets(self):\n '''\n Method to loop through update snippets and fire\n '''\n\n for snippet in self.registered_snippets:\n try:\n snippet()\n except Exception as e:\n logger.debug('Could not run udpate snippet: %s' %\n snippet.__name__)\n logger.debug(str(e))\n\n def v0_4__set_job_baseline_combine_version(self):\n '''\n Method to set combine_version as v0.1 in job_details for all lacking version\n '''\n\n logger.debug(\n 'v0_4__set_job_baseline_combine_version: setting Job combine_version to v0.1 if not set')\n\n # get Transform Jobs\n jobs = Job.objects.all()\n\n # loop through jobs\n for job in jobs:\n\n # check for combine_version key\n if not job.job_details_dict.get('combine_version', False):\n logger.debug('stamping v0.1 combine_version to Job: %s' % (job))\n\n # update job_details\n job.update_job_details({'combine_version': 'v0.1'})\n\n def v0_4__set_job_current_combine_version(self):\n '''\n Method to set combine_version as current Combine version in job_details\n '''\n\n logger.debug('v0_4__set_job_current_combine_version: checking and setting Job combine_version to %s' % (\n settings.COMBINE_VERSION))\n\n # get Transform Jobs\n jobs = Job.objects.all()\n\n # loop through jobs\n for job in jobs:\n\n # compare and stamp\n if version.parse(job.job_details_dict['combine_version']) < version.parse(settings.COMBINE_VERSION):\n logger.debug('stamping %s combine_version to Job: %s' % (settings.COMBINE_VERSION, job))\n\n # update job_details\n job.update_job_details({'combine_version': settings.COMBINE_VERSION})\n\n def v0_4__update_transform_job_details(self):\n '''\n Method to update job_details for Transform Jobs if from_v < v0.4 or None\n '''\n\n logger.debug(\n 'v0_4__update_transform_job_details: updating job details for pre v0.4 Transform Jobs')\n\n # get Transform Jobs\n trans_jobs = Job.objects.filter(job_type='TransformJob')\n\n # loop through and check for single Transformation Scenario\n for job in trans_jobs:\n\n # check version\n if version.parse(job.job_details_dict['combine_version']) < version.parse('v0.4'):\n\n logger.debug('Transform Job \"%s\" is Combine version %s, checking if needs updating' % (\n job, job.job_details_dict['combine_version']))\n\n # check for 'transformation' key in job_details\n if job.job_details_dict.get('transformation', False):\n\n # get transform details\n trans_details = job.job_details_dict.get('transformation')\n\n # check for 'id' key at this level, indicating < v0.4\n if 'id' in trans_details.keys():\n logger.debug('Transform Job \"%s\" requires job details updating, performing' % job)\n\n # create dictionary\n trans_dict = {\n 'scenarios': [\n {\n 'id': trans_details['id'],\n 'name':trans_details['name'],\n 'type':trans_details['type'],\n 'type_human':trans_details['type'],\n 'index':0\n }\n ],\n 'scenarios_json': '[{\"index\":0,\"trans_id\":%s}]' % trans_details['id']\n }\n\n # update job_details\n job.update_job_details({'transformation': trans_dict})\n\n def v0_7_1__fix_redis_version_mismatches(self):\n '''\n Method to fix any redis version mismatches\n '''\n\n if version.parse(settings.COMBINE_VERSION) == version.parse('v0.7'):\n logger.debug('v0_7_1__fix_redis_version_mismatches: fixing redis versioning')\n\n # ensure redis version\n os.system('%s/pip uninstall redis celery -y' % (self.PYTHON_PATH))\n os.system('%s/pip install redis==3.2.1 celery==4.3.0' %\n (self.PYTHON_PATH))\n\n # restart celery background tasks\n # get supervisor handle\n sp = SupervisorRPCClient()\n # fire action\n results = sp.restart_process('celery')\n logger.debug(results)\n","sub_path":"core/management/commands/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":10399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"436526579","text":"# -*- coding: utf-8 -*-\nimport tkinter\nfrom tkinter import filedialog\nimport fileinput\nimport urllib.request\nimport re\nimport vk_requests\nimport vk\n############ Vk-auth-function\n\n'''\ndef login():\n\tent1_get = entry1.get()\n\tent2_get = entry2.get()\n\n\t#GET req for auth vk\n\n\tget_auth = https://oauth.vk.com/access_token?client_id=5523311&client_secret=qKjnr8T62DZVfZMNk8eR&username=\"+ent1_get+\"&password=\"+ent2_get\n\n\t#try:\n\t\tauth = urllib.request.urlopen(get_auth)\n\t\tuserid = re.split(\",\", auth.read())[2]\n\t\tfind_id = re.findall(\":\\w+\", userid)\n\t#except:\n\t\t#status.set(\"Wrong login credentials\")\n\t#else:\n\t\t#status.set(\"id: \"+''.join(find_id)[1:])\n'''\ngpid =[]\nparseddata=[]\nvkapi = 0\ndef login():\n\tglobal vkapi\n\tent1_get = entry1.get()\n\tent2_get = entry2.get()\n\tvkapi = vk_requests.create_api(app_id=5523311, login=ent1_get, password=ent2_get)\n\n\ndef opengpid():\n\tglobal gpid\n\top = filedialog.askopenfile()\n\t#with open(op,'r') as f:\n\tfor line in op:\n\t\tgpid = gpid + line.split()\n\t\n\ndef sparsed():\n\tglobal parseddata\n\tglobal vkapi\n\tcityid=2\n\tsave=filedialog.asksaveasfile(mode='w',defaultextension=\".txt\")\n\tfor i in range(len(gpid)):\n\t\tparseddata=vkapi.groups.getMembers(group_id=gpid[i], fields='contacts,city')\n\t\tfor i in parseddata['items']:\n\t\t\ttry:\n\t\t\t\tif cityid == int(i['city']['id']):\n\t\t\t\t\ttry:\n\t\t\t\t\t\ti['mobile_phone']\n\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tl=i['mobile_phone']\t\t\t\t\t\n\t\t\t\t\t\tif 10 < len(l) <= 16:\n\t\t\t\t\t\t\tsave.write(i['mobile_phone']+\" \"+i['first_name']+\" \"+i['last_name']+\" (http://vk.com/id\"+str(i['id'])+\")\"+'\\n')\n\t\t\texcept KeyError:\n\t\t\t\tcontinue\n\t\tsave.close\n\n#main window\n\nmain_window = tkinter.Tk()\nmain_window.title(\"VKPRSR\") # title\nmain_window.geometry(\"284x260\") # size\nmain_window.resizable(False, False) #deny resize\n\n#refresh status\nstatus = tkinter.StringVar()\n\n#interface\nimage_load = tkinter.PhotoImage(file=\"\")\nimage = tkinter.Label(main_window, image=image_load)\n\nlabel1 = tkinter.Label(main_window, text=\"Телефон или email: \")\nlabel2 = tkinter.Label(main_window, text=\"Пароль: \")\n\nentry1 = tkinter.Entry(main_window, width=32)\nentry2 = tkinter.Entry(main_window, show=\"*\", width=32) #password field\n\nbutton = tkinter.Button(main_window, text=\"Войти\", command=login)\nbutton2 = tkinter.Button(main_window, text=\"Открыть список групп\", command=opengpid)\nbutton3 = tkinter.Button(main_window, text=\"Сохранить резалт\", command=sparsed)\nstatus_label = tkinter.Label(main_window, textvariable=status)\n\n#packagers\nimage.place(x=0, y=0)\nlabel1.place(x=10, y=60)\nentry1.place(x=10, y=80)\nlabel2.place(x=10,y=110)\nentry2.place(x=10,y=130)\nbutton.place(x=10,y=160)\nbutton2.place(x=10,y=195)\nbutton3.place(x=10, y=225)\n#status_label.place(x=10, y=190)\n\nmain_window.mainloop()\n","sub_path":"auth_window.py","file_name":"auth_window.py","file_ext":"py","file_size_in_byte":2765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"349502140","text":"import random\nimport os.path\nimport pickle\nimport vertex\nimport edge\nimport graph\n\n\"\"\" AI For Game Learning \"\"\"\nclass jigsaw():\n\n # Verbosity levels\n # 0 - no printing\n VERBOSITY = 0\n\n \"\"\" Load old settings from pickle file \"\"\"\n def __init__(self):\n\n if (os.path.isfile(\"jigsaw.p\")):\n\n # Load class info from file\n pickleFile = open(\"jigsaw.p\",\"rb\")\n self.Games = pickle.load(pickleFile)\n pickleFile.close()\n\n else:\n self.Games = {}\n\n self.curGame = \"\"\n self.curMoves = []\n self.wins = 0\n self.loss = 0\n self.ties = 0\n\n \"\"\" Save pickle file when class is destroyed \"\"\"\n def __del__(self):\n\n # print out wins & losses\n print(\"Won : \" + str(self.wins))\n print(\"Lost : \" + str(self.loss))\n print(\"Tied : \" + str(self.ties))\n\n if pickle:\n pickleFile = open(\"jigsaw.p\", \"wb\")\n pickle.dump(self.Games, pickleFile)\n pickleFile.close()\n\n def newGame(self, gameName):\n\n # Check against old games\n if (self.Games.get(gameName) == None):\n self.Games.update({gameName : graph.Graph(gameName)})\n\n self.curGame = gameName\n self.curMoves = []\n\n \"\"\" Main function, returns a move as an int from list of game.moves() \"\"\"\n def move(self, game):\n\n # Lookup the current game graph\n curGraph = self.Games.get(self.curGame)\n\n if (curGraph == None):\n raise ValueError(\"No current graph for game\")\n\n # Get the game info\n current = game.gameInfo()\n\n # Lookup the game position\n foundVertex = curGraph.getVertex(current)\n\n # Get a list of available moves\n mymoves = game.moves()\n\n # If there is no node for this game state, add the state and pick first move available\n if (foundVertex == None):\n\n # Pick first available move\n mymove = mymoves[0]\n\n # Add it to graph\n newVertex = vertex.Vertex(current)\n myEdge = edge.Edge(mymove)\n newVertex.addEdge(myEdge)\n curGraph.newVertex(newVertex)\n\n # set which edge we selected\n edgeSelection = myEdge\n\n else: # There is a current node for this game state\n\n knownMoves = foundVertex.getEdges()\n\n # DEBUG print the available moves\n if (jigsaw.VERBOSITY >= 2):\n for mov in knownMoves:\n print(mov)\n\n # Loop over all edges in current vertex pick an edge with no losses recorded\n # If no such edge exists, pick an edge from available moves that does not exist in knownMoves\n # If all moves are known and no moves exist with no loss pick a move at random\n bestEdge = None\n for edg in knownMoves:\n if (edg.Loss == 0):\n bestEdge = edg\n break\n\n # All known moves have lost. Pick a new move if one exists\n if (bestEdge == None):\n for newMove in mymoves:\n found = False\n for oldMove in knownMoves:\n if (newMove == oldMove.value()):\n found = True\n break\n if (not found):\n\n # Add the new edge\n myEdge = edge.Edge(newMove)\n foundVertex.addEdge(myEdge)\n\n # set which edge we selected\n bestEdge = myEdge \n\n # Still no edge selected: Pick edge with higest wins\n if (bestEdge == None):\n maxWins = 0\n for move in knownMoves:\n if (move.Wins > maxWins):\n maxWins = move.Wins\n bestEdge = move\n\n # Still no edge selected: Random selection\n if (bestEdge == None):\n bestEdge = knownMoves[random.randrange(0,len(knownMoves))]\n\n # set which edge we selected\n mymove = bestEdge.value()\n edgeSelection = bestEdge \n\n # add edge to stack of edges\n self.curMoves.append(edgeSelection)\n\n # DEBUG print the edge we selected\n if (jigsaw.VERBOSITY >= 1):\n print(\"\\nSelection: \" + str(edgeSelection))\n\n # Return the move that was selected\n return mymove\n\n \"\"\" Input the results of the current game \"\"\"\n def result(self, won):\n\n # WON\n if (won == 1):\n\n self.wins += 1\n\n # Walk the stack and increse wins on all edges\n for edg in reversed(self.curMoves):\n\n edg.incrwin();\n\n if (edg.Wins == 1):\n break\n\n # TIED\n elif (won == -1):\n\n self.ties += 1\n\n # Walk the stack and increse ties on all edges\n for edg in reversed(self.curMoves):\n\n edg.incrtie()\n\n if (edg.Tie == 1):\n break\n\n else: #LOSS\n\n self.loss += 1\n\n # Walk all edges in stack\n for edg in reversed(self.curMoves):\n\n edg.incrloss()\n\n # If the edge had no losses stop walking the stack\n if (edg.Loss == 1):\n break\n\n \"\"\"\" Print out all game info \"\"\"\n def __str__(self):\n\n retStr = \"\"\n for key in self.Games:\n retStr += str(self.Games.get(key))\n\n return retStr\n\nif __name__ == \"__main__\":\n\n ai = jigsaw()\n print(ai)\n del ai\n","sub_path":"jigsaw.py","file_name":"jigsaw.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"280600723","text":"from heapq import merge\r\nimport pandas as pd\r\n\r\ndef Sort_Tuple(tup):\r\n tup.sort(key=lambda x: x[1])\r\n return tup\r\n\r\n# Driver Code\r\nR = [(\"Kumar\", 2),\r\n (\"Wess\", 1),\r\n (\"Terry\", 1),\r\n (\"Gowri\", 2),\r\n (\"Morgan\", 3),\r\n (\"Sachin\", 3)\r\n ] # EName,DeptNo\r\n\r\nS = [(\"Design\", 1),\r\n (\"Production\", 2),\r\n (\"Administration\", 3)\r\n ] # DName,DeptNo\r\n\r\ndfr = pd.DataFrame(R, columns=['EName', 'DeptNo'])\r\nprint(dfr)\r\nprint(\"\\n\")\r\ndfs = pd.DataFrame(R, columns=['DName', 'DeptNo'])\r\nprint(dfs)\r\nprint(\"\\n\")\r\n# printing the sorted list of tuples\r\n# print(Sort_Tuple(R))\r\n# print(Sort_Tuple(S))\r\ntmp1 = Sort_Tuple(R)\r\ndfsr = pd.DataFrame(tmp1, columns=['EName', 'DeptNo'])\r\nprint(dfsr)\r\nprint(\"\\n\")\r\ntmp2 = Sort_Tuple(S)\r\ndfss = pd.DataFrame(R, columns=['DName', 'DeptNo'])\r\nprint(dfss)\r\nprint(\"\\n\")\r\ni = tmp1[0][1]\r\n# print(i)\r\nj = tmp2[0][1]\r\nprint(\"\\n\") # print(j)\r\njoin = []\r\n\r\nfor i in range(0, 6):\r\n for j in range(0, 3):\r\n # print(i,j)\r\n if tmp1[i][1] == tmp2[j][1]:\r\n join.append(tmp1[i])\r\n join.append(tmp2[j])\r\n break\r\n\r\n# print(join)\r\n# print(\"\\n\")\r\n\r\nfor i in range(0, len(tmp1) + len(tmp2) + 3): # or (len(tmp1)*2)+1\r\n if i % 2 == 0:\r\n print(join[i][0], \" \", end='')\r\n else:\r\n print(join[i][0], \"\\n\")","sub_path":"SortMergeJoin.py","file_name":"SortMergeJoin.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"50248488","text":"import tbump.config\nimport tbump.git\nimport tbump.git_bumper\n\n\ndef test_git_bumper(test_repo):\n config = tbump.config.parse(test_repo.joinpath(\"tbump.toml\"))\n git_bumper = tbump.git_bumper.GitBumper(test_repo)\n git_bumper.set_config(config)\n git_bumper.check_state(\"1.2.42\")\n test_repo.joinpath(\"VERSION\").write_text(\"1.2.42\")\n git_bumper.bump(\"1.2.42\")\n rc, out = tbump.git.run_git(test_repo, \"log\", \"--oneline\", raises=False)\n assert rc == 0\n assert \"Bump to 1.2.42\" in out\n","sub_path":"tbump/test/test_git_bumper.py","file_name":"test_git_bumper.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"68214334","text":"name = input(\"Enter the name of the employee : \")\nsalary = 0\nAverage = 0\nHighest = 0\nLowest = 1e10\nNameLowest = \"\"\nNameHighest = \"\"\nwhile(name != \"End\"):\n salary = int(input(\"Enter the salary\"))\n Average += salary\n if(salary > Highest):\n Highest = salary\n NameHighest = name\n if(Lowest < salary):\n Lowest = salary\n NameLowest = name\n name = input(\"Enter the name of the employee\")\n \nprint(\"Highest salary employee is \" + NameHighest + \" with amount \" + str(Highest)) \nprint(\"Lowest salary employee is \" + NameLowest + \" with amount \" + str(Highest)) \n\n\n \n \n ","sub_path":"Codes/Lab_1/Set1/Highest.py","file_name":"Highest.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"297348827","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\nimport warnings\nfrom scipy import ndimage\nfrom matplotlib import cm\nimport pandas as pd\nimport os as os\nimport csv as csv\nimport hicstuff.io as hio\nfrom hicstuff.log import logger\n\n\ndef export_distance_law(xs, ps, names, out_file=None):\n \"\"\" Export the x(s) and p(s) from two list of numpy.ndarrays to a table\n in txt file with three columns separated by a tabulation. The first column\n contains the x(s), the second the p(s) and the third the name of the arm or\n chromosome. The file is created in the directory given by outdir or the\n current file if no file is given.\n\n Parameters\n ----------\n xs : list of numpy.ndarray\n The list of the start position of logbins of each p(s) in base pairs.\n ps : list of numpy.ndarray\n The list of p(s).\n names : list of string\n List containing the names of the chromosomes/arms/conditions of the p(s)\n values given.\n out_file : str or None\n Path where output file should be written. ./distance_law.txt by default.\n\n Return\n ------\n txt file:\n File with three columns separated by a tabulation. The first column\n contains the x(s), the second the p(s) and the third the name of the arm\n or chromosome. The file is creates in the output file given or the\n default one if none given.\n \"\"\"\n # ./distance_law.txt as out_file if no out_file is given.\n if out_file is None:\n out_file = os.getcwd() + \"/distance_law.txt\"\n # Sanity check: as many chromosomes/arms as ps\n if len(xs) != len(names):\n logger.error(\"Number of chromosomes/arms and number of p(s) list differ.\")\n sys.exit(1)\n # Create the file and write it\n f = open(out_file, \"w\")\n for i in range(len(xs)):\n for j in range(len(xs[i])):\n line = (\n str(format(xs[i][j], \"g\"))\n + \"\\t\"\n + str(format(ps[i][j], \"g\"))\n + \"\\t\"\n + names[i]\n + \"\\n\"\n )\n f.write(line)\n f.close()\n\n\ndef import_distance_law(distance_law_file):\n \"\"\" Import the table created by export_distance_law and return the list of\n x(s) and p(s) in the order of the chromosomes.\n\n Parameters\n ----------\n distance_law_file : string\n Path to the file containing three columns : the x(s), the p(s), and the\n chromosome/arm name.\n\n Returns\n -------\n list of numpy.ndarray :\n The start coordinate of each bin one array per chromosome or arm.\n list of numpy.ndarray :\n The distance law probabilities corresponding of the bins of the\n previous list.\n list of numpy.ndarray :\n The names of the arms/chromosomes corresponding to the previous\n list.\n \"\"\"\n file = pd.read_csv(\n distance_law_file,\n sep=\"\\t\",\n header=None,\n dtype={\"a\": np.int32, \"b\": np.float32, \"c\": str},\n )\n names_idx = np.unique(file.iloc[:, 2], return_index=True)[1]\n names = [file.iloc[:, 2][index] for index in sorted(names_idx)]\n xs = [None] * len(names)\n ps = [None] * len(names)\n labels = [None] * len(names)\n for i in range(len(names)):\n subfile = file[file.iloc[:, 2] == names[i]]\n xs[i] = np.array(subfile.iloc[:, 0])\n ps[i] = np.array(subfile.iloc[:, 1])\n labels[i] = np.array(subfile.iloc[:, 2])\n return xs, ps, labels\n\n\ndef get_chr_segment_bins_index(fragments, centro_file=None, rm_centro=0):\n \"\"\"Get the index positions of the start and end bins of different \n chromosomes, or arms if the centromers position have been given from the\n fragments file made by hicstuff.\n \n Parameters\n ----------\n fragments : pandas.DataFrame\n Table containing in the first coulum the ID of the fragment, in the \n second the names of the chromosome in the third and fourth the start \n position and the end position of the fragment. The file have no header.\n (File like the 'fragments_list.txt' from hicstuff)\n centro_file : None or str\n None or path to a file with the genomic positions of the centromers \n sorted as the chromosomes separated by a space. The file have only one \n line.\n rm_centro : int\n If a value is given, will remove the contacts close the centromeres.\n It will remove as many kb as the argument given. Default is zero.\n \n Returns\n -------\n list of floats :\n The start and end indices of chromosomes/arms to compute the distance\n law on each chromosome/arm separately.\n \"\"\"\n # Get bins where chromosomes start\n chr_start_bins = np.where(fragments == 0)[0]\n # Create a list of same length for the end of the bins\n chr_end_bins = np.zeros(len(chr_start_bins))\n # Get bins where chromsomes end\n for i in range(len(chr_start_bins) - 1):\n chr_end_bins[i] = chr_start_bins[i + 1]\n chr_end_bins[-1] = len(fragments.iloc[:, 0])\n # Combine start and end of bins in a single array. Values are the id of the\n # bins\n chr_segment_bins = np.sort(np.concatenate((chr_start_bins, chr_end_bins)))\n if centro_file is not None:\n # Read the file of the centromers\n with open(centro_file, \"r\", newline=\"\") as centro:\n centro = csv.reader(centro, delimiter=\" \")\n centro_pos = next(centro)\n # Sanity check: as many chroms as centromeres\n if len(chr_start_bins) != len(centro_pos):\n logger.warning(\n \"Number of chromosomes and centromeres differ, centromeres position are not taking into account.\"\n )\n centro_file = None\n if centro_file is not None:\n # Get bins of centromeres\n centro_bins = np.zeros(2 * len(centro_pos))\n for i in range(len(chr_start_bins)):\n if (i + 1) < len(chr_start_bins):\n subfrags = fragments[chr_start_bins[i] : chr_start_bins[i + 1]]\n else:\n subfrags = fragments[chr_start_bins[i] :]\n # index of last fragment starting before centro in same chrom\n centro_bins[2 * i] = chr_start_bins[i] + max(\n np.where(\n subfrags[\"start_pos\"][:] // (int(centro_pos[i]) - rm_centro) == 0\n )[0]\n )\n centro_bins[2 * i + 1] = chr_start_bins[i] + max(\n np.where(\n subfrags[\"start_pos\"][:] // (int(centro_pos[i]) + rm_centro) == 0\n )[0]\n )\n # Combine centro and chrom bins into a single array. Values are the id\n # of the bins started and ending the arms.\n chr_segment_bins = np.sort(\n np.concatenate((chr_start_bins, chr_end_bins, centro_bins))\n )\n return list(chr_segment_bins)\n\n\ndef get_chr_segment_length(fragments, chr_segment_bins):\n \"\"\"Compute a list of the length of the different objects (arm or \n chromosome) given by chr_segment_bins.\n \n Parameters\n ----------\n fragments : pandas.DataFrame\n Table containing in the first coulum the ID of the fragment, in the \n second the names of the chromosome in the third and fourth the start \n position and the end position of the fragment. The file have no header.\n (File like the 'fragments_list.txt' from hicstuff)\n chr_segment_bins : list of floats\n The start and end indices of chromosomes/arms to compute the distance\n law on each chromosome/arm separately.\n \n Returns\n -------\n list of numpy.ndarray:\n The length in base pairs of each chromosome or arm.\n \"\"\"\n chr_segment_length = [None] * int(len(chr_segment_bins) / 2)\n # Iterate in chr_segment_bins in order to obtain the size of each chromosome/arm\n for i in range(len(chr_segment_length)):\n # Obtain the size of the chromosome/arm, the if loop is to avoid the\n # case of arms where the end position of the last fragments doesn't\n # mean the size of arm. If it's the right arm we have to start to count the\n # size from the beginning of the arm.\n if fragments[\"start_pos\"].iloc[int(chr_segment_bins[2 * i])] == 0:\n n = fragments[\"end_pos\"].iloc[int(chr_segment_bins[2 * i + 1]) - 1]\n else:\n n = (\n fragments[\"end_pos\"].iloc[int(chr_segment_bins[2 * i + 1]) - 1]\n - fragments[\"start_pos\"].iloc[int(chr_segment_bins[2 * i])]\n )\n chr_segment_length[i] = n\n return chr_segment_length\n\n\ndef logbins_xs(fragments, chr_segment_length, base=1.1, circular=False):\n \"\"\"Compute the logbins of each chromosome/arm in order to have theme to\n compute distance law. At the end you will have bins of increasing with a \n logspace with the base of the value given in base.\n \n Parameters\n ----------\n fragments : pandas.DataFrame\n Table containing in the first coulum the ID of the fragment, in the \n second the names of the chromosome in the third and fourth the start \n position and the end position of the fragment. The file have no header.\n (File like the 'fragments_list.txt' from hicstuff)\n chr_segment_length: list of floats\n List of the size in base pairs of the different arms or chromosomes.\n base : float\n Base use to construct the logspace of the bins, 1.1 by default.\n circular : bool\n If True, calculate the distance as the chromosome is circular. Default \n value is False.\n \n Returns\n -------\n list of numpy.ndarray :\n The start coordinate of each bin one array per chromosome or arm.\n \"\"\"\n # Create the xs array and a list of the length of the chromosomes/arms\n xs = [None] * len(chr_segment_length)\n # Iterate in chr_segment_bins in order to make the logspace\n for i in range(len(chr_segment_length)):\n n = chr_segment_length[i]\n # if the chromosome is circular the mawimum distance between two reads\n # are divided by two\n if circular:\n n /= 2\n n_bins = int(np.log(n) / np.log(base))\n # For each chromosome/arm compute a logspace to have the logbin\n # equivalent to the size of the arms and increasing size of bins\n xs[i] = np.unique(\n np.logspace(0, n_bins, num=n_bins + 1, base=base, dtype=int)\n )\n return xs\n\n\ndef circular_distance_law(distance, chr_segment_length, chr_bin):\n \"\"\"Recalculate the distance to return the distance in a circular chromosome\n and not the distance between the two genomic positions.\n\n Parameters\n ----------\n chr_segment_bins : list of floats\n The start and end indices of chromosomes/arms to compute the distance\n law on each chromosome/arm separately.\n chr_segment_length: list of floats\n List of the size in base pairs of the different arms or chromosomes.\n distance : int\n Distance between two fragments with a contact.\n\n Returns\n -------\n int :\n The real distance in the chromosome circular and not the distance \n between two genomic positions\n\n Examples\n --------\n >>> circular_distance_law(7500, [2800, 9000], 1)\n 1500\n >>> circular_distance_law(1300, [2800, 9000], 0)\n 1300\n >>> circular_distance_law(1400, [2800, 9000], 0)\n 1400\n \"\"\"\n chr_len = chr_segment_length[chr_bin]\n if distance > chr_len / 2:\n distance = chr_len - distance\n return distance\n\n\ndef get_pairs_distance(\n line, fragments, chr_segment_bins, chr_segment_length, xs, ps, circular=False\n):\n \"\"\"From a line of a pair reads file, filter -/+ or +/- reads, keep only the \n reads in the same chromosome/arm and compute the distance of the the two\n fragments. It modify the input ps in order to count or not the line given. \n It will add one in the logbin corresponding to the distance.\n\n Parameters\n ----------\n line : OrderedDict\n Line of a pair reads file with the these keys readID, chr1, pos1, chr2,\n pos2, strand1, strand2, frag1, frag2. The values are in a dictionnary.\n fragments : pandas.DataFrame\n Table containing in the first coulum the ID of the fragment, in the \n second the names of the chromosome in the third and fourth the start \n position and the end position of the fragment. The file have no header.\n (File like the 'fragments_list.txt' from hicstuff)\n chr_segment_bins : list of floats\n The start and end indices of chromosomes/arms to compute the distance\n law on each chromosome/arm separately.\n chr_segment_length: list of floats\n List of the size in base pairs of the different arms or chromosomes.\n xs : list of lists\n The start coordinate of each bin one array per chromosome or arm.\n ps : list of lists\n The sum of contact already count. xs and ps should have the same \n dimensions.\n circular : bool\n If True, calculate the distance as the chromosome is circular. Default \n value is False.\n \"\"\"\n # Check this is a pairs_idx file and not simple pairs\n if line['frag1'] is None:\n logger.error(\n 'Input pairs file must have frag1 and frag2 columns. In hicstuff '\n 'pipeline, this is the \"valid_idx.pairs\" file.'\n )\n # We only keep the event +/+ or -/-. This is done to avoid to have any\n # event of uncut which are not possible in these events. We can remove the\n # good events of +/- or -/+ because we don't need a lot of reads to compute\n # the distance law and if we eliminate these reads we do not create others\n # biases as they should have the same distribution.\n if line[\"strand1\"] == line[\"strand2\"]:\n # Find in which chromosome/arm are the fragment 1 and 2.\n chr_bin1 = (\n np.searchsorted(chr_segment_bins, int(line[\"frag1\"]), side=\"right\") - 1\n )\n chr_bin2 = (\n np.searchsorted(chr_segment_bins, int(line[\"frag2\"]), side=\"right\") - 1\n )\n # We only keep the reads with the two fragments in the same chromosome\n # or arm.\n if chr_bin1 == chr_bin2:\n # Remove the contacts in the centromeres if centro_remove\n if chr_bin1 % 2 == 0:\n chr_bin1 = int(chr_bin1 / 2)\n # For the reads -/-, the fragments should be religated with both\n # their start position (position in the left on the genomic\n # sequence, 5'). For the reads +/+ it's the contrary. We compute\n # the distance as the distance between the two extremities which\n # are religated.\n if line[\"strand1\"] == \"-\":\n distance = abs(\n np.array(fragments[\"start_pos\"][int(line[\"frag1\"])])\n - np.array(fragments[\"start_pos\"][int(line[\"frag2\"])])\n )\n if line[\"strand1\"] == \"+\":\n distance = abs(\n np.array(fragments[\"end_pos\"][int(line[\"frag1\"])])\n - np.array(fragments[\"end_pos\"][int(line[\"frag2\"])])\n )\n if circular:\n distance = circular_distance_law(\n distance, chr_segment_length, chr_bin1\n )\n xs_temp = xs[chr_bin1][:]\n # Find the logbins in which the distance is and add one to the sum\n # of contact.\n ps_indice = np.searchsorted(xs_temp, distance, side=\"right\") - 1\n ps[chr_bin1][ps_indice] += 1\n\n\ndef get_names(fragments, chr_segment_bins):\n \"\"\"Make a list of the names of the arms or the chromosomes.\n\n Parameters\n ----------\n fragments : pandas.DataFrame\n Table containing in the first coulum the ID of the fragment, in the \n second the names of the chromosome in the third and fourth the start \n position and the end position of the fragment. The file have no header.\n (File like the 'fragments_list.txt' from hicstuff)\n chr_segment_bins : list of floats\n The start position of chromosomes/arms to compute the distance law on \n each chromosome/arm separately.\n\n Returns\n -------\n list of floats : \n List of the labels given to the curves. It will be the name of the arms\n or chromosomes.\n \"\"\"\n # Get the name of the chromosomes.\n chr_names_idx = np.unique(fragments.iloc[:, 1], return_index=True)[1]\n chr_names = [fragments.iloc[:, 1][index] for index in sorted(chr_names_idx)]\n # Case where they are separate in chromosomes\n if len(chr_segment_bins) / 2 != len(chr_names):\n names = []\n for chr in chr_names:\n names.append(str(chr) + \"_left\")\n names.append(str(chr) + \"_rigth\")\n chr_names = names\n return chr_names\n\n\ndef get_distance_law(\n pairs_reads_file,\n fragments_file,\n centro_file=None,\n base=1.1,\n out_file=None,\n circular=False,\n rm_centro=0,\n):\n \"\"\"Compute distance law as a function of the genomic coordinate aka P(s).\n Bin length increases exponentially with distance. Works on pairs file \n format from 4D Nucleome Omics Data Standards Working Group. If the genome \n is composed of several chromosomes and you want to compute the arms \n separately, provide a file with the positions of centromers. Create a file \n with three coulumns separated by a tabulation. The first column contains \n the xs, the second the ps and the third the name of the arm or chromosome. \n The file is create in the directory given in outdir or in the current \n directory if no directory given.\n\n Parameters\n ----------\n pairs_reads_file : string\n Path of a pairs file format from 4D Nucleome Omics Data Standards \n Working Group with the 8th and 9th coulumns are the ID of the fragments\n of the reads 1 and 2.\n fragments_file : path\n Path of a table containing in the first column the ID of the fragment,\n in the second the names of the chromosome in the third and fourth \n the start position and the end position of the fragment. The file have \n no header. (File like the 'fragments_list.txt' from hicstuff)\n centro_file : None or str\n None or path to a file with the genomic positions of the centromers \n sorted as the chromosomes separated by a space. The file have only one \n line.\n base : float\n Base use to construct the logspace of the bins - 1.1 by default.\n out_file : None or str\n Path of the output file. If no path given, the output is returned.\n circular : bool\n If True, calculate the distance as the chromosome is circular. Default \n value is False. Cannot be True if centro_file is not None\n rm_centro : int\n If a value is given, will remove the contacts close the centromeres.\n It will remove as many kb as the argument given. Default is None.\n\n Returns\n -------\n xs : list of numpy.ndarray\n Basepair coordinates of log bins used to compute distance law.\n ps : list of numpy.ndarray\n Contacts value, in arbitrary units, at increasingly long genomic ranges\n given by xs.\n names : list of strings\n Names of chromosomes that are plotted\n \"\"\"\n # Sanity check : centro_fileition should be None if chromosomes are\n # circulars (no centromeres is circular chromosomes).\n if circular and centro_file != None:\n logger.error(\"Chromosomes cannot have a centromere and be circular\")\n sys.exit(1)\n # Import third columns of fragments file\n fragments = pd.read_csv(fragments_file, sep=\"\\t\", header=0, usecols=[0, 1, 2, 3])\n # Calculate the indice of the bins to separate into chromosomes/arms\n chr_segment_bins = get_chr_segment_bins_index(fragments, centro_file, rm_centro)\n # Calculate the length of each chromosoms/arms\n chr_segment_length = get_chr_segment_length(fragments, chr_segment_bins)\n xs = logbins_xs(fragments, chr_segment_length, base, circular)\n # Create the list of p(s) with one array for each chromosome/arm and each\n # array contain as many values as in the logbin\n ps = [None] * len(chr_segment_length)\n for i in range(len(xs)):\n ps[i] = [0] * len(xs[i])\n # Read the pair reads file\n with open(pairs_reads_file, \"r\", newline=\"\") as reads:\n # Remove the line of the header\n header_length = len(hio.get_pairs_header(pairs_reads_file))\n for i in range(header_length):\n next(reads)\n # Reads all the others lines and put the values in a dictionnary with\n # the keys : 'readID', 'chr1', 'pos1', 'chr2', 'pos2', 'strand1',\n # 'strand2', 'frag1', 'frag2'\n reader = csv.DictReader(\n reads,\n fieldnames=[\n \"readID\",\n \"chr1\",\n \"pos1\",\n \"chr2\",\n \"pos2\",\n \"strand1\",\n \"strand2\",\n \"frag1\",\n \"frag2\",\n ],\n delimiter=\"\\t\",\n )\n for line in reader:\n # Iterate in each line of the file after the header\n get_pairs_distance(\n line, fragments, chr_segment_bins, chr_segment_length, xs, ps, circular\n )\n # Divide the number of contacts by the area of the logbin\n for i in range(len(xs)):\n n = chr_segment_length[i]\n for j in range(len(xs[i]) - 1):\n # Use the area of a trapezium to know the area of the logbin with n\n # the size of the matrix.\n ps[i][j] /= ((2 * n - xs[i][j + 1] - xs[i][j]) / 2) * (\n (1 / np.sqrt(2)) * (xs[i][j + 1] - xs[i][j])\n )\n # print(\n # ((2 * n - xs[i][j + 1] - xs[i][j]) / 2)\n # * ((1 / np.sqrt(2)) * (xs[i][j + 1] - xs[i][j]))\n # )\n # Case of the last logbin which is an isosceles rectangle triangle\n # print(ps[i][-5:-1], ((n - xs[i][-1]) ** 2) / 2)\n ps[i][-1] /= ((n - xs[i][-1]) ** 2) / 2\n names = get_names(fragments, chr_segment_bins)\n if out_file:\n export_distance_law(xs, ps, names, out_file)\n return xs, ps, names\n\n\ndef normalize_distance_law(xs, ps, inf=3000, sup=None):\n \"\"\"Normalize the distance in order to have the sum of the ps values between\n 'inf' (default value is 3kb) until the end of the array equal to one and\n limit the effect of coverage between two conditions/chromosomes/arms when\n you compare them together. If we have a list of ps, it will normalize until\n the length of the shorter object or the value of sup, whichever is smaller.\n\n Parameters\n ----------\n xs : list of numpy.ndarray\n list of logbins corresponding to the ps.\n ps : list of numpy.ndarray\n Average ps or list of ps of the chromosomes/arms. xs and ps have to \n have the same shape.\n inf : integer\n Inferior value of the interval on which, the normalization is applied.\n sup : integer\n Superior value of the interval on which, the normalization is applied.\n\n Returns\n -------\n list of numpy.ndarray :\n List of ps each normalized separately.\n \"\"\"\n # Sanity check: xs and ps have the same dimension\n if np.shape(xs) != np.shape(ps):\n logger.error(\"xs and ps should have the same dimension.\")\n sys.exit(1)\n # Define the length of shortest chromosomes as a lower bound for the sup boundary\n min_xs = len(min(xs, key=len))\n normed_ps = [None] * len(ps)\n if sup is None:\n sup = np.inf\n for chrom_id, chrom_ps in enumerate(ps):\n # Iterate on the different ps to normalize each of theme separately\n chrom_sum = 0\n # Change the last value to have something continuous because the last\n # one is much bigger (computed on matrix corner = triangle instead of trapezoid).\n chrom_ps[-1] = chrom_ps[-2]\n for bin_id, bin_value in enumerate(chrom_ps):\n # Compute normalization factor based on values between inf and sup\n # Sup will be whatever is smaller between user-provided sup and length of\n # the shortest chromosome\n if (xs[chrom_id][bin_id] > inf) and (xs[chrom_id][bin_id] < sup) and (bin_id < min_xs):\n chrom_sum += bin_value\n if chrom_sum == 0:\n chrom_sum += 1\n logger.warning(\"No values of p(s) in one segment\")\n # Make the normalisation\n normed_ps[chrom_id] = np.array(ps[chrom_id]) / chrom_sum\n return normed_ps\n\n\ndef average_distance_law(xs, ps, sup, big_arm_only=False):\n \"\"\"Compute the average distance law between the file the different distance\n law of the chromosomes/arms.\n\n Parameters\n ----------\n xs : list of numpy.ndarray\n The list of logbins.\n ps : list of lists of floats\n The list of numpy.ndarray.\n sup : int\n Value given to set the minimum size of the chromosomes/arms to make the\n average.\n big_arm_only : bool\n By default False. If True, will only take into account the arms/chromosomes \n longer than the value of sup. Sup mandatory if set.\n\n Returns\n -------\n numpy.ndarray :\n List of the xs with the max length.\n numpy.ndarray :\n List of the average_ps.\n \"\"\"\n # Find longest chromosome / arm and make two arrays of this length for the\n # average distance law and remove the last value.\n xs = max(xs, key=len)\n max_length = len(xs)\n ps_values = np.zeros(max_length)\n ps_occur = np.zeros(max_length)\n for chrom_ps in ps:\n # Iterate on ps in order to calculate the number of occurences (all the\n # chromossomes/arms are not as long as the longest one) and the sum of\n # the values of distance law.\n # Change the last value to have something continuous because the last\n # one is much bigger.\n chrom_ps[-1] = chrom_ps[-2]\n # Sanity check : sup strictly inferior to maw length arms.\n if big_arm_only:\n if sup >= xs[-1]:\n logger.error(\n \"sup have to be inferior to the max length of arms/chromsomes if big arm only set\"\n )\n sys.exit(1)\n if sup <= xs[len(chrom_ps) - 1]:\n ps_occur[: len(chrom_ps)] += 1\n ps_values[: len(chrom_ps)] += chrom_ps\n else:\n ps_occur[: len(chrom_ps)] += 1\n ps_values[: len(chrom_ps)] += chrom_ps\n # Make the mean\n averaged_ps = ps_values / ps_occur\n return xs, averaged_ps\n\n\ndef slope_distance_law(xs, ps):\n \"\"\"Compute the slope of the loglog curve of the ps as the \n [log(ps(n+1)) - log(ps(n))] / [log(n+1) - log(n)].\n Compute only list of ps, not list of array.\n\n Parameters\n ----------\n xs : list of numpy.ndarray\n The list of logbins.\n ps : list of numpy.ndarray\n The list of ps.\n\n Returns\n -------\n list of numpy.ndarray :\n The slope of the distance law. It will be shorter of one value than the\n ps given initially.\n \"\"\"\n slope = [None] * len(ps)\n for i in range(len(ps)):\n ps[i][ps[i] == 0] = 10 ** (-9)\n # Compute the slope\n slope_temp = np.log(np.array(ps[i][1:]) / np.array(ps[i][:-1])) / np.log(\n np.array(xs[i][1:]) / np.array(xs[i][:-1])\n )\n # The 1.8 is the intensity of the normalisation, it could be adapted.\n slope_temp[slope_temp == np.nan] = 10 ** (-15)\n slope[i] = ndimage.filters.gaussian_filter1d(slope_temp, 1.8)\n return slope\n\n\ndef get_ylim(xs, curve, inf, sup):\n \"\"\"Compute the max and the min of the list of list between the inferior\n (inf) and superior (sup) bounds.\n\n Parameters\n ----------\n xs : list of numpy.ndarray\n The list of the logbins starting position in basepair.\n curve : list of numpy.ndarray\n A list of numpy.ndarray from which you want to extract minimum and\n maximum values in a given interval.\n inf : int\n Inferior limit of the interval in basepair.\n sup : int\n Superior limit of the interval in basepair.\n\n Returns\n -------\n min_tot : float\n Minimum value of the list of list in this interval.\n max_tot : float\n Maximum value of the list of list in this interval.\n\n Examples\n --------\n >>> get_ylim([np.array([1, 4, 15]), np.array([1, 4, 15, 40])],\n ... [np.array([5.5, 3.2, 17.10]), np.array([24, 32, 1.111, 18.5])],\n ... 2,\n ... 15\n ... )\n (1.111, 32.0)\n \"\"\"\n # Create a list in order to add all the interesting values\n flatten_list = []\n for i, logbins in enumerate(xs):\n # Iterate on xs.\n # Search for the minimum index corresponding to the smallest bin\n # superior or equal to inf (in pair base).\n min_value = min(logbins[logbins >= inf], default=0)\n min_index = np.where(logbins == min_value)[0]\n # Skip chromosome if total size smaller than inf\n if len(min_index) == 0:\n continue\n # Search for the maximum index corresponding to the biggest bin\n # inferior or equal to sup (in pair base).\n max_value = max(logbins[logbins <= sup])\n max_index = np.where(logbins == max_value)[0]\n # Add the values in the interval in the flattened list.\n if int(max_index) != len(logbins) - 1:\n max_index += 1\n for j in range(int(min_index), int(max_index)):\n flatten_list.append(curve[i][j])\n # Caluclate the min and the max of this list.\n min_tot = min(flatten_list)\n max_tot = max(flatten_list)\n return min_tot, max_tot\n\n\ndef plot_ps_slope(xs, ps, labels, fig_path=None, inf=3000, sup=None):\n \"\"\"Compute two plots, one with the different distance law of each \n arm/chromosome in loglog scale and one with the slope (derivative) of these\n curves. Generate a svg file with savefig.\n\n Parameters\n ----------\n xs : list of numpy.ndarray\n The list of the logbins of each ps.\n ps : list of numpy.ndarray\n The list of ps.\n labels_file : list of strings\n Names of the different curves in the order in which they are given.\n fig_path : str\n Path where the figure will be created. If None (default), the plot is\n shown in an interactive window.\n inf : int \n Value of the mimimum x of the window of the plot. Have to be strictly\n positive. By default 3000.\n sup : int \n Value of the maximum x of the window of the plot. By default None.\n \n \"\"\"\n # Give the max value for sup if no value have been attributed\n if sup is None:\n sup = max(max(xs, key=len))\n\n # Compute slopes from the curves\n slope = slope_distance_law(xs, ps)\n # Make the plot of distance law\n # Give a range of color\n cols = iter(cm.rainbow(np.linspace(0, 1, len(ps))))\n fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, figsize=(18, 10))\n plt.subplots_adjust(left=0.05, right=0.85, top=0.93, bottom=0.07)\n ax1.set_xlabel(\"Distance (pb)\", fontsize=\"x-large\")\n ax1.set_ylabel(\"P(s)\", fontsize=\"x-large\")\n ax1.set_title(\"Distance law\", fontsize=\"xx-large\")\n ylim = get_ylim(xs, ps, inf, sup)\n ax1.set_ylim(0.9 * ylim[0], 1.1 * ylim[1])\n for i in range(len(ps)):\n # Iterate on the different distance law array and take them by order of\n # size in order to have the color scale equivalent to the size scale\n col = next(cols)\n ax1.loglog(xs[i], ps[i], label=labels[i])\n # Make the same plot with the slope\n cols = iter(cm.rainbow(np.linspace(0, 1, len(slope))))\n ax2.set_xlabel(\"Distance (pb)\", fontsize=\"x-large\")\n ax2.set_ylabel(\"Slope\", fontsize=\"x-large\")\n ax2.set_title(\"Slope of the distance law\", fontsize=\"xx-large\")\n ax2.set_xlim([inf, sup])\n ylim = get_ylim(xs, slope, inf, sup)\n ax2.set_ylim(1.1 * ylim[0], 0.9 * ylim[1])\n xs2 = [None] * len(xs)\n for i in range(len(slope)):\n xs2[i] = xs[i][:-1]\n col = next(cols)\n ax2.semilogx(xs2[i], slope[i], label=labels[i], subs=[2, 3, 4, 5, 6, 7, 8, 9])\n ax2.legend(loc=\"upper left\", bbox_to_anchor=(1.02, 1.00), ncol=1, fontsize=\"large\")\n # Save the figure in svg\n if fig_path is not None:\n plt.savefig(fig_path)\n else:\n plt.show()\n","sub_path":"hicstuff/distance_law.py","file_name":"distance_law.py","file_ext":"py","file_size_in_byte":32461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"154328682","text":"import tensorflow as tf\nstate = tf.Variable(0.0,dtype=tf.float32)\none = tf.constant(1.0,dtype=tf.float32)\nnew_val = tf.add(state, one)\nupdate = tf.assign(state, new_val) #返回tensor, 值为new_val\nupdate2 = tf.assign(state, 10000) #没有fetch,便没有执行\ninit = tf.initialize_all_variables()\n\nwith tf.Session() as sess:\n sess.run(init)\n for _ in range(3):\n print(sess.run(update))\n","sub_path":"Contextual_Bandit/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"69188049","text":"'''\nCreated on Jul. 23, 2019\nData analysis of the simulation results.\n\n@file simulator_analysis.py\n@author Evandro de Souza\n@date 2019.07.23 \n@version 0.1\n@company University of Alberta - Computing Science\n'''\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport sys\n\n#--- select dataset file\nif len(sys.argv) > 1:\n storename = sys.argv[1]\nelse:\n storename = 'CollectorStore.hd5'\n\n#--- Load data\nstore = pd.HDFStore(storename)\ndf = store['Collector']\nstore.close()\n\n#--- select sets\ndf_sets = []\ndf_names = []\nmax_t = 0\nfor col in df:\n df_sets.append(df[col])\n df_names.append(col)\n if (max_t < max(df[col]['t'])): max_t = max(df[col]['t'])\n\nfig, axs = plt.subplots(len(df_sets))\nfig.set_size_inches(11, 18.5)\nplt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)\nplt.xlabel('Time (ms)')\nfor i in range(len(df_sets)):\n axs[i].set_title(df_names[i])\n axs[i].plot(df_sets[i]['t'], df_sets[i]['v'], '.')\n axs[i].set_xlim(-5, max_t+5)\n axs[i].grid(b=True, which='both', axis='both')\n\nplt.tight_layout()\nfig.savefig('Monitor.png', dpi=100)\n\n\n\n\n\n","sub_path":"TapControl/tapcontrol/simulator_analysis.py","file_name":"simulator_analysis.py","file_ext":"py","file_size_in_byte":1120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"124274499","text":"#!/usr/bin/env python\nimport json\nimport os\nimport subprocess\nimport sys\n\n_BITS = []\n\n\ndef _bit(idx):\n def wrapper(func):\n _BITS.append([idx, func.__name__.replace('_', ''), func])\n return func\n return wrapper\n\n\n@_bit(6)\ndef _mem():\n with open('/proc/meminfo') as meminfo_fp:\n attrs = {}\n for line in meminfo_fp.readlines():\n parts = line.split(':', 2)\n attrs[parts[0].strip()] = parts[1].strip()\n avail = int(attrs['MemAvailable'].split()[0])\n total = int(attrs['MemTotal'].split()[0])\n used = int(((total - avail) / total) * 100)\n color = None\n if used > 75:\n color = '#ff0000'\n if used < 25:\n color = '#00ff00'\n return 'M:{}%'.format(used), color\n\n\n@_bit(0)\ndef _backlight(dev_dir='/sys/class/backlight/intel_backlight'):\n with open('{}/brightness'.format(dev_dir)) as br_fp:\n with open('{}/max_brightness'.format(dev_dir)) as mb_fp:\n value = int(br_fp.read().strip())\n max_value = int(mb_fp.read().strip())\n pct = int(float(float(value) / float(max_value)) * 100)\n color = None\n if pct >= 75:\n color = '#ffaa00'\n if pct <= 25:\n color = '#5599ff'\n return '☼:{}%'.format(pct), color\n\n\nTHINKFAN_CONF = '/etc/thinkfan.conf'\nACPI_IBM_FAN = '/proc/acpi/ibm/fan'\n\n\n@_bit(7)\ndef _hwtemp(conf=THINKFAN_CONF, fan=ACPI_IBM_FAN):\n if not os.path.exists(conf):\n return None, None\n\n temps = []\n\n with open('/etc/thinkfan.conf') as tfc_fp:\n for line in tfc_fp.readlines():\n if not line.startswith('hwmon '):\n continue\n try:\n with open(line.split(' ')[1].strip()) as temp_fp:\n temps.append(float(temp_fp.read()))\n except (OSError, IOError) as exc:\n sys.stderr.write(str(exc) + '\\n')\n\n avg_temp = float(sum(temps)) / len(temps) / 1000.0\n color = None\n\n fan_level = 'unset'\n try:\n with open(fan) as fan_fp:\n for line in fan_fp.readlines():\n if not line.startswith('level:\\t\\t'):\n continue\n fan_level = int(line.replace('level:\\t\\t', ''))\n except (OSError, IOError) as exc:\n sys.stderr.write(str(exc) + '\\n')\n\n if avg_temp > 75:\n color = '#ff0000'\n if avg_temp >= 50:\n color = '#ffaa00'\n if avg_temp <= 25:\n color = '#5599ff'\n return 'T:{:.1f}°C L:{}'.format(avg_temp, fan_level), color\n\n\ndef _print_line(message):\n sys.stdout.write(message + '\\n')\n sys.stdout.flush()\n\n\ndef _read_line():\n try:\n line = sys.stdin.readline().strip()\n if not line:\n sys.exit(3)\n return line\n except KeyboardInterrupt:\n sys.exit()\n\n\ndef main(bits=_BITS):\n _print_line(_read_line())\n _print_line(_read_line())\n\n while True:\n line, prefix = _read_line(), ''\n if line.startswith(','):\n line, prefix = line[1:], ','\n\n loaded = json.loads(line)\n for idx, name, func in bits:\n try:\n value, color = func()\n if value is None:\n continue\n\n record = dict(full_text=str(value), name=name)\n if color is not None:\n record.update(dict(color=color))\n\n loaded.insert(idx, record)\n except Exception as exc:\n sys.stderr.write(str(exc) + '\\n')\n sys.stderr.flush()\n\n _print_line(prefix+json.dumps(loaded))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"local/bin/i3wrapper.py","file_name":"i3wrapper.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"352006314","text":"# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this\n# software and associated documentation files (the \"Software\"), to deal in the Software\n# without restriction, including without limitation the rights to use, copy, modify,\n# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n \n\n# Global configuration dict object for the app\n#\n# can be used as state as well\n#\nimport datetime\n\n# these are the defaults, they can be overwritten\nstate = {\n 'file': 'file:///generated_data',\n 'record_separator': '\\t',\n 'quote_records': True,\n\n #\n # Timestamp handling\n #\n 'time_col_name': 'Timestamp(ms)', # column name to use for time \n 'time_scale': 1000.0, # units/second -- e.g. 1000.0 means stamps in milliseconds\n\n # Select a Strategy from MessagePayload.py to define how to format a payload from the record\n 'payload_strategy': 'DotLabelledPayload',\n \n # Topic to publish messages, different payload_strategies may need different templates using local vars\n 'topic_name': \"dt/{deviceid}\",\n \n # what to do at the end of the file... 'stop' or 'repeat'\n 'at_end': 'repeat',\n \n 'MAX_DISCOVERY_RETRIES': 2,\n 'OFFLINE_QUEUE_DEPTH': 1\n}\n","sub_path":"samples/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"174903062","text":"import discord\nimport random\nimport humanize\nimport asyncio\nimport datetime\nimport string\nfrom discord.ext import commands\n\n\nclass Miscellaneous(commands.Cog):\n \"\"\"Helpful commands that don't quite fit in a certain category\"\"\"\n\n def __init__(self, client):\n self.client = client\n\n @commands.command()\n async def invite(self, ctx):\n \"\"\"Invite NOVA to your own server\"\"\"\n embed = discord.Embed(title='Invite links for NOVA',\n description='[<:news:730866149109137520> Required Permissions](https://discord.com/api/'\n 'oauth2/authorize?client_id=709922850953494598&permissions=1573252215&scope='\n 'bot)\\n'\n '[<:news:730866149109137520> No Permissions]'\n '(https://discord.com/api/oauth2/authorize?client_id=709922850953494598&permi'\n 'ssions=0&scope=bot)\\n[<:news:730866149109137520> All Permissions (admin)]'\n '(https://discord.com/api/oauth2/authorize?client_id=709922850953494598&perm'\n 'issions=8&scope=bot)', color=0x5643fd)\n embed.set_footer(text='Developed by YeetVegetabales', icon_url='https://cdn.discordapp.com/avatars'\n '/569374429218603019'\n '/a_6dac6946906e498650f6c2466aa82200.gif?size'\n '=256&f=.gif')\n embed.set_thumbnail(url='https://images-ext-2.discordapp.net/external/54Mim4lahztGCP4hgmpy4lOdEUc4'\n '-dOeNA_x6hVHMlc/%3Fsize%3D4096/https/cdn.discordapp.com/avatars/709922850953494598'\n '/f78ed19924e8c95abc30f406d47670d7.png')\n await ctx.send(embed=embed)\n\n @commands.command()\n async def discord(self, ctx):\n \"\"\"Generate a link to join NOVA's discord server!\"\"\"\n embed = discord.Embed(title='Join the discord today!', color=0x5643fd, description=\"This server is where \"\n \"all of \"\n \"NOVA's updates and \"\n \"important \"\n \"announcements will pass \"\n \"through. The creator of \"\n \"this \"\n \"bot, YeetVegetabales#5313, \"\n \"will also be there testing \"\n \"and letting the communtiy \"\n \"in \"\n \"on things first hand!\")\n embed.set_thumbnail(url='https://images-ext-2.discordapp.net/external/AQCEqCF4Yl_PWAfuA-GReZoDify6'\n '--y4hXOJVkqaDHo/%3Fsize%3D1024/https/cdn.discordapp.com/avatars/709922850953494598'\n '/f78ed19924e8c95abc30f406d47670d7.png')\n embed.add_field(name='Server Invite', value='<:news:730866149109137520> '\n '[Join here](https://discord.gg/Uqh9NXY)')\n await ctx.send(embed=embed)\n\n @commands.command()\n async def ping(self, ctx):\n \"\"\"Calculate bot latency\"\"\"\n ping = round(self.client.latency, 5)\n await ctx.send(f\" ``{ping * 1000} milliseconds`` \")\n\n @commands.command(aliases=['dev'])\n async def developer(self, ctx):\n embed = discord.Embed(title='Developer - YeetVegetabales', color=0x5643fd, timestamp=ctx.message.created_at,\n description=\"The developer of this bot is YeetVegetabales. He is 15 years old and\"\n \" made NOVA in order to learn how to code. DM him on discord to get any \"\n \"information on this bot or if you just want to chat about anything :)\\n\\n\"\n \"<:Discord:735530547992068146> - \"\n \"**[YeetVegetabales#5313](https://discord.gg/Uqh9NXY)**\\n\\n\"\n \"<:reddit:749433072549625897> - **[u/YeetVegetabales]\"\n \"(https://reddit.com/user/YeetVegetabales)**\\n\\n\"\n \"<:github:734999696845832252> - **[YeetVegetabales]\"\n \"(https://github.com/YeetVegetabales/)**\\n\\n\"\n \"<:steamsquare512:770389717342224465> - **[Vendetta](\"\n \"https://steamcommunity.com/profiles/76561199089966378)**\")\n await ctx.send(embed=embed)\n\n @commands.command(aliases=['wordcounter', 'wordcount'])\n async def words(self, ctx, *, message):\n \"\"\"Count how many words are in your document or sentence.\"\"\"\n doc = str(message)\n res = str(sum([i.strip(string.punctuation).isalpha() for i in doc.split()]))\n final = \"\"\n if res == \"1\":\n final += \"Your message is only **1** word.\"\n else:\n final += f'Your message is **{res}** words long.'\n await ctx.send(final)\n\n\ndef setup(client):\n client.add_cog(Miscellaneous(client))\n","sub_path":"cogs/Miscellaneous.py","file_name":"Miscellaneous.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"338070750","text":"from __future__ import absolute_import, unicode_literals\n\nimport re\nfrom datetime import datetime\n\nfrom django.db import models\nfrom django.template.defaultfilters import slugify\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.translation import ugettext_lazy as _\nfrom modelcluster.fields import ParentalKey\nfrom user_agents import parse\nfrom wagtail.wagtailadmin.edit_handlers import (\n FieldPanel, FieldRowPanel, PageChooserPanel)\n\n\n@python_2_unicode_compatible\nclass AbstractBaseRule(models.Model):\n \"\"\"Base for creating rules to segment users with.\"\"\"\n segment = ParentalKey(\n 'wagtail_personalisation.Segment',\n related_name=\"%(app_label)s_%(class)s_related\",\n related_query_name=\"%(app_label)s_%(class)ss\"\n )\n\n def test_user(self):\n \"\"\"Test if the user matches this rule.\"\"\"\n return True\n\n def __str__(self):\n return _('Abstract segmentation rule')\n\n def encoded_name(self):\n \"\"\"Return a string with a slug for the rule.\"\"\"\n return slugify(self.__str__().lower())\n\n def description(self):\n \"\"\"Return a description explaining the functionality of the rule.\n Used in the segmentation dashboard.\n\n :returns: A dict containing a title and a value\n :rtype: dict\n\n \"\"\"\n description = {\n 'title': _('Abstract segmentation rule'),\n 'value': _(''),\n }\n\n return description\n\n class Meta:\n abstract = True\n\n\n@python_2_unicode_compatible\nclass TimeRule(AbstractBaseRule):\n \"\"\"Time rule to segment users based on a start and end time.\n\n Matches when the time a request is made falls between the\n set start time and end time.\n\n \"\"\"\n start_time = models.TimeField(_(\"Starting time\"))\n end_time = models.TimeField(_(\"Ending time\"))\n\n panels = [\n FieldRowPanel([\n FieldPanel('start_time'),\n FieldPanel('end_time'),\n ]),\n ]\n\n def __init__(self, *args, **kwargs):\n super(TimeRule, self).__init__(*args, **kwargs)\n\n def test_user(self, request=None):\n current_time = datetime.now().time()\n starting_time = self.start_time\n ending_time = self.end_time\n\n return starting_time <= current_time <= ending_time\n\n def __str__(self):\n return _('Time Rule')\n\n def description(self):\n description = {\n 'title': _('These users visit between'),\n 'value': _('{} and {}').format(\n self.start_time.strftime(\"%H:%M\"),\n self.end_time.strftime(\"%H:%M\")\n ),\n }\n\n return description\n\n\n@python_2_unicode_compatible\nclass DayRule(AbstractBaseRule):\n \"\"\"Day rule to segment users based on the day(s) of a visit.\n\n Matches when the day a request is made matches with the days\n set in the rule.\n\n \"\"\"\n mon = models.BooleanField(_(\"Monday\"), default=False)\n tue = models.BooleanField(_(\"Tuesday\"), default=False)\n wed = models.BooleanField(_(\"Wednesday\"), default=False)\n thu = models.BooleanField(_(\"Thursday\"), default=False)\n fri = models.BooleanField(_(\"Friday\"), default=False)\n sat = models.BooleanField(_(\"Saturday\"), default=False)\n sun = models.BooleanField(_(\"Sunday\"), default=False)\n\n panels = [\n FieldPanel('mon'),\n FieldPanel('tue'),\n FieldPanel('wed'),\n FieldPanel('thu'),\n FieldPanel('fri'),\n FieldPanel('sat'),\n FieldPanel('sun'),\n ]\n\n def __init__(self, *args, **kwargs):\n super(DayRule, self).__init__(*args, **kwargs)\n\n def test_user(self, request=None):\n current_day = datetime.today().weekday()\n\n days = [self.mon, self.tue, self.wed, self.thu,\n self.fri, self.sat, self.sun]\n\n return days[current_day]\n\n def __str__(self):\n return _('Day Rule')\n\n def description(self):\n days = {\n 'mon': self.mon, 'tue': self.tue, 'wed': self.wed,\n 'thu': self.thu, 'fri': self.fri, 'sat': self.sat,\n 'sun': self.sun\n }\n\n chosen_days = []\n\n for key, value in days.items():\n if days[key]:\n chosen_days.append(key)\n\n description = {\n 'title': _('These users visit on'),\n 'value': _('{}').format(\", \".join([f\"{day}\" for day in chosen_days]).title()),\n }\n\n return description\n\n\n@python_2_unicode_compatible\nclass ReferralRule(AbstractBaseRule):\n \"\"\"Referral rule to segment users based on a regex test.\n\n Matches when the referral header in a request matches with\n the set regex test.\n\n \"\"\"\n regex_string = models.TextField(\n _(\"Regex string to match the referer with\"))\n\n panels = [\n FieldPanel('regex_string'),\n ]\n\n def __init__(self, *args, **kwargs):\n super(ReferralRule, self).__init__(*args, **kwargs)\n\n def test_user(self, request):\n pattern = re.compile(self.regex_string)\n\n if 'HTTP_REFERER' in request.META:\n referer = request.META['HTTP_REFERER']\n if pattern.search(referer):\n return True\n return False\n\n def __str__(self):\n return _('Referral Rule')\n\n def description(self):\n description = {\n 'title': _('These visits originate from'),\n 'value': _('{}').format(\n self.regex_string\n ),\n 'code': True\n }\n\n return description\n\n\n@python_2_unicode_compatible\nclass VisitCountRule(AbstractBaseRule):\n \"\"\"Visit count rule to segment users based on amount of visits to a\n specified page.\n\n Matches when the operator and count validate True\n when visiting the set page.\n\n \"\"\"\n OPERATOR_CHOICES = (\n ('more_than', _(\"More than\")),\n ('less_than', _(\"Less than\")),\n ('equal_to', _(\"Equal to\")),\n )\n operator = models.CharField(max_length=20,\n choices=OPERATOR_CHOICES, default=\"more_than\")\n count = models.PositiveSmallIntegerField(default=0, null=True)\n counted_page = models.ForeignKey(\n 'wagtailcore.Page',\n null=False,\n blank=False,\n on_delete=models.CASCADE,\n related_name='+',\n )\n\n panels = [\n PageChooserPanel('counted_page'),\n FieldRowPanel([\n FieldPanel('operator'),\n FieldPanel('count'),\n ]),\n ]\n\n def __init__(self, *args, **kwargs):\n super(VisitCountRule, self).__init__(*args, **kwargs)\n\n def test_user(self, request):\n operator = self.operator\n segment_count = self.count\n\n def get_visit_count(request):\n \"\"\"Search through the request sessions to get the page visit count\n corresponding to the request.\n\n :param request: The http request\n :type request: django.http.HttpRequest\n :returns: A number indicating the amount of visits\n to the requested page\n :rtype: int\n\n \"\"\"\n for page in request.session['visit_count']:\n if page['path'] == request.path:\n return page['count']\n\n visit_count = get_visit_count(request)\n\n if visit_count and operator == \"more_than\":\n if visit_count > segment_count:\n return True\n elif visit_count and operator == \"less_than\":\n if visit_count < segment_count:\n return True\n elif visit_count and operator == \"equal_to\":\n if visit_count == segment_count:\n return True\n return False\n\n def __str__(self):\n return _('Visit count Rule')\n\n def description(self):\n description = {\n 'title': _('These users visited {}').format(\n self.counted_page\n ),\n 'value': _('{} {} times').format(\n self.get_operator_display(),\n self.count\n ),\n }\n\n return description\n\n\n@python_2_unicode_compatible\nclass QueryRule(AbstractBaseRule):\n \"\"\"Query rule to segment users based on matching queries.\n\n Matches when both the set parameter and value match with one\n present in the request query.\n\n \"\"\"\n parameter = models.SlugField(_(\"The query parameter to search for\"),\n max_length=20)\n value = models.SlugField(_(\"The value of the parameter to match\"),\n max_length=20)\n\n panels = [\n FieldPanel('parameter'),\n FieldPanel('value'),\n ]\n\n def __init__(self, *args, **kwargs):\n super(QueryRule, self).__init__(*args, **kwargs)\n\n def test_user(self, request):\n parameter = self.parameter\n value = self.value\n\n req_value = request.GET.get(parameter, '')\n if req_value == value:\n return True\n return False\n\n def __str__(self):\n return _('Query Rule')\n\n def description(self):\n description = {\n 'title': _('These users used a url with the query'),\n 'value': _('?{}={}').format(\n self.parameter,\n self.value\n ),\n 'code': True\n }\n\n return description\n\n\n@python_2_unicode_compatible\nclass DeviceRule(AbstractBaseRule):\n \"\"\"Device rule to segment users based on matching devices.\n\n Matches when the set device type matches with the one present\n in the request user agent headers.\n\n \"\"\"\n mobile = models.BooleanField(_(\"Mobile phone\"), default=False)\n tablet = models.BooleanField(_(\"Tablet\"), default=False)\n desktop = models.BooleanField(_(\"Desktop\"), default=False)\n\n panels = [\n FieldPanel('mobile'),\n FieldPanel('tablet'),\n FieldPanel('desktop'),\n ]\n\n def __init__(self, *args, **kwargs):\n super(DeviceRule, self).__init__(*args, **kwargs)\n\n def test_user(self, request=None):\n ua_header = request.META['HTTP_USER_AGENT']\n user_agent = parse(ua_header)\n\n if user_agent.is_mobile:\n return self.mobile\n elif user_agent.is_tablet:\n return self.tablet\n elif user_agent.is_pc:\n return self.desktop\n else:\n return False\n\n def __str__(self):\n return _('Device Rule')\n\n\n@python_2_unicode_compatible\nclass UserIsLoggedInRule(AbstractBaseRule):\n \"\"\"User is logged in rule to segment users based on their authentication\n status.\n\n Matches when the user is authenticated.\n\n \"\"\"\n is_logged_in = models.BooleanField(default=False)\n\n panels = [\n FieldPanel('is_logged_in'),\n ]\n\n def __init__(self, *args, **kwargs):\n super(UserIsLoggedInRule, self).__init__(*args, **kwargs)\n\n def test_user(self, request=None):\n return request.user.is_authenticated() == self.is_logged_in\n\n def __str__(self):\n return _('Logged In Rule')\n\n def description(self):\n status = _('Logged in')\n if self.is_logged_in is False:\n status = _('Not logged in')\n\n description = {\n 'title': _('These visitors are'),\n 'value': _('{}').format(\n status\n ),\n }\n\n return description\n","sub_path":"src/wagtail_personalisation/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":11237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"212363582","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\"\"\"\nAWS S3 Uploader Script\n======================\nModified: 2021-02\n\nThis script uploads files to AWS S3.\n\"\"\"\nimport sys\nimport getopt\nimport os\nimport logging\nimport boto3\n\ndef main(argv):\n target_file = ''\n obj = ''\n bucket = ''\n try:\n opts, args = getopt.getopt(argv,\"hi:o:b:\",[\"input=\",\"output=\",\"bucket=\"])\n except getopt.GetoptError:\n logging.exception(\"test.py -i -o -b \")\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n logging.info(\"test.py -i -o -b \")\n sys.exit()\n elif opt in (\"-i\", \"--input\"):\n target_file = arg\n elif opt in (\"-o\", \"--output\"):\n obj = arg\n elif opt in (\"-b\", \"--bucket\"):\n bucket = arg\n\n logging.info(\"Input file: %s\", target_file)\n logging.info(\"Output file: %s\", obj)\n logging.info(\"Bucket: %s\", bucket)\n\n s3 = boto3.client(\n \"s3\",\n aws_access_key_id=os.environ['ACCESS_ID'],\n aws_secret_access_key=os.environ['ACCESS_KEY']\n )\n\n with open(target_file, \"rb\") as f:\n s3.upload_fileobj(f, bucket, obj)\n\n logging.info(\"S3 upload complete.\")\n\nif __name__ == \"__main__\":\n # bind logging to config file\n logging.basicConfig(\n level=logging.DEBUG,\n format=\"%(asctime)s %(levelname)s %(threadName)s %(name)s %(message)s\"\n )\n logging.info(\"S3 uploader script\")\n logging.info(\"------------------\")\n main(sys.argv[1:])","sub_path":"docker/s3_push.py","file_name":"s3_push.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"13752215","text":"from avocado.models import DataView\nfrom cStringIO import StringIO\n\n\nclass BaseExporter(object):\n \"Base class for all exporters\"\n file_extension = 'txt'\n content_type = 'text/plain'\n preferred_formats = []\n\n def __init__(self, concepts):\n if isinstance(concepts, DataView):\n node = concepts.parse()\n concepts = node.get_concepts_for_select()\n\n self.params = []\n self.row_length = 0\n self.concepts = concepts\n\n for concept in concepts:\n length = concept.concept_fields.count()\n self.row_length += length\n self.params.append((concept.format, length))\n\n def get_file_obj(self, name=None):\n if name is None:\n return StringIO()\n if isinstance(name, basestring):\n return open(name, 'w+')\n return name\n\n def _format_row(self, row):\n for formatter, length in self.params:\n values, row = row[:length], row[length:]\n yield formatter(values, self.preferred_formats)\n\n def read(self, iterable, force_distinct=True, *args, **kwargs):\n \"\"\"Takes an iterable that produces rows to be formatted.\n\n If `force_distinct` is true, rows will be filtered based on the slice\n of the row that is *up* for to be formatted. Note, this assumes the\n rows are ordered.\n \"\"\"\n last_row = None\n for row in iterable:\n _row = row[:self.row_length]\n if force_distinct and _row == last_row:\n continue\n last_row = _row\n yield self._format_row(_row)\n\n def write(self, iterable, *args, **kwargs):\n raise NotImplemented\n","sub_path":"avocado/export/_base.py","file_name":"_base.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"407183730","text":"# =========================================================================\n# Copyright 2012-present Yunify, Inc.\n# -------------------------------------------------------------------------\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this work except in compliance with the License.\n# You may obtain a copy of the License in the LICENSE file, or at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =========================================================================\nfrom qingcloud.cli.iaas_client.actions.base import BaseAction\n\n\nclass CreateUserGroupsAction(BaseAction):\n action = 'CreateUserGroups'\n command = 'create-user-groups'\n usage = '%(prog)s [-n ...] [-f ]'\n\n @classmethod\n def add_ext_arguments(cls, parser):\n parser.add_argument(\"-n\", \"--user-group-name\", dest=\"user_group_name\",\n action=\"store\", type=str, default=None,\n help=\"the name of user groups.\")\n\n parser.add_argument(\"-d\", \"--description\", dest=\"description\",\n action=\"store\", type=str, default=None,\n help=\"the description of user groups.\")\n\n parser.add_argument(\"-c\", \"--count\", dest=\"count\",\n action=\"store\", type=int, default=1,\n help=\"the number of user groups created at one time,defaults 1.\")\n\n @classmethod\n def build_directive(cls, options):\n directive = {\n \"user_group_name\": options.user_group_name,\n \"description\": options.description,\n \"count\": options.count,\n }\n\n return directive\n","sub_path":"qingcloud/cli/iaas_client/actions/collaboration/create_user_groups.py","file_name":"create_user_groups.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"259385349","text":"# binance_commons.py\nimport calendar\nfrom datetime import datetime\nfrom binance_commons import go\n\n\ndef main(event, context):\n now = datetime.utcnow()\n unixtime = calendar.timegm(now.utctimetuple())\n # (unixtime - num hours * sixty minutes * sixty seconds) * 1000 ms\n since = (unixtime - 24 * 60 * 60) * 1000 # UTC timestamp in milliseconds\n go('1d', since)\n\n\nif __name__ == \"__main__\":\n main('', '')","sub_path":"binance_1d.py","file_name":"binance_1d.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"430128938","text":"import os\nfrom time import sleep\nfrom multiprocessing import Process, Pipe\ndef ponger(p,s):\n count = 0\n while count < 100:\n msg = p.recv()\n print (\"Process {0} got message: {1}\".format(os.getpid(),msg))\n sleep(1)\n p.send(s)\n count+=1\n\nif __name__ == \"__main__\":\n parent,child = Pipe()\n proc = Process(target = ponger,args=(child,\"ping\"))\n proc.start()\n parent.send(\"pong\")\n ponger(parent,\"pong\")\n proc.join()\n","sub_path":"Python_For_Pentesters/Module2/proc.py","file_name":"proc.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"192755362","text":"import time # importa el modulo time\nimport limpiador as l # importa el modulo limpiador para limpiar la consola\n\n# se inicializa lista vacia para almacenar los valores ingresados por usuario\nlistado_de_valores = []\n\n\n# funcion que pedira el valor al usuario\ndef pedir_valor():\n valor = 0 # se inicializa variable valor en 0\n while True: # sentencia se ejecuta hasta que se produzca un break\n try: # se intenta capturar un numero en la variable valor\n valor = int(input('Ingrese un valor entre 0 y 999.999: '))\n# si se ingresa otro tipo de dato distinto a int enviara mensaje de error y volvera a iterar el while\n except Exception:\n print('\\nEl valor ingresado no es valido\\n')\n time.sleep(1)\n l.clear()\n continue\n if valor < 1000000: # si el valor ingresado es menor a 1.000.000 saldra del bucle con break\n break\n else: # si el valor es mayor a 1.000.000 dara mensaje de error y volvera a iterar\n print('\\nEl valor ingresado no es valido\\n')\n time.sleep(1) # esperara 1 segundo y limpiara la consola\n l.clear()\n# cuando salga del bucle el valor se agregara a listado_de_valores para ser impreso al\n# final de la ejecucion del programa\n listado_de_valores.append(valor)\n valor_str = str(valor) # el valor ingresado se pasa de int a str\n# ya con valor str se pasa a una lista que contiene sus elementos por separado\n# ejemplo: '13456' = ['1','3','4','5','6']\n lista = list(valor_str)\n while len(lista) < 6: # en el caso que el valor ingresado tenga un largo de elementos menor a 6\n # se agreagara una posicion al inicio con el valor '0'\n lista[-100:-50] = ['0']\n return lista\n\n\n# metodo que convierte los elementos igresados clave:valor en una lista\ndef diccionario(**kwargs):\n for cla, val in kwargs.items():\n # imprimira los elementos uno por uno con el siguiente formato:\n print(cla, ':', val, end=' ')\n return kwargs # clave:valor clave: valor etc...\n\n\n# funcion que imprime abaco en pantalla\ndef pintar_abaco():\n a1 = [' +-+ ', ' | | ', ' XXXXX '] # valores de print\n b1 = a1 # cada uno de los siguientes elementos tendra el mismo valor que a1\n c1 = a1\n d1 = a1\n e1 = a1\n f1 = a1\n # valores sera una lista con los elementos que entrega la funcion pedir valores\n valores = pedir_valor()\n print() # que retorna la lista creada en base al valor ingresado por usuario\n # imprime la fila superior de los 6 abacos\n print(a1[0], b1[0], c1[0], d1[0], e1[0], f1[0])\n# for con un contador en reversa para ir pintando cada nivel de cada abaco\n for i in [9, 8, 7, 6, 5, 4, 3, 2, 1]:\n # en cada uno de los siguientes if y else los valores de a2,b2,c2,d2,e2 y f2\n # se pìntaran de acuerdo al nivel que este iterando i hasta completar las 9 iteraciones\n if int(valores[0]) < i: # ejemplo si en la ieracion 9 a2 = 1 imprime | |\n a2 = 1 # en caso contrario si vale 2 imprime XXXXX\n else:\n a2 = 2\n if int(valores[1]) < i:\n b2 = 1\n else:\n b2 = 2\n if int(valores[2]) < i:\n c2 = 1\n else:\n c2 = 2\n if int(valores[3]) < i:\n d2 = 1\n else:\n d2 = 2\n if int(valores[4]) < i:\n e2 = 1\n else:\n e2 = 2\n if int(valores[5]) < i:\n f2 = 1\n else:\n f2 = 2\n# en cada iteracion de 9 a 1 completara una linea de cada ilera del abaco\n print(a1[a2], b1[b2], c1[c2], d1[d2], e1[e2], f1[f2])\n # imprime la base del abaco con +-+\n print(a1[0], b1[0], c1[0], d1[0], e1[0], f1[0])\n # imprime los valores bajo cada ilera del abaco\n print('100.000 10.000 1.000 100 10 1')\n print() # salto de linea\n# se llama a la funcion diccionario y se le pasan como argumentos los valores de la\n# lista creada con el valor ingresado por usuario, searandolo por unidad, decena, centena etc.\n diccionario(CM=valores[0], DM=valores[1],\n UM=valores[2], C=valores[3], D=valores[4], U=valores[5])\n print()\n\n\n# funcion para iniciar el juego\ndef abaco():\n while True: # se repetira el loop hasta que se produzca un brake\n l.clear() # parte limpiando la consola con la importacion de clear desde script limpiador.py\n pintar_abaco() # llama a funcion pintar abaco\n salir = input( # una vez realzada la primera iteracion del abaco, pregunta si desea continuar\n '\\nPara terminar escriba \"salir\" o presione Enter para continuar: ') # a traves de un input\n# en caso que el usuario escriba la palabra salir la convierte a mayusculas en\n if salir.upper() == 'SALIR': # caso que el usuario active las mayusculas del teclado\n l.clear() # limpiara la consola y enviara un brake para salir del loop\n break\n # en caso que el usuario presione enter o ingrese cualquier otro caracter\n time.sleep(1.5)\n l.clear() # el proograma limpiara la consola luego de 1.5 segundos y comenzara otra iteración\n# una vez que el usuario indique salir se imprimira el siguiente mensaje\n print('Los valores ingresados en el abaco fueron los siguientes: \\n')\n# sentencia for para imprimir cada valor alojado en el listado_de_valores\n for i in listado_de_valores:\n # da formato de . para separar por miles cada valor y lo guarda en item\n item = '{:,}'.format(i).replace(\",\", \".\")\n # imprime el valor con formato guardado en item y le da nuevamente\n print(format(item, '>20'))\n print() # formato pero esta vez para alinear cada item a la derecha\n","sub_path":"M2_Final/funciones.py","file_name":"funciones.py","file_ext":"py","file_size_in_byte":5713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"6074477","text":"import pymysql\n#import MySQLdb\nimport dash\nfrom dash.dependencies import Input, Output, Event\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport plotly.graph_objs as go\nfrom collections import deque\nimport time\nimport _thread\nimport paho.mqtt.client as mqtt\n#import os\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\nimport sqlalchemy\n\nserver = Flask(__name__)\napp = dash.Dash(__name__, server=server)\nserver = app.server\napp.config.supress_callback_exceptions=True\n\nmax_lengthx = 501\nmax_length = 501\nX = deque(maxlen=max_lengthx)\nY = deque(maxlen=max_lengthx)\nY2 = deque(maxlen=max_lengthx)\nX.append(1)\nY.append(1)\nY2.append(1)\n\nserver.config['SQLALCHEMY_DATABASE_URI'] ='mysql://rpi:**coolguys88@reii327-1.cerftscrwkav.us-west-2.rds.amazonaws.com/geyser'\nserver.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(server)\nclass Service(db.Model):\n __tablename__ = 'service'\n id = db.Column('id', db.Integer, primary_key =True)\n time = db.Column('time', db.Text)\n temp = db.Column('temp', db.Text)\n amp = db.Column('amp', db.Text)\n\ndef clamp(n, minn, maxn):\n return max(min(maxn, n), minn)\n#-----------------------------------------------DATABASEPROCESSING---------------------------------------------------\ndef connect_to_cloud():\n global X\n global Y\n global Y2\n while True:\n service = Service.query.order_by(sqlalchemy.desc(Service.id)).limit(500)\n for ex in service:\n X.append(str(ex.time))\n Y.append(str(ex.temp))\n Y2.append(str(ex.amp))\n db.session.commit()\n time.sleep(1)\n\n#-----------------------------------------------DATABASEPROCESSING------------------------------------------------------\n_thread.start_new_thread(connect_to_cloud, ())\ntime.sleep(1)\n\napp.layout =html.Div(\n [\n html.H2(children='Tempreture'), \n dcc.Graph(id='live-graph', animate=True), \n dcc.Interval(\n id='graph-update', \n interval = 1000\n ), \n html.H2(children='Amp'), \n dcc.Graph(id='live-graph1', animate=True), \n dcc.Interval(\n id='graph-update1', \n interval = 1000\n ), \n html.H2(children='Enter a Tempreture'), \n html.Div(dcc.Input(id='input-box', type='text')),\n html.Button('Submit', id='button'),\n html.Div(id='output-container-button',\n children='Enter a value and press submit')\n ]\n)\n \n@app.callback(Output('live-graph', 'figure'), \n events = [Event('graph-update', 'interval')])\n \ndef update_graph():\n global X\n global Y\n\n data = go.Scatter(\n x= list(X), \n y= list(Y), \n name='Scatter', \n mode ='lines+markers'\n )\n \n return {'data':[data], 'layout': go.Layout(xaxis = dict(range=[min(X), max(X)]), \n yaxis = dict(range=[0,80]))}\n\n@app.callback(Output('live-graph1', 'figure'), \n events = [Event('graph-update1', 'interval')])\n \ndef update_graph1():\n global X\n global Y2\n \n data = go.Scatter(\n x= list(X), \n y= list(Y2), \n name='Scatter', \n mode ='lines+markers'\n )\n return {'data':[data], 'layout': go.Layout(xaxis = dict(range=[min(X), max(X)]), \n yaxis = dict(range=[0,40]))}\n\n@app.callback(\n Output('output-container-button', 'children'),\n [Input('button', 'n_clicks')],\n [dash.dependencies.State('input-box', 'value')])\ndef update_output(n_clicks, value):\n global outv \n outv = clamp(int(value), 0, 100)\n mqttc = mqtt.Client()\n mqttc.username_pw_set( \"pnnjtdjo\", \"19x76LL8QvRw\")\n mqttc.connect(\"m23.cloudmqtt.com\",18836,60)\n mqttc.subscribe(\"picontrol\", 0)\n mqttc.publish(\"picontrol\", str(outv))\n mqttc.disconnect()\n return 'The input value was \"{}\"'.format(\n str(outv)\n )\n\nif __name__ == \"__main__\":\n app.run_server(debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"32350882","text":"import os\nimport re\nimport json\nimport requests\n\njson_compile = re.compile('(\\'.*\\')')\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0'\n}\n\n\ndef get_station_code():\n station_code_dict = {}\n\n url = 'https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_version=1.9083'\n response = requests.get(url, headers=headers)\n response.encoding = 'utf-8'\n if response.status_code == 200:\n text = response.text\n text = re.search(json_compile, text).group(1)\n code_list = text.split('|')\n for _1, city, code, _2, _3 in zip(code_list[0::5], code_list[1::5], code_list[2::5],\n code_list[3::5], code_list[4::5]):\n if city not in station_code_dict.keys():\n station_code_dict[city] = code\n\n json_str = json.dumps(station_code_dict, indent=4)\n json_path = os.path.join(os.getcwd(), 'station_code.json')\n with open(json_path, 'w') as json_file:\n json_file.write(json_str)\n\n\nif __name__ == '__main__':\n get_station_code()\n\n","sub_path":"Scrapy/railway/railway/spiders/get_station_code.py","file_name":"get_station_code.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"244523850","text":"from pyrogram import Client, Filters, StopPropagation, InlineKeyboardButton, InlineKeyboardMarkup\n\n\n@Client.on_message(Filters.command([\"start\"]), group=-2)\nasync def start(client, message):\n # return\n joinButton = InlineKeyboardMarkup([\n [InlineKeyboardButton(\"Owner\", url=\"https://t.me/Ola_z_slim_yoda\")],\n [InlineKeyboardButton(\n \"Report Bugs 😊\", url=\"https://t.me/Ola_z_slim_yoda\")]\n ])\n welcomed = f\"Hello {message.from_user.first_name}.\\n/help for More info.\\nCreated by Ola Zona\"\n await message.reply_text(welcomed, reply_markup=joinButton)\n raise StopPropagation\n","sub_path":"plugins/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"548631279","text":"# -*- coding: UTF-8 -*-\n'''\n@author: xuqiang\n'''\n# import numpy as np\n# a = np.zeros((50,1,2,2,3))\n# print(a)\n\nimport tensorflow as tf\nimport numpy as np\nimport tensorlayer\n\n'''\n进行批加载\n'''\n# def generate_data():\n# num = 25\n# label = np.asarray(range(0, num))\n# images = np.random.random([num, 5, 5, 3])\n# print('label size :{}, image size {}'.format(label.shape, images.shape))\n# return label, images\n#\n# def get_batch_data():\n# label, images = generate_data()\n# images = tf.cast(images, tf.float32)\n# label = tf.cast(label, tf.int32)\n# input_queue = tf.train.slice_input_producer([images, label], shuffle=False)\n# image_batch, label_batch = tf.train.batch(input_queue, batch_size=10, num_threads=1, capacity=64)\n# return image_batch, label_batch\n#\n# image_batch, label_batch = get_batch_data()\n# with tf.Session() as sess:\n# coord = tf.train.Coordinator()\n# threads = tf.train.start_queue_runners(sess, coord)\n# i = 0\n# try:\n# while not coord.should_stop():\n# image_batch_v, label_batch_v = sess.run([image_batch, label_batch])\n# i += 1\n# for j in range(10):\n# print(image_batch_v.shape, label_batch_v[j])\n# except tf.errors.OutOfRangeError:\n# print(\"done\")\n# finally:\n# coord.request_stop()\n# coord.join(threads)\n\n\n\n\n'''\n进行文件的读写操作\n'''\nimport csv\n# def write_to_csv(output_path_file_name):\n# a = []\n# dict = {}\n# for i in range(100):\n# a.append(str(i)+\"yes\")\n# dict[str(i)] = str(i)+\"yes\"\n# with open(output_path_file_name,'w',newline='') as file:\n# csv_writer = csv.writer(file)\n# csv_writer.writerow(dict)\n# # for text in enumerate(dict):\n# # csv_writer.writerow(text)\n# if __name__ == \"__main__\":\n# write_to_csv('yes.csv')\n\n\n\"\"\"\nload_sample by the queue\n\"\"\"\nimport tensorflow as tf\nimport cyclegan_datasets\nimport model\nimport matplotlib.pyplot as plt\n\n\n\"\"\"\nload data的操作\n\"\"\"\ndef _load_samples(csv_name, image_type):\n filename_queue = tf.train.string_input_producer(\n [csv_name])\n\n reader = tf.TextLineReader()\n _, csv_filename = reader.read(filename_queue)\n\n record_defaults = [tf.constant([], dtype=tf.string),\n tf.constant([], dtype=tf.string)]\n\n filename_i, filename_j = tf.decode_csv(\n csv_filename, record_defaults=record_defaults)\n\n file_contents_i = tf.read_file(filename_i)\n file_contents_j = tf.read_file(filename_j)\n if image_type == '.jpg':\n image_decoded_A = tf.image.decode_jpeg(\n file_contents_i, channels=model.IMG_CHANNELS)\n image_decoded_B = tf.image.decode_jpeg(\n file_contents_j, channels=model.IMG_CHANNELS)\n elif image_type == '.png':\n image_decoded_A = tf.image.decode_png(\n file_contents_i, channels=model.IMG_CHANNELS, dtype=tf.uint8)\n image_decoded_B = tf.image.decode_png(\n file_contents_j, channels=model.IMG_CHANNELS, dtype=tf.uint8)\n\n return image_decoded_A, image_decoded_B\n\n\ndef load_data(dataset_name, image_size_before_crop,\n do_shuffle=True, do_flipping=False):\n \"\"\"\n\n :param dataset_name: The name of the dataset.\n :param image_size_before_crop: Resize to this size before random cropping.\n :param do_shuffle: Shuffle switch.\n :param do_flipping: Flip switch.\n :return:\n \"\"\"\n print(\"============yes===========\")\n if dataset_name not in cyclegan_datasets.DATASET_TO_SIZES:\n raise ValueError('split name %s was not recognized.'\n % dataset_name)\n\n csv_name = cyclegan_datasets.PATH_TO_CSV[dataset_name]\n #进行数据的加载\n image_i, image_j = _load_samples(\n csv_name, cyclegan_datasets.DATASET_TO_IMAGETYPE[dataset_name])\n inputs = {\n 'image_i': image_i,\n 'image_j': image_j\n }\n\n # Preprocessing:\n #进行图片大小的调整,调整为image_size_before_crop=286大小\n inputs['image_i'] = tf.image.resize_images(\n inputs['image_i'], [image_size_before_crop, image_size_before_crop])\n inputs['image_j'] = tf.image.resize_images(\n inputs['image_j'], [image_size_before_crop, image_size_before_crop])\n\n if do_flipping is True:\n #进行图片的翻转--左右\n inputs['image_i'] = tf.image.random_flip_left_right(inputs['image_i'])\n inputs['image_j'] = tf.image.random_flip_left_right(inputs['image_j'])\n #按特定的大小对调整后的图片进行修剪\n inputs['image_i'] = tf.random_crop(\n inputs['image_i'], [model.IMG_HEIGHT, model.IMG_WIDTH, 3])\n inputs['image_j'] = tf.random_crop(\n inputs['image_j'], [model.IMG_HEIGHT, model.IMG_WIDTH, 3])\n\n inputs['image_i'] = tf.subtract(tf.div(inputs['image_i'], 127.5), 1)\n inputs['image_j'] = tf.subtract(tf.div(inputs['image_j'], 127.5), 1)\n\n inputs['images_i'], inputs['images_j'] = tf.train.batch([inputs['image_i'], inputs['image_j']], 1)\n\n #Batch\n if do_shuffle is True:\n inputs['images_i'], inputs['images_j'] = tf.train.shuffle_batch(\n [inputs['image_i'], inputs['image_j']], 1, 5000, 100)\n else:\n inputs['images_i'], inputs['images_j'] = tf.train.batch(\n [inputs['image_i'], inputs['image_j']], 1)\n #注意:这里的inputs可是有四张图片啊images_i,images_j,image_i,image_j\n #print(inputs['images_j'].eval())\n return inputs\n\nimport layers\nimport matplotlib.pyplot as plt\ndef discriminator_tf(inputdisc, name=\"discriminator\"):\n with tf.variable_scope(name):\n f = 4\n o_c1 = layers.general_conv2d(inputdisc, 64, f, f, 2, 2,0.02, \"SAME\", \"c1\", do_norm=False,relufactor=0.2)\n o_c2 = layers.general_conv2d(o_c1, 64 * 2, f, f, 2, 2,0.02, \"SAME\", \"c2\", relufactor=0.2)\n o_c3 = layers.general_conv2d(o_c2, 64 * 4, f, f, 2, 2,0.02, \"SAME\", \"c3\", relufactor=0.2)\n o_c4 = layers.general_conv2d(o_c3, 64 * 8, f, f, 1, 1, 0.02, \"SAME\", \"c4\", relufactor=0.2)\n o_c5 = layers.general_conv2d(o_c4, 1, f, f, 1, 1, 0.02,\"SAME\", \"c5\", do_norm=False, do_relu=False)\n return o_c5\n\nif __name__ == \"__main__\":\n init = (tf.global_variables_initializer(),\n tf.local_variables_initializer())\n inputs = load_data(\"horse2zebra_train\", 286, do_shuffle=True, do_flipping=False)\n prob = discriminator_tf(inputs['images_j'])\n with tf.Session() as sess:\n sess.run(init)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n inputs = sess.run(inputs)\n # print(\"==========image_i============\")\n # print(inputs['image_i'].shape)\n # print(inputs['image_i'])\n # plt.imshow(inputs['image_i'])\n # plt.show()\n # print(\"==========image_i============\")\n # print(\"==========image_i还原============\")\n # img = sess.run(tf.cast(((inputs['image_i'] + 1) * 127.5), dtype=tf.uint8))\n # print(img)\n # plt.imshow(img)\n # plt.show()\n # print(\"==========image_i还原============\")\n #\n # print(\"==========images_i============\")\n #\n # inputs['images_i'] = np.reshape(inputs['images_i'], (256, 256, 3))\n # print(inputs['images_i'].shape)\n # print(inputs['images_i'])\n # plt.imshow(inputs['images_i'])\n # plt.show()\n # print(\"==========images_i============\")\n # print(\"==========images_i还原============\")\n # img = sess.run(tf.cast(((inputs['images_i'] + 1) * 127.5), dtype=tf.uint8))\n # print(img)\n # plt.imshow(img)\n # plt.show()\n\n print(\"==========images_i还原============\")\n\n # prob = sess.run([prob],feed_dict={inputs['images_j']:inputs['images_j']})\n #feed_dict = {\n # self.input_a:\n # inputs['images_i'],\n print(discriminator_tf(inputs['images_j']))\n\n\n\n\n\n\n\n\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":7959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"567262639","text":"def outer_function(message):\n def inner_function():\n print(message)\n\n return inner_function\n\n\nif __name__ == '__main__':\n closure = outer_function(\"Today you are awesome!\")\n closure()\n\n# example\nimport logging\n\nlogging.basicConfig(filename=\"log_example.log\", level=logging.INFO)\n\n\ndef logger(func):\n def log_func(*args):\n logging.info(\n 'Running \"{}\" with arguments {}'.format(func.__name__, args))\n print(func(*args))\n\n return log_func\n\n\ndef count_words(sentence):\n word_list = sentence.split() # type: list # returns a list of words\n print(word_list)\n return len(word_list)\n\n\nquantity = count_words(\"Universe is leading you\")\nprint(quantity)\n\ncount_logger = logger(count_words)\ncount_logger(\"Become a best version of yourself\")\n\nprint(list({4, 3, 4})) # set to list conversion\n\n# Pluralization of English words (not all cases)\n\nimport re # regular expressions module\n\n\n# first version\n\ndef plural(noun):\n if re.search('[sxz]$', noun):\n return re.sub('$', 'es', noun)\n elif re.search('[^aeioudgkprt]h$', noun):\n return re.sub('$', 'es', noun)\n elif re.search('[^aeiou]y$', noun):\n return re.sub('y$', 'ies', noun)\n else:\n return '{0}s'.format(noun)\n\n\nprint(plural(\"cow\"))\n\n# close look on substitutions\n\nprint(re.search('[abc]', 'Sally'))\nprint(re.sub('[a]$', 's', 'Nika'))\nprint(re.sub('[o]', 'a', 'Moon'))\nprint(re.sub('\\d', '$', '5432'))\nprint(re.sub('s', '$', '100 s'))\nprint(re.sub('dollars', '$', '5 dollars'))\n\nprint(re.search('[^aeiou]y$', 'Sally'))\n\nprint(re.search('[^aeiou]y$', 'Day'))\nprint(re.sub('([^aeiou])y$', r'\\1ies', 'vacancy'))\n\nimport re\n\n\ndef match_sxz(noun):\n return re.search('[sxz]', noun)\n\n\ndef apply_sxz(noun):\n return re.sub('$', 'es', noun)\n\n\ndef match_h(noun):\n return re.search('[^aeioudgkprt]h$', noun)\n\n\ndef apply_h(noun):\n return re.sub('$', 'es', noun)\n\n\ndef match_y(noun):\n return re.search('[^aeiou]y$', noun)\n\n\ndef apply_y(noun):\n return re.sub('y$', 'ies', noun)\n\n\ndef match_default(noun):\n return True\n\n\ndef apply_default(noun):\n return '{0}s'.format(noun)\n\n\n# define a tuple of rules (data structure which is a sequence of pairs of functions)\nrules = ((match_sxz, apply_sxz), (match_h, apply_h),\n (match_y, apply_y), (match_default, apply_default))\n\n\n# second version of plural\n\ndef plural(noun):\n for matches_rule, apply_rule in rules:\n if matches_rule(noun):\n return apply_rule(noun)\n\n\nprint(plural('Corgi'))\n\n\n# third version\n\ndef build_match_and_apply_functions(pattern, search, replace): # builds other functions dynamically\n def matches_rule(word):\n return re.search(pattern, word)\n\n def apply_rule(word):\n return re.sub(search, replace, word)\n\n return (matches_rule, apply_rule)\n\n\n'''\n The constants you defined within those functions \n (pattern within the matches_rule() function, \n and search and replace within the apply_rule() function) \n stay with those functions, even after you return from build_match_and_apply_functions().\n'''\npatterns = \\\n (\n ('[sxz]$', '$', 'es'),\n ('[^aeioudgkprt]h$', '$', 'es'),\n ('(qu|[^aeiou])y$', 'y$', 'ies'),\n ('$', '$', 's') # functionally equivalent to 'match default\"; every string has an end, even an empty strings\n )\nrules = [build_match_and_apply_functions(pattern, search, replace) for (pattern, search, replace) in patterns]\n\nrules = []\nwith open('rules.txt', encoding='utf-8') as pattern_file:\n for line in pattern_file:\n pattern, search, replace = line.split(None, 3)\n rules.append(build_match_and_apply_functions(pattern, search, replace))\n\n'''\nThe with statement creates what’s called a context: when the with block ends, \nPython will automatically close the file, \neven if an exception is raised inside the with block.\n'''\n'''\nThe improvement here is that you’ve completely separated the pluralization rules into an external file,\nso it can be maintained separately from the code that uses it. \nCode is code, data is data, and life is good.'''\n\n'''\nGenerators\n'''\n\n\ndef rules(rules_filename):\n with open(rules_filename, encoding='utf-8') as pattern_file:\n for line in pattern_file:\n pattern, search, replace = line.split(None, 3)\n yield build_match_and_apply_functions(pattern, search, replace)\n\n\ndef plural(noun, rules_filename='rules.txt'):\n for matches, apply in rules(rules_filename):\n if matches(noun):\n return apply(noun)\n raise ValueError(\"No matching rule for {0}\".format(noun))\n\n\nprint(plural(\"Tendency\"))\n\n'''\n It is a special kind of function which generates values one at a time. \n You can think of it as a resumable function. \n Calling it will return a generator that can be used to generate successive values of x.\n'''\n\n\ndef make_counter(x):\n print(\"entering make_counter\")\n while True:\n yield x\n print('incrementing x')\n x = x + 1\n\n\ncounter = make_counter(4)\nprint(counter)\nnext(counter)\nprint(next(counter))\n\n\ndef generator_words(word, letter):\n print(\"entering generator\")\n while len(word) < 20:\n yield word\n count_words('{0} - is new sentence'.format(word))\n word = '{0}{1}'.format(word, letter)\n\n\n'''\nRepeatedly calling next() with the same generator object resumes exactly \nwhere it left off and continues until it hits the next yield statement.\n'''\nword = generator_words(\"hello\", \"m\")\nprint(word)\nnext(word)\nnext(word)\nnext(word) # calls count(words) (if we want to see the result that was returned we have to call print(next(word))\nprint(next(word)) # returns result of yield\n\n\n# All variables, local state, &c. are saved on yield and restored on next().\n\n# Fibonacci generator\ndef fib(max=100):\n print(\"entering generator\")\n a, b = 0, 1\n while a < max:\n yield a\n a, b = b, a + b\n\n\nmaximum = 20\nfib_numbers = fib(maximum)\nprint(fib_numbers)\nfor i in range(maximum):\n print(next(fib_numbers))\n\n","sub_path":"closures.py","file_name":"closures.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"126319880","text":"# Write a program that takes a positive floating-point number as input and outputs an \n# approximation of its square root.\n#First, I must create the function for square root, using newtons method for estimating square roots \n#This was firstly done on a seperate program named 'funtion.py'\n#I will then write to code to allow the user to enter the number and along with output print\n\nnumber = float(input(\"Please enter a positive number: \")) #coding for numer user enters \n\n#How to write code for Newtons method was found using the below link\n#https://medium.com/@sddkal/newton-square-root-method-in-python-270853e9185d\n#Function reading: )\n\ndef sqRt(value, number_iters = 10): #value = number - number_iters is the no of times the value will be itterated\n a = float(value) \n for i in range(number_iters):\n value = 0.5 * (value + a / value)\n return value \n\nprint(\"The square root of {} is approx. {}\".format(number, sqRt(number)))\n","sub_path":"task05_squareroot/squareroot.py","file_name":"squareroot.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"224666331","text":"from django.db import models\n\n# Create your models here.\nfrom apps.customer.models import CustomerInfo\n\n\nclass ShopCategory(models.Model):\n ShopCategoryId = models.AutoField(db_column='ShopCategoryId', primary_key=True, verbose_name='商城品类ID',\n help_text='商城品类ID')\n Category = models.CharField(db_column='Category', max_length=200, verbose_name='商城品类名',\n help_text='商城品类名')\n\n class Meta:\n db_table = 'ShopCategory'\n verbose_name = \"商城品类\"\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.Category\n\n\nclass ShopGood(models.Model):\n ShopGoodId = models.AutoField(db_column='ShopGoodId', primary_key=True, verbose_name='商品ID', help_text='商品ID')\n # ShopCategoryId = models.IntegerField(db_column='ShopCategoryId', verbose_name='商城品类ID',help_text='商城品类ID')\n # Category = models.CharField(db_column='Category', max_length=200, verbose_name='商城品类名',\n # help_text='商城品类名')\n ShopCategory = models.ForeignKey(ShopCategory, db_column='ShopCategory', on_delete=models.CASCADE,\n related_name='ShopGood',help_text='商城品类ID')\n GoodName = models.CharField(db_column='GoodName', max_length=200, verbose_name='商品名',help_text='商品名')\n CoverImage = models.ImageField(db_column='CoverImage', upload_to='shop', max_length=100,\n verbose_name='商品封面图片', help_text='商品封面图片')\n Price = models.IntegerField(db_column='Price',verbose_name='积分值',help_text='积分值')\n PriceCutdown = models.IntegerField(db_column='PriceCutdown',blank=True,null=True,verbose_name='折扣价',\n help_text='折扣价')\n Describe = models.CharField(db_column='Describe', max_length=500,blank=True,null=True , verbose_name='商品描述', help_text='商品描述')\n Details = models.TextField(db_column='Details', max_length=1000,blank=True,null=True, verbose_name='商品详情', help_text='商品详情')\n\n class Meta:\n db_table = 'ShopGood'\n verbose_name = \"商品\"\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.GoodName\n\n\n# 商品规格,如型号等\nclass ShopGood_Enum(models.Model):\n Id = models.AutoField(db_column='ShopGood_Enum_Id', primary_key=True, verbose_name='型号ID', help_text='型号ID')\n Label = models.CharField(db_column='Label',max_length=50,verbose_name='型号标签',help_text='型号标签')\n ShopGood = models.ForeignKey(ShopGood,on_delete=models.CASCADE,related_name='ShopGood_Enum',\n db_column='ShopGoodId',verbose_name='关联商品',help_text='关联商品')\n class Meta:\n db_table = 'ShopGood_Enum'\n verbose_name = '型号'\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return '型号:'+self.Label\n\n# 流程不完整,积分商品兑换了,付款了,需要用户查看该订单,司机是否需要派送该商品\n# 积分的获取从何而来\n\n\nclass ShopCustomer(models.Model):\n CustomerAccountDetailsId = models.AutoField(db_column='CustomerAccountDetailsId',primary_key=True,\n verbose_name='顾客ID', help_text='顾客ID')\n CartGood = models.ManyToManyField(ShopGood, related_name='ShopCustomer', verbose_name='购物车商品',\n help_text='购物车商品', through='ShoppingCart')\n CustomerName = models.CharField(db_column='CustomerName', max_length=100, verbose_name='顾客名字',\n help_text='顾客名字')\n CustomerInfo = models.OneToOneField(CustomerInfo, on_delete=models.CASCADE, related_name='ShopCustomer',\n help_text='顾客信息Id', verbose_name='顾客信息Id')\n IsPaid = models.BooleanField(default=0, verbose_name='是否已支付', help_text='是否已支付')\n IsDel = models.BooleanField(default=0,verbose_name='是否已取消', help_text='是否已取消')\n class Meta:\n db_table = 'ShopCustomer'\n verbose_name = \"顾客\"\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.CustomerAccountDetailsId\n\n\nclass ShoppingCart(models.Model):\n ShoppingCartId = models.AutoField(db_column='ShoppingCartId', primary_key=True, verbose_name='购物车ID',\n help_text='购物车ID')\n ShopGood = models.ForeignKey(ShopGood, on_delete=models.CASCADE, db_column='ShopGood',\n verbose_name='商品', help_text='商品')\n ShopCustomer = models.ForeignKey(ShopCustomer, db_column='ShopCustomer', verbose_name='顾客',\n help_text='顾客')\n GoodNum = models.IntegerField(default=1, db_column='GoodNum', verbose_name='数量', help_text='数量')\n\n class Meta:\n db_table = 'ShoppingCart'\n verbose_name = \"顾客的购物车\"\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.ShoppingCartId\n\n","sub_path":"XJSExpress/apps/shop/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"467131461","text":"'''\nSPOTLESS Package Library: file operations\n\nTo avoid code duplication and errors, increasing speed of module deployment.\n'''\nimport os\n\n\ndef dirIter(folder_name):\n for dirpath, dirnames, filenames in os.walk(folder_name):\n for f in filenames:\n if f[0:2] != \"ex\":\n continue\n yield os.path.join(dirpath, f)\n #for each file in folder & sub folders\n #yield file\n","sub_path":"lib/fileLib.py","file_name":"fileLib.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"515099702","text":"from character import Character\n\ndef saveFile(checkpoint):\n\twith open('game.save', 'w') as file:\n\t\tfile.write(checkpoint)\n\ndef loadSave():\n\twith open('game.save', 'r') as file:\n\t\tfunction = file.read()\n\t\texec(function)\n\ndef characterCreation():\n\tcharacter = Character()\n\tcharacter.level = 1\n\tprint(\"Welcome to the desolate land of Phyrexia. You are a hero that was chosen to rise up against the Phyrexians and defeat the mechanized menace. Before we begin our journey, please answer a few questions...\")\n\twhile True:\n\t\tgender = input(\"Are you male or female? [m/f] \")\n\t\tif gender == 'm':\n\t\t\tcharacter.gender = 'Male'\n\t\telif gender == 'f':\n\t\t\tcharacter.gender = 'Female'\n\t\tcharacter.name = input(\"What is your name? \")\n\t\tcharacter.equipment = ['weapon', 'Leather cap', 'Leather armor']\n\t\tcharacter.inventory = ['Health Potion', 'Mana Potion']\n\t\tjob = input(\"You can be one of four classes. Which of the following fits you best? Warrior [w] / Rogue [r] / Mage [m] / Archer [a] \")\n\t\tif job == 'w':\n\t\t\tcharacter.job = 'Warrior'\n\t\t\tcharacter.changeWeapon('Longsword')\n\t\t\tcharacter.addSkill(\"Power Strike\")\n\t\telif job == 'r':\n\t\t\tcharacter.job = 'Rogue'\n\t\t\tcharacter.changeWeapon('Dagger')\n\t\t\tcharacter.addSkill(\"Steal\")\n\t\t\tcharacter.addSkill(\"Quick Cut\")\n\t\telif job == 'm':\n\t\t\tcharacter.job = 'Mage'\n\t\t\tcharacter.changeWeapon('Wooden Staff')\n\t\t\tcharacter.addSkill(\"Fire\")\n\t\t\tcharacter.addSkill(\"Lightning\")\n\t\t\tcharacter.addSkill(\"Ice\")\n\t\telif job == 'a':\n\t\t\tcharacter.job = 'Archer'\n\t\t\tcharacter.changeWeapon('Longbow')\n\t\t\tcharacter.addSkill(\"Quickdraw\")\n\t\t\tcharacter.addSkill(\"Aim: Torso\")\n\t\tprint('Is the following information okay?\\n')\n\t\tprint('Name: ' + character.name)\n\t\tprint('Gender: ' + character.gender)\n\t\tprint('Class: ' + character.job)\n\t\tchoice = input('\\n[y/n] ')\n\t\tif choice == 'y':\n\t\t\tif character.gender != 'Male' and character.gender != 'Female':\n\t\t\t\tprint(\"Please choose a valid gender choice\\n\")\n\t\t\t\tcontinue\n\t\t\tif character.job != 'Warrior' and character.job != 'Rogue' and character.job != 'Mage' and character.job != 'Archer':\n\t\t\t\tprint(\"Please choose a valid class choice\\n\")\n\t\t\t\tcontinue\n\t\t\tbreak\n\tcharacter.save()\n\ndef runGame():\n\twhile True:\n\t\tprint('Would you like to create a new game or continue from a save file?')\n\t\tchoice = input('[new]/[continue] ')\n\t\tif choice == 'new':\n\t\t\tcharacterCreation()\n\t\t\tprint(\"\\nNow your adventure begins.\")\n\t\t\tsaveFile('beginning()')\n\t\t\tloadSave()\n\t\t\tbreak\n\t\telif choice == 'continue':\n\t\t\tcharacter = Character()\n\t\t\tcharacter.load()\n\t\t\tloadSave()\n\t\t\tbreak\n\ndef beginning():\n\tprint(\"\\nWelcome\\n\")\n\tprint(\"You wake up in a dark cave, illuminated by the torches lining the damp, glistening walls. The pathway splits in two separate directions.\")\n\tchoice = input(\"Go left or right [l/r]: \")\n\tif choice == 'l':\n\t\tprint(\"You chose to go left\")\n\t\tsaveFile('leftPath()')\n\t\tloadSave()\n\tif choice == 'r':\n\t\tprint(\"You chose to go right\")\n\t\tsaveFile('rightPath()')\n\t\tloadSave()\n\ndef leftPath():\n\tprint(\"You went left in the path. This is the left path save file. Hurray! :)\")\n\ndef rightPath():\n\tprint(\"In this life, you went right in the previous path. Goodbye.\")\n\nrunGame()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":3120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"262957348","text":"#2/12/2019\n#network model - this imports data from the 2 CSVs\n\nimport gurobipy as grb\nimport sqlite3\nimport pandas as pd\n\n#import data usually\ndata=pd.read_csv(\"Data.csv\")\nfloordata = pd.read_csv(\"Floors.csv\")\nhours = [835]\n#creating english index for easy reference\nmachines = data.iloc[0:,0].values\ndata=data.set_index('NAME')\nfloors=floordata.iloc[0:,1].values\nfloordata=floordata.set_index('Floor')\n\nprint(machines)\n#make model\nslotsmodel = grb.Model('model name')\nslotsmodel.modelSense = grb.GRB.MAXIMIZE #objective function goal GRB. = constant\nslotsmodel.update() #need to update after each change to model - after constraints, model, and variables\n\n# make variables - use dictionaries - does positivity constraint for you...\nslots = {}\nfor f in floors:\n for slot in machines:\n slots[slot,f] = slotsmodel.addVar(obj = data.loc[slot]['EXPREV']-data.loc[slot]['OCOST'], name = 'Slot(%s,%s)' % (slot,f)) #obj=objective function coefficient for decision variables\nslotsmodel.update() #save variables\n\n#add constraints\nmyConstrs = {}\n\n#floor space:\nfor f in floors:\n cName = 'floorspace_%s' % f\n print(cName)\n myConstrs[cName] = slotsmodel.addConstr(grb.quicksum(slots[slot,f] * data.loc[slot]['AREA'] for slot in machines) <= floordata.loc[f], name=cName)\n\n#hours:\ncName = 'hours'\nmyConstrs[cName] = slotsmodel.addConstr(grb.quicksum(slots[slot,f] * data.loc[slot]['MAINTENANCE'] for slot in machines for f in floors) <= hours[0], name=cName)\n\n#OnHandLimits:\nfor slot in machines:\n cName = 'onhand_%s' % slot\n myConstrs[cName] = slotsmodel.addConstr(grb.quicksum(slots[slot,f] for f in floors) <= data.loc[slot]['HAND'], name=cName)\n\nslotsmodel.update()\nslotsmodel.write('test.lp') #check if constrainst I want, coefficients, indexed properly\n\n\nslotsmodel.optimize()\nslotsmodel.update()\n\n\nif slotsmodel.Status == grb.GRB.OPTIMAL:\n slotsmodel.write('solution.sol') #write the solution to file\n\n #make DB and write output\n conn = sqlite3.connect('Casino.db')\n c = conn.cursor()\n try:\n table_name = 'Casino_Machine_Floor_Count'\n c.execute('''CREATE TABLE %s (\n Machine text,\n Floor text,\n Count text)''' %\n (table_name))\n except:\n c.execute(\"Delete from %s\" % (table_name)) #delete table data if already created\n\n\n for key, value in slots.items():\n if value.x>0:\n insert = list(key) + [value.x]\n c.executemany('insert into %s values (?,?,?)' % (table_name), (insert,))\n conn.commit()\n #print count\n c.execute('select count(*) from %s'% (table_name))\n result = c.fetchone()\n print('Inserted ' + str(result[0])+ ' records into the '+ table_name+ ' table.')\n\n\n\n\n #hw 1 only output the values greater than 0\n # B D KEGS\n # SAV CHR 3 text, datacsv, database csv - single zip file - relative referencing\n","sub_path":"HW03/3-1/3-1-import.py","file_name":"3-1-import.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"285716854","text":"# When I wrote this, only God and I understood what I was doing\n# Now, God only knows :D\n\nfrom selenium import *\nfrom selenium import webdriver\nfrom selenium import selenium\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nimport time\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nimport csv\nimport xlwt\nfrom xlutils.copy import copy\nfrom xlrd import open_workbook\nimport sys\nimport os\n\ntry:\n reload(sys)\n sys.setdefaultencoding('utf8')\nexcept NameError:\n # Python3: sys already set to UTF-8 Encoding\n pass\n\nNEW_XLS = 0 # To write into new file, change to '1'\nTEMP = False # Just a debug variable meant to be removed, It turns off pie-ug pie-pg and courses offered\n\nPAGE_OFFSET = 0\nENTRY_OFFSET = 0\nGLOBAL_OFFSET = 0\nOUTPUT_FILE=os.path.join(os.path.dirname(__file__),\"output\",'data_careers_1_100.xls')\nCHECKPOINT = open('checkpoint.dat', 'r+')\nHEADER = ['Name', 'Type', 'Phone1', 'Phone2', 'Phone3', 'Phone4', 'Phone5', 'Logo URL', 'Also Known As', 'Location', 'Estd.', 'Website', 'Mail', 'Ownership', 'Approved By', 'Affiliated to', 'Link-Affiliated to', 'Facilities', 'State Rank', 'Facebook',\n 'Twitter', 'Youtube', 'Wikipedia', 'Total Faculty', 'Ratio-Student:Faculty', 'UG Pie Chart', 'PG Pie Chart', 'Notable Alumni', 'Top Following States', 'Admission Mode', 'Gender Ratio', 'Avg. Age', 'Geometric Insights',\n 'Images', 'Videos', 'Total Courses', 'Total UG', 'Total PG', 'Courses']\n\n\ndef check_exists_by_xpath(xpath):\n try:\n driver.find_element_by_xpath(xpath)\n except NoSuchElementException:\n return False\n return True\n\n\ndef safe_get_xpath(xpath, attrib=None, parent=None):\n try:\n if parent:\n element = parent.find_element_by_xpath(xpath)\n else:\n element = driver.find_element_by_xpath(xpath)\n except NoSuchElementException:\n print(xpath, \"was not found!!\")\n return \"\"\n if attrib:\n return element.get_attribute(attrib)\n return element.text\n\n\ndef newCheckPoint(pages, entry_no):\n global GLOBAL_OFFSET\n global CHECKPOINT\n CHECKPOINT.seek(0)\n CHECKPOINT.truncate()\n CHECKPOINT.write(str(pages) + \"\\n\")\n CHECKPOINT.write(str(entry_no) + \"\\n\")\n CHECKPOINT.write(str(GLOBAL_OFFSET) + \"\\n\")\n GLOBAL_OFFSET += 1\n CHECKPOINT.flush()\n\n\nif NEW_XLS:\n\n wb = xlwt.Workbook()\n ws = wb.add_sheet('Career Data')\n ulstyle = xlwt.easyxf('font: underline single')\n for col, head in enumerate(HEADER):\n ws.write(0, col, head, ulstyle)\n ws.col(col).width = min(len(head) * 380, 6000)\nelse:\n PAGE_OFFSET, ENTRY_OFFSET, GLOBAL_OFFSET = map(int, CHECKPOINT.readlines())\n\n wb = copy(open_workbook(OUTPUT_FILE))\n ws = wb.get_sheet(0)\n print(\"Found\", GLOBAL_OFFSET, \"entries completed\")\n print(\"Resuming from page \", PAGE_OFFSET, \"and entry no.:\", ENTRY_OFFSET)\n\n\nif len(sys.argv) > 1:\n init_page = sys.argv[0] # INITIAL PAGE NO.\n count_coll = sys.argv[1] # FINAL PAGE NO. - EACH PAGE 10 College\n\nflag = True # indicates zero loops\nprint('Launch...')\ndriver = webdriver.Firefox()\nprint('Navigate.')\n\ncount_coll = PAGE_OFFSET\nwhile count_coll <= 10:\n\n url = 'http://www.engineering.careers360.com/colleges/list-of-engineering-colleges-in-India?page=' + \\\n str(count_coll)\n\n #driver = webdriver.PhantomJS()\n #driver = webdriver.Remote(desired_capabilities=webdriver.DesiredCapabilities.FIREFOX, command_executor='http://127.0.0.1:4444/wd/hub')\n\n driver.get(url)\n print('Wait new URL: ....', url[40:])\n if flag:\n time.sleep(6) # DDOS protection requires 5 sec. sleep for first get\n flag = False\n # time.sleep(6)############################IF CLOUDFLARE PROBLEM or use\n # By. dynamic ele\n\n colls_url = driver.find_elements_by_xpath(\n \"//div[@class='content-box f-right']\")\n\n for entry_no, coll in enumerate(colls_url[ENTRY_OFFSET:]):\n\n newCheckPoint(count_coll, ENTRY_OFFSET + entry_no)\n\n # Create new Checkpoint, Processing resumes from this offset, if the\n # program breaks\n name = ''\n coll_url = ''\n typeofcoll = ''\n phones = ''\n\n title = coll.find_element_by_xpath(\".//div[@class='title']/a\")\n name = title.text\n print(name)\n\n coll_url = title.get_attribute('href')\n #coll_url = 'http://www.engineering.careers360.com/cmr-institute-technology-hyderabad'\n print(coll_url)\n\n typeofcoll = coll.find_element_by_xpath(\n \".//div[@class='clg-type clgAtt']\").text\n if 'Type: ' in typeofcoll:\n typeofcoll = typeofcoll.replace('Type: ', '')\n else:\n typeofcoll = ''\n print(typeofcoll)\n\n phones_nos = ''\n phone1 = ''\n phone2 = ''\n phone3 = ''\n phone4 = ''\n phone5 = ''\n\n phones = coll.find_element_by_xpath(\n \".//div[@class='clg-contact clgAtt']\").text.replace('Contact: ', '') + \",,,,,\"\n phone = phones.split(',')[:5]\n print(phones)\n\n '''url+='/branches'\n #url.split('/')[3] = ''\n #''.join(url)\n print(url)\n print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')\n driver.get(url)'''\n\n driver.find_element_by_tag_name(\"body\").send_keys(Keys.CONTROL + 't')\n #driver = webdriver.Firefox()\n driver.get(coll_url)\n # time.sleep(6)\n\n also_known_as = safe_get_xpath(\"//div[@class='infoQuestion']/span\")\n print('Also Known as : ' + also_known_as)\n\n logo = ''\n logo = driver.find_element_by_xpath(\n \"/html/body/div/div/div/div[2]/div/div/div/div/img\").get_attribute('src')\n print('logo : ' + logo)\n\n info = driver.find_elements_by_xpath(\n \"//ul[@class='clg-info']/li\") + ['', '', '', '', '', '', '', '']\n\n location = ''\n location = info[0].text\n print('location: ' + location)\n\n estd = safe_get_xpath(\".//span\", parent=info[1])\n print('Estd:', estd)\n\n website = ''\n website = info[2].text\n print('Website:', website)\n\n mail = safe_get_xpath(\".//span\", parent=info[3])\n print('Email:', mail)\n\n ownership = safe_get_xpath(\".//span\", parent=info[5])\n print('Ownership:', ownership)\n\n approved_by = safe_get_xpath(\".//span\", parent=info[6])\n print(\"Approved by:\", approved_by)\n\n affiliated_to_text = safe_get_xpath(\".//a\", parent=info[7])\n print(\"Affiliated to:\", affiliated_to_text)\n\n affiliated_to_link = safe_get_xpath(\n \".//a\", attrib='href', parent=info[7])\n print(\"Affilited to Link:\", affiliated_to_link)\n\n facilities = '< '\n for x in driver.find_elements_by_xpath(\"//div[@class='facilitylist']//li\"):\n y = x.get_attribute('innerHTML')\n facilities += y[y.find(''):].replace('', ' # ')\n facilities += ' >'\n print('Facilities:', facilities)\n\n #stu_to_fact = driver.find_element_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div[2]/div/div/div/div/span\")\n # print(stu_to_fact)##########################################format\n\n state_rank = ''\n\n state_rank = safe_get_xpath(\n \"/html/body/div/div/div/div[3]/div/div/div/div[3]/div/div/div/span\")\n if 'A' not in state_rank:\n state_rank = ''\n print('College Grade:', state_rank) # PG KYUN\n\n #no_courses = driver.find_element_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div[4]/div/h4\").text\n #no_courses = int(no_courses[no_courses.find(':'):].replace(':',''))\n # print(no_courses)\n\n facebook = driver.find_element_by_xpath(\n \"/html/body/div/div/div/div[2]/div/div/div/div[2]/ul/li/a\").get_attribute('href')\n if 'javascript' in str(facebook):\n facebook = ''\n print(facebook)\n\n twitter = driver.find_element_by_xpath(\n '/html/body/div/div/div/div[2]/div/div/div/div[2]/ul/li[2]/a').get_attribute('href')\n if 'javascript' in str(twitter):\n twitter = ''\n print(twitter)\n\n youtube = driver.find_element_by_xpath(\n '/html/body/div/div/div/div[2]/div/div/div/div[2]/ul/li[3]/a').get_attribute('href')\n if 'javascript' in str(youtube):\n youtube = ''\n print(youtube)\n\n wiki = driver.find_element_by_xpath(\n '/html/body/div/div/div/div[2]/div/div/div/div[2]/ul/li[4]/a').get_attribute('href')\n if 'javascript' in str(wiki):\n wiki = ''\n print(wiki)\n\n # faculty\n print('Faculty : ')\n tot_faculty = safe_get_xpath(\n \"//div[@id='faculty']//h4[@class='blockSubHeading']\")\n tot_faculty = tot_faculty[\n tot_faculty.find(':'):].replace(':', '').lstrip()\n print('Total Factuly :', tot_faculty)\n\n stu_to_fact = ''\n\n stu_to_fact = safe_get_xpath(\"//div[@id='faculty']//div[@class='countBlockRayco']/span\",\n attrib='innerHTML').replace(':', ' : ')\n print('Factuly to Stud Ratio : ' + stu_to_fact) # format\n # print(stu_to_fact.text)\n\n # ug_PIE\n pie_color_li = []\n pie_name_li = []\n pie_intake_li = []\n\n if check_exists_by_xpath(\"//div[@id='chart_div_ug']\") and TEMP:\n\n pie_temp = driver.find_element_by_xpath(\n \"//div[@id='chart_div_ug']/div/div/div\")\n #/html/body/div/div/div/div[3]/div/div/div/div[4]/div/div[2]/div/div\n #/html/body/div/div/div/div[3]/div/div/div/div[4]/div/div[2]/div/div/div/div/div/svg/g/g\n #/html/body/div/div/div/div[3]/div/div/div/div[4]/div/div[2]/div/div/div/div/div/svg/g/g/circle\n block_li = pie_temp.find_elements_by_xpath(\n \".//*[local-name() = 'svg']/*[local-name() = 'g']/*[local-name() = 'g']\")\n for y in block_li:\n # print(y.get_attribute('outerHTML'))\n # print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$')\n pie_color_li.append(y.find_element_by_xpath(\n \".//*[local-name() = 'circle']\").get_attribute('fill'))\n k = y.find_elements_by_xpath(\".//*[local-name() = 'text']\")\n k1 = ''\n for x in k:\n k1 += x.text + ' '\n pie_name_li.append(k1)\n pie_intake_li.append('')\n\n print(pie_name_li)\n print(pie_color_li)\n temp_li = pie_temp.find_elements_by_xpath(\n \".//*[local-name() = 'svg']/*[local-name() = 'g']\")\n for x in range(1, len(temp_li) - 1):\n # print(pie_intake_li)\n try:\n pie_intake_li[pie_color_li.index(temp_li[x].find_element_by_xpath(\n \".//*[local-name() = 'path']\").get_attribute('fill'))] = temp_li[x].find_element_by_xpath(\".//*[local-name() = 'text']\").text\n except NoSuchElementException:\n continue\n\n # print(pie_color_li)\n print(pie_name_li)\n print(pie_intake_li)\n\n str_ug_pie = ''\n for x in range(len(pie_name_li)):\n str_ug_pie += '< ' + pie_name_li[x] + \\\n ' : ' + pie_intake_li[x] + ' >'\n\n # pg_PIE\n pie2_color_li = []\n pie2_name_li = []\n pie2_intake_li = []\n\n if check_exists_by_xpath(\"//div[@id='chart_div_pg']\") and TEMP:\n pie_temp = driver.find_element_by_xpath(\n \"//div[@id='chart_div_pg']/div/div/div\")\n #/html/body/div/div/div/div[3]/div/div/div/div[4]/div/div[2]/div/div\n #/html/body/div/div/div/div[3]/div/div/div/div[4]/div/div[2]/div/div/div/div/div/svg/g/g\n #/html/body/div/div/div/div[3]/div/div/div/div[4]/div/div[2]/div/div/div/div/div/svg/g/g/circle\n block_li = pie_temp.find_elements_by_xpath(\n \".//*[local-name() = 'svg']/*[local-name() = 'g']/*[local-name() = 'g']\")\n for y in block_li:\n # print(y.get_attribute('outerHTML'))\n # print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$')\n pie2_color_li.append(y.find_element_by_xpath(\n \".//*[local-name() = 'circle']\").get_attribute('fill'))\n k = y.find_elements_by_xpath(\".//*[local-name() = 'text']\")\n k1 = ''\n for x in k:\n k1 += x.text + ' '\n pie2_name_li.append(k1)\n pie2_intake_li.append('')\n\n temp2_li = pie_temp.find_elements_by_xpath(\n \".//*[local-name() = 'svg']/*[local-name() = 'g']\")\n for x in range(1, len(temp2_li) - 1):\n try:\n pie2_intake_li[pie2_color_li.index(temp2_li[x].find_element_by_xpath(\n \".//*[local-name() = 'path']\").get_attribute('fill'))] = temp2_li[x].find_element_by_xpath(\".//*[local-name() = 'text']\").text\n except NoSuchElementException:\n continue\n\n # print(pie2_color_li)\n print(pie2_name_li)\n print(pie2_intake_li)\n\n str_pg_pie = ''\n for x in range(len(pie2_name_li)):\n str_pg_pie += '< ' + \\\n pie2_name_li[x] + ' : ' + pie2_intake_li[x] + ' >'\n\n # Notable alumni\n str_alumni = ''\n if check_exists_by_xpath(\"//div[@class='custom-slider-alumni']\"):\n alumni_temp = driver.find_element_by_xpath(\n \"//div[@class='custom-slider-alumni']\")\n all_alumni = alumni_temp.find_elements_by_xpath(\n \".//div[@class='sliderPadding']\")\n for x in all_alumni:\n try:\n # print(x.get_attribute('outerHTML'))\n alumni_img = x.find_element_by_xpath(\n \".//div[@class='alumni_img']/img\").get_attribute('src')\n # print(alumni_img)\n alumni_name = x.find_element_by_xpath(\n \".//div[@class='alumni_Info']/div[1]\").text\n # print(alumni_name)\n alumni_designation = x.find_element_by_xpath(\n \".//div[@class='alumni_Info']/div[2]\").text\n # print(alumni_designation)\n alumni_company = x.find_element_by_xpath(\n \".//div[@class='alumni_Info']/div[3]\").text\n # print(alumni_company)\n alumni_linked_in = x.find_element_by_xpath(\n \".//div[@id='social-platforms']//a\").get_attribute('href')\n # print(alumni_linked_in)\n str_alumni += '< ' + 'Photo Link : ' + alumni_img + ' # Name : ' + alumni_name + ' # Designation : ' + \\\n alumni_designation + ' # Company : ' + alumni_company + \\\n ' # LinkedIn Link : ' + alumni_linked_in + ' >'\n except NoSuchElementException:\n continue\n print('Notable alumni : ')\n print(str_alumni)\n\n # admission\n str_mode = ''\n gender_ratio = ''\n avg_age = ''\n temp_mode = driver.find_elements_by_xpath(\n \"//div[@id='mCSB_1_container']/table/tbody/tr\")\n for x in temp_mode:\n mode_exam_name = safe_get_xpath('.//td[1]/a', parent=x)\n mode_type = safe_get_xpath('.//td[2]', parent=x)\n mode_level = safe_get_xpath('.//td[3]', parent=x)\n str_mode += '< ' + 'Exam : ' + mode_exam_name + ' # Type : ' + \\\n mode_type + ' # Level : ' + mode_level + ' >'\n print(mode_exam_name + ' | ' + mode_type + ' | ' + mode_level)\n print(str_mode)\n\n # insights\n try:\n temp_insights = driver.find_element_by_xpath(\n \"//div[@id='block-college-college-insight-data']\")\n gender_ratio = temp_insights.find_element_by_xpath(\".//div[@class='countBlockLeft dividerRight']/div/span[2]\").get_attribute(\n 'innerHTML').replace(':', ' : ')\n print('Gender Ratio : ' + gender_ratio)\n except NoSuchElementException:\n print('-')\n try:\n avg_age = driver.find_element_by_xpath(\"//div[@id='block-college-college-insight-data']\").find_element_by_xpath(\n \".//div[@class='countBlockRight']/div/p\").get_attribute('innerHTML').replace('', ' ')\n print('Avg. Age : ')\n print(avg_age) # FORMAT\n except NoSuchElementException:\n print('-')\n\n # insights_geo\n print('Insights geo : ')\n in_name_li = []\n in_color_li = []\n in_data_li = []\n\n if check_exists_by_xpath(\"//div[@id='piechartgeo']\") == True:\n temp_geo = driver.find_element_by_xpath(\"//div[@id='piechartgeo']\")\n temp_g = temp_geo.find_elements_by_xpath(\n \".//*[local-name() = 'svg']/*[local-name() = 'g']\")\n temp_blocks = temp_g[0].find_elements_by_xpath(\n \".//*[local-name() = 'g']\")\n\n for x in temp_blocks[::2]:\n in_name_li.append(x.find_element_by_xpath(\n \".//*[local-name() = 'text']\").text)\n # print(in_name_li)\n # print(x.get_attribute('innerHTML'))\n in_color_li.append(x.find_element_by_xpath(\n \".//*[local-name() = 'circle']\").get_attribute('fill'))\n in_data_li.append('')\n print(in_color_li)\n print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')\n\n for x in temp_g[1:]:\n # print(x.get_attribute('innerHTML'))\n # print('$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$')\n try:\n in_data_li[in_color_li.index(x.find_element_by_xpath(\".//*[local-name() = 'path']\").get_attribute(\n 'fill'))] = x.find_element_by_xpath(\".//*[local-name() = 'text']\").text\n except NoSuchElementException:\n continue\n # print(in_data_li)\n print(in_name_li)\n print(in_data_li)\n\n str_in_geo = ''\n for x in range(len(in_name_li)):\n str_in_geo += '< ' + in_name_li[x] + ' : ' + in_data_li[x] + ' >'\n\n # top_following_states\n str_top_states = ''\n if check_exists_by_xpath(\"//div[@class='college-chart-common-div']/ul\") == True:\n for x in driver.find_elements_by_xpath(\"//div[@class='college-chart-common-div']/ul/li/div\"):\n str_top_states += '< ' + x.find_element_by_xpath(\n './/h5').text + ' : ' + x.find_element_by_xpath(\".//span\").text + \" >\"\n print(str_top_states)\n\n # gallery\n print('Gallery : ')\n url = driver.find_element_by_link_text(\"Gallery\").get_attribute('href')\n print(url)\n driver.get(url)\n\n gall_images = []\n gall_vids = []\n li_images = []\n li_vids = []\n\n print('\\nImages : ')\n gall_images = driver.find_elements_by_xpath(\n \"//div[@id='coleges-gallery-photos']/div/a\")\n # print(gall_images)\n for x in gall_images:\n print(x.get_attribute('data-big'))\n li_images.append(x.get_attribute('data-big'))\n # print('---------------------------------')\n # print(x.get_attribute('outerHTML'))\n\n print('\\nVIDEOS : ')\n gall_vids = driver.find_elements_by_xpath(\n \"//div[@id='college-gallery-video']/div/a\")\n for x in gall_vids:\n print(x.get_attribute('href'))\n li_vids.append(x.get_attribute('href'))\n\n # courses\n courses = ''\n tot_ug = ''\n tot_pg = ''\n str_courses = ''\n\n print('\\nCourses : ')\n # url+='/branches'\n # url = url.replace(\"/colleges\",'')#immutable\n try:\n url = driver.find_element_by_link_text(\n \"Courses\").get_attribute('href')\n print(url)\n driver.get(url)\n except:\n continue\n\n courses = driver.find_element_by_xpath(\n \"/html/body/div/div/div/div[3]/div/div/div/div/div/div/h4\").text.replace('Number of Courses Available:', '')\n print(courses)\n pg_exists = 0\n if check_exists_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div/div/div\") == True:\n tot_ug = driver.find_element_by_xpath(\n \"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div/div/div\").text.replace('UG (', '').replace(')', '')\n print('UG : ' + tot_ug)\n if check_exists_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div/div/span\") == True:\n pg_exists = 1\n tot_pg = driver.find_element_by_xpath(\n \"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div/div/span\").text.replace('PG (', '').replace(')', '')\n print('PG : ' + tot_pg)\n\n '''\n #ug_pie\n if check_exists_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div[2]/div/div/div/div/div/svg/g\") == True:\n count_ug = len(driver.find_elements_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div[2]/div/div/div/div/div/svg/g\"))\n ug_pie_data = driver.find_elements_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div[2]/div/div/div/div/div/svg/g\")\n for x in ug_pie_data:\n print(x.text)\n\n #pg_pie\n if check_exists_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div[3]/div/div/div/div/div/svg/g\") == True:\n count_pg = len(driver.find_elements_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div[3]/div/div/div/div/div/svg/g\"))\n pg_pie_data = driver.find_elements_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div/div/div[3]/div/div/div/div/div/svg/g\")\n for x in pg_pie_data:\n print(x.text)\n \n\n\n #all_courses = driver.find_elements_by_xpath(\"/html/body/div/div/div/div[3]/div/div/div/div/div[2]/div[2]/div[2]/div\")\n \n i=0\n for x in range(len(all_courses)//2):\n course_logo = all_courses[i].find_element_by_xpath(\".//span[@class='accordion_course_image']/img\").get_attribute('src')\n print(course_logo)\n \n i+=1\n eligibility = all_courses[i].find_element_by_xpath(\".//div[@class='match-interest-eligibillity']\").text\n print(eligibility)\n\n temp = all_courses[i].find_elements_by_xpath(\"div[@class='degree relDiv']\")\n for x in temp:\n print(x.get_attribute('outerHTML'))\n degree = temp[0].find_element_by_xpath(\".//span\").text\n print(degree)\n\n duration = temp[1].find_element_by_xpath(\".//span\").text\n print(duration)\n\n mode = temp[2].find_element_by_xpath(\".//span\").text\n print(mode)\n '''\n\n while(True):\n\n all_courses = driver.find_elements_by_xpath(\n \"/html/body/div/div/div/div[3]/div/div/div/div/div[2]/div[2]/div[2]/div\")\n\n i = 0\n for x in range(len(all_courses) // 2):\n i += 1\n if i > 2 and not TEMP:\n break\n\n print(\n '######################################################################')\n # print(all_courses[i].find_element_by_xpath(\".//a[@class='apply_btn']\").get_attribute('outerHTML'))\n\n clink = all_courses[i].find_element_by_xpath(\n \".//a[@class='apply_btn']\").get_attribute('href')\n #clink = 'http://www.engineering.careers360.com/colleges/pes-university-bangalore/courses/m-tech-digital-electronics-and-communications-systems'\n driver.find_element_by_tag_name(\n \"body\").send_keys(Keys.CONTROL + 't')\n #driver = webdriver.Firefox()\n try:\n driver.get(clink)\n except:\n break\n\n cname = safe_get_xpath(\n \"/html/body/div/div/div/div[3]/div/div/div/div/h2\")\n print(cname)\n\n eligibility = ''\n #eligibility = driver.find_element_by_xpath(\"//span[@class='more-eligibility']\").get_attribute('innerHTML').replace('...See Less','')\n\n print('Eligibility : ')\n if check_exists_by_xpath(\"//span[@class='more-eligibility']\") == True:\n eligibility = driver.find_element_by_xpath(\"//span[@class='more-eligibility']\").get_attribute('innerHTML').replace(\n '...See Less', '')\n elif check_exists_by_xpath(\"//div[@class='default-elig']\") == True:\n eligibility = driver.find_element_by_xpath(\n \"//div[@class='default-elig']\").text\n print(eligibility)\n\n all_cdet = driver.find_elements_by_xpath(\n \"//div[@class='coursesPageLableInnerSec']\")\n\n str_temp = ''\n for y in all_cdet:\n str_temp += ' # ' + \\\n y.find_element_by_xpath(\n \".//strong\").text + ' : ' + y.find_element_by_xpath(\".//p\").text\n print(y.find_element_by_xpath(\".//strong\").text + ' : ' +\n y.find_element_by_xpath(\".//p\").text) # CSV TAKE CARE\n\n det = ''\n if check_exists_by_xpath(\"//span[@class='moreCourseDetails']\") == True:\n det = driver.find_element_by_xpath(\"//span[@class='moreCourseDetails']\").get_attribute('innerHTML').replace(\n '...See Less', '')\n elif check_exists_by_xpath(\"//div[@class='coursesPageLableDetail']\") == True:\n detail = driver.find_element_by_xpath(\n \"//div[@class='coursesPageLableDetail']\")\n print(detail.find_element_by_xpath(\".//strong\").text +\n ' : ' + detail.find_element_by_xpath(\".//div\").text)\n det = detail.find_element_by_xpath(\".//div\").text\n print(det)\n\n i += 1\n\n str_courses += ('< ' + 'Course Name : ' + cname + ' # Eligibility : ' +\n eligibility + str_temp + ' # Details : ' + det + ' >')\n\n driver.find_element_by_tag_name(\n \"body\").send_keys(Keys.CONTROL + 'w')\n time.sleep(0.5)\n #driver.find_element_by_tag_name(\"body\").send_keys(Keys.CONTROL\n if check_exists_by_xpath(\"//a[@title='Go to next page']\") and TEMP == False:\n break\n else:\n clink_nxt_page = safe_get_xpath(\n \"//a[@title='Go to next page']\", attrib='href')\n if not clink_nxt_page:\n break\n\n time.sleep(0.5)\n #driver.find_element_by_tag_name(\"body\").send_keys(Keys.CONTROL + Keys.TAB)\n driver.get(clink_nxt_page)\n print(\n '\\n!!!!!!!!!!!!!!!!!!!!!!!!NEXT!!!PAGE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n')\n\n str_images = ''\n for x in li_images:\n str_images += '< ' + x + ' >'\n\n str_vids = ''\n for x in li_vids:\n str_vids += '< ' + x + ' >'\n\n name = name.replace(',', '$')\n typeofcoll = typeofcoll.replace(',', '$')\n also_known_as = also_known_as.replace(',', '$')\n location = location.replace(',', '$')\n ownership = ownership.replace(',', '$')\n approved_by = approved_by.replace(',', '$')\n affiliated_to_text = affiliated_to_text.replace(',', '$')\n str_alumni = str_alumni.replace(',', '$')\n avg_age = avg_age.replace(',', '$')\n courses = courses.replace(',', '$')\n str_courses = str_courses.replace(',', '$')\n\n entry = [\n name,\n typeofcoll,\n phone[0],\n phone[1],\n phone[2],\n phone[3],\n phone[4],\n logo,\n also_known_as,\n location,\n estd,\n website,\n mail,\n ownership,\n approved_by,\n affiliated_to_text,\n affiliated_to_link,\n facilities,\n state_rank,\n facebook,\n twitter,\n youtube,\n wiki,\n tot_faculty,\n stu_to_fact,\n str_ug_pie,\n str_pg_pie,\n str_alumni,\n str_top_states,\n str_mode,\n gender_ratio,\n avg_age,\n str_in_geo,\n str_images,\n str_vids,\n courses,\n tot_ug,\n tot_pg,\n str_courses\n\n ]\n for col, data in enumerate(entry):\n ws.write(GLOBAL_OFFSET, col, data)\n if not data:\n continue\n wid = min(len(data) * 380, 9000)\n if ws.col(col).width < wid:\n ws.col(col).width = wid\n wb.save(OUTPUT_FILE)\n\n driver.find_element_by_tag_name(\"body\").send_keys(Keys.CONTROL + 'w')\n time.sleep(0.5)\n driver.find_element_by_tag_name(\n \"body\").send_keys(Keys.CONTROL + Keys.TAB)\n print('\\n--------------------------------------------\\n')\n count_coll += 1\nprint('All DONE')\ndriver.close()\n","sub_path":"scrap_careers.py","file_name":"scrap_careers.py","file_ext":"py","file_size_in_byte":30568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"83130601","text":"import unittest\nimport os\n\nfrom whitenoise.tree import *\n\nbase_path = os.path.join(os.path.dirname(__file__), 'build_tree')\n\n\nclass TestBuildTree(unittest.TestCase):\n\n def test_single_file(self):\n path = os.path.join(base_path, 'single_file')\n\n should = Directory(path)\n should.index = Node(os.path.join(path, 'index.html'))\n\n actual = build_tree(path)\n\n assert should == actual\n\n def test_flat_files(self):\n path = os.path.join(base_path, 'flat_files')\n\n should = Directory(path)\n should.index = Node(os.path.join(path, 'index.html'))\n\n bar = Node(os.path.join(path, 'bar.html'))\n foo = Node(os.path.join(path, 'foo.html'))\n should.children.append(bar)\n should.children.append(foo)\n\n actual = build_tree(path)\n\n assert should == actual\n\n def test_hiearchical(self):\n path = os.path.join(base_path, 'hierarchical')\n\n should = Directory(path)\n should.index = Node(os.path.join(path, 'index.html'))\n\n secondary = Directory(os.path.join(path, 'secondary'))\n bar = Node(os.path.join(secondary.path, 'bar.html'))\n secondary.children.append(bar)\n should.children.append(secondary)\n\n foo = Node(os.path.join(path, 'foo.html'))\n should.children.append(foo)\n\n actual = build_tree(path)\n\n assert should == actual\n","sub_path":"tests/build_tree.py","file_name":"build_tree.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"22387083","text":"class Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n def kadane(a, k):\n n = len(arr)\n max_so_far, max_ending_here = 0, 0\n for i in range(0, k*n):\n max_ending_here = max(a[i%n], max_ending_here+a[i%n])\n max_so_far = max(max_so_far, max_ending_here)\n return max_so_far\n total = sum(arr)\n if(min(arr)>=0): return total*k%(10**9+7)\n if(max(arr)<0): return 0\n res = kadane(arr, 2)\n return max(res, total*(k-2)+res)%(10**9+7)\n","sub_path":"Leetcode/arrays/1191_K-ConcatenationMaximumSum/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"352010720","text":"#!/usr/bin/env python\n\n'''\nGet direct media URLs to YouTube media, freeing you having to view them in your\nbrowser.\n'''\n\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\ntry:\n from urllib.parse import parse_qsl, urlparse\n from itertools import chain, zip_longest\nexcept ImportError: # Python 2 fallback\n from urlparse import parse_qsl, urlparse\n from itertools import chain, izip_longest as zip_longest\n\nimport argparse\nimport sys\nimport requests\nfrom collections import namedtuple\n\n\nclass YturlError(Exception): error_code = None\nclass UnknownQualityError(YturlError): error_code = 1\nclass YouTubeAPIError(YturlError): error_code = 2\nclass NoLocallyKnownItagsAvailableError(YturlError): error_code = 3\nclass VideoIDParserError(YturlError): error_code = 4\n\n\nItag = namedtuple('Itag', [\n 'v_dimensions', 'v_bitrate', 'a_bitrate', 'a_samplerate', 'v_encoding'\n])\nITAGS = {\n 5: Itag(400*240, 0.25, 64, 22.05, 'h263'),\n 6: Itag(480*270, 0.8, 64, 22.05, 'h263'),\n 13: Itag(176*144, 0.5, 64, 22.05, 'mp4v'),\n 17: Itag(176*144, 2, 64, 22.05, 'mp4v'),\n 18: Itag(640*360, 0.5, 96, 44.1, 'h264'),\n 22: Itag(1280*720, 2.9, 192, 44.1, 'h264'),\n 34: Itag(640*360, 0.5, 128, 44.1, 'h264'),\n 35: Itag(854*480, 1, 128, 44.1, 'h264'),\n 36: Itag(320*240, 0.17, 38, 44.1, 'mp4v'),\n 37: Itag(1920*1080, 2.9, 192, 44.1, 'h264'),\n 38: Itag(4096*3072, 5, 192, 44.1, 'h264'),\n 43: Itag(640*360, 0.5, 128, 44.1, 'vp8'),\n 44: Itag(854*480, 1, 128, 44.1, 'vp8'),\n 45: Itag(1280*720, 2, 192, 44.1, 'vp8'),\n 46: Itag(1920*1080, 2, 192, 44.1, 'vp8'),\n}\nITAGS_BY_QUALITY = sorted(ITAGS, reverse=True, key=lambda itag: ITAGS[itag])\n\nNAMED_QUALITY_GROUPS = {\n \"low\": -1,\n \"medium\": len(ITAGS_BY_QUALITY) // 2,\n \"high\": 0,\n}\n\nVIDEO_ID_LEN = 11\nGVI_BASE_URL = 'https://youtube.com/get_video_info?hl=en&video_id='\nGENERIC_API_FAIL_MSG = 'The YouTube API returned malformed data.'\n\n\ndef video_id_from_url(url):\n '''\n Parse a video ID from a YouTube URL.\n\n There are basically two different types of input we're trying to parse:\n\n - A youtube.com URL: youtube.com/watch?v=12345&foo=bar. In this case, we\n want to grab the value of the \"v\" key, and return that.\n - A youtu.be URL: youtu.be/12345. In this case, we grab the path component\n from urlparse and get the last path element (I don't know of any cases\n where there would be more than one element, this is mostly just an\n artifact of how the algorithm works).\n '''\n\n parsed_url = urlparse(url)\n url_params = dict(parse_qsl(parsed_url.query))\n video_id = url_params.get('v', parsed_url.path.split('/')[-1])\n\n # Google has made no commitment about this length, although it's likely to\n # stay like this. I'd usually prefer to just let the API complain about the\n # video ID down the line so that we don't duplicate its logic to determine\n # \"correctness\", but we have the opportunity to make the error message much\n # clearer here.\n if len(video_id) != VIDEO_ID_LEN:\n raise VideoIDParserError(\n 'Could not parse video ID from {url!r} '\n '(expected len: {expected}, got: {got})'.format(\n url=url, expected=VIDEO_ID_LEN, got=len(video_id),\n )\n )\n\n return video_id\n\n\ndef itags_by_similarity(desired_itag):\n '''\n Return itags ordered by the similarity to the desired one. Similarity is\n determined by seeking outwards from the index of the desired itag in the\n sorted list of known itags.\n '''\n\n desired_index = ITAGS_BY_QUALITY.index(desired_itag)\n pairs_by_distance = zip_longest(\n ITAGS_BY_QUALITY[desired_index::-1],\n ITAGS_BY_QUALITY[desired_index+1:],\n )\n return (x for x in chain(*pairs_by_distance) if x is not None)\n\n\ndef itags_for_video(video_id):\n '''\n Return the available itags for a video with their associated URLs.\n '''\n\n gvi_url = GVI_BASE_URL + video_id\n api_response_raw = requests.get(gvi_url).text\n api_response = dict(parse_qsl(api_response_raw))\n\n try:\n streams = api_response['url_encoded_fmt_stream_map'].split(',')\n except KeyError:\n raise YouTubeAPIError(api_response.get('reason', GENERIC_API_FAIL_MSG))\n\n for stream in streams:\n video = dict(parse_qsl(stream))\n yield int(video[\"itag\"]), video[\"url\"]\n\n\ndef itag_from_quality(group):\n '''\n Return the itag representing a quality group name, or if the quality is a\n known itag, return that itag.\n '''\n\n try:\n return ITAGS_BY_QUALITY[NAMED_QUALITY_GROUPS[group]]\n except KeyError:\n if group in ITAGS_BY_QUALITY:\n return group\n else:\n raise UnknownQualityError(\n '{group!r} is not a known quality (known: {known})'.format(\n group=group, known=', '.join(NAMED_QUALITY_GROUPS),\n )\n )\n\n\ndef most_similar_available_itag(desired_itag, available_itags):\n '''\n Return the most similar available itag to the desired itag. See\n itags_by_similarity for information about how \"similarity\" is determined.\n '''\n\n itags_by_preference = itags_by_similarity(desired_itag)\n\n for itag in itags_by_preference:\n if itag in available_itags:\n return itag\n\n raise NoLocallyKnownItagsAvailableError(\n 'No local itags available. '\n '(known: {known_itags!r}, available: {available_itags!r})'.format(\n known_itags=sorted(itags_by_preference),\n available_itags=sorted(available_itags),\n )\n )\n\n\ndef parse_args(args):\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-q\", \"--quality\",\n help='\"low\", \"medium\", \"high\", or an itag',\n # We accept either an int or string here because this could be either\n # an itag or a quality group.\n type=lambda arg: int(arg) if arg.isdigit() else arg,\n default=\"medium\",\n )\n parser.add_argument(\n \"url\",\n metavar=\"video_id/url\",\n help=\"a YouTube url (or bare video ID)\",\n )\n return parser.parse_args(args)\n\n\ndef run(args=sys.argv[1:], force_return=False):\n args = parse_args(args)\n\n video_id = video_id_from_url(args.url)\n desired_itag = itag_from_quality(args.quality)\n video_itags = dict(itags_for_video(video_id))\n\n most_similar_itag = most_similar_available_itag(desired_itag, video_itags)\n url_to_video = video_itags[most_similar_itag]\n\n if force_return:\n return url_to_video\n else:\n print('Using itag {0}.'.format(most_similar_itag), file=sys.stderr)\n print(url_to_video)\n\n\ndef main():\n try:\n run()\n except YturlError as thrown_exc:\n print('fatal: {0!s}'.format(thrown_exc), file=sys.stderr)\n sys.exit(thrown_exc.error_code)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"yturl.py","file_name":"yturl.py","file_ext":"py","file_size_in_byte":6969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"334064912","text":"import threading\n \nclass MyThread(threading.Thread):\n def run(self) :\n i = 0\n for n in range(1000000):\n i += n\n if 0 == (n % 10000): #10000おきに表示\n print('[mid] %s : %d' % (self.getName(), n))\n print('[end] %s : %d' % (self.getName(), i))\n \ndef main():\n thd1 = MyThread()\n \n thd1.start()\n \n print('in join')\n thd1.join() #スレッド完了まで待機\n print('[finish]')\n \nif __name__ == '__main__':\n main()","sub_path":"thread/count_number.py","file_name":"count_number.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"193573145","text":"import os, glob\nimport json\n\nfrom binaryninja.log import log_info, log_warn\nfrom binaryninja.enums import SymbolType, SettingsScope\nfrom binaryninja.settings import Settings\nfrom binaryninja.plugin import PluginCommand\n\nfrom .util import (\n\tnormalize_module, supports_ordinals, demangle,\n\tget_symbol_module, set_symbol_name, set_symbol_type, set_type_metadata\n)\nfrom .base import MatchingMethod, parse_dependency\n# dependency formats\nfrom . import msdef, idt, binja\n\n\ndef get_identifier(bv, sym):\n\t\"\"\" Find identifier for symbol according to current matching method \"\"\"\n\tmethod = get_matching_method(bv)\n\tif method == MatchingMethod.Ordinal:\n\t\treturn sym.ordinal\n\telif method == MatchingMethod.Address:\n\t\treturn sym.address\n\telif method == MatchingMethod.Name:\n\t\treturn sym.raw_name.split('@', 1)[0]\n\ndef analyze_dependency(bv, module, filename, candidates):\n\t\"\"\" Analyze single dependency and apply found information to given symbols \"\"\"\n\tfor dep in parse_dependency(filename):\n\t\t# Rename imports to more accurate information from dependency\n\t\tfor nsym in dep.get_exports():\n\t\t\tident = get_identifier(bv, nsym)\n\t\t\tif ident not in candidates:\n\t\t\t\tcontinue\n\t\t\tname = demangle(bv, nsym.full_name)\n\t\t\ttype = dep.get_symbol_type(nsym)\n\n\t\t\tfor ref, t in dep.get_user_types(nsym).items():\n\t\t\t\tnewname = bv.define_type(ref.type_id, ref.name, t)\n\t\t\t\tnewtype = bv.get_type_by_name(newname)\n\t\t\t\tset_type_metadata(bv, newtype, 'namespace', normalize_module(module))\n\t\t\t\tlog_info('Imported type: {}'.format(newname))\n\n\t\t\tfor osym in candidates.pop(ident):\n\t\t\t\tset_symbol_name(bv, osym, name)\n\t\t\t\tif type is not None:\n\t\t\t\t\tset_symbol_type(bv, osym, type)\n\t\t\t\tlog_info('Renamed: {} -> {}'.format(osym.name, name))\n\n\ndef prioritize_file_types(k):\n\t\"\"\" Give a proper priority to certain file types when sorting \"\"\"\n\t# BN databases should always go first\n\tif k.endswith('.bndb'):\n\t\treturn 0\n\t# Definition files matter more than raw files\n\tif any(k.endswith(e) for e in ('.def', '.idt')):\n\t\treturn 5\n\treturn 10\n\ndef find_possible_dependencies(bv, names):\n\tmatchnames = [normalize_module(n) for n in names]\n\tfor path in get_search_paths(bv):\n\t\tpattern = os.path.join(path, '*.*')\n\t\tfor filename in sorted(glob.iglob(pattern), key=prioritize_file_types):\n\t\t\tif not os.path.isfile(filename):\n\t\t\t\tcontinue\n\t\t\tbasename, _ = os.path.splitext(os.path.basename(filename))\n\t\t\tif normalize_module(basename) not in matchnames:\n\t\t\t\tcontinue\n\t\t\tyield (basename, filename)\n\ndef analyze_self(bv):\n\t\"\"\" Analyze metadata for self and apply found information \"\"\"\n\townname = os.path.realpath(bv.file.filename)\n\tbasename, ext = os.path.splitext(os.path.basename(ownname))\n\tdbname = ownname[:-len(ext)] + '.bndb'\n\n\t# Get all own modules and symbols\n\tcandidates = {}\n\tfor type in (SymbolType.DataSymbol, SymbolType.FunctionSymbol):\n\t\tfor sym in bv.get_symbols_of_type(type):\n\t\t\tident = get_identifier(bv, sym)\n\t\t\tif ident is None:\n\t\t\t\tcontinue\n\t\t\tsyms = candidates.setdefault(ident, [])\n\t\t\tsyms.append(sym)\n\n\t# Find any associated dependency files and process them\n\tfor module, filename in find_possible_dependencies(bv, [basename]):\n\t\tif os.path.realpath(filename) in (ownname, dbname):\n\t\t\tcontinue\n\n\t\tlog_info('Processing: {}...'.format(filename))\n\t\tanalyze_dependency(bv, None, filename, candidates)\n\ndef analyze_dependencies(bv):\n\t\"\"\" Get all imported symbols, analyze dependencies and apply found information \"\"\"\n\t# Get all imported modules and symbols\n\tcandidates = {}\n\tfor type in (SymbolType.ImportAddressSymbol, SymbolType.ImportedFunctionSymbol, SymbolType.ImportedDataSymbol):\n\t\tfor sym in bv.get_symbols_of_type(type):\n\t\t\tident = get_identifier(bv, sym)\n\t\t\tif ident is None:\n\t\t\t\tcontinue\n\t\t\tmodule = normalize_module(get_symbol_module(sym))\n\t\t\tmod_syms = candidates.setdefault(module, {})\n\t\t\tthese_syms = mod_syms.setdefault(ident, [])\n\t\t\tthese_syms.append(sym)\n\n\t# Find any associated dependency files and process them\n\tfor module, filename in find_possible_dependencies(bv, candidates.keys()):\n\t\tlog_info('Processing: {}...'.format(filename))\n\t\tanalyze_dependency(bv, module, filename, candidates[normalize_module(module)])\n\nPluginCommand.register(\"Analyze self\", \"Resolve metadata for self\", analyze_self)\nPluginCommand.register(\"Analyze dependencies\", \"Resolve metadata for analyzed dependencies\", analyze_dependencies)\n\n\nsettings = Settings()\nsettings.register_group(\"depanalyzer\", \"Dependency Analyzer Plugin\")\nsettings.register_setting(\"depanalyzer.path\", json.dumps({\n\t'title': 'Dependency Paths',\n\t'description': 'Paths to search for dependencies',\n\t'type': 'array',\n\t'elementType': 'string',\n\t'default': ['.'],\n}))\nsettings.register_setting(\"depanalyzer.matching_method\", json.dumps({\n\t'title': 'Matching Method',\n\t'description': 'Method used to match dependency symbols to imported symbols',\n\t'type': 'string',\n\t'enum': [m.value for m in MatchingMethod],\n\t'default': 'auto',\n}))\n\ndef get_matching_method(bv):\n\tmethod = MatchingMethod(settings.get_string('depanalyzer.matching_method'))\n\tif method == MatchingMethod.Address and bv.relocatable:\n\t\tlog_warn('Attempted address-based matching on relocatable file: resetting to auto')\n\t\tmethod = MatchingMethod.Auto\n\t\tsettings.set_string('depanalyzer.matching_method', method.value, view=bv, scope=SettingsScope.SettingsContextScope)\n\tif method == MatchingMethod.Ordinal and not supports_ordinals(bv):\n\t\tlog_warn('Attempted ordinal-based matching on non-supported file type: resetting to auto')\n\t\tmethod = MatchingMethod.Auto\n\t\tsettings.set_string('depanalyzer.matching_method', method.value, view=bv, scope=SettingsScope.SettingsContextScope)\n\n\tif method == MatchingMethod.Auto:\n\t\tif supports_ordinals(bv):\n\t\t\tmethod = MatchingMethod.Ordinal\n\t\telse:\n\t\t\tmethod = MatchingMethod.Name\n\n\treturn method\n\ndef get_search_paths(bv):\n\tbase_path = os.path.dirname(bv.file.filename)\n\treturn (os.path.join(base_path, path) for path in settings.get_string_list('depanalyzer.path'))\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"109496995","text":"class TreeNode():\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n def __str__(self):\n return str(self.val)\n\n def __iter__(self):\n # return TreeNodeIterator(self)\n return gen_tree_node(self)\n\n\nclass TreeNodeIterator():\n def __init__(self, tree: TreeNode):\n self._root = tree\n self._que = [self._root]\n\n def __next__(self):\n try:\n node = self._que.pop(0)\n except IndexError:\n raise StopIteration\n else:\n if node.left:\n self._que.append(node.left)\n if node.right:\n self._que.append(node.right)\n return node\n\n def __iter__(self):\n return self\n\n\ndef gen_tree_node(root: TreeNode):\n que = [root]\n while que:\n node = que.pop(0)\n yield node\n if node.left:\n que.append(node.left)\n if node.right:\n que.append(node.right)\n\n\ndef make_simple_tree(rootVal, leftVal, rightVal):\n root = TreeNode(rootVal)\n root.left = TreeNode(leftVal)\n root.right = TreeNode(rightVal)\n return root\n\n\ndef make_basic_tree():\n \"\"\"\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \"\"\"\n root = TreeNode(1)\n root.left = make_simple_tree(2, 4, 5)\n root.right = make_simple_tree(3, 6, 7)\n return root\n\n\ndef inorder_genrator(root: TreeNode):\n nodes = []\n\n def find_first(node: TreeNode):\n p = node\n while p:\n nodes.append(p)\n p = p.left\n find_first(root)\n while nodes:\n node = nodes.pop()\n yield node\n if node.right:\n find_first(node.right)\n\n\ndef inorder_traversal(root: TreeNode):\n out = []\n\n def inorder(branch: TreeNode):\n if not branch:\n return\n if branch.left:\n inorder(branch.left)\n out.append(branch.val)\n if branch.right:\n inorder(branch.right)\n inorder(root)\n return out\n\n\ndef test_inorder_traversal():\n t1 = make_basic_tree()\n print(inorder_traversal(t1))\n\n\ndef BFS(root: TreeNode):\n if not root:\n return None\n depth = 0\n que = []\n que.append(root)\n\n while que:\n for _ in range(len(que)):\n cur = que.pop(0)\n print(cur.val)\n if cur.left:\n que.append(cur.left)\n if cur.right:\n que.append(cur.right)\n depth += 1\n print('****', depth)\n return depth\n\n\ndef test_iter():\n root = make_basic_tree()\n # iterator = TreeNodeIterator(root)\n l1 = [node.val for node in root]\n print(l1)\n\n\ndef test_inorder_gen():\n t1 = make_basic_tree()\n assert [4, 2, 5, 1, 6, 3, 7] == [node.val for node in inorder_genrator(t1)]\n\n\ndef DFS(root: TreeNode):\n if not root:\n return 0\n stack = []\n stack.append((root, 1))\n ans_dep = 0\n while stack:\n curNode, curDep = stack.pop()\n print(curNode.val, curDep)\n if curDep > ans_dep:\n ans_dep = curDep\n if curNode.right:\n stack.append((curNode.left, curDep+1))\n if curNode.right:\n stack.append((curNode.right, curDep+1))\n return ans_dep\n\n\ndef depthOfTreeRecur(root: TreeNode):\n if not root:\n return 0\n return 1 + max(depthOfTreeRecur(root.left), depthOfTreeRecur(root.right))\n\n\nclass Solution():\n\n def _isleaf(self, node):\n if not node.left and not node.right:\n return True\n return False\n\n def _dfs(self, node: TreeNode, level):\n if not node:\n return\n\n if self._isleaf(node) and level > self.Max:\n self.Max = level\n self._dfs(node.left, level+1)\n self._dfs(node.right, level+1)\n\n def dpethOfDFS(self, root: TreeNode):\n if not root:\n return 0\n self.Max = 1\n self._dfs(root, 1)\n return self.Max\n\n\ndef preorder_traversal(root: TreeNode):\n out = []\n\n def preorder(branch: TreeNode):\n out.append(branch.val)\n if branch.left:\n preorder(branch.left)\n if branch.right:\n preorder(branch.right)\n preorder(root)\n return out\n\n\ndef test_preorder_traversal():\n t1 = make_basic_tree()\n assert [1, 2, 4, 5, 3, 6, 7] == preorder_traversal(t1)\n\n\ndef preorder_generator(root: TreeNode):\n visited = []\n nodes = [root]\n while nodes:\n node = nodes.pop()\n visited.append(node)\n yield node.val\n if node.left:\n nodes.append(node.left)\n\n while not nodes:\n if visited:\n vnode = visited.pop()\n if vnode.right:\n nodes.append(vnode.right)\n else:\n break\n\n\ndef test_preorder_generator():\n t1 = make_basic_tree()\n assert [1, 2, 4, 5, 3, 6, 7] == [val for val in preorder_generator(t1)]\n\n\ndef post_traversal(root: TreeNode):\n out = []\n\n def postortder(branch: TreeNode):\n if not branch:\n return\n if branch.left:\n postortder(branch.left)\n if branch.right:\n postortder(branch.right)\n out.append(branch.val)\n postortder(root)\n return out\n\n\ndef test_postorder_traversal():\n t1 = make_basic_tree()\n assert [4, 5, 2, 6, 7, 3, 1] == post_traversal(t1)\n\n\ndef postorder_iter(root: TreeNode):\n \"\"\"\n\n \"\"\"\n if not root:\n return []\n out = []\n stack = [(root, False)]\n while stack:\n cur, visited = stack.pop()\n if visited:\n out.append(cur.val)\n else:\n stack.append((cur, True))\n if cur.right:\n stack.append((cur.right, False))\n if cur.left:\n stack.append((cur.left, False))\n return out\n\n\ndef test_postorder_iter():\n t1 = make_basic_tree()\n assert [4, 5, 2, 6, 7, 3, 1] == postorder_iter(t1)\n\n\ndef main():\n root = make_basic_tree()\n BFS(root)\n # print('dfs', DFS(root))\n test_iter()\n print('depthOfTreeRecur: ', depthOfTreeRecur(root))\n s = Solution()\n print(s.dpethOfDFS(root))\n test_inorder_gen()\n test_inorder_traversal()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"data_strucr_and_algorithms/test_binaryTree.py","file_name":"test_binaryTree.py","file_ext":"py","file_size_in_byte":6175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"423495502","text":"# import pandas as pd\n\n# x = pd.read_csv(\"db_inminder.csv\", delimiter=\",\")\n# print(x)\n\nfrom tkinter import *\nimport csv\nimport datetime\n\ndef enter_button():\n now = datetime.datetime.now()\n amount = e1.get()# That is where I thought I should get the Input from the widget\n with open('File.csv', 'a') as f:\n w = csv.writer(f,dialect='excel-tab')\n w.writerow([now.strftime(\"%Y-%m-%d %H:%M\"), amount]) # write Date/Time and the value\n f.close()\n\nmaster = Tk()\ne1 = Entry(master)\nLabel(master, text='Enter Number Here').grid(row=0)\nmyButton=Button(master,text='Enter',command=enter_button)\ne1.grid(row=0,column=1)\nmyButton.grid(row=1,column=0)\nmainloop()","sub_path":"eiei.py","file_name":"eiei.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"374442826","text":"import sys\n\nfrom PyQt5.QtWidgets import QApplication, QWidget, QTableWidgetItem, QHeaderView\n\nfrom PyQt5 import uic\n\nfrom db_client import DBClient\nfrom edit_row import EditWindow\nfrom insert_row import InsertWindow\n\n\nclass DBViewer(QWidget):\n def __init__(self):\n super().__init__(None, )\n Form, _ = uic.loadUiType('main.ui')\n self.mainForm = Form()\n self.mainForm.setupUi(self)\n\n self.db_client = DBClient()\n self.current_db = None\n self.current_table = None\n self.current_row = None\n self._init_db_combobox()\n self._select_db()\n\n self.mainForm.b_editRow.setEnabled(False)\n self.mainForm.dbBox.currentTextChanged.connect(self._select_db)\n self.mainForm.tableBox.currentTextChanged.connect(self.draw_table)\n self.mainForm.b_newRow.clicked.connect(self._new_row)\n self.mainForm.b_editRow.clicked.connect(self._edit_row)\n self.mainForm.table.currentCellChanged.connect(self._cell_changed)\n\n def _init_db_combobox(self):\n dbs = self.db_client.databases()\n if dbs:\n self.mainForm.dbBox.addItems(dbs)\n\n def _select_db(self):\n self.current_db = self.mainForm.dbBox.currentText()\n self.db_client.set_database(self.current_db)\n self._init_tables_combobox()\n\n def _init_tables_combobox(self):\n self.mainForm.tableBox.clear()\n tables = self.db_client.get_tables()\n if tables:\n self.mainForm.tableBox.addItems(tables)\n self.draw_table()\n else:\n self.clear_table()\n\n def draw_table(self):\n self.mainForm.b_editRow.setEnabled(False)\n self.current_table = self.mainForm.tableBox.currentText()\n if self.current_table:\n data = self.db_client.get_data(self.current_table)\n self.clear_table()\n self.mainForm.table.setColumnCount(len(data['columns']))\n self.mainForm.table.setHorizontalHeaderLabels(data['columns'])\n self.mainForm.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)\n\n self.mainForm.table.setRowCount(len(data['rows']))\n current_row = 0\n for row in data['rows']:\n current_columnt = 0\n for column in row:\n item = QTableWidgetItem(str(column))\n item.setTextAlignment(0x0042)\n self.mainForm.table.setItem(current_row, current_columnt, item)\n current_columnt += 1\n current_row += 1\n\n def clear_table(self):\n self.mainForm.table.setRowCount(0)\n self.mainForm.table.setColumnCount(0)\n\n def _cell_changed(self):\n self.mainForm.b_editRow.setEnabled(True)\n self.current_row = self.mainForm.table.currentRow()\n\n def _new_row(self):\n insert_row_window = InsertWindow(self)\n insert_row_window.show()\n\n def _edit_row(self):\n edit_row_window = EditWindow(self)\n edit_row_window.show()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n w = DBViewer()\n w.show()\n\n sys.exit(app.exec())\n","sub_path":"qt_database/Database_browser.py","file_name":"Database_browser.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"363538864","text":"import json\r\nimport logging\r\nfrom copy import deepcopy\r\nfrom datetime import datetime\r\n\r\nfrom dateutil import parser as date_parser\r\n\r\nfrom ..exceptions import InvalidDataFormatError\r\n\r\nfrom ..constants import (DARK_SKY_KEY, DARK_SKY_URL, GOOGLE_MAPS_GEOCODE_KEY,\r\n GOOGLE_MAPS_GEOCODE_URL, GOOGLE_MAPS_TIMEZONE_KEY,\r\n GOOGLE_MAPS_TIMEZONE_URL, WEATHER_PARAMETERS)\r\nfrom ..sessions.web import WebSession\r\n\r\nlog = logging.getLogger(__name__)\r\n\r\nweb = WebSession()\r\n\r\n\r\ndef generate_darksky_url(coordinates):\r\n # type: (dict) -> str\r\n \"\"\"\r\n Generate a dark_sky url with lat and lng\r\n\r\n :param coordinates: dict containing the lat and lng keys (and their respective values)\r\n :return: The generated dark_sky url, with lat and lng properly formatted and positioned\r\n \"\"\"\r\n lat = coordinates['lat']\r\n lng = coordinates['lng']\r\n url = f'{DARK_SKY_URL}{DARK_SKY_KEY}/{lat},{lng}'\r\n return url\r\n\r\n\r\ndef get_coordinates(location):\r\n # type: (str) -> dict\r\n \"\"\"\r\n Returns a dict (json), with the coordinates for specified location\r\n\r\n :param location: the location for which coordinates are to be parsed\r\n :returns: dict that contains lat and lng\r\n \"\"\"\r\n location = location.replace(' ', '+')\r\n params = {\r\n 'address': location,\r\n 'key': GOOGLE_MAPS_GEOCODE_KEY\r\n }\r\n json_data = web.get_json(GOOGLE_MAPS_GEOCODE_URL, params=params)\r\n coordinates = json_data['results'][0]['geometry']['location']\r\n coordinates['lng'] = round(coordinates['lng'], 7)\r\n coordinates['lat'] = round(coordinates['lat'], 7)\r\n return coordinates\r\n\r\n\r\ndef get_datetime_from_string(datetime_str):\r\n # type: (str) -> datetime\r\n \"\"\"\r\n Given a str, generate equivalent datetime object\r\n\r\n :param datetime_str: string representation of time\r\n :return: the corresponding datetime object\r\n \"\"\"\r\n datetime_object = date_parser.parse(datetime_str)\r\n return datetime_object\r\n\r\n\r\ndef get_offset_from_utc(coordinates):\r\n # type: (dict) -> int\r\n \"\"\"\r\n Calculate the offset coordinates has from utc\r\n\r\n :param coordinates: dict containing the lat and lng keys (and their respective values)\r\n :return: the offset, in seconds, that coordinates has from utc time\r\n \"\"\"\r\n\r\n current_epoch_time = datetime.utcnow().timestamp()\r\n lat = coordinates['lat']\r\n lng = coordinates['lng']\r\n location_param = f'{lat},{lng}'\r\n\r\n params = {'key': GOOGLE_MAPS_TIMEZONE_KEY,\r\n 'location': location_param,\r\n 'timestamp': current_epoch_time}\r\n\r\n json_data = web.get_json(GOOGLE_MAPS_TIMEZONE_URL, params=params)\r\n return json_data['dstOffset'] + json_data['rawOffset']\r\n\r\n\r\ndef get_weather_data(coordinates, include=None):\r\n # type: (dict, Optional(list[str])) -> dict\r\n \"\"\"\r\n Returns a dict (json), with weather data for the specified coordinates.\r\n If include is specified, only that data is retrieved.\r\n Otherwise, all data is retrieved.\r\n\r\n :param coordinates: dict containing the lat and lng keys (and their respective values)\r\n :param include: Optional list of json data to include\r\n :returns: a dict (json) with (the specified) data\r\n \"\"\"\r\n url = generate_darksky_url(coordinates)\r\n params = {'units': 'si'}\r\n if include is not None:\r\n weather_parameters = deepcopy(WEATHER_PARAMETERS)\r\n for param in include:\r\n weather_parameters.remove(param)\r\n params['exclude'] = ','.join(weather_parameters)\r\n return web.get_json(url, params=params)\r\n\r\n\r\ndef generate_summary(json_data, index=None):\r\n if index is not None:\r\n summary = json_data[index]['summary']\r\n temperature = json_data[index]['apparentTemperature']\r\n else:\r\n summary = json_data['summary']\r\n temperature = (json_data['apparentTemperatureMax'] + json_data['apparentTemperatureMin']) / 2\r\n result = f'{summary} with a temperature of {str(round(temperature, 2))} degrees celsius'\r\n return result\r\n\r\n\r\ndef get_weather_summary_current(coordinates):\r\n # type: (dict) -> str\r\n \"\"\"\r\n Returns current weather summary\r\n\r\n :param coordinates: dict containing the lat and lng keys (and their respective values)\r\n :returns: a str summary of the current weather located at coordinates\r\n \"\"\"\r\n json_data = get_weather_data(coordinates, include=['currently'])\r\n result = generate_summary(json_data, 'currently')\r\n return result\r\n\r\n\r\ndef get_weather_summary_no_datetime(coordinates):\r\n # type: (dict) -> str\r\n \"\"\"\r\n Returns weather summary for the next few hours\r\n\r\n :param coordinates: dict containing the lat and lng keys (and their respective values)\r\n :returns: a str summary of the upcoming weather (next few hours) located at coordinates\r\n \"\"\"\r\n json_data = get_weather_data(coordinates, include=['currently'])\r\n result = generate_summary(json_data, 'currently')\r\n return result\r\n\r\n\r\ndef get_weather_summary_for_hour(datetime_, coordinates):\r\n # type: (dict) -> str\r\n \"\"\"\r\n Returns weather summary for the specific hour\r\n\r\n :param datetime_: The specific hour to get weather summary for\r\n :type datetime_: datetime_\r\n :param coordinates: The coordinates to get weather summary for\r\n :returns: a str summary of the upcoming weather at the specified hour located at coordinates\r\n \"\"\"\r\n timestamp = datetime_.timestamp()\r\n\r\n json_data = get_weather_data(coordinates, include=['hourly'])\r\n for entry in json_data['hourly']['data']:\r\n if entry['time'] == timestamp:\r\n summary = entry['summary']\r\n apparent_temperature = entry['apparentTemperature']\r\n res = f'{summary} with a temperature of {str(int(round(apparent_temperature)))} degrees Celsius.'\r\n return res\r\n\r\n\r\ndef get_weather_summary_for_day(datetime_: datetime, coordinates: str) -> str:\r\n \"\"\"\r\n Returns weather summary for the entire day\r\n\r\n :param datetime_: The specific day to get weather summary for\r\n :type datetime_: datetime\r\n :param coordinates: dict containing the lat and lng keys (and their respective values)\r\n :returns: a str summary of the weather on the specified day located at coordinates\r\n \"\"\"\r\n\r\n if datetime_.timestamp() < datetime.utcnow().timestamp():\r\n raise InvalidDataFormatError(f'{datetime_.isoformat()} is in the past')\r\n new_datetime = datetime(\r\n datetime_.year,\r\n datetime_.month,\r\n datetime_.day\r\n\r\n )\r\n timestamp = new_datetime.timestamp()\r\n json_data = get_weather_data(coordinates, include=['daily'])\r\n\r\n for entry in json_data['daily']['data']:\r\n try:\r\n if entry['time'] == timestamp:\r\n summary = generate_summary(entry)\r\n return summary\r\n except IndexError:\r\n return 'weather.get_weather_for_day()_1'\r\n\r\n\r\ndef get_weather_summary_for_time_period(datetime_, coordinates):\r\n # type: (datetime, dict) -> str\r\n \"\"\"\r\n Return weather summary for a a time period (around 4 hours)\r\n\r\n :param datetime_: The time to get weather summary for\r\n :param coordinates: dict containing the lat and lng keys (and their respective values)\r\n :returns: a str summary of the weather for the specified datetime_ located at coordinates\r\n \"\"\"\r\n timestamp = datetime_.timestamp()\r\n json_data = get_weather_data(coordinates, include=['hourly'])\r\n for entry in json_data['hourly']['data']:\r\n if entry['time'] == timestamp:\r\n summary = entry['summary']\r\n apparent_temperature = entry['apparentTemperature']\r\n res = f'{summary} with a temperature of {apparent_temperature} degreese Celsius.'\r\n return res\r\n\r\n\r\ndef weather_action(query_result: dict):\r\n \"\"\"\r\n Perform a weather action\r\n query_result_example = {\r\n \"action\": \"weather.weather\",\r\n \"parameters\": {\r\n \"location\": \"Amsterdam\",\r\n \"date-time\": \"2018-09-04T12:00:00+02:00\"\r\n }\r\n }\r\n \"\"\"\r\n if 'queryResult' in query_result:\r\n query_result = query_result['queryResult']\r\n\r\n parameters = query_result.get('parameters')\r\n action = query_result.get('action')\r\n\r\n if action.endswith('followup'):\r\n specific_action = action.split('.')[1]\r\n output_contexts = query_result.get('outputContexts')\r\n if specific_action == 'location':\r\n # Have to get date-time from previous request\r\n date_time = output_contexts[0]['parameters']['date-time']\r\n location = parameters.get('location')\r\n elif specific_action == 'time':\r\n # Have to get location from previous request\r\n location = output_contexts[0]['parameters']['location']\r\n date_time = parameters.get('date-time', None)\r\n\r\n else:\r\n date_time = parameters.get('date-time', None)\r\n location = parameters.get('location', None)\r\n\r\n if isinstance(location, dict):\r\n location = location['city']\r\n coordinates = get_coordinates(location)\r\n\r\n if date_time:\r\n # Get weather for specific datetime (day and hour)\r\n if isinstance(date_time, dict):\r\n # Assume that the request is for a period of time, with a start and end\r\n # We simply take the point in time that is between the start and end,\r\n # and return the weather for that time\r\n start_hour = date_parser.parse(date_time['startDateTime']).hour\r\n end_hour = date_parser.parse(date_time['endDateTime']).hour\r\n\r\n average_hour_int = int((start_hour + end_hour) / 2)\r\n\r\n if average_hour_int < 0 or average_hour_int > 24:\r\n return \"Error, average_hour has been calculated as invalid\"\r\n if average_hour_int <= 9:\r\n average_hour_str = f'0{average_hour_int}'\r\n else:\r\n average_hour_str = average_hour_int\r\n\r\n first_part = date_time['startDateTime'][:11]\r\n second_part = str(average_hour_str)\r\n third_part = date_time['startDateTime'][13:]\r\n average_hour_str = f'{first_part}{second_part}{third_part}'\r\n\r\n datetime_object = date_parser.parse(average_hour_str)\r\n\r\n res = get_weather_summary_for_time_period(datetime_object, coordinates)\r\n\r\n else:\r\n datetime_object: datetime = date_parser.parse(date_time)\r\n\r\n if len(date_time) == 25:\r\n now_timestamp = datetime.utcnow().timestamp()\r\n datetime_object_timestamp = datetime_object.timestamp()\r\n if datetime_object_timestamp - 60.0 <= now_timestamp <= datetime_object_timestamp + 60.0:\r\n # Get current weather\r\n res = get_weather_summary_current(coordinates)\r\n else:\r\n res = get_weather_summary_for_day(datetime_object, coordinates)\r\n\r\n else:\r\n raise InvalidDataFormatError(f'The given datetime format is invalid: {datetime_}')\r\n\r\n else:\r\n # Assume that the weather is for the current time\r\n res = get_weather_summary_current(coordinates)\r\n datetime_object = datetime.utcnow()\r\n\r\n coordinates_str = json.dumps(coordinates)\r\n log.debug(f'Returning weather information for the following:\\n'\r\n f'date: {str(datetime_object)}\\n'\r\n f'coordinates: {coordinates_str}')\r\n if res:\r\n return res\r\n else:\r\n return f'Specified date-time is invalid: {date_time}'\r\n # raise InvalidDataFormat(f'Specified date-time is invalid: {date_time}')\r\n","sub_path":"sam/action_handlers/weather.py","file_name":"weather.py","file_ext":"py","file_size_in_byte":11604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"62768012","text":"import atexit\r\nimport json\r\nimport os\r\nimport pickle\r\nimport time\r\nimport unittest\r\nfrom urllib.request import urlopen\r\n\r\nfrom bs4 import BeautifulSoup\r\nfrom selenium import webdriver\r\n\r\nT = 0\r\ntweet_objs = []\r\nhtml_source = ''\r\nglobal_sel = None\r\n\r\n\r\nclass Sel(unittest.TestCase):\r\n def setUp(self):\r\n global global_sel\r\n global_sel = self\r\n firefox_profile = webdriver.FirefoxProfile()\r\n\r\n firefox_profile.add_extension(\"./quickjava-2.0.7-fx.xpi\")\r\n firefox_profile.set_preference(\"thatoneguydotnet.QuickJava.curVersion\", \"2.0.6.1\") ## Prevents loading the 'thank you for installing screen'\r\n firefox_profile.set_preference(\"thatoneguydotnet.QuickJava.startupStatus.Images\", 2) ## Turns images off\r\n firefox_profile.set_preference(\"thatoneguydotnet.QuickJava.startupStatus.AnimatedImage\", 2) ## Turns animated images off\r\n\r\n self.driver = webdriver.Firefox(firefox_profile)\r\n self.driver.implicitly_wait(30)\r\n self.base_url = \"https://twitter.com\"\r\n self.verificationErrors = []\r\n self.accept_next_alert = True\r\n\r\n def test_sel(self):\r\n driver = self.driver\r\n #driver.get(self.base_url + \"/search?q=%23justkidding&lang%3Aen until%3A2016-01-13 since%3A2015-02-14&src=typd\")\r\n driver.get(self.base_url + \"/search?q=%23justkidding lang%3Aen until%3A2015-11-14&src=typd\")\r\n #driver.get(self.base_url + \"/search?q=%23justkidding&lang=en&src=typd\")\r\n global T, html_source\r\n for i in range(1,2000):\r\n T = i\r\n print(\"scroll #\",i)\r\n driver.execute_script(\"window.scrollTo(0, document.body.scrollHeight);\")\r\n time.sleep(4)\r\n if i % 50 == 0:\r\n handle_with_bs()\r\n\r\n\r\ndef write_to_files():\r\n global T,tweet_objs\r\n fn = \"scraped-with-JUSTKIDDING-\"+str(T)+'.pkl'\r\n if os.path.exists(fn):\r\n fn += \"-1\"\r\n f1 = open(fn,'wb')\r\n pickle.dump(tweet_objs,f1)\r\n f1.close()\r\n tweet_objs = []\r\n\r\n\r\ndef create_tweet_obj(tweet):\r\n obj = dict()\r\n try:\r\n obj['username'] = tweet.find('span','username').text\r\n obj['text'] = tweet.find('p','tweet-text').text.encode('utf8')\r\n obj['id'] = int(tweet['data-item-id'])\r\n obj['timestamp'] = tweet.find('a','tweet-timestamp')['title']\r\n return obj\r\n except KeyError as k:\r\n print(k)\r\n\r\n\r\n@atexit.register\r\ndef handle_with_bs():\r\n global T, global_sel\r\n soup = BeautifulSoup(global_sel.driver.page_source.encode('utf-8'),'lxml')\r\n\r\n tweets = soup.find_all('li','js-stream-item')\r\n\r\n for tweet in tweets:\r\n if tweet.find('p','tweet-text'):\r\n tweet_objs.append(create_tweet_obj(tweet))\r\n\r\n write_to_files()\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n","sub_path":"gettweetsbyscraping-selenium.py","file_name":"gettweetsbyscraping-selenium.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"180619241","text":"import csv\nimport numpy as np\nimport numpy.random as rd\nimport matplotlib.pyplot as plt\n\nlength = 10000\nalpha_2 = 0.25\nsigma_2 = 0.2\n\n\n\nx = []\ny = []\nx.append(rd.normal(0, np.sqrt(alpha_2)))\ny.append(x[0] + rd.normal(0, np.sqrt(sigma_2)))\nfor t in range(length):\n # 1階差分トレンドを適用\n #Predictor Step\n\n x.append(x[t] + rd.normal(0, np.sqrt(alpha_2)))\n y.append(x[t+1] + rd.normal(0, np.sqrt(sigma_2)))\n # x[t+1, i] = x_resampled[t, i] + v # システムノイズの付加\n # sigma_2 += float(t) * 0.5/ float(length) \nx = np.array(x)\ny = np.array(y)\n\nprint(x)\nprint(y)\n\ndef draw_graph():\n # グラフ描画\n T = len(y)\n \n plt.figure(figsize=(16,8))\n plt.plot(range(T), y,\"r\")\n plt.plot(range(T), x, \"g\")\n plt.show()\n # for t in range(T):\n # plt.scatter(np.ones(self.n_particle)*t, self.x[t][:,0], color=\"r\", s=2, alpha=0.1)\n \n # plt.title(\"sigma^2={0}, alpha^2={1}, log likelihood={2:.3f}\".format(self.sigma_2, \n # self.alpha_2, \n # self.log_likelihood))\nnp.savetxt(\"noisy_obs.txt\", y)\nnp.savetxt(\"noisy_truth.txt\", x)\n\ndraw_graph()\n ","sub_path":"particle_filter_with_reresampling/noise_emmiter.py","file_name":"noise_emmiter.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"454743512","text":"\"\"\"Give a concrete implementation of the pop method in the context of the MutableMapping class,\nrelying only on the five primary abstract methods of that class.\"\"\"\n\nfrom collections import MutableMapping\n\n\nclass MutableMappingPop(MutableMapping):\n # Removes the key value pair associated with k, and returns the value, otherwise it returns the default value.\n # If no default value set, then raises a KeyError.\n def pop(self, k, default=None):\n try:\n value = self[k]\n del self[k]\n return value\n except KeyError:\n if default is not None:\n return default\n else:\n raise KeyError(\"Key not found\")\n","sub_path":"ch10maps/R-10.1.py","file_name":"R-10.1.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"370543809","text":"from ConfigSpace import ConfigurationSpace\nfrom ConfigSpace.hyperparameters import UniformFloatHyperparameter\nfrom multiprocessing import Process\nfrom smac.epm.gaussian_gradient_epm import GaussianGradientEPM\nfrom smac.facade.smac_facade import SMAC\nfrom smac.optimizer.objective import average_cost\nfrom smac.runhistory.runhistory import RunHistory\nfrom smac.runhistory.runhistory2epm import RunHistory2EPM4Cost\nfrom smac.scenario.scenario import Scenario\nfrom smac.tae.execute_ta_run import StatusType\nfrom smac.tae.execute_ta_customized import CustomizedTA\nfrom smac.epm.hoag.dummy_hoag import DummyHOAG\n#from smac.pssmac.ps_server import Server\nimport numpy as np\nimport typing\n\n\nclass OurSMAC(Process):\n def __init__(self,\n X_train: np.ndarray,\n y_train: np.ndarray,\n X_valid: np.ndarray,\n y_valid: np.ndarray,\n dirs: typing.List[str],\n smbo_id: int,\n #server: Server = None,\n cs: ConfigurationSpace = None,\n our_work: bool = False):\n if smbo_id >= len(dirs):\n raise ValueError(\"SMBO ID exceeds size of the pool.\")\n super().__init__()\n # 创建一个ta函数\n ta = CustomizedTA(X_train, y_train, X_valid, y_valid)\n # 如果未指定configspace,则赋值默认\n if cs is None:\n cs = ConfigurationSpace()\n # 超参搜索空间,使用[1e-6, 1]\n alpha = UniformFloatHyperparameter(name=\"alpha\", lower=1e-3,\n upper=1,\n default_value=1, log=False)\n cs.add_hyperparameters([alpha])\n\n # 创建scenario\n scenario_dict = {\n \"cs\": cs,\n \"run_obj\": \"quality\",\n \"cutoff_time\": 100,\n \"shared_model\": True if len(dirs) > 1 else False,\n #\"initial_incumbent\": 'RANDOM\"\n \"input_psmac_dirs\": dirs,\n \"output_dir\": dirs[smbo_id]\n }\n\n scenario = Scenario(scenario_dict)\n\n runhistory = RunHistory(aggregate_func=average_cost)\n runhistory2epm = RunHistory2EPM4Cost(scenario=scenario,\n num_params=1,\n success_states=[\n StatusType.SUCCESS,\n StatusType.CRASHED],\n impute_censored_data=False,\n impute_state=None)\n\n # 创建smac\n if our_work is not None:\n # 读入梯度信息\n with open(our_work, \"r\") as fp:\n lines = fp.readlines()\n # 计算loss的值\n loss = [float(line.strip().split()[0]) for line in lines]\n gradient = []\n for i in range(1, len(loss)):\n gradient.append((loss[i] - loss[i - 1]) * len(loss))\n hoag = DummyHOAG(0.00095, 1, np.array(gradient))\n # 创建epm\n gpr = GaussianGradientEPM\n self.smac = SMAC(\n scenario=scenario,\n tae_runner=ta,\n model=gpr(),\n hoag=hoag,\n runhistory2epm=runhistory2epm,\n runhistory=runhistory,\n #server=server\n )\n else:\n self.smac = SMAC(scenario=scenario, tae_runner=ta,\n runhistory2epm=runhistory2epm,\n runhistory=runhistory)\n #server=server)\n\n # 进程类固定名字run\n def run(self):\n self.smac.optimize()\n","sub_path":"smac/facade/oursmac_facade.py","file_name":"oursmac_facade.py","file_ext":"py","file_size_in_byte":3749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"115277290","text":"from collections import defaultdict\nfrom itertools import permutations\n\nfrom indra.assemblers.english import EnglishAssembler\nfrom indra.statements import Agent, get_statement_by_name\n\n\ndef _get_keyed_stmts(stmt_list):\n def name(agent):\n return 'None' if agent is None else agent.name\n\n for s in stmt_list:\n # Create a key.\n verb = s.__class__.__name__\n key = (verb,)\n ags = s.agent_list()\n if verb == 'Complex':\n ag_ns = {name(ag) for ag in ags}\n if 1 < len(ag_ns) < 6:\n for pair in permutations(ag_ns, 2):\n yield key + tuple(pair), s\n if len(ag_ns) == 2:\n continue\n key += tuple(sorted(ag_ns))\n elif verb == 'Conversion':\n subj = name(s.subj)\n objs_from = {name(ag) for ag in s.obj_from}\n objs_to = {name(ag) for ag in s.obj_to}\n key += (subj, tuple(sorted(objs_from)), tuple(sorted(objs_to)))\n elif verb == 'ActiveForm':\n key += (name(ags[0]), s.activity, s.is_active)\n elif verb == 'HasActivity':\n key += (name(ags[0]), s.activity, s.has_activity)\n else:\n key += tuple([name(ag) for ag in ags])\n\n yield key, s\n\n\ndef group_and_sort_statements(stmt_list, ev_totals=None):\n \"\"\"Group statements by type and arguments, and sort by prevalence.\n\n Parameters\n ----------\n stmt_list : list[Statement]\n A list of INDRA statements.\n ev_totals : dict{int: int}\n A dictionary, keyed by statement hash (shallow) with counts of total\n evidence as the values. Including this will allow statements to be\n better sorted.\n\n Returns\n -------\n sorted_groups : list[tuple]\n A list of tuples containing a sort key, the statement type, and a list\n of statements, also sorted by evidence count, for that key and type.\n The sort key contains a count of statements with those argument, the\n arguments (normalized strings), the count of statements with those\n arguements and type, and then the statement type.\n \"\"\"\n def _count(stmt):\n if ev_totals is None:\n return len(stmt.evidence)\n else:\n return ev_totals[stmt.get_hash()]\n\n stmt_rows = defaultdict(list)\n stmt_counts = defaultdict(lambda: 0)\n arg_counts = defaultdict(lambda: 0)\n for key, s in _get_keyed_stmts(stmt_list):\n # Update the counts, and add key if needed.\n stmt_rows[key].append(s)\n\n # Keep track of the total evidence counts for this statement and the\n # arguments.\n stmt_counts[key] += _count(s)\n\n # Add up the counts for the arguments, pairwise for Complexes and\n # Conversions. This allows, for example, a complex between MEK, ERK,\n # and something else to lend weight to the interactions between MEK\n # and ERK.\n if key[0] == 'Conversion':\n subj = key[1]\n for obj in key[2] + key[3]:\n arg_counts[(subj, obj)] += _count(s)\n else:\n arg_counts[key[1:]] += _count(s)\n\n # Sort the rows by count and agent names.\n def process_rows(stmt_rows):\n for key, stmts in stmt_rows.items():\n verb = key[0]\n inps = key[1:]\n sub_count = stmt_counts[key]\n arg_count = arg_counts[inps]\n if verb == 'Complex' and sub_count == arg_count and len(inps) <= 2:\n if all([len(set(ag.name for ag in s.agent_list())) > 2\n for s in stmts]):\n continue\n new_key = (arg_count, inps, sub_count, verb)\n stmts = sorted(stmts,\n key=lambda s: _count(s) + 1/(1+len(s.agent_list())),\n reverse=True)\n yield new_key, verb, stmts\n\n sorted_groups = sorted(process_rows(stmt_rows),\n key=lambda tpl: tpl[0], reverse=True)\n\n return sorted_groups\n\n\ndef make_stmt_from_sort_key(key, verb):\n \"\"\"Make a Statement from the sort key.\n\n Specifically, the sort key used by `group_and_sort_statements`.\n \"\"\"\n def make_agent(name):\n if name == 'None' or name is None:\n return None\n return Agent(name)\n\n StmtClass = get_statement_by_name(verb)\n inps = list(key[1])\n if verb == 'Complex':\n stmt = StmtClass([make_agent(name) for name in inps])\n elif verb == 'Conversion':\n stmt = StmtClass(make_agent(inps[0]),\n [make_agent(name) for name in inps[1]],\n [make_agent(name) for name in inps[2]])\n elif verb == 'ActiveForm' or verb == 'HasActivity':\n stmt = StmtClass(make_agent(inps[0]), inps[1], inps[2])\n else:\n stmt = StmtClass(*[make_agent(name) for name in inps])\n return stmt\n\n\ndef stmt_to_english(stmt):\n \"\"\"Return an English assembled Statement as a sentence.\"\"\"\n ea = EnglishAssembler([stmt])\n return ea.make_model()[:-1]\n\n\ndef make_string_from_sort_key(key, verb):\n \"\"\"Make a Statement string via EnglishAssembler from the sort key.\n\n Specifically, the sort key used by `group_and_sort_statements`.\n \"\"\"\n stmt = make_stmt_from_sort_key(key, verb)\n return stmt_to_english(stmt)\n\n\ndef get_simplified_stmts(stmts):\n simple_stmts = []\n for key, s in _get_keyed_stmts(stmts):\n simple_stmts.append(make_stmt_from_sort_key(key, s.__class__.__name__))\n return simple_stmts\n","sub_path":"indra/util/statement_presentation.py","file_name":"statement_presentation.py","file_ext":"py","file_size_in_byte":5495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"506699439","text":"# libraries\nimport pandas as pd\nimport numpy as np\n\ndef dcg_at_k(r, k, method=1):\n \"\"\"\n Score is discounted cumulative gain (dcg)\n Relevance is positive real values. Can use binary\n as the previous methods.\n Example from\n http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf\n Args:\n r: Relevance scores (list or numpy) in rank order\n (first element is the first item)\n k: Number of results to consider\n method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...]\n If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...]\n Returns:\n Discounted cumulative gain\n\n Source: https://github.com/benhamner/ExpediaPersonalizedSortCompetition\n \"\"\"\n r = np.asfarray(r)[:k]\n if r.size:\n if method == 0:\n return 2**r[0] - 1 + np.sum((2**r[1:]-1) / np.log2(np.arange(2, r.size + 1)))\n elif method == 1:\n return np.sum((2**r - 1) / np.log2(np.arange(2, r.size + 2)))\n else:\n raise ValueError('method must be 0 or 1.')\n return 0.\n\ndef ndcg_at_k(r, k, method=1):\n \"\"\"\n Score is normalized discounted cumulative gain (ndcg)\n Relevance is positive real values. Can use binary\n as the previous methods.\n Example from\n http://www.stanford.edu/class/cs276/handouts/EvaluationNew-handout-6-per.pdf\n Args:\n r: Relevance scores (list or numpy) in rank order\n (first element is the first item)\n k: Number of results to consider\n method: If 0 then weights are [1.0, 1.0, 0.6309, 0.5, 0.4307, ...]\n If 1 then weights are [1.0, 0.6309, 0.5, 0.4307, ...]\n Returns:\n Normalized discounted cumulative gain\n\n Source: https://github.com/benhamner/ExpediaPersonalizedSortCompetition\n \"\"\"\n dcg_max = dcg_at_k(sorted(r, reverse=True), k, method)\n if not dcg_max:\n return 0.\n return dcg_at_k(r, k, method) / dcg_max\n\ndef compute_ndcg(path_results):\n \"\"\"\n path_results is a string containing the path to the .csv file\n which contains the results of the model. The .csv should have\n columns:\n\n SearchId = unique ID for each user\n Relevance = 5 if booked, 1 if clicked\n PropertyId = unique ID for each property\n \"\"\"\n\n # load results and dataset\n results = pd.read_csv(path_results)\n ndcg_list = []\n\n # iterate over all queries\n id_list = results['SearchId'].unique()\n for id in id_list:\n\n # get relevance scores of query\n list_rscores = results['Relevance'][results.SearchId == id]\n\n # number of results to consider\n num_res = len(list_rscores)\n\n # compute ndcg for each query\n ndcg_list.append(ndcg_at_k(list_rscores,num_res))\n return np.mean(ndcg_list)\n","sub_path":"Assignment2/nDCG.py","file_name":"nDCG.py","file_ext":"py","file_size_in_byte":2778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"652307251","text":"class Animal:\n def __init__(self, name, colour):\n self.name = name\n self.colour = colour\n\nclass Dog(Animal):\n def Bark(self):\n print(\" Woof! Woof!\") \n\nclass Cat(Animal):\n def Purr(self):\n print(\" Meow...\")\n\nclass DecideAnimalType:\n def __init__(self, type):\n if type == \"dog\":\n print(\"\\nEnter details of the dog \")\n animal_name = str(input(\" => Name of Dog : \"))\n animal_colour = str(input(\" => Colour of Dog : \"))\n name = Dog(animal_name, animal_colour)\n print(\"\\n Let\\'s hear what the Doggy says... \")\n name.Bark()\n\n if type == \"cat\":\n print(\"\\nEnter details of the cat \")\n animal_name = str(input(\" => Name of Cat : \"))\n animal_colour = str(input(\" => Colour of Cat : \"))\n name = Cat(animal_name, animal_colour)\n print(\"\\n Let\\'s hear what the Cat says... \")\n name.Purr()\n\n input(\"\\n[Press ENTER or RETURN to continue]...\")\n\n print(\"\\n\" + \"-\"*37 + \"\\n\")\n print(\" * Printing Summary of Program *\\n\")\n print(\"- Type of Animal = \" + type)\n print(\"- Name of \" + type + \" = \" + name.name)\n print(\"- Colour of \" + name.name + \" = \" + name.colour)\n print(\" -- Program Finished --\")\n print(\"\\n\" + \"-\"*37 + \"\\n\")\n\ndef main():\n type = str(input(\"Enter type of Animal, [Dog] or [Cat] = \"))\n type = type.lower()\n if type == \"dog\" or \"cat\":\n DecideAnimalType(type)\n else:\n print(\" ** Invalid Input, try again! **\\n\")\n main()\n\nif __name__ == '__main__': \n print(\"\\n --------------------------------------------\")\n print(\" | Demonstration of Classes and Inheritance |\")\n print(\" --------------------------------------------\\n\")\n main()\n ","sub_path":"Class_Inheritance v1.py","file_name":"Class_Inheritance v1.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"416084247","text":"import torch\nfrom .library_functions import AffineFeatureSelectionFunction\n\nOFFSET = 158\n# MARS_FEATURE_SUBSETS = {\n# \"angle_head_body\" : torch.LongTensor([25, 26, OFFSET + 25, OFFSET + 26]),\n# \"axis_ratio\" : torch.LongTensor([29, OFFSET + 29]),\n# \"speed\" : torch.LongTensor([34, 38, OFFSET + 34, OFFSET + 38]),\n# \"acceleration\" : torch.LongTensor([36, OFFSET + 36]),\n# \"resh_twd_itrhb\" : torch.LongTensor([39]),\n# \"velocity\" : torch.LongTensor([62, 63, OFFSET + 62, OFFSET + 63]),\n# \"rel_angle\" : torch.LongTensor([60, 49, 61, OFFSET + 49, OFFSET + 61]),\n# \"rel_dist\" : torch.LongTensor([50, 51, 53, 54]),\n# \"area_ellipse_ratio\" : torch.LongTensor([59])\n# }\nMARS_FEATURE_SUBSETS = {\n \"angle_head_body\" : torch.arange(0, 4, dtype = torch.long),\n \"axis_ratio\" : torch.arange(4, 6, dtype = torch.long),\n \"speed\" : torch.arange(6, 10, dtype = torch.long),\n \"acceleration\" : torch.arange(10, 12, dtype = torch.long),\n \"resh_twd_itrhb\" : torch.arange(12, 13, dtype = torch.long),\n \"velocity\" : torch.arange(13, 17, dtype = torch.long),\n \"rel_angle\" : torch.arange(17, 22, dtype = torch.long),\n \"rel_dist\" : torch.arange(22, 26, dtype = torch.long),\n \"area_ellipse_ratio\" : torch.arange(26, 27, dtype = torch.long)\n}\n\nMARS_INDICES = [25, 26, OFFSET + 25, OFFSET + 26, 29, OFFSET + 29, 34, 38, OFFSET + 34, OFFSET + 38, 36, OFFSET + 36, \\\n 39, 62, 63, OFFSET + 62, OFFSET + 63, 60, 49, 61, OFFSET + 49, OFFSET + 61, 50, 51, 53, 54, 59]\nMARS_FULL_FEATURE_DIM = len(MARS_INDICES)\n# MARS_FULL_FEATURE_DIM = 316\n\nclass MarsAngleHeadBodySelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"angle_head_body\"]\n super().__init__(input_size, output_size, num_units, name=\"AngleHeadBodySelect\")\n\nclass MarsAxisRatioSelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"axis_ratio\"]\n super().__init__(input_size, output_size, num_units, name=\"AxisRatioSelect\")\n\nclass MarsSpeedSelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"speed\"]\n super().__init__(input_size, output_size, num_units, name=\"SpeedSelect\")\n\nclass MarsVelocitySelection(AffineFeatureSelectionFunction):\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"velocity\"]\n super().__init__(input_size, output_size, num_units, name=\"VelocitySelect\")\n\nclass MarsAccelerationSelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"acceleration\"]\n super().__init__(input_size, output_size, num_units, name=\"AccelerationSelect\")\n\nclass MarsResidentTowardIntruderSelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"resh_twd_itrhb\"]\n super().__init__(input_size, output_size, num_units, name=\"ResidentTowardIntruderSelect\")\n\nclass MarsRelAngleSelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"rel_angle\"]\n super().__init__(input_size, output_size, num_units, name=\"RelativeAngleSelect\")\n\nclass MarsRelDistSelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"rel_dist\"]\n super().__init__(input_size, output_size, num_units, name=\"RelativeDistanceSelect\")\n\nclass MarsAreaEllipseRatioSelection(AffineFeatureSelectionFunction):\n\n def __init__(self, input_size, output_size, num_units):\n self.full_feature_dim = MARS_FULL_FEATURE_DIM\n self.feature_tensor = MARS_FEATURE_SUBSETS[\"area_ellipse_ratio\"]\n super().__init__(input_size, output_size, num_units, name=\"AreaEllipseRatioSelect\")","sub_path":"pro_near/dsl/mars.py","file_name":"mars.py","file_ext":"py","file_size_in_byte":4590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"460577895","text":"import textwrap\n\nimport pytest\n\nfrom conans.test.utils.tools import TestClient\n\n\n@pytest.mark.tool_cmake\n@pytest.mark.parametrize(\"package\", [\"hello\", \"ZLIB\"])\n@pytest.mark.parametrize(\"find_package\", [\"module\", \"config\"])\ndef test_cmaketoolchain_path_find(package, find_package):\n \"\"\"Test with user \"Hello\" and also ZLIB one, to check that package ZLIB\n has priority over the CMake system one\n\n Also, that user cmake files in the root are accessible via CMake include()\n \"\"\"\n client = TestClient()\n conanfile = textwrap.dedent(\"\"\"\n from conans import ConanFile\n class TestConan(ConanFile):\n exports = \"*\"\n def layout(self):\n pass\n def package(self):\n self.copy(pattern=\"*\", keep_path=False)\n \"\"\")\n find = textwrap.dedent(\"\"\"\n SET({package}_FOUND 1)\n MESSAGE(\"HELLO FROM THE {package} FIND PACKAGE!\")\n \"\"\").format(package=package)\n myowncmake = textwrap.dedent(\"\"\"\n MESSAGE(\"MYOWNCMAKE FROM {package}!\")\n \"\"\").format(package=package)\n\n filename = \"{}Config.cmake\" if find_package == \"config\" else \"Find{}.cmake\"\n filename = filename.format(package)\n client.save({\"conanfile.py\": conanfile,\n \"{}\".format(filename): find,\n \"myowncmake.cmake\": myowncmake})\n client.run(\"create . {}/0.1@\".format(package))\n\n consumer = textwrap.dedent(\"\"\"\n set(CMAKE_CXX_COMPILER_WORKS 1)\n set(CMAKE_CXX_ABI_COMPILED 1)\n project(MyHello CXX)\n cmake_minimum_required(VERSION 3.15)\n\n find_package({package} REQUIRED)\n include(myowncmake)\n \"\"\").format(package=package)\n\n client.save({\"CMakeLists.txt\": consumer}, clean_first=True)\n client.run(\"install {}/0.1@ -g CMakeToolchain\".format(package))\n with client.chdir(\"build\"):\n client.run_command(\"cmake .. -DCMAKE_TOOLCHAIN_FILE=../conan_toolchain.cmake\")\n assert \"Conan: Target declared\" not in client.out\n assert \"HELLO FROM THE {package} FIND PACKAGE!\".format(package=package) in client.out\n assert \"MYOWNCMAKE FROM {package}!\".format(package=package) in client.out\n\n # If using the CMakeDeps generator, the in-package .cmake will be ignored\n # But it is still possible to include(owncmake)\n client.run(\"install {}/0.1@ -g CMakeToolchain -g CMakeDeps\".format(package))\n with client.chdir(\"build2\"): # A clean folder, not the previous one, CMake cache doesnt affect\n client.run_command(\"cmake .. -DCMAKE_TOOLCHAIN_FILE=../conan_toolchain.cmake\")\n assert \"Conan: Target declared '{package}::{package}'\".format(package=package) in client.out\n assert \"HELLO FROM THE {package} FIND PACKAGE!\".format(package=package) not in client.out\n assert \"MYOWNCMAKE FROM {package}!\".format(package=package) in client.out\n\n\n@pytest.mark.tool_cmake\ndef test_cmaketoolchain_path_find_real_config():\n client = TestClient()\n conanfile = textwrap.dedent(\"\"\"\n from conans import ConanFile\n from conan.tools.cmake import CMake\n class TestConan(ConanFile):\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n exports = \"*\"\n generators = \"CMakeToolchain\"\n\n def layout(self):\n pass\n\n def build(self):\n cmake = CMake(self)\n cmake.configure()\n\n def package(self):\n cmake = CMake(self)\n cmake.install()\n \"\"\")\n cmake = textwrap.dedent(\"\"\"\n cmake_minimum_required(VERSION 3.15)\n project(MyHello NONE)\n\n add_library(hello INTERFACE)\n install(TARGETS hello EXPORT helloConfig)\n export(TARGETS hello\n NAMESPACE hello::\n FILE \"${CMAKE_CURRENT_BINARY_DIR}/helloConfig.cmake\"\n )\n install(EXPORT helloConfig\n DESTINATION \"${CMAKE_INSTALL_PREFIX}/hello/cmake\"\n NAMESPACE hello::\n )\n \"\"\")\n client.save({\"conanfile.py\": conanfile,\n \"CMakeLists.txt\": cmake})\n client.run(\"create . hello/0.1@\")\n\n consumer = textwrap.dedent(\"\"\"\n project(MyHello NONE)\n cmake_minimum_required(VERSION 3.15)\n\n find_package(hello REQUIRED)\n \"\"\")\n\n client.save({\"CMakeLists.txt\": consumer}, clean_first=True)\n client.run(\"install hello/0.1@ -g CMakeToolchain\")\n with client.chdir(\"build\"):\n client.run_command(\"cmake .. -DCMAKE_TOOLCHAIN_FILE=../conan_toolchain.cmake\")\n # If it didn't fail, it found the helloConfig.cmake\n assert \"Conan: Target declared\" not in client.out\n\n # If using the CMakeDeps generator, the in-package .cmake will be ignored\n # But it is still possible to include(owncmake)\n client.run(\"install hello/0.1@ -g CMakeToolchain -g CMakeDeps\")\n with client.chdir(\"build2\"): # A clean folder, not the previous one, CMake cache doesnt affect\n client.run_command(\"cmake .. -DCMAKE_TOOLCHAIN_FILE=../conan_toolchain.cmake\")\n assert \"Conan: Target declared 'hello::hello'\" in client.out\n\n","sub_path":"conans/test/functional/toolchains/cmake/test_cmaketoolchain_paths.py","file_name":"test_cmaketoolchain_paths.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"375803091","text":"# Definition for singly-linked list.\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n\n def isPalindrome(self, head):\n \"\"\"\n Given a singly linked list, determine if it is a palindrome.\n\n Runtime: 84 ms, faster than 37.27% of Python3 online submissions for Palindrome Linked List.\n Memory Usage: 24.2 MB, less than 7.69% of Python3 online submissions for Palindrome Linked List.\n\n\n Parameters\n ----------\n head : ListNode\n\n\n Returns\n -------\n ret : bool\n\n \"\"\"\n\n if not head:\n return True\n if not head.next:\n return True\n try:\n hare = head.next.next\n except AttributeError:\n if head.val == head.next.val:\n return True\n return False\n tortoise = head.next\n head.next = None\n while hare and hare.next:\n n_p = tortoise.next\n tortoise.next = head\n head = tortoise\n tortoise = n_p\n hare = hare.next.next\n # Odd number of nodes\n if hare:\n tortoise = tortoise.next\n while head:\n if head.val != tortoise.val:\n return False\n head = head.next\n tortoise = tortoise.next\n return True\n\n\nif __name__ == \"__main__\":\n a = ListNode(1)\n b = ListNode(2)\n c = ListNode(2)\n d = ListNode(1)\n\n a.next = b\n b.next = c\n c.next = d\n\n print(Solution().isPalindrome(a))\n\n a = ListNode(1)\n b = ListNode(2)\n c = ListNode(3)\n d = ListNode(2)\n e = ListNode(1)\n\n a.next = b\n b.next = c\n c.next = d\n d.next = e\n\n print(Solution().isPalindrome(a))","sub_path":"algorithms/234_Palindrome_Linked_List.py","file_name":"234_Palindrome_Linked_List.py","file_ext":"py","file_size_in_byte":1778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"637210405","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import division\n\nfrom numpy import pi\nfrom numpy import linspace\nfrom numpy import column_stack\nfrom numpy import sin\nfrom numpy import cos\nfrom numpy import arange\nfrom numpy import reshape\nfrom numpy import zeros\nfrom numpy.random import random\nfrom scipy.interpolate import splprep\nfrom scipy.interpolate import splev\n\n\nTWOPI = pi*2\nHPI = pi*0.5\n\n\nclass Sand(object):\n def __init__(\n self,\n size,\n noise_stp,\n grains,\n inum\n ):\n\n self.itt = 0\n\n self.size = size\n self.one = 1.0/size\n self.inum = inum\n self.noise_stp = noise_stp\n\n self.grains = grains\n\n self.xy = []\n self.interpolated_xy = []\n self.noise = []\n self.snums = []\n\n def init(self, xy):\n snum = len(xy)\n self.snums.append(snum)\n interp = self._interpolate(xy, self.inum)\n noise = zeros((snum,1), 'float')\n self.noise.append(noise)\n self.xy.append(xy)\n self.interpolated_xy.append(interp)\n\n def _interpolate(self, xy, num_points):\n tck,u = splprep([\n xy[:,0],\n xy[:,1]],\n s=0\n )\n unew = linspace(0, 1, num_points)\n out = splev(unew, tck)\n return column_stack(out)\n\n def draw(self, render):\n for xy in self.interpolated_xy:\n points = column_stack((xy[1:,:], xy[:-1,:]))\n render.sandstroke(points,self.grains)\n\n def step(self):\n self.itt+=1\n\n inum = self.inum\n one = self.one\n noise_stp = self.noise_stp\n\n new_interpolated = []\n\n for snum,xy,noise in zip(self.snums, self.xy, self.noise):\n\n r = (1.0-2.0*random((snum,1)))\n scale = reshape(arange(snum).astype('float'), (snum,1))\n noise[:] += r*scale*noise_stp\n\n a = random(snum)*TWOPI\n rnd = column_stack((cos(a), sin(a)))\n xy[:,:] += rnd * one*noise\n new_interpolated.append(self._interpolate(xy,inum))\n\n self.interpolated_xy = new_interpolated\n\n return True\n\n","sub_path":"_sandSpline/modules/sand.py","file_name":"sand.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"483329336","text":"\"\"\"\nThis module provides a helper object to manage an updateable timechart search\nthrough the export API which doesn't support aggregated live searches.\n\nNOTE: IF you stumbled upon this, know that this is pretty much just a POC/playground.\n\"\"\"\n\nimport json\nfrom threading import Lock\n\nimport pandas as pd\nimport structlog\n\nfrom snaptime import snap\n\nfrom .utils import humio_to_timeseries, parse_ts\n\nlogger = structlog.getLogger(__name__)\n\n\nclass WindowedTimeseries:\n \"\"\"\n Define an aggregated search for timeseries data in the spesified time\n window which may be static or moving (with relative timestamps).\n\n Parameters\n ----------\n api : humiocore.HumioAPI\n An API instance for interacting with Humio\n query : string\n A Humio query string to execute\n repos : list\n A list of repositories to search against\n start : string\n A snaptime-token (-1h@h) or timestring to search after\n end : string\n A snaptime-token (@h) or timestring to search before\n freq : str\n A pandas frequency string to use when calculating missing buckets.\n This *must* correspond to the frequency used in the Humio search.\n timefield : str, optional\n The name of the timestamp field in the search result, by default \"_bucket\"\n datafields : list, optional\n A list of all data fields (\"columns\") in the search result, by default None\n which means all fields remaining after groupby are used.\n groupby : list, optional\n A list of all groupby fields (\"series\") in the search result, by default None\n which means no grouping is performed.\n title : str, optional\n A title identifying this search - use however you like, by default \"\"\n cutoff_start : str, optional\n An unsigned snaptime-token to cutoff the head of the final DataFrame, by default \"0m\"\n cutoff_end : str, optional\n An unsigned snaptime-token to cutoff the tail of the final DataFrame, by default \"0m\"\n trusted_pickle : string, optional\n A path to a trusted pickle-file to save/load the DataFrame, by default None\n \"\"\"\n\n def __init__(\n self,\n api,\n query,\n repos,\n start,\n end,\n freq,\n timefield=\"_bucket\",\n datafields=None,\n groupby=None,\n title=\"\",\n cutoff_start=\"0m\",\n cutoff_end=\"0m\",\n trusted_pickle=None,\n ):\n self.api = api\n self.query = query\n self.repos = repos\n self.start = start\n self.end = end\n\n self.freq = freq\n self.timefield = timefield\n self.datafields = datafields\n self.groupby = groupby\n self.title = title\n self.cutoff_start = cutoff_start\n self.cutoff_end = cutoff_end\n\n self.data = pd.DataFrame()\n self.trusted_pickle = trusted_pickle\n self._metadata = {}\n self.lock = Lock()\n\n if self.trusted_pickle:\n self.load_df()\n\n logger.debug(\n \"Initialized search object definition\",\n start=self.start,\n end=self.end,\n event_count=len(self.data),\n )\n\n def copyable_attributes(self, ignore=None):\n \"\"\"\n Provieds all instance attributes that can be considered copyable\n\n Parameters\n ----------\n ignore : list, optional\n A list of attributes to ignore, by default all non-copyable keys\n\n Returns\n -------\n dict\n A dictionary of all copyable keys\n \"\"\"\n if ignore is None:\n ignore = [\"api\", \"data\", \"trusted_pickle\", \"lock\", \"_metadata\"]\n return {k: v for k, v in self.__dict__.items() if k not in ignore}\n\n def sanity_check(self):\n # Check that the searchstring span is equal to the pandas freq\n pass\n\n def load_df(self):\n \"\"\"Loads and unpickles a trusted pickled pd.DataFrame\"\"\"\n\n try:\n with open(self.trusted_pickle + \".meta\", \"r\") as metafile:\n meta = json.load(metafile)\n\n for key, value in self.copyable_attributes().items():\n if key in meta and value != meta[key]:\n logger.info(\n \"Search has changed since DataFrame was pickled\",\n parameter=key,\n stored_value=meta[key],\n current_value=value,\n )\n self.data = pd.DataFrame()\n return\n\n self.data = pd.read_pickle(self.trusted_pickle + \".pkl\")\n logger.debug(\n \"Loaded pickled data from file\",\n event_count=len(self.data),\n pickle=self.trusted_pickle + \".pkl\",\n )\n except FileNotFoundError:\n pass\n\n def save_df(self):\n \"\"\"Saves a pickled `pd.DataFrame` to file\"\"\"\n with open(self.trusted_pickle + \".meta\", \"w\") as metafile:\n json.dump(self.copyable_attributes(), metafile)\n self.data.to_pickle(self.trusted_pickle + \".pkl\")\n logger.debug(\n \"Saved pickled data to file\",\n event_count=len(self.data),\n pickle=self.trusted_pickle + \".pkl\",\n )\n\n def current_refresh_window(self):\n \"\"\"Returns the smallest possible search window required to update missing data\n\n Returns:\n (`pd.Timestamp`, `pd.Timestamp`)\n \"\"\"\n\n # Shrink the search window according to the cutoffs and generate all buckets\n # that should appear in the current DataFrame\n wanted_buckets = pd.date_range(\n snap(parse_ts(self.start), \"+\" + self.cutoff_start),\n snap(parse_ts(self.end), \"-\" + self.cutoff_end),\n freq=self.freq,\n closed=\"left\",\n )\n missing = wanted_buckets.difference(self.data.index.dropna(how=\"all\").unique())\n\n if missing.empty:\n logger.debug(\n \"Calculated minimum required search range and found no missing buckets\",\n current_start=self.data.index.min(),\n current_stop=self.data.index.max(),\n wanted_start=wanted_buckets.min(),\n wanted_stop=wanted_buckets.max(),\n )\n return None, None\n\n # Expand the search window again according to the cutoffs\n start = snap(missing.min(), \"-\" + self.cutoff_start)\n end = snap(missing.max() + pd.Timedelta(self.freq), \"+\" + self.cutoff_end)\n\n logger.debug(\n \"Calculated minimum required search range\",\n current_start=self.data.index.min(),\n current_stop=self.data.index.max(),\n wanted_start=wanted_buckets.min(),\n wanted_stop=wanted_buckets.max(),\n next_start=start,\n next_stop=end,\n )\n return start, end\n\n def update(self):\n \"\"\"\n Find and update missing data in the current `pd.DataFrame` according\n to the start and end timestamps. Optionally load and save a pickled\n `pd.DataFrame` to file.\n\n Concurrent calls will return non-blocking until the first call\n has completed its update request.\n\n Returns: None\n \"\"\"\n\n if self.trusted_pickle:\n self.load_df()\n\n if self.lock.acquire(blocking=False):\n try:\n start, end = self.current_refresh_window()\n if all([start, end]):\n new_data = list(self.api.streaming_search(self.query, self.repos, start, end))\n\n if new_data:\n logger.info(\"Search returned new data\", events=len(new_data))\n data = humio_to_timeseries(\n new_data,\n timefield=self.timefield,\n datafields=self.datafields,\n groupby=self.groupby,\n )\n self.data = data.combine_first(self.data)\n\n else:\n logger.warn(\"Search didnt return any data\")\n else:\n logger.info(\"Data is already current. Not fetching new data.\")\n\n # Clean up data outside the current search window, adjusted with the cutoffs\n self.data = self.data[\n (self.data.index >= str(snap(parse_ts(self.start), \"+\" + self.cutoff_start)))\n & (self.data.index < str(snap(parse_ts(self.end), \"-\" + self.cutoff_end)))\n ]\n\n if self.trusted_pickle:\n self.save_df()\n finally:\n self.lock.release()\n else:\n logger.info(\"Data update already in progress in another thread\", lock=self.lock)\n","sub_path":"humiocore/timeseries.py","file_name":"timeseries.py","file_ext":"py","file_size_in_byte":8840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"624518174","text":"from __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport sys\nfrom os import path\nfrom argparse import ArgumentParser\nimport logging\n\nsys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))) + '/utils/')\nsys.path.append(path.dirname(path.dirname(path.dirname(path.abspath(__file__)))) +\n '/LOGISTIC_REGRESSION/')\n\nfrom algorithm_utils import StateData, set_algorithms_output_data\nfrom log_regr_lib import PREC\n\n\ndef termination_condition(global_state, max_iter):\n delta = global_state['delta']\n iter = global_state['iter']\n if delta < PREC or iter >= max_iter:\n set_algorithms_output_data('STOP')\n else:\n set_algorithms_output_data('CONTINUE')\n\n\ndef main():\n # Parse arguments\n parser = ArgumentParser()\n parser.add_argument('-prev_state_pkl', required=True,\n help='Path to the pickle file holding the previous state.')\n parser.add_argument('-max_iter', type=int, required=True, help='Maximum number of iterations.')\n args, unknown = parser.parse_known_args()\n fname_prev_state = path.abspath(args.prev_state_pkl)\n max_iter = args.max_iter\n\n global_state = StateData.load(fname_prev_state).data\n termination_condition(global_state, max_iter)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Exareme-Docker/src/mip-algorithms/LOGISTIC_REGRESSION/termination_condition/global.py","file_name":"global.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"533984638","text":"## Conversion from key to address ##\nimport os\nimport hashlib\nimport base58\nimport ecdsa\nimport binascii\nfrom six import b\n\nclass identity:\n \"\"\" \n Class with keys and encoded address. \n Must be initialized with private_key(hex or wif format).\n \"\"\"\n def __init__(self, priv=None, pub=None, wif=None, addr=None, addr_c=None, mainnet=True):\n self.privkey = b(priv) if isinstance(priv,str) else priv\n self.privkey_wif = b(wif) if isinstance(wif,str) else wif\n self.pubkey = b(pub) if isinstance(pub,str) else pub\n self.pub_compressed = None\n self.addr = b(addr) if isinstance(addr,str) else addr\n self.addr_compressed = b(addr_c) if isinstance(addr_c,str) else addr_c\n self.signkey = None\n self.verkey = None\n self.mainnet = mainnet\n\n def init_priv(self, private_key=None, wif=None):\n if private_key is None:\n assert(wif is not None),\"Missing argument: key!\"\n self.privkey_wif = b(wif) if isinstance(wif,str) else wif\n self.privkey = self.wif2privkey()\n self.get_privkey()\n else:\n self.privkey = b(private_key) if isinstance(private_key,str) else private_key\n if wif is None: \n self.privkey_wif = self.privkey2wif() \n else:\n self.privkey_wif = b(wif) if isinstance(wif,str) else wif\n\n #key = str(self.privkey)\n self.signkey = ecdsa.SigningKey.from_string(self.privkey, curve=ecdsa.SECP256k1)\n self.verkey = self.signkey.get_verifying_key()\n self.pubkey = b\"04\" + binascii.hexlify(self.verkey.to_string())\n self.pub_compressed = self.compress_pub()\n #self.pubkey = binascii.hexlify(self.verkey.to_string()) #pubkey ==\n #self.pubkey = b\"04\" + self.verkey #binascii.hexlify(self.verkey.to_string())\n #self.addr = self.pubkey2addr(self.pubkey.to_string())\n self.pub2addr(self.pubkey)\n self.pub2addr(self.pub_compressed)\n\n def pub2addr_compress(self, key, main=True): \n #input string/bytes, output string\n self.mainnet = main\n pubkey = b(key) if isinstance(key,str) else key\n if len(pubkey) == 130:\n pb_comp = self.compress_pub(pubkey[2:])\n elif len(pubkey) == 128:\n pb_comp = self.compress_pub(pubkey)\n else:\n print(\"error!! key length neither 130 nor 128\")\n ripemd = hashlib.new('ripemd160')\n #ripemd.update(hashlib.sha256(binascii.unhexlify(pubkey)).digest())\n ripemd.update(hashlib.sha256(binascii.unhexlify(pb_comp)).digest())\n key = ripemd.digest()\n ad = b\"00\" if self.mainnet else b\"6F\"\n self.addr_compressed = self.encrypt(key,ad)\n return self.get_addr(compressed=True)\n '''\n if len(pubkey) == 130:\n self.addr = self.encrypt(key, ad)\n return self.get_addr(compressed=False)\n elif len(pubkey) == 66:\n self.addr_compressed = self.encrypt(key, ad)\n return self.get_addr(compressed=True)\n else:\n print(\"Length of key incorrect, must be 130 or 66. Length: %i\" % len(pubkey))\n '''\n def pub2addr(self, key, main=True): \n #input string/bytes, output string\n #self.mainnet = main\n pubkey = b(key) if isinstance(key,str) else key\n if len(pubkey) == 128:\n pubkey = b\"04\" + pubkey\n ripemd = hashlib.new('ripemd160')\n #ripemd.update(hashlib.sha256(binascii.unhexlify(pubkey)).digest())\n ripemd.update(hashlib.sha256(binascii.unhexlify(pubkey)).digest())\n key = ripemd.digest()\n ad = b\"00\" if self.mainnet else b\"6F\"\n self.addr = self.encrypt(key,ad)\n return self.get_addr(compressed=False)\n\n def sign_data(self, data):\n assert (self.signkey is not None), \"No private key provided! Init with private key first.\"\n data = b(data) if isinstance(data, str) else data\n return binascii.hexlify(self.signkey.sign(data))\n\n def verify_data(self, sig_data, orig_data):\n assert (self.verkey is not None), \"No private key provided! Init with private key first.\"\n sig_data = binascii.unhexlify(sig_data)\n orig_data = b(orig_data)\n return self.verkey.verify(sig_data, orig_data)\n \n def compress_pub(self, key=None):\n portion = self.pubkey[2:] if key==None else key\n l = len(portion)\n assert l==128, \"portion length wrong: %i\" % l\n x = portion[:int(l/2)]\n y = portion[int(l/2):]\n assert len(x)==int(l/2) and len(y)==int(l/2), \"x and y wrong length!\"\n if int(binascii.hexlify(y))%2:\n return b\"03\" + x\n else:\n return b\"02\" + x\n\n def privkey2wif(self):\n if self.mainnet:\n return self.encrypt(self.privkey, b\"80\")\n else:\n return self.encrypt(self.privkey, b\"EF\")\n\n def wif2privkey(self):\n print(str(self.privkey_wif)[0])\n ad = base58.b58decode_check(self.privkey_wif)\n print(str(binascii.hexlify(ad), 'ascii'))\n\n if str(self.privkey_wif,'ascii')[0]=='K' or str(self.privkey_wif,'ascii')[0]=='L':\n #print('Compressed wif!')\n return ad[1:-1]\n else:\n #print('Non-compressed wif!')\n return ad[1:]\n\n def encrypt(self, key, ad):\n key = ad + binascii.hexlify(key)\n hash_key = binascii.unhexlify(key)\n checksum = hashlib.sha256(hashlib.sha256(hash_key).digest()).digest()[:4]\n key = key + binascii.hexlify(checksum)\n return base58.b58encode(binascii.unhexlify(key))\n\n def get_keys(self):\n '''Returns key pair and address as tuple'''\n return (binascii.hexlify(self.privkey), self.pubkey, self.addr) \n\n def get_privkey(self):\n return str(binascii.hexlify(self.privkey), 'ascii')\n\n def get_wifkey(self):\n return str(self.privkey_wif, 'ascii')\n\n def get_pubkey(self,compressed):\n if not compressed:\n return str(self.pubkey, 'ascii')#\n else:\n return str(self.pub_compressed, 'ascii')\n #return str(binascii.hexlify(self.pubkey), 'ascii')\n\n def get_addr(self,compressed):\n if not compressed:\n return str(self.addr, 'ascii')\n else:\n return str(self.addr_compressed, 'ascii')\n\n\n# unit tests\nif __name__ == \"__main__\":\n # test1: random generate 32 bytes\n '''pk = os.urandom(32)\n unit = identity(private_key=pk)\n print(\"private key: \", unit.get_privkey())\n print(\"private wif: \", unit.get_wifkey())\n print(\"public key: \", unit.get_pubkey())\n print(\"address:\", unit.get_addr())\n '''\n '''\n pk = '5JdFN2jJvC9bCuN4F9i93RkDqBDBqcyinpzBRmnW8xXiXsnGmHT'\n data = \"this is a bunch of test messages\"\n unit = identity()\n unit.init_priv(wif=pk)\n print(\"private key: \", unit.get_privkey())\n print(\"private wif: \", unit.get_wifkey())\n pb = unit.get_pubkey()\n print(\"public key: \", pb)#unit.get_pubkey())\n print(\"address:\", unit.get_addr())\n sig = unit.sign_data(data)\n print(\"signed data: \", str(sig, 'ascii'))\n print(\"verifying: \", unit.verify_data(sig, data))\n '''\n #wif = 'L1uyy5qTuGrVXrmrsvHWHgVzW9kKdrp27wBC7Vs6nZDTF2BRUVwy'\n #wif = '5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ'\n '''\n unit2 = identity()\n unit2.init_priv(wif=wif)\n addr = unit2.get_addr()\n print(\"testing new function: \", addr)'''\n # test2: input 32 bytes string\n '''\n pk = 'this is my key!!'\n unit = identity(pk, bin=False)\n print(\"private key: \", unit.get_privkey())\n print(\"public key: \", unit.get_pubkey())\n print(\"address:\", unit.get_addr())\n unit3 = identity(mainnet=False)\n wif = 'L3ChN4SuZpRD4oXgMyDxoVkGzxtroas5D67hdA5EmjZ82Vi9kCas'\n #wif = '5HqAEzhde6Qqc5w6Eu1yHqCkEGspdbHpbPZLYxEXicxzuAp3yhC'\n unit3.init_priv(wif=wif)\n print(\"privkey: %s\" %(unit3.get_privkey()))\n pb1 = unit3.get_pubkey(False)\n pb2 = unit3.get_pubkey(True)\n print(\"not compressed pubkey: %s \" %(pb1))\n print(\"compressed pubkey: %s \" %(pb2))\n addr = unit3.get_addr(False)\n print(\"not compressed address: %s\" % addr)\n addr_c = unit3.get_addr(True)\n print(\"compressed address: %s\" % addr_c)\n '''\n key = '04b8117df5139749f1e776cc06e6a32fd3b23acf975029abb827124e101a5417384edbc5aad877f55721f470c35bf910add2a4868134d4273afb42f56368bbd3f2'\n print(len(key))\n unit4 = identity()\n print(\"not compressed: \",unit4.pub2addr(key,True))\n print(\"compressed: \",unit4.pub2addr_compress(key,True))\n key = 'b8117df5139749f1e776cc06e6a32fd3b23acf975029abb827124e101a5417384edbc5aad877f55721f470c35bf910add2a4868134d4273afb42f56368bbd3f2'\n print(\"not compressed: \",unit4.pub2addr(key,True))\n print(\"compressed: \",unit4.pub2addr_compress(key,True))\n #print(unit4.get_addr(True))\n #print(unit4.pub2addr('03919f9806cd4d07b588b14bcf7f5e8466d1c59f3694eb24101bbf59b91f933bfa',True))\n #print(unit4.pub2addr('03919f9806cd4d07b588b14bcf7f5e8466d1c59f3694eb24101bbf59b91f933bfa',False))","sub_path":"crypto/identity.py","file_name":"identity.py","file_ext":"py","file_size_in_byte":9029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"302085297","text":"\"\"\"\nProgrammer: Trinav Bhattacharyya\nDate of Development: 18/10/2020\nThis code has been developed according to the procedures mentioned in the following research article:\nX.-S. Yang, S. Deb, “Cuckoo search via Levy flights”, in: Proc. of\nWorld Congress on Nature & Biologically Inspired Computing (NaBIC 2009),\nDecember 2009, India. IEEE Publications, USA, pp. 210-214 (2009).\n\n\"\"\"\n\n# set the directory path\nimport os,sys\nimport os.path as path\nabs_path_pkg = path.abspath(path.join(__file__ ,\"../../../../\"))\ndir_path = os.path.dirname(os.path.realpath(__file__))\nsys.path.insert(0, abs_path_pkg)\n\n# import other libraries\nimport numpy as np\nfrom sklearn import datasets\nfrom sklearn.model_selection import train_test_split\n\nfrom Py_FS.wrapper.population_based.algorithm import Algorithm\nfrom Py_FS.wrapper.population_based._utilities import Data, compute_fitness, initialize, sort_agents, compute_accuracy, call_counter\nfrom Py_FS.wrapper.population_based._transfer_functions import get_trans_function\n\nclass CS(Algorithm):\n # Cuckoo Search (CS)\n ############################### Parameters ####################################\n # #\n # num_agents: number of agents #\n # max_iter: maximum number of generations #\n # train_data: training samples of data #\n # train_label: class labels for the training samples #\n # test_data (optional): test samples of data #\n # test_label (optional): class labels for the test samples #\n # save_conv_graph (optional): True to save conv graph, else False #\n # seed (optional): seed for our random number generator #\n # default_mode (optional): True to use default values for every #\n # user input #\n # verbose (optional): True to print simulation, else False #\n ###############################################################################\n\n def __init__(self,\n num_agents, \n max_iter, \n train_data, \n train_label, \n test_data=None,\n test_label=None,\n save_conv_graph=False, \n seed=0,\n default_mode=False,\n verbose=True):\n\n super().__init__(num_agents=num_agents,\n max_iter=max_iter,\n train_data=train_data,\n train_label=train_label,\n test_data=test_data,\n test_label=test_label,\n save_conv_graph=save_conv_graph,\n seed=seed,\n default_mode=default_mode,\n verbose=verbose)\n\n self.algo_name='CS'\n self.agent_name='Cuckoo'\n self.trans_function=None\n \n def user_input(self):\n # first set the default values for the attributes\n self.default_vals[\"trans_function\"] = 's'\n self.default_vals[\"p_a\"] = 0.25\n\n # accept the parameters as user inputs (if default_mode not set)\n if self.default_mode:\n self.set_default()\n else: \n self.algo_params['trans_function'] = input(f'Shape of Transfer Function [s/v/u] (default={self.default_vals[\"trans_function\"]}): ') or self.default_vals[\"trans_function\"]\n self.algo_params['p_a'] = float(input(f'Fraction of nests to be replaced [0-1] (default={self.default_vals[\"p_a\"]}): ') or self.default_vals[\"p_a\"])\n \n self.trans_function = get_trans_function(self.algo_params['trans_function'])\n \n def initialize(self):\n #call the base class function\n super().initialize()\n \n self.levy_flight = np.random.uniform(low=-2, high=2, size=(self.num_features))\n self.cuckoo = np.random.randint(low=0, high=2, size=(self.num_features))\n self.cuckoo_fitness = self.obj_function(self.cuckoo,self.training_data)\n \n #rank initial nests\n self.fitness = self.obj_function(self.population,self.training_data)\n self.population,self.fitness = sort_agents(self.population,self.fitness)\n \n def get_cuckoo(self,agent, alpha=np.random.randint(-2,3)):\n features = len(agent)\n lamb = np.random.uniform(low=-3, high=-1, size=(features))\n levy = np.zeros((features))\n get_test_value = 1/(np.power((np.random.normal(0,1)),2))\n for j in range(features):\n levy[j] = np.power(get_test_value, lamb[j])\n for j in range(features):\n agent[j]+=(alpha*levy[j])\n\n return agent\n \n def replace_worst(self,agent, fraction):\n pop, features = agent.shape\n for i in range(int((1-fraction)*pop), pop):\n agent[i] = np.random.randint(low=0, high=2, size=(features))\n if np.sum(agent[i])==0:\n agent[i][np.random.randint(0,features)]=1\n\n return agent\n \n def next(self):\n self.print('\\n================================================================================')\n self.print(' Iteration - {}'.format(self.cur_iter+1))\n self.print('================================================================================\\n')\n \n # get new cuckoo\n self.levy_flight = self.get_cuckoo(self.levy_flight)\n for j in range(self.num_features):\n if self.trans_function(self.levy_flight[j]) > np.random.random():\n self.cuckoo[j]=1\n else:\n self.cuckoo[j]=0\n self.cuckoo_fitness = self.obj_function(self.cuckoo,self.training_data)\n \n # check if a nest needs to be replaced\n j = np.random.randint(0,self.num_agents)\n if self.cuckoo_fitness > self.fitness[j]:\n self.population[j] = self.cuckoo.copy()\n self.fitness[j] = self.cuckoo_fitness\n \n self.fitness = self.obj_function(self.population,self.training_data)\n self.population, self.fitness = sort_agents(self.population,self.fitness)\n \n # eliminate worse nests and generate new ones\n self.population = self.replace_worst(self.population, self.algo_params['p_a'])\n \n self.cur_iter += 1\n \n############# for testing purpose ################\nif __name__ == '__main__':\n data = datasets.load_digits()\n algo = CS(num_agents=20, max_iter=20, train_data=data.data, train_label=data.target, default_mode=True)\n algo.run()\n############# for testing purpose ################","sub_path":"Py_FS/wrapper/population_based/CS.py","file_name":"CS.py","file_ext":"py","file_size_in_byte":6858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"478076021","text":"import hashlib\r\nimport json\r\nimport sys\r\nimport time\r\nfrom urllib import parse\r\nimport requests\r\n\r\ndef get_sign(st,et):\r\n strs = ''\r\n self_param = {'flag': 'Testing', 'method': 'iostock.getList',\r\n 'type': 'json',\r\n 'timestamp': int(time.time()), 'start_time': st,\r\n 'end_time': et, 'page_no': '1',\r\n 'page_size': '100'\r\n }\r\n tmp = sorted(self_param.keys()) # 按照key值排序\r\n for i in tmp:\r\n strs += i + str(self_param[i]) # 存储为字符串secret_key\r\n result = hashlib.md5(strs.encode(encoding='utf-8')) # 将字符串加密\r\n Res = result.hexdigest().upper() # 将字符串以字母/数字表示,并全部大写\r\n # 添加私钥\r\n temp = Res + 'egCFpcGpliNUyIDjtwjNhIJeBSWiSzYJ'\r\n tmp_key = hashlib.md5(temp.encode(encoding='utf-8'))\r\n key = tmp_key.hexdigest().upper()\r\n print('签名返回值:', key)\r\n return key,st,et\r\n\r\ndef get_Iostock(key,st,et):\r\n base_url = 'http://two.erp.taoex.com/index.php/openapi/rpc/service/'\r\n print('11')\r\n param = {'flag': 'Testing','sign': key, 'method': 'iostock.getList',\r\n 'type': 'json',\r\n 'timestamp': int(time.time()), 'start_time': st,\r\n 'end_time': et, 'page_no': '1',\r\n 'page_size': '100'\r\n }\r\n request_param = parse.urlencode(param).encode('utf-8')\r\n print(type(request_param))\r\n\r\n header = {'content-Type': 'application/x-www-form-urlencoded;charset=utf-8'}\r\n response_iostock = requests.post(base_url, data= request_param,headers=header) # post请求\r\n return response_iostock.text\r\n\r\n\r\nif __name__=='__main__':\r\n n,st,et = get_sign('2020-03-03 00:00:00','2020-04-03 19:30:00')#'2020-03-03 00:00:00','2020-04-03 19:30:00'\r\n print(get_Iostock(n,st,et))\r\n","sub_path":"SHYL/接口单侧.py","file_name":"接口单侧.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"100327584","text":"#!usr/bin/python2\n# -*- coding:utf-8 -*-\n\nimport sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nimport os\nimport re\nimport shutil\nimport time\nimport itchat\nfrom itchat.content import *\nimport logging.config\nimport config\nimport sqlite3\nimport datetime\nimport SavedMsg\n\n# NORMAL_MSG = [TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO, FRIENDS]\n# {msg_id:(msg_from,msg_to,msg_time,msg_time_touser,msg_type,msg_content,msg_url)}\nmsg_dict = {}\ntype_dict = {'Recording': '@fil',\n 'Attachment': '@fil',\n 'Video': '@vid',\n 'Picture': '@img'}\ndownload_folder = config.download_folder\nqr_folder = config.qr_folder\nrecalled_file_folder = config.recalled_file_folder\nstatus_storage_folder = config.status_storage_folder\npid_file = config.pid_file\n\nidentifier = None\n\n# log配置文件\nlogging.config.fileConfig('logging.conf')\n# 创建logger\nlogger = logging.getLogger('wechatLogger')\n\n\n\n# 记录正在运行进程的pid\ndef pid_logger(pid, mode='a'):\n info_text = ('追加pid:%d' % pid) if os.path.exists(pid_file) else ('pid.txt文件不存在,创建并追加pid:%d' % pid)\n logger.info(info_text)\n\n with open('./pid.txt', mode) as f:\n f.write('%d\\n' % pid)\n\n\n# 获取下载文件的文件路径\ndef get_download_path(filename):\n global identifier\n\n return download_folder + identifier + '_' + filename\n\n\n# _clear_timeout_msg用于清理消息字典,把超时消息清理掉\n# 为减少资源占用,此函数只在有新消息动态时调用\ndef _clear_timeout_msg():\n if not len(msg_dict):\n return\n\n for msgid in list(msg_dict):\n if time.time() - msg_dict.get(msgid, None)[\"msg_time\"] > 180.0: # 超时三分钟\n item = msg_dict.pop(msgid)\n # print(\"超时的消息:\", item['msg_content'])\n # 可下载类消息,并删除相关文件\n if item['msg_type'] in ['Picture', 'Recording', 'Video', 'Attachment']:\n file_path = get_download_path(item['msg_content'])\n if os.path.exists(file_path):\n # print \"要删除的文件:\", item['msg_content']\n logger.debug('要删除的文件:%s' % file_path)\n os.remove(item['msg_content'])\n else:\n # print '要删除的文件不存在:', item['msg_content']\n logger.debug('要删除的文件不存在:%s' % file_path)\n\n\n# 从接受的信息中获取必要的字段,处理后返回信息字典\ndef _get_saved_msg(msg, chat_type):\n saved_msg = SavedMsg.SavedMsg()\n\n # 展示给用户的,接收消息时的本地时间 2017/03/03 13:23:53\n saved_msg.time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())\n saved_msg.create_time = msg['CreateTime'] # 消息时间\n\n saved_msg.type = msg['Type'] # 消息类型\n if saved_msg.type in ('Text', 'Friends'):\n saved_msg.content = msg['Text']\n elif saved_msg.type == 'Card':\n saved_msg.content = msg['RecommendInfo']['NickName'] + ' 的名片'\n elif saved_msg.type == 'Map':\n x, y, location = re.search(\"', x, ' ', '经度->', y])\n elif saved_msg.has_file():\n # 图片 语音 附件 视频,可下载消息将内容下载暂存到当前目录\n saved_msg.content = msg['FileName']\n msg['Text'](get_download_path(msg['FileName']))\n elif saved_msg.is_sharing():\n saved_msg.content = msg['Text']\n saved_msg.link = msg['Url']\n\n # 根据是否是群聊消息,消息发送人昵称的获取方式有所不同\n if chat_type == 'friendChat':\n friend_name = msg['FromUserName']\n saved_msg.from_user = itchat.search_friends(userName=friend_name)['NickName'] # 消息发送人昵称\n elif chat_type == 'groupChat':\n msg_from = msg.get('ActualNickName', u'Winters先生') # 消息发送人昵称\n group_name = msg['FromUserName']\n msg_group = itchat.search_chatrooms(userName=group_name).get('NickName', u'未保存到通讯录的群') #群名\n saved_msg.group_name = msg_group\n saved_msg.from_user = msg_from\n else:\n raise Exception('传入的参数msgFrom不符合要求!')\n\n return saved_msg\n\n\n# 将已撤回的消息发给文件传输助手\ndef _send_recalled_msg(saved_msg):\n global identifier\n\n if not saved_msg:\n logger.error('撤回��消息不在本地暂存的消息列表中!')\n return\n\n send_text = saved_msg.get_send_text()\n\n itchat.send(send_text, toUserName='filehelper') # 将撤回消息的通知以及细节发送到文件助手\n # 撤回消息是可保存的文件类型\n if saved_msg.has_file():\n file_name = saved_msg.content\n shutil.move(get_download_path(file_name), recalled_file_folder)\n msg_file = type_dict[saved_msg.type] + '@recalled_file/' + identifier + '_' + file_name\n itchat.send(msg=msg_file, toUserName='filehelper')\n\n logger.debug('msg_send: ---------->' + send_text)\n\n\n# 登录完成后在数据库中插入一条用户数据\ndef _login_callback():\n # 清除二维码文件\n qr_dir = qr_folder + identifier + '.jpg'\n if os.path.exists(qr_dir):\n os.remove(qr_dir)\n logger.debug('清除二维码文件:%s' % qr_dir)\n\n # insert or update\n time_now = str(datetime.datetime.fromtimestamp(time.time()))\n ins_up_sql = \"INSERT OR REPLACE INTO USER (username, isLogin, pid, lastLogin) VALUES ('%s', 1, %d, '%s')\" % (\n identifier, os.getpid(), time_now)\n conn = sqlite3.connect(config.db)\n conn.execute(ins_up_sql)\n conn.commit()\n conn.close()\n\n logger.info('用户:%s 成功登陆' % identifier)\n\n\ndef _exit_callback():\n time_now = str(datetime.datetime.fromtimestamp(time.time()))\n logoff_sql = \"UPDATE USER SET isLogin = 0, pid = -1, lastLogoff = '%s' WHERE username = '%s'\" % (\n time_now, identifier)\n conn = sqlite3.connect(config.db)\n conn.execute(logoff_sql)\n conn.commit()\n conn.close()\n\n logger.info('用户:%s 退出' % identifier)\n\n\n# 判断当前用户是否已经登陆\ndef is_login():\n is_login_sql = \"SELECT isLogin FROM USER WHERE USERNAME = '%s'\" % identifier\n conn = sqlite3.connect(config.db)\n cursor = conn.execute(is_login_sql)\n result = cursor.fetchone()[0]\n conn.close()\n\n return True if result == 1 else False\n\n\n# 将接收到的消息存放在字典中,当接收到新消息时对字典中超时的消息进行清理\n# 没有注册note(通知类)消息,通知类消息一般为:红包 转账 消息撤回提醒等,不具有撤回功能\n# 处理朋友消息\n@itchat.msg_register([TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO, FRIENDS],\n isFriendChat=True)\ndef save_friends_msg(msg):\n msg_id = msg['MsgId'] # 消息ID\n\n saved_msg = _get_saved_msg(msg, 'friendChat')\n # 更新字典\n # {msg_id:(msg_from,msg_time,msg_time_touser,msg_type,msg_content,msg_url)}\n msg_dict.update({msg_id: saved_msg})\n # 清理缓存消息列表\n _clear_timeout_msg()\n\n\n# 处理群消息\n@itchat.msg_register([TEXT, PICTURE, MAP, CARD, SHARING, RECORDING, ATTACHMENT, VIDEO, FRIENDS],\n isGroupChat=True)\ndef save_groups_msg(msg):\n msg_id = msg['MsgId'] # 消息ID\n\n saving_msg = _get_saved_msg(msg, 'groupChat')\n # 更新字典\n # {msg_id:(msg_group,msg_from,msg_time,msg_time_touser,msg_type,msg_content,msg_url)}\n msg_dict.update({msg_id: saving_msg})\n # 清理缓存消息列表\n _clear_timeout_msg()\n\n\n# 收到note类消息,判断是不是撤回并进行相应操作\n@itchat.msg_register([NOTE], isFriendChat=True, isGroupChat=True)\ndef recalled_msg(msg):\n logger.debug(msg['Text'])\n # 创建可下载消息内容的存放文件夹,并将暂存在当前目录的文件移动到该文件中\n if not os.path.exists(download_folder):\n os.mkdir(download_folder)\n\n if re.search(u'.*撤回了一条消息', msg['Text']) is not None:\n if not re.search(u';msgid>(.*?)</msgid', msg['Content']):\n old_msg_id = re.search(u'\\(.*?)\\<\\/msgid\\>', msg['Content']).group(1)\n else:\n old_msg_id = re.search(u';msgid>(.*?)</msgid', msg['Content']).group(1)\n\n # 从暂存的消息列表中获取撤回的消息\n saved_msg = msg_dict.get(old_msg_id)\n # 将撤回的消息发给自己\n _send_recalled_msg(saved_msg)\n msg_dict.pop(old_msg_id)\n _clear_timeout_msg()\n\n\ndef run(username):\n global identifier\n\n identifier = username\n\n if is_login():\n return 1\n\n # 启动程序,并且设置二维码的保存路径\n qr_dir = qr_folder + identifier + '.jpg'\n status_storage_dir = status_storage_folder + identifier + '.pkl'\n\n pid = os.fork()\n # 如果是子进程\n if pid == 0:\n try:\n # 第二次fork避免僵尸进程\n child_pid = os.fork()\n if child_pid > 0:\n # 将第二个子进程pid记录下来\n pid_logger(pid, 'a')\n os._exit(0)\n\n itchat.auto_login(hotReload=True, statusStorageDir=status_storage_dir, enableCmdQR=True, picDir=qr_dir,\n loginCallback=_login_callback, exitCallback=_exit_callback)\n itchat.run()\n\n except Exception:\n logger.exception('username: %s, pid %d' % (username, os.getpid()))\n _exit_callback()\n else:\n # 等待第一个子进程结束\n os.waitpid(pid, 0)\n\n return pid\n\n\nif __name__ == '__main__':\n # 启动程序,并且设置二维码的保存路径\n itchat.auto_login(hotReload=True, enableCmdQR=True, picDir=qr_folder + 'aaa.png')\n itchat.run()\n","sub_path":"fuck_recall.py","file_name":"fuck_recall.py","file_ext":"py","file_size_in_byte":9970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"306667111","text":"from ravestate.module import Module\nfrom ravestate.constraint import s\nfrom ravestate.state import state\nfrom ravestate.wrappers import ContextWrapper\nfrom ravestate_interloc import handle_single_interlocutor_input\nfrom ravestate_ros2.ros2_properties import Ros2SubProperty\n\nfrom reggol import get_logger\nlogger = get_logger(__name__)\n\n\nPYROBOY_AVAILABLE = False\ntry:\n from pyroboy import say\n from roboy_cognition_msgs.msg import RecognizedSpeech\n PYROBOY_AVAILABLE = True\nexcept ImportError as e:\n logger.error(f\"\"\"\n--------\nAn exception occured during imports: {e}\nPlease make sure to have the following items installed & sourced:\n1. ROS2 bouncy\n2. roboy_communication\n3. pyroboy\n--------\n \"\"\")\n\n\nif PYROBOY_AVAILABLE:\n\n with Module(name=\"roboyio\"):\n\n recognized_speech = Ros2SubProperty(\n name=\"recognized_speech\",\n topic=\"/roboy/cognition/speech/recognition\",\n msg_type=RecognizedSpeech,\n always_signal_changed=True)\n\n @state(read=recognized_speech.id())\n def roboy_input(ctx: ContextWrapper):\n handle_single_interlocutor_input(ctx, ctx[recognized_speech.id()].text)\n\n @state(read=\"rawio:out\")\n def roboy_output(ctx):\n ret = say(ctx[\"rawio:out:changed\"])\n logger.info(str(ret))\n","sub_path":"modules/ravestate_roboyio/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"226686923","text":"\n\n#calss header\nclass _DESCENDING():\n\tdef __init__(self,): \n\t\tself.name = \"DESCENDING\"\n\t\tself.definitions = [u'used to refer to a body part that is in a downward direction: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_descending.py","file_name":"_descending.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"561262430","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\bucks\\bucks_tracker.py\n# Compiled at: 2020-07-09 20:42:41\n# Size of source mod 2**32: 33971 bytes\nfrom _collections import defaultdict\nfrom bucks import bucks_handlers\nfrom collections import namedtuple\nfrom contextlib import contextmanager\nfrom protocolbuffers import Dialog_pb2, Consts_pb2\nfrom bucks.bucks_enums import BucksType\nfrom bucks.bucks_perk import BucksPerkTunables\nfrom bucks.bucks_telemetry import bucks_telemetry_writer, TELEMETRY_HOOK_BUCKS_GAIN, TELEMETRY_FIELD_BUCKS_TYPE, TELEMETRY_FIELD_BUCKS_AMOUNT, TELEMETRY_FIELD_BUCKS_TOTAL, TELEMETRY_FIELD_BUCKS_SOURCE, TELEMETRY_HOOK_PERKS_REFUND, TELEMETRY_HOOK_PERKS_GAIN, TELEMETRY_HOOK_BUCKS_SPEND, perks_telemetry_writer\nfrom bucks.bucks_utils import BucksUtils\nfrom clock import interval_in_sim_hours\nfrom date_and_time import DateAndTime\nfrom distributor import shared_messages\nfrom distributor.rollback import ProtocolBufferRollback\nfrom distributor.shared_messages import IconInfoData, create_icon_info_msg\nfrom distributor.system import Distributor\nfrom event_testing.resolver import SingleSimResolver\nfrom event_testing.test_events import TestEvent\nfrom sims4.callback_utils import CallableList\nfrom sims4.tuning.tunable import TunableRange\nimport alarms, caches, clock, services, sims4, telemetry_helper\nlogger = sims4.log.Logger('Bucks', default_owner='tastle')\nPerkData = namedtuple('PerkData', ('unlocked_by', 'timestamp', 'currently_unlocked'))\n\nclass BucksTrackerBase:\n MAX_BUCKS_ALLOWED = TunableRange(description='\\n The max amount of bucks that a tracker is allowed to accrue.\\n ',\n tunable_type=int,\n default=9999999,\n minimum=0,\n maximum=(sims4.math.MAX_INT32))\n\n def __init__(self, owner):\n self._owner = owner\n self._unlocked_perks = {}\n self._bucks = {}\n self._bucks_modified_callbacks = defaultdict(CallableList)\n self._perk_unlocked_callbacks = defaultdict(CallableList)\n self._active_perk_timers = {}\n self._inactive_perk_timers = {}\n self._recently_locked_perks = defaultdict(set)\n for bucks_type in BucksType:\n self._unlocked_perks[bucks_type] = {}\n self._active_perk_timers[bucks_type] = {}\n self._inactive_perk_timers[bucks_type] = {}\n\n def clear_bucks_tracker(self):\n self._unlocked_perks = {}\n self._bucks = {}\n self._bucks_modified_callbacks = defaultdict(CallableList)\n self._perk_unlocked_callbacks = defaultdict(CallableList)\n for bucks_type in BucksType:\n self.deactivate_all_temporary_perk_timers_of_type(bucks_type)\n self._unlocked_perks[bucks_type] = {}\n self._active_perk_timers[bucks_type] = {}\n self._inactive_perk_timers[bucks_type] = {}\n\n def has_bucks_type(self, bucks_type):\n return bucks_type in self._bucks\n\n def get_bucks_amount_for_type(self, bucks_type):\n return self._bucks.get(bucks_type, 0)\n\n def add_bucks_modified_callback(self, bucks_type, callback):\n self._bucks_modified_callbacks[bucks_type].register(callback)\n\n def remove_bucks_modified_callback(self, bucks_type, callback):\n self._bucks_modified_callbacks[bucks_type].unregister(callback)\n\n def add_perk_unlocked_callback(self, bucks_type, callback):\n self._perk_unlocked_callbacks[bucks_type].register(callback)\n\n def remove_perk_unlocked_callback(self, bucks_type, callback):\n self._perk_unlocked_callbacks[bucks_type].unregister(callback)\n\n def has_perk_unlocked_for_bucks_type(self, bucks_type):\n return len(self._unlocked_perks[bucks_type]) > 0\n\n def is_perk_unlocked(self, perk):\n if perk not in self._unlocked_perks[perk.associated_bucks_type]:\n return False\n return self._unlocked_perks[perk.associated_bucks_type][perk].currently_unlocked\n\n def _get_perk_unlock_timestamp(self, perk):\n if not self.is_perk_unlocked(perk):\n return\n perk_data = self._unlocked_perks[perk.associated_bucks_type][perk]\n return perk_data.timestamp\n\n def unlock_perk(self, perk, unlocked_by=None, suppress_telemetry=False):\n self._award_rewards(perk)\n self._award_buffs(perk)\n self._award_loots(perk.loots_on_unlock)\n if perk.temporary_perk_information is not None:\n if not self._set_up_temporary_perk_timer(perk):\n return\n self._perk_unlocked_callbacks[perk.associated_bucks_type](perk)\n timestamp = services.time_service().sim_now\n self._unlocked_perks[perk.associated_bucks_type][perk] = PerkData(unlocked_by, timestamp, True)\n for sim_info in self._owner_sim_info_gen():\n services.get_event_manager().process_event((TestEvent.BucksPerkUnlocked), sim_info=sim_info)\n\n for linked_perk in perk.linked_perks:\n if not self.is_perk_unlocked(linked_perk):\n self.unlock_perk(linked_perk, unlocked_by=perk, suppress_telemetry=suppress_telemetry)\n\n if not suppress_telemetry:\n self._handle_perk_unlock_telemetry(perk)\n caches.clear_all_caches()\n\n def _award_rewards(self, perk, **kwargs):\n if not perk.rewards:\n return\n dummy_sim = next(self._owner.sim_info_gen(), None)\n if dummy_sim is None:\n logger.error('Trying to unlock a Perk for owner {}, but there are no Sims.', self._owner)\n return\n for reward in perk.rewards:\n reward().open_reward(dummy_sim, reward_source=perk)\n\n def _award_loots(self, loot_list):\n resolver = SingleSimResolver(self._owner)\n for loot in loot_list:\n loot.apply_to_resolver(resolver)\n\n def _award_buffs(self, perk):\n if not perk.buffs_to_award:\n return\n for sim_info in self._owner_sim_info_gen():\n for buff in perk.buffs_to_award:\n sim_info.add_buff((buff.buff_type), buff_reason=(buff.buff_reason))\n\n def _owner_sim_info_gen(self):\n yield self._owner\n\n def pay_for_and_unlock_perk(self, perk):\n if self.is_perk_unlocked(perk):\n logger.error('Attempting to unlock a Perk {} for owner {} that has already been unlocked.', perk, self._owner)\n return False\n else:\n self.try_modify_bucks(perk.associated_bucks_type, -perk.unlock_cost) or logger.error('Attempting to unlock a Perk {} for owner {} that they cannot afford.', perk, self._owner)\n return False\n self.unlock_perk(perk)\n if perk.lock_on_purchase is not None:\n for perk_to_lock in perk.lock_on_purchase:\n if self.is_perk_unlocked(perk_to_lock):\n self.lock_perk(perk_to_lock)\n\n active_sim = services.get_active_sim()\n services.get_event_manager().process_event((TestEvent.PerkPurchased), sim_info=(active_sim.sim_info), bucks_type=(perk.associated_bucks_type), perk=perk)\n return True\n\n def lock_perk(self, perk, refund_cost=False, allow_distribute=True):\n if not self.is_perk_unlocked(perk):\n logger.error('Attempting to lock a Perk {} for owner {} that has not been unlocked.', perk, self._owner)\n return\n if perk.temporary_perk_information is not None:\n self.deactivate_temporary_perk_timer(perk, cancel_remaining_time=True)\n if perk.buffs_to_award:\n for sim_info in self._owner_sim_info_gen():\n for buff in perk.buffs_to_award:\n sim_info.remove_buff_by_type(buff.buff_type)\n\n self._award_loots(perk.loots_on_lock)\n if refund_cost:\n self.try_modify_bucks((perk.associated_bucks_type), (perk.unlock_cost), allow_distribute=allow_distribute)\n self._unlocked_perks[perk.associated_bucks_type][perk] = PerkData(None, 0, False)\n self._recently_locked_perks[perk.associated_bucks_type].add(perk)\n self._handle_perk_lock_telemetry(perk)\n\n def lock_all_perks(self, bucks_type, refund_cost=False):\n for perk in list(self._unlocked_perks[bucks_type]):\n self.lock_perk(perk, refund_cost=refund_cost, allow_distribute=False)\n\n self.distribute_bucks(bucks_type)\n\n def activate_stored_temporary_perk_timers_of_type(self, bucks_type):\n if bucks_type not in self._inactive_perk_timers:\n return\n for perk, remaining_ticks in list(self._inactive_perk_timers[bucks_type].items()):\n self._set_up_temporary_perk_timer(perk, remaining_ticks=remaining_ticks)\n del self._inactive_perk_timers[bucks_type][perk]\n\n def deactivate_all_temporary_perk_timers_of_type(self, bucks_type):\n if bucks_type not in self._active_perk_timers:\n return\n for perk in list(self._active_perk_timers[bucks_type]):\n self.deactivate_temporary_perk_timer(perk)\n\n def deactivate_temporary_perk_timer(self, perk, cancel_remaining_time=False):\n if perk in self._active_perk_timers[perk.associated_bucks_type]:\n perk_timer_handle = self._active_perk_timers[perk.associated_bucks_type][perk]\n if perk_timer_handle is not None:\n current_time = services.time_service().sim_now\n remaining_ticks = (perk_timer_handle.finishing_time - current_time).in_ticks()\n if remaining_ticks > 0:\n if not cancel_remaining_time:\n self._inactive_perk_timers[perk.associated_bucks_type][perk] = remaining_ticks\n perk_timer_handle.cancel()\n del self._active_perk_timers[perk.associated_bucks_type][perk]\n else:\n if perk in self._inactive_perk_timers[perk.associated_bucks_type]:\n if cancel_remaining_time:\n del self._inactive_perk_timers[perk.associated_bucks_type][perk]\n\n def _set_up_temporary_perk_timer(self, perk, remaining_ticks=None):\n if perk.temporary_perk_information is None:\n logger.error('Attempting to setup and alarm for a Perk that is not temporary. {}', perk)\n return False\n elif perk in self._active_perk_timers[perk.associated_bucks_type]:\n logger.error('Attempting to add a timer for a temporary Perk that arleady has a timer set up. {}', perk)\n return False\n if remaining_ticks is None:\n time_until_perk_lock = interval_in_sim_hours(perk.temporary_perk_information.duration)\n else:\n time_until_perk_lock = clock.TimeSpan(remaining_ticks)\n perk_timer_handle = alarms.add_alarm(self, time_until_perk_lock, (lambda _: self.lock_perk(perk)), cross_zone=True)\n self._active_perk_timers[perk.associated_bucks_type][perk] = perk_timer_handle\n return True\n\n def all_perks_of_type_gen(self, bucks_type):\n perks_instance_manager = services.get_instance_manager(sims4.resources.Types.BUCKS_PERK)\n for perk in perks_instance_manager.types.values():\n if perk.associated_bucks_type is bucks_type:\n yield perk\n\n def all_perks_of_type_with_lock_state_gen(self, bucks_type, is_unlocked):\n perks_instance_manager = services.get_instance_manager(sims4.resources.Types.BUCKS_PERK)\n for perk in perks_instance_manager.types.values():\n if perk.associated_bucks_type is bucks_type and self.is_perk_unlocked(perk) is is_unlocked:\n yield perk\n\n def get_disabled_tooltip_for_perk(self, perk):\n if perk.temporary_perk_information is not None:\n if perk.temporary_perk_information.unlocked_tooltip is not None:\n return perk.temporary_perk_information.unlocked_tooltip()\n return\n perk_data = self._unlocked_perks[perk.associated_bucks_type][perk]\n if perk_data.unlocked_by is not None:\n return BucksPerkTunables.LINKED_PERK_UNLOCKED_TOOLTIP(perk_data.unlocked_by.display_name())\n return BucksPerkTunables.PERK_UNLOCKED_TOOLTIP()\n\n def send_perks_list_for_bucks_type(self, bucks_type, sort_key=None, reverse=True):\n bucks_msg = Dialog_pb2.GameplayPerkList()\n bucks_msg.bucks_type = bucks_type\n resolver = SingleSimResolver(self._owner)\n perk_messages = []\n for perk in self.all_perks_of_type_gen(bucks_type):\n perk_message = Dialog_pb2.GameplayPerk()\n perk_message.id = perk.guid64\n perk_message.display_name = perk.display_name()\n perk_message.description = self._get_description_string(perk)\n perk_message.icon = create_icon_info_msg(IconInfoData(icon_resource=(perk.icon.key)))\n perk_message.cost = perk.unlock_cost\n if bucks_type not in self._bucks:\n self._bucks[bucks_type] = 0\n perk_message.affordable = self._bucks[bucks_type] >= perk.unlock_cost\n perk_message.ui_display_flags = perk.ui_display_flags\n if perk.required_unlocks is not None:\n locked = False\n for required_perk in perk.required_unlocks:\n if not self.is_perk_unlocked(required_perk):\n locked = True\n perk_message.required_perks.append(required_perk.guid64)\n\n perk_message.locked = locked\n result = perk.available_for_puchase_tests.run_tests(resolver=resolver, search_for_tooltip=True)\n if not result:\n perk_message.locked_from_tests = True\n if result.tooltip is not None:\n perk_message.disabled_tooltip = result.tooltip(self._owner)\n unlocked = self.is_perk_unlocked(perk)\n if unlocked:\n perk_message.purchased = unlocked\n timestamp = self._get_perk_unlock_timestamp(perk)\n if timestamp is not None:\n perk_message.unlock_timestamp = timestamp\n if not unlocked:\n if self.is_perk_recently_locked(perk):\n perk_message.recently_locked = True\n if unlocked:\n disabled_tooltip = self.get_disabled_tooltip_for_perk(perk)\n if disabled_tooltip is not None:\n perk_message.disabled_tooltip = disabled_tooltip\n if perk.lock_on_purchase:\n for perk_to_lock in perk.lock_on_purchase:\n perk_message.lock_on_purchase.append(perk_to_lock.guid64)\n\n if perk.next_level_perk is not None:\n perk_message.next_perk_id = perk.next_level_perk.guid64\n if perk.conflicting_perks is not None:\n for conflicting_perk in perk.conflicting_perks:\n perk_message.conflicting_perks.append(conflicting_perk.guid64)\n\n perk_messages.append(perk_message)\n\n if sort_key is not None:\n perk_messages.sort(key=sort_key, reverse=reverse)\n bucks_msg.perk_list.extend(perk_messages)\n op = shared_messages.create_message_op(bucks_msg, Consts_pb2.MSG_GAMEPLAY_PERK_LIST)\n Distributor.instance().add_op_with_no_owner(op)\n\n def _get_description_string(self, perk):\n if perk.undiscovered_description is None or perk in self._unlocked_perks[perk.associated_bucks_type]:\n return perk.perk_description()\n return perk.undiscovered_description()\n\n def on_all_households_and_sim_infos_loaded(self):\n for bucks_type in self._bucks.keys():\n self.try_modify_bucks(bucks_type, 0)\n\n def on_zone_load(self):\n for bucks_type in self._bucks.keys():\n self.distribute_bucks(bucks_type)\n\n for perk_dict in self._unlocked_perks.values():\n for perk, perk_data in perk_dict.items():\n if perk_data.currently_unlocked:\n self._award_buffs(perk)\n\n def distribute_bucks(self, bucks_type):\n raise NotImplementedError\n\n def is_distributable_tracker(self):\n return True\n\n def try_modify_bucks(self, bucks_type, amount, allow_distribute=True, reason=None, force_refund=False, from_load=False, suppress_telemetry=False, *args, **kwargs):\n if bucks_type in self._bucks:\n new_amount = self._bucks[bucks_type] + amount\n else:\n new_amount = amount\n if new_amount < 0:\n if force_refund:\n perks_to_lock = []\n for recently_unlocked_perk in self._most_recently_acquired_perks_gen(bucks_type):\n new_amount += recently_unlocked_perk.unlock_cost\n perks_to_lock.append(recently_unlocked_perk)\n if new_amount >= 0:\n break\n else:\n return False\n\n for perk in perks_to_lock:\n self.lock_perk(perk, refund_cost=False)\n\n else:\n return False\n new_amount = min(new_amount, self.MAX_BUCKS_ALLOWED)\n self._bucks[bucks_type] = new_amount\n if not from_load:\n if bucks_handlers.archiver.enabled:\n bucks_handlers.add_bucks_data(self._owner, bucks_type, amount, new_amount)\n self._bucks_modified_callbacks[bucks_type]()\n headline = None\n if allow_distribute:\n if self.is_distributable_tracker():\n self.distribute_bucks(bucks_type)\n if not suppress_telemetry:\n (self._handle_modify_bucks_telemetry)(bucks_type, amount, new_amount, *args, source=reason, **kwargs)\n if bucks_type in BucksUtils.BUCK_TYPE_TO_DISPLAY_DATA:\n headline = BucksUtils.BUCK_TYPE_TO_DISPLAY_DATA[bucks_type].headline\n for sim_info in self._owner_sim_info_gen():\n if not from_load:\n services.get_event_manager().process_event((TestEvent.BucksEarned), bucks_type=bucks_type,\n amount=amount,\n sim_info=sim_info)\n if headline is not None and sim_info.is_selectable:\n headline.send_headline_message(sim_info, amount)\n\n return True\n\n def validate_perks(self, bucks_type, current_rank):\n pass\n\n def _most_recently_acquired_perks_gen(self, bucks_type):\n yield from sorted((self._unlocked_perks[bucks_type]), key=(lambda k: self._unlocked_perks[bucks_type][k].timestamp), reverse=True)\n if False:\n yield None\n\n def is_perk_recently_locked(self, perk):\n if perk.associated_bucks_type in self._recently_locked_perks:\n if perk in self._recently_locked_perks[perk.associated_bucks_type]:\n return True\n return False\n\n def reset_recently_locked_perks(self, bucks_type=None):\n if bucks_type is None:\n self._recently_locked_perks.clear()\n return\n if bucks_type in self._recently_locked_perks:\n del self._recently_locked_perks[bucks_type]\n\n def _handle_modify_bucks_telemetry(self, type_gained, amount_gained, new_total, source=None, obj_purchased=None):\n if type_gained is BucksType.INVALID or amount_gained == 0:\n return\n elif obj_purchased is None:\n telemetry_hook = TELEMETRY_HOOK_BUCKS_GAIN if amount_gained >= 0 else TELEMETRY_HOOK_BUCKS_SPEND\n with telemetry_helper.begin_hook(bucks_telemetry_writer, telemetry_hook) as (hook):\n hook.write_int(TELEMETRY_FIELD_BUCKS_TYPE, type_gained)\n hook.write_int(TELEMETRY_FIELD_BUCKS_AMOUNT, abs(amount_gained))\n hook.write_int(TELEMETRY_FIELD_BUCKS_TOTAL, new_total)\n if source is not None:\n hook.write_string(TELEMETRY_FIELD_BUCKS_SOURCE, source)\n else:\n new_total -= amount_gained\n for obj_def_id, purchase_info in obj_purchased.items():\n price = purchase_info['price']\n telemetry_hook = TELEMETRY_HOOK_BUCKS_GAIN if price < 0 else TELEMETRY_HOOK_BUCKS_SPEND\n with telemetry_helper.begin_hook(bucks_telemetry_writer, telemetry_hook) as (hook):\n new_total -= price\n hook.write_int(TELEMETRY_FIELD_BUCKS_TYPE, type_gained)\n hook.write_int(TELEMETRY_FIELD_BUCKS_AMOUNT, abs(price))\n hook.write_int(TELEMETRY_FIELD_BUCKS_TOTAL, new_total)\n if source is not None:\n hook.write_string(TELEMETRY_FIELD_BUCKS_SOURCE, str(obj_def_id))\n\n def _handle_perk_unlock_telemetry(self, perk):\n if perk.associated_bucks_type is BucksType.INVALID:\n return\n new_bucks_total = self.get_bucks_amount_for_type(perk.associated_bucks_type)\n with telemetry_helper.begin_hook(perks_telemetry_writer, TELEMETRY_HOOK_PERKS_GAIN) as (hook):\n hook.write_int(TELEMETRY_FIELD_BUCKS_TYPE, perk.associated_bucks_type)\n hook.write_int(TELEMETRY_FIELD_BUCKS_AMOUNT, perk.unlock_cost)\n hook.write_int(TELEMETRY_FIELD_BUCKS_TOTAL, new_bucks_total)\n hook.write_guid(TELEMETRY_FIELD_BUCKS_SOURCE, perk.guid64)\n\n def _handle_perk_lock_telemetry(self, perk):\n new_bucks_total = self.get_bucks_amount_for_type(perk.associated_bucks_type)\n with telemetry_helper.begin_hook(perks_telemetry_writer, TELEMETRY_HOOK_PERKS_REFUND) as (hook):\n hook.write_int(TELEMETRY_FIELD_BUCKS_TYPE, perk.associated_bucks_type)\n hook.write_int(TELEMETRY_FIELD_BUCKS_AMOUNT, perk.unlock_cost)\n hook.write_int(TELEMETRY_FIELD_BUCKS_TOTAL, new_bucks_total)\n hook.write_guid(TELEMETRY_FIELD_BUCKS_SOURCE, perk.guid64)\n\n def load_data(self, owner_proto):\n bucks_perk_manager = services.get_instance_manager(sims4.resources.Types.BUCKS_PERK)\n for bucks_data in owner_proto.bucks_data:\n self.try_modify_bucks((bucks_data.bucks_type), (bucks_data.amount), allow_distribute=False, from_load=True)\n for perk_data in bucks_data.unlocked_perks:\n perk_ref = bucks_perk_manager.get(perk_data.perk)\n if perk_ref is None:\n logger.info('Trying to load unavailable BUCKS_PERK resource: {}', perk_data.perk)\n continue\n unlocked_by = bucks_perk_manager.get(perk_data.unlock_reason)\n timestamp = DateAndTime(perk_data.timestamp)\n self._unlocked_perks[perk_ref.associated_bucks_type][perk_ref] = PerkData(unlocked_by, timestamp, perk_data.currently_unlocked)\n if not perk_data.currently_unlocked:\n continue\n self._award_buffs(perk_ref)\n if perk_data.time_left:\n self._set_up_temporary_perk_timer(perk_ref, perk_data.time_left)\n\n def save_data(self, owner_msg):\n for bucks_type in BucksType:\n with self._deactivate_perk_timers(bucks_type):\n with ProtocolBufferRollback(owner_msg.bucks_data) as (bucks_data):\n bucks_data.bucks_type = bucks_type\n bucks_data.amount = self._bucks.get(bucks_type, 0)\n for perk, perk_data in self._unlocked_perks[bucks_type].items():\n with ProtocolBufferRollback(bucks_data.unlocked_perks) as (unlocked_perks):\n unlocked_perks.perk = perk.guid64\n unlocked_perks.timestamp = perk_data.timestamp\n unlocked_perks.currently_unlocked = perk_data.currently_unlocked\n if perk_data.unlocked_by is not None:\n unlocked_perks.unlock_reason = perk_data.unlocked_by.guid64\n if perk in self._inactive_perk_timers[bucks_type]:\n unlocked_perks.time_left = self._inactive_perk_timers[bucks_type][perk]\n\n @contextmanager\n def _deactivate_perk_timers(self, bucks_type):\n if self._active_perk_timers[bucks_type]:\n if self._inactive_perk_timers[bucks_type]:\n logger.error('Household {} has both active and inactive temporary Perk timers. This is not expected and will cause save/load issues.', self._owner)\n self.deactivate_all_temporary_perk_timers_of_type(bucks_type)\n had_active_timers = True\n else:\n had_active_timers = False\n try:\n yield\n finally:\n if had_active_timers:\n self.activate_stored_temporary_perk_timers_of_type(bucks_type)\n\n def award_unlocked_perks(self, bucks_type, sim_info=None):\n for perk in self.all_perks_of_type_gen(bucks_type):\n if self.is_perk_unlocked(perk):\n self._award_rewards(perk, sim_info=sim_info)\n self._award_buffs(perk)","sub_path":"Scripts/simulation/bucks/bucks_tracker.py","file_name":"bucks_tracker.py","file_ext":"py","file_size_in_byte":25054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"336294059","text":"import os\nimport argparse\nimport subprocess\nimport pandas as pd\nfrom itertools import repeat\nfrom multiprocessing import Pool, freeze_support\n'''\ndef RunBWAindexParallel(InFileList):\n pool = Pool(processes=jobs)\n pool.starmap(RunBWAindex, zip(InFileList))\n pool.close()\n pool.join()\n pool.terminate()\n''' \ndef RunBWAParallel(indexList, R1List, R2List, jobs, threads, outFileList):\n pool = Pool(processes=jobs)\n pool.starmap(RunBWA, zip(repeat(indexList),R1List, R2List, repeat(threads), outFileList))\n pool.close()\n pool.join()\n pool.terminate()\n\ndef RunBBMapParallel(InFileList, OutFileList):\n pool = Pool(processes=jobs)\n pool.starmap(RunBBMap, zip(InFileList, OutFileList))\n pool.close()\n pool.join()\n pool.terminate()\n\ndef RunCatRPKMParallel(InFileList, OutFileList):\n pool = Pool(processes=jobs)\n pool.starmap(RunCatRPKM, zip(InFileList, OutFileList))\n pool.close()\n pool.join()\n pool.terminate()\n\ndef RunCatCPMParallel(InFileList, OutFileList):\n pool = Pool(processes=jobs)\n pool.starmap(RunCatCPM, zip(InFileList, OutFileList))\n pool.close()\n pool.join()\n pool.terminate()\n\ndef RunBWAindex(InFile):\n cmd = \"bwa index \" + InFile\n subprocess.call(cmd, shell=True)\n\ndef RunBWA(index, R1, R2, threads, OutFile):\n cmd = \"bwa mem -t \" + str(threads) + \" \"+ index + \" \" + R1 + \" \" + R2 + \" > \" + os.path.join(outputDir, OutFile + \".sam\")\n subprocess.call(cmd, shell=True)\n\ndef RunBBMap(InFile, OutFile):\n cmd = \"pileup.sh in=\" + InFile + \" out=\" + os.path.join(outputDir, OutFile + \"_coverage.txt\") + \" rpkm=\" + os.path.join(outputDir, OutFile + \"_rpkm.txt\")\n subprocess.call(cmd, shell=True)\n\ndef RunCatRPKM(InFile, OutFile):\n cmd = \"cat \" + InFile + \" | grep -v '#' | cut -f1, 6 > \" + os.path.join(outputDir, OutFile + \"_gene_abundance_rpkm.txt\")\n subprocess.call(cmd, shell=True)\n\ndef RunCatCPM(InFile, OutFile):\n cmd = \"cat \" + InFile + \" | grep -v '#' | cut -f1,2,5 > \" + os.path.join(outputDir, OutFile + \"_reads.input.txt\")\n subprocess.call(cmd, shell=True)\n\n\nparser = argparse.ArgumentParser(description='Calculate CAZy gene coverage')\nparser.add_argument('-i', '--input', dest='fileDir', type=str, required=True,\n help=\"the path of the bwa index .fasta file path\")\nparser.add_argument('-d', '--kneaddata', dest='kneaddata', type=str, required=True,\n help=\"the path of the keandata file path\")\nparser.add_argument('-o', '--output', dest='OpDir', type=str, required=True,\n help=\"the output path of result\")\nparser.add_argument('-j', '--jobs', dest='jobs', type=str, required=True,\n help=\"the number of jobs run in parallel\")\nparser.add_argument('-t', '--threads', dest='threads', type=str, required=True,\n help=\"the number of threads run for a job\") \nargs = parser.parse_args()\n\nindex = os.path.abspath(args.fileDir)\ninputDir = os.path.abspath(args.kneaddata)\noutputDir = os.path.abspath(args.OpDir)\njobs = int(args.jobs)\nthreads = int(args.threads)\n\n\nR1 = \"\"\nR2 = \"\"\nOutFile = \"\"\nR1List = []\nR2List = []\nOutFileList = []\nfor files in os.listdir(inputDir):\n if files.endswith(\"_kneaddata_paired_1.fastq\"):\n R1 = os.path.join(inputDir, files)\n R2 = os.path.join(inputDir, files[:-25]+\"_kneaddata_paired_2.fastq\")\n OutFile = files.replace(\"_kneaddata_paired_1.fastq\", \"\")\n R1List.append(R1)\n R2List.append(R2)\n OutFileList.append(OutFile)\nRunBWAParallel(index,R1List, R2List, jobs, threads, OutFileList)\n\nBBMapIn = \"\"\nBBMapOut = \"\"\nBBMapInList = []\nBBMapOutList = []\nfor files in os.listdir(outputDir):\n if files.endswith(\".sam\"):\n BBMapIn = os.path.join(outputDir, files)\n BBMapOut = files.replace(\".sam\", \"\")\n BBMapInList.append(BBMapIn)\n BBMapOutList.append(BBMapOut)\nRunBBMapParallel(BBMapInList, BBMapOutList)\n\nfor file in os.listdir(outputDir):\n if file.endswith(\"_rpkm.txt\"):\n InFile = os.path.join(outputDir, file)\n OutFile = files.replace(\"_rpkm.txt\", \"\")\n RunCatRPKM(InFile, OutFile)\n RunCatCPM(InFile, OutFile)","sub_path":"CAZy-Analysis/CAZy-Analysis.py","file_name":"CAZy-Analysis.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"188831860","text":"from django import forms\nfrom django.forms import ModelForm\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field\nfrom crispy_forms.bootstrap import AppendedText, PrependedText, FormActions\nfrom directory.models import Business\n\nclass AddForm(ModelForm):\n beaver_question = forms.RegexField(\n label=(\"What is the Karns Mascot?\"),\n max_length=32,\n regex=r'[bB][eE][aA][vV][eE][rR](|[sS])$',\n error_message = (\"Wrong Answer\")\n )\n\n def __init__(self, *args, **kwargs):\n super(AddForm, self).__init__(*args, **kwargs)\n\n # If you pass FormHelper constructor a form instance\n # It builds a default layout with all its fields\n self.helper = FormHelper(self)\n\n # You can dynamically adjust your layout\n self.helper.layout.append(Submit('save', 'Submit'))\n \n class Meta:\n model = Business\n fields = ['name', 'address', 'phone', 'community', 'categories', 'comment', 'url', 'link_google', 'link_facebook', 'link_yelp']\n\n #def save(self, commit=True):\n # return super(AddForm, self).save\n\n # Uni-form\n helper = FormHelper()\n helper.form_class = 'form-horizontal'\n\n","sub_path":"directory/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"482215776","text":"\n\n\ndef zip1(x,y):\n\ti = 0\n\n\tassert hasattr(x,\"__iter__\")\n\tassert hasattr(y,\"__iter__\")\n\t\n\tif len(x)1,[-5,-4,-3,13])\nprint(li)\n","sub_path":"cs373-practice/exam1/functionsimplementation.py","file_name":"functionsimplementation.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"157446779","text":"# -*- coding: utf-8 -*-\n\"\"\"\nExamples for use the python functions: get push data\n\"\"\"\n\nfrom futuquant import *\nfrom time import sleep\nfrom futuquant.common.ft_logger import logger\nimport multiprocessing as mp\nfrom threading import Thread, RLock\n\n\n\"\"\"\n 简介:\n 1.futu api一个牛牛号的默认定阅额度是500, 逐笔的权重是5, 故最多只能定阅100支股票\n 2.港股全市场正股约2300支, 需要启动23个进程(建议在centos上运行)\n 3.本脚本创建多个对象多个进程来定阅ticker, 达到收集尽可能多的股票逐笔数据的目的\n 4.仅供参考学习\n 接口调用:\n 1. ..\n 2....\n\"\"\"\n\n\nclass FullTickerHandleBase(object):\n def on_recv_rsp(self, data_dict):\n print(data_dict)\n\n\nclass SubscribeFullTick(object):\n # 逐笔的权重\n TICK_WEIGHT = 5\n # 配置信息\n DEFAULT_SUB_CONFIG = {\n \"sub_max\": 4000, # 最多定阅多少支股票(需要依据定阅额度和进程数作一个合理预估)\n \"sub_stock_type_list\": [SecurityType.STOCK], # 选择要定阅的股票类型\n \"sub_market_list\": [Market.US], # 要定阅的市场\n \"ip\": \"127.0.0.1\", # FutuOpenD运行IP\n \"port_begin\": 11113, # port FutuOpenD开放的第一个端口号\n \"port_count\": 30, # 启动了多少个FutuOPenD进程,每个进程的port在port_begin上递增\n \"sub_one_size\": 150, # 最多向一个FutuOpenD定阅多少支股票\n \"is_adjust_sub_one_size\": True, # 依据当前剩余定阅量动态调整一次的定阅量(测试白名单不受定阅额度限制可置Flase)\n 'one_process_ports': 2, # 用多进程提高性能,一个进程处理多少个端口\n }\n def __init__(self):\n self.__sub_config = copy(self.DEFAULT_SUB_CONFIG)\n self.__mp_manage = mp.Manager()\n self.__share_sub_codes = self.__mp_manage.list() # 共享记录进程已经定阅的股票\n self.__share_left_codes = self.__mp_manage.list() # 共享记录进程剩余要定阅的股票\n\n self.__ns_share = self.__mp_manage.Namespace()\n self.__ns_share.is_process_ready = False\n self.__share_queue_exit = mp.Queue()\n self.__share_queue_tick = mp.Queue()\n\n self.__timestamp_adjust = 0 # 时间与futu server时间校准偏差 : (本地时间 - futu时间) 秒\n self.__codes_pool = []\n self.__process_list = []\n self.__loop_thread = None\n self.__tick_thread = None\n self.__is_start_run = False\n self._tick_handler = FullTickerHandleBase()\n\n @classmethod\n def cal_timstamp_adjust(cls, quote_ctx):\n # 计算本地时间与futu 时间的偏差, 3次取最小值\n diff_ret = None\n ret = RET_ERROR\n for x in range(3):\n while ret != RET_OK:\n ret, data = quote_ctx.get_global_state()\n if ret != RET_OK:\n sleep(0.1)\n one_diff = (int(time.time()) - int(data['timestamp']))\n diff_ret = min(diff_ret, one_diff) if diff_ret is not None else one_diff\n\n return diff_ret\n\n @classmethod\n def cal_all_codes(cls, quote_ctx, market_list, stock_type_list, max_count):\n all_codes = []\n for market in market_list:\n for stock_type in stock_type_list:\n ret = RET_ERROR\n while ret != RET_OK:\n ret, data = quote_ctx.get_stock_basicinfo(market, stock_type)\n if ret != RET_OK:\n sleep(0.1)\n codes = list(data['code'])\n [all_codes.append(code) for code in codes]\n break\n if len(all_codes) >= max_count:\n all_codes = all_codes[0: max_count]\n break\n return all_codes\n\n @classmethod\n def loop_subscribe_codes(cls, quote_ctx, codes):\n ret = RET_ERROR\n while ret != RET_OK:\n ret, data = quote_ctx.subscribe(codes, SubType.TICKER)\n if ret == RET_OK:\n break\n else:\n print(\"loop_subscribe_codes :{}\".format(data))\n sleep(1)\n\n @classmethod\n def loop_get_subscription(cls, quote_ctx):\n ret = RET_ERROR\n while ret != RET_OK:\n ret, data = quote_ctx.query_subscription(True)\n if ret == RET_OK:\n return data\n sleep(0.1)\n\n def set_handler(self, handler):\n self._tick_handler = handler\n\n def start(self, create_loop_run=True):\n if self.__is_start_run:\n return\n self.__is_start_run = True\n\n ip = self.__sub_config['ip']\n port_begin = self.__sub_config['port_begin']\n quote_ctx = OpenQuoteContext(ip, port_begin)\n\n # 如果外面不指定定阅股票,就从股票列表中取出\n if len(self.__codes_pool) == 0:\n self.__codes_pool = self.cal_all_codes(quote_ctx, self.__sub_config['sub_market_list'],\n self.__sub_config['sub_stock_type_list'], self.__sub_config['sub_max'])\n\n if len(self.__codes_pool) == 0:\n raise Exception(\"codes pool is empty\")\n\n # 共享记录剩余的要定阅的股票\n self.__share_left_codes = self.__mp_manage.list()\n [self.__share_left_codes.append(code) for code in self.__codes_pool]\n\n self.__timestamp_adjust = self.cal_timstamp_adjust(quote_ctx)\n quote_ctx.close()\n\n # 创建进程定阅\n port_idx = 0\n sub_one_size = self.__sub_config['sub_one_size']\n is_adjust_sub_one_size = self.__sub_config['is_adjust_sub_one_size']\n one_process_ports = self.__sub_config['one_process_ports']\n\n # 创建多个进程定阅ticker\n while len(self.__share_left_codes) > 0 and port_idx < self.__sub_config['port_count']:\n\n # 备份下遗留定阅股票\n left_codes = []\n [left_codes.append(code) for code in self.__share_left_codes]\n\n self.__ns_share.is_process_ready = False\n process = mp.Process(target=self.process_fun, args=(ip, port_begin+port_idx, one_process_ports, sub_one_size,\n is_adjust_sub_one_size, self.__share_queue_exit, self.__share_queue_tick,\n self.__share_sub_codes, self.__share_left_codes, self.__ns_share))\n process.start()\n while process.is_alive() and not self.__ns_share.is_process_ready:\n sleep(0.1)\n\n if process.is_alive():\n port_idx += one_process_ports\n self.__process_list.append(process)\n else:\n self.__share_left_codes.clear()\n [self.__share_left_codes.append(code) for code in left_codes]\n\n #log info\n logger.debug(\"all_sub_code count={} codes={}\".format(len(self.__share_sub_codes), self.__share_sub_codes))\n logger.debug(\"process count={}\".format(len(self.__process_list)))\n\n # 创建tick 处理线程\n self.__tick_thread = Thread(\n target=self._thread_tick_check, args=())\n self.__tick_thread.setDaemon(True)\n self.__tick_thread.start()\n\n # 创建loop 线程\n if create_loop_run:\n self.__loop_thread = Thread(\n target=self._thread_loop_hold, args=())\n self.__loop_thread.start()\n\n def close(self):\n if not self.__is_start_run:\n return\n self.__share_queue_exit.put(True)\n\n for proc in self.__process_list:\n proc.join()\n self.__process_list.clear()\n\n self.__is_start_run = False\n if self.__loop_thread:\n self.__loop_thread.join(timeout=10)\n self.__loop_thread = None\n\n if self.__tick_thread:\n self.__tick_thread.join(timeout=10)\n self.__tick_thread = None\n\n def _thread_loop_hold(self):\n while not self.__is_start_run:\n sleep(0.1)\n\n def _thread_tick_check(self):\n while self.__is_start_run:\n try:\n if self.__share_queue_tick.empty() is False:\n dict_data = self.__share_queue_tick.get_nowait()\n if self._tick_handler:\n self._tick_handler.on_recv_rsp(dict_data)\n except Exception as e:\n pass\n\n @classmethod\n def process_fun(cls, ip, port, port_count, sub_one_size, is_adjust_sub_one_size,\n share_queue_exit, share_queue_tick, share_sub_codes, share_left_codes, ns_share):\n \"\"\"\n :param ip:\n :param port: 超始端口\n :param port_count: 端口个数\n :param sub_one_size: 一个端口定阅的个数\n :param is_adjust_sub_one_size: 依据当前剩余定阅量动态调整一次的定阅量(测试白名单不受定阅额度限制可置Flase)\n :param share_queue_exit: 进程共享 - 退出标志\n :param share_queue_tick: 进程共享 - tick数据队列\n :param share_sub_codes: 进程共享 - 定阅成功的股票\n :param share_left_codes: 进程共享 - 剩余需要定阅的量\n :param ns_share: 进程共享 - 变量 is_process_ready 进程定阅操作完成\n :return:\n \"\"\"\n if not port or sub_one_size <= 0:\n return\n\n class ProcessTickerHandle(TickerHandlerBase):\n def on_recv_rsp(self, rsp_pb):\n \"\"\"数据响应回调函数\"\"\"\n ret_code, content = super(ProcessTickerHandle, self).on_recv_rsp(rsp_pb)\n if ret_code != RET_OK:\n return RET_ERROR, content\n\n data_tmp = content.to_dict(orient='index')\n for dict_data in data_tmp.values():\n share_queue_tick.put(dict_data)\n return RET_OK, content\n\n quote_ctx_list = []\n def create_new_quote_ctx(host, port):\n obj = OpenQuoteContext(host=host, port=port)\n quote_ctx_list.append(obj)\n obj.set_handler(ProcessTickerHandle())\n obj.start()\n return obj\n\n port_index = 0\n all_sub_codes = []\n while len(share_left_codes) > 0 and port_index < port_count:\n quote_ctx = create_new_quote_ctx(ip, port + port_index)\n cur_sub_one_size = sub_one_size\n data = cls.loop_get_subscription(quote_ctx)\n\n # 已经定阅过的不占用额度可以直接定阅\n codes = data['sub_list'][SubType.TICKER] if SubType.TICKER in data['sub_list'] else []\n codes_to_sub = []\n for code in codes:\n if code not in share_left_codes:\n continue\n all_sub_codes.append(code)\n share_left_codes.remove(code)\n codes_to_sub.append(code)\n\n if len(codes_to_sub):\n cls.loop_subscribe_codes(quote_ctx, codes_to_sub)\n cur_sub_one_size -= len(codes_to_sub)\n\n # 依据剩余额度,调整要定阅的数量\n if is_adjust_sub_one_size:\n size_remain = int(data['remain'] / cls.TICK_WEIGHT)\n cur_sub_one_size = cur_sub_one_size if cur_sub_one_size < size_remain else size_remain\n\n # 执行定阅\n cur_sub_one_size = cur_sub_one_size if cur_sub_one_size < len(share_left_codes) else len(share_left_codes)\n if cur_sub_one_size > 0:\n codes = share_left_codes[0: cur_sub_one_size]\n [share_left_codes.remove(x) for x in codes]\n # share_left_codes = share_left_codes[cur_sub_one_size:]\n [all_sub_codes.append(x) for x in codes]\n cls.loop_subscribe_codes(quote_ctx, codes)\n\n port_index += 1\n\n # 共享记录定阅成功的股票,并标志该进程定阅完成\n [share_sub_codes.append(code) for code in all_sub_codes]\n ns_share.is_process_ready = True\n\n # 等待结束信息\n while share_queue_exit.empty() is True:\n sleep(0.2)\n\n for quote_ctx in quote_ctx_list:\n quote_ctx.close()\n quote_ctx_list = []\n\n\nif __name__ ==\"__main__\":\n\n tick_subcrible = SubscribeFullTick()\n tick_subcrible.set_handler(FullTickerHandleBase())\n tick_subcrible.start()\n\n # 运行24小时后退出\n sleep(24 * 3600)\n tick_subcrible.close()\n\n\n\n\n\n\n\n\n\n","sub_path":"futuquant-3.0/futuquant/examples/learn/suscribe_full_tick.py","file_name":"suscribe_full_tick.py","file_ext":"py","file_size_in_byte":12788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"211432859","text":"import pandas as pd\n\n########################################################################\n\nclass mpr_data():\n\n # Read a text file with N columns and returns the list of N column data\n # Skip first \"col_start\" columns if col_start is not 0.\n def read_mpr(input_file, col_last, col_start = 0, header=None,\n delim_whitespace=True, keep_default_na=False,\n skiprows=1, dtype='string'):\n mpr_data = pd.read_csv(input_file, header=header,\n delim_whitespace=delim_whitespace,\n keep_default_na=keep_default_na,\n skiprows=skiprows,\n usecols=range(col_start,col_last+1),\n dtype=dtype).values.tolist()\n return mpr_data\n\n\n########################################################################\n","sub_path":"scripts/python/met/mprbase.py","file_name":"mprbase.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"481701531","text":"# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other\n# Spack Project Developers. See the top-level COPYRIGHT file for details.\n#\n# SPDX-License-Identifier: (Apache-2.0 OR MIT)\n# adapted from official quantum espresso package\n\n\nfrom spack.package import *\n\n\nclass QESirius(CMakePackage):\n \"\"\"SIRIUS enabled fork of QuantumESPRESSO.\"\"\"\n\n homepage = \"https://github.com/electronic-structure/q-e-sirius/\"\n url = \"https://github.com/electronic-structure/q-e-sirius/archive/v6.5-rc4-sirius.tar.gz\"\n git = \"https://github.com/electronic-structure/q-e-sirius.git\"\n\n maintainers = [\"simonpintarelli\"]\n\n version(\"develop-ristretto\", branch=\"ristretto\", submodules=True)\n version(\"6.7-rc1-sirius\", tag=\"v6.7-rc1-sirius\", submodules=True)\n\n variant(\"mpi\", default=True, description=\"Builds with MPI support\")\n variant(\"openmp\", default=True, description=\"Enables OpenMP support\")\n variant(\"scalapack\", default=False, description=\"Enables SCALAPACK support\")\n variant(\"elpa\", default=False, description=\"Uses ELPA as an eigenvalue solver\")\n variant(\"libxc\", default=False, description=\"Support functionals through libxc\")\n variant(\"hdf5\", default=False, description=\"Enables HDF5 support\")\n variant(\"sirius_apps\", default=False, description=\"Build SIRIUS standalone binaries\")\n\n depends_on(\"sirius +fortran\")\n depends_on(\"sirius +apps\", when=\"+sirius_apps\")\n depends_on(\"sirius ~apps\", when=\"~sirius_apps\")\n depends_on(\"sirius +openmp\", when=\"+openmp\")\n depends_on(\"sirius@develop\", when=\"@develop\")\n\n depends_on(\"mpi\", when=\"+mpi\")\n depends_on(\"scalapack\", when=\"+scalapack\")\n depends_on(\"elpa\", when=\"+elpa\")\n depends_on(\"libxc\", when=\"+libxc\")\n depends_on(\"hdf5\", when=\"+hdf5\")\n\n depends_on(\"git\", type=\"build\")\n depends_on(\"pkgconfig\", type=\"build\")\n\n conflicts(\"~mpi\", when=\"+scalapack\", msg=\"SCALAPACK requires MPI support\")\n conflicts(\"~scalapack\", when=\"+elpa\", msg=\"ELPA requires SCALAPACK support\")\n\n def cmake_args(self):\n args = [\n \"-DQE_ENABLE_SIRIUS=ON\",\n \"-DQE_ENABLE_CUDA=OFF\",\n \"-DQE_LAPACK_INTERNAL=OFF\",\n \"-DQE_ENABLE_DOC=OFF\",\n self.define_from_variant(\"QE_ENABLE_MPI\", \"mpi\"),\n self.define_from_variant(\"QE_ENABLE_OPENMP\", \"openmp\"),\n self.define_from_variant(\"QE_ENABLE_ELPA\", \"elpa\"),\n self.define_from_variant(\"QE_ENABLE_LIBXC\", \"libxc\"),\n self.define_from_variant(\"QE_ENABLE_HDF5\", \"hdf5\"),\n self.define_from_variant(\"QE_ENABLE_SCALAPACK\", \"scalapack\"),\n ]\n\n # Work around spack issue #19970 where spack sets\n # rpaths for MKL just during make, but cmake removes\n # them during make install.\n if \"^mkl\" in self.spec:\n args.append(\"-DCMAKE_INSTALL_RPATH_USE_LINK_PATH=ON\")\n\n return args\n","sub_path":"var/spack/repos/builtin/packages/q-e-sirius/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":2876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"412245065","text":"import os\n# sys.path.append(os.path.join(os.getcwd(), 'cytomod', 'otherTools'))\nimport app.cytomod.assoc_to_outcome as outcome\nfrom app.cytomod import plotting as cyplot\nfrom app.cytomod.otherTools.hclusterplot import plotHColCluster\nimport numpy as np\nimport warnings\nwarnings.filterwarnings('ignore')\nwarnings.simplefilter('ignore')\nimport app.cytomod.io\nfrom pandas.api.types import is_string_dtype\n\ndef pairwise_person(stage, args):\n if stage == 'abs':\n plotHColCluster(args.cyto_mod_abs.cyDf, method='complete', metric='pearson-signed', figsize=(10, 6),\n save_path=os.path.join(args.paths['correlation_figures_abs'], '%s_correlation_heatmap.png' % args.cyto_mod_abs.name))\n elif stage == 'adj':\n plotHColCluster(args.cyto_mod_adj.cyDf, method='complete', metric='pearson-signed', figsize=(10, 6),\n save_path=os.path.join(args.paths['correlation_figures_adj'], '%s_correlation_heatmap.png' % args.cyto_mod_adj.name))\n return args\n\n\ndef mean_person(args):\n cyplot.plotMeanCorr(args.cyto_mod_abs.withMean, args.cyto_mod_abs.meanS.name,\n cyList=sorted(args.cyto_mod_abs.cyDf.columns),\n save_path=os.path.join(args.paths['overview'],\n '%s_cy_mean_correlation.png' % args.cyto_mod_abs.name))\n img = {'height': '800',\n 'width': '400',\n 'path': os.path.join(args.paths['overview'],\n '%s_cy_mean_correlation.png' % args.cyto_mod_abs.name),\n 'headline': 'Correlations of the absolute cytokine levels with the mean cytokine level',\n 'location': 'overview',\n 'explanation': 'This plot demonstrates the correlations between cytokine levels and mean cytokine levels'\n }\n args.images.append(img)\n return args\n\ndef figsize(args, many_cytokines_size, small_cytokine_size):\n if args.num_of_cytokines < 50:\n return small_cytokine_size\n return many_cytokines_size\n\ndef pairwise_correlation_with_moudles(stage, args):\n app.cytomod.io.plot_clustering_heatmap(args.cyto_modules[stage], args.paths[f'clustering_{stage}'],\n figsize=figsize(args, (15, 9), (10, 6)))\n img = {'height': '700',\n 'width': '1000',\n 'path': args.paths[f'clustering_{stage}'] + '/%s_hierchical_clust_heatmap.png' % args.cyto_modules[stage].name,\n 'headline': 'Hierarchical Clustering Heatmap for %s Cytokines' % stage ,\n 'location': f'clustering_{stage}',\n 'explanation': f\"Pairwise Pearson's correlations among the {stage} cytokine levels in the given cohort. Cytokines were sorted along both axes using hierarchical clustering (complete-linkage)\"\n }\n args.images.append(img)\n return args\n\ndef same_cluster_reliability(stage,args):\n app.cytomod.io.plot_reliability(args.cyto_modules[stage], args.paths[f'clustering_{stage}'],\n figsize=figsize(args, (15, 9), (10, 6)))\n app.cytomod.io.plot_color_legend(args.cyto_modules[stage], args.paths[f'clustering_{stage}'])\n img = {'height': '700',\n 'width': '1000',\n 'path': args.paths[f'clustering_{stage}'] + '/%s_reliability.png' % args.cyto_modules[stage].name,\n 'headline': 'Reliability Figure Of Pairwise Correlations of %s Cytokines' % stage,\n 'location': f'clustering_{stage}',\n 'explanation': 'Heatmap of cytokine modules - Complete linkage clustering over the Pearson pairwise correlation similarity measure is used to cluster cytokines into K modules, where K is selected using the gap statistic. '\n 'A clustering reliability score is computed over 1, 000 samplings of subjects that are sampled with replacement. '\n 'The score for each pair of cytokines represents the fraction of times they clustered together across 1,000 random samples. '\n 'The reliability score of the chosen K is presented here. The final modules are then constructed by clustering the pairwise reliability scores, and are represented by the colored stripes below the clustering dendrogram.'}\n args.images.append(img)\n img = {'height': '300',\n 'width': '500',\n 'path': args.paths[f'clustering_{stage}'] + '/%s_color_label_legend.png' % args.cyto_modules[stage].name,\n 'headline': 'Modules Labels',\n 'location': f'clustering_{stage}',\n 'explanation': 'Modules are presented by the following colors'}\n args.images.append(img)\n return args\n\n\ndef modules_cytokine_correlation(stage, args):\n args = app.cytomod.io.plot_module_correl(args.cyto_modules[stage], args.paths[f'correlation_figures_{stage}'], args, stage)\n return args\n\n\ndef write_results(args):\n app.cytomod.io.write_modules(args.cyto_modules['abs'], args.paths['overview'])\n app.cytomod.io.write_modules(args.cyto_modules['adj'], args.paths['overview'])\n\n\ndef associations_to_outcomes(stage, args):\n # standardize numeric covariates\n standardizeFunc = lambda col: (col - np.nanmean(col)) / np.nanstd(col)\n\n if args.covariates != []:\n for covariate in args.covariates:\n if covariate != '':\n args.patient_data[[covariate]] = args.patient_data[[covariate]].apply(standardizeFunc)\n\n if args.outcomes != []:\n if stage == 'abs':\n args.mod_outcome_abs_df, args.need_OR = outcome.outcomeAnalysis(args.cyto_modules['abs'], args.patient_data,\n analyzeModules=True,\n outcomeVars=args.outcomes if args.outcomes[0] != '' else [],\n adjustmentVars=args.covariates if args.covariates[0] != '' else [],\n standardize=True)\n args.cy_outcome_abs_df, args.need_OR = outcome.outcomeAnalysis(args.cyto_modules['abs'], args.patient_data,\n analyzeModules=False,\n outcomeVars=args.outcomes if args.outcomes[0] != '' else [],\n adjustmentVars=args.covariates if args.covariates[0] != '' else [],\n standardize=True)\n if stage == 'adj':\n args.mod_outcome_adj_df, args.need_OR = outcome.outcomeAnalysis(args.cyto_modules['adj'], args.patient_data,\n analyzeModules=True,\n outcomeVars=args.outcomes if args.outcomes[0] != '' else [],\n adjustmentVars=args.covariates if args.covariates[0] != '' else [],\n standardize=True)\n args.cy_outcome_adj_df, args.need_OR = outcome.outcomeAnalysis(args.cyto_modules['adj'], args.patient_data,\n analyzeModules=False,\n outcomeVars=args.outcomes if args.outcomes[0] != '' else [],\n adjustmentVars=args.covariates if args.covariates[0] != '' else [],\n standardize=True)\n return args\n\n\ndef outcomes_figures(stage, args):\n if args.outcomes != []:\n if stage == 'abs':\n outcome.plotResultSummary(args.cyto_modules['abs'],\n args.mod_outcome_abs_df,\n args.cy_outcome_abs_df,\n args.outcomes,\n fdr_thresh_plot=0.2,\n compartmentName=args.name_compartment,\n figsize=figsize(args, (8, 12), (6, 9)),\n save_fig_path=os.path.join(args.paths['outcome_abs'],\n 'associations_abs.png'),\n logistic= args.need_OR)\n img = {'height': '800',\n 'width': '400',\n 'path':os.path.join(args.paths['outcome_abs'],\n 'associations_abs.png'),\n 'headline': 'Associations with clinical outcomes (absolute cytokines)',\n 'location':'outcome_abs',\n 'explanation': 'Associations of cytokine modules, and individual cytokines with clinical phenotypes.'\n 'Associations were identified using the relevant regression (linear for continues outcomes and logistic for binary outcomes) controlling for the inserted covariates. '\n 'Each cytokine or module is indicated along the rows, grouped by their assigned module. Heatmap color indicates the direction and magnitude of the regression coefficient between cytokine or module level with a given clinical phenotype. '\n 'Only associations with false-discovery rate (FDR)-adjusted q-value ≤ 0.2 are colored. Asterisks indicate family-wise error rate (FWER)-adjusted p-values with ***, **, and * indicating p ≤ 0.0005, 0.005, and 0.05, respectively.'}\n args.images.append(img)\n elif stage == 'adj':\n outcome.plotResultSummary(args.cyto_modules['adj'],\n args.mod_outcome_adj_df,\n args.cy_outcome_adj_df,\n args.outcomes,\n fdr_thresh_plot=0.2,\n compartmentName=args.name_compartment,\n figsize=figsize(args, (8, 12), (6, 9)),\n save_fig_path=os.path.join(args.paths['outcome_adj'],\n 'associations_adj.png'),\n logistic=args.need_OR)\n img = {'height': '800',\n 'width': '400',\n 'path': os.path.join(args.paths['outcome_adj'],\n 'associations_adj.png'),\n 'headline': 'Associations with clinical outcomes (adjusted cytokines)',\n 'location':'outcome_adj',\n 'explanation': 'Associations of cytokine modules, and individual cytokines with clinical phenotypes.'\n 'Associations were identified using the relevant regression (linear for continues outcomes and logistic for binary outcomes) controlling for the inserted covariates. '\n 'Each cytokine or module is indicated along the rows, grouped by their assigned module. Heatmap color indicates the direction and magnitude of the regression coefficient between cytokine or module level with a given clinical phenotype. '\n 'Only associations with false-discovery rate (FDR)-adjusted q-value ≤ 0.2 are colored. Asterisks indicate family-wise error rate (FWER)-adjusted p-values with ***, **, and * indicating p ≤ 0.0005, 0.005, and 0.05, respectively.'}\n args.images.append(img)\n return args\n","sub_path":"app/backend/visualization/figure_scheme.py","file_name":"figure_scheme.py","file_ext":"py","file_size_in_byte":11564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"565000093","text":"# -*- coding: utf-8 -*-\n\n# Define here the models for your spider middleware\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/spider-middleware.html\n\nfrom scrapy.http import HtmlResponse\nfrom scrapy.utils.python import to_bytes\nfrom scrapy import signals\n\nfrom webdriver_manager.chrome import ChromeDriverManager\nfrom selenium import webdriver\nimport time\nfrom selenium.webdriver.chrome.options import Options\n\n\nclass SeleniumMiddleware(object):\n\n @classmethod\n def from_crawler(cls, crawler):\n middleware = cls()\n crawler.signals.connect(middleware.spider_opened, signals.spider_opened)\n crawler.signals.connect(middleware.spider_closed, signals.spider_closed)\n return middleware\n\n def process_request(self, request, spider):\n # import requests\n #\n # headers = {\n # \"apikey\": \"7bbae810-dcc5-11ea-8d11-3b853f2dbb82\"\n # }\n #\n # params = (\n # (\"url\", request.url),\n # )\n #\n # response = requests.get('https://app.zenscrape.com/api/v1/get',\n # headers=headers,\n # params=params)\n request.meta['driver'] = self.driver # to access driver from response\n self.driver.get(request.url)\n time.sleep(1)\n\n body = to_bytes(self.driver.execute_script(\"return document.getElementsByTagName('html')[0].innerHTML\")) # body must be of type bytes\n\n return HtmlResponse(self.driver.current_url,\n body=body,\n encoding='utf-8',\n request=request)\n\n def spider_opened(self, spider):\n options = Options()\n\n options.add_argument('--headless')\n options.add_argument('--disable-gpu')\n\n self.driver = webdriver.Chrome(\n executable_path=ChromeDriverManager().install(),\n chrome_options=options\n )\n\n def spider_closed(self, spider):\n self.driver.close()","sub_path":"aws/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"230026537","text":"import math\n\n# Prompting the user to input nSides and sLength values\nprint(\"Welcome to the Polygon Area Calculator!\")\nnSides = eval(input(\"Please enter the number of sides your polygon has: \"))\nsLength = eval(input(\"Please enter the side length: \"))\n\n# Calculating the Area\narea = (nSides * (sLength ** 2)) / (4 * math.tan(math.pi / nSides))\n\n# Displaying the Results\nprint(\"Your polygon has an area of \" + str(area))","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"51899003","text":"#!/usr/bin/env python3\nimport sys\n\nimport requests\n\n\n\ndef eprint(message):\n print(message, file=sys.stderr)\n\n\nif len(sys.argv) == 2:\n base_url = sys.argv[1]\n eprint(\"Starting '{}' from scratch\".format(base_url))\nelse:\n eprint(\"Usage: ./dump.py BASE_URL\")\n sys.exit(1)\n\nif not base_url.endswith(\"/\"):\n base_url += \"/\"\n\nWIKI_ALL_PAGES = (\n \"{}w/api.php?action=query&list=allpages&format=json&aplimit=500&apfrom={}\"\n)\n\n\ndef iter_titles():\n apfrom = ''\n while True:\n url = WIKI_ALL_PAGES.format(base_url, apfrom)\n response = requests.get(url)\n items = response.json()\n for item in items[\"query\"][\"allpages\"]:\n yield item[\"title\"]\n # continue?\n apfrom = items.get(\"continue\", {}).get(\"apcontinue\")\n if apfrom is None:\n break\n\n\nfor title in iter_titles():\n surface = title.replace('_', ' ').lower()\n if any(x not in 'abcdefhijklmnopqrstuvwxyz ' for x in surface):\n eprint('skip {}'.format(surface))\n continue\n uid = base_url + 'wiki/' + title\n print(\"{}\\t{}\".format(uid, surface))\n","sub_path":"src/wiktionary-entities.py","file_name":"wiktionary-entities.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"440819088","text":"#!/usr/bin/env python3\n\nimport sys,os\nsys.path.append(os.path.dirname(__file__))\n\n\nfrom config import DropboxAPP,DB\nfrom dropbox import client, session\nimport time\n\ndef make_dump_db():\n path=os.path.dirname(__file__)+'/backup/'\n now=time.ctime().split()\n date=now[1]+'_'+now[2]+'.sql'\n filename=path+date\n command='/usr/bin/mysqldump -u%s -p%s %s > %s' % (DB['user'],DB['passwd'],DB['db'], filename)\n os.system(command)\n Dropboxuploader(filename,dropbox_path='/Web/Bishop/backup/%s' % date)\n\ndef Dropboxuploader(local_path,dropbox_path):\n APP_KEY=DropboxAPP['APP_KEY']\n APP_SECRET=DropboxAPP['APP_SECRET']\n ACCESS_TYPE=DropboxAPP['ACCESS_TYPE']\n ACCESS_KEY=DropboxAPP['ACCESS_KEY']\n ACCESS_SECRET=DropboxAPP['ACCESS_SECRET']\n sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)\n sess.set_token(ACCESS_KEY, ACCESS_SECRET)\n upload_session = client.DropboxClient(sess)\n filesize=os.path.getsize(local_path)\n try:\n uploader=upload_session.get_chunked_uploader(local_path,filesize)\n while uploader.offset < filesize:\n try:\n upload=uploader.upload_chunked()\n except:\n raise\n uploader.finish(local_path)\n except:\n openfile=open(local_path, 'rb')\n upload_session.put_file(dropbox_path,openfile)\n openfile.close()\n\n\nmake_dump_db()\n\n\n","sub_path":"Bishop/backuphandler.py","file_name":"backuphandler.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"108315921","text":"import numpy as np\nimport random\nimport math\nimport matplotlib.pyplot as plt\nfrom shapely.geometry import Polygon\nfrom shapely.geometry import Point\nimport time\nfrom joblib import Parallel, delayed\nimport multiprocessing\n\n\n######################################### calculate lh lp ############################################################\nclass Bound:\n def __init__(self, cfg, vwind0, alphaw0):\n self.vuav = cfg['vuav']\n self.a = cfg['a']\n self.tt = cfg['tt']\n self.ori = cfg['ori']\n self.des = cfg['des']\n self.vwind0 = vwind0\n self.alphaw0 = alphaw0\n\n ############################## proposed error #######################################################################\n def winderror(self):\n #np.random.seed(100)\n self.evwind = np.random.normal(0, 0.05 * self.vwind0)\n #random.seed(100)\n ff = random.randint(1,2)\n if ff == 1 :\n self.evwind = -1 * self.evwind\n # np.random.seed(100)\n self.ealphaw = np.random.normal(0, 0.05 * self.alphaw0)\n #np.random.seed()\n\n def uaverror(self):\n np.random.seed()\n self.epGPS = np.random.uniform(0, 1.5)\n self.evuav = np.random.normal(0, 0.05 * self.vuav)\n self.ea = np.random.normal(0, 0.05 * self.a)\n self.ett = np.random.normal(0, 0.05 * self.tt)\n\n #################### dynamic error ##############################################################################\n def dynuaverror(self):\n # self.evuav, self.evwind, self.ealphaw = proposed\n np.random.seed()\n self.evuav = np.random.normal(0, 0.05 * self.vuav)\n self.a = np.random.uniform(3.2, 6.7)\n self.tt = np.random.uniform(0, 2)\n self.epGPS = np.random.uniform(0, 1.5)\n\n self.ea = np.random.normal(0, 0.05 * self.a)\n self.ett = np.random.normal(0, 0.05 * self.tt)\n\n #################### static error ############################################################################\n def staticwinderror(self):\n np.random.seed()\n self.vwind0 = 3.2 * np.random.weibull(2.2)\n self.alphaw0 = np.random.uniform(0, 2 * np.pi)\n self.evwind = np.random.normal(0, 0.05 * self.vwind0)\n staticff = random.randint(1, 2)\n if staticff == 1:\n self.evwind = -1 * self.evwind\n self.ealphaw = np.random.normal(0, 0.05 * self.alphaw0)\n\n def staticuaverror(self):\n self.vuav = np.random.lognormal(3, 0.1)\n self.a = np.random.uniform(3.2, 6.7)\n self.tt = np.random.uniform(0, 2)\n\n self.evuav = np.random.normal(0, 0.05 * self.vuav)\n self.ea = np.random.normal(0, 0.05 * self.a)\n self.ett = np.random.normal(0, 0.05 * self.tt)\n\n self.epGPS = np.random.uniform(0, 1.5)\n\n ######################### calculate size (same in 3 case)#######################################################################\n def size(self):\n #np.random.seed()\n #self.uaverror()\n ### angle between uav and wind\n self.vecwind = ((self.vwind0 + self.evwind) * np.cos(self.alphaw0 + self.ealphaw), (self.vwind0 + self.evwind) * np.sin(self.alphaw0 + self.ealphaw))\n self.uavdir = np.subtract(self.des, self.ori)\n self.uavvvec = self.vuav / np.linalg.norm(self.uavdir) * self.uavdir\n self.alphaw = np.arccos(np.dot(self.uavdir, self.vecwind)/(np.linalg.norm(self.uavdir)*np.linalg.norm(self.vecwind)))\n\n ### size\n self.valong = self.vuav + self.evuav + (self.vwind0 + self.evwind) * (np.cos(self.alphaw))\n self.vper = (self.vwind0 + self.evwind) * (np.sin(self.alphaw))\n\n self.lh = abs(self.valong) * (self.tt + self.ett) + (self.valong) ** 2 / 2 / (self.a + self.ea)\n self.lp = abs(self.vper) * (self.tt + self.ett) + (self.vper) ** 2 / 2 / (self.a + self.ea) + self.epGPS\n self.r = self.lh + self.lp\n\n\n\n\n############################### proposed collision rate #################################################################\nclass Conflict:\n def __init__(self, cfg1, cfg2, vwind0, alphaw0):\n self.cfg1 = cfg1\n self.cfg2 = cfg2\n # type: (object, object, object, object) -> object\n ### uav1\n self.vuav1 = cfg1['vuav']\n self.a1 = cfg1['a']\n self.tt1 = cfg1['tt']\n self.ori1 = cfg1['ori']\n self.des1 = cfg1['des']\n ### uav2\n self.vuav2 = cfg2['vuav']\n self.a2 = cfg2['a']\n self.tt2 = cfg2['tt']\n self.ori2 = cfg2['ori']\n self.des2 = cfg2['des']\n ### wind\n self.vwind0 = vwind0\n self.alphaw0 = alphaw0\n\n ####################### find boundary ##############################################################\n def uavbound(self):\n ####################### stop time ##############################################################\n self.ref = Bound(self.cfg1, self.vwind0, self.alphaw0)\n self.ref.winderror()\n self.ref.uaverror()\n self.ref.size()\n self.tuav1 = np.linalg.norm(np.subtract(self.des1, self.ori1)) / self.ref.valong\n self.move = Bound(self.cfg2, self.vwind0, self.alphaw0)\n self.move.evwind = self.ref.evwind\n self.move.ealphaw = self.ref.ealphaw\n self.move.uaverror()\n self.move.size()\n self.tuav2 = np.linalg.norm(np.subtract(self.des2, self.ori2)) / self.move.valong\n self.systime = min(self.tuav1, self.tuav2)\n\n ####################### ref, move boundary ##############################################################\n self.prolh = np.empty([1, 600])\n self.prolp = np.empty([1, 600])\n self.ref2 = Bound(self.cfg1, self.vwind0, self.alphaw0)\n\n self.prolh2 = np.empty([1, 600])\n self.prolp2 = np.empty([1, 600])\n self.move2 = Bound(self.cfg2, self.vwind0, self.alphaw0)\n\n for j in range(0, 600):\n self.ref2.winderror()\n self.ref2.uaverror()\n self.ref2.size()\n self.prolh[0, j] = self.ref2.lh\n self.prolp[0, j] = self.ref2.lp\n\n self.move2.winderror()\n self.move2.uaverror()\n self.move2.size()\n self.prolh2[0, j] = self.move2.lh\n self.prolp2[0, j] = self.move2.lp\n\n self.prolh = np.sort(self.prolh)\n self.prolp = np.sort(self.prolp)\n\n self.ref.lp = self.prolp[0, 539]\n self.ref.lh = self.prolh[0, 539]\n\n self.prolh2 = np.sort(self.prolh2)\n self.prolp2 = np.sort(self.prolp2)\n\n self.move.lp = self.prolp2[0, 539]\n self.move.lh = self.prolh2[0, 539]\n\n self.refcir1 = self.ori1\n self.refr = self.ref.lp\n self.refcir2 = self.ori1 + self.ref.lh / (np.linalg.norm(self.ref.uavdir)) * np.array(self.ref.uavdir)\n self.refortho = (-self.ref.uavdir[1], self.ref.uavdir[0])\n self.refp1 = self.refcir1 + self.ref.lp / np.linalg.norm(self.refortho) * np.array(self.refortho)\n self.refp2 = self.refcir2 + self.ref.lp / np.linalg.norm(self.refortho) * np.array(self.refortho)\n self.refp3 = self.refcir2 - self.ref.lp / np.linalg.norm(self.refortho) * np.array(self.refortho)\n self.refp4 = self.refcir1 - self.ref.lp / np.linalg.norm(self.refortho) * np.array(self.refortho)\n self.refrect = [self.refp1, self.refp2, self.refp3, self.refp4]\n\n\n #self.refvel = self.move.uavvvec + self.move.vecwind - self.ref.uavvvec - self.ref.vecwind\n self.refvel = self.move.valong / np.linalg.norm(self.move.uavdir) * self.move.uavdir - self.ref.valong / np.linalg.norm(self.ref.uavdir) * self.ref.uavdir\n self.movecir1 = self.ori2\n self.mover = self.move.lp\n self.movecir2 = self.movecir1 + np.array(self.refvel) * self.systime + self.move.lh / np.linalg.norm(self.refvel) * np.array(self.refvel)\n self.moveortho = (-self.refvel[1], self.refvel[0])\n self.movep1 = self.movecir1 + self.move.lp / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n self.movep2 = self.movecir2 + self.move.lp / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n self.movep3 = self.movecir2 - self.move.lp / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n self.movep4 = self.movecir1 - self.move.lp / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n self.moverect = [self.movep1, self.movep2, self.movep3, self.movep4]\n\n ##################### collision check ##############################################################\n def collision(self):\n self.uavbound()\n FLAG = 0\n geo = geometry()\n self.fff = 1\n if self.ref.valong < 0 or self.move.valong < 0:\n self.fff = 0\n if self.fff == 1:\n if (\n geo.Flag2rect(self.moverect, self.refrect) == 1 or\n geo.Flagrectc(self.moverect, self.refcir1, self.refr) == 1 or\n geo.Flagrectc(self.moverect, self.refcir2, self.refr) == 1 or\n geo.Flag2cir(self.movecir1, self.mover, self.refcir1, self.refr) == 1 or\n geo.Flag2cir(self.movecir1, self.mover, self.refcir2, self.refr) == 1 or\n geo.Flagrectc(self.refrect, self.movecir1, self.mover) == 1 or\n geo.Flag2cir(self.movecir2, self.mover, self.refcir1, self.refr) == 1 or\n geo.Flag2cir(self.movecir2, self.mover, self.refcir2, self.refr) == 1 or\n geo.Flagrectc(self.refrect, self.movecir2, self.mover) == 1\n ):\n\n FLAG = 1\n #print 'collision'\n return FLAG\n\n\n\n\n############################## static collision rate ##############################################################\nclass staticconflict:\n def __init__(self, cfg1, cfg2, refvel, systime, refvalong, movevalong, fff): #vwind0, alphaw0,\n ### uav1\n self.vuav1 = cfg1['vuav']\n self.a1 = cfg1['a']\n self.tt1 = cfg1['tt']\n self.ori1 = cfg1['ori']\n self.des1 = cfg1['des']\n ### uav2\n self.vuav2 = cfg2['vuav']\n self.a2 = cfg2['a']\n self.tt2 = cfg2['tt']\n self.ori2 = cfg2['ori']\n self.des2 = cfg2['des']\n ### wind\n # self.vwind0 = vwind0\n # self.alphaw0 = alphaw0\n self.refvel = refvel\n self.systime = systime\n self.refvalong = refvalong\n self.movevalong = movevalong\n self.fff = fff\n\n####################### find boundary ##############################################################\n def staticuavbound(self):\n\n self.staticrefcir1 = self.ori1\n self.staticrefr = 99.5\n\n self.staticmovecir1 = self.ori2\n self.staticmovecir2 = self.staticmovecir1 + np.array(self.refvel) * self.systime\n self.staticmover = 99.5\n\n self.moveortho = (-self.refvel[1], self.refvel[0])\n self.staticmovep1 = self.staticmovecir1 + self.staticmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.staticmovep2 = self.staticmovecir2 + self.staticmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.staticmovep3 = self.staticmovecir2 - self.staticmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.staticmovep4 = self.staticmovecir1 - self.staticmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.staticmoverect = [self.staticmovep1, self.staticmovep2, self.staticmovep3, self.staticmovep4]\n\n # ####################### stop time ##############################################################\n # self.staticref = Bound(cfg1, self.vwind0, self.alphaw0)\n # self.staticref.staticwinderror()\n # self.staticref.staticuaverror()\n # self.staticref.size()\n # self.tuav1 = np.linalg.norm(np.subtract(self.des1, self.ori1)) / self.staticref.valong\n #\n # self.staticmove = Bound(cfg2, self.vwind0, self.alphaw0)\n # self.staticmove.vwind0 = self.staticref.vwind0\n # self.staticmove.evwind = self.staticref.evwind\n # self.staticmove.alphaw0 = self.staticref.alphaw0\n # self.staticmove.ealphaw = self.staticref.ealphaw\n # self.staticmove.staticuaverror()\n # self.staticmove.size()\n # self.tuav2 = np.linalg.norm(np.subtract(self.des2, self.ori2)) / self.staticmove.valong\n # self.systime = min(self.tuav1, self.tuav2)\n #\n # ####################### ref boundary ##############################################################\n # self.staticrefcir1 = self.ori1\n # self.staticrefr = self.staticref.r\n #\n # ###################### move boundary ###############################################################\n # self.refvel = self.staticmove.uavvvec + self.staticmove.vecwind - self.staticref.uavvvec - self.staticref.vecwind\n # self.staticmovecir1 = self.ori2\n # self.staticmover = self.staticmove.r\n # self.staticmovecir2 = self.staticmovecir1 + np.array(self.refvel) * self.systime\n # self.moveortho = (-self.refvel[1], self.refvel[0])\n # self.staticmovep1 = self.staticmovecir1 + self.staticmover / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n # self.staticmovep2 = self.staticmovecir2 + self.staticmover / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n # self.staticmovep3 = self.staticmovecir2 - self.staticmover / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n # self.staticmovep4 = self.staticmovecir1 - self.staticmover / np.linalg.norm(self.moveortho) * np.array(self.moveortho)\n # self.staticmoverect = [self.staticmovep1, self.staticmovep2, self.staticmovep3, self.staticmovep4]\n\n ##################### collision check ##############################################################\n def staticcollision(self):\n FLAG = 0\n if self.fff == 1:\n self.staticuavbound()\n geo = geometry()\n if (\n geo.Flagrectc(self.staticmoverect, self.staticrefcir1, self.staticrefr) == 1 or\n geo.Flag2cir(self.staticmovecir1, self.staticmover, self.staticrefcir1, self.staticrefr) == 1 or\n geo.Flag2cir(self.staticmovecir2, self.staticmover, self.staticrefcir1, self.staticrefr) == 1\n ):\n FLAG = 1\n #print 'collision'\n return FLAG\n\n\n\n############################## dyn collision rate ##############################################################\nclass dynconflict:\n def __init__(self, cfg1, cfg2, vwind0, alphaw0, refvel, systime, refvalong, movevalong, fff): #vwind0, alphaw0, evwind, ealphaw, cfg1evuav, cfg2evuav):\n self.cfg1 = cfg1\n self.cfg2 = cfg2\n ### uav1\n self.vuav1 = cfg1['vuav']\n self.a1 = cfg1['a']\n self.tt1 = cfg1['tt']\n self.ori1 = cfg1['ori']\n self.des1 = cfg1['des']\n ### uav2\n self.vuav2 = cfg2['vuav']\n self.a2 = cfg2['a']\n self.tt2 = cfg2['tt']\n self.ori2 = cfg2['ori']\n self.des2 = cfg2['des']\n\n self.vwind0 = vwind0\n self.alphaw0 = alphaw0\n\n self.refvel= refvel\n self.systime = systime\n self.refvalong = refvalong\n self.movevalong = movevalong\n self.fff = fff\n ### wind\n # self.vwind0 = vwind0\n # self.alphaw0 = alphaw0\n # self.evwind = evwind\n # self.ealphaw = ealphaw\n # self.cfg1evuav = cfg1evuav\n # self.cfg2evuav = cfg2evuav\n\n ####################### find boundary ##############################################################\n def dynuavbound(self):\n\n ########## ref, move boundary size #####################################33\n self.dynr1 = np.empty([1, 600])\n self.dynref2 = Bound(self.cfg1, self.vwind0, self.alphaw0)\n self.dynr2 = np.empty([1, 600])\n self.dynmove2 = Bound(self.cfg2, self.vwind0, self.alphaw0)\n for j in range(0, 600):\n self.dynref2.winderror()\n self.dynref2.dynuaverror()\n self.dynref2.size()\n self.dynr1[0, j] = self.dynref2.r\n\n self.dynmove2.winderror()\n self.dynmove2.dynuaverror()\n self.dynmove2.size()\n self.dynr2[0, j] = self.dynmove2.r\n\n self.dynr1 = np.sort(self.dynr1)\n self.dynr2 = np.sort(self.dynr2)\n\n ###### boundary to check ########################################\n self.dynrefcir1 = self.ori1\n self.dynrefr = self.dynr1[0, 539]\n\n self.dynmovecir1 = self.ori2\n self.dynmover = self.dynr2[0, 539]\n self.dynmovecir2 = self.dynmovecir1 + np.array(self.refvel) * self.systime\n\n self.moveortho = (-self.refvel[1], self.refvel[0])\n self.dynmovep1 = self.dynmovecir1 + self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.dynmovep2 = self.dynmovecir2 + self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.dynmovep3 = self.dynmovecir2 - self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.dynmovep4 = self.dynmovecir1 - self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n self.moveortho)\n self.dynmoverect = [self.dynmovep1, self.dynmovep2, self.dynmovep3, self.dynmovep4]\n\n # ####################### stop time ##############################################################\n # self.dynref = Bound(cfg1, self.vwind0, self.alphaw0)\n #\n # self.dynref.dynuaverror()\n # self.dynref.evuav = self.cfg1evuav\n # self.dynref.evwind = self.evwind\n # self.dynref.ealphaw = self.ealphaw\n # self.dynref.size()\n # self.tuav1 = np.linalg.norm(np.subtract(self.des1, self.ori1)) / self.dynref.valong\n #\n # self.dynmove = Bound(cfg2, self.vwind0, self.alphaw0)\n # self.dynmove.dynuaverror()\n # self.dynmove.evuav = self.cfg2evuav\n # self.dynmove.evwind = self.evwind\n # self.dynmove.ealphaw = self.ealphaw\n # self.dynmove.size()\n # self.tuav2 = np.linalg.norm(np.subtract(self.des2, self.ori2)) / self.dynmove.valong\n #\n # self.systime = min(self.tuav1, self.tuav2)\n #\n # ####################### ref boundary ##############################################################\n # self.dynrefcir1 = self.ori1\n # self.dynrefr = self.dynref.r\n #\n # ###################### move boundary ###############################################################\n # self.refvel = self.dynmove.uavvvec + self.dynmove.vecwind - self.dynref.uavvvec - self.dynref.vecwind\n # self.dynmovecir1 = self.ori2\n # self.dynmover = self.dynmove.r\n # self.dynmovecir2 = self.dynmovecir1 + np.array(self.refvel) * self.systime\n # self.moveortho = (-self.refvel[1], self.refvel[0])\n # self.dynmovep1 = self.dynmovecir1 + self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n # self.moveortho)\n # self.dynmovep2 = self.dynmovecir2 + self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n # self.moveortho)\n # self.dynmovep3 = self.dynmovecir2 - self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n # self.moveortho)\n # self.dynmovep4 = self.dynmovecir1 - self.dynmover / np.linalg.norm(self.moveortho) * np.array(\n # self.moveortho)\n # self.dynmoverect = [self.dynmovep1, self.dynmovep2, self.dynmovep3, self.dynmovep4]\n\n##################### collision check ##############################################################\n def dyncollision(self):\n FLAG = 0\n if self.fff == 1:\n self.dynuavbound()\n geo = geometry()\n if (\n geo.Flagrectc(self.dynmoverect, self.dynrefcir1, self.dynrefr) == 1 or\n geo.Flag2cir(self.dynmovecir1, self.dynmover, self.dynrefcir1, self.dynrefr) == 1 or\n geo.Flag2cir(self.dynmovecir2, self.dynmover, self.dynrefcir1, self.dynrefr) == 1\n ):\n FLAG = 1\n #print 'collision'\n return FLAG\n\n\n############################### geometry collision check ###########################################################\nclass geometry:\n ###################### check collision between rect and circle #################################################\n def dist(self, p1, p2, p3):\n x1, y1 = p1\n x2, y2 = p2\n x3, y3 = p3\n px = x2 - x1\n py = y2 - y1\n\n something = px * px + py * py\n\n u = ((x3 - x1) * px + (y3 - y1) * py) / (float(something)+1e-8)\n #print ((x3 - x1) * px + (y3 - y1) * py), u, something, float(something)\n if u > 1:\n u = 1\n elif u < 0:\n u = 0\n\n x = x1 + u * px\n y = y1 + u * py\n\n dx = x - x3\n dy = y - y3\n\n dist = math.sqrt(dx * dx + dy * dy)\n return dist\n\n def Flagrectc(self, rect, c, r):\n rect = rect\n c = c\n r = r\n\n distances = [self.dist(rect[i], rect[j], c) for i, j in zip([0, 1, 2, 3], [1, 2, 3, 0])]\n point = Point(c)\n polygon = Polygon(rect)\n\n flag = 0\n if any(d < r for d in distances) == True:\n flag = 1\n if any(d < r for d in distances) == False and polygon.contains(point) == True: #np.abs(\n #distances[0] + distances[2] - np.linalg.norm(np.subtract(rect[3], rect[0]))) < 10 ** -10 and np.abs(\n #distances[1] + distances[3] - np.linalg.norm(np.subtract(rect[1], rect[0]))) < 10 ** -10:\n flag = 1 # type: int\n return flag\n\n ####################### check collision between 2 rect ########################################\n def Flag2rect(self, poly1, poly2):\n polygons = [Polygon(poly1), Polygon(poly2)]\n flag = 0\n if polygons[0].intersects(polygons[1]) == True and polygons[0].touches(polygons[1]) == False:\n flag = 1\n return flag\n\n ####################### check collision between 2 circle ########################################\n def Flag2cir(self, c1, r1, c2, r2):\n flag = 0\n if np.linalg.norm(np.subtract(c1, c2)) < r1 + r2:\n flag = 1\n return flag\n\n\n\n################## Draw #################################################################################\nclass Draw:\n ###################### draw rect ################################################################\n def drawrect(self, ax, rect):\n coord = rect\n coord.append(coord[0]) #repeat the first point to create a 'closed loop'\n xs, ys = zip(*coord) #create lists of x and y values\n plt.plot(xs, ys)\n\n ################# draw circle ###################################################################\n def drawcir(self, ax, cir, r):\n circle1 = plt.Circle(cir, r)\n ax.add_artist(circle1)\n\n\n\n################# ori des ###############################################################################\nclass orides:\n def __init__(self, xx, yy):\n self.xx = xx\n self.yy = yy\n\n ############# a=(x=0, x=xx, y=0, y=yy)########################################################################\n def point(self):\n aa = [(0, np.random.uniform(0, self.yy)), (self.xx, np.random.uniform(0, self.yy)), (np.random.uniform(0, self.xx), 0), (np.random.uniform(0, self.xx), self.yy)]\n a = range(0, 3)\n o = random.choice(a)\n self.ori = aa[o]\n a.remove(o)\n d = random.choice(a)\n self.des = aa[d]\n return self.ori\n return self.des\n\n\n#######################################################################################################################################################################################\nif __name__ == '__main__':\n\n N = 100000\n Cpro = 0\n Cdyn = 0\n Csta = 0\n xx = 800\n yy = 800\n\n inputs = range(N)\n t1=time.time()\n def processInput(i):\n #for i in range(0, N):\n ccc1 = orides(xx, yy)\n ccc1.point()\n ccc2 = orides(xx, yy)\n ccc2.point()\n\n cfg1 = {'vuav': np.random.lognormal(3,0.1), #np.random.lognormal(3,0.1),\n 'a': np.random.uniform(3.2, 6.7), #np.random.uniform(3.2, 6.7),\n 'tt': np.random.uniform(0,2), #np.random.uniform(0,2),\n 'ori': ccc1.ori,\n 'des': ccc1.des}\n\n cfg2 = {'vuav': np.random.lognormal(3,0.1), #np.random.lognormal(3,0.1),\n 'a': np.random.uniform(3.2, 6.7), #np.random.uniform(3.2, 6.7),\n 'tt': np.random.uniform(0,2), #np.random.uniform(0,2),\n 'ori': ccc2.ori,\n 'des': ccc2.des}\n\n vwind0 = 3.2 * np.random.weibull(2.2)\n alphaw0 = np.random.uniform(0, 2*np.pi) #2*\n\n #t1=time.time()\n cr1 = Conflict(cfg1, cfg2, vwind0, alphaw0)\n #Cpro = Cpro + cr1.collision()\n a = cr1.collision()\n #t2=time.time()\n cr2 = dynconflict(cfg1, cfg2, vwind0, alphaw0, cr1.refvel, cr1.systime, cr1.ref.valong, cr1.move.valong, cr1.fff)\n #Cdyn = Cdyn + cr2.dyncollision()\n b = cr2.dyncollision()\n #print cr2.dynmover, cr2.dynrefr\n #t3=time.time()\n cr3 = staticconflict(cfg1, cfg2, cr1.refvel, cr1.systime, cr1.ref.valong, cr1.move.valong, cr1.fff)\n # Csta = Csta + cr3.staticcollision()\n c = cr3.staticcollision()\n\n return [a, b, c]\n\n #t4=time.time()\n\n num_cores = multiprocessing.cpu_count()\n\n results = Parallel(n_jobs=num_cores)(delayed(processInput)(i) for i in inputs)\n t2 = time.time()\n #print t2-t1, t3-t2, t4-t3\n # sta = sta + Csta\n # dyn = dyn + Cdyn\n # pro = pro + Cpro\n #print results\n print (np.sum(results, axis=0))\n print (t2-t1)\n\n #print Csta\n #print Cdyn\n # print Cpro\n\n # plt.figure(1)\n # ax = plt.gca()\n # plt.xlim(-100, 1000)\n # plt.ylim(-100,1000)\n # Draw().drawrect(ax, cr1.moverect)\n # plt.hold('True')\n # Draw().drawrect(ax, cr1.refrect)\n # plt.hold('True')\n # Draw().drawcir(ax, cr1.refcir1, cr1.refr)\n # plt.hold('True')\n # Draw().drawcir(ax, cr1.refcir2, cr1.refr)\n # plt.hold('True')\n # Draw().drawcir(ax, cr1.movecir1, cr1.mover)\n # plt.hold('True')\n # Draw().drawcir(ax, cr1.movecir2, cr1.mover)\n #\n # plt.figure(2)\n # ax2 = plt.gca()\n # plt.xlim(-100, 1000)\n # plt.ylim(-100, 1000)\n # Draw().drawrect(ax2, cr3.staticmoverect)\n # plt.hold('True')\n # Draw().drawcir(ax2, cr3.staticrefcir1, cr3.staticrefr)\n # plt.hold('True')\n # Draw().drawcir(ax2, cr3.staticmovecir2, cr3.staticmover)\n # plt.hold('True')\n # Draw().drawcir(ax2, cr3.staticmovecir1, cr3.staticmover)\n # # plt.show()\n #\n # plt.figure(3)\n # ax3 = plt.gca()\n # plt.xlim(-100, 1000)\n # plt.ylim(-100, 1000)\n # Draw().drawrect(ax3, cr2.dynmoverect)\n # plt.hold('True')\n # Draw().drawcir(ax3, cr2.dynrefcir1, cr2.dynrefr)\n # plt.hold('True')\n # Draw().drawcir(ax3, cr2.dynmovecir2, cr2.dynmover)\n # plt.hold('True')\n # Draw().drawcir(ax3, cr2.dynmovecir1, cr2.dynmover)\n # plt.show()\n\n # Csta\n # c1 = Bound(cfg1, 3, np.pi / 4)\n # c1.winderror()\n # c1.uaverror()\n # c1.size()\n # c2 = Bound(cfg1, c1.vwind0, c1.alphaw0)\n # c2.evwind = c1.evwind\n # c2.ealphaw = c1.ealphaw\n # c2.evuav = c1.evuav\n # c2.dynuaverror()\n # c2.size()\n # c3 = Bound(cfg1, c1.vwind0, c1.alphaw0)\n # c3.staticwinderror()\n # c3.staticuaverror()\n # c3.size()\n # ccc = Conflict(cfg1, cfg2, 3, np.pi / 4)\n # ccc.uavbound()\n # print ccc.collision()\n","sub_path":"conflictrate.py","file_name":"conflictrate.py","file_ext":"py","file_size_in_byte":27766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"21692086","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport random\n\n\ndef HomogeneousPoisson(rate, duration, dt=1e-3):\n '''\n Homogeneous Poisson process spike generator,\n implemented by dividing time into bins of and\n calculating probability of spike generation at each bin\n\n Return: array with spike times\n '''\n NoBins = int(duration / dt)\n time = np.random.uniform(0, 1, NoBins)\n\n # choose elements that have x_rand less than prob. of firing a spike\n spikes_indices = np.nonzero(rate * dt > time)\n\n # convert indices to time\n spikes = (np.array(spikes_indices) / NoBins) * duration\n\n return spikes.flatten()\n\ndef HomogeneousPoissonEfficient(rate, duration):\n '''\n Hoomogeneous Poisson process spike generator,\n implemented by estimating interspike intervals.\n\n Return: array with spike times\n '''\n spikes = [0]\n\n while spikes[-1] < duration:\n spikes.append( spikes[-1] - np.log(np.random.rand()) / rate )\n\n return np.array( spikes[1:-1] )\n\ndef NonhomogeneousPoisson(rate_func, duration):\n '''\n Nonhomogeneous Poisson process spike generator\n with time-dependent firing rate\n\n Return: array with spike times\n '''\n r_max = np.max( rate_func( np.linspace(0, duration, duration*1000 ) ))\n spikes = [0]\n while spikes[-1] < duration:\n spikes.append( spikes[-1] - np.log(np.random.rand()) / r_max )\n ToBeRemoved = []\n for i in range(1, len(spikes)):\n if rate_func(spikes[i])/r_max < np.random.rand():\n ToBeRemoved.append(i)\n spikes_thinned = np.delete( np.array(spikes), ToBeRemoved )\n return spikes_thinned\n\ndef NonhomogeneousPoissonVector(rate_vec, time, duration):\n '''\n Nonhomogeneous Poisson process spike generator\n with time-dependent firing rate\n\n Return: array with spike times\n '''\n r_max = rate_vec.max()\n spikes = [0]\n while spikes[-1] < duration:\n spikes.append( spikes[-1] - np.log(np.random.rand()) / r_max )\n ToBeRemoved = []\n for i in range(1, len(spikes)):\n\t\t# get the index in the rate_vec that is closest to the spike time\n idx = np.argmax(time >= spikes[i]) - 1\n if rate_vec[idx]/r_max < np.random.rand():\n ToBeRemoved.append(i)\n spikes_thinned = np.delete( np.array(spikes), ToBeRemoved )\n return spikes_thinned, spikes\n\n\ndef HomogeneousPoissonRefractory(rate, duration, tau):\n '''\n Homogeneous Poisson spike generator,\n with dynamic refractoriness after the spike\n '''\n spikes = [0]\n while spikes[-1] < duration:\n spikes.append(spikes[-1] - np.log(np.random.rand()) / rate)\n ToBeRemoved = []\n for i in range(1, len(spikes)):\n t = spikes[i]\n t_prev = spikes[i-1]\n # calculating how much rate has recovered after previous spike\n new_rate = rate_recovery(t - t_prev, r0=rate, tau_ref=tau)\n x_rand = random.random()\n if new_rate / rate < x_rand:\n ToBeRemoved.append(i)\n spikes = np.delete( np.array(spikes), ToBeRemoved )\n return spikes\n\ndef rate_recovery(t, r0, tau_ref):\n '''\n Introduces exponential recovering of firing rate,\n after firing a spike\n Should be used with Inhomogeneous Poisson process\n '''\n tau_ref /= 1000 # converts to seconds\n return r0 * (1 - np.exp(-t/tau_ref) )\n\ndef STA(stim, time, spikes, window=500):\n '''Spike-triggered average, by summing stimulus in the range \n spike_time - 300 ms for all spikes and dividing by the number of sums\n '''\n window /= 1000 # converts to seconds\n sum_stim = np.zeros(np.shape(stim[:np.argmax(time > window)]))\n valid_spikes = spikes[np.argmax(spikes > window):np.argmax(spikes > time.max())]\n for t in valid_spikes:\n start = np.argmax(time > t-window) - 1\n end = np.argmax(time > t)\n sum_stim += stim[start:end]\n avg_stim = sum_stim / len(valid_spikes)\n time_stim = time[:np.argmax(time > window)]\n return avg_stim, time_stim\n\ndef STA_new(stim, time, spikes, window=500):\n '''\n This Spike-triggered averaging works with binary string of spikes [0,1] = [not a spikes, spike];\n and time vector, which is used for finding time steps for the window and giving time sequence for \n plotting STA stimulus\n '''\n window /= 1000 # converts to seconds\n time_steps = int(window / (time[1]-time[0]))\n sum_stim = np.zeros((time_steps, 1))\n for i, val in enumerate(spikes):\n if i > time_steps:\n if val == 1:\n sum_stim += stim[i - time_steps: i] \n avg_stim = sum_stim / len(spikes[spikes==1])\n time_stim = time[:time_steps]*(-1)\n return avg_stim, time_stim\n \n\ndef PlotTrials(process=HomogeneousPoissonEfficient, rate=40, duration=1, trials=20):\n plt.figure(figsize=(8, 5), dpi=100)\n NeuralResponses = []\n for i in range(trials):\n NeuralResponses.append( process(10, 1) )\n\n plt.eventplot(NeuralResponses, linelengths=0.5)\n plt.xlabel('time [ms]')\n plt.ylabel('trial number')\n\ndef distribution_spike_counts(spikes, step_interval=100, bindwidth=1, plot=False):\n spikes_counts = spike_count(spikes, step_interval)\n if plot:\n plt.figure(dpi=100)\n plt.hist(spikes_counts, bins='auto',\n color='purple', ec='black')\n plt.xlabel('no. of spikes in the interval')\n else:\n return spikes_counts\n\ndef ISI_distribution(spikes):\n isi = np.diff(spikes) * 1000\n plt.hist(isi, bins='auto', color='purple', ec='black')\n plt.xlabel('ISI [ms]', fontsize=16)\n plt.ylabel('no. of intervals', fontsize=16)\n\ndef spike_count(spikes, step_interval=100):\n '''\n Calculates the number of spikes over duration of spikes\n with a given step interval\n '''\n spikes_counts = []\n step_interval /= 1000 # converts to seconds\n start = 0\n end = step_interval\n while end <= np.max(spikes):\n spikes_counts.append( len(spikes[ (spikes > start) & (spikes <= end) ] ) )\n start += step_interval\n end += step_interval\n return np.array(spikes_counts)\n\n\ndef crosscorrelation2(ts1, ts2, time, time_lag=100):\n\t'''Calculates crosscorrelation function for \n\ttwo time series t1 and t2 in the range of time_lag\n\t'''\n\ttime_lag /= 1000 # convert to seconds\n\t# this is needed to conserve temporal resolution\n\tCorrespondingTimeIdx = np.argmax(time > time_lag)\n\tQ = np.zeros(CorrespondingTimeIdx + 1)\n\t# averaging term: dt divided by the duration of the trial\n\tΔt = time[1] - time[0]\n\tfor tau in range( len(Q) ):\n\t\tshift_backward = np.hstack((ts1[tau:], ts1[:tau]))\n\t\tM = len(shift_backward)\n\t\tinitial = np.hstack((ts2[:M], ts1[M:]))\n\t\tQ[tau] = (Δt/float(M)) * np.sum(initial * shift_backward) \n\t\t\n\treturn Q, time[:CorrespondingTimeIdx+1] * (-1)\n\t\t\n\ndef autocorrelation(spikes, time_lag=100, dt=1e-2):\n '''\n Computes autocorrelation histogram, by dividing\n time into bins and calculating. For each bin we calculate the no. of\n times 2 spikes are separated by some ISI (ms) (x-axis).\n '''\n duration = np.max(spikes)\n time_lag /= 1000 # convert to seconds\n NoBins = int( time_lag/dt)\n CountIntervals = []\n IBS = []\n for i in range(len(spikes)):\n # counting differences in time between current spike and all subsequent spikes\n intervals = spikes - spikes[i]\n IBS.extend(intervals)\n IBS = np.array(IBS)\n for m in range(-NoBins, NoBins+1):\n lower = m*dt - (dt/2)\n upper = m*dt + (dt/2)\n InBin = np.count_nonzero( (IBS >= lower) & (IBS < upper) )\n InBin = (InBin/duration) - ((len(spikes)*len(spikes) * dt) / (duration**2))\n CountIntervals.append(InBin)\n\n CountIntervals = np.array(CountIntervals)\n BinsBoundaries = np.array([m*dt for m in range(-NoBins, NoBins+1)]) * 1000\n return BinsBoundaries, CountIntervals\n\ndef fano(spikes):\n '''\n Computes Fanos factors for different intervals over\n which spikes are counted.\n duration/interval = no. of counts\n F = Var(X) / mean(X)\n '''\n fanos = []\n spikes = np.array(spikes)\n for t in range(1, 100): # ms\n spikes_counts = spike_count(spikes, step_interval=t)\n fanos.append( np.var(spikes_counts) / np.mean(spikes_counts) )\n return fanos\n\ndef coefficient_variation(data):\n '''\n C_v = std(X) / mean(X)\n '''\n return np.std(data) / np.mean(data)\n","sub_path":"chapter2/spike_generator.py","file_name":"spike_generator.py","file_ext":"py","file_size_in_byte":8313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"616419631","text":"# File: breedCate.py\r\n# Author: Simon Chu\r\n# Date modified: 7/11/2017\r\n# Purpose: find different kinds of images\r\n# click Stop box to end the program\r\n\r\n# Designed by Simon Chu\r\n# for Wilkes University Research Project of Mathematics\r\n# and Computer Science Department in Summer, 2017\r\n\r\n\r\nimport os\r\nimport shutil\r\nimport sys\r\nimport datetime\r\n\r\n\r\ndef progress(count, total):\r\n bar_len = 60\r\n filled_len = int(round(bar_len * count / float(total)))\r\n\r\n percents = round(100.0 * count / float(total), 1)\r\n bar = '=' * filled_len + '-' * (bar_len - filled_len)\r\n\r\n sys.stdout.write('[%s] %s%s ...%s\\r' % (bar, percents, '%', 'progress'))\r\n #sys.stdout.flush()\r\n\r\n\r\ndef main():\r\n\r\n # list files in target folder\r\n path = input(\"Please enter the directory path that you want to categorize(without '/' at the end: \")\r\n directList = os.listdir(path)\r\n\r\n # open the code file\r\n fileName1 = '../code/code1.txt' # path to file: breed tags\r\n breedList = open(fileName1, 'r').read().split('\\n')\r\n\r\n\r\n\r\n\r\n # init count num variable\r\n count = 1\r\n\r\n\r\n # init total\r\n total = len(directList)\r\n\r\n for s in directList:\r\n\r\n # init breedName & eyeNumber\r\n breedName = \"Unknown\"\r\n\r\n\r\n format = 'jpg'\r\n if s[-3:] == format:\r\n i = s[:-4]\r\n\r\n count = count + 1\r\n\r\n\r\n # grab the breed\r\n try:\r\n breed = i[6:8]\r\n except IndexError:\r\n breedName = \"Unknown\"\r\n except NameError:\r\n breedName = \"Unknown\"\r\n else:\r\n breed = i[6:8]\r\n\r\n for line in breedList:\r\n\r\n j = line.split(': ')\r\n\r\n if breed == j[0]:\r\n breedName = j[1]\r\n elif breed == \"MI\":\r\n breedName = \"Mixed Breed\"\r\n\r\n\r\n filePath = \"breed/\" + breedName\r\n if not os.path.exists(filePath):\r\n os.makedirs(filePath)\r\n\r\n\r\n imgPath = path + '/' + s\r\n\r\n\r\n shutil.copy2(imgPath, filePath + '/' + s)\r\n\r\n\r\n\r\n print(str(round(100.0 * count / float(total), 1)) + '%')\r\n if s == directList[-1]:\r\n print()\r\n print('Done!')\r\n file = open(\"breed/log.txt\", 'a+')\r\n\r\n time = datetime.datetime.now().strftime(\"%I:%M%p on %B %d, %Y\")\r\n\r\n\r\n fileWrote = str(total)\r\n string = \"Time: \" + time + \" File wrote: \" + fileWrote + '\\n'\r\n print(string)\r\n file.write(string)\r\n file.close()\r\n print('log file generated!')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nmain()\r\n","sub_path":"dataCategorization/directCate/breedCate.py","file_name":"breedCate.py","file_ext":"py","file_size_in_byte":2673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"92007286","text":"# Given a phone keypad as shown below:\n\n# 1 2 3\n# 4 5 6\n# 7 8 9\n# 0\n# How many different 10-digit numbers can be formed starting from 1?\n# The constraint is that the movement from 1 digit to the next is similar\n# to the movement of the Knight in a chess game.\n# For eg. if we are at 1 then the next digit can be either 6 or 8 if we are at 6\n# then the next digit can be 1, 7 or 0.\n\n# Repetition of digits are allowed - 1616161616 is a valid number.\n\nknight_move = {\n 1 : [8,6],\n 2 : [7,9],\n 3 : [4,8],\n 4 : [0,9],\n 5 : None,\n 6 : [0,7],\n 7 : [2,6],\n 8 : [1,3],\n 9 : [2,4],\n 0 : [4,6]\n}\n\ndef find_10_digit_num_count(start_num,count):\n if count == 1:\n return 1\n if start_num == 5:\n return 0\n # find the knight next position\n next_move = knight_move[start_num]\n return find_10_digit_num_count(next_move[0],count - 1) + find_10_digit_num_count(next_move[1],count - 1)\n\nmemo_dict = {}\ndef find_10_digit_num_count_memo(start_num,count):\n if count == 1:\n return 1\n if start_num == 5:\n return 0\n # check if already computed\n if (start_num,count) in memo_dict:\n return memo_dict[(start_num,count)]\n\n # find the next position\n next_move = knight_move[start_num]\n first_move = find_10_digit_num_count_memo(next_move[0], count - 1)\n second_move = find_10_digit_num_count_memo(next_move[1], count - 1)\n memo_dict[(start_num,count)] = first_move + second_move\n return (first_move+second_move)\n\n# Below shows how the DP table is filled\n# 0 1 2 3 4 5 6 7 8 9 Digit in the keypad\n# 1 1 1 1 1 1 0 1 1 1 1 Count for 1 digit\n# 2 2 2 2 2 2 0 2 2 2 2 Count for 2 digit\n# 3 4 4 4 4 4 0 4 4 4 4 Count for 3 digit\n# 4 8 8 8 8 8 0 8 8 8 8\n# . . . . . . . . . . .\n# 10 512 512 512 512 512 0 512 512 512 512 Count for 10 digit\n# The table id filled by adding the the value from the posotion which leads to\n# the current position\n# e.g Count of numbers form of length 3 dtarting at 1 is given by sum of counts\n# of length 2 at position 6 and 8\n# If we look closely the answer is just 2 ** (digit_count -1) , since in each\n# number can be reached from 2 other number\n\ndef find_10_digit_num_count_memo_bottom_up(start_num,count):\n # Auxillary array to hold the result\n S = [[0] * 10 for i in range(count)]\n\n # Initialize the base case\n for i in range(10):\n S[0][i] = 1\n # Set 0 for 5\n S[0][5] = 0\n\n\n for i in range(1,count):\n for j in range(10):\n previous_pos = knight_move[j]\n if previous_pos is not None:\n S[i][j] = S[i-1][previous_pos[0]] + S[i-1][previous_pos[1]]\n else:\n S[i][j] = 0\n\n return S[count-1][start_num]\n\nif __name__ == \"__main__\":\n\n print(find_10_digit_num_count(1,10))\n print(find_10_digit_num_count_memo(1,10))\n print(find_10_digit_num_count_memo_bottom_up(1,10))\n","sub_path":"src/DP/knights_tour.py","file_name":"knights_tour.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"298307172","text":"#!/opt/anaconda3/bin/python -u\nimport getopt\nimport os.path\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom time import sleep\nfrom datetime import datetime, timedelta\nsys.path.append(os.path.abspath(os.path.dirname(__file__) + '/' + '../..'))\nfrom common.lib.log import debug, error, fatal, info, warn\nfrom common.lib.cal import business_days\nfrom common.lib.db import query_mysql\nfrom common.lib.sym import local_hk_symbology\nfrom data.lib.reports import set_charges\n\n__ACCOUNTID__ = \"CPB10860\"\n\ndef print_usage():\n print (\" Usage: %s [options]\" % (os.path.basename(__file__))) \n print (\" Options:\")\n print (\" \\t-c, --exchcode\\t\\texchange code\")\n print (\" \\t-d, --database\\t\\tdatabase connection string\")\n print (\" \\t-p, --portfolio\\t\\tportfolio name\")\n print (\" \\t-s, --start\\t\\tstart date\")\n print (\" \\t-e, --end\\t\\tend date\") \n print (\" \\t-i, --input\\t\\tinput directory\") \n print (\" \\t-r, --dryrun\\t\\tdry run\") \n print (\" \\t-h,\\t\\t\\thelp\")\n\ndef format_time(time):\n today = datetime.strftime(datetime.now(), \"%Y%m%d\")\n return datetime.strptime(today + \"T\" + time, \"%Y%m%dT%H:%M:%S\")\n \ndef stockloan_payments(iDate, iPortfolio, dbConn, exchCode, inputDir, dryRun):\n inputFile = \"%s/SUB_%s_20953289.CSV\" % (inputDir, iDate.strftime(\"%Y-%m-%d\"))\n if os.path.exists(inputFile):\n info(\"Reading file %s\" % (inputFile))\n stockloan_df = pd.read_csv(inputFile, skiprows=1, parse_dates=['From Date','To Date'])\n stockloan_df = stockloan_df[stockloan_df['Account ID'] == __ACCOUNTID__] # filter by account\n \n stockload_grp_df = stockloan_df.groupby('To Date').sum()\n stockload_grp_df = pd.DataFrame(stockload_grp_df['Amount Due in Accrual Currency'])\n stockload_grp_df = stockload_grp_df.reset_index()\n stockload_grp_df.columns = ['date','amount']\n stockload_grp_df['type'] = 'Borrow Fee'\n stockload_grp_df['indicator'] = 'Short'\n stockload_grp_df['portfolio'] = iPortfolio\n\n # prepare insert to portfolios/charges database\n set_charges(stockload_grp_df, dbConn, dryrun=dryRun) \n \n else:\n warn(\"File %s not found.\" % (inputFile))\n \ndef main(argv): \n argDBConn = \"\"\n argExchCode = \"\"\n argPortfolio = \"\"\n argStart = \"\"\n argEnd = \"\"\n argDryRun = True \n argInput = \"/home/sqtdata/dfs/raw/live/bcar.day/reports\"\n try:\n opts, args = getopt.getopt(argv,\"hrc:d:s:e:p:i:\",[\"dryrun\",\"database=\",\"exchcode=\",\"start=\",\"end=\",\"portfolio=\",\"input=\"])\n except getopt.GetoptError:\n print_usage()\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print_usage()\n sys.exit()\n elif opt in (\"-d\", \"--database\"):\n argDBConn = arg \n elif opt in (\"-c\", \"--exchcode\"):\n argExchCode = arg\n elif opt in (\"-p\", \"--portfolio\"):\n argPortfolio = arg \n elif opt in (\"-s\", \"--start\"):\n argStart = datetime.strptime(arg, '%Y%m%d')\n elif opt in (\"-e\", \"--end\"):\n argEnd = datetime.strptime(arg, '%Y%m%d') \n elif opt in (\"-i\", \"--input\"):\n argInput = arg \n elif opt in (\"-r\", \"--dryrun\"):\n argDryRun = False \n \n if len(argDBConn) == 0 or len(argExchCode) == 0 or len(argPortfolio) == 0 or len(argInput) == 0:\n print_usage()\n exit(0)\n if argStart > argEnd:\n error(\"Start date must be less than End date\")\n print_usage()\n exit(0) \n \n dates = business_days(argStart, argEnd, argExchCode)\n for date in dates:\n info(\"Running payments for %s\" % (date.strftime('%Y-%m-%d')))\n stockloan_payments(date, argPortfolio, argDBConn, argExchCode, argInput, argDryRun)\n \nif __name__ == '__main__':\n main(sys.argv[1:])\n \n","sub_path":"portlab/report/bin/stockloan_payments.py","file_name":"stockloan_payments.py","file_ext":"py","file_size_in_byte":3920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"214035988","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Mar 20 11:36:32 2017\r\n\r\n@author: maxim\r\n\"\"\"\r\n\r\nimport dimensionless_parameters as dp\r\nimport read_flight_data as rfd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport ISA_Calculation_Tool as isa\r\nimport utility_functions as utils\r\nimport ac_characteristics as ac\r\n\r\ndef moment_datum_at_index_m(index,flightdata):\r\n #This function calculates the moment arm with respect to the datum line (nosecone) in meters.\r\n #First getting several parameters used in the calculation\r\n gravity = 9.81\r\n ac_parameters = ac.get_ac_general_parameters()\r\n payloads_arms = ac.get_payload_arms_m()\r\n #Defining when the mass distribution changes during the flight\r\n index_begin_changed_cg = 25900\r\n index_end_changed_cg = 26600\r\n #Depending on whether or not index falls within the time interval when the mass is changed,\r\n #the appropriate mass distribution dictionairy is loaded.\r\n if index_begin_changed_cg <= index < index_end_changed_cg:\r\n payloads_masses = ac.get_payload_masses_movedpassenger_kg()\r\n else:\r\n payloads_masses = ac.get_payload_masses_kg()\r\n #Next the moment caused by the payload is calculated by iterating over the keys in the payloads_masses dictionairy.\r\n payload_moment = 0\r\n for key in payloads_masses:\r\n payload_moment += payloads_arms[key]*payloads_masses[key]*gravity\r\n #Next the fuel mass remaining is calculated \r\n fuel_mass_remaining = ac_parameters[\"AC_fuel_at_takeoff\"] - ac.used_fuel_at_index_kg(index,flightdata)\r\n #And then the moment caused by the remaining fuel is calculated and multiplied with gravity to obtain NM\r\n fuel_moment = gravity * ac.get_fuel_moment_kgm(fuel_mass_remaining)\r\n #The total weight of the aircraft at the index is determined.\r\n totalweight = ac.total_weight_at_index_N(index,flightdata)\r\n #Then the total moment is determined using the parameters above.\r\n total_moment = ac_parameters[\"AC_empty_moment_NM\"] + payload_moment + fuel_moment\r\n #Finally the moment arm is determined by dividing the total_moment by the total weight.\r\n moment_arm_total = total_moment/totalweight\r\n return moment_arm_total\r\n\r\ndef moment_leading_edge_at_index(index,flightdata):\r\n #This function takes the moment arm with respect to the datum and converts it to a distance to the leading edge.\r\n xcg_datum_m = moment_datum_at_index_m(index,flightdata)\r\n xcg_le = xcg_datum_m - utils.inches_to_m(261.56)\r\n return xcg_le\r\n\r\ndef moment_normalised_c_at_index_percent(index,flightdata):\r\n #This function takes the moment with respect to the leading edge and divides it by the mean airdynamic chord,\r\n #to obtain a dimensionless parameter, which allows comparison to other aircraft.\r\n xcg_le = moment_leading_edge_at_index(index,flightdata)\r\n #inputting the chrod length and converting it to meters.\r\n c= ac.get_ac_general_parameters()[\"Mac\"]\r\n xcg_normalised = (xcg_le / c)*100\r\n return xcg_normalised\r\n\r\ndef graph_cg_change(flightdata,startindex,endindex,num_of_steps,cg_unit):\r\n #This function is used to graph the cg change over a certain index range in the given number of steps.\r\n #Depending on what is defined for cg_unit, the corresponding graph is returned.\r\n #Look in the if statements below for the possible choices of cg_unit.\r\n #the save_graphs parameter can be adjusted to save the figures.\r\n indexes = np.linspace(startindex,endindex-1,num_of_steps)\r\n cgs = []\r\n ts = []\r\n for index in indexes:\r\n index = int(np.round(index,0))\r\n if cg_unit == \"cg_datum_inches\":\r\n #Cg in meters to the nose\r\n cgs.append(utils.m_to_inches(moment_datum_at_index_m(index,flightdata)))\r\n label_unit = \"[inches]\"\r\n if cg_unit == \"cg_datum_m\":\r\n #Cg in meters to the nose\r\n cgs.append(moment_datum_at_index_m(index,flightdata))\r\n label_unit = \"[m]\"\r\n if cg_unit == \"cg_le\":\r\n #Cg in meters to the leading edge\r\n cgs.append(moment_leading_edge_at_index(index,flightdata))\r\n label_unit = \"[m]\"\r\n if cg_unit == \"cg_rel\":\r\n #Cg in percent over the MAC\r\n cgs.append(moment_normalised_c_at_index_percent(index,flightdata))\r\n label_unit = \"[%]\"\r\n ts.append(flightdata[\"T\"][\"data\"][index])\r\n save_graphs = False\r\n if save_graphs:\r\n #Graphing and saving the graphs:\r\n utils.plot_x_y(ts,cgs,\"Time [s]\",\"Cg position wrt nose \"+str(cg_unit)+\" \"+str(label_unit),\"cg_graph/\")\r\n else:\r\n #Only graphing but not saving them:\r\n utils.plot_x_y(ts,cgs,\"Time [s]\",\"Cg position wrt nose \"+str(cg_unit)+\" \"+str(label_unit))\r\n return\r\n \r\ndef graph_fuel_usage(flightdata,startindex,endindex,num_of_steps):\r\n #This function can be used to graph the fuel usage throughout a range of index in a number of steps.\r\n indexes = np.linspace(startindex,endindex-1,num_of_steps)\r\n fuelused = []\r\n ts = []\r\n for index in indexes:\r\n index = int(np.round(index,0))\r\n fuelused.append(ac.used_fuel_at_index_kg(index,flightdata))\r\n ts.append(flightdata[\"T\"][\"data\"][index])\r\n utils.plot_x_y(ts,fuelused,\"Time [s]\",\"Fuel used [kg]\")\r\n \r\nif __name__ == \"__main__\":\r\n flightdata = rfd.get_flightdata_dict()\r\n measurement_indexes = rfd.get_measurements_indexes(flightdata)\r\n index_of_interest = 10000\r\n #print(ac.used_fuel_at_index_kg(index_of_interest,flightdata))\r\n #totalweight = ac.total_weight_at_index(42000,flightdata)\r\n cg = moment_datum_at_index_m(index_of_interest,flightdata)\r\n print(\"Center of gravity [m] from nose: \"+str(cg))\r\n print(\"Center of gravity [inces] from nose: \"+str(utils.m_to_inches(cg)))\r\n #graph_fuel_usage(flightdata,0,len(flightdata[\"T\"][\"data\"]),100)\r\n #graph_cg_change(flightdata,0,len(flightdata[\"T\"][\"data\"]),100,\"cg_rel\")\r\n delta_cg = moment_datum_at_index_m(25699,flightdata) - moment_datum_at_index_m(25700,flightdata)\r\n print(\"Delta cg: \"+str(delta_cg))\r\n# cg_untis_wanted = [\"cg_datum_inches\",\"cg_datum_m\",\"cg_le\",\"cg_rel\"]\r\n# for cg_type in cg_untis_wanted:\r\n# graph_cg_change(flightdata,0,len(flightdata[\"T\"][\"data\"]),400,cg_type)\r\n ","sub_path":"cg_calculator_2.py","file_name":"cg_calculator_2.py","file_ext":"py","file_size_in_byte":6296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"595075845","text":"from unittest import TestCase\n\nimport pyVmomi\n\nfrom k8_vmware.linux.Ubuntu import Ubuntu\nfrom k8_vmware.vsphere.VM_Create import VM_Create\n\n\nclass test_Ubuntu(TestCase):\n\n def setUp(self) -> None:\n self.vm_create = VM_Create()\n self.vm = self.vm_create.create()\n self.vm_name = self.vm_create.vm_name\n self.ubuntu = Ubuntu(self.vm_name)\n\n def tearDown(self) -> None:\n self.vm.task().delete()\n\n def test__init__(self):\n assert self.ubuntu.vm_name == self.vm_name\n\n def test_vm(self):\n assert self.ubuntu.vm().name() == self.vm_name\n assert self.ubuntu.exists()\n\n def test_sample_properties_fetch(self):\n sdk = self.ubuntu.sdk\n vm = sdk.get_object(pyVmomi.vim.VirtualMachine, self.vm_name)\n assert vm.name == self.vm_name\n\n properties = ['parent', 'configStatus', 'config', 'tag']\n result = sdk.get_objects_properties(pyVmomi.vim.VirtualMachine, [vm], properties)\n self.assertIsNotNone(result.get(self.vm.id()).get(\"config\"))\n self.assertIsNotNone(result.get(self.vm.id()).get(\"parent\"))\n self.assertIsNotNone(result.get(self.vm.id()).get(\"configStatus\"))\n self.assertIsNotNone(result.get(self.vm.id()).get(\"tag\"))\n","sub_path":"tests/unit/linux/test_Ubuntu.py","file_name":"test_Ubuntu.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"54446964","text":"# import unicodecsv\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom networkx.algorithms import community\n\n# Computed only once\n# row = []\n# with open('casts.csv', 'r') as f:\n# tmp = unicodecsv.reader(f, delimiter=';', encoding=\"utf-8\")\n# for line in tmp:\n# # Filtering outliers\n# if(len(line[0]) > 1 and len(line[0]) < 6):\n# row.append(line)\n# actorsAndMovies = {}\n# for i in range(len(row)):\n# if(row[i][2] not in actorsAndMovies):\n# name = row[i][2]\n# tmp = []\n# for j in range(len(row)):\n# if(row[j][2] == row[i][2] and\n# row[j][1] not in tmp):\n# tmp.append(row[j][1])\n# actorsAndMovies[name] = tmp\n# save = open(\"save.txt\", \"w\")\n# for actor in actorsAndMovies:\n# line = actor.encode('utf-8') + \";\"\n# word = str(actorsAndMovies[actor]).encode('utf-8') + \"\\n\"\n# save.write(line+word)\n\ntext = None\nwith open(\"save.txt\", \"r\") as f:\n text = f.read()\n text = text.split(\"\\n\")\n# We got a '' because of split(\"\\n\") so we delete this element\ndel text[-1]\ntab = []\nfor line in text:\n line = line.split(\";\")\n # removing space betwen \":\"\n line[1] = line[1].replace('u', '')\n line[1] = line[1].replace('[', '')\n line[1] = line[1].replace(']', '')\n tab.append(line)\n# deleting first element because it is the actor \" \" so no meaning keeping this\ndel tab[0]\nfor i in range(len(tab)):\n tab[i][1] = tab[i][1].split(\",\")\n # we remove blank space after the comma\n tab[i][1] = [word.strip() for word in tab[i][1]]\n\n# Creating the graph now\nG = nx.Graph()\nfor i in range(len(tab)):\n G.add_node(tab[i][0], label=tab[i][0])\n for j in range(i+1, len(tab)):\n for movie in tab[j][1]:\n if(movie in tab[i][1]):\n G.add_edge(tab[i][0], tab[j][0], label=movie, weight=1)\nprint(\"Number of nodes: %s\" % nx.number_of_nodes(G))\nprint(\"Number of edges: %s\" % nx.number_of_edges(G))\nprint(\"Density: %s\" % nx.density(G))\narrays = []\nfor component in nx.connected_components(G):\n arrays.append(list(component))\ni = 0\nfor array in arrays:\n i += 1\nprint(\"Number of components: %s\" % i)\n\ncentralities = [nx.degree_centrality, nx.eigenvector_centrality]\n# closeness centrality, betweeness centrality don't work, it gets stuck\nlargest_cc = max(nx.connected_components(G), key=len)\nsubgraph = G.subgraph(largest_cc)\ncentralTab = {}\nfor centrality in centralities:\n topNode = []\n print(centrality.__name__)\n result = centrality(G)\n for k in result:\n valueWithIndex = [result[k], k]\n topNode = sorted(topNode, key=lambda value: value[0],\n reverse=True)[:10]\n topNode.append(valueWithIndex)\n print(topNode)\n centralTab[centrality.__name__] = topNode\nprint(centralTab)\n\ncommunities = {node: cid+1 for cid, community in\n enumerate(community.k_clique_communities(G, 3))\n for node in community}\nsortedCommunities = sorted(communities.values())\nnbPeopleInCommunity = []\ncounter = 0\nfor k in range(len(sortedCommunities)):\n value = sortedCommunities[k]\n counter += 1\n if(value != sortedCommunities[k+1]):\n nbPeopleInCommunity.append([value, counter])\n counter = 0\n if(value == sortedCommunities[-1]):\n for j in range(k, len(sortedCommunities)):\n counter += 1\n nbPeopleInCommunity.append([value, counter])\n break\ntopNb = sorted(nbPeopleInCommunity, key=lambda value: value[1],\n reverse=True)[:10]\nprint(topNb)\n\n\n# Kevin Bacon himself has a Bacon number of 0.\n# Those actors who have worked directly with Kevin Bacon\n# have a Bacon number of 1.\n# If the lowest Bacon number of any actor with whom X\n# has appeared in any movie is N, X's Bacon number is N+1.\n\n\ndef findActorsFromMovie(movie, tab, kevinBaconTab, iterator):\n actors = []\n for i in range(len(tab)):\n if(movie in tab[i][1] and tab[i][0] in kevinBaconTab):\n if(kevinBaconTab[tab[i][0]] != iterator):\n actors.append(tab[i][0])\n return actors\n\n\nkevinBaconTab = {}\nallActors = {}\nfor i in range(len(tab)):\n allActors[tab[i][0]] = tab[i][1]\nkevinBaconMovie = allActors[\"Kevin Bacon\"]\nfor i in range(len(tab)):\n if(tab[i][0] == \"Kevin Bacon\"):\n kevinBaconTab[tab[i][0]] = 0\n allActors.pop('Kevin Bacon', None)\n else:\n for j in range(len(tab[i][1])):\n if(tab[i][1][j] in kevinBaconMovie):\n kevinBaconTab[tab[i][0]] = 1\n allActors.pop(tab[i][0], None)\niterator = 2\nwhile(len(allActors) != 0):\n print(len(allActors))\n actorToDelete = []\n for actor in allActors:\n if(actor not in kevinBaconTab):\n for j in range(len(allActors[actor])):\n actors = findActorsFromMovie(allActors[actor][j], tab,\n kevinBaconTab, iterator)\n if(len(actors) != 0):\n kevinBaconTab[actor] = iterator\n actorToDelete.append(actor)\n break\n for i in range(len(actorToDelete)):\n allActors.pop(actorToDelete[i], None)\n if(iterator == 6):\n break\n iterator += 1\n# print(kevinBaconTab)\navg = 0\nfor actor in kevinBaconTab:\n avg += kevinBaconTab[actor]\navg /= float(len(kevinBaconTab))\nprint(avg)\nhighestActors = sorted(kevinBaconTab.items(), key=lambda x: x[1],\n reverse=True)[:10]\nprint(highestActors)\nlowestActors = sorted(kevinBaconTab.items(), key=lambda x: x[1])[:10]\nprint(lowestActors)\n\n# Visualization\nconnected = sorted(nx.connected_components(G), key=len)\nprint(list(connected[len(connected)-2]))\nsubgraph = G.subgraph(list(connected[len(connected)-2]))\ncentralities = [nx.degree_centrality, nx.eigenvector_centrality]\nplt.figure(figsize=(15, 5))\nregion = 120\npos = nx.spring_layout(subgraph)\nfor centrality in centralities:\n region += 1\n plt.subplot(region)\n plt.title(centrality.__name__)\n nx.draw(subgraph, pos, labels={v: str(v) for v in subgraph},\n cmap=plt.get_cmap(\"bwr\"), node_color=[centrality(subgraph)[k]\n for k in\n centrality(subgraph)], node_size=20, font_size=8, linewidths=0.4,\n width=0.15)\nplt.savefig(\"centralities.png\")\n# nx.write_gexf(G, \"export.gexf\")\nsubgraphForGephi = nx.Graph()\nfor i in range(50):\n subgraphForGephi.add_node(tab[i][0], label=tab[i][0])\n for j in range(i+1, len(tab)):\n for movie in tab[j][1]:\n if(movie in tab[i][1]):\n subgraphForGephi.add_edge(tab[i][0], tab[j][0],\n label=movie, weight=1)\nnx.write_gexf(subgraphForGephi, \"export1.gexf\")\n","sub_path":"socialNetworkAnalysis.py","file_name":"socialNetworkAnalysis.py","file_ext":"py","file_size_in_byte":6672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"517112722","text":"\"\"\"Assignment 2: Files and Streaming Data\n\nWrite code to read and process a large data file. In this case you\nwill be generating complement of a DNA strand. The problem is that the\nDNA strand is very long (3 billion bases) so you cannot (or at least\nshould not) load it all into memory at once.\n\n\"\"\"\n\ndef load_dna(filename):\n \"\"\"Load a DNA strand from the given filename.\n\n The file is a sequence of letters (\"A\", \"T\", \"C\", \"G\") and white\n space. You should remove all white space leaving just the letters.\n\n For example, if the file contains:\n AG T\n CG\n The output of the returned generator should be \"A\", \"G\", \"T\", \"C\",\n \"G\".\n\n This function is a generator for the sequence. So instead of loading\n the whole sequence you should load one base at a time (or a few\n bases at a time) and yield the bases.\n\n \"\"\"\n with open(filename, \"r\", encoding=\"utf-8\") as file:\n while True:\n cur = file.read(1)\n if not cur:\n break\n if cur == \"A\" or cur == \"T\" or cur == \"G\" or cur == \"C\":\n yield cur\n\ndef complement_dna(strand):\n \"\"\"Given a single DNA strand build the complement strand.\n\n The single DNA strand is represented as an iterable of strings\n (\"A\", \"T\", \"C\", \"G\").\n\n The output should be the complement of the input strand using the\n DNA pairing rules: A pairs with T, C pairs with G. For example:\n\n list(complement_dna([\"A\", \"T\", \"G\", \"G\", \"C\"])) ==\n [\"T\", \"A\", \"C\", \"C\", \"G\"]\n\n The input iterable could be a generator or iterator. So it can\n only be iterated once. Also the output should be a generator. This\n is critical because the input and output strands may be larger\n than system memory and if you use generators properly the entire\n thing never needs to be stored at the same time.\n\n Grading: 80% for correct answer, 100% for nice clean *declarative*\n answer using a single generator expression.\n\n \"\"\"\n for cur in strand:\n if cur == \"A\":\n temp = \"T\"\n if cur == \"T\":\n temp = \"A\"\n if cur == \"C\":\n temp = \"G\"\n if cur == \"G\":\n temp = \"C\"\n yield temp\n\n\n\ndef save_dna(strand, filename):\n \"\"\"Save a DNA strand to the given filename.\n\n Simply write each base to the file as a single character. You do\n not need to add any white space, but if you want to add a new line\n every 80 characters go ahead.\n\n Remember the input may be extremely long and you should NOT store\n the whole strand in memory at any point.\n \"\"\"\n with open(filename, \"w\", encoding = \"utf-8\") as file:\n for cur in strand:\n file.write(cur)\n\n","sub_path":"A2/assignment2.py","file_name":"assignment2.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"466490329","text":"#! /usr/bin/python3\n# coding:utf-8\nimport argparse\nimport drink_detect\nimport time\n\n# ログのライブラリ\nimport logging\nfrom logging import getLogger, StreamHandler, Formatter\n\n# loggerの設定\n## loggerオブジェクトの宣言\nlogger = getLogger(\"DJGLASS\")\n## loggerのログレベル設定(ハンドラに渡すエラーメッセージのレベル)\nlogger.setLevel(logging.DEBUG)\n## handlerの生成\nstream_handler = StreamHandler()\n## ログ出力フォーマット設定\nhandler_format = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nstream_handler.setFormatter(handler_format)\n# loggerにhandlerをセット\nlogger.addHandler(stream_handler)\n# loggerの設定終わり\n\ndef main(dummy = False, debug = False):\n # setup camera\n CAPTURE_WIDTH = 32\n CAPTURE_HEIGHT = 32\n if dummy:\n import dummy_camera\n cam = dummy_camera.DummyCamera(CAPTURE_WIDTH,CAPTURE_HEIGHT, debug=debug)\n else:\n import camera\n cam = camera.Camera(CAPTURE_WIDTH,CAPTURE_HEIGHT, debug=debug)\n cam.setup()\n \n # setup drink detector\n dd = drink_detect.DrinkDetector(debug=debug)\n dd.setup()\n\n while True:\n img = cam.captureImg()\n #logger.debug(img)\n answer = dd.detect(img)\n logger.debug(answer)\n time.sleep(1)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--debug', action=\"store_true\", help='debug mode switch')\n parser.add_argument('--dummycamera', action=\"store_true\" ,help='dummy camera mode switch')\n args = parser.parse_args()\n # set logging handler level\n if args.debug:\n stream_handler.setLevel(logging.DEBUG)\n else:\n stream_handler.setLevel(logging.INFO)\n main(debug=args.debug, dummy=args.dummycamera)\n\n\n","sub_path":"dj_glass.py","file_name":"dj_glass.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"349532784","text":"__author__ = 'tingxxu'\n\nfrom DevIoTGateway.config import config\nfrom DevIoTGatewayPi.pigateway import PiGateway\n\nfrom logic.defaultsensorlogic import DefaultSensorLogic\n\nif __name__ == '__main__':\n\n devIot_address = config.get_string(\"address\", \"10.140.92.22:9000\")\n mqtt_address = config.get_string(\"mqtthost\", \"10.140.92.22:1883\")\n app_name = config.get_string(\"appname\", \"raspberry\")\n devIot_account = config.get_info(\"account\", \"\")\n\n app = PiGateway(app_name, devIot_address, mqtt_address, devIot_account)\n app.default_sensor_logic = DefaultSensorLogic\n app.run()\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"440888611","text":"import re\ndef search(addr, i, r, p):\n\tf = open(\"results.csv\", \"a\")\n\tstrtow = str(i) + \",\" + str(r) + \",\" + str(p) + \",\"\n\tsearchfile = open(addr, \"r\")\n\tfor line in searchfile:\n\t\tif \"sim_seconds\" in line:\n\t\t\tp = re.compile(r'\\d+\\.\\d+') # Compile a pattern to capture float values\n\t\t\tnum1 = [float(i) for i in p.findall(line)] # Convert strings to float\n\t\t\tstrtow = strtow + str(num1[0]) + \",\"\n\t\tif \"# Number of integer rename lookups\" in line:\n\t\t\tnum2 = int(re.search(r'\\d+', line).group()) # Convert strings to float\n\t\t\tstrtow = strtow + str(num2) + \",\"\n\t\tif \"# Inst issue rate\" in line:\n\t\t\tp = re.compile(r'\\d+\\.\\d+') # Compile a pattern to capture float values\n\t\t\tnum3 = [float(i) for i in p.findall(line)] # Convert strings to float\n\t\t\tstrtow = strtow + str(num3[0]) + \",\"\n\t\tif \"Number of cycles rename is idle\" in line:\n\t\t\tnum4 = int(re.search(r'\\d+', line).group()) # Convert strings to float\n\t\t\tstrtow = strtow + str(num4) + \",\"\n\t\tif \"# Number of times rename has blocked due to ROB full\" in line:\n\t\t\tnum5 = int(re.search(r'\\d+', line).group())\n\t\t\tstrtow = strtow + str(num5) + \",\"\n\t\tif \"system.cpu.dcache.overall_miss_rate::total\" in line:\n\t\t\tp = re.compile(r'\\d+\\.\\d+') # Compile a pattern to capture float values\n\t\t\tnum6 = [float(i) for i in p.findall(line)] # Convert strings to float\n\t\t\tstrtow = strtow + str(num6[0]) + \",\"\n\tsearchfile.close()\n\tf.write(strtow + \"\\n\")\n\tf.close()\n\ni = 4\nr = 4\np = 256\nil = []\nrl = []\npl = []\nwhile i < 257:\n\til.append(i)\n\ti = i * 2\nwhile r < 257:\n\trl.append(r)\n\tr = r * 2\nwhile p < 4097:\n\tpl.append(p)\n\tp = p * 2\nprint(il)\nprint(rl)\nprint(pl)\n\nfor i in il:\n\tfor r in rl:\n\t\tfor p in pl:\n\t\t\tstrbase = \"/home/warehouse/yuqiuz/cse560m/homework3/result/\"\n\t\t\tstradd = \"daxpy_arm_f\" + str(p) + \"_i\" + str(i) + \"_r\" + str(r) + \"/stats.txt\"\n\t\t\tadd = strbase + stradd\n\t\t\tsearch(add, i, r, p)\n\t\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"get_data2.py","file_name":"get_data2.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"316654756","text":"import scrapy\nfrom scrapy.linkextractors import LinkExtractor\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy_splash import SplashRequest\nimport re\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport requests\nimport json\nfrom ScrapySpider.ifvodItems import IfVodItem\nimport pymysql\nfrom pymysql.cursors import DictCursor\nfrom scrapy import signals\nimport time\n\nconfig = {\n 'user': 'root',\n 'password': '696d9c48b1875ffe',\n 'port': 3306,\n 'host': '47.74.90.95',\n 'db': 'beiwo2',\n 'charset': 'utf8'\n}\n\nclass IfqqSpider(scrapy.Spider):\n name = 'ifqq'\n # allowed_domains = ['www.jxsp.tv']\n base_jiexi_url = 'http://66.165.227.210:8899/?url='\n custom_settings = {\n 'ITEM_PIPELINES': {\n 'ScrapySpider.pipelines.ifIqiyiPipeline': 300,\n },\n }\n caiji_list_url = 'http://jhzy.jhdyw.vip:8091/api.php/provide/vod/from/qq/at/json/?ac=list&t=&pg=1&h=24&ids=&wd='\n base_caiji_url = 'http://jhzy.jhdyw.vip:8091/api.php/provide/vod/from/qq/at/json/?ac=videolist&t=&h=24&ids=&wd=&pg='\n drama_bind = ['连续剧', '国产', '港台', '日韩', '欧美']\n movie_bind = ['电影', '动作', '喜剧', '爱情', '科幻', '恐怖', '剧情', '战争', '惊悚', '犯罪', '冒险', '悬疑', '武侠', '奇幻']\n enter_bind = ['综艺']\n anni_bind = ['动画', '动漫']\n docu_bind = ['记录']\n\n start_urls = list()\n\n @classmethod\n def from_crawler(cls, crawler, *args, **kwargs):\n spider = super(IfqqSpider, cls).from_crawler(crawler, *args, **kwargs)\n spider.conn = pymysql.Connect(**config)\n crawler.signals.connect(spider.spider_closed, signal=signals.spider_closed)\n return spider\n\n def spider_closed(self, spider):\n spider.conn.close()\n print('爬虫结束了')\n\n def start_requests(self):\n list_res = requests.get(self.caiji_list_url, timeout=10)\n list_dict = json.loads(list_res.text)\n page_count = list_dict['pagecount']\n # for page in range(1, 2, 1):\n for page in range(1, page_count+1, 1):\n caiji_url = self.base_caiji_url + str(page)\n caiji_res = requests.get(caiji_url, timeout=10)\n caiji_str = caiji_res.text\n caiji_dict = json.loads(caiji_str)\n video_list = caiji_dict['list']\n # for i in range(0, 2, 1):\n for i in range(0, len(video_list), 1):\n video = video_list[i]\n item = IfVodItem()\n if video['type_name'] in self.drama_bind:\n item['type_name'] = '连续剧'\n elif video['type_name'] in self.movie_bind:\n item['type_name'] = '电影'\n elif video['type_name'] in self.enter_bind:\n item['type_name'] = '综艺'\n elif video['type_name'] in self.anni_bind:\n item['type_name'] = '动漫'\n elif video['type_name'] in self.docu_bind:\n item['type_name'] = '纪录片'\n\n item['vod_name'] = video['vod_name']\n item['vod_class'] = video['vod_class']\n item['vod_actor'] = video['vod_actor']\n item['vod_director'] = video['vod_director']\n item['vod_class'] = video['vod_class'] + ',' + video['type_name']\n item['vod_pic'] = video['vod_pic']\n item['vod_score'] = video['vod_score']\n item['vod_content'] = video['vod_content']\n item['vod_year'] = video['vod_year']\n if video['vod_area'] == '中国' or '内地' in video['vod_area'] or '大陆' in video['vod_area'] or '华语' in video['vod_area']:\n item['vod_area'] = '大陆'\n elif '港' in video['vod_area']:\n item['vod_area'] = '香港'\n elif '台' in video['vod_area']:\n item['vod_area'] = '台湾'\n elif '美' in video['vod_area'] or '欧' in video['vod_area'] or '法' in video['vod_area']:\n item['vod_area'] = '欧美'\n elif '韩国' in video['vod_area']:\n item['vod_area'] = '韩国'\n elif '日' in video['video_area']:\n item['vod_area'] = '韩国'\n elif '英' in video['video_area']:\n item['vod_area'] = '英国'\n elif '泰' in video['video_area']:\n item['vod_area'] = '泰国'\n else:\n item['vod_area'] = '其他'\n play_url_str = video['vod_play_url']\n play_url_arr = play_url_str.split('#')\n # for j in range(0, 1, 1):\n for j in range(0, len(play_url_arr), 1):\n ifitem = IfVodItem()\n ifitem = dict(item)\n chapter_str = play_url_arr[j]\n chapter_arr = chapter_str.split('$')\n chapter_name = chapter_arr[0]\n if item['type_name'] == '连续剧' or item['type_name'] == '动漫' or item['type_name'] == '纪录片':\n if '第' in chapter_name:\n chapter_name = chapter_name.replace('第', '')\n if '集' in chapter_name:\n chapter_name = chapter_name.replace('集', '')\n if len(chapter_name) == 1:\n chapter_name = '0' + chapter_name\n\n ifitem['chapter_name'] = chapter_name\n chapter_url = chapter_arr[1]\n chapter_url = self.base_jiexi_url + chapter_url\n # --------------判断是否存在--------------\n # conn = pymysql.Connect(**config)\n cusor = self.conn.cursor(cursor=DictCursor)\n query_table_sql = \"\"\"\n SELECT * FROM vod_Play_720 where vod_name = %(vod_name)s and chapter_name = %(chapter_name)s\n and type_name = %(type_name)s\n \"\"\"\n item_dict = dict(ifitem)\n # --------------查询数据--------------\n cusor.execute(query_table_sql, item_dict)\n results = cusor.fetchall()\n print('查询到1:' + '/' + ifitem['vod_name'] + '/' + ifitem['chapter_name'])\n if len(results) > 0:\n print('该视频已经入库:' + '/' + ifitem['vod_name'] + '/' + ifitem['chapter_name'])\n continue\n if chapter_url != '':\n yield scrapy.Request(chapter_url, callback=self.parseDetail\n , meta={'item': ifitem})\n time.sleep(2)\n\n def parseDetail(self, response):\n item = response.meta['item']\n j = json.loads(response.text)\n if not ('code' in j.keys()) or j['code'] != '200':\n print(\"解析失败\")\n return\n m3u8_url = j['url']\n item['vod_url'] = m3u8_url\n item['path'] = response.url\n\n yield item\n\n def start_requests2(self):\n with self.conn.cursor(cursor=DictCursor) as c:\n # 查询语句\n query_table_sql = \"\"\"\n SELECT a.video_id, b.title as vod_name, a.title, a.resource_url \n from sf_video_chapter AS a \n inner join sf_video as b on a.video_id = b.id\n WHERE a.resource_url like '%.iqiyi.%' limit 5\n \"\"\"\n c.execute(query_table_sql)\n results = c.fetchall()\n print('视频数量: ' + str(len(results)))\n # for i in range(0, 1, 1):\n for i in range(0, len(results), 1):\n chapter = results[i]\n resource_str = chapter['resource_url']\n resource_arr = json.loads(resource_str)\n source = \"\"\n response_url = ''\n for key in resource_arr:\n source = key\n value = resource_arr[key]\n if \".iqiyi.\" in value:\n response_url = self.base_jiexi_url + value\n\n print(response_url)\n video_id = chapter['video_id']\n title = chapter['title']\n vod_name = chapter['vod_name']\n if response_url != '':\n yield scrapy.Request(response_url, callback=self.parseDetail\n , meta={'source': source, 'title': title, 'vod_name': vod_name})\n\n def parseDetail2(self, response):\n source = response.meta['source']\n title = response.meta['title']\n vod_name = response.meta['vod_name']\n\n j = json.loads(response.text)\n if not ('code' in j.keys()) or j['code'] != '200':\n print(\"解析失败\")\n return\n\n m3u8_url = j['url']\n item = IfVodItem()\n item['vod_name'] = vod_name\n item['chapter_name'] = title\n item['vod_url'] = m3u8_url\n item['source'] = source\n item['type_name'] = 'iqiyi'\n\n yield item\n\n\n","sub_path":"ScrapySpider/ScrapySpider/spiders/ifqq.py","file_name":"ifqq.py","file_ext":"py","file_size_in_byte":9226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"148688004","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n[Python 2.7 (Mayavi is not yet compatible with Python 3+)]\r\nCreated on Tue Feb 10 18:27:17 2015\r\n@author: Ryan Stauffer\r\nhttps://github.com/ryanpstauffer/market-vis\r\n\r\nMarket Visualization Prototype \r\nVisualization and Interactive module\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom mayavi import mlab\r\nimport moviepy.editor as mpy\r\n\r\ndef visualizePrices(prices):\r\n '''Creates a mayavi visualization of a pd DataFrame containing stock prices\r\n Inputs:\r\n prices => a pd DataFrame, w/ index: dates; columns: company names\r\n '''\r\n #Because of mayavi requirements, replace dates and company names with integers\r\n #until workaround is figured out\r\n x_length, y_length = prices.shape\r\n xTime = np.array([list(xrange(x_length)),] * y_length).transpose()\r\n yCompanies = np.array([list(xrange(y_length)),] * x_length)\r\n \r\n #Sort indexed prices by total return on last date\r\n lastDatePrices = prices.iloc[-1]\r\n lastDatePrices.sort_values(inplace=True)\r\n sortOrder = lastDatePrices.index\r\n zPrices = prices[sortOrder]\r\n \r\n #Create mayavi2 object\r\n dims = xTime.shape\r\n fig = mlab.figure(bgcolor=(.4,.4,.4))\r\n vis = mlab.surf(xTime, yCompanies, zPrices)\r\n mlab.outline(vis)\r\n mlab.orientation_axes(vis)\r\n #mlab.title('S&P 500 Market Data Visualization', size = .25)\r\n mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price')\r\n \r\n #Functionality to be added:\r\n # cursor3d = mlab.points3d(0., 0., 0., mode='axes',\r\n # color=(0, 0, 0),\r\n # scale_factor=20)\r\n #picker = fig.on_mouse_pick(picker_callback)\r\n \r\n mlab.show()\r\n\r\ndef make_frame(t):\r\n mlab.view(elevation=70, azimuth=360*t/4.0, distance=1400) #Camera angle\r\n return mlab.screenshot(antialiased=True)\r\n\r\ndef animateGIF(filename, prices):\r\n '''Creates a mayavi visualization of a pd DataFrame containing stock prices\r\n Then uses MoviePy to animate and save as a gif\r\n Inputs:\r\n prices => a pd DataFrame, w/ index: dates; columns: company names\r\n '''\r\n #Because of mayavi requirements, replace dates and company names with integers\r\n #until workaround is figured out\r\n x_length, y_length = prices.shape\r\n xTime = np.array([list(xrange(x_length)),] * y_length).transpose()\r\n yCompanies = np.array([list(xrange(y_length)),] * x_length)\r\n \r\n #Sort indexed prices by total return on last date\r\n lastDatePrices = prices.iloc[-1]\r\n lastDatePrices.sort_values(inplace=True)\r\n sortOrder = lastDatePrices.index\r\n zPrices = prices[sortOrder]\r\n \r\n \r\n #Create mayavi2 object\r\n dims = xTime.shape\r\n fig = mlab.figure(bgcolor=(.4,.4,.4))\r\n vis = mlab.surf(xTime, yCompanies, zPrices)\r\n mlab.outline(vis)\r\n mlab.orientation_axes(vis)\r\n mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price')\r\n \r\n# duration = 2 #Duration of the animation in seconds (will loop)\r\n \r\n animation = mpy.VideoClip(make_frame, duration = 4).resize(1.0)\r\n# animation.write_videofile('prototype_animation.mp4', fps=20)\r\n animation.write_gif(filename, fps=20)\r\n \r\n\r\ndef pickerCallback(pickerObj):\r\n #Currently unused, functionality to be added\r\n picked = pickerObj.actors\r\n if vis.actor.actor._vtk_obj in [o._vtk_obj for o in picked]:\r\n # m.mlab_source.points is the points array underlying the vtk\r\n # dataset. GetPointId return the index in this array.\r\n x_, y_ = np.lib.index_tricks.unravel_index(pickerObj.point_id,dims)\r\n print('Data indices: %i, %i' % (x_, y_))\r\n print(x[x_, y_], y[x_, y_], z[x_, y_] )\r\n cursor3d.mlab_source.set(x=x[x_, y_],\r\n y=y[x_, y_],\r\n z=z[x_, y_])","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"449147179","text":"\"\"\"Class template and SkillTree\n\nRevision ID: 099456d603d1\nRevises: 7271ac6c9b67\nCreate Date: 2018-06-01 23:51:00.425104\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '099456d603d1'\ndown_revision = '7271ac6c9b67'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('class',\n sa.Column('hp', sa.Integer(), nullable=False),\n sa.Column('attack_p', sa.Integer(), nullable=True),\n sa.Column('attack_m', sa.Integer(), nullable=True),\n sa.Column('defense_p', sa.Integer(), nullable=True),\n sa.Column('defense_m', sa.Integer(), nullable=True),\n sa.Column('initiative', sa.Integer(), nullable=True),\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(), nullable=False),\n sa.Column('display_name', sa.String(), nullable=False),\n sa.PrimaryKeyConstraint('id', name=op.f('pk_class'))\n )\n op.create_table('skill_tree',\n sa.Column('id_skill', sa.Integer(), nullable=False),\n sa.Column('id_class', sa.Integer(), nullable=False),\n sa.Column('level', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['id_class'], ['class.id'], name=op.f('fk_skill_tree_id_class_class')),\n sa.ForeignKeyConstraint(['id_skill'], ['skill.id'], name=op.f('fk_skill_tree_id_skill_skill')),\n sa.PrimaryKeyConstraint('id_skill', 'id_class', name=op.f('pk_skill_tree'))\n )\n op.create_table('unit_skill',\n sa.Column('unit_id', sa.Integer(), nullable=False),\n sa.Column('skill_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['skill_id'], ['skill.id'], name=op.f('fk_unit_skill_skill_id_skill')),\n sa.ForeignKeyConstraint(['unit_id'], ['unit.id'], name=op.f('fk_unit_skill_unit_id_unit')),\n sa.PrimaryKeyConstraint('unit_id', 'skill_id', name=op.f('pk_unit_skill'))\n )\n with op.batch_alter_table('encounter', schema=None) as batch_op:\n batch_op.add_column(sa.Column('players', postgresql.ARRAY(sa.Integer()), nullable=True))\n batch_op.drop_column('blue')\n batch_op.drop_column('red')\n\n with op.batch_alter_table('unit', schema=None) as batch_op:\n batch_op.add_column(sa.Column('class_id', sa.Integer(), nullable=False))\n batch_op.alter_column('attack_m',\n existing_type=sa.INTEGER(),\n nullable=True)\n batch_op.alter_column('attack_p',\n existing_type=sa.INTEGER(),\n nullable=True)\n batch_op.alter_column('defense_m',\n existing_type=sa.INTEGER(),\n nullable=True)\n batch_op.alter_column('defense_p',\n existing_type=sa.INTEGER(),\n nullable=True)\n batch_op.alter_column('initiative',\n existing_type=sa.INTEGER(),\n nullable=True)\n batch_op.create_foreign_key(batch_op.f('fk_unit_class_id_class'), 'class', ['class_id'], ['id'])\n batch_op.drop_column('class_name')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('unit', schema=None) as batch_op:\n batch_op.add_column(sa.Column('class_name', sa.VARCHAR(), autoincrement=False, nullable=False))\n batch_op.drop_constraint(batch_op.f('fk_unit_class_id_class'), type_='foreignkey')\n batch_op.alter_column('initiative',\n existing_type=sa.INTEGER(),\n nullable=False)\n batch_op.alter_column('defense_p',\n existing_type=sa.INTEGER(),\n nullable=False)\n batch_op.alter_column('defense_m',\n existing_type=sa.INTEGER(),\n nullable=False)\n batch_op.alter_column('attack_p',\n existing_type=sa.INTEGER(),\n nullable=False)\n batch_op.alter_column('attack_m',\n existing_type=sa.INTEGER(),\n nullable=False)\n batch_op.drop_column('class_id')\n\n with op.batch_alter_table('encounter', schema=None) as batch_op:\n batch_op.add_column(sa.Column('red', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))\n batch_op.add_column(sa.Column('blue', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))\n batch_op.drop_column('players')\n\n op.drop_table('unit_skill')\n op.drop_table('skill_tree')\n op.drop_table('class')\n # ### end Alembic commands ###\n","sub_path":"server/migrations/versions/099456d603d1_class_template_and_skilltree.py","file_name":"099456d603d1_class_template_and_skilltree.py","file_ext":"py","file_size_in_byte":4542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"431329890","text":"#!/usr/bin/env python3\n\n# import modules\nimport sys\nimport os\nimport inspect\nimport glob\nimport argparse\nimport skimage\nfrom skimage import measure, io\nfrom pprint import pprint # for human readable file output\ntry:\n import cPickle as pickle\nexcept:\n import pickle\n\n# user modules\n# realpath() will make your script run, even if you symlink it\ncmd_folder = os.path.realpath(os.path.abspath(\n os.path.split(inspect.getfile(inspect.currentframe()))[0]))\nif cmd_folder not in sys.path:\n sys.path.insert(0, cmd_folder)\n\n# This makes python look for modules in ./external_lib\ncmd_subfolder = os.path.realpath(os.path.abspath(\n os.path.join(os.path.split(inspect.getfile(\n inspect.currentframe()))[0], \"external_lib\")))\nif cmd_subfolder not in sys.path:\n sys.path.insert(0, cmd_subfolder)\n\nimport mm3_helpers as mm3\n\n#%%\n# when using this script as a function and not as a library the following will execute\nif __name__ == \"__main__\":\n\n # set switches and parameters\n parser = argparse.ArgumentParser(\n prog='python combine_tracks_from_chtc.py',\n description='CHTC saves a separate track file for each fov/peak. Here we combine them.'\n )\n parser.add_argument(\n '-f',\n '--paramfile',\n type=str,\n required=True,\n help='Yaml file containing parameters.'\n )\n\n namespace = parser.parse_args()\n\n # Load the project parameters file\n mm3.information('Loading experiment parameters.')\n if namespace.paramfile:\n param_file_path = namespace.paramfile\n else:\n mm3.warning('No param file specified. Using 100X template.')\n param_file_path = 'yaml_templates/params_SJ110_100X.yaml'\n p = mm3.init_mm3_helpers(param_file_path) # initialized the helper library\n\n # Get file names\n fnames = glob.glob(os.path.join(p['cell_dir'], \"{}*_tracks.pkl\".format(p['experiment_name'])))\n\n ### Now prune and save the data.\n mm3.information(\"Reading cell data from each file and combining into one.\")\n\n tracks = {}\n\n for fname in fnames:\n with open(fname, 'rb') as cell_file:\n cell_data = pickle.load(cell_file)\n os.remove(fname)\n tracks.update(cell_data)\n\n with open(p['cell_dir'] + '/all_cells.pkl', 'wb') as cell_file:\n pickle.dump(tracks, cell_file, protocol=pickle.HIGHEST_PROTOCOL)\n\n if os.path.isfile(os.path.join(p['cell_dir'], 'complete_cells.pkl')):\n os.remove(os.path.join(p['cell_dir'], 'complete_cells.pkl'))\n\n os.symlink(\n os.path.join(p['cell_dir'], 'all_cells.pkl'),\n os.path.join(p['cell_dir'], 'complete_cells.pkl')\n )\n\n mm3.information(\"Finished curating and saving cell data.\")\n","sub_path":"combine_tracks_from_chtc.py","file_name":"combine_tracks_from_chtc.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"541227254","text":"import neurokit2 as nk\nimport numpy as np\n\ndef test_bio_process():\n\n sampling_rate = 1000\n\n # Create data\n ecg = nk.ecg_simulate(duration=30, sampling_rate=sampling_rate)\n rsp = nk.rsp_simulate(duration=30, sampling_rate=sampling_rate)\n eda = nk.eda_simulate(duration=30, sampling_rate=sampling_rate, scr_number=3)\n emg = nk.emg_simulate(duration=30, sampling_rate=sampling_rate, burst_number=3)\n\n bio_df, bio_info = nk.bio_process(ecg=ecg,\n rsp=rsp,\n eda=eda,\n emg=emg,\n sampling_rate=sampling_rate)\n\n # SCR components\n scr = [val for key, val in bio_info.items() if \"SCR\" in key]\n assert all(len(elem) == len(scr[0]) for elem in scr)\n assert all(bio_info[\"SCR_Onsets\"] < bio_info[\"SCR_Peaks\"])\n assert all(bio_info[\"SCR_Peaks\"] < bio_info[\"SCR_Recovery\"])\n\n # RSP\n assert all(bio_info[\"RSP_Peaks\"] > bio_info[\"RSP_Troughs\"])\n assert len(bio_info[\"RSP_Peaks\"]) == len(bio_info[\"RSP_Troughs\"])\n\n # EMG\n assert all(bio_info[\"EMG_Offsets\"] > bio_info[\"EMG_Onsets\"])\n assert len(bio_info[\"EMG_Offsets\"] == len(bio_info[\"EMG_Onsets\"]))\n\n assert all(elem in ['ECG_Raw', 'ECG_Clean', 'ECG_Rate', 'ECG_R_Peaks',\n \"ECG_P_Peaks\", \"ECG_Q_Peaks\", \"ECG_S_Peaks\",\n \"ECG_T_Peaks\", \"ECG_P_Onsets\", \"ECG_T_Offsets\",\n \"ECG_Atrial_Phase\", \"ECG_Ventricular_Phase\",\n \"ECG_Atrial_PhaseCompletion\",\n \"ECG_Ventricular_PhaseCompletion\",\n 'RSP_Raw', 'RSP_Clean', 'RSP_Amplitude', 'RSP_Rate',\n 'RSP_Phase', 'RSP_PhaseCompletion',\n 'RSP_Peaks', 'RSP_Troughs',\n 'EDA_Raw', 'EDA_Clean', 'EDA_Tonic', 'EDA_Phasic',\n 'SCR_Onsets', 'SCR_Peaks', 'SCR_Height', 'SCR_Amplitude',\n 'SCR_RiseTime', 'SCR_Recovery', 'SCR_RecoveryTime',\n 'EMG_Raw', 'EMG_Clean', 'EMG_Amplitude', 'EMG_Activity',\n 'EMG_Onsets', 'EMG_Offsets']\n for elem in np.array(bio_df.columns.values, dtype=str))\n","sub_path":"tests/tests_bio.py","file_name":"tests_bio.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"510527032","text":"# -*- coding: utf-8 -*-\nimport json\nimport time\nfrom odoo import http\n\nfrom odoo.tools.safe_eval import safe_eval\nfrom werkzeug.urls import url_decode\nfrom odoo.http import content_disposition, request, \\\n serialize_exception as _serialize_exception\n\nfrom odoo.tools import html_escape\n\nfrom odoo.addons.web.controllers.main import ReportController\n\nclass ReportControllerInherit(ReportController):\n\n @http.route([\n '/report//',\n '/report///',\n ], type='http', auth='user', website=True)\n def report_routes(self, reportname, docids=None, converter=None, **data):\n report = request.env['ir.actions.report']._get_report_from_name(reportname)\n context = dict(request.env.context)\n\n if converter == 'pdf' and report.populating_ms_word_template:\n if docids:\n docids = [int(i) for i in docids.split(',')]\n if data.get('options'):\n data.update(json.loads(data.pop('options')))\n if data.get('context'):\n # Ignore 'lang' here, because the context in data is the one from the webclient *but* if\n # the user explicitely wants to change the lang, this mechanism overwrites it.\n data['context'] = json.loads(data['context'])\n if data['context'].get('lang'):\n del data['context']['lang']\n context.update(data['context'])\n datas = request.env[report.model].search([('id', '=', docids[0])])\n\n docx = report.with_context(context).render_doc_doc(datas, data=data)[0]\n docxhttpheaders = [('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')]\n return request.make_response(docx, headers=docxhttpheaders)\n else:\n return super(ReportControllerInherit, self).report_routes(reportname,docids,converter,**data)\n\n @http.route(['/report/download'], type='http', auth=\"user\")\n def report_download(self, data, token):\n requestcontent = json.loads(data)\n url, type = requestcontent[0], requestcontent[1]\n try:\n if type in ['qweb-pdf', 'qweb-text']:\n converter = 'pdf' if type == 'qweb-pdf' else 'text'\n extension = 'pdf' if type == 'qweb-pdf' else 'txt'\n\n pattern = '/report/pdf/' if type == 'qweb-pdf' else '/report/text/'\n reportname = url.split(pattern)[1].split('?')[0]\n\n docids = None\n if '/' in reportname:\n reportname, docids = reportname.split('/')\n\n if docids:\n # Generic report:\n response = self.report_routes(reportname, docids=docids, converter=converter)\n else:\n # Particular report:\n data = url_decode(url.split('?')[1]).items() # decoding the args represented in JSON\n response = self.report_routes(reportname, converter=converter, **dict(data))\n\n report = request.env['ir.actions.report']._get_report_from_name(reportname)\n\n if not report.populating_ms_word_template:\n return super(ReportControllerInherit, self).report_download(data, token)\n extension = 'docx'\n\n filename = \"%s.%s\" % (report.name, extension)\n if docids:\n ids = [int(x) for x in docids.split(\",\")]\n obj = request.env[report.model].browse(ids)\n if report.print_report_name and not len(obj) > 1:\n report_name = safe_eval(report.print_report_name, {'object': obj, 'time': time})\n filename = \"%s.%s\" % (report_name, extension)\n response.headers.add('Content-Disposition', content_disposition(filename))\n response.set_cookie('fileToken', token)\n return response\n else:\n return\n except Exception as e:\n se = _serialize_exception(e)\n error = {\n 'code': 200,\n 'message': \"Odoo Server Error\",\n 'data': se\n }\n return request.make_response(html_escape(json.dumps(error)))\n","sub_path":"populating_ms_word_template/controllers/report_controller.py","file_name":"report_controller.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"250101159","text":"def qs(arr, low, high):\n '''Sort arr from low to high (inclussive).'''\n\n if low >= high:\n return\n\n pivot = (low + high) // 2\n i = low\n j = high\n\n while True:\n while arr[i] < arr[pivot]:\n i += 1\n while arr[pivot] < arr[j]:\n j -= 1\n\n if i > j:\n break\n\n arr[i], arr[j] = arr[j], arr[i]\n i += 1\n j -= 1\n qs(arr, low, j)\n qs(arr, i, high)\n\n\ndef quick_sort(arr):\n '''Sort arr.'''\n\n qs(arr, 0, len(arr) - 1)\n\n\nif __name__ == '__main__':\n arr = [1, 7, 0, 2, 4, 1, 9]\n print(arr)\n quick_sort(arr)\n print('Sorted arr:', arr)\n","sub_path":"quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"470334029","text":"\"\"\"\n3PO: Tutorial 1, Question 1\nGenevieve Clifford (1779290), University of Birmingham\nsxc1065@student.bham.ac.uk / genevieve@becquerel.me\n\"\"\"\n\nimport numpy as np\nfrom scipy.optimize import linprog\n\nA_ub=np.array([\n [1,0],\n [0,1],\n [1,2],\n [1,1]\n])\n\nb_ub=np.array([70,50,120,90])\n\nc=np.array([-20,-30])\n\nres=linprog(c,A_ub=A_ub,b_ub=b_ub,bounds=(0,None))\n\nprint('A profit of £',-round(res.fun,0),' is to be made by producing ',round(res.x[0],0),\n' low-cost and ',round(res.x[1],0),' high-cost units respectively')","sub_path":"week_1/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"54759015","text":"from __future__ import (absolute_import, division, print_function)\nfrom mantid.api import AnalysisDataService\nimport mantid.simpleapi as simpleapi\nimport os\nimport math\n\n\nclass AddieDriver(object):\n \"\"\"\n Driver for addie application\n \"\"\"\n\n def __init__(self):\n \"\"\" Initialization\n Returns\n -------\n\n \"\"\"\n # name of the MatrixWorkspace for S(Q)\n self._currSqWsName = ''\n # dictionary to record workspace index of a certain S(Q)\n self._sqIndexDict = dict()\n\n # dictionary of the workspace with rmin, rmax and delta r setup\n self._grWsIndex = 0\n self._grWsNameDict = dict()\n\n # dictionary to manage the GSAS data\n # key: ws_group_name, value: (gss_ws_name, ws_list). it is in similar architecture with tree\n self._braggDataDict = dict()\n\n def calculate_gr(self, sq_ws_name, pdf_type, min_r, delta_r, max_r, min_q, max_q, pdf_filter, rho0):\n \"\"\" Calculate G(R)\n :param sq_ws_name: workspace name of S(q)\n :param pdf_type: type of PDF as G(r), g(r) and RDF(r)\n :param min_r: R_min\n :param delta_r: delta R\n :param max_r:\n :param min_q:\n :param max_q:\n :param pdf_filter: type of PDF filter\n :param rho0: average number density used for g(r) and RDF(r) conversions\n :return: string as G(r) workspace's name\n \"\"\"\n # check\n assert isinstance(sq_ws_name, str) and AnalysisDataService.doesExist(sq_ws_name)\n assert isinstance(pdf_type, str) and len(pdf_type) > 0, \\\n 'PDF type is %s is not supported.' % str(pdf_type)\n assert min_r < max_r, 'Rmin must be less than Rmax (%f >= %f)' % (min_r, max_r)\n assert delta_r < (max_r - min_r), 'Must have more than one bin in G(r) (%f >= %f)' \\\n '' % (delta_r, (max_r - min_r))\n\n assert min_q < max_q, 'Qmin must be less than Qmax (%f >= %f)' % (min_q, max_q)\n assert isinstance(pdf_filter, str) or pdf_filter is None, 'PDF filter must be a string or None.'\n assert isinstance(rho0, float) or rho0 is None, 'rho0 must be either None or a float but not a %s.' \\\n '' % str(type(rho0))\n\n # set to the current S(q) workspace name\n self._currSqWsName = sq_ws_name\n\n # set up the parameters for FourierTransform\n # output workspace\n prefix = 'G'\n if pdf_type.startswith('g'):\n prefix = 'g'\n elif pdf_type.startswith('R'):\n prefix = 'RDF'\n\n if self._currSqWsName in self._sqIndexDict:\n # for S(q) loaded from file\n ws_seq_index = self._sqIndexDict[self._currSqWsName]\n update_index = True\n else:\n # for S(q) calculated from IPython console\n ws_seq_index = 0\n update_index = False\n\n if pdf_filter is None:\n pdf_filter = False\n else:\n pdf_filter = True\n if pdf_filter != 'lorch':\n print('[WARNING] PDF filter {0} is not supported.'.format(pdf_filter))\n\n gr_ws_name = '%s(R)_%s_%d' % (prefix, self._currSqWsName, ws_seq_index)\n kwargs = {'OutputWorkspace': gr_ws_name,\n 'Qmin': min_q,\n 'Qmax': max_q,\n 'PDFType': pdf_type,\n 'DeltaR': delta_r,\n 'Rmax': max_r,\n 'Filter': pdf_filter}\n if rho0 is not None:\n kwargs['rho0'] = rho0\n\n # get the input unit\n sofq_type = 'S(Q)'\n\n # do the FFT\n simpleapi.PDFFourierTransform(InputWorkspace=self._currSqWsName,\n InputSofQType=sofq_type,\n **kwargs)\n\n # check\n assert AnalysisDataService.doesExist(gr_ws_name), 'Failed to do Fourier Transform.'\n self._grWsNameDict[(min_q, max_q)] = gr_ws_name\n\n # update state variable\n if update_index:\n self._sqIndexDict[self._currSqWsName] += 1\n\n return gr_ws_name\n\n @staticmethod\n def clone_workspace(src_name, target_name):\n \"\"\"clone workspace\n :param src_name:\n :param target_name:\n :return:\n \"\"\"\n # check\n assert isinstance(src_name, str), 'blabla'\n assert isinstance(target_name, str), 'blabla'\n\n # check existence\n if AnalysisDataService.doesExist(src_name):\n simpleapi.CloneWorkspace(InputWorkspace=src_name, OutputWorkspace=target_name)\n else:\n raise RuntimeError('Workspace with name {0} does not exist in ADS. CloneWorkspace fails!'.format(src_name))\n\n @staticmethod\n def delete_workspace(workspace_name, no_throw=False):\n \"\"\"\n Delete a workspace from Mantid's AnalysisDataService\n Args:\n workspace_name: name of a workspace as a string instance\n no_throw: if True, then it won't throw any exception if the workspace does not exist in AnalysisDataService\n\n Returns: None\n\n \"\"\"\n # check\n assert isinstance(workspace_name, str), \\\n 'Input workspace name must be a string, but not %s.' % str(type(workspace_name))\n\n # check whether the workspace exists\n does_exit = AnalysisDataService.doesExist(workspace_name)\n if does_exit:\n # delete\n simpleapi.DeleteWorkspace(Workspace=workspace_name)\n elif not no_throw:\n raise RuntimeError('Workspace %s does not exist.' % workspace_name)\n\n return\n\n @staticmethod\n def edit_matrix_workspace(sq_name, scale_factor, shift, edited_sq_name=None):\n \"\"\"\n Edit the matrix workspace of S(Q) by scaling and shift\n :param sq_name: name of the SofQ workspace\n :param scale_factor:\n :param shift:\n :param edited_sq_name: workspace for the edited S(Q)\n :return:\n \"\"\"\n # get the workspace\n if AnalysisDataService.doesExist(sq_name) is False:\n raise RuntimeError('S(Q) workspace {0} cannot be found in ADS.'.format(sq_name))\n\n if edited_sq_name is not None:\n simpleapi.CloneWorkspace(InputWorkspace=sq_name, OutputWorkspace=edited_sq_name)\n sq_ws = AnalysisDataService.retrieve(edited_sq_name)\n else:\n sq_ws = AnalysisDataService.retrieve(sq_name)\n\n # get the vector of Y\n sq_ws = sq_ws * scale_factor\n sq_ws = sq_ws + shift\n if sq_ws.name() != edited_sq_name:\n simpleapi.DeleteWorkspace(Workspace=edited_sq_name)\n simpleapi.RenameWorkspace(InputWorkspace=sq_ws, OutputWorkspace=edited_sq_name)\n\n assert sq_ws is not None, 'S(Q) workspace cannot be None.'\n print('[DB...BAT] S(Q) workspace that is edit is {0}'.format(sq_ws))\n\n # RMCProfile format. The 1st column tells how many X,Y pairs,\n # the second is a comment line with information regarding the data\n # (title, multiplier for data, etc.), and then the X,Y pairs for G(r) or S(Q) data.\n\n @staticmethod\n def export_to_rmcprofile(ws_name, output_file_name, comment='', ws_index=0):\n \"\"\" Export a workspace 2D to a 2 column data for RMCProfile\n \"\"\"\n # check inputs\n assert isinstance(ws_name, str), \\\n 'Workspace name {0} must be a string but not a {1}.'.format(ws_name, str(ws_name))\n assert isinstance(output_file_name, str), \\\n 'Output file name {0} must be a string but not a {1}.'.format(output_file_name,\n type(output_file_name))\n assert isinstance(comment, str), \\\n 'Comment {0} must be a string but not a {1}.'.format(comment, type(comment))\n assert isinstance(ws_index, int), \\\n 'Workspace index must be an integer but not a {1}.'.format(ws_index, type(ws_index))\n\n # convert to point data from histogram\n simpleapi.ConvertToPointData(InputWorkspace=ws_name, OutputWorkspace=ws_name)\n\n # get workspace for vecX and vecY\n if AnalysisDataService.doesExist(ws_name):\n workspace = AnalysisDataService.retrieve(ws_name)\n else:\n raise RuntimeError('Workspace {0} does not exist in ADS.'.format(ws_name))\n if not 0 <= ws_index < workspace.getNumberHistograms():\n raise RuntimeError('Workspace index {0} is out of range.'.format(ws_index))\n\n vec_x = workspace.readX(ws_index)\n vec_y = workspace.readY(ws_index)\n\n # write to buffer\n wbuf = ''\n wbuf += '{0}\\n'.format(len(vec_x))\n wbuf += '{0}\\n'.format(comment)\n for index in range(len(vec_x)):\n wbuf += ' {0} {1}\\n'.format(vec_x[index], vec_y[index])\n\n # write to file\n try:\n ofile = open(output_file_name, 'w')\n ofile.write(wbuf)\n ofile.close()\n except IOError as io_err:\n raise RuntimeError(\n 'Unable to export data to file {0} in RMCProfile format due to {1}.'.format(output_file_name, io_err))\n\n def get_bragg_data(self, ws_group_name, bank_id, x_unit):\n \"\"\" Get Bragg diffraction data of 1 bank\n Args:\n ws_group_name\n bank_id:\n x_unit:\n Returns:\n 3-tuple of numpy 1D array for X, Y and E\n \"\"\"\n # check\n assert isinstance(bank_id, int) and bank_id > 0\n msg = 'Workspace groups {} does not exist in controller.'.format(ws_group_name)\n msg += 'Current existing are {}.'.format(self._braggDataDict.keys())\n assert ws_group_name in self._braggDataDict, msg\n\n ws_name = '%s_bank%d' % (ws_group_name.split('_group')[0], bank_id)\n error_message = 'Bank %d is not found in group %s. Available bank IDs are %s.' % (\n bank_id, ws_group_name, str(self._braggDataDict[ws_group_name][1]))\n assert ws_name in self._braggDataDict[ws_group_name][1], error_message\n\n # FIXME - It is quite messy here! Using dictionary or forming workspace name?\n # construct bank workspace name\n # ws_name = self._braggDataDict[ws_group_name][1][bank_id]\n assert AnalysisDataService.doesExist(ws_name), 'Workspace %s does not exist.' % ws_name\n\n # convert units if necessary\n bank_ws = AnalysisDataService.retrieve(ws_name)\n curr_unit = bank_ws.getAxis(0).getUnit().unitID()\n if curr_unit != x_unit:\n simpleapi.ConvertToHistogram(InputWorkspace=ws_name, OutputWorkspace=ws_name)\n simpleapi.ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name,\n Target=x_unit, EMode='Elastic')\n\n # convert to point data for plotting\n simpleapi.ConvertToPointData(InputWorkspace=ws_name, OutputWorkspace=ws_name)\n\n # get workspace\n bank_ws = AnalysisDataService.retrieve(ws_name)\n\n return bank_ws.readX(0), bank_ws.readY(0), bank_ws.readE(0)\n\n def get_current_sq_name(self):\n \"\"\"\n Get the (workspace) name of current S(Q)\n Returns:\n\n \"\"\"\n return self._currSqWsName\n\n def get_current_workspaces(self):\n \"\"\"\n Get current workspaces' names\n Returns\n -------\n a list of strings\n \"\"\"\n return AnalysisDataService.getObjectNames()\n\n def get_gr(self, min_q, max_q):\n \"\"\"Get G(r)\n\n :param min_q:\n :param max_q:\n :return: 3-tuple for numpy.array\n \"\"\"\n # check... find key in dictionary\n error_msg = 'R-range and delta R are not support. Current stored G(R) parameters' \\\n ' are {}.'.format(list(self._grWsNameDict.keys()))\n assert (min_q, max_q) in self._grWsNameDict, error_msg\n\n # get the workspace\n gr_ws_name = self._grWsNameDict[(min_q, max_q)]\n gr_ws = AnalysisDataService.retrieve(gr_ws_name)\n\n return gr_ws.readX(0), gr_ws.readY(0), gr_ws.readE(0)\n\n def get_sq(self, sq_name=None):\n \"\"\"Get S(Q)\n :param sq_name:\n :return: 3-tuple of numpy array as Q, S(Q) and Sigma(Q)\n \"\"\"\n # check\n assert isinstance(sq_name, str) or sq_name is None, 'Input S(Q) must either a string or None but not {0}.' \\\n ''.format(type(sq_name))\n\n # set up default\n if sq_name is None:\n sq_name = self._currSqWsName\n\n if not AnalysisDataService.doesExist(sq_name):\n raise RuntimeError('S(Q) matrix workspace {0} does not exist.'.format(sq_name))\n\n # access output workspace and return vector X, Y, E\n out_ws = AnalysisDataService.retrieve(sq_name)\n\n return out_ws.readX(0), out_ws.readY(0), out_ws.readE(0)\n\n @staticmethod\n def get_ws_data(ws_name):\n \"\"\"\n\n Parameters\n ----------\n ws_name\n\n Returns\n -------\n\n \"\"\"\n # convert to point data for plotting\n simpleapi.ConvertToPointData(InputWorkspace=ws_name, OutputWorkspace=ws_name)\n\n out_ws = AnalysisDataService.retrieve(ws_name)\n\n return out_ws.readX(0), out_ws.readY(0), out_ws.readE(0)\n\n @staticmethod\n def get_ws_unit(ws_name):\n \"\"\"\n Find out the unit of the workspace\n Parameters\n ----------\n ws_name\n\n Returns\n -------\n\n \"\"\"\n # check\n assert isinstance(ws_name, str), 'Workspace name must be a string but not a %s.' % ws_name.__class__.__name__\n assert AnalysisDataService.doesExist(ws_name), 'Workspace %s does not exist.' % ws_name\n\n ws = AnalysisDataService.retrieve(ws_name)\n\n unit = ws.getAxis(0).getUnit().unitID()\n\n return unit\n\n @staticmethod\n def load_bragg_file(file_name):\n \"\"\"\n Load Bragg diffraction file (including 3-column data file, GSAS file) for Rietveld\n Parameters\n ----------\n file_name\n\n Returns\n -------\n\n \"\"\"\n # load with different file type\n base_file_name = os.path.basename(file_name).lower()\n gss_ws_name = os.path.basename(file_name).split('.')[0]\n if base_file_name.endswith('.gss') or base_file_name.endswith('.gsa') or base_file_name.endswith('.gda'):\n simpleapi.LoadGSS(Filename=file_name,\n OutputWorkspace=gss_ws_name)\n elif base_file_name.endswith('.nxs'):\n simpleapi.LoadNexusProcessed(Filename=file_name, OutputWorkspace=gss_ws_name)\n simpleapi.ConvertUnits(InputWorkspace=gss_ws_name, OutputWorkspace=gss_ws_name, EMode='Elastic', Target='TOF')\n elif base_file_name.endswith('.dat'):\n simpleapi.LoadAscii(Filename=file_name,\n OutputWorkspace=gss_ws_name,\n Unit='TOF')\n else:\n raise RuntimeError('File %s is not of a supported type.' % file_name)\n\n # check\n assert AnalysisDataService.doesExist(gss_ws_name)\n\n return gss_ws_name\n\n def load_gr(self, gr_file_name):\n \"\"\"\n Load an ASCII file containing G(r)\n Args:\n gr_file_name:\n\n Returns:\n\n \"\"\"\n # check\n assert len(gr_file_name) > 0\n\n # load\n gr_ws_name = os.path.basename(gr_file_name).split('.')[0]\n simpleapi.LoadAscii(Filename=gr_file_name, OutputWorkspace=gr_ws_name, Unit='Empty')\n\n # check output\n if not AnalysisDataService.doesExist(gr_ws_name):\n return False, 'Unable to load file %s as target workspace %s cannot be found.' % (gr_ws_name,\n gr_ws_name)\n\n return True, gr_ws_name\n\n def load_sq(self, file_name):\n \"\"\"\n Load S(Q) to a numpy\n Guarantees: the file is loaded to self._currSQX, _currSQY and _currSQE\n Parameters\n ----------\n file_name :: name of the S(Q)\n\n Returns\n -------\n 2-tuple range of Q\n \"\"\"\n # generate S(Q) workspace name\n sq_ws_name = os.path.basename(file_name).split('.')[0]\n\n # call mantid LoadAscii\n ext = file_name.upper().split('.')[-1]\n if ext == 'NXS':\n simpleapi.LoadNexusProcessed(Filename=file_name, OutputWorkspace=sq_ws_name)\n simpleapi.ConvertUnits(InputWorkspace=sq_ws_name, OutputWorkspace=sq_ws_name,\n EMode='Elastic', Target='MomentumTransfer')\n simpleapi.ConvertToPointData(InputWorkspace=sq_ws_name, OutputWorkspace=sq_ws_name) # TODO REMOVE THIS LINE\n elif ext == 'DAT' or ext == 'txt':\n simpleapi.LoadAscii(Filename=file_name, OutputWorkspace=sq_ws_name, Unit='MomentumTransfer')\n\n assert AnalysisDataService.doesExist(sq_ws_name), 'Unable to load S(Q) file %s.' % file_name\n\n # The S(Q) file is in fact S(Q)-1 in sq file. So need to add 1 to the workspace\n out_ws = AnalysisDataService.retrieve(sq_ws_name)\n out_ws += 1\n\n # set to the current S(Q) workspace name\n self._currSqWsName = sq_ws_name\n self._sqIndexDict[self._currSqWsName] = 0\n\n # get range of Q from the loading\n sq_ws = AnalysisDataService.retrieve(sq_ws_name)\n q_min = sq_ws.readX(0)[0]\n q_max = sq_ws.readX(0)[-1]\n\n return sq_ws_name, q_min, q_max\n\n def split_to_single_bank(self, gss_ws_name):\n \"\"\"\n Split a multiple-bank GSAS workspace to a set of single-spectrum MatrixWorkspace\n Parameters\n ----------\n gss_ws_name\n\n Returns\n -------\n Name of grouped workspace and list\n \"\"\"\n # check\n assert isinstance(gss_ws_name, str)\n assert AnalysisDataService.doesExist(gss_ws_name)\n\n # get workspace\n gss_ws = AnalysisDataService.retrieve(gss_ws_name)\n\n ws_list = list()\n angle_list = list()\n\n if gss_ws.getNumberHistograms() == 1:\n # input is already a single-spectrum workspace\n ws_list.append(gss_ws_name)\n else:\n num_spec = gss_ws.getNumberHistograms()\n\n for i_ws in range(num_spec):\n # split this one to a single workspace\n out_ws_name = '%s_bank%d' % (gss_ws_name, i_ws+1)\n # also can use ExtractSpectra()\n simpleapi.CropWorkspace(InputWorkspace=gss_ws_name,\n OutputWorkspace=out_ws_name,\n StartWorkspaceIndex=i_ws, EndWorkspaceIndex=i_ws)\n assert AnalysisDataService.doesExist(out_ws_name)\n ws_list.append(out_ws_name)\n\n # calculate bank angles\n for ws_name in ws_list:\n bank_angle = calculate_bank_angle(ws_name)\n angle_list.append(bank_angle)\n\n # group all the workspace\n ws_group_name = gss_ws_name + '_group'\n simpleapi.GroupWorkspaces(InputWorkspaces=ws_list,\n OutputWorkspace=ws_group_name)\n\n self._braggDataDict[ws_group_name] = (gss_ws_name, ws_list)\n\n return ws_group_name, ws_list, angle_list\n\n def save_ascii(self, ws_name, file_name, gr_file_type, comment=''):\n \"\"\"\n save ascii for G(r) or S(Q)\n Args:\n ws_name:\n file_name:\n gr_file_type: xye, csv, rmcprofile, dat\n comment: user comment to the file\n\n Returns:\n\n \"\"\"\n assert isinstance(ws_name, str), 'blabla'\n assert isinstance(file_name, str), 'blabla'\n assert isinstance(gr_file_type, str), 'GofR file type {0} must be a supported string.'.format(gr_file_type)\n\n if gr_file_type == 'xye':\n simpleapi.SaveAscii(InputWorkspace=ws_name, Filename=file_name, Separator='Space')\n elif gr_file_type == 'csv':\n simpleapi.SaveAscii(InputWorkspace=ws_name, Filename=file_name, Separator='CSV')\n elif gr_file_type == 'rmcprofile' or gr_file_type == 'dat':\n self.export_to_rmcprofile(ws_name, file_name, comment=comment)\n elif gr_file_type == 'gr':\n simpleapi.SavePDFGui(InputWorkspace=ws_name, Filename=file_name)\n else:\n # non-supported type\n raise RuntimeError('G(r) or S(Q) file type {0} is not supported.'.format(gr_file_type))\n\n @staticmethod\n def write_gss_file(ws_name_list, gss_file_name):\n \"\"\"\n Write a MatrixWorkspace to a GSAS file\n Args:\n workspace:\n gss_file_name:\n\n Returns:\n\n \"\"\"\n # check\n assert isinstance(ws_name_list, list) and len(ws_name_list) > 1, \\\n 'There must be at least 2 workspaces for conjoining operation.'\n assert isinstance(gss_file_name, str)\n\n # write with appending\n append_mode = False\n for i_ws, ws_name in enumerate(ws_name_list):\n simpleapi.SaveGSS(InputWorkspace=ws_name, Filename=gss_file_name,\n Format='SLOG', Bank=1, Append=append_mode)\n append_mode = True\n\n\ndef calculate_bank_angle(ws_name):\n \"\"\" Calculate bank's angle (2theta) focused detector\n \"\"\"\n try:\n bank_ws = AnalysisDataService.retrieve(ws_name)\n instrument = bank_ws.getInstrument()\n det_pos = bank_ws.getDetector(0).getPos()\n sample_pos = instrument.getSample().getPos()\n source_pos = instrument.getSource().getPos()\n\n angle = (det_pos - sample_pos).angle(sample_pos - source_pos) * 180. / math.pi\n\n except KeyError:\n return None\n\n return angle\n","sub_path":"addie/addiedriver.py","file_name":"addiedriver.py","file_ext":"py","file_size_in_byte":21733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"3546878","text":"# !/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Time : 2020/10/28 15:35\n# Author : Amd794\n# Email : 2952277346@qq.com\n# Github : https://github.com/Amd794\n\nimport re\n\nimport execjs\n\nfrom threading_download_images import get_response\n\n\nclass CoCoManHua(object):\n @staticmethod\n def _cocomanhua(detail_url):\n response = get_response(detail_url)\n data = re.findall('var C_DATA.*?\\'(.*?)\\'', response.text)[0]\n ctx = execjs.get().compile(open('js/_cocomanhua.js', encoding='utf-8').read(), cwd='js/node_modules')\n images_url = ctx.eval(f'getArr(\"{data}\")')\n return images_url\n\n\nif __name__ == '__main__':\n import os\n os.chdir('../')\n print(CoCoManHua._cocomanhua('https://www.cocomanhua.com/11749/1/233.html'))\n","sub_path":"site/cocomanhua_com.py","file_name":"cocomanhua_com.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"230461977","text":"from Bio import SeqIO\nimport argparse\n\nprogram_description = \"Parse GBK and creates table\"\nparser = argparse.ArgumentParser(description=program_description)\nparser.add_argument(\"-g\", \"--gbk_file\", type=str, required=True, help=\"GBK file\")\nparser.add_argument(\"-o\", \"--output_prefix\", type=str, required=True, help=\"Output prefix for the files\")\n\nargs = parser.parse_args()\n\n# Types CDS, gene, misc_binding, ncRNA, rRNA, repeat_region, source, tRNA, tmRNA\n\noutput_table = open(args.output_prefix + \".txt\", 'w')\noutput_fasta = open(args.output_prefix + \".faa\", 'w')\n\ntable_line = []\n\nfor index, record in enumerate(SeqIO.parse(args.gbk_file, \"genbank\")):\n for feature in record.features:\n note = \"\"\n\n if feature.type == \"source\" or feature.type == \"misc_binding\" or feature.type== \"repeat_region\":\n continue\n\n if feature.type == \"CDS\":\n contig = record.id\n gene_id = feature.qualifiers[\"locus_tag\"][0]\n start = feature.location.start\n stop = feature.location.end\n strand = feature.location.strand\n\n try:\n product = feature.qualifiers[\"product\"][0]\n except KeyError:\n product = \"\"\n\n try:\n protein_seq = feature.qualifiers[\"translation\"][0]\n note = \"\"\n except KeyError:\n protein_seq = \"\"\n note = \"pseudogene\"\n\n table_line.append([contig, gene_id, feature.type, str(start), str(stop), str(strand),\n product, note])\n\n # Create fasta protein files\n if protein_seq == \"\":\n continue\n else:\n output_fasta.write(\">\" + gene_id + \"\\n\")\n output_fasta.write(protein_seq + \"\\n\")\n\n if feature.type == \"ncRNA\":\n\n contig = record.id\n gene_id = feature.qualifiers[\"locus_tag\"][0]\n start = feature.location.start\n stop = feature.location.end\n strand = feature.location.strand\n try:\n product = feature.qualifiers[\"product\"][0]\n except KeyError:\n product = \"\"\n\n table_line.append([contig, gene_id, feature.type, str(start), str(stop), str(strand),\n product, note])\n\n if feature.type == \"rRNA\":\n contig = record.id\n gene_id = feature.qualifiers[\"locus_tag\"][0]\n start = feature.location.start\n stop = feature.location.end\n strand = feature.location.strand\n try:\n product = feature.qualifiers[\"product\"][0]\n except KeyError:\n product = \"\"\n\n table_line.append([contig, gene_id, feature.type, str(start), str(stop), str(strand),\n product, note])\n\n if feature.type == \"tRNA\":\n contig = record.id\n gene_id = feature.qualifiers[\"locus_tag\"][0]\n start = feature.location.start\n stop = feature.location.end\n strand = feature.location.strand\n try:\n product = feature.qualifiers[\"product\"][0]\n except KeyError:\n product = \"\"\n\n table_line.append([contig, gene_id, feature.type, str(start), str(stop), str(strand),\n product, note])\n\n if feature.type == \"tmRNA\":\n contig = record.id\n gene_id = feature.qualifiers[\"locus_tag\"][0]\n start = feature.location.start\n stop = feature.location.end\n strand = feature.location.strand\n try:\n product = feature.qualifiers[\"product\"][0]\n except KeyError:\n product = \"\"\n\n table_line.append([contig, gene_id, feature.type, str(start), str(stop), str(strand),\n product, note])\n\n\nheader=[\"contig\",\"geneID\", \"feature Type\", \"start\", \"end\", \"strand\", \"product\", \"note\"]\noutput_table.write(\"\\t\".join(header) + \"\\n\")\nfor line in table_line:\n output_table.write(\"\\t\".join(line) + \"\\n\")\n\noutput_table.close()\noutput_fasta.close()","sub_path":"Annotation/gbk_2_table.py","file_name":"gbk_2_table.py","file_ext":"py","file_size_in_byte":4185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"202426828","text":"from functools import reduce\n\na = list(map(int, input().split()))\n\nanswer = 0\n\nfor i in range(a[0] + 1):\n b = int(reduce(lambda x, y: int(x) + int(y), str(i)))\n \n if a[1] <= b and b <= a[2]:\n answer += i\n\nprint(answer)\n","sub_path":"beginnersSelection/some_sums.py","file_name":"some_sums.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"229300900","text":"import os\nfrom flask import Flask, request, abort, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_cors import CORS\nimport random\n\nfrom models import setup_db, Question, Category\n\nQUESTIONS_PER_PAGE = 10\n\n\ndef paginate_questions(request, selection):\n page = request.args.get('page', 1, type=int)\n start = (page - 1) * QUESTIONS_PER_PAGE\n end = start + QUESTIONS_PER_PAGE\n questions = [question.format() for question in selection]\n current_questions = questions[start:end]\n return current_questions\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n setup_db(app)\n\n # Set up CORS\n\n CORS(app)\n\n @app.after_request\n def after_request(response):\n response.headers.add(\n 'Access-Control-Allow-Headers',\n 'Content-Type, Authorization, true')\n response.headers.add(\n 'Access-Control-Allow-Methods',\n 'GET, PUT, POST, DELETE, OPTIONS')\n return response\n\n # Create an categories requests\n\n @app.route('/categories')\n def return_categories():\n categories = {}\n for category in Category.query.order_by(Category.id).all():\n categories.update({category.id: category.type})\n return jsonify({\n 'success': True,\n 'categories': categories,\n 'total_categoreis': len(Category.query.all())\n })\n\n # GET requests for questions\n\n @app.route('/questions')\n def return_questions():\n selections = Question.query.order_by(Question.id).all()\n total_questions = len(Question.query.all())\n current_question = paginate_questions(request, selections)\n current_category = [\n current_question[x]['category'] for x in range(len(current_question))]\n if len(current_question) == 0:\n abort(404)\n categories = {}\n for category in Category.query.order_by(Category.id).all():\n categories.update({category.id: category.type})\n return jsonify({\n 'success': True,\n 'questions': current_question,\n 'total_questions': total_questions,\n 'current_category': current_category,\n 'categories': categories\n })\n\n # DELETE question\n\n @app.route('/questions/', methods=['DELETE'])\n def delete_questions(question_id):\n try:\n question = Question.query.filter(Question.id == question_id).one_or_none()\n question.delete()\n return jsonify({\n 'success': True,\n 'deleted': question_id,\n\n })\n except:\n abort(404)\n\n # Create new question,\n\n @app.route('/questions', methods=['POST'])\n def crate_questions():\n body = request.get_json()\n new_question = body.get('question')\n new_answer = body.get('answer')\n new_category = body.get('category')\n new_difficulty = body.get('difficulty')\n if (new_question or new_answer or new_category or new_difficulty) is None:\n abort(404)\n try:\n question = Question(question=new_question, answer=new_answer, category=new_category,\n difficulty=new_difficulty)\n question.insert()\n total_questions = len(Question.query.all())\n current_questions = question.format()\n return jsonify({\n 'success': True,\n 'created': question.id,\n 'current_questions': current_questions,\n 'total_questions': total_questions\n\n })\n except:\n abort(422)\n\n # search questions\n\n @app.route('/questions/search', methods=['POST'])\n def questions_search():\n body = request.get_json()\n search_term = body.get('searchTerm')\n selections = Question.query.filter(\n Question.question.ilike(f'%{search_term}%')).all()\n if len(selections) == 0 or search_term == '':\n abort(404)\n current_questions = paginate_questions(request, selections)\n return jsonify({\n 'success': True,\n 'questions': current_questions,\n 'total_questions': len(Question.query.all()),\n })\n\n # questions based on category.\n\n @app.route('/categories//questions')\n def categories_questions(category_id):\n try:\n questions = Question.query.filter(Question.category == category_id).all()\n current_questions = [question.format() for question in questions]\n if len(questions) == 0:\n abort(404)\n return jsonify({\n 'success': True,\n 'category': category_id,\n 'questions': current_questions,\n 'total_categories_questions': len(current_questions),\n })\n\n except:\n abort(404)\n\n @app.route('/quizzes', methods=['POST'])\n def quizzes():\n\n body = request.get_json()\n\n category = body.get('quiz_category')\n previous = body.get('previous_questions')\n print('########################################')\n print(category,previous)\n\n current_question = None\n\n if category == {}:\n abort(404)\n\n if (category['id'] == 0):\n questions = Question.query.all()\n else:\n questions = Question.query.filter_by(category=category['id']).all()\n\n while len(previous) < len(questions):\n\n rand_num = random.randint(0, len(questions) - 1)\n\n random_question = questions[rand_num].format()\n\n if not (random_question['id'] in previous):\n current_question = random_question\n break\n\n return jsonify({\n 'success': True,\n 'question': current_question\n })\n\n # error handlers\n\n @app.errorhandler(404)\n def not_found(error):\n return jsonify({\n 'success': False,\n 'error': 404,\n 'message': 'resource not found'\n }), 404\n\n @app.errorhandler(422)\n def unprocessable(error):\n return jsonify({\n 'success': False,\n 'error': 422,\n 'message': 'unprocessable'\n }), 422\n\n return app\n","sub_path":"backend/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"360259610","text":"# Copyright 2019-present MongoDB Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport genny.perf_json as perf_json\nimport tests.parser_test_lib as test_lib\n\n\nclass PerfJsonTests(unittest.TestCase):\n def test_hole_in_thread_numbers(self):\n parsed = test_lib.parse_string(\"\"\"\n Clocks\n SystemTime,1\n MetricsTime,2\n\n Timers\n 12,A.0.o,50\n 13,A.3.o,50\n \"\"\")\n actual = perf_json.translate(parsed.timers())\n self.assertEqual(\n actual, {\n 'results': [{\n 'end': 0.00012,\n 'name': 'A.o',\n 'results': {\n 2: {\n 'ops_per_sec': 50.0,\n 'ops_per_sec_values': [50.0]\n }\n },\n 'start': -0.00039,\n 'workload': 'A.o'\n }],\n })\n\n def test_fixture2(self):\n parsed = test_lib.parse_fixture('csvoutput2')\n actual = perf_json.translate(parsed.timers())\n self.assertEqual(\n actual, {\n 'results': [{\n 'name': 'InsertRemoveTest.remove',\n 'workload': 'InsertRemoveTest.remove',\n 'start': 15402331038.70294,\n 'end': 15402333831.99723,\n 'results': {\n 100: {\n 'ops_per_sec': 4297048.190765492,\n 'ops_per_sec_values': [4297048.190765492]\n }\n }\n },\n {\n 'name': 'InsertRemoveTest.insert',\n 'workload': 'InsertRemoveTest.insert',\n 'start': 15402330730.74953,\n 'end': 15402333807.63649,\n 'results': {\n 100: {\n 'ops_per_sec': 8656706.69744836,\n 'ops_per_sec_values': [8656706.69744836]\n }\n }\n },\n {\n 'name': 'Genny.Setup',\n 'workload': 'Genny.Setup',\n 'start': 15402330355.93684,\n 'end': 15402330442.88445,\n 'results': {\n 1: {\n 'ops_per_sec': 8694761.0,\n 'ops_per_sec_values': [8694761.0]\n }\n }\n }]\n })\n\n def test_fixture1(self):\n parsed = test_lib.parse_fixture('csvoutput1')\n actual = perf_json.translate(parsed.timers())\n self.assertEqual(\n actual, {\n 'results': [{\n 'name': 'InsertTest.output',\n 'workload': 'InsertTest.output',\n 'start': 15378141410.61109,\n 'end': 15378141436.8726,\n 'results': {\n 2: {\n 'ops_per_sec': 1252307.75,\n 'ops_per_sec_values': [1252307.75]\n }\n }\n },\n {\n 'name': 'HelloTest.output',\n 'workload': 'HelloTest.output',\n 'start': 15378141410.61476,\n 'end': 15378141434.57943,\n 'results': {\n 2: {\n 'ops_per_sec': 55527.25,\n 'ops_per_sec_values': [55527.25]\n }\n }\n }]\n })\n","sub_path":"src/python/tests/perf_json_test.py","file_name":"perf_json_test.py","file_ext":"py","file_size_in_byte":4370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"401303197","text":"\r\nfrom api.baseDeDatos.baseDeDatos import cnx\r\nfrom flask import jsonify, request\r\n\r\nclass connectionDataBase:\r\n global cur\r\n cur = cnx.cursor()\r\n def validarUsuario(usuario, password):\r\n lista = []\r\n cur.execute(\"SELECT * FROM cliente WHERE nombreDeUsuario = '\"+ usuario+\"' AND contraseña ='\"+password+\"'\")\r\n rows = cur.fetchall()\r\n if len(rows) == 1:\r\n columns = [i[0] for i in cur.description]\r\n registro = zip(columns, rows[0])\r\n json = dict(registro)\r\n #cnx.close()\r\n else:\r\n json = False\r\n return json\r\n \r\n def create(body):\r\n data = (body['cedula'], body['nombre'], body['actividad'], \r\n body['estrato'], body['foto'])\r\n sql = \"INSERT INTO evergreen.participantes(cedula, nombre, actividad, estrato, foto) VALUES(%s,%s,%s,%s,%s)\"\r\n cur.execute(sql, data)\r\n #cnx.commit()\r\n return {'estado':\"Insertado\"}, 200\r\n \r\n def consultaProductos():\r\n lista = []\r\n cur.execute(\"SELECT * FROM productoServicio\")\r\n rows = cur.fetchall()\r\n columns = [i[0] for i in cur.description]\r\n for row in rows:\r\n registro = zip(columns, row)\r\n json = dict(registro)\r\n lista.append(json)\r\n #cnx.close()\r\n print(lista)\r\n return jsonify(lista)\r\n \r\n def updateDataBase(nombre, valor):\r\n print(nombre)\r\n print(valor)\r\n puntos = int(int(valor)/20)\r\n cur.execute(\"UPDATE cliente SET puntos = puntos+\"+str(puntos)+\" WHERE nombreDeUsuario = '\"+nombre+\"'\")\r\n cur.execute(\"SELECT * FROM cliente WHERE nombreDeUsuario = '\"+nombre+\"'\")\r\n rows= cur.fetchall()\r\n print(rows)\r\n columns = [i[0] for i in cur.description]\r\n registro = zip(columns, rows[0])\r\n json = dict(registro)\r\n json2 = json['puntos']\r\n json = dict({'puntos': json2})\r\n #cnx.close()\r\n return jsonify(json) ","sub_path":"api/controllers/connectionDataBase.py","file_name":"connectionDataBase.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"424316473","text":"import logging, os\nfrom datetime import datetime, timedelta\nfrom airflow import DAG\nfrom airflow.operators import DHUSSearchOperator, DHUSDownloadOperator, Sentinel2ThumbnailOperator, Sentinel2MetadataOperator, Sentinel2ProductZipOperator, RSYNCOperator, BashOperator, PythonOperator\nfrom sentinel2.utils import publish_product\nfrom sentinel1.secrets import dhus_credentials, geoserver_credentials\nfrom sentinel2.config import sentinel2_config, geoserver_url, geoserver_collection_name\n\nlog = logging.getLogger(__name__)\n\n# Settings\ndefault_args = {\n ##################################################\n # General configuration\n #\n 'start_date': datetime.today() - timedelta(days=1),\n 'owner': 'airflow',\n 'depends_on_past': False,\n 'provide_context': True,\n 'email': ['airflow@evoodas.dlr.de'],\n 'email_on_failure': False,\n 'email_on_retry': False,\n 'retries': 1,\n 'max_threads': 1,\n # 'queue': 'bash_queue',\n # 'pool': 'backfill',\n # 'priority_weight': 10,\n # 'end_date': datetime(2016, 1, 1),\n #\n}\n\n# DAG definition\ndag = DAG('Sentinel2', description='DAG for searching, filtering and downloading Sentinel-2 data from DHUS server',\n default_args = default_args,\n dagrun_timeout = timedelta(hours=10),\n schedule_interval = '0 0 * * *',\n catchup = False)\n\n# Sentinel2- Search Task Operator\nsearch_task = DHUSSearchOperator(task_id = 'dhus_search_task',\n dhus_url = 'https://scihub.copernicus.eu/dhus',\n dhus_user = dhus_credentials['username'],\n dhus_pass = dhus_credentials['password'],\n geojson_bbox = sentinel2_config['geojson_bbox'],\n startdate = sentinel2_config['startdate'],\n enddate = sentinel2_config['enddate'],\n keywords = sentinel2_config['search_keywords'],\n dag = dag)\n\n# Sentinel-2 Download Task Operator\ndownload_task = DHUSDownloadOperator(task_id = 'dhus_download_task',\n dhus_url = 'https://scihub.copernicus.eu/dhus',\n dhus_user = dhus_credentials['username'],\n dhus_pass = dhus_credentials['password'],\n download_max = sentinel2_config['download_max'],\n download_dir = sentinel2_config['download_dir'],\n dag = dag)\n\n# Archive Sentinel-2 RSYNC Task Operator\narchive_task = RSYNCOperator(task_id=\"original_package_upload\",\n host = sentinel2_config[\"rsync_hostname\"], \n remote_usr = sentinel2_config[\"rsync_username\"],\n ssh_key_file = sentinel2_config[\"rsync_ssh_key\"], \n remote_dir = sentinel2_config['granules_upload_dir'], \n xk_pull_dag_id = 'Sentinel2', \n xk_pull_task_id = 'dhus_download_task', \n xk_pull_key = 'downloaded_products_paths',\n dag=dag)\n\n\n# Sentinel-2 Create thumbnail Operator\nthumbnail_task = Sentinel2ThumbnailOperator(task_id = 'dhus_thumbnail_task',\n thumb_size_x = '64',\n thumb_size_y = '64',\n dag=dag)\n\n# Sentinel-2 Metadata Operator\nmetadata_task = Sentinel2MetadataOperator(task_id = 'dhus_metadata_task',\n bands_res = sentinel2_config['bands_res'],\n remote_dir = sentinel2_config['granules_upload_dir'],\n bands_dict = sentinel2_config['bands_dict'],\n GS_WORKSPACE = sentinel2_config['GS_WORKSPACE'], \n GS_LAYER = sentinel2_config['GS_LAYER'],\n GS_WMS_WIDTH = sentinel2_config['GS_WMS_WIDTH'],\n GS_WMS_HEIGHT = sentinel2_config['GS_WMS_HEIGHT'],\n GS_WMS_FORMAT = sentinel2_config['GS_WMS_FORMAT'],\n coverage_id = sentinel2_config['coverage_id'],\n dag = dag)\n\n# Archive Sentinel-2 RSYNC with .prj and .wld files Task Operator\narchive_wldprj_task = RSYNCOperator(task_id=\"sentinel2_upload_granules\",\n host = sentinel2_config[\"rsync_hostname\"],\n remote_usr = sentinel2_config[\"rsync_username\"],\n ssh_key_file = sentinel2_config[\"rsync_ssh_key\"], \n remote_dir = sentinel2_config['granules_upload_dir'], \n xk_pull_dag_id = 'Sentinel2',\n xk_pull_task_id = 'dhus_metadata_task', \n xk_pull_key = 'downloaded_products_with_wldprj',\n dag=dag)\n\n# Sentinel-2 Product.zip Operator.\n# The following variables are just pointing to placeholders until we implement the real files.\nbase_dir = \"/usr/local/airflow/metadata-ingestion/templates\"\nplaceholders_list = [os.path.join(base_dir,\"metadata.xml\"), os.path.join(base_dir,\"owsLinks.json\"), os.path.join(base_dir,\"product_abstract.html\")]\ngenerated_files_list = ['product/product.json','product/granules.json','product/thumbnail.jpeg']\n\nproduct_zip_task = Sentinel2ProductZipOperator(task_id = 'product_zip_task',\n target_dir = sentinel2_config[\"product_zip_target_dir\"],\n generated_files = generated_files_list,\n placeholders = placeholders_list,\n dag = dag)\n\npublish_task = PythonOperator(\n task_id=\"publish_product\",\n python_callable=publish_product,\n op_kwargs={\n 'geoserver_username': geoserver_credentials['username'],\n 'geoserver_password': geoserver_credentials['password'],\n 'geoserver_rest_endpoint': '{}/rest/oseo/collections/{}/products'.format(\n geoserver_url, geoserver_collection_name)\n },\n dag = dag\n)\n\n\nsearch_task >> download_task >> archive_task >> thumbnail_task >> metadata_task >> archive_wldprj_task >> product_zip_task >> publish_task\n","sub_path":"airflow/dags/sentinel2/Sentinel2.py","file_name":"Sentinel2.py","file_ext":"py","file_size_in_byte":6671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"321228153","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\" unit test for CDGM optical glass catalog\n\n.. codeauthor: Michael J. Hayford\n\"\"\"\n\nimport unittest\nimport opticalglass.cdgm as c\n\n\nclass CDGMTestCase(unittest.TestCase):\n catalog = c.CDGMCatalog()\n\n def compare_indices(self, glass, tol=5e-6):\n nC = glass.rindex(656.27)\n nd = glass.rindex(587.56)\n ne = glass.rindex(546.07)\n nF = glass.rindex(486.13)\n ng = glass.rindex(435.84)\n nh = glass.rindex(404.66)\n nI = glass.rindex(365.01)\n indxC = glass.glass_data()[self.catalog.data_index('nc')]\n indxd = glass.glass_data()[self.catalog.data_index('nd')]\n indxe = glass.glass_data()[self.catalog.data_index('ne')]\n indxF = glass.glass_data()[self.catalog.data_index('nF')]\n indxg = glass.glass_data()[self.catalog.data_index('ng')]\n indxh = glass.glass_data()[self.catalog.data_index('nh')]\n indxI = glass.glass_data()[self.catalog.data_index('ni')]\n self.assertAlmostEqual(nC, indxC, delta=tol)\n self.assertAlmostEqual(nd, indxd, delta=tol)\n self.assertAlmostEqual(ne, indxe, delta=tol)\n self.assertAlmostEqual(nF, indxF, delta=tol)\n self.assertAlmostEqual(ng, indxg, delta=tol)\n self.assertAlmostEqual(nh, indxh, delta=tol)\n self.assertAlmostEqual(nI, indxI, delta=tol)\n\n def test_cdgm_catalog_glass_index(self):\n g1 = self.catalog.glass_index('H-FK61') # first in list\n self.assertEqual(g1, 0)\n g2 = self.catalog.glass_index('H-QK3L')\n self.assertEqual(g2, 4)\n g3 = self.catalog.glass_index('F4')\n self.assertEqual(g3, 97)\n g4 = self.catalog.glass_index('H-K9L')\n self.assertEqual(g4, 13)\n g5 = self.catalog.glass_index('D-LaF50')\n self.assertEqual(g5, 229)\n g6 = self.catalog.glass_index('D-ZLaF85L') # last in list\n self.assertEqual(g6, 239)\n\n def test_cdgm_catalog_data_index(self):\n nd = self.catalog.data_index('nd')\n self.assertEqual(nd, 9)\n vd = self.catalog.data_index('υd')\n self.assertEqual(vd, 17)\n A0 = self.catalog.data_index('A0')\n self.assertEqual(A0, 21)\n nt = self.catalog.data_index('nt')\n self.assertEqual(nt, 2)\n\n def test_cdgm_glass_hfk61(self):\n glass = c.CDGMGlass('H-FK61')\n self.assertIsNotNone(glass.gindex)\n self.assertEqual(glass.name(), 'H-FK61')\n self.compare_indices(glass, tol=6e-6)\n\n def test_cdgm_glass_f4(self):\n glass = c.CDGMGlass('F4')\n self.assertIsNotNone(glass.gindex)\n self.assertEqual(glass.name(), 'F4')\n self.compare_indices(glass, tol=1e-5)\n\n def test_cdgm_glass_hk9l(self):\n glass = c.CDGMGlass('H-K9L')\n self.assertIsNotNone(glass.gindex)\n self.assertEqual(glass.name(), 'H-K9L')\n self.compare_indices(glass)\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)\n","sub_path":"test/test_cdgm.py","file_name":"test_cdgm.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"595036629","text":"#############################################################################################\n# Exercise #1\n# because the argument is list = [], that means that list is created\n# during function declaration rather than function invocation\ndef extend_list(elemenet, list = []):\n list.append(elemenet)\n return list\n# all calls of extend_list without specified list will append to only one list\nlist0 = extend_list(1)\nlist1 = extend_list(10)\nlist2 = extend_list(123, [])\nlist3 = extend_list('a')\nprint(list0, list1, list2, list3)\n\n# How to modify extend_list to produce append for separate lists\ndef extend_list(element, list = None):\n if list is None:\n list = []\n list.append(element)\n return list\nlist0 = extend_list(1)\nlist1 = extend_list(10)\nlist2 = extend_list(123, [])\nlist3 = extend_list('a')\nprint(list0, list1, list2, list3)\n\n#############################################################################################\n# Exercise #2\ndef multipliers():\n return [lambda x : i*x for i in range(4)]\n\nprint(m(2) for m in multipliers())\n# [6,6,6,6]\n# expected output would be [0,2,4,6], but\n\n\n#############################################################################################\n# Exercise #3\nlist1 = ['a', 'b', 'c', 'd', 'e']\nprint(list1[10:]) # []\n# This code will not result in the IndexError because it uses slicing and not indexing\nprint(list1[0:15]) # ['a', 'b', 'c', 'd', 'e'] it does not matter taht end index is higher\n\ntry:\n print(list1[15])\nexcept IndexError:\n print(\"This causes an error because it is out of bounds.\")\n\n#############################################################################################\n# Exercise #4\n# What will be the output of following commands\n\nlist0 = [ [ ] ] * 5 #Creates 5 list that reference the same one, that is why all the rest is affected\nprint(list0) # [[],[],[],[],[]]\nlist0[0].append(10)\nprint(list0) # [[10],[10],[10],[10],[10]]\nlist0[1].append(20)\nprint(list0) # [[10,20],[10,20],[10,20],[10,20],[10,20]]\nlist0.append(30)\nprint(list0) # [[10,20],[10,20],[10,20],[10,20],[10,20], 30]\n\n#If list is created with standard syntax it is different\nlist1 = [[],[],[],[],[]]\nprint(list1) # [[],[],[],[],[]]\nlist1[0].append(10)\nprint(list1) # [[10],[],[],[],[]]\nlist1[1].append(20)\nprint(list1) # [[10],[20],[],[],[]]\nlist1.append(30)\nprint(list1) # [[10],[20],[],[],[], 30]\n\n#############################################################################################\n# Exercise #5\n# Given a list of N numbers, use a single list comprehension to produce a new list that only contains values that are\n# a) even numbers\n# b) are from elements in the original list that had even indices\nlist0 = [1,5,4,3,6,8,1,2,6,4]\n\n#alternative using enumerate\nnew_list = [num for index,num in enumerate(list0) if num % 2 == 0 and index % 2 == 0]\nprint(new_list)\n\n#simpler solution\nnew_list = [num for num in list0[::2] if num % 2 == 0]\nprint(new_list, end=\"\\n\\n\\n\")\n\n#############################################################################################\n# Exercise #6\n# Write a function that prints the least integer that is not present in the given list\n# However this integer can not be sum of other elements in the list either.\nimport itertools\ndef check_number_bigger_by_1(a,b):\n c = b - a\n if c <= 1:\n return False\n elif c > 1:\n return True\n\n\ndef check_sum_equals_number(input_list, number):\n sum = 0\n for i in range(len(input_list)):\n for j in input_list[i]:\n sum += j\n if number == sum:\n return True\n else:\n sum = 0\n\n return False\n\ndef check_if_number_is_sum(number, list_slice):\n list_len = len(list_slice)\n for i in range(list_len):\n combinations = list(itertools.combinations(list_slice, i + 2)) # incerement by 2 because at least combination of 2\n if check_sum_equals_number(combinations, number) == True:\n return True\n return False\n\ndef find_least_number_missing(input_list):\n input_list = sorted(input_list) # needs to be sorted\n missing_number = - 1\n index = 0\n while index < len(input_list):\n if check_number_bigger_by_1(input_list[index], input_list[index+1]) == True:\n for i in range(1,input_list[index+1] - input_list[index]):\n missing_number = input_list[index] + i\n if check_if_number_is_sum(missing_number, input_list[0:index+1]) == False:\n return missing_number\n\n index += 1\n return missing_number\n\nlist0 = [1,2,5,7] # least not included is 4\nprint(find_least_number_missing(list0))\n\n#############################################################################################\na = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}\nprint(sorted([a[s] for s in a]))\n\nassert sum([1,2,3]) == 6, \"Should be 6\"\nassert sum([1,2,8]) == 6, \"Should be 6\"\n\n","sub_path":"snippets.py","file_name":"snippets.py","file_ext":"py","file_size_in_byte":4845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"26637560","text":"from add_vhost_4.Guessers.Posix_Guesser import Posix_Guesser\nimport os\nimport subprocess\n\nclass DebianLikeVHostEntry:\n\n def __init__(self, vhost_desired):\n self.vhost_desired = vhost_desired\n self.guesser = Posix_Guesser()\n self.vhost_file_entry = self.guesser.guess_debian_like_vhost_file(self.vhost_desired)\n self.physical_vhost_path = self.guesser.get_base_physical_path()\n\n\n def add(self, vhost_desired: str):\n template_file_resource = open(self.__get_template_config_file__(), \"r\")\n template_lines = template_file_resource.readlines()\n self.__write_entry__(template_lines)\n self.__link__()\n\n\n def write_folder(self):\n if not os.path.isdir(self.physical_vhost_path):\n os.makedirs(self.physical_vhost_path)\n self.__make_stub_php__()\n\n\n def can_write(self) -> bool:\n try:\n resource_test = open(self.vhost_file_entry, \"a\")\n resource_test.close()\n return True\n except:\n return False\n\n\n def get_physical_vhost_path(self):\n return self.physical_vhost_path\n\n\n def __get_template_config_file__(self) -> str:\n current_file_full_path = os.path.realpath(__file__)\n current_folder = os.path.dirname(current_file_full_path)\n return os.path.join(current_folder, 'vhost_config.template')\n\n\n def __write_entry__(self, template_lines: list):\n\n vhost_file_resource = open(self.vhost_file_entry, 'a')\n\n self.physical_vhost_path = os.path.join(self.guesser.get_base_physical_path(), self.vhost_desired)\n\n line_loop = 0\n\n for template_line in template_lines:\n if line_loop == 1:\n line_string = template_line.format(self.vhost_desired)\n elif line_loop == 2:\n line_string = template_line.format(self.physical_vhost_path)\n else:\n line_string = template_line\n vhost_file_resource.write(line_string)\n line_loop += 1\n\n\n def __make_stub_php__(self):\n file_name = os.path.join(self.physical_vhost_path, 'index.html')\n file_resource = open(file_name, \"w\")\n file_resource.write('Hello world! This VirtualHost name is ' + self.vhost_desired)\n\n\n def __link__(self):\n subprocess.call(['a2ensite', self.vhost_desired])\n","sub_path":"add_vhost_4/DebianLikeVHostEntry.py","file_name":"DebianLikeVHostEntry.py","file_ext":"py","file_size_in_byte":2342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"539184929","text":"#-*- coding: utf-8 -*-\n\nfrom gensim.models import Word2Vec\nfrom sklearn.manifold import TSNE\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\nmodel = Word2Vec.load(\"/home/hyeyoung/NKDB/model/CBOW_model.model\")\nvocab = model.wv.vocab\nX = model[vocab]\n\ntsne = TSNE(n_components=2)\n\nX_tsne = tsne.fit_transform(X[:100])\ndf = pd.DataFrame(X_tsne, index=X[:100], columns=['x', 'y'])\ndf.head(10)\n\n\n\nfig = plt.figure()\nfig.set_size_inches(40,20)\nax = fig.add_subplot(1, 1, 1)\n\nax.scatter(df['x'], df['y'])\n\nfor word, pos in df.iterrows():\n ax.annotate(word, pos, fontsize=30)\nplt.show()\n","sub_path":"topicmodel/testCBOW.py","file_name":"testCBOW.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"247931607","text":"#!/usr/bin/python3\n# Distributes archives to web servers with do_deploy().\nfrom fabric.api import *\nfrom datetime import datetime\nimport os.path\n\nenv.hosts = [\"54.145.28.120\", \"35.229.33.79\"]\n\n\ndef do_pack():\n \"\"\"Create a tar gzipped archive of the directory web_static.\"\"\"\n DateTime = datetime.utcnow()\n File = \"versions/web_static_{}{}{}{}{}{}.tgz\".format(DateTime.year,\n DateTime.month,\n DateTime.day,\n DateTime.hour,\n DateTime.minute,\n DateTime.second)\n if os.path.isdir(\"versions\") is False:\n if local(\"mkdir -p versions\").failed is True:\n return None\n if local(\"tar -cvzf {} web_static\".format(File)).failed is True:\n return None\n return File\n\n\ndef do_deploy(archive_path):\n \"\"\"Deploys static archive to web servers.\"\"\"\n if os.path.isfile(archive_path) is False:\n return False\n Path = archive_path.split(\"/\")[-1]\n Name = Path.split(\".\")[0]\n\n if put(archive_path, \"/tmp/{}\".format(Path)).failed is True:\n return False\n if run(\"rm -rf /data/web_static/releases/{}/\".\n format(Name)).failed is True:\n return False\n if run(\"mkdir -p /data/web_static/releases/{}/\".\n format(Name)).failed is True:\n return False\n if run(\"tar -xzf /tmp/{} -C /data/web_static/releases/{}/\".\n format(Path, Name)).failed is True:\n return False\n if run(\"rm /tmp/{}\".format(Path)).failed is True:\n return False\n if run(\"mv /data/web_static/releases/{}/web_static/* \"\n \"/data/web_static/releases/{}/\".format(Name, Name)).failed is True:\n return False\n if run(\"rm -rf /data/web_static/releases/{}/web_static\".\n format(Name)).failed is True:\n return False\n if run(\"rm -rf /data/web_static/current\").failed is True:\n return False\n if run(\"ln -s /data/web_static/releases/{}/ /data/web_static/current\".\n format(Name)).failed is True:\n return False\n print(\"\\nNew Version Successfuly Deployed!\\n\")\n return True\n\n\ndef deploy():\n \"\"\"Executes do_deploy & do_pack.\"\"\"\n NewPath = do_pack()\n if not NewPath:\n return False\n else:\n return (do_deploy(NewPath))\n","sub_path":"3-deploy_web_static.py","file_name":"3-deploy_web_static.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"176592323","text":"from preprocess import get_test_train_data\nfrom save_load import get_last_file_number\nfrom save_load import load\nfrom model import accuracy, loss\nfrom keras import backend\nimport sys, os\nimport tensorflow as tf\n\ndef evaluate_model(model, x_test, y_test):\n y_pred = model.predict(x_test)\n y_pred = backend.cast(y_pred, 'float32')\n current_accuracy = accuracy(y_test, y_pred)\n current_loss = loss(y_test, y_pred)\n return [current_loss, current_accuracy]\n\nif __name__ == '__main__':\n \n # file = \"F:\\Projects\\python\\self_driving_game\\data\\dataset_mini.pz\"\n file = os.environ['DATA_DIR']+ \"/dataset_75p_gray.pz\"\n if len(sys.argv)<=1: count = None\n else: count = int(sys.argv[1]);\n \n # Load model\n exp_folder = 'experiments/comparison/dropout/exp_' + '{0:03d}'.format(get_last_file_number(prefix='exp_', suffix=''))\n model = load(count, path=exp_folder)\n\n # Evaluate model\n x_train, x_test, y_train, y_test = get_test_train_data(file, 10000, tanh=True)\n print('x_test shape', x_test.shape)\n scores = evaluate_model(model, x_test, y_test)\n\n # Print scores\n print('\\n\\n')\n print(\"Loss: \", backend.get_value(scores[0]))\n print(\"Accuracy: \", backend.get_value(scores[1])*100, \"%\")\n","sub_path":"experiments/comparisons/filter_visualisation/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"330581581","text":"import States\nimport OPEP\nimport LS_Rmat_solve\nimport numpy as np\n\n\ntermSymbols = ['S','P','D','F','G','H',\\\n\t\t\t 'I','K','L','M','N','O',\\\n\t\t\t 'Q','R','T','U','V','W',\\\n\t\t\t 'X','Y','Z']\n\n\ndef findPhases(Tlab, basis, LS_solve, model):\n\t\n\tJmin = basis.Jmin\n\tJmax = basis.Jmax\n\t\n\tmu = model.mu\n\tpi = np.pi\n\tradToDeg = 180./pi\n\tk0 = np.sqrt(Tlab*mu/2)\n\t\n\td\t = dict()\n\td2\t = dict()\n\tstates = []\n\tphases = []\n\t\n\tmixStates = []\n\tmixing = []\n\t\n\tfor J in range(Jmin, Jmax+1):\t\t\t\t\t# we set out to find phases for all desired J\n\t\tstatesInJ = basis.states[J-Jmin] \t\t\t\t# this is a list of references to states with tot. ang. mom. J\n\t\t\n\t\tskipState = [] # we use this list to skip states we've already calculated\n\t\t\n\t\tfor i in range(0, len(statesInJ)):\t\t\t# we loop through the states in statesInJ\n\t\t\t\n\t\t\tif i in skipState:\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tBra = statesInJ[i]\n\t\t\tcoupled = False\n\t\t\t\n\t\t\tl1 = Bra.L\n\t\t\tl2 = Bra.L\n\t\t\tS = Bra.S\n\t\t\tJ = Bra.J\n\t\t\tT = Bra.T\n\t\t\t\n\t\t\tstateBra = '{}{}{}'.format(2*Bra.S+1, termSymbols[Bra.L], Bra.J)\n\t\t\t\n\t\t\t# we try to find coupled states (i.e. S==S', J==J', L=/=L')\n\t\t\tfor j in range(i+1, len(statesInJ)):\n\t\t\t\tKet = statesInJ[j]\n\t\t\t\t\n\t\t\t\tif Bra.S == Ket.S and Bra.T == Ket.T and Bra.L != Ket.L:\n\t\t\t\t\t\n\t\t\t\t\tl2 = Ket.L\n\t\t\t\t\tstateKet = '{}{}{}'.format(2*Ket.S+1, termSymbols[Ket.L], Ket.J)\n\t\t\t\t\t\n\t\t\t\t\tstateMix = '{}_{}'.format(stateBra, stateKet)\n\t\t\t\t\t\n\t\t\t\t\t# each state can be coupled to only one other state, if at all\n\t\t\t\t\tskipState.append(j)\n\t\t\t\t\tcoupled = True\n\t\t\t\t\tbreak\n\t\t\t\n\t\t\t# solve the Lippmann-Schwinger equation\n\t\t\tR = LS_solve.makeReactionMat(l1,l2,S,J,T,Tlab)\n\t\t\t\n\t\t\t# find coupled phase-shifts\n\t\t\tif coupled == True:\t\n\t\t\t\t# Blatt-Biedenharn (BB) convention\n\t\t\t\ttwoEpsilonJ_BB = np.arctan(2*R[1]/(R[0]-R[3]))\t# mixing parameter\n\t\t\t\tdelta_plus_BB = np.arctan(-(pi/4)*k0*mu*(R[0] + R[3] - (R[0] - R[3])/(np.cos(twoEpsilonJ_BB))))\n\t\t\t\tdelta_minus_BB = np.arctan(-(pi/4)*k0*mu*(R[0] + R[3] + (R[0] - R[3])/(np.cos(twoEpsilonJ_BB))))\n\t\t\t\t\n\t\t\t\t# Stapp convention (bar-phase shifts) in terms of Blatt-Biedenharn convention\n\t\t\t\ttwoEpsilonJ = np.arcsin(np.sin(twoEpsilonJ_BB)*np.sin(delta_minus_BB - delta_plus_BB))\t# mixing parameter\n\t\t\t\tdelta_minus\t= 0.5*(delta_plus_BB + delta_minus_BB + np.arcsin(np.tan(twoEpsilonJ)/np.tan(twoEpsilonJ_BB)))*radToDeg\n\t\t\t\tdelta_plus\t= 0.5*(delta_plus_BB + delta_minus_BB - np.arcsin(np.tan(twoEpsilonJ)/np.tan(twoEpsilonJ_BB)))*radToDeg\n\t\t\t\ttwoEpsilonJ *= -radToDeg\t# the minus is due to convention on how the epsilons are calculated (I think)\n\t\t\t\t\n\t\t\t\tif stateBra not in d:\n\t\t\t\t\td[stateBra] = len(states)\n\t\t\t\t\tstates.append(stateBra)\n\t\t\t\t\tphases.append([])\n\t\t\t\tif stateKet not in d:\n\t\t\t\t\td[stateKet] = len(states)\n\t\t\t\t\tstates.append(stateKet)\n\t\t\t\t\tphases.append([])\n\t\t\t\tif stateMix not in d2:\n\t\t\t\t\td2[stateMix] = len(mixStates)\n\t\t\t\t\tmixStates.append(stateMix)\n\t\t\t\t\tmixing.append([])\n\t\t\t\t\n\t\t\t\tphases[d[stateBra]].append(delta_minus)\n\t\t\t\tphases[d[stateKet]].append(delta_plus)\n\t\t\t\tmixing[d2[stateMix]].append(twoEpsilonJ/2.)\n\t\t\t\t\n\t\t\t# find uncoupled phase-shifts\n\t\t\telse:\n\t\t\t\tdelta = np.arctan(-(pi/2)*k0*mu*R)*radToDeg\n\t\t\t\t\n\t\t\t\tif stateBra not in d:\n\t\t\t\t\td[stateBra] = len(states)\n\t\t\t\t\tstates.append(stateBra)\n\t\t\t\t\tphases.append([])\n\t\t\t\t\n\t\t\t\tphases[d[stateBra]].append(delta)\n\t\t\tskipState.append(i)\n\t\t\t\t\n\treturn states, phases, mixStates, mixing\n","sub_path":"Lippmann-Schwinger modular solver/Old_Solve/Calculate_Phases.py","file_name":"Calculate_Phases.py","file_ext":"py","file_size_in_byte":3309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"540569567","text":"#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n\"\"\"\ngera_adn.py\n\nCreated by Ernesto Costa on 2008-09-28.\nCopyright (c) 2008 University of Coimbra. All rights reserved.\n\"\"\"\n\nimport sys\nimport os\n\nfrom string import *\nfrom random import *\n\ndef gera_adn(tamanho):\n\tbases='ATCG'\n\tadn=''\n\tfor i in range(tamanho):\n\t\tadn=adn + choice(bases)\n\treturn adn\n\ndef main():\n\tprint(gera_adn(25))\n\n\nif __name__ == '__main__':\n\tmain()\n\n","sub_path":"controlo/programas/gera_adn.py","file_name":"gera_adn.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"138668667","text":"import matplotlib.pylab as plt\nimport matplotlib\nfrom io import BytesIO, StringIO\nimport matplotlib.pyplot as plt\nimport mpld3\nfrom matplotlib.pyplot import figure\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.colors import ListedColormap\nfrom typing import List\nimport numpy as np\nimport math\nimport copy\nfrom colour import Color\n\n\n# FSIZE_TITLE = 16\n# FSIZE_LABEL = 14\n# FSIZE_LABEL_S = 14\n# FSIZE_LABEL_XS = 12\n\n\n# FSIZE_TITLE = 16\n# FSIZE_LABEL = 14\n# FSIZE_LABEL_S = 14\n# FSIZE_LABEL_XS = 12\n# OPACITY = 0.9\n\nFSIZE_TITLE = 18\nFSIZE_LABEL = 18\nFSIZE_LABEL_S = 16\nFSIZE_LABEL_XS = 14\nOPACITY = 0.9\n\n\nclass Timeseries:\n # declare props as object NOT class props!\n def __init__(self):\n self.label = \"None\"\n self.color = \"blue\"\n self.x = []\n self.y = []\n\n\nclass Barseries:\n # declare props as object NOT class props!\n def __init__(self):\n self.label = \"None\"\n self.color = \"blue\"\n self.data = []\n self.average = None\n\n\nclass CMapMatrixElement:\n def __init__(self):\n self.i = 0\n self.j = 0\n self.ilabel = \"\"\n self.jlabel = \"\"\n self.val = 0\n self.auxval = 0\n\n\ndef plot_timeseries_multi_sub2(timeseries_arrays: List[List[Timeseries]], title, xlabel, ylabel, figsize):\n matplotlib.style.use('default')\n id = 0\n\n if not figsize:\n # fig = plt.figure(id, figsize=(9, 16))\n fig = plt.figure(id)\n else:\n fig = plt.figure(id, figsize=figsize)\n \n n_sub = len(timeseries_arrays)\n for (i, timeseries_array) in enumerate(timeseries_arrays):\n\n set_plot_font()\n\n plt.subplot(n_sub * 100 + 11 + i)\n plt.grid()\n for ts in timeseries_array:\n x = ts.x\n y = ts.y\n\n plt.plot(x, y, label=ts.label, color=ts.color, linewidth=3)\n if n_sub == 1 or (i == (n_sub - 1)):\n set_disp(title[i], xlabel, ylabel[i])\n else:\n set_disp(title[i], \"\", ylabel[i])\n \n plt.legend(fontsize=FSIZE_LABEL_S)\n\n # ax.tick_params(axis = 'both', which = 'major', labelsize = FSIZE_LABEL_XS)\n # ax.tick_params(axis = 'both', which = 'minor', labelsize = FSIZE_LABEL_XS)\n\n fig = plt.gcf()\n\n plt.show()\n\n return fig, mpld3.fig_to_html(fig)\n\ndef plot_timeseries_multi(id, timeseries_array: List[Timeseries], title, xlabel, ylabel, show=True, scale=None, figsize=None):\n matplotlib.style.use('default')\n \n if not figsize:\n # fig = plt.figure(id, figsize=(9, 16))\n fig = plt.figure(id)\n else:\n fig = plt.figure(id, figsize=figsize)\n \n ax = plt.gca()\n ax.tick_params(axis='both', which='major', labelsize=FSIZE_LABEL_XS)\n ax.tick_params(axis='both', which='minor', labelsize=FSIZE_LABEL_XS)\n\n for ts in timeseries_array:\n x = ts.x\n y = ts.y\n plt.plot(x, y, label=ts.label, color=ts.color, linewidth=3) \n set_disp(title, xlabel, ylabel) \n plt.legend(fontsize=FSIZE_LABEL_S)\n\n # ax.tick_params(axis = 'both', which = 'major', labelsize = FSIZE_LABEL_XS)\n # ax.tick_params(axis = 'both', which = 'minor', labelsize = FSIZE_LABEL_XS)\n\n if not scale:\n pass\n else:\n ax.set_xlim(scale[0])\n ax.set_ylim(scale[1])\n\n plt.grid()\n\n fig = plt.gcf()\n\n if show:\n plt.show()\n\n return fig, fig\n\ndef set_plot_font(size=FSIZE_LABEL_XS):\n plt.rc('xtick', labelsize=size)\n plt.rc('ytick', labelsize=size)\n plt.rc('legend', fontsize=size)\n\n\n\n\n\ndef stem_timeseries_multi(timeseries_array: List[Timeseries], title, xlabel, ylabel, separate):\n matplotlib.style.use('default')\n fig = plt.figure()\n\n bottom = None\n for ts in timeseries_array:\n for y in ts.y:\n if bottom is None or y < bottom:\n bottom = y\n\n for ts in timeseries_array:\n plt.stem(ts.x, ts.y, label=ts.label, bottom=bottom)\n\n set_disp(title, xlabel, ylabel)\n\n plt.legend(fontsize=FSIZE_LABEL_S)\n fig = plt.gcf()\n\n plt.show()\n\n return fig, mpld3.fig_to_html(fig)\n\n\ndef plot_timeseries_ax(timeseries: Timeseries, title, xlabel, ylabel, fig, ax, vlines):\n set_plot_font()\n\n ax.plot(timeseries.x, timeseries.y)\n # set_disp(title, xlabel, ylabel)\n\n if vlines is not None:\n for vline in vlines:\n ax.axvline(x=vline, ymin=0, ymax=1, c=\"coral\", ls=\"-\")\n\n set_disp_ax(ax, title, xlabel, ylabel)\n\n # plt.legend()\n # plt.show()\n return fig\n\n\ndef plot_timeseries(id, timeseries: Timeseries, title, xlabel, ylabel, scale=None, figsize=None):\n\n if not figsize:\n fig = plt.figure(id)\n else:\n fig = plt.figure(id, figsize=figsize)\n\n plt.plot(timeseries.x, timeseries.y, linewidth=3)\n set_disp(title, xlabel, ylabel)\n\n ax = plt.gca()\n ax.tick_params(axis='both', which='major', labelsize=FSIZE_LABEL_XS)\n ax.tick_params(axis='both', which='minor', labelsize=FSIZE_LABEL_XS)\n\n if not scale:\n pass\n else:\n ax.set_xlim(scale[0])\n ax.set_ylim(scale[1])\n\n plt.grid()\n\n plt.legend(fontsize=FSIZE_LABEL_S)\n\n fig = plt.gcf()\n\n plt.show()\n\n return fig, mpld3.fig_to_html(fig)\n\n\ndef save_figure(fig, file):\n fig.savefig(file, dpi=300)\n\n\ndef set_disp_ax(ax, title, xlabel, ylabel):\n if title:\n ax.set_title(title, fontsize=FSIZE_TITLE)\n if xlabel:\n ax.set_xlabel(xlabel, fontsize=FSIZE_LABEL)\n if ylabel:\n ax.set_ylabel(ylabel, fontsize=FSIZE_LABEL)\n\n\ndef set_disp(title, xlabel, ylabel):\n if title:\n plt.gca().set_title(title, fontsize=FSIZE_TITLE)\n if xlabel:\n plt.xlabel(xlabel, fontsize=FSIZE_LABEL)\n if ylabel:\n plt.ylabel(ylabel, fontsize=FSIZE_LABEL)\n\n\n# fig = plt.figure()\n# ax1 = fig.add_subplot(111)\n# ax1.plot(x, y1)\n# ax1.set_ylabel('y1')\n\n# ax2 = ax1.twinx()\n# ax2.plot(x, y2, 'r-')\n# ax2.set_ylabel('y2', color='r')\n# for tl in ax2.get_yticklabels():\n# tl.set_color('r')\n\n# plt.savefig('images/two-scales-5.png')\n\ndef plot_barchart_multi(bss: List[Barseries], xlabel, ylabel, title, xlabels, limits):\n return plot_barchart_multi_core(bss, xlabel, ylabel, title, xlabels, limits, None, None, True, None, 0, None)[0]\n # 0.155\n # return plot_barchart_multi_core(bss, xlabel, ylabel, title, xlabels, top, None, None, True, -0.125, 0, None)[0]\n\n\ndef plot_barchart_multi_dual(bss1: List[Barseries], bss2: List[Barseries], xlabel, ylabel1, ylabel2, title, xlabels, limits: List[List[int]], show):\n fig = plt.figure()\n ax1 = fig.add_subplot(111)\n\n if limits is None:\n limits = [None, None]\n\n fig, ax1 = plot_barchart_multi_core(\n bss1, xlabel, ylabel1, title, xlabels, limits[0], fig, ax1, False, -0.155, 2, \"upper left\")\n\n for b in bss2:\n b.color = \"red\"\n\n ax2 = ax1.twinx()\n fig, _ = plot_barchart_multi_core(\n bss2, xlabel, ylabel2, title, xlabels, limits[1], fig, ax2, True, 0.155, 2, \"upper right\")\n\n return fig\n\n\ndef plot_barchart_multi_core(bss: List[Barseries], xlabel, ylabel, title, xlabels, limits: List[int], fig, ax, show, offset, bcount, legend_loc):\n\n # create plot\n if fig is None or ax is None:\n print(\"creating new figure\")\n fig, ax = plt.subplots()\n\n # ax = plt.gca()\n ax.tick_params(axis='both', which='major', labelsize=FSIZE_LABEL_XS)\n ax.tick_params(axis='both', which='minor', labelsize=FSIZE_LABEL_XS)\n\n n_groups = len(bss)\n\n if bcount != 0:\n bar_width = 1 / (bcount + 1)\n else:\n bar_width = 1 / (n_groups+1)\n\n if offset is None:\n # offset = -1 / (n_groups * 2 * bar_width + 1)\n if n_groups == 2:\n offset = bar_width / 2\n else:\n offset = -bar_width / 2\n\n # if n_groups == 1:\n # bar_width = 1\n\n opacity = OPACITY\n\n low = None\n high = None\n\n for i in range(n_groups):\n\n index = np.arange(len(bss[i].data))\n\n # print(bss[i].data)\n\n low1 = min(bss[i].data)\n high1 = max(bss[i].data)\n\n if low is None:\n low = low1\n high = high1\n\n if low1 < low:\n low = low1\n if high1 > high:\n high = high1\n\n rb = plt.bar(\n index + offset + i * bar_width,\n bss[i].data,\n bar_width,\n alpha=opacity,\n color=bss[i].color,\n label=bss[i].label,\n zorder=3)\n\n plt.xlabel(xlabel, fontsize=FSIZE_LABEL)\n plt.ylabel(ylabel, fontsize=FSIZE_LABEL)\n plt.title(title, fontsize=FSIZE_TITLE)\n\n # plt.xlabel(xlabel)\n # plt.ylabel(ylabel)\n # plt.title(title)\n\n if n_groups == 1:\n plt.xticks(index, xlabels)\n else:\n plt.xticks(index + bar_width, xlabels)\n\n if not legend_loc:\n legend_loc = \"upper left\"\n\n plt.legend(loc=legend_loc, fontsize=FSIZE_LABEL_S)\n\n ax.grid(zorder=0)\n\n print(\"low limit: \", low)\n print(\"high limit: \", high)\n # plt.ylim([math.ceil(low-0.5*(high-low)), math.ceil(high+0.5*(high-low))])\n # plt.ylim([math.ceil(low-0.005*(high-low)), math.ceil(high+0.005*(high-low))])\n # plt.ylim([low, high])\n\n # kscale = 0.25\n kscale = 0.01\n\n if limits is not None:\n low = limits[0]\n high = limits[1]\n else:\n high += kscale * high\n low -= kscale * low\n\n plt.ylim([low, high])\n\n # set_fontsize()\n plt.tight_layout()\n\n if show:\n print(\"show\")\n plt.show()\n\n return fig, ax\n\n\ndef set_fontsize():\n # SMALL_SIZE = 20\n # MEDIUM_SIZE = 24\n # BIGGER_SIZE = 28\n\n # plt.rc('font', size=SMALL_SIZE) # controls default text sizes\n # plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title\n # plt.rc('axes', labelsize=MEDIUM_SIZE) # fontsize of the x and y labels\n # plt.rc('xtick', labelsize=SMALL_SIZE) # fontsize of the tick labels\n # plt.rc('ytick', labelsize=SMALL_SIZE) # fontsize of the tick labels\n # plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize\n # plt.rc('figure', titlesize=BIGGER_SIZE)\n\n matplotlib.rcParams.update({'font.size': 16})\n\n\ndef plot_barchart(labels, values, xlabel, ylabel, title, color):\n\n fig = plt.figure()\n\n y_pos = np.arange(len(labels))\n\n plt.bar(y_pos, values, align='center', alpha=OPACITY, color=color)\n plt.xticks(y_pos, labels)\n\n plt.xlabel(xlabel)\n plt.ylabel(ylabel)\n\n low = min(values)\n high = max(values)\n\n print(low)\n print(high)\n # plt.ylim([math.ceil(low-0.5*(high-low)), math.ceil(high+0.5*(high-low))])\n # plt.ylim([math.ceil(low-0.005*(high-low)), math.ceil(high+0.005*(high-low))])\n plt.ylim([low - 0.005*low, high + 0.005*high])\n\n plt.title(title)\n\n fig = plt.gcf()\n\n plt.show()\n\n return fig\n\n\ndef heatmap(data, row_labels, col_labels, ax=None,\n cbar_kw={}, cbarlabel=\"\", scale=None, **kwargs):\n \"\"\"\n Create a heatmap from a numpy array and two lists of labels.\n\n Parameters\n ----------\n data\n A 2D numpy array of shape (N, M).\n row_labels\n A list or array of length N with the labels for the rows.\n col_labels\n A list or array of length M with the labels for the columns.\n ax\n A `matplotlib.axes.Axes` instance to which the heatmap is plotted. If\n not provided, use current axes or create a new one. Optional.\n cbar_kw\n A dictionary with arguments to `matplotlib.Figure.colorbar`. Optional.\n cbarlabel\n The label for the colorbar. Optional.\n **kwargs\n All other arguments are forwarded to `imshow`.\n \"\"\"\n\n if not ax:\n ax = plt.gca()\n\n # Plot the heatmap\n\n # ax.figure.clim(0, 1)\n\n im = ax.imshow(data, **kwargs)\n\n # ax.figure.clim(0, 1)\n\n if scale is not None:\n for im in plt.gca().get_images():\n im.set_clim(scale[0], scale[1])\n\n # Create colorbar\n cbar = None\n if cbarlabel is not None:\n cbar = ax.figure.colorbar(im, ax=ax, **cbar_kw)\n cbar.ax.set_ylabel(cbarlabel, rotation=-90, va=\"bottom\")\n\n # We want to show all ticks...\n ax.set_xticks(np.arange(data.shape[1]))\n ax.set_yticks(np.arange(data.shape[0]))\n # ... and label them with the respective list entries.\n ax.set_xticklabels(col_labels)\n ax.set_yticklabels(row_labels)\n\n # Let the horizontal axes labeling appear on top.\n # ax.tick_params(top=False, bottom=True,\n # labeltop=False, labelbottom=True)\n\n ax.tick_params(top=False, bottom=False, left=False,\n labeltop=False, labelbottom=True)\n\n # Rotate the tick labels and set their alignment.\n # plt.setp(ax.get_xticklabels(), rotation=30, ha=\"right\",\n # rotation_mode=\"anchor\")\n\n # plt.setp(ax.get_yticklabels(), rotation=30, ha=\"right\",\n # rotation_mode=\"anchor\")\n\n # Turn spines off and create white grid.\n for edge, spine in ax.spines.items():\n spine.set_visible(False)\n\n ax.set_xticks(np.arange(data.shape[1]+1)-.5, minor=True)\n ax.set_yticks(np.arange(data.shape[0]+1)-.5, minor=True)\n\n ax.grid(which=\"minor\", color=\"w\", linestyle='-', linewidth=3)\n # ax.grid(which=\"minor\", color=\"w\", linestyle='-', linewidth=0)\n ax.tick_params(which=\"minor\", bottom=False, left=False)\n\n return im, cbar\n\n\ndef annotate_heatmap(im, data=None, valfmt=\"{x:.2f}\",\n textcolors=[\"black\", \"white\"],\n threshold=None, **textkw):\n \"\"\"\n A function to annotate a heatmap.\n\n Parameters\n ----------\n im\n The AxesImage to be labeled.\n data\n Data used to annotate. If None, the image's data is used. Optional.\n valfmt\n The format of the annotations inside the heatmap. This should either\n use the string format method, e.g. \"$ {x:.2f}\", or be a\n `matplotlib.ticker.Formatter`. Optional.\n textcolors\n A list or array of two color specifications. The first is used for\n values below a threshold, the second for those above. Optional.\n threshold\n Value in data units according to which the colors from textcolors are\n applied. If None (the default) uses the middle of the colormap as\n separation. Optional.\n **kwargs\n All other arguments are forwarded to each call to `text` used to create\n the text labels.\n \"\"\"\n\n if not isinstance(data, (list, np.ndarray)):\n data = im.get_array()\n\n # Normalize the threshold to the images color range.\n if threshold is not None:\n threshold = im.norm(threshold)\n else:\n threshold = im.norm(data.max())/2.\n\n # Set default alignment to center, but allow it to be\n # overwritten by textkw.\n kw = dict(horizontalalignment=\"center\",\n verticalalignment=\"center\")\n kw.update(textkw)\n\n # Get the formatter in case a string is supplied\n if isinstance(valfmt, str):\n valfmt = matplotlib.ticker.StrMethodFormatter(valfmt)\n\n # Loop over the data and create a `Text` for each \"pixel\".\n # Change the text's color depending on the data.\n texts = []\n for i in range(data.shape[0]):\n for j in range(data.shape[1]):\n kw.update(color=textcolors[int(im.norm(data[i, j]) > threshold)])\n text = im.axes.text(j, i, valfmt(data[i, j], None), **kw)\n texts.append(text)\n\n return texts\n\n\ndef plot_matrix_cmap(elements: List[CMapMatrixElement], xsize, ysize, title, xlabel, ylabel, xlabels, ylabels, scale=None):\n\n min_val, max_val = elements[0].val, elements[0].val\n\n # intersection_matrix = np.random.randint(0, 10, size=(max_val, max_val))\n intersection_matrix = np.zeros((xsize, ysize))\n\n # print(intersection_matrix)\n for e in elements:\n intersection_matrix[e.i][e.j] = e.val\n if e.val < min_val:\n min_val = e.val\n if e.val > max_val:\n max_val = e.val\n\n fig, ax = plt.subplots()\n\n # ax = plt.gca()\n ax.tick_params(axis='both', which='major', labelsize=FSIZE_LABEL_XS)\n ax.tick_params(axis='both', which='minor', labelsize=FSIZE_LABEL_XS)\n\n cmap = \"RdYlGn\"\n cmap = \"viridis\"\n cmap = \"YlGnBu\"\n\n im, cbar = heatmap(intersection_matrix, xlabels, ylabels, ax=ax,\n cmap=cmap, cbarlabel=\"\", scale=scale)\n\n # texts = annotate_heatmap(im, valfmt=\"{x:.1f} t\")\n\n def millions(x, pos):\n 'The two args are the value and tick position'\n return '%.1f' % (x)\n\n texts = annotate_heatmap(im, valfmt=millions)\n\n set_disp(title, xlabel, ylabel)\n\n fig.tight_layout()\n plt.show()\n\n return fig\n\n\ndef plot_matrix_cmap_plain(elements: List[CMapMatrixElement], xsize, ysize, title, xlabel, ylabel, xlabels, ylabels, scale=None, figsize=None):\n\n min_val, max_val = elements[0].val, elements[0].val\n\n # intersection_matrix = np.random.randint(0, 10, size=(max_val, max_val))\n intersection_matrix = np.zeros((xsize, ysize))\n\n # print(intersection_matrix)\n\n # intersection_matrix = np.zeros((xsize, ysize + 2))\n\n for row in range(xsize):\n for col in range(ysize):\n intersection_matrix[row][col] = -1\n\n for e in elements:\n if e.val == 0:\n e.val = -1\n\n intersection_matrix[e.i][e.j] = e.val\n # print(e.val)\n if e.val < min_val:\n min_val = e.val\n if e.val > max_val:\n max_val = e.val\n\n # intersection_matrix[0][ysize] = 0\n # intersection_matrix[0][ysize+1] = 1\n\n if figsize is not None:\n fig, ax = plt.subplots(figsize=figsize)\n else:\n fig, ax = plt.subplots()\n\n cmap = \"RdYlGn\"\n cmap = \"viridis\"\n cmap = \"YlGnBu\"\n cmap = \"Blues\"\n\n # color_map = plt.cm.get_cmap('Blues')\n # cmap = color_map\n\n cmap = copy.copy(plt.get_cmap(cmap))\n\n # modify colormap\n alpha = OPACITY\n colors = []\n for ind in range(cmap.N):\n c = []\n # print(cmap(ind))\n # quit()\n c = list(cmap(ind))\n rgb = [c[0], c[1], c[2]]\n hsv = list(rgb2hsv(rgb[0], rgb[1], rgb[2]))\n hsv[0] += 10\n # print(hsv)\n # quit()\n rgb = hsv2rgb(hsv[0], hsv[1], hsv[2])\n c[0] = rgb[0]\n c[1] = rgb[1]\n c[2] = rgb[2]\n c[3] = alpha\n \n colors.append(tuple(c))\n\n\n cmap = matplotlib.colors.ListedColormap(colors, name='my_name')\n\n cmap.set_under('white', -1)\n\n ax.tick_params(axis='both', which='major', labelsize=FSIZE_LABEL_S)\n ax.tick_params(axis='both', which='minor', labelsize=FSIZE_LABEL_S)\n\n im, cbar = heatmap(intersection_matrix, xlabels, ylabels, ax=ax,\n cmap=cmap, cbarlabel=None, scale=scale)\n\n set_disp(title, xlabel, ylabel)\n\n fig.tight_layout()\n plt.show()\n\n return fig\n\n\ndef get_n_ax(n, figsize=None, height_ratios=None):\n if figsize:\n # print(n)\n if height_ratios is not None:\n fig, ax = plt.subplots(nrows=n, ncols=1, figsize=figsize, gridspec_kw={\n 'height_ratios': height_ratios})\n else:\n fig, ax = plt.subplots(nrows=n, ncols=1, figsize=figsize)\n\n # fig = plt.figure(figsize=figsize)\n # gs = GridSpec(n, 1)\n # ax = []\n # for row in range(n):\n # ax1 = plt.subplot(gs[row, 0])\n # ax.append(ax1)\n else:\n fig, ax = plt.subplots(nrows=n, ncols=1)\n return fig, ax\n\n\ndef plot_matrix_cmap_plain_ax(elements: List[CMapMatrixElement], xsize, ysize, title, xlabel, ylabel, xlabels, ylabels, scale, fig, ax, annotate, cmap):\n min_val, max_val = elements[0].val, elements[0].val\n intersection_matrix = np.zeros((xsize, ysize))\n print(np.shape(intersection_matrix))\n\n for e in elements:\n intersection_matrix[e.i][e.j] = e.val\n # print(e.i, e.j, e.val)\n if e.val < min_val:\n min_val = e.val\n if e.val > max_val:\n max_val = e.val\n\n # cmap = \"RdYlGn\"\n # cmap = \"Blues\"\n\n ax.tick_params(axis='both', which='major', labelsize=FSIZE_LABEL_XS)\n ax.tick_params(axis='both', which='minor', labelsize=FSIZE_LABEL_XS)\n\n im, cbar = heatmap(intersection_matrix, xlabels, ylabels, ax=ax,\n cmap=cmap, cbarlabel=None, scale=scale, aspect=1.3)\n\n # forceAspect(im, ax, 1.0)\n\n def millions(x, pos):\n 'The two args are the value and tick position'\n return '%d' % (x)\n # return str(x)\n\n if annotate:\n texts = annotate_heatmap(im, valfmt=millions)\n\n set_disp(title, xlabel, ylabel)\n\n\ndef show_fig(fig):\n fig.tight_layout()\n plt.show()\n\n return fig\n\n\ndef hsv2rgb(h, s, v):\n h = float(h)\n s = float(s)\n v = float(v)\n h60 = h / 60.0\n h60f = math.floor(h60)\n hi = int(h60f) % 6\n f = h60 - h60f\n p = v * (1 - s)\n q = v * (1 - f * s)\n t = v * (1 - (1 - f) * s)\n r, g, b = 0, 0, 0\n if hi == 0:\n r, g, b = v, t, p\n elif hi == 1:\n r, g, b = q, v, p\n elif hi == 2:\n r, g, b = p, v, t\n elif hi == 3:\n r, g, b = p, q, v\n elif hi == 4:\n r, g, b = t, p, v\n elif hi == 5:\n r, g, b = v, p, q\n \n return r, g, b\n\n\ndef rgb2hsv(r, g, b):\n r, g, b = r, g, b\n mx = max(r, g, b)\n mn = min(r, g, b)\n df = mx-mn\n if mx == mn:\n h = 0\n elif mx == r:\n h = (60 * ((g-b)/df) + 360) % 360\n elif mx == g:\n h = (60 * ((b-r)/df) + 120) % 360\n elif mx == b:\n h = (60 * ((r-g)/df) + 240) % 360\n if mx == 0:\n s = 0\n else:\n s = df/mx\n v = mx\n return h, s, v\n","sub_path":"results/plot/modules/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":21456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"11605180","text":"import requests\nimport whois\nimport argparse\nimport datetime\n\n\ndef console_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('path', help='Enter a path of file with urls')\n arg = parser.parse_args()\n return arg\n\n\ndef load_urls4check(path):\n with open(path, 'r', encoding='utf-8') as file:\n urls_list = [url.replace('\\n', '') for url in file]\n return urls_list\n\n\ndef is_server_respond_with_200(url):\n response = requests.get(url)\n if response.ok:\n return 'OK'\n else:\n return response.status_code\n\n\ndef check_expiration_date(url):\n whois_response = whois.whois(url)\n first_exp_index = 0\n exp_date = whois_response['expiration_date'][first_exp_index]\n tz = exp_date.tzinfo\n now = datetime.datetime.now(tz=tz)\n max_exp_time = datetime.timedelta(days=30)\n days_before_exp = exp_date - now\n if days_before_exp > max_exp_time:\n return 'more than 30'\n else:\n return days_before_exp.days\n\n\nif __name__ == '__main__':\n arguments = console_args()\n urls_file_path = arguments.path\n urls_list = load_urls4check(urls_file_path)\n for url in urls_list:\n url_status = is_server_respond_with_200(url)\n exp_status = check_expiration_date(url)\n print(url, 'status: {}'.format(url_status), \n 'days before expiration: {}'.format(exp_status))\n","sub_path":"check_sites_health.py","file_name":"check_sites_health.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"567074377","text":"\"\"\"Fondat module for Amazon Simple Email Service (SES).\"\"\"\n\nimport logging\n\nfrom collections.abc import Iterable\nfrom fondat.aws import Client, wrap_client_error\nfrom fondat.http import AsBody\nfrom fondat.resource import operation, resource, mutation\nfrom fondat.security import Policy\nfrom typing import Annotated, Union\n\n\n_logger = logging.getLogger(__name__)\n\n\ndef ses_resource(\n client: Client,\n policies: Iterable[Policy] = None,\n):\n \"\"\"\n Create SES resource.\n\n Parameters:\n • client: SES client object\n • policies: security policies to apply to all operations\n \"\"\"\n\n if client.service_name != \"ses\":\n raise TypeError(\"expecting SES client\")\n\n @resource\n class Identity:\n \"\"\"Verified identity.\"\"\"\n\n def __init__(self, identity: str):\n self.identity = identity\n\n @operation(policies=policies)\n async def delete(self):\n \"\"\"Delete the identity from verified identities.\"\"\"\n await client.delete_identity(Identity=self.identity)\n\n @resource\n class Identities:\n \"\"\"Identities for Amazon SES account in a specific region.\"\"\"\n\n @operation(policies=policies)\n async def post(self, identity):\n \"\"\"Add email address to list of identities for SES account.\"\"\"\n await client.verify_email_identity(EmailAddress=identity)\n\n def __getitem__(self, identity) -> Identity:\n return Identity(identity)\n\n @resource\n class SESResource:\n \"\"\"Simple Email Service (SES) resource.\"\"\"\n\n @mutation(policies=policies)\n async def send_raw_email(\n self,\n source: str,\n destinations: Union[str, Iterable[str]],\n data: Annotated[bytes, AsBody],\n ):\n \"\"\"\n Compose an email message and immediately queue it for sending.\n\n Parameters:\n • source: email address to send message message from\n • desinations: email address(es) to send message to\n • data: byte string containing headers and body of message to send\n \"\"\"\n\n if isinstance(destinations, str):\n destinations = [destinations]\n\n with wrap_client_error():\n await client.send_raw_email(\n Source=source, Destinations=destinations, RawMessage={\"Data\": data}\n )\n\n identities = Identities()\n\n return SESResource()\n","sub_path":"fondat/aws/ses.py","file_name":"ses.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"126590482","text":"# Given an undirected graph and a node, modify the graph into a directed graph\n# such that, any path leads to one particular node.\nfrom collections import deque, defaultdict\n\n\ndef transform(graph, start):\n result = {}\n queue = deque()\n queue.append((start, None))\n\n while len(queue):\n node, parent = queue.popleft()\n if node not in result:\n result[node] = [i for i in graph[node] if i != parent]\n\n for child in graph[node]:\n if child not in result:\n queue.append((child, node))\n\n transformed = defaultdict(list)\n for node, children in result.items():\n for child in children:\n transformed[child].append(node)\n\n return transformed\n\n\nif __name__ == '__main__':\n # 1\n # / | \\\n # 2 3 4 - 9 - 10\n # | | |\n # 5 7 8\n # |\n # 6\n graph = {\n 1: [2, 3, 4],\n 2: [1, 5],\n 3: [1, 7],\n 4: [1, 8, 9],\n 5: [2, 6],\n 6: [5],\n 7: [3],\n 8: [4],\n 9: [4, 10],\n 10: [9],\n }\n print(transform(graph, 1))\n","sub_path":"other/0003_undirected_to_directed.py","file_name":"0003_undirected_to_directed.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"433722205","text":"from django.conf.urls import patterns, include, url\nfrom django.conf import settings\n\n# Enable Admin\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns(\n '',\n #home\n url(r'^$', 'home.views.home_view'),\n #login/registration\n url(r'^loggedout/$', 'logout.views.logout_view'),\n url(r'^login/$', 'login.views.login_view'),\n url(r'^register/$', 'register.views.register_view'),\n #@login_required redirect point\n url(r'^accounts/login/$', 'login.views.login_view'),\n #user pages\n url(r'^hub/$', 'hub.views.hub_view'),\n url(r'^reoccurring/$', 'reoccurring.views.reoccurring_view'),\n url(r'^todo/$', 'todo.views.todo_view'),\n #Admin Urls\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n url(r'^admin/', include(admin.site.urls)),\n)\n\n# Serving static files in production\nif settings.DEBUG is False:\n urlpatterns += patterns('',\n url(r'^static/(?P.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT}),\n )","sub_path":"interest/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"577305223","text":"\"\"\"CREATING A NEW CLASS\"\"\"\nclass Employee:\n raise_amount=1.04\n def __init__(self, first, last, pay):\n self.first=first\n self.last=last\n self.pay=pay\n self.email=first+last+\"@gmail.com\"\n def fullname(self):\n return \"{} {}\".format(self.first,self.last)\n def apply_raise(self):\n self.pay=int(self.pay*self.raise_amount)\n \n\n \"\"\" Inheritance\"\"\"\nclass Developer(Employee):\n raise_amount=1.10\n def __init__(self, first, last, pay, prog_lan):\n Employee.__init__(self, first, last, pay) \n self.prog_lan=prog_lan\n \"\"\"As we have already defined first,last and pay in employee class, so instead of defining them again\n we can use super function with init to define them and it will automatically take the value from employee class\"\"\"\n\nclass Manager(Employee):\n raise_amount=1.15\n def __init__(self,first,last,pay,employees=None):\n Employee.__init__(self,first,last,pay)\n if employees is None:\n self.employees=[]\n else:\n self.employees=employees\n def add_emp(self, emp):\n if emp not in self.employees:\n self.employees.append(emp)\n def remove_emp(self, emp):\n if emp in self.employees:\n self.employees.remove(emp)\n def print_emp(self):\n for emp in self.employees:\n print (\"-->\",emp.fullname())\n \n\nemp1=Employee(\"Rishab\",\"Garg\",30000)\nemp2=Employee(\"Ayush\",\"Mittal\",60000)\n\ndev1=Developer(\"Mayham\",\"livid\",50000,\"Python\")\ndev2=Developer(\"Ayush\",\"Mittal\",60000,\"Ruby\")\n\nmang1=Manager(\"Ashish\",\"Ranot\",100000,[dev1,dev2])\n\nprint(mang1.fullname())\nprint(mang1.pay)\nmang1.apply_raise()\nprint(mang1.pay)\n#mang1.print_emp()\nmang1.add_emp(emp1)\nmang1.print_emp()\n\nprint(isinstance(mang1,Manager))\n#print(dev1.pay)\n#dev1.apply_raise()\n#print(dev1.pay)\n\n#print(emp1.pay)\n#emp1.apply_raise()\n#print(emp1.pay)\n#print (emp1.email)\n#print (emp1.fullname())\n#print (emp1.pay)\n\n#print(dev1.prog_lan)\n#print(emp2.raise_amount)\n#print(Employee.raise_amount)","sub_path":"PythonApplication2.py","file_name":"PythonApplication2.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"30061299","text":"class Node:\n def __init__(self):\n self.val = 0\n self.key = 0\n self.prev = None\n self.next = None\nclass LRUCache:\n\n def __init__(self, capacity: int):\n self.head = Node()\n self.tail = Node()\n self.head.next = self.tail\n self.tail.prev = self.head\n self.dict = {}\n self.capacity = capacity\n self.size = 0\n\n def get(self, key: int) -> int:\n if key in self.dict:\n node = self.dict[key]\n ret = node.val\n node.prev.next = node.next\n node.next.prev = node.prev\n node.next = self.head.next\n node.prev = self.head\n self.head.next = node\n node.next.prev = node\n return ret\n else:\n return -1\n\n def put(self, key: int, value: int) -> None:\n if key in self.dict:\n node = self.dict[key]\n node.prev.next = node.next\n node.next.prev = node.prev\n node.val = value\n else:\n node = Node()\n node.val = value\n node.key = key\n self.size += 1\n self.dict[key] = node\n node.next = self.head.next\n node.prev = self.head\n self.head.next = node\n node.next.prev = node\n \n if self.size > self.capacity:\n deleted = self.tail.prev\n self.tail.prev.prev.next = self.tail\n self.tail.prev = self.tail.prev.prev\n self.size -= 1\n del self.dict[deleted.key]\n \n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n\n\"\"\"\nThought process:\nleast recently used: use a queue/linkedlist, head = recently used\nget/put: use a dictionary\ncombine these two: use dictionary to store mapping\nuse a queue to store the timely relation\n\n> put 1 2 3 4 5\n[1, 2, 3, 4, 5]\n\n> get 2, 2 become most recently used\ndelete 2 (we have O(1) access from dict)\nand add 2 to the end (we store ref to head and tail)\n\nmeta-algo: combination problem: combine two algorithms\n\ntrick:\ndummy head and tail for linked list\n\"\"\"\n","sub_path":"Linked_lists/146_LRU_Cache.py","file_name":"146_LRU_Cache.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"417715521","text":"# 데이터를 학습, 평가 데이터로 분리하기\n\n# 데이터 준비하기\nimport numpy as np\nimport pandas as pd # 모듈 추가하기\ndf = pd.read_csv('bk_ebs_ai/3-3/temp_ice.csv', encoding='euc-kr')\n\n# 학습(train) 데이터를 입력 변수와 출력 변수로 나누기\ndata = np.array(df)\nX = data[:, 1] # 평균기온 열의 데이터를 출력 변수로 지정\nY = data[:, -1] # 아이스크림/빙수 열의 데이터를 출력 변수로 지정\n\n# 비용을 계산하고 업데이트하기 -----------------------------------------\n\n# 입력 변수와 출력 변수 각각의 평균(mean) 구하기\nmean_x = np.mean(X)\nmean_y = np.mean(Y)\n\n# X변수의 개수 구하기\nn = len(X)\n\n# 최소제곱법을 이용하여 beta0과 beta1 구하기\ntemp1 = 0\ntemp2 = 0\nfor i in range(n):\n temp1 += (X[i] - mean_x) * (Y[i] - mean_y)\n temp2 += (X[i] - mean_x) ** 2\nbeta1 = temp1 / temp2\nbeta0 = mean_y - (beta1 * mean_x)\n\n# 계산 결과 출력하기\nprint(\"기울기(beta1): {0}, 절편(beta0): {1}\".format(beta1, beta0))\n","sub_path":"bk_ebs_ai_math/3-3/3-3-11.py","file_name":"3-3-11.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"432254115","text":"\"\"\"\nDOCSTRING\n\"\"\"\nimport autoencoder.utils\nimport numpy\nimport tensorflow\n\nclass VariationalAutoencoder:\n \"\"\"\n DOCSTRING\n \"\"\"\n def __init__(self, n_input, n_hidden, optimizer=tensorflow.train.AdamOptimizer()):\n self.n_input = n_input\n self.n_hidden = n_hidden\n network_weights = self._initialize_weights()\n self.weights = network_weights\n # model\n self.x = tensorflow.placeholder(tensorflow.float32, [None, self.n_input])\n self.z_mean = tensorflow.add(tensorflow.matmul(\n self.x, self.weights['w1']), self.weights['b1'])\n self.z_log_sigma_sq = tensorflow.add(tensorflow.matmul(\n self.x, self.weights['log_sigma_w1']), self.weights['log_sigma_b1'])\n # sample from gaussian distribution\n eps = tensorflow.random_normal(tensorflow.pack(\n [tensorflow.shape(self.x)[0], self.n_hidden]), 0, 1, dtype = tensorflow.float32)\n self.z = tensorflow.add(self.z_mean, tensorflow.mul(\n tensorflow.sqrt(tensorflow.exp(self.z_log_sigma_sq)), eps))\n self.reconstruction = tensorflow.add(tensorflow.matmul(\n self.z, self.weights['w2']), self.weights['b2'])\n # cost\n reconstr_loss = 0.5 * tensorflow.reduce_sum(tensorflow.pow(\n tensorflow.sub(self.reconstruction, self.x), 2.0))\n latent_loss = -0.5 * tensorflow.reduce_sum(\n 1 + self.z_log_sigma_sq - tensorflow.square(self.z_mean) \\\n - tensorflow.exp(self.z_log_sigma_sq), 1)\n self.cost = tensorflow.reduce_mean(reconstr_loss + latent_loss)\n self.optimizer = optimizer.minimize(self.cost)\n init = tensorflow.initialize_all_variables()\n self.sess = tensorflow.Session()\n self.sess.run(init)\n\n def _initialize_weights(self):\n \"\"\"\n DOCSTRING\n \"\"\"\n all_weights = dict()\n all_weights['w1'] = tensorflow.Variable(\n autoencoder.utils.xavier_init(self.n_input, self.n_hidden))\n all_weights['log_sigma_w1'] = tensorflow.Variable(\n autoencoder.utils.xavier_init(self.n_input, self.n_hidden))\n all_weights['b1'] = tensorflow.Variable(\n tensorflow.zeros([self.n_hidden], dtype=tensorflow.float32))\n all_weights['log_sigma_b1'] = tensorflow.Variable(\n tensorflow.zeros([self.n_hidden], dtype=tensorflow.float32))\n all_weights['w2'] = tensorflow.Variable(tensorflow.zeros(\n [self.n_hidden, self.n_input], dtype=tensorflow.float32))\n all_weights['b2'] = tensorflow.Variable(tensorflow.zeros(\n [self.n_input], dtype=tensorflow.float32))\n return all_weights\n\n def calc_total_cost(self, X):\n \"\"\"\n DOCSTRING\n \"\"\"\n return self.sess.run(self.cost, feed_dict={self.x: X})\n\n def generate(self, hidden=None):\n \"\"\"\n DOCSTRING\n \"\"\"\n if hidden is None:\n hidden = numpy.random.normal(size=self.weights[\"b1\"])\n return self.sess.run(self.reconstruction, feed_dict={self.z_mean: hidden})\n\n def get_biases(self):\n \"\"\"\n DOCSTRING\n \"\"\"\n return self.sess.run(self.weights['b1'])\n\n def get_weights(self):\n \"\"\"\n DOCSTRING\n \"\"\"\n return self.sess.run(self.weights['w1'])\n\n def partial_fit(self, X):\n \"\"\"\n DOCSTRING\n \"\"\"\n cost, opt = self.sess.run((self.cost, self.optimizer), feed_dict={self.x: X})\n return cost\n\n def reconstruct(self, X):\n \"\"\"\n DOCSTRING\n \"\"\"\n return self.sess.run(self.reconstruction, feed_dict={self.x: X})\n\n def transform(self, X):\n \"\"\"\n DOCSTRING\n \"\"\"\n return self.sess.run(self.z_mean, feed_dict={self.x: X})\n","sub_path":"ai_reader_demo/autoencoder/autoencoder_models/variational_autoencoder.py","file_name":"variational_autoencoder.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"263792205","text":"from views import viewmain\nfrom backup import backup\n\n## Controller of the main window.\nclass ControllerMain(object):\n \n ## Constructor of the class.\n # @param self The object pointer.\n # @param root_window Pointer to the root window of the graphical interface.\n def __init__(self, root_window):\n self.view_main = viewmain.ViewMain(root_window)\n self.model_backup = backup.Backup()\n self.button_backup = self.view_main.get_directories().get_button_backup()\n self.button_backup.configure(command=self.event_start_backup)\n \n ## Method for the start backup event.\n # Provides the actions taken if the event start backup is started. This includes performing the\n # backup and changing the graphical user interface.\n # @param self The object pointer.\n def event_start_backup(self):\n self.model_backup.set_source(self.view_main.get_directories().get_source())\n self.model_backup.set_target(self.view_main.get_directories().get_target())\n if self.model_backup.run() == True:\n self.button_backup.configure(text=\"Backup successful!\\n-QUIT-\",\n bg=\"green\",\n activebackground=\"green\",\n command=self.view_main.quit)\n else:\n self.button_backup.configure(bg=\"red\",\n activebackground=\"red\")","sub_path":"src/controller/controllermain.py","file_name":"controllermain.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"531097532","text":"# 1230.py 암호문3\nimport sys\nsys.stdin = open(\"1230input.txt\", \"r\")\n\n\ntc = 10\nfor test_count in range(1, tc + 1):\n N_ = int(input()) # 원본 암호문의 길이 100 ≤ N ≤ 200\n string = list(map(int, input().split())) # 원본 암호문\n M_ = int(input()) # 명령어 개수 10 ≤ N ≤ 20\n commands = list(input().split()) # 명령어들\n # pprint.pprint(string)\n # print(commands)\n index = 0\n\n while index < len(commands):\n \n if commands[index] == 'A':\n count = int(commands[index + 1])\n index = index + 2 + count\n continue\n\n if commands[index] == 'I':\n location, count = int(commands[index + 1]), int(commands[index + 2])\n index += 3\n\n for i in range(N_ - count -1, location - 1, -1 ):\n string[i + count] = string[i]\n\n temp = index \n if location + count >= N_:\n for i in range(location, N_):\n string[i] = int(commands[index])\n index += 1\n index = temp + count\n else:\n for i in range(location, location + count):\n string[i] = int(commands[index])\n index += 1\n\n elif commands[index] == 'D':\n location, count = int(commands[index + 1]), int(commands[index + 2])\n\n for i in range(location, N_ - count):\n string[i] = string[i + count]\n index += 3\n\n print('#{}'.format(test_count), end=\" \")\n for i in range(10):\n print(string[i], end=\" \") \n print() ","sub_path":"SWEA/difficulty3/1230.py","file_name":"1230.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"624640591","text":"\nimport pandas as pd\n\nPATH = \"movie_recommendations.xlsx\"\n\ndf = pd.read_excel(PATH)\n\ndf['Genre'] = df['Genre'].str.lower()\n\n# produce clean unique index\ndf.sort_values(by=['Name', 'Genre', 'Reviewer'], inplace=True)\nclean = df.drop_duplicates().dropna()\n\nlong = clean.set_index(['Name', 'Genre', 'Reviewer'])\n\n# mean rating per genre\nprint(long.unstack(1).mean())\n","sub_path":"longwide.py","file_name":"longwide.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"558562210","text":"from pytorch_lightning import Callback\nfrom pytorch_lightning.callbacks.progress import ProgressBar\n\nimport sys\nimport importlib\nif importlib.util.find_spec('ipywidgets') is not None:\n from tqdm.auto import tqdm\nelse:\n from tqdm import tqdm\n\nclass MetricsCallback(Callback):\n \"\"\"PyTorch Lightning metric callback.\"\"\"\n def __init__(self):\n super().__init__()\n self.metrics = []\n\n def on_validation_end(self, trainer, pl_module):\n self.metrics.append(trainer.callback_metrics)\n\nclass MyProgressBar(ProgressBar):\n def __init__(self, *args, **kwargs):\n super().__init__(*args,**kwargs)\n \n def init_validation_tqdm(self) -> tqdm:\n \"\"\" Override this to customize the tqdm bar for validation. \"\"\"\n bar = tqdm(\n desc='Validating',\n position=(2 * self.process_position + 1),\n disable=True,\n leave=False,\n dynamic_ncols=True,\n file=sys.stdout\n )\n return bar","sub_path":"src/utils/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"631389736","text":"##############################################################################\n#\n# Copyright (C) Zenoss, Inc. 2014, all rights reserved.\n#\n# This content is made available according to terms specified in\n# License.zenoss under the directory where your Zenoss product is installed.\n#\n##############################################################################\n\nimport random\nimport string\n\nfrom Products.ZenModel.IpInterface import IpInterface\nfrom ZenPacks.zenoss.Layer2.utils import asmac\n\ndiamond = '''\n a b\n a c\n b d\n c d\n'''\n\nY_to_existing = '''\n 10.87.100.1 fake1\n fake1 fake2\n fake1 fake3\n'''\n\ndef binary_tree_topology(deepness=5, root='bin', edges=[]):\n if deepness <= 0:\n return\n\n l = root + '0'\n edges.append((root, l))\n binary_tree_topology(deepness - 1, l, edges)\n\n r = root + '1'\n edges.append((root, r))\n binary_tree_topology(deepness - 1, r, edges)\n\n return edges\n \n\ndef main():\n # create_topology(diamond)\n # create_topology(Y_to_existing)\n create_topology(binary_tree_topology(deepness=5, root='test'))\n commit()\n\ndef create_topology(connections):\n ''' Connections - iterable of pairs of device id's '''\n if isinstance(connections, basestring):\n connections = parse_topology(connections)\n\n for d1, d2 in connections:\n connect(get_device(d1), get_device(d2))\n\n dmd.Devices.reIndex()\n\ndef parse_topology(text):\n return (x.strip().split() for x in text.splitlines() if x.strip())\n\ndef get_device(id):\n ''' Find device if exists, or return new '''\n d = dmd.Devices.findDevice(id)\n if d:\n return d\n return create_router(id)\n\ndef create_router(id):\n return dmd.Devices.Network.Router.Cisco.createInstance(id)\n\ndef connect(d1, d2):\n ''' Connect two devices by l2 link '''\n mac = random_mac()\n\n add_interface(d1, clientmacs=[mac])\n add_interface(d2, macaddress=mac)\n\ndef add_interface(dev, macaddress='', clientmacs=[]):\n ''' Add new interface to device '''\n eth_id = random_id()\n eth = IpInterface(eth_id, eth_id)\n eth.macaddress = macaddress\n eth.clientmacs = clientmacs\n dev.os.interfaces._setObject('unused_id_param', eth)\n\ndef random_id(length=6):\n return ''.join(random.choice(string.lowercase) for i in range(length))\n\ndef random_mac():\n return asmac(random_id())\n\nif __name__ == '__main__':\n main()\n","sub_path":"ZenPacks/zenoss/Layer2/tests/create_fake_devices.py","file_name":"create_fake_devices.py","file_ext":"py","file_size_in_byte":2374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"209828866","text":"'''\n부분집합 합 문제 구현하기\n\n10개의 정수를 입력받아 부분집합의 합이 0이 되는 것을 존재하는지를 계산하는 함수를 작성해보자\n'''\n# arr = [3, 6, 7, 1, 5, 4]\n# n = len(arr)\n# for i in range(i< 0:\n print('yes', temp)","sub_path":"class/tips/subset.py","file_name":"subset.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"226598683","text":"from django.urls import reverse\n\nfrom tests.test_profile.test_group.test_group_base import TestGroupBase\n\n\nclass TestGroupProcessing(TestGroupBase):\n\n def setUp(self):\n super(TestGroupProcessing, self).setUp()\n\n def test_update_users_in_group(self):\n args_group = {\n 'group_id': self.my_group.id\n }\n url = reverse('profiles:user_in_group_update', kwargs=args_group)\n data_list = [\n {'users': [self.my_user.id, self.my_user2.id, self.my_user3.id, self.my_user4.id]},\n {'users': [self.my_user.id]},\n {'users': [self.my_user2.id, self.my_user3.id]},\n ]\n for data in data_list:\n self.client.post(url, data=data)\n self.assertEquals(list(set(data.get('users', []))),\n list(set([user.id for user in self.my_group.user_set.all()])))\n","sub_path":"tests/test_profile/test_group/test_group_model.py","file_name":"test_group_model.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"572409420","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('back_office', '0003_auto_20151014_1211'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='AssetHolder',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=75, verbose_name='name')),\n ('created', models.DateTimeField(auto_now=True, verbose_name='date created')),\n ('modified', models.DateTimeField(auto_now_add=True, verbose_name='last modified')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.AddField(\n model_name='backofficeasset',\n name='property_of',\n field=models.ForeignKey(blank=True, to='back_office.AssetHolder', null=True, on_delete=django.db.models.deletion.PROTECT),\n ),\n ]\n","sub_path":"src/ralph/back_office/migrations/0004_auto_20151023_1308.py","file_name":"0004_auto_20151023_1308.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"129786987","text":"#1 #prediction output, 5...I was right.\ndef number_of_food_groups():\n return 5\nprint(number_of_food_groups())\n\n\n#2 #prediction output, 19... Actual output: NameError: name 'number_of_days_in_a_week_silicon_or_triangle_sides' is not defined\ndef number_of_military_branches():\n return 5\nprint(number_of_days_in_a_week_silicon_or_triangle_sides() + number_of_military_branches())\n\n\n#3 #prediction output, 5...I was right.\ndef number_of_books_on_hold():\n return 5\n return 10\nprint(number_of_books_on_hold())\n\n\n#4 #prediction output, 5...I was right.\ndef number_of_fingers():\n return 5\n print(10)\nprint(number_of_fingers())\n\n\n#5 #prediction output, 5...Actual output was 5, None.\ndef number_of_great_lakes():\n print(5)\nx = number_of_great_lakes()\nprint(x)\n\n\n#6 prediction output, 8...Actual output was TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'\ndef add(b,c):\n print(b+c)\nprint(add(1,2) + add(2,3))\n\n\n#7 prediction output, 25...I was right.\ndef concatenate(b,c):\n return str(b)+str(c)\nprint(concatenate(2,5))\n\n\n#8 prediction output, 10...Actual output was 100, 10\ndef number_of_oceans_or_fingers_or_continents():\n b = 100\n print(b)\n if b < 10:\n return 5\n else:\n return 10\n return 7\nprint(number_of_oceans_or_fingers_or_continents())\n\n\n#9 prediction output, 7, 14, 21...I was right.\ndef number_of_days_in_a_week_silicon_or_triangle_sides(b,c):\n if b[0-9]+)/$', views.ProshowsGenre1.as_view()), #info on one genre\n url(r'^proshows/event/(?P[0-9]+)/$', views.ProshowsEvent1.as_view()),#info on one event\n url(r'^proshows/events/(?P[0-9]+)/$', views.ProshowsEventList.as_view()),#all events under a genre\n]\n\nurlpatterns = format_suffix_patterns(urlpatterns)","sub_path":"proshows/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"203854743","text":"import pandas as pd\nfrom pandas import Series, DataFrame\nimport numpy as np\n\nfrom bs4 import BeautifulSoup\nimport re\n\nfrom datetime import datetime\n\nimport R50_general.advanced_helper_funcs as ahf\nimport R50_general.general_constants\nimport R50_general.general_helper_funcs as gcf\nfrom R50_general.general_helper_funcs import logprint\nimport R50_general.dfm_to_table_common as df2db\n\n\"\"\"\nTHIS PROGRAM IS OBSELETE DUE TO WEB LINK DOESN'T WORK ANY MORE!!!\nthis program parse the stock basic info page from qq :\nhttp://stock.finance.qq.com/corp1/profile.php?zqdm=%(stock_id)s\n\n\nit extract below datas \n-change hist, name change log\n-stock category info (obsolete,data source quality not good!!)\n\"\"\"\nglobal_module_name = gcf.get_cur_file_name_by_module_name(__name__)\n\nmode = 'update_log'\n\ndef fetch2DB(stockid:str = ''):\n \"\"\"\n fetch stock name history and update into DB\n :param mode: if mode = 'update_log\" then delete all entries in YY_stock_changes_qq,otherwise only update name changes\n :return:\n \"\"\"\n # init step\n # step2.1: get current stock list\n dfm_stocks = df2db.get_cn_stocklist(stockid)\n\n #get chars for name change hist\n dfm_db_chars = df2db.get_chars('QQ', ['NAME_HIST'])\n dict_misc_pars = {}\n dict_misc_pars['char_origin'] = 'QQ'\n dict_misc_pars['char_freq'] = \"D\"\n dict_misc_pars['allow_multiple'] ='N'\n dict_misc_pars['created_by'] = dict_misc_pars['update_by'] =global_module_name\n dict_misc_pars['char_usage'] = 'NAME_HIST'\n\n #get chars for stock category\n dfm_db_chars_catg = df2db.get_chars('QQ', ['CATG'])\n dict_misc_pars_catg = {}\n dict_misc_pars_catg['char_origin'] = 'QQ'\n dict_misc_pars_catg['char_freq'] = \"D\"\n dict_misc_pars_catg['allow_multiple'] ='Y'\n dict_misc_pars_catg['created_by'] = dict_misc_pars_catg['update_by'] =global_module_name\n dict_misc_pars_catg['char_usage'] = 'CATG'\n\n # check whether db table is created.\n table_name = R50_general.general_constants.dbtables['name_hist_qq']\n df2db.create_table_by_template(table_name,table_type='stock_date')\n\n # table_name_concept = gcf.dbtables['category_qq']\n # df2db.create_table_by_template(table_name_concept,table_type='stock_date_multi_value')\n\n # get db category list\n # dfm_db_catg = df2db.get_stock_catg('QQ')\n # set_db_catg = df2db.dfm_value_to_set(dfm_db_catg,['Catg_Name'])\n # print(set_db_catg)\n\n ls_changes =[]\n # step2:loop at stock list and fetch and save to DB\n for item in dfm_stocks['Stock_ID']: # get column Stock_ID from dataframe\n # Step1: parsing webpage and produce stock list\n logprint('Processing stock:', item)\n url_stock_profile = R50_general.general_constants.weblinks['stock_change_record_qq'] % {'stock_id':item}\n soup_profile = gcf.get_webpage(url_stock_profile)\n if soup_profile:\n # func1: fetch name change log\n dfm_item_changes = soup_parse_change_hist(soup_profile)\n if len(dfm_item_changes) > 0:\n gcf.dfm_col_type_conversion(dfm_item_changes,columns={'变动日期':'datetime','公布日期':'datetime'})\n dfm_item_name_changes = dfm_item_changes[dfm_item_changes['变动项目']=='证券简称']\n # print(dfm_item_name_changes)\n dfm_item_name_changes=dfm_item_name_changes.set_index('变动日期')\n dfm_item_name_changes = dfm_item_name_changes.rename(columns={'公布前内容':'原证券简称',\n '公布后内容':'证券简称',\n '公布日期':'简称变动公布日期'})\n del(dfm_item_name_changes['变动项目'])\n dict_cols_cur = {'证券简称': 'nvarchar(50)',\n '简称变动公布日期':'datetime',\n '原证券简称':'nvarchar(50)'}\n if len(dfm_item_name_changes) > 0:\n df2db.add_new_chars_and_cols(dict_cols_cur,list(dfm_db_chars['Char_ID']),table_name,dict_misc_pars)\n # step4: insert transaction data into transaction table\n market_id = 'SH' if item.startswith('6') else 'SZ'\n df2db.load_dfm_to_db_single_value_by_mkt_stk_w_hist(market_id, item, dfm_item_name_changes, table_name,\n dict_misc_pars,\n processing_mode='w_update')\n dfm_item_changes['Stock_ID'] = item\n dfm_item_changes['Market_ID'] = 'SH' if item.startswith('6') else 'SZ'\n ls_changes.append(dfm_item_changes)\n # print (dfm_item_name_changes )\n # func2: fetch stock category info\n # dfm_item_catgs = soup_parse_catg(soup_profile)\n # if type(dfm_item_catgs) != type(None):\n # dict_cols_cur_catg = {'所属板块': 'nvarchar(50)'}\n # df2db.add_new_chars_and_cols(dict_cols_cur_catg,list(dfm_db_chars_catg['Char_ID']),table_name_concept,\n # dict_misc_pars_catg)\n # market_id = 'SH' if item.startswith('6') else 'SZ'\n # for id in range(len(dfm_item_catgs)):\n # if not (dfm_item_catgs.iloc[id]['所属板块'],) in set_db_catg:\n # logprint(\"Stock %s Concept %s doesn't exist in table ZFCG_Category\" %(item,dfm_item_catgs.iloc[id]['所属板块']))\n # df2db.load_dfm_to_db_multi_value_by_mkt_stk_cur(market_id,item,dfm_item_catgs,table_name_concept,\n # dict_misc_pars_catg,process_mode = 'w_check')\n # else:\n # logprint(\"Stock %s can't find category info\" %item)\n\n\n if ls_changes and mode == 'update_log':\n dfm_changes = pd.concat(ls_changes)\n df2db.load_snapshot_dfm_to_db(dfm_changes,'YY_stock_changes_qq','del&recreate')\n\ndef soup_parse_catg(soup):\n # print(soup)\n # 使用正则表达式找到\"所属板块\"之后的第一个的td节点.请获取这个td节点里面所有标记为a的tag对应的string\n # obselete:注意[^/]*代表和所属板块之间不能有/这个符号.这样可以防止比配到如下的结果\n # ..........所属板块...\n str_catg = re.findall('所属板块.*?(',str(soup),re.I|re.S)\n ls_catgs = []\n if str_catg:\n soup_catg = BeautifulSoup(str_catg[0],'lxml')\n# print(str_catg)\n ls_soup_catg = soup_catg.find_all('a')\n for catg in ls_soup_catg:\n dt_catg = {}\n dt_catg['所属板块'] = catg.string.strip()\n ls_catgs.append(dt_catg)\n return DataFrame(ls_catgs)\n\n\n\ndef soup_parse_change_hist(soup:BeautifulSoup):\n body_content = soup.find_all('table',class_= 'list')\n stock_changes = body_content[1].find_all('tr')\n # print(stock_profile[0].td)\n # print(stock_profile[1].contents)\n stock_changes = stock_changes[2:] if len(stock_changes) > 2 else []\n ls_changes =[]\n for tr in stock_changes:\n change_record = {}\n ls_change_item = list(tr.stripped_strings)\n if len(ls_change_item) == 5:\n change_record['变动项目'] = ls_change_item[0].strip()\n change_record['变动日期'] = ls_change_item[1].strip()\n change_record['公布日期'] = ls_change_item[2].strip()\n change_record['公布前内容'] = ls_change_item[3].strip()\n change_record['公布后内容'] = ls_change_item[4].strip()\n ls_changes.append(change_record)\n\n return DataFrame(ls_changes)\n\ndef auto_reprocess():\n ahf.auto_reprocess_dueto_ipblock(identifier=global_module_name,\n func_to_call=fetch2DB,\n wait_seconds=300)\n\nif __name__ == '__main__':\n # fetch2DB()\n auto_reprocess()","sub_path":"R10_sensor/fetch_stock_change_record_from_qq.py","file_name":"fetch_stock_change_record_from_qq.py","file_ext":"py","file_size_in_byte":8102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"171560561","text":"import sys\nimport os\nimport pandas as pd\nimport numpy as np\nimport warnings\nwarnings.simplefilter(\"ignore\")\nimport time\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\npath = 'C://Users//raque//Documents//GitHub//ParKCa'\n\nsys.path.append(path+'//src')\nsys.path.append(path+'//extra')\nimport datapreprocessing as dp\n#import CEVAE as cevae\nimport train as models\nimport eval as eval\nimport numpy.random as npr\nfrom os import listdir\nfrom os.path import isfile, join\nos.chdir(path)\nimport random\nrandseed = 123\nprint(\"random seed: \", randseed)\nrandom.seed(randseed)\nnp.random.seed(randseed)\n\npd.set_option('display.max_columns', 500)\n\nfrom scipy.stats import ttest_ind,ttest_rel\n\nSIMULATION = False\nEVALUATION_A = True\nEVALUATION_S = True\n#cuda test torch.cuda.FloatTensor(2)\n\n\n\nif EVALUATION_A:\n '''\n Real-world application\n level 0 data: gene expression of patients with cancer\n level 0 outcome: metastasis\n '''\n print(\"\\n\\n\\n STARTING EXPERIMENTS ON APPLICATION\")\n\n #BART is tested using an R code\n models.learners(APPLICATIONBOOL=True,DABOOL=True, BARTBOOL=False, CEVAEBOOL=False,path = path)\n\n features_bart = pd.read_csv(\"results\\\\coef_bart.txt\",sep=';')\n features_da15 = pd.read_pickle(\"results\\\\coef_15.txt\")\n features_da15c = pd.read_pickle(\"results\\\\coefcont_15.txt\")\n\n level1data = features_bart.merge(features_da15, left_on='gene', right_on='genes').drop(['genes'],1)\n level1datac = features_bart.merge(features_da15c, left_on='gene', right_on='genes').drop(['genes'],1)\n\n cgc_list = dp.cgc('extra\\\\cancer_gene_census.csv')\n level1data = cgc_list.merge(level1data, left_on='genes',right_on='gene',how='right').drop(['genes'],1)\n level1datac = cgc_list.merge(level1datac, left_on='genes',right_on='gene',how='right').drop(['genes'],1)\n\n level1data['y_out'].fillna(0,inplace=True)\n level1datac['y_out'].fillna(0,inplace=True)\n\n level1data.set_index('gene', inplace = True, drop = True)\n level1datac.set_index('gene', inplace = True, drop = True)\n\n data1 = dp.data_norm(level1data)\n data1c = dp.data_norm(level1datac)\n\n #DIVERSITY\n qav, q_ = eval.diversity(['bart_all', 'bart_FEMALE', 'bart_MALE' ],\n ['dappcalr_15_LGG','dappcalr_15_SKCM','dappcalr_15_all','dappcalr_15_FEMALE','dappcalr_15_MALE'],\n data1)\n print('DIVERSITY: ', qav)\n\n #Metalearners\n experiments1 = models.meta_learner(data1, ['adapter','upu','lr','rf','nn','random'],1)\n experiments1c = models.meta_learner(data1c, ['adapter','upu','lr','rf','nn','random'],1)\n\n experiments0 = eval.first_level_asmeta(['bart_all', 'bart_FEMALE', 'bart_MALE' ],\n ['dappcalr_15_LGG','dappcalr_15_SKCM','dappcalr_15_all','dappcalr_15_FEMALE','dappcalr_15_MALE'],\n data1)\n\n\n experiments1.to_csv('results\\\\eval_metalevel1.txt', sep=';')\n experiments1c.to_csv('results\\\\eval_metalevel1c.txt', sep=';')\n experiments0.to_csv('results\\\\eval_metalevel0.txt', sep=';')\n print(\"DONE WITH EXPERIMENTS ON APPLICATION\")\n\n\n\n\nif EVALUATION_S:\n '''\n Simulation\n level 0 data: Binary treatments\n level 0 outcome: Binary\n '''\n print(\"\\n\\n\\n STARTING EXPERIMENTS ON SIMULATION\")\n\n #SAVING 10 datasets\n n_units = 5000\n n_causes = 10000# 10% var\n sim = 10\n\n #CREATE THE DATASET\n dp.generate_samples(sim,n_units, n_causes)\n\n #DA\n pathtc = 'data_s\\\\snp_simulated1_truecauses.txt'\n pathy01 = 'data_s\\\\snp_simulated1_y01.txt'\n tc = pd.read_pickle(pathtc)\n y01 = pd.read_pickle(pathy01)\n\n #CEVAE IS RUN IN A NOTEBOOK\n print(\"DONE WITH EXPERIMENTS ON SIMULATION\")\n\n #learners and meta-learners\n dp.sim_level1data([0,1,2,3,4,5,6,7,8,9],tc,y01,'sim_roc_simulations')\n eval.roc_plot('results//sim_roc_simulations.txt')\n eval.simulation_eval(10)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"276401747","text":"from flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\nfrom models.item import ItemModel\n\n#Resources are external representaiton\n#where client or api use.\n\nclass Item(Resource):\n #Avoid name changes only price\n parser = reqparse.RequestParser()\n #look at JSON payload or form payload to a specific field, ex. \"price\"\n parser.add_argument(\n 'price',\n type = float,\n required=True,\n help= \"This field cannot be left blank\"\n )\n parser.add_argument(\n 'store_id',\n type = int,\n required=True,\n help= \"Every item needs a store_id\"\n )\n\n\n @jwt_required()\n def get(self, name):\n # for item in items:\n # if item['name'] == name:\n # return item\n\n # filter() takes two arguments, a filtering function and the list of targets.\n # next() gives us the first item by the filter() function\n # item = next(filter(lambda x: x['name'] == name, items), None)\n # return {'item': item}, 200 if item else 404\n item = ItemModel.find_by_name(name)\n if item:\n return item.json()\n else:\n return {'message': 'Item not found'}, 404\n\n\n\n def post(self, name):\n # if next(filter(lambda x: x['name'] == name, items), None) is not None:\n # return {'message': \"An item with name '{}' already exists\".format(name)}, 400\n #prevent error if Content-Type header is not set.\n #data = request.get_json(force=True)\n #prevent error, it returns None\n #data = request.get_json(silent=True)\n #data = request.get_json()\n\n if ItemModel.find_by_name(name):\n return {'message': \"An item with name '{}' already exists\".format(name)}, 400\n\n data = Item.parser.parse_args()\n\n #item = ItemModel(name, data['price'], data['store_id'])\n item = ItemModel(name, **data)\n\n #items.append(item) # This line was for item[] memory database\n try:\n item.save_to_db()\n except:\n return {\"message\": \"An error occured inserting the item.\"}, 500\n\n return item.json(), 201\n\n\n\n def delete(self, name):\n item = ItemModel.find_by_name(name)\n if item:\n item.delete_from_db()\n\n return {'message': 'Item deleted'}\n\n def put(self, name):\n data = Item.parser.parse_args()\n #print(data['something_elase'])\n #data = request.get_json()\n\n item = ItemModel.find_by_name(name)\n\n if item is None:\n #item = ItemModel(name, data['price'], data['store_id'])\n item = ItemModel(name, **data)\n else:\n item.price = data['price']\n\n item.save_to_db()\n return item.json()\n\n\nclass ItemList(Resource):\n def get(self):\n return {'items': [item.json() for item in ItemModel.query.all() ]}\n #return {'items': list(map(lambda x: x.json(), ItemModel.query.all()))}\n","sub_path":"resources/item.py","file_name":"item.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"618974781","text":"import logging\nfrom telegram import InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters\nimport requests\nfrom model import Model\nimport time\nfrom fuckinIO import FuckinIO\nfrom CurrentFlow import CurrentFlow\n\nmodel = Model()\nios = FuckinIO()\n\n\n\ndef start(bot, update):\n keyboard = [\n [InlineKeyboardButton(\"Rate\", callback_data='0')],\n [InlineKeyboardButton(\"Send Someone Photo\", callback_data='1')],\n [InlineKeyboardButton(\"About\", callback_data='8')]\n ]\n\n reply_markup = InlineKeyboardMarkup(keyboard)\n query = update.callback_query\n bot.send_message(chat_id=update.message.chat_id, text=\"What can i do for you dear iust student?\",\n reply_markup=reply_markup)\n\n\n\nmsgs = []\ndef button(bot, update):\n query = update.callback_query\n if query.data == '0' or query.data == '4' or query.data == '5' or query.data == '6':\n keyboard = [\n [InlineKeyboardButton(\"Up\", callback_data='4')],\n [InlineKeyboardButton(\"Same\", callback_data='5')],\n [InlineKeyboardButton(\"Down\", callback_data='6')],\n [InlineKeyboardButton(\"Main\", callback_data='2')]\n ]\n\n our_two_random = model.fetchRandom()\n current_flow = CurrentFlow(our_two_random[0]['photo_hash'], our_two_random[1]['photo_hash'],\n our_two_random[0]['score'], our_two_random[1]['score'])\n\n msg = bot.send_message(chat_id=query.message.chat_id, text=\"Please Wait...\")\n msgs.append(msg.message_id)\n imagebytes = our_two_random[0]['photo']\n # bot.send_photo(chat_id=update.message.chat_id, photo=ios.bytes_to_file(imagebytes))\n msg = bot.send_message(chat_id=query.message.chat_id, text=our_two_random[0]['photo_hash'])\n msgs.append(msg.message_id)\n imagebytes = our_two_random[1]['photo']\n # bot.send_photo(chat_id=update.message.chat_id, photo=ios.bytes_to_file(imagebytes))\n msg = bot.send_message(chat_id=query.message.chat_id, text=our_two_random[1]['photo_hash'])\n msgs.append(msg.message_id)\n\n\n\n bot.delete_message(query.message.chat_id, query.message.message_id)\n if len(msgs) > 3:\n for msg in msgs[0:3]:\n msgs.remove(msg)\n bot.delete_message(query.message.chat_id, msg)\n reply_markup = InlineKeyboardMarkup(keyboard)\n bot.send_message(chat_id=query.message.chat_id, text=\"Up or Down !?\",\n reply_markup=reply_markup)\n\n if query.data == '4':\n current_flow.calcscore(1)\n if query.data == '5':\n current_flow.calcscore(0.5)\n if query.data == '6':\n current_flow.calcscore(0)\n\n\n if query.data == '1':\n keyboard = [\n [InlineKeyboardButton(\"Candel\", callback_data='2')]\n ]\n bot.edit_message_text(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\"Please send me a photo of yourself or Someone else.\"\n )\n reply_markup = InlineKeyboardMarkup(keyboard)\n bot.edit_message_reply_markup(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n reply_markup=reply_markup\n )\n\n if query.data == '2':\n keyboard = [\n [InlineKeyboardButton(\"Rate\", callback_data='0')],\n [InlineKeyboardButton(\"Send Someone Photo\", callback_data='1')],\n [InlineKeyboardButton(\"About\", callback_data='2')]\n ]\n bot.edit_message_text(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\"What can i do for you dear IUST student?\"\n )\n reply_markup = InlineKeyboardMarkup(keyboard)\n\n bot.edit_message_reply_markup(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n reply_markup=reply_markup\n )\n\n if query.data == '8':\n keyboard = [\n [InlineKeyboardButton(\"Rate\", callback_data='0')],\n [InlineKeyboardButton(\"Send Someone Photo\", callback_data='1')],\n [InlineKeyboardButton(\"About\", callback_data='2')]\n ]\n bot.edit_message_text(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n text=\"Hot or Not is a rating site that allows users to rate the attractiveness of photos submitted voluntarily by others.\"\n )\n reply_markup = InlineKeyboardMarkup(keyboard)\n bot.edit_message_reply_markup(\n chat_id=query.message.chat_id,\n message_id=query.message.message_id,\n reply_markup=reply_markup\n )\n\n\ndef photo(bot, update):\n user = update.message.from_user\n photo_file = bot.getFile(update.message.photo[-1].file_id)\n recvImage = requests.get(photo_file.file_path, stream=True)\n success = model.insert(recvImage.content, int(user.id), str(time.strftime(\"%Y-%m-%d %H:%M\")))\n keyboard = [\n [InlineKeyboardButton(\"Rate\", callback_data='0')],\n [InlineKeyboardButton(\"Send Someone Photo\", callback_data='1')],\n [InlineKeyboardButton(\"About\", callback_data='2')]\n ]\n reply_markup = InlineKeyboardMarkup(keyboard)\n if success:\n bot.send_message(chat_id=update.message.chat_id, text=\"Gorgeous!\", reply_markup=reply_markup)\n else:\n bot.send_message(chat_id=update.message.chat_id, text=\"Photo already exists!\", reply_markup=reply_markup)\n\n\n\n\ndef error(bot, update, error):\n logging.warning('Update \"%s\" caused error \"%s\"' % (update, error))\n\n\n# Create the Updater and pass it your bot's token.\nupdater = Updater('378715116:AAHQTsXS3Y7N60lC85MTWERQNoNQU48vzGs')\n\nupdater.dispatcher.add_handler(CommandHandler('start', start))\nupdater.dispatcher.add_handler(MessageHandler(Filters.photo, photo))\nupdater.dispatcher.add_handler(CallbackQueryHandler(button))\n\nupdater.dispatcher.add_error_handler(error)\n\n# Start the Bot\nupdater.start_polling()\n\n# Run the bot until the user presses Ctrl-C or the process receives SIGINT,\n# SIGTERM or SIGABRT\nupdater.idle()","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"154446070","text":"#!/usr/bin/python\nimport sys, logging, json, os\nsys.path.insert(0, \"/usr/share/DataSea\")\n\ndef setup_logging(path=\"logging_config.json\", lvl=\"INFO\"):\n\tif os.path.exists(path):\n\t\twith open(path, 'r') as f:\n\t\t\tconfig = json.load(f)\n\t\tlogging.config.dictConfig(config)\n\telse:\n\t\tlogging.basicConfig(level=lvl)\n\nsetup_logging()\n\nfrom __init__ import app as application","sub_path":"DataSea.wsgi","file_name":"DataSea.wsgi","file_ext":"wsgi","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"263193781","text":"# Pablo Abad 2017\n#\n# Toshl database program\n\nclass SimpleConsoleUI():\n def __init__(self, io, database):\n self.io = io\n self.database = database\n\n def classifyManually(self, bankEntry):\n # Show the entry:\n self.io.stdout('-----------------------------------------------')\n self.io.stdout('Account: ' + bankEntry.account)\n self.io.stdout('Purpose: ' + bankEntry.purpose)\n self.io.stdout('Message: ' + bankEntry.message)\n self.io.stdout('Date : ' + str(bankEntry.date))\n self.io.stdout('Amount : ' + str(bankEntry.amount))\n self.io.stdout('-----------------------------------------------')\n self.io.stdout('Choose a category:')\n category = self._choose_category_from_list(self.database.getCategories())\n if category is not None and category != '':\n self.io.stdout('Choose a tag:')\n tag = self._choose_tag_from_list(self.database.getTags(), category)\n else:\n tag = ''\n\n if category is None or tag is None:\n return None, None\n\n return category, tag\n\n def askForOverwrite(self, toshlEntry):\n self.io.stdout('-----------------------------------------------')\n self.io.stdout('A similar entry was found:')\n toshlEntry.prettyPrint()\n self.io.stdout('-----------------------------------------------')\n selection = self.io.getString(\"Overwrite? (Enter yes to overwrite)\")\n return selection == \"yes\"\n\n\n def _choose_from_list(self, elements, label, create_function):\n index = 0\n elementsPerRow = 4\n while index < len(elements):\n lastInRow = min(len(elements), index + elementsPerRow)\n while index < lastInRow:\n e = elements[index]\n self.io.stdoutnnl('%2d. %-30s' % (index+1, ((e[:26] + '..') if len(e) > 28 else e)))\n index += 1\n self.io.stdout('')\n\n selection = self.io.getString(\"Please choose (E for skip, N for None, G to add a new expense type, I for a new Income type)\")\n if selection.upper() == \"N\":\n return ''\n elif selection.upper() == \"G\":\n name = self.io.getString(\"Enter the name for the new expense \" + label + \":\")\n create_function(name, \"expense\")\n return name\n elif selection.upper() == \"I\":\n name = self.io.getString(\"Enter the name for the new income \" + label + \":\")\n create_function(name, \"income\")\n return name\n elif selection.upper() == \"E\":\n return None\n else:\n selectionIdx = int(selection)\n return elements[selectionIdx-1]\n\n def _choose_category_from_list(self, elements):\n return self._choose_from_list(elements, \"category\", lambda name, t: self.database.addCategory(name, t))\n\n def _choose_tag_from_list(self, elements, category):\n return self._choose_from_list(elements, \"tag\", lambda name, t: self.database.addTag(name, t, category))\n","sub_path":"toshl/SimpleConsoleUI.py","file_name":"SimpleConsoleUI.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"562124035","text":"from amble import *\n\ntrim = Texture('pq_edge_white_2', [0.5, 0.5])\nfloor = Texture('pq_neutral_7_med', [4, 4], [0.5, 0.5])\nwall = Texture('pq_wall_blue', [4, 4], [0.5, 0.5])\nceiling = Texture('pq_ray_wall_combo', [4, 4], [0.5, 0.5])\nmp_floor = Texture('pq_neutral_5_med', [4, 4], [0.5, 0.5])\ncaution = Texture('stripe_caution', [4, 4], [0.5, 0.5])\n\nMission.normal(\n name=\"Example Mission\",\n artist=\"hPerks\",\n desc=\"Showcasing some of the features in my text-based MB level maker. This entire level - including the interior - was constructed in under 200 lines of Python code.\",\n starthelptext=\"\",\n platinumtime=25000,\n ultimatetime=18000,\n awesometime=15500,\n music='Good To Jump To.ogg',\n\n sky=Sky.blender1,\n sun=Sun(ambient=(0.3, 0.3, 0.4, 1))\n).add(\n StartPad('StartPoint', position=vec.zero),\n Map(\n [\n Brush.make_cube(\n center=center, size=size,\n texture={'top': floor, 'side': wall, 'bottom': ceiling},\n origin='0 0 0'\n ) for center, size in [\n ('0 0 -0.25', '8 8 0.5'),\n ('0 4.25 2.5', '8 0.5 6'),\n ('0 10 5.75', '8 12 0.5'),\n ('8 12 5.75', '8 8 0.5'),\n ('12.25 12 11.5', '0.5 8 12'),\n ('16 12 17.75', '8 8 0.5'),\n ('24 0 17.75', '8 32 0.5'),\n ('11.75 -12 23.5', '0.5 8 12'),\n ('8 -12 29.75', '8 8 0.5'),\n\n ('24 10 35.75', '8 12 0.5'),\n ('24 3.75 41.5', '8 0.5 12'),\n ('24 0 47.75', '8 8 0.5'),\n ('24 -3.75 43.5', '8 0.5 8'),\n ('24 -10 39.75', '8 12 0.5'),\n ]\n ],\n\n Brush.make_cube(\n center='0 -12 29.75', size='8 8 0.5',\n texture={'top': floor, 'side': caution, 'bottom': ceiling},\n origin='0 0 0'\n ),\n\n Brush.make_cube(\n center='0 12 29.75', size='8 8 0.5',\n texture={'top': floor, 'side': caution, 'bottom': ceiling},\n origin='0 0 0'\n ),\n\n Brush.make_cube(\n texture={'top': floor, 'side': wall, 'bottom': ceiling},\n center='12 12 29.75', size='16 8 0.5', origin='0 0 0'\n ).move_face('right', '0 0 6'),\n\n Brush.make_cube(\n texture={'all': ceiling, 'top': floor},\n center='12 0 23.75', size='16 16 48.5', origin='0 0 0'\n ),\n\n [\n Brush.make_cube(center=center, size=size, texture=trim) for center, size in [\n ('0 -4.25 -0.25', '8 0.5 0.5'),\n ('-4.25 0 -0.25', '0.5 9 0.5'),\n ('-4.25 4.25 2.75', '0.5 0.5 5.5'),\n ('-4.25 10 5.75', '0.5 12 0.5'),\n ('4 16.25 5.75', '17 0.5 0.5'),\n ('12.25 16.25 11.75', '0.5 0.5 11.5'),\n ('20 16.25 17.75', '16 0.5 0.5'),\n ('28.25 0 17.75', '0.5 33 0.5'),\n ('24 -16.25 17.75', '8 0.5 0.5'),\n ('11.75 -16.25 23.5', '0.5 0.5 12'),\n ('4 -16.25 29.75', '16 0.5 0.5'),\n ('-4.25 0 29.75', '0.5 33 0.5'),\n ('0 16.25 29.75', '8 0.5 0.5'),\n ('24 16.25 35.75', '8 0.5 0.5'),\n ('28.25 10 35.75', '0.5 13 0.5'),\n ('28.25 3.75 41.75', '0.5 0.5 11.5'),\n ('28.25 0 47.75', '0.5 8 0.5'),\n ('28.25 -3.75 43.75', '0.5 0.5 7.5'),\n ('28.25 -10 39.75', '0.5 13 0.5'),\n ('24 -16.25 39.75', '8 0.5 0.5'),\n ('19.75 -12.25 39.75', '0.5 8.5 0.5'),\n ]\n ],\n\n Brush.make_cube(texture=trim, center='12 16.25 29.75', size='16 0.5 0.5').move_face('right', '0 0 6'),\n\n Map(\n Brush.make_cube(\n texture={'top': mp_floor, 'side': caution, 'bottom': ceiling},\n center='16 -12 17.75', size='8 8 0.5', origin='0 0 0'\n ),\n Brush.make_cube(texture=trim, center='16 -16.25 17.75', size='8 0.5 0.5')\n )\n ).to_interior('examplemission'),\n\n SuperJump(position='0 3 0'),\n HelpTrigger(\n position='-4.5 -4.5 0', scale='8.5 8.5 4',\n text=\"Items are placed with a single tiny line of code, and customized however much you want.\"\n ),\n\n TimeTravel(position='-4 16 6.5', timebonus=2000),\n\n GravityModifier(position='11 12 7', rotation=rot.right),\n GravityModifier(position='13 12 19', rotation=rot.right + rot.right),\n HelpTrigger(\n position='10 8 6', scale='2 8.5 4',\n text=\"There are many tools for handling lists of numbers like positions and rotations. You can even \"\n \"(finally) combine rotations with a simple + sign!\"\n ),\n\n Bumper(scale='1.5 1.5 1.5').copies(\n 'position',\n '21 -3 18', '25 -3 18',\n '23 -1 18', '27 -1 18',\n '21 1 18', '25 1 18',\n '23 3 18', '27 3 18',\n ),\n HelpTrigger(\n position='20 -8 18', scale='8.5 16 4',\n text=\"Placing multiple similar items is made super easy with functions like copies(), as well as the \"\n \"builtlin loops and list comprehensions in Python.\"\n ),\n\n MovingInterior.make(\n PathedInterior.local('examplemission', 0),\n Path.make_accelerate('0 0 0', 3500, '0 0 12', 1500, '0 0 0')\n ),\n HelpTrigger(\n position='12 -16.5 18', scale='8 8.5 12',\n text='There are quite a few convenient ways to build moving platforms. This one uses the '\n 'MovingInterior.make() and Path.make_accelerate() builders.'\n ),\n\n TrapDoor().copies('position', [(x, y, 30) for x in range(-3, 5, 2) for y in range(-7, 9, 2)]),\n HelpTrigger(\n position='-4.5 -8 30', scale='8.5 16 4',\n text=\"These trapdoors would take ages to make and tweak using either the LE or a normal text editor. \"\n \"Here it's done in one simple line of code, using copies() and Python\\'s range().\"\n ),\n\n HelpTrigger(\n polyhedron=polyhedron.make(o='4 8 30', i='16 0 6', j='0 8 0', k='0 0 4'),\n text=\"This help trigger is skewed so as to align with the ramp. You can't activate it from below!\",\n ),\n\n TeleportTrigger(position='22.5 4.5 36', scale='3 3 2')\n .with_destination('destination', '24 0 48')\n .with_pad(offset='1.5 1.5 0', scale='.25 .25 .25'),\n\n HelpTrigger(\n position='20 4 36', scale='8.5 12.5 4',\n text=\"Friends and the ObjectName type facilitate linking objects, like teleports and destinations. \"\n \"Additional methods such as TeleportTrigger.with_destination() make this even simpler.\"\n ),\n\n NestEgg(position='24 -6 40'),\n TeleportTrigger(position='22.5 -13.5 40', scale='3 3 2', destination='destination')\n .with_pad(offset='1.5 1.5 0', scale='.25 .25 .25'),\n\n EndPad(position='12 0 48', rotation='0 0 -1 90').with_sign(),\n\n HelpTrigger(\n position='4 -8 48', scale='24 16 4',\n text=\"Finally, the autobounds() function adds a bounds trigger to your level automatically. Trying to save \"\n \"your level without a bounds trigger throws an error!\"\n ),\n\n).autobounds().write('examplemission')\n","sub_path":"examples/examplemission.py","file_name":"examplemission.py","file_ext":"py","file_size_in_byte":7142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"502551375","text":"\n\n#calss header\nclass _BURLESQUE():\n\tdef __init__(self,): \n\t\tself.name = \"BURLESQUE\"\n\t\tself.definitions = [u'a type of writing or acting that tries to make something serious seem stupid', u'a type of theatre entertainment in the US in the late 19th and early 20th centuries that had funny acts and a striptease (= a performance in which someone removes their clothes)']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_burlesque.py","file_name":"_burlesque.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"113827807","text":"##################################################\n##### 'Python Crash Course' Book - Exercises #####\n##################################################\n\n# 2-5. 1\n\nfamous_person=\"Eleanor Roosevelt\"\nfamous_quote=\"There is noone in the world who can make you feel inferior without your consent\"\n\nprint (famous_person, 'once said,','\"',famous_quote,'\"')\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"py_crash2-5_famousquote.py","file_name":"py_crash2-5_famousquote.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"211816780","text":"menor = nome = 0\nfor c in range(1, 4):\n n = int(input(f'Digite o preço do {c}° produto: R$ '))\n if c == 1:\n menor = n\n nome = c\n else:\n if n < menor:\n menor = n\n nome = c\nprint(f'O melhor produto a se comprar é o {nome}° produto.')\n","sub_path":"ex 2.08.py","file_name":"ex 2.08.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"292058959","text":"#\n# [23] Merge k Sorted Lists\n#\n# https://leetcode.com/problems/merge-k-sorted-lists/description/\n#\n# algorithms\n# Hard (28.60%)\n# Total Accepted: 229K\n# Total Submissions: 800.2K\n# Testcase Example: '[[1,4,5],[1,3,4],[2,6]]'\n#\n# Merge k sorted linked lists and return it as one sorted list. Analyze and\n# describe its complexity.\n#\n# Example:\n#\n#\n# Input:\n# [\n# 1->4->5,\n# 1->3->4,\n# 2->6\n# ]\n# Output: 1->1->2->3->4->4->5->6\n#\n#\n#\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\nclass Solution:\n def mergeKLists(self, lists):\n \"\"\"\n :type lists: List[ListNode]\n :rtype: ListNode\n \"\"\"\n # Log(k) times call mergeTwoLists\n if len(lists) == 0:\n return []\n if len(lists) == 1:\n return lists[0]\n\n return self.mergeTwoLists(self.mergeKLists(lists[:len(lists)//2]),\n self.mergeKLists(lists[len(lists)//2:]))\n\n def mergeTwoLists(self, a, b):\n \"\"\"\n Merge two list, cost O(len(a)+len(b))\n \"\"\"\n root = ListNode(-1)\n res = root\n while a is not None and b is not None:\n if a.val < b.val:\n res.next = a\n a, res = a.next, res.next\n else:\n res.next = b\n b, res = b.next, res.next\n\n if a is not None:\n res.next = a\n if b is not None:\n res.next = b\n return root.next\n","sub_path":"23.merge-k-sorted-lists.python3.py","file_name":"23.merge-k-sorted-lists.python3.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"160718643","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n\n path('',views.index,name='index'),\n path('signup/',views.signup,name='signup'),\n path('login/',views.login_view,name='login'),\n path('signout/',views.logout,name='logout'),\n path('leaderboard/',views.leaderboard,name='leaderboard'),\n path('get_question',views.get_question,name='get_question'),\n ]\n","sub_path":"quiz/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"421278701","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2017, Frappe Technologies and contributors\n# For license information, please see license.txt\n\nimport frappe\n\ndef run_webhooks(doc, method):\n\t'''Run webhooks for this method'''\n\tif frappe.flags.in_import or frappe.flags.in_patch or frappe.flags.in_install:\n\t\treturn\n\n\tif not getattr(frappe.local, 'webhooks_executed', None):\n\t\tfrappe.local.webhooks_executed = []\n\n\tif doc.flags.webhooks == None:\n\t\twebhooks = frappe.cache().hget('webhooks', doc.doctype)\n\t\tif webhooks==None:\n\t\t\twebhooks = frappe.get_all('Webhook',\n\t\t\t\tfields=[\"name\", \"webhook_docevent\", \"webhook_doctype\"])\n\t\t\tfrappe.cache().hset('webhooks', doc.doctype, webhooks)\n\t\tdoc.flags.webhooks = webhooks\n\n\tif not doc.flags.webhooks:\n\t\treturn\n\n\tdef _webhook_request(webhook):\n\t\tif not webhook.name in frappe.local.webhooks_executed:\n\t\t\tfrappe.enqueue(\"frappe.integrations.doctype.webhook.webhook.enqueue_webhook\", doc=doc, webhook=webhook)\n\t\t\tfrappe.local.webhooks_executed.append(webhook.name)\n\n\tevent_list = [\"on_update\", \"after_insert\", \"on_submit\", \"on_cancel\", \"on_trash\"]\n\n\tif not doc.flags.in_insert:\n\t\t# value change is not applicable in insert\n\t\tevent_list.append('on_change')\n\t\tevent_list.append('before_update_after_submit')\n\n\tfor webhook in doc.flags.webhooks:\n\t\tevent = method if method in event_list else None\n\t\tif event and webhook.webhook_docevent == event and webhook.webhook_doctype == doc.doctype:\n\t\t\t_webhook_request(webhook)\n","sub_path":"frappe/integrations/doctype/webhook/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"379313692","text":"import os\nimport numpy as np\nimport torch\nfrom torchvision import datasets,transforms\nfrom torch.utils.data import Dataset\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom PIL import Image\n\n\n\ndef psnr(original, contrast):\n mse = np.mean((original - contrast) ** 2)\n if mse == 0:\n return 100\n PSNR = 10 * np.log10(1 / (mse))\n return PSNR\n\ndef unnormalized_show(img):\n img = img * 0.5 + 0.5 # unnormalize\n npimg = img.detach().numpy()\n return np.transpose(npimg, (2, 3, 1, 0))\n\ndef findlabel(featurepath,labelimgs):\n count = 0;\n index = count;\n for k in labelimgs:\n if k[-7:-4] == featurepath[-7:-4]:\n index = count\n count = count+1\n return index\n\ndef getdataset(Q,transform):\n featpath2 = './train2_feature/'\n labelpath2 = './train2_label/'\n train = compset(os.path.join(featpath2,Q),labelpath2,transform)\n return train\n\nclass compset(Dataset):\n def __init__(self,featroot,labelroot,transform):\n featimgs = os.listdir(featroot)\n self.featimgs=[os.path.join(featroot,k) for k in featimgs]\n self.featimgs.sort(key=lambda x:int(x[-7:-4]))\n #self.featimgs.sort(key=lambda x:float(x[-12:-8]))\n labelimgs = os.listdir(labelroot)\n self.labelimgs=[os.path.join(labelroot,k) for k in labelimgs]\n self.labelimgs.sort(key=lambda x:int(x[-7:-4]))\n self.transforms = transform\n \n def __getitem__(self, index):\n feature_img_path = self.featimgs[index]\n feature_img = Image.open(feature_img_path)\n if self.transforms:\n feature = self.transforms(feature_img)\n else:\n feature = np.asarray(feature_img)\n feature = torch.from_numpy(feature)\n \n labelindex = findlabel(feature_img_path,self.labelimgs);\n label_img_path = self.labelimgs[labelindex]\n label_img = Image.open(label_img_path)\n if self.transforms:\n label = self.transforms(label_img)\n else:\n label = np.asarray(label_img)\n label = torch.from_numpy(label)\n data = (feature,label)\n return data\n \n def __len__(self):\n return len(self.featimgs)\n \nclass ARCNN(nn.Module):\n\n def __init__(self):\n \"\"\"\n Class constructor which preinitializes NN layers with trainable\n parameters.\n \"\"\"\n super(ARCNN, self).__init__()\n # 3 input image channel, 64 output channels, 9x9 square convolution\n # conv kernel\n self.conv1 = nn.Conv2d(3, 64, kernel_size=9, bias=None, stride=1, padding=4)\n nn.init.normal_(self.conv1.weight,mean=0.0,std=0.001)\n self.conv2 = nn.Conv2d(64, 32, kernel_size=7, bias=None, stride=1, padding=3)\n nn.init.normal_(self.conv2.weight,mean=0.0,std=0.001)\n self.conv3 = nn.Conv2d(32, 16, kernel_size=1, bias=None, stride=1, padding=0)\n nn.init.normal_(self.conv3.weight,mean=0.0,std=0.001)\n self.conv4 = nn.Conv2d(16, 3, kernel_size=5, bias=None, stride=1, padding=2)\n nn.init.normal_(self.conv4.weight,mean=0.0,std=0.001)\n\n\n\n def forward(self, x):\n x = F.relu(self.conv1(x))\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = self.conv4(x)\n return x ","sub_path":"IVC_ZHOU_SONG/ARCNN/Functions_and_classes.py","file_name":"Functions_and_classes.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"30248842","text":"import os\nimport unittest\nfrom distutils.version import StrictVersion\nfrom io import StringIO\nimport contextlib\nimport warnings\nimport numpy\nfrom numpy.testing import assert_almost_equal\nimport onnx\nimport onnxruntime\nfrom onnx import numpy_helper, helper\nfrom skl2onnx.algebra.onnx_ops import dynamic_class_creation\nfrom skl2onnx.algebra import OnnxOperator\nfrom skl2onnx.proto import onnx_proto\n\n\nclass TestMetaOnnx(unittest.TestCase):\n\n def setUp(self):\n self._algebra = dynamic_class_creation()\n\n def test_dynamic_class_creation(self):\n res = self._algebra\n for cl in res:\n assert hasattr(cl, '__init__')\n assert hasattr(cl, '__doc__')\n\n def test_mul(self):\n from skl2onnx.algebra.onnx_ops import OnnxMul\n assert OnnxMul.operator_name == 'Mul'\n assert isinstance(OnnxMul('a', 'b'), OnnxOperator)\n\n @unittest.skipIf(StrictVersion(onnx.__version__) < StrictVersion(\"1.5.0\"),\n reason=\"too unstable with older versions\")\n @unittest.skipIf(StrictVersion(onnxruntime.__version__) <\n StrictVersion(\"0.5.0\"),\n reason=\"too unstable with older versions\")\n def test_onnx_spec(self):\n untested = {}\n folder = os.path.dirname(onnx.__file__)\n folder = os.path.join(folder, \"backend\", \"test\", \"data\", \"node\")\n subs = os.listdir(folder)\n excs = []\n for sub in subs:\n path = os.path.join(folder, sub)\n model = os.path.join(path, \"model.onnx\")\n if not os.path.exists(model):\n continue\n dataset = os.path.join(path, \"test_data_set_0\")\n inps = [os.path.join(dataset, \"input_0.pb\")]\n outs = [os.path.join(dataset, \"output_0.pb\")]\n if not os.path.exists(inps[0]) or not os.path.exists(outs[0]):\n continue\n for d in range(1, 9):\n name = os.path.join(dataset, \"input_%d.pb\" % d)\n if os.path.exists(name):\n inps.append(name)\n else:\n break\n for d in range(1, 9):\n name = os.path.join(dataset, \"output_%d.pb\" % d)\n if os.path.exists(name):\n outs.append(name)\n else:\n break\n tests = dict(model=model, inputs=inps, outputs=outs)\n try:\n op_type, success, reason = self._check_algebra_onnxruntime(\n untested=untested, **tests)\n except Exception as e:\n warnings.warn(\"Unable to handle operator '{}'\".format(model))\n excs.append((op_type, reason, e))\n if __name__ == \"__main__\":\n if not success or len(excs) > 0:\n import pprint\n pprint.pprint([(op, reason or str(exc).split('\\n')[0])\n for op, reason, exc in excs])\n\n def _load_data(self, name):\n tensor = onnx.TensorProto()\n with open(name, 'rb') as fid:\n content = fid.read()\n tensor.ParseFromString(content)\n return tensor\n\n def _load_data_test(self, name, test):\n try:\n return self._load_data(name)\n except Exception as e:\n raise RuntimeError(\n \"Unable to load data '{}' for test '{}'\"\n \".\".format(name, test)) from e\n\n def _check_algebra_onnxruntime(self, untested=None, model=None,\n inputs=None, outputs=None):\n if untested is None:\n untested = {}\n name = os.path.split(os.path.split(model)[0])[-1]\n try:\n onx = onnx.load(model)\n except Exception as e:\n raise RuntimeError(\n \"Unable to load model '{}' - '{}'.\".format(name, model)) from e\n inps = [self._load_data_test(input, name) for input in inputs]\n outs = [self._load_data_test(output, name) for output in outputs]\n\n if len(onx.graph.node) != 1:\n op_type = \",\".join([n.op_type for n in onx.graph.node])\n return (op_type, False,\n \"The graph contains more than one node. Not tested.\")\n\n # get the operator to test\n node = onx.graph.node[0]\n op_class = self._algebra.get(\"Onnx\" + node.op_type, None)\n if op_class is None:\n raise RuntimeError(\n \"Unable to find the corresponding operator in the algebra \"\n \"'{}'.\".format(node.op_type))\n atts = {}\n if node.attribute:\n for att in node.attribute:\n atts[att.name] = helper.get_attribute_value(att)\n\n if len(node.input) != len(inps):\n if node.op_type in untested:\n return (node.op_type, False,\n \"unexpected number of inputs {} != {}\".format(\n len(node.output), len(outs)))\n raise RuntimeError(\n \"'{}': unexpected number of inputs {} != {}.\".format(\n node.op_type, len(node.input), len(inps)))\n if len(node.output) < len(outs):\n raise RuntimeError(\n \"'{}': unexpected number of inputs {} != {}.\".format(\n node.op_type, len(node.output), len(outs)))\n\n # See file onnx-ml.proto.\n if inps[0].data_type in (onnx_proto.TensorProto.FLOAT16, ):\n # not supported\n return (node.op_type, False,\n \"Unsupported type {}\".format(inps[0].data_type))\n expected_data_type = (onnx_proto.TensorProto.UINT8,\n onnx_proto.TensorProto.INT32,\n onnx_proto.TensorProto.INT64,\n onnx_proto.TensorProto.FLOAT,\n onnx_proto.TensorProto.DOUBLE,\n onnx_proto.TensorProto.BOOL,\n onnx_proto.TensorProto.STRING)\n if inps[0].data_type not in expected_data_type:\n if node.op_type in untested:\n return (node.op_type, False,\n \"unexpected data_type {} not in {}\".format(\n inps[0].data_type, expected_data_type))\n raise NotImplementedError(\n \"Unexpected data_type {}: {}\\n---\\n{}\\n---\".format(\n inps[0].data_type, node.op_type, inps[0]))\n\n # prepare the inputs\n inp_arrays = [numpy_helper.to_array(inp) for inp in inps]\n out_arrays = [numpy_helper.to_array(out) for out in outs]\n\n for i in range(len(inp_arrays)):\n inp_array = inp_arrays[i]\n if inp_array.dtype == numpy.float64:\n inp_arrays[i] = inp_array.astype(numpy.float32)\n inps[i] = numpy_helper.from_array(inp_arrays[i])\n\n # check the test from onnx is working.\n import onnxruntime as ort\n monx = onx.SerializeToString()\n try:\n sess = ort.InferenceSession(monx)\n except RuntimeError as e:\n if node.op_type in untested:\n return (node.op_type, False,\n \"cannot load ONNX model {}\".format(e))\n if StrictVersion(onnx.__version__) >= StrictVersion(\"1.5.0\"):\n # onnx 1.5.0 and onnx dev version have the same version number\n # some operators defined in onnx but not yet implemented in\n # onnxruntime.\n return (node.op_type, False,\n \"cannot load ONNX model* {}\".format(e))\n raise RuntimeError(\n \"'{}': cannot load(1) due to {}.\".format(node.op_type, e))\n\n names = [i.name for i in sess.get_inputs()]\n ort_inputs = {name: inp_array for name,\n inp_array in zip(names, inp_arrays)}\n try:\n Y = sess.run(None, ort_inputs)\n except RuntimeError as e:\n if node.op_type in untested:\n return (node.op_type, False,\n \"cannot load skl2onnx model {}\".format(e))\n raise RuntimeError(\n \"'{}': cannot run(1) due to {}.\".format(node.op_type, e))\n for exp, got in zip(out_arrays, Y):\n try:\n assert_almost_equal(exp, got, decimal=4)\n except TypeError:\n pass\n\n # instantiate the operator\n for i, inp in enumerate(inps):\n inp.name = 'I%d' % i\n op = op_class(*[inp.name for inp in inps],\n output_names=[out.name for out in outs],\n **atts)\n st = StringIO()\n with contextlib.redirect_stdout(st):\n with contextlib.redirect_stderr(st):\n ort_inputs = {'I%d' % i: inp for i, inp in enumerate(inps)}\n try:\n onx2 = op.to_onnx(ort_inputs)\n except (RuntimeError, NotImplementedError, TypeError) as e:\n if node.op_type in untested:\n return (node.op_type, False,\n \"cannot load skl2onnx model {}\".format(e))\n raise NotImplementedError(\n \"Unable to continue {}\\n{}\\n{}\".format(\n inp_array.dtype, st.getvalue(), ort_inputs)) from e\n\n # test with onnxruntime\n monx2 = onx2.SerializeToString()\n try:\n sess = ort.InferenceSession(monx2)\n except RuntimeError as e:\n if node.op_type in untested:\n return (node.op_type, False,\n \"cannot load skl2onnx model {}\".format(e))\n raise RuntimeError(\"'{}': cannot load(2) due to {}\\n\"\n \"---ONNX--\\n{}\\n---SKL2ONNX---\\n{}\".format(\n node.op_type, e, onx, onx2))\n\n names = [i.name for i in sess.get_inputs()]\n ort_inputs = {name: inp_array for name,\n inp_array in zip(names, inp_arrays)}\n try:\n Y = sess.run(None, ort_inputs)\n except RuntimeError as e:\n if node.op_type in untested:\n return (node.op_type, False,\n \"cannot load skl2onnx model {}\".format(e))\n raise RuntimeError(\"'{}': cannot run(2) due to {}\\n\"\n \"---ONNX--\\n{}\\n---SKL2ONNX---\\n{}\".format(\n node.op_type, e, onx, onx2))\n for exp, got in zip(out_arrays, Y):\n try:\n assert_almost_equal(exp, got, decimal=4)\n except (TypeError, AssertionError):\n pass\n return node.op_type, True, \"\"\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_algebra_meta_onnx.py","file_name":"test_algebra_meta_onnx.py","file_ext":"py","file_size_in_byte":10719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"613600536","text":"from django.shortcuts import render\nfrom django.shortcuts import HttpResponse\nfrom django.shortcuts import redirect, HttpResponseRedirect\nfrom django.core.paginator import Paginator, EmptyPage,PageNotAnInteger\nfrom django.contrib import auth\n\n\n\nfrom express_app import models\n\nfrom PIL import Image\nimport time\n\n\ndef home(request):\n return HttpResponse('

Hello Home

')\n\ndef login(request):\n\tif request.method == 'POST':\n\t\tinput_number = request.POST['input_username']\n\t\tinput_pwd = request.POST['input_pwd']\n\n\t\t# 匹配成功的话返回用户对象\n\t\tuser = auth.authenticate(username=input_number,password=input_pwd)\n\n\t\tif user is not None and user.is_active:\n\t\t\t# 更新登陆时间\n\t\t\tnow_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n\t\t\tuser.last_login = now_time\n\t\t\tuser.save()\n\n\t\t\trequest.session[\"username\"] = input_number\n\t\t\trequest.session.set_expiry(6000) \n\n\t\t\tauth.login(request, user)\n\n\t\t\tif user.is_admin:\n\t\t\t\treturn HttpResponseRedirect('/manager/main/')\n\t\t\telse:\n\t\t\t\treturn HttpResponseRedirect('/user/')\n\n\treturn render(request,'login.html')\n\n\n\n\ndef register(request):\n\tif request.method == 'POST':\n\t\tinput_username = request.POST['input_username']\n\t\tinput_pwd = request.POST['input_pwd']\n\t\tinput_rank = request.POST['input_rank']\n\n\t\tif input_rank == 'admin':\n\t\t\tmodels.UserProfile.objects.create_user(username = input_username, \n\t\t\t\tpassword = input_pwd, is_admin=True)\n\n\t\t\treturn render(request,'login.html',{'status':'注册成功,自由登录'})\n\n\t\telse:\n\t\t\tmodels.UserProfile.objects.create_user(username = input_username, \n\t\t\t\tpassword = input_pwd)\n\n\t\t\treturn render(request,'login.html',{'status':'注册成功,自由登录'})\n\n\treturn render(request, 'register.html')\n\n\n\n\n##########################################\n########### 管理员的使用功能 #############\n#\n# 主页: admin_main(request) \n# 查看用户:check_users(request)\n# 添加用户:check_users(request)\n# 修改用户:\n# 删除用户:delete_user(request,username)\n# \n# 查看快件:check_express(request)\n# 添加快件:check_express(request)\n# 修改快件:\n# 删除快件:delete_express(request)\n#\n##########################################\n\ndef admin_main(request):\n\treturn render(request,'admin_main.html')\n\n######################\n#\n# 实现添加用户,分页功能\n#\n######################\n\ndef check_users(request):\n\n\tif request.method =='POST':\n\t\tinput_username = request.POST['input_username']\n\t\tinput_pwd = request.POST['input_pwd']\n\t\tinput_rank\t = request.POST['input_rank']\n\n\t\tis_admin = False\n\n\t\tif input_rank == 'admin':\n\t\t\tis_admin = True\n\n\t\tmodels.UserProfile.objects.create(username = input_username, \n\t\t\t\tpassword = input_pwd, is_admin=is_admin)\n\n\tuser_info_list = models.UserProfile.objects.all()\n\n\tpaginator = Paginator(user_info_list,5)\n\tpage = request.GET.get('page')\n\n\ttry:\n\t\tuser_page = paginator.page(page)\n\n\texcept PageNotAnInteger:\n\t\tuser_page = paginator.page(1)\n\texcept EmptyPage:\n\t\tuser_page = paginator.page(paginator.num_pages)\n\n\treturn render(request,'admin_check_users.html', {'user_page':user_page})\n\t\n\ndef delete_user(request,username):\n\tmodels.UserProfile.objects.filter(username=username).delete()\n\tuser_info_list = models.UserProfile.objects.all()\n\treturn HttpResponseRedirect('/manager/check_users/')\n\n\ndef check_express(request):\n\n\tExpress_info_list = models.ParcelProfile.objects.all()\n\n\tpaginator = Paginator(Express_info_list,5)\n\tpage = request.GET.get('page')\n\n\ttry:\n\t\tparcel_page = paginator.page(page)\n\n\texcept PageNotAnInteger:\n\t\tparcel_page = paginator.page(1)\n\texcept EmptyPage:\n\t\tparcel_page = paginator.page(paginator.num_pages)\n\t\n\treturn render(request,'admin_check_express.html', {'parcel_page':parcel_page})\n\ndef delete_express(request,number):\n\tmodels.ParcelProfile.objects.filter(number=number).delete()\n\n\tExpress_info_list = models.ParcelProfile.objects.all()\n\treturn render(request,'check_express.html', {'Express_info_list':Express_info_list})\n\n\n\n##########################################\n########### 管理员的使用功能 #############\n\n# 主页: user_main(request) \n# 查询快件:search_express(request)\n# 领取快件:take_express(request)\n# 完善信息:complete(request)\n\n##########################################\n\n\n\n\ndef user_main(request):\n\treturn render(request, 'user_main.html')\n\ndef search_express(request):\n\tif request.method =='POST':\n \n\t\tinput_num = request.POST['input_num']\n\t\tinput_num = int(input_num)\n\n\t\tprint(input_num)\n\t\t\n\t\tExpress_info_list = models.ParcelProfile.objects.all()\n\t\tsearched_express = []\n\n\t\tfor line in Express_info_list:\n\t\t\tprint(line.pnum == input_num)\n\t\t\tif line.pnum == input_num:\n\t\t\t\tprint(line.robot.rname)\n\t\t\t\treturn render(request, 'user_search_express.html',{'line':line})\n\t\t\n\t\treturn render(request, 'user_search_express.html',{'status':'无此快件,请检查!'})\n\t\n\treturn render(request,'user_search_express.html')\n\n\ndef take_express(request):\n\n\tif request.method =='POST':\n \n\t\tinput_express_number = request.POST['number']\n\t\t\n\t\tExpress_info_list = models.ExpressInfo.objects.all()\t\n\n\t\tfor line in Express_info_list:\n\t\t\tif line.number == input_express_number:\n\t\t\t\tmodels.ExpressInfo.objects.filter(number=line.number).delete()\n\t\t\t\treturn render(request, 'user_take_express.html',{'status':'取件成功,谢谢使用!'})\n\t\telse:\n\t\t\treturn render(request, 'user_take_express.html',{'status':'无此快件,请检查!'})\n\t\n\n\n\n\treturn render(request, 'user_take_express.html')\n\n\ndef complete(request):\n\n\tusername = request.user.username\n\tprint(username)\n\n\tuser_info = models.UserProfile.objects.get(username=username)\n\n\tif request.method == 'POST':\n\t\tinput_username = request.POST['input_username']\n\t\tinput_nickname = request.POST['input_nickname']\n\t\tinput_email = request.POST['input_email']\n\t\tinput_mobile = request.POST['input_mobile']\n\t\tinput_birthday = request.POST['input_birthday']\n\t\tinput_gender = request.POST['input_gender']\n\t\tinput_img = request.FILES['input_img']\n\n\t\tif input_img:\n\t\t\timg=Image.open(input_img)\n\t\t\timg.save('E:/package_1.0/media/img/'+input_img.name)\n\t\t\n\t\tmodels.UserProfile.objects.filter(username=username).update(username=input_username,\n\t\t\tnick_name=input_nickname,email=input_email,mobile=input_mobile,birday=input_birthday,\n\t\t\tgender=input_gender,headImg = input_img)\n\n\t\tuser_info = models.UserProfile.objects.get(username=input_username)\n\t\treturn render(request,'complete.html',{'status':'修改成功','user_info':user_info})\n\n\n\treturn render(request, 'complete.html',{'user_info':user_info}) \n\n\n\ndef logout_view(request):\n\tauth.logout(request)\n\treturn render(request,'login.html',{'status':'注销成功,谢谢使用'})\n\treturn HttpResponseRedirect(\"/login/\")\n\n","sub_path":"express_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"196645302","text":"# CIRC16 - IR Sensor make it better rgb\n# (CircuitPython)\n# this circuit was designed for use with the Metro Express Explorers Guide on Learn.Adafruit.com\n\n# by Asher Lieber for Adafruit Industries\n\nimport board\nimport digitalio\nimport IRrecvPCI\nimport IRLib_P01_NECd # remote uses NEC\n\n\nLEDs = [digitalio.DigitalInOut(board.D4), digitalio.DigitalInOut(board.D1), digitalio.DigitalInOut(board.D2)]\n\n\n\nfor i in LEDs:\n i.switch_to_output()\n\n# only red\nRED = [True, False, False] \n# only green\nGREEN = [False, True, False] \n# only blue\nBLUE = [False, False, True] \n# red+green\nYELLOW = [True, True, False] \n# green+blue\nCYAN = [False, True, True] \n# red+blue\nMAGENTA = [True, False, True] \n# all on\nWHITE = [True, True, True] \n# all off\nBLACK = [False, False, False] \n\n# dict of button values and their corresponding colors\nbuttons = {\n16582903: RED ,\n16615543: GREEN,\n16599223: BLUE,\n16591063: YELLOW,\n16623703: CYAN,\n16607383: MAGENTA,\n16586983: WHITE,\n16619623: BLACK}\n\ndef set_color(color):\n for i in range(len(LEDs)):\n LEDs[i].value = not color[i]\n\n\nrecvr = IRrecvPCI.IRrecvPCI(board.D6)\nrecvr.enableIRIn()\n\ndec = IRLib_P01_NECd.IRdecodeNEC()\nprint('awaiting signal!')\n\ndef get_signal():\n while not recvr.getResults():\n pass\n recvr.enableIRIn()\n dec.decode()\n #dec.dumpResults(True)\n return dec.value\nwhile True:\n tmp = get_signal()\n if tmp in buttons:\n set_color(buttons[tmp])\n # if none of the mapped buttons were pressed, turn LED off\n else:\n set_color(BLACK)\n","sub_path":"circuitpython/CIRC16/mib_ir_sensor.py","file_name":"mib_ir_sensor.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"566525381","text":"# Split an audio file into multiple audio file each consiting of an\n# individual attack\n\nfrom pydub import AudioSegment\nimport wave\nimport numpy as np\nimport matplotlib.pyplot as plt\n# sound = AudioSegment.from_file(file_path)\nimport visualize\nimport scipy\nfrom enum import Enum\nfrom pyAudioAnalysis import audioFeatureExtraction\nimport librosa\n\n# from visualize import Point, LinearLine, VerticalLine, LinePlot, GraphItem\n\n\nTRANSIENT_MAX = 5000 # Guessing here. half a second\n\nclass Sample:\n\n def __init__(self, t, amp):\n self.t = t\n self.amplitude = amp\n\n def tangent(self, other_sample):\n slope = (other_sample.amplitude - self.amplitude)/(other_sample.t - self.t)\n y_intercept = other_sample.amplitude - slope*other_sample.t\n return lambda time: slope*time + y_intercept\n\n @staticmethod\n def get_list(signal, sr):\n num_samples = len(signal)\n return [Sample(signal[i], sr*i) for i in range(num_samples)]\n\n @staticmethod\n def split(samples):\n t_vals = map(lambda s: s.t, samples)\n amp_vals = map(lambda s: s.amplitude, samples)\n return list(t_vals), list(amp_vals)\n\n# Does every sound go through every phase\nclass Phase: # this should be called phase\n\n\n def __init__(self, sr, decaying, animate=False):\n self.sr = sr\n self.decaying = decaying\n self.hull = []\n self.max_index = -1\n self.animate = animate\n\n def growth_rate(self):\n return\n\n # https://www.geeksforgeeks.org/dynamic-convex-hull-adding-points-existing-convex-hull/\n def update_hull(self, new_point):\n def tangent(p0, p1):\n slope = (p1[1] - p0[1])/(p1[0] - p0[0])\n y_intercept = p1[1] - slope*p1[0]\n return lambda time: slope*time + y_intercept\n\n # Since points are fed in chronological order, point.x is always\n # going to be larger than the lastHullPoint.x. Therefore, each new\n # point is garunteed to be outside the hull, and must be added. The\n # role of this method is to remove hull points if adding the new\n # point requires so\n if self.hull_size() > 1:\n\n for hull_index in range(self.hull_size() - 1, 0, -1):\n hull_pnt = self.hull[hull_index]\n\n # Get the tangent line of the new point and the last hull point\n point_tangent = tangent(hull_pnt, new_point)\n # Get the tangent line of the last hull point and second to last hull point\n hull_tangent = tangent(self.hull[hull_index-1], hull_pnt)\n\n # Get the closest possible t value that is less than the hull\n # points t value. Since you can't subtract 1/inf to get infinitely\n # close value to t, I use the sample rate\n t_close = hull_pnt[0] - self.sr\n if point_tangent(t_close) < hull_tangent(t_close):\n # hull_pnt must be deleted\n del self.hull[hull_index]\n if self.max_index == hull_index:\n # This means the new point is the new y_max point\n # and the old y_max is beind removed\n self.max_index = -1\n\n # if self.animate:\n # Point.delete_at(hull_pnt[0], hull_pnt[1])\n plt.plot(hull_pnt[0], hull_pnt[1], 'g.')\n # for line in GraphItem.get_all(hull_pnt):\n # line.delete()\n else:\n # hull point is valid. Therefore, all previous hull points\n # must be valid too. Adding new point to hull will result\n # in valid hull. Can break out of loop now\n break\n\n\n hull_size = self.hull_size() # size may have changed from hp removal above\n if new_point[1] > self.max_amplitude():\n # new point is the new highest point. Set max index to last index\n # which will be the index of new point after being added\n self.max_index = hull_size\n\n # if self.animate:\n plt.plot(new_point[0], new_point[1], 'b.')#, markersize=0.5)\n # plot the new point if plot mode is on\n # if self.animate and hull_size != 0:\n # plot new hull point\n # p = Point(new_point[0], new_point[1], color='r', point_size=5).draw()\n # plt.plot(new_point[0], new_point[1], 'b.', markersize=0.5)\n # Next, plot a line from the last hull point to the new one\n # last_hull_point = self.hull[-1]\n # t0, t1 = last_hull_point[0], new_point[0]\n # hull_line = tangent(last_hull_point, new_point)\n # l = LinePlot.draw_function(hull_line, t0, t1, step_size=self.sr )\n # l.set_tag(new_point) # set tag to be deleted later if point is removed from hull\n\n # Finally, add the new point to the hull\n self.hull.append(new_point)\n\n\n\n def hull_size(self):\n return len(self.hull)\n\n def shift_detected(self):\n if self.decaying:\n return False\n else:\n hull_size = len(self.hull)\n if hull_size > 3 and self.max_index != hull_size-1: # TODO Should this really be 3?\n highest_point = self.hull[self.max_index]\n first_hull_point = self.hull[0]\n last_hull_point = self.hull[-1]\n\n gain_time = highest_point[0] - first_hull_point[0]\n decay_time = last_hull_point[0] - highest_point[0]\n if decay_time > gain_time:\n return True\n return False\n\n def find_phase_shift(self, points):\n for pnt in points:\n self.update_hull(pnt)\n if self.shift_detected():\n self.hull = self.hull[:self.max_index+1]\n return self.hull[self.max_index]\n raise Exception('Could not find end of phase')\n\n def get_last_point(self):\n return self.hull[-1]\n\n def max_amplitude(self):\n if self.max_index == -1:\n return 0\n else:\n highest_point = self.hull[self.max_index]\n return highest_point[1]\n\n def plot(self):\n last_point = self.get_last_point()\n t = last_point[0]\n amp = last_point[1]\n plt.plot([t, t],[0,amp],'r--', lw=1)\n t_vals = [p[0] for p in self.hull]\n a_vals = [p[1] for p in self.hull]\n plt.plot(t_vals, a_vals, 'g--', lw=1)\n\n\ndef get_2d_signal(amplitudes, sr, plot=False):\n duration = sr * len(amplitudes)\n time_axis = np.arange(0., duration, sr)\n if plot:\n plt.plot(time_axis, amplitudes, color='black')\n return np.column_stack( (time_axis, amplitudes) )\n\ndef find_cross_peaks(amplitudes, sr):\n peaks = []\n cur_peak = amplitudes[0]\n cur_peak_t = 0\n positive = amplitudes[0] > 0\n for i in range(1, len(amplitudes)):\n amp = amplitudes[i]\n pnt_is_positive = amp > 0\n if positive != pnt_is_positive:\n peak = (cur_peak_t, cur_peak)\n peaks.append(peak)\n positive = pnt_is_positive\n cur_peak = amp\n cur_peak_t = sr*i\n elif abs(amp) > abs(cur_peak):\n cur_peak_t = sr * i\n cur_peak = amp\n return peaks\n\n\ndef find_peaks(amplitudes, sr):\n peaks = []\n for i in range(1, len(amplitudes) - 1):\n was_increasing = amplitudes[i] - amplitudes[i-1] > 0\n is_increasing = amplitudes[i+1] - amplitudes[i] > 0\n if was_increasing != is_increasing:\n t = sr * i\n inflection_point = (t, amplitudes[i])\n peaks.append(inflection_point)\n return peaks\n\ndef cut_file(file, seconds): # seconds can be a double\n cut_point = seconds * 1000\n sound = AudioSegment.from_file(file)\n\n first = sound[:cut_point]\n\n # create a new file \"first_half.mp3\":\n first.export(\"testaudio/split.wav\", format=\"wav\")\n\n\n# The attack starts when amplitude starts increasing. Once a decrease of\n# amplitude starts, the file should end whenever the next increase happens\n# there should be a slope threshold that has to be reached to institue\n# amplitude increase. There should be a min file time.\ndef find_attacks():\n return []\n\n\n# cross rates are really high after decay is finished.\n# Cross rates and amplitude sums are high when new phase starts\n# Find cycle start/end with num cross peak?\ndef energy(peaks, sr, duration):\n energy_snapshots = []\n frame_size = sr*50\n t = 0\n num_peaks = len(peaks)\n while t < duration:\n frame_start = t - frame_size/2\n frame_end = t + frame_size/2\n index = 0\n peaks_found = 0\n amplitude_sum = 0\n while index < num_peaks and peaks[index][0] < frame_end:\n if peaks[index][0] > frame_start:\n peaks_found += 1\n amplitude_sum += abs(peaks[index][1])\n index += 1\n snapshot = (peaks_found, amplitude_sum)\n energy_snapshots.append(snapshot)\n t += sr\n return energy_snapshots\n\n\n# Finds frequency segment that repeats (can lower in amplitude)\ndef find_repeated_segment():\n return\n # split sound1 in 5-second slices: slices = sound1[::5000]\n# If amplitude does not reach 0 (or baseline amplitude before attack) after a\n# attack starts, then it is not a complete 'note'\n\n\n# It would be cool to be able to tell if an audio clip contains isolate 'notes'\n\ndef energy_entropy(amplitudes, sr):\n features, f_names = audioFeatureExtraction.stFeatureExtraction(amplitudes, sr, 0.002*sr, 0.001*sr);\n return features[f_names.index('energy_entropy')]\n\n\nif __name__ == '__main__':\n\n\n # file_path = 'training_data/breathing/breathing_0.wav'\n file_path = 'testaudio/trimmed_b.wav'\n # specto = visualize.spectogram(file_path, plot=False)\n plt.ion()\n spf = wave.open(file_path)\n sr = spf.getframerate()\n amplitudes = np.fromstring(spf.readframes(-1), 'Int16')\n\n # tempo = np.array([float(a) for a in amplitudes])\n # tempo = librosa.feature.tempogram(y=tempo,sr=sr)\n # print(tempo)\n # eng = energy_entropy(amplitudes, sr)\n amplitudes = amplitudes[4150::]\n\n samples = Sample.get_list(amplitudes, sr)\n\n duration = len(amplitudes)*sr\n idk = find_peaks(amplitudes, sr)\n\n # HIGH AMOUNTS OF LOW AMPLITUDES CROSS PEAKS IN A FRAME INDICATES\n peaks = find_cross_peaks(amplitudes, sr)\n peaks = [(pnt[0], abs(pnt[1])) for pnt in peaks]\n #eng = energy(peaks, sr, duration)\n # Make all negative amps positive with absolute value\n amplitudes = np.absolute(amplitudes)\n signal = get_2d_signal(amplitudes, sr, plot=True)\n\n transient = Phase(sr, False)\n last_point = transient.find_phase_shift(peaks)\n transient.plot()\n\n decay_start_index = peaks.index(last_point)\n peaks = peaks[decay_start_index::]\n decay = Phase(sr, True, animate=True)\n\n for point in peaks:\n decay.update_hull(point)\n # input()\n t_axis, amp_axis = [], []\n for pnt in idk:\n t_axis.append(pnt[0])\n amp_axis.append(abs(pnt[1]))\n plt.plot(t_axis, amp_axis, 'r.', markersize=0.8)\n input()\n # cross_rates = []\n # amp_sums = []\n # for i in range(len(eng)):\n # e = eng[i]\n # cross_rates.append((i*sr,1000*e[0]))\n # amp_sums.append((i*sr,e[1]))\n #\n # l0 = LinePlot(cross_rates, color='m').draw()\n # l1 = LinePlot(amp_sums, color='g').draw()\n\n # energy2d = [signal[0], [max(fr) for fr in eng] ]\n # for pnt in peaks:\n # t_axis.append(pnt[0])\n # amp_axis.append(abs(pnt[1]))\n # plt.plot(t_axis, amp_axis, 'r,')\n","sub_path":"splitter copy.py","file_name":"splitter copy.py","file_ext":"py","file_size_in_byte":11636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"588013411","text":"import logging\n\nimport requests.exceptions\nfrom rest_auth.serializers import UserDetailsSerializer\nfrom rest_framework import serializers\n\nfrom . import models\nfrom .open_graph import OpenGraph\nfrom .utils import convert_url\n\nL = logging.getLogger(__name__)\n\n\nclass OptionSerializer(serializers.HyperlinkedModelSerializer):\n answer_count = serializers.IntegerField(read_only=True)\n\n class Meta:\n model = models.Option\n fields = [\n 'id',\n 'title',\n 'url',\n 'answer_count',\n ]\n\n\nclass QuestionSerializer(serializers.HyperlinkedModelSerializer):\n options = OptionSerializer(many=True)\n\n class Meta:\n model = models.Question\n fields = [\n 'id',\n 'title',\n 'url',\n 'options',\n ]\n\n\nclass TaskSerializer(serializers.HyperlinkedModelSerializer):\n questions = QuestionSerializer(many=True)\n og_image_link = serializers.URLField(read_only=True)\n user = UserDetailsSerializer(read_only=True)\n warning_message = serializers.SerializerMethodField(read_only=True)\n\n def create(self, validated_data):\n questions = validated_data.pop('questions')\n task = models.Task.objects.create(**validated_data)\n for question in questions:\n q = models.Question.objects.create(title=question['title'], task=task)\n for option in question['options']:\n models.Option.objects.create(title=option['title'], question=q)\n return task\n\n def validate_website_link(self, website_link):\n return convert_url(website_link)\n\n def validate(self, attrs):\n website_link = attrs.get('website_link')\n if website_link:\n try:\n self._og = OpenGraph(url=website_link)\n except requests.exceptions.ConnectionError as e:\n L.warning(e)\n raise serializers.ValidationError({'website_link': f'Connection error for {website_link}'})\n attrs.update({\n 'og_image_link': self._og.image,\n 'website_link': self._og.RESOLVED_URL or website_link\n })\n return super().validate(attrs)\n\n def get_warning_message(self, obj):\n warning_msg = ''\n if hasattr(self, '_og'): # from validate only\n og = self._og\n if og.X_FRAME_OPTIONS:\n # Website doesn't allow us to be viewed\n warning_msg = f'Website has strict X-Frame-Options: {og.X_FRAME_OPTIONS}'\n return warning_msg\n\n class Meta:\n model = models.Task\n fields = [\n 'id',\n 'title',\n 'description',\n 'user',\n 'og_image_link',\n 'website_link',\n 'reward_per_click',\n 'reward_usd_per_click',\n 'spend_daily',\n 'time_duration',\n 'questions',\n 'warning_message',\n ]\n\n\nclass SelectedOptionSerializer(serializers.HyperlinkedModelSerializer):\n id = serializers.IntegerField()\n title = serializers.CharField(read_only=True)\n\n class Meta:\n model = models.Option\n fields = [\n 'id',\n 'title',\n ]\n\n\nclass AnsweredQuestionSerializer(serializers.HyperlinkedModelSerializer):\n id = serializers.IntegerField()\n options = SelectedOptionSerializer(many=True)\n\n class Meta:\n model = models.Answer\n fields = [\n 'id',\n 'options',\n ]\n\n\nclass AnswerSerializer(serializers.HyperlinkedModelSerializer):\n user = UserDetailsSerializer(read_only=True)\n questions = AnsweredQuestionSerializer(many=True, source='answered_questions')\n selected_options = OptionSerializer(many=True, read_only=True)\n timestamp = serializers.DateTimeField(read_only=True, allow_null=True)\n\n class Meta:\n model = models.Answer\n fields = [\n 'user',\n 'selected_options',\n 'questions',\n 'timestamp',\n ]\n\n def create(self, validated_data):\n selected_options = []\n for question in validated_data['answered_questions']:\n for option in question['options']:\n selected_options.append(option['id'])\n answer = models.Answer.objects.create(\n task=validated_data['task'],\n user=validated_data['user'],\n )\n answer.selected_options.set(selected_options)\n return answer\n\n\nclass TaskDashboardSerializer(TaskSerializer):\n answers_result_count = serializers.IntegerField(read_only=True)\n answers = AnswerSerializer(many=True)\n\n class Meta:\n model = models.Task\n fields = [\n 'id',\n 'title',\n 'description',\n 'user',\n 'og_image_link',\n 'website_link',\n 'reward_per_click',\n 'reward_usd_per_click',\n 'spend_daily',\n 'time_duration',\n 'questions',\n 'answers_result_count',\n 'answers',\n ]\n\n\nclass SubscribeSerializer(serializers.ModelSerializer):\n class Meta:\n model = models.Subscribe\n fields = [\n 'email'\n ]\n","sub_path":"ad_source/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"155995900","text":"class Sudoku (object):\r\n\t\"\"\"docstring for Sudoku \"\"\"\r\n\tempty = [[0 for _ in range(9)] for _ in range(9)]\r\n\r\n\tdef __init__(self, sheet = empty):\r\n\t\tself.sheet = sheet\r\n# Abstraction \r\n\r\n\tdef show(self):\r\n\t\tfor x in self.sheet:\r\n\t\t\tprint(x)\r\n\t\treturn\r\n\tdef show_prob(self):\r\n\t\tfor x in self.sheet:\r\n\t\t\tlst = []\r\n\t\t\tfor y in x:\r\n\t\t\t\tlst += [y.probabilit]\r\n\t\t\tprint(lst)\r\n\r\n\r\n# Return Sudoku objects with list of Ind_cells according to 9 lines of user input \r\n\tdef sheet_input():\r\n\t\tq = []\r\n\t\tfor _ in range(9):\r\n\t\t\ta = [int(x) for x in input()]\r\n\t\t\tq += [a]\r\n\t\tp = Sudoku(q)\r\n\t\treturn Ind_cell.numtocell(p)\r\n# Return the number in given index\r\n\tdef search(self, row, column):\r\n\t\treturn self.sheet[row][column]\r\n# Return the row in given index\r\n\tdef search_row(self, index):\r\n\t\treturn self.sheet[index]\r\n# Change the number in given index\r\n\tdef update(self, row, column, number):\r\n\t\tself.sheet[row][column] = number\r\n\t\treturn self\r\n# Return Sudoku object consists of 9 columns\r\n\tdef columns(self):\r\n\t\tp = []\r\n\t\tfor x in range(9):\r\n\t\t\tq = []\r\n\t\t\tfor y in range(9):\r\n\t\t\t\tq += [self.search(y, x)]\r\n\t\t\tp += [q]\r\n\t\treturn Sudoku(p)\r\n# Return Sudoku object consists of list of 9 cells\r\n\tdef cells(self):\r\n\t\tp = []\r\n\t\tfor y in [0,3,6]:\r\n\t\t\tq = []\r\n\t\t\tfor z in [0,3,6]:\r\n\t\t\t\tq = []\r\n\t\t\t\tfor x in range(z, z+3):\r\n\t\t\t\t\tq += self.search_row(x)[y:y+3]\r\n\t\t\t\tp += [q]\r\n\t\treturn Sudoku(p)\r\n# Used in method\r\n\t\"\"\"def zero_count(self):\r\n\t\tlst = []\r\n\t\tfor row in self.sheet:\r\n\t\t\tcount = 0\r\n\t\t\tfor x in row:\r\n\t\t\t\tif x.number == 0:\r\n\t\t\t\t\tcount += 1\r\n\t\t\tlst += [count]\r\n\t\treturn lst\r\n\r\n\tdef fofi_check(self):\r\n\t\tlst = []\r\n\t\tfor row in self.sheet:\r\n\t\t\tnum = 45 - sum([x.number for x in row])\r\n\t\t\tlst += [num]\r\n\t\treturn lst\"\"\"\r\n\r\n\r\nclass Ind_cell(object):\r\n\tdef __init__(self, number, Sudok, rown, columnn, celln):\r\n\t\tself.number = number\r\n\t\tself.Sudok = Sudok\r\n\t\tself.row = []\r\n\t\tself.column = []\r\n\t\tself.cell = [] \r\n\t\tself.rown = rown\r\n\t\tself.columnn = columnn\r\n\t\tself.celln = celln\r\n\t\tself.probabilit = []\r\n\r\n\tdef infoupdate(self):\r\n\t\tself.row = self.Sudok.search_row(self.rown)\r\n\t\tself.column = self.Sudok.columns().search_row(self.columnn)\r\n\t\tself.cell = self.Sudok.cells().search_row(self.celln)\r\n\r\n\tdef cellnum(rown, columnn):\r\n\t\tcelln = 0\r\n\t\tif 0 <= rown <= 2:\r\n\t\t\tcelln += 0\r\n\t\telif 3 <= rown <= 5:\r\n\t\t\tcelln += 1\r\n\t\telif 6 <= rown <= 8:\r\n\t\t\tcelln += 2\r\n\t\tif 0 <= columnn <= 2:\r\n\t\t\tcelln += 0\r\n\t\telif 3 <= columnn <= 5:\r\n\t\t\tcelln += 3\r\n\t\telif 6 <= columnn <= 8:\r\n\t\t\tcelln += 6\r\n\t\treturn celln\r\n\r\n\tdef numtocell(Sudok):\r\n\t\tfor x in range(9):\r\n\t\t\tfor y in range(9):\r\n\t\t\t\tSudok.sheet[x][y] = Ind_cell(Sudok.search(x,y), Sudok, x, y, Ind_cell.cellnum(x, y))\r\n\t\treturn Sudok\r\n\r\n\t\"\"\"def celltonum(Sudok):\r\n\t\tlst = []\r\n\t\tfor x in range(9):\r\n\t\t\tlst2 = []\r\n\t\t\tfor y in range(9):\r\n\t\t\t\tlst2 += [Sudok.search(x,y).number]\r\n\t\t\tlst += [lst2]\r\n\t\treturn Sudoku(lst)\"\"\"\r\n\r\n\tdef probability(self):\r\n\t\tlst = list(range(1,10))\r\n\t\tif self.number != 0:\r\n\t\t\tself.probabilit = []\r\n\t\t\treturn []\r\n\t\tfor x in self.column:\r\n\t\t\ttry:\r\n\t\t\t\tlst.remove(x.number)\r\n\t\t\texcept ValueError:\r\n\t\t\t\tpass\r\n\t\tfor x in self.cell:\r\n\t\t\ttry:\r\n\t\t\t\tlst.remove(x.number)\r\n\t\t\texcept ValueError:\r\n\t\t\t\tpass\r\n\t\tfor x in self.row:\r\n\t\t\ttry:\r\n\t\t\t\tlst.remove(x.number)\r\n\t\t\texcept ValueError:\r\n\t\t\t\tpass\r\n\t\tself.probabilit = lst\r\n\t\treturn lst\r\n\r\n\tdef hard_probability(self):\r\n\t\tlst = list(range(1,10))\r\n\t\tif self.number != 0:\r\n\t\t\tself.probabilit = []\r\n\t\t\treturn []\r\n\t\tfor x in self.column:\r\n\t\t\ttry:\r\n\t\t\t\tlst.remove(x.number)\r\n\t\t\texcept ValueError:\r\n\t\t\t\tpass\r\n\t\tfor x in self.cell:\r\n\t\t\ttry:\r\n\t\t\t\tlst.remove(x.number)\r\n\t\t\texcept ValueError:\r\n\t\t\t\tpass\r\n\t\tfor x in self.row:\r\n\t\t\ttry:\r\n\t\t\t\tlst.remove(x.number)\r\n\t\t\texcept ValueError:\r\n\t\t\t\tpass\r\n\r\n\t\tself.probabilit = lst\r\n\t\ttwo_two(self.row)\r\n\t\tprint(self.probabilit)\r\n\t\ttwo_two(self.column)\r\n\t\tprint(self.probabilit)\r\n\t\ttwo_two(self.cell)\r\n\t\tprint(self.probabilit)\r\n\t\tsamecell(self.cell)\r\n\t\tprint(self.probabilit)\r\n\t\treturn lst\r\n\r\n\r\n\r\n\tdef __repr__(self):\r\n\t\treturn str(self.number)\r\n\tdef __str__(self):\r\n\t\treturn str(self.number)\r\n\r\n\"\"\"def replace_num(row, numold, numnew):\r\n\tfor x in range(9):\r\n\t\tif row[x].number == numold:\r\n\t\t\trow[x].number = numnew\r\n\treturn row[x]\"\"\"\r\n\r\ndef unique(lst):\r\n\tdic = {}\r\n\tfor p in lst:\r\n\t\tdic[str(p)] = 0\r\n\tfor p in lst:\r\n\t\tdic[str(p)] += 1\r\n\tfor p in lst:\r\n\t\tif dic[str(p)] == 1:\r\n\t\t\treturn p\r\n\treturn False\r\n\r\n\r\n\"\"\"def mathod_a(Sudok):\r\n\tfor x in range(9):\r\n\t\tif Sudok.zero_count()[x] == 1:\r\n\t\t\treplace_num(Sudok.search_row(x), 0, Sudok.fofi_check()[x])\r\n\r\n\treturn Sudok\"\"\"\r\n\r\ndef mathod_b(Sudok):\r\n\tfor x in range(9):\r\n\t\tfor y in range(9):\r\n\t\t\tprint(Sudok.search(x,y).probabilit)\r\n\t\t\tif len(Sudok.search(x,y).probabilit) == 1:\r\n\t\t\t\tprint(\"b\", Sudok.search(x,y).probabilit,Sudok.search(x,y).rown,Sudok.search(x,y).columnn)\r\n\t\t\t\tSudok.search(x,y).number = Sudok.search(x,y).probabilit[0]\r\n\t\t\t\tSudok.search(x,y).probabilit = []\r\n\t\t\tSudok.search(x,y).hard_probability()\r\n\treturn Sudok\r\n\r\ndef mathod_c(Sudok):\r\n\tfor p in Sudok.sheet:\r\n\t\tlst = []\r\n\t\tfor q in p:\r\n\t\t\tif q.number == 0:\r\n\t\t\t\tlst += q.probabilit\r\n\t\tfor q in p:\r\n\t\t\tif unique(lst) in q.probabilit:\r\n\t\t\t\tprint(\"c\", q.probabilit, q.rown, q.columnn)\r\n\t\t\t\tq.number = unique(lst)\r\n\t\t\t\tq.probabilit = []\r\n\t\t\tupdate2(Sudok)\r\n\r\n\treturn Sudok\r\n\r\ndef mathod_d(Sudok):\r\n\tpass\r\n\r\n\r\n#HELPER FUNCTIONS FOR PROBABILIT\r\n\r\ndef two_two(p):\r\n\tfor q in p:\r\n\t\tif len(q.probabilit) == 2:\r\n\t\t\tfor w in p:\r\n\t\t\t\tif w is not q:\r\n\t\t\t\t\tif w.probabilit == q.probabilit:\r\n\t\t\t\t\t\tfor z in p:\r\n\t\t\t\t\t\t\tif z is not w and z is not q:\r\n\t\t\t\t\t\t\t\ttry:\r\n\t\t\t\t\t\t\t\t\tz.probabilit.remove(w.probabilit[0])\r\n\t\t\t\t\t\t\t\t\tz.probabilit.remove(w.probabilit[1])\r\n\t\t\t\t\t\t\t\texcept ValueError:\r\n\t\t\t\t\t\t\t\t\tpass\r\n\r\ndef samecell(cell):\r\n\tfor x in range(1,10):\r\n\t\tlst = []\r\n\t\tfor p in cell:\r\n\t\t\tif x in p.probabilit:\r\n\t\t\t\tlst += [p.rown]\r\n\t\tif lst != [] and sum(lst) == lst[0] * len(lst):\r\n\t\t\tfor q in p.row:\r\n\t\t\t\ttry:\r\n\t\t\t\t\tq.probabilit.remove(x)\r\n\t\t\t\texcept ValueError:\r\n\t\t\t\t\tpass\r\n\r\n\r\n\r\n\r\ndef update(Sudok):\r\n\tfor p in Sudok.sheet:\r\n\t\tfor q in p:\r\n\t\t\tq.infoupdate()\r\n\r\n\r\ndef update2(Sudok):\r\n\tfor p in Sudok.sheet:\r\n\t\tfor q in p:\r\n\t\t\tq.hard_probability()\r\n\r\ndef update2_new(Sudok):\r\n\tfor p in Sudok.sheet:\r\n\t\tfor q in p:\r\n\t\t\tq.probability()\r\n\tfor p in Sudok.sheet:\r\n\t\ttwo_two(p)\r\n\tfor q in Sudok.columns().sheet:\r\n\t\ttwo_two(q)\r\n\tfor z in Sudok.cells().sheet:\r\n\t\ttwo_two(z)\r\n\t\tsamecell(z)\r\n\r\n\r\ndef solve(Sudok):\r\n\tupdate(Sudok)\r\n\tupdate2(Sudok)\r\n\tSudok.show()\r\n\tprint(0)\r\n\tfor _ in range(3):\r\n\t\t#mathod_a(Sudok)\r\n\t\t#mathod_a(Sudok.columns())\r\n\t\t#mathod_a(Sudok.cells())\r\n\t\tmathod_b(Sudok)\r\n\t\tSudok.show()\r\n\t\tprint(0)\r\n\t\tmathod_c(Sudok)\r\n\t\tSudok.show()\r\n\t\tprint(0)\r\n\t\tmathod_c(Sudok.columns())\r\n\t\tSudok.show()\r\n\t\tprint(0)\r\n\t\tmathod_c(Sudok.cells())\r\n\t\tSudok.show()\r\n\t\tprint(0)\r\n\t\tupdate(Sudok)\r\n\t\tupdate2(Sudok)\r\n\treturn Sudok\r\n\r\n\r\n\t\t\r\n\r\n","sub_path":"sudoku.py","file_name":"sudoku.py","file_ext":"py","file_size_in_byte":6739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"603828677","text":"\"\"\"Distutils setup file\"\"\"\nimport textwrap\n\nfrom setuptools import setup, find_packages\n\nwith open('README.rst') as f_readme:\n readme = f_readme.read()\n\nsetup(\n name='buildpipe',\n description='Dynamically generate Buildkite pipelines',\n long_description=readme,\n packages=find_packages(exclude=['tests', 'examples']),\n use_scm_version=True,\n author='Kamil Sindi',\n author_email='ksindi@ksindi.com',\n url='https://github.com/ksindi/buildpipe',\n keywords='pipeline buildkite cicd'.split(),\n license='MIT',\n install_requires=[\n 'jsonschema>=2.6.0',\n 'ruamel.yaml>=0.16.5',\n 'python-box>=4.0.1',\n 'pytz>=2017.2',\n ],\n setup_requires=[\n 'pytest-runner',\n 'setuptools_scm',\n 'sphinx_rtd_theme',\n ],\n tests_require=[\n 'freezegun',\n 'pytest',\n 'pytest-cov',\n 'pytest-flake8',\n ],\n include_package_data=True,\n zip_safe=False,\n entry_points={\n 'console_scripts': [\n 'buildpipe=buildpipe.__main__:main'\n ]\n },\n classifiers=textwrap.dedent(\"\"\"\n Development Status :: 5 - Production/Stable\n Intended Audience :: Developers\n License :: OSI Approved :: MIT License\n Environment :: Console\n Programming Language :: Python :: 3\n Programming Language :: Python :: 3.6\n Programming Language :: Python :: 3.7\n \"\"\").strip().splitlines(),\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"241520165","text":"import json, requests\n\nENDPOINT = 'https://swapi.co/api'\n\nPEOPLE_KEYS = (\"url\", \"name\", \"height\", \"mass\", \"hair_color\", \"skin_color\", \"eye_color\", \"birth_year\", \"gender\", \"homeworld\", \"species\",)\nPLANETS_KEYS = (\"url\", \"name\", \"rotation_period\", \"orbital_period\", \"diameter\", \"climate\", \"gravity\", \"terrain\", \"surface_water\", \"population\", \"indigenous_life_forms\",)\nSTARSHIP_KEYS = (\"url\", \"starship_class\", \"name\", \"model\", \"manufacturer\", \"length\", \"width\", \"max_atmosphering_speed\", \"hyperdrive_rating\", \"MGLT\", \"crew\", \"passengers\", \"cargo_capactiy\", \"consumables\", \"armament\",)\nSPECIES_KEYS = (\"url\", \"name\", \"classification\", \"designation\", \"average_height\", \"skin_colors\", \"hair_colors\", \"eye_colors\", \"average_lifespan\", \"language\",)\nVEHICLES_KEYS = (\"url\", \"vehicle_class\", \"name\", \"model\", \"manufacturer\", \"length\", \"max_atmosphering_speed\", \"crew\", \"passengers\", \"cargo_capacity\", \"consumables\", \"armament\",)\n\n\ndef read_json(filepath):\n \"\"\"Given a valid filepath, reads a JSON document and returns a dictionary.\n\n Parameters:\n filepath (str): path to file.\n\n Returns:\n dict: decoded JSON document expressed as a dictionary.\n \"\"\"\n\n with open(filepath, 'r', encoding='utf-8') as file_obj:\n data = json.load(file_obj)\n\n return data\n\ndef get_swapi_resource(url, params=None):\n \"\"\"Issues an HTTP GET request to return a representation of a resource. If no category is\n provided, the root resource will be returned. An optional query string of key:value pairs\n may be provided as search terms (e.g., {'search': 'yoda'}). If a match is achieved the\n JSON object that is returned will include a list property named 'results' that contains the\n resource(s) matched by the search query.\n\n Parameters:\n url (str): a url that specifies the resource.\n params (dict): optional dictionary of querystring arguments.\n\n Returns:\n dict: decoded JSON document expressed as dictionary.\n \"\"\"\n\n if params:\n response = requests.get(url, params=params).json()\n else:\n response = requests.get(url).json()\n\n return response\n\ndef combine_data(default_data, override_data):\n \"\"\"Creates a shallow copy of the default dictionary and then updates the new\n copy with override data. Override values will replace default values when if\n the keys match.\n\n For shallow vs deep copying of mutable objects like dictionaries and lists see:\n https://docs.python.org/3/library/copy.html\n\n For another approach see unpacking, see: https://www.python.org/dev/peps/pep-0448/\n\n Parameters:\n default_data (dict): entity data that provides the default representation of the object.\n override_data (dict): entity data intended to override matching default values.\n\n Returns:\n dict: updated dictionary that contains override values.\n\n \"\"\"\n\n combined_data = default_data.copy() # shallow\n # combined_data = copy.copy(default_data) # shallow\n # combined_data = copy.deepcopy(default_data) # deep\n combined_data.update(override_data) # in place\n\n # Dictionary unpacking\n # combined_data = {**default_data, **override_data}\n\n return combined_data\n\ndef filter_data(data, filter_keys):\n \"\"\"Returns a new dictionary based containing a filtered subset of key-value pairs\n sourced from a dictionary provided by the caller.\n\n Parameters:\n data (dict): source entity.\n filter_keys (tuple): sequence of keys used to select a subset of key-value pairs.\n\n Returns:\n dict: a new entity containing a subset of the source entity's key-value pairs.\n\n \"\"\"\n\n # Alternative: dictionary comprehension (post-Thanksgiving discussion)\n # return {key: data[key] for key in filter_keys if key in data.keys()}\n\n record = {}\n for key in filter_keys:\n if key in data.keys():\n record[key] = data[key]\n\n return record\n\ndef is_unknown(value):\n \"\"\"\n Determines whether the value is unknown or n/a using a Truth test.\n\n Parameters:\n Value (str): a string that is evaluated for being unknown or n/a.\n\n Returns:\n Boolean: returns True is the string is unknown or n/a. Otherwise returns the value entered.\n \"\"\"\n if type(value) == str:\n value = value.lower().strip()\n if value == \"unknown\":\n return True\n elif value == \"n/a\":\n return True\n else:\n return False\n\ndef convert_string_to_float(value):\n \"\"\"\n Converts a string to a float.\n\n Parameters:\n A string.\n\n Returns:\n Returns the converted string as a float, if the function works.\n Otherwise spits whatever was entered back out.\n \"\"\"\n try:\n return float(value)\n except ValueError:\n return value\n\ndef convert_string_to_int(value):\n \"\"\"\n Converts a string into an integer.\n\n Parameters:\n A string.\n\n Returns:\n Returns the converted string as an integer, if the function works.\n Otherwise spits whatever was entered back atcha.\n\n \"\"\"\n try:\n return int(value)\n except ValueError:\n return value\n\ndef convert_string_to_list(value, delimiter=', '):\n \"\"\"\n Converts a string to a list.\n\n Parameters:\n Value (str): a string.\n Delimiter: default assignment of the delimiter as a comma, \",\".\n\n Returns:\n List: a string converted into a list.\n \"\"\"\n new_list = value.split(delimiter)\n return new_list\n\n#silly_dict = {'name': 'jumbo', 'mass': '165 lb', 'gravity': 'life, is, so, great ', 'climate': [\"wet\", \"dry\", \"swampy\"], 'family': 'Unknown', 'IQ': 10}\n\ndef clean_data(entity):\n \"\"\"\n Converts string values to appropriate types (float, int, list, None). Manages property\n checks with tuples of named keys.\n\n Parameters:\n planet (dict): dictionary with values to be cleaned.\n\n Returns:\n dict: dictionary with cleaned values.\n \"\"\"\n i = (\n \"height\", \n \"mass\", \n \"rotation_period\", \n \"orbital_period\", \n \"diameter\",\n \"surface_water\", \n \"population\",\n \"average_height\",\n \"average_lifespan\",\n \"max_atmosphering_speed\",\n \"MGLT\",\n \"crew\",\n \"passengers\",\n \"cargo_capacity\",\n )\n f = (\n \"gravity\",\n \"length\",\n \"hyperdrive_rating\",\n )\n l = (\n \"hair_color\",\n \"skin_color\",\n \"climate\",\n \"terrain\",\n \"skin_colors\",\n \"hair_colors\",\n \"eye_colors\",\n )\n d = (\"homeworld\", \"species\",)\n\n new_dict = {}\n\n for key,value in entity.items(): # loops through keys and values of given dictionary\n if is_unknown(value): # checks if the value is unknown or n/a\n new_dict[key] = None # converts value to None if true\n elif key in i: # if the entity key is in our i tuple\n new_dict[key] = convert_string_to_int(value) # we convert the string to an int and add it to our new dictionary\n elif key in f: # if the entity key is in our f tuple\n temp_list = value.split(\" \") # we make a temporary list where we split the value on whitespace\n new_dict[key] = convert_string_to_float(temp_list[0]) # we convert the value to a float and take the first item from the list and add it to our new dict\n elif key in l: # if the entity key is in our l tuple\n value = value.strip()\n new_dict[key] = convert_string_to_list(value) # we convert the string into a list and add it to our new dictionary\n elif key in d: # if the entity key is in our d tuple\n if key == \"homeworld\": # if the key is homeworld\n entity = get_swapi_resource(value) # assign the entity entered to what get_swapi produces (which I don't really know)\n filtered_dict = filter_data(entity, PLANETS_KEYS) # create a new dictionary with just the key values of the tuple we use\n done = clean_data(filtered_dict) # clean the data (i.e. convert items) from that dict using clean_data, assign it to a temp variable\n new_dict[key] = done # assign our new dictionary to the temp variable\n elif key == \"species\": # if the key is species\n entity = get_swapi_resource(value[0]) # assign the entity entered to what get_swapi produces (which I don't really know)\n filtered_dict = filter_data(entity, SPECIES_KEYS) # create a new dictionary with just the key values of the tuple we use\n done = clean_data(filtered_dict) # clean the data (i.e. convert items) from that dict using clean_data, assign it to a temp variable\n new_dict[key] = [done] # assign our new dictionary to the temp variable\n else:\n new_dict[key] = value # if none of the above applies, just maintain the format of the entity\n\n return new_dict # return the new dicionary\n\n#print(clean_data(silly_dict))\n\ndef assign_crew(starship, crew):\n \"\"\"blah blah blah.\n\n Parameters:\n None.\n\n Returns:\n None.\n\n \"\"\"\n for key,value in crew.items():\n starship[key] = value\n return starship\n\ndef write_json(filepath, data):\n \"\"\"Given a valid filepath, write data to a JSON file.\n\n Parameters:\n filepath (str): the path to the file.\n data (dict): the data to be encoded as JSON and written to the file.\n\n Returns:\n None\n \"\"\"\n with open(filepath, 'w', encoding='utf-8') as file_obj:\n json.dump(data, file_obj, ensure_ascii=False, indent=2)\n\n# copy and paste from lecture25.py into main\ndef main():\n \"\"\"blah blah blah.\n\n Parameters:\n None.\n\n Returns:\n None.\n\n \"\"\"\n \n planets_data = read_json(\"swapi_planets-v1p0.json\")\n \n uninhabited_planets = []\n\n for planet in planets_data:\n if is_unknown(planet['population']) == True:\n dictionary = filter_data(planet, PLANETS_KEYS)\n uninhabited_planets.append(clean_data(dictionary))\n \n write_json(\"swapi_planets_uninhabited-v1p1.json\", uninhabited_planets)\n\n # grab hoth representations\n echo_base = read_json(\"swapi_echo_base-v1p0.json\")\n swapi_hoth = get_swapi_resource('https://swapi.co/api/planets/4/')\n\n\n echo_base_hoth = echo_base['location']['planet']\n hoth = combine_data(echo_base_hoth, swapi_hoth)\n hoth = filter_data(hoth, PLANETS_KEYS)\n hoth = clean_data(hoth)\n echo_base['location']['planet'] = hoth\n\n #echo base commander \n echo_base_commander = echo_base['garrison']['commander']\n echo_base_commander = clean_data(echo_base_commander)\n echo_base['garrison']['commander'] = echo_base_commander\n\n echo_base_commander = echo_base['visiting_starships']['freighters']\n echo_base_commander = clean_data(echo_base_commander)\n echo_base['visiting_starships']['freighters'] = echo_base_commander\n\n # vehicles\n swapi_vehicles_url = f\"{ENDPOINT}/vehicles/\"\n swapi_snowspeeder = get_swapi_resource(swapi_vehicles_url, {'search': 'snowspeeder'})['results'][0]\n\n # echo base snowspeeder\n echo_base_snowspeeder = echo_base['vehicle_assets']['snowspeeders'][0]['type']\n\n snowspeeder = combine_data(echo_base_snowspeeder, swapi_snowspeeder)\n snowspeeder = filter_data(snowspeeder, VEHICLES_KEYS)\n snowspeeder = clean_data(snowspeeder)\n echo_base['vehicle_assets']['snowspeeders'][0]['type'] = snowspeeder\n\n # starships\n swapi_starships_url = f\"{ENDPOINT}/starships/\"\n\n # x-wing\n echo_base_x_wing = get_swapi_resource(swapi_starships_url, {'search': 'T-65 X-wing'})['results'][0]\n echo_base_model = echo_base['starship_assets']['starfighters'][0]['type']\n \n x_wing_model = combine_data(echo_base_x_wing, echo_base_model)\n x_wing_model = filter_data(x_wing_model, STARSHIP_KEYS)\n x_wing_model = clean_data(x_wing_model)\n echo_base['starship_assets']['starfighters'][0]['type'] = x_wing_model\n\n # gr_75\n gr_75 = get_swapi_resource(swapi_starships_url, {'search': 'GR-75 medium transport'})['results'][0]\n echo_base_gr_75 = echo_base['starship_assets']['transports'][0]['type']\n\n gr_75_model = combine_data(gr_75, echo_base_gr_75)\n gr_75_model = filter_data(gr_75_model, STARSHIP_KEYS)\n gr_75_model = clean_data(gr_75_model)\n echo_base['starship_assets']['transports'][0]['type'] = gr_75_model\n\n # millennium falcon\n m_falcon = get_swapi_resource(swapi_starships_url, {'search': 'GR-75 medium transport'})['results'][0]\n echo_base_m_falcon = echo_base['visiting_starships']['freighters'][0]['type']\n\n falcon_model = combine_data(m_falcon, echo_base_m_falcon)\n falcon_model = filter_data(falcon_model, STARSHIP_KEYS)\n falcon_model = clean_data(falcon_model)\n echo_base['visiting_starships']['freighters'][0]['type'] = falcon_model\n\n # people\n swapi_people_url = f\"{ENDPOINT}/people/\"\n\n # han\n han = get_swapi_resource(swapi_people_url, {'search': 'han solo'})['results'][0]\n han = filter_data(han, PEOPLE_KEYS)\n han = clean_data(han)\n\n # chewbacca\n chewers = get_swapi_resource(swapi_people_url, {'search': 'Chewbacca'})['results'][0]\n chewers = filter_data(chewers, PEOPLE_KEYS)\n chewers = clean_data(chewers)\n\n combine_falcon = assign_crew(falcon_model, {'pilot': han, 'copilot': chewers})\n\n\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"final_proj/swapi_final.py","file_name":"swapi_final.py","file_ext":"py","file_size_in_byte":13309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"60370644","text":"from discord.ext import commands\nimport discord\nfrom .objects import game\nimport contextlib\nfrom utils import checks\nfrom utils.miniutils.data import json\nfrom utils.miniutils.minidiscord import input\nimport asyncio\nimport os\nfrom . import errors\nimport typing\nimport flag\n\ndefault_lang = \"gb\"\n\n\ndef allow_runs(ctx):\n if not ctx.bot.allow_running_cah_games:\n raise errors.Development(\"Unfortunately I'm in development mode right now, come back later\")\n return True\n\n\ndef no_cah_in_channel(ctx):\n if ctx.bot.running_cah_game_objects.get(ctx.channel, None) is not None:\n raise errors.GameExists(\"There's already a game in this channel. Try ending it first?\")\n return True\n\n\n# noinspection DuplicatedCode\nclass CAH(commands.Cog):\n def __init__(self, bot):\n self.languages = json.Json(\"languages\")\n self.bot = bot\n try:\n bot.running_cah_games\n except AttributeError:\n bot.set(\n \"running_cah_games\",\n 0\n )\n try:\n bot.allow_running_cah_games\n except AttributeError:\n bot.set(\n \"allow_running_cah_games\",\n True\n )\n try:\n bot.running_cah_game_objects\n except AttributeError:\n bot.set(\n \"running_cah_game_objects\",\n {}\n )\n self._load_packs()\n\n @commands.command(aliases=[\"reloadpacks\", \"rpacks\"])\n @commands.check(checks.bot_mod)\n async def loadpacks(self, ctx):\n \"\"\"Reloads all packs.\n \"\"\"\n self._load_packs()\n await ctx.send(\n \"I've reloaded all the packs\",\n title=f\"{ctx.bot.emotes['success']} Complete!\",\n color=ctx.bot.colors[\"info\"]\n )\n\n @commands.command(aliases=[\"language\", \"lang\", \"setlang\"])\n async def setlanguage(self, ctx):\n \"\"\"Set what language you want to use for your packs.\n \"\"\"\n languages = {\n \"gb\": \"English\",\n \"es\": \"Español\",\n \"fr\": \"Français\",\n \"de\": \"Deutsch\",\n \"ru\": \"русский\",\n \"ua\": \"Українська\",\n \"nl\": \"Nederlands\",\n \"pt\": \"Português\"\n }\n supported = \"**Already supported:**\"\n for language in self.bot.cah_packs:\n supported += f\"\\n:flag_{language}: {languages.get(language, 'Unknown')}\"\n soon = \"||**Coming Soon:**\"\n for language, name in languages.items():\n if language not in self.bot.cah_packs:\n soon += f\"\\n:flag_{language}: {name}\"\n language = self.languages.read_key(ctx.guild.id) if ctx.guild else None\n title = f\"{self.bot.emotes['choice']} All available languages:\"\n if language is not None:\n title += f\" (You currently have your language set to :flag_{language}:)\"\n if ctx.channel.permissions_for(ctx.author).manage_guild:\n menu = input.Menu(\n self.bot,\n callbacks=False\n ) # Create our reaction menu\n for language in self.bot.cah_packs:\n menu.add(flag.flag(language))\n msg = await ctx.send(\n supported + \"\\n\\n\" + soon + \"||\\n\\n*Select a flag below (or say it in chat) to set it as the default \"\n \"language for this server*\",\n title=title\n )\n try:\n emote = flag.dflagize(\n await menu(\n msg,\n ctx.author\n )\n )[1:-1].lower()\n self.languages.save_key(ctx.guild.id, emote)\n await ctx.send(\n \"We've successfully changed your language\",\n title=f\":flag_{emote}: Language changed\"\n )\n except asyncio.TimeoutError:\n pass\n finally:\n with contextlib.suppress(discord.NotFound):\n await msg.delete()\n else:\n await ctx.send(\n supported + \"\\n\\n\" + soon + \"||\",\n title=title\n )\n\n @commands.command(aliases=[\"listpacks\", \"list\"])\n async def packs(self, ctx):\n \"\"\"Shows a list of packs available in your language.\n \"\"\"\n lang = (self.languages.read_key(ctx.guild.id) if ctx.guild else None) or default_lang\n\n packs = \"*Language switching is currently in beta while we wait on our translators and give the commands a \" \\\n \"good test*\"\n\n lang_packs = self.bot.cah_packs.get(lang, None)\n if not lang_packs:\n lang = default_lang\n lang_packs = self.bot.cah_packs.get(lang, None)\n\n for pack in lang_packs[\"packs\"]:\n if pack.endswith(\"w\"):\n packs += f\"\\n~ **{pack[:-1]}** - {lang_packs['descriptions'].get(pack[:-1], 'No description found')}\"\n\n await ctx.send(\n packs,\n title=f\":flag_{lang}: All the packs available for your language\",\n paginate_by=\"\\n\",\n color=ctx.bot.colors[\"info\"]\n )\n\n def _load_packs(self):\n packs = {}\n for path, _, files in os.walk(\"packs\"):\n lang = path.replace(\"\\\\\", \"/\").split(\"/\")[-1]\n if files:\n lang_packs = {\n \"packs\": {},\n \"descriptions\": {}\n }\n for pack in sorted(files):\n with open(os.path.join(path, pack)) as file:\n if pack == \"-descriptions.txt\":\n descriptions = [\n desc.strip().split(\n \":\", 1\n ) for desc in file.readlines() if len(desc.strip().split(\n \":\", 1\n ))\n ]\n lang_packs[\"descriptions\"] = dict(descriptions)\n pack_name = \".\".join(pack.split(\".\")[:-1])\n lang_packs[\"packs\"][pack_name] = [card.strip() for card in file.readlines()]\n packs[lang] = lang_packs\n self.bot.set(\n \"cah_packs\",\n packs\n )\n self.bot.set(\n \"cah_answer_data\",\n self.bot.AIAnswerStore.load_data()\n )\n self.bot.set(\n \"cah_question_data\",\n self.bot.AIQuestionStore.load_data()\n )\n\n @commands.command(aliases=[\"start\"])\n @commands.check(no_cah_in_channel)\n @commands.check(checks.bypass_check(allow_runs))\n @commands.guild_only()\n async def play(self, ctx, advanced: typing.Optional[bool] = False, whitelist: commands.Greedy[discord.Member] = ()):\n \"\"\"Starts the game.\n `%%play` will start a game, and allow players to join using the %%join command, or do %%play True for even more\n game options.\n \"\"\"\n self.bot.running_cah_games += 1\n try:\n _game = game.Game(\n context=ctx,\n advanced_setup=advanced,\n whitelist=whitelist,\n lang=(self.languages.read_key(ctx.guild.id) if ctx.guild else None) or default_lang\n )\n self.bot.running_cah_game_objects[ctx.channel] = _game\n with contextlib.suppress(asyncio.CancelledError):\n _game.coro = asyncio.create_task(_game.setup())\n if await _game.coro:\n await _game.begin()\n except Exception as e:\n raise e\n finally:\n with contextlib.suppress(Exception):\n del self.bot.running_cah_game_objects[ctx.channel]\n self.bot.running_cah_games -= 1\n if self.bot.running_cah_games < 0:\n self.bot.running_cah_games = 0\n self.bot.running_cah_game_objects[\"Less than 0 games found\"] = \"Please find out why this happened\"\n\n @commands.command()\n @commands.guild_only()\n @commands.max_concurrency(1, commands.BucketType.channel, wait=True)\n async def join(self, ctx):\n \"\"\"Joins an active game in the channel. This can be during the 1m period when starting a game, or midway through\n \"\"\"\n _game = self.bot.running_cah_game_objects.get(ctx.channel, None)\n if _game is None:\n return await ctx.send(\n \"There doesn't seem to be a game in this channel\",\n title=f\"{ctx.bot.emotes['valueerror']} No game\",\n color=ctx.bot.colors[\"error\"]\n )\n if _game.whitelisted_players and ctx.author not in _game.whitelisted_players:\n return await ctx.send(\n \"You aren't whitelisted so you can't join this game\",\n title=f\"{ctx.bot.emotes['valueerror']} Couldn't join...\",\n color=ctx.bot.colors[\"error\"]\n )\n if len(_game.players) >= _game.maximumPlayers:\n return await ctx.send(\n f\"For safe social distancing we can't have more than {_game.maximumPlayers} in this game\",\n # TODO: ^ Change this when corona becomes irrelevant\n title=f\"{ctx.bot.emotes['valueerror']} It's a bit busy round here...\",\n color=ctx.bot.colors[\"error\"]\n )\n if any(_player == ctx.author for _player in _game.players):\n return await ctx.send(\n f\"You're already in this game, I haven't added you but you're still in there anyway...\",\n title=f\"{ctx.bot.emotes['valueerror']} *Confused applause*\",\n color=ctx.bot.colors[\"error\"]\n )\n if _game.joined:\n await _game.add_player(ctx.author)\n\n @commands.command(aliases=[\"leave\"])\n @commands.guild_only()\n @commands.max_concurrency(1, commands.BucketType.channel)\n async def exit(self, ctx):\n \"\"\"Removes the player who ran it from the current game in that channel.\n \"\"\"\n _game = self.bot.running_cah_game_objects.get(ctx.channel, None)\n if _game is None:\n return await ctx.send(\n \"There doesn't seem to be a game in this channel\",\n title=f\"{ctx.bot.emotes['valueerror']} No game\",\n color=ctx.bot.colors[\"error\"]\n )\n if not _game.chosen_options:\n return await ctx.send(\n \"This game isn't setup yet\",\n title=f\"{ctx.bot.emotes['valueerror']} I'm not ready yet...\",\n color=ctx.bot.colors[\"error\"]\n )\n for player in _game.players:\n if player == ctx.author:\n await player.quit()\n break\n else:\n return await ctx.send(\n f\"You're not in this game... I couldn't remove you but I guess that doesn't matter much\",\n title=f\"{ctx.bot.emotes['valueerror']} *Confused applause*\",\n color=ctx.bot.colors[\"error\"]\n )\n\n @commands.command(aliases=[\"mulligan\"])\n @commands.guild_only()\n @commands.max_concurrency(1, commands.BucketType.channel)\n async def shuffle(self, ctx):\n \"\"\"Reshuffles your cards\n \"\"\"\n _game = self.bot.running_cah_game_objects.get(ctx.channel, None)\n if _game is None:\n return await ctx.send(\n \"There doesn't seem to be a game in this channel\",\n title=f\"{ctx.bot.emotes['valueerror']} No game\",\n color=ctx.bot.colors[\"error\"]\n )\n if not _game.chosen_options:\n return await ctx.send(\n \"This game isn't setup yet\",\n title=f\"{ctx.bot.emotes['valueerror']} I'm not ready yet...\",\n color=ctx.bot.colors[\"error\"]\n )\n for player in _game.players:\n if player == ctx.author:\n await player.shuffle(ctx)\n break\n else:\n return await ctx.send(\n f\"You're not in this game. Not only can I not shuffle your cards: you don't even have any cards to \"\n f\"shuffle\",\n title=f\"{ctx.bot.emotes['valueerror']} *Not sure what's going on here...*\",\n color=ctx.bot.colors[\"error\"]\n )\n\n @commands.command()\n @commands.guild_only()\n async def end(self, ctx, instantly: typing.Optional[bool] = False):\n \"\"\"Ends the current game in that channel.\n \"\"\"\n old_game = self.bot.running_cah_game_objects.get(ctx.channel, None)\n if old_game is not None:\n if not (ctx.author.permissions_in(ctx.channel).manage_channels or ctx.author == old_game.context.author):\n return await ctx.send(\n \"You didn't start this game, and you can't manage this channel\",\n title=f\"{ctx.bot.emotes['valueerror']} You don't have permission to do that\",\n color=ctx.bot.colors[\"error\"]\n )\n with contextlib.suppress(Exception):\n del self.bot.running_cah_game_objects[ctx.channel]\n await old_game.end(instantly=instantly)\n else:\n await ctx.send(\n \"Has it already been ended?\",\n title=f\"{ctx.bot.emotes['valueerror']} We couldn't find a game in this channel...\",\n color=ctx.bot.colors[\"error\"]\n )\n\n @commands.command()\n @commands.guild_only()\n @commands.check(checks.bot_mod)\n async def setmaxplayers(self, ctx, new_max=25):\n \"\"\"Set the maximum player count of the game. Can only be used in setup and when players are joining\n \"\"\"\n _game = self.bot.running_cah_game_objects.get(ctx.channel, None)\n if _game is None:\n return await ctx.send(\n \"Did you mean another channel?\",\n title=f\"{ctx.bot.emotes['valueerror']} We couldn't find a game in this channel...\",\n color=ctx.bot.colors[\"error\"]\n )\n _game.maximumPlayers = new_max\n _game.players = _game.players[:new_max]\n if new_max < _game.minimumPlayers:\n return await ctx.send(\n f\"The minimum minimum player count is {_game.minimumPlayers}\",\n title=f\"{ctx.bot.emotes['valueerror']} Bit to small...\",\n color=ctx.bot.colors['error']\n )\n if _game.chosen_options:\n return await ctx.send(\n f\"This command can only be used before players are given the option to join\",\n title=f\"{ctx.bot.emotes['valueerror']} You're too late\",\n color=ctx.bot.colors['error']\n )\n await ctx.send(\n f\"We've set the player limit on this game to {new_max} and kicked out any players who bring the game over \"\n f\"that limit\",\n title=f\"{ctx.bot.emotes['success']} Great!\",\n color=ctx.bot.colors['status']\n )\n\n @commands.command(aliases=[\"bc\", \"sall\"])\n @commands.check(checks.is_owner)\n async def broadcast(self, ctx, nostart: typing.Optional[bool] = True, *, message):\n \"\"\"Broadcasts a message to every currently active game channel.\n \"\"\"\n if nostart:\n self.bot.allow_running_cah_games = False\n await self.bot.change_presence(\n status=discord.Status.dnd,\n activity=discord.Activity(\n name=\"my developers in maintenance mode\",\n type=discord.ActivityType.listening,\n )\n )\n for _game in self.bot.running_cah_game_objects.values():\n with contextlib.suppress(Exception):\n await _game.context.send(\n message,\n title=\"Developer broadcast - Because you're playing CAH here...\",\n color=ctx.bot.colors[\"dev\"]\n )\n await ctx.send(\n message,\n title=\"Sent to every server currently ingame...\"\n )\n\n @commands.command(aliases=[\"denystart\", \"stopstart\"])\n @commands.check(checks.is_owner)\n async def nostart(self, ctx, end: typing.Optional[bool] = False, instantly: typing.Optional[bool] = False):\n \"\"\"Stops games from being played\n \"\"\"\n self.bot.allow_running_cah_games = False\n await self.bot.change_presence(\n status=discord.Status.dnd,\n activity=discord.Activity(\n name=\"my developers in maintenance mode\",\n type=discord.ActivityType.listening,\n )\n )\n if end:\n for _game in list(self.bot.running_cah_game_objects.values()):\n with contextlib.suppress(Exception):\n await _game.end(\n instantly=instantly,\n reason=\"the bot is going into development mode...\"\n )\n await ctx.send(\n (\n f\"Old games {'have ended' if instantly else 'will end after the current round'}\"\n if end else \"Old games will continue to run their course\"\n ),\n title=\"Stopped new games from being started\"\n )\n\n @commands.command(aliases=[\"allowstart\", \"startstart\", 'yestart'])\n @commands.check(checks.is_owner)\n async def yesstart(self, ctx):\n \"\"\"Allows games to be started.\n \"\"\"\n self.bot.allow_running_cah_games = True\n await self.bot.change_presence(\n status=discord.Status.online,\n activity=discord.Activity(\n name=\"your games of CAH\",\n type=discord.ActivityType.watching,\n )\n )\n await ctx.send(\n \"Games can be started again\",\n title=\"Action complete!\"\n )\n\n\ndef setup(bot):\n errors.setup_handlers(bot.error_handler)\n bot.add_cog(CAH(bot))\n","sub_path":"cogs/cah/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":17952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"200840584","text":"#coding:utf-8\n\nimport json\nimport xlrd\nimport xlwt\nfrom handler.base import BaseHandler\nfrom utils.usual import parse_argument, login_required, FixedForm\nfrom wtforms.fields import StringField\nfrom wtforms.validators import Required\nfrom StringIO import StringIO\nfrom common.settings import TPNScheme, GLOBALS\n\n\nclass UserTemplateHandler(BaseHandler):\n class GetForm(FixedForm):\n location = StringField(validators=[Required()])\n @login_required\n @parse_argument(GetForm)\n def get(self):\n _location = self.arguments['location'].encode('utf-8')\n schemes = json.loads(self.session.query(TPNScheme).get(_location).scheme)\n wb = xlwt.Workbook()\n ws = wb.add_sheet('sheet 1')\n for i in range(len(schemes)):\n ws.write(0, i, schemes[i]['title'])\n output = StringIO()\n wb.save(output)\n self.set_header('Content-Type', 'application/vnd.ms-excel')\n self.finish(output.getvalue())\n\n\n class PostForm(FixedForm):\n location = StringField(validators=[Required()])\n @login_required\n @parse_argument(PostForm)\n def post(self):\n metas = self.request.files['uploadfile']\n for meta in metas:\n content = meta['body']\n book = xlrd.open_workbook(file_contents=content)\n sh = book.sheet_by_index(0)\n _location = self.arguments['location']\n pn = int(_location.split(',')[-1])\n TPNUser = GLOBALS['base'].classes.__getattr__('pn_{}'.format(pn))\n schemes = json.loads(self.session.query(TPNScheme).get(_location).scheme)\n params = []\n for rx in range(1, sh.nrows):\n row = sh.row_values(rx)\n p = {}\n for i , v in enumerate(row):\n if schemes[i]['type'] == 'string' and (isinstance(v, float) or isinstance(v, int)):\n v = str(v)\n if '.' in v:\n v = ''.join(list(v)[:v.find('.')])\n elif schemes[i]['type'] == 'int':\n v = int(v)\n p.update({schemes[i]['column']: v})\n params.append(TPNUser(**p))\n if params:\n self.session.add_all(params)\n self.session.commit()\n res = {'code': 200}\n self.finish(json.dumps(res))\n","sub_path":"core/handler/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"127852091","text":"import datetime\nimport json\n\nimport redis\n\nimport easytrader\nimport tushare as ts\nfrom bbi_strategy import get_bbi_match_3\nfrom strategies.StrategyBase import StrategyBase\nfrom utils.wx_msg import send_msg, APP_ID_报告\n\n\ndef can_sell(is_st, settlement, price):\n \"\"\"ST股每日涨跌上限5%\"\"\"\n p = (price - settlement) / settlement * 100\n return p < 4.5 if is_st else p < 9\n\n\nclass BBI(StrategyBase):\n \"\"\"大概年化320%\"\"\"\n name = 'bbi'\n\n HOLD_DAYS = 17 # 最大持股天数\n ZHISUN_RATE = -.15 # 跌破15%止损\n HOLD_RATE = .05 # 5%算盈利\n ZHIYING_RATE = -.04 # 回撤4%止盈\n\n user = None\n redis_conn = None\n date = None\n quote = None\n\n send_msg = False\n\n def __init__(self, user=None, redis_conn=None, send_msg=False):\n self.quote = None\n if user is not None:\n self.user = user\n else:\n self.user = easytrader.use('yh')\n self.user.prepare('../easytrader/yh.json')\n\n if redis_conn is not None:\n self.redis_conn = redis_conn\n else:\n self.redis_conn = redis.Redis(db=1)\n\n self.send_msg = send_msg\n\n def selector(self, date):\n return get_bbi_match_3(date)\n\n def pre_open(self):\n self.date = None\n\n def open(self):\n \"\"\"开盘买入或者调仓\"\"\"\n\n # 空仓,开盘买入\n candidate = self.get_info('candidate')\n positions = self.user.position\n if len(positions) == 0 and len(candidate) > 0:\n code = candidate[0]\n quote = self.get_quote(code)\n if quote:\n bid = quote['bid']\n self.buy(code, bid)\n\n # 更新持股天数,调仓\n info = self.get_info('position')\n for position in positions:\n code = position['stock_code']\n c = info[code]\n if c['buy_date'] != self.get_date():\n c['days'] += 1\n\n # 持仓结束,卖出\n if position['enable_amount'] > 0:\n is_st = self.is_st(position['stock_name'])\n quote = self.get_quote(code)\n if quote:\n if c['days'] >= self.HOLD_DAYS and c['profit'] < self.HOLD_RATE \\\n and can_sell(is_st, quote['pre_close'], quote['price']):\n self.sell(position, quote['ask'])\n del info[code]\n\n self.set_info('position', info)\n\n def tick(self):\n \"\"\"间隔一段时间执行一遍\"\"\"\n positions = self.user.position\n info = self.get_info('position')\n for position in positions:\n if position['enable_amount'] > 0:\n code = position['stock_code']\n quote = self.get_quote(code)\n if quote:\n price = quote['price']\n\n c = info[code]\n is_st = self.is_st(position['stock_name'])\n\n # 止盈\n if c['high'] > 0:\n diff_high = (price - c['high']) / c['high']\n if diff_high < self.ZHIYING_RATE and can_sell(is_st, quote['pre_close'], quote['price']):\n self.sell(position, quote['ask'])\n\n # 止损\n p = (price - c['buy_price']) / c['buy_price']\n if p < self.ZHISUN_RATE and can_sell(is_st, quote['pre_close'], quote['price']):\n self.sell(position, quote['ask'])\n\n def close(self):\n positions = self.user.position\n info = self.get_info('position')\n for position in positions:\n code = position['stock_code']\n quote = self.get_quote(code)\n if quote:\n info[code]['profit'] = (quote['price'] - info[code]['buy_price']) / info[code]['buy_price']\n info[code]['profit'] = round(info[code]['profit'], 3)\n if info[code]['profit'] > self.HOLD_RATE: # 达到一定标准才算盈利,有盈利才有止盈,否则只有止损\n info[code]['high'] = max(info[code]['high'], quote['high']) # 更新最高收益\n\n self.set_info('position', info)\n\n def after_close(self):\n \"\"\"选股\"\"\"\n date = self.get_date()\n code = self.selector(date)\n candidate = [code] if code else []\n self.set_info('candidate', candidate)\n\n self.mail_to('选股{}'.format(date), json.dumps(candidate))\n\n def get_info(self, key):\n \"\"\"获取存储在redis的信息\"\"\"\n if self.redis_conn.exists(key):\n info_str = self.redis_conn.get(key).decode('utf-8')\n info = json.loads(info_str)\n return info\n else:\n return {} if key == 'position' else []\n\n def set_info(self, key, info):\n \"\"\"存储信息到redis\"\"\"\n self.redis_conn.set(key, json.dumps(info))\n\n def buy(self, code, price):\n self.user.buy(code, price=price, volume=self.user.balance[0]['可用资金'], entrust_prop='market')\n\n date = self.get_date()\n c = {'code': code, 'buy_date': date, 'buy_price': price, 'days': 1, 'high': 0, 'profit': 0}\n\n self.mail_to('买入{}'.format(date), json.dumps(c))\n\n info = self.get_info('position')\n info[code] = c\n self.set_info('position', info)\n\n def sell(self, position, price=None):\n code = position['stock_code']\n if price is None:\n quote = self.get_quote(code)\n price = quote['ask']\n self.user.sell(code, price=price, amount=position['enable_amount'], entrust_prop='market')\n\n date = self.get_date()\n\n info = self.get_info('position')\n c = info[code]\n c['sell_date'] = date\n c['sell_price'] = price\n\n self.mail_to('卖出{}'.format(date), json.dumps(c))\n\n del info[code]\n self.set_info('position', info)\n\n @staticmethod\n def is_st(stock_name):\n return 'st' in stock_name\n\n def get_date(self):\n if self.date is None:\n self.date = str(datetime.datetime.now().date())\n return self.date\n\n def get_quote(self, code):\n return self.quote(code) if self.quote else ts.get_realtime_quotes(code)[0]\n\n def mail_to(self, title, content):\n if self.send_msg:\n try:\n # info = json.load(open('config/email.json'))\n # send_mail(info['sender'], info['sender'], info['password'], info['smtp_server'], title, content)\n send_msg(content, APP_ID_报告)\n except Exception as e:\n print(e)\n","sub_path":"strategies/bbi.py","file_name":"bbi.py","file_ext":"py","file_size_in_byte":6658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"550958257","text":"\"\"\"\nXMoney class unittests\n\"\"\"\nfrom decimal import Decimal\nimport unittest\n\nfrom money import XMoney, xrates\nfrom money.money import BABEL_AVAILABLE\nfrom .mixins import *\n\n\nclass TestXMoneyClass(ClassMixin, unittest.TestCase):\n MoneyClass = XMoney\n\nclass TestXMoneyRepresentations(RepresentationsMixin, unittest.TestCase):\n MoneyClass = XMoney\n\n@unittest.skipUnless(BABEL_AVAILABLE, \"requires Babel\")\nclass TestXMoneyFormatting(FormattingMixin, unittest.TestCase):\n MoneyClass = XMoney\n\nclass TestXMoneyParser(ParserMixin, unittest.TestCase):\n MoneyClass = XMoney\n\nclass TestXMoneyNumericOperations(NumericOperationsMixin, unittest.TestCase):\n MoneyClass = XMoney\n\nclass TestXMoneyUnaryOperationsReturnNew(UnaryOperationsReturnNewMixin, unittest.TestCase):\n MoneyClass = XMoney\n\nclass TestXMoneyLeftmostTypePrevails(LeftmostTypePrevailsMixin, unittest.TestCase):\n MoneyClass = XMoney\n\n\nclass TestXMoneyAutoConversion(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n xrates.install('money.exchange.SimpleBackend')\n xrates.base = 'XXX'\n xrates.setrate('AAA', Decimal('2'))\n xrates.setrate('BBB', Decimal('8'))\n \n @classmethod\n def tearDownClass(cls):\n xrates.uninstall()\n \n def setUp(self):\n self.x = XMoney('10', 'XXX')\n self.a = XMoney('10', 'AAA')\n self.b = XMoney('10', 'BBB')\n self.ax = XMoney('20', 'AAA')\n self.bx = XMoney('80', 'BBB')\n \n def test_lt(self):\n self.assertTrue(self.b < self.a)\n self.assertFalse(self.a < self.b)\n self.assertFalse(self.ax < self.bx)\n \n def test_le(self):\n self.assertTrue(self.b <= self.a)\n self.assertFalse(self.a <= self.b)\n self.assertTrue(self.ax <= self.bx)\n self.assertTrue(self.bx <= self.ax)\n \n def test_gt(self):\n self.assertTrue(self.a > self.b)\n self.assertFalse(self.b > self.a)\n self.assertFalse(self.ax > self.bx)\n \n def test_ge(self):\n self.assertTrue(self.a >= self.b)\n self.assertFalse(self.b >= self.a)\n self.assertTrue(self.ax >= self.bx)\n self.assertTrue(self.bx >= self.ax)\n \n def test_add(self):\n self.assertEqual(self.a + self.b, XMoney('12.5', 'AAA'))\n self.assertEqual(self.b + self.a, XMoney('50', 'BBB'))\n \n def test_sub(self):\n self.assertEqual(self.a - self.b, XMoney('7.5', 'AAA'))\n self.assertEqual(self.b - self.a, XMoney('-30', 'BBB'))\n \n def test_truediv(self):\n self.assertEqual(self.a / self.b, Decimal('4'))\n self.assertEqual(self.b / self.a, Decimal('0.25'))\n \n def test_floordiv(self):\n self.assertEqual(self.a // self.b, Decimal('4'))\n self.assertEqual(self.b // self.a, Decimal('0'))\n \n def test_divmod(self):\n whole, remainder = divmod(self.a, self.b)\n self.assertEqual(whole, Decimal('4'))\n self.assertEqual(remainder, Decimal('0'))\n whole, remainder = divmod(self.b, self.a)\n self.assertEqual(whole, Decimal('0'))\n self.assertEqual(remainder, Decimal('10'))\n\n\n\n","sub_path":"money/tests/test_xmoney.py","file_name":"test_xmoney.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"312591338","text":"import os\n\nfrom doxybook.markdown import MdDocument, MdLink, MdBold, MdHeader, MdList, MdParagraph, MdRenderer, Text, Br\nfrom doxybook.node import Node\nfrom doxybook.kind import Kind\n\ndef recursiveDictionary(node: Node, dictionary: dict):\n if node.kind == Kind.CLASS or node.kind == Kind.STRUCT:\n key = node.name.upper()[0]\n if key not in dictionary:\n dictionary[key] = []\n dictionary[key].append(node)\n for child in node.members:\n recursiveDictionary(child, dictionary)\n\ndef generateClassIndex(outputDir: str, root: Node):\n outputFile = os.path.join(outputDir, 'classes.md')\n print('Generating ' + outputFile)\n document = MdDocument()\n\n # Add title\n document.append(MdHeader(1, [Text('Class Index')]))\n\n # Sort\n dictionary = {}\n recursiveDictionary(root, dictionary)\n\n for key in list(sorted(dictionary.keys())):\n document.append(MdHeader(2, [Text(key)]))\n\n mdl = MdList([])\n for member in dictionary[key]:\n p = MdParagraph([])\n p.append(MdLink([MdBold([Text(member.getFullName(False))])], member.url))\n\n namespace = member.getNamespace()\n if namespace is not None:\n p.append(Text(' ('))\n p.append(MdLink([MdBold([Text(namespace.getFullName(False))])], namespace.url))\n p.append(Text(')'))\n mdl.append(p)\n\n document.append(mdl)\n document.append(Br())\n\n # Save\n with open(outputFile, 'w') as f:\n document.render(MdRenderer(f))\n","sub_path":"doxybook/generators/classindex.py","file_name":"classindex.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"40504173","text":"arquivo = open(\"macacos-me-mordam.txt\", \"r\")\nquantidade = 0\nfor linha in arquivo.readlines():\n\tlinha.upper()\n\n\ni = 0\nwhile i < len(linha):\n if linha[i:i+6] == \"BANANA\":\n quantidade += 1\n i += 1 \n \nprint(quantidade)\narquivo.close()\n","sub_path":"backup/user_366/ch85_2019_06_05_15_47_10_747629.py","file_name":"ch85_2019_06_05_15_47_10_747629.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"147449387","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import Http404\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .models import Venue, Artist, Note, Show, LikeNote\nfrom .forms import VenueSearchForm, NewNoteForm, ArtistSearchForm, UserRegistrationForm\nfrom django.db.models import Count, Max\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import authenticate, login, logout\n\nfrom django.utils import timezone\n\n\n@login_required\ndef new_note(request, show_pk):\n\n show = get_object_or_404(Show, pk=show_pk)\n artists = show.artists.all()\n\n if request.method == 'POST' :\n\n form = NewNoteForm(request.POST, request.FILES)\n if form.is_valid():\n note = form.save(commit=False)\n note.user = request.user\n note.show = show\n note.posted_date = timezone.now()\n note.save()\n return redirect('lmn:note_detail', note_pk=note.pk)\n\n else :\n form = NewNoteForm()\n\n return render(request, 'lmn/notes/new_note.html' , { 'form' : form , 'show':show , 'artists': artists})\n\n\n\ndef latest_notes(request):\n notes = Note.objects.all().order_by('posted_date').reverse()\n return render(request, 'lmn/notes/note_list.html', {'notes':notes})\n\n\ndef notes_for_show(request, show_pk): # pk = show pk\n\n # Notes for show, most recent first\n notes = Note.objects.filter(show=show_pk).order_by('posted_date').reverse()\n show = Show.objects.get(pk=show_pk) # Contains artist, venue\n\n return render(request, 'lmn/notes/note_list.html', {'show': show, 'notes':notes } )\n\n\ndef note_detail(request, note_pk):\n note = get_object_or_404(Note, pk=note_pk)\n show = get_object_or_404(Show, pk=note.show_id)\n artists = show.artists.all()\n return render(request, 'lmn/notes/note_detail.html' , {'note' : note, 'artists':artists})\n\n@login_required\ndef add_note_like(request, note_pk):\n note = get_object_or_404(Note, pk=note_pk)\n user = request.user\n try:\n query = LikeNote.objects.filter(note=note_pk)\n like = query.get(user=user.pk)\n if like.value != 1:\n note.add_like()\n like.like()\n except LikeNote.DoesNotExist:\n like = LikeNote(note=note, user=user, value=0)\n like.save()\n like.like()\n note.add_like()\n return render(request, 'lmn/notes/note_detail.html', {'note': note })\n\n@login_required\ndef add_note_dislike(request, note_pk):\n note = get_object_or_404(Note, pk=note_pk)\n user = request.user\n try:\n query = LikeNote.objects.filter(note=note_pk)\n like = query.get(user=user.pk)\n if like.value != -1:\n note.add_dislike()\n like.dislike()\n except LikeNote.DoesNotExist:\n like = LikeNote(note=note, user=note, value=0)\n like.save()\n like.dislike()\n note.add_dislike()\n return render(request, 'lmn/notes/note_detail.html', {'note': note})\n\n\ndef popular_notes(request):\n notes = Note.objects.all().order_by('rating', 'likes').reverse()\n return render(request, 'lmn/notes/note_list.html', {'notes': notes})\n\n@login_required\ndef edit_note(request, note_pk):\n note = Note.objects.get(pk=note_pk)\n show = Show.objects.get(pk=note.show_id)\n artists = show.artists.all()\n if request.user!=note.user:\n return redirect('lmn:latest_notes')\n if request.method=='POST':\n form = NewNoteForm(request.POST, request.FILES, instance=note)\n if form.is_valid():\n note = form.save(commit=False)\n note.user = request.user\n note.show = show\n note.save()\n return redirect('lmn:note_detail', note_pk=note.pk)\n else:\n form = NewNoteForm(instance=note)\n return render(request, 'lmn/notes/edit_note.html', {'show': show, 'note': note, 'form': form, 'artists':artists})\n\n\n@login_required\ndef delete_note(request, note_pk):\n note = Note.objects.get(pk=note_pk)\n if request.user != note.user:\n return redirect('lmn:latest_notes')\n Note.objects.filter(pk=note_pk).delete()\n return redirect('lmn:latest_notes')\n\n\n@login_required\ndef popular_shows(request):\n shows = Show.objects.annotate(notes=Count('note')).order_by('notes').reverse()\n return render(request, 'lmn/shows/show_list.html', {'shows': shows})\n","sub_path":"lmn/views_notes.py","file_name":"views_notes.py","file_ext":"py","file_size_in_byte":4345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"400879984","text":"import io\nimport random\nimport aiounittest\nimport itchat\nfrom collections import namedtuple\nfrom forklift.config import STICKERS_FOR_SPAM, ANIMATED_QUERY_TYPE\nfrom forklift.util import get_file, match_query_from_text, is_spam_msg\n\n\nclass TestUtil(aiounittest.AsyncTestCase):\n async def test_get_file(self):\n file = await get_file(random.choice(STICKERS_FOR_SPAM))\n self.assertIsInstance(file, io.BytesIO)\n\n def test_match_query_from_text(self):\n query, query_type = match_query_from_text('求水果表情')\n self.assertEqual(query, '水果')\n self.assertNotEqual(query_type, ANIMATED_QUERY_TYPE)\n\n query, query_type = match_query_from_text('有没有水果表情')\n self.assertEqual(query, '水果')\n self.assertNotEqual(query_type, ANIMATED_QUERY_TYPE)\n\n query, query_type = match_query_from_text('谁有水果表情')\n self.assertEqual(query, '水果')\n self.assertNotEqual(query_type, ANIMATED_QUERY_TYPE)\n\n query, query_type = match_query_from_text('有没有水果动图')\n self.assertEqual(query, '水果')\n self.assertEqual(query_type, ANIMATED_QUERY_TYPE)\n\n def test_is_spam_msg(self):\n Msg = namedtuple('Msg', ['type', 'text'])\n\n msg = Msg(type=itchat.content.SHARING, text='')\n self.assertTrue(is_spam_msg(msg))\n\n text = '''\n 【我正在PK人气赢能量,快来为我点赞】,復·制这段描述¥VNEkbhtJMv0¥后咑閞👉手机淘宝👈或者用浏览器咑閞https://m.tb.cn/h.3846eWj 查看\n '''.strip()\n msg = Msg(type=itchat.content.TEXT, text=text)\n self.assertTrue(is_spam_msg(msg))\n\n msg = Msg(type=itchat.content.TEXT, text='asdfasdf')\n self.assertFalse(is_spam_msg(msg))\n","sub_path":"test/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"308870331","text":"import os\nimport shutil\nimport sys\nimport tempfile\n\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\nfrom machotools import rewriter_factory\n\nfrom egginst.main import EggInst\nfrom egginst.object_code import (_compute_targets, _find_lib, _fix_object_code,\n get_object_type)\nfrom egginst import _zipfile\n\nfrom .common import (DUMMY_EGG_WITH_INST_TARGETS, FILE_TO_RPATHS,\n LEGACY_PLACEHOLD_FILE_RPATH, NOLEGACY_RPATH_FILE,\n MACHO_ARCH_TO_FILE,\n PYEXT_WITH_LEGACY_PLACEHOLD_DEPENDENCY, PYEXT_DEPENDENCY)\n\n\nclass TestObjectCode(unittest.TestCase):\n def setUp(self):\n self.prefix = tempfile.mkdtemp()\n\n def tearDown(self):\n shutil.rmtree(self.prefix)\n\n def test_get_object_type(self):\n self.assertEqual(get_object_type(MACHO_ARCH_TO_FILE[\"x86\"]), \"MachO-i386\")\n self.assertEqual(get_object_type(MACHO_ARCH_TO_FILE[\"amd64\"]), \"MachO-x86_64\")\n\n self.assertEqual(get_object_type(\"dummy_no_exist\"), None)\n self.assertEqual(get_object_type(__file__), None)\n\n def test_fix_object_code_legacy_macho(self):\n \"\"\"\n Test that we handle correctly our legacy egg with the /PLACHOLD * 20 hack.\n \"\"\"\n copy = os.path.join(self.prefix, \"foo.dylib\")\n shutil.copy(LEGACY_PLACEHOLD_FILE_RPATH, copy)\n\n _fix_object_code(copy, [self.prefix])\n rpaths = rewriter_factory(copy).rpaths\n\n self.assertEqual(rpaths, [self.prefix])\n\n def test_fix_object_code_wo_legacy_macho(self):\n \"\"\"\n Test that we handle correctly egg *without* the /PLACHOLD (i.e. we\n don't touch them).\n \"\"\"\n r_rpaths = FILE_TO_RPATHS[NOLEGACY_RPATH_FILE]\n copy = os.path.join(self.prefix, \"foo.dylib\")\n shutil.copy(NOLEGACY_RPATH_FILE, copy)\n\n _fix_object_code(copy, self.prefix)\n rpaths = rewriter_factory(copy).rpaths\n\n self.assertEqual(rpaths, r_rpaths)\n\n def test_fix_object_code_with_targets(self):\n \"\"\"\n Test we handle the targets.dat hack correctly in fix_object_code.\n\n Some of our eggs use /PLACEHOLD in the LC_LOAD_DYLIB command (i.e.\n inside the dependency names). Those are rewritten by finding the\n dependency in the installed egg first.\n\n We're ensuring here that those are also rewritten correctly.\n \"\"\"\n # targets.dat hack is handled in the function that expects an egg, but\n # we don't want to deal with an egg. Instead, we emulate the\n # targets.dat hack by patching object_code._targets with mock\n pyext_dependency_dir = os.path.join(\"lib\", \"foo-4.2\")\n\n installed_pyext_dependency = os.path.join(self.prefix,\n pyext_dependency_dir,\n os.path.basename(PYEXT_DEPENDENCY))\n installed_pyext_dependency_dir = os.path.dirname(installed_pyext_dependency)\n targets = [self.prefix, installed_pyext_dependency_dir]\n\n installed_pyext = os.path.join(self.prefix,\n os.path.basename(PYEXT_WITH_LEGACY_PLACEHOLD_DEPENDENCY))\n shutil.copy(PYEXT_WITH_LEGACY_PLACEHOLD_DEPENDENCY, installed_pyext)\n\n os.makedirs(installed_pyext_dependency_dir)\n shutil.copy(PYEXT_DEPENDENCY, installed_pyext_dependency_dir)\n\n _fix_object_code(installed_pyext, targets)\n deps = set(rewriter_factory(installed_pyext).dependencies)\n\n self.assertTrue(installed_pyext_dependency in deps)\n\n @unittest.skipIf(sys.platform == \"win32\", \"This feature is not used on windows.\")\n def test_find_lib_with_targets(self):\n def _compute_target_list(path, d):\n # FIXME: we need this hack as the internal EggInst zipfile\n # object is only available within an EggInst.install call.\n egg_inst = EggInst(path, d)\n egg_inst.z = zp\n\n return _compute_targets(egg_inst.iter_targets(), egg_inst.prefix)\n\n # Given\n with _zipfile.ZipFile(DUMMY_EGG_WITH_INST_TARGETS) as zp:\n egg_inst = EggInst(DUMMY_EGG_WITH_INST_TARGETS, self.prefix)\n egg_inst.install()\n\n targets = _compute_target_list(DUMMY_EGG_WITH_INST_TARGETS, self.prefix)\n\n path = \"libfoo.dylib\"\n r_found_lib = os.path.join(self.prefix, \"lib\", \"foo-4.2\", path)\n\n # When\n found_lib = _find_lib(path, targets)\n\n # Then\n self.assertEqual(found_lib, r_found_lib)\n","sub_path":"venv/lib/python2.7/site-packages/egginst/tests/test_object_code.py","file_name":"test_object_code.py","file_ext":"py","file_size_in_byte":4592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"263289017","text":"import os\n\nfrom setuptools import find_packages\nfrom setuptools import setup\n\n\nif os.environ.get(\"GITHUB_RELEASE_TAG\"):\n version = os.environ[\"GITHUB_RELEASE_TAG\"]\nelif os.environ.get(\"CI_JOB_ID\"):\n version = os.environ[\"CI_JOB_ID\"]\nelse:\n try:\n with open(\"PKG-INFO\") as f:\n for line in f:\n if line.startswith(\"Version: \"):\n version = line.split(\"Version: \")[1].split(\"\\n\")[0]\n break\n except IOError:\n version = \"unkown version\"\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\ninstall_requires = [\n \"acme\",\n \"certbot\",\n \"f5-icontrol-rest\",\n \"f5-sdk\",\n \"requests\",\n \"setuptools>=1.0\",\n \"zope.component\",\n \"zope.interface\",\n]\n\nsetup(\n name=\"certbot-bigip\",\n version=version,\n description=\"F5 BIG-IP plugin for Certbot\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author=\"Certbot Team @ Open Networks\",\n author_email=\"certbot@on.at\",\n license=\"Apache License 2.0\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"Environment :: Plugins\",\n \"Intended Audience :: System Administrators\",\n \"License :: OSI Approved :: Apache Software License\",\n \"Operating System :: POSIX :: Linux\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.6\",\n \"Topic :: Internet :: WWW/HTTP\",\n \"Topic :: Security\",\n \"Topic :: System :: Installation/Setup\",\n \"Topic :: System :: Networking\",\n \"Topic :: System :: Systems Administration\",\n \"Topic :: Utilities\",\n ],\n packages=find_packages(),\n include_package_data=True,\n install_requires=install_requires,\n extras_require={},\n entry_points={\n \"certbot.plugins\": [\n \"bigip = certbot_bigip.configurator:BigipConfigurator\",\n ],\n },\n setup_requires=[\"pytest-runner\"],\n tests_require=[\"pytest\"],\n test_suite=\"certbot_bigip\",\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"530723521","text":"from math import ceil, sqrt\nfrom RULEngine.Util.constant import *\nfrom os import remove\nimport numpy\n\n__author__ = 'Maxime Gagnon-Legault'\n\n\nclass InfluenceMap(object):\n \"\"\"\n Class InfluenceMap\n A class to represent a influence map for a Robocup SSL field.\n\n Parameter:\n TODO implement them\n\n decay algorithm = strengthpeak * (strengthdecay**distance)\n\n \"\"\"\n def __init__(self, resolution=100.0, strengthdecay = 0.8, strengthpeak=100, effectradius=8):\n assert(isinstance(resolution, float))\n assert(isinstance(strengthdecay, float))\n assert(0 < strengthdecay < 1)\n assert(isinstance(strengthpeak, int))\n assert(isinstance(effectradius, int))\n assert(0 < effectradius)\n\n #todo see how to better implement a graphic representation!\n #this option is not useful anymore\n #numpy.set_printoptions(threshold=10000)\n #GOD NO!\n try:\n remove(\"IMBoard\")\n remove(\"StaticBoard\")\n except:\n print(\"Nothing to remove!\")\n\n self._resolution = resolution\n self._strengthdecay = strengthdecay\n self._strengthpeak = strengthpeak\n self._effectradius = effectradius\n self._borderstrength = -strengthpeak * 0.02\n self._addedpoint = []\n\n #set the number of Horizontal/Vertical case for the field given the resolution chosen\n numberOfColumn = (abs(FIELD_X_LEFT) + FIELD_X_RIGHT) / self._resolution\n numberOfRow = (abs(FIELD_Y_BOTTOM) + FIELD_Y_TOP) / self._resolution\n\n self._numberOfRow = int(ceil(numberOfRow)) + 2\n self._numberOfColumn = int(ceil(numberOfColumn)) + 2\n\n self._IMBoard = numpy.zeros( (self._numberOfRow, self._numberOfColumn), numpy.int16)\n self._StarterIMBoard = numpy.zeros( (self._numberOfRow, self._numberOfColumn), numpy.int16)\n\n self._StaticBoard = numpy.zeros((self._numberOfRow, self._numberOfColumn), numpy.bool)\n self._StarterStaticBoard = numpy.zeros((self._numberOfRow, self._numberOfColumn), numpy.bool)\n\n def printNumberOfCases(self):\n numpy.savetxt(\"IMBoard\", self._IMBoard, fmt='%4i')\n numpy.savetxt(\"StaticBoard\", self._StaticBoard, fmt='%4i')\n print(self._numberOfRow, \" \", self._numberOfColumn, \" - \", self._addedpoint)\n\n def setStarterBoard(self):\n self.setBorders()\n self.distributeStartingStrength()\n\n def setBorders(self):\n self._StarterIMBoard[0] = self._borderstrength\n self._StarterStaticBoard[0] = True\n self._StarterIMBoard[:, 0] = self._borderstrength\n self._StarterStaticBoard[:, 0] = True\n self._StarterIMBoard[:, -1] = self._borderstrength\n self._StarterStaticBoard[:, -1] = True\n self._StarterIMBoard[-1] = self._borderstrength\n self._StarterStaticBoard[-1] = True\n\n def distributeStartingStrength(self):\n\n for border in range(self._numberOfColumn):\n\n for x in range(1, self._effectradius):\n\n if border - self._effectradius - 1 < 1:\n columnmin = 1\n else:\n columnmin = border - self._effectradius - 1\n\n if border + self._effectradius + 1 > self._numberOfColumn:\n columnmax = self._numberOfColumn\n else:\n columnmax = border + self._effectradius + 1\n\n for y in range(columnmin, columnmax):\n if not self._StarterStaticBoard[x, y] and ((x - 0)**2 + (y - border)**2) <= self._effectradius**2:\n decay = int((self._borderstrength * (self._strengthdecay ** \\\n self.distance(0, border, x, y))))\n self._StarterIMBoard[x, y] += decay\n\n for border in range(self._numberOfColumn):\n\n for x in range(self._numberOfRow - 2, self._numberOfRow - self._effectradius, -1):\n\n if border - self._effectradius - 1 < 1:\n columnmin = 1\n else:\n columnmin = border - self._effectradius - 1\n\n if border + self._effectradius + 1 > self._numberOfColumn:\n columnmax = self._numberOfColumn\n else:\n columnmax = border + self._effectradius + 1\n\n for y in range(columnmin, columnmax):\n if not self._StarterStaticBoard[x, y] and \\\n ((x - self._numberOfRow-1)**2 + (y - border)**2) <= self._effectradius**2:\n\n decay = int((self._borderstrength * (self._strengthdecay ** \\\n self.distance(self._numberOfRow - 1, border, x, y))))\n self._StarterIMBoard[x, y] += decay\n\n for border in range(self._numberOfRow):\n\n for y in range(1, self._effectradius):\n\n if border - self._effectradius - 1 < 1:\n rowmin = 1\n else:\n rowmin = border - self._effectradius - 1\n\n if border + self._effectradius + 1 > self._numberOfRow:\n rowmax = self._numberOfRow\n else:\n rowmax = border + self._effectradius + 1\n\n for x in range(rowmin, rowmax):\n if not self._StarterStaticBoard[x, y] and ((x - border)**2 + (y - 0)**2) <= self._effectradius**2:\n decay = int((self._borderstrength * (self._strengthdecay ** \\\n self.distance(border, 0, x, y))))\n self._StarterIMBoard[x, y] += decay\n\n for border in range(self._numberOfRow):\n\n for y in range(self._numberOfColumn - 2, self._numberOfColumn - self._effectradius, -1):\n\n if border - self._effectradius - 1 < 1:\n rowmin = 1\n else:\n rowmin = border - self._effectradius - 1\n\n if border + self._effectradius + 1 > self._numberOfRow:\n rowmax = self._numberOfRow\n else:\n rowmax = border + self._effectradius + 1\n\n for x in range(rowmin, rowmax):\n if not self._StarterStaticBoard[x, y] and \\\n ((x - border)**2 + (y - self._numberOfColumn - 1)**2) <= self._effectradius**2:\n decay = int((self._borderstrength * (self._strengthdecay ** \\\n self.distance(border, self._numberOfColumn - 1, x, y))))\n self._StarterIMBoard[x, y] += decay\n\n self._IMBoard = numpy.copy(self._StarterIMBoard)\n self._StaticBoard = numpy.copy(self._StarterStaticBoard)\n\n def addPoint(self, row, column, strength=0):\n assert(isinstance(row, int))\n assert(isinstance(column, int))\n assert(isinstance(strength, int))\n assert(0 <= row <= self._numberOfRow)\n assert(0 <= column <= self._numberOfColumn)\n assert(-self._strengthpeak <= strength <= self._strengthpeak)\n\n self._IMBoard[row, column] = strength\n self._StaticBoard[row, column] = True\n self._addedpoint.append((row, column, strength))\n\n\n def addPointAndInfluence(self, row, column, strength=0):\n assert(isinstance(row, int))\n assert(isinstance(column, int))\n assert(isinstance(strength, int))\n assert(0 <= row <= self._numberOfRow)\n assert(0 <= column <= self._numberOfColumn)\n assert(-self._strengthpeak <= strength <= self._strengthpeak)\n\n self._IMBoard[row, column] = strength\n self._StaticBoard[row, column] = True\n self._addedpoint.append((row, column, strength))\n\n if row - self._effectradius - 1 < 1:\n rowmin = 1\n else:\n rowmin = row - self._effectradius - 1\n\n if row + self._effectradius + 1> self._numberOfRow:\n rowmax = self._numberOfRow\n else:\n rowmax = row + self._effectradius + 1\n\n if column - self._effectradius - 1 < 1:\n columnmin = 1\n else:\n columnmin = column - self._effectradius - 1\n\n if column + self._effectradius + 1 > self._numberOfColumn:\n columnmax = self._numberOfColumn\n else:\n columnmax = column + self._effectradius + 1\n\n for x in range(rowmin, rowmax):\n for y in range(columnmin, columnmax):\n if not self._StaticBoard[x,y] and ((x - row)**2 + (y - column)**2) <= self._effectradius**2:\n decay = int((strength * (self._strengthdecay ** self.distance(x, y, row, column))))\n self._IMBoard[x, y] += decay\n\n def addSquareAndInfluence(self, top, bottom, left, right, strength):\n assert(isinstance(top, int))\n assert(isinstance(bottom, int))\n assert(isinstance(left, int))\n assert(isinstance(right, int))\n assert(0 < top < self._numberOfRow - 1)\n assert(0 < bottom < self._numberOfRow - 1)\n assert(0 < left < self._numberOfColumn - 1)\n assert(0 < right < self._numberOfColumn - 1)\n assert(top <= bottom)\n assert(left <= right)\n assert(isinstance(strength, int))\n assert(-self._strengthpeak <= strength <= self._strengthpeak)\n\n for x in range(top, bottom):\n for y in range(left, right):\n self.addPointOfInfluence(x, y, strength)\n\n def addSimplisticRobotOnBoard(self, row, column):\n #TODO THIS FUNCTION IS NOT DONE!\n #TODO see what we do with this function, is it the one used?\n assert(isinstance(row, int))\n assert(isinstance(column, int))\n assert(0 <= row <= self._numberOfRow - 2)\n assert(0 <= column <= self._numberOfColumn - 2)\n\n robotRadius = int(ROBOT_RADIUS / self._resolution) - 1\n\n if robotRadius < 1:\n self._StaticBoard[row, column] = True\n else:\n for x in range(-robotRadius, robotRadius+1):\n self._StaticBoard[row+x, column] = True\n self._StaticBoard[row, column+x] = True\n #TODO please change that for the love of god\n self._StaticBoard[row-1, column-1] = True\n self._StaticBoard[row+1, column+1] = True\n self._StaticBoard[row-1, column+1] = True\n self._StaticBoard[row+1, column-1] = True\n\n def addRobotOnBoard(self, row, column, strength):\n assert(isinstance(row, int))\n assert(isinstance(column, int))\n assert(isinstance(strength, int))\n assert(0 <= row <= self._numberOfRow - 2)\n assert(0 <= column <= self._numberOfColumn - 2)\n assert(-self._strengthpeak <= strength <= self._strengthpeak)\n #todo see if this useful.\n pass\n\n\n\n def findClosestPoint(self, row, column, strengthrequired):\n assert(isinstance(row, int))\n assert(isinstance(column, int))\n assert(isinstance(strengthrequired, int))\n assert(0 <= row <= self._numberOfRow)\n assert(0 <= column <= self._numberOfColumn)\n assert(-4*self._strengthpeak <= strengthrequired <= 4*self._strengthpeak)\n\n\n result = []\n counter = 1\n rtop = False\n rbottom = False\n cleft = False\n cright = False\n rowinsidesquare = [row]\n columninsidesquare = [column]\n\n while not result:\n\n for x in range(row-counter,row+counter+1):\n\n if rtop and rbottom and cleft and cright:\n result.append(0)\n break\n\n if x < 1:\n rtop = True\n continue\n\n if x > self._numberOfRow - 1:\n rbottom = True\n break\n\n for y in range(column-counter,column+counter+1):\n\n if y < 1:\n cleft = True\n continue\n\n if y > self._numberOfColumn - 1:\n cright = True\n break\n\n if x in rowinsidesquare and y in columninsidesquare:\n continue\n\n if self._IMBoard[x,y] >= strengthrequired:\n result.append((x,y))\n\n counter += 1\n rowinsidesquare = range(row-counter+1, row+counter)\n columninsidesquare = range(column-counter+1, column+counter)\n\n if not result[0]:\n result.clear()\n\n return result\n\n def clearBoard(self):\n self._IMBoard = numpy.copy(self._StarterIMBoard)\n self._StaticBoard = numpy.copy(self._StarterStaticBoard)\n self._addedpoint.clear()\n\n def transformFieldPositionToGridPosition(self, position):\n assert(isinstance(position, Position))\n assert(position.x <= FIELD_X_RIGHT + 100)\n assert(position.x >= FIELD_X_LEFT - 100)\n assert(position.y <= FIELD_Y_TOP + 100)\n assert(position.y >= FIELD_Y_BOTTOM - 100)\n\n Xpos = position.x + ((abs(FIELD_X_LEFT) + FIELD_X_RIGHT) / 2)\n Ypos = position.y + ((abs(FIELD_Y_BOTTOM) + FIELD_Y_TOP) / 2)\n\n Xpos = int(round(Xpos / self._resolution, 0))\n Ypos = int(round(Ypos / self._resolution, 0))\n\n return (Xpos, Ypos)\n\n def transformGridPositionToFieldPosition(self, row, column):\n assert(isinstance(row, int))\n assert(isinstance(column, int))\n assert(0 <= row <= self._numberOfRow - 2)\n assert(0 <= column <= self._numberOfColumn - 2)\n\n Xpos = FIELD_X_LEFT + (column * self._resolution)\n Ypos = FIELD_Y_TOP - (row * self._resolution)\n\n tempPosition = Position(Xpos, Ypos)\n return tempPosition\n\n def distance(self, x1, y1, x2, y2):\n assert(isinstance(x1, int) or isinstance(x1, float))\n assert(isinstance(x2, int) or isinstance(x2, float))\n assert(isinstance(y1, int) or isinstance(y1, float))\n assert(isinstance(y2, int) or isinstance(y2, float))\n return sqrt((x2 - x1)**2 + (y2 - y1)**2)\n\n","sub_path":"InfluenceMap.py","file_name":"InfluenceMap.py","file_ext":"py","file_size_in_byte":14162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"600448061","text":"number = int(input())\r\r\n\r\r\none = 'I hate'\r\r\ntwo = 'I love'\r\r\nresult = ''\r\r\n\r\r\nfirst = True\r\r\nsecond = False\r\r\n\r\r\nfor i in range(1, number + 1):\r\r\n if first is True and i is 1:\r\r\n result += one\r\r\n first = False\r\r\n second = True\r\r\n elif first is True and i is not 1:\r\r\n result += ' that '\r\r\n result += one\r\r\n first = False\r\r\n second = True\r\r\n elif second is True:\r\r\n result += ' that '\r\r\n result += two\r\r\n second = False\r\r\n first = True\r\r\n\r\r\nresult += ' it'\r\r\nprint(result)","sub_path":"python_files/adiIspas_20656431_705.py","file_name":"adiIspas_20656431_705.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"492676058","text":"import turtle\n__import__(\"turtle\").__traceable__ = False\n\ndef draw_rectangle(t, w ,h):\n \"\"\"Get turtle t to draw a rectangle of width w and height h\"\"\"\n for i in range(2):\n t.forward(w)\n t.left(90)\n t.forward(h)\n t.left(90)\n\n\ndef draw_square(tx, sz):\n \"\"\"Make turtle t draw a square with sides of length sz\"\"\"\n draw_rectangle(tx, sz, sz)\n\nwn = turtle.Screen() # setup the window and its attributes\nwn.bgcolor(\"pink\")\nwn.title(\"Using a function to draw a square\")\n\nalex = turtle.Turtle()\ndraw_square(alex, 50)\n\ndraw_rectangle(alex, 50, 100)\n\nwn.mainloop()\n\n","sub_path":"4.2_functions_calling_other_functions.py","file_name":"4.2_functions_calling_other_functions.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"361188410","text":"''' DFS CLASS '''\r\n\r\nimport numpy as np\r\nimport pygame as py\r\n\r\nfrom variables import *\r\n\r\nclass Graph:\r\n\r\n def __init__(self, graph):\r\n self.graph = graph\r\n self.path = []\r\n self.height = len(graph)\r\n self.width = len(graph[0])\r\n self.cellsize_x = int(DISPLAY_HEIGHT / self.width)\r\n self.cellsize_y = int(DISPLAY_WIDTH / self.height)\r\n \r\n def drawGraph(self, surface, boxx, boxy):\r\n for x in range(0, DISPLAY_WIDTH, self.cellsize_x):\r\n py.draw.line(surface, BLACK, (x,0), (x,DISPLAY_HEIGHT))\r\n\r\n for y in range(0, DISPLAY_HEIGHT, self.cellsize_y):\r\n py.draw.line(surface, BLACK, (0,y), (DISPLAY_WIDTH,y))\r\n\r\n for y_pos in range(self.height):\r\n for x_pos in range(self.width):\r\n\r\n box = self.graph[y_pos][x_pos]\r\n board_x = x_pos * self.cellsize_x\r\n board_y = y_pos * self.cellsize_x\r\n square = py.Rect(board_x, board_y,\r\n self.cellsize_x, self.cellsize_y)\r\n\r\n if(box == 'P'):\r\n py.draw.rect(surface, BLUE, square)\r\n\r\n elif(box == 'e'):\r\n py.draw.rect(surface, RED, square)\r\n\r\n elif(box == 'x'):\r\n py.draw.rect(surface, BLACK, square)\r\n\r\n elif(box == 's'):\r\n py.draw.rect(surface, GREEN, square)\r\n \r\n py.draw.rect(surface, BLUE, (boxx, boxy, self.cellsize_x, self.cellsize_y), 2)\r\n\r\n def move(self,x,y,direction):\r\n\r\n if direction == 0:\r\n x+=1\r\n\r\n elif direction == 1:\r\n y+=1\r\n\r\n elif direction == 2:\r\n x-=1\r\n\r\n elif direction == 3:\r\n y-=1\r\n\r\n return x,y\r\n\r\n def isValid(self,x,y,direction):\r\n x,y = self.move(x,y,direction)\r\n\r\n if(x<0 or x>=self.width):\r\n return False\r\n\r\n if(y<0 or y>=self.height):\r\n return False\r\n\r\n if(self.graph[y][x] == 'x'):\r\n return False\r\n\r\n if([x,y] in self.path):\r\n return False\r\n\r\n else:\r\n return True\r\n \r\n\r\n\r\n def dfsUtil(self, x, y):\r\n\r\n if(self.graph[y][x] == 'e'):\r\n return True\r\n\r\n for direction in range(4):\r\n\r\n if self.isValid(x,y,direction):\r\n a,b = self.move(x,y,direction)\r\n self.path.append([a,b])\r\n\r\n if self.dfsUtil(a,b) == True:\r\n return True\r\n\r\n self.path.pop()\r\n\r\n return False\r\n\r\n def DFS(self):\r\n x = STARTX\r\n y = STARTY\r\n if self.dfsUtil(x,y) == True:\r\n #print(\"Solution Exists\")\r\n self.updateBoard()\r\n #print(self.graph)\r\n else:\r\n print(\"No Solution\")\r\n\r\n def updateBoard(self):\r\n for coordinate in self.path:\r\n x = coordinate[0]\r\n y = coordinate[1]\r\n if (self.graph[y][x] == 'e'):\r\n continue\r\n self.graph[y][x] = 'P'\r\n\r\n self.path.clear()\r\n\r\n\r\n","sub_path":"DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"265719021","text":"import numpy as np \nimport sys\nimport csv\nfrom inspection import inspectData\nimport copy\nimport math\n\n\n\ndef splitCol(trainData, attribute, attributesLst):\n\n trainDataCopy = copy.deepcopy(trainData)\n\n attCount = list(attributesLst).index(attribute)\n branchLeft = [list(trainDataCopy[0,:])]\n branchRight = [list(trainDataCopy[0,:])]\n \n val1 = trainDataCopy[1, attCount]\n val2 = \"\"\n \n for row in trainDataCopy[1:,:]:\n if row[attCount] != val1:\n val2 = row[attCount]\n branchRight.append(list(row))\n \n elif row[attCount] == val1:\n branchLeft.append(list(row))\n\n\n branchLeft = np.reshape(branchLeft, (len(branchLeft), len(branchLeft[0])))\n branchRight = np.reshape(branchRight, (len(branchRight), len(branchRight[0])))\n\n bundle = [branchLeft, branchRight, val1, val2]\n return bundle\n\n\n\ndef allZeroMutual(trainData, attributesLst, classes):\n \n for attribute in attributesLst:\n mI = mutualInfo(trainData, attribute, attributesLst, classes)\n if mI != 0:\n return False\n return True\n\n\n\n\ndef mutualInfo(trainData, attribute, attributesLst, classes):\n\n trainDataCopy = copy.deepcopy(trainData)\n\n entropy = inspectData(trainData, classes)[0]\n class1 = inspectData(trainData, classes)[2]\n class2 = inspectData(trainData, classes)[3]\n\n attCount = list(attributesLst).index(attribute)\n\n class1CountA = 0\n class2CountA = 0\n\n class1CountB = 0\n class2CountB = 0\n\n label1 = trainData[1, attCount]\n\n label2 = \"\"\n\n for row in trainDataCopy[1:, :]:\n if row[attCount] != label1:\n label2 = row[attCount]\n \n label1Count = 0\n label2Count = 0\n for row in trainDataCopy[1:, :]:\n if row[attCount] == label1 and row[-1] == class1:\n class1CountA += 1\n label1Count += 1\n elif row[attCount] == label1 and row[-1] == class2:\n class2CountA += 1\n label1Count += 1\n\n if row[attCount] == label2 and row[-1] == class1:\n class1CountB += 1\n label2Count += 1\n\n elif row[attCount] == label2 and row[-1] == class2:\n class2CountB += 1\n label2Count += 1\n\n if label1Count == 0 or label2Count == 0:\n return 0\n\n pClass1Label1 = class1CountA / label1Count \n pClass2Label1 = class2CountA / label1Count \n\n pClass1Label2 = class1CountB / label2Count \n pClass2Label2 = class2CountB / label2Count \n\n tmpCond1A = 0\n tmpCond1B = 0\n tmpCond2A = 0\n tmpCond2B = 0\n\n if pClass1Label1 == 0:\n tmpCond1A = 0\n else:\n tmpCond1A = pClass1Label1*math.log(pClass1Label1,2)\n\n if pClass2Label1 == 0:\n tmpCond1B = 0\n else:\n tmpCond1B = pClass2Label1*math.log(pClass2Label1,2)\n\n if pClass1Label2 == 0:\n tmpCond2A = 0\n else:\n tmpCond2A = pClass1Label2*math.log(pClass1Label2,2)\n\n if pClass2Label2 == 0:\n tmpCond2B = 0\n else:\n tmpCond2B = pClass2Label2*math.log(pClass2Label2,2)\n\n #H(Y | A = a)\n\n specCondEntropy1 = -(tmpCond1A + tmpCond1B)\n specCondEntropy2 = -(tmpCond2A + tmpCond2B)\n\n #H(Y | A)\n\n pA1 = label1Count / len(trainData[1:,:])\n pA2 = label2Count / len(trainData[1:,:])\n \n condEntropy = pA1*specCondEntropy1 + pA2*specCondEntropy2\n\n #I(Y ; A)\n\n mI = entropy - condEntropy\n return mI\n\n\n\n\ndef bestAttribute(trainData, attributesLst, classes):\n\n mutualDict = dict()\n for attribute in attributesLst:\n\n mI = mutualInfo(trainData, attribute, attributesLst, classes)\n mutualDict[attribute] = mI\n\n keyLst = []\n\n for key in mutualDict.keys():\n keyLst.append(key)\n\n bestVal = 0\n bestKey = keyLst[0]\n \n for key in mutualDict:\n \n if float(mutualDict[key]) > bestVal:\n bestVal = float(mutualDict[key])\n bestKey = key\n \n return bestKey\n \n\n\n\nclass Node(object):\n\n def __init__(self, att = None, val = \"\", left = None, right = None, label = \"\", countA = 0, countB = 0):\n self.att = att \n self.val = \"\"\n self.left = left\n self.right = right\n self.label = \"\"\n self.countA = countA\n self.countB = countB\n\n\n\ndef majorityVote(class1, class2, class1Count, class2Count, node):\n\n \n node.countA = class1Count\n node.countB = class2Count\n\n if class1Count == class2Count:\n if class1 > class2:\n node.val = str(class1)\n elif class2 > class1:\n node.val = str(class2)\n\n elif class1Count > class2Count:\n node.val = str(class1)\n \n elif class2Count > class1Count:\n node.val = str(class2)\n \n node.left = None\n node.right = None\n \n return node\n\n\n\n\ndef getOutputStats(trainData, classes):\n\n class1 = inspectData(trainData, classes)[2]\n class2 = inspectData(trainData, classes)[3]\n class1Count = inspectData(trainData, classes)[4]\n class2Count = inspectData(trainData, classes)[5]\n\n return [class1,class2, class1Count, class2Count]\n\n\n\n\ndef buildDecisionTree(trainData, attributesLst, maxDepth, currentDepth, classes, node):\n\n \n if maxDepth == 0: #Just a leaf node, perform majority vote\n\n print((currentDepth * \"|\") + \"[%d %s / %d %s]\" % (getOutputStats(trainData, classes)[2],\n getOutputStats(trainData, classes)[0], \n getOutputStats(trainData, classes)[3], \n getOutputStats(trainData, classes)[1]))\n\n return majorityVote(getOutputStats(trainData, classes)[0], \n getOutputStats(trainData, classes)[1], \n getOutputStats(trainData, classes)[2], \n getOutputStats(trainData,classes)[3], node)\n \n\n currentDepth += 1\n \n \n if allZeroMutual(trainData, attributesLst, classes):\n\n return majorityVote(getOutputStats(trainData, classes)[0], \n getOutputStats(trainData, classes)[1], \n getOutputStats(trainData, classes)[2], \n getOutputStats(trainData,classes)[3], node)\n \n\n \n if currentDepth == maxDepth:\n \n attribute = bestAttribute(trainData, attributesLst, classes)\n node.att = attribute\n node = decisionStump(trainData, attributesLst, node, classes)\n \n print((currentDepth * \"|\") + \"%s = %s: [%d %s / %d %s]\" %(attribute, node.left.label, node.left.countA, \n getOutputStats(trainData, classes)[0], \n node.left.countB, \n getOutputStats(trainData, classes)[1]))\n\n print((currentDepth * \"|\") + \"%s = %s: [%d %s / %d %s]\" %(attribute, node.right.label, node.right.countA, \n getOutputStats(trainData, classes)[0], \n node.right.countB, \n getOutputStats(trainData, classes)[1]))\n \n return node\n\n \n \n \n else:\n \n att = bestAttribute(trainData, attributesLst, classes)\n split = splitCol(trainData, att, attributesLst)\n \n node.att = att\n \n nextNodeLeft = Node(None, \"\", None, None, \"\", 0, 0)\n nextNodeLeft.label = split[2]\n\n nextNodeRight = Node(None, \"\", None, None, \"\", 0, 0)\n nextNodeRight.label = split[3]\n\n print((currentDepth * \"|\") + \"%s = %s: [%d %s / %d %s]\" %(att, split[2] ,getOutputStats(split[0], classes)[2], \n getOutputStats(split[0], classes)[0], \n getOutputStats(split[0], classes)[3], \n getOutputStats(split[0], classes)[1]))\n \n \n node.left = buildDecisionTree(split[0], attributesLst, maxDepth, currentDepth, classes, nextNodeLeft)\n \n print((currentDepth * \"|\") + \"%s = %s: [%d %s / %d %s]\" %(att , split[3],getOutputStats(split[1], classes)[2], \n getOutputStats(split[1], classes)[0], \n getOutputStats(split[1], classes)[3], \n getOutputStats(split[1], classes)[1]))\n \n \n \n node.right = buildDecisionTree(split[1], attributesLst, maxDepth, currentDepth, classes, nextNodeRight)\n \n return node\n\n\ndef decisionStump(trainData, attributesLst, node, classes):\n\n att = node.att\n\n attCount = list(attributesLst).index(att)\n\n split = splitCol(trainData, att, attributesLst)\n\n leftBranch = split[0] \n rightBranch = split[1]\n\n class1Left = leftBranch[1,-1]\n class2Left = \"\"\n\n class1CountLeft = 0\n class2CountLeft = 0\n\n for row in leftBranch[1:,:]:\n if row[-1] != class1Left:\n class2Left = row[-1]\n class2CountLeft += 1\n else:\n class1CountLeft += 1\n\n \n if class2Left == \"\":\n for cl in classes:\n if cl != class1Left:\n class2Left = cl\n \n\n class1Right = rightBranch[1,-1]\n class2Right = \"\"\n\n class1CountRight = 0\n class2CountRight = 0\n\n\n for row in rightBranch[1:,:]:\n if row[-1] != class1Right:\n class2Right = row[-1]\n class2CountRight += 1\n else:\n class1CountRight += 1\n\n \n if class2Right == \"\":\n for cl in classes:\n if cl != class1Right:\n class2Right = cl\n \n nextNodeLeft = Node(None, \"\", None, None, \"\", 0, 0)\n nextNodeLeft.label = split[2]\n\n nextNodeRight = Node(None, \"\", None, None, \"\", 0, 0)\n nextNodeRight.label = split[3]\n\n\n node.left = majorityVote(class1Left, class2Left, class1CountLeft, class2CountLeft, nextNodeLeft)\n node.right = majorityVote(class1Right, class2Right, class1CountRight, class2CountRight, nextNodeRight)\n\n return node \n\n\n\n\n\n\n\ndef trainError(trainData, predictedTrainLabels):\n\n trainDataCopy = copy.deepcopy(trainData)\n actualLabels = trainDataCopy[1:,-1]\n errorCount = 0\n \n for idx in range(0, len(predictedTrainLabels)):\n\n if predictedTrainLabels[idx] != actualLabels[idx]:\n errorCount += 1\n\n trainError = float(errorCount) / len(predictedTrainLabels)\n return trainError\n\n\n\n\ndef testError(testData, predictedTestLabels):\n\n testDataCopy = copy.deepcopy(testData)\n actualLabels = testDataCopy[1:,-1]\n errorCount = 0\n \n for idx in range(0, len(predictedTestLabels)):\n\n if predictedTestLabels[idx] != actualLabels[idx]:\n errorCount += 1\n\n testError = float(errorCount) / len(predictedTestLabels)\n return testError\n\n\n\ndef writeMetrics(trainError, testError, outputMetricFile):\n\n outputMetric = open(outputMetricFile, \"w\")\n \n\n outputMetric.write(\"error(train): %f\\n\" % (trainError))\n outputMetric.write(\"error(test): %f\" % (testError))\n\n \n\n\n\ndef predictLabels(trainData, maxDepth, attributesLst, decisionTree):\n\n trainDataCopyTmp = copy.deepcopy(trainData)\n trainDataCopy = trainDataCopyTmp[:,0:-1]\n predictedLabels = []\n \n if maxDepth == 0:\n predictedLabels.append(decisionTree.val)\n return predictedLabels \n\n root = decisionTree.att\n idx = list(attributesLst).index(root)\n \n\n for row in trainDataCopy[1:,:]:\n \n if decisionTree.left.label == row[idx]:\n createPath(row, attributesLst, decisionTree.left, predictedLabels)\n \n elif decisionTree.right.label == row[idx]:\n createPath(row, attributesLst, decisionTree.right, predictedLabels)\n\n return predictedLabels\n \n\n\ndef createPath(data, attributesLst, decisionTree, predictedLabels):\n\n \n if decisionTree.left == None and decisionTree.right == None:\n \n predictedLabels.append(decisionTree.val)\n return predictedLabels \n\n currAttribute = decisionTree.att\n attIdx = list(attributesLst).index(currAttribute)\n\n\n if decisionTree.left.label == data[attIdx]:\n return createPath(data, attributesLst, decisionTree.left, predictedLabels)\n\n elif decisionTree.right.label == data[attIdx]:\n return createPath(data, attributesLst, decisionTree.right, predictedLabels)\n\n\ndef writeLabelsFile(predictedTrainLabels, outputTrainFile, predictedTestLabels, outputTestFile):\n\n trainLabels = open(outputTrainFile, \"w\")\n\n for trainLabel in predictedTrainLabels:\n \n trainLabels.write(trainLabel)\n trainLabels.write(\"\\n\")\n\n\n testLabels = open(outputTestFile, \"w\")\n\n for testLabel in predictedTestLabels:\n\n testLabels.write(testLabel)\n testLabels.write(\"\\n\")\n\n\n\n\n\ndef main():\n\n trainInput = sys.argv[1]\n testInput = sys.argv[2]\n maxDepthTmp = sys.argv[3]\n outputTrainFile = sys.argv[4]\n outputTestFile = sys.argv[5]\n outputMetrics = sys.argv[6]\n\n print(\"The train input file is: %s\\n\" % (trainInput))\n \n tmpTrainData = csv.reader(open(trainInput), delimiter = \"\\t\")\n trainDataTmp = np.array(list(tmpTrainData))\n\n tmpTestData = csv.reader(open(testInput), delimiter = \"\\t\")\n testDataTmp = np.array(list(tmpTestData))\n\n attributesLstTrain = copy.deepcopy(trainDataTmp)[0, 0:-1]\n attributesLstTest = copy.deepcopy(testDataTmp)[0, 0:-1]\n\n trainData = np.reshape(trainDataTmp, (len(trainDataTmp), len(trainDataTmp[0])))\n testData = np.reshape(testDataTmp, (len(testDataTmp), len(testDataTmp[0])))\n \n currentDepth = 0\n maxDepth = int(maxDepthTmp)\n \n trainDataCopy = copy.deepcopy(trainData)\n outputLst = trainDataCopy[1:,-1]\n\n class1 = outputLst[0]\n class2 = \"\"\n\n for row in outputLst:\n if row != class1:\n class2 = row\n\n classes = [class1, class2]\n \n\n node = Node(None, None, None, None, None, 0, 0)\n\n print((currentDepth * \"|\") + \"[%d %s / %d %s]\" % (getOutputStats(trainData, classes)[2],\n getOutputStats(trainData, classes)[0], \n getOutputStats(trainData, classes)[3], \n getOutputStats(trainData, classes)[1]))\n\n tree = buildDecisionTree(trainData, attributesLstTrain, maxDepth, currentDepth, classes, node)\n\n predictedTrainLabels = predictLabels(trainData, maxDepth, attributesLstTrain, tree)\n predictedTestLabels = predictLabels(testData, maxDepth, attributesLstTest, tree)\n\n #writeLabelsFile(predictedTrainLabels, outputTrainFile, predictedTestLabels, outputTestFile)\n\n trainingError = trainError(trainData, predictedTrainLabels)\n testingError = testError(testData, predictedTestLabels)\n\n #writeMetrics(trainingError, testingError, outputMetrics)\n\n\n \nif __name__ == '__main__':\n main()","sub_path":"Decision Tree/decisionTree.py","file_name":"decisionTree.py","file_ext":"py","file_size_in_byte":14630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"167164464","text":"import sys as s\r\nimport func\r\nimport crusher as c\r\nimport os\r\n###################################### old version old version old version old version old version\r\n\r\ny = 0\r\nx = str(s.argv[1])\r\nprint('python toolkit [Version 1.5.2004] '\r\n 'Copyright (c) 2019 backpack. All rights reserved.')\r\nprint('')\r\n\r\nif x == '-h':\r\n print('usage: [encrypt/powme/multicalc/crusher/fib/palindrome/power/squereme/trinum] -r ')\r\n x = input()\r\n if x == 'encrypt -r':\r\n func.encrypter()\r\n exit(0)\r\n if x == 'powme -r':\r\n y = int(input('choose a number to power by himself: '))\r\n func.powme(y)\r\n exit(0)\r\n if x == 'multicalc -r':\r\n func.multicalc()\r\n exit(0)\r\n if x == 'crusher -r':\r\n c.crusher()\r\n exit(0)\r\n if x == 'fib -r':\r\n func.fib()\r\n exit(0)\r\n if x == 'palindrome -r':\r\n y = int(input('enter a board: '))\r\n func.palindrome(y)\r\n exit(0)\r\n if x == 'power -r':\r\n func.power()\r\n exit(0)\r\n if x == 'squereme -r':\r\n func.squereme()\r\n exit(0)\r\n if x == 'trinum -r':\r\n y=int(input('how many triangular number you want:'))\r\n print(func.trinum(y))\r\n exit(0)\r\n\r\nif x == '-i':\r\n print('')\r\n print('-backpack(toolkit) born in the name pyhelp and it began writing on 28.1.2019 by Adam Ofer.'\r\n 'The purpose of the script is to use other function that can'\r\n ' solve problems, encryption and complex math calculations. the script also run cmd functions:'\r\n 'ip finder, CMD color change, shutdown dialog and shows the code source')\r\n print('')\r\n print('-The script was written in Pycharm and it combines two other scripts written by Adam Ofer and combines additional modules')\r\n print('')\r\n y=os.system('pause')\r\n print('Run instructions:')\r\n print(' r: run the program functions (run).')\r\n print(' i: show this text (information)')\r\n print(' h: show the functions and how to run them (help).')\r\n print(' ?: show the functions and how to run them (help).')\r\n print(' p: print a text (print).')\r\n print(' s: open shutdown dialog.')\r\n print(' cs: show code source (code source)')\r\n print(' c: change the color (color)')\r\n print('')\r\n y=os.system('pause')\r\n print('functions:')\r\n print(' encrypt: slove and encrypt sentenses and words')\r\n print('')\r\n print(' powme: power a number by himself. y=x**x')\r\n print('')\r\n print(' multicalc: a calculator containing all the operations of the account is rooting for the numbers entered'\r\n ' and showing the abbreviated multiplication formulas.')\r\n print('')\r\n print(' crusher: force the user to shutdown/restart the computer.')\r\n print('')\r\n print(' fib: print all Fibonacci numbers up to z.')\r\n print('')\r\n print(' palindrome: print all the palindrome numbers up to x.')\r\n print('')\r\n print(' power: power number with another one.')\r\n print('')\r\n print(' squereme: print and sum all to squere numbers up to x + the digit lenght.')\r\n print('')\r\n print(' trinum: return list of all the triangle numbers up to x.')\r\n print('')\r\n\r\n exit(0)\r\nif x == '-?':\r\n print('usage: [encrypter/powme/multicalc/crusher/fib/palindrome/power/squereme] -r ')\r\n x=input()\r\n if x == 'encrypter -r':\r\n func.encrypter()\r\n exit(0)\r\n if x == 'powme -r':\r\n y = int(input('choose a number to power by himself: '))\r\n func.powme(y)\r\n exit(0)\r\n if x == 'multicalc -r':\r\n func.multicalc()\r\n exit(0)\r\n if x == 'crusher -r':\r\n c.crusher()\r\n exit(0)\r\n if x == 'fib -r':\r\n func.fib()\r\n exit(0)\r\n if x == 'palindrome -r':\r\n y = int(input('enter a board: '))\r\n func.palindrome(y)\r\n exit(0)\r\n if x == 'power -r':\r\n func.power()\r\n exit(0)\r\n if x == 'squereme -r':\r\n func.squereme()\r\n exit(0)\r\n\r\nif x=='-p':\r\n print('usage: -r')\r\n x=input()\r\n if x[-2]+x[-1]=='-r':\r\n print('\"'+x[0:-3]+'\"')\r\n exit(0)\r\n else:\r\n print('forgot: \"-r\"')\r\n exit(0)\r\nif x=='-s':\r\n y=os.system('shutdown -i')\r\n exit(0)\r\nif x=='-ip':\r\n y=os.system('ipconfig')\r\n print('')\r\n print('search for \" IPv4 Address\" to find your ip')\r\n exit(0)\r\nif x=='-cs':\r\n y=os.system('type backpack.py')\r\n exit(0)\r\nif x=='-c':\r\n y=input('choose a color: [red/green/blue/white/yellow/gray] ')\r\n if y=='red':\r\n os.system('color 4')\r\n exit(0)\r\n if y=='green':\r\n os.system('color 2')\r\n exit(0)\r\n if y=='blue':\r\n os.system('color 1')\r\n exit(0)\r\n if y=='white':\r\n os.system('color 7')\r\n exit(0)\r\n if y == 'yellow':\r\n os.system('color 6')\r\n exit(0)\r\n if y == 'gray':\r\n os.system('color 8')\r\n exit(0)\r\n if y == 'black':\r\n os.system('color 0')\r\n exit(0)\r\nelse:\r\n print('try: backpack.py [-i/-h/-p/-s/-ip/-cs/-c/-?] ')\r\n","sub_path":"toolkit project/toolkit.py","file_name":"toolkit.py","file_ext":"py","file_size_in_byte":5166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"66855671","text":"import webapp2, logging\r\nfrom google.appengine.ext import db\r\nfrom base import BaseHandler\r\nfrom models import Piskel\r\nimport models\r\n\r\nPUBLIC_CATEGORIES = ['public']\r\nPRIVATE_CATEGORIES = ['all', 'public', 'private', 'deleted']\r\n\r\nclass UserHandler(BaseHandler):\r\n def get_default(self, user_id):\r\n user = self.auth.store.user_model.get_by_id(long(user_id))\r\n if user:\r\n is_own_profile = self.is_logged_in and long(user_id) == self.session_user['user_id']\r\n if is_own_profile:\r\n self.get(user_id, 'all')\r\n else:\r\n self.get(user_id, 'public')\r\n\r\n else:\r\n self.abort(404)\r\n\r\n def get(self, user_id, cat):\r\n user = self.auth.store.user_model.get_by_id(long(user_id))\r\n if user:\r\n stats = models.get_stats_for_user(user_id)\r\n is_own_profile = self.is_logged_in and long(user_id) == self.session_user['user_id']\r\n\r\n if self._is_valid_category(user_id, cat):\r\n piskels = self._get_piskels_for_category(user_id, cat)\r\n view_piskels = Piskel.prepare_piskels_for_view(piskels)\r\n categories = PRIVATE_CATEGORIES if is_own_profile else PUBLIC_CATEGORIES\r\n values = {\r\n 'profile_user': user,\r\n 'category' : cat,\r\n 'categories' : categories,\r\n 'profile_stats' : stats,\r\n 'profile_piskels': view_piskels,\r\n 'is_own_profile': is_own_profile\r\n }\r\n self.render('user/user.html', values)\r\n else:\r\n self.redirect('/user/' + user_id + '/public')\r\n else:\r\n self.abort(404)\r\n\r\n def _get_piskels_for_category(self, user_id, cat):\r\n if cat == 'all':\r\n return models.get_piskels_for_user(user_id)\r\n if cat == 'public':\r\n return models.get_public_piskels_for_user(user_id)\r\n if cat == 'private':\r\n return models.get_private_piskels_for_user(user_id)\r\n if cat == 'deleted':\r\n return models.get_deleted_piskels_for_user(user_id)\r\n\r\n def _is_valid_category(self, user_id, cat):\r\n is_own_profile = self.is_logged_in and long(user_id) == self.session_user['user_id']\r\n if is_own_profile and cat in ['all', 'public', 'private', 'deleted']:\r\n return True\r\n else:\r\n return cat == 'public'","sub_path":"handlers/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"163809066","text":"import json\nfrom collections import defaultdict\n\nfrom fastavro import reader, writer, parse_schema\n\nfrom utils import dictionary\nfrom utils.db import DB\nfrom utils.db import dump_edge_table, dump_node_table\nfrom utils.str_utils import str_hook\n\nimport gc\n\nimport datetime\nimport time\n\n\ndef from_psql(psql_credentials, model, pfb_file, output):\n start = time.time()\n print(datetime.datetime.now())\n\n db = DB(credentials=psql_credentials)\n\n node_table_label, edge_table_label = dictionary.get_table_label(model)\n\n get_all_tables_query = \"\"\"SELECT table_name FROM information_schema.tables\n WHERE table_schema = 'public' ORDER BY table_name;\"\"\"\n tables = db.execute_query(get_all_tables_query)\n\n metadata = []\n\n avro_reader = reader(pfb_file)\n for record in avro_reader:\n metadata.append(record)\n\n avro_schema = avro_reader.writer_schema\n avro_schema = json.loads(json.dumps(avro_schema), object_pairs_hook=str_hook)\n parsed_schema = parse_schema(avro_schema)\n\n table_logs = '{:>40} = {:<10} [{:<12}]'\n\n with open(output, 'wb') as output_file:\n writer(output_file, parsed_schema, metadata)\n\n edge_tables = [t['table_name'] for t in tables if t['table_name'].startswith('edge_')]\n\n iter = defaultdict(list)\n\n for e, v in edge_table_label.items():\n if e in edge_tables:\n iter[v['src']].append(e)\n\n total = 0\n\n for k, v in iter.items():\n node_edges = defaultdict(list)\n for edge_table in v:\n edges = dump_edge_table(db, edge_table, edge_table_label)\n total += len(edges)\n print(table_logs.format(edge_table, len(edges), total))\n\n with open(output, 'a+b') as output_file:\n writer(output_file, parsed_schema, edges)\n\n for e in edges:\n node_edges[e['src_id']].append({'dst_id': e['dst_id'], 'dst_name': e['dst_name']})\n\n node_table = 'node_' + k.replace('_', '')\n print(table_logs.format(node_table, 0, total))\n\n nodes = dump_node_table(db, node_table, parsed_schema, node_edges, node_table_label)\n total += len(nodes)\n print(table_logs.format('^' * len(node_table), len(nodes), total))\n\n with open(output, 'a+b') as output_file:\n writer(output_file, parsed_schema, nodes)\n\n gc.collect()\n\n end = time.time()\n print(datetime.datetime.now())\n print(\"--- %s seconds ---\" % (end - start))\n","sub_path":"utils/psql_import.py","file_name":"psql_import.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"475882536","text":"#!/usr/bin/python\n# -*- coding:utf8 -*-\nimport numpy as np\nimport math\nimport os\nimport json\n\nimport torch\n#from model import vaeakf_combinational_linears\nfrom model import vaeakf_combinational_linears as vaeakf_combinational_linears\nfrom model.srnn import SRNN\nfrom model.vrnn import VRNN\nfrom model.deepar import DeepAR\n#from model import vaeakf_combinational_linears_random as vaeakf_combinational_linears\n\n\ndef generate_model(args):\n\n if args.model.type == 'vaecl':\n #model = vaeakf_cl.VAEAKFCombinedLinear(\n model = vaeakf_combinational_linears.VAEAKFCombinedLinear(\n input_size=args.dataset.input_size,\n state_size=args.model.state_size,\n observations_size=args.dataset.observation_size,\n k=args.model.posterior.k_size,\n num_layers=args.model.posterior.num_layers,\n L=args.model.L,\n R=args.model.R,\n D=args.model.D,\n num_linears=args.model.dynamic.num_linears\n )\n elif args.model.type == 'srnn':\n model = SRNN(\n input_size=args.dataset.input_size,\n state_size=args.model.state_size,\n observations_size=args.dataset.observation_size,\n net_type=args.model.net_type,\n k=args.model.k_size,\n num_layers=args.model.num_layers,\n filtering=args.model.filtering,\n D=args.model.D\n )\n elif args.model.type == 'vrnn':\n model = VRNN(\n input_size=args.dataset.input_size,\n state_size=args.model.state_size,\n observations_size=args.dataset.observation_size,\n net_type=args.model.net_type,\n k=args.model.k_size,\n num_layers=args.model.num_layers,\n D=args.model.D\n )\n elif args.model.type == 'deepar':\n model = DeepAR(\n input_size=args.dataset.input_size,\n observations_size=args.dataset.observation_size,\n net_type=args.model.net_type,\n k=args.model.k_size,\n num_layers=args.model.num_layers\n )\n else:\n raise NotImplementedError\n return model\n","sub_path":"model/generate_model.py","file_name":"generate_model.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"432384384","text":"import glob\nimport json\nimport logging\nimport os\nimport time\nfrom typing import Tuple\nfrom COMPS import Client\nfrom COMPS.Data import AssetCollection\nfrom COMPS.Data import QueryCriteria\nfrom COMPS.Data import WorkItem, WorkItemFile\nfrom COMPS.Data.WorkItem import WorkerOrPluginKey, WorkItemState\nfrom simtools.COMPSAccess.InputDataWorker import InputDataWorker\nfrom dtk.utils.ioformat.OutputMessage import OutputMessage as om\nfrom simtools.SetupParser import SetupParser\nfrom simtools.Utilities.COMPSUtilities import download_asset_collection\nfrom simtools.Utilities.General import file_size\nfrom logging import FileHandler\nfrom logging import Formatter\n\n\nlogger = logging.getLogger(__name__)\nlogger_file_handler = FileHandler('ClimateGenerator_Log.log')\nlogger_file_handler.setLevel(logging.DEBUG)\nlogger_file_handler.setFormatter(Formatter('%(asctime)s: %(levelname)s: %(message)s'))\nlogger.addHandler(logger_file_handler)\n\n# use 150 if you want resolution = 2.5arcmin\nALLOW_RESOLUTIONS = ['0', '150', '30']\n\n\nclass ClimateGenerator:\n def __init__(self, demographics_file_path: str, work_order_path: str, climate_files_output_path: str,\n climate_project: str = \"IDM-Zambia\", start_year: str = str(2000), num_years: str = str(1),\n resolution: str = str(0), project_root: str = 'v2017'):\n \"\"\"\n Climate Generator handles generating climate related input files for the DTK from the COMPS Large DataSets\n\n Example:\n ```\n demographics_fp = os.path.join(path, 'demographics.json')\n output_path = os.path.dirname(os.path.abspath(__file__))\n climate_output_path = os.path.join(output_path, 'climate')\n cg = ClimateGenerator(demographics_file_path=demographics_fp,\n work_order_path=os.path.join(output_path, 'wo.json'),\n climate_files_output_path=climate_output_path,\n climate_project='IDM-Zambia',\n start_year='2008', num_years='1',\n resolution='0',\n project_root='v2017',\n idRef=\"Gridded world grump2.5arcmin\")\n rain_fn, tempfn, humidity_fn = cg.generate_climate_files()\n ```\n Args:\n demographics_file_path: The path to the Demographics file.\n work_order_path: Path to work order\n climate_files_output_path: Path to save climate output files and logs\n climate_project: Climate project name. See https://comps.idmod.org/#demoui for a List of supported\n project names\n start_year: What year to start generation from\n num_years: Total years to generate climate files\n resolution: What resolution to run the climate generation at\n project_root: What project root should we use. Usually the default is best as it reflects the latest data\n sets\n \"\"\"\n self.work_order_path = work_order_path\n self.demographics_file_path = demographics_file_path\n self.climate_project = climate_project\n self.start_year = start_year\n self.num_years = num_years\n if resolution not in ALLOW_RESOLUTIONS:\n raise ValueError(f\"{resolution} is not a valid resolution. Please use one\"\n f\" of the following values {', '.join(ALLOW_RESOLUTIONS)} \")\n self.resolution = resolution\n self.project_root = project_root\n self.wo = None\n\n self.validate_inputs()\n\n # Get the idRef from the demographics_file if notspecified\n # Raise FileNotFoundError if demographics_file_path does not exist.\n with open(demographics_file_path, 'r') as demographics_file:\n demog = json.load(demographics_file)\n demog_idref = demog['Metadata']['IdReference']\n\n # fetch idRef from the input demographics file's Metadata->IdReference field.\n self.idRef = demog_idref\n\n # use \"wo.json\" as the work order name and save it in the working directory if user inputs an empty string.\n if not self.work_order_path:\n self.work_order_path = \"wo.json\"\n work_order_dirname = os.path.dirname(self.work_order_path)\n if work_order_dirname:\n # Create folder to save wo.json if user input a path that doesn't exist\n if not os.path.isdir(work_order_dirname):\n os.mkdir(work_order_dirname)\n\n # save climate files to working directory if user passes in an empty string\n if not climate_files_output_path:\n climate_files_output_path = '.'\n self.climate_files_output_path = climate_files_output_path\n if not os.path.exists(self.climate_files_output_path): os.makedirs(self.climate_files_output_path)\n\n def validate_inputs(self):\n \"\"\"\n Performs the following validations with the specified climate inputs\n\n 1. Is their a project data set name(climate_project) exist in the Large Data API\n 2. Is the specified year range valid for the specified project?\n\n This is called during construction of the Climate Generator object\n Returns: None\n\n \"\"\"\n client = Client()\n client.login(SetupParser.get('server_endpoint'))\n response = client.get('/ld/DataSets.json')\n if response.status_code is not 200:\n raise EnvironmentError(\"Issue connecting to the COMPS Large Data Datasets API\"\n f\"({SetupParser.get('server_endpoint')}/api/ld/DataSets.json)\")\n data_sets = response.json()\n try:\n project_data_set = [ds for ds in data_sets if ds['name'] == self.climate_project][0]\n end_year = int(self.start_year) + int(self.num_years)\n\n if project_data_set['endYear'] < end_year or int(self.start_year) < project_data_set['startYear']:\n raise ValueError(f\"The Climate Project {self.climate_project} dataset does not support contain the \"\n f\"specified year range of {self.start_year} to {end_year}. The dataset supports the\"\n f\" years {project_data_set['startYear']} to {project_data_set['endYear']}.\")\n except IndexError as e: # The\n supported_projects = \"\\n\".join(sorted([ds['name'] for ds in data_sets if ds['name'].startswith('IDM-')]))\n raise ValueError(f\"Cannot locate the Climate Project with name: {self.climate_project}. The list of\"\n f\" supported projects are as follows: {supported_projects}\")\n\n @staticmethod\n def wait_for_work_item(wi: WorkItem, work_item_name: str='work item', check_state_interval: str=5) -> WorkItem.state:\n \"\"\"\n Wait on the specified work item to either finish by Succeeding, Failing, or being Canceled\n Args:\n wi: Work item to wait on\n work_item_name: Name of work item to display as part of the periodic state check. Default to 'work item'\n check_state_interval: How often to check work items state in secs. Defaults to every 5\n\n Returns: Work item state\n\n \"\"\"\n while wi.state not in (WorkItemState.Succeeded, WorkItemState.Failed, WorkItemState.Canceled):\n om(f'Waiting for {work_item_name} to complete (current state: {str(wi.state)}\\n', style='flushed')\n time.sleep(check_state_interval)\n wi.refresh()\n return wi.state\n\n def create_work_item(self) -> WorkItem:\n \"\"\"\n Creates the work item to generator the Climate Files\n\n Returns: work item\n\n \"\"\"\n workerkey = WorkerOrPluginKey(name='InputDataWorker', version='1.0.0.0_RELEASE')\n wi = WorkItem('dtk-tools InputDataWorker WorkItem', workerkey, SetupParser.get('environment'))\n wi.set_tags({'dtk-tools': None, 'WorkItem type': 'InputDataWorker dtk-tools'})\n with open(self.work_order_path, 'rb') as workorder_file:\n # wi.AddWorkOrder(workorder_file.read())\n wi.add_work_order(data=workorder_file.read())\n with open(self.demographics_file_path, 'rb') as demog_file:\n wi.add_file(WorkItemFile(os.path.basename(self.demographics_file_path), 'Demographics', ''),\n data=demog_file.read())\n wi.save()\n\n logger.info(\"Created request for climate files generation.\")\n\n logger.info(\"Commissioning...\")\n wi.commission()\n logger.info(\"CommissionRequested.\")\n logger.info(f\"Work item id is: {wi.id}.\")\n\n return wi\n\n def download_climate_assets(self, wi: WorkItem) -> bool:\n \"\"\"\n Download the climate asset files from the specified work item\n Args:\n wi:\n\n Returns: True if assests were located, otherwise False\n\n \"\"\"\n\n # Get the collection with our files\n collections = wi.get_related_asset_collections()\n collection_id = collections[0].id\n comps_collection = AssetCollection.get(collection_id, query_criteria=QueryCriteria().select_children('assets'))\n\n # Get the files\n if len(comps_collection.assets) > 0:\n logger.info(\"Found output files:\")\n for asset in comps_collection.assets:\n logger.info(f\"- {asset.file_name} ({file_size(asset.length)})\")\n\n logger.info(f\"Downloading to {self.climate_files_output_path}...\")\n # Download the collection\n download_asset_collection(comps_collection, self.climate_files_output_path)\n return True\n return False\n\n def generate_climate_files(self) -> Tuple[str, str, str]:\n \"\"\"\n The main method of the class that performs the manages the workflow of generating climate files.\n\n The workflow is a follows\n 1. The method first creates an InputDataWorker from the specified data inputs\n 2. Then a work item is created from the InputDataWorker workorder\n 3. Once the work item finishes, we check the work item state.\n If it's succeeded, we attempt to download the generated assets.\n If it's failed or canceled, we throw Error.\n 4. If successful, we return the rain_file_name, temperature_file_name, humidity_file_name\n\n Returns:\n\n \"\"\"\n # see InputDataWorker for other work options\n self.wo = InputDataWorker(demographics_file_path=self.demographics_file_path,\n wo_output_path=self.work_order_path,\n project_info=self.climate_project,\n start_year=str(self.start_year),\n num_years=str(self.num_years),\n resolution=str(self.resolution),\n idRef=self.idRef,\n project_root=self.project_root)\n\n # login to COMPS (if not already logged in) to submit climate files generation work order\n\n self.wo.wo_2_json()\n\n wi = self.create_work_item()\n\n # Wait until the work item is Done(Succeeded, Fails, or Canceled)\n wi_state = self.wait_for_work_item(wi)\n logger.info(f\"Work item state is: {str(wi_state)}\")\n\n if wi_state == WorkItemState.Succeeded:\n logger.info(\"Climate files SUCCESSFULLY generated\")\n # try to download the climate files into climate_files_output_path if work item runs successfully.\n if self.download_climate_assets(wi):\n # return filenames; this use of re in conjunction w/ glob is not great; consider refactor\n rain_bin_re = os.path.abspath(f'{self.climate_files_output_path}/*rain*.bin')\n humidity_bin_re = os.path.abspath(f'{self.climate_files_output_path}/*humidity*.bin')\n temperature_bin_re = os.path.abspath(f'{self.climate_files_output_path}/*temperature*.bin')\n\n rain_file_name = os.path.basename(glob.glob(rain_bin_re)[0])\n humidity_file_name = os.path.basename(glob.glob(humidity_bin_re)[0])\n temperature_file_name = os.path.basename(glob.glob(temperature_bin_re)[0])\n\n logger.info('Climate files SUCCESSFULLY stored.')\n\n return rain_file_name, temperature_file_name, humidity_file_name\n\n else:\n logger.info('No output files found')\n raise ValueError(\"No Climate output files generated. Please check work item log\")\n else:\n # raise ValueError if work item doesn't run successfully.\n logger.info('Work item status is not Succeeded')\n raise ValueError(\"Work item status is not Succeeded. Please check work item log\")\n\n","sub_path":"dtk/tools/climate/ClimateGenerator.py","file_name":"ClimateGenerator.py","file_ext":"py","file_size_in_byte":12833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"489769846","text":"#!/usr/bin/env python\nimport rospy as rp\nfrom grid_map import GridMap\nimport heapq as pq\n\n\nclass ASTAR(GridMap):\n def __init__(self):\n super(ASTAR, self).__init__()\n self.position = position\n self.parent = parent\n self.g = 0\n self.f = 0\n \n def heapsort(self, list_in): # metoda sortujaca liste do odwiedzenia\n h = []\n for val in list_in:\n pq.heappush(h, val)\n return [pq.heappop(h) for i in range(len(h))]\n\n def heuristics(self, pos):\n distance = ((pos[1] - end[1]) ** 2) + ((pos[0] - end[0]) ** 2)\n return distance\n\n def search(self):\n start = self.start\n end = self.end\n start_n = ASTAR(None, start)\n start_n.g = 0\n start_n.f = dfs.heuristics(start_n.position, end)\n end_n = ASTAR(None, end)\n end_n.g = end_n.f = 0\n visited = []\n toVisit = [(start_n.f, start_n)] # dodaje punkt startowy do listy do odwiedzenia\n path = []\n neighbours = [(0, -1), (0, 1), (-1, 0), (1, 0)] # okreslam czterosasiedztwo\n\n while len(toVisit) > 0:\n actual_n = toVisit[0][1] # ustawiam aktualny wierzcholek\n\n toVisit = dfs.heapsort(toVisit) # sortuje liste do odwiedzenia, tak by wierzcholek z najmniejsza wartoscia F byl na poczatku\n if toVisit[0][0] < actual_n.f: # jezeli wierzcholek na poczatku listy ma mniejsza wartosc F niz obecny, zostaje ustawiony jako aktualny\n actual_n = toVisit[0][1]\n\n toVisit.pop(0) # usuwam aktualny wierzcholek z listy do odwiedzenia\n visited.append(actual_n) # dodaje aktualny wierzcholek do odwiedzonych\n\n self.map.data[actual_n.position[1] + actual_n.position[0] * self.map.info.width] = 50 # zmieniam wartosc komorki mapy na \"odwiedzona\" i publikuje mape\n self.publish_visited()\n if actual_n.position == end_n.position: # jezeli aktualny wierzcholek jest koncowym, odtwarzam sciezke\n while actual_n is not None:\n path.append(actual_n.position) # dodaje rodzicow wierzcholka do sciezki\n actual_n = actual_n.parent # ustawiam rodzica aktualnego wierzcholka jako aktualny w celu sprawdzenia jego rodzica\n path = path[::-1] # odwracam sciezke, aby prowadzila od poczatku do konca\n print(\"Znaleziono rozwiazanie!\")\n break\n\n children = []\n for neigh in neighbours:\n neigh_pos = (actual_n.position[0] + neigh[1], actual_n.position[1] + neigh[0]) # uzyskanie pozycji sasiada\n if self.map.data[neigh_pos[1] + neigh_pos[0] * self.map.info.width] != 100: # jezeli sasiad nie jest sciana, stworz nowy obiekt i dodaj go do listy wierzcholkow potomnych\n new_n = ASTAR(actual_n, neigh_pos)\n children.append(new_n)\n for child in children:\n if self.map.data[child.position[1] + child.position[0] * self.map.info.width] == 50: # jezeli wierzcholek potomny byl odwiedzony, sprawdz nastepnego\n continue\n child.g = actual_n.g + 1 # jezeli wierzcholek potomny nie byl odwiedzony, oblicz wartosi G i F\n child.f = child.g + dfs.heuristics(child.position, end)\n for vis in toVisit:\n if child == vis and child.g > vis.g: # jezeli wierzcholek potomny znajduje sie na liscie do odwiedzenia, a jego obecna sziezka jest dluzsza niz odkryta wczesniej, zbadaj nastepny wierzcholek\n continue\n toVisit.append((child.f, child)) # jezeli wierzcholka nie ma na liscie do odwiedzenia lub jest to krotsza sciezka, dopisz do odwiedzenia\n\n self.publish_visited()\n self.publish_path(path)\n\n\nif __name__ == '__main__':\n dfs = ASTAR()\n dfs.search()\n","sub_path":"src/astar.py","file_name":"astar.py","file_ext":"py","file_size_in_byte":4801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"291256232","text":"import sys, os, subprocess, glob\nfrom pygame.locals import *\n\nsys.path.append('support_scripts')\n\nimport pygame, pygbutton, inputbox\n\nWINDOWWIDTH, WINDOWHEIGHT = 500, 750\n\ncaptionFont = pygame.font.SysFont('courier',16)\n\nsendpraat = os.path.join(os.getcwd(),'support_scripts','sendpraat')\n\ngetPitch = os.path.join(os.getcwd(),'getPitch.praat')\n\nupdateFormants = os.path.join(os.getcwd(),'updateFormants.py') \n\nplotmish = os.path.join(os.getcwd(), 'plotmish.py')\n\nFPS = 10\n\nWHITE = (255, 255, 255)\nBLACK = (0,0,0)\nGREY = Color('gray20')\n\npygame.init()\nDISPLAYSURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))\nFPSCLOCK = pygame.time.Clock()\npygame.display.set_caption('Plotmish')\n\nbutton = pygbutton.PygButton\n\nargs =\t{\t'formant' : '',\n\t\t\t'wav' : '',\n\t\t\t'keyword' : '',\t\n\t\t\t'log' : '',\n\t\t\t'praat' : '',\n\t\t\t'pitch tracks' : '',\n\t\t\t'overwrite' : False,\n\t\t\t'corrected': '', \n\t\t\t'annotator': '',\n\t\t\t'celex dict': '',\n\t\t\t'mode': False}\n\ndefaultsPath = os.path.join(os.getcwd(),'defaults.txt')\n\nakeys = {0:'formant',1:'wav',2:'keyword', 3:'log',4:'praat',5:'pitch tracks',6:'celex dict', 7:'corrected', 8: 'annotator'}\n\n\ndef writeDefaults():\n\tdefaultF = open(defaultsPath, 'wb')\n\tfor k,v in args.items():\n\t\tdefaultF.write(k+'\\t'+str(v)+'\\n')\n\tdefaultF.close()\t\n\ndef readDefaults():\n\tdefaultF = open(defaultsPath, 'rb')\n\tfor d in defaultF.readlines():\n\t\tif d.strip():\n\t\t\td = d.replace('\\n','').split('\\t')\n\t\t\targs[d[0].strip()] = d[1].strip() if d[0] not in ['overwrite', 'mode'] else eval(d[1].strip()) \n\tdefaultF.close()\n\ndef updateArgs():\n\tfor i,b in enumerate(textbuttons):\n\t\targs[akeys[i]] = b.caption\n\n\ndef checkDefaults():\n\tbad = []\n\tfor k,v in args.items():\n\t\tif k in ['formant','wav']:\n\t\t\tif not (os.path.isdir(v) or os.path.isfile(v)):\n\t\t\t\tif not v:\n\t\t\t\t\tbad.append('no entry for '+k)\n\t\t\t\telse:\t\n\t\t\t\t\tbad.append(k+' path does not exist')\n\t\tif k == 'praat':\n\t\t\tif not v:\n\t\t\t\tbad.append('no entry for '+k) \n\t\t\telif not (os.path.isdir(v) and os.path.basename(v) == 'Praat.app'):\n\t\t\t\tbad.append('Praat not found at given path')\n\t\tif k == 'log':\n\t\t\tif not v:\n\t\t\t\tbad.append('no entry for '+k)\n\t\t\telif not os.path.isdir(v):\n\t\t\t\tif os.path.isdir(os.path.dirname(v)):\n\t\t\t\t\tsubprocess.call(['mkdir',v])\n\t\t\t\telse:\n\t\t\t\t\tbad.append(k+' path does not exist')\n\t\tif k == 'pitch tracks':\n\t\t\tif not os.path.isdir(v) and v:\n\t\t\t\tbad.append(k+' path does not exist')\n\t\t\telif not glob.glob(os.path.join(os.path.basename(v),'*.Pitch')) and v:\n\t\t\t\tbad.append('no Pitch files found in '+k+' folder')\n\t\tif k == 'corrected':\n\t\t\tif not os.path.isdir(v) and v:\n\t\t\t\tbad.append(k+' path does not exist')\n\t\t\telif not v:\n\t\t\t\tbad.append('no entry for '+k)\n\t\tif k == 'annotator':\n\t\t\tif not v:\n\t\t\t\tbad.append('no entry for '+k)\n\t\tif k == 'celex dict':\n\t\t\tif not os.path.isfile(v) and v:\n\t\t\t\tbad.append(k+' file not found')\n\t\t\telif not v and args['mode']:\n\t\t\t\tbad.append(k +' required for Celex Mode')\n\treturn bad\n\t\nroot = os.path.abspath(os.sep)\n\ndef shortcut(pth):\n\tif not pth: \n\t\treturn pth\n\tif pth[0] == '~':\n\t\tpth = os.path.expanduser(\"~\")+pth[1:]\n\tif pth[:2+len(os.sep)] == '..'+os.sep:\n\t\tpth = os.path.join(os.path.dirname(pth.split('..'+os.sep,1)[1]),pth.split('..'+os.sep,1)[1])\n\telif pth == '..':\n\t\tpth = os.path.dirname(os.getcwd())\n\tif pth[:1+len(os.sep)] == '.'+os.sep:\n\t\tpth = os.path.join(os.getcwd(),pth.split('.'+os.sep,1)[1])\n\telif pth == '.':\n\t\tpth = os.getcwd()\t\n\ttry:\n\t\tif pth[:len(root)] != root:\n\t\t\tpth = root+pth\n\texcept:\n\t\tpth = root+pth\n\treturn pth\n\ndef completePath(path):\n\timmedDir = shortcut(path.rsplit(os.sep,1)[0])\n\tif os.path.isdir(immedDir):\n\t\tsuffix = path.rsplit(os.sep,1)[1]\n\t\topts = [os.path.basename(g) for g in glob.glob(os.path.join(immedDir,suffix+'*'))]\n\t\tif len(opts) == 1:\n\t\t\tcompleted = os.path.join(path.rsplit(os.sep,1)[0], opts[0])\n\t\t\tcompleted += os.sep if os.path.isdir(os.path.join(immedDir,opts[0])) else ''\n\t\t\treturn [completed]\n\treturn [path]\n\n\ndef errorMessage(message):\n for i,m in enumerate(message):\n mess = captionFont.render(m,1,BLACK)\n DISPLAYSURFACE.blit(mess,(WINDOWWIDTH/2.0-(captionFont.size(m)[0]/2.0),WINDOWHEIGHT/2.0-(captionFont.size(m)[1]/2.0)+(i*(captionFont.size(m)[1])+5)))\n #pygame.display.update()\n #DISPLAYSURFACE.fill(WHITE)\n\ndef resizeText(button):\n\tfontsize = 16\n\twhile button.rect.width < button._font.size(button.caption)[0] and fontsize > 7:\n\t\tfontsize -= 1\n\t\tbutton._font = pygame.font.SysFont('courier',fontsize)\n\t\tbutton._update()\n\nif not os.path.isfile(defaultsPath):\n\twriteDefaults()\nelse:\n\treadDefaults()\n\n\n\n\n\ntextbuttons = [\tbutton(rect = pygame.Rect(20, 100, 460, 20),caption = args['formant'], border = False, bgcolor = GREY, fgcolor = WHITE),\n\t\t\t\tbutton(rect = pygame.Rect(20, 150, 460, 20),caption = args['wav'], border = False, bgcolor = GREY, fgcolor = WHITE),\n \t\t\t\tbutton(rect = pygame.Rect(20, 200, 460, 20),caption = args['keyword'], border = False, bgcolor = GREY, fgcolor = WHITE),\n \t\t\t\tbutton(rect = pygame.Rect(20, 250, 460, 20),caption = args['log'], border = False, bgcolor = GREY, fgcolor = WHITE),\n \t\t\t\tbutton(rect = pygame.Rect(20, 300, 460, 20),caption = args['praat'], border = False, bgcolor = GREY, fgcolor = WHITE),\n \t\t\t\tbutton(rect = pygame.Rect(20, 350, 460, 20),caption = args['pitch tracks'], border = False, bgcolor = GREY, fgcolor = WHITE),\n \t\t\t\tbutton(rect = pygame.Rect(20, 400, 460, 20),caption = args['celex dict'], border = False, bgcolor = GREY, fgcolor = WHITE),\n \t\t\t\tbutton(rect = pygame.Rect(20, 450, 460, 20),caption = args['corrected'], border = False, bgcolor = GREY, fgcolor = WHITE), \n \t\t\t\tbutton(rect = pygame.Rect(20, 500, 460, 20),caption = args['annotator'], border = False, bgcolor = GREY, fgcolor = WHITE)]\n\nfor t in textbuttons:\n\tresizeText(t)\n\nonoffbuttons = [ button(rect = pygame.Rect(20, 550, 200, 20), caption = 'Overwrite Log Files' if args['overwrite'] else 'Append to Log files', bgcolor = pygame.Color('gray46')),\n\t\t\t\t button(rect = pygame.Rect(270, 550, 200, 20), caption = 'Celex Mode' if args['mode'] else 'ARPABET Mode', bgcolor = pygame.Color('gray46')),\n\t\t\t\t button(rect = pygame.Rect(20, 600, 200, 20), caption = 'Make Pitch Tracks'),\n\t\t\t\t button(rect = pygame.Rect(270, 600, 200, 20), caption = 'Set As Default'),\n\t\t\t\t button(rect = pygame.Rect(0, 650, 200, 20), caption = 'Update Formants'),\n\t\t\t\t button(rect = pygame.Rect(0, 700, 200, 40), caption = 'Start Plotmish')]\n\nfor o in onoffbuttons[-2:]:\n\to.rect.centerx = WINDOWWIDTH/2.0\n\nerrorButton = button(rect = pygame.Rect(270, 550, 200, 20), caption = 'BACK')\nerrorButton.rect.centerx = WINDOWWIDTH/2.0\n\nbuttons = textbuttons + onoffbuttons\n\ntext = \t[ \t(captionFont.render('formant.txt files:',1,BLACK),(20,82)),\n\t\t\t(captionFont.render('.wav files:',1,BLACK),(20,132)),\n\t\t\t(captionFont.render('keyword:',1,BLACK),(20,182)),\n\t\t\t(captionFont.render('log folder:',1,BLACK),(20,232)),\n\t\t\t(captionFont.render('praat:',1,BLACK),(20,282)),\n\t\t\t(captionFont.render('pitch tracks:',1,BLACK),(20,332)),\n\t\t\t(captionFont.render('celex pronunciation dictionary:',1,BLACK),(20,382)),\n\t\t\t(captionFont.render('corrected folder:',1,BLACK),(20,432)),\n\t\t\t(captionFont.render('annotator:',1,BLACK),(20,482))]\n\nmode = 'main'\n\nwhile True: # main loop\n\tfor event in pygame.event.get():\n\t\tif event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):\n\t\t\tpygame.quit() \n\t\t\tsys.exit()\n\t\t\n\t\tif mode == 'main':\n\t\t\tfor i,b in enumerate(textbuttons):\n\t\t\t\tif 'click' in b.handleEvent(event):\n\t\t\t\t\tanswer = []\n\t\t\t\t\twhile isinstance(answer, list):\n\t\t\t\t\t\tanswer = inputbox.ask(DISPLAYSURFACE,'',size = b.rect, newFont = captionFont, currentText = b.caption if not answer else answer[0], pathMode = True if i not in [2,8] else False)\n\t\t\t\t\t\tif isinstance(answer, list):\n\t\t\t\t\t\t\tanswer = completePath(answer[0].strip())\n\t\t\t\t\tif answer == 'QUITNOW':\n\t\t\t\t\t\tpygame.quit() \n\t\t\t\t\t\tsys.exit()\n\n\t\t\t\t\tb.caption = shortcut(answer.strip()) if i not in [2,8] else answer\n\t\t\t\t\tresizeText(b)\n\t\t\t\t\tupdateArgs() \n\n\t\t\n\t\t\tfor b in onoffbuttons:\n\t\t\t\tif 'click' in b.handleEvent(event):\n\t\t\t\t\tif b.caption == 'Overwrite Log Files':\n\t\t\t\t\t\tb.caption = 'Append to Log files'\n\t\t\t\t\t\targs['overwrite'] = False\n\t\t\t\t\telif b.caption == 'Append to Log files':\n\t\t\t\t\t\tb.caption = 'Overwrite Log Files'\n\t\t\t\t\t\targs['overwrite'] = True\n\t\t\t\t\tif b.caption == 'ARPABET Mode':\n\t\t\t\t\t\tb.caption = 'Celex Mode'\n\t\t\t\t\t\targs['mode'] = True\n\t\t\t\t\telif b.caption == 'Celex Mode':\n\t\t\t\t\t\tb.caption = 'ARPABET Mode'\n\t\t\t\t\t\targs['mode'] = False\n\t\t\t\t\tif b.caption == 'Set As Default':\n\t\t\t\t\t\terrors = checkDefaults()\n\t\t\t\t\t\tif not errors:\n\t\t\t\t\t\t\twriteDefaults()\n\t\t\t\t\t\telse: \n\t\t\t\t\t\t\tmode = 'error'\n\t\t\t\t\tif b.caption == 'Make Pitch Tracks':\n\t\t\t\t\t\terrors = [e for e in checkDefaults() if 'praat' in e]\n\t\t\t\t\t\tif not errors:\n\t\t\t\t\t\t\tsubprocess.call(['open', args['praat']])\n\t\t\t\t\t\t\tsubprocess.call([sendpraat, '0', 'praat', 'execute \"'+getPitch+'\"'])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmode = 'error'\n\t\t\t\t\tif b.caption == 'Update Formants':\n\t\t\t\t\t\terrors = [e for e in checkDefaults() if 'praat' in 'formant' in e or 'log' in e or 'corrected' in e]\n\t\t\t\t\t\tif not errors:\n\t\t\t\t\t\t\tsubprocess.call(['python', updateFormants, args['formant'], '-l', args['log'], '-c', args['corrected']])\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmode = 'error'\n\t\t\t\t\tif b.caption == 'Start Plotmish':\n\t\t\t\t\t\terrors = [e for e in checkDefaults() if 'corrected' not in e]\n\t\t\t\t\t\tif not errors:\n\t\t\t\t\t\t\tmessage = ['python', plotmish, args['formant'], args['wav'],args['annotator'], '-k', args['keyword'], '-o', args['log'], '-p', args['praat'], '-f0', args['pitch tracks']] \n\t\t\t\t\t\t\tif not args['overwrite']:\n\t\t\t\t\t\t\t\tmessage += ['-a']\n\t\t\t\t\t\t\tif args['mode']:\n\t\t\t\t\t\t\t\tmessage += ['-c', args['celex dict']]\n\t\t\t\t\t\t\tsubprocess.call(['cd', 'plotmish'])\n\t\t\t\t\t\t\tsubprocess.call(message)\n\t\t\t\t\t\t\tpygame.event.clear()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tmode = 'error'\n\n\t\telif mode == 'error':\n\t\t\tif 'click' in errorButton.handleEvent(event):\n\t\t\t\tmode = 'main'\n\n\tDISPLAYSURFACE.fill(WHITE)\n\tif mode == 'main':\n\t\tfor b in buttons: b.draw(DISPLAYSURFACE)\n\t\tfor t in text: DISPLAYSURFACE.blit(t[0],t[1])\n\tif mode == 'error':\n\t\terrorMessage(errors)\n\t\terrorButton.draw(DISPLAYSURFACE)\n\n\tpygame.display.update() # update screen\n\tFPSCLOCK.tick(FPS)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"start_plotmish.py","file_name":"start_plotmish.py","file_ext":"py","file_size_in_byte":10086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"242628306","text":"import os\nimport numpy as np\nimport pandas as pd\nimport xarray as xr\nimport matplotlib.pyplot as plt\n\n\ndef load_Neah_Bay(datadir):\n \"\"\"\n Function to load the Neah Bay tidal station data from 2015 - 2016\n and returns a dataframe and a Datetime Index object\n Datadir is the directory path to where the data is located\n \"\"\"\n if not os.path.exists(datadir + '/*NeahBay.csv'):\n return None\n else:\n NeahBay_2014 = pd.read_csv(datadir + \"/2014_NeahBay.csv\",\n parse_dates=['Date Time'])\n NeahBay_2015 = pd.read_csv(datadir + \"/2015_NeahBay.csv\",\n parse_dates=['Date Time'])\n NeahBay_2016 = pd.read_csv(datadir + \"/2016_NeahBay.csv\",\n parse_dates=['Date Time'])\n NeahBay = NeahBay_2014.append(NeahBay_2015)\n NeahBay = NeahBay.append(NeahBay_2016)\n return NeahBay\n\n\ndef load_Port_Townsend(datadir):\n \"\"\"\n Function to load the Port Townsend tidal station data from 2015\n & 2016. Supply the directory to where the csv files with the\n data are saved. Returns None if files are not located in\n specified directory.\n \"\"\"\n if not os.path.exists(datadir + '/*PortTownsend.csv'):\n return None\n else:\n PortTownsend_2015 = pd.read_csv(datadir +\n '/2015_PortTownsend.csv',\n parse_dates=['Date Time'])\n PortTownsend_2016 = pd.read_csv(datadir +\n '/2016_PortTownsend.csv',\n parse_dates=['Date Time'])\n PortTownsend = PortTownsend_2014.append(PortTownsend_2015)\n PortTownsend = PortTownsend.append(PortTownsend_2016)\n return PortTownsend\n\n\ndef load_Port_Angeles(datadir):\n \"\"\"\n Function to load the Port Angeles tidal station data from 2015\n & 2016. Supply the directory to where the csv files with the\n data are saved. Returns None if files are not located in\n specified directory.\n \"\"\"\n if not os.path.exists(datadir + '/*PortAngeles.csv'):\n return None\n else:\n # Load the Port Angeles tidal data and put into one dataframe\n PortAngeles_2014 = pd.read_csv(datadir +\n '/2014_PortAngeles.csv',\n parse_dates=['Date Time'])\n PortAngeles_2015 = pd.read_csv(datadir +\n '/2015_PortAngeles.csv',\n parse_dates=['Date Time'])\n PortAngeles_2016 = pd.read_csv(datadir +\n '/2016_PortAngeles.csv',\n parse_dates=['Date Time'])\n PortAngeles = PortAngeles_2014.append(PortAngeles_2015)\n PortAngeles = PortAngeles.append(PortAngeles_2016)\n return PortAngeles\n\n\ndef load_tide_data(datadir):\n \"\"\"\n Upper level load function for the Tide Data.\n Datadir is the directory where the data .csv files are saved\n \"\"\"\n NeahBay = load_Neah_Bay(datadir)\n PortAngeles = load_Port_Angeles(datadir)\n PortTownsend = load_Port_Townsend(datadir)\n if NeahBay is None:\n return None\n elif PortAngeles is None:\n return None\n elif PortTownsend is None:\n return None\n else:\n return NeahBay, PortAngeles, PortTownsend\n\n\ndef create_tide_dataset(NeahBay, PortAngeles, PortTownsend):\n \"\"\"\n Function takes in the tidal station dataframes and returns\n an Xarray Dataset with the tidal station data\n \"\"\"\n NB = xr.DataArray(NeahBay[' Water Level'], dims='datetime')\n PA = xr.DataArray(PortAngeles[' Water Level'], dims='datetime')\n PT = xr.DataArray(PortTownsend[' Water Level'], dims='datetime')\n Tides = xr.Dataset({'NeahBay': NB, 'PortAngeles': PA,\n 'PortTownsend': PT})\n return Tides\n\n\ndef plot_tide_data(dt):\n \"\"\"\n This function plots the three tidal stations for the given\n time period along with a marker showing the time and elevation\n selected using the widget slider\n \"\"\"\n fig, axes = plt.subplots(nrows=3)\n NB.plot(ax=axes[0])\n axes[0].scatter(x=NB.datetime.values[dt], y=NB.values[dt],\n color=\"red\", s=100)\n axes[0].grid()\n\n PA.plot(ax=axes[1])\n axes[1].scatter(x=NB.datetime.values[dt], y=PA.values[dt],\n color=\"red\", s=100)\n axes[1].grid()\n\n PT.plot(ax=axes[2])\n axes[2].scatter(x=NB.datetime.values[dt], y=PT.values[dt],\n color=\"red\", s=100)\n axes[2].grid()\n\n\ndef plot_tidal_elevation(slide):\n \"\"\"\n Function to plot the tidal elevation taken from\n the function plot_tide_data interactive slider\n \"\"\"\n try:\n fig, axes = plt.subplots(nrows=1, ncols=1)\n # Get each station's tidal elevation based on the widget slider\n NBelev = NB.values[slide.value]\n PAelev = PA.values[slide.value]\n PTelev = PT.values[slide.value]\n # Create dummy x-values\n x = (1, 2, 3)\n y = (NBelev, PAelev, PTelev)\n # Create the figure with station labels\n plt.scatter(x, y, s=100, color=\"red\", zorder=2)\n plt.plot(x, y, 'b', zorder=1)\n plt.xticks(x, ['Neah Bay', 'Port Angeles', 'Port Townsend'],\n rotation='vertical')\n plt.grid()\n plt.ylabel('Tidal Elevation (m)')\n except:\n return None\n","sub_path":"tydal/tide_utils.py","file_name":"tide_utils.py","file_ext":"py","file_size_in_byte":5456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"619966889","text":"N, M = map(int, input().split())\nif N < M:\n max_num = M\n min_num = N\nelif N > M:\n max_num = M\n min_num = N\nelse:\n max_num == M\n min_num == N\n\n\nfor i in range(1, min_num+1): #2부터 min_num까지 체크\n if min_num % i == 0 and max_num % i == 0:\n result_1 = i\n\nj = 1\nwhile True: #max_num이 min_num으로 나누어 떨어지는 첫번째 수\n if (max_num * j) % min_num == 0:\n result_2 = max_num * j\n break\n else:\n j += 1\n\nprint(result_1)\nprint(result_2)","sub_path":"2609.py","file_name":"2609.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"619442550","text":"# -*- coding: utf-8 -*-\r\nfrom django import template\r\nfrom django.template import Node, Variable, TemplateSyntaxError\r\nfrom django.conf import settings\r\nfrom django.contrib.contenttypes.models import ContentType\r\nfrom django.template.loader import get_template, select_template\r\nfrom django.contrib.auth.models import User\r\n\r\nfrom ratings.models import Rating, RatingVote\r\n\r\nregister = template.Library()\r\n\r\nRATINGS_CONFIG = getattr(settings, \"RATINGS_CONFIG\", {})\r\nRATING_TABLE_COUNT = getattr(settings, 'RATING_TABLE_COUNT', 5)\r\n\r\n@register.simple_tag\r\ndef get_rating_span(obj):\r\n rating = str(obj.rating_score)\r\n if score > 0:\r\n rating += '+'\r\n rating_class = \"positive\"\r\n elif score < 0:\r\n rating_class = \"negative\"\r\n else:\r\n rating_class = \"default\"\r\n return \"\" + rating + \"\"\r\n\r\n@register.inclusion_tag('ratings/user_rating.html', takes_context=True)\r\ndef get_user_rating_div(context, obj):\r\n rating = round(obj.rating_score, 1)\r\n if abs(rating) < 2210:\r\n context['score'] = abs(int(rating/23))\r\n else:\r\n context['score'] = 96\r\n context['rating'] = rating\r\n return context\r\n \r\n@register.tag\r\ndef render_rating(parser, token):\r\n bits = token.contents.split(' ')[1:]\r\n if not (len(bits) == 2 or len(bits) == 3):\r\n raise TemplateSyntaxError(\"Incorrect count of parameters %d expected 2 or 3\" % len(bits))\r\n if len(bits) == 2:\r\n return RenderRatingNode(bits[0], bits[1])\r\n else:\r\n return RenderRatingNode(bits[0], bits[1], bits[2])\r\n \r\nclass RenderRatingNode(Node):\r\n \r\n def __init__(self, obj, obj_type, user=None):\r\n self.obj = Variable(obj)\r\n self.obj_type = Variable(obj_type)\r\n self.user = user and Variable(user) or None\r\n\r\n def can_vote(self, current_user, owner, rating):\r\n # Check if anonymus\r\n res = current_user.is_authenticated()\r\n # Check if this object owned by current user\r\n if res and owner: \r\n # Check, if owner is list, turple, or some other iterable object - to check on all items of it\r\n if getattr(owner, '__iter__', False):\r\n res = reduce(lambda r, u: r and u != current_user, owner, True)\r\n else:\r\n res = owner != current_user\r\n # Check if already voted\r\n if res:\r\n res = not RatingVote.objects.filter(rating=rating, user=current_user).exists()\r\n return res\r\n\r\n def get_rating(self, obj):\r\n rating = '%.1f' % obj.rating_score\r\n if obj.rating_score > 0:\r\n rating = '+' + rating\r\n rating_class = \"positive\"\r\n elif obj.rating_score < 0:\r\n rating_class = \"negative\"\r\n else:\r\n rating_class = \"default\"\r\n return rating, rating_class\r\n \r\n def render(self, context, template_name=\"ratings/default_rating.html\"):\r\n obj = self.obj.resolve(context)\r\n obj_type = self.obj_type.resolve(context)\r\n if self.user: \r\n user = self.user.resolve(context)\r\n else:\r\n user = None\r\n can_vote = self.can_vote(context['request'].user, user, obj.rating)\r\n rating, rating_class = self.get_rating(obj)\r\n context['rating'] = rating\r\n context['can_vote'] = can_vote\r\n context['rating_class'] = rating_class\r\n context['obj_id'] = obj.id\r\n context['obj_type'] = obj_type\r\n \r\n t = get_template(template_name)\r\n return t.nodelist.render(context)\r\n\r\n\r\n@register.inclusion_tag('ratings/rating_table.html', takes_context=True)\r\ndef get_rating_table(context):\r\n from poetry.models import Book\r\n context['top_users'] = User.objects\\\r\n .order_by('-profile__rating_score')[:RATING_TABLE_COUNT]\r\n context['top_books'] = Book.objects\\\r\n .order_by('-rating_score')[:RATING_TABLE_COUNT]\r\n return context\r\n\r\n","sub_path":"ratings/templatetags/ratings_tags.py","file_name":"ratings_tags.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"489888679","text":"##########################################################################################\n# This script will create a EKS cluster and set up kubectl to connect to it. #\n# It assumes that: #\n# - you have a working AWS CLI (of which we will use the credentials) #\n# - the AWS CLI credentials refer to an admin user #\n# - you have set up a role, a VPC and a security group #\n# using the instructions on the Getting started page #\n# https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html #\n# #\n# Parameters: #\n# --clusterName name of the cluster, default myCluster #\n# --eksRoleName name of the IAM role for the cluster, default EKSEC2UserRole #\n# --stackName CloudFormation stack for VPC and security group, default eks-vpc #\n# #\n# At this point, we use Kubernetes version 1.11 #\n##########################################################################################\n\n\nimport boto3\nimport yaml\nimport argparse\nfrom os.path import expanduser\nk8Version=\"1.13\"\n\n\n##########################################################################################\n# Parse parameters #\n##########################################################################################\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--clusterName\",\n type=str,\n default=\"myCluster\",\n help=\"Name of the cluster that we will create\")\n\nparser.add_argument(\"--eksRoleName\",\n type=str,\n default=\"EKSEC2UserRole\",\n help=\"Name of the EKS service IAM role\")\n\n\nparser.add_argument(\"--stackName\",\n type=str,\n default=\"eks-vpc\",\n help=\"Name of the cloud formation stack containing VPC and security group\")\n\n\nargs = parser.parse_args()\nclusterName = args.clusterName\neksRoleName = args.eksRoleName\nstackName = args.stackName\n\nprint(\"Creating cluster \", clusterName)\nprint(\"Using IAM role \", eksRoleName)\nprint(\"Using CloudFormation stack \", stackName)\n\n##########################################################################################\n# Collect data #\n##########################################################################################\n\n\n# Create IAM client\niam = boto3.client('iam')\n\n# Get role information\nresponse = iam.get_role(RoleName=eksRoleName)\nroleArn = response['Role']['Arn']\nprint(\"Found role ARN: \", roleArn)\n\n\ncloudFormation = boto3.client('cloudformation')\nresponse = cloudFormation.describe_stack_resources(StackName = stackName, LogicalResourceId=\"VPC\")\nvpcId = response['StackResources'][0]['PhysicalResourceId']\nprint(\"Found VPC ID: \", vpcId)\n\n\nresponse = cloudFormation.describe_stack_resources(StackName = stackName, LogicalResourceId=\"ControlPlaneSecurityGroup\")\nsecGroupId = response['StackResources'][0]['PhysicalResourceId']\nprint(\"Found security group ID: \", secGroupId)\n\n\nec2 = boto3.resource('ec2')\nvpc = ec2.Vpc(vpcId)\nsubnets = [subnet.id for subnet in vpc.subnets.all()]\nprint(\"Found subnets: \", subnets)\n\n##########################################################################################\n# Create cluster #\n##########################################################################################\n\n\neks = boto3.client(\"eks\")\nr = eks.create_cluster(name=clusterName, version=k8Version, roleArn = roleArn, resourcesVpcConfig = {'subnetIds' : subnets, 'securityGroupIds' : [secGroupId]})\nprint(\"Submitted create command, response status is : \", r['cluster']['status'])\nprint(\"Now waiting for cluster creation to be completed - be patient, this can take up to ten minutes\")\nwaiter = eks.get_waiter(\"cluster_active\")\nwaiter.wait(name=clusterName)\n\n##########################################################################################\n# Update kubectl configuration #\n##########################################################################################\n\n\nprint(\"Cluster available, now creating config file\")\ncluster = eks.describe_cluster(name=clusterName)\ncluster_cert = cluster[\"cluster\"][\"certificateAuthority\"][\"data\"]\ncluster_ep = cluster[\"cluster\"][\"endpoint\"]\ncluster_arn = cluster[\"cluster\"][\"arn\"]\n\ncluster_config = {\n \"apiVersion\": \"v1\",\n \"kind\": \"Config\",\n \"clusters\": [\n {\n \"cluster\": {\n \"server\": str(cluster_ep),\n \"certificate-authority-data\": str(cluster_cert)\n },\n \"name\": cluster_arn\n }\n ],\n \"contexts\": [\n {\n \"context\": {\n \"cluster\": cluster_arn,\n \"user\": cluster_arn,\n },\n \"name\": cluster_arn\n }\n ],\n \"current-context\": cluster_arn,\n \"preferences\": {},\n \"users\": [\n {\n \"name\": cluster_arn,\n \"user\": {\n \"exec\": {\n \"apiVersion\": \"client.authentication.k8s.io/v1alpha1\",\n \"command\": \"aws-iam-authenticator\",\n \"args\": [\n \"token\", \"-i\", clusterName\n ]\n }\n }\n\t }\n ]\n}\n\nconfig_text=yaml.dump(cluster_config, default_flow_style=False)\nconfig_file = expanduser(\"~\") + \"/.kube/config\"\nprint(\"Writing kubectl configuration to \", config_file)\nopen(config_file, \"w\").write(config_text)\nprint(\"Done\")\n\n","sub_path":"cluster/create_cluster.py","file_name":"create_cluster.py","file_ext":"py","file_size_in_byte":6274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"125740937","text":"# 求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222\n# (此时共有5个数相加),几个数相加由键盘控制。\n\nfrom functools import reduce\n\ndef f():\n #输入\n a=int(input('Please input a:'))\n n=int(input('Please input n:'))\n\n # 获得n个数值\n sn=[]\n tn=0\n for i in range (1,n+1):\n tn=tn+a\n a=a*10\n sn.append(tn)\n print(tn)\n\n # 对n个数值进行求和\n '''\n S=0\n for j in range(0,len(sn)):\n S+=sn[j]\n\n print('The sum is',S)\n '''\n \n print(type(sn))\n sn = reduce(lambda x,y : x + y,sn)\n print(type(sn))\n print('The sum is',sn)\n\ndef run():\n f()\n\n\n\nrun()\n\n \n","sub_path":"Practices/Practice18.py","file_name":"Practice18.py","file_ext":"py","file_size_in_byte":702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"20275932","text":"class Solution:\n def reverseWords(self, s: str) -> str:\n s= s.strip()\n s = s.split(\" \")\n ans = \"\"\n for elem in s[::-1]:\n if elem != \"\":\n ans = ans + elem + \" \"\n\n return ans.strip()\nprint(Solution().reverseWords(\"a good example\"))","sub_path":"字符串/151. 翻转字符串里的单词.py","file_name":"151. 翻转字符串里的单词.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"10614760","text":"import math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the countingValleys function below.\ndef countingValleys(n, s):\n c = 0\n counter = 0\n \n val = []\n for i in range(n):\n if (s[i] == 'U'):\n val.append(1)\n elif(s[i] == 'D'):\n val.append(-1)\n \n for i in range(len(val)):\n flag = 0\n if (c == -1):\n flag = 1\n c = c + val[i]\n if((flag == 1) & (c == 0)):\n counter = counter + 1\n return (counter)\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input())\n\n s = input()\n\n result = countingValleys(n, s)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()","sub_path":"Count_Valley.py","file_name":"Count_Valley.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"56382425","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\ndef noop_gettext(s):\n return s\n\ngettext = noop_gettext\n\n\nHELPER_SETTINGS = {\n 'TIME_ZONE': 'UTC',\n 'INSTALLED_APPS': [\n 'aldryn_apphook_reload', # for tests\n 'aldryn_apphooks_config',\n 'aldryn_common',\n 'aldryn_reversion',\n 'aldryn_translation_tools',\n 'reversion',\n 'appconf',\n 'bootstrap3',\n 'djangocms_text_ckeditor',\n 'easy_thumbnails',\n 'extended_choices',\n 'filer',\n 'mptt',\n 'parler',\n 'sortedm2m',\n 'standard_form',\n ],\n 'LANGUAGES': (\n ('en', 'English'),\n ('de', 'German'),\n ),\n 'PARLER_LANGUAGES': {\n 1: [\n {\n 'code': u'en',\n 'fallbacks': [u'de'],\n 'hide_untranslated': False\n },\n {\n 'code': u'de',\n 'fallbacks': [u'en'],\n 'hide_untranslated': False\n }\n ],\n 'default': {\n 'code': u'en',\n 'fallbacks': [u'en'],\n 'hide_untranslated': False}\n },\n 'PARLER_ENABLE_CACHING': False,\n 'CMS_LANGUAGES': {\n 'default': {\n 'public': True,\n 'hide_untranslated': False,\n 'fallbacks': ['en']\n\n },\n 1: [\n {\n 'public': True,\n 'code': 'en',\n 'fallbacks': [u'de'],\n 'hide_untranslated': False,\n 'name': gettext('en'),\n 'redirect_on_fallback': True,\n },\n {\n 'public': True,\n 'code': 'de',\n 'fallbacks': [u'en'],\n 'hide_untranslated': False,\n 'name': gettext('de'),\n 'redirect_on_fallback': True,\n },\n ],\n },\n 'THUMBNAIL_PROCESSORS': (\n 'easy_thumbnails.processors.colorspace',\n 'easy_thumbnails.processors.autocrop',\n 'filer.thumbnail_processors.scale_and_crop_with_subject_location',\n 'easy_thumbnails.processors.filters',\n ),\n 'EMAIL_BACKEND': 'django.core.mail.backends.locmem.EmailBackend',\n 'DEBUG': True,\n # 'TEMPLATE_DEBUG': True,\n 'ALDRYN_EVENTS_USER_REGISTRATION_EMAIL': True,\n 'CACHES': {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.dummy.DummyCache',\n }\n },\n 'MIDDLEWARE_CLASSES': [\n 'aldryn_apphook_reload.middleware.ApphookReloadMiddleware',\n 'django.middleware.http.ConditionalGetMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.locale.LocaleMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'cms.middleware.language.LanguageCookieMiddleware',\n 'cms.middleware.user.CurrentUserMiddleware',\n 'cms.middleware.page.CurrentPageMiddleware',\n 'cms.middleware.toolbar.ToolbarMiddleware'\n ],\n 'ALDRYN_BOILERPLATE_NAME': 'bootstrap3',\n}\n\n# tablib does not supports py2.6/django1.6\nimport imp\ntry:\n imp.find_module('django_tablib')\n HELPER_SETTINGS['INSTALLED_APPS'].append('django_tablib')\nexcept ImportError:\n pass\n\n\ndef run():\n from djangocms_helper import runner\n runner.cms('aldryn_events', extra_args=['--boilerplate'])\n\nif __name__ == \"__main__\":\n run()\n","sub_path":"test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":3588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"156621271","text":"# -*- coding: utf8 -*-\n\n# Code from https://wikidocs.net/26 - Jump to Python\nf = open(\"new_file.txt\", 'w', encoding='utf8')\n# new_file.txt 라는 이름의 파일에 쓰기 위해 연다(open), ecoding 방식은 utf8\n\nfor i in range(1, 11): \n data = \"%d 번째 줄입니다.\\n\" % i \n # print(data)\n f.write(data) \n\nf.close()","sub_path":"15_file_handling/file_write_ex_1.py","file_name":"file_write_ex_1.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"73084151","text":"#!/usr/bin/env python\n#coding:utf8\n\nimport sys\nimport os\nimport struct\nimport socket\nimport json\nimport time\n\nfrom errcode import *\nfrom lib.queryEngine import *\n\nfrom comm.config import config\nfrom comm.srf_log import logger,init_log,logger_d,logger_e\nfrom comm.deco import DecoLog\nimport zyd_interface\nimport channel_interface\nimport const_ops\nfrom city_code import *\nfrom distutils.version import LooseVersion, StrictVersion\n\nimport const\nimport const_activity\nimport const_state\nimport assets_config\nimport xycd_crypt\nimport urllib\nfrom mako.template import Template\n\nCUR_PATH = os.path.dirname(os.path.abspath(__file__))\n\n\n\nURL_GET_NOTICE = 'https://%s/homeinfo/get_notice?' % (const.HTTPS_DOMAIN)\n \nclass HomePageHandler(object):\n def __init__(self):\n self._host = config.get_string('MysqlApp', 'host')\n self._user = config.get_string('MysqlApp', 'user')\n self._passwd = config.get_string('MysqlApp', 'password')\n self._port = config.get_int('MysqlApp', 'port')\n self._db = config.get_string('MysqlApp', 'db')\n self._order_table = 'loan_order'\n self._reward_table = 'grant_reward_record'\n self._user_table = 'user_info'\n self._zyd_commission_table = 'zyd_commission_rate'\n #公告配置\n self._notice_table = 'announcements'\n self._notice_template_file = CUR_PATH + \"/../\" + \"misc/fenxiang/announcement.html\"\n self._op_content_table = 'operation_contents'\n self._banner_table = 'banner_configs'\n\n\n def do_homeinfo(self, path_func, params):\n function = getattr(self, \"handle_\" + path_func)\n if callable(function):\n return function(params)\n \n\n def get_product(self, pic_conf, city_code, soft_version):\n #获取当前城市的最高返佣比\n mysql_conn = queryEngine(self._host, self._user, self._passwd, self._port, self._db)\n mysql_conn.init()\n sql_cmd = \"SELECT MAX(max_commission_rate) from %s.%s WHERE city_code=%d\" % (self._db, self._zyd_commission_table, city_code)\n s_results = mysql_conn.execute(sql_cmd)\n max_rate = 0.0\n if s_results is not None and len(s_results) > 0:\n max_rate = float(s_results[0][0]) / 1000\n\n #{'name':产品名称, 'icon':首页产品列表的图标, 'desc':首页产品的说明, 'ratio':首页的产品浮动显示的比例, 'url':产品点击的url, 'detail_pic':产品详情说明的图片, 'state':在线或下线, 'pro_id':产品id}\n #PRO_DIYA = {'name':'房屋抵押贷款', 'icon':pic_conf.get('diya_icon_pic_url'), 'desc':const.DIYA_DESC, 'ratio':max_rate, 'url':const.DIYA_DETAIL_URL, 'state':const.PRO_STATE_ONLINE, 'pro_id':const.PRO_ID_DIYA}\n PRO_DIYA = {'name':'房屋抵押贷款', 'icon':const_ops.PRODUCT_ICON['diya'], 'desc':const.DIYA_DESC, 'ratio':max_rate, 'url':const.DIYA_DETAIL_URL, 'state':const.PRO_STATE_ONLINE, 'pro_id':const.PRO_ID_DIYA}\n PRO_DIYA['periods'] = const.loan_period_list\n PRO_DIYA['loan_type'] = const.loan_type_list\n city_name = city_code_list[city_code]['cityName']\n PRO_DIYA['pro_feature'] = const.diya_pro_feature[city_name]\n PRO_DIYA['month_rate'] = const.diya_month_rate[city_name]\n PRO_DIYA['ci_freq'] = ''\n \n #PRO_XINYONG = {'name':'信用贷款', 'icon':pic_conf.get('wudiya_icon_pic_url'), 'desc':const.XINYONG_DESC, 'ratio':const.wudiya_tips_ratio, 'url':const.DIYA_DETAIL_URL, 'state':const.PRO_STATE_OFFLINE, 'add_cont':const.XINYONG_NEW_WINDOW_TITLE, 'pro_id':const.PRO_ID_XINYONG}\n PRO_XINYONG = {'name':'信用贷款', 'icon':const_ops.PRODUCT_ICON['xinyong'], 'desc':const.XINYONG_DESC, 'ratio':const.wudiya_tips_ratio, 'url':const.DIYA_DETAIL_URL, 'state':const.PRO_STATE_OFFLINE, 'add_cont':const.XINYONG_NEW_WINDOW_TITLE, 'pro_id':const.PRO_ID_XINYONG}\n PRO_XINYONG['pro_feature'] = const.wudiya_pro_feature[city_name]\n PRO_XINYONG['month_rate'] = const.wudiya_month_rate \n\n #兼容1.1.0之前版本的产品图标\n if LooseVersion(soft_version) < LooseVersion(\"1.1.0\"):\n PRO_DIYA['icon'] = \"https://dn-xiaoying-zyd.qbox.me/chengdan/icon/diya-20160601.png\"\n PRO_XINYONG['icon'] = \"https://dn-xiaoying-zyd.qbox.me/chengdan/icon/xinyong-20151224.png\"\n \n\n return [PRO_DIYA, PRO_XINYONG]\n \n\n def handle_get_home_info(self, params, is_login):\n mysql_conn = queryEngine(self._host, self._user, self._passwd, self._port, self._db)\n mysql_conn.init()\n\n ret_obj = {'errcode':ERR_SUCC, 'errstr':ERR_STR.get(ERR_SUCC), 'data':{}}\n #产品列表\n city_code = int(params.get('city_code', 0))\n if city_code == 0:\n ret_obj['errcode'] = ERR_PARAMS\n ret_obj['errstr'] = ERR_STR.get(ERR_PARAMS)\n return ret_obj\n city_name = city_code_list[city_code]['cityName']\n soft_version = params.get('soft_version')\n\n pic_conf = assets_config.get_pic_config()\n product_list = self.get_product(pic_conf, city_code, soft_version)\n banner_1 = pic_conf.get('banner_1_url')\n banner_2 = pic_conf.get('banner_2_url')\n banner_3 = pic_conf.get('banner_3_url')\n banner_4 = pic_conf.get('banner_4_url') \n banner_5 = pic_conf.get('banner_5_url') \n #统计提单次数\n sql_cmd = \"SELECT count(FuiOrder_id) from %s.%s WHERE FuiOrder_loan_type=%d AND FuiProperty_city_code=%d\" % (self._db, self._order_table, const.ORDER_LOAN_TYPE_DIYA, city_code)\n s_results = mysql_conn.execute(sql_cmd)\n logger_d.info(\"sql_cmd:%s\" % (sql_cmd))\n ci_freq = 0\n if s_results is not None and len(s_results) > 0:\n ci_freq = int(s_results[0][0]) \n\n if city_name in ['南京市', '合肥市']:\n product_list[0]['ci_freq'] = str(ci_freq + 500) + '次提交' \n\n \n #公告\n notice_info = []\n sql_cmd = \"SELECT id, title from %s.%s WHERE ended_at>=%d AND published_at<=%d\" % (self._db, self._notice_table, int(time.time()), int(time.time())) \n s_results = mysql_conn.execute(sql_cmd)\n if s_results is not None:\n for i in range(len(s_results)):\n notice_id = int(s_results[i][0])\n info_dict = {'notice_id':notice_id}\n info_dict['sign'] = xycd_crypt.app_encrypt(info_dict)\n notice_info.append({'title':s_results[i][1], 'link':URL_GET_NOTICE + urllib.urlencode(info_dict)}) \n\n banner = None\n \n #banner��容配置从数据库中读取\n if is_login:\n str_login = 'login'\n action_name = 'action'\n else:\n str_login = 'not_login'\n action_name = 'pre_login_action'\n '''\n str_login = 'login'\n action_name = 'action'\n '''\n\n #extra_date在数据库表中的字段名\n request_os = params.get('os')\n extra_data_name = const_ops.BANNER_EXTRA_DADA_NAME[request_os][str_login]\n\n sql_cmd = \"SELECT title, image_url, %s, %s FROM %s.%s WHERE city_id = %d AND is_del = %d AND published_at < %d AND ended_at > %d AND location != 0 ORDER BY location\" %\\\n (action_name, extra_data_name, self._db, self._banner_table, city_code, 0, int(time.time()), int(time.time()))\n logger_d.info(\"sql_cmd:%s\" % (sql_cmd))\n s_result = mysql_conn.execute(sql_cmd)\n if s_result is not None and len(s_result) > 0:\n banner = []\n for i in range(len(s_result)):\n banner_item = {}\n banner_item['title'] = s_result[i][0]\n banner_item['imageurl'] = s_result[i][1]\n banner_item['action'] = s_result[i][2]\n banner_item['extra_data'] = s_result[i][3]\n banner.append(banner_item)\n\n\n #获取统计信息\n user_id = params.get('user_id')\n if user_id is not None and user_id != '':\n sql_cmd = \"\"\"SELECT FuiOrder_id, FuiLoan_amount, FstrOrder_state FROM %s.%s WHERE FuiUid=%d\"\"\" % (self._db, self._order_table, int(user_id))\n logger_d.info(\"sql_cmd:%s\" %(sql_cmd))\n s_results = mysql_conn.execute(sql_cmd)\n if s_results is not None:\n total = {'num':0, 'amount':0}\n for i in range(len(s_results)):\n order_item = {}\n amount = float(s_results[i][1])/100\n\n temp_state = json.loads(s_results[i][2])\n #if temp_state[-1]['state'] == const_state.state_fangkuan:\n if temp_state[-1]['state_type'] == const_state.state_type_chengjiao:\n total['num'] += 1\n total['amount'] += amount\n \n ret_obj['data']['total'] = total\n else:\n logger_d.info(\"mysql error:%s\" % (sql_cmd))\n ret_obj['errcode'] = ERR_SERVICE\n ret_obj['errstr'] = ERR_STR.get(ERR_SERVICE)\n\n ret_obj['data']['product_list'] = product_list\n ret_obj['data']['banner'] = banner\n\n #获取动态返佣\n reward_num = int(params.get('reward_num', 20))\n ret_obj['data']['reward_info'] = self.get_latest_reward(reward_num)\n #获取首页运营内容\n ret_obj['data']['op_contents'] = self.get_home_ops(params)\n\n #其他配置\n ret_obj['data']['planform_feature'] = const.platform_feature\n ret_obj['data']['notice'] = notice_info\n ret_obj['data']['activity_doc'] = const.activity_doc\n return ret_obj\n\n def handle_get_notice(self, params):\n mysql_conn = queryEngine(self._host, self._user, self._passwd, self._port, self._db)\n mysql_conn.init()\n notice_id = params.get('notice_id')\n if notice_id is None:\n return ''\n sql_cmd = \"select title, content, published_at content from %s.%s where id=%d\" % (self._db, self._notice_table, int(notice_id))\n s_results = mysql_conn.execute(sql_cmd)\n if s_results is not None and len(s_results) > 0:\n notice_title = s_results[0][0]\n notice_content = s_results[0][1]\n publish_time = s_results[0][2]\n template = Template(filename=self._notice_template_file, input_encoding='utf-8')\n \n return template.render(announcement_title=notice_title, announcement_content=notice_content, announcement_date=time.strftime(\"%Y/%m/%d %H:%M\",time.localtime(publish_time)), announcement_time='').encode('utf8')\n else:\n return ''\n\n\n def get_latest_reward(self, reward_num):\n mysql_conn = queryEngine(self._host, self._user, self._passwd, self._port, self._db)\n mysql_conn.init()\n\n ret_list = []\n\n sql_cmd = \"SELECT id, grant_user_id, grant_reward_amount, update_time FROM %s.%s WHERE grant_reward_status = %d AND grant_reward_type = %d ORDER BY id DESC LIMIT %d\" %\\\n (self._db, self._reward_table, const.GR_REWARD_OK, const.GR_TYPE_COMMISSION, reward_num)\n\n logger_d.info(\"sql_cmd:%s\" % (sql_cmd))\n s_results = mysql_conn.execute(sql_cmd)\n if s_results is not None:\n for i in range(len(s_results)):\n reward_item = {}\n reward_item['reward_id'] = int(s_results[i][0]) \n reward_item['reward_amount'] = int(s_results[i][2])/100\n t_time = str(s_results[i][3])\n t_obj = time.strptime(t_time, \"%Y-%m-%d %H:%M:%S\")\n #reward_item['reward_time'] = int(time.mktime(t_obj))\n\n grant_user_id = int(s_results[i][1])\n sql_cmd = \"SELECT nickname FROM %s.%s WHERE user_id = %d\" % (self._db, self._user_table, grant_user_id)\n logger_d.info(\"sql_cmd:%s\" % (sql_cmd))\n t_results = mysql_conn.execute(sql_cmd)\n if t_results is not None:\n reward_item['nick_name'] = str(t_results[0][0])\n else:\n logger_d.info(\"mysql query error:%s\" % (sql_cmd))\n return []\n ret_list.append(reward_item)\n else:\n logger_d.info(\"mysql query error:%s\" % (sql_cmd))\n return []\n\n return ret_list\n\n\n def get_home_ops(self, params):\n '''\n 首页内容运营\n '''\n mysql_conn = queryEngine(self._host, self._user, self._passwd, self._port, self._db)\n mysql_conn.init()\n\n city_code = int(params.get('city_code', 0))\n ret_list = []\n #获取置顶广告位内容\n sql_cmd = \"SELECT title, img_url, content, id, published_at FROM %s.%s WHERE position = %d AND ended_at = %d AND published_at < %d AND city_id in (0, %d) \" %\\\n (self._db, self._op_content_table, const_ops.HOMEPAGE_OPS_TYPE['top'], 0, int(time.time()), city_code)\n logger_d.info(\"sql_cmd:%s\" % (sql_cmd))\n s_results = mysql_conn.execute(sql_cmd)\n top_op_exist = False\n if s_results is not None and len(s_results) > 0:\n top_op_exist = True\n op_item = {}\n #op_item['position'] = const_ops.HOMEPAGE_OPS_TYPE['top']\n op_item['title'] = str(s_results[0][0])\n op_item['img_url'] = str(s_results[0][1])\n #op_item['content'] = str(s_results[0][2])\n op_item['redirect_url'] = const_ops.HOMEPAGE_OPS_REDIRECT_URL + '?op_id=' + str(s_results[0][3]) \n op_item['date'] = int(s_results[0][4])\n ret_list.append(op_item)\n else: #将最新一条内容显示到置顶广告位\n sql_cmd = \"SELECT title, img_url, content, id, published_at FROM %s.%s WHERE city_id in (0, %d) AND position = %d AND ended_at = %d AND published_at < %d ORDER BY updated_at DESC LIMIT 1\" %\\\n (self._db, self._op_content_table, city_code, const_ops.HOMEPAGE_OPS_TYPE['list'], 0, int(time.time()))\n logger_d.info(\"sql_cmd:%s\" % (sql_cmd))\n s_results = mysql_conn.execute(sql_cmd)\n if s_results is not None and len(s_results) > 0:\n op_item = {}\n #op_item['position'] = const_ops.HOMEPAGE_OPS_TYPE['top']\n op_item['title'] = str(s_results[0][0])\n op_item['img_url'] = str(s_results[0][1])\n #op_item['content'] = str(s_results[0][2])\n op_item['redirect_url'] = const_ops.HOMEPAGE_OPS_REDIRECT_URL + '?op_id=' + str(s_results[0][3]) \n op_item['date'] = int(s_results[0][4])\n ret_list.append(op_item)\n else:\n return []\n\n #获取最新三条运营内容\n sql_cmd = \"SELECT title, img_url, content, id, published_at FROM %s.%s WHERE city_id in (0, %d) AND position = %d AND ended_at = %d AND published_at < %d ORDER BY updated_at DESC LIMIT 4\" %\\\n (self._db, self._op_content_table, city_code, const_ops.HOMEPAGE_OPS_TYPE['list'], 0, int(time.time()))\n logger_d.info(\"sql_cmd:%s\" % (sql_cmd))\n s_results = mysql_conn.execute(sql_cmd)\n if s_results is not None:\n if top_op_exist:\n s_results = s_results[:3]\n else:\n s_results = s_results[1:4]\n for i in range(len(s_results)):\n op_item = {}\n #op_item['position'] = const_ops.HOMEPAGE_OPS_TYPE['list']\n op_item['title'] = str(s_results[i][0])\n op_item['img_url'] = str(s_results[i][1])\n #op_item['content'] = str(s_results[i][2])\n op_item['redirect_url'] = const_ops.HOMEPAGE_OPS_REDIRECT_URL + '?op_id=' + str(s_results[i][3]) \n op_item['date'] = int(s_results[0][4])\n ret_list.append(op_item) \n\n return ret_list \n\n\n\n\n\n","sub_path":"小赢理财-APP服务器/homepage_handler.py","file_name":"homepage_handler.py","file_ext":"py","file_size_in_byte":15854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"60649747","text":"import pandas as pd\nfrom keras.utils import to_categorical\nimport numpy as np\nimport time\nimport gc\nfrom SNN_architecture import SNN\nfrom SNN_RelatedFunction import rmsprop\nfrom SNN_RelatedFunction import sgd\nfrom SNN_RelatedFunction import adam\nfrom SNN_RelatedFunction import adagrad\nfrom SNN_RelatedFunction import sgdm\nfrom SNN_RelatedFunction import nesterov\nfrom SNN_RelatedFunction import accuracy\n\nif __name__ == \"__main__\":\n print(\"Data load, process and split\")\n train = pd.read_csv('mnist.csv')\n np.random.seed(2099)\n index = np.random.permutation(train.shape[0])\n train_index = index[0: 40000]\n test_index = index[40000: 42000]\n test = train.iloc[test_index].copy()\n train = train.iloc[train_index]\n train_label = train[\"label\"].copy()\n test_label = test[\"label\"].copy()\n del train[\"label\"], train_index, test[\"label\"], test_index, index\n gc.collect()\n\n train = np.array(train)\n test = np.array(test)\n train_label = np.array(train_label)\n train_label = to_categorical(train_label, num_classes=10, dtype=\"int\")\n test_label = np.array(test_label)\n test_label = to_categorical(test_label, num_classes=10, dtype=\"int\")\n\n # this is a whole procedure for training a snn with this SNN class using various optimizer\n print(\"Network initilization\\n\")\n np.random.seed(2099)\n snn = SNN()\n snn.separate(data=train)\n snn.set_network(start=0.75, end=1.75, n_stage_layer=[4, 4, 4, 1], output=10)\n print(\"The nodes of in each stage:\", snn.stage_nodes)\n print(\"The nodes of each:\", snn.layer_nodes)\n snn.init()\n # snn.forward(train.T) # This is to test if forward can work\n\n optimization = input(\"choose a optimizer: sgd, sgdm, nesterov, adagrad, rmsprop, adam\\n\")\n while optimization not in [\"sgd\", \"sgdm\", \"nesterov\", \"adagrad\", \"rmsprop\", \"adam\"]:\n optimization = input(\"Wrong input, choose one of sgd, sgdm, nesterov, adagrad, rmsprop, adam\")\n\n # choose one of the following line to train\n tic = time.time()\n if optimization == \"sgd\":\n snn.fit(x=train.T, y=train_label.T, optimizer=sgd, batch_size=128, epoch=5, learning_rate=0.01)\n elif optimization == \"sgdm\":\n snn.fit(x=train.T, y=train_label.T, optimizer=sgdm, batch_size=128, epoch=5, learning_rate=0.01)\n elif optimization == \"nesterov\":\n snn.fit(x=train.T, y=train_label.T, optimizer=nesterov, batch_size=128, epoch=5, learning_rate=0.01)\n elif optimization == \"adagrad\":\n snn.fit(x=train.T, y=train_label.T, optimizer=adagrad, batch_size=128, epoch=5, learning_rate=0.001)\n elif optimization == \"rmsprop\":\n snn.fit(x=train.T, y=train_label.T, optimizer=rmsprop, batch_size=128, epoch=5, learning_rate=0.0001)\n elif optimization == \"adam\":\n snn.fit(x=train.T, y=train_label.T, optimizer=adam, batch_size=128, epoch=5, learning_rate=0.0005)\n toc = time.time()\n print(\"time used:\", toc - tic, \"s\")\n\n print(accuracy(test_label.T, snn.predict(test_set=test.T)))\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"232231782","text":"params = {\n 'n_epochs': 100,\n 'n_class': 19,\n 'n_class_per_batch': 19,\n 'n_per_class': 10,\n 'size': [224, 224],\n 'margin': 0.7,\n 'lr': 'default',\n 'early_stopping': 20,\n\n 'pretrained_weight': './exp/sample_experiment/baseline_softmax/model', # path to baseline_softmax\n 'train_ds': '/home/ubuntu/dataset/CowFace19/train/',\n 'save_every_n_epoch': 1\n}\n","sub_path":"exp/sample_experiment/baseline_triplet/params.py","file_name":"params.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"381843753","text":"import optparse\nimport subprocess\nimport sys\nimport traceback\nimport threading\nimport time\nimport requests\nimport uuid\nimport os\nfrom pathlib import Path\nimport shutil\n\nfrom io import StringIO\nfrom contextlib import redirect_stdout\n\nproc = None\n\n\ndef exec_code(job_user_token, job_runtime, job_id, rscript_executable):\n global proc\n\n extension = \".py\" if job_runtime == \"python\" else \".R\"\n program = sys.executable if job_runtime == \"python\" else rscript_executable\n filename = job_id + extension\n\n my_env = os.environ.copy()\n my_env[\"DSTACK_CONFIG\"] = \"./config.yaml\" if job_runtime == \"python\" else \"./.dstack/config.yaml\"\n proc = subprocess.Popen([program, filename],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n cwd=\"executions/\" + job_user_token,\n env=my_env\n )\n\n while proc.poll() is None:\n line = proc.stdout.readline()\n if not line:\n break\n print(line.decode(\"utf-8\")) # TODO: update job directly\n\n\ndef run_job(server_url, job_user_name, job_user_token, job_id, job_runtime, rscript_executable):\n job_path = \"executions/\" + job_user_token\n shutil.rmtree(os.path.join(job_path, \".dstack\"), ignore_errors=True)\n p = subprocess.Popen([\"dstack\", \"config\", \"add\", \"--server\", server_url, \"--token\", job_user_token,\n \"--user\", job_user_name, \"--force\", \"--file\",\n \"./config.yaml\" if job_runtime == \"python\" else \"./.dstack/config.yaml\"],\n cwd=job_path)\n p.wait()\n\n exec_code(job_user_token, job_runtime, job_id, rscript_executable)\n\n\ndef update_job_status(server_url, user_name, user_token, job_id, job_status, job_logs=None, job_started_at=None,\n job_finished_at=None):\n payload = {\n \"user\": user_name,\n \"id\": job_id,\n \"status\": job_status\n }\n if job_logs is not None:\n payload[\"logs\"] = job_logs\n if job_started_at is not None:\n payload[\"started_at\"] = job_started_at\n if job_finished_at is not None:\n payload[\"finished_at\"] = job_finished_at\n status = requests.post(server_url + \"/jobs/update\", headers={\"Authorization\": \"Bearer \" + user_token},\n json=payload).json()\n if status.get(\"job\") and status[\"job\"][\"status\"] == \"STOPPING\":\n global proc\n proc.terminate()\n return False\n else:\n return True\n\n\ndef main():\n parser = optparse.OptionParser()\n parser.add_option(\"-s\", \"--server\", dest=\"server\")\n parser.add_option(\"-u\", \"--user\", dest=\"user\")\n parser.add_option(\"-t\", \"--token\", dest=\"token\")\n parser.add_option(\"-r\", \"--runtime\", dest=\"runtime\")\n parser.add_option(\"-j\", \"--job\", dest=\"job\")\n parser.add_option(\"-a\", \"--rscript\", dest=\"rscript\")\n\n options, args = parser.parse_args()\n\n if options.user and options.token and options.job:\n server_url = options.server\n job_user_name = options.user\n job_user_token = options.token\n job_runtime = options.runtime\n job_id = options.job\n rscript_executable = options.rscript if options.rscript else \"Rscript\"\n\n logs_handler = StringIO() # TODO: update job directly from exec_code\n job_is_running = True\n try:\n print(\n \"Running job: \" + job_user_name + \"/\" + job_id + \"; runtime: \" + job_runtime + \"; server_url: \" + server_url)\n is_first_job_update = True\n\n def monitor_job_status():\n nonlocal is_first_job_update\n if job_is_running:\n if update_job_status(server_url, job_user_name, job_user_token, job_id, \"RUNNING\",\n logs_handler.getvalue(),\n job_started_at=round(time.time() * 1000) if is_first_job_update else None):\n is_first_job_update = False\n # TODO: stop job by timeout\n threading.Timer(10.0, monitor_job_status).start()\n\n monitor_job_status()\n with redirect_stdout(logs_handler):\n run_job(server_url, job_user_name, job_user_token, job_id, job_runtime, rscript_executable)\n job_is_running = False\n logs = logs_handler.getvalue()\n update_job_status(server_url, job_user_name, job_user_token, job_id, \"FINISHED\", logs,\n job_finished_at=round(time.time() * 1000))\n except Exception:\n job_is_running = False\n error = str(traceback.format_exc())\n logs = logs_handler.getvalue()\n update_job_status(server_url, job_user_name, job_user_token, job_id, \"FAILED\",\n error if not logs else logs + \"\\n\" + error,\n job_finished_at=round(time.time() * 1000))\n # finally:\n # if proc:\n # if proc.poll() is not None:\n # proc.terminate()\n\n else:\n parser.print_help()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"server-base/src/main/resources/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":5184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"108472345","text":"# Python script to understand Lissajous Scan\n# Jed Diller\n\n\nimport sys\nimport numpy as np\nimport scipy.fftpack\nfrom scipy import fftpack\nimport matplotlib.pyplot as plt\n\n\n# // AX,AY = amplitude in arcseconds\n# // TX,TY = period in seconds\n# // dx(t) = AX cos(2*pi*t/TX)\n\n# // x=Asin(at+ delta) \n# // y=Bsin(bt),\n# // where a = 1, b = N (N is a natural number) and\n# // delta= (N-1/N)*pi/2;\n\n# // global time keeper\n# ljHorz = MIDDLE + MIDDLE*cos(2*M_PI*t/TY);\n# ljVert = MIDDLE + MIDDLE*sin(2*M_PI*t/TY);\n# dx(t) = AX cos(2*pi*t/TX)\n# dy(t) = AY sin(2*pi*t/TY)\n\n# grid density\nnumPos = 2.0**16.0-1.0;\n\nDscan = 10.0; #degrees\nDsun = 0.5 #degrees\nAscan = Dscan**2;\nAsun = 2*np.pi*(Dsun/2.0)**2.0;\nratio = Ascan/Asun;\n\nsearchWidth = numPos/(10/0.5); #3276\n\n\nmiddle = (2.0**16.0-1)/2.0;\namp = middle;\na = 13.1;\nb = 11.0;\n# a = 5.0;\n# b = 4.0;\nN = b/a;\ndelta = (N-1.0)/N*np.pi/2.0;\ndt = 0.005; # period of iteration, 200Hz\n\nmaxStep = numPos/20.0*Dsun; \nmaxStep = 1;\nscanPeriod = numPos/maxStep*dt;\n\nitr = np.linspace(0 , numPos, numPos/50);\n\nx = middle + amp*np.sin(a*itr/numPos*2*np.pi + delta);\ny = middle + amp*np.sin(b*itr/numPos*2*np.pi);\n\t\n\n# ## Brute force scan\n# x = np.linspace(0,numPos,numPos);\n# y = np.linspace(0,numPos,numPos);\n# itr = np.linspace(0 , numPos , numPos);\n\n########## Plotting\nplt.figure(1)\nplt.subplot(121)\nplt.plot(x, y,'.')\nplt.title('Lissajous')\nplt.ylabel('Y')\nplt.xlabel('X')\n\nplt.subplot(122)\nplt.plot(x, y)\nplt.title('Lissajous')\nplt.ylabel('Y')\nplt.xlabel('X')\n\n# plt.subplot(122)\n# plt.plot(itr, x, 'r')\n# plt.plot(itr, y, 'g')\n# plt.xlabel('step')\n\n\n# plt.show()","sub_path":"main/testing/lissajous/lissajous.py","file_name":"lissajous.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"404254104","text":"from copy import deepcopy\r\nimport cv2\r\nimport vision.image_processor as ip\r\nimport numpy as np\r\n\r\n\r\ndef init():\r\n global cap\r\n cap = cv2.VideoCapture(0)\r\n print(\"Video initialized {0}x{1}, {2} fps\".format(int(cap.get(3)), int(cap.get(4)), int(cap.get(5))))\r\n\r\n\r\ndef _paste_non_zero(dest, src):\r\n s = deepcopy(dest)\r\n for i in range(len(s)):\r\n for j in range(len(s[i])):\r\n if np.any(src[i][j] != 0):\r\n s[i][j] = src[i][j]\r\n return s\r\n\r\n\r\ndef _add_lines(frame, lines):\r\n sh = frame.shape\r\n for i in lines[0]:\r\n cv2.line(frame, (0, i), (sh[1], i), (0, 255, 0))\r\n\r\n for i in lines[1]:\r\n cv2.line(frame, (i, 0), (i, sh[0]), (0, 255, 0))\r\n\r\n\r\ndef get_state():\r\n threshold = 5\r\n # for testing\r\n # frame = cv2.imread('out3.png')\r\n ret, frame = cap.read()\r\n binary = ip.to_binary_color(frame)\r\n sq, lines = ip.split_to_squares(binary)\r\n if len(sq) < 2 or len(sq) > threshold or len(sq[0]) > threshold:\r\n cv2.imshow('frame', binary)\r\n cv2.waitKey(1) & 0xFF == ord('q')\r\n return []\r\n state = []\r\n # ip.recognize_shape(sq[1][1])\r\n for row in sq:\r\n state.append([])\r\n for column in row:\r\n state[-1].append(ip.recognize_shape(column))\r\n # cv2.imwrite('out4.png', binary)\r\n _add_lines(binary, lines)\r\n cv2.imshow('frame', binary)\r\n cv2.waitKey(1) & 0xFF == ord('q') # required to show\r\n return state\r\n\r\n\r\ndef destroy():\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n","sub_path":"vision/state_reader.py","file_name":"state_reader.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"402083246","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\nfrom codecs import open\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetup(\n name='cr2-projects',\n version='0.0.1',\n description='Sistema de generación de reportes del (CR)2',\n long_description=long_description,\n url='https://github.com/nmiranda/cr2-reports',\n author='Nicolás Miranda',\n author_email='nmiranda@dgf.uchile.cl',\n license='MIT',\n packages=find_packages(),\n install_requires=[\n 'beautifulsoup4',\n 'dedupe',\n 'dedupe-hcluster',\n 'fuzzywuzzy',\n 'Jinja2',\n 'mysql-connector-python',\n 'numpy',\n 'python-dateutil',\n 'requests',\n 'Unidecode',\n 'xlrd',\n 'xlwt',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"412967229","text":"\ndef unpack(coins, val):\n\tif coins % val == 0:\n\t\treturn ((coins-val) // val, val)\n\treturn (coins // val, coins % val)\n\ndef reduce(g, s, b):\n\tbronze = unpack(b, 5)\n\tb = bronze[1]\n\ts += bronze[0]\n\tsilver = unpack(s, 10)\n\ts = silver[1]\n\tg += silver[0]\n\tprint(str(g) + ' ' + str(s) + ' ' + str(b))\n\t\ncases = int(input())\nfor x in range(cases):\n\tvals = [int(x) for x in input().split()]\n\treduce(vals[0], vals[1], vals[2])\n","sub_path":"2017/p4.py","file_name":"p4.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"583648814","text":"import MSLogger; log = MSLogger.get('wsgi_server')\nimport MSUser\nimport threading\nimport os\n\ndef genUsers(path):\n if not os.path.exists(path): return\n for f in os.listdir(path):\n if f[0] == '.': continue\n if f.find('.user') == -1: continue\n\n name = f.split('.user')[0]\n obj = MSUser.MSUser(path, name)\n obj.open()\n if obj.storage.txn == 0: continue\n if obj.storage.meta.has_key('dont_load') and obj.storage.meta['dont_load'] == True: continue\n yield (obj.hash, obj)\n\nclass MSUsers:\n def __init__(self, path):\n self.path = path\n self.objs = {}\n self.lock = threading.Lock()\n\n def load(self):\n self.lock.acquire()\n try:\n log.debug('Users::load: ...')\n for oid,obj in genUsers(self.path):\n log.debug('loaded %s user(%s)', oid, obj.storage.meta['email'])\n self.objs[oid] = obj\n log.info('Users::load: done')\n finally:\n self.lock.release()\n\n def find(self, userId, Locked=False):\n if not Locked: self.lock.acquire()\n try:\n if self.objs.has_key(userId): return self.objs[userId]\n return None\n finally:\n if not Locked: self.lock.release()\n","sub_path":"database/MSUsers.py","file_name":"MSUsers.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"343388493","text":"from PIL import Image, ImageChops\nimport sys\nimport os\nimport csv\nfrom layouts import layouts, applyLayout, BoundingBox, applyPreciseLayout\n\n# global variables\nBASE_IMAGES_PATH = \"\"\nTARGET_PATH = \"\"\nCHARACTER_DATABASE_PATH = \"\"\n\nCHARDEF_DIC = {}\nCHAR_DIC = {}\n\nclass CharDef:\n def __init__(self, lid, compIds, preciseDef=False, boxes=None):\n self.lid = lid\n self.compIds = compIds\n self.preciseDef = preciseDef\n self.boxes = boxes\n\ndef createCharDefDic():\n global CHARDEF_DIC\n with open(CHARACTER_DATABASE_PATH) as csvfile:\n fileReader = csv.reader(csvfile, delimiter=',')\n count = 0\n for row in fileReader:\n # TODO: verify numbers\n count += 1\n Id = row[0]\n lid = int(row[1])\n compsLenght = len(layouts.get(lid))\n compIds = []\n for i in range(compsLenght):\n compIds.append(row[i + 2])\n preciseDef = int(row[compsLenght + 2])\n if preciseDef == 1:\n boxes = []\n for i in range(compsLenght):\n x = int(row[1 + 4*i + 2 + compsLenght])\n y = int(row[2 + 4*i + 2 + compsLenght])\n dx = int(row[3 + 4*i + 2 + compsLenght])\n dy = int(row[4 + 4*i + 2 + compsLenght])\n box = BoundingBox(x,y,dx,dy)\n print(box)\n boxes.append(box)\n charDef = CharDef(lid, compIds, True, boxes)\n else: \n charDef = CharDef(lid, compIds)\n CHARDEF_DIC.update({Id: charDef})\n\ndef addBaseImages():\n global CHAR_DIC\n for file in os.listdir(BASE_IMAGES_PATH):\n if file.endswith(\".png\"):\n Id = file[:-4]\n charDef = CHARDEF_DIC.get(Id)\n try:\n if charDef.lid == 0:\n image = Image.open(BASE_IMAGES_PATH + file)\n image = image.convert('1')\n CHAR_DIC.update({Id: image})\n except Exception as error:\n pass\n\ndef createCharImage(Id):\n global CHAR_DIC\n try:\n cDef = CHARDEF_DIC.get(Id)\n lid = cDef.lid\n compIds = cDef.compIds\n preciseDef = cDef.preciseDef\n boxes = cDef.boxes\n except Exception as error:\n print(error)\n if lid == 0:\n raise Exception(\"Base image for character id \" + Id + \" was not provided.\")\n compImgs = []\n for i in compIds:\n if i not in CHAR_DIC.keys():\n createCharImage(i)\n img = CHAR_DIC.get(i)\n compImgs.append(img)\n if preciseDef:\n im = applyPreciseLayout(boxes, compImgs)\n else:\n im = applyLayout(lid,compImgs)\n CHAR_DIC.update({Id: im})\n\ndef completeImageDic():\n global CHAR_DIC\n for key in CHARDEF_DIC.keys():\n try:\n if key not in CHAR_DIC.keys():\n createCharImage(key)\n except Exception as error:\n print(key)\n print(error)\n\ndef saveImages():\n for Id, im in CHAR_DIC.items():\n charDef = CHARDEF_DIC.get(Id)\n if charDef.lid != 0:\n if charDef.preciseDef:\n im.save(TARGET_PATH + \"preciseDef/\" + Id + \".png\")\n im.save(TARGET_PATH + Id + \".png\")\n\n\ndef createCharacterSet():\n createCharDefDic()\n addBaseImages()\n completeImageDic()\n saveImages()\n\ndef main():\n if len(sys.argv) != 4:\n print(\"Wrong number of arguments, please provide:\")\n print(\"1) a path to the directory containing the images of the base characters\")\n print(\"2) a path to the target directory\")\n print(\"3) the filename (with path) of the character database\")\n else:\n global BASE_IMAGES_PATH\n global TARGET_PATH\n global CHARACTER_DATABASE_PATH\n BASE_IMAGES_PATH = sys.argv[1]\n TARGET_PATH = sys.argv[2]\n CHARACTER_DATABASE_PATH = sys.argv[3]\n createCharacterSet()\n\nif __name__ == \"__main__\":\n main()","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"9541209","text":"import psycopg2\n# from .database import *\nfrom proj.config import database\nimport os\nimport re\nimport json\nimport requests\nimport sys\nimport time\nimport psycopg2\nimport os\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(rootPath)\nimport datetime\nfrom proj.python_project.scats_operate_parsing import operate_record_resolve\nimport cx_Oracle\nimport threading\nfrom datetime import timedelta, date, datetime\n\n# from database import pg_inf,OracleUser\nfrom proj.python_project.scats_operate_parsing import state_information_feedback\nfrom proj.python_project.scats_operate_parsing import database_gai\nfrom proj.python_project.scats_operate_parsing import content\n\nsys.setrecursionlimit(10 ** 5)\n\nKeyWord = {'IP': '绿信比方案', 'CL': '周期', 'SS': '子系统', 'LP': '协调方案', 'LP0': '0号协调方案', 'MG': '协调关系', 'PL': '绿信比方案',\n 'DV': '离婚', 'XSF': None, 'SF': None, 'PD': '主相位', 'NGNS': None, 'NSNG': None,\n 'NGNG': None, 'PP1': None, 'HCL': '高周期', 'Plan': None, 'Activated': None}\n\nlast = []\n\n\ndef seperate(data):\n END = []\n for record in data:\n dict = {}\n list = [''] * 9\n # print(record)\n meaning = operate_record_resolve.resolve_operate_data(record)\n oper_code = record[0] # 链接数据库时用这句\n opercode = record[1]\n opertime = record[2]\n opertype = str(record[3])\n region = str(record[4])\n siteid = record[5]\n userid = str(record[6])\n list[0] = oper_code\n list[1] = meaning\n list[2] = opercode\n list[3] = opertime\n list[4] = ''\n list[5] = region\n list[7] = userid\n if oper_code:\n # print(oper_code)\n # re.match匹配开头\n m0 = re.match(r'([0-9]+): ([0-9]+)!(.*)', oper_code, re.I)\n m1 = re.match(r'SS=([0-9]+) (.*)', oper_code, re.I)\n m2 = re.match(r'IP(.*)', oper_code, re.I)\n m3 = re.match(r'([0-9]+): I=([0-9]+)(.*)', oper_code, re.I)\n m4 = re.match(r'PL(.*)', oper_code, re.I)\n m5 = re.match(r'XSF(.*)', oper_code, re.I)\n m6 = re.match(r'([0-9]+): SS=([0-9]+)(.*)', oper_code, re.I)\n m7 = re.match(r'KEY=([0-9]+) I=([0-9]+)(.*)', oper_code, re.I)\n m8 = re.match(r'KEY=([0-9]+) (SI|SA)=([0-9]+)(.*)', oper_code, re.I)\n m9 = re.match(r'KEY=([0-9]+) ([a-z]+)([0-9]{1,5})=(.{1,5})! \\((.{1,10})\\)(.*)', oper_code, re.I)\n m10 = re.match(r'Term(.*)', oper_code, re.I)\n m11 = re.match(r'KEY=([0-9]+) SS=([0-9]+)(.*)', oper_code, re.I)\n lll = None\n if m0:\n lll = 'I=' + m0.group(2)\n if m3:\n lll = 'I=' + m3.group(2)\n if m1:\n lll = 'SS=' + m1.group(1)\n if m6:\n lll = 'SS=' + m6.group(2)\n if m7:\n lll = 'I=' + m7.group(2)\n if m11:\n lll = 'SS=' + m11.group(2)\n\n if siteid == None:\n list[6] = lll\n else:\n # 读表格数据\n site = siteid\n # 读数据库数据\n # site='I='+siteid\n list[6] = site\n\n if m0:\n extra = m0.group(1) + ':' + m0.group(2) + '!'\n # list[19]=extra\n m0_7 = re.finditer(r'([a-z]{2,3})=([0-9]+)\\^!', m0.group(3), re.I)\n m0_1 = re.finditer(r'([a-z]{2,3})=([0-9]+)(#|)!', m0.group(3), re.I)\n m0_2 = re.finditer(r'([a-z]{2,3})(/|#.{0,30}!)', m0.group(3), re.I)\n m0_3 = re.finditer(r'Plan(.*)', m0.group(3), re.I)\n m0_4 = re.finditer(r'([a-z]{2,3})=([+\\-])([0-9]+)#(.{0,30})!', m0.group(3), re.I)\n m0_5 = re.search(r'(CL|PL)=([0-9]+)(#;|#!;)(.*)', m0.group(3), re.I)\n m0_6 = re.finditer(r'XSF=(\\+|-)([0-9]+)(.{0,15})!', m0.group(3), re.I)\n dict['extra'] = [extra]\n if m0_7:\n for match in m0_7:\n location = int(match.span(1)[0])\n key = match.group(1)\n message = match.group(2) + '^!'\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n if m0_6:\n for match in m0_6:\n location = int(match.span(1)[0])\n key = 'XSF'\n message = match.group(1) + match.group(2) + match.group(3) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n if m0_5:\n location = int(m0_5.span(1)[0])\n key = m0_5.group(1)\n message = m0_5.group(2) + m0_5.group(3) + m0_5.group(4)\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n if m0_1:\n for match in m0_1:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2) + match.group(3) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n\n if m0_2:\n for match in m0_2:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n\n if m0_3:\n for match in m0_3:\n key = 'Plan'\n message = match.group(1)\n location = int(match.span(1)[0])\n m0_3_1 = re.finditer(r'([0-9]+)!(.*)', match.group(1), re.I)\n m0_3_1_1 = re.finditer(r'([a-z]+)=(.{0,8})!', match.group(1), re.I)\n for match in m0_3_1:\n message = match.group(1) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n for match in m0_3_1_1:\n message = match.group(1) + '=' + match.group(2) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n if m0_4:\n for match in m0_4:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2) + match.group(3) + '#' + match.group(4) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n else:\n dict[key] = [[message, location]]\n\n if m1:\n SS = m1.group(1)\n # list[4]=SS\n dict['SS'] = [SS]\n # print(list)\n m1_1 = re.finditer(r'([a-z]+)=([0-9]+)(.{1,11})!(.*)', m1.group(2), re.I)\n m1_2 = re.finditer(r'([a-z]+)(/|.{1,12}!)(.*)', m1.group(2), re.I)\n m1_3 = re.finditer(r'LP0=([0-9]+),(.*)', m1.group(2), re.I)\n dict['extra'] = []\n if m1_1:\n for match in m1_1:\n location1 = int(match.span(1)[0])\n location2 = int(match.span(4)[0])\n key1 = match.group(1).upper()\n value = match.group(2)\n way = match.group(3)\n extra = match.group(4)\n if key1 in dict.keys():\n dict[key1].append([value + way + '!', location1])\n # dict['extra'].append(extra)\n else:\n dict[key1] = [[value + way + '!', location1]]\n dict['extra'].append(extra)\n\n if m1_2:\n for match in m1_2:\n location1 = int(match.span(1)[0])\n location2 = int(match.span(3)[0])\n key1 = match.group(1).upper()\n way = match.group(2)\n extra = match.group(3)\n if key1 in dict.keys():\n dict[key1].append([way, location1])\n # dict['extra'].append(extra)\n else:\n dict[key1] = [[way, location1]]\n dict['extra'].append(extra)\n\n if m1_3:\n for match in m1_3:\n value = match.group(1)\n location1 = int(match.span(1)[0])\n location2 = int(match.span(2)[0])\n extra = match.group(2)\n if 'LP0' in dict.keys():\n dict['LP0'].append([value, location1])\n # dict['extra'].append(extra)\n else:\n dict['LP0'] = [[value, location1]]\n dict['extra'].append(extra)\n\n if m2:\n IP = m2.group()\n m2_1 = re.match(r'(/|(.{1,30}))', m2.group(1), re.I)\n m2_2 = re.match(r'=([0-9]+)(.{0-30})!(.*)', m2.group(1), re.I)\n m2_3 = re.match(r'=([0-9]+)/(.*)', m2.group(1), re.I)\n dict['extra'] = []\n if m2_1:\n location = int(m2_1.span(1)[0])\n message = m2_1.group(1)\n if 'IP' in dict.keys():\n dict['IP'].append([message, location])\n else:\n dict['IP'] = [[message, location]]\n # list[2]=message\n if m2_2:\n location1 = int(m2_2.span(1)[0])\n location2 = int(m2_2.span(3)[0])\n number = m2_2.group(1) + m2_2.group(2)\n extra = m2_2.group(3)\n if 'IP' in dict.keys():\n dict['IP'].append([number, location1])\n # dict['extra'].append(extra)\n else:\n dict['IP'] = [[number, location1]]\n dict['extra'].append(extra)\n # list[2]=number\n # list[19]=extra\n if m2_3:\n location1 = int(m2_3.span(1)[0])\n location2 = int(m2_3.span(2)[0])\n number = m2_3.group(1)\n extra = m2_3.group(2)\n if 'IP' in dict.keys():\n dict['IP'].append([number, location1])\n # dict['extra'].append(extra)\n else:\n dict['IP'] = [[number, location1]]\n dict['extra'].append(extra)\n # list[2]=number\n # list[19]=extra\n if m3:\n extra1 = m3.group(1) + ':I=' + m3.group(2)\n m3_1 = re.finditer(r'([a-z]{2,3})=([0-9]+)#(.{0,10})!', m3.group(3), re.I)\n m3_2 = re.finditer(r'([a-z]{2,3})(/|#!|#.{0,10}!)', m3.group(3), re.I)\n m3_3 = re.finditer(r'PL=([0-9]+)(.*)', m3.group(3), re.I)\n m3_4 = re.finditer(r'PP1(.*)', m3.group(3), re.I)\n m3_5 = re.finditer(r'XSF=(.{1,30})!', m3.group(3), re.I)\n dict['extra'] = [extra1]\n if m3_1:\n for match in m3_1:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2) + '#' + match.group(3) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n\n if m3_2:\n for match in m3_2:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n\n if m3_3:\n for match in m3_3:\n location1 = int(match.span(1)[0])\n location2 = int(match.span(2)[0])\n message = match.group(1)\n extra = match.group(2)\n if '#' in extra:\n pass\n else:\n m3_3_1 = re.finditer(r'([a-z]+)=(.{0,8})!', match.group(2), re.I)\n if 'PL' in dict.keys():\n dict['PL'].append([message, location1])\n # dict['extra'].append(extra2)\n else:\n dict['PL'] = [[message, location1]]\n for match in m3_3_1:\n key_word = match.group(1)\n if key_word == 'PL':\n dict['PL'].append([match.group(1) + '=' + match.group(2) + '!', location1])\n elif key_word == 'XSF':\n pass\n else:\n location2 = int(match.span(1)[0])\n if len(key_word) == 1:\n key_word = 'PL'\n else:\n key_word = key_word\n message2 = match.group(2)\n if key_word in dict.keys():\n dict[key_word].append([message2 + '!', location2])\n # dict['extra'].append(extra2)\n else:\n dict[key_word] = [[message2 + '!', location2]]\n\n if m3_4:\n for match in m3_4:\n location = int(match.span(1)[0])\n message = match.group(1)\n if 'PP1' in dict.keys():\n dict['PP1'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['PP1'] = [[message, location]]\n\n if m3_5:\n for match in m3_5:\n # print(match)\n location1 = int(match.span(1)[0])\n # location2 = int(match.span(2)[0])\n message = match.group(1)\n # extra2=match.group(2)\n if 'XSF' in dict.keys():\n dict['XSF'].append([message + '!', location1])\n # dict['extra'].append(extra2)\n else:\n dict['XSF'] = [[message + '!', location1]]\n\n if m4:\n m4_1 = re.match(r'=([0-9]+)(.*)', m4.group(1), re.I)\n PL = m4_1.group(1)\n extra = m4_1.group(2)\n location1 = int(m4_1.span(1)[0])\n location2 = int(m4_1.span(2)[0])\n if 'PL' in dict.keys():\n dict['PL'].append([PL, location1])\n # dict['extra'].append(extra)\n else:\n dict['PL'] = [[PL, location1]]\n dict['extra'].append(extra)\n\n if m5:\n m5_1 = re.match(r'=(.{1,30})!(.*)', m5.group(1), re.I)\n XSF = m5_1.group(1) + '!'\n extra = m5_1.group(2)\n location1 = int(m5_1.span(1)[0])\n location2 = int(m5_1.span(2)[0])\n if 'XSF' in dict.keys():\n dict['XSF'].append([XSF, location1])\n # dict['extra'].append(extra)\n else:\n dict['XSF'] = [[XSF, location1]]\n dict['extra'].append(extra)\n # list[10]=XSF\n # list[19]=extra\n if m6:\n SS = m6.group(2)\n # list[4]=SS\n extra = m6.group(1) + ':SS=' + SS\n # list[19]=extra\n m6_1 = re.finditer(r'([a-z]{1,2})(/|=|!)(.*)', m6.group(3), re.I)\n m6_2 = re.finditer(r'([a-z]{1,2})#(.{0,30})!', m6.group(3), re.I)\n m6_3 = re.finditer(r'LP0=([0-9]+),(.{1,15})(#!|#;)(.*)', m6.group(3), re.I)\n m6_8 = re.finditer(r'LP0=(\\+|-)([0-9]+),(.{1,15})#;(.{1,10})!', m6.group(3), re.I)\n m6_4 = re.finditer(r'HCL=(.{1,8})!(\\(was (.{1,8})\\)| \\(was (.{1,8})\\)|)', m6.group(3), re.I)\n m6_5 = re.finditer(r'LCL=(.{1,8})!(\\(was (.{1,8})\\)| \\(was (.{1,8})\\))', m6.group(3), re.I)\n m6_6 = re.finditer(r'SCL=(.{1,8})!(\\(was (.{1,8})\\)| \\(was (.{1,8})\\)|)', m6.group(3), re.I)\n m6_7 = re.finditer(r'XCL=(.{1,8})!(\\(was (.{1,8})\\)| \\(was (.{1,8})\\)|)', m6.group(3), re.I)\n dict['extra'] = [extra]\n if m6_1:\n for match in m6_1:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n if '!' in match.group(2):\n message = match.group(2)\n elif '/' in match.group(2):\n message = match.group(2)\n else:\n message = match.group(3)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n\n if m6_2:\n for match in m6_2:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2)\n if key in dict.keys():\n dict[key].append(['#' + message + '!', location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [['#' + message + '!', location]]\n\n if m6_3:\n for match in m6_3:\n message = ''\n location1 = int(match.span(1)[0])\n location2 = int(match.span(3)[0])\n if '#!' in match.group(3):\n extra = match.group(4)\n message = match.group(1) + ',' + match.group(2) + '#!'\n elif '#;' in match.group(3):\n extra = ''\n message = match.group(1) + ',' + match.group(2) + match.group(3) + match.group(4)\n if extra == '':\n pass\n else:\n dict['extra'].append(extra)\n # message=match.group(1)+','+match.group(2)\n if 'LP0' in dict.keys():\n dict['LP0'].append([message, location1])\n # dict['extra'].append(extra)\n else:\n dict['LP0'] = [[message, location1]]\n\n if m6_4:\n for match in m6_4:\n extra11 = ''\n location = int(match.span(1)[0])\n if match.group(2) == '':\n message = match.group(1) + '!'\n else:\n extra11 = match.group(2)\n message = match.group(1) + '!' + extra11\n if 'HCL' in dict.keys():\n dict['HCL'].append([message, location])\n else:\n dict['HCL'] = [[message, location]]\n\n if 'CL' in dict.keys():\n del dict['CL']\n\n if m6_5:\n for match in m6_5:\n extra11 = ''\n location = int(match.span(1)[0])\n if match.group(2) == '':\n message = match.group(1) + '!'\n else:\n extra11 = match.group(2)\n message = match.group(1) + '!' + extra11\n if 'LCL' in dict.keys():\n dict['LCL'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['LCL'] = [[message, location]]\n if 'CL' in dict.keys():\n del dict['CL']\n if m6_6:\n for match in m6_6:\n extra11 = ''\n location = int(match.span(1)[0])\n if match.group(2) == '':\n message = match.group(1) + '!'\n else:\n extra11 = match.group(2)\n message = match.group(1) + '!' + extra11\n if 'SCL' in dict.keys():\n dict['SCL'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['SCL'] = [[message, location]]\n if 'CL' in dict.keys():\n del dict['CL']\n if m6_7:\n for match in m6_7:\n extra11 = ''\n location = int(match.span(1)[0])\n if match.group(2) == '':\n message = match.group(1) + '!'\n else:\n extra11 = match.group(2)\n message = match.group(1) + '!' + extra11\n if 'XCL' in dict.keys():\n dict['XCL'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['XCL'] = [[message, location]]\n if 'CL' in dict.keys():\n del dict['CL']\n if m6_8:\n for match in m6_8:\n key = 'LP0'\n location = int(match.span(1)[0])\n message = match.group(1) + match.group(2) + ',' + match.group(3) + '#;' + match.group(4) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7:\n extra = 'KEY=' + m7.group(1) + ' I=' + m7.group(2)\n m7_1 = re.finditer(r'([a-z]+)/(.*)', m7.group(3), re.I)\n m7_2 = re.finditer(r'([a-z]+)=([0-9]+)#;(.{1,15})!(.*)', m7.group(3), re.I)\n m7_3 = re.finditer(r'([a-z]+);(.*)', m7.group(3), re.I)\n m7_4 = re.finditer(r'PL=([0-9]+)(.*)', m7.group(3), re.I)\n m7_5 = re.finditer(r'([a-z]+)=([0-9]+)/(.*)', m7.group(3), re.I)\n m7_6 = re.finditer(r'XSF=(\\+|-)([0-9]+)(.{0,15})!(.*)', m7.group(3), re.I)\n m7_7 = re.finditer(r'XSF=(\\+|-)([0-9]+)/(.*)', m7.group(3), re.I)\n m7_8 = re.finditer(r'IP=([0-9]+)!(.*)', m7.group(3), re.I)\n m7_9 = re.finditer(r'PP([0-9]+)=(.*)', m7.group(3), re.I)\n m7_10 = re.finditer(r'PP([0-9]+)#(.*)', m7.group(3), re.I)\n dict['extra'] = extra\n if m7_10:\n for match in m7_10:\n location = int(match.span(1)[0])\n key = 'PP'\n message = match.group(1) + ',#' + match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_9:\n for match in m7_9:\n location = int(match.span(1)[0])\n key = 'PP'\n message = match.group(1) + ',' + match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_8:\n for match in m7_8:\n location = int(match.span(1)[0])\n key = 'IP'\n message = match.group(1) + '!' + match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_7:\n for match in m7_7:\n location = int(match.span(1)[0])\n key = 'XSF'\n message = match.group(1) + match.group(2) + '/' + match.group(3)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_6:\n for match in m7_6:\n location = int(match.span(1)[0])\n key = 'XSF'\n message = match.group(1) + match.group(2) + match.group(3) + '!' + match.group(4)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_5:\n for match in m7_5:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2) + '/' + match.group(3)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_4:\n for match in m7_4:\n location1 = int(match.span(1)[0])\n location2 = int(match.span(2)[0])\n message = match.group(1)\n extra = match.group(2)\n if '#;' in extra:\n pass\n else:\n if 'PL' in dict.keys():\n dict['PL'].append([message, location1])\n # dict['extra'].append(extra2)\n else:\n dict['PL'] = [[message, location1]]\n m3_3_1 = re.finditer(r'([a-z]+)=(.{0,15})!', match.group(2), re.I)\n if m3_3_1:\n for match in m3_3_1:\n location2 = int(match.span(1)[0])\n message = match.group(1) + '=' + match.group(2) + '!'\n if 'PL' in dict.keys():\n dict['PL'].append([message, location2])\n # dict['extra'].append(extra2)\n else:\n dict['PL'] = [[message, location2]]\n # dict['extra'].append(extra2)\n # list[8]=message\n # list[19]=extra1+' '+extra2\n if m7_1:\n for match in m7_1:\n key = match.group(1).upper()\n location = int(match.span(1)[0])\n message = '/' + match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_2:\n for match in m7_2:\n key = match.group(1)\n location = int(match.span(1)[0])\n message = match.group(2) + '#;' + match.group(3) + '!' + match.group(4)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m7_3:\n for match in m7_3:\n key = match.group(1)\n location = int(match.span(1)[0])\n message = ';' + match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m8:\n extra = 'KEY=' + m8.group(1) + ' ' + m8.group(2) + '=' + m8.group(3)\n dict['extra'] = extra\n m8_1 = re.finditer(r'(SA|SI)=([0-9]+)', m8.group(4), re.I)\n m8_2 = re.finditer(r'([a-z]{2,2})=(.{1,15})! \\((.{1,25})\\)', m8.group(4), re.I)\n m8_3 = re.finditer(r'([a-z]{1})(#|\\^)=(.{1,15})! \\((.{1,15})\\)', m8.group(4), re.I)\n m8_4 = re.finditer(r'([a-z]{2,2})([0-9]{1,4})=([0-9]+)! \\((.{1,25})\\)', m8.group(4), re.I)\n if m8_1:\n for match in m8_1:\n key = match.group(1)\n location = int(match.span(1)[0])\n message = match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m8_2:\n for match in m8_2:\n # print(match)\n key = match.group(1)\n location = int(match.span(1)[0])\n message = match.group(2) + '!' + '(' + match.group(3) + ')'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m8_3:\n for match in m8_3:\n # print(match)\n key = match.group(1) + match.group(2)\n location = int(match.span(1)[0])\n message = match.group(3) + '!' + ' (' + match.group(4) + ')'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m8_4:\n for match in m8_4:\n key = match.group(1) + match.group(2)\n location = int(match.span(1)[0])\n message = match.group(3) + '!' + '(' + match.group(4) + ')'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m9:\n extra = 'KEY=' + m9.group(1)\n dict['extra'] = extra\n key1 = m9.group(2) + m9.group(3)\n location = m9.group(2)\n message = m9.group(4) + '! ' + '(' + m9.group(5) + ')'\n if key1 in dict.keys():\n dict[key1].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key1] = [[message, location]]\n m9_1 = re.finditer(r'(SA|SI)=([0-9]+)', m9.group(6), re.I)\n m9_2 = re.finditer(r'([a-z]{2,2})=(.{1,15})! \\((.{1,25})\\)', m9.group(6), re.I)\n m9_3 = re.finditer(r'([a-z]{1})(#|\\^)=(.{1,15})! \\((.{1,15})\\)', m9.group(6), re.I)\n m9_4 = re.finditer(r'([a-z]{2,2})([0-9]{1,4})=([0-9]+)! \\((.{1,25})\\)', m9.group(6), re.I)\n if m9_1:\n for match in m9_1:\n key = match.group(1)\n location = int(match.span(1)[0])\n message = match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m9_2:\n for match in m9_2:\n # print(match)\n key = match.group(1)\n location = int(match.span(1)[0])\n message = match.group(2) + '!' + '(' + match.group(3) + ')'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m9_3:\n for match in m9_3:\n # print(match)\n key = match.group(1) + match.group(2)\n location = int(match.span(1)[0])\n message = match.group(3) + '!' + '(' + match.group(4) + ')'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m9_4:\n for match in m9_4:\n key = match.group(1) + match.group(2)\n location = int(match.span(1)[0])\n message = match.group(3) + '!' + '(' + match.group(4) + ')'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m10:\n extra = 'Term' + m10.group(1)\n dict['extra'] = extra\n if m11:\n SS = m11.group(2)\n # list[4]=SS\n extra = 'KEY=' + m11.group(1) + ':SS=' + SS\n # list[19]=extra\n m11_1 = re.finditer(r'([a-z]{1,2})(/|=|!)(.*)', m11.group(3), re.I)\n m11_2 = re.finditer(r'([a-z]{1,2})#(.{0,30})!', m11.group(3), re.I)\n m11_3 = re.finditer(r'LP0=([0-9]+),(.{1,15})(#!|#;)(.*)', m11.group(3), re.I)\n m11_4 = re.finditer(r'HCL=(.*)', m11.group(3), re.I)\n m11_5 = re.finditer(r'LCL=(.*)', m11.group(3), re.I)\n m11_6 = re.finditer(r'SCL=(.*)', m11.group(3), re.I)\n m11_7 = re.finditer(r'XCL=(.*)', m11.group(3), re.I)\n m11_8 = re.finditer(r'LP0=([0-9]+)#;(.{1,15})!(.*)', m11.group(3), re.I)\n m11_9 = re.finditer(r'LP0(/)(.*)', m11.group(3), re.I)\n m11_10 = re.finditer(r'LP0=([0-9]+)!(.*)', m11.group(3), re.I)\n m11_11 = re.finditer(\n r'LP([0-9]+)=(\\+|-|)([0-9]+),(\\+|-|)([0-9]+)\\^([a-z]+)([0-9]+)! \\(was (\\+|-|)([0-9]+),(\\+|-|)([0-9]+)\\^([a-z]+)([0-9]+)\\)',\n m11.group(3), re.I)\n m11_12 = re.finditer(r'LP0=(\\+|-)([0-9]+),(.{1,15})#;(.{1,15})!', m11.group(3), re.I)\n m11_13 = re.finditer(r'LP0=([0-9]+),([0-9]+)\\^([a-z]+)([0-9]+)!', m11.group(3), re.I)\n dict['extra'] = [extra]\n if m11_13:\n for match in m11_13:\n location = int(match.span(1)[0])\n key = 'LP0'\n message = match.group(1) + ',' + match.group(2) + '^' + match.group(3) + match.group(4) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m11_12:\n for match in m11_12:\n location = int(match.span(1)[0])\n key = 'LP0'\n message = match.group(1) + match.group(2) + ',' + match.group(3) + '#;' + match.group(4) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m11_11:\n for match in m11_11:\n location = int(match.span(1)[0])\n key = 'LP' + match.group(1)\n message = match.group(2) + match.group(3) + ',' + match.group(4) + match.group(\n 5) + '^' + match.group(6) + match.group(7) + '!(was' + match.group(8) + match.group(\n 9) + ',' + match.group(10) + match.group(11) + '' + match.group(12) + match.group(13) + ')'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m11_10:\n for match in m11_10:\n location = int(match.span(1)[0])\n key = 'LP0'\n message = match.group(1) + '!' + match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m11_9:\n for match in m11_9:\n location = int(match.span(1)[0])\n key = 'LP0'\n message = '/' + match.group(2)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m11_8:\n for match in m11_8:\n location = int(match.span(1)[0])\n key = 'LP0'\n message = match.group(1) + '#;' + match.group(2) + '!' + match.group(3)\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n if m11_1:\n for match in m11_1:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n extra = match.group(3)\n if extra == ' (Activated)' or extra == ' (Timed - removed by system)':\n extra = extra\n else:\n extra = ''\n if '!' in match.group(2):\n message = match.group(2)\n elif '/' in match.group(2):\n message = match.group(2)\n else:\n message = match.group(3)\n if key in dict.keys():\n dict[key].append([message + extra, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message + extra, location]]\n # if key=='IP':\n # list[2]=message\n # if key=='CL':\n # list[3]=message\n # if key=='SS':\n # list[4]=message\n # if key=='LP':\n # list[5]=message\n # if key=='LP0':\n # list[6]=message\n # if key=='MG':\n # list[7]=message\n # if key=='PL':\n # list[8]=message\n # if key=='DV':\n # list[9]=message\n # if key=='XSF':\n # list[10]=message\n # if key=='SF':\n # list[11]=message\n # if key=='PD':\n # list[12]=message\n if m11_2:\n for match in m11_2:\n location = int(match.span(1)[0])\n key = match.group(1).upper()\n message = match.group(2)\n if key in dict.keys():\n dict[key].append(['#' + message + '!', location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [['#' + message + '!', location]]\n\n if m11_3:\n for match in m11_3:\n message = ''\n location1 = int(match.span(1)[0])\n location2 = int(match.span(3)[0])\n if '#!' in match.group(3):\n extra = match.group(4)\n message = match.group(1) + ',' + match.group(2) + '#!'\n elif '#;' in match.group(3):\n extra = ''\n message = match.group(1) + ',' + match.group(2) + match.group(3) + match.group(4)\n if extra == '':\n pass\n else:\n dict['extra'].append(extra)\n # message=match.group(1)+','+match.group(2)\n if 'LP0' in dict.keys():\n dict['LP0'].append([message, location1])\n # dict['extra'].append(extra)\n else:\n dict['LP0'] = [[message, location1]]\n # dict['extra'] = [extra]\n # list[6]=message\n if m11_4:\n for match in m11_4:\n location = int(match.span(1)[0])\n message = match.group(1)\n if 'HCL' in dict.keys():\n dict['HCL'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['HCL'] = [[message, location]]\n # dict['extra'] = [extra]\n # list[17]=message\n if m11_5:\n for match in m11_5:\n location = int(match.span(1)[0])\n message = match.group(1)\n if 'LCL' in dict.keys():\n dict['LCL'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['LCL'] = [[message, location]]\n if m11_6:\n for match in m11_6:\n location = int(match.span(1)[0])\n message = match.group(1)\n if 'SCL' in dict.keys():\n dict['SCL'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['SCL'] = [[message, location]]\n if m11_7:\n for match in m11_7:\n location = int(match.span(1)[0])\n message = match.group(1)\n if 'XCL' in dict.keys():\n dict['XCL'].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict['XCL'] = [[message, location]]\n if m11_8:\n for match in m11_8:\n key = 'LP0'\n location = int(match.span(1)[0])\n message = match.group(1) + match.group(2) + ',' + match.group(3) + '#;' + match.group(4) + '!'\n if key in dict.keys():\n dict[key].append([message, location])\n # dict['extra'].append(extra)\n else:\n dict[key] = [[message, location]]\n\n for key in dict.keys():\n aa = key\n bb = dict[key]\n if 'DW' in aa:\n if len(aa) > 2:\n del dict[key]\n t = str(aa)[0]\n bb.append(t)\n dict['DW'] = bb\n # 排序操作\n for key in dict:\n if key == 'extra':\n pass\n elif key == 'DW':\n pass\n else:\n l = len(dict[key])\n # print(dict[key])\n if len(dict[key]) > 1:\n for i in range(0, len(dict[key])):\n for j in range(i, len(dict[key])):\n if int(dict[key][i][1]) > int(dict[key][j][1]):\n mid = dict[key][i]\n dict[key][i] = dict[key][j]\n dict[key][j] = mid\n else:\n pass\n else:\n pass\n # print(dict)\n for key in dict:\n lll = dict[key]\n if key == 'extra':\n pass\n else:\n dd = []\n l = len(dict[key])\n for i in range(0, l):\n k = ''\n k = dict[key][i][0]\n # print(k)\n dd.append(dict[key][i][0])\n dict[key] = dd\n if 'CL' in dict.keys():\n if 'HCL' in dict.keys():\n if dict['CL'] == dict['HCL']:\n del dict['CL']\n if 'XCL' in dict.keys():\n if dict['CL'] == dict['XCL']:\n del dict['CL']\n if 'SCL' in dict.keys():\n if dict['CL'] == dict['SCL']:\n del dict['CL']\n if 'LCL' in dict.keys():\n if dict['CL'] == dict['LCL']:\n del dict['CL']\n elif 'LAN' in dict.keys():\n del dict['LAN']\n else:\n pass\n # m6_8多出来的错误匹配删除\n if 'X' in dict.keys():\n del dict['X']\n\n aaaa = []\n for key in dict.keys():\n aaaa.append(key)\n\n # 类型匹配\n if 'PL' in aaaa:\n message1 = 'Split,'\n else:\n message1 = ''\n if 'IP' in aaaa:\n message2 = 'Split,'\n else:\n message2 = ''\n if 'SP' in aaaa:\n message3 = 'Split,'\n else:\n message3 = ''\n if 'OPD' in aaaa:\n message4 = 'Split,'\n else:\n message4 = ''\n if 'Plan' in aaaa:\n message15 = 'Split,'\n else:\n message15 = ''\n\n if message1 != '' or message2 != '' or message3 != '' or message4 != '' or message15 != '':\n message111 = 'Split,'\n else:\n message111 = ''\n\n if 'CL' in aaaa:\n message5 = 'Cycle,'\n else:\n message5 = ''\n if 'HCL' in aaaa:\n message6 = 'Cycle,'\n else:\n message6 = ''\n if 'XCL' in aaaa:\n message7 = 'Cycle,'\n else:\n message7 = ''\n if 'SCL' in aaaa:\n message8 = 'Cycle,'\n else:\n message8 = ''\n if 'LCL' in aaaa:\n message9 = ' Cycle,'\n else:\n message9 = ''\n\n if message5 != '' or message6 != '' or message7 != '' or message8 != '' or message9 != '':\n message222 = 'Cycle,'\n else:\n message222 = ''\n\n if 'LP' in aaaa:\n message10 = 'Coordination,'\n else:\n message10 = ''\n if 'LP0' in aaaa:\n message11 = 'Coordination,'\n else:\n message11 = ''\n if 'MG' in aaaa:\n message12 = 'Coordination,'\n else:\n message12 = ''\n if 'DV' in aaaa:\n message13 = 'Coordination,'\n else:\n message13 = ''\n\n if message10 != '' or message11 != '' or message12 != '' or message13 != '':\n message333 = 'Coordination,'\n else:\n message333 = ''\n\n if 'PP' in aaaa:\n message14 = 'PP,'\n else:\n message14 = ''\n\n if message14 != '':\n message444 = 'PP,'\n else:\n message444 = ''\n\n if 'DW' in aaaa:\n message16 = 'Dwell,'\n else:\n message16 = ''\n if 'XSF' in aaaa:\n message17 = 'XSF,'\n else:\n message17 = ''\n\n if message17 != '':\n message555 = 'XSF,'\n else:\n message555 = ''\n\n if message16 != '':\n message999 = 'Dwell,'\n else:\n message999 = ''\n\n if 'VF' in aaaa:\n message18 = 'Other,'\n else:\n message18 = ''\n if 'SD' in aaaa:\n message19 = 'Other,'\n else:\n message19 = ''\n if 'D#' in aaaa:\n message20 = 'Other,'\n else:\n message20 = ''\n\n if message18 != '' or message19 != '' or message20 != '':\n message666 = 'Other,'\n else:\n message666 = ''\n\n if 'Activated' in oper_code:\n message21 = 'Activated,'\n else:\n message21 = ''\n #\n # if 'Timed' in oper_code:\n # message22='Remove,'\n # else:\n # message22=''\n #\n if message21 != '':\n list[4] = message21\n else:\n list[4] = message999 + message111 + message222 + message333 + message444 + message555 + message666\n\n if list[4] == '':\n list[4] = None\n else:\n list[4] = str(list[4])[:-1]\n\n j = json.dumps(dict)\n list[8] = j\n # print(list)\n END.append(list)\n\n # print(END)\n return END\n\n\n# 连接数据库用这个\ndef insert_data(data):\n sql = content.CONTENT.sql4\n pp = database.Postgres()\n pp.send_pg_data(sql, data)\n pp.db_close()\n return\n\n\ndef task():\n global net_state\n try:\n timer = threading.Timer(180, task)\n timer.start()\n except Exception as e:\n print(e)\n '''链接数据库读取数据'''\n endtime = datetime.now()\n starttime = endtime - timedelta(minutes=10)\n orcl = database.Oracle.get_instance()\n # starttime = '2018-10-15 12:00:00'\n # endtime = '2018-10-15 14:00:00'\n\n try:\n operate_data = orcl.call_oracle_data(content.CONTENT.sql_get_manoperate.format(starttime, endtime))\n # print(content.CONTENT.sql_get_manoperate.format(starttime, endtime))\n except Exception as e:\n print('get operate data failed! the error is:', e)\n pass\n else:\n print(\"get data success!\")\n if operate_data:\n '''后续操作'''\n nowTime = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n dict = seperate(operate_data)\n insert_data(dict)\n # 本地输出\n pg = database.Postgres.get_instance()\n result = pg.call_pg_data(content.CONTENT.sql_operate_match.format(starttime, endtime))\n # print(content.CONTENT.sql_operate_match.format(starttime, endtime))\n # result = pg.call_pg_data(content.CONTENT.sql3)\n if len(result) > 0:\n print(\"更新路口状态\")\n net_state.int_status_update(result)\n state_information_feedback.insert(net_state.net_state)\n else:\n print(\"无法获取路口操作记录解析结果\")\n\n print(\"当前时间为:%s 操作完成,下次将在3分钟后进行\" % nowTime)\n\n else:\n print('匹配不到操作记录解析数据')\n\n\n# 添加定时器,定时操作\ndef main():\n global scats_split_init\n # 初始化所有路口\n pg = database.Postgres()\n scats_split_init = {}\n # orcl = database.Oracle.get_instance()\n # sum_int = orcl.call_oracle_data(content.CONTENT.sql1)\n int_split = pg.call_pg_data(sql=content.CONTENT.sql_get_splitlocked)\n\n int_list = []\n for split in int_split:\n scats_id = split[0]\n int_list.append(scats_id)\n split_locked = split[1]\n scats_split_init[scats_id] = {'updatatime': None, 'user_name': None, 'spilt': None, 'cycle': None,\n 'coordination': None,\n 'pp': None, 'xsf': None, 'other': None, 'dwell': None, 'siteid': scats_id}\n\n if split_locked == '0':\n scats_split_init[scats_id]['spilt'] = 'adaptive'\n elif split_locked == '1':\n scats_split_init[scats_id]['spilt'] = 'fixed'\n else:\n scats_split_init[scats_id]['spilt'] = 'other'\n\n if len(int_list) > 0:\n global net_state\n net_state = state_information_feedback.NetState(int_list, scats_split_init)\n print(\"这次的操作开始,下次将在3分钟后进行\")\n global timer\n task()\n else:\n print(\"路口状态初始化失败!\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"xjc_pyfile/proj_scats/proj/python_project/scats_operate_parsing/seperate_operate_record.py","file_name":"seperate_operate_record.py","file_ext":"py","file_size_in_byte":57053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"554745624","text":"import re\n\ntabs = 0\nisRec = False\ndef checkDigit(text):\n if (text == \"0\" or text ==\"1\" or text ==\"2\" or text ==\"3\" or text ==\"4\" or text ==\"5\" or text ==\"6\" or text ==\"7\" or text ==\"8\"\n or text ==\"9\"):\n return True\n else:\n return False\n\n\ndef parseRegexp(text):\n\n regex = \"(var |;|:?(\\\\s)?integer|:?(\\\\s)?real|:?(\\\\s)?boolean|\\n)\"\n\n reg = re.sub(\"(\\t)\", \"\", text)\n ch = \" \"\n mark = 0\n countSp = 0\n for c in text:\n countSp = countSp +1\n if c == ch:\n mark = countSp\n else:\n break\n reg = reg [mark:]\n reg = re.sub(regex, \"\", reg)\n reg = re.sub(\"(?= prev.val:\n prev = prev.next\n node = node.next\n else:\n p, q = head, head.next\n while q != node:\n if p.val <= node.val and q.val > node.val:\n print(\"p\", p.val)\n print(\"q\", q.val)\n print(\"prev\", prev.val)\n print(\"node\", node.val)\n prev.next = node.next\n p.next = node\n node.next = q\n node = prev.next\n print(\"p\", p.val)\n print(\"q\", q.val)\n print(\"prev\", prev.val)\n print(\"node\", node.val)\n print(\"the list is now\")\n printList(head)\n break\n p= p.next\n q = q.next\n return head\n\ndef reorderList(head):\n if not head or not head.next:\n return head\n mid = findMid(head)\n mid = reverse(mid)\n start = head\n while mid and start:\n p = mid.next\n mid.next = start.next\n start.next = mid\n mid = p\n start = start.next.next\n start = mid\n return head\ndef reverse(root):\n new_root = None\n while root:\n nextNode = root.next\n root.next = new_root\n new_root = root\n root = nextNode\n return new_root\n\ndef findMid(head):\n p = head\n q = head.next\n while q:\n q = q.next\n if q:\n q = q.next\n p = p.next\n res = p.next\n p.next = None\n return res\n\ndef makeList(a):\n head = ListNode(a[0])\n p = head\n for item in a[1:]:\n node = ListNode(item)\n p.next = node\n p = p.next\n return head\n\ndef printList(head):\n while head:\n print(head.val, end =\", \")\n head = head.next\n print()\n\ndef test():\n a = [1, 2, 3, 4]\n head = makeList(a)\n\n\n #sortedA = sortList(head)\n printList(head)\n sortedList = reorderList(head)\n printList(sortedList)\n\ntest()\n","sub_path":"week20/Jing/test_sort_list.py","file_name":"test_sort_list.py","file_ext":"py","file_size_in_byte":3380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"17559055","text":"import math\nimport numpy as np\nimport mpmath as mp\n\nmp.mp.dps = 30\nG_const = 6.67408e-11 # Gravitational Constant [m^3 kg^-1 s^-2]\n\n\nclass VectorData:\n \"\"\"Class for 3D vector data.\"\"\"\n\n def __init__(self, point=(0,0,0)):\n self.x, self.y, self.z = float(point[0]), float(point[1]), float(point[2])\n\n\nclass Body:\n \"\"\"Class representing a typical object and its properties.\"\"\"\n\n def __init__(self, mass, position, velocity, old_position = None, old_velocity = None, radius=None, time_step=None,\n E_potential = None, E_kinetic = None, E_total = None, name=\"\"):\n\n self.mass = mass\n self.position = position\n self.velocity = velocity\n\n self.old_position = old_position\n self.old_velocity = old_velocity\n\n self.radius = radius\n self.time_step = time_step\n self.body_time = 0.\n\n self.E_potential = E_potential\n self.E_kinetic = E_kinetic\n self.E_total = E_total\n\n self.name = name\n\n\nclass EulerMethod:\n \"\"\"Class for evaluation of the Euler method of integration.\n The most simple numerical solution to Newton's equations of motion.\n Determines new trajectories in discrete timesteps from forces applied by influencing bodies.\"\"\"\n\n def __init__(self, time_step, bodies_list):\n self.time_step = time_step\n self.bodies = bodies_list\n\n def perform_integration(self):\n # initial data for step\n pos_arr = np.array([(i.position.x, i.position.y, i.position.z) for i in self.bodies[:]])\n vel_arr = np.array([(i.velocity.x, i.velocity.y, i.velocity.z) for i in self.bodies[:]])\n mass_arr = np.array([[i.mass] for i in self.bodies[:]])\n time_step_arr = np.array([[self.time_step] for i in self.bodies[:]])\n\n # calculation of the acceleration on bodies from all other bodies\n dr_arr = pos_arr[np.newaxis, :] - pos_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n r_between_arr[~np.isfinite(r_between_arr)] = 1\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n acc_arr = (dr_arr.T * tmp_arr).T\n acc_arr = acc_arr.sum(axis=1)\n\n # new trajectory calculations\n pos_arr += vel_arr * time_step_arr\n vel_arr += acc_arr * time_step_arr\n\n for index, body in enumerate(self.bodies):\n # update trajectories\n body.position.x = pos_arr[index][0]\n body.position.y = pos_arr[index][1]\n body.position.z = pos_arr[index][2]\n body.velocity.x = vel_arr[index][0]\n body.velocity.y = vel_arr[index][1]\n body.velocity.z = vel_arr[index][2]\n\n\nclass EulerCromerMethod:\n \"\"\"Class for evaluation of the Euler-Cromer method of integration.\n Solves with Hamiltionian mechanics therefore symplectic.\n Updates velocity and then position from acting forces.\"\"\"\n\n def __init__(self, time_step, bodies_list):\n self.time_step = time_step\n self.bodies = bodies_list\n\n def perform_integration(self):\n # initial data for step\n pos_arr = np.array([(i.position.x, i.position.y, i.position.z) for i in self.bodies[:]])\n vel_arr = np.array([(i.velocity.x, i.velocity.y, i.velocity.z) for i in self.bodies[:]])\n mass_arr = np.array([[i.mass] for i in self.bodies[:]])\n time_step_arr = np.array([[self.time_step] for i in self.bodies[:]])\n\n # calculation of the acceleration on bodies from all other bodies\n dr_arr = pos_arr[np.newaxis, :] - pos_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n r_between_arr[~np.isfinite(r_between_arr)] = 1\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n acc_arr = (dr_arr.T * tmp_arr).T\n acc_arr = acc_arr.sum(axis=1)\n\n # new trajectory calculations, velocity before position unlike the Euler method\n vel_arr += acc_arr * time_step_arr\n pos_arr += vel_arr * time_step_arr\n\n for index, body in enumerate(self.bodies):\n # update trajectories\n body.position.x = pos_arr[index][0]\n body.position.y = pos_arr[index][1]\n body.position.z = pos_arr[index][2]\n body.velocity.x = vel_arr[index][0]\n body.velocity.y = vel_arr[index][1]\n body.velocity.z = vel_arr[index][2]\n\n\nclass EulerRichardsonMethod:\n \"\"\"Class for evaluation of the Euler-Richardson method of integration.\n Midstep version of Euler method.\"\"\"\n\n def __init__(self, time_step, bodies_list):\n self.time_step = time_step\n self.bodies = bodies_list\n\n def perform_integration(self):\n # initial data for step\n pos_arr = np.array([(i.position.x, i.position.y, i.position.z) for i in self.bodies[:]])\n vel_arr = np.array([(i.velocity.x, i.velocity.y, i.velocity.z) for i in self.bodies[:]])\n mass_arr = np.array([[i.mass] for i in self.bodies[:]])\n time_step_arr = np.array([[self.time_step] for i in self.bodies[:]])\n\n # calculation of the acceleration on bodies from all other bodies using starting trajectories\n dr_arr = pos_arr[np.newaxis, :] - pos_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n r_between_arr[~np.isfinite(r_between_arr)] = 1\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n start_acc_arr = (dr_arr.T * tmp_arr).T\n start_acc_arr = start_acc_arr.sum(axis=1)\n\n # midstep trajectory calculations\n vel_mid_arr = vel_arr + start_acc_arr * 0.5 * time_step_arr\n pos_mid_arr = pos_arr + vel_arr * 0.5 * time_step_arr\n\n # calculation of the acceleration on bodies from all other bodies using midstep trajectories\n dr_arr = pos_mid_arr[np.newaxis, :] - pos_mid_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n r_between_arr[~np.isfinite(r_between_arr)] = 1\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n acc_mid_arr = (dr_arr.T * tmp_arr).T\n acc_mid_arr = acc_mid_arr.sum(axis=1)\n\n # new trajectory calculations\n vel_arr += acc_mid_arr * time_step_arr\n pos_arr += vel_mid_arr * time_step_arr\n\n for index, body in enumerate(self.bodies):\n # update trajectories\n body.position.x = pos_arr[index][0]\n body.position.y = pos_arr[index][1]\n body.position.z = pos_arr[index][2]\n body.velocity.x = vel_arr[index][0]\n body.velocity.y = vel_arr[index][1]\n body.velocity.z = vel_arr[index][2]\n\n\nclass RK4Method:\n \"\"\"Class for evaluation of the Fourth Order Runge-Kutta method of integration.\n Solves for Newton's equations of motion, therefore not symplectic.\n Takes an average of the forces acting over a timestep using different starting forces.\"\"\"\n # TODO: rewrite as matrices\n\n def __init__(self, time_step, bodies_list):\n self.time_step = time_step\n self.bodies = bodies_list\n\n def __partial_step(self, p1, p2, time_step):\n # calculation for the partial steps of the RK4 method\n ret = VectorData((0,0,0))\n ret.x = p1.x + p2.x * time_step\n ret.y = p1.y + p2.y * time_step\n ret.z = p1.z + p2.z * time_step\n return ret\n\n def acc_func(self, other_body, focus_body_current, vec):\n # determine distance between two bodies\n dx = (other_body.position.x - focus_body_current.x)\n dy = (other_body.position.y - focus_body_current.y)\n dz = (other_body.position.z - focus_body_current.z)\n\n # calculate total acceleration for vector calculations\n r_between = ((dx * dx) + (dy * dy) + (dz * dz))\n r_between = mp.sqrt(r_between)\n tmp = G_const * other_body.mass / (r_between * r_between * r_between)\n\n # calculation of the new acceleration vector\n vec.x += tmp * dx\n vec.y += tmp * dy\n vec.z += tmp * dz\n\n return vec\n\n def calc_trajectory(self, body_index):\n # call focus body class and setup partial step vectors\n focus_body = self.bodies[body_index]\n k1v = VectorData((0, 0, 0))\n k2v = VectorData((0, 0, 0))\n k3v = VectorData((0, 0, 0))\n k4v = VectorData((0, 0, 0))\n k1p = VectorData((0, 0, 0))\n k2p = VectorData((0, 0, 0))\n k3p = VectorData((0, 0, 0))\n k4p = VectorData((0, 0, 0))\n\n for index, other_body in enumerate(self.bodies):\n # calculate the partial step accelerations acting on the focus body from all other bodies\n # does not use old trajectory date => some error from using updated trajectories for successive bodies\n if index != body_index:\n k1v = self.acc_func(other_body, focus_body.position, k1v)\n\n k1p.x = focus_body.velocity.x\n k1p.y = focus_body.velocity.y\n k1p.z = focus_body.velocity.z\n\n k2dp = self.__partial_step(focus_body.position, k1p, (self.time_step * 0.5))\n k2v = self.acc_func(other_body, k2dp, k2v)\n k2p = self.__partial_step(focus_body.velocity, k1v, (self.time_step * 0.5))\n\n k3dp = self.__partial_step(focus_body.position, k2p, (self.time_step * 0.5))\n k3v = self.acc_func(other_body, k3dp, k3v)\n k3p = self.__partial_step(focus_body.velocity, k2v, (self.time_step * 0.5))\n\n k4dp = self.__partial_step(focus_body.position, k3p, self.time_step)\n k4v = self.acc_func(other_body, k4dp, k4v)\n k4p = self.__partial_step(focus_body.velocity, k3v, self.time_step)\n\n # calculate average acceleration and update trajectories\n focus_body.velocity.x = (focus_body.velocity.x + (self.time_step / 6.) *\n (k1v.x + (2. * k2v.x) + (2. * k3v.x) + k4v.x))\n focus_body.velocity.y = (focus_body.velocity.y + (self.time_step / 6.) *\n (k1v.y + (2. * k2v.y) + (2. * k3v.y) + k4v.y))\n focus_body.velocity.z = (focus_body.velocity.z + (self.time_step / 6.) *\n (k1v.z + (2. * k2v.z) + (2. * k3v.z) + k4v.z))\n focus_body.position.x = (focus_body.position.x + (self.time_step / 6.) *\n (k1p.x + (2. * k2p.x) + (2. * k3p.x) + k4p.x))\n focus_body.position.y = (focus_body.position.y + (self.time_step / 6.) *\n (k1p.y + (2. * k2p.y) + (2. * k3p.y) + k4p.y))\n focus_body.position.z = (focus_body.position.z + (self.time_step / 6.) *\n (k1p.z + (2. * k2p.z) + (2. * k3p.z) + k4p.z))\n\n def perform_integration(self):\n for body_index, focus_body in enumerate(self.bodies):\n self.calc_trajectory(body_index)\n\n\nclass VelocityVerletMethod: # synchronised / integer step version of leapfrog\n \"\"\"Class for evaluation of the Velocity Verlet method of integration.\n Updates position and velocity at the same time variable unlike Leapfrog,\n and incorporates velocity, solving the first time step problem in basic Verlet method..\"\"\"\n\n def __init__(self, time_step, bodies_list):\n self.time_step = time_step\n self.bodies = bodies_list\n\n def perform_integration(self):\n # initial data for step\n pos_arr = np.array([(i.position.x, i.position.y, i.position.z) for i in self.bodies[:]])\n vel_arr = np.array([(i.velocity.x, i.velocity.y, i.velocity.z) for i in self.bodies[:]])\n mass_arr = np.array([[i.mass] for i in self.bodies[:]])\n\n # calculation of the acceleration on bodies from all other bodies using starting trajectories\n dr_arr = pos_arr[np.newaxis, :] - pos_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n start_acc_arr = (dr_arr.T * tmp_arr).T\n start_acc_arr = start_acc_arr.sum(axis=1)\n\n # new position calculation using starting velocity\n pos_arr += vel_arr * self.time_step + 0.5 * start_acc_arr * self.time_step * self.time_step\n\n # calculation of the acceleration on bodies from all other bodies using midstep position\n dr_arr = pos_arr[np.newaxis, :] - pos_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n new_acc_arr = (dr_arr.T * tmp_arr).T\n new_acc_arr = new_acc_arr.sum(axis=1)\n\n # new velocity calculation using starting and new acceleration average\n vel_arr += (start_acc_arr + new_acc_arr) * 0.5 * self.time_step\n\n for index, body in enumerate(self.bodies):\n # update trajectories\n body.position.x = pos_arr[index][0]\n body.position.y = pos_arr[index][1]\n body.position.z = pos_arr[index][2]\n body.velocity.x = vel_arr[index][0]\n body.velocity.y = vel_arr[index][1]\n body.velocity.z = vel_arr[index][2]\n\n\nclass VariableLeapfrogMethod:\n \"\"\"Class for evaluation of the Velocity Verlet method of integration.\n The velocity and position calculations leapfrog over one another in terms of time evaluated for.\"\"\"\n # TODO: fix issue of bodies with smaller timestep not following the same path as their matrices counterpart\n def __init__(self, time_step, bodies_list):\n self.time_step = time_step # Use largest timestep\n self.bodies = bodies_list\n self.time = 0.\n self.fixed_ts = False\n\n def _calculate_acceleration(self, body_index):\n \"\"\"Calculates the net acceleration of a body at the beginning of the step\n from all gravitational forces acting on it.\"\"\"\n\n # setup acceleration vector class and call focus body class\n acceleration = VectorData((0, 0, 0))\n focus_body = self.bodies[body_index]\n\n for index, other_body in enumerate(self.bodies):\n # calculate and sum the accelerations from all other bodies acting on the focus body\n if index != body_index:\n dx = (other_body.old_position.x - focus_body.position.x)\n dy = (other_body.old_position.y - focus_body.position.y)\n dz = (other_body.old_position.z - focus_body.position.z)\n\n r_between = ((dx * dx) + (dy * dy) + (dz * dz))\n r_between = mp.sqrt(r_between)\n tmp = G_const * other_body.mass / (r_between * r_between * r_between)\n acceleration.x += tmp * dx\n acceleration.y += tmp * dy\n acceleration.z += tmp * dz\n\n return acceleration\n\n def perform_integration(self):\n # add global timestep for final time of current step\n self.time += self.time_step\n\n for body_index, focus_body in enumerate(self.bodies):\n # update previous position for other bodies to calculate from (and not use 'future'/updated positions)\n focus_body.old_position = focus_body.position\n\n for body_index, focus_body in enumerate(self.bodies):\n # corrects timesteps that would step out of range, designed for precision by choosing smaller timestep\n if self.fixed_ts is False and self.time_step % focus_body.time_step != 0:\n focus_body.time_step = self.time_step / int(math.ceil(self.time_step / focus_body.time_step))\n print(\"changing \" + str(focus_body.name) + \" timestep to \" + str(focus_body.time_step))\n\n while focus_body.body_time < self.time: # calculates for a bodies local steps until caught up with global\n # calculate acceleration from starting trajectories\n acceleration = self._calculate_acceleration(body_index)\n\n # calculate midstep velocity from starting acceleration\n focus_body.velocity.x += acceleration.x * focus_body.time_step * 0.5\n focus_body.velocity.y += acceleration.y * focus_body.time_step * 0.5\n focus_body.velocity.z += acceleration.z * focus_body.time_step * 0.5\n\n # calculate new position from midstep velocity\n focus_body.position.x += focus_body.velocity.x * focus_body.time_step\n focus_body.position.y += focus_body.velocity.y * focus_body.time_step\n focus_body.position.z += focus_body.velocity.z * focus_body.time_step\n\n # calculate new acceleration with new position\n acceleration = self._calculate_acceleration(body_index)\n\n # calculate new velocity from new acceleration\n focus_body.velocity.x += acceleration.x * focus_body.time_step * 0.5\n focus_body.velocity.y += acceleration.y * focus_body.time_step * 0.5\n focus_body.velocity.z += acceleration.z * focus_body.time_step * 0.5\n\n # update body local time with bodies timestep\n focus_body.body_time += focus_body.time_step\n\n self.fixed_ts = True # updates correct timesteps variable to stop correction from repeating\n\n\nclass VariableLeapfrogMethodM: # Fixed timestep because of matrices\n \"\"\"Class for evaluation of the Velocity Verlet method of integration.\n The velocity and position calculations leapfrog over one another in terms of time evaluated for.\n This method uses NumPy arrays and therefore cannot current utilise variable timesteps and is only for evaluation\"\"\"\n\n def __init__(self, time_step, bodies_list):\n self.time_step = time_step\n self.bodies = bodies_list\n\n def perform_integration(self):\n # initial data for step\n pos_arr = np.array([(i.position.x, i.position.y, i.position.z) for i in self.bodies[:]])\n vel_arr = np.array([(i.velocity.x, i.velocity.y, i.velocity.z) for i in self.bodies[:]])\n mass_arr = np.array([[i.mass] for i in self.bodies[:]])\n time_step_arr = np.array([[self.time_step] for i in self.bodies[:]])\n\n # calculation of the acceleration on bodies from all other bodies using starting trajectories\n dr_arr = pos_arr[np.newaxis, :] - pos_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n r_between_arr[~np.isfinite(r_between_arr)] = 1\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n start_acc_arr = (dr_arr.T * tmp_arr).T\n start_acc_arr = start_acc_arr.sum(axis=1)\n\n # midstep velocity and new position calculations\n vel_mid_arr = vel_arr + start_acc_arr * 0.5 * time_step_arr\n pos_arr += vel_mid_arr * time_step_arr\n\n # calculation of the acceleration on bodies from all other bodies using midstep trajectories\n dr_arr = pos_arr[np.newaxis, :] - pos_arr[:, np.newaxis]\n r_between_arr = np.sqrt(np.sum(dr_arr * dr_arr, axis=-1))\n tmp_arr = G_const * mass_arr / (r_between_arr * r_between_arr * r_between_arr)\n tmp_arr[~np.isfinite(tmp_arr)] = 0\n new_acc_arr = (dr_arr.T * tmp_arr).T\n new_acc_arr = new_acc_arr.sum(axis=1)\n\n # new velocity calculation\n vel_arr = vel_mid_arr + new_acc_arr * 0.5 * time_step_arr\n\n for index, body in enumerate(self.bodies):\n # update trajectories\n body.position.x = pos_arr[index][0]\n body.position.y = pos_arr[index][1]\n body.position.z = pos_arr[index][2]\n body.velocity.x = vel_arr[index][0]\n body.velocity.y = vel_arr[index][1]\n body.velocity.z = vel_arr[index][2]\n","sub_path":"integrators.py","file_name":"integrators.py","file_ext":"py","file_size_in_byte":20060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"492881684","text":"# -*- coding: utf-8 -*-\n\nimport scrapy\nimport os\nfrom ca_salary.items import SalaryItem\nimport re\n\n\nclass SalarySpider(scrapy.Spider):\n\n name = 'salary'\n allowed_domains = ['transparentcalifornia.com']\n start_urls = ['https://transparentcalifornia.com/salaries/2011/']\n\n page_count = 0\n\n def start_requests(self):\n\n file = self.settings[\"FEED_URI\"]\n\n if os.path.isfile(file):\n with open(file, 'w') as f:\n f.truncate()\n print(\"'{0}' truncated ...\".format(file))\n\n for url in self.start_urls:\n yield scrapy.Request(url, self.parse)\n\n @staticmethod\n def strip_money(value):\n\n if value == \"Not provided\":\n return \"\"\n\n value = value.replace(\"$\", \"\")\n value = value.replace(\",\", \"\")\n return value\n\n def parse(self, response):\n\n self.page_count = self.page_count + 1\n\n print(\"\\n\\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Processing Page {0} !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n\\n\".format(self.page_count))\n\n table = response.xpath('//table[@id=\"main-listing\"]')\n\n for row in table.xpath('tbody//tr'):\n\n item = SalaryItem()\n\n item['name'] = row.xpath('td[1]/a/text()').extract()[0].strip()\n item['title'] = row.xpath('td[2]/a/text()').extract()[0].strip()\n\n item['employer'] = row.xpath('td[2]/small/a/text()').extract()[0].strip()\n item['year'] = \"\"\n\n match = re.match(r'^(.+?)(\\d{4})$', item['employer'])\n if match:\n item['employer'] = match.group(1).strip().rstrip(\",\")\n item['year'] = match.group(2)\n\n item['regular'] = SalarySpider.strip_money(row.xpath('td[3]/text()').extract()[0].strip())\n item['overtime'] = SalarySpider.strip_money(row.xpath('td[4]/text()').extract()[0].strip())\n item['other'] = SalarySpider.strip_money(row.xpath('td[5]/text()').extract()[0].strip())\n\n item['total_pay'] = SalarySpider.strip_money(row.xpath('td[6]/text()').extract()[0].strip())\n item['total_benefits'] = SalarySpider.strip_money(row.xpath('td[7]/text()').extract()[0].strip())\n item['total'] = SalarySpider.strip_money(row.xpath('td[8]/text()').extract()[0].strip())\n\n yield item\n\n next_page = response.css('li.next a::attr(href)').extract_first()\n\n #if self.page_count >= 5:\n # exit()\n\n if next_page is not None:\n yield response.follow(next_page, self.parse)\n\n\n\n","sub_path":"ca_salary/ca_salary/spiders/salary.py","file_name":"salary.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"260913802","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 18 16:59:35 2020\n\n@author: wyue\n\"\"\"\n\nclass Solution(object):\n def findNthDigit(self, n):\n\n if n < 10:\n return n\n pwr = 1\n remain = n\n while remain - pwr * 9 * (10 ** (pwr - 1)) > 0:\n remain -= pwr * 9 * (10 ** (pwr - 1))\n pwr += 1\n div = remain // pwr\n remainder = remain % pwr\n if remainder == 0:\n nxtnum = (10 ** (pwr - 1)) - 1 + div\n remainder = pwr\n else:\n nxtnum = (10 ** (pwr - 1)) - 1 + div + 1\n rst = str(nxtnum)[remainder-1]\n \n return int(rst)\n\n\n # \"\"\"\n # :type n: int\n # :rtype: int\n # \"\"\"\n # i = 1\n # while n > 9*(10**(i-1))*i:\n # n = n - 9*(10**(i-1))*i\n # i += 1\n \n # start = 10**(i-1)\n \n # rst_string = str(start + (n-1)//i)[(n-1)%i]\n # rst = int(rst_string)\n \n\n # return rst\n\nn = 11\nprint(Solution().findNthDigit(n))","sub_path":"Algorithms/400. Nth Digit.py","file_name":"400. Nth Digit.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"38713450","text":"import QSTK.qstkutil.qsdateutil as du\nimport QSTK.qstkutil.DataAccess as da\nimport datetime as dt\nfrom pylab import *\nimport sys\nimport pandas\nimport csv\n\n\ndef _csv_read_sym_dates(filename):\n reader = csv.reader(open(filename, 'rU'), delimiter=',')\n symbols = []\n dates = []\n for row in reader:\n if not(row[3] in symbols):\n symbols.append(row[3])\n date = dt.datetime(int(row[0]), int(row[1]), int(row[2]))\n if not(date in dates):\n dates.append(date)\n dates = sorted(dates)\n return symbols, dates\n\n\ndef _read_data(symbols, dates):\n timeofday = dt.timedelta(hours=16)\n timestamps = du.getNYSEdays(dates[0], dates[-1] + dt.timedelta(days=1), timeofday)\n\n dataobj = da.DataAccess('Yahoo')\n close = dataobj.get_data(timestamps, symbols, \"close\", verbose=True)\n close = close.fillna(method='ffill')\n close = close.fillna(method='bfill')\n return close, timestamps\n\n\ndef _share_holdings(filename, symbols, timestamps, close):\n reader = csv.reader(open(filename, 'rU'), delimiter=',')\n share_matrix = np.zeros((len(timestamps), len(symbols)))\n share_matrix = pandas.DataFrame(share_matrix, index=timestamps, columns=symbols)\n for row in reader:\n date = dt.datetime(int(row[0]), int(row[1]), int(row[2]))\n time_stp = close.index[close.index >= date][0]\n if row[4] == 'Buy':\n share_matrix.ix[time_stp][row[3]] += float(row[5])\n elif row[4] == 'Sell':\n share_matrix.ix[time_stp][row[3]] -= float(row[5])\n return share_matrix\n\n\ndef _share_value_cash(share_matrix, close, i_start_cash):\n ts_cash = pandas.TimeSeries(0.0, close.index)\n ts_cash[0] = i_start_cash\n for row_index, row in share_matrix.iterrows():\n cash = np.dot(row.values.astype(float), close.ix[row_index].values)\n ts_cash[row_index] -= cash\n share_matrix['_CASH'] = ts_cash\n share_matrix = share_matrix.cumsum()\n return share_matrix\n\n\ndef _fund_value(share_matrix, close):\n historic = close\n historic['_CASH'] = 1\n ts_fund = pandas.TimeSeries(0.0, close.index)\n for row_index, row in share_matrix.iterrows():\n ts_fund[row_index] += np.dot(row.values.astype(float), close.ix[row_index].values)\n return ts_fund\n\n\ndef _write_fund(ts_fund, filename):\n writer = csv.writer(open(filename, 'wb'), delimiter=',')\n for row_index in ts_fund.index:\n row_to_enter = [str(row_index.year), str(row_index.month), \\\n str(row_index.day), str(ts_fund[row_index])]\n writer.writerow(row_to_enter)\n\n\ni_start_cash = float(sys.argv[1])\nsymbols, dates = _csv_read_sym_dates(sys.argv[2])\nclose, timestamps = _read_data(symbols, dates)\nshare_matrix = _share_holdings(sys.argv[2], symbols, timestamps, close)\nshare_matrix = _share_value_cash(share_matrix, close, i_start_cash)\nts_fund = _fund_value(share_matrix, close)\n_write_fund(ts_fund, sys.argv[3])\n","sub_path":"python/computational-investment-course/homeworks/hw3/teacher/marketsim.py","file_name":"marketsim.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"122359922","text":"import matplotlib.pyplot as plt\n\n#Minimax\nwith open('Graph/pointsMM.txt') as f:\n lines = f.readlines()\n x = [int(line.split()[0]) for line in lines]\n y = [int(line.split()[1]) for line in lines]\n\nplt.ylim(0, 101)\nplt.plot(x ,y)\n\nplt.xlabel('Number of Games')\nplt.ylabel('Number of Points')\nplt.title('Minimax Algorithm')\n\nplt.show()\n\n\n","sub_path":"Graph/graphMinimax.py","file_name":"graphMinimax.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"400428769","text":"# shape=(n, row, col, 9), shape=(n, row, col, 36)\nimport numpy as np\nfrom core import *\n\n\ndef rpn_to_roi(box_BC_return_value, regression_return_value, max_boxes=300, overlap_thresh=0.9):\n \"\"\"\n box_BC_return_value : shape=(1, row, col, 9)\n regression_return_value: shape=(1, row, col, 36)\n\n\n \"\"\"\n # std_scaling=4\n regression_return_value = regression_return_value / Config.std_scaling\n\n anchor_sizes = Config.anchor_sizes\n anchor_ratios = Config.anchor_ratios\n\n (rows, cols) = box_BC_return_value.shape[1:3]\n\n curr_layer = 0\n # shape=(row, col, 9, 4)\n box_BC_tmp_value = np.zeros((box_BC_return_value.shape[1], box_BC_return_value.shape[2], box_BC_return_value.shape[3], 4))\n\n for anchor_size in anchor_sizes:\n for anchor_ratio in anchor_ratios:\n # rpn_stride=16\n anchor_x = anchor_w = (anchor_size * anchor_ratio[0]) / Config.pooling_size\n anchor_y = anchor_h = (anchor_size * anchor_ratio[1]) / Config.pooling_size\n regression_tmp_value = regression_return_value[0, :, :, 4 * curr_layer:4 * curr_layer + 4]\n\n box_BC_tmp_x, box_BC_tmp_y = np.meshgrid(np.arange(cols), np.arange(rows))\n\n box_BC_tmp_value[:, :, curr_layer, 0] = regression_return_value[0, :, :, 0] * anchor_w + box_BC_tmp_x\n box_BC_tmp_value[:, :, curr_layer, 1] = regression_return_value[0, :, :, 1] * anchor_h + box_BC_tmp_y\n box_BC_tmp_value[:, :, curr_layer, 2] = np.exp(np.asarray(regression_return_value[0, :, :, 2], dtype=np.float32)) * anchor_w\n box_BC_tmp_value[:, :, curr_layer, 3] = np.exp(np.asarray(regression_return_value[0, :, :, 3], dtype=np.float32)) * anchor_h\n\n '''\n center_gt_x = (bboxes[bbox_num]['x1'] + bboxes[bbox_num]['x2']) / 2\n center_gt_y = (bboxes[bbox_num]['y1'] + bboxes[bbox_num]['y2']) / 2\n center_anchor_x = (anchor_box['x1'] + anchor_box['x2']) / 2\n center_anchor_y = (anchor_box['y1'] + anchor_box['y2']) / 2\n\n dx = (center_gt_x - center_anchor_x) / (anchor_box['x2'] - anchor_box['x1'])\n dy = (center_gt_y - center_anchor_y) / (anchor_box['y2'] - anchor_box['y1'])\n dw = np.log((bboxes[bbox_num]['x2'] - bboxes[bbox_num]['x1']) / (anchor_box['x2'] - anchor_box['x1']))\n dh = np.log((bboxes[bbox_num]['y2'] - bboxes[bbox_num]['y1']) / (anchor_box['y2'] - anchor_box['y1']))\n '''\n\n # xy最小值不能低于0.5\n box_BC_tmp_value[:, :, curr_layer, 0] = np.maximum(0.5, box_BC_tmp_value[:, :, curr_layer, 0])\n box_BC_tmp_value[:, :, curr_layer, 1] = np.maximum(0.5, box_BC_tmp_value[:, :, curr_layer, 1])\n\n # wh最小值不能低于1个像素\n box_BC_tmp_value[:, :, curr_layer, 2] = np.maximum(1, box_BC_tmp_value[:, :, curr_layer, 2])\n box_BC_tmp_value[:, :, curr_layer, 3] = np.maximum(1, box_BC_tmp_value[:, :, curr_layer, 3])\n\n # #\n # box_BC_tmp_value[:, :, curr_layer, 2] = np.minimum(cols - 1, box_BC_tmp_value[:, :, curr_layer, 2])\n # box_BC_tmp_value[:, :, curr_layer, 3] = np.minimum(rows - 1, box_BC_tmp_value[:, :, curr_layer, 3])\n # 到这里,才真正形成(x1, y1, x2, y2)\n curr_layer += 1\n\n # A shape=(4, row, col, 9)\n # all_boxes shape=(row*col*9, 4)\n all_boxes = np.reshape(box_BC_tmp_value, (-1, 4))\n # all_probs shape=(row*col*9)\n all_probs = np.reshape(box_BC_return_value, (-1))\n # 删除小于一个像素的局部(似乎上面以前排除掉这部分了, 似乎)\n idxs = np.where((all_boxes[:, 0] >= 0) | (all_boxes[:, 1] >= 0))\n\n # TODO 删除下列代码\n all_boxes = np.delete(all_boxes, idxs, 0)\n all_probs = np.delete(all_probs, idxs, 0)\n\n # return shape=(nn, 4), (x,y,w,h)\n result = utils.non_max_suppression(all_boxes, all_probs, overlap_thresh=overlap_thresh, max_boxes=max_boxes)[0]\n\n # # return [{'x1':x1, 'x2':x2, 'y1':y1, 'y2':y2}...]\n # result = list(map(lambda x: {'x1': x[0] - 0.5 * x[2], 'x2': x[0] + 0.5 * x[2], 'y1': x[1] - 0.5 * x[3], 'y2': x[1] + 0.5 * x[3]}, result))\n # return shape=(nn, 4)\n return result\n\n\ndef roi_to_result(regions, bboxes, class_mapping):\n\n\n output_coord = []\n # (n, class_num)类别索引\n output_index = []\n output_regr = []\n output_label = []\n output_regr_label = []\n\n for region in regions:\n best_iou = 0.0\n for bbox_num in range(len(bboxes)):\n iou = utils.iou_calculate(region, bboxes[bbox_num])\n if iou > best_iou:\n best_iou = iou\n best_num = bbox_num\n class_name = bboxes[bbox_num]['class']\n\n regr = [0] * 4 * (len(class_mapping) - 1)\n labels = [0] * 4 * (len(class_mapping) - 1)\n\n if best_iou >= Config.rpn_threshold_max and best_iou != 0.0:\n dx = (bboxes[best_num]['x'] - region[0]) / (region[1] - region[0])\n dy = (bboxes[best_num]['y'] - region[1]) / (region[3] - region[2])\n dw = np.log(bboxes[best_num]['w']) / region[1] - region[0]\n dh = np.log(bboxes[best_num]['h']) / region[3] - region[2]\n\n class_id = class_mapping[class_name]\n class_labels = [0] *len(class_mapping)\n class_labels[class_id] = 1\n # (n, class_num)类别索引\n output_index.append(class_labels)\n # (n, 4)预测xywh\n output_coord.append({'x1': region[0], 'y1': region[1], 'x2': region[2], 'y2': region[3]})\n\n\n pos = class_id * 4\n regr[pos: pos + 4] = [dx, dy, dw, dh]\n labels[pos: pos + 4] = [1, 1, 1, 1]\n\n output_regr.append(regr)\n output_label.append(labels)\n\n # (n, 8*numclass)\n output_regr_label.append(np.concatenate([np.asarray(output_label), np.asarray(output_regr)], axis=1))\n\n return np.expand_dims(np.asarray(output_coord), axis=0), np.expand_dims(np.asarray(output_index), axis=0), output_regr_label","sub_path":"core/rpn_funcs.py","file_name":"rpn_funcs.py","file_ext":"py","file_size_in_byte":6033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"138553928","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\"\"\"\nManage all operations.\n\"\"\"\n\nfrom karbor import exception\nfrom karbor.i18n import _\nfrom karbor.services.operationengine import operations\n\n\nclass OperationManager(object):\n \"\"\"Manage all operation classes which are defined at operations dir.\"\"\"\n def __init__(self, user_trust_manager):\n super(OperationManager, self).__init__()\n self._user_trust_manager = user_trust_manager\n all_ops = operations.all_operations()\n self._ops_map = {op.OPERATION_TYPE: op(self._user_trust_manager)\n for op in all_ops}\n\n def _get_operation(self, operation_type):\n if operation_type not in self._ops_map:\n msg = (_(\"Invalid operation type: %s\") % operation_type)\n raise exception.InvalidInput(msg)\n\n return self._ops_map[operation_type]\n\n def check_operation_definition(self, operation_type, operation_definition):\n \"\"\"Check operation definition.\n\n :param operation_type: the type of operation\n :param operation_definition: the definition of operation\n :raise InvalidInput: if the operation_type is invalid or\n InvalidOperationDefinition if operation_definition is invalid\n \"\"\"\n op = self._get_operation(operation_type)\n op.check_operation_definition(operation_definition)\n\n def run_operation(self, operation_type, operation_definition, **kwargs):\n \"\"\"Run operation.\n\n :param operation_type: the type of operation\n :param operation_definition: the definition of operation\n :raise InvalidInput: if the operation_type is invalid.\n \"\"\"\n op = self._get_operation(operation_type)\n op.run(operation_definition, **kwargs)\n","sub_path":"karbor-1.3.0/karbor/services/operationengine/operation_manager.py","file_name":"operation_manager.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"372041731","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 20 13:19:25 2015\n\n@author: Duncan\n\nUse a Kalman filter on GPS serial data to predict the PPS arrial time\n\nKalman filter smooths time of GPS serial data arrival, use PPS-SER distribution average to get expected PPS time\n\nWe must supply uncertainties in GPS serial time (given by PPS_SER dist) and arduino time (~1 ms)\nAlso we use the *drift* on the arduino -- the average second length discrepency\n\nformat:\nlines must contain\ntxxxx...,xxxx... (times for serial,pps)\n\n\"\"\"\nimport numpy as np\nimport matplotlib as mplt\nimport matplotlib.pyplot as plt\nimport KalmanFilter as klm\nfilename = \"GARNMEA20160131_190024ChckdCor\"\n\n# extract data into arrays\n\ncontents = open(\"../../Results/\"+filename+\".txt\", mode='r')\ncontentsTxt = contents.readlines()\ncontents.close()\n\nser_T = [0]*len(contentsTxt)\npps_T = [0]*len(contentsTxt)\n\nj = 0\nfor i in range(len(contentsTxt)):\n\tline = contentsTxt[i]\n\tif (line[0]=='t'):\n\t\tcommaLoc = line.index(',')\n\t\tser_T[j] = int(line[1:commaLoc])\n\t\tpps_T[j] = int(line[commaLoc+1:])\n\t\tj += 1\n\t\t\nstart = 0\t\t\nend = j\nser_T = ser_T[start:end]\npps_T = pps_T[start:end]\n\n\nserE_T = [0]*len(ser_T)\t \t# expected time of serial arrival\ncovU_T = [0]*len(ser_T)\t \t# expected uncertainty\nardU_t = 0.5\t\t\t\t# uncertainty in arduino times\nardD_t = (pps_T[-1]-pps_T[0])/(len(pps_T)-1)-1000\t# arduino drift per millisecond (from post-analysis) - defined as ard_ms in 1s - 1000\nserU_t = 150\t\t\t \t# uncertainty in gps serial arrival times\n\t\ncovU_T[0] = 100\nserE_T[0] = ser_T[0]\n\nfor i in range(len(serE_T)-1):\n\tserE_T[1+i], covU_T[1+i] = klm.KalFilIter(serE_T[i], 1000+ardD_t, ser_T[1+i], covU_T[i], ardU_t, serU_t)\n\t\nppsserE_dT = [0]*len(serE_T)\nfor i in range(len(serE_T)):\n\tppsserE_dT[i] = serE_T[i]-pps_T[i]\n\t\nppsser_dT = [0]*len(ser_T)\nfor i in range(len(ppsser_dT)):\n\tppsser_dT[i] = ser_T[i]-pps_T[i]\n\t\n\t\nserser_dT = [0]*(len(ser_T)-1)\nfor i in range(len(serser_dT)):\n\tserser_dT[i] = ser_T[1+i]-ser_T[i]\n\t\n\t\nppspps_dT = [0]*(len(ser_T)-1)\nfor i in range(len(serser_dT)):\n\tppspps_dT[i] = pps_T[1+i]-pps_T[i]\n\t\n\t\nserEserE_dT = [0]*(len(serE_T)-1)\nfor i in range(len(serEserE_dT)):\n\tserEserE_dT[i] = serE_T[1+i]-serE_T[i]\n\t\n\nmplt.rcParams.update({'font.size': 16})\nfig = plt.figure(figsize=(10,6))\n\nyLow = min(min(ppsser_dT),min(ppsserE_dT))\nyHi = max(max(ppsser_dT),max(ppsserE_dT))\nyLow = max(0, int(yLow/20)*20)\nyHi = min(1000, int(yHi/20+1)*20)\n\t\nxplot = np.linspace(0,len(ppsser_dT),len(ppsser_dT))\nser_ppsser = plt.scatter(xplot, ppsser_dT, s=2, linewidth=0, color=\"black\")\nser_ppsserE = plt.scatter(xplot, ppsserE_dT, s=2, linewidth=0, color=\"red\")\nplt.xlim(min(xplot),max(xplot))\nplt.ylim(yLow,yHi)\nplt.title(\"PPS Serial difference using Kalman filter\")\nplt.xlabel(\"Sample\")\nplt.ylabel(\"Time difference / ms\")\nlgndh = plt.legend([ser_ppsser,ser_ppsserE],[\"Raw\",\"Kalman\"])\nlgndh.legendHandles[0]._sizes = [30]\nlgndh.legendHandles[1]._sizes = [30]\nparams = {'legend.fontsize': 18}\nplt.rcParams.update(params) # the legend text fontsize\nplt.annotate(\"std dev \"+str(int(round(np.std(ppsser_dT),0)))+\n\t \" --> \"+str(int(round(np.std(ppsserE_dT),0)))+\" ms\", xy=(0.05, 0.95), xycoords='axes fraction')\nplt.savefig(\"../../Results/\"+filename+\"ppsserKalman(\"+str(start)+\"-\"+str(end)+\").png\",dpi=400)\nplt.savefig(\"../../Results/\"+filename+\"ppsserKalman(\"+str(start)+\"-\"+str(end)+\").svg\")\n\n\nfig = plt.figure(figsize=(10,6))\n\t\nyLow = min(min(serser_dT),min(serEserE_dT))\nyHi = max(max(serser_dT),max(serEserE_dT))\nyLow = max(0, int(yLow/20)*20)\nyHi = min(2000, int(yHi/20+1)*20)\n\nxplot = np.linspace(0,len(serser_dT),len(serser_dT))\nser_serser = plt.scatter(xplot, serser_dT, s=2, linewidth=0, color=\"black\")\nser_serEserE = plt.scatter(xplot, serEserE_dT, s=2, linewidth=0, color=\"red\")\nplt.xlim(min(xplot),max(xplot))\nplt.ylim(yLow,yHi)\nplt.title(\"Consecutive serial time difference using Kalman filter\")\nplt.xlabel(\"Sample\")\nplt.ylabel(\"Time difference / ms\")\nlgndh = plt.legend([ser_serser,ser_serEserE],[\"Raw\",\"Kalman\"])\nlgndh.legendHandles[0]._sizes = [30]\nlgndh.legendHandles[1]._sizes = [30]\nparams = {'legend.fontsize': 18}\nplt.rcParams.update(params) # the legend text fontsize\nplt.annotate(\"std dev \"+str(int(round(np.std(serser_dT),0)))+\n\t \" --> \"+str(round(np.std(serEserE_dT),1))+\" ms\", xy=(0.05, 0.95), xycoords='axes fraction')\nplt.savefig(\"../../Results/\"+filename+\"serserKalman(\"+str(start)+\"-\"+str(end)+\").png\",dpi=400)\nplt.savefig(\"../../Results/\"+filename+\"serserKalman(\"+str(start)+\"-\"+str(end)+\").svg\")","sub_path":"GARMIN/Analysis/Kalman/Kalman.py","file_name":"Kalman.py","file_ext":"py","file_size_in_byte":4472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"569424960","text":"#!/usr/bin/env python3\nfrom tornado.tcpserver import TCPServer\nfrom tornado.ioloop import IOLoop\nimport logging.config\nfrom netproto import UserInterface\n\nlogging.config.fileConfig(\"loger.conf\")\nlogger = logging.getLogger('example01')\n\n\nclass Connection(object):\n clientSets = set()\n\n def __init__(self, stream, address, io_loop):\n Connection.clientSets.add(self)\n self._stream = stream\n self._conn = UserInterface(self._stream)\n self._stream.set_close_callback(self.on_close)\n self._address = address\n self.read_message()\n \n def on_close(self):\n Connection.clientSets.remove(self)\n logger.debug('Connection %s:%s get away' % (self._address[0], self._address[1]))\n\n def read_message(self):\n self._stream.read_until_close(streaming_callback=self._process_connection)\n # self._stream.read_until_close(streaming_callback=self.write_message)\n\n def write_message(self, data):\n print(data)\n self._stream.write(data)\n\n # @staticmethod # 加上会报错\n def _process_connection(self, data):\n # process_connection(self._stream, data)\n self._conn.process_connection(data)\n\n\nclass MyServer(TCPServer):\n def __init__(self, io_loop=None, **kwargs):\n # TCPServer.__init__(self, io_loop=io_loop, **kwargs)\n super(MyServer, self).__init__(io_loop=io_loop, **kwargs)\n\n # 用户必须重写 handle_stream方法\n def handle_stream(self, stream, address):\n # print(\"A new connection : %s %s\" % (address[0], address[1]))\n logger.debug('Connection %s:%s come in'% (address[0], address[1]))\n Connection(stream, address, io_loop=self.io_loop)\n \nif __name__ == \"__main__\":\n server = MyServer()\n server.listen(8889)\n # server.start() #这个start应该和多进程有关\n # IOLoop.current().start()\n IOLoop.instance().start()\n","sub_path":"learn/MysqlServer/tcpserver.py","file_name":"tcpserver.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"246511091","text":"'''\nGiven InOrder and Pre-Order traversal,contruct the binary tree\n'''\n\n\nclass Node:\n def __init__(self, info):\n self.info = info\n self.left = None\n self.right = None\n self.level = None\n\n def __str__(self):\n return str(self.info)\n\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n\n def create(self, val):\n if self.root == None:\n self.root = Node(val)\n else:\n current = self.root\n\n while True:\n if val < current.info:\n if current.left:\n current = current.left\n else:\n current.left = Node(val)\n break\n elif val > current.info:\n if current.right:\n current = current.right\n else:\n current.right = Node(val)\n break\n else:\n break\n\n\n\"\"\"\nNode is defined as\nself.left (the left child of the node)\nself.right (the right child of the node)\nself.info (the value of the node)\n\"\"\"\n\n\ndef inOrder(root: Node):\n # Write your code here\n if(root):\n inOrder(root.left)\n print(root.info, end=\" \")\n inOrder(root.right)\n\n\ndef constructTree(inOrder, preOrder):\n\n if len(preOrder) > 0:\n value = preOrder[0]\n root = Node(value)\n\n partition = inOrder.index(value)\n root.left = constructTree(\n inOrder[:partition], preOrder[1:partition + 1])\n root.right = constructTree(\n inOrder[partition + 1:], preOrder[partition + 1:])\n return root\n return None\n\n\ndef evaluate(root: Node):\n if root:\n op1 = evaluate(root.left)\n op2 = evaluate(root.right)\n operator = root.info\n\n if op1 and op2:\n root.info = operation(op1, op2, operator)\n\n return root.info\n\n return None\n\n\ndef operation(a, b, operator):\n if operator == \"+\":\n return a + b\n elif operator == \"-\":\n return a - b\n elif operator == \"*\":\n return a*b\n else:\n return a/b\n\n\nif __name__ == '__main__':\n tree = BinarySearchTree()\n\n inOrder = [3, '*', 4, '/', 5, '+', 2, '+', 3, '*', 4]\n preOrder = ['+', '/', '*', 3, 4, 5, '+', 2, '*', 3, 4]\n\n root = constructTree(inOrder, preOrder)\n\n print(evaluate(root))\n","sub_path":"Trees/treeConstruction.py","file_name":"treeConstruction.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"205154344","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/10/30 19:05\n# @Author : mrwuzs\n# @Site :\n# @File : test_09_sync_phy_resource.py\n# @Software: PyCharm\n\nimport time\nimport pytest\nimport allure\n\nfrom public.common.publicfunction import *\nfrom public.common import datainfo\nfrom public.appmodel import ressyncaction\nfrom public.pages import resSyncPage\n\n\n@allure.feature(\"资源同步\")\nclass TestPhySunc():\n \"\"\"物理资源同步\"\"\"\n\n @allure.story(\"同步物理资源\")\n @pytest.mark.flaky(reruns=globalparam.RENUM)\n def test_sync_phy_res(self,login_domain):\n dr = login_domain\n p_data = datainfo.get_xls_to_dict(\"phy_sync_data.xlsx\", \"Sheet1\")[\"物理资源同步\"]\n sync_a = ressyncaction.ResSync(dr)\n sync_pg = resSyncPage.ResSyncPage(dr)\n sync_a.phy_res_sync(\n p_data[\"regionname\"],\n p_data[\"nodename\"],\n \"DC1\",\n \"DC2\")\n time.sleep(20)\n sync_pg.click_refresh_button()\n status1 = dr.get_text(\n \"xpath->//td[contains(.,'DC1')]/../td[3]\").strip()\n count1 = 0\n while status1 == \"执行中\":\n time.sleep(10)\n sync_pg.click_refresh_button()\n status1 = dr.get_text(\n \"xpath->//td[contains(.,'DC1')]/../td[3]\").strip()\n count1 += 1\n if count1 == 10:\n break\n add_image(dr,\"同步物理资源-DC1\")\n assert status1 == \"执行成功\"\n status2 = dr.get_text(\n \"xpath->//td[contains(.,'DC2')]/../td[3]\").strip()\n count2 = 0\n while status2 == \"执行中\":\n time.sleep(10)\n sync_pg.click_refresh_button()\n status2 = dr.get_text(\n \"xpath->//td[contains(.,'DC1')]/../td[3]\").strip()\n count2 += 1\n if count2 == 10:\n break\n add_image(dr,\"同步物理资源-DC2\")\n assert status2 == \"执行成功\"\n\n\nif __name__ == \"__main__\":\n pytest.main([\"-s\", \"test_09_sync_phy_resource.py\"])\n","sub_path":"testcase/test_09_sync_phy_resource.py","file_name":"test_09_sync_phy_resource.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"339701207","text":"import locale\n\nfrom django import template\nfrom django.conf import settings\n\nregister = template.Library()\n\n\n@register.filter(name='currency')\ndef currency(value):\n \"\"\"\n Format decimal value as currency\n \"\"\"\n try:\n locale.setlocale(locale.LC_ALL, settings.LOCALE)\n except AttributeError:\n locale.setlocale(locale.LC_ALL, '')\n\n # We allow the currency symbol to be overridden as the version in system\n # locales if often not the desired one.\n try:\n symbol = getattr(settings, 'CURRENCY_SYMBOL', None)\n if symbol:\n # A custom currency symbol is specified. Check to see if a\n # custom format is specified too - this allows the position of the\n # currency symbol to be controlled.\n format = getattr(\n settings, 'CURRENCY_FORMAT', u\"%(symbol)s%(value)s\")\n return format % {\n 'symbol': symbol,\n 'value': locale.format(\"%.2f\", value, grouping=True)}\n else:\n # Use locale's currency format\n c = locale.currency(value, symbol=True, grouping=True)\n return unicode(c, 'utf8')\n except TypeError:\n return ''\n","sub_path":"oscar/templatetags/currency_filters.py","file_name":"currency_filters.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"560393367","text":"#!/usr/bin/env python3\n\nimport urllib.request\nimport urllib.parse\nimport json\n\napi_url = \"http://localhost:8983/solr/solrbook/select\"\n\nwhile 1:\n\n query = input()\n\n pars = {\"facet.field\":\"genre\",\n \"facet\":\"on\",\n \"indent\":\"on\",\n \"q\":\"title:\" + query,\n \"spellcheck\":\"on\",\n \"wt\":\"json\"\n }\n enc_pars = urllib.parse.urlencode(pars)\n\n with urllib.request.urlopen(api_url + '?' + enc_pars) as res:\n html = res.read().decode(\"utf-8\")\n #print(html)\n json_res = json.loads(html)\n #print(json_res[\"responseHeader\"])\n print(\"関連する書籍として以下のものがあります。\")\n max = json_res[\"response\"][\"numFound\"]\n if max > 5:\n max = 5\n for i in range(max):\n print(json.dumps(json_res[\"response\"][\"docs\"][i][\"title\"], ensure_ascii=False))\n print()\n print(\"下記のジャンルで絞り込めます。\")\n glen = len(json_res[\"facet_counts\"][\"facet_fields\"][\"genre\"])\n for i in range(10):\n freq = json_res[\"facet_counts\"][\"facet_fields\"][\"genre\"][i*2+1]\n if freq > 0:\n print(str(freq) + \"件:\" + json.dumps(json_res[\"facet_counts\"][\"facet_fields\"][\"genre\"][i*2], ensure_ascii=False))\n if (i+1)*2 > glen:\n break\n #print(json.dumps(json_res[\"facet_counts\"][\"facet_fields\"][\"genre\"], ensure_ascii=False))\n\n break\n","sub_path":"python/test_solr.py","file_name":"test_solr.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"150490695","text":"'''\n#scatter 散点图\nimport matplotlib.pyplot as plt \nimport numpy as np \n\nn = 1024\nX = np.random.normal(0,1,n)\nY = np.random.normal(0,1,n)\nT = np.arctan2(Y,X)\t\t\t#随机生成好看的颜色\n\nplt.scatter(X, Y, s=75, c=T, alpha=0.6)\t\t#创建散点图,点由XY定位,s代表size,c代表color,alpha代表透明度\nplt.scatter(np.arange(10), np.arange(10))\n\nplt.xlim((-1.5, 1.5))\t\t#限定x轴上点在-1.5~1.5之间\nplt.ylim((-1.5, 1.5))\t\t#限定y轴上点在-1.5~1.5之间\nplt.xticks(())\t\t\t\t#不显示x轴坐标轴\nplt.yticks(())\t\t\t\t#比现实y轴坐标轴\n\nplt.show()\n'''\n\n\n\n'''\n#bar 柱状图\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nn = 12\nX = np.arange(n)\nY1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)\nY2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)\n\nplt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')\t\t#创建bar图,+代表图显示在双轴bar图的上半部分,facecolor是填充颜色,edgecolor是边框颜色\nplt.bar(X, -Y1, facecolor='#ff9999', edgecolor='white')\t\t#- 代表创建的图为双轴bar图的下半部分\n\nfor x,y in zip(X, Y1):\t\t\t#zip是指将X和Y1数值分别传递给x和y\n\tplt.text(x+0.04, y+0.05, '%.2f'%y, ha='center', va='bottom')\n\t#x+0.4和y+0.05指标注的位置,%.2f指保留两位小数,ha代表横向居中,va代表纵向底部对齐\nfor x,y in zip(X, Y2):\n\tplt.text(x+0.04, -y-0.05, '%.2f'%y, ha='center', va='top')\n\nplt.xlim(-0.5,n)\nplt.xticks(())\nplt.ylim(-1.25,1.25)\nplt.yticks(())\n\nplt.show()\n'''\n\n\n\n\n'''\n#Contours 等高线图\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef f(x,y):\n\t#计算高度的函数\n\treturn (1 - x/2 + x**5 + y**3)*np.exp(-x**2 - y**2)\n\nn = 256\nx = np.linspace(-3, 3, n)\t\t#取值范围是-3~3,有256个点\ny = np.linspace(-3, 3, n)\nX,Y = np.meshgrid(x,y)\t\t\t#meshgrid在二维平面中将每一个x和y分别对应起来,编制成栅格\n\nplt.contourf(X, Y, f(X,Y), 8, alpha=0.75, cmap=plt.cm.hot)\n#创建等高线图,8代表等高线密集程度,alpha是透明度,color map将暖色组分配给不同的数值\n\nC = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidths=0.5)\n#创建图中等高线,同样密集程度为8,颜色为黑色,线条粗细为0.5\n\nplt.clabel(C, inline=True, fontsize=10)\n#为等高线条件标注,inline为在线内标注,fontsize为字体大小\n\nplt.xticks(())\nplt.yticks(())\nplt.show()\n'''\n\n\n\n'''\n#Image 图片\nimport matplotlib.pyplot as plt\nimport numpy as np\n\na = np.array([0.313660827978, 0.365348418405, 0.423733120134,\n 0.365348418405, 0.439599930621, 0.525083754405,\n 0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)\n\nplt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')\n#创建image,interpolation是显示色块的效果\n\nplt.colorbar(shrink=0.5)\n#显示旁边的colorbar,shrink为colorbar的比例大小\n\nplt.xticks(())\nplt.yticks(())\nplt.show()\n'''\n\n\n\n\n#3D 数据\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfig = plt.figure()\nax = Axes3D(fig)\t\t\t#显示3D坐标轴\n\nX = np.arange(-4, 4, 0.25)\t\t#创建x,y的值\nY = np.arange(-4, 4, 0.25)\nX, Y = np.meshgrid(X, Y)\t\t#与等高线一样,创建点格栅\nR = np.sqrt(X ** 2 + Y ** 2)\t#计算X和Y的值对应的高度值\nZ = np.sin(R)\t\t\t\t\t#显示高度值\n\nax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'), edgecolor='black')\n#restride是指row的跨度,cstride是column的跨度\n\nax.contourf(X, Y, Z, zdir='z',offset=-2, cmap='rainbow')\t\t#创建z轴映射上的等高线图\nax.contourf(X, Y, Z, zdir='x',offset=-4, cmap='rainbow')\nax.set_zlim(-2,2)\t\t#限制等高线图的位置\nplt.show()\n\n\n","sub_path":"Matplotlib/matplotlib_2.py","file_name":"matplotlib_2.py","file_ext":"py","file_size_in_byte":3665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"247297719","text":"from sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, Text, DateTime, Float, Boolean, PickleType\nfrom datetime import datetime\n\n\nBase = declarative_base()\n\nclass UserTable(Base):\n\n __tablename__ = \"UserTable\"\n \n user_id = Column(\n Integer,\n primary_key=True,\n nullable=False\n )\n \n user_name = Column(\n String(100),\n nullable = False\n )\n\n age = Column(\n Integer,\n nullable=False\n )\n\n birthday = Column(\n DateTime,\n nullable = False\n )\n\n gender = Column(\n String(20),\n nullable=False\n )\n\n degree = Column(\n String(100),\n nullable=False\n )\n\n time_created = Column(\n DateTime,\n default=datetime.now\n )\n\n time_modified = Column(\n DateTime,\n default=datetime.now,\n onupdate=datetime.now\n )\n\nengine = create_engine(\n \"mysql+pymysql://remoteUser:123456@47.103.136.85:3306/mydevdb?charset=utf8mb4\",\n echo=True,\n encoding=\"utf-8\")\n \nBase.metadata.create_all(engine)\n\n","sub_path":"week03/code/create_user_table.py","file_name":"create_user_table.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"604670395","text":"from musicschool.libs.logged_view import LoggedProfView, LoggedStudentView\nfrom musicschool.groups.models import MemberGroup, Media, Article\nfrom django.shortcuts import redirect, render\nfrom django.contrib.auth.models import User\nfrom musicschool.groups.forms import ArticleForm\nfrom django.shortcuts import get_object_or_404\n\n\n# Detail \nclass ArticleDetailView(LoggedStudentView):\n template_name = \"article/home.html\"\n \n def get(self, request, article_id):\n article = get_object_or_404(Article, pk=article_id)\n if request.user.is_staff or request.user.user_information.is_prof:\n return render(\n request, \n 'article_detail.html', \n {\n 'article':article,\n }\n )\n elif request.user.is_authenticated: \n membergroup = request.user.members_group.all()[0]\n if article in membergroup.articles.all():\n return render(\n request, \n 'article_detail.html', \n {\n 'article':article,\n }\n ) \n return redirect('login')\n\n\n# List \nclass ArticleListView(LoggedProfView):\n template_name = \"prof/article/article_list.html\"\n \n def get(self, request):\n articles = Article.objects.all()\n return render(\n request, \n self.template_name, \n {\n 'articles':articles\n }\n ) \n\n\n#Edit - add\nclass ArticleManageView(LoggedProfView):\n template_name = \"prof/article/article_add_edit.html\"\n \n def get(self, request, article_id = None):\n if article_id:\n article = get_object_or_404(Article, pk=article_id)\n article_form = ArticleForm(instance=article)\n return render(\n request, \n self.template_name,\n {\n 'article_form': article_form\n }\n ) \n else:\n article_form = ArticleForm()\n return render(\n request, \n self.template_name,\n {\n 'article_form': article_form\n }\n ) \n\n def post(self, request, article_id = None):\n if article_id:\n article = get_object_or_404(Article, pk=article_id)\n article_form = ArticleForm(request.POST or None, instance=article)\n else:\n article_form = ArticleForm(request.POST)\n if article_form.is_valid():\n article_form.save()\n return redirect('article-list')\n\n#Delete\nclass ArticleDeleteView(LoggedProfView): \n def get(self, request, article_id = None):\n article = get_object_or_404(Article, pk=article_id)\n article.delete()\n return redirect('article-list')","sub_path":"etriolet/backoffice/groups/views/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"590344054","text":"def distance(dna1, dna2):\n\t\"\"\" Calculate the Hamming difference between two DNA strands. Strands should have equal lenght. Hamming difference is the number of differences is the strands. For equal or empty strands the diffrence is zero.\"\"\"\n\t\n\t# set difference to 0 \n\thamming = 0\n\t\n\t\n\tif len(dna1) != len(dna2):\n\t\traise ValueError('Strands should have same length.')\n\telse:\t\n\t\tfor i in range(0, len(dna1)):\t\n\t\t\tif dna1[i] != dna2[i]:\n\t\t\t\thamming += 1\n\t\t\t\t\t\n\treturn hamming\n","sub_path":"hamming.py","file_name":"hamming.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"412291142","text":"import asyncio\nimport os\nfrom typing import List\n\nimport asyncpg\nimport typer\nimport orjson\nfrom smart_open import open\nfrom enum import Enum\n\nfrom pypgstac import __version__ as version\n\nimport logging\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\napp = typer.Typer()\n\ndirname = os.path.dirname(__file__)\nmigrations_dir = os.path.join(dirname, \"migrations\")\n\n\ndef pglogger(conn, message):\n logging.debug(message)\n\n\nasync def con_init(conn):\n \"\"\"Use orjson for json returns.\"\"\"\n await conn.set_type_codec(\n \"json\",\n encoder=orjson.dumps,\n decoder=orjson.loads,\n schema=\"pg_catalog\",\n )\n await conn.set_type_codec(\n \"jsonb\",\n encoder=orjson.dumps,\n decoder=orjson.loads,\n schema=\"pg_catalog\",\n )\n\n\nclass DB:\n pg_connection_string = None\n connection = None\n\n def __init__(self, pg_connection_string: str = None):\n self.pg_connection_string = pg_connection_string\n\n async def create_connection(self):\n self.connection = await asyncpg.connect(\n self.pg_connection_string,\n server_settings={\n \"search_path\": \"pgstac,public\",\n \"application_name\": \"pypgstac\",\n },\n )\n await con_init(self.connection)\n return self.connection\n\n async def __aenter__(self):\n if self.connection is None:\n await self.create_connection()\n return self.connection\n\n async def __aexit__(self, exc_type, exc_val, exc_tb):\n await self.connection.close()\n\n\nasync def run_migration(dsn: str = None):\n conn = await asyncpg.connect(dsn=dsn)\n async with conn.transaction():\n try:\n oldversion = await conn.fetchval(\n \"\"\"\n SELECT version FROM pgstac.migrations\n ORDER BY datetime DESC LIMIT 1;\n \"\"\"\n )\n except asyncpg.exceptions.UndefinedTableError:\n oldversion = None\n logging.debug(\n f\"Old Version: {oldversion} New Version: {version} Migrations Dir: {migrations_dir}\"\n )\n if oldversion == version:\n logging.debug(f\"Target database already at version: {version}\")\n return version\n if oldversion is None:\n logging.debug(\n f\"No pgstac version set, installing {version} from scratch\"\n )\n migration_file = os.path.join(migrations_dir, f\"pgstac.{version}.sql\")\n else:\n logging.debug(f\"Migrating from {oldversion} to {version}.\")\n migration_file = os.path.join(\n migrations_dir, f\"pgstac.{oldversion}-{version}.sql\"\n )\n\n if not os.path.exists(migration_file):\n raise Exception(\n f\"Pypgstac does not have a migration from {oldversion} to {version} ({migration_file})\"\n )\n\n with open(migration_file) as f:\n migration_sql = f.read()\n logging.debug(migration_sql)\n async with conn.transaction():\n conn.add_log_listener(pglogger)\n await conn.execute(migration_sql)\n await conn.execute(\n \"\"\"\n INSERT INTO pgstac.migrations (version)\n VALUES ($1);\n \"\"\",\n version,\n )\n\n await conn.close()\n return version\n\n\n@app.command()\ndef migrate(dsn: str = None):\n typer.echo(asyncio.run(run_migration(dsn)))\n\n\nclass loadopt(str, Enum):\n insert = \"insert\"\n insert_ignore = \"insert_ignore\"\n upsert = \"upsert\"\n\n\nclass tables(str, Enum):\n items = \"items\"\n collections = \"collections\"\n\n\nasync def aiter(list: List):\n for i in list:\n if isinstance(i, bytes):\n i = i.decode(\"utf-8\")\n elif isinstance(i, dict):\n i = orjson.dumps(i).decode(\"utf-8\")\n if isinstance(i, str):\n line = \"\\n\".join(\n [\n i.rstrip()\n .replace(r\"\\n\", r\"\\\\n\")\n .replace(r\"\\t\", r\"\\\\t\")\n ]\n ).encode(\"utf-8\")\n yield line\n else:\n raise Exception(f\"Could not parse {i}\")\n\n\nasync def copy(iter, table: tables, conn: asyncpg.Connection):\n logger.debug(f\"copying to {table} directly\")\n logger.debug(f\"iter: {iter}\")\n iter = aiter(iter)\n async with conn.transaction():\n logger.debug(\"Copying data\")\n await conn.copy_to_table(\n table,\n source=iter,\n columns=[\"content\"],\n format=\"csv\",\n quote=chr(27),\n delimiter=chr(31),\n )\n logger.debug(\"Backfilling partitions\")\n await conn.execute(\n f\"\"\"\n SELECT backfill_partitions();\n \"\"\"\n )\n logger.debug(\"Copy complete\")\n\n\nasync def copy_ignore_duplicates(\n iter, table: tables, conn: asyncpg.Connection\n):\n logger.debug(f\"inserting to {table} ignoring duplicates\")\n iter = aiter(iter)\n async with conn.transaction():\n await conn.execute(\n \"\"\"\n CREATE TEMP TABLE pgstactemp (content jsonb)\n ON COMMIT DROP;\n \"\"\"\n )\n await conn.copy_to_table(\n \"pgstactemp\",\n source=iter,\n columns=[\"content\"],\n format=\"csv\",\n quote=chr(27),\n delimiter=chr(31),\n )\n logger.debug(\"Data Copied\")\n await conn.execute(\n \"\"\"\n SELECT make_partitions(\n min((content->>'datetime')::timestamptz),\n max((content->>'datetime')::timestamptz)\n ) FROM pgstactemp;\n \"\"\"\n )\n logger.debug(\"Made Partitions\")\n await conn.execute(\n f\"\"\"\n INSERT INTO {table} (content)\n SELECT content FROM pgstactemp\n ON CONFLICT DO NOTHING;\n \"\"\"\n )\n logger.debug(\"Data Inserted\")\n\n\nasync def copy_upsert(iter, table: tables, conn: asyncpg.Connection):\n logger.debug(f\"upserting to {table}\")\n iter = aiter(iter)\n async with conn.transaction():\n await conn.execute(\n \"\"\"\n CREATE TEMP TABLE pgstactemp (content jsonb)\n ON COMMIT DROP;\n \"\"\"\n )\n await conn.copy_to_table(\n \"pgstactemp\",\n source=iter,\n columns=[\"content\"],\n format=\"csv\",\n quote=chr(27),\n delimiter=chr(31),\n )\n logger.debug(\"Data Copied\")\n if table == \"collections\":\n await conn.execute(\n f\"\"\"\n INSERT INTO collections (content)\n SELECT content FROM pgstactemp\n ON CONFLICT (id) DO UPDATE\n SET content = EXCLUDED.content\n WHERE collections.content IS DISTINCT FROM EXCLUDED.content;\n \"\"\"\n )\n if table == \"items\":\n logger.debug(\"Upserting Data\")\n await conn.execute(\n f\"\"\"\n SELECT upsert_item(content)\n FROM pgstactemp;\n \"\"\"\n )\n\n\nasync def load_iterator(\n iter, table: tables, conn: asyncpg.Connection, method: loadopt = \"insert\"\n):\n logger.debug(f\"Load Iterator Connection: {conn}\")\n if method == \"insert\":\n await copy(iter, table, conn)\n elif method == \"insert_ignore\":\n await copy_ignore_duplicates(iter, table, conn)\n else:\n await copy_upsert(iter, table, conn)\n\n\nasync def load_ndjson(\n file: str, table: tables, method: loadopt = \"insert\", dsn: str = None\n):\n print(f\"loading {file} into {table} using {method}\")\n with open(file, \"rb\") as f:\n async with DB(dsn) as conn:\n await load_iterator(f, table, conn, method)\n\n\n@app.command()\ndef load(\n table: tables,\n file: str,\n dsn: str = None,\n method: loadopt = typer.Option(\n \"insert\", prompt=\"How to deal conflicting ids\"\n ),\n):\n typer.echo(\n asyncio.run(\n load_ndjson(file=file, table=table, dsn=dsn, method=method)\n )\n )\n\n\nif __name__ == \"__main__\":\n app()\n","sub_path":"pypgstac/pypgstac/pypgstac.py","file_name":"pypgstac.py","file_ext":"py","file_size_in_byte":8056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"534292486","text":"class Solution:\n def smallestSubsequence(self, s: str) -> str:\n # 统计每个字符出现的频率\n # 配合单调递增栈\n # 如果遇到比当前栈顶元素小的字符而且该字符的剩余出现频率大于0\n # 那么就出栈\n n = len(s)\n stack = []\n count = [0] * 26\n for i in range(n):\n count[ord(s[i]) - 97] += 1\n visited = set()\n for i in range(n):\n if s[i] in visited:\n count[ord(s[i]) - 97] -= 1\n continue\n while stack and s[stack[-1]] >= s[i]:\n if count[ord(s[stack[-1]]) - 97] > 0:\n idx = stack.pop()\n visited.remove(s[idx])\n else:\n break\n count[ord(s[i]) - 97] -= 1\n visited.add(s[i])\n stack.append(i)\n res = ''\n for idx in stack:\n res += s[idx]\n return res","sub_path":"1081_SmallestSubsequenceOfDistinctCharacters.py","file_name":"1081_SmallestSubsequenceOfDistinctCharacters.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"350295848","text":"# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# # Encoding of categorical variables\n#\n# In this notebook, we will present typical ways to deal with **categorical\n# variables**, namely **ordinal encoding** and **one-hot encoding**.\n\n# %% [markdown]\n# Let's first load the entire adult dataset containing both numerical and\n# categorical data.\n\n# %%\nimport pandas as pd\n\ndf = pd.read_csv(\"../datasets/adult-census.csv\")\n\ntarget_name = \"class\"\ntarget = df[target_name]\n\ndata = df.drop(columns=[target_name, \"fnlwgt\"])\n\n# %% [markdown]\n#\n# ## Identify categorical variables\n#\n# As we have seen in the previous section, a numerical variable is a continuous\n# quantity represented by a real or integer number. These variables can be\n# naturally handled by machine learning algorithms that are typically composed\n# of a sequence of arithmetic instructions such as additions and\n# multiplications.\n#\n# In contrast, categorical variables have discrete values, typically\n# represented by string labels taken from a finite list of possible choices.\n# For instance, the variable `native-country` in our dataset is a categorical\n# variable because it encodes the data using a finite list of possible\n# countries (along with the `?` symbol when this information is missing):\n\n# %%\ndata[\"native-country\"].value_counts().sort_index()\n\n# %% [markdown]\n# One might question how could we easily recognize categorical columns. One\n# useful tip is to look at the data type of each column.\n\n# %%\ndata.dtypes\n\n# %% [markdown]\n# If we look at the \"native-country\" column data type, we observe it is of\n# `object` data type. The reason is that categories are represented with\n# string.\n#\n# Sometimes, categorical columns could also be encoded with integers. In this\n# case, looking at the data type will not be enough. In the exploration and in\n# the previous notebook, we saw that the column `\"education-num\"` is such a\n# column.\n\n# %%\ndata[\"education-num\"].value_counts()\n\n# %% [markdown]\n# When considering categorical columns, we should include this columns.\n# However, we also saw that `\"education-num\"` and `\"education\"` columns\n# represent exactly the same information. Therefore, we can use one of the two\n# columns. So, we can make the choice to consider only `object` dtype columns.\n#\n# ## Select features based on their data type\n#\n# In the previous notebook, we manually defined the numerical columns. We could\n# to the same here. However, since that we can select columns based on a\n# specific dtypes, we can use a scikit-learn helper allowing to select the\n# column based on their data types. It is called `make_column_selector`. We\n# will illustrate how to use this helper.\n\n# %%\nfrom sklearn.compose import make_column_selector as selector\n\ncategorical_columns_selector = selector(dtype_include=object)\ncategorical_columns = categorical_columns_selector(data)\ncategorical_columns\n\n# %% [markdown]\n# We can create the selector by passing the data type to include or exclude.\n# Once the selector created, we can pass the input dataset and the name of\n# the selected columns will be returned.\n\n# %%\ndata_categorical = data[categorical_columns]\ndata_categorical.head()\n\n# %%\nprint(f\"The dataset is composed of {data_categorical.shape[1]} features\")\n\n# %% [markdown]\n# In the remainder of this section, we will present different strategies to\n# encode categorical data into numerical data which can be used by a\n# machine-learning algorithm.\n\n# %% [markdown]\n# ## Encoding ordinal categories\n#\n# The most intuitive strategy is to encode each category with a different\n# number. The `OrdinalEncoder` will transform the data in such manner.\n# We will start by encoding a single column to understand how the encoding\n# works.\n\n# %%\nfrom sklearn.preprocessing import OrdinalEncoder\n\neducation_column = data_categorical[[\"education\"]]\n\nencoder = OrdinalEncoder()\neducation_encoded = encoder.fit_transform(education_column)\n\n# %% [markdown]\n# We can visually check the encoding obtained.\n\n# %%\nimport seaborn as sns\nsns.set_context(\"talk\")\n\ndf = pd.DataFrame(\n education_encoded[:10], columns=education_column.columns)\nax = sns.heatmap(df, annot=True, cmap=\"tab20\", cbar=False)\nax.set_ylabel(\"Sample index\")\n_ = ax.set_title(\"Ordinal encoding of 'education' column\")\n\n# %% [markdown]\n# We see that each category in `\"education\"` has been replaced by a numeric\n# value. Now, we can check the encoding applied on all categorical features.\n\n# %%\ndata_encoded = encoder.fit_transform(data_categorical)\ndata_encoded[:5]\n\n# %%\nprint(\n f\"The dataset encoded contains {data_encoded.shape[1]} features\")\n\n# %% [markdown]\n# We can see that the categories have been encoded for each feature (column)\n# independently. We can also note that the number of features before and after\n# the encoding is the same.\n#\n# ```{tip}\n# This encoding was used by the persons who published the dataset to transform\n# the `\"education\"` feature into the `\"education-num\"` feature for instance.\n# ```\n#\n# However, one has to be careful when using this encoding strategy. Using this\n# integer representation can lead the downstream models to make the assumption\n# that the categories are ordered: 0 is smaller than 1 which is smaller than 2,\n# etc.\n#\n# By default, `OrdinalEncoder` uses a lexicographical strategy to map string\n# category labels to integers. This strategy is completely arbitrary and often\n# be meaningless. For instance suppose the dataset has a categorical variable\n# named \"size\" with categories such as \"S\", \"M\", \"L\", \"XL\". We would like the\n# integer representation to respect the meaning of the sizes by mapping them to\n# increasing integers such as 0, 1, 2, 3. However lexicographical strategy used\n# by default would map the labels \"S\", \"M\", \"L\", \"XL\" to 2, 1, 0, 3.\n#\n# The `OrdinalEncoder` class accepts a `categories` constructor argument to\n# pass in the correct ordering explicitly.\n#\n# If a categorical variable does not carry any meaningful order information\n# then this encoding might be misleading to downstream statistical models and\n# you might consider using one-hot encoding instead (see below).\n#\n# ```{important}\n# Note however that the impact of violating this ordering assumption is really\n# dependent on the downstream models (for instance linear models are much more\n# sensitive than models built from an ensemble of decision trees).\n# ```\n#\n# ## Encoding nominal categories (without assuming any order)\n#\n# `OneHotEncoder` is an alternative encoder that can prevent the dowstream\n# models to make a false assumption about the ordering of categories. For a\n# given feature, it will create as many new columns as there are possible\n# categories. For a given sample, the value of the column corresponding to the\n# category will be set to `1` while all the columns of the other categories\n# will be set to `0`.\n#\n# We will start by encoding a single feature (e.g. `\"education\"`) to illustrate\n# how the encoding works.\n#\n# ```{note}\n# We will pass the argument `sparse=False` to the `OneHotEncoder` which will\n# avoid obtaining a sparse matrix, which is less efficient but easier to\n# inspect results for didactic purposes.\n# ```\n\n# %%\nfrom sklearn.preprocessing import OneHotEncoder\n\nencoder = OneHotEncoder(sparse=False)\neducation_encoded = encoder.fit_transform(education_column)\n\n# %% [markdown]\n# As in the previous section, we will visually check the encoding.\n\n# %%\ndf = pd.DataFrame(\n education_encoded[:10],\n columns=encoder.get_feature_names(education_column.columns))\nax = sns.heatmap(df, annot=True, cmap=\"RdBu\", cbar=False)\nax.set_ylabel(\"Sample index\")\n_ = ax.set_title(\"Ordinal encoding of 'education' column\")\n\n# %% [markdown]\n# So we observed that each category in education becomes a column and the\n# data resulting from the encoding is indicating whether or not the sample\n# belong to this category.\n#\n# Let's apply this encoding on the full dataset.\n\n# %%\nprint(\n f\"The dataset is composed of {data_categorical.shape[1]} features\")\ndata_categorical.head()\n\n# %%\ndata_encoded = encoder.fit_transform(data_categorical)\ndata_encoded[:5]\n\n# %%\nprint(\n f\"The dataset encoded contains {data_encoded.shape[1]} features\")\n\n# %% [markdown]\n# Let's wrap this NumPy array in a dataframe with informative column names as\n# provided by the encoder object:\n\n# %%\ncolumns_encoded = encoder.get_feature_names(data_categorical.columns)\npd.DataFrame(data_encoded, columns=columns_encoded).head()\n\n# %% [markdown]\n# Look at how the \"workclass\" variable of the first 3 records has been encoded\n# and compare this to the original string representation.\n#\n# The number of features after the encoding is more than 10 times larger than\n# in the original data because some variables such as `occupation` and\n# `native-country` have many possible categories.\n#\n# ## Evaluate our predictive pipeline\n#\n# We can now integrate this encoder inside a machine learning pipeline like we\n# did with numerical data: let's train a linear classifier on the encoded data\n# and check the performance of this machine learning pipeline using\n# cross-validation.\n#\n# Before to create the pipeline, we have to linger on the `native-country`.\n# Let's recall some statistics regarding this column.\n\n# %%\ndata[\"native-country\"].value_counts()\n\n# %% [markdown]\n# We see that the `Holand-Netherlands` category is occuring rarely. This will\n# be a problem during cross-validation: if the sample is in the test set then\n# the classifier would not have seen the category during training and will not\n# be able to encode it.\n#\n# In scikit-learn, there is two solutions to bypass this issue:\n#\n# * list all the possible categories and provide it to the `categories`;\n# * set the parameter `handle_unknown=\"ignore\"`.\n#\n# Here, we will use the former strategy because we are going to use it as well\n# for the ordinal encoder later on.\n\n# %%\ncategories = [data_categorical[column].unique()\n for column in data_categorical]\n\n# %% [markdown]\n# We can now create our machine learning pipeline.\n\n# %%\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\n\nmodel = make_pipeline(\n OneHotEncoder(categories=categories, drop=\"if_binary\"),\n LogisticRegression(max_iter=500))\n\n# %% [markdown]\n# Finally, we can check the model's performance only using the categorical\n# columns.\n\n# %%\nfrom sklearn.model_selection import cross_val_score\nscores = cross_val_score(model, data_categorical, target)\nscores\n\n# %%\nprint(f\"The accuracy is: {scores.mean():.3f} +/- {scores.std():.3f}\")\n\n# %% [markdown]\n# As you can see, this representation of the categorical variables of the data\n# is slightly more predictive of the revenue than the numerical variables that\n# we used previously.\n\n# %% [markdown]\n#\n# In this notebook we have:\n# * seen two common strategies for encoding categorical features : **ordinal\n# encoding** and **one-hot encoding**;\n# * used a **pipeline** to use a **one-hot encoder** before fitting a logistic\n# regression.\n","sub_path":"python_scripts/03_categorical_pipeline.py","file_name":"03_categorical_pipeline.py","file_ext":"py","file_size_in_byte":11195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"212250742","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport logging\nimport warnings\nimport time\nimport codecs\nimport sys\nimport re\n#import jieba\nfrom gensim.models import word2vec\nfrom text_model import TextConfig\nimport loader\nimport Tools\n\nwarnings.filterwarnings(action='ignore',category=UserWarning,module='gensim')\n#将每个文本转成Sentence List列表\ndef CorpusToSentenceList(train_path):\n\ttrain, label = loader.read_myfile(train_path)\n\tsentencelist = [] #sentencelist, 每个元素是word list\n\tfor line in train:\n\t\t#line = line.decode('utf-8')\n\t\tline = line.replace('\\r\\n', '').strip()\n\t\tline = line.split(',')\n\t\tsentencelist.append(line)\n\treturn sentencelist\n\nre_han= re.compile(u\"([\\u4E00-\\u9FD5a-zA-Z0-9+#&\\._%]+)\") # the method of cutting text by punctuation\n\nclass Get_Sentences(object):\n\t'''\n\tArgs:\n\t\tfilenames: a list of train_filename,test_filename,val_filename\n\tYield:\n\t\tword:a list of word cut by jieba\n\t'''\n\n\tdef __init__(self,filenames):\n\t\tself.filenames= filenames\n\n\tdef __iter__(self):\n\t\tfor filename in self.filenames:\n\t\t\twith codecs.open(filename, 'r', encoding='utf-8') as f:\n\t\t\t\tfor _,line in enumerate(f):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tline=line.strip()\n\t\t\t\t\t\tline=line.split('\\t')\n\t\t\t\t\t\tassert len(line)==2\n\t\t\t\t\t\tblocks=re_han.split(line[1])\n\t\t\t\t\t\tword=[]\n\t\t\t\t\t\tfor blk in blocks:\n\t\t\t\t\t\t\tif re_han.match(blk):\n\t\t\t\t\t\t\t\tword.extend(jieba.lcut(blk))\n\t\t\t\t\t\tyield word\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpass\n\ndef train_word2vec(filenames):\n\t'''\n\tuse word2vec train word vector\n\targv:\n\t\tfilenames: a list of train_filename,test_filename,val_filename\n\treturn: \n\t\tsave word vector to config.vector_word_filename\n\t'''\n\tt1 = time.time()\n\tsentences = Get_Sentences(filenames)\n\tlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\tmodel = word2vec.Word2Vec(sentences, size=100, window=5, min_count=2, workers=4)\n\tmodel.wv.save_word2vec_format(config.vector_word_filename, binary=False)\n\tprint('-------------------------------------------')\n\tprint(\"Training word2vec model cost %.3f seconds...\\n\" % (time.time() - t1))\n\ndef train_myword2vec(file_path):\n\t'''\n\tuse word2vec train word vector\n\targv:\n\t\tfilenames: a list of train_filename,test_filename,val_filename\n\treturn: \n\t\tsave word vector to config.vector_word_filename\n\t'''\n\tt1 = time.time()\n\t#sentences = Get_Sentences(filenames)\n\tsentences = CorpusToSentenceList(file_path) #list\n\tlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\tmodel = word2vec.Word2Vec(sentences, sg=1,hs=1,size=200, window=1, min_count=5, sample=0.001, negative=5, workers=4)\n\t#model.wv.save_word2vec_format(config.vector_word_filename, binary=False)\n\tmodel.save_word2vec_format(config.vector_word_filename, binary=False)\n\tprint('------------------------------------')\n\tprint(\"Training word2vec model cost %.3f seconds...\\n\" % (time.time() - t1))\n\ndef train_model(filepath, modelpath):\n\tfpath = filepath\n\tmpath = modelpath\n\tsentences = CorpusToWordList(fpath) #list\n\tmodel = word2vec.Word2Vec(sentences, sg=1,hs=1,min_count=5,window=3,size=200, negative=3, sample=0.001,workers=4)\n\tmodel.save_word2vec_format(mpath,binary=True)\n\ndef get_model(modelpath):\n\tmpath = modelpath\n\tmodel= word2vec.Word2Vec.load_word2vec_format(mpath, binary=True)\n\treturn model\n\t\nif __name__ == '__main__':\n\t \n\t#logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\t\n\tconfig=TextConfig()\n\t'''\n\tfilenames=[config.train_filename,config.test_filename,config.val_filename]\n\ttrain_word2vec(filenames)\n\t'''\n\tfilepath1 = \"/usr/jyf/chinanews/total_seg/total_seg.txt\"\n\t\n\t#train and save model\n\ttrain_myword2vec(filepath1)\n\t\n\t#load model\n\t#model = get_model(modelpath1)\n\t","sub_path":"tc_all/old20190213/train_word2vec.py","file_name":"train_word2vec.py","file_ext":"py","file_size_in_byte":3673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"467049600","text":"\r\ndata = open(\"D-large.in\").read().split()\r\ndata = map(int, data)\r\nn = data[0]\r\ndata = zip(data[1::3], data[2::3], data[3::3])\r\nansw = []\r\n\r\nfor k,c,s in data:\r\n ca = []\r\n found = False\r\n j = 0\r\n for i in xrange(s):\r\n pos = 0\r\n for x in xrange(c):\r\n pos = pos*k + j\r\n if j < k - 1:\r\n j += 1\r\n else:\r\n found = True\r\n ca.append(str(pos+1))\r\n if found:\r\n break\r\n\r\n if found:\r\n answ.append(\" \".join(ca))\r\n else:\r\n answ.append(\"IMPOSSIBLE\")\r\n\r\nwith open(\"D-large.out\",'w') as f:\r\n for i,o in enumerate(answ):\r\n f.write(\"Case #{}: {}\\n\".format(i+1, o))\r\n","sub_path":"codes/CodeJamCrawler/16_0_4/Metaray21/problem-d.py","file_name":"problem-d.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"203993724","text":"# 사이킷런 데이터셋\n# LSTM모델링\n# Dense와 성능비교\n# 회귀모델\n\n# 실습 19_1번,2,3,4,5,6 earlystopping까지 총 6개 파일을 환성하시오\n\nimport numpy as np\nfrom sklearn.datasets import load_diabetes\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense,LSTM\nfrom sklearn.metrics import r2_score,mean_squared_error\nfrom sklearn.preprocessing import MinMaxScaler,StandardScaler\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport tensorflow as tf\nnp.random.seed(0)\n#tf.set_random_seed(0)\n\ndatasets = load_diabetes()\nx=datasets.data\ny=datasets.target\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2)\nx_train,x_val,y_train,y_val = train_test_split(x_train,y_train,test_size=0.2)\n\nx_scaler = MinMaxScaler()\nx_scaler.fit(x_train)\nx_train = x_scaler.transform(x_train)\nx_test = x_scaler.transform(x_test)\nx_val = x_scaler.transform(x_val)\n\nx_train = x_train.reshape(x_train.shape[0],x_train.shape[1],1)\nx_test = x_test.reshape(x_test.shape[0],x_test.shape[1],1)\nx_val = x_val.reshape(x_val.shape[0],x_val.shape[1],1)\n\nearly_stopping =EarlyStopping(monitor='loss',patience=70)\n\nmodel=Sequential()\nmodel.add(LSTM(128,input_shape = (x_train.shape[1],x_train.shape[2]),activation='relu'))\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dense(64,activation='relu'))\nmodel.add(Dense(32,activation='relu'))\nmodel.add(Dense(16,activation='relu'))\nmodel.add(Dense(8,activation='relu'))\nmodel.add(Dense(1))\nmodel.compile(loss='mse',optimizer='adam',metrics=['mae'])\nmodel.fit(x_train,y_train,epochs=20000,batch_size=4,verbose=1,validation_data=(x_val,y_val),callbacks=[early_stopping])\n\nloss = model.evaluate(x_test,y_test,batch_size=4)\ny_predict = model.predict(x_test)\nrmse = mean_squared_error(y_predict,y_test)**0.5\nr2 = r2_score(y_predict,y_test)\nprint('loss : ',loss)\nprint('rmse : ',rmse)\nprint('R2 : ',r2)\n\n'''\nloss : 17834.29296875\nrmse : 17834.295936238046\nR2 : -1225563484693248.8\n\nrmse : 4319.449432814543\nR2 : 0.2393480819718682\n'''\n\n\n\n\n","sub_path":"keras/keras33_LSTM2_diabetes.py","file_name":"keras33_LSTM2_diabetes.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"615993885","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/5/6 17:56\n# @Author : cui\n# @File : zuoye1.py\nimport http.client\nimport unittest\nimport HTMLTestRunner\nimport string\nclass Woniu(unittest.TestCase):\n @classmethod\n def setUpClass(cls):\n print('***************开始测试*********************')\n\n def test2(self):\n #查询接口\n parameters = 'barcode=11111111'\n head = {'Content-Type': 'application/x-www-form-urlencoded'}\n connect = http.client.HTTPConnection(host='cuishao', port=8080)\n connect.request('POST', 'http://cuishao:8080/WoniuSales1.4/sell/barcode ', parameters, head)\n response=connect.getresponse()\n #断言\n result = response.read().decode('utf8')\n serial=result.split(',')[7].split(\":\")[1]\n self.assertIn(serial,result,'垃圾')\n\n\n def test3(self):\n parameters = 'barcode='\n head = {'Content-Type': 'application/x-www-form-urlencoded'}\n connect = http.client.HTTPConnection(host='cuishao', port=8080)\n connect.request('POST', ' http://cuishao:8080/WoniuSales1.4/sell/barcode ', parameters, head)\n response = connect.getresponse()\n result = response.read().decode('utf8')\n self.assertNotEqual(result,\"[]\",\"error\")\n\n @classmethod\n def tearDownClass(cls):\n print('***************测试结束*********************')\n\n\n","sub_path":"jiaoben/xingneng/zuoye2/zuoye1.py","file_name":"zuoye1.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"304112378","text":"from pn532 import PN532\nfrom machine import Pin\nfrom neopixel import NeoPixel\nfrom utime import sleep_ms,ticks_ms,ticks_add,ticks_diff\n\nnp = NeoPixel(Pin(2),24)\nnp.write()\npn = PN532()\ncardid = None\ncolors = [(20,0,0),(15,15,0),(0,20,0),(0,15,15),(0,0,20),(15,0,15)]\nfor r in range(6000):\n ct = ticks_add(ticks_ms(),10)\n try:\n pn.mainloop()\n except:\n sleep_ms(100)\n continue\n if pn.cardid != cardid:\n cardid = pn.cardid\n if cardid:\n print(\"Card: %08x\" % cardid)\n for i in range(24):\n np[i] = colors[i%6]\n if (r%2)==0:\n for i in range(24):\n np[i] = (max(0,np[i][0]-1),max(0,np[i][1]-1),max(0,np[i][2]-1))\n np.write()\n et = ticks_diff(ct,ticks_ms())\n if et > 0:\n sleep_ms(et)\n","sub_path":"rfidreader/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"179524444","text":"import sys, os\nimport glob\nimport subprocess\nfrom timeout import timeout\n\nfile_list = glob.glob('..' + os.path.sep + '..' + os.path.sep + 'source' +\n os.path.sep + '*' + os.path.sep + '*' + sys.argv[1] + os.path.sep + 'run1.xml')\n\nwith open(\"runs\" + os.path.sep + \"run1POST_\" + sys.argv[1] + \".log\", 'w+') as log:\n for index, item in enumerate(file_list):\n log.write(str(index) + \":\" + item + \"\\n\")\n\nerr_list = []\nto_do = file_list[int(sys.argv[2]):]\nfor index, mainfile in enumerate(to_do):\n with open(mainfile[:-8] + \"run1TEIcmml.log\", 'w+') as log:\n print(str(index + int(sys.argv[2])) + \":\" + mainfile)\n try:\n subprocess.call([\"perl\", \"latexmlpost\",\n \"--destination=\" + mainfile[:-8] + \"run1cmml.tei\", \"-format=tei\",\n \"-cmml\", mainfile], stdout=log, stderr=subprocess.STDOUT, timeout=120)\n except Exception as err:\n print(\"error with\" + mainfile + \": \")\n print(err)\n err_list.append(mainfile)\n\nif err_list:\n with open(\"runs\" + os.path.sep + \"errrun1POST_\" + sys.argv[1] + \".log\", 'w+') as log:\n for index, item in enumerate(err_list):\n log.write(str(index + int(sys.argv[2])) + \":\" + item + \"\\n\")\n","sub_path":"run_tei.py","file_name":"run_tei.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"440836084","text":"import pandas as pd\nimport numpy as np\nimport csv\n\nimport collections\ndataset = pd.read_csv('level1sam.csv')\nftCol = dataset.iloc[:, 0].values\n\n\nvar = len(ftCol)\n\ndef syllable_count(word):\n word = word.lower()\n count = 0\n vowels = \"aeiouy\"\n if word[0] in vowels:\n count += 1\n for index in range(1, len(word)):\n if word[index] in vowels and word[index - 1] not in vowels:\n count += 1\n if word.endswith(\"e\"):\n count -= 1\n if count == 0:\n count += 1\n return count\nprint(ftCol)\narray = []\n\nfor j in range(var):\n array.append([syllable_count(i) for i in ftCol])\n#print(array)\n\nlist1 = {'Names':array}\n#print(list1)\ndf = pd.DataFrame(list1)\ndf_csv = pd.read_csv('level1 + syllable + word filter.csv')\n#df_csv['syllable'] = df.Names # changed here\n#df_csv.to_csv('withsyllable.csv', index=False, mode= 'w')\ndf_csv = pd.DataFrame(columns=['Syllabel'])\nfor i in range(var):\n df_csv.loc[i] = [array[i][i]]\ndf_csv.to_csv('syllablemlll,ll,l.csv', index=False, mode= 'w')\n","sub_path":"Test2/Syllable.py","file_name":"Syllable.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"634309954","text":"#!/usr/bin/env python\n\nimport pymongo\nfrom pymongo import MongoClient\n\nconn = MongoClient('localhost', 27017)\nbase = conn.school\ncoll = base.students\n\ntry:\n cursor = coll.find({}, {'scores' : 1})\n for entry in cursor:\n student_id = entry['_id']\n scores = entry['scores']\n\n my_list = []\n\n for score in scores:\n if score['type'] == 'homework':\n my_list.append(score['score'])\n my_list.sort()\n scores.remove({'type' : 'homework', 'score' : my_list[0]})\n coll.update({ '_id' : student_id }, { '$set' : { 'scores' : scores} })\nexcept Exception as e:\n print(\"Произошла ошибка: \", type(e), e)\n raise\n","sub_path":"homework31.py","file_name":"homework31.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"202064887","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nfrom echomesh.base import Config\nfrom echomesh.base import Platform\nfrom echomesh.util import Log\nfrom echomesh.util import Subprocess\n\nLOGGER = Log.logger(__name__)\n\nOUTPUT_COMMAND = 'sudo', 'amixer', 'cset', 'numid=3'\nCOMMANDS = dict(default='0', audio='1', hdmi='2')\nOUTPUT_SET = False\n\ndef set_output(output=None):\n output = output or Config.get('audio', 'output', 'route')\n if Platform.IS_LINUX:\n command = COMMANDS.get(output)\n if not command:\n LOGGER.error(\"Didn't understand output '%s'\", output)\n return\n\n result, returncode = Subprocess.run(OUTPUT_COMMAND + (command, ))\n if returncode:\n LOGGER.error(\"Couldn't open output %s\\n%s\", output, result)\n else:\n LOGGER.vdebug('Set audio output to %s', output)\n global OUTPUT_SET\n OUTPUT_SET = True\n","sub_path":"code/python/echomesh/sound/SetOutput.py","file_name":"SetOutput.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"562596683","text":"# Copyright (c) 2017 Cisco and/or its affiliates.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at:\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Test variables for Policer test suite.\"\"\"\n\n\ndef get_variables():\n \"\"\"Create and return a dictionary of test variables for the specified\n test case.\n\n :returns: Dictionary of test variables - settings for Honeycomb's Policer.\n :rtype: dict\n \"\"\"\n policer_data = {\n \"policer_data\": {\n \"name\": \"policy1\",\n \"cir\": 450,\n \"cb\": 50000,\n \"rate-type\": \"kbps\",\n \"round-type\": \"closest\",\n \"type\": \"1r2c\",\n \"conform-action\": {\n \"meter-action-type\": \"meter-action-transmit\"\n },\n \"exceed-action\": {\n \"meter-action-type\": \"meter-action-drop\"\n }\n },\n \"policer_data_oper\": {\n \"name\": \"policy1\",\n \"cir\": 450,\n \"cb\": 50000,\n \"rate-type\": \"kbps\",\n \"round-type\": \"closest\",\n \"type\": \"1r2c\",\n \"conform-action\": {\n \"meter-action-type\": \"policer:meter-action-transmit\"\n },\n \"exceed-action\": {\n \"meter-action-type\": \"policer:meter-action-drop\"\n }\n },\n \"policer_data_2\": {\n \"name\": \"policy1\",\n \"cir\": 900,\n \"cb\": 50000,\n \"rate-type\": \"kbps\",\n \"round-type\": \"closest\",\n \"type\": \"1r2c\",\n \"conform-action\": {\n \"meter-action-type\": \"meter-action-transmit\"\n },\n \"exceed-action\": {\n \"meter-action-type\": \"meter-action-drop\"\n }\n },\n \"policer_data_oper_2\": {\n \"name\": \"policy1\",\n \"cir\": 900,\n \"cb\": 50000,\n \"rate-type\": \"kbps\",\n \"round-type\": \"closest\",\n \"type\": \"1r2c\",\n \"conform-action\": {\n \"meter-action-type\": \"policer:meter-action-transmit\"\n },\n \"exceed-action\": {\n \"meter-action-type\": \"policer:meter-action-drop\"\n }\n },\n \"policer_data_3\": {\n \"name\": \"policy1\",\n \"cir\": 100,\n \"eir\": 150,\n \"cb\": 200,\n \"eb\": 300,\n \"rate-type\": \"pps\",\n \"round-type\": \"closest\",\n \"type\": \"2r3c-2698\",\n \"conform-action\": {\n \"meter-action-type\": \"meter-action-transmit\"\n },\n \"exceed-action\": {\n \"meter-action-type\": \"meter-action-mark-dscp\",\n \"dscp\": \"AF22\"\n },\n \"violate-action\": {\n \"meter-action-type\": \"meter-action-drop\"\n },\n \"color-aware\": True\n },\n \"policer_data_oper_3\": {\n \"name\": \"policy1\",\n \"cir\": 100,\n \"eir\": 150,\n \"cb\": 200,\n \"eb\": 300,\n \"rate-type\": \"pps\",\n \"round-type\": \"closest\",\n \"type\": \"2r3c-2698\",\n \"conform-action\": {\n \"meter-action-type\": \"policer:meter-action-transmit\"\n },\n \"exceed-action\": {\n \"meter-action-type\": \"policer:meter-action-mark-dscp\",\n },\n \"violate-action\": {\n \"meter-action-type\": \"policer:meter-action-drop\"\n },\n \"color-aware\": True\n },\n\n \"acl_tables\": {\n # settings for policer tables\n \"hc_acl_table\": {\n \"name\": \"table0\",\n \"nbuckets\": 2,\n \"memory_size\": 1048576,\n \"skip_n_vectors\": 12,\n \"miss_next\": \"permit\",\n \"mask\": \"00:00:00:00:00:00:00:00:00:00:00:00:ff:ff:ff:ff\"\n },\n # setting for acl sessions\n \"hc_acl_session\": {\n \"match\": \"00:00:00:00:00:00:00:00:00:00:00:00:C0:A8:7A:01\",\n \"policer_hit_next\": \"policy1\",\n \"color_classfier\": \"exceed-color\",\n },\n \"hc_acl_session2\": {\n \"match\": \"00:00:00:00:00:00:00:00:00:00:00:00:C0:A8:7A:02\",\n \"policer_hit_next\": \"policy1\",\n \"color_classfier\": \"exceed-color\",\n },\n },\n }\n return policer_data\n","sub_path":"resources/test_data/honeycomb/policer_variables.py","file_name":"policer_variables.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"56298244","text":"# Write a program that outputs the string representation of numbers from 1 to n.\n#\n# But for multiples of three it should output “Fizz” instead of the number\n# And for the multiples of five output “Buzz”.\n# For numbers which are multiples of both three and five output “FizzBuzz”.\n#\n# Example:\n#\n# n = 15,\n#\n# Return:\n# [\n# \"1\",\n# \"2\",\n# \"Fizz\",\n# \"4\",\n# \"Buzz\",\n# \"Fizz\",\n# \"7\",\n# \"8\",\n# \"Fizz\",\n# \"Buzz\",\n# \"11\",\n# \"Fizz\",\n# \"13\",\n# \"14\",\n# \"FizzBuzz\"\n# ]\n\nfrom random import *\n\nn = randint(1, 50)\nprint(f\"n is: {n}\")\n\nif n is 1:\n print([str(1)])\nelse:\n my_list = []\n for number in range(1, n + 1):\n # If divisible by both 3 and 5, append FizzBuzz\n if number % 3 is 0 and number % 5 is 0:\n my_list.append(\"FizzBuzz\")\n # Else, if divisible by 3, append Fizz\n elif number % 3 is 0:\n my_list.append(\"Fizz\")\n # Else, if divisible by 5, append Buzz\n elif number % 5 is 0:\n my_list.append(\"Buzz\")\n # Else, append the number itself\n else:\n my_list.append(str(number))\n print(f\"String representation for '{n}' is: {my_list}\")","sub_path":"LeCoSolutions/4_FizzBuzz.py","file_name":"4_FizzBuzz.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"329863084","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.7-x86_64/egg/wptherml/numlib/numlib.py\n# Compiled at: 2019-07-23 16:27:58\n# Size of source mod 2**32: 853 bytes\n\n\ndef Integrate(y, x, a, b):\n som = 0.0\n keep = 1\n idx = 0\n if x[(len(x) - 1)] - x[0] < 0:\n xnew = x[::-1]\n x = xnew\n ynew = y[::-1]\n y = ynew\n for i in range(0, len(x)):\n if x[i] > b:\n break\n\n return som","sub_path":"pycfiles/wptherml-1.0.0-py3.7/numlib.cpython-37.py","file_name":"numlib.cpython-37.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"173338941","text":"import point\r\nimport obser\r\n\r\n\r\nCELL_EMPTY = 0\r\nCELL_FOOD = 2\r\n\r\nclass Area(obser.Observable):\r\n\t\"\"\"docstring for Area\"\"\"\r\n\tdef __init__(self, width, height):\r\n\t\tsuper(Area, self).__init__()\r\n\t\tself.width, self.height = width, height\r\n\t\tself.m = [[CELL_EMPTY for c in range(width)] for r in range(height)]\r\n\r\n\tdef rawStr(self):\r\n\t\t'\\n'.join([''.join(c) for c in self.m])\r\n","sub_path":"src/python/area.py","file_name":"area.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"503984770","text":"def main():\n ' main entry point for module execution\\n '\n argument_spec = dict(src=dict(type='path'), replace_src=dict(), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', 'none']), replace=dict(default='line', choices=['line', 'block', 'config']), running_config=dict(aliases=['config']), intended_config=dict(), defaults=dict(type='bool', default=False), backup=dict(type='bool', default=False), save_when=dict(choices=['always', 'never', 'modified'], default='never'), diff_against=dict(choices=['running', 'startup', 'intended']), diff_ignore_lines=dict(type='list'), save=dict(default=False, type='bool', removed_in_version='2.4'), force=dict(default=False, type='bool', removed_in_version='2.2'))\n argument_spec.update(nxos_argument_spec)\n mutually_exclusive = [('lines', 'src', 'replace_src'), ('parents', 'src'), ('save', 'save_when')]\n required_if = [('match', 'strict', ['lines']), ('match', 'exact', ['lines']), ('replace', 'block', ['lines']), ('replace', 'config', ['replace_src']), ('diff_against', 'intended', ['intended_config'])]\n module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, required_if=required_if, supports_check_mode=True)\n warnings = list()\n nxos_check_args(module, warnings)\n result = {\n 'changed': False,\n 'warnings': warnings,\n }\n config = None\n info = get_capabilities(module).get('device_info', {\n \n })\n os_platform = info.get('network_os_platform', '')\n if (module.params['replace'] == 'config'):\n if ('9K' not in os_platform):\n module.fail_json(msg='replace: config is supported only for Nexus 9K series switches')\n if module.params['replace_src']:\n if (module.params['replace'] != 'config'):\n module.fail_json(msg='replace: config is required with replace_src')\n if (module.params['backup'] or (module._diff and (module.params['diff_against'] == 'running'))):\n contents = get_config(module)\n config = NetworkConfig(indent=2, contents=contents)\n if module.params['backup']:\n result['__backup__'] = contents\n if any((module.params['src'], module.params['lines'], module.params['replace_src'])):\n match = module.params['match']\n replace = module.params['replace']\n candidate = get_candidate(module)\n if ((match != 'none') and (replace != 'config')):\n config = get_running_config(module, config)\n path = module.params['parents']\n configobjs = candidate.difference(config, match=match, replace=replace, path=path)\n else:\n configobjs = candidate.items\n if configobjs:\n commands = dumps(configobjs, 'commands').split('\\n')\n if module.params['before']:\n commands[:0] = module.params['before']\n if module.params['after']:\n commands.extend(module.params['after'])\n result['commands'] = commands\n result['updates'] = commands\n if (not module.check_mode):\n load_config(module, commands)\n result['changed'] = True\n running_config = None\n startup_config = None\n diff_ignore_lines = module.params['diff_ignore_lines']\n if module.params['save']:\n module.params['save_when'] = 'always'\n if (module.params['save_when'] != 'never'):\n output = execute_show_commands(module, ['show running-config', 'show startup-config'])\n running_config = NetworkConfig(indent=1, contents=output[0], ignore_lines=diff_ignore_lines)\n startup_config = NetworkConfig(indent=1, contents=output[1], ignore_lines=diff_ignore_lines)\n if ((running_config.sha1 != startup_config.sha1) or (module.params['save_when'] == 'always')):\n result['changed'] = True\n if (not module.check_mode):\n cmd = {\n 'command': 'copy running-config startup-config',\n 'output': 'text',\n }\n run_commands(module, [cmd])\n else:\n module.warn('Skipping command `copy running-config startup-config` due to check_mode. Configuration not copied to non-volatile storage')\n if module._diff:\n if (not running_config):\n output = execute_show_commands(module, 'show running-config')\n contents = output[0]\n else:\n contents = running_config.config_text\n running_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines)\n if (module.params['diff_against'] == 'running'):\n if module.check_mode:\n module.warn('unable to perform diff against running-config due to check mode')\n contents = None\n else:\n contents = config.config_text\n elif (module.params['diff_against'] == 'startup'):\n if (not startup_config):\n output = execute_show_commands(module, 'show startup-config')\n contents = output[0]\n else:\n contents = output[0]\n contents = startup_config.config_text\n elif (module.params['diff_against'] == 'intended'):\n contents = module.params['intended_config']\n if (contents is not None):\n base_config = NetworkConfig(indent=1, contents=contents, ignore_lines=diff_ignore_lines)\n if (running_config.sha1 != base_config.sha1):\n if (module.params['diff_against'] == 'intended'):\n before = running_config\n after = base_config\n elif (module.params['diff_against'] in ('startup', 'running')):\n before = base_config\n after = running_config\n result.update({\n 'changed': True,\n 'diff': {\n 'before': str(before),\n 'after': str(after),\n },\n })\n module.exit_json(**result)","sub_path":"Data Set/bug-fixing-5/736d6406c049851d9490a3d60d1da049629f3ceb-
-bug.py","file_name":"736d6406c049851d9490a3d60d1da049629f3ceb-
-bug.py","file_ext":"py","file_size_in_byte":6160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"482576371","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport sys\nsys.path.append(\"models/\")\nfrom mlp_cadae import MLP\nfrom innerproductdecoder import InnerProductDecoder\n\n\nclass Base_CADAE(nn.Module):\n def __init__(self, num_layers, dec_num_layers, num_mlp_layers, input_dim, hidden_dim, embedd_dim, str_recon_dim, learn_eps, neighbor_pooling_type, dropout, device):\n '''\n num_layers: number of layers in the neural networks (INCLUDING the input layer)\n dec_num_layers: umber of layers in the decoder (INCLUDING the input layer)\n num_mlp_layers: number of layers in mlps (EXCLUDING the input layer)\n input_dim: dimensionality of input features\n hidden_dim: dimensionality of hidden units at ALL layers\n embedd_dim: dimensionality of output embeedings from encoder\n final_dropout: dropout ratio on the final linear layer\n learn_eps: If True, learn epsilon to distinguish center nodes from neighboring nodes. If False, aggregate neighbors and center nodes altogether. \n neighbor_pooling_type: how to aggregate neighbors\n '''\n\n super(Base_CADAE, self).__init__()\n\n self.device = device\n self.num_layers = num_layers\n self.dec_num_layers = dec_num_layers\n\n self.neighbor_pooling_type = neighbor_pooling_type\n self.learn_eps = learn_eps\n self.eps = nn.Parameter(torch.zeros(self.num_layers-1))\n self.dropout = dropout\n \n ###encoder\n ###List of MLPs\n self.mlps = torch.nn.ModuleList()\n\n ###List of batchnorms applied to the output of MLP (input of the final prediction linear layer)\n self.batch_norms = torch.nn.ModuleList()\n\n for layer in range(self.num_layers-1):\n if layer == 0:\n self.mlps.append(MLP(num_mlp_layers, input_dim, hidden_dim, hidden_dim))\n self.batch_norms.append(nn.BatchNorm1d(hidden_dim))\n else:\n self.mlps.append(MLP(num_mlp_layers, hidden_dim, embedd_dim, embedd_dim))\n self.batch_norms.append(nn.BatchNorm1d(embedd_dim))\n\n \n ###attribute decoder \n self.dec_mlps = torch.nn.ModuleList()\n self.dec_batch_norms = torch.nn.ModuleList()\n for layer in range(self.dec_num_layers-1):\n if layer == 0:\n self.dec_mlps.append(MLP(num_mlp_layers, embedd_dim, embedd_dim, hidden_dim))\n self.dec_batch_norms.append(nn.BatchNorm1d(hidden_dim))\n else:\n self.dec_mlps.append(MLP(num_mlp_layers, hidden_dim, hidden_dim, input_dim))\n \n \n ###structure decoder\n self.dec_str_mlp = MLP(num_mlp_layers, embedd_dim, hidden_dim, str_recon_dim)\n ## innerproduct for reconstructing adjacent matrix\n self.innerproduct = InnerProductDecoder(self.dropout)\n\n\n def neighbors_sumavepool(self, adj_ori):\n \n if self.learn_eps == True:\n return adj_ori\n #Add self-loops in the adjacency matrix if learn_eps is False, i.e., aggregate center nodes and neighbor nodes altogether.\n elif not self.learn_eps:\n if self.training:\n adj_selfloop = torch.cuda.FloatTensor(adj_ori+torch.eye(adj_ori.shape[0]).cuda())\n else:\n adj_selfloop = torch.FloatTensor(adj_ori+torch.eye(adj_ori.shape[0]))\n return adj_selfloop\n###encoder next layers\n\n def next_layer_eps(self, h, layer, Adj_block = None):\n ###if eps=True, pooling neighboring nodes and center nodes separately by eps reweighting. \n\n pooled = torch.mm(Adj_block, h)\n\n ### aggregate representations of node and its neighbors by the parameter and sum aggregation\n pooled = pooled + (1 + self.eps[layer])*h\n pooled_rep = self.mlps[layer](pooled)\n h = self.batch_norms[layer](pooled_rep)\n\n #non-linearity\n h = F.relu(h)\n return h\n\n\n def next_layer(self, h, layer, padded_neighbor_list = None, Adj_block = None):\n ###if eps = False, pooling neighboring nodes and center nodes altogether \n \n pooled = torch.mm(Adj_block, h)\n \n #representation of neighboring and center nodes \n pooled_rep = self.mlps[layer](pooled)\n\n h = self.batch_norms[layer](pooled_rep)\n\n #non-linearity, last layer without batchnorm and relu\n h = F.relu(h)\n return h\n \n###decoder next layers\n def dec_next_layer_eps(self, h, layer, Adj_block = None, last = False):\n ###same with encoder layers\n\n pooled = torch.mm(Adj_block, h)\n\n pooled = pooled + (1 + self.eps[layer])*h \n pooled_rep = self.dec_mlps[layer](pooled)\n\n #non-linearity\n if last == False:\n h = self.batch_norms[layer](pooled_rep)\n h = F.relu(h)\n else:\n h = pooled_rep\n return h\n\n def dec_next_layer(self, h, layer, padded_neighbor_list = None, Adj_block = None, last = False):\n ###same with encoder layers\n \n pooled = torch.mm(Adj_block, h)\n\n #representation of neighboring and center nodes \n pooled_rep = self.dec_mlps[layer](pooled)\n #non-linearity, last layer without batchnorm and relu\n if last == False:\n h = self.batch_norms[layer](pooled_rep)\n h = F.leaky_relu(h)\n else:\n h = pooled_rep\n return h\n \n def forward(self, batch_graph, adj_ori):\n\n Adj_block = self.neighbors_sumavepool(adj_ori)\n\n #matrix of hidden representation at each layer (including input)\n \n h = batch_graph\n\n for layer in range(self.num_layers-1):\n if self.learn_eps ==True:\n h = self.next_layer_eps(h, layer, Adj_block = Adj_block)\n elif not self.learn_eps:\n h = self.next_layer(h, layer, Adj_block = Adj_block)\n \n #hidden embeddings\n hidden_embs = h\n \n for layer in range(self.dec_num_layers-1):\n if layer != self.dec_num_layers - 2:\n if self.learn_eps ==True:\n h_1 = self.dec_next_layer_eps(hidden_embs, layer, Adj_block = Adj_block, last=False)\n elif not self.learn_eps:\n h_1 = self.dec_next_layer(hidden_embs, layer, Adj_block = Adj_block, last=False)\n elif layer == self.dec_num_layers - 2:\n if self.learn_eps ==True:\n h = self.dec_next_layer_eps(h_1, layer, Adj_block = Adj_block, last=True)\n elif not self.learn_eps:\n h = self.dec_next_layer(h_1, layer, Adj_block = Adj_block, last=True)\n else:\n raise ValueError('not valid layer number!')\n \n att_recons = h\n #reconstruct adjacent matrix (structure)\n str_embs = self.dec_str_mlp(hidden_embs)\n str_recons = self.innerproduct(str_embs)\n\n return att_recons, str_recons, hidden_embs\n \n","sub_path":"method/cadae_model.py","file_name":"cadae_model.py","file_ext":"py","file_size_in_byte":7040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"539313769","text":"# -*- coding: utf-8 -*-\nimport os\nimport json\nfrom flask import render_template\nfrom flask import request\nfrom flask_login import login_required\nfrom docker import Client\n\nfrom app import app\nfrom app import db\nfrom app import socketio\nfrom app.models import ProjectModel\nfrom app.models import ServerModel\nfrom app.models import AppModel\n\nREGISTRY_IP = app.config['REGISTRY']\nAPPS = None\nAPP_NAME = None\nHOST = None\nIMAGE = None\nPORT = None\n\n\n@app.route('/apps')\n@login_required\ndef apps():\n page = request.args.get('page', 1, type=int)\n pagination = AppModel.query.order_by(\n AppModel.create_on.desc()).paginate(\n page, app.config['FLASKY_POSTS_PER_PAGE'], error_out=False)\n apps = pagination.items\n return render_template('container.html', apps=apps, pagination=pagination)\n\n\n@app.route('/apps/create/')\n@login_required\ndef create_app(verify):\n project = ProjectModel.query.filter_by(verify=verify).first()\n servers = ServerModel.query.order_by(ServerModel.create_on.desc())\n app_verify = ''.join(map(lambda xx: (hex(ord(xx))[2:]), os.urandom(16)))\n return render_template(\n 'create-app.html',\n project=project,\n servers=servers,\n app_verify=app_verify\n )\n\n\n@app.route('/apps/per/', methods=['GET', 'POST'])\ndef per_app(verify):\n apps = AppModel.query.filter_by(verify=verify).first()\n global APPS\n global APP_NAME\n global HOST\n global IMAGE\n global PORT\n if request.method == 'POST' and apps is None:\n APP_NAME = appname = request.form['appname']\n HOST = ip = request.form['server']\n PORT = port = request.form['port']\n IMAGE = image = REGISTRY_IP + request.form['image']\n APPS = apps = AppModel(\n appname=appname,\n port=port,\n host=ip,\n image=image,\n verify=verify,\n )\n db.session.add(apps)\n db.session.commit()\n return render_template('app.html', apps=apps)\n elif apps is not None:\n APPS = apps\n APP_NAME = apps.appname\n HOST = apps.host\n IMAGE = apps.image\n PORT = apps.port\n elif apps is None:\n apps = APPS\n return render_template('app.html', apps=apps)\n\n\n@app.route('/apps/create', methods=['POST'])\ndef create_app_socket():\n logs = []\n status = json.loads(container_status())['status']\n # 如果容器还没有,就开始创建\n if status == 'pending':\n cli = Client(base_url=HOST+':5678')\n for line in cli.pull(IMAGE, stream=True):\n socketio.emit('response', json.dumps({'resp': line}))\n logs.append(line)\n container = cli.create_container(\n image=IMAGE, ports=[PORT], name=APP_NAME,\n host_config=cli.create_host_config(port_bindings={\n 3000: (HOST, PORT)\n })\n )\n APPS.containerId = container.get('Id')\n db.session.add(APPS)\n db.session.commit()\n response = cli.start(container=container.get('Id'))\n if response is not None:\n return json.dumps({'msg': 'false'})\n return json.dumps({'msg': 'ok'})\n\n\n@app.route('/apps/per/status', methods=['POST'])\ndef container_status():\n status = find_container(APP_NAME, HOST)\n return json.dumps({'status': status})\n\n\n@app.route('/apps/all/status', methods=['POST'])\ndef all_container_status():\n resp = {}\n data = json.loads(request.get_data())\n for i in range(len(data['data'])):\n apps = AppModel.query.filter_by(appname=data['data'][str(i)]).first()\n resp[str(i)] = find_container(apps.appname, apps.host)\n return json.dumps(resp)\n\n\ndef find_container(appName, host):\n run_names = []\n all_names = []\n cli = Client(base_url=str(host)+':5678')\n run_containers = cli.containers()\n all_containers = cli.containers(all=True)\n for container in run_containers:\n run_names.append(container['Names'][0].split('/')[1])\n for container in all_containers:\n all_names.append(container['Names'][0].split('/')[1])\n if appName in run_names:\n status = 'up'\n return status\n else:\n if appName in all_names:\n status = 'down'\n return status\n else:\n status = 'pending'\n return status\n\n\n@app.route('/apps/check/appname', methods=['POST'])\ndef check_appname():\n data = json.loads(request.get_data())\n app = AppModel.query.filter_by(appname=data['data']).first()\n if app is None:\n return json.dumps({'resp': 'ok'})\n else:\n return json.dumps({'resp': 'no'})\n\n\n@app.route('/apps/delete', methods=['POST'])\ndef delete_app():\n data = json.loads(request.get_data())\n apps = AppModel.query.filter_by(appname=data['data']).first()\n cli = Client(base_url=apps.host+':5678')\n response = cli.remove_container(container=apps.containerId, force=True)\n if response is None:\n try:\n db.session.delete(apps)\n except:\n db.session.roolback()\n return json.dumps({'resp': 'no'})\n db.session.commit()\n return json.dumps({'resp': 'ok'})\n else:\n return json.dumps({'resp': 'no'})\n\n\n@socketio.on('start app')\ndef start_app(message):\n appName = message['appName']\n apps = AppModel.query.filter_by(appname=appName).first()\n cli = Client(base_url=apps.host+':5678')\n response = cli.start(container=apps.containerId)\n socketio.emit('status response', {'data': response, 'info': '运行中', 'color': '#169f2d'})\n\n\n@socketio.on('stop app')\ndef stop_app(message):\n appName = message['appName']\n apps = AppModel.query.filter_by(appname=appName).first()\n cli = Client(base_url=apps.host+':5678')\n response = cli.stop(container=apps.containerId)\n socketio.emit('status response', {'data': response, 'info': '待机', 'color': 'red'})\n\n\n# 获取应用的运行日志\n@app.route('/apps/logs', methods=['POST'])\n@login_required\ndef get_app_logs():\n data = json.loads(request.get_data())\n cli = Client(base_url=str(data['host'])+':5678')\n for log in cli.logs(container=data['appName'], stream=True):\n socketio.emit('logs response', {'data': log})\n","sub_path":"app/views/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":6172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"80513647","text":"import pytest\n\nfrom blockserver.backend.transfer import StorageObject\n\nwith_etag = StorageObject('foo', 'bar', 'etag', size=10)\nwithout_etag = with_etag._replace(etag=None, size=None) # type: StorageObject\n\n\ndef test_storage_cache_basics(cache):\n with pytest.raises(KeyError):\n cache.get_storage(without_etag)\n with pytest.raises(ValueError):\n cache.set_storage(without_etag)\n cache.set_storage(with_etag)\n assert cache.get_storage(without_etag) == with_etag\n\n\ntoken_and_prefix_get = 'MAGICFAIRYTALE', 'EXAMPLEPREFIX', 'get'\ntoken_and_prefix_post = 'MAGICFAIRYTALE', 'EXAMPLEPREFIX', 'post'\ntoken_and_prefix_delete = 'MAGICFAIRYTALE', 'EXAMPLEPREFIX', 'delete'\n\n\ndef test_auth_cache_basics(cache):\n with pytest.raises(KeyError):\n cache.get_auth(*token_and_prefix_get)\n with pytest.raises(ValueError):\n cache.set_auth(*token_and_prefix_get, None)\n cache.set_auth(*token_and_prefix_get, True)\n assert cache.get_auth(*token_and_prefix_get) == True\n cache.set_auth(*token_and_prefix_get, False)\n assert cache.get_auth(*token_and_prefix_get) == False\n\n","sub_path":"src/blockserver/tests/test_cache.py","file_name":"test_cache.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"440790323","text":"from math import *\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef moment_of_inertia(l , m , theta_z, w):\n theta_z = radians(theta_z)\n const = m * l**2 / 2\n I11 = const * cos(theta_z)**2\n I12 = 0\n I13 = - const * cos(theta_z)*sin(theta_z)\n I22 = const\n I32 = 0\n I33 = const * sin(theta_z)**2\n\n I = np.array ([[I11, I12, I13],\n [I12, I22, I32],\n [I13, I32, I33]])\n\n w1 = w[2] * sin(theta_z) + w[0]\n w2 = w[2] * sin(theta_z) - w[0]\n w3 = w[2] * cos(theta_z) + w[1]\n w = [w1, w2, w3]\n return I, w\n\ndef rubbuh(w, I, part2=0):\n print('moment of inertia %s' % I)\n principal = np.linalg.eig(I)\n I1 = principal[0][0]\n I2 = principal[0][1]\n I3 = principal[0][2]\n\n if part2:\n I1 = 5\n I2 = 3\n I3 = 1\n print('rotation in body frame : %s' % w)\n print('eigenvalues %s %s %s' % (I1, I2, I3))\n \n t = 20\n dt = 1\n Nt = int(t / dt)\n\n w1 = [w[0]]\n w2 = [w[1]]\n w3 = [w[2]]\n for i in range(Nt):\n w1dot = (I2 - I3) * w2[i] * w3[i] / I1\n w2dot = (I3 - I1) * w3[i] * w1[i] / I2\n w3dot = (I1 - I2) * w1[i] * w2[i] / I3\n w1.append(w1dot * dt)\n w2.append(w2dot * dt)\n w3.append(w3dot * dt)\n\n t_arr = np.linspace(0, t, Nt+1)\n\n fig ,axs = plt.subplots(1 , 3)\n\n axs[0].scatter(t_arr, w1)\n axs[0].set_title('w1 vs t')\n axs[0].set_xlabel('time (s)')\n axs[0].set_ylabel('w (1/s)')\n \n axs[1].scatter(t_arr, w2)\n axs[1].set_title('w2 vs t')\n axs[1].set_xlabel('time (s)')\n axs[1].set_ylabel('w (1/s)')\n\n axs[2].scatter(t_arr, w3)\n axs[2].set_title('w3 vs t')\n axs[2].set_xlabel('time (s)')\n axs[2].set_ylabel('w (1/s)')\n\n plt.show()\n\n w = [ sqrt( w1[i]**2 + w2[i]**2 + w3[i]**2) for i in range(len(w1))]\n\n plt.scatter(t_arr, w)\n plt.title('magnitude of w vs t')\n plt.xlabel('time (s)')\n plt.ylabel('w (1/s)')\n\n plt.show()\n\n\nif __name__ == '__main__':\n w = [0, 0, 1]\n I, w = moment_of_inertia(10, 5, 15, w)\n rubbuh(w, I)\n\n\n #part 2\n w = [1.1, 0, 0]\n I, w = moment_of_inertia(10, 5, 15, w)\n rubbuh(w, I, part2=1)\n\n \n w = [0, 1.1, 0]\n I, w = moment_of_inertia(10, 5, 15, w)\n rubbuh(w, I, part2=1)\n\n \n w = [0, 0, 1.1]\n I, w = moment_of_inertia(10, 5, 15, w)\n rubbuh(w, I, part2=1)\n \n \n","sub_path":"Computational_HW/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"87966207","text":"import os\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom keras.callbacks import TensorBoard, EarlyStopping\r\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, \\\r\n BatchNormalization, Concatenate, MaxPool2D, GlobalAveragePooling2D\r\nfrom keras.layers.core import Activation, regularizers\r\nfrom keras.models import Sequential, Input, Model\r\nfrom keras.optimizers import Adam\r\n\r\nfrom readImg import readimg\r\n\r\nimgsize = 128\r\nFlag = True\r\n\r\n\r\ndef model_set(in_data):\r\n # モデルの定義\r\n model_rec = Sequential()\r\n\r\n model_rec.add(Conv2D(32, 16, input_shape=in_data.shape))\r\n model_rec.add(Activation('relu'))\r\n model_rec.add(MaxPool2D(pool_size=(2, 2)))\r\n # model_rec.add(Dropout(0.25))\r\n\r\n model_rec.add(Conv2D(32, 10))\r\n # model_rec.add(BatchNormalization())\r\n model_rec.add(Activation('relu'))\r\n model_rec.add(MaxPool2D(pool_size=(2, 2)))\r\n # model_rec.add(Dropout(0.25))\r\n\r\n # model_rec.add(Conv2D(32, 5))\r\n # model_rec.add(Activation(\"relu\"))\r\n # model_rec.add(Dropout(0.25))\r\n # model_rec.add(Conv2D(16, 3))\r\n # model_rec.add(BatchNormalization())\r\n # model_rec.add(Activation(\"relu\"))\r\n\r\n model_rec.add(Flatten())\r\n # model_rec.add(Dense(128))\r\n # model_rec.add(Activation('relu'))\r\n # model_rec.add(Dropout(0.4))\r\n model_rec.add(Dense(1, activation='sigmoid'))\r\n\r\n optimizer = Adam(lr=0.00005)\r\n model_rec.compile(loss='mse',\r\n optimizer=optimizer,\r\n metrics=['mae'])\r\n return model_rec\r\n\r\n\r\n# loss\r\ndef plot_history_loss(fit):\r\n # Plot the loss in the history\r\n axL.plot(fit.history['loss'], label=\"loss for training\")\r\n axL.plot(fit.history['val_loss'], label=\"loss for validation\")\r\n axL.set_title('model loss(MSE)')\r\n axL.set_xlabel('epoch')\r\n axL.set_ylabel('loss')\r\n axL.set_ylim(0, 3e-04)\r\n axL.legend(loc='upper right')\r\n\r\n\r\n# acc\r\ndef plot_history_acc(fit):\r\n # Plot the loss in the history\r\n axR.plot(fit.history['mae'], label=\"MAE for training\")\r\n axR.plot(fit.history['val_mae'], label=\"MAE for validation\")\r\n axR.set_title('model Mean absolute error')\r\n axR.set_xlabel('epoch')\r\n axR.set_ylabel('Mean absolute error')\r\n axR.set_ylim(0, 0.02)\r\n axR.legend(loc='upper right')\r\n\r\n\r\n# データセット読み込み\r\n(x_train, y_train), (x_test, y_test), y_origin = readimg(\"./ImageData/\", imgsize, \"/F4/\", Flag)\r\n\r\n# 正規化\r\nx_train, x_test = x_train / 255.0, x_test / 255.0\r\n\r\n# tb_cb = TensorBoard(log_dir=\"tflog\", histogram_freq=1)\r\ntb_cb = TensorBoard(log_dir=\"tflog\", histogram_freq=1)\r\nes_cb = EarlyStopping(patience=10, verbose=1, monitor=\"val_mae\", mode=\"min\",\r\n min_delta=0.0001)\r\n# モデル\r\nmodel = model_set(x_train[0])\r\n\r\n# 学習\r\nmodel.summary()\r\nresult = model.fit(x_train, y_train, epochs=100, batch_size=32,\r\n verbose=2, callbacks=[], validation_split=0.2)\r\n\r\n# テストスコア\r\nscore = model.evaluate(x_test, y_test, batch_size=32, verbose=0)\r\nprint('Test loss:', score[0])\r\nprint('Test MAE:', score[1])\r\n\r\n\r\n# モデルの保存\r\nif not os.path.exists(\"models/\" + str(imgsize)):\r\n os.mkdir(\"models/\" + str(imgsize))\r\njson_string = model.to_json()\r\nif Flag:\r\n open(os.path.join('./models/' + str(imgsize), str(imgsize) + 'F_model.json'), 'w').write(json_string)\r\n model.save_weights(os.path.join('./models/' + str(imgsize), str(imgsize) + 'F_weight.hdf5'))\r\n model.save(\"./models/\" + str(imgsize) + \"/\" + str(imgsize) + \"F_model.h5\")\r\nelse:\r\n open(os.path.join('./models/' + str(imgsize), str(imgsize) + '_model.json'), 'w').write(json_string)\r\n model.save_weights(os.path.join('./models/' + str(imgsize), str(imgsize) + '_weight.hdf5'))\r\n model.save(\"./models/\" + str(imgsize) + \"/\" + str(imgsize) + \"_model.h5\")\r\n\r\n\r\n# 実際の流量の予測\r\nexpect = model.predict(x_test, batch_size=32)\r\nif Flag:\r\n test = len(y_test)\r\n ex = np.zeros(test)\r\n yy = np.zeros(test)\r\n for i in range(0, test):\r\n ex[i] = expect[i, 0] * 0.09 + 0.52\r\n yy[i] = y_test[i] * 0.09 + 0.52\r\n # print(y_origin[i], yy[i], ex[i], ex[i] - y_origin[i])\r\n print(np.mean(abs(ex - yy)), np.mean(abs(ex - y_origin)))\r\n\r\nelse:\r\n print(np.mean(abs(expect - y_test)))\r\n\r\n# lossと平均誤差の表示\r\nfig, (axL, axR) = plt.subplots(ncols=2, figsize=(10, 4))\r\nplot_history_loss(result)\r\nplot_history_acc(result)\r\nif Flag:\r\n fig.savefig(\"./result/\" + str(imgsize) + \"F.png\")\r\nelse:\r\n fig.savefig(\"./result/\" + str(imgsize) + \".png\")\r\nplt.close()\r\n","sub_path":"NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"347433633","text":"import simpleaudio as sa\nimport numpy as np\nfrom morse import morse_text_processing\nimport wave, struct\n\ntime_unit = 0.1\ntime_dot = time_unit\ntime_dash = 3 * time_unit\ntime_element_gap = time_unit\ntime_letter_gap = 3 * time_unit\ntime_word_gap = 7 * time_unit\n\nmorse_frequency = 700\nsample_rate = 44100\n\n\ndef tone_audio_buffer(frequency, duration, volume=0.9):\n t = np.linspace(0, duration, int(duration * sample_rate), False)\n buffer = np.sin(frequency * t * 2 * np.pi)\n audio = buffer * (volume / np.max(np.abs(buffer))) * (2 ** 15 - 1)\n return audio.astype(np.int16)\n\n\ndef gap_audio_buffer(duration):\n return np.zeros(int(duration * sample_rate), dtype=np.int16)\n\n\ndef morse_element_to_audio_buffer(morse_element):\n if morse_element == \".\":\n return tone_audio_buffer(morse_frequency, time_dot)\n elif morse_element == \"-\":\n return tone_audio_buffer(morse_frequency, time_dash)\n elif morse_element == \"e\":\n return gap_audio_buffer(time_element_gap)\n elif morse_element == \"l\":\n return gap_audio_buffer(time_letter_gap)\n elif morse_element == \"w\":\n return gap_audio_buffer(time_word_gap)\n\n\ndef morse_text_to_audio_buffer(morse_text):\n words = morse_text.split(\" \")\n words = [word.strip().split(\" \") for word in words if len(word.strip()) > 0]\n elements = \"w\".join(\"l\".join(\"e\".join(letter) for letter in word) for word in words)\n return np.concatenate([morse_element_to_audio_buffer(el) for el in elements])\n\n\ndef text_to_audio_buffer(text):\n morse_text = morse_text_processing.encode(text)\n return morse_text_to_audio_buffer(morse_text)\n\n\ndef save_audio_buffer(audio_buffer, filename):\n wav_writer = wave.open(filename, \"wb\")\n wav_writer.setnchannels(1)\n wav_writer.setsampwidth(2)\n wav_writer.setframerate(sample_rate)\n wav_writer.writeframesraw(b\"\".join(audio_buffer))\n\n\ndef play_audio_buffer(audio_buffer):\n play = sa.play_buffer(audio_buffer, 1, 2, sample_rate)\n play.wait_done()","sub_path":"morse/morse_audio_encode.py","file_name":"morse_audio_encode.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"61126135","text":"from searchdir.node import *\nfrom searchdir.util import *\n\n## This method must implement Breadth-first search (BFS)\n## It must return the solution node and the number of visited nodes\ndef breadthfirst_search(initialState):\n print('BFS------------------------------')\n first = Node(initialState)\n visited = set() # a Set data structure was used for optimized speed\n q = Queue()\n q.enqueue(first) # enqueue the first item\n\n while not q.isEmpty():\n v = q.dequeue()\n visited.add(v.state) # add the visited vertex to the set\n if not v.state.isGoal():\n for newV in v.expand(): # for each new vertice in the list of possible targets.\n if newV.state not in visited : # if new vertex has not been explored\n q.enqueue(newV) # enqueue the new vertice\n visited.add(newV.state) # This is not needed, however is does optimize the speed\n\n else:\n \treturn v, len(visited) #returns the last vertex (solution) and the length of vertex traversed\n\n\n\n","sub_path":"assignments/assignment 1/searchdir/blindSearch/breadthfirst_search.py","file_name":"breadthfirst_search.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"613980492","text":"\"\"\"\nread_instance_BH-cyclic.py\n\"\"\"\n\n'''\n[seed graph]\n V_C : \"V_C\"\n E_C : \"E_C\"\n\n[core specification]\n ell_LB : \"\\ell_{\\rm LB}\"\n ell_UB : \"\\ell_{\\rm UB}\"\n cs_LB : \"\\textsc{cs}_{\\rm LB}\"\n cs_UB : \"\\textsc{cs}_{\\rm UB}\"\n'''\n\nimport sys\n\ndef read_seed_graph(filename):\n with open(filename,'r') as f:\n F = [line.rstrip('\\n') for line in f if line[0]!='#']\n\n ### read V_C ###\n num_V_C = int(F.pop(0))\n V_C = tuple(range(1,num_V_C+1))\n \n ### read E_C ###\n num_E_C = int(F.pop(0))\n E_C = {}\n for e in range(num_E_C):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n E_C[arr[0]] = (arr[0], arr[1], arr[2]) # Add arr[0] to distinguish two edges with same starting and ending vertices, by Zhu\n \n ### read ell_LB and ell_UB ###\n ell_LB = {}\n ell_UB = {}\n for e in range(num_E_C):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n ell_LB[arr[0]] = arr[1]\n ell_UB[arr[0]] = arr[2]\n\n ### compute E_ge_two, E_ge_one, E_zero_one, E_equal_one ###\n E_ge_two = []\n E_ge_one = []\n E_zero_one = []\n E_equal_one = []\n I_ge_two = []\n I_ge_one = []\n I_zero_one = []\n I_equal_one = []\n for e in E_C:\n if ell_LB[e] >= 2:\n E_ge_two.append(E_C[e])\n I_ge_two.append(e)\n elif ell_LB[e] == 1 and ell_UB[e] >= 2:\n E_ge_one.append(E_C[e])\n I_ge_one.append(e)\n elif ell_LB[e] == 0 and ell_UB[e] == 1:\n E_zero_one.append(E_C[e])\n I_zero_one.append(e)\n elif ell_LB[e] == 1 and ell_UB[e] == 1:\n E_equal_one.append(E_C[e])\n I_equal_one.append(e)\n else:\n sys.stderr.write('error: a strange edge is found.\\n')\n sys.exit(1)\n \n ### read n_LB_int and n_UB_int ###\n n_LB_int = int(F.pop(0))\n n_UB_int = int(F.pop(0))\n\n # read n_LB and n_star\n n_LB = int(F.pop(0))\n n_star = int(F.pop(0))\n\n # read rho\n rho = int(F.pop(0))\n\n ### read ch_LB and ch_UB ###\n ch_LB = {}\n ch_UB = {}\n for v in range(num_V_C):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n ch_LB[arr[0]] = arr[1]\n ch_UB[arr[0]] = arr[2]\n for e in range(len(E_ge_two + E_ge_one)):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n ch_LB[E_C[arr[0]]] = arr[1]\n ch_UB[E_C[arr[0]]] = arr[2]\n\n ### read bl_LB and bl_UB ###\n bl_LB = {}\n bl_UB = {}\n for v in range(num_V_C):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n bl_LB[arr[0]] = arr[1]\n bl_UB[arr[0]] = arr[2]\n for e in range(len(E_ge_two + E_ge_one)):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n bl_LB[E_C[arr[0]]] = arr[1]\n bl_UB[E_C[arr[0]]] = arr[2]\n\n # read Lambda\n s = F.pop(0)\n Lambda = list(s.split(' '))\n\n # read Lambda_dg_int\n s = F.pop(0)\n num = int(s)\n Lambda_dg_int = list()\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n Lambda_dg_int.append((arr[0], int(arr[1])))\n\n # read Gamma_int_ac\n s = F.pop(0)\n num = int(s)\n Gamma_int_ac = list()\n nu_int = list()\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n tmp_1 = (arr[0], arr[1], int(arr[2]))\n tmp_2 = (arr[1], arr[0], int(arr[2]))\n nu_int.append(tmp_1)\n if tmp_1 not in Gamma_int_ac:\n Gamma_int_ac.append(tmp_1)\n if tmp_2 not in Gamma_int_ac:\n Gamma_int_ac.append(tmp_2)\n\n # read Gamma_int\n s = F.pop(0)\n num = int(s)\n Gamma_int = list()\n gam_int = list()\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n tmp_1 = ((arr[0], int(arr[1])), (arr[2], int(arr[3])), int(arr[4]))\n tmp_2 = ((arr[2], int(arr[3])), (arr[0], int(arr[1])), int(arr[4]))\n gam_int.append(tmp_1)\n if tmp_1 not in Gamma_int:\n Gamma_int.append(tmp_1)\n if tmp_2 not in Gamma_int:\n Gamma_int.append(tmp_2)\n\n # read Lambda_star\n Lambda_star = {i: set() for i in range(1, num_V_C + 1)}\n for i in range(1, num_V_C + 1):\n s = F.pop(0)\n arr = list(s.split(' '))\n ind = int(arr[0])\n arr.pop(0)\n for a in arr:\n Lambda_star[ind].add(a)\n\n Lambda_int = list()\n # read na_LB and na_UB\n s = F.pop(0)\n num = int(s)\n na_LB = {}\n na_UB = {}\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n na_LB[arr[0]] = int(arr[1])\n na_UB[arr[0]] = int(arr[2])\n\n # read na_LB_int and na_UB_int\n s = F.pop(0)\n num = int(s)\n na_LB_int = {}\n na_UB_int = {}\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n na_LB_int[arr[0]] = int(arr[1])\n na_UB_int[arr[0]] = int(arr[2])\n Lambda_int.append(arr[0])\n\n # read ns_LB_int and ns_UB_int\n s = F.pop(0)\n num = int(s)\n ns_LB_int = {}\n ns_UB_int = {}\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n ns_LB_int[(arr[0], int(arr[1]))] = int(arr[2])\n ns_UB_int[(arr[0], int(arr[1]))] = int(arr[3])\n\n # read ac_LB_int and ac_UB_int\n s = F.pop(0)\n num = int(s)\n ac_LB_int = {}\n ac_UB_int = {}\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n a1, a2, m = nu_int[int(arr[0]) - 1]\n ac_LB_int[(a1, a2, m)] = int(arr[1])\n ac_LB_int[(a2, a1, m)] = int(arr[1])\n ac_UB_int[(a1, a2, m)] = int(arr[2])\n ac_UB_int[(a2, a1, m)] = int(arr[2])\n\n # read ec_LB_int and ec_UB_int\n s = F.pop(0)\n num = int(s)\n ec_LB_int = {}\n ec_UB_int = {}\n for i in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n a1, a2, m = gam_int[int(arr[0]) - 1]\n ec_LB_int[(a1, a2, m)] = int(arr[1])\n ec_LB_int[(a2, a1, m)] = int(arr[1])\n ec_UB_int[(a1, a2, m)] = int(arr[2])\n ec_UB_int[(a2, a1, m)] = int(arr[2])\n\n # read bd2_LB and bd2_UB\n bd2_LB = {}\n bd2_UB = {}\n for e in range(len(E_C)):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n bd2_LB[E_C[arr[0]]] = arr[1]\n bd2_UB[E_C[arr[0]]] = arr[2]\n\n # read bd3_LB and bd3_UB\n bd3_LB = {}\n bd3_UB = {}\n for e in range(len(E_C)):\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n bd3_LB[E_C[arr[0]]] = arr[1]\n bd3_UB[E_C[arr[0]]] = arr[2]\n\n # read ac_LB_lf and ac_UB_lf\n s = F.pop(0)\n num = int(s)\n ac_LB_lf = dict()\n ac_UB_lf = dict()\n for e in range(num):\n s = F.pop(0)\n arr = list(s.split(' '))\n ac_LB_lf[(arr[0], arr[1], int(arr[2]))] = int(arr[3])\n ac_UB_lf[(arr[0], arr[1], int(arr[2]))] = int(arr[4])\n s = F.pop(0)\n arr = list(map(int, s.split(' ')))\n ac_LB_lf_common = arr[0]\n ac_UB_lf_common = arr[1] \n \n ####################################\n # # Undefined constants for instances but used in MILP\n r_GC = num_E_C - (num_V_C - 1)\n dg_LB = [0,0,0,0,0]\n dg_UB = [n_star,n_star,n_star,n_star,n_star]\n \n return V_C, E_C, \\\n E_ge_two, E_ge_one, E_zero_one, E_equal_one, \\\n I_ge_two, I_ge_one, I_zero_one, I_equal_one, \\\n ell_LB, ell_UB, n_LB_int, n_UB_int, \\\n n_LB, n_star, rho, \\\n ch_LB, ch_UB, bl_LB, bl_UB, \\\n Lambda, Lambda_dg_int, Gamma_int_ac, Gamma_int, \\\n Lambda_star, na_LB, na_UB, Lambda_int, \\\n na_LB_int, na_UB_int, ns_LB_int, ns_UB_int, \\\n ac_LB_int, ac_UB_int, ec_LB_int, ec_UB_int, \\\n bd2_LB, bd2_UB, bd3_LB, bd3_UB, \\\n dg_LB, dg_UB, ac_LB_lf, ac_UB_lf, ac_LB_lf_common, ac_UB_lf_common, r_GC\n\ndef get_value(filename):\n \n y_min = 0\n y_max = 0\n\n ind = 0\n\n with open(filename, 'r') as f:\n lines = f.readlines()\n for line in lines:\n if len(line.split(\",\")) < 2:\n continue\n if line.split(\",\")[0] == \"CID\":\n continue\n if ind == 0:\n y_min = float(line.split(\",\")[1])\n y_max = float(line.split(\",\")[1])\n ind = 1\n else:\n y_tmp = float(line.split(\",\")[1])\n if y_tmp > y_max:\n y_max = y_tmp\n if y_tmp < y_min:\n y_min = y_tmp\n\n return y_min, y_max \n\n\n# prepare a set of chemical rooted tree\nclass chemicalRootedTree():\n def __init__(self):\n self.root = (\"e\", 0)\n self.index = 0\n self.vertex = []\n self.adj = []\n self.alpha = []\n self.beta = []\n self.height = 0\n self.chg = []\n\ndef prepare_fringe_trees(fringe_filename, Lambda):\n\n# modified for 2LMM, 0527\n set_F = list()\n strF = dict()\n\n fc_LB = dict()\n fc_UB = dict()\n \n with open(fringe_filename,'r') as f:\n lines = f.readlines()\n for line in lines:\n if len(line.split(\",\")) < 4:\n continue\n ind = int(line.split(\",\")[0])\n str1 = line.split(\",\")[1]\n str2 = line.split(\",\")[2]\n str3 = line.split(\",\")[3].replace('\\n', '')\n if len(line.split(\",\")) > 4:\n LB_tmp = line.split(\",\")[4].replace('\\n', '')\n LB_tmp = LB_tmp.replace(' ', '')\n fc_LB[ind] = int(LB_tmp)\n UB_tmp = line.split(\",\")[5].replace('\\n', '')\n UB_tmp = UB_tmp.replace(' ', '')\n fc_UB[ind] = int(UB_tmp)\n else:\n fc_LB[ind] = 0\n fc_UB[ind] = 10\n \n psi = chemicalRootedTree()\n seq1 = str1.split()\n seq2 = [int(mul) for mul in line.split(\",\")[2].split()]\n seq3 = [int(chg) for chg in line.split(\",\")[3].split()]\n psi.index = ind\n psi.vertex = [(seq1[j], int(seq1[j + 1])) for j in range(0, len(seq1), 2)]\n psi.root = psi.vertex[0]\n psi.height = max(psi.vertex[v][1] for v in range(len(psi.vertex)) if psi.vertex[v][0] != \"H1\")\n psi.adj = [set() for _ in range(len(psi.vertex))]\n psi.beta = [[0 for _ in range(len(psi.vertex))] for _ in range(len(psi.vertex))]\n psi.chg = [chg for chg in seq3]\n for j in range(len(seq2)):\n cld = j + 1\n prt = max(v for v in range(j + 1) if psi.vertex[v][1] == psi.vertex[cld][1] - 1) \n psi.adj[prt].add(cld)\n psi.adj[cld].add(prt)\n psi.beta[prt][cld] = seq2[j]\n psi.beta[cld][prt] = seq2[j]\n # print(str(prt) + \" \" + str(cld) + \" \" + str(j) + \" \" + str(seq2[j]))\n flag = True\n for (a, d) in psi.vertex:\n if a not in Lambda:\n flag = False\n break\n if flag:\n strF[ind] = (str1, str2, str3)\n set_F.append(psi)\n\n Lambda_ex = list()\n for psi in set_F:\n for (a, d) in psi.vertex[1:]:\n if a not in Lambda_ex and a in Lambda:\n Lambda_ex.append(a)\n\n return set_F, Lambda_ex, strF, fc_LB, fc_UB\n \nif __name__==\"__main__\":\n \n V_C, E_C, \\\n E_ge_two, E_ge_one, E_zero_one, E_equal_one, \\\n I_ge_two, I_ge_one, I_zero_one, I_equal_one, \\\n ell_LB, ell_UB, n_LB_int, n_UB_int, \\\n n_LB, n_star, rho, \\\n ch_LB, ch_UB, bl_LB, bl_UB, \\\n Lambda, Lambda_dg_int, Gamma_int_ac, Gamma_int, \\\n Lambda_star, na_LB, na_UB, Lambda_int, \\\n na_LB_int, na_UB_int, ns_LB_int, ns_UB_int, \\\n ac_LB_int, ac_UB_int, ec_LB_int, ec_UB_int, \\\n bd2_LB, bd2_UB, bd3_LB, bd3_UB, dg_LB, dg_UB = read_seed_graph(sys.argv[1])\n\n set_F, psi_epsilon, Code_F, n_psi, deg_r, \\\n beta_r, atom_r, ht, Lambda_ex = prepare_fringe_trees(sys.argv[2])\n \n # print(V_C)\n # print(E_C)\n # print(E_ge_two)\n # print(E_ge_one)\n # print(E_zero_one)\n # print(E_equal_one)\n # print(ell_LB)\n # print(ell_UB)\n # print(bl_UB)\n\n for psi in (set_F + [psi_epsilon]):\n print(str(Code_F[psi]) + \" \" + str(n_psi[Code_F[psi]]) + \" \" + \\\n str(ht[Code_F[psi]]) + \" \" + str(atom_r[Code_F[psi]]) + \" \" + \\\n str(deg_r[Code_F[psi]]) + \" \" + str(beta_r[Code_F[psi]]))\n\n # print(Lambda_ex)\n\n # set_F_v = {v : set_F for v in V_C}\n # set_F_E = set_F\n # n_C = max(psi.numVertex - 1 for v in V_C for psi in set_F_v[v])\n # n_T = max(psi.numVertex - 1 for psi in set_F_E)\n # n_F = max(psi.numVertex - 1 for psi in set_F_E)\n # print(str(n_C) + \" \" + str(n_T) + \" \" + str(n_F))\n\n MAX_VAL = 4\n val = {\"C\": 4, \"O\": 2, \"N\": 3}\n\n n_H = dict()\n na_alpha_ex = {ele : {i + 1 : 0} for i in range(len(set_F)) for ele in Lambda_ex}\n for i, psi in enumerate(set_F):\n n_H_tmp = {d : 0 for d in range(MAX_VAL)}\n na_ex_tmp = {ele : 0 for ele in Lambda_ex}\n for u, (ele, dep) in enumerate(psi.vertex[1:]):\n beta_tmp = 0\n na_ex_tmp[ele] += 1\n for v in psi.adj[u + 1]:\n beta_tmp += psi.beta[u + 1][v]\n d_tmp = val[ele] - beta_tmp\n n_H_tmp[d_tmp] += 1\n\n for ele, d in na_alpha_ex.items():\n d[i + 1] = na_ex_tmp[ele]\n\n n_H[i + 1] = n_H_tmp\n\n print(n_H)\n print(na_alpha_ex)\n\n\n","sub_path":"2LMM-LLR/bin/read_instance_2layer_2LMM_L.py","file_name":"read_instance_2layer_2LMM_L.py","file_ext":"py","file_size_in_byte":13366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"461651320","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions\nimport unittest\n\nclass ExplictWaitTest(unittest.TestCase):\n def setUp(self):\n self.driver = webdriver.Chrome()\n self.driver.maximize_window()\n self.driver.get(\"http://demo-store.seleniumacademy.com\")\n\n def test_create_new_customer(self):\n self.driver.find_element_by_link_text(\"ACCOUNT\").click()\n my_account = WebDriverWait(self.driver, 10).until(expected_conditions.visibility_of_element_located((By.LINK_TEXT,\"My Account\")))\n my_account.click()\n create_account_button = WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable((By.LINK_TEXT,\"CREATE AN ACCOUNT\")))\n create_account_button.click()\n WebDriverWait(self.driver, 10).until(expected_conditions.title_contains((\"Create New Customer Account\")))\n\n def tearDown(self):\n self.driver.quit()\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n \n \n \n","sub_path":"selenium1/visibilitycondition.py","file_name":"visibilitycondition.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"573885575","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom six.moves import xrange\nimport tensorflow as tf\n\n_BATCH_NORM_DECAY = 0.9 #0.997\n_BATCH_NORM_EPSILON = 1e-5\n_USE_BIAS = False\n_KERNEL_INITIALIZER=tf.variance_scaling_initializer(mode='fan_out')\nrelu = tf.nn.relu\n\ndef get_channel_dim(x, data_format='INVALID'):\n assert data_format != 'INVALID'\n assert x.shape.ndims == 4\n if data_format == 'channels_first':\n return x.shape[1].value\n else:\n return x.shape[3].value\n\n\ndef get_channel_index(data_format='INVALID'):\n assert data_format != 'INVALID'\n axis = 1 if data_format == 'channels_first' else 3\n return axis\n\n\ndef batch_normalization(inputs, data_format, is_training):\n inputs = tf.layers.batch_normalization(\n inputs=inputs, axis=get_channel_index(data_format),\n momentum=_BATCH_NORM_DECAY, epsilon=_BATCH_NORM_EPSILON, center=True,\n scale=True, training=is_training, fused=True)\n return inputs\n\n\ndef _pooling(operation, inputs, strides, data_format):\n pooling_type, pooling_size = _operation_to_pooling_info(operation)\n if pooling_type == 'avg_pool':\n inputs = tf.layers.average_pooling2d(\n inputs=inputs, pool_size=pooling_size, strides=strides,\n padding='SAME', data_format=data_format)\n elif pooling_type == 'max_pool':\n inputs = tf.layers.max_pooling2d(\n inputs=inputs, pool_size=pooling_size, strides=strides,\n padding='SAME', data_format=data_format)\n elif pooling_type == 'min_pool':\n inputs = -tf.layers.max_pooling2d(\n inputs=-inputs, pool_size=pooling_size, strides=strides,\n padding='SAME', data_format=data_format)\n else:\n raise NotImplementedError('Unimplemented pooling type: ', pooling_type)\n return inputs\n\n\ndef _separable_conv2d(operation, inputs, filters, strides, data_format, is_training):\n kernel_size, _ = _operation_to_info(operation)\n\n inputs = relu(inputs)\n with tf.variable_scope('separable_conv_{0}x{0}_{1}'.format(kernel_size, 1)):\n inputs = tf.layers.separable_conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, \n strides=strides, depth_multiplier=1,\n padding='SAME', use_bias=_USE_BIAS,\n depthwise_initializer=_KERNEL_INITIALIZER,\n pointwise_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_sep_{0}x{0}_{1}'.format(kernel_size, 1)):\n inputs = batch_normalization(inputs, data_format, is_training)\n strides = 1\n\n inputs = relu(inputs)\n with tf.variable_scope('separable_conv_{0}x{0}_{1}'.format(kernel_size, 2)):\n inputs = tf.layers.separable_conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, \n strides=strides, depth_multiplier=1,\n padding='SAME', use_bias=_USE_BIAS,\n depthwise_initializer=_KERNEL_INITIALIZER,\n pointwise_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_sep_{0}x{0}_{1}'.format(kernel_size, 2)):\n inputs = batch_normalization(inputs, data_format, is_training)\n\n return inputs\n\n\ndef _dil_separable_conv2d(operation, inputs, filters, strides, data_format, is_training):\n kernel_size, dilation_rate = _operation_to_info(operation)\n\n if not dilation_rate:\n dilation_rate = 2\n\n inputs = relu(inputs)\n with tf.variable_scope('dil_separable_conv_{0}x{0}_{1}_{2}'.format(kernel_size, dilation_rate, 1)):\n inputs = tf.layers.separable_conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, \n strides=strides, depth_multiplier=1,\n padding='SAME', use_bias=_USE_BIAS,\n dilation_rate=dilation_rate,\n depthwise_initializer=_KERNEL_INITIALIZER,\n pointwise_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_dil_sep_{0}x{0}_{1}'.format(kernel_size, 1)):\n inputs = batch_normalization(inputs, data_format, is_training)\n strides = 1\n\n inputs = relu(inputs)\n with tf.variable_scope('dil_separable_conv_{0}x{0}_{1}_{2}'.format(kernel_size, dilation_rate, 2)):\n inputs = tf.layers.separable_conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, \n strides=strides, depth_multiplier=1,\n padding='SAME', use_bias=_USE_BIAS,\n dilation_rate=dilation_rate,\n depthwise_initializer=_KERNEL_INITIALIZER,\n pointwise_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_dil_sep_{0}x{0}_{1}'.format(kernel_size, 2)):\n inputs = batch_normalization(inputs, data_format, is_training)\n\n return inputs\n\n\ndef _conv2d(operation, inputs, filters, strides, data_format, is_training):\n kernel_size, _ = _operation_to_info(operation)\n if isinstance(kernel_size, int):\n inputs = relu(inputs)\n with tf.variable_scope('conv_{0}x{0}_{1}'.format(kernel_size, 1)):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, \n strides=strides, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_conv_{0}x{0}_{1}'.format(kernel_size, 1)):\n inputs = batch_normalization(inputs, data_format, is_training)\n return inputs\n else:\n kernel_size1 = kernel_size[0]\n inputs = relu(inputs)\n with tf.variable_scope('conv_{0}x{1}_{2}'.format(kernel_size1[0], kernel_size1[1], 1)):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size1, \n strides=strides, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_conv_{0}x{1}_{2}'.format(kernel_size1[0], kernel_size1[1], 1)):\n inputs = batch_normalization(inputs, data_format, is_training)\n strides = 1\n\n kernel_size2 = kernel_size[1]\n inputs = relu(inputs)\n with tf.variable_scope('conv_{0}x{1}_{2}'.format(kernel_size2[0], kernel_size2[1], 2)):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size2, \n strides=strides, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_conv_{0}x{1}_{2}'.format(kernel_size2[0], kernel_size2[1], 2)):\n inputs = batch_normalization(inputs, data_format, is_training)\n return inputs\n\n\ndef _dil_conv2d(operation, inputs, filters, strides, data_format, is_training):\n kernel_size, dilation_rate = _operation_to_info(operation)\n inputs = relu(inputs)\n with tf.variable_scope('dil_conv_{0}x{0}_{1}_{2}'.format(kernel_size, dilation_rate, 1)):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=kernel_size, \n strides=strides, padding='SAME', use_bias=_USE_BIAS,\n dilation_rate=dilation_rate,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn_dil_conv_{0}x{0}_{1}_{2}'.format(kernel_size, dilation_rate, 1)):\n inputs = batch_normalization(inputs, data_format, is_training)\n \n return inputs\n\n\ndef _operation_to_filter_shape(operation):\n if '+' in operation:\n filter_shapes = operation.split('+')\n filter_shape = []\n for fs in filter_shapes:\n filter_height_width = fs.split('x')\n filter_height = int(filter_height_width[0])\n filter_width = int(filter_height_width[1])\n filter_shape.append((filter_height, filter_width))\n return filter_shape\n else:\n filter_height_width = operation.split('x')\n filter_shape = int(filter_height_width[0])\n assert filter_shape == int(\n filter_height_width[1]), 'Rectangular filters not supported.'\n return filter_shape\n\n\ndef _operation_to_num_layers(operation):\n splitted_operation = operation.split(' ')\n if 'x' in splitted_operation[-1]:\n return 1\n return int(splitted_operation[-1])\n\n\ndef _operation_to_dilation_rate(operation):\n return int(operation)\n\n\ndef _operation_to_info(operation):\n operation = operation.split(' ')\n filter_shape = _operation_to_filter_shape(operation[1])\n if len(operation) == 3:\n dilation_rate = _operation_to_dilation_rate(operation[2])\n else:\n dilation_rate = None\n return filter_shape, dilation_rate\n\n\ndef _operation_to_pooling_type(operation):\n splitted_operation = operation.split(' ')\n return splitted_operation[0]\n\n\ndef _operation_to_pooling_shape(operation):\n splitted_operation = operation.split(' ')\n shape = splitted_operation[-1]\n assert 'x' in shape\n filter_height, filter_width = shape.split('x')\n assert filter_height == filter_width\n return int(filter_height)\n\n\ndef _operation_to_pooling_info(operation):\n pooling_type = _operation_to_pooling_type(operation)\n pooling_shape = _operation_to_pooling_shape(operation)\n return pooling_type, pooling_shape\n\n\ndef factorized_reduction(inputs, filters, strides, data_format, is_training):\n assert filters % 2 == 0, (\n 'Need even number of filters when using this factorized reduction')\n if strides == 1:\n with tf.variable_scope('path_conv'):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=1, \n strides=strides, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('path_bn'):\n inputs = batch_normalization(inputs, data_format, is_training)\n return inputs\n\n path1 = tf.layers.average_pooling2d(inputs, pool_size=1, strides=strides, padding='VALID', data_format=data_format)\n with tf.variable_scope('path1_conv'):\n path1 = tf.layers.conv2d(\n inputs=path1, filters=int(filters / 2), kernel_size=1, \n strides=1, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n\n if data_format == 'channels_first':\n pad_arr = [[0, 0], [0, 0], [0, 1], [0, 1]]\n path2 = tf.pad(inputs, pad_arr)[:, :, 1:, 1:]\n else:\n pad_arr = [[0, 0], [0, 1], [0, 1], [0, 0]]\n path2 = tf.pad(inputs, pad_arr)[:, 1:, 1:, :]\n\n path2 = tf.layers.average_pooling2d(path2, pool_size=1, strides=strides, padding='VALID', data_format=data_format)\n with tf.variable_scope('path2_conv'):\n path2 = tf.layers.conv2d(\n inputs=path2, filters=int(filters / 2), kernel_size=1, \n strides=1, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n\n final_path = tf.concat(values=[path1, path2], axis=get_channel_index(data_format))\n with tf.variable_scope('final_path_bn'):\n inputs = batch_normalization(final_path, data_format, is_training)\n\n return inputs\n\n\ndef drop_path(inputs, keep_prob, is_training=True):\n if is_training:\n batch_size = tf.shape(inputs)[0]\n noise_shape = [batch_size, 1, 1, 1]\n random_tensor = keep_prob\n random_tensor += tf.random_uniform(noise_shape, dtype=tf.float32)\n binary_tensor = tf.floor(random_tensor)\n inputs = tf.div(inputs, keep_prob) * binary_tensor\n return inputs\n\n\nclass NASCell(object):\n def __init__(self, filters, dag, num_nodes, drop_path_keep_prob, num_cells,\n total_steps, data_format, is_training):\n self._filters = filters\n self._dag = dag\n self._num_nodes = num_nodes\n self._drop_path_keep_prob = drop_path_keep_prob\n self._num_cells = num_cells\n self._total_steps = total_steps\n self._is_training = is_training\n self._data_format = data_format\n\n def _reduce_prev_layer(self, prev_layer, curr_layer):\n if prev_layer is None:\n return curr_layer\n\n curr_num_filters = self._filter_size\n data_format = self._data_format\n is_training = self._is_training\n\n prev_num_filters = get_channel_dim(prev_layer, data_format)\n curr_filter_shape = int(curr_layer.shape[2])\n prev_filter_shape = int(prev_layer.shape[2])\n if curr_filter_shape != prev_filter_shape:\n prev_layer = relu(prev_layer)\n prev_layer = factorized_reduction(prev_layer, curr_num_filters, 2, data_format, is_training)\n elif curr_num_filters != prev_num_filters:\n prev_layer = relu(prev_layer)\n with tf.variable_scope('prev_1x1'):\n prev_layer = tf.layers.conv2d(\n inputs=prev_layer, filters=curr_num_filters, kernel_size=1, \n strides=1, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('prev_bn'):\n prev_layer = batch_normalization(prev_layer, data_format, is_training)\n return prev_layer\n\n\n def _cell_base(self, last_inputs, inputs):\n filters = self._filter_size\n data_format = self._data_format\n is_training = self._is_training\n\n with tf.variable_scope('transforme_last_inputs'):\n last_inputs = self._reduce_prev_layer(last_inputs, inputs)\n with tf.variable_scope('transforme_inputs'):\n inputs = relu(inputs)\n with tf.variable_scope('1x1'):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=1, \n strides=1, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn'):\n inputs = batch_normalization(inputs, data_format, is_training)\n return last_inputs, inputs\n\n\n def __call__(self, inputs, filter_scaling=1, strides=1,\n last_inputs=None, cell_num=-1):\n self._cell_num = cell_num\n self._filter_scaling = filter_scaling\n self._filter_size = int(self._filters * filter_scaling)\n num_nodes = self._num_nodes\n dag = self._dag\n data_format = self._data_format\n\n # node 1 and node 2 are last_inputs and inputs respectively\n # begin processing from node 3\n\n last_inputs, inputs = self._cell_base(last_inputs, inputs)\n\n h = {}\n loose_ends = ['node_%d' % i for i in xrange(1, num_nodes+1)]\n for i in xrange(1, num_nodes+1):\n name = 'node_%d' % i\n with tf.variable_scope(name):\n node = dag[name]\n assert name == node[0], 'name incompatible with node name'\n if i == 1:\n h[name] = last_inputs\n continue\n elif i == 2:\n h[name] = inputs\n continue\n previous_node_1, previous_node_2 = node[1], node[2]\n h1, h2 = h[previous_node_1], h[previous_node_2]\n if previous_node_1 in loose_ends:\n loose_ends.remove(previous_node_1)\n if previous_node_2 in loose_ends:\n loose_ends.remove(previous_node_2)\n operation_1, operation_2 = node[3], node[4]\n with tf.variable_scope('input_1'):\n is_from_original_input = int(previous_node_1.split('_')[-1]) < 3\n h1 = self._apply_operation(operation_1, h1, strides, is_from_original_input)\n with tf.variable_scope('input_2'):\n is_from_original_input = int(previous_node_2.split('_')[-1]) < 3\n h2 = self._apply_operation(operation_2, h2, strides, is_from_original_input)\n \n output = h1 + h2\n h[name] = output\n\n if 'loose_ends' in dag:\n loose_ends = dag['loose_ends']\n\n with tf.variable_scope('cell_output'):\n output = self._combine_unused_states(h, loose_ends)\n \n return output\n\n\n def _apply_operation(self, operation, inputs, strides, is_from_original_input):\n filters = self._filter_size\n data_format = self._data_format\n is_training = self._is_training\n\n if strides > 1 and not is_from_original_input:\n strides = 1\n input_filters = get_channel_dim(inputs, data_format)\n if 'dil_sep_conv' in operation:\n inputs = _dil_separable_conv2d(operation, inputs, filters, strides, data_format, is_training)\n elif 'dil_conv' in operation:\n #dilation > 1 is not compatible with strides > 1, so set strides to 1, and use a 1x1 conv with expected strdies\n inputs = _dil_conv2d(operation, inputs, filters, 1, data_format, is_training)\n if strides > 1:\n inputs = relu(inputs)\n with tf.variable_scope('1x1'):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=1, \n strides=strides, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format,)\n with tf.variable_scope('bn'):\n inputs = batch_normalization(inputs, data_format, is_training)\n elif 'sep_conv' in operation:\n inputs = _separable_conv2d(operation, inputs, filters, strides, data_format, is_training)\n elif 'conv' in operation:\n inputs = _conv2d(operation, inputs, filters, strides, data_format, is_training)\n elif 'identity' in operation:\n if strides > 1 or (input_filters != filters):\n inputs = relu(inputs)\n with tf.variable_scope('1x1'):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=1, \n strides=strides, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn'):\n inputs = batch_normalization(inputs, data_format, is_training)\n elif 'pool' in operation:\n inputs = _pooling(operation, inputs, strides, data_format)\n if input_filters != filters:\n inputs = relu(inputs)\n with tf.variable_scope('1x1'):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=filters, kernel_size=1, \n strides=1, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('bn'):\n inputs = batch_normalization(inputs, data_format, is_training)\n else:\n raise ValueError('Unimplemented operation', operation)\n\n if operation != 'identity':\n inputs = self._apply_drop_path(inputs, is_training)\n\n return inputs\n\n\n def _combine_unused_states(self, h, loose_nodes):\n data_format = self._data_format\n is_training = self._is_training\n filters = self._filter_size\n\n out_height = min([int(h[name].shape[2]) for name in loose_nodes])\n\n for i in range(1, self._num_nodes+1):\n node_name = 'node_%d'%i\n curr_height = int(h[node_name].shape[2])\n curr_filters = get_channel_dim(h[node_name], data_format)\n\n # Determine if a reduction should be applied to make the number of filters match.\n should_reduce = filters != curr_filters\n should_reduce = (out_height != curr_height) or should_reduce\n should_reduce = should_reduce and (node_name in loose_nodes)\n if should_reduce:\n strides = 2 if out_height != curr_height else 1\n with tf.variable_scope('reduction_{}'.format(i)):\n h[node_name] = factorized_reduction(h[node_name], filters, strides, data_format, is_training)\n\n output = tf.concat([h[name] for name in loose_nodes], axis=get_channel_index(data_format))\n return output\n\n def _apply_drop_path(self, inputs, is_training, current_step=None, use_summaries=False, drop_connect_version='v3'):\n drop_path_keep_prob = self._drop_path_keep_prob\n if drop_path_keep_prob < 1.0:\n assert drop_connect_version in ['v1', 'v2', 'v3']\n if drop_connect_version in ['v2', 'v3']:\n # Scale keep prob by layer number\n assert self._cell_num != -1\n num_cells = self._num_cells\n layer_ratio = (self._cell_num + 1) / float(num_cells)\n if use_summaries:\n with tf.device('/cpu:0'):\n tf.summary.scalar('layer_ratio', layer_ratio)\n drop_path_keep_prob = 1 - layer_ratio * (1 - drop_path_keep_prob)\n if drop_connect_version in ['v1', 'v3']:\n # Decrease the keep probability over time\n if not current_step:\n current_step = tf.cast(tf.train.get_or_create_global_step(),\n tf.float32)\n drop_path_burn_in_steps = self._total_steps\n current_ratio = current_step / drop_path_burn_in_steps\n current_ratio = tf.minimum(1.0, current_ratio)\n if use_summaries:\n with tf.device('/cpu:0'):\n tf.summary.scalar('current_ratio', current_ratio)\n drop_path_keep_prob = (1 - current_ratio * (1 - drop_path_keep_prob))\n if use_summaries:\n with tf.device('/cpu:0'):\n tf.summary.scalar('drop_path_keep_prob', drop_path_keep_prob)\n inputs = drop_path(inputs, drop_path_keep_prob, is_training)\n return inputs\n\n\ndef _build_aux_head(aux_net, num_classes, params, data_format, is_training):\n with tf.variable_scope('aux_head'):\n aux_logits = relu(aux_net)\n aux_logits = tf.layers.average_pooling2d(\n inputs=aux_logits, \n pool_size=5, strides=3, padding='VALID', data_format=data_format)\n with tf.variable_scope('proj'):\n aux_logits = tf.layers.conv2d(\n inputs=aux_logits, filters=128, kernel_size=1, \n strides=1, padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER, \n data_format=data_format)\n aux_logits = batch_normalization(aux_logits, data_format, is_training)\n aux_logits = relu(aux_logits)\n \n with tf.variable_scope('avg_pool'):\n shape = aux_logits.shape\n if data_format == 'channels_first':\n shape = shape[2:4]\n else:\n shape = shape[1:3]\n aux_logits = tf.layers.conv2d(\n inputs=aux_logits, filters=768, kernel_size=shape, \n strides=1, padding='VALID', use_bias=_USE_BIAS, \n kernel_initializer=_KERNEL_INITIALIZER, \n data_format=data_format)\n aux_logits = batch_normalization(aux_logits, data_format, is_training)\n aux_logits = relu(aux_logits)\n\n with tf.variable_scope('fc'):\n if data_format == 'channels_first':\n aux_logits = tf.reduce_mean(aux_logits, axis=[2,3])\n else:\n aux_logits = tf.reduce_mean(aux_logits, axis=[1,2])\n aux_logits = tf.layers.dense(inputs=aux_logits, units=num_classes)#, use_bias=_USE_BIAS)\n return aux_logits\n\n\ndef _imagenet_stem(inputs, stem_cell, filters, filter_scaling_rate, stem_multiplier, data_format, is_training):\n \"\"\"Stem used for models trained on ImageNet.\"\"\"\n num_stem_cells = 2\n\n num_stem_filters = int(32 * stem_multiplier)\n with tf.variable_scope('stem_conv_3x3'):\n net = tf.layers.conv2d(\n inputs=inputs, filters=num_stem_filters, kernel_size=3, strides=2,\n padding='VALID', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('stem_conv_bn'):\n net = batch_normalization(net, data_format, is_training)\n\n # Run the reduction cells\n cell_outputs = [None, net]\n filter_scaling = 1.0 / (filter_scaling_rate**num_stem_cells)\n for cell_num in range(num_stem_cells):\n with tf.variable_scope('stem_reduction_cell_%d' % (cell_num + 1)):\n net = stem_cell(net, filter_scaling, 2, cell_outputs[-2], cell_num)\n cell_outputs.append(net)\n filter_scaling *= filter_scaling_rate\n return net, cell_outputs\n\n\ndef _cifar_stem(inputs, filters, stem_multiplier, data_format, is_training):\n \"\"\"Stem used for models trained on Cifar.\"\"\"\n with tf.variable_scope('stem_conv_3x3'):\n inputs = tf.layers.conv2d(\n inputs=inputs, filters=int(filters * stem_multiplier), kernel_size=3, strides=1,\n padding='SAME', use_bias=_USE_BIAS,\n kernel_initializer=_KERNEL_INITIALIZER,\n data_format=data_format)\n with tf.variable_scope('stem_bn'):\n inputs = batch_normalization(inputs, data_format, is_training)\n return inputs, [None, inputs]\n\ndef build_model(inputs, params, is_training, reuse=False):\n \"\"\"Generator for net.\n\n Args:\n inputs: inputs\n params: A dict containing following keys:\n num_nodes: A single integer for the number of nodes.\n num_classes: The number of possible classes for image classification.\n filters: The numer of filters\n conv_dag: The DAG of the convolution cell\n reduc_dag: The DAG of the reduction cell\n data_format: The input format ('channels_last', 'channels_first', or None).\n If set to None, the format is dependent on whether a GPU is available.\n is_training: boolean, whether is in training mode\n\n Returns:\n The model function that takes in `inputs` and `is_training` and\n returns the output tensor of the model.\n \"\"\"\n \n filters = params['filters']\n conv_dag = params['conv_dag']\n reduc_dag = params['reduc_dag']\n N = params['N']\n num_nodes = params['num_nodes']+2\n if is_training:\n drop_path_keep_prob = params['drop_path_keep_prob']\n dense_dropout_keep_prob = params['dense_dropout_keep_prob']\n else:\n drop_path_keep_prob = 1.0\n dense_dropout_keep_prob = 1.0\n total_steps = params['total_steps']\n if params['data_format'] is None:\n data_format = 'channels_first' if tf.test.is_built_with_cuda() else 'channels_last'\n else:\n data_format = params['data_format']\n num_classes = params['num_classes']\n stem_multiplier = params['stem_multiplier']\n use_aux_head = params['use_aux_head']\n\n \n if data_format == 'channels_first':\n # Convert the inputs from channels_last (NHWC) to channels_first (NCHW).\n # This provides a large performance boost on GPU. See\n # https://www.tensorflow.org/performance/performance_guide#data_formats\n inputs = tf.transpose(inputs, [0, 3, 1, 2])\n \n num_cells = N * 3\n total_num_cells = num_cells + 2\n if params['dataset'] == 'imagenet':\n total_num_cells += 2\n\n convolution_cell = NASCell(filters, conv_dag, num_nodes, drop_path_keep_prob, total_num_cells,\n total_steps, data_format, is_training)\n reduction_cell = NASCell(filters, reduc_dag, num_nodes, drop_path_keep_prob, total_num_cells,\n total_steps, data_format, is_training)\n\n reduction_indices = []\n for pool_num in range(1, 3):\n layer_index = int((float(pool_num) / (2 + 1)) * num_cells)\n reduction_indices.append(layer_index)\n\n if len(reduction_indices) >= 2:\n aux_head_ceill_index = reduction_indices[1] - 1 #[TODO]\n filter_scaling = 1.0\n with tf.variable_scope('body', reuse=reuse):\n if params['dataset'] in ['cifar10', 'cifar100']:\n net, cell_outputs = _cifar_stem(inputs, filters, stem_multiplier, data_format, is_training)\n true_cell_num = 0\n elif params['dataset'] == 'imagenet':\n net, cell_outputs = _imagenet_stem(inputs, reduction_cell, filters, 2, stem_multiplier, data_format, is_training)\n true_cell_num = 2\n for cell_num in range(num_cells):\n strides = 1\n if params['skip_reduction_layer_input']:\n prev_layer = cell_outputs[-2]\n if cell_num in reduction_indices:\n filter_scaling *= 2\n with tf.variable_scope('reduction_cell_%d' % (reduction_indices.index(cell_num)+1)):\n net = reduction_cell(net, filter_scaling, 2, cell_outputs[-2], true_cell_num)\n true_cell_num += 1\n cell_outputs.append(net)\n if not params['skip_reduction_layer_input']:\n prev_layer = cell_outputs[-2]\n with tf.variable_scope('convolution_cell_%d' % (cell_num+1)):\n net = convolution_cell(net, filter_scaling, strides, prev_layer, true_cell_num)\n true_cell_num += 1\n cell_outputs.append(net)\n if use_aux_head and aux_head_ceill_index == cell_num and num_classes and is_training:\n aux_logits = _build_aux_head(net, num_classes, params, data_format, is_training)\n\n net = relu(net)\n\n assert net.shape.ndims == 4\n \n if data_format == 'channels_first':\n net = tf.reduce_mean(net, axis=[2,3])\n else:\n net = tf.reduce_mean(net, axis=[1,2])\n \n # tf.layers.dropout(inputs, rate) where rate is the drop rate\n # tf.nn.dropout(inputs, rate) where rate is the keep prob\n net = tf.layers.dropout(net, 1 - dense_dropout_keep_prob, training=is_training)\n\n with tf.variable_scope('fully_connected_layer'):\n logits = tf.layers.dense(inputs=net, units=num_classes)#, use_bias=_USE_BIAS)\n\n res = {'logits': logits}\n if use_aux_head and is_training:\n res['aux_logits'] = aux_logits\n return res\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":27798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"233702338","text":"#-------------------------------------------------------------------------------\n# Name: CopyLocalParcelPlus2FTP.py\n# Purpose: To copy local parcelsplus to the FTP site for distribution.\n# Author: Bryan May\n# Created: 20171011\n# Modified:\n#-------------------------------------------------------------------------------\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\nimport arcpy,os,shutil\n\ninputunittmp = arcpy.GetParameterAsText(0) # list of values such as AlleganTwp,CascoTwp\n#inputlayertmp = arcpy.GetParameterAsText(1) # list of values such as Addresses,Parcels\n#inputunit = [\"AlleganTwp\",\"CascoTwp\"]\n\nsrcDir = ''\ntrgtDir = ''\nunitdict = {}\nlayerlist = []\nunitlist = []\n\ninputunit = inputunittmp.split(\";\")\n#inputlayer = inputlayertmp.split(\";\")\n#layerlist = inputlayer\nunitlist = inputunit\narcpy.env.workspace = \"J:/Apps/Python/LayerUpdates/parcels/\"\nsrcPath = 'J:/data/Shapefiles/'\ntrgtPath = 'S:/Secure/Units/'\n\nunitdict = {\n 'AlleganTwp': '01',\n 'CascoTwp': '02',\n 'CheshireTwp': '03',\n 'ClydeTwp': '04',\n 'DorrTwp': '05',\n 'FillmoreTwp': '06',\n 'GangesTwp': '07',\n 'GunPlainTwp': '08',\n 'HeathTwp': '09',\n 'HopkinsTwp': '10',\n 'LaketownTwp': '11',\n 'LeeTwp': '12',\n 'LeightonTwp': '13',\n 'ManliusTwp': '14',\n 'MartinTwp': '15',\n 'MontereyTwp': '16',\n 'OtsegoTwp': '17',\n 'OveriselTwp': '18',\n 'SalemTwp': '19',\n 'SaugatuckTwp': '20',\n 'TrowbridgeTwp': '21',\n 'ValleyTwp': '22',\n 'WatsonTwp': '23',\n 'WaylandTwp': '24',\n 'MartinVillage': '42',\n 'HopkinsVillage': '44',\n 'AlleganCity': '51',\n 'FennvilleCity': '52',\n 'HollandCity': '53',\n 'OtsegoCity': '54',\n 'PlainwellCity': '55',\n 'WaylandCity': '56',\n 'SaugatuckCity': '57',\n 'SouthHavenCity': '58',\n 'DouglasCity': '59',\n }\n\nfiletype = ['.shp',\n '.dbf',\n '.sbn',\n '.sbx',\n '.cpg',\n '.shx',\n '.prj'\n ]\n\nfor unit in inputunit:\n unitID = str(unitdict.get(unit))\n srcFolder = unitID+unit\n trgtFolder = trgtPath+unit+'/LIS/'\n arcpy.AddMessage('processing: '+unitID + ' '+unit)\n for ext in filetype:\n srcFile = srcPath+srcFolder+'/ParcelsPlus'+ext\n trgtFile = trgtFolder+'ParcelsPlus'+ext\n arcpy.AddMessage('source file: '+srcFile)\n arcpy.AddMessage('target file: '+trgtFile)\n #manual format: shutil.copyfile('J:/data/Shapefiles/01AlleganTwp/Parcels.shp','J:/data/Shapefiles/01AlleganTwp/archive/Parcels.shp')\n shutil.copyfile(srcFile,trgtFile)\n","sub_path":"parcels/processing/CopyLocalParcelPlus2FTP.py","file_name":"CopyLocalParcelPlus2FTP.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"562473601","text":"import math\nimport scipy.stats\nimport numpy\nimport random\n\n\ndef percentage(z_score):\n return .5 * (math.erf(z_score / 2 ** .5) + 1)\n\n\n\n\nmean1 = 19.787819193651494\nvar1 = 29680.186598120901\nstd1 = math.sqrt(var1)\n\nmean2 = 18.505704910048621\nvar2 = 29082.653864213582\nstd2 = math.sqrt(var2)\n\ndef z_score(percent):\n return scipy.stats.norm.ppf(percent)\n\n# mean1 = 3.2851584846564279\n# var1 = 6026.101720881039\n# mean2 = 47.226987906711642\n# var2 = 3806.5056004096614\n\n'''\nold = 1\nfor i in range(1, 10000):\n z1 = (-1500 - (i * mean1)) / math.sqrt(pow(i, 2) * var1)\n percent1 = 1 - percentage(z1) # Prob. that player is still in\n\n z2 = (-1500 - (i * mean2)) / math.sqrt(pow(i, 2) * var2)\n percent2 = 1 - percentage(z2) # Prob. that player is still in\n\n new = old * percent1 * percent2\n print(percent1, percent2, \"*\", new)\n old = new\n\n\n'''\n\n'''\nstill_going = 0\nfor i in range(1, 10000):\n z1 = (-1500 - (i * mean1)) / math.sqrt(pow(i, 2) * var1)\n percent1 = percentage(z1)\n\n z2 = (-1500 - (i * mean2)) / math.sqrt(pow(i, 2) * var2)\n percent2 = percentage(z2)\n\n p1_wins = (1 - percent1) * percent2 * still_going\n p2_wins = percent1 * (1 - percent2) * still_going\n\n still_going = percent1 * (1 - still_going) * (1 - percent2)\n\n print(i, percent1, still_going)\n\n'''\n\n\ndef reverse_attempt():\n print(\"*******************\")\n for i in [10000]:\n print(i, (mean1 * i) + (z_score(0.3767) * (math.sqrt(var1)) * i))\n\n\ndef simulation():\n sample = 5000\n winners = [0, 0, 0]\n for i in range(sample):\n p1_money = 2000\n p2_money = 2000\n counter = 0\n\n while (p2_money > 0 and p1_money > 0) and counter < 1000:\n p1_money += random.gauss(mean1, std1)\n p2_money += random.gauss(mean2, std2)\n counter += 1\n\n if counter >= 1000:\n winners[0] += 1\n elif p1_money < 0:\n winners[2] += 1\n else:\n winners[1] += 1\n\n print(winners[0] / sample, winners[1] / sample, winners[2] / sample)\n\n\nsimulation()\n","sub_path":"longTime.py","file_name":"longTime.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"457416931","text":"'''\nCreated on Dec 8, 2017\n\n@author: marcel.zoll\n'''\n\nimport sys, copy\nimport itertools\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn.base import BaseEstimator, TransformerMixin, MetaEstimatorMixin\nfrom sklearn.utils.metaestimators import _BaseComposition\nfrom sklearn import pipeline \nfrom sklearn.pipeline import _fit_transform_one, _transform_one, _fit_one_transformer\nfrom sklearn import clone\nfrom sklearn.externals import six\nfrom sklearn.externals.joblib import Parallel, delayed, Memory\nfrom sklearn.utils import check_array, safe_mask\nfrom sklearn.utils.validation import check_memory\n\nfrom ..Transformers.LabelDummy import LabelDummyTransformer\nfrom ..base import assert_dfncol\n\n\nclass SplitterFork(TransformerMixin, object): #_BaseComposition\n \"\"\" A Pipeline that splices up a subsequent pipeline based on the yield variable of cat_trans, applies preprocessing by\n pre_trans and the applies sub_pipe individually for each so trained segment\n \n Parameters\n ----------\n cat_trans : class Transformer or TransformerPipeline\n a Transformer which yields a single column categorical output feature of finite number of classes\n pre_trans : class Transformer or TransformerPipeline\n a Transformer which is applied to all data before it is passed to the individualized pipelines\n sub_pipe : class Pipeline\n A pipeline that is gonna be copied and trained for each of the classes yielded by cat_trans\n min_coverage : float (0..1)\n minimal coverage required in each level, otherwise substituted by `default_key` (default: 0.0)\n max_levels : int >0 \n maximal number of highest ranked original levels that are retained (default: sys.maxsize)\n default_name: obj\n name that is substituted for any level with coverage less than `min_coverage` (default: 'DEFAULT')\n propagate_disc_labels : bool\n propagate dummy lables of the categorical feature from `cat_trans` to the `sub_pipes` (default: False)\n take_pre_only : bool\n only take the features yielded by pre_trans to be parsed into individual training by the sub_pipe's (default: False)\n n_jobs : int\n number of jobs to execute on; effective value min(.,len(self,pipeline_list_)) (default: 1)\n \n Attributes\n ----------\n sub_pipes_ : list of pipelines\n the trained pipelines, one for each levelgroup \n levels_ : list of strings\n the levels / labels taken by the variable\n coverage_ : list of floats \n relative coverage in each of the groups determined in fit()\n \"\"\"\n class TheseLabelsDummyTransformer(object):\n \"\"\" one hot encode categorical column with dummies for these lables \n \n Parameters\n ----------\n lables : list of str\n list of the names of the to onehot-encode lables\n sparse_output : bool\n return a sparse DataFrame (true), else dense DataFrame (false) (default: True)\n \"\"\"\n def __init__(self, lables, sparse_output = False):\n self.classes_ = lables\n self.sparse_output = sparse_output\n def className_to_dummyName_(self, cn):\n return '_'.join([self.invar_, str(cn)])\n def constructTransdict(self):\n s_dummy = pd.Series( { e:False for e in self.feature_names_ } )\n def xthelper(c):\n sx = s_dummy.copy()\n sx[self.className_to_dummyName_(c) ] = True\n return(sx)\n self.transdict = { c:xthelper(c) for c in self.classes_ }\n self.transdict[None] = s_dummy\n #optimize for single row evals\n self.transdfdict = { k:pd.DataFrame(v).T for k,v in self.transdict.items() }\n \n def fit(self, X, y=None, **fit_params):\n self.invar_ = X.columns[0]\n \n self.feature_names_ = [ self.className_to_dummyName_(c) for c in self.classes_ ]\n self.constructTransdict()\n \n return self\n \n def transform(self, X):\n check_is_fitted(self, 'classes_')\n assert_dfncol(X, 1)\n \n if X.shape[0]==1: #optimize for single row evals\n df = self.transdfdict.get(X[invar_].values[0]) \n df.index = X.index\n return df\n \n def xthelper(row):\n v = row[self.invar_]\n r = self.transdict.get(v)\n return r\n Xt = X.apply(xthelper, axis=1)\n \n if self.sparse_output:\n return Xt.to_sparse(fill_value=False)\n return Xt\n \n def __init__(self,\n cat_trans,\n pre_trans,\n sub_pipe,\n min_coverage = 0.,\n max_levels = sys.maxsize,\n propagate_disc_labels =False,\n take_pre_only = False,\n default_name = 'DEFAULT',\n n_jobs=1):\n self.cat_trans = cat_trans\n self.pre_trans = pre_trans\n self.sub_pipe = sub_pipe\n self.min_coverage = min_coverage\n self.max_levels = max_levels\n self.propagate_disc_labels = propagate_disc_labels\n self.take_pre_only = take_pre_only\n self.default_name = default_name\n self.n_jobs = n_jobs\n #-----------------\n self.default_key =None\n def fit(self, X, y, **fit_params):\n ''' determine the factor levels, build the fits '''\n #--- determine groups\n Xg = self.cat_trans.fit_transform(X) \n assert(Xg.shape[1] == 1)\n self.varname = self.cat_trans.get_feature_names()[0]\n \n levels, counts = np.unique( Xg.iloc[:,0], return_counts=True )\n idx = np.array(list(reversed(np.argsort(counts))))\n levels, counts, coverage = [ np.take(x, idx ) for x in [levels, counts, counts / np.sum(counts)] ]\n \n #--- decide which levels to take\n self.levels_ = []\n self.default_levels_ = []\n self.coverage_ = []\n for l,c in zip(levels, coverage):\n if len(self.levels_) < self.max_levels and c >= self.min_coverage:\n self.levels_.append(l)\n self.coverage_.append(c)\n else:\n self.default_levels_.append(l)\n \n #--- insert the default key if neccessary\n if len(self.levels_) < len(levels):\n self.default_key_= self.default_name\n else:\n self.default_key_= None\n \n if self.default_key_ is not None:\n self.levels_.append(self.default_name)\n self.coverage_.append( 1. - sum(self.coverage_) )\n \n print('grouping')\n #--- translate labels to group_indexes\n self.lg_dict = { l:g for g,l in enumerate(self.levels_) }\n def xghelper(v):\n res = self.lg_dict.get(v)\n if res is not None:\n return res\n if v in self.default_levels_:\n return self.lg_dict.get(self.default_key_)\n raise Exception(\"Unknown level '%s' encountered for variable '%s', and no default enabled\" % (v, self.varname))\n xgroups = Xg.iloc[:,0].apply(xghelper).values\n \n \n print(\"pre\")\n #--- compute the pre_pipe result and split up into groups\n Xt = self.pre_trans.fit_transform(X, y)\n if isinstance(Xt, pd.SparseDataFrame):\n Xt = Xt.to_dense()\n \n \n print(\"segment fit\")\n #--- create pipes and fit them for every group\n #fit the easy ones : for all levels with enough coverage the sub_pipe is copied locally (DANGER or so I hope) and trained\n #print(Xt.columns)\n gk_idx_groups = y.index.groupby(xgroups)\n gkd = len(self.lg_dict)-1\n \n #self.sub_pipes_ = [ copy.deepcopy(self.sub_pipe) for l in self.levels_ ]\n pls = Parallel(n_jobs=self.n_jobs)(\n delayed(_fit_one_fittable)(self.sub_pipe_, Xtgroups.loc[idx,:], ygroups.loc[idx]) for gk, idx in gk_idx_groups if gk!=gkd)\n self.sub_pipes_ = pls\n \n #do the hard one: Add the one hot encoding to the grouped block\n #then ovesample from rest until min_coverage is reached \n \n gkd_idx = gk_idx_groups[gkd]\n gkx_idx = y.index[~ y.index.isin(gkd_idx)]\n \n oversample_size = int(len(y)*self.min_coverage- len(gkd_idx))\n \n gkx_idx_os = gkx_idx( np.random.permutation( [True]*oversample_size + [False]*(len(gkx_idx)-oversample_size) ) )\n \n #we know which indexes to take, so now put it all together:\n Xg_gkd = Xg.loc[gkd_idx]\n self.level_encoder_ = TheseLabelsDummyTransformer(self.default_levels_, sparse_output=False).fit(Xg)\n Xgt_gkd = self.level_encoder_.transform(Xgt_gkd)\n \n Xt_gkd = Xt.loc[gkd_idx]\n \n XtXgt_gkd = pd.concat(Xt_gkd, Xgt_gkd, axis=1) \n \n XtXgt_gkdgkxos = pd.concat(XtXgt_gkd, Xt.loc[gkx_idx_os])\n \n y_gkdgkxos = pd.concat(y.loc[gkd_idx], y.loc[gkx_idx_os])\n \n #now fit the last pipe\n self.sub_pipes_.append(_fit_one_fittable(self.sub_pipe_, XtXgt_gkdgkxos, y_gkdgkxos))\n\n return self\n def _transform(self, X):\n ''' transform an input X by applying the grouping, the pre and then the individual pipelines '''\n Xg = self.cat_trans.fit_transform(X) \n \n #--- translate labels to group_indexes\n def xghelper(v):\n res = self.lg_dict.get(v)\n if res is not None:\n return res\n if v in self.default_levels_:\n return self.lg_dict.get(self.default_key_)\n raise Exception(\"Unknown level '%s' encountered for variable '%s', and no default enabled\" % (v, self.varname))\n xgroups = Xg.iloc[:,0].apply(xghelper)\n \n #--- compute the pre_pipe result and split up into groups \n Xt = self.pre_trans.fit_transform(X)\n if isinstance(Xt, pd.SparseDataFrame):\n Xt = Xt.to_dense()\n \n gk_idx_groups = y.index.groupby(xgroups)\n gkd = len(self.lg_dict)-1\n \n #self.sub_pipes_ = [ copy.deepcopy(self.sub_pipe) for l in self.levels_ ]\n results = Parallel(n_jobs=self.n_jobs)(\n delayed(_predict_one)(self.sub_pipes_[gk], Xtgroups.loc[idx,:], ygroups.loc[idx]) for gk, idx in gk_idx_groups if gk!=gkd)\n \n #do the hard one: Add the one hot encoding to the grouped block and predict \n gkd_idx = gk_idx_groups[gkd]\n Xt_gkd = Xt.loc[gkd_idx]\n Xg_gkd = Xg.loc[gkd_idx]\n Xgt_gkd = self.level_encoder_.transform(Xg)\n \n XtXgt_gkd = pd.concat(XtXgt_gkd, Xt.loc[gkx_idx_os])\n \n results.append(self.sub_pipes_[gkd_idx].predict(XtXgt_gkd))\n \n return pd.concat(results).reindex(index= X.index)\n \n def predict(self, X):\n return self._transform(X)\n def transform(self, X):\n return self._transform(X)\n def get_feature_importances_deep(self):\n features = set( fi[0] for p in self.sub_pipes_ for fi in p.get_feature_importances() )\n from collections import defaultdict\n dd = defaultdict(list)\n for p in self.sub_pipes_:\n fi_dict = dict(p.get_feature_importances())\n for f in features:\n dd[f].append( fi_dict[f] if f in fi_dict.keys() else 0. )\n return list(dd.items())\n \n def get_feature_importances(self): \n fi = []\n for f,il in self.get_feature_importances_deep():\n fi.append( (f, sum(np.array(il) * self.coverage_ )) )\n return fi\n @property\n def feature_importances_(self):\n ''' wrap this as property for chaining to work correctly '''\n return self.get_feature_importances()\n \n\n#==================================\n# Auxilaries\n#=================================\n#auxilary to CategoryFork\ndef _fit_one_fittable(fittable, X, y):\n return fittable.fit(X,y)\n\ndef _predict_one(est, X, y):\n return est.predict(X,y)","sub_path":"python/sklearnext/Assembly/SplicerFork.py","file_name":"SplicerFork.py","file_ext":"py","file_size_in_byte":12103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"137150299","text":"def list_up_next_games(players):\n games = set()\n for p in players:\n if A[p]:\n opponent = A[p][-1] - 1\n if A[opponent][-1] - 1 == p:\n if p < opponent:\n games.add((p, opponent))\n else:\n games.add((opponent, p))\n return(games)\n\nN = int(input())\nA = [list(map(int, input().split())) for i in range(N)]\nfor i in range(N):\n A[i].reverse()\n\ngames = list_up_next_games(list(range(N)))\n\ndone_games = []\ndays = 0\nwhile games:\n days += 1\n players = []\n for game in games:\n done_games.append(game)\n A[game[0]].pop()\n A[game[1]].pop()\n players.append(game[0])\n players.append(game[1])\n games = list_up_next_games(players)\n\nif len(done_games) == N*(N-1)//2:\n print(days)\nelse:\n print(-1)\n","sub_path":"old/ABC139/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"590016750","text":"from flask import Flask,request,abort\nfrom flask_restful import Resource, Api\nfrom categories import CategoryService,FooterService,HeaderService,Wish_list,Del_Prod,Match_Product,Compare_Prod_Details,Brand_Service,Search_Product\nfrom time import strftime\n\napp = Flask(__name__)\napi = Api(app)\n\napi.add_resource(CategoryService, '/categories')\napi.add_resource(FooterService, '/footerservice')\napi.add_resource(HeaderService, '/headerservice')\napi.add_resource(Search_Product, '/searchproduct')\napi.add_resource(Wish_list, '/wishlist')\n#api.add_resource(Compare_All_Prod, '/allproducts')\napi.add_resource(Del_Prod, '/delprod')\napi.add_resource(Match_Product, '/matchprod')\napi.add_resource(Compare_Prod_Details, '/productdetails')\napi.add_resource(Brand_Service, '/brandinfo')\n\n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*')\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')\n response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')\n return response\n\nif __name__ == '__main__':\n app.run(host='192.168.20.56', port=8000)\n","sub_path":"SERVICES/pos_app.py","file_name":"pos_app.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"238586060","text":"import pathlib\n\n\ndef keep_data(data, data_name, header_line=\"\"):\n tools_directory = pathlib.Path(__file__).parent\n implementation_directory = tools_directory.parent\n path = implementation_directory / \"data\" / data_name + \".py\"\n with path.open(\"w\") as output:\n output.write(\"import abjad\\n\")\n if header_line:\n output.write(header_line + \"\\n\")\n output.write(\"\\n\")\n output.write(\"\\n\")\n output.write(f\"{data_name} = {data}\")\n output.close()\n","sub_path":"archipel/etc/implementation/utilities/keep_data.py","file_name":"keep_data.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"468836272","text":"import time\nimport subprocess\nimport picamera\nfrom django.conf import settings\n# Use to ensure Pi Camera LED is off\n# import RPi.GPIO as GPIO\n\n\nclass CameraTools(object):\n \"\"\"\n Tools for working with Pi Camera.\n \"\"\"\n\n ### Pi Camera Default Settings\n # https://www.raspberrypi.org/documentation/raspbian/applications/camera.md\n\n # camera.sharpness = 0\n # camera.contrast = 0\n # camera.brightness = 50\n # camera.saturation = 0\n # camera.ISO = 0\n # camera.video_stabilization = False\n # camera.exposure_compensation = 0\n # camera.exposure_mode = 'auto'\n # camera.meter_mode = 'average'\n # camera.awb_mode = 'auto'\n # camera.image_effect = 'none'\n # camera.color_effects = None\n # camera.rotation = 0\n # camera.hflip = False\n # camera.vflip = False\n # camera.crop = (0.0, 0.0, 1.0, 1.0)\n\n def __init__(self):\n self.type = 'Pi'\n # Pi Camera Photo options\n self.photo_cmd = 'raspistill'\n self.photo_path = settings.BASE_DIR + '/photos/'\n self.photo_format = '.png'\n # Pi Camera Video options\n self.video_cmd = 'raspivid'\n self.video_path = settings.BASE_DIR + '/videos/'\n self.video_format = '.h264'\n # Timestamp format for photos and videos\n self.timestamp = time.strftime('%Y-%m-%d_%H%M%S')\n\n def photo(self):\n \"\"\"\n Take photo with Pi Camera.\n \"\"\"\n # cmd = self.photo_cmd + \\\n # ' -o' + self.photo_path + \\\n # ' -t 1000' \\\n # ' -w 640' \\\n # ' -t 480' \\\n # ' -rot 0' \\\n # subprocess.call(cmd, shell=True)\n # time.sleep(4)\n with picamera.PiCamera() as camera:\n # Set filename for photo\n camera.capture(self.photo_path + 'photo_' + self.timestamp + self.photo_format)\n\n def timelapse(self, duration, interval):\n \"\"\"\n Record timelapse with Pi Camera.\n \"\"\"\n # Use raspistill timelapse functionality\n # http://picamera.readthedocs.org/en/release-1.10/recipes1.html#capturing-timelapse-sequences\n # https://www.raspberrypi.org/documentation/usage/camera/raspicam/timelapse.md\n\n # camera.resolution = (1280, 720)\n # camera.framerate = 30\n\n # Wait for the automatic gain control to settle\n # time.sleep(2)\n\n # Now fix the values\n # camera.shutter_speed = camera.exposure_speed\n # camera.exposure_mode = 'off'\n # g = camera.awb_gains\n # camera.awb_mode = 'off'\n # camera.awb_gains = g\n\n # Finally, take several photos with the fixed settings\n # camera.capture_sequence(['image%02d.jpg' % i for i in range(10)])\n\n # with picamera.PiCamera() as camera:\n # camera.start_preview()\n # time.sleep(2)\n # for filename in camera.capture_continuous('img{counter:03d}.jpg'):\n # print('Captured %s' % filename)\n # # Wait 5 minutes\n # time.sleep(interval)\n pass\n\n def video(self, duration):\n \"\"\"\n Record video with Pi Camera.\n \"\"\"\n # cmd = self.video_cmd + \\\n # ' -o' \\\n # self.video_path\n # subprocess.call(cmd, shell=True)\n with picamera.PiCamera() as camera:\n # Set filename for video\n camera.start_recording(self.video_path + 'video_' + self.timestamp + self.video_format)\n # Record for the duration\n time.sleep(int(duration))\n # Stop video recording\n camera.stop_recording()\n\n def overlay_text(self, text):\n # http://picamera.readthedocs.org/en/release-1.10/recipes1.html#overlaying-text-on-the-output\n # TODO: Add ability to overlay text or a timestamp\n camera.annotate_text = str(text)","sub_path":"monitoring/utilities/CameraTools.py","file_name":"CameraTools.py","file_ext":"py","file_size_in_byte":3815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"332621471","text":"import typer\nfrom icon_cli.models.Config import Config\nfrom icon_cli.commands.subcommands.config import keystore\nfrom icon_cli.utils import die, print_json, print_object\n\napp = typer.Typer()\n\napp.add_typer(keystore.app, name=\"keystore\")\n\n\n@app.command()\ndef debug():\n print_object(__name__)\n\n\n@app.command()\ndef init():\n confirmation = typer.confirm(\n \"This will delete your existing config.yml file, and generate a new config.yml file. Please confirm.\"\n )\n if confirmation:\n Config.delete_config()\n Config.initialize_config()\n else:\n die()\n\n\n@app.command()\ndef inspect():\n config = Config.inspect_config()\n print_json(config)\n","sub_path":"icon_cli/commands/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"379422089","text":"#!/usr/bin/env python3\n\ndef fibonnaci(num):\n y = 1\n # num = num-1\n fiblist = []\n if num == 1:\n fiblist = [1]\n elif num == 2:\n fiblist = [1, 1]\n elif num > 2:\n y = 2\n fiblist = [1, 1]\n while num != 2:\n fiblist.append(y)\n y = y + fiblist[(fiblist.index(y)-1)]\n num = num - 1\n return fiblist\n\n\nprint(fibonnaci(int(input(\"Please enter the number of fibonacci numbers to return: \"))))\n","sub_path":"practicepython/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"378651260","text":"# Test description\nTEST_DESCRIPTION = \"64 pixels\"\nMODEL_NAME= \"instagram\"\nTAGS=[\"beach\", \"burguer\", \"coffee\", \"mirrorselfie\", \"night_concert\", \"paella\", \"shoes\", \"shot_closeup2\", \"shot_group\", \"shot_medium2\", \"sushi\", \"beer\", \"car\", \"croissant\", \"dog\", \"fried-eggs\", \"nails\", \"other\", \"pizza\", \"shot_closeup1\", \"shot_closeup3\", \"shot_medium1\", \"spam\", \"wine_cup\", \"watch\", \"collar\", \"cat\", \"handbag\"]\n\n# Model and training configuration code\nCONFIG_MODULE = \"instafood_config7_scope\"\n\n# Directories\nTRAIN_CHECKPOINT_DIR = \"models/instagram\" \nDATASET_DIR = \"data/no-git/instagram\"\n\n# Constants describing the dataset.\nNUM_CLASSES = 28\n\n# Constants describing the training process.\nBATCH_SIZE = 128\nORIGINAL_IMAGE_SIZE = 64 #We are cropping the images!\nIMAGE_SIZE = 48 #We are cropping the images!\nNUM_CHANNELS = 3\nMAX_STEPS = 100000\n\nMOVING_AVERAGE_DECAY = 0.9999 # The decay to use for the moving average.\nNUM_EPOCHS_PER_DECAY = 350.0 # Epochs after which learning rate decays.\nLEARNING_RATE_DECAY_FACTOR = 0.1 # Learning rate decay factor.\nINITIAL_LEARNING_RATE = 0.1 # Initial learning rate.\nNUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000\nNUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000\n\n# If a model is trained with multiple GPU's prefix all Op names with tower_name\n# to differentiate the operations. Note that this prefix is removed from the\n# names of the summaries when visualizing a model.\nTOWER_NAME = 'tower'\n#NUM_GPU = 0\n\n\n\n","sub_path":"homemade_params_instagram.py","file_name":"homemade_params_instagram.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"359705747","text":"from django.db import models as django_models\nfrom django.db.models import Q\nfrom django.db.models.functions import window\nfrom rest_framework import viewsets, status, mixins\nfrom rest_framework.response import Response\nfrom rest_framework import filters as drf_filers\nfrom django_filters import rest_framework as django_filters\nfrom apps.movies import models, serializers, filters, omdb_api, mappers\n\n\nclass MovieViewSet(mixins.CreateModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n mixins.ListModelMixin,\n viewsets.GenericViewSet):\n queryset = models.Movie.objects.all()\n serializer_class = serializers.MovieSerializer\n filter_backends = (django_filters.DjangoFilterBackend, drf_filers.OrderingFilter, drf_filers.SearchFilter,)\n filter_class = filters.MovieFilter\n http_method_names = ['delete', 'get', 'head', 'post', 'put']\n ordering_fields = ('username', 'email')\n search_fields = ('username', 'email')\n\n def get_serializer_class(self):\n if self.request.method == 'POST':\n return serializers.MovieCreateSerializer\n return self.serializer_class\n\n def create(self, request, *args, **kwargs):\n serializer = self.get_serializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n try:\n omdb_movie_data = omdb_api.OmdbApiWrapper().get_movie_by_title(serializer.data['title'])\n except omdb_api.OmdbApiException:\n return Response('External API call failed', status=status.HTTP_400_BAD_REQUEST)\n serializer = serializers.MovieSerializer(data={**omdb_movie_data, **serializer.data})\n serializer.is_valid(raise_exception=True)\n self.perform_create(serializer)\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)\n\n\nclass CommentViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):\n queryset = models.Comment.objects.all()\n serializer_class = serializers.CommentSerializer\n filter_backends = (django_filters.DjangoFilterBackend,)\n filter_class = filters.CommentFilter\n http_method_names = ['get', 'head', 'post']\n\n\nclass TopMovieViewSet(viewsets.ViewSet):\n def list(self, request):\n serializer = serializers.TopMovieQueryParamsSerializer(data=request.query_params)\n serializer.is_valid()\n if serializer.errors:\n response_data = {}\n for err_key, err_val in serializer.errors.items():\n err_msg = mappers.serializer_error_query_param_mapper.get(err_val[0].code, 'Something is wrong.')\n response_data[err_key] = err_msg\n return Response(response_data, status=status.HTTP_400_BAD_REQUEST)\n\n queryset = models.Movie.objects.annotate(\n total_comments=django_models.Count('comments', filter=Q(comments__created_at__range=[\n serializer.validated_data['date_from'], serializer.validated_data['date_to']\n ]))\n ).annotate(\n rank=django_models.Window(\n expression=window.DenseRank(),\n order_by=django_models.F(\"total_comments\").desc()\n )\n ).order_by(\n 'rank'\n ).values(\n 'id', 'rank', 'total_comments'\n )\n serializer = serializers.TopMovieSerializer(queryset, many=True)\n return Response(serializer.data)\n","sub_path":"apps/movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"40834719","text":"from fractional_knapsack import get_optimal_value\nimport numpy as np\nimport itertools\n\n\ndef get_optimal_value_slow(capacity, weights, values):\n a = list(range(0, len(weights)))\n alls = []\n for combination in itertools.permutations(a, len(a)):\n value = 0\n c_capacity = capacity\n for c in combination:\n if c_capacity >= weights[c]:\n value += values[c]\n c_capacity -= weights[c]\n else:\n value += values[c] / weights[c] * c_capacity\n break\n alls.append(value)\n\n return round(sorted(alls, reverse=True)[0], 4)\n\n\nif __name__ == '__main__':\n\n tests = [(66, np.array([44, 99]), np.array([60, 64])),\n (50, np.array([60, 100, 120]), np.array([20, 50, 30]), 180.),\n (10, np.array([500]), np.array([30]), 166.6667),\n (10, np.array([20, 10, 20]), np.array([20, 5, 4]), 31.)]\n\n for test in tests:\n c, w, v = test[0], test[2], test[1]\n fast = get_optimal_value(c, w, v)\n slow = get_optimal_value_slow(c, w, v)\n if (fast - slow) <= 10 ** (-3):\n print(c, w, v, 'OK')\n else:\n print(c, w, v, slow, fast)\n break\n\n while True:\n n = np.random.randint(1, 5, 1)[0]\n c = np.random.randint(1, 100, 1)[0]\n w = np.random.randint(1, 100, n)\n v = np.random.randint(1, 100, n)\n fast = get_optimal_value(c, w, v)\n slow = get_optimal_value_slow(c, w, v)\n if (fast - slow) <= 10**(-3):\n print(c, w, v, 'OK')\n else:\n print(c, w, v, slow, fast)\n break","sub_path":"c1/w3/2_maximum_value_of_the_loot/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"431053375","text":"# -*- coding: utf-8 -*-\nimport pygame\n\nclass WeaponFireSprite(pygame.sprite.Sprite):\n def __init__(self, screen, last_direction, x, y):\n super(WeaponFireSprite, self).__init__()\n self.x, self.y = x, y\n self.last_direction = last_direction\n self.screen = screen\n self.left, self.right, self.up, self.down = [], [], [], []\n for i in range(6):\n self.right.append(pygame.image.load(\"./images/enemies/weapon-fire-right_{}.png\".format(i+1)))\n self.left.append(pygame.image.load(\"./images/enemies/weapon-fire-left_{}.png\".format(i+1)))\n self.up.append(pygame.image.load(\"./images/enemies/weapon-fire-up_{}.png\".format(i+1)))\n self.down.append(pygame.image.load(\"./images/enemies/weapon-fire-down_{}.png\".format(i+1)))\n self.index = 0\n self.image = self.right[self.index]\n self.rect = pygame.Rect(self.x, self.y, 32, 32)\n\n def update(self):\n self.index += 1\n if self.index >= len(self.left) * 20:\n self.index = 0\n if self.index % 20 == 0:\n if self.last_direction == 'left':\n self.image = self.left[int(self.index/20)]\n elif self.last_direction == 'right':\n self.image = self.right[int(self.index/20)]\n elif self.last_direction == 'up':\n self.image = self.up[int(self.index/20)]\n elif self.last_direction == 'down':\n self.image = self.down[int(self.index/20)]\n super(WeaponFireSprite, self).update()\n\n# enemy's weapon class (fire)\nclass WeaponFire(pygame.sprite.Group):\n def __init__(self, screen, enemy):\n self.enemy, self.screen = enemy, screen\n self.drawing, self.last_direction = False, self.enemy.face\n if self.last_direction == 'left':\n self.x, self.y = self.enemy.x, self.enemy.y\n elif self.last_direction == 'right':\n self.x, self.y = self.enemy.x + 4, self.enemy.y\n elif self.last_direction == 'up':\n self.x, self.y = self.enemy.x + 2, self.enemy.y\n elif self.last_direction == 'down':\n self.x, self.y = self.enemy.x, self.enemy.y + 4\n self.rect = pygame.Rect(self.x, self.y, 32, 32)\n self.centerx, self.centery = self.rect.center\n self.weapon_fire_sprite = WeaponFireSprite(self.screen, self.last_direction, self.x, self.y)\n super(WeaponFire, self).__init__(self.weapon_fire_sprite)\n\n def draw(self):\n if self.drawing:\n self.screen.blit(self.weapon_fire_sprite.image, [self.x, self.y])\n\n def update(self):\n self.centerx, self.centery = self.rect.center\n if self.drawing:\n if self.last_direction == 'left':\n if self.x >= 2:\n self.x -= 0.5\n elif self.last_direction == 'right':\n if self.x <= 632:\n self.x += 0.5\n elif self.last_direction == 'up':\n if self.y >= 2:\n self.y -= 0.5\n elif self.last_direction == 'down':\n if self.y <= 632:\n self.y += 0.5\n if self.x <= 4 or self.x >= 632 or self.y <= 4 or self.y >= 632:\n self.drawing = False\n self.last_direction = self.enemy.face\n if self.enemy.face == 'left':\n self.x, self.y = self.enemy.x, self.enemy.y\n elif self.enemy.face == 'right':\n self.x, self.y = self.enemy.x + 4, self.enemy.y\n elif self.enemy.face == 'up':\n self.x, self.y = self.enemy.x + 2, self.enemy.y\n elif self.enemy.face == 'down':\n self.x, self.y = self.enemy.x, self.enemy.y + 4\n else:\n self.last_direction = self.enemy.face\n if self.enemy.face == 'left':\n self.x, self.y = self.enemy.x, self.enemy.y\n elif self.enemy.face == 'right':\n self.x, self.y = self.enemy.x + 4, self.enemy.y\n elif self.enemy.face == 'up':\n self.x, self.y = self.enemy.x + 2, self.enemy.y\n elif self.enemy.face == 'down':\n self.x, self.y = self.enemy.x, self.enemy.y + 4\n self.rect = pygame.Rect(self.x, self.y, 32, 32)\n super(WeaponFire, self).update()\n\n","sub_path":"core/weapon_fire.py","file_name":"weapon_fire.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"26336672","text":"##\n# copyright 2009, James William Pye\n# http://python.projects.postgresql.org\n##\n'pg_config Python interface; provides member based access to pg_config data'\nimport sys\nimport os\nimport os.path\nimport subprocess\nimport io\nimport pprint\nimport errno\nfrom itertools import chain\nfrom operator import itemgetter\nfrom . import versionstring\nfrom . import api as pg_api\nfrom . import string as pg_str\nfrom . import exceptions as pg_exc\n\ndef get_command_output(exe, *args):\n\t'helper function for the instance class'\n\tpa = [\n\t\t'--' + x.strip() for x in args if x is not None\n\t]\n\tpa.insert(0, exe)\n\tp = subprocess.Popen(pa,\n\t\tclose_fds = True,\n\t\tstdout = subprocess.PIPE,\n\t\tstderr = subprocess.PIPE,\n\t\tstdin = subprocess.PIPE,\n\t\tshell = False\n\t)\n\tp.stdin.close()\n\t##\n\t# Sigh. Fucking gdb.\n\twhile True:\n\t\ttry:\n\t\t\trv = p.wait()\n\t\t\tbreak\n\t\texcept OSError as e:\n\t\t\tif e.errno != errno.EINTR:\n\t\t\t\traise\n\tif rv != 0:\n\t\treturn None\n\treturn io.TextIOWrapper(p.stdout).read()\n\ndef pg_config_dictionary(pg_config_path):\n\t\"\"\"\n\tCreate a dictionary of the information available in the given\n\tpg_config_path. This provides a one-shot solution to fetching information\n\tfrom the pg_config binary.\n\t\"\"\"\n\tdefault_output = get_command_output(pg_config_path)\n\tif default_output is not None:\n\t\td = {}\n\t\tfor x in default_output.splitlines():\n\t\t\tif not x or x.isspace() or x.find('=') == -1:\n\t\t\t\tcontinue\n\t\t\tk, v = x.split('=', 1)\n\t\t\t# keep it semi-consistent with instance\n\t\t\td[k.lower().strip()] = v.strip()\n\t\treturn d\n\n\t# Support for 8.0 pg_config and earlier.\n\t# This requires three invocations of pg_config:\n\t# First --help, to get the -- options available,\n\t# Second, all the -- options except version.\n\t# Third, --version as it appears to be exclusive.\n\topt = []\n\tfor l in get_command_output(pg_config_path, 'help').splitlines():\n\t\tdash_pos = l.find('--')\n\t\tif dash_pos == -1:\n\t\t\tcontinue\n\t\tsp_pos = l.find(' ', dash_pos)\n\t\t# the dashes are added by the call command\n\t\topt.append(l[dash_pos+2:sp_pos])\n\tif 'help' in opt:\n\t\topt.remove('help')\n\tif 'version' in opt:\n\t\topt.remove('version')\n\n\td=dict(zip(opt, get_command_output(pg_config_path, *opt).splitlines()))\n\td['version'] = get_command_output(pg_config_path, 'version').strip()\n\treturn d\n\ndef parse_configure_options(confopt):\n\tquote = confopt[0]\n\tparts = pg_str.split_using(confopt, quote, sep = ' ')\n\tfor x in parts:\n\t\t# remove the quotes around '--' from option\n\t\tx = x[1:-1].lstrip('-')\n\t\t# if the split fails, the '1' index will\n\t\t# be true, indicating that the flag was given.\n\t\tkv = x.split('=', 1) + [True]\n\t\tyield (kv[0].replace('-','_'), kv[1])\n\ndef platform_binary(path):\n\treturn path\n\nif sys.platform == 'win32':\n\tdef platform_binary(path):\n\t\treturn path + '.exe'\n\ninstallations = {}\nclass Installation(pg_api.Installation):\n\t\"\"\"\n\tClass providing a Python interface to PostgreSQL installation metadata.\n\t\"\"\"\n\tversion = None\n\tversion_info = None\n\ttype = None\n\tconfigure_options = None\n\n\tpg_binaries = (\n\t\t'pg_config',\n\t\t'psql',\n\t\t'initdb',\n\t\t'pg_resetxlog',\n\t\t'pg_controldata',\n\t\t'clusterdb',\n\t\t'pg_ctl',\n\t\t'pg_dump',\n\t\t'pg_dumpall',\n\t\t'postgres',\n\t\t'postmaster',\n\t\t'reindexdb',\n\t\t'vacuumdb',\n\t\t'ipcclean',\n\t\t'createdb',\n\t\t'ecpg',\n\t\t'createuser',\n\t\t'createlang',\n\t\t'droplang',\n\t\t'dropuser',\n\t\t'pg_restore',\n\t)\n\n\tpg_libraries = (\n\t\t'libpq',\n\t\t'libecpg',\n\t\t'libpgtypes',\n\t\t'libecpg_compat',\n\t)\n\n\tpg_config_directories = (\n\t\t'bindir',\n\t\t'docdir',\n\t\t'includedir',\n\t\t'pkgincludedir',\n\t\t'includedir_server',\n\t\t'libdir',\n\t\t'pkglibdir',\n\t\t'localedir',\n\t\t'mandir',\n\t\t'sharedir',\n\t\t'sysconfdir',\n\t)\n\n\tdef _e_metas(self):\n\t\tl = list(self.configure_options.items())\n\t\tl.sort(key = itemgetter(0))\n\t\tyield ('version', self.version)\n\t\tif l:\n\t\t\tyield ('configure_options',\n\t\t\t\t(os.linesep).join((\n\t\t\t\t\tk if v is True else k + '=' + v\n\t\t\t\t\tfor k,v in l\n\t\t\t\t))\n\t\t\t)\n\n\tdef __repr__(self):\n\t\treturn \"{mod}.{name}({path!r})\".format(\n\t\t\tmod = type(self).__module__,\n\t\t\tname = type(self).__name__,\n\t\t\tpath = self.pg_config_path\n\t\t)\n\n\t@staticmethod\n\tdef default_pg_config():\n\t\tpg_config_path = os.environ.get(\n\t\t\t'PGINSTALLATION', ([\n\t\t\t\tos.path.join(x, 'pg_config')\n\t\t\t\tfor x in os.environ.get('PATH', '').split(os.pathsep)\n\t\t\t\tif os.path.exists(os.path.join(x, 'pg_config'))\n\t\t\t] + [None])[0]\n\t\t)\n\t\treturn pg_config_path if (\n\t\t\tpg_config_path and os.path.exists(pg_config_path)\n\t\t) else None\n\n\t@classmethod\n\tdef default(typ):\n\t\tpath = typ.default_pg_config()\n\t\tif path is None:\n\t\t\treturn None\n\t\treturn typ(path)\n\n\tdef __new__(typ, pg_config_path):\n\t\t# One instance for each installation.\n\t\tglobal installations\n\t\tif not os.path.isabs(pg_config_path):\n\t\t\traise ValueError(\"pg_config path is not absolute, {0!r}\".format(\n\t\t\t\tpg_config_path\n\t\t\t))\n\t\tpg_config_path = os.path.realpath(pg_config_path)\n\t\tcurrent = installations.get(pg_config_path)\n\t\tif current is not None:\n\t\t\tpg_config_data = pg_config_dictionary(pg_config_path)\n\t\t\tif current.version == pg_config_data['version']:\n\t\t\t\treturn current\n\t\telse:\n\t\t\tpg_config_data = pg_config_dictionary(pg_config_path)\n\t\trob = super().__new__(typ)\n\t\trob.pg_config_data = pg_config_data\n\t\treturn rob\n\n\tdef __init__(self, pg_config_path):\n\t\tself.version = self.pg_config_data[\"version\"]\n\t\tself.type, vs = self.version.split()\n\t\tself.version_info = versionstring.normalize(versionstring.split(vs))\n\t\tself.configure_options = dict(\n\t\t\tparse_configure_options(self.pg_config_data.get('configure'))\n\t\t)\n\n\t\tbindir_path = self.pg_config_data.get('bindir')\n\t\tlibdir_path = self.pg_config_data.get('libdir')\n\t\tself.paths = {\n\t\t\tk : v for k,v in (\n\t\t\t\t(k, (v if os.path.exists(v) else None)) for k,v in chain(\n\t\t\t\t\t(\n\t\t\t\t\t\t(k, platform_binary(os.path.join(bindir_path, k)))\n\t\t\t\t\t\tfor k in self.pg_binaries\n\t\t\t\t\t),\n\t\t\t\t\t(\n\t\t\t\t\t\t(k, self.pg_config_data[k]) for k in\n\t\t\t\t\t\tself.pg_config_directories if k in self.pg_config_data\n\t\t\t\t\t),\n\t\t\t\t)\n\t\t\t)\n\t\t}\n\t\tppg_config = self.paths.get('pg_config')\n\t\tif ppg_config is not None:\n\t\t\tself.pg_config_path = ppg_config\n\t\telse:\n\t\t\tself.pg_config_path = pg_config_path\n\t\tinstallations[self.pg_config_path] = self\n\n\tdef __dir__(self):\n\t\treturn list(set(chain(\n\t\t\tself.paths.keys(),\n\t\t\tdir(super()),\n\t\t)))\n\n\t@property\n\tdef ssl(self):\n\t\treturn 'with_openssl' in self.configure_options\n\n\tdef __getattr__(self, attname):\n\t\ttry:\n\t\t\treturn getattr(super(), attname)\n\t\texcept AttributeError:\n\t\t\tif attname in self.paths:\n\t\t\t\treturn self.paths[attname]\n\t\t\traise\n\nif __name__ == '__main__':\n\ti = Installation(pg_config_path = sys.argv[1])\n\tfrom .python.element import format_element\n\tprint(format_element(i))\n","sub_path":"postgresql/installation.py","file_name":"installation.py","file_ext":"py","file_size_in_byte":6489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"638560867","text":"\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n\ndir = 'cifar-10-batches-py'\ndict = unpickle(dir + '/data_batch_1')\nx = dict[b'data']\ny = dict[b'labels']\n\n","sub_path":"cifar_detector.py","file_name":"cifar_detector.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"482537423","text":"\"\"\"\r\nsplit all json to validating dataset and training dataset\r\n将全部文件分成训练集和测试集两部分,会移动测试集文件到指定文件夹\r\n\"\"\"\r\n\r\n# public\r\nimport os\r\nimport re\r\nimport random\r\nimport shutil\r\n\r\n\r\ndef split(path_work: str, path_out: str, prob: float=0.1):\r\n\r\n if not os.path.exists(path_work):\r\n raise NotADirectoryError(\"{} not a directory\".format(path_work))\r\n\r\n if not os.path.exists(path_out):\r\n raise NotADirectoryError(\"{} not a directory\".format(path_out))\r\n\r\n for idx_anno, name_anno in \\\r\n enumerate([file for file in os.listdir(path_work) if \"annotation\" in file]):\r\n num = random.randint(0, 100)\r\n if num > int(100 * (1-prob)):\r\n print(name_anno, \"bingo!\")\r\n # move\r\n path_anno = os.path.join(path_work, name_anno)\r\n name_meta = re.sub(\"annotation\", \"meta\", name_anno)\r\n path_meta = os.path.join(path_work, name_meta)\r\n shutil.move(path_anno, os.path.join(path_out, name_anno))\r\n shutil.move(path_meta, os.path.join(path_out, name_meta))\r\n else:\r\n print(name_anno)\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n random.seed(2)\r\n split(path_work=\"I:\\\\GIST\\\\annos\", path_out=\"I:\\\\GIST\\\\annos\\\\val\", prob=0.2)\r\n\r\n print(\"End.\")\r\n","sub_path":"datasets/gist/split.py","file_name":"split.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"579588856","text":"from django.shortcuts import render, get_object_or_404\n\nfrom .models import Product, ProductImage\n\ndef home(request):\n\tcontext = {}\n\n\tproducts = Product.objects.all()\n\tcontext['products'] = products\n\t#if request.user.is_authenticated():\n\t#\tcontext = {'user': request.user}\n\t#contect = locals() #all variables in local function home available\n\ttemplate = 'products/home.html'\n\treturn render(request, template, context)\n\ndef search(request):\n\tcontext = {}\n\ttemplate = 'products/home.html'\n\ttry:\n\t\tq = request.GET.get('q')\n\texcept:\n\t\tq = None\n\tcontext['query'] = q\n\tif q:\n\t\tcontext['products'] = Product.objects.filter(title__icontains=q)\n\t\ttemplate = 'products/results.html'\n\treturn render(request, template, context)\n\ndef all(request):\n\tproducts = Product.objects.all()\n\tcontext = {'products': products}\n\ttemplate = 'products/all.html'\n\treturn render(request, template, context)\n\ndef single(request, slug):\n\tproduct = get_object_or_404(Product, slug=slug)\n\timages = ProductImage.objects.filter(product=product)\n\tcontext = {'product': product, 'images': images}\n\ttemplate = 'products/single.html'\n\treturn render(request, template, context)","sub_path":"src/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"237722302","text":"from func_Astar import *\nfrom gridworld import Gridworld\n\n\nclass Repeated_Astar():\n \"\"\"\n Create a Repeated A* agent with the given unexplored maze, dimension, start, and goal cell.\n Parameters:\n ----------\n dim : Dimension of the gridworld as a int.\n start : cell to start from.\n goal : goal cell to search for.\n maze: An (dim) * (dim) unexplored maze.\n\n Returns:\n -------\n agent: Unexplored Gridworld as a 2-D cell array. Dimension is (dim) * (dim).\n The knowledge of the agent increases as it explored through the maze to find path between the start and goal cell.\n \"\"\"\n def __init__(self, dim: int, start: list, goal: list, maze: Gridworld, backtrack: bool = False, flag: int = 0):\n self._dim = dim\n self._start = start\n self._goal = goal\n self._maze = maze\n # Create an unblocked gridworld\n self._knowledge = Gridworld(self._dim, 0.0)\n self._backtrack = backtrack\n self._flag = flag\n\n def backtrack(self, current: Cell) -> Cell:\n \"\"\"\n This function is designed for Q8. \n When the agent walk to the end of a hallway, it would backtrack to the other end.\n Therefore we would get to a better point restarting the A* search.\n \n Returns:\n -------\n restart_cell: Returns a cell that is not in the hallway.\n \"\"\"\n trajectory_backtrack = 1\n while current.get_parent() is not None:\n blocked_neighbors_count = current.get_no_of_blocked_neighbors()\n neibors_count = current.get_no_of_neighbors()\n if 4 - neibors_count + blocked_neighbors_count >= 2:\n current = current.get_parent()\n else:\n return current, trajectory_backtrack\n trajectory_backtrack += 1\n return current, trajectory_backtrack\n \n def is_end_of_hallway(self, current: Cell) -> bool:\n \"\"\"\n This function is designed for Q8.\n It returns True if the agent walk to the end of a hallway.\n Otherwise, False.\n \"\"\"\n\n blocked_neighbors_count = current.get_no_of_blocked_neighbors()\n neibors_count = current.get_no_of_neighbors()\n if 4 - neibors_count + blocked_neighbors_count >= 3:\n return True\n else:\n return False\n\n def path_walker(self, path: list):\n \"\"\"\n This function checks whether the path has any blocked cell. If the cell is not blocked, we will update the unexplored \n maze and add this cell to out knowledge grid.\n \n Returns:\n -------\n blocked cell, status_string: Returns the parent of the blocked cell, if a blocked cell present in the path, along with a status string to indicate.\n If no blocked cell is found the return None.\n \"\"\"\n trajectory = -1\n while path:\n current = path.pop()\n if self._maze.get_cell(current.x, current.y).get_flag() == 1:\n return current.get_parent(), 'blocked', trajectory\n trajectory += 1\n\n children = current.get_children()\n for child in children:\n self._knowledge.update_cell(self._maze.get_cell(child[0], child[1]), \n child[0], child[1])\n return None, 'unblocked', trajectory\n \n def path_walker_backtrack(self, path: list):\n \"\"\"\n This function checks whether the path has any blocked cell. If the cell is not blocked, we will update the unexplored \n maze and add this cell to out knowledge grid.\n\n If the cell is blocked and the agent is at the end of a hallway, it will backtrack to the nearest exit.\n \n Returns:\n -------\n blocked cell, status_string: Returns the parent of the blocked cell, if a blocked cell present in the path, along with a status string to indicate.\n If no blocked cell is found the return None.\n \"\"\"\n trajectory = -1\n while path:\n current = path.pop()\n if self._maze.get_cell(current.x, current.y).get_flag() == 1:\n current = current.get_parent()\n if current.get_parent() is not None and self.is_end_of_hallway(current):\n current, trajectory_backtrack = self.backtrack(current.get_parent())\n return current, 'blocked', trajectory + trajectory_backtrack\n else:\n return current, 'blocked', trajectory\n trajectory += 1\n\n children = current.get_children()\n blocked_neighbors_count = 0\n for child in children:\n child_cell = self._maze.get_cell(child[0], child[1])\n self._knowledge.update_cell(child_cell, child[0], child[1])\n if child_cell.get_flag() == 1:\n blocked_neighbors_count += 1\n current.update_no_of_neighbors(len(children))\n current.update_no_of_blocked_neighbors(blocked_neighbors_count)\n return None, 'unblocked', trajectory\n\n def generate_path(self, current) -> list:\n \"\"\"\n This function will help the agent to find the path between current and their parent cell.\n \n Returns:\n -------\n path: Returns a path between the current cell and it's parent until the hightes hierarchical parent is found.\n \"\"\"\n path = []\n path.append(current)\n while current.get_parent() is not None:\n current = current.get_parent()\n path.append(current)\n return path\n\n def find_path(self):\n \"\"\"\n Main function which will help the agent to find the path between start and goal cell.\n \n Returns:\n -------\n path, status_string: Returns a path between the start and goal node if found, otherwise will return None.\n The status string indicates if the solution is found or not.\n \"\"\"\n start_cell = Cell(self._start[0], self._start[1], 0, self._dim, None, self._flag)\n overall_trajectory = 0\n while True:\n goal_cell, status = func_Astar(start_cell, self._goal, self._knowledge, self._dim, self._flag)\n if status == 'no_solution':\n return None, 'no_solution', overall_trajectory\n path = self.generate_path(goal_cell)\n if self._backtrack:\n start_cell, node_status, trajectory = self.path_walker_backtrack(path)\n else:\n start_cell, node_status, trajectory = self.path_walker(path)\n overall_trajectory += trajectory\n if node_status == 'unblocked':\n return self.generate_path(goal_cell), 'solution', overall_trajectory","sub_path":"repeated_Astar.py","file_name":"repeated_Astar.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"580683625","text":"from __future__ import print_function\nfrom mailmerge import MailMerge\n\n\n\ndocfile='resume_maker/my_resume.docx'\n\ndocument = MailMerge(template)\nprint(document.get_merge_fields())\n\ndocument.merge(\n test='test sucess'\n )\n\ndocument.write('test-output.docx')","sub_path":"ondemandservices-master/resume_maker/maker.py","file_name":"maker.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"194030207","text":"from tkinter import *\nfrom tkinter.messagebox import showerror\n\n\n\n\n\ndef Mot(event):\n \n p = int(entre_valeur3.get())\n mot = str(entre_valeur1.get())\n mot_cesar = ''\n entre_valeur2.delete(0,END)\n\n for k in range (0,len(mot)):\n\n if 232 <= ord(mot[k]) <= 235:\n ltte = ord('e')+p\n mot_cesar = mot_cesar + chr(ltte)\n \n elif mot[k] == \"?\":\n mot_cesar = mot_cesar + \"\"\n\n elif mot[k] == \"!\":\n mot_cesar = mot_cesar + \"\"\n\n elif mot[k] == \",\":\n mot_cesar = mot_cesar + \"\"\n\n elif mot[k] == \" \":\n mot_cesar = mot_cesar + ' '\n\n elif mot[k] == \"à\":\n ltta = ord('a')+p\n mot_cesar = mot_cesar + chr(ltta)\n\n elif mot[k] == \"'\":\n mot_cesar = mot_cesar + \"'\"\n \n elif ord(mot[k]) >122-p :\n xyz = ord(mot[k]) - 26+p\n mot_cesar = mot_cesar + chr (xyz)\n\n elif ord(mot[k])>=65 and ord(mot[k])<=90:\n maj = ord(mot[k])+32\n \n if maj>122-p:\n mot_cesar = mot_cesar + chr((maj-(26-p)))\n else:\n mot_cesar = mot_cesar + chr((maj+p))\n\n\n elif 39 <= ord(mot[k]) <= 47 :\n mot_cesar = mot_cesar + \"\"\n \n else:\n position_cesar = ord(mot[k]) + p\n mot_cesar = mot_cesar + chr(position_cesar)\n \n entre_valeur2.insert(0,mot_cesar)\n\n \n\n\ndef Lettre(event):\n \n p = int(entre_valeur3.get())\n mot_cesar = str(entre_valeur2.get())\n mot = ''\n entre_valeur1.delete(0,END)\n\n for k in range (0,len(mot_cesar)):\n\n if 232 <= ord(mot[k]) <= 235:\n ltte = ord('e')+p\n mot_cesar = mot_cesar + chr(ltte)\n\n elif mot_cesar[k] == \"?\":\n mot = mot + \"\"\n\n elif mot_cesar[k] == \",\":\n mot = mot + \"\"\n\n elif mot_cesar[k] == \"!\":\n mot = mot + \"\"\n\n elif mot_cesar[k] == \" \":\n mot = mot + ' '\n\n elif mot_cesar[k] == \"'\":\n mot = mot + \"'\"\n\n elif mot_cesar[k] == \"à\":\n ltta = ord('a')-p\n mot = mot + chr(ltta)\n\n elif ord(mot_cesar[k])>=65 and ord(mot_cesar[k])<=90:\n maj = ord(mot_cesar[k])+32\n \n if maj<97+p:\n mot = mot + chr((maj+(26-p)))\n else:\n mot = mot + chr((maj-p))\n\n elif ord(mot_cesar[k]) <97+p :\n xyz = ord(mot_cesar[k]) + 26-p\n mot = mot + chr (xyz)\n\n elif 39 <= ord(mot_cesar[k]) <= 47 :\n mot_cesar = mot_cesar + \"\"\n\n else:\n position = ord(mot_cesar[k]) - p\n mot = mot + chr(position)\n\n entre_valeur1.insert(0,mot)\n\n\n\n\ndef suppr(event):\n \n entre_valeur1.delete(0,END)\n entre_valeur2.delete(0,END)\n\n\n\ndef décallage(event):\n global affichage7\n\n if int(entre_valeur3.get()) == 3:\n affichage1.grid(row=0,column=1,sticky=N+S)\n affichage2.grid(row=1,column=1,sticky=N+S)\n affichage4.grid(row=0,column=2,sticky=N+S)\n affichage5.grid(row=1,column=2,sticky=N+S)\n \n \n entre_valeur1.grid(row=0,column=3,sticky=E+W+N+S)\n entre_valeur2.grid(row=1,column=3,sticky=E+W+N+S)\n affichage3.grid_forget()\n affichage6.grid_forget()\n entre_valeur3.grid_forget()\n \n affichage7 = Label(cadre,text=\"Ceci est le code 'César'\",font='arial 9')\n affichage7.grid(row=2,column=1,columnspan=3,sticky=N+S)\n\n bouton.grid(row=2,column=3,sticky=E)\n\n elif 0<=int(entre_valeur3.get())>=26:\n error2()\n \n else:\n affichage1.grid(row=0,column=1,sticky=N+S)\n affichage2.grid(row=1,column=1,sticky=N+S)\n affichage4.grid(row=0,column=2,sticky=N+S)\n affichage5.grid(row=1,column=2,sticky=N+S)\n \n \n entre_valeur1.grid(row=0,column=3,sticky=E+W+N+S)\n entre_valeur2.grid(row=1,column=3,sticky=E+W+N+S)\n affichage3.grid_forget()\n affichage6.grid_forget()\n entre_valeur3.grid_forget()\n \n affichage7 = Label(cadre,text='Le décalage est de' + ' ' + entre_valeur3.get() + ' '+'lettres.',font='arial 9')\n affichage7.grid(row=2,column=1,columnspan=3,sticky=N+S)\n \n\n bouton.grid(row=2,column=3,sticky=E)\n\n\n\ndef error():\n showerror('Erreur',\"Veuillez n'utiliser que des minuscules. Cordialement, la direction\")\n \ndef error2():\n showerror('Erreur','Veuillez choisir un décalage entre 1 et 26. Cordialement, la direction')\n \n\n\ndef reset():\n global affichage7\n\n entre_valeur3.delete(0,END)\n entre_valeur1.delete(0,END)\n entre_valeur2.delete(0,END)\n \n affichage1.grid_forget()\n affichage2.grid_forget()\n affichage4.grid_forget()\n affichage5.grid_forget()\n affichage7.grid_forget()\n bouton.grid_forget()\n \n \n entre_valeur1.grid_forget()\n entre_valeur2.grid_forget()\n\n affichage3.grid(row=1,column=1)\n affichage6.grid(row=1,column=2)\n entre_valeur3.grid(row=1,column=3)\n\n \n\n\n\n\n\ncadre = Tk()\ncadre.title(\"Traducteur\")\ncadre.resizable(width=False, height=False)\n\n\n\n\n\naffichage1 = Label(cadre,text='Mot',font=\"arial 10 bold\")\n\naffichage2 = Label(cadre,text='Mot avec décalage',font=\"arial 10 bold\")\n\naffichage3 = Label(cadre,text='Veuillez entrer un décalage',font=\"arial 10 bold\")\naffichage3.grid(row=1,column=0,sticky=N+S)\n\naffichage4 = Label(cadre,text=':',font=\"arial 10 bold\")\n\naffichage5 = Label(cadre,text=':',font=\"arial 10 bold\")\n\naffichage6 = Label(cadre,text=':',font=\"arial 10 bold\")\naffichage6.grid(row=1,column=1,sticky=N+S)\n\nentre_valeur1 = Entry(cadre,width=30,font=\"arial 10 bold\")\nentre_valeur1.config(bg='bisque')\n\nentre_valeur2 = Entry(cadre,width=9,font=\"arial 10 bold\")\nentre_valeur2.config(bg='bisque')\n\nentre_valeur3 = Entry(cadre,width=9,font=\"arial 10 bold\")\nentre_valeur3.grid(row=1,column=3,sticky=E+W+N+S)\nentre_valeur3.config(bg='bisque')\n\nbouton = Button(cadre,text='RESET',bg='white',fg='red',command=reset)\n\n\n\nentre_valeur1.bind(\"\",Mot)\nentre_valeur2.bind(\"\",Lettre)\nentre_valeur1.bind(\"\",suppr)\nentre_valeur2.bind(\"\",suppr)\nentre_valeur3.bind(\"\",décallage)\n\n\n\n\ncadre.mainloop()\n","sub_path":"Traducteur décalage.py","file_name":"Traducteur décalage.py","file_ext":"py","file_size_in_byte":6275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"318463936","text":"import webapp2\nfrom api.base import BaseHandler\nfrom api import user_service, venue_service\n\n\n\nclass HomeHandler(BaseHandler):\n def get(self):\n self.redirect('/webclient')\n\n\n\n#ERROR HANDLERS\n\ndef handle_404(request, response, exception):\n response.write('Oops! I could swear this page was here! go back')\n response.set_status(404)\n\ndef handle_500(request, response, exception):\n response.write('A server error occurred!')\n response.set_status(500)\n\n\nconfig = {\n 'webapp2_extras.sessions': {\n 'secret_key': 'muvedo-is-art-09-2007',\n 'cookie_args':{'max_age':31622400}\n }\n}\n\napp = webapp2.WSGIApplication([\n ('/', HomeHandler),\n ('/access/passport', user_service.AccessPassportHandler),\n ('/access/request', user_service.AccessRequestHandler),\n ('/access/verify', user_service.AccessVerifyHandler),\n ('/service/venue', venue_service.VenueHandler)\n], debug=True, config=config)\n\n\napp.error_handlers[404] = handle_404\napp.error_handlers[500] = handle_500","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"482492494","text":"\"\"\"miscellany pgctl functions\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport json\nimport os\n\nfrom frozendict import frozendict\n\nfrom .errors import LockHeld\n\n\ndef exec_(argv, env=None): # never returns\n \"\"\"Wrapper to os.execv which runs any atexit handlers (for coverage's sake).\n Like os.execv, this function never returns.\n \"\"\"\n if env is None:\n env = os.environ\n\n # in python3, sys.exitfunc has gone away, and atexit._run_exitfuncs seems to be the only pubic-ish interface\n # https://hg.python.org/cpython/file/3.4/Modules/atexitmodule.c#l289\n import atexit\n atexit._run_exitfuncs() # pylint:disable=protected-access\n os.execvpe(argv[0], argv, env)\n\n\ndef uniq(iterable):\n \"\"\"remove duplicates while preserving ordering -- first one wins\"\"\"\n return tuple(_uniq(iterable))\n\n\ndef _uniq(iterable):\n seen = set()\n for i in iterable:\n if i in seen:\n pass\n else:\n yield i\n seen.add(i)\n\n\nclass JSONEncoder(json.JSONEncoder):\n \"\"\"knows that frozendict is like dict\"\"\"\n\n def default(self, obj): # pylint:disable=method-hidden\n if isinstance(obj, frozendict):\n return dict(obj)\n else:\n # Let the base class default method raise the TypeError\n return json.JSONEncoder.default(self, obj)\n\n\ndef bestrelpath(path, relto=None):\n if relto is None:\n from os import getcwd\n relto = getcwd()\n from os.path import relpath\n relpath = relpath(path, relto)\n if len(relpath) < len(path):\n return relpath\n else:\n return path\n\n\ndef lsof(path):\n from subprocess import STDOUT, Popen, PIPE\n cmd = 'lsof -tau $(whoami) {} | xargs -r ps -fj'.format(path)\n p = Popen(('sh', '-c', cmd), stdout=PIPE, stderr=STDOUT)\n stdout, _ = p.communicate()\n if stdout.count('\\n') > 1:\n return stdout\n else:\n # race condition: we only got the ps -f header\n return ''\n\n\ndef check_lock(path):\n locks = lsof(path)\n if locks:\n raise LockHeld(\n '''\\\nThe supervisor has stopped, but these processes did not:\n%s\ntemporary fix: lsof -t %s | xargs kill -9\npermanent fix: http://pgctl.readthedocs.org/en/latest/user/quickstart.html#writing-playground-services\n''' % (locks, bestrelpath(path))\n )\n else:\n pass\n\n\ndef commafy(items):\n return ', '.join(str(x) for x in items)\n","sub_path":"pgctl/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"224013363","text":"import datetime\n\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.http import Http404\nfrom django.urls import reverse_lazy\nfrom django.views.generic import TemplateView, ListView, CreateView, UpdateView, DeleteView, DetailView\n\nfrom CargoDelivery import settings\nfrom apps.company.models import Company\nfrom apps.main.forms import OrderForm, ApplicationForm, OrderCreationForm\nfrom apps.main.models import Order, Sending, Application, Warehouse, Transport\n\n\nclass MainPageView(TemplateView):\n \"\"\"\n View for main page of site\n \"\"\"\n template_name = 'main/index.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n\nclass CompanyList(ListView):\n \"\"\"\n View for list all transport companies\n \"\"\"\n model = Company\n paginate_by = settings.PAGINATION_SIZE\n template_name = 'company/../../templates/main/companies.html'\n\n\nclass CompanyDetail(DetailView):\n \"\"\"\n View for details of transport company\n \"\"\"\n model = Company\n template_name = 'company/../../templates/main/company_detail.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['warehouses'] = Warehouse.objects.filter(company=self.object)\n context['cars'] = Transport.objects.filter(company=self.object, transport_type='CAR')\n context['trains'] = Transport.objects.filter(company=self.object, transport_type='TRAIN')\n context['planes'] = Transport.objects.filter(company=self.object, transport_type='PLANE')\n context['ships'] = Transport.objects.filter(company=self.object, transport_type='SHIP')\n context['sendings'] = Sending.objects.filter(company=self.object)\n\n return context\n\n\nclass OrderList(LoginRequiredMixin, ListView):\n \"\"\"\n View for list of all orders, created by user\n \"\"\"\n model = Order\n paginate_by = settings.PAGINATION_SIZE\n\n template_name = 'main/orders.html'\n\n def get_queryset(self):\n \"\"\"\n Show only orders of user\n :return:\n \"\"\"\n try:\n queryset = Order.objects.filter(user=self.request.user)\n except Exception:\n raise Http404\n else:\n return queryset\n\n\nclass CreateOrder(LoginRequiredMixin, CreateView):\n \"\"\"\n View for creation of order\n (for users)\n \"\"\"\n model = Order\n template_name = 'main/forms/create_form.html'\n form_class = OrderCreationForm\n login_url = 'login/'\n success_url = reverse_lazy('main:orders')\n\n def get_form_kwargs(self):\n kwargs = super(CreateOrder, self).get_form_kwargs()\n kwargs['user'] = self.request.user\n return kwargs\n\n def form_valid(self, form):\n \"\"\"\n Set user as request.user\n :param form:\n :return:\n \"\"\"\n form.instance.user = self.request.user\n return super().form_valid(form)\n\n\nclass UpdateOrder(LoginRequiredMixin, UpdateView):\n \"\"\"\n View for updating of order\n (for users)\n \"\"\"\n model = Order\n template_name = 'main/forms/update_form.html'\n form_class = OrderForm\n login_url = 'login/'\n success_url = reverse_lazy('main:orders')\n\n def form_valid(self, form):\n \"\"\"\n Set user as request.user\n :param form:\n :return:\n \"\"\"\n form.instance.user = self.request.user\n return super().form_valid(form)\n\n\nclass DeleteOrder(LoginRequiredMixin, DeleteView):\n \"\"\"\n View for deleting orders\n (for users)\n \"\"\"\n model = Order\n template_name = 'main/forms/delete_form.html'\n success_url = reverse_lazy('main:orders')\n\n\nclass OrderSendings(LoginRequiredMixin, DetailView):\n \"\"\"\n View for matching sendings for order\n \"\"\"\n model = Order\n\n template_name = 'main/order_sendings.html'\n\n def get_context_data(self, **kwargs):\n \"\"\"\n :param kwargs:\n :return: context, with sendings appropriate for order\n \"\"\"\n context = super().get_context_data(**kwargs)\n try:\n application = Application.objects.get(order=self.object)\n except Exception:\n matching_sendings = Sending.objects.filter(\n departure_warehouse__city=self.object.departure_city,\n arrival_warehouse__city=self.object.arrival_city,\n departure_date=self.object.departure_date)\n\n near_matching_sendings = Sending.objects.filter(\n departure_warehouse__city=self.object.departure_city,\n arrival_warehouse__city=self.object.arrival_city,\n departure_date__gte=self.object.departure_date - datetime.timedelta(\n days=7),\n departure_date__lte=self.object.departure_date + datetime.timedelta(\n days=7)).difference(matching_sendings)\n\n context['sendings'] = matching_sendings\n context['near_sendings'] = near_matching_sendings\n else:\n context['application'] = application\n return context\n\n\nclass CreateApplication(LoginRequiredMixin, CreateView):\n \"\"\"\n View for creation of application\n (for users)\n \"\"\"\n model = Application\n template_name = 'main/forms/create_application_form.html'\n form_class = ApplicationForm\n login_url = 'login/'\n success_url = reverse_lazy('main:applications')\n\n def form_valid(self, form):\n \"\"\"\n Substitution of selected order and sending\n :param form:\n :return:\n \"\"\"\n form.instance.order = Order.objects.get(pk=self.kwargs['order_pk'])\n form.instance.sending = Sending.objects.get(pk=self.kwargs['sending_pk'])\n if self.request.user == form.instance.order.user:\n return super().form_valid(form)\n else:\n raise Http404('You can not do it')\n\n\nclass ApplicationList(LoginRequiredMixin, ListView):\n \"\"\"\n View for list all applications\n (for users)\n \"\"\"\n model = Application\n paginate_by = settings.PAGINATION_SIZE\n\n template_name = 'main/applications.html'\n\n def get_queryset(self):\n \"\"\"\n Show only orders of user\n :return:\n \"\"\"\n try:\n queryset = Application.objects.filter(order__user=self.request.user)\n except Exception:\n raise Http404\n else:\n return queryset\n\n\nclass DeleteApplication(LoginRequiredMixin, DeleteView):\n \"\"\"\n View for deleting application\n (for users)\n \"\"\"\n model = Application\n template_name = 'main/forms/delete_application_form.html'\n success_url = reverse_lazy('main:orders')\n\n def delete(self, request, *args, **kwargs):\n \"\"\"\n on delete of application order deletes from sending\n :param request:\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n self.object = self.get_object()\n if self.object.status == 'CONF':\n order = self.object.order\n sending = self.object.sending\n sending.orders.remove(order)\n sending.save()\n return super(DeleteApplication, self).delete(request, *args, **kwargs)\n","sub_path":"apps/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"457570979","text":"# coding=utf-8\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\n\nfrom abc import ABCMeta, abstractmethod as abstract_method\nfrom json.encoder import JSONEncoder as BaseJsonEncoder\n\nfrom six import with_metaclass\n\n\nclass JsonSerializable(with_metaclass(ABCMeta)):\n \"\"\"\n Interface for classes that can be safely converted to JSON.\n \"\"\"\n @abstract_method\n def as_json_compatible(self):\n \"\"\"\n Returns a JSON-compatible representation of the object.\n\n References:\n - :py:class:`iota.json.JsonEncoder`.\n \"\"\"\n raise NotImplementedError(\n 'Not implemented in {cls}.'.format(cls=type(self).__name__),\n )\n\n def _repr_pretty_(self, p, cycle):\n \"\"\"\n Makes JSON-serializable objects play nice with IPython's default\n pretty-printer.\n\n Sadly, :py:func:`pprint.pprint` does not have a similar mechanism.\n\n References:\n - http://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html\n - :py:meth:`IPython.lib.pretty.RepresentationPrinter.pretty`\n - :py:func:`pprint._safe_repr`\n \"\"\"\n # type: (JsonSerializable, bool) -> Text\n class_name = type(self).__name__\n\n if cycle:\n p.text('{cls}(...)'.format(\n cls = class_name,\n ))\n else:\n with p.group(len(class_name)+1, '{cls}('.format(cls=class_name), ')'):\n p.pretty(self.as_json_compatible())\n\n\n# noinspection PyClassHasNoInit\nclass JsonEncoder(BaseJsonEncoder):\n \"\"\"\n JSON encoder with support for :py:class:`JsonSerializable`.\n \"\"\"\n def default(self, o):\n if isinstance(o, JsonSerializable):\n return o.as_json_compatible()\n\n return super(JsonEncoder, self).default(o)\n","sub_path":"src/iota/json.py","file_name":"json.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"604990461","text":"#coding=utf-8\n__date__ = ' 10:47'\n__author__ = 'sixkery'\n\nimport jieba\nimport wordcloud\nfrom scipy.misc import imread\n\ncomment = []\nwith open('data_new.txt','r',encoding='utf-8') as f:\n for item in f.readlines():\n comment.append(item.split(',')[2].replace('\\n',''))\n\n\ncomment_ci = jieba.lcut(str(comment),cut_all=False)\ntxt = ' '.join(comment_ci)\nw = wordcloud.WordCloud(font_path='msyh.ttc',width=1000,max_font_size=100,font_step=2,\n height=700,max_words=600,stopwords={'content','contemt','电影','剧情','有点'})\n\nw.generate(txt)\nw.to_file('词云图.jpg')","sub_path":"词云图分析.py","file_name":"词云图分析.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"569168390","text":"import App\n\ndef CreateAI(pShip, sTargetName):\n\n\t#########################################\n\t# Creating PlainAI CircleTarget at (50, 86)\n\tpCircleTarget = App.PlainAI_Create(pShip, \"CircleTarget\")\n\tpCircleTarget.SetScriptModule(\"CircleObject\")\n\tpCircleTarget.SetInterruptable(1)\n\tpScript = pCircleTarget.GetScriptInstance()\n\tpScript.SetFollowObjectName(sTargetName)\n\tpScript.SetNearFacingVector(App.TGPoint3_GetModelLeft())\n\tpScript.SetRoughDistances(fNearDistance = 200, fFarDistance = 250)\n\tpScript.SetCircleSpeed(fSpeed = 1.0)\n\t# Done creating PlainAI CircleTarget\n\t#########################################\n\t#########################################\n\t# Creating ConditionalAI WarbirdsInOurSet at (52, 139)\n\t## Conditions:\n\t#### Condition WarbirdsInSet\n\tpWarbirdsInSet = App.ConditionScript_Create(\"Conditions.ConditionAllInSameSet\", \"ConditionAllInSameSet\", pShip.GetName(), \"Warbird 1\", \"Warbird 2\")\n\t## Evaluation function:\n\tdef EvalFunc(bWarbirdsInSet):\n\t\tACTIVE = App.ArtificialIntelligence.US_ACTIVE\n\t\tDORMANT = App.ArtificialIntelligence.US_DORMANT\n\t\tDONE = App.ArtificialIntelligence.US_DONE\n\t\tif not bWarbirdsInSet:\n\t\t\treturn DONE\n\t\treturn ACTIVE\n\t## The ConditionalAI:\n\tpWarbirdsInOurSet = App.ConditionalAI_Create(pShip, \"WarbirdsInOurSet\")\n\tpWarbirdsInOurSet.SetInterruptable(1)\n\tpWarbirdsInOurSet.SetContainedAI(pCircleTarget)\n\tpWarbirdsInOurSet.AddCondition(pWarbirdsInSet)\n\tpWarbirdsInOurSet.SetEvaluationFunction(EvalFunc)\n\t# Done creating ConditionalAI WarbirdsInOurSet\n\t#########################################\n\t#########################################\n\t# Creating PreprocessingAI Cloak at (54, 187)\n\t## Setup:\n\timport AI.Preprocessors\n\tpScript = AI.Preprocessors.CloakShip(1)\n\t## The PreprocessingAI:\n\tpCloak = App.PreprocessingAI_Create(pShip, \"Cloak\")\n\tpCloak.SetInterruptable(1)\n\tpCloak.SetPreprocessingMethod(pScript, \"Update\")\n\tpCloak.SetContainedAI(pWarbirdsInOurSet)\n\t# Done creating PreprocessingAI Cloak\n\t#########################################\n\t#########################################\n\t# Creating PlainAI CircleTarget_2 at (149, 86)\n\tpCircleTarget_2 = App.PlainAI_Create(pShip, \"CircleTarget_2\")\n\tpCircleTarget_2.SetScriptModule(\"CircleObject\")\n\tpCircleTarget_2.SetInterruptable(1)\n\tpScript = pCircleTarget_2.GetScriptInstance()\n\tpScript.SetFollowObjectName(sTargetName)\n\tpScript.SetNearFacingVector(App.TGPoint3_GetModelLeft())\n\tpScript.SetRoughDistances(fNearDistance = 200, fFarDistance = 250)\n\tpScript.SetCircleSpeed(fSpeed = 1.0)\n\t# Done creating PlainAI CircleTarget_2\n\t#########################################\n\t#########################################\n\t# Creating ConditionalAI ShortTimer at (146, 141)\n\t## Conditions:\n\t#### Condition TimerA\n\tpTimerA = App.ConditionScript_Create(\"Conditions.ConditionTimer\", \"ConditionTimer\", 10)\n\t## Evaluation function:\n\tdef EvalFunc(bTimerA):\n\t\tACTIVE = App.ArtificialIntelligence.US_ACTIVE\n\t\tDORMANT = App.ArtificialIntelligence.US_DORMANT\n\t\tDONE = App.ArtificialIntelligence.US_DONE\n\t\tif bTimerA:\n\t\t\treturn DONE\n\t\treturn ACTIVE\n\t## The ConditionalAI:\n\tpShortTimer = App.ConditionalAI_Create(pShip, \"ShortTimer\")\n\tpShortTimer.SetInterruptable(1)\n\tpShortTimer.SetContainedAI(pCircleTarget_2)\n\tpShortTimer.AddCondition(pTimerA)\n\tpShortTimer.SetEvaluationFunction(EvalFunc)\n\t# Done creating ConditionalAI ShortTimer\n\t#########################################\n\t#########################################\n\t# Creating PreprocessingAI Cloak_2 at (148, 190)\n\t## Setup:\n\timport AI.Preprocessors\n\tpScript = AI.Preprocessors.CloakShip(1)\n\t## The PreprocessingAI:\n\tpCloak_2 = App.PreprocessingAI_Create(pShip, \"Cloak_2\")\n\tpCloak_2.SetInterruptable(1)\n\tpCloak_2.SetPreprocessingMethod(pScript, \"Update\")\n\tpCloak_2.SetContainedAI(pShortTimer)\n\t# Done creating PreprocessingAI Cloak_2\n\t#########################################\n\t#########################################\n\t# Creating PlainAI Call_KlingonsDecloak at (272, 80)\n\tpCall_KlingonsDecloak = App.PlainAI_Create(pShip, \"Call_KlingonsDecloak\")\n\tpCall_KlingonsDecloak.SetScriptModule(\"RunScript\")\n\tpCall_KlingonsDecloak.SetInterruptable(1)\n\tpScript = pCall_KlingonsDecloak.GetScriptInstance()\n\tpScript.SetScriptModule(\"Maelstrom.Episode2.E2M0.E2M0\")\n\tpScript.SetFunction(\"KlingonsDecloak\")\n\tpScript.SetArguments(None)\n\t# Done creating PlainAI Call_KlingonsDecloak\n\t#########################################\n\t#########################################\n\t# Creating PlainAI InterceptTarget at (358, 119)\n\tpInterceptTarget = App.PlainAI_Create(pShip, \"InterceptTarget\")\n\tpInterceptTarget.SetScriptModule(\"Intercept\")\n\tpInterceptTarget.SetInterruptable(1)\n\tpScript = pInterceptTarget.GetScriptInstance()\n\tpScript.SetTargetObjectName(sTargetName)\n\tpScript.SetAddObjectRadius(bUseRadius = 1)\n\t# Done creating PlainAI InterceptTarget\n\t#########################################\n\t#########################################\n\t# Creating PlainAI StayPut at (449, 118)\n\tpStayPut = App.PlainAI_Create(pShip, \"StayPut\")\n\tpStayPut.SetScriptModule(\"Stay\")\n\tpStayPut.SetInterruptable(1)\n\t# Done creating PlainAI StayPut\n\t#########################################\n\t#########################################\n\t# Creating PriorityListAI PriorityList at (297, 181)\n\tpPriorityList = App.PriorityListAI_Create(pShip, \"PriorityList\")\n\tpPriorityList.SetInterruptable(1)\n\t# SeqBlock is at (421, 171)\n\tpPriorityList.AddAI(pInterceptTarget, 1)\n\tpPriorityList.AddAI(pStayPut, 2)\n\t# Done creating PriorityListAI PriorityList\n\t#########################################\n\t#########################################\n\t# Creating PreprocessingAI GreenAlert at (294, 238)\n\t## Setup:\n\timport AI.Preprocessors\n\tpScript = AI.Preprocessors.AlertLevel(App.ShipClass.GREEN_ALERT)\n\t## The PreprocessingAI:\n\tpGreenAlert = App.PreprocessingAI_Create(pShip, \"GreenAlert\")\n\tpGreenAlert.SetInterruptable(1)\n\tpGreenAlert.SetPreprocessingMethod(pScript, \"Update\")\n\tpGreenAlert.SetContainedAI(pPriorityList)\n\t# Done creating PreprocessingAI GreenAlert\n\t#########################################\n\t#########################################\n\t# Creating SequenceAI Sequence at (36, 254)\n\tpSequence = App.SequenceAI_Create(pShip, \"Sequence\")\n\tpSequence.SetInterruptable(1)\n\tpSequence.SetLoopCount(1)\n\tpSequence.SetResetIfInterrupted(1)\n\tpSequence.SetDoubleCheckAllDone(0)\n\tpSequence.SetSkipDormant(0)\n\t# SeqBlock is at (181, 251)\n\tpSequence.AddAI(pCloak)\n\tpSequence.AddAI(pCloak_2)\n\tpSequence.AddAI(pCall_KlingonsDecloak)\n\tpSequence.AddAI(pGreenAlert)\n\t# Done creating SequenceAI Sequence\n\t#########################################\n\t#########################################\n\t# Creating PreprocessingAI AvoidObstacles at (35, 305)\n\t## Setup:\n\timport AI.Preprocessors\n\tpScript = AI.Preprocessors.AvoidObstacles()\n\t## The PreprocessingAI:\n\tpAvoidObstacles = App.PreprocessingAI_Create(pShip, \"AvoidObstacles\")\n\tpAvoidObstacles.SetInterruptable(1)\n\tpAvoidObstacles.SetPreprocessingMethod(pScript, \"Update\")\n\tpAvoidObstacles.SetContainedAI(pSequence)\n\t# Done creating PreprocessingAI AvoidObstacles\n\t#########################################\n\treturn pAvoidObstacles\n","sub_path":"scripts/Maelstrom/Episode2/E2M0/E2M0_AI_KlingonTransfer.py","file_name":"E2M0_AI_KlingonTransfer.py","file_ext":"py","file_size_in_byte":7020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"349592167","text":"#! /usr/bin/python\n#-------------------------------------------------------------------------------\n# curses1.py\n# Demonstrates the use of Python's curses module.\n# Translated from the console6.py example.\n#-------------------------------------------------------------------------------\n# Example source code for the book \"Real-World Instrumentation with Python\"\n# by J. M. Hughes, published by O'Reilly Media, December 2010,\n# ISBN 978-0-596-80956-0.\n#-------------------------------------------------------------------------------\n\nimport random\nimport time\nimport datetime\nimport curses\nimport traceback\n\ndata_vals = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\ncurrdate = \"\"\ncurrtime = \"\"\nupdt_cnt1 = 0\nupdt_cnt2 = 0\n\nran = random.random\n\ndef getDate():\n global currdate\n\n t = datetime.datetime.now()\n currdatetime = t.timetuple()\n yr = str(currdatetime[0])\n currdate = \"%02d\"%int(yr[2:]) + \"%02d\"%currdatetime[1] + \"%02d\"%currdatetime[2]\n\ndef getTime():\n global currtime\n\n t = datetime.datetime.now()\n currdatetime = t.timetuple()\n currtime = \"%02d:\"%currdatetime[3] + \"%02d:\"%currdatetime[4] + \"%02d\"%currdatetime[5]\n\n# write data and time to display\ndef writeDateTime(win):\n getDate()\n getTime()\n\n win.move(2,15)\n win.clrtoeol()\n win.addstr(\"%s\" % currdate)\n win.move(3,15)\n win.clrtoeol()\n win.addstr(\"%s\" % currtime)\n win.refresh()\n\n# get simulated data input values\ndef getDataVals():\n global data_vals, updt_cnt1, updt_cnt2\n\n data_vals[0] = ran() * 10.0\n data_vals[1] = ran() * 10.0\n\n if updt_cnt1 >= 4:\n for i in range(2,5):\n data_vals[i] = ran() * 10.0\n updt_cnt1 = 0\n else:\n updt_cnt1 += 1\n\n if updt_cnt2 >= 10:\n for i in range(4,8):\n data_vals[i] = ran() * 10.0\n updt_cnt2 = 0\n else:\n updt_cnt2 += 1\n\n# write channel data values\ndef writeDataVals(win):\n idx = 0\n for i in range(6,14):\n win.move(i,10)\n win.clrtoeol()\n win.addstr(\"%6.2f\" % data_vals[idx])\n idx += 1\n\n win.refresh()\n # put cursor below display text when update is done\n win.move(16,1)\n\n# generate the main display\ndef mainScreen(win):\n win.erase()\n\n win.move(1,1)\n win.addstr(\"Input Data Monitor\")\n win.refresh()\n\n win.move(2,1)\n win.addstr(\"Current Date:\")\n win.move(3,1)\n win.addstr(\"Current Time:\")\n win.refresh()\n\n writeDateTime(win)\n\n win.move(5,1)\n win.addstr(\"Chan Last Value\")\n win.refresh()\n\n rownum = 1\n for row in range(6,14):\n win.move(row, 1)\n win.addstr(\" %d\" % rownum)\n rownum += 1\n win.refresh()\n\n writeDataVals(win)\n\n win.move(15,1)\n win.addstr(\"Enter X to exit.\")\n win.refresh()\n\ndef mainloop(win):\n win.nodelay(1) # disable getch() blocking\n # draw the main display template\n mainScreen(win)\n\n # run until the user wants to quit\n while 1:\n # check for keyboard input\n inch = win.getch()\n # getch() will return -1 if no character is available\n if inch != -1:\n # see if inch is really a character\n try:\n instr = str(chr(inch))\n except:\n # just ignore non-character input\n pass\n else:\n if instr.upper() == 'X':\n break\n writeDateTime(win)\n getDataVals()\n writeDataVals(win)\n time.sleep(0.2)\n\ndef startup():\n # borrowed the idea of using a try-except wrapper around the\n # initialization from David Mertz.\n try:\n # Initialize curses\n stdscr = curses.initscr()\n\n # Turn off echoing of keys, and enter cbreak mode,\n # where no buffering is performed on keyboard input\n curses.noecho()\n curses.cbreak()\n\n mainloop(stdscr) # Enter the main loop\n\n # Set everything back to normal\n curses.echo()\n curses.nocbreak()\n\n curses.endwin() # Terminate curses\n except:\n # In event of error, restore terminal to sane state.\n curses.echo()\n curses.nocbreak()\n curses.endwin()\n traceback.print_exc() # Print the exception\n\nif __name__=='__main__':\n startup()\n","sub_path":"Advance/Real World Instrumentation with Python/CH13/curses1.py","file_name":"curses1.py","file_ext":"py","file_size_in_byte":4262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"640583879","text":"import gurobipy as gp\nfrom gurobipy import GRB\n\nimport numpy as np\n\n# Inizializzo il modello\nmod = gp.Model('Farmer')\n\n# Creo variabili di decisione\nprod = range(2) # equivale ad aggiungerne una per volta con mod.addVar(name='x1')\nxvar = mod.addVars(prod, name='X') # x0, x1\nres = range(4)\n\n# Coefficienti della FO\nobjcoeff = [1, 1]\n# Definisco FO\nobj = mod.setObjective(xvar.prod(objcoeff), GRB.MAXIMIZE)\n\n# Definisco tassi assorbimento\ntassi_assorbimento = [[1, 0], [0, 1], [2, 5], [2, 1]]\nsigns = ['lte', 'lte', 'gte', 'gte']\n# Definisco capacità\ncap = [6, 4, 10, 4]\n\n# Aggiungo i vincoli alla funzione obiettivo\nconstraints = []\nfor i in res:\n constraints.append(\n mod.addConstr(\n (xvar.prod(tassi_assorbimento[i]) <= cap[i]) if signs[i] == 'lte' else (xvar.prod(tassi_assorbimento[i]) >= cap[i]),\n 'constraints'\n )\n )\n\n# Risoluzione\nmod.optimize()\n\n# Prelevo soluzione e stampo\nif mod.status == GRB.OPTIMAL:\n print(\"\\nSoluzione ottima trovata: %g\\n\" % mod.objVal)\n\n X = mod.getAttr('x', xvar)\n for i in prod:\n print(\"X(%s) = %g\" % (i, X[i]))\nelse:\n print(\"\\nNon esiste una soluzione ottima :(\")\n\nmod.write(\"Meko.lp\")\n","sub_path":"main/esercizi/simplesso/esercizio_big_m_1.py","file_name":"esercizio_big_m_1.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"208937935","text":"# Copyright 2015, Cisco Systems.\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n# http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nTest class for UCS ManagementInterface\n\"\"\"\n\nimport mock\nfrom oslo_config import cfg\nfrom oslo_utils import importutils\n\nfrom ironic.common import boot_devices\nfrom ironic.common import exception\nfrom ironic.conductor import task_manager\nfrom ironic.drivers.modules.ucs import helper as ucs_helper\nfrom ironic.drivers.modules.ucs import management as ucs_mgmt\nfrom ironic.tests.unit.conductor import mgr_utils\nfrom ironic.tests.unit.db import base as db_base\nfrom ironic.tests.unit.db import utils as db_utils\nfrom ironic.tests.unit.objects import utils as obj_utils\n\nucs_error = importutils.try_import('UcsSdk.utils.exception')\n\nINFO_DICT = db_utils.get_test_ucs_info()\nCONF = cfg.CONF\n\n\nclass UcsManagementTestCase(db_base.DbTestCase):\n\n def setUp(self):\n super(UcsManagementTestCase, self).setUp()\n mgr_utils.mock_the_extension_manager(driver='fake_ucs')\n self.node = obj_utils.create_test_node(self.context,\n driver='fake_ucs',\n driver_info=INFO_DICT)\n self.interface = ucs_mgmt.UcsManagement()\n self.task = mock.Mock()\n self.task.node = self.node\n\n def test_get_properties(self):\n expected = ucs_helper.COMMON_PROPERTIES\n self.assertEqual(expected, self.interface.get_properties())\n\n def test_get_supported_boot_devices(self):\n with task_manager.acquire(self.context, self.node.uuid) as task:\n expected = [boot_devices.PXE, boot_devices.DISK,\n boot_devices.CDROM]\n self.assertEqual(\n sorted(expected),\n sorted(self.interface.get_supported_boot_devices(task)))\n\n @mock.patch('ironic.drivers.modules.ucs.helper.ucs_helper',\n spec_set=True, autospec=True)\n @mock.patch(\n 'ironic.drivers.modules.ucs.management.ucs_mgmt.BootDeviceHelper',\n spec_set=True, autospec=True)\n def test_get_boot_device(self, mock_ucs_mgmt, mock_helper):\n mock_helper.generate_ucsm_handle.return_value = (True, mock.Mock())\n mock_mgmt = mock_ucs_mgmt.return_value\n mock_mgmt.get_boot_device.return_value = {\n 'boot_device': 'disk',\n 'persistent': False\n }\n with task_manager.acquire(self.context, self.node.uuid,\n shared=False) as task:\n expected_device = boot_devices.DISK\n expected_response = {'boot_device': expected_device,\n 'persistent': False}\n self.assertEqual(expected_response,\n self.interface.get_boot_device(task))\n mock_mgmt.get_boot_device.assert_called_once_with()\n\n @mock.patch('ironic.drivers.modules.ucs.helper.ucs_helper',\n spec_set=True, autospec=True)\n @mock.patch(\n 'ironic.drivers.modules.ucs.management.ucs_mgmt.BootDeviceHelper',\n spec_set=True, autospec=True)\n def test_get_boot_device_fail(self, mock_ucs_mgmt, mock_helper):\n mock_helper.generate_ucsm_handle.return_value = (True, mock.Mock())\n mock_mgmt = mock_ucs_mgmt.return_value\n side_effect = ucs_error.UcsOperationError(\n operation='getting boot device',\n error='failed',\n node=self.node.uuid\n )\n mock_mgmt.get_boot_device.side_effect = side_effect\n with task_manager.acquire(self.context, self.node.uuid,\n shared=False) as task:\n self.assertRaises(exception.UcsOperationError,\n self.interface.get_boot_device,\n task)\n mock_mgmt.get_boot_device.assert_called_once_with()\n\n @mock.patch('ironic.drivers.modules.ucs.helper.ucs_helper',\n spec_set=True, autospec=True)\n @mock.patch(\n 'ironic.drivers.modules.ucs.management.ucs_mgmt.BootDeviceHelper',\n spec_set=True, autospec=True)\n def test_set_boot_device(self, mock_mgmt, mock_helper):\n mc_mgmt = mock_mgmt.return_value\n mock_helper.generate_ucsm_handle.return_value = (True, mock.Mock())\n with task_manager.acquire(self.context, self.node.uuid,\n shared=False) as task:\n self.interface.set_boot_device(task, boot_devices.CDROM)\n\n mc_mgmt.set_boot_device.assert_called_once_with('cdrom', False)\n\n @mock.patch('ironic.drivers.modules.ucs.helper.ucs_helper',\n spec_set=True, autospec=True)\n @mock.patch(\n 'ironic.drivers.modules.ucs.management.ucs_mgmt.BootDeviceHelper',\n spec_set=True, autospec=True)\n def test_set_boot_device_fail(self, mock_mgmt, mock_helper):\n mc_mgmt = mock_mgmt.return_value\n mock_helper.generate_ucsm_handle.return_value = (True, mock.Mock())\n side_effect = exception.UcsOperationError(\n operation='setting boot device',\n error='failed',\n node=self.node.uuid)\n mc_mgmt.set_boot_device.side_effect = side_effect\n with task_manager.acquire(self.context, self.node.uuid,\n shared=False) as task:\n self.assertRaises(exception.IronicException,\n self.interface.set_boot_device,\n task, boot_devices.PXE)\n mc_mgmt.set_boot_device.assert_called_once_with(\n boot_devices.PXE, False)\n\n def test_get_sensors_data(self):\n self.assertRaises(NotImplementedError,\n self.interface.get_sensors_data, self.task)\n","sub_path":"ironic/tests/unit/drivers/modules/ucs/test_management.py","file_name":"test_management.py","file_ext":"py","file_size_in_byte":6200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"567003364","text":"from PyQt5 import QtCore, QtSerialPort, QtWidgets # pyqt imports\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\nvalue = 200 # value set by user\r\nmaxCount = 100 # maxcount set by user\r\n\r\ndata = [] # list to store data\r\nnumCount = [] # this is made as a list instead of an int counter, since it's incremented in a function, so it would have to be declared global\r\ntimeCount = [] # list of time counts\r\n\r\n#app = QtCore.QCoreApplication([]) # can use with inline plotting\r\napp = QtWidgets.QApplication([]) # use with automatic plotting\r\n#[print('port:', i.portName()) for i in QtSerialPort.QSerialPortInfo().availablePorts()] # can show available COM ports\r\nserial_port = QtSerialPort.QSerialPort('COM4') # COM? choose COM port number\r\n\r\n#serial_port.setBaudRate(QtSerialPort.QSerialPort.Baud9600) # not needed since defaults is 9600\r\n\r\nserial_port.open(QtCore.QIODevice.ReadWrite) # open port and set it to read/write\r\n# port specifications\r\nprint('serial port:', serial_port)\r\nprint('description:',QtSerialPort.QSerialPortInfo(serial_port).description())\r\nprint('baud rate:', serial_port.baudRate())\r\nprint('data bits:', serial_port.dataBits())\r\nprint('parity:', serial_port.parity())\r\nprint('stop bits:', serial_port.StopBits())\r\nprint('DTR signal:', serial_port.DataTerminalReadySignal) \r\nprint('flow control:', serial_port.flowControl())\r\nprint('is DTR', serial_port.isDataTerminalReady())\r\n\r\ntimer = QtCore.QElapsedTimer() # create instance of qt's elapsed timer\r\ntimer.start() # start elapsed timer\r\n\r\ndef handle_ready_read(): # slot to handle when something is ready to be read\r\n\r\n while serial_port.canReadLine(): # while a realine can be read from serialport\r\n serialStringIn = serial_port.readLine().data().decode().strip() # read a line from the serial port, get the data from it, decode the bytes to a string, then strip spaces around string\r\n if serialStringIn == 'C': # if the string read is C\r\n numCount.append(1) # append a 1 to numcount list\r\n to = timer.nsecsElapsed() # get the nanoseconds time elapsed since started\r\n print('click number:', len(numCount)) # print the click number, from the length of the numcount list\r\n print('time-stamp (ns):', to) # print the time stamp of the click\r\n timeCount.append(to) # append the time stamp to the timecount list\r\n if len(numCount) == maxCount: # if number of counts is equal to maxcount\r\n # DTR reset is needed to restart the arduino sketch the next time it's run\r\n # since the numCount in arduino is initialized at the start\r\n # see https://arduino.stackexchange.com/questions/439/why-does-starting-the-serial-monitor-restart-the-sketch\r\n serial_port.setDataTerminalReady(0) # set dtr to 0\r\n serial_port.setDataTerminalReady(1) # set dtr to 1\r\n serial_port.setDataTerminalReady(0) # and 0 again\r\n serial_port.close() # close serial port\r\n app.quit() # quit pyqt event loop\r\n\r\n#serial_port.clear() # maybe needed, if spaces are around 'C', if printed\r\n\r\nserial_port.readyRead.connect(handle_ready_read) # when something is ready to read, signal is sent to run handle ready read slot\r\n\r\nserial_port.writeData(bytes([value])) # encode value to bytes then write byte data to serial port\r\n#app.setQuitOnLastWindowClosed(True) # could be needed \r\napp.exec_() # start qt eventloop\r\n\r\nmaxT = max(timeCount) # get max of timecount0\r\nnumZeros = 1000 # num zeros to use\r\ntimeZeros = np.linspace(0, maxT, numZeros) # 1D array from 0 to maxt of length numzeros\r\nzeroValues = np.zeros(numZeros) # np array of zeros of numzeros shape\r\noneValues = np.ones(maxCount) # np array of ones of maxcount shape\r\nplt.figure() # create plot figure, may be not needed\r\nplt.plot(timeCount, oneValues, 'o') # plot one values vs timecounts\r\nplt.plot(timeZeros, zeroValues, 'o') # plot zero values vs timezeros\r\nplt.xlabel(\"Time (ns)\") # x label\r\nplt.ylabel(\"Spike\") # y label\r\nplt.show() # show plot, may be not needed\r\n","sub_path":"Click_counter.py","file_name":"Click_counter.py","file_ext":"py","file_size_in_byte":4064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"86"} +{"seq_id":"61944556","text":"import logging\nimport csv\nimport json\nfrom overrides import overrides\n\nfrom allennlp.data.dataset_readers.dataset_reader import DatasetReader\nfrom allennlp.data.fields import LabelField, TextField, SequenceLabelField\nfrom allennlp.data.instance import Instance\nfrom allennlp.data.tokenizers import WordTokenizer # to split the sentence we read to words\nfrom allennlp.data.tokenizers.word_splitter import JustSpacesWordSplitter\nfrom allennlp.data.token_indexers import SingleIdTokenIndexer,ELMoTokenCharactersIndexer\n\nlogger = logging.getLogger(__name__)\n\n@DatasetReader.register(\"vua_reader\")\nclass VuaDatasetReader(DatasetReader):\n \"\"\"\n Reads a csv file containing the following columns: {\"text_idx\", \"sentence_idx\", \"verb\", \"sentence\", \"verbIdx\", \"label\"}\n 1. text idx in vua corpus\n 2. sentence index in vua corus\n 3. The verb of the metaphore\n 4. Sentence that includes also a pair of verb and an object.\n\t5. The index of the verb in the sentence.\n\t6. Label - 1 if the verb-object pair in the sentence is a metaphore, 0 otherwise\n\n The output of 'read' is a list of ``Instance`` s with the fields:\n\t1. Sentence of type 'TextField'\n\t2. VerbIndex of type 'SequenceLabelField'\n\t3. Label of type 'LabelField'\n \"\"\"\n def __init__(self) -> None:\n # we use simple word tokenizer to split sentence to words\n self._tokenizer = WordTokenizer(word_splitter=JustSpacesWordSplitter())\n\t\t\n #initialize indexers\n singleIdIndexer = SingleIdTokenIndexer()\n elmoIndexer = ELMoTokenCharactersIndexer()\n self.indexers = {}\n self.indexers[\"tokens\"] = singleIdIndexer\n self.indexers[\"elmo_characters\"] = elmoIndexer \n\t\t\n \"\"\"\n Define how data reader is reaing the input file\n \"\"\"\n @overrides\n def _read(self, file_path):\n\t\n instances = []\n \n # count how many sentences were read\n counter = 0\n #open data csv file\n with open(file_path, encoding='latin-1') as f:\n lines = csv.reader(f)\n\n # raw lines is used to convert csv reader lines to list\n raw_lines = []\n for line in lines:\n counter = counter + 1\n raw_lines.append(line)\n\t\t \n # line[3] is the sentence\n # line[4] is the index of verb in the sentence\n # line[5] is the label - 0 for non-metaphore, 1 for metaphore\n \n for line in raw_lines:\n # Generate tuple of sentence, indexOfVerb, Label for each read operation.\n # This tuple will be used to create the input to train the model using previous embedding\n yield self.text_to_instance(line[3].strip(),line[4], line[5]) \n print('VUA dataset', counter) # print number of lines read from csv file\n\n # This function will convert the fields read from csv line to instance.\n # later the trainer will organize instances in a batch\n\n # Each instance will include: \n # 1. The sentence for training - TextField. Each token of the sentence will be indexed as\n # Single id for a word and also elmo tocken charecters to be used in case the sentence needs \n # to be embedded with elmo embedder\n # 2. The index of the verb in a text - SequenceField because we are not indexing this field\n # 3. The label (is metaphore or not) - LabelField\n @overrides\n def text_to_instance(self, sentence: str, verb_index: str = None, label: str = None) -> Instance:\n\n # tokenize the sentence to words - will be part of the 'text' field in instance\n # use standard database reader tokenizer and indexers\n tokenizedSentence = self._tokenizer.tokenize(sentence)\n # we want to create 1-hot vector of 0/1 for every index of verb\n indicated_sequence = [0] * len(tokenizedSentence)\n indicated_sequence[int(verb_index)] = 1\n\n # One index is for single indexing of word token.\n # the second will be used for elmo embedder if enabled.\n fields = {'sentences': TextField(tokenizedSentence, self.indexers)}\n\t\t\n # send also index of verb - for each word in a sentence, 1 means this is \n # the verb we are refering when classifying the sentence as metaphore\n if verb_index is not None:\n # sequence of labels. Each label is 0 or 1. It won't be indexed since this is a number.\n # also, each label here referes to one word.\n fields['verb_index'] = SequenceLabelField (indicated_sequence, fields['sentences'])\n\n if label is not None:\n fields['labels'] = LabelField(int(label),skip_indexing=True)\n\n return Instance(fields)\n","sub_path":"models/data_readers/vua_reader.py","file_name":"vua_reader.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"199879694","text":"class Calculator(object):\n\n def __init__(self):\n # 操作符集合\n self.operators = ['+', '-', '*', '/', '(', ')']\n # 操作符优先级\n self.priority = {\n '+': 1,\n '-': 1,\n '*': 2,\n '/': 2,\n '(': 3,\n ')': 3\n }\n\n def generate_postfix_expression(self, expression):\n \"\"\"\n 生成后缀表达式\n :param expression:\n :return:\n \"\"\"\n\n # 去除表达式中所有空格\n expression = expression.replace(' ', '')\n\n exprelst = []\n temp = ''\n for i,each in enumerate(expression):\n if each.isdigit() or each == '.':\n temp += each\n if i == len(expression)-1:\n exprelst.append(temp)\n else:\n if len(temp)>0:\n exprelst.append(temp)\n temp = ''\n exprelst.append(each)\n\n expression = exprelst\n\n # 创建list作为栈,list的append和pop方法刚好和栈的入栈和出栈方法相同\n # 操作符栈\n operator_stack = list()\n # 后缀表达式是从尾部插入数据,使用后缀表达式计算结果是从头开始遍历,可以理解为先进先出,可以使用队列实现,\n # 这里为了简便用list代替,不做内存释放处理\n expression_stack = list()\n\n for element in expression:\n # 如果是数字则直接入表达式栈\n if element in self.operators:\n\n # 如果栈为空,操作符直接入操作符栈,或者为左括号,也直接入操作符栈\n if not operator_stack:\n operator_stack.append(element)\n else:\n # 如果目标元素是右括号,操作符栈顶出栈直接遇到左括号,且出栈的操作符除了括号入到表达式队列中\n if element == ')':\n for top in operator_stack[::-1]:\n if top != '(':\n expression_stack.append(top)\n operator_stack.pop()\n else:\n operator_stack.pop()\n break\n else:\n for top in operator_stack[::-1]:\n # 如果目标元素大于栈顶元素,则直接入栈,否则栈顶元素出栈,入到表达式队列中\n # 左括号只有遇到右括号才出栈\n if self.priority[top] >= self.priority[element] and top != '(':\n expression_stack.append(top)\n operator_stack.pop()\n else:\n operator_stack.append(element)\n break\n\n # 可能操作符栈所有的元素优先级都大于等于目标操作符的优先级,这样的话操作符全部出栈了,\n # 而目标操作符需要入栈操作\n if not operator_stack:\n operator_stack.append(element)\n\n else:\n expression_stack.append(element)\n\n # 中缀表达式遍历结束,操作符栈仍有操作符,将操作符栈中的操作符入到表达式栈中\n for i in range(len(operator_stack)):\n expression_stack.append(operator_stack.pop())\n\n return expression_stack\n\n def calcaulate(self, expression):\n # 生成后缀表达式\n expression_result = self.generate_postfix_expression(expression)\n # 使用list作为栈来计算\n calcalate_stack = list()\n\n # 遍历后缀表达式\n for element in expression_result:\n # 如果为数字直接入栈\n # 遇到操作符,将栈顶的两个元素出栈\n if element not in self.operators:\n calcalate_stack.append(element)\n else:\n # 操作数\n number1 = calcalate_stack.pop()\n # 被操作数\n number2 = calcalate_stack.pop()\n # 结果 = 被操作数 操作符 操作数 (例:2 - 1)\n result = self.operate(number1, number2, element)\n # 计算结果入栈\n calcalate_stack.append(result)\n\n ret = calcalate_stack[0]\n if int(ret) == ret:\n ret = int(ret)\n return ret\n\n def operate(self, number1, number2, operator):\n \"\"\"\n 计算结果\n :param number1: 操作数\n :param number2: 被操作数\n :param operator: 操作符\n :return:\n \"\"\"\n number1 = float(number1)\n number2 = float(number2)\n\n if operator == '+':\n return number2 + number1\n if operator == '-':\n return number2 - number1\n if operator == '*':\n return number2 * number1\n if operator == '/':\n return number2 / number1\n\n\nif __name__ == '__main__':\n c = Calculator()\n expression = '2.1 + (3 - 1)*3 + 8 / 4'\n expression_result = c.calcaulate(expression)\n print(expression_result)\n\n","sub_path":"Basic/Array&&LinkedList/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"151431173","text":"import numpy as np\r\nfrom scipy import misc\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef sigmoid(Z):\r\n out = 1 / (1 + np.exp(-Z))\r\n return out\r\n\r\n\r\nface1 = misc.imread('1.gif')\r\n\"\"\"plt.imshow(face1)\r\nplt.show()\"\"\"\r\nprint(face1)\r\nface2 = misc.imread('2.gif')\r\n\"\"\"plt.imshow(face2)\r\nplt.show()\"\"\"\r\nprint(face2)\r\nface3 = misc.imread('3.gif')\r\n\"\"\"plt.imshow(face3)\r\nplt.show()\"\"\"\r\nprint(face3)\r\nface4 = misc.imread('4.gif')\r\n\"\"\"plt.imshow(face4)\r\nplt.show()\"\"\"\r\nprint(face4)\r\ndata = np.loadtxt(\"river.txt\",dtype=np.int64,delimiter=\",\")\r\nX = data[:,0:1]\r\nY = data[:,1:2]\r\ndata2 = np.loadtxt(\"Nonriver.txt\",dtype=np.int64,delimiter=\",\")\r\nX2 = data2[:,0:1]\r\nY2 = data2[:,1:2]\r\nm,n =X.shape\r\nm2,n2 = X2.shape\r\npr1 = np.ones((m,1))\r\nfor i in range(m):\r\n pr1[i] = face1[X[i],Y[i],1]\r\n#print(pr1)\r\npn1 = np.ones((m2,1))\r\nfor i in range(m2):\r\n pn1[i] = face1[X2[i],Y2[i],1]\r\n#print(pn1)\r\npr2 = np.ones((m,1))\r\nfor i in range(m):\r\n pr2[i] = face2[X[i],Y[i],1]\r\n#print(pr2)\r\npn2 = np.ones((m2,1))\r\nfor i in range(m2):\r\n pn2[i] = face2[X2[i],Y2[i],1]\r\n#print(pn2)\r\npr3 = np.ones((m,1))\r\nfor i in range(m):\r\n pr3[i] = face3[X[i],Y[i],1]\r\n#print(pr3)\r\npn3 = np.ones((m,1))\r\nfor i in range(m2):\r\n pn3[i] = face3[X2[i],Y2[i],1]\r\n#print(pn3)\r\npr4 = np.ones((m,1))\r\nfor i in range(m):\r\n pr4[i] = face4[X[i],Y[i],1]\r\n#print(pr4)\r\npn4 = np.ones((m2,1))\r\nfor i in range(m2):\r\n pn4[i] = face4[X2[i],Y2[i],1]\r\n#print(pn4)\r\nm,n = pn1.shape\r\nprint(m)\r\nprint(n)\r\nd1 = np.ones((2*m,n))\r\nd2 = np.ones((2*m,n))\r\nd3 = np.ones((2*m,n))\r\nd4 = np.ones((2*m,n))\r\nd1[0:m,0:1] = pr1\r\nd1[m:,0:1] = pn1\r\nd2[0:m,0:1]= pr2\r\nd2[m: , :] = pn2\r\nd3[0:m,:] = pr3\r\nd3[m:,:] = pn3\r\nd4[:m,:] =pr4\r\nd4[m:,:]=pn4\r\nprint(d4)\r\n\r\nmean1 = np.mean(d1)\r\nmean2 = np.mean(d2)\r\nmean3 = np.mean(d3)\r\nmean4 = np.mean(d4)\r\n\r\nstd1 = np.std(d1)\r\nstd2 = np.std(d2)\r\nstd3 = np.std(d3)\r\nstd4 = np.std(d4)\r\n\r\nd1 = (d1 - mean1)/std1\r\nd2 = (d2 - mean2)/std2\r\nd3 = (d3 - mean3)/std3\r\nd4 = (d4 - mean4)/std4\r\n\r\n\r\nX_bias = np.ones((2*m,n*4+1))\r\nX_bias[:, 1:2] = d1\r\nX_bias[:,2:3] = d2\r\nX_bias[:,3:4] = d3\r\nX_bias[:,4:] = d4\r\nprint(X_bias)\r\n\r\nW = np.zeros((5,1))\r\niteration = 10000\r\nalpha = 0.3\r\n\r\nY = np.ones((2*m,1))\r\nY[:m,:] = data[:,-1:]\r\nY[m:] = data2[:,-1:]\r\nprint(Y)\r\nfor i in range(iteration) :\r\n hypothesis = sigmoid(np.dot(X_bias,W))\r\n J = sum( - (np.dot(Y.transpose(),np.log(hypothesis)) +( np.dot((1 - Y).transpose(), np.log(1 - hypothesis)))))\r\n inc = np.dot(X_bias.transpose(), (Y - hypothesis))\r\n W = (W )+ ((alpha/2*m)*inc);\r\n\r\ntest = misc.imread('4.gif')\r\nm,n,p = test.shape\r\noutimg = np.zeros([512,512,3],dtype=np.uint8)\r\noutimg.fill(255)\r\nx_predict = np.zeros((m,n))\r\nfor i in range(m):\r\n for j in range(n):\r\n x_predict[i, j] = np.dot([1, (((test[i, j,1]) - mean1)/std1), ((test[i, j,1]) - mean2)/std2,(((test[i, j,1]) - mean3)/std3),(((test[i, j,1]) - mean4)/std4)],W)\r\n x_predict[i,j] = sigmoid(x_predict[i,j])\r\n if x_predict[i,j] >= 0.5:\r\n outimg[i,j] = 255\r\n else :\r\n outimg[i,j] = 0\r\nplt.imshow(outimg);\r\nplt.show()","sub_path":"Distinguish between river and non river from satellite image using logistic regression/satellitelogistic.py","file_name":"satellitelogistic.py","file_ext":"py","file_size_in_byte":3053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"494722009","text":"# TO-DO: Complete the selection_sort() function below \ndef selection_sort(arr):\n for i in range(0, len(arr) - 1):\n leftIndex = i\n for j in range(i+1, len(arr)):\n rightIndex = j\n if arr[j] < arr[i]:\n arr[leftIndex], arr[rightIndex] = arr[rightIndex], arr[leftIndex]\n return arr\n\n# TO-DO: implement the Bubble Sort function below\ndef bubble_sort( arr ):\n for i in range(0, len(arr) - 1):\n sortedIndex = i\n for j in range(0, len(arr) - 1 - sortedIndex):\n leftIndex = j\n rightIndex = j+1\n if arr[j] > arr[j+1]:\n arr[leftIndex], arr[rightIndex] = arr[rightIndex], arr[leftIndex] \n return arr\n\n\n# STRETCH: implement the Count Sort function below\n# def count_sort( arr, maximum=-1 ):\n\n# return arr","sub_path":"src/iterative_sorting/iterative_sorting.py","file_name":"iterative_sorting.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"88616179","text":"# encoding=utf-8\nimport random\nfrom WebHub.user_agents import agents\nimport json\nimport requests\n\n\nclass UserAgentMiddleware(object):\n \"\"\" 换User-Agent \"\"\"\n\n def process_request(self, request, spider):\n agent = random.choice(agents)\n request.headers[\"User-Agent\"] = agent\n\n\nclass CookiesMiddleware(object):\n \"\"\" 换Cookie \"\"\"\n cookie = {\n 'platform': 'pc',\n 'ss': '367701188698225489',\n 'bs': '%s',\n 'RNLBSERVERID': 'ded6699',\n 'FastPopSessionRequestNumber': '1',\n 'FPSRN': '1',\n 'performance_timing': 'home',\n 'RNKEY': '40859743*68067497:1190152786:3363277230:1'\n }\n\n def process_request(self, request, spider):\n bs = ''\n for i in range(32):\n bs += chr(random.randint(97, 122))\n _cookie = json.dumps(self.cookie) % bs\n request.cookies = json.loads(_cookie)\n\nclass MyProxyMiddleware(object):\n def __init__(self):\n self.ip_url = 'http://localhost:5555/random'\n self.base_url_ip = 'https://'\n self.ip_list = []\n for i in range(10):\n ip = self.get_proxy()\n if ip not in self.ip_list:\n self.ip_list.append(ip)\n\n def process_request(self, request, spider):\n ip = random.choice(self.ip_list)\n if ip:\n request.meta['proxy'] = ip\n\n def get_proxy(self):\n url_response = requests.get(self.ip_url)\n if url_response.status_code == 200:\n ip = self.base_url_ip + url_response.text\n return ip\n else:\n None\n","sub_path":"WebHub/WebHub/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"298370202","text":"from collections import namedtuple\n\nt = (1,2,3)\nprint(t[0])\n\n# named tuples almost like classes\nDog = namedtuple('Dog', 'age weight color')\nsam = Dog(age=2, weight=145, color=\"black\")\n\nprint(sam.weight, sam[1])\n\n\nCat = namedtuple('Cat', 'name claws age')\ncat = Cat(name='cat', claws=False, age=11)\n\nprint(cat.name, cat[0])","sub_path":"python/learning concepts/useful_modules/namedtuple_module.py","file_name":"namedtuple_module.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"381612079","text":"import torch\nimport torch.nn as nn\nimport torch.distributions as td\nfrom torch import optim\nfrom copy import deepcopy\nfrom src.Util.Util_Model import Util_Model\n\n\nclass Hidden(nn.Module, Util_Model):\n\n def __init__(self, no_in, no_out, bias=True, activation=nn.ReLU()):\n \"\"\"\n Hidden Layer, that provides its prior_log_prob model\n\n :param no_in:\n :param no_out:\n :param bias: bool, whether or not to use bias in the computation\n :param activation: Any \"nn.activation function\" instance. Examine\n https://src.org/docs/stable/nn.html?highlight=nn%20relu#torch.nn.ReLU\n should work with their functional correspondance e.g. F.relu. Notably,\n A final Layer in Regression setup looks like e.g.\n Hidden(10, 1, bias=False, activation=nn.Identity())\n \"\"\"\n\n super().__init__()\n\n self.no_in = no_in\n self.no_out = no_out\n self.has_bias = bias\n self.activation = activation\n\n self.define_model()\n\n # initialize the parameters\n self.reset_parameters()\n self.true_model = deepcopy(self.state_dict())\n\n def define_model(self):\n self.tau_w = torch.tensor([1.])\n\n # self.tau_w = nn.Parameter(torch.tensor([1.]))\n # self.tau_w.distrib = td.Gamma(torch.tensor([2.]), torch.tensor([1.]))\n # self.tau_w.data = self.tau_w.distrib.sample()\n\n self.W = nn.Parameter(torch.Tensor(self.no_in, self.no_out))\n self.W.dist = td.Normal(loc=torch.zeros_like(self.W.data), scale=self.tau_w)\n\n if self.has_bias:\n self.b = nn.Parameter(torch.Tensor(self.no_out))\n self.b.dist = td.Normal(torch.zeros(self.no_out), 1.)\n\n @torch.no_grad()\n def reset_parameters(self):\n for p in self.parameters():\n p.data = p.dist.sample()\n\n self.init_model = deepcopy(self.state_dict())\n\n def update_distributions(self):\n # here no hierarchical distributions exists\n # self.W.distrib.scale = torch.ones_like(self.W.distrib.scale) * self.tau_w\n return None\n\n # (2) DEFINE THESE FUNCTIONS IN REFERENCE TO SURROGATE PARAM: --------------\n # & inherit for layers\n def forward(self, X):\n XW = X @ self.W\n if self.has_bias:\n XW += self.b\n return self.activation(XW)\n\n def prior_log_prob(self):\n \"\"\"evaluate each parameter in respective distrib.\"\"\"\n value = torch.tensor(0.)\n for p in self.parameters():\n value += p.dist.log_prob(p).sum()\n return value\n\n def sample_model(self, n):\n self.true_model = deepcopy(self.state_dict())\n X_dist = td.Uniform(torch.ones(self.no_in) * (-10.), torch.ones(self.no_in) * 10.)\n X = X_dist.sample(torch.Size([n]))\n y = self.likelihood(X).sample()\n\n return X, y\n\n\nclass Hidden_flat(Hidden):\n def define_model(self):\n \"\"\"\n formulate the model with truncated flat priors\n :return:\n \"\"\"\n self.W = nn.Parameter(torch.Tensor(self.no_in, self.no_out))\n self.W.dist = td.Uniform(torch.ones(self.no_in, self.no_out) * -100.,\n torch.ones(self.no_in, self.no_out) * 100)\n\n if self.has_bias:\n self.b = nn.Parameter(torch.Tensor(self.no_out))\n self.b.dist = td.Uniform(torch.ones(self.no_out) * -100.,\n torch.ones(self.no_out) * 100)\n\n\nif __name__ == '__main__':\n\n no_in = 1\n no_out = 1\n n = 1000\n\n # single Hidden Unit Example\n reg = Hidden(no_in, no_out, bias=True) #, activation=nn.Identity())\n X, y = reg.sample_model(n)\n reg.reset_parameters()\n\n reg.forward(X=torch.ones(100, no_in))\n\n # (Pretraining) ------------------------------------------------------------\n optimizer = optim.SGD(reg.parameters(), lr=0.1)\n # criterion = nn.MSELoss()\n criterion = reg.log_prob\n LOSS = []\n CHAIN = []\n n = 1\n from tqdm import tqdm\n\n for epoch in tqdm(range(500)):\n # x, Y = next(data._get_iterator())\n yhat = reg(X)\n # loss = criterion(yhat, y) + (reg.W.data.t() @ reg.W.data)[0][0]\n # loss = -criterion(X, y)\n\n # explicit posterior:\n # prior:\n value = torch.tensor([0.])\n for p in reg.parameters():\n value += p.dist.log_prob(p.data).sum()\n\n # posterior = like + prior\n # - due to optim!\n loss = -X.shape[0]**-1 *(reg.likelihood(X).log_prob(y).sum() + value)\n\n print('loss', loss)\n print('penMSE:', nn.MSELoss()(yhat, y) + (reg.W.data.t() @ reg.W.data)[0][0])\n optimizer.zero_grad()\n loss.backward()\n for name, p in reg.named_parameters():\n print(name, 'grad:', p.grad, '\\n', 'current', p.data)\n optimizer.step()\n LOSS.append(loss)\n\n # LOSS.append(reg.log_prob(X, y))\n CHAIN.append(deepcopy(reg.state_dict()))\n\n print('true model', reg.true_model)\n print('current model', reg.state_dict())\n\n print('init model', reg.init_model)\n print(reg.log_prob(X, y))\n #\n\n # (PLOTTING THE TRAVERSAL) ---------------------------------------------------\n # from numpy import exp, arange\n # from pylab import meshgrid, cm, imshow, contour, clabel, colorbar, axis, title, show\n #\n # # the function that I'm going to plot\n # # def z_func(x, y):\n # # return (1 - (x ** 2 + y ** 3)) * exp(-(x ** 2 + y ** 2) / 2)\n #\n # z_func = reg.log_prob\n #\n # a = arange(-10.0, 10., 0.2) # x1\n # b = arange(-10.0, 10.0, 0.2) # x2\n # A, B = meshgrid(a, b) # grid of point\n #\n # params = torch.stack([torch.flatten(torch.tensor(A, dtype=torch.float)),\n # torch.flatten(torch.tensor(B, dtype=torch.float))]).t()\n # from collections import OrderedDict\n #\n # loss = []\n # for p in params:\n # reg.load_state_dict(OrderedDict({'W': torch.reshape(p, [2, 1])}))\n #\n # loss.append(z_func(X, y)) # evaluation of the function on the grid\n # # loss.append(criterion(reg.forward(X), y) +torch.tensor([1.0]) )\n # Z = torch.reshape(torch.tensor(loss), A.shape).numpy()\n #\n # from mpl_toolkits.mplot3d import Axes3D\n # from matplotlib import cm\n # from matplotlib.ticker import LinearLocator, FormatStrFormatter\n # import matplotlib.pyplot as plt\n #\n # import matplotlib\n #\n # matplotlib.use('TkAgg')\n #\n # fig = plt.figure()\n # ax = fig.gca(projection='3d')\n # surf = ax.plot_surface(A, B, Z, rstride=1, cstride=1,\n # cmap=cm.RdBu, linewidth=0, antialiased=False)\n #\n # ax.zaxis.set_major_locator(LinearLocator(10))\n # ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))\n #\n # fig.colorbar(surf, shrink=0.5, aspect=5)\n # ax1 = fig.gca(projection='3d')\n # ax1.plot(torch.flatten(torch.stack([d['W'][0] for d in CHAIN[:4]])).numpy(),\n # torch.flatten(torch.stack([d['W'][1] for d in CHAIN[:4]])).numpy(),\n # torch.flatten(torch.stack(loss[:4]).detach()).numpy())\n # plt.show()\n #\n # # reg.reset_parameters()\n # import matplotlib\n #\n # matplotlib.use('TkAgg')\n # reg.plot(X[:100], y[:100], chain=CHAIN[-20:])\n\n from src.Samplers.LudwigWinkler import SGNHT, SGLD, MALA\n from src.Samplers.mygeoopt import myRHMC, mySGRHMC, myRSGLD\n from torch.utils.data import TensorDataset, DataLoader\n import numpy as np\n import matplotlib\n import random\n import traceback\n\n matplotlib.use('Agg') # 'TkAgg' for explicit plotting\n\n sampler_name = ['SGNHT', 'SGLD', 'MALA', 'RHMC', 'SGRLD', 'SGRHMC'][0]\n model = reg\n\n\n # Setting up the parameters -----------------------------------------------\n sg_batch = 1000\n for rep in range(1):\n for L in reversed([1, 2, 3]):\n for eps in np.arange(0.0003, 0.0001, -0.00003):\n model.reset_parameters()\n print('init avg MSE:', nn.MSELoss()(y, model.forward(X)))\n name = '{}_{}_{}_{}'.format(sampler_name, str(eps), str(L), str(rep))\n path = '/home/tim/PycharmProjects/Thesis/Experiments/Results_Hidden4/'\n sampler_param = dict(\n epsilon=eps, num_steps=1000, burn_in=1000,\n pretrain=False, tune=False, num_chains=1)\n\n if sampler_name in ['SGNHT', 'RHMC', 'SGRHMC']:\n sampler_param.update(dict(L=L))\n\n if sampler_name == 'SGRHMC':\n sampler_param.update(dict(alpha=0.2))\n\n if 'SG' in sampler_name:\n batch_size = sg_batch\n else:\n batch_size = X.shape[0]\n\n trainset = TensorDataset(X, y)\n\n # Setting up the sampler & sampling\n if sampler_name in ['SGNHT', 'SGLD', 'MALA']: # geoopt based models\n trainloader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=0)\n Sampler = {'SGNHT': SGNHT, # step_size, hmc_traj_length\n 'MALA': MALA, # step_size\n 'SGLD': SGLD # step_size\n }[sampler_name]\n sampler = Sampler(model, trainloader, **sampler_param)\n try:\n sampler.sample()\n sampler.model.check_chain(sampler.chain)\n print(sampler.chain[:3])\n print(sampler.chain[-3:])\n\n # Visualize the resulting estimation -------------------------\n sampler.model.plot(X[:100], y[:100], sampler.chain[:30], path=path + name)\n sampler.model.plot(X[:100], y[:100], random.sample(sampler.chain, 30), path=path + name)\n matplotlib.pyplot.close('all')\n except Exception as error:\n print(name, 'failed')\n sampler.model.plot(X[:100], y[:100], path=path + 'failed_' + name)\n print(error)\n\n print(traceback.format_exc())\n\n elif sampler_name in ['RHMC', 'SGRLD', 'SGRHMC']:\n n_samples = sampler_param.pop('num_steps')\n burn_in = sampler_param.pop('burn_in')\n sampler_param.pop('pretrain')\n sampler_param.pop('tune')\n sampler_param.pop('num_chains')\n\n trainloader = DataLoader(trainset, batch_size=n, shuffle=True, num_workers=0)\n\n Sampler = {'RHMC': myRHMC, # epsilon, n_steps\n 'SGRLD': myRSGLD, # epsilon\n 'SGRHMC': mySGRHMC # epsilon, n_steps, alpha\n }[sampler_name]\n sampler = Sampler(model, **sampler_param)\n try:\n sampler.sample(trainloader, burn_in, n_samples)\n\n sampler.model.check_chain(sampler.chain)\n print(sampler.chain[:3])\n print(sampler.chain[-3:])\n\n # Visualize the resulting estimation -------------------------\n # import matplotlib\n # matplotlib.use('TkAgg')\n # sampler.model.plot(X[:100], y[:100], sampler.chain[-30:])\n # sampler.model.plot(X[:100], y[:100], random.sample(sampler.chain, 30))\n\n print('avg MSE:', nn.MSELoss()(y, model.forward(X)))\n sampler.model.plot(X[:100], y[:100], sampler.chain[-30:], path=path + name)\n sampler.model.plot(X[:100], y[:100], random.sample(sampler.chain, 30), path=path + name +\n 'random')\n\n except Exception as error:\n print(name, 'failed')\n sampler.model.plot(X[:100], y[:100], path=path + 'failed_' + name)\n print(error)\n print(traceback.format_exc())\n\n matplotlib.pyplot.close('all')\n print()\n\n # EXPERIMENTAL ---------------------------\n # x = x[:, 1]\n # a = acf(x, nlags=100, fft=True)\n # sgnht.acf = a\n # len(sgnht.chain) / (1 + 2 * sum(sgnht.acf))\n # print(sgnht.ess())\n # lag = np.arange(len(a))\n # # lag = np.arange(len(sgnht.acf))\n # plt.plot(lag, a)\n # plt.show()\n #\n # tsaplots.plot_acf(x, lags=100)\n #\n # # my own trials on autocorrelation plots\n # x = sgnht.chain_mat\n # x = x - np.mean(x, axis=0)\n # x = x[:, 0]\n #\n # # Display the autocorrelation plot of your time series\n # fig = tsaplots.plot_acf(x, lags=1000, fft=True)\n # plt.show()\n #\n # import tidynamics\n #\n # sgnht.acf = tidynamics.acf(x)[1: len(sgnht.chain) // 3]\n # lag = np.arange(len(sgnht.acf))\n # plt.plot(lag, sgnht.acf)\n # plt.show()\n #\n # sgnht.fast_autocorr(0)\n","sub_path":"src/Layer/Hidden.py","file_name":"Hidden.py","file_ext":"py","file_size_in_byte":13122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"585514160","text":"\"\"\"\nSimulation of the string with mass example,\nwith flatness based state feedback and flatness based state observer\n(design + approximation), presented in [RW2018a]_.\n\nReferences:\n\n .. [RW2018a] Marcus Riesmeier and Frank Woittennek;\n Modale Approximation eines verteiltparametrischen Beobachters\n für das Modell der Saite mit Last. GMA Fachausschuss 1.40\n „Systemtheorie und Regelungstechnik“, Salzburg, Austria,\n September 17-20, 2018.\n\"\"\"\nfrom pyinduct.examples.string_with_mass.control import *\nfrom pyinduct.hyperbolic.feedforward import FlatString\nimport pyinduct as pi\nimport pickle\nimport time\n\n\ndef run(show_plots):\n\n # control mode\n control_mode = [\"open_loop\",\n \"closed_loop\",\n \"modal_observer\",\n \"fem_observer\"][2]\n\n # constant observer initial error\n ie = 0.2\n\n # domains\n z_end = 1\n spatial_discretization = 100\n spatial_domain = pi.Domain((0, z_end), spatial_discretization)\n spat_domain_cf = pi.Domain((-z_end, z_end), spatial_discretization)\n t_end = 30\n temporal_discretization = int(30 * t_end)\n temporal_domain = pi.Domain((0, t_end), temporal_discretization)\n\n # planning input trajectories\n smooth_transition1 = pi.SmoothTransition(\n (0, 1), (2, 4), method=\"poly\", differential_order=2)\n smooth_transition2 = pi.SmoothTransition(\n (0, -1.5), (23, 25), method=\"poly\", differential_order=2)\n not_too_smooth_transition = pi.SmoothTransition(\n (0, -.5), (14, 14.2), method=\"poly\", differential_order=2)\n closed_loop_traj1 = SecondOrderFeedForward(smooth_transition1)\n closed_loop_traj2 = SecondOrderFeedForward(smooth_transition2)\n disturbance = SecondOrderFeedForward(not_too_smooth_transition)\n open_loop_traj = FlatString(\n y0=0, y1=1, z0=spatial_domain.bounds[0], z1=spatial_domain.bounds[1],\n t0=1, dt=3, params=param)\n\n # set up bases\n sys_fem_lbl = \"fem_system\"\n sys_modal_lbl = \"modal_system\"\n obs_fem_lbl = \"fem_observer\"\n obs_modal_lbl = \"modal_observer\"\n n1 = 11\n n2 = 11\n n_obs_fem = 11\n n_obs_modal = 16\n build_fem_bases(sys_fem_lbl, n1, n2, obs_fem_lbl, n_obs_fem, sys_modal_lbl)\n build_modal_bases(sys_modal_lbl, n_obs_modal, obs_modal_lbl, n_obs_modal)\n\n # controller\n controller = build_controller(sys_fem_lbl, sys_modal_lbl)\n if control_mode == \"open_loop\":\n input_ = pi.SimulationInputSum([open_loop_traj])\n else:\n input_ = pi.SimulationInputSum(\n [closed_loop_traj1, controller, disturbance, closed_loop_traj2])\n\n # observer error\n obs_fem_error, obs_modal_error = init_observer_gain(\n sys_fem_lbl, sys_modal_lbl, obs_fem_lbl, obs_modal_lbl)\n\n # input / observer error vector\n input_vector = pi.SimulationInputVector([input_, obs_fem_error, obs_modal_error])\n control = pi.Input(input_vector, index=0)\n yt_fem = pi.Input(input_vector, index=1)\n yt_modal = pi.Input(input_vector, index=2)\n\n # system approximation\n sys_wf = build_original_weak_formulation(\n sys_fem_lbl, spatial_domain, control, sys_fem_lbl)\n obs_fem_wf = build_canonical_weak_formulation(\n obs_fem_lbl, spat_domain_cf, control, yt_fem, obs_fem_lbl)\n obs_modal_wf = build_canonical_weak_formulation(\n obs_modal_lbl, spat_domain_cf, control, yt_modal, obs_modal_lbl)\n\n # set control mode\n apply_control_mode(sys_fem_lbl, sys_modal_lbl, obs_fem_lbl, obs_modal_lbl,\n control_mode)\n\n # define initial conditions\n init_cond = {\n sys_wf.name: [SwmBaseFraction(\n [pi.ConstantFunction(0, domain=spatial_domain.bounds),\n pi.ConstantFunction(0, domain=spatial_domain.bounds)],\n [0, 0])],\n obs_fem_wf.name: [SwmBaseCanonicalFraction(\n [pi.Function(lambda th: ie * (2 - th), (-1, 1))], [0, ie * 4])],\n obs_modal_wf.name: [SwmBaseCanonicalFraction(\n [pi.Function(lambda th: ie * (2 - th), (-1, 1))], [0, ie * 4])]\n }\n\n # simulation\n spatial_domains = {sys_wf.name: spatial_domain,\n obs_fem_wf.name: spat_domain_cf,\n obs_modal_wf.name: spat_domain_cf}\n intermediate_results = list()\n _ = pi.simulate_systems(\n [sys_wf, obs_fem_wf, obs_modal_wf],\n init_cond, temporal_domain, spatial_domains, out=intermediate_results\n )\n ceq, ss, init_weights, weights = intermediate_results\n\n # print some stuff for debugging\n # check_eigenvalues(sys_fem_lbl, obs_fem_lbl, obs_modal_lbl, ceq, ss)\n\n # visualization data\n split_indizes = [n1 + n2,\n n1 + n2 + n_obs_fem,\n n1 + n2 + n_obs_fem + n_obs_modal]\n # system\n weights_sys = weights[:, :split_indizes[0]]\n eval_data1 = pi.get_sim_result(sys_fem_lbl + \"_1_visu\", weights_sys,\n temporal_domain, spatial_domain, 0, 0,\n name=\"x1(z,t)\")[0]\n\n # fem observer\n weights_fem_obs = weights[:, split_indizes[0]: split_indizes[1]]\n fem_obs_ed = pi.get_sim_result(sys_fem_lbl + \"_1_trafo_visu\",\n weights_fem_obs,\n temporal_domain, spatial_domain,\n 0, 0,\n name=r\"\\hat x1_fem(z,t)\")[0]\n # modal observer\n weights_modal_obs = weights[:, split_indizes[1]: split_indizes[2]]\n modal_obs_ed = pi.get_sim_result(sys_modal_lbl + \"_1_trafo_visu\",\n weights_modal_obs,\n temporal_domain, spatial_domain,\n 0, 0,\n name=r\"\\hat x1_modal(z,t)\")[0]\n pi.tear_down([sys_fem_lbl, sys_modal_lbl, obs_fem_lbl, obs_modal_lbl])\n\n if show_plots:\n # create plots\n plots = list()\n plots.append(SwmPgAnimatedPlot([eval_data1, modal_obs_ed]))\n plots.append(pi.surface_plot([eval_data1, modal_obs_ed]))\n pi.show()\n\n # save results\n if 0:\n timestamp = time.strftime(\"%Y-%m-%d__%H-%M-%S__\")\n path = \"results/\"\n conf = \"{}__({}-{}-{})__\".format(\n control_mode, n1 + n2, n_obs_fem, n_obs_modal)\n description = input(\"result description:\").replace(\" \", \"-\")\n file = open(path + timestamp + conf + description + \".pkl\", \"wb\")\n pickle.dump([eval_data1, fem_obs_ed, modal_obs_ed], file)\n file.close()\n\n\nif __name__ == \"__main__\":\n run(True)\n","sub_path":"pyinduct/examples/string_with_mass/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"480234815","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 10 19:13:51 2021\n\n@author: Junio\n\"\"\"\nfrom sqlalchemy import create_engine, MetaData, Table, Column, String, ForeignKey\nimport textReader as t\ndonnee = create_engine(\"sqlite:///test4.bd\", echo = True)\nconn = donnee.connect()\nmeta = MetaData()\n\n#drop\nconn.execute(\"drop table if exists Semestre;\")\nconn.execute(\"drop table if exists UE;\")\nconn.execute(\"drop table if exists Module;\")\nconn.execute(\"drop table if exists Prerequis;\")\n# table\nSemestre = Table(\n 'Semestre', meta,\n Column('nomSemestre', String, primary_key = True)\n )\n\nUE = Table(\n 'UE', meta,\n Column('nomUE', String, primary_key = True),\n Column('nomSemestre', String, ForeignKey('Semestre.nomSemestre'))\n )\n\nModule = Table(\n 'Module', meta,\n Column('nomModule', String, primary_key=True),\n Column('competence', String),\n Column('nomUE', String, ForeignKey('UE.nomUE'))\n )\n\nPrerequis = Table(\n 'Prerequis', meta,\n Column('nomModule', String, ForeignKey('Module.nomModule')),\n Column('nomModule_prerequis', String, ForeignKey('Module.nomModule'))\n )\n\nmeta.create_all(donnee)\n#####################################################################\n\n# insertion dans semestre\ntext = t.text\nsemestre_UE = t.semestre_UE(text)\nUE_module = t.UE_module_court(text)\n#\nprint(1)\nliste_semestre = []\nfor semestre in semestre_UE.items():\n #liste_semestre.append({'Semestre':semestre[0]})\n #print(semestre[0])\n sem = Semestre.insert().values(nomSemestre= semestre[0])\n conn.execute(sem)\n#\nliste_UE = []\nfor termes in semestre_UE.items(): \n for ue in termes[1]:\n #liste_UE.append({'nomUE':ue,'nomSemestre':termes[0]})\n ue_p = UE.insert().values(nomUE = ue,nomSemestre = termes[0])\n conn.execute(ue_p)\n\n#\nUE_modules = t.UE_module_court(text)\nliste_module = []\nfor modules in UE_modules.items():\n for module in modules[1]:\n consequence = t.attributModule(module, text)[1]\n #liste_module.append({'nomModule':module,'consequence':consequence,'nomUE':modules[0]})\n mod = Module.insert().values(nomModule = module,competence = consequence,nomUE = modules[0])\n conn.execute(mod)\n#\nrelations = t.relation_entre_matiere(text)\nliste_rel =[]\nfor relation in relations.items():\n for prerequis in relation[1]:\n #liste_rel.append({'nomModule':relation[0],'nomModule_prerequis':prerequis})\n pre = Prerequis.insert().values(nomModule = relation[0],nomModule_prerequis = prerequis)\n conn.execute(pre)\n#\n\n# conn.execute(sem,liste_semestre)\n# conn.execute(ue_p,liste_UE)\n# conn.execute(mod,liste_module)\n# conn.execute(pre, liste_rel)\n\n","sub_path":"BDcreator.py","file_name":"BDcreator.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"64"} +{"seq_id":"51703053","text":"#%%\nimport torch\nimport torch.nn as nn\nfrom torchviz import make_dot\n\n#%%\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.fc1 = nn.Linear(10,5)\n self.fc2 = nn.Linear(5,2)\n self.relu1 = nn.ReLU()\n def forward(self,x):\n x = self.fc1(x)\n x = self.fc2(x)\n x = self.relu1(x)\n return x\n#%%\nn = Net()\ninput_x = torch.randn(10)\no = n(input_x)\n\n#%%\nprint(n)\n#%%保存模型+参数\ntorch.save(n,\"torch_model.pth\")\n\n#%%\ng = make_dot(o)\ng.render('espnet_model', view=False)","sub_path":"tutorials/01-basics/feedforward_neural_network/mytry.py","file_name":"mytry.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"550665767","text":"class InputOutOfRange(Exception):\n pass\n\n\nclass CellNotEmpty(Exception):\n pass\n\n\nclass TicTacToe:\n def __init__(self, board=None, player_turn=1):\n if type(board) == list:\n self.board = board\n elif type(board) == str and len(board) == 9:\n self.board = [[int(j) for j in board[i * 3:i * 3 + 3]] for i in range(3)]\n else:\n self.board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n\n self.player_turn = player_turn if player_turn in [1, 2] else 1\n self.winner = None\n\n def _display_board(self):\n [print(i) for i in self.board]\n\n def board_as_string(self):\n return ''.join(str(i) for i in self.board[0] + self.board[1] + self.board[2])\n\n def _change_turn(self):\n self.player_turn = 1 if self.player_turn == 2 else 2\n\n def _update_winner(self):\n\n def check_triplet(s):\n s_set = set(s)\n if len(s_set) == 1:\n result = s_set.pop()\n if result != 0:\n self.winner = result\n return True\n\n # vertical\n for i in range(3):\n column = [row[i] for row in self.board]\n if check_triplet(column):\n return\n\n # horizontal\n for row in self.board:\n if check_triplet(row):\n return\n\n # top left to bottom right\n across = [self.board[i][i] for i in range(3)]\n if check_triplet(across):\n return\n\n # top right to bottom left\n across = [self.board[i][2 - i] for i in range(3)]\n if check_triplet(across):\n return\n\n # check if there is a 0 if not, return 0 which is a draw\n for row in self.board:\n if 0 in row:\n return\n\n self.winner = 0\n\n def move(self, x, y):\n if x not in range(0, 3) or y not in range(0, 3):\n raise InputOutOfRange\n if self.board[y][x]:\n raise CellNotEmpty\n self.board[y][x] = self.player_turn\n self._update_winner()\n if self.winner is not None:\n return self.winner\n self._change_turn()\n\n def restart(self):\n self.__init__(player_turn=self.winner)\n","sub_path":"mainapp/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"320337394","text":"# highest mileage data\n# from http://www.fueleconomy.gov/FEG/download.shtml\n\ndef create_mileage_list(epa_file):\n \"\"\"Create a list of cars and mileage from epa_file.\"\"\"\n # 2a create a mileage list and initialize it to empty\n mileage_list = []\n\n for line in epa_file: # 2b. get each line from the file\n if line[0:5] == 'CLASS' or 'VAN' in line or 'PICKUP' in line: \n continue # skip header, vans and pickups\n line_list = line.split(',') # 2bI. csv => split on comma\n mileage_list.append(int(line_list[9])) # 2bII. append highway mileage\n return mileage_list\n\n#################################\n\n# 1. open EPA data file\nepa_file = open(\"epaData.csv\", \"rU\")\nmileage_list = create_mileage_list(epa_file)\n\n# 3. find max and min mileage\nmax_mileage = max(mileage_list)\nmin_mileage = min(mileage_list)\n\nprint(\"Max and Min Mileage: \", max_mileage, min_mileage)\n","sub_path":"ch07/codeListing7-12.py","file_name":"codeListing7-12.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"105567741","text":"from twilio.rest import Client\n\n \naccount_sid = 'AC970aa9aa62f3d0907eae384d484cdb09' \nauth_token = 'e5533d6fddd2da471381a994b0ab1331' \nclient = Client(account_sid, auth_token) \n\n\ndef send_text():\n bomdia = client.messages.create(\n from_='whatsapp:+',\n body=f'Bom dia.',\n to='whatsapp:+'\n )\n\n print(bomdia.sid)\n\n lembretes = client.messages.create(\n from_='whatsapp: num',\n body=f'lorem ipsum',\n to='boiler plate text'\n )\n\n print(lembretes.sid)\n","sub_path":"mom_send.py","file_name":"mom_send.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"400513872","text":"# unzip label files\n# tianye li\n\nimport os\nfrom os.path import join, basename, exists\nimport numpy as np\nfrom glob import glob\nfrom time import time\nfrom utils import list_dirs\n\n# -----------------------------------------------------------------------------\n\ndef unzip_one_folder( data_dir, verbose=False ):\n\n # parse\n semantic_paths = sorted( glob( join( data_dir, '*2d-label-filt.zip' ) ) ) # only filtered folder\n if semantic_paths and len(semantic_paths) != 1:\n raise RuntimeError( 'unexpected number for semantic label files' )\n semantic_zip_path = semantic_paths[0]\n\n instance_paths = sorted( glob( join( data_dir, '*2d-instance-filt.zip' ) ) ) # only filtered folder\n if instance_paths and len(instance_paths) != 1:\n raise RuntimeError( 'unexpected number for instance instance files' )\n instance_zip_path = instance_paths[0]\n\n # unzip\n def unzip( file_path, dst_dir ):\n zip_name = basename( file_path )\n folder_name = zip_name[:-4] # hardcode: corresponds to .zip\n target_dir = join( dst_dir, folder_name )\n\n if not exists( target_dir ):\n os.system( \"unzip -qq -o %s -d %s\" % ( file_path, dst_dir ) )\n if verbose:\n print( '\\nunzipped %s' % ( file_path ) )\n print( ' to %s' % ( dst_dir ) )\n else:\n if verbose:\n print( '\\nskipped %s' % ( file_path ) )\n\n unzip( semantic_zip_path, data_dir )\n unzip( instance_zip_path, data_dir )\n\n# -----------------------------------------------------------------------------\n\ndef run_unzip_all( data_root ):\n\n # hardcode scene range:\n # scene_list = list_dirs( data_root ) # parse all\n scene_list = [ 'scene%04d_00' % (idx) for idx in range(0,20) ] # parse 0-19, enforce scan 00\n\n for sid, this_scene in enumerate( scene_list ):\n print( \"\\nprocessing %d of %d: %s\" % ( sid, len(scene_list), this_scene ) )\n this_data_dir = join( data_root, this_scene )\n\n timer_start = time()\n unzip_one_folder( this_data_dir, verbose=True )\n print( \"using %f sec\" % ( time() - timer_start ) )\n\n# -----------------------------------------------------------------------------\n\nif __name__ == '__main__':\n\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_root', required=True, help='root dir to store scannet dataset')\n opt = parser.parse_args()\n print(opt)\n run_unzip_all( opt.data_root )","sub_path":"Utils/unzip_labels.py","file_name":"unzip_labels.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"232462132","text":"import pandas as pd\n\ndfHeight = pd.read_csv(\"./8842height.phe.txt\", sep=\"\\t\")\ndfKare = pd.read_csv(\"./KARE.csv\", sep=\",\")\n\n# print(dfKare.count())\n# print(dfHeight.count())\ndfMerged = pd.merge(dfHeight, dfKare, on=\"hid\")\n\n# print(dfMerged.count())\n\ndef save(df, filename):\n writer = pd.ExcelWriter(filename)\n df.to_excel(writer, 'Sheet1')\n writer.save()\n\ndfOrder = dfMerged[['id', 'hid','Area', 'Age', 'Sex', 'Height']]\nsave(dfOrder, \"./order.xlsx\")\n\n","sub_path":"lecture/02_merge.py","file_name":"02_merge.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"} +{"seq_id":"605243435","text":"from django.contrib.auth import views as auth_views\nfrom django.urls import path\n\nfrom .views import profile, SignUpView, who_innovates\n\nurlpatterns = [\n path('accounts/login/', auth_views.login, name='login'),\n path('accounts/logout/', auth_views.logout, name='logout'),\n path('accounts/sign-up/', SignUpView.as_view(), name='sign-up'),\n path('users/profile//', profile, name='profile'),\n path('users/whoinnovates/', who_innovates, name='whoinnovates'),\n]\n","sub_path":"ideax/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"83"}